kacperwikiel commited on
Commit
2d4c842
·
1 Parent(s): 14fb526

Add multi-agent tokenizer judging benchmark

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