test(tokenizer): committed oracle differential, per-codepoint pre-tokenizer check, batch CLI
- crates/tokenizer pre_tokenize + model pre-tokenize-batch/tokenize-batch/detokenize-batch (debug/differential) - scripts/offline/diff_tokenizer.py: every Unicode scalar x 13 contexts vs Python regex (0 real mismatches; 14k strings differ only where regex 2026.9.10 has Unicode 17 and regex-syntax/unicodedata 16), a synthetic GGUF with BPE-trained merges past the heap path, 5-file extraction compare, encode/decode fuzz - golden crates/tokenizer/tests/fixtures/tokenizer_oracle.json + integration test - stricter-by-design: duplicate merges, missing chat template, negative special ids Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
f3bff3842d
commit
debfbd0941
@@ -772,6 +772,36 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?);
|
||||
Ok(())
|
||||
}
|
||||
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
|
||||
[model, action] if model == "model" && action == "pre-tokenize-batch" => {
|
||||
for line in std::io::stdin().lines() {
|
||||
let text: String = serde_json::from_str(&line?)?;
|
||||
let pieces = tokenizer::pre_tokenize(&text);
|
||||
println!("{}", serde_json::to_string(&pieces.ok())?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
[model, action, path, rest @ ..]
|
||||
if model == "model"
|
||||
&& action == "tokenize-batch"
|
||||
&& rest.iter().all(|flag| flag == "--special") =>
|
||||
{
|
||||
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
||||
for line in std::io::stdin().lines() {
|
||||
let text: String = serde_json::from_str(&line?)?;
|
||||
let ids = tokenizer.encode(&text, !rest.is_empty()).ok();
|
||||
println!("{}", serde_json::to_string(&ids)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
[model, action, path] if model == "model" && action == "detokenize-batch" => {
|
||||
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
||||
for line in std::io::stdin().lines() {
|
||||
let ids: Vec<u32> = serde_json::from_str(&line?)?;
|
||||
println!("{}", serde_json::to_string(&tokenizer.decode(&ids).ok())?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
[version] if version == "--version" || version == "-V" => {
|
||||
println!("strata-next {}", env!("CARGO_PKG_VERSION"));
|
||||
Ok(())
|
||||
@@ -781,7 +811,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
print!("{}", include_str!("../third_party/ggml/LICENSE"));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()),
|
||||
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model detokenize TOKENIZER_DIR IDS]".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,21 @@ pub const QWEN35_PATTERN: &str = concat!(
|
||||
|
||||
type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
||||
|
||||
/// The `qwen35` pre-tokenizer alone: the pieces `text` is split into before byte-level BPE. Exposed so the split can
|
||||
/// be compared with Python's `regex` for every Unicode scalar value (scripts/offline/diff_tokenizer.py).
|
||||
pub fn pre_tokenize(text: &str) -> Result<Vec<&str>> {
|
||||
static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
|
||||
let pattern = match PATTERN.get() {
|
||||
Some(pattern) => pattern,
|
||||
None => PATTERN.get_or_init(|| Regex::new(QWEN35_PATTERN).expect("pinned qwen35 pattern")),
|
||||
};
|
||||
let mut pieces = Vec::new();
|
||||
for found in pattern.find_iter(text) {
|
||||
pieces.push(found?.as_str());
|
||||
}
|
||||
Ok(pieces)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
model: String,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,99 @@
|
||||
//! Tokenizer versus `engine/strata/tools/strata_tokenizer.py` (the unmodified oracle, regex 2026.9.10).
|
||||
//!
|
||||
//! `tests/fixtures/tokenizer_oracle.json` is produced by `scripts/offline/gen_goldens.py tokenizer_oracle`: a
|
||||
//! synthetic byte-level BPE vocabulary (256-byte alphabet, 300 trained merges that reach past the 64-symbol heap
|
||||
//! path, type-3 and type-4 specials including ones with regex metacharacters) and the oracle's answers for ~190
|
||||
//! boundary and fuzzed texts (ids with and without special parsing, decoded text, pre-tokenizer pieces) plus the
|
||||
//! pre-tokenizer split of sampled Unicode scalar values in five contexts.
|
||||
//! `scripts/offline/diff_tokenizer.py` runs the exhaustive live version (every scalar value x 13 contexts).
|
||||
use leleka_tokenizer::{Tokenizer, pre_tokenize};
|
||||
use serde_json::Value;
|
||||
|
||||
fn golden() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/tokenizer_oracle.json")).unwrap()
|
||||
}
|
||||
|
||||
fn strings(value: &Value) -> Vec<String> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ids(value: &Value) -> Vec<u32> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap() as u32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tokenizer(golden: &Value) -> Tokenizer {
|
||||
let types = golden["token_types"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap() as u32)
|
||||
.collect();
|
||||
Tokenizer::from_vocabulary(
|
||||
"gpt2",
|
||||
"qwen35",
|
||||
strings(&golden["tokens"]),
|
||||
strings(&golden["merges"]),
|
||||
Some(types),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_matches_the_oracle_with_and_without_special_parsing() {
|
||||
let golden = golden();
|
||||
let tokenizer = tokenizer(&golden);
|
||||
let cases = golden["cases"].as_array().unwrap();
|
||||
assert!(cases.len() > 150);
|
||||
for case in cases {
|
||||
let text = case["text"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
tokenizer.encode(text, false).unwrap(),
|
||||
ids(&case["plain"]),
|
||||
"plain {text:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
tokenizer.encode(text, true).unwrap(),
|
||||
ids(&case["special"]),
|
||||
"special {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_matches_the_oracle_including_split_multibyte_characters() {
|
||||
let golden = golden();
|
||||
let tokenizer = tokenizer(&golden);
|
||||
for case in golden["decodes"].as_array().unwrap() {
|
||||
let ids = ids(&case["ids"]);
|
||||
match case["text"].as_str() {
|
||||
Some(text) => assert_eq!(tokenizer.decode(&ids).unwrap(), text, "{ids:?}"),
|
||||
// a token outside the byte alphabet (the `<|im_` literal): neither side decodes it
|
||||
None => assert!(tokenizer.decode(&ids).is_err(), "{ids:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_tokenizer_matches_python_regex() {
|
||||
let golden = golden();
|
||||
let splits = golden["pre_tokenizer"].as_array().unwrap();
|
||||
assert!(splits.len() > 500);
|
||||
for case in splits {
|
||||
let text = case["text"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
pre_tokenize(text).unwrap(),
|
||||
strings(&case["pieces"]),
|
||||
"{text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tokenizer differential: strata-next (crates/tokenizer, extract-tokenizer) vs the unmodified tools/strata_tokenizer.py.
|
||||
|
||||
1. pre-tokenizer: for EVERY Unicode scalar value, the qwen35 split of 13 one-character contexts (alone, next to a
|
||||
letter / space / digit / punctuation / newline, doubled) in Rust's `fancy_regex` vs Python's `regex`.
|
||||
2. a synthetic GGUF (full 256-byte alphabet, BPE-trained merges that reach words past the 64-symbol heap path,
|
||||
type-3 and type-4 specials, some with regex metacharacters): `extract-tokenizer` against `extract()` for all
|
||||
five files, then ids from `tokenize-batch` (with and without special parsing) and text from `detokenize-batch`
|
||||
over a boundary corpus plus fuzzed Unicode.
|
||||
|
||||
python scripts/offline/diff_tokenizer.py <strata-next> [--stride N] [--fuzz N] [--seed S]
|
||||
|
||||
Needs `regex` (pip install regex). --stride N checks every Nth scalar value (default 1 = all 1,112,064).
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import regex # noqa: E402
|
||||
import strata_tokenizer as T # noqa: E402 (the oracle, unchanged)
|
||||
from ggufgen import write_gguf # noqa: E402
|
||||
|
||||
CONTEXTS = ['{c}', 'a{c}', '{c}a', ' {c}', '{c} ', '1{c}', '{c}1', '!{c}', '{c}!', '\n{c}', '{c}\n', '\r{c}',
|
||||
'{c}{c}']
|
||||
|
||||
|
||||
def run_batch(binary, args, lines, chunk=200_000):
|
||||
out = []
|
||||
for at in range(0, len(lines), chunk):
|
||||
payload = ('\n'.join(lines[at:at + chunk]) + '\n').encode('utf-8')
|
||||
r = subprocess.run([binary, 'model', *args], input=payload, capture_output=True, timeout=3600)
|
||||
if r.returncode:
|
||||
raise RuntimeError(r.stderr.decode('utf-8', 'replace')[-300:])
|
||||
out.extend(r.stdout.decode('utf-8').split('\n')[:-1]) # not splitlines(): U+2028, U+0085 ...
|
||||
return out
|
||||
|
||||
|
||||
def per_codepoint(binary, stride):
|
||||
"""-> (strings checked, version-skew strings, real mismatches).
|
||||
|
||||
Python's `regex` (pinned 2026.9.10 by requirements.txt) carries Unicode 17 tables; Rust's regex-syntax carries
|
||||
Unicode 16 (the same as Python 3.14's `unicodedata`); the pinned llama.cpp C++ tables are older still. A code
|
||||
point that is unassigned in Unicode 16 (category Cn) but assigned in 17 may therefore split differently - that is
|
||||
table skew, counted and reported, not a defect of the port. Anything else is a real mismatch."""
|
||||
import unicodedata
|
||||
pattern = regex.compile(T.QWEN35_PATTERN)
|
||||
scalars = [c for c in range(0x110000) if not 0xD800 <= c <= 0xDFFF]
|
||||
scalars = scalars[::stride] if stride > 1 else scalars
|
||||
real, skew, checked, groups = [], 0, 0, 20_000
|
||||
for at in range(0, len(scalars), groups):
|
||||
batch = scalars[at:at + groups]
|
||||
texts = [ctx.format(c=chr(c)) for c in batch for ctx in CONTEXTS]
|
||||
owners = [c for c in batch for _ in CONTEXTS]
|
||||
got = run_batch(binary, ['pre-tokenize-batch'], [json.dumps(t, ensure_ascii=True) for t in texts])
|
||||
assert len(got) == len(texts)
|
||||
for text, owner, line in zip(texts, owners, got):
|
||||
checked += 1
|
||||
have = json.loads(line)
|
||||
if have == pattern.findall(text):
|
||||
continue
|
||||
if unicodedata.category(chr(owner)) == 'Cn':
|
||||
skew += 1
|
||||
else:
|
||||
real.append(f'U+{owner:04X} text={text!r}: regex={pattern.findall(text)!r} fancy={have!r}')
|
||||
return checked, skew, real
|
||||
|
||||
|
||||
def train_bpe(rng, merges_wanted=700):
|
||||
"""Byte-level BPE merges over a synthetic multilingual corpus, in GGUF order (tokens, merges)."""
|
||||
b2u = T.BYTE_TO_UNICODE
|
||||
pattern = regex.compile(T.QWEN35_PATTERN)
|
||||
pools = ['the quick brown fox jumps over the lazy dog ', 'def foo(bar):\n return bar + 1\n', '你好,世界!今日は天気です。',
|
||||
'héllo wörld ça va ', 'Привет мир, как дела? ', 'x = [1, 2, 3] # list\n', "it's don't we're I'll they've ",
|
||||
'😀🚀 emoji ', 'aaaa' * 40, 'abababababab' * 30, 'tool_call response result ']
|
||||
words = {}
|
||||
for _ in range(1500):
|
||||
text = ''.join(rng.choice(pools) for _ in range(rng.randint(1, 4)))
|
||||
for piece in pattern.findall(text):
|
||||
word = tuple(b2u[b] for b in piece.encode('utf-8'))
|
||||
words[word] = words.get(word, 0) + 1
|
||||
for n in (70, 100, 130): # long words that exercise the heap path (> 64 symbols)
|
||||
words[tuple('a' for _ in range(n))] = 50
|
||||
words[tuple(b2u[b] for b in ('ab' * n).encode())] = 40
|
||||
words[tuple(b2u[b] for b in ('中文' * n).encode())] = 30
|
||||
merges = []
|
||||
for _ in range(merges_wanted):
|
||||
counts = {}
|
||||
for word, freq in words.items():
|
||||
for pair in zip(word, word[1:]):
|
||||
counts[pair] = counts.get(pair, 0) + freq
|
||||
if not counts:
|
||||
break
|
||||
best = max(counts.items(), key=lambda kv: (kv[1], kv[0]))[0]
|
||||
merges.append(best)
|
||||
merged = {}
|
||||
for word, freq in words.items():
|
||||
out, i = [], 0
|
||||
while i < len(word):
|
||||
if i + 1 < len(word) and (word[i], word[i + 1]) == best:
|
||||
out.append(word[i] + word[i + 1])
|
||||
i += 2
|
||||
else:
|
||||
out.append(word[i])
|
||||
i += 1
|
||||
merged[tuple(out)] = merged.get(tuple(out), 0) + freq
|
||||
words = merged
|
||||
tokens = [b2u[b] for b in range(256)]
|
||||
for left, right in merges:
|
||||
tokens.append(left + right)
|
||||
return tokens, [f'{l} {r}' for l, r in merges]
|
||||
|
||||
|
||||
SPECIALS = [('<|im_start|>', 3), ('<|im_end|>', 3), ('<|endoftext|>', 3), ('<think>', 4), ('</think>', 4),
|
||||
('<tool_call>', 4), ('<tool_response>', 4), ('<|a[b|>', 3), ('(x*)', 4), ('<|im_', 3)]
|
||||
|
||||
|
||||
def build_gguf(root, rng):
|
||||
tokens, merges = train_bpe(rng)
|
||||
types = [1] * len(tokens)
|
||||
for text, ty in SPECIALS:
|
||||
tokens.append(text)
|
||||
types.append(ty)
|
||||
n_plain = len(tokens) - len(SPECIALS)
|
||||
meta = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'),
|
||||
('tokenizer.ggml.pre', 'str', 'qwen35'),
|
||||
('tokenizer.ggml.tokens', ('array', 'str'), tokens), ('tokenizer.ggml.merges', ('array', 'str'), merges),
|
||||
('tokenizer.ggml.token_type', ('array', 'i32'), types),
|
||||
('tokenizer.ggml.eos_token_id', 'u32', n_plain + 1), ('tokenizer.ggml.padding_token_id', 'u32', n_plain + 2),
|
||||
('tokenizer.ggml.bos_token_id', 'u32', n_plain),
|
||||
('tokenizer.chat_template', 'str', "{%- for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{%- endfor %}\nünïcode ✓")]
|
||||
path = root / 'synthetic-tokenizer.gguf'
|
||||
write_gguf(path, [('w', [1], 0, bytes(4))], meta)
|
||||
return path, tokens, merges
|
||||
|
||||
|
||||
def stricter_cases(binary, root):
|
||||
"""Inputs the Python tokenizer accepts that the Rust extractor refuses on purpose (each one asserted both ways)."""
|
||||
bad = []
|
||||
b2u = T.BYTE_TO_UNICODE
|
||||
base_tokens = [b2u[b] for b in range(256)] + ['ab']
|
||||
base = [('general.architecture', 'str', 'qwen4exp'), ('tokenizer.ggml.model', 'str', 'gpt2'),
|
||||
('tokenizer.ggml.pre', 'str', 'qwen35'), ('tokenizer.ggml.tokens', ('array', 'str'), base_tokens),
|
||||
('tokenizer.ggml.merges', ('array', 'str'), ['a b']), ('tokenizer.chat_template', 'str', 'tpl')]
|
||||
|
||||
def case(label, meta):
|
||||
path = root / f'stricter-{label}.gguf'
|
||||
write_gguf(path, [('w', [1], 0, bytes(4))], meta)
|
||||
T.Tokenizer.from_gguf(path) # the oracle accepts it
|
||||
r = subprocess.run([binary, 'model', 'extract-tokenizer', str(path), '--output', str(root / f'out-{label}')],
|
||||
capture_output=True, text=True)
|
||||
if r.returncode == 0:
|
||||
bad.append(f'{label}: rust accepted')
|
||||
|
||||
merges = base[4]
|
||||
case('duplicate-merge', [m if m is not merges else ('tokenizer.ggml.merges', ('array', 'str'), ['a b', 'a b'])
|
||||
for m in base])
|
||||
case('no-chat-template', base[:5])
|
||||
case('negative-special-id', base + [('tokenizer.ggml.padding_token_id', 'i32', -1)])
|
||||
return bad
|
||||
|
||||
|
||||
def compare_extraction(binary, gguf, root):
|
||||
bad = []
|
||||
py_out, rs_out = root / 'py', root / 'rs'
|
||||
T.extract(gguf, py_out)
|
||||
r = subprocess.run([binary, 'model', 'extract-tokenizer', str(gguf), '--output', str(rs_out)],
|
||||
capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
return [f'extract-tokenizer failed: {r.stderr[-200:]}']
|
||||
a, b = py_out / 'tokenizer', rs_out / 'tokenizer'
|
||||
if sorted(p.name for p in a.iterdir()) != sorted(p.name for p in b.iterdir()):
|
||||
bad.append('file sets differ')
|
||||
for name in ('vocab.json', 'token_type.json'):
|
||||
if json.loads((a / name).read_text('utf-8')) != json.loads((b / name).read_text('utf-8')):
|
||||
bad.append(f'{name} differs')
|
||||
for name in ('merges.txt', 'chat_template.jinja'):
|
||||
if (a / name).read_bytes() != (b / name).read_bytes():
|
||||
bad.append(f'{name} differs')
|
||||
ca, cb = json.loads((a / 'tokenizer.json').read_text('utf-8')), json.loads((b / 'tokenizer.json').read_text('utf-8'))
|
||||
if ca != cb:
|
||||
bad.append(f'tokenizer.json differs: {[(k, ca.get(k), cb.get(k)) for k in set(ca) | set(cb) if ca.get(k) != cb.get(k)]}')
|
||||
return bad
|
||||
|
||||
|
||||
BOUNDARY = ['', ' ', 'Hello, world!', ' leading and trailing ', 'a\n\n\nb', 'def f(x):\n\treturn x # comment\n',
|
||||
'你好,世界', 'مرحبا', '\U0001f600\U0001f680\U0001f1fa\U0001f1f8', 'é́ combining', '\x00\x01\x7f control',
|
||||
' non-breaking space', '1234567890', 'MixedCASE_and-dashes', '\r\n\r\n', '
', 'x' * 5000,
|
||||
"it's don't WE'RE I'LL they've 'D 'm", '<|im_start|>user\nhi<|im_end|>\n', '<|im_star', '<|im_', '<think>x</think>',
|
||||
'<tool_call><tool_response>', '(x*)(x*)', '<|a[b|>', 'a<|im_end|>b<|endoftext|>', '<<|im_end|>>',
|
||||
'中' * 3000, '中文' * 600, 'a' * 500, 'ab' * 400, 'a' * 64, 'a' * 65, 'ab' * 32, 'ab' * 33,
|
||||
'तुम्हें नमस्ते', 'ก็ไป', '́leading mark', '٣١٢ ½ Ⅷ ² 𝟘', '\x1c\x1d\x1e\x1f', '\x85 ',
|
||||
' \n \n ', 'a b c d', ' \n', '\n ', '!!!\n\n', 'ab', '👨👩👧', 'BOM', '�',
|
||||
'"quoted"', 'path/to/file.txt', 'a.b.c', 'x.y_z-9']
|
||||
|
||||
|
||||
def fuzz_text(rng):
|
||||
pools = [
|
||||
list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), list('0123456789'), list(' \t\n\r\x0b\x0c'),
|
||||
list("'s't're've'm'll'd'S'T'RE"), list('.,;:!?()[]{}<>/\\|_-+=*&^%$#@~`"'),
|
||||
list('ً̀́̂̈҃ؐͅऀ़ั⃐️\U000e0100'),
|
||||
list('éüñßçøåÆŒΩλπΣЖЯ中文日本語한국어กขคअआइ'), list('٣١٢½Ⅷ²𝟘¼'),
|
||||
list('
\x85\x1c\x1f'),
|
||||
list('�'), list('😀😂🚀🎉👨👩👧🏳🌈'), [chr(i) for i in range(0, 32)],
|
||||
['<|im_start|>', '<|im_end|>', '<think>', '</think>', '<tool_call>', '<|im_', '(x*)', '<|a[b|>'],
|
||||
['ab', 'abab', 'aaaa', 'tool', 'call', 'the ', 'ing ', 'ion', '中文'],
|
||||
]
|
||||
out = []
|
||||
for _ in range(rng.choice([1, 3, 8, 20, 60, 200])):
|
||||
pool = rng.choice(pools)
|
||||
out.append(rng.choice(pool))
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def compare_tokenization(binary, gguf, root, fuzz, rng):
|
||||
bad = []
|
||||
tk = T.Tokenizer.from_gguf(gguf)
|
||||
tok_dir = str(root / 'rs' / 'tokenizer')
|
||||
texts = BOUNDARY + [fuzz_text(rng) for _ in range(fuzz)]
|
||||
lines = [json.dumps(t) for t in texts]
|
||||
for special in (False, True):
|
||||
got = run_batch(binary, ['tokenize-batch', tok_dir] + (['--special'] if special else []), lines)
|
||||
for text, line in zip(texts, got):
|
||||
want = tk.encode(text, parse_special=special)
|
||||
have = json.loads(line)
|
||||
if have != want:
|
||||
bad.append(f'encode(special={special}) {text[:60]!r}: python {want[:12]}.. rust {str(have)[:80]}')
|
||||
if len(bad) > 15:
|
||||
return bad
|
||||
# decode: the ids Python produced, plus random id lists (multi-byte characters split across tokens)
|
||||
id_lists = [tk.encode(t, parse_special=True) for t in texts]
|
||||
n = len(tk.tokens)
|
||||
for _ in range(max(200, fuzz // 4)):
|
||||
id_lists.append([rng.randrange(n) for _ in range(rng.randint(0, 30))])
|
||||
got = run_batch(binary, ['detokenize-batch', tok_dir], [json.dumps(ids) for ids in id_lists])
|
||||
for ids, line in zip(id_lists, got):
|
||||
try:
|
||||
want = tk.decode(ids)
|
||||
except KeyError:
|
||||
want = None # a special token such as <|im_ is not in the byte alphabet (neither side decodes)
|
||||
if json.loads(line) != want:
|
||||
bad.append(f'decode {ids[:10]}: python {want!r} rust {line[:80]}')
|
||||
if len(bad) > 15:
|
||||
break
|
||||
return bad
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
opt = lambda name, default: int(args[args.index(name) + 1]) if name in args else default
|
||||
binary = str(Path(args[0]).resolve())
|
||||
stride, fuzz, seed = opt('--stride', 1), opt('--fuzz', 4000), opt('--seed', 20261014)
|
||||
rng = random.Random(seed)
|
||||
failures = []
|
||||
root = Path(tempfile.mkdtemp(prefix='strata-tokenizer-diff-'))
|
||||
gguf, tokens, merges = build_gguf(root, rng)
|
||||
failures += ['extract: ' + b for b in compare_extraction(binary, gguf, root)]
|
||||
failures += ['stricter: ' + b for b in stricter_cases(binary, root)]
|
||||
failures += ['tokenize: ' + b for b in compare_tokenization(binary, gguf, root, fuzz, rng)]
|
||||
checked, skew, real = per_codepoint(binary, stride)
|
||||
failures += ['pre-tokenize: ' + b for b in real]
|
||||
for f in failures[:50]:
|
||||
print('FAIL', f[:400])
|
||||
print(json.dumps({'pretokenizer_strings_checked': checked, 'unicode17_table_skew_strings': skew, 'pretokenizer_real_mismatches': len(real),
|
||||
'vocab': len(tokens), 'merges': len(merges), 'fuzz_texts': fuzz, 'failures': len(failures),
|
||||
'oracle': 'tools/strata_tokenizer.py (unmodified) with regex ' + regex.__version__}))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -81,6 +81,52 @@ def gguf_headers():
|
||||
(OUT / 'gguf_headers.json').write_text(json.dumps({'cases': cases, 'geometry': geometry}, separators=(',', ':')) + '\n')
|
||||
|
||||
|
||||
@golden
|
||||
def tokenizer_oracle():
|
||||
"""Synthetic byte-level BPE vocabulary + what the unmodified tools/strata_tokenizer.py produces for it:
|
||||
pre-tokenizer splits (sampled code points), encode with/without special parsing, decode."""
|
||||
import random
|
||||
import unicodedata
|
||||
import diff_tokenizer as D
|
||||
import regex
|
||||
import strata_tokenizer as T
|
||||
rng = random.Random(20261014)
|
||||
tokens, merges = D.train_bpe(rng, 300)
|
||||
types = [1] * len(tokens)
|
||||
for text, ty in D.SPECIALS:
|
||||
tokens.append(text)
|
||||
types.append(ty)
|
||||
tk = T.Tokenizer(tokens, merges, types, 'qwen35', {})
|
||||
texts = [t for t in D.BOUNDARY if len(t) <= 1200] + [D.fuzz_text(rng) for _ in range(120)]
|
||||
texts = [t for t in texts if len(t) <= 1200]
|
||||
cases = [{'text': t, 'plain': tk.encode(t), 'special': tk.encode(t, parse_special=True)} for t in texts]
|
||||
id_lists = [c['special'] for c in cases[:40]] + [[rng.randrange(len(tokens)) for _ in range(rng.randint(0, 20))]
|
||||
for _ in range(60)]
|
||||
decodes = []
|
||||
for ids in id_lists:
|
||||
try:
|
||||
decodes.append({'ids': ids, 'text': tk.decode(ids)})
|
||||
except KeyError:
|
||||
decodes.append({'ids': ids, 'text': None})
|
||||
pattern = regex.compile(T.QWEN35_PATTERN)
|
||||
splits = []
|
||||
for c in range(0, 0x110000, 4001):
|
||||
if 0xD800 <= c <= 0xDFFF or unicodedata.category(chr(c)) == 'Cn':
|
||||
continue
|
||||
for ctx in ('{c}', 'a{c}', '{c}a', ' {c}', '{c}\n'):
|
||||
text = ctx.format(c=chr(c))
|
||||
splits.append({'text': text, 'pieces': pattern.findall(text)})
|
||||
for t in texts:
|
||||
if len(t) <= 200:
|
||||
splits.append({'text': t, 'pieces': pattern.findall(t)})
|
||||
out = {'tokens': tokens, 'merges': merges, 'token_types': types, 'cases': cases, 'decodes': decodes,
|
||||
'pre_tokenizer': splits, 'regex_version': regex.__version__}
|
||||
target = REPO / 'crates/tokenizer/tests/fixtures'
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
(target / 'tokenizer_oracle.json').write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')) + '\n',
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
names = sys.argv[1:] or list(GENERATORS)
|
||||
|
||||
Reference in New Issue
Block a user