This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/tests/mk_tokenizer_goldens.py
T
Deadcode 1e968f6e1d radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
2026-10-16 18:25:18 +02:00

349 lines
16 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Expected outputs of HuggingFace `tokenizers` for text_test's tokenizer.json parity cases.
Prints a C++ block (tokenizer.json fixtures as raw strings, then the decode, pre-tokenizer and
encode goldens) to paste into tests/text_test.cpp between the "BEGIN/END generated by
mk_tokenizer_goldens.py" markers. Needs only `pip install tokenizers` (0.23.2 produced the
current block); no model files.
python3 tests/mk_tokenizer_goldens.py > /tmp/goldens.inc
"""
import json
import tokenizers
from tokenizers import Tokenizer
MS = "▁"
def cstr(s):
"""A C++ string literal for `s` (UTF-8 bytes, non-ASCII and controls escaped)."""
out = '"'
prev_hex = False
for b in s.encode("utf-8"):
c = chr(b)
if c == '"':
out += '\\"'; prev_hex = False
elif c == "\\":
out += "\\\\"; prev_hex = False
elif c == "\n":
out += "\\n"; prev_hex = False
elif c == "\t":
out += "\\t"; prev_hex = False
elif 0x20 <= b < 0x7F:
if prev_hex and c in "0123456789abcdefABCDEF":
out += '" "'
out += c; prev_hex = False
else:
out += "\\x%02x" % b; prev_hex = True
return out + '"'
def added(entries):
return [{"id": i, "content": c, "single_word": False, "lstrip": False, "rstrip": False,
"normalized": False, "special": sp} for i, c, sp in entries]
def ids_cpp(ids):
return "{ " + ", ".join(str(i) for i in ids) + " }"
# ---------------------------------------------------------------------------- decoders
def bpe_model(vocab, byte_fallback=False, unk=None):
return {"type": "BPE", "byte_fallback": byte_fallback, "unk_token": unk,
"vocab": {t: i for i, t in enumerate(vocab)}, "merges": []}
DEC_VOCAB = ["<unk>", "<s>", "</s>", "<0xE2>", "<0x82>", "<0xAC>", MS, MS + MS, MS + "Hello",
MS + "world", "Hello", "a" + MS + "b", "x", MS + "x", "!"]
def llama_like():
return {
"added_tokens": added([(0, "<unk>", True), (1, "<s>", True), (2, "</s>", True)]),
"normalizer": None,
"pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": "first",
"split": False},
"decoder": {"type": "Sequence", "decoders": [
{"type": "Replace", "pattern": {"String": MS}, "content": " "},
{"type": "ByteFallback"}, {"type": "Fuse"},
{"type": "Strip", "content": " ", "start": 1, "stop": 0}]},
"model": bpe_model(DEC_VOCAB, byte_fallback=True, unk="<unk>"),
}
def metaspace_dec(scheme):
return {
"added_tokens": added([(0, "<unk>", True), (1, "<s>", True), (2, "</s>", True)]),
"pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme,
"split": True},
"decoder": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme,
"split": True},
"model": bpe_model(DEC_VOCAB, byte_fallback=True, unk="<unk>"),
}
WP_VOCAB = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "hello", "##world", "!", "a", "'", "s", "do",
"n't", ",", "x", "##y", ".", "##s"]
def wordpiece_dec(cleanup):
return {
"added_tokens": added([(0, "[PAD]", True), (1, "[UNK]", True), (2, "[CLS]", True),
(3, "[SEP]", True)]),
"pre_tokenizer": {"type": "BertPreTokenizer"},
"decoder": {"type": "WordPiece", "prefix": "##", "cleanup": cleanup},
"model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##",
"max_input_chars_per_word": 100,
"vocab": {t: i for i, t in enumerate(WP_VOCAB)}},
}
BPED_VOCAB = ["hel", "lo</w>", "wor", "ld</w>", "hi</w>", "x", "<unk>"]
def bpe_decoder():
return {
"pre_tokenizer": {"type": "WhitespaceSplit"},
"decoder": {"type": "BPEDecoder", "suffix": "</w>"},
"model": bpe_model(BPED_VOCAB, unk="<unk>"),
}
BL_VOCAB = ["Ġhello", "Ġworld", "Ċ", "x", "Ã", "©"]
def bytelevel_dec():
return {
"pre_tokenizer": {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True,
"use_regex": True},
"decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True,
"use_regex": True},
"model": bpe_model(BL_VOCAB),
}
DECODERS = [
("llama_like", llama_like(), [[8, 9], [1, 8, 9], [6, 8], [7, 8], [10, 9, 14],
[3, 4, 5, 13], [9, 3, 4, 5], [11, 9], [1, 6, 9]]),
("metaspace_always", metaspace_dec("always"), [[8, 9], [7, 12], [11, 13], [10, 9], [1, 8]]),
("metaspace_first", metaspace_dec("first"), [[8, 9], [7, 12], [11, 13], [10, 9]]),
("metaspace_never", metaspace_dec("never"), [[8, 9], [7, 12], [11, 13], [10, 9]]),
("wordpiece_cleanup", wordpiece_dec(True),
[[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [5, 4], [2, 4, 16, 3], [7, 8, 9]]),
("wordpiece_raw", wordpiece_dec(False), [[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [5, 4]]),
("bpe_decoder", bpe_decoder(), [[0, 1, 2, 3], [4], [4, 4], [0, 1, 5]]),
("bytelevel", bytelevel_dec(), [[0, 1, 2], [3, 0], [4, 5]]),
]
# ---------------------------------------------------------------------------- pre-tokenizers
PRE_TEXT = "hello, world!! a,,b €5 → x́y ‿z 12345 don't ©x_y " \
"٣٤ Ⅻ ½ x²  n m ¿q?"
PRETOKS = [
("Whitespace", {"type": "Whitespace"}),
("WhitespaceSplit", {"type": "WhitespaceSplit"}),
("BertPreTokenizer", {"type": "BertPreTokenizer"}),
("Punctuation_Removed", {"type": "Punctuation", "behavior": "Removed"}),
("Punctuation_Isolated", {"type": "Punctuation", "behavior": "Isolated"}),
("Punctuation_MergedWithPrevious", {"type": "Punctuation", "behavior": "MergedWithPrevious"}),
("Punctuation_MergedWithNext", {"type": "Punctuation", "behavior": "MergedWithNext"}),
("Punctuation_Contiguous", {"type": "Punctuation", "behavior": "Contiguous"}),
("Digits_individual", {"type": "Digits", "individual_digits": True}),
("Digits_runs", {"type": "Digits", "individual_digits": False}),
("Metaspace_split_always", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "always",
"split": True}),
("Metaspace_split_never", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "never",
"split": True}),
("Metaspace_whole_first", {"type": "Metaspace", "replacement": MS, "prepend_scheme": "first",
"split": False}),
("Sequence_Whitespace_Digits", {"type": "Sequence", "pretokenizers": [
{"type": "WhitespaceSplit"}, {"type": "Digits", "individual_digits": True},
{"type": "Punctuation", "behavior": "Isolated"}]}),
]
def pretok_case(name, pt):
"""A WordPiece vocabulary of exactly the pieces HF cuts the text into, so the ids name the
pieces one for one and any other cut shows as [UNK] or a different id."""
probe = Tokenizer.from_str(json.dumps({
"pre_tokenizer": pt,
"model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##",
"max_input_chars_per_word": 100, "vocab": {"[UNK]": 0}}}))
pieces = [w for w, _ in probe.pre_tokenizer.pre_tokenize_str(PRE_TEXT)]
vocab = {"[UNK]": 0}
for w in pieces:
vocab.setdefault(w, len(vocab))
js = {"pre_tokenizer": pt,
"model": {"type": "WordPiece", "unk_token": "[UNK]", "continuing_subword_prefix": "##",
"max_input_chars_per_word": 100, "vocab": vocab}}
tok = Tokenizer.from_str(json.dumps(js))
ids = tok.encode(PRE_TEXT, add_special_tokens=False).ids
assert 0 not in ids, (name, pieces)
return js, pieces, ids
# ---------------------------------------------------------------------------- Gemma-shaped
def gemma_like():
pieces = ["<pad>", "<eos>", "<bos>", "<unk>", "<mask>", "<start_of_turn>", "<end_of_turn>"]
pieces += ["<0x%02X>" % b for b in range(256)]
base = list("abcdefghijklmnopqrstuvwxyz") + [MS, "\n", "\t", "H", "T", ".", ",", "!", "?",
"é", "'"]
pieces += base
merges = [("h", "e"), ("l", "l"), ("he", "ll"), ("hell", "o"), (MS, "w"), ("o", "r"),
(MS + "w", "or"), ("l", "d"), (MS + "wor", "ld"), (MS, "t"), (MS + "t", "h"),
(MS + "th", "e"), (MS, "c"), (MS + "c", "a"), (MS + "ca", "t"), (MS, MS),
(MS + MS, MS + MS), ("\n", "\n"), (MS, "the"), ("t", "h"), ("th", "e"),
("i", "n"), ("in", "g"), ("e", "d"), (MS, "a"), (MS, "hello"), ("H", "e"),
("He", "ll"), ("Hell", "o"), ("é", "m"), ("o", "j"), ("oj", "i")]
vocab = {p: i for i, p in enumerate(pieces)}
for a, b in merges:
vocab.setdefault(a + b, len(vocab))
js = {
"added_tokens": added([(0, "<pad>", True), (1, "<eos>", True), (2, "<bos>", True),
(3, "<unk>", True), (4, "<mask>", False),
(5, "<start_of_turn>", True), (6, "<end_of_turn>", True)]),
"normalizer": {"type": "Replace", "pattern": {"String": " "}, "content": MS},
"pre_tokenizer": {"type": "Split", "pattern": {"String": " "},
"behavior": "MergedWithPrevious", "invert": False},
"post_processor": {"type": "TemplateProcessing",
"single": [{"SpecialToken": {"id": "<bos>", "type_id": 0}},
{"Sequence": {"id": "A", "type_id": 0}},
{"SpecialToken": {"id": "<eos>", "type_id": 0}}],
"pair": [{"SpecialToken": {"id": "<bos>", "type_id": 0}},
{"Sequence": {"id": "A", "type_id": 0}},
{"SpecialToken": {"id": "<eos>", "type_id": 0}},
{"Sequence": {"id": "B", "type_id": 1}},
{"SpecialToken": {"id": "<eos>", "type_id": 1}}],
"special_tokens": {"<bos>": {"id": "<bos>", "ids": [2],
"tokens": ["<bos>"]},
"<eos>": {"id": "<eos>", "ids": [1],
"tokens": ["<eos>"]}}},
"decoder": {"type": "Sequence", "decoders": [
{"type": "Replace", "pattern": {"String": MS}, "content": " "},
{"type": "ByteFallback"}, {"type": "Fuse"}]},
"model": {"type": "BPE", "dropout": None, "unk_token": "<unk>",
"continuing_subword_prefix": None, "end_of_word_suffix": None,
"fuse_unk": True, "byte_fallback": True, "ignore_merges": False,
"vocab": vocab, "merges": [[a, b] for a, b in merges]},
}
return js
def metaspace_specials(scheme):
"""Metaspace BPE with special tokens: "first" prepends only where the text starts."""
vocab = {"<s>": 0, "[INST]": 1, MS: 2, "H": 3, "i": 4, MS + "H": 5, "Hi": 6, MS + "Hi": 7,
"<unk>": 8}
return {"added_tokens": added([(0, "<s>", True), (1, "[INST]", True)]),
"pre_tokenizer": {"type": "Metaspace", "replacement": MS, "prepend_scheme": scheme,
"split": False},
"model": {"type": "BPE", "dropout": None, "unk_token": "<unk>",
"continuing_subword_prefix": None, "end_of_word_suffix": None,
"fuse_unk": False, "byte_fallback": False, "ignore_merges": False,
"vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}}
SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "<s>Hi", "Hi Hi[INST]Hi"]
GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat",
" leading", "trailing ", "a\tb", "émoji \U0001F600", "x<eos>y",
"<start_of_turn>user\nhello<end_of_turn>", "Hello, world!", " ",
"th the thee", "日本", "zz zz zz", "<mask> the", "<bos>hello", ""]
def main():
print("/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers %s) */" % tokenizers.__version__)
print()
print("struct DecodeGolden { const char* fixture; std::vector<int32_t> ids; const char* text; };")
print("struct PretokGolden { const char* name; const char* json; std::vector<int32_t> ids; };")
print("struct EncodeGolden { const char* text; std::vector<int32_t> ids; "
"std::vector<int32_t> with_special; };")
print()
print("const std::vector<std::pair<const char*, const char*>>& decode_fixtures() {")
print(" static const std::vector<std::pair<const char*, const char*>> v = {")
for name, js, _ in DECODERS:
print(" { %s, R\"JSON(%s)JSON\" }," % (cstr(name), json.dumps(js, ensure_ascii=False)))
print(" };")
print(" return v;")
print("}")
print()
print("const std::vector<DecodeGolden>& decode_goldens() {")
print(" static const std::vector<DecodeGolden> v = {")
for name, js, cases in DECODERS:
tok = Tokenizer.from_str(json.dumps(js))
for ids in cases:
print(" { %s, %s, %s }," % (cstr(name), ids_cpp(ids),
cstr(tok.decode(ids, skip_special_tokens=True))))
print(" };")
print(" return v;")
print("}")
print()
print("const char* const kPretokText = %s;" % cstr(PRE_TEXT))
print()
print("const std::vector<PretokGolden>& pretok_goldens() {")
print(" static const std::vector<PretokGolden> v = {")
for name, pt in PRETOKS:
js, pieces, ids = pretok_case(name, pt)
print(" /* %s */" % " | ".join(p.replace("*/", "* /") for p in pieces)
.encode("ascii", "backslashreplace").decode())
print(" { %s, R\"JSON(%s)JSON\", %s }," % (cstr(name),
json.dumps(js, ensure_ascii=False),
ids_cpp(ids)))
print(" };")
print(" return v;")
print("}")
print()
g = gemma_like()
tok = Tokenizer.from_str(json.dumps(g))
print("const char* const kGemmaLike = R\"JSON(%s)JSON\";" % json.dumps(g, ensure_ascii=False))
print()
print("const std::vector<EncodeGolden>& gemma_goldens() {")
print(" static const std::vector<EncodeGolden> v = {")
for t in GEMMA_TEXTS:
a = tok.encode(t, add_special_tokens=False).ids
b = tok.encode(t, add_special_tokens=True).ids
print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b)))
print(" };")
print(" return v;")
print("}")
print()
print("/* The decode of every Gemma golden with special tokens skipped, as HF reports it. */")
print("const std::vector<const char*>& gemma_decoded() {")
print(" static const std::vector<const char*> v = {")
for t in GEMMA_TEXTS:
print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids,
skip_special_tokens=True)))
print(" };")
print(" return v;")
print("}")
print()
print("const std::vector<std::pair<const char*, const char*>>& metaspace_special_fixtures() {")
print(" static const std::vector<std::pair<const char*, const char*>> v = {")
for scheme in ["first", "always"]:
print(" { %s, R\"JSON(%s)JSON\" }," % (cstr(scheme),
json.dumps(metaspace_specials(scheme),
ensure_ascii=False)))
print(" };")
print(" return v;")
print("}")
print()
print("const std::vector<std::pair<const char*, EncodeGolden>>& metaspace_special_goldens() {")
print(" static const std::vector<std::pair<const char*, EncodeGolden>> v = {")
for scheme in ["first", "always"]:
tok = Tokenizer.from_str(json.dumps(metaspace_specials(scheme)))
for text in SPECIAL_TEXTS:
ids = tok.encode(text, add_special_tokens=False).ids
print(" { %s, { %s, %s, {} } }," % (cstr(scheme), cstr(text), ids_cpp(ids)))
print(" };")
print(" return v;")
print("}")
print()
print("/* END generated by mk_tokenizer_goldens.py */")
if __name__ == "__main__":
main()