Commit ·
2d4c842
1
Parent(s): 14fb526
Add multi-agent tokenizer judging benchmark
Browse filesFiles changed (10)
- EVIDENCE_REVIEW.mdAdded+125
- README.md+38
- benchmark_tokenizers.pyAdded+212
- custom_tokenizer_adapters.pyAdded+166
- evaluation/README.mdAdded+32
- evaluation/polish_suite.jsonlAdded+20
- results/author_evidence_scores.csvAdded+8
- results/tokenizer_benchmark.jsonAdded
- results/tokenizer_benchmark.parquetAdded+3
- test_custom_tokenizer_adapters.pyAdded+24
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# Independent submission evidence review
Scope: the seven contributor folders selected for the normalized dataset at source commit`1a5cd2c2e4df2287b4c19b3dbf5051f5d460fdc1`. This is a review of submitted evidence,documentation, and reproducibility—not a ranking of tokenizer quality. Author-reportedcompression values use different corpora, held-outs, vocabulary sizes, and word definitionsand are therefore not compared across authors.
## Rubric
Each dimension is scored 0–4 (maximum 20):
- **Artifact usability:** complete runtime artifact, loadability, round-trip/special-token readiness.- **Documentation:** design, data, configuration, outputs, and limitations are explained.- **Evaluation protocol:** held-out construction, denominators, controls, stress tests, and baselines.- **Reproducibility:** committed code, pinned inputs, seeds/environment, and runnable evaluation.- **Claims discipline:** conclusions match evidence; confounds and non-comparability are acknowledged.
The score measures strength of the evidence package only. It must not be combined with futurecommon-corpus benchmark results as if it were a tokenizer-performance score.
## Results
| GitHub author | Artifact | Docs | Protocol | Repro | Claims | Total | Evidence judgment ||---|---:|---:|---:|---:|---:|---:|---|| `KateMajzel` | 4 | 4 | 4 | 2 | 4 | **18** | Strongest controlled-methodology package; excellent failure analysis and explicit limits. || `janbanot` | 4 | 4 | 3 | 1 | 4 | **16** | Broadest qualitative/stress analysis and a directly loadable final artifact; exact split/code absent. || `Maggio333` | 2 | 4 | 4 | 1 | 4 | **15** | Deepest research narrative and unusually good caveats; custom runtime and missing scripts prevent replay. || `olajachymiak` | 2 | 4 | 4 | 1 | 4 | **15** | Strong progression of controlled experiments and candid overfitting analysis; referenced scripts absent. || `dawidmajewski` | 4 | 3 | 2 | 1 | 3 | **13** | Seven loadable artifacts and concrete corpus/source tables; mostly exploratory, with no fixed replay harness. || `ktalik` | 4 | 2 | 1 | 1 | 2 | **10** | Loadable minimal tokenizer plus interactive plots; sparse protocol and referenced training/report code absent. || `p4pryk` | 1 | 3 | 2 | 1 | 2 | **9** | Useful design explanation and corpus accounting, but only a custom vocab/merge map was submitted. |
## Per-author findings
### `KateMajzel` (source folder `KasiaMP`)
- Best evidence of experimental hygiene: identical stated corpus size (9,363,020 chars), matched total vocab (6,756), shared 2,696-character/371-word held-out, and the same word denominator.- Documents and repairs serialization loss, boilerplate contamination, corpus reconstruction drift, and the 6,500-merges versus 6,756-total-vocab convention. Four HF artifacts load directly.- Excellent claims discipline: calls the 1.3% spread inconclusive and explicitly lists limitations.- Reproduction gap: no training/evaluation code, held-out text, corpus manifest/hash, seed, lockfile, or one-command replay is present. Character count is a useful check but not a cryptographic identity.
### `janbanot` (source folder `Janek`)
- Directly loadable HF ByteLevel BPE (8,192); comprehensive discussion of corpus balancing, vocabulary sweep, utilization, morphology, multilingual/emoji/numeric/code stress cases, and limits.- Small peer-baseline suite is clearly described as contextual rather than a definitive benchmark.- Protocol gap: the exact held-out composition/identity and split procedure are not committed, and neither training nor evaluation code is present. Reported tables therefore cannot be replayed.
### `Maggio333` (source folder `Arek`)
- Most ambitious research account: matched-vocab pre-tokenizer comparisons, vocabulary curve, distribution-shift matrix, compute-head trade-off, Renyi efficiency, and morphology caveats.- Explicitly warns that different held-outs cannot be compared and that compression is not downstream model quality. That restraint is exemplary.- All 17 artifacts use a custom BPE serialization and fail direct HF `Tokenizer.from_file` loading. A loading sketch is documented, but the actual encoder/pre-tokenizer implementation is absent.- Major replay gap: referenced `vocab_cost.py`, training/evaluation code, exact data manifests, held-out artifacts, and environment are not in the repository. Several broad empirical claims are supported only by prose/tables embedded in the README.
### `olajachymiak` (source folder `ola`)
- Strong pedagogical chain: controls corpus at vocab 512, controls vocab on one corpus, exposes the in-domain `Quo Vadis` illusion, then builds an 8k diverse/pretokenized version.- Clearly reports train/held-out boundary for the book experiment, exact held-out counts, round-trip, overfitting mechanisms, and remaining weaknesses.- All four JSONs are custom experiment bundles rather than directly loadable HF serializations.- Referenced `homework_diverse.py` and `homework_vocab_sweep.py` are absent, as are the exact corpora, corpus hashes, environment, and executable evaluator. The final Pan Tadeusz result is not a fully out-of-domain test because the training mix is still majority Polish literature.
### `dawidmajewski` (source folder `dawidm`)
- Seven submitted tokenizer files load directly. The writeup gives source URLs/revisions for test snippets, corpus sizes, regex, vocab variants, round-trip claim, and raw token-count tables.- The author accurately labels the work exploratory rather than research, which appropriately limits claims.- Training-corpus fertility appears to be reported alongside short out-of-corpus token counts; there is no fixed held-out benchmark across every model, no vocabulary-utilization analysis, and no statistical treatment. Code, pinned training inputs, preprocessing, seeds, and evaluator are absent.
### `ktalik` (source folder `Konrad`)
- Submitted 456-vocab HF ByteLevel BPE loads directly; three HTML plots preserve some experimental output.- README states SJP scale, merge sweep, and an aggregate token-count trend.- The claimed `bpe.py` and `report.py` are not committed. No train/eval split, exact word list, preprocessing, denominator, round-trip suite, corpus version/license, or reproducible command is given.
### `p4pryk` (source folder `patryk`)
- Explains ByteLevel motivation, a Polish regex, balanced DynaWord/Wikipedia sampling, length/newline constraints, exact stated training character count, and a Pan Tadeusz evaluation.- Submitted JSON is only a custom vocabulary/merge mapping, not a complete runtime tokenizer; it lacks normalizer, pre-tokenizer, decoder, added-token policy, and a runnable loader.- No code, exact data manifest/hash, held-out artifact, environment, or evaluation command is present. Phrases such as "commercial standard", "ideal", and character compression as taking less storage overstate what round-trip and token-count results establish. The held-out may also be adjacent in literary domain to some training sources.
## Cross-submission conclusions
1. **Do not select a winner from reported metrics.** Vocabulary ranges from 456 to 512,000 and evaluation domains range from the training corpus to held-out book tails, Pan Tadeusz, SpeakLeash, and tiny probe suites.2. **Artifact readiness differs sharply.** `KateMajzel`, `janbanot`, `dawidmajewski`, and `ktalik` have at least one directly loadable HF artifact. The others need author-specific adapters or reconstruction.3. **No submission is fully reproducible from this repository.** The repository contains no contributor training/evaluation scripts; exact evaluation texts and dependency environments are also absent.4. **Documentation distinction:** strongest controlled-methodology evidence is `KateMajzel`; broadest research analysis is `Maggio333`; broadest practical stress analysis is `janbanot`; clearest controlled learning progression is `olajachymiak`.5. **Next judging step:** run loadable artifacts (and validated adapters for custom formats) through one versioned, multi-domain Polish test manifest. Publish per-domain metrics and Pareto fronts within vocab bands; keep this evidence score as a separate reproducibility/documentation axis.
## Minimum evidence upgrade requested from every author
- `train.py` and `evaluate.py` (or notebook exported with deterministic cells), dependency lock, and commands.- Corpus source/version/license, preprocessing config, byte count plus SHA-256, and deterministic split rule.- Committed held-out manifest or hashes, explicit word-count definition, round-trip/stress test corpus.- Standard `tokenizer.json` plus special-token configuration, or a versioned adapter with parity tests.- Machine-readable result JSON containing tokenizer hash, dataset hash, code commit, environment, and timings.5 unmodified lines6789101142 unmodified lines5455565 unmodified linesdata_files:- split: trainpath: data/train-*.parquet---# SlayerLab Tokenizers42 unmodified linesuseful for inspecting an individual submission but not for ranking authors. Afair quality ranking requires running every compatible tokenizer against thesame held-out Polish evaluation corpus.5 unmodified lines67891011121314151617181942 unmodified lines6263646566676869707172737475767778798081828384858687888990919293945 unmodified linesdata_files:- split: trainpath: data/train-*.parquet- config_name: benchmarkdata_files:- split: testpath: results/tokenizer_benchmark.parquet- config_name: evidence_reviewdata_files:- split: reviewpath: results/author_evidence_scores.csv---# SlayerLab Tokenizers42 unmodified linesuseful for inspecting an individual submission but not for ranking authors. Afair quality ranking requires running every compatible tokenizer against thesame held-out Polish evaluation corpus.## Common diagnostic benchmarkThe `benchmark` configuration evaluates all 39 artifacts on the same versioned,ten-domain Polish diagnostic suite. Fourteen run natively through the Rust`tokenizers` library and 25 run through the included custom-format adapters.- 39/39 artifacts executed successfully.- 32 are reconstructed exactly; 7 are `core_only` because their intendedpre-tokenizer was not serialized.- 37/39 preserve exact input; two normalized `KateMajzel` variants convert atab to a space.- No unknown tokens were observed in this suite.The benchmark reports compression, round-trip behavior, unknown-token rate,per-domain results, serialized size, and local throughput. Throughput is onlycomparable within the same `runtime`; Python reference adapters must not bespeed-ranked against native Rust tokenizers.This is a small synthetic diagnostic corpus, not a statistically representativeheld-out benchmark and not evidence of downstream language-model quality. Rawcompression must be compared within vocabulary-size bands.## Evidence reviewThe `evidence_review` configuration separately scores artifact usability,documentation, evaluation protocol, reproducibility, and claims discipline.These scores judge the submitted evidence package—not tokenizer performance—andmust not be combined with compression metrics into a single winner score. See`EVIDENCE_REVIEW.md` for the full evidence and limitations.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212#!/usr/bin/env python3"""Benchmark every tokenizer JSON row on one fixed Polish suite.
The benchmark is diagnostic, not a downstream-language-model quality score.All tokenizers see exactly the same strings and are loaded from the lossless``tokenizer_json`` column, so no contributor-specific files are required."""
from __future__ import annotations
import argparseimport hashlibimport importlib.metadataimport jsonimport platformimport reimport statisticsimport timefrom collections import Counterfrom pathlib import Path
import pyarrow as paimport pyarrow.parquet as pqfrom tokenizers import Tokenizer
from custom_tokenizer_adapters import AdaptedTokenizer, load_custom_tokenizer_document
WORD_RE = re.compile(r"\w+", re.UNICODE)
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--input", type=Path, default=Path("data/train-00000-of-00001.parquet")) parser.add_argument("--suite", type=Path, default=Path("evaluation/polish_suite.jsonl")) parser.add_argument("--output", type=Path, default=Path("results/tokenizer_benchmark.parquet")) parser.add_argument("--summary-json", type=Path, default=Path("results/tokenizer_benchmark.json")) parser.add_argument("--repeats", type=int, default=15, help="Timed batch repetitions") return parser.parse_args()
def load_suite(path: Path) -> list[dict[str, str]]: records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] if not records or any(set(record) != {"domain", "text"} for record in records): raise ValueError("suite must contain non-empty JSONL records with exactly domain and text") return records
def timed_median(function, repeats: int) -> float: samples = [] for _ in range(repeats): start = time.perf_counter_ns() function() samples.append((time.perf_counter_ns() - start) / 1e9) return statistics.median(samples)
def encode_batch(tokenizer: Tokenizer | AdaptedTokenizer, texts: list[str]) -> list[list[int]]: if isinstance(tokenizer, Tokenizer): return [encoding.ids for encoding in tokenizer.encode_batch(texts, add_special_tokens=False)] return [tokenizer.encode(text) for text in texts]
def decode_batch(tokenizer: Tokenizer | AdaptedTokenizer, batches: list[list[int]]) -> list[str]: if isinstance(tokenizer, Tokenizer): return tokenizer.decode_batch(batches, skip_special_tokens=False) return [tokenizer.decode(ids) for ids in batches]
def counts_for(tokenizer: Tokenizer | AdaptedTokenizer, records: list[dict[str, str]]) -> tuple[dict, list, list]: texts = [record["text"] for record in records] id_batches = encode_batch(tokenizer, texts) unk_id = tokenizer.token_to_id("<unk>") if isinstance(tokenizer, Tokenizer) else None model_unk = None try: model_unk = json.loads(tokenizer.to_str()).get("model", {}).get("unk_token") if isinstance(tokenizer, Tokenizer) else None except (TypeError, json.JSONDecodeError): pass if model_unk: unk_id = tokenizer.token_to_id(model_unk)
result = Counter() failures = [] decoded_batch = decode_batch(tokenizer, id_batches) for record, ids, decoded in zip(records, id_batches, decoded_batch): text = record["text"] result["texts"] += 1 result["chars"] += len(text) result["bytes"] += len(text.encode("utf-8")) result["words"] += len(WORD_RE.findall(text)) result["tokens"] += len(ids) if unk_id is not None: result["unks"] += sum(token_id == unk_id for token_id in ids) if decoded != text: result["roundtrip_failures"] += 1 failures.append({"domain": record["domain"], "text": text, "decoded": decoded}) return dict(result), id_batches, failures
def ratios(counts: dict) -> dict: tokens = counts.get("tokens", 0) words = counts.get("words", 0) return { "text_count": counts.get("texts", 0), "word_count": words, "token_count": tokens, "tokens_per_word": tokens / words if words else None, "chars_per_token": counts.get("chars", 0) / tokens if tokens else None, "bytes_per_token": counts.get("bytes", 0) / tokens if tokens else None, "unk_rate": counts.get("unks", 0) / tokens if tokens else None, "roundtrip_failures": counts.get("roundtrip_failures", 0), "roundtrip_pass": counts.get("roundtrip_failures", 0) == 0, }
def main() -> None: args = parse_args() if args.repeats < 1: raise ValueError("--repeats must be positive") suite = load_suite(args.suite) table = pq.read_table(args.input) rows = table.to_pylist() texts = [record["text"] for record in suite] total_bytes = sum(len(text.encode("utf-8")) for text in texts) results = []
for source in rows: base = {key: source[key] for key in ("author", "name", "size", "sha256", "source_path")} try: if source["hf_loadable"]: tokenizer: Tokenizer | AdaptedTokenizer = Tokenizer.from_str(source["tokenizer_json"]) adapter_status = "native" adapter_fidelity = "exact" adapter_note = "Native Hugging Face Tokenizers artifact; no adapter used." adapter_source_format = "hf_tokenizers" runtime = "rust_tokenizers" else: adapted = load_custom_tokenizer_document( json.loads(source["tokenizer_json"]), source["source_path"] ) tokenizer = adapted adapter_status = "custom_adapter" # Only fully serialized behavior is exact. Documented-but-not- # serialized pre-tokenization remains core_only for judging. adapter_fidelity = "exact" if adapted.fidelity == "exact" else "core_only" adapter_note = adapted.fidelity_note adapter_source_format = adapted.source_format runtime = "python_reference_adapter" encode_batch(tokenizer, texts) # warm-up total, id_batches, failures = counts_for(tokenizer, suite) encode_seconds = timed_median( lambda: encode_batch(tokenizer, texts), args.repeats ) decode_seconds = timed_median( lambda: decode_batch(tokenizer, id_batches), args.repeats ) domains = {} for domain in sorted({record["domain"] for record in suite}): domain_counts, _, _ = counts_for( tokenizer, [record for record in suite if record["domain"] == domain] ) domains[domain] = ratios(domain_counts) result = { **base, "status": "ok", "adapter_status": adapter_status, "adapter_fidelity": adapter_fidelity, "adapter_note": adapter_note, "adapter_source_format": adapter_source_format, "runtime": runtime, **ratios(total), "encode_mb_per_s": total_bytes / 1_000_000 / encode_seconds, "decode_mb_per_s": total_bytes / 1_000_000 / decode_seconds, "serialized_bytes": len(source["tokenizer_json"].encode("utf-8")), "domain_metrics_json": json.dumps(domains, ensure_ascii=False, sort_keys=True), "roundtrip_examples_json": json.dumps(failures[:3], ensure_ascii=False), "error": "", } except Exception as exc: # retain failed rows instead of silently changing the cohort result = {**base, "status": "error", "error": f"{type(exc).__name__}: {exc}"} results.append(result)
metadata = { "suite": str(args.suite), "suite_sha256": hashlib.sha256(args.suite.read_bytes()).hexdigest(), "suite_records": len(suite), "suite_bytes": total_bytes, "repeats": args.repeats, "timer": "median wall-clock batch time after one warm-up", "python": platform.python_version(), "tokenizers": importlib.metadata.version("tokenizers"), "pyarrow": importlib.metadata.version("pyarrow"), "platform": platform.platform(), } args.output.parent.mkdir(parents=True, exist_ok=True) args.summary_json.parent.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(results), args.output, compression="zstd") args.summary_json.write_text( json.dumps({"benchmark_metadata": metadata, "results": results}, ensure_ascii=False, indent=2), encoding="utf-8", ) print(json.dumps(metadata, indent=2)) for result in sorted(results, key=lambda row: (row.get("tokens_per_word", float("inf")), row["author"])): print( result["author"], result["name"], result["status"], f"tpw={result.get('tokens_per_word', float('nan')):.4f}", f"roundtrip_failures={result.get('roundtrip_failures', '-')}" )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166#!/usr/bin/env python3"""Load and evaluate the non-Hugging-Face tokenizer JSONs in this dataset.
The adapters deliberately do not pretend that missing configuration is known.``load_custom_tokenizer`` returns a usable byte-level BPE core, plus a fidelityclassification describing whether its intended pre-tokenization is reproduciblefrom the artifact alone."""
from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Callable
try: import regexexcept ImportError: # pragma: no cover - surfaced only for regex tokenizers regex = None
GPT2_PATTERN = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"
def bytes_to_unicode() -> dict[int, str]: """The reversible byte alphabet used by GPT-2/minBPE-style artifacts.""" visible = list(range(ord("!"), ord("~") + 1)) visible += list(range(ord("¡"), ord("¬") + 1)) visible += list(range(ord("®"), ord("ÿ") + 1)) chars = visible[:] extra = 0 for byte in range(256): if byte not in visible: visible.append(byte) chars.append(256 + extra) extra += 1 return dict(zip(visible, map(chr, chars)))
@dataclassclass AdaptedTokenizer: source_format: str fidelity: str fidelity_note: str vocab_size: int merge_count: int merge_ranks: dict[tuple[int, int], int] token_bytes: dict[int, bytes] pretokenizer: Callable[[str], list[str]] | None = None
def _encode_bytes(self, data: bytes) -> list[int]: ids = list(data) while len(ids) >= 2: candidate = min( ((self.merge_ranks[pair], pair) for pair in zip(ids, ids[1:]) if pair in self.merge_ranks), default=None, ) if candidate is None: break new_id, pair = candidate out: list[int] = [] i = 0 while i < len(ids): if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair: out.append(new_id) i += 2 else: out.append(ids[i]) i += 1 ids = out return ids
def encode(self, text: str) -> list[int]: chunks = self.pretokenizer(text) if self.pretokenizer else [text] return [token for chunk in chunks for token in self._encode_bytes(chunk.encode("utf-8"))]
def decode(self, ids: list[int]) -> str: return b"".join(self.token_bytes[token] for token in ids).decode("utf-8")
def _regex_split(pattern: str) -> Callable[[str], list[str]]: if regex is None: raise RuntimeError("The 'regex' package is required by this tokenizer") compiled = regex.compile(pattern) return lambda text: compiled.findall(text)
def _from_symbol_bpe(document: dict, path: Path) -> AdaptedTokenizer: model = document["model"] vocab: dict[str, int] = model["vocab"] byte_for_symbol = {symbol: byte for byte, symbol in bytes_to_unicode().items()} token_bytes: dict[int, bytes] = {} for symbol, token_id in vocab.items(): token_bytes[token_id] = bytes(byte_for_symbol[c] for c in symbol)
ranks = {} for line in model["merges"]: left, right = line.split(" ") ranks[(vocab[left], vocab[right])] = vocab[left + right]
meta = document.get("meta", {}) variant = str(meta.get("variant", "")) if "naive" in path.name: pretok, fidelity, note = None, "exact", "Artifact specifies no pre-tokenization." elif "slayer-v2" in path.name: # README specifies cl100k + full digit runs, but the exact cl100k # expression is not serialized. This is enough to inspect the BPE core, # not enough to claim benchmark parity. pretok, fidelity, note = None, "core_only", "Exact cl100k pre-tokenizer is absent from JSON; BPE core is lossless but intended boundaries are not reproducible from the artifact alone." elif isinstance(meta.get("regex_pretok"), str): pretok, fidelity, note = _regex_split(meta["regex_pretok"]), "exact", "Exact pre-tokenizer regex is serialized in artifact metadata." elif variant == "fast": pretok, fidelity, note = _regex_split(GPT2_PATTERN), "documented", "README identifies GPT-2 pre-tokenization, but the exact expression is not serialized." else: pretok, fidelity, note = None, "core_only", "Pre-tokenization is not fully specified." return AdaptedTokenizer("symbol_bpe", fidelity, note, len(vocab), len(ranks), ranks, token_bytes, pretok)
def _from_integer_bpe(document: dict) -> AdaptedTokenizer: merges = document.get("merges") or document.get("reguly_merge") vocab = document["vocab"] ranks = {(int(left), int(right)): int(new) for left, right, new in merges} # Merge triples are the authoritative lossless representation. Some early # Kasia artifacts rendered invalid standalone UTF-8 bytes as U+FFFD in # ``vocab``; reconstructing recursively avoids inheriting that display loss. token_bytes = {token_id: bytes([token_id]) for token_id in range(256)} for left, right, new in merges: token_bytes[int(new)] = token_bytes[int(left)] + token_bytes[int(right)]
pattern = document.get("pretokenizer_regex") if pattern: pretok, fidelity, note = _regex_split(pattern), "exact", "Pre-tokenizer regex is serialized in the artifact." else: pretok, fidelity, note = None, "exact", "Artifact defines raw-stream byte BPE without pre-tokenization." return AdaptedTokenizer("integer_bpe", fidelity, note, len(vocab), len(ranks), ranks, token_bytes, pretok)
def _from_vocab_export(document: dict) -> AdaptedTokenizer: inverse = {symbol: byte for byte, symbol in bytes_to_unicode().items()} vocab: dict[str, int] = document["token_to_id"] token_bytes = {token_id: bytes(inverse[c] for c in symbol) for symbol, token_id in vocab.items()} ranks = {(int(left), int(right)): int(new) for left, right, new in document["merges"]} return AdaptedTokenizer( "vocab_export", "core_only", "Vocabulary and merge ranks are complete, but the intended Polish regex pre-tokenizer is documented only in the write-up, not serialized in JSON.", len(vocab), len(ranks), ranks, token_bytes, None, )
def load_custom_tokenizer(path: str | Path) -> AdaptedTokenizer: path = Path(path) document = json.loads(path.read_text(encoding="utf-8")) return load_custom_tokenizer_document(document, path)
def load_custom_tokenizer_document(document: dict, source_path: str | Path) -> AdaptedTokenizer: """Load an artifact already parsed from JSON, retaining its source filename hints.""" path = Path(source_path) if isinstance(document.get("model"), dict) and isinstance(document["model"].get("merges"), list): return _from_symbol_bpe(document, path) if "token_to_id" in document and "merges" in document: return _from_vocab_export(document) if ("merges" in document or "reguly_merge" in document) and "vocab" in document: return _from_integer_bpe(document) raise ValueError(f"Unsupported custom tokenizer schema: {path}")1234567891011121314151617181920212223242526272829303132# Polish tokenizer diagnostic suite
`polish_suite.jsonl` is a fixed, synthetic stress suite written for thisrepository on 2026-08-26. It has not been copied from a corpus and makes noclaim of being held out from tokenizer training data. Each domain contains twoshort examples so domain metrics are useful for inspection, not statisticalinference.
Run the benchmark with:
```bashpython3 benchmark_tokenizers.py```
All dataset rows are retained. Native Hugging Face artifacts have`adapter_status=native`; other formats use the local reference adapter. An`adapter_fidelity` of `exact` means the serialized artifact contains enoughinformation to reproduce its behavior. `core_only` means the byte-BPE core islossless but intended pre-tokenization is missing, so its segmentation metricsmust not be ranked as if they represented the author's full tokenizer.
Metrics use Unicode code points for `chars`, UTF-8 bytes for `bytes`, andPython Unicode `\\w+` spans for words. Special tokens are disabled duringencoding and retained during decoding. Throughput is the median of repeatedwhole-suite batches after one warm-up and is only comparable within the samerun, machine, and `runtime`. In particular, `python_reference_adapter` speedmeasures this diagnostic adapter and is not comparable to `rust_tokenizers`.
This suite can catch broken round trips, unknown-token behavior, pathologicalsegmentation, and operational cost differences. It cannot establish modelquality. A defensible final ranking also needs a larger provenance-controlledheld-out corpus and identical downstream language-model experiments.1234567891011121314151617181920{"domain":"general","text":"Zażółć gęślą jaźń — to krótkie zdanie sprawdza wszystkie polskie znaki."}{"domain":"general","text":"W sobotę pojedziemy pociągiem z Gdańska do Krakowa, jeśli pogoda dopisze."}{"domain":"literature","text":"Nad spokojną rzeką zapadał zmierzch, a wilgotne łąki pachniały miętą i sianem."}{"domain":"literature","text":"Nie wiedział jeszcze, że ten niepozorny list odmieni całe jego życie."}{"domain":"news","text":"Rada miasta przyjęła uchwałę większością dwudziestu trzech głosów."}{"domain":"news","text":"Według wstępnych danych inflacja wyniosła 4,7 proc. rok do roku."}{"domain":"legal","text":"Wnioskodawcy przysługuje prawo wniesienia odwołania w terminie czternastu dni."}{"domain":"legal","text":"Na podstawie art. 15 § 2 pkt 3 postępowanie zostało umorzone."}{"domain":"technical","text":"Model wykorzystuje mechanizm uwagi, normalizację warstwową i kwantyzację do czterech bitów."}{"domain":"technical","text":"Uruchom polecenie `python3 -m pytest`, a następnie sprawdź kod wyjścia procesu."}{"domain":"dialogue","text":"— Naprawdę tam byłeś? — zapytała. — Tak, ale nikomu o tym nie mów."}{"domain":"dialogue","text":"Cześć! Możesz mi wysłać ten plik jeszcze dziś? Jasne, zrobię to po 18:00."}{"domain":"web","text":"XD ale sztos 😅 wrzucisz linka na priv? #polska #AI"}{"domain":"web","text":"Kontakt: użytkownik+test@example.org, https://żółw.pl/a?x=1&y=2"}{"domain":"names_numbers","text":"Łódź, Bielsko-Biała, Świętochłowice, Szczebrzeszyn i Nowy Sącz."}{"domain":"names_numbers","text":"Zamówienie PL-2026/08/26 kosztuje 12 345,67 zł, czyli około €2890."}{"domain":"morphology","text":"dom, domu, domem, domowi, domy, domów, domami, domach; najnieprawdopodobniejszego"}{"domain":"morphology","text":"robić, zrobię, zrobiłabyś, robilibyśmy, niezrobionymi, poprzerabiawszy"}{"domain":"unicode_noise","text":"Emoji: 🧠🚀🇵🇱; alfabet: Ελληνικά, кириллица, العربية, 漢字."}{"domain":"unicode_noise","text":"Spacje\t tabulator\nnowa linia; cudzysłowy „polskie”, NBSP i wielokropek…"}12345678author,artifact_usability,documentation,evaluation_protocol,reproducibility,claims_discipline,total,evidence_judgmentKateMajzel,4,4,4,2,4,18,Strongest controlled-methodology package; excellent failure analysis and explicit limits.janbanot,4,4,3,1,4,16,Broadest qualitative and stress analysis with a directly loadable final artifact.Maggio333,2,4,4,1,4,15,Deepest research narrative and strong caveats; missing runtime and scripts limit replay.olajachymiak,2,4,4,1,4,15,Clear controlled experimental progression and candid overfitting analysis.dawidmajewski,4,3,2,1,3,13,Seven loadable artifacts and concrete corpus tables; primarily exploratory evidence.ktalik,4,2,1,1,2,10,Loadable minimal tokenizer and plots but sparse protocol and missing training code.p4pryk,1,3,2,1,2,9,Useful design explanation but only a custom vocabulary and merge map was submitted.123version https://git-lfs.github.com/spec/v1oid sha256:edf17d25ca1c4f8f8056fc7ff0f09885bcd15dd3de06be32232b2ed6303ae548size 31021123456789101112131415161718192021222324import globimport unittest
from custom_tokenizer_adapters import load_custom_tokenizer
ROOT = "/tmp/tokenizer-extract.GBtvQ0/repo"PATTERNS = ["Arek/**/*.json", "KasiaMP/wyniki/tokenizer z boilerplate.json", "KasiaMP/wyniki/wyniki*.json", "ola/*.json", "patryk/*.json"]SAMPLES = ["Zażółć gęślą jaźń.", "Łódź 2026 — € 😀\n\tKoniec"]
class CustomAdaptersTest(unittest.TestCase): def test_every_custom_artifact_roundtrips(self): paths = sorted({p for pattern in PATTERNS for p in glob.glob(f"{ROOT}/{pattern}", recursive=True)}) self.assertEqual(len(paths), 25) for path in paths: with self.subTest(path=path): tokenizer = load_custom_tokenizer(path) for sample in SAMPLES: self.assertEqual(tokenizer.decode(tokenizer.encode(sample)), sample)
if __name__ == "__main__": unittest.main()EVIDENCE_REVIEW.mdAdded+125
README.md+38
benchmark_tokenizers.pyAdded+212
custom_tokenizer_adapters.pyAdded+166
evaluation/README.mdAdded+32
evaluation/polish_suite.jsonlAdded+20
results/author_evidence_scores.csvAdded+8
results/tokenizer_benchmark.jsonAdded
results/tokenizer_benchmark.parquetAdded+3
test_custom_tokenizer_adapters.pyAdded+24