Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,27 @@ jobs:
# intentionally NOT run in CI (require cargo + crates.io fetch
# and aren't reproducible quickly). Run zig build test only.
run: zig build test --summary all
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Differential gate refusal tests
run: python3 -m unittest discover -s tests -p test_diff_check.py
- name: Install comparison CLI
run: zig build -Doptimize=ReleaseSafe
- name: Frozen original WordPiece fixture
run: python3 tools/check_wordpiece.py
- name: Install pinned upstream oracle
run: python3 -m pip install --only-binary=:all: -r tools/requirements-oracle.txt
- name: Live upstream comparison and punctuation-table identity
run: |
python3 tools/check_wordpiece.py --live
python3 tools/generate_bert_punctuation.py
- name: Fetch pinned real tokenizer JSON files (no weights)
run: python3 tools/fetch_real_fixtures.py
- name: Real-fixture tests and specific model conformance
run: |
zig build test --summary all
python3 tools/check_real_parity.py --model bert
python3 tools/check_real_parity.py --model tinyllama
# T5's known Precompiled-normalizer mismatch remains documented.
# --model all reports it and exits nonzero; it is not a passing parity claim.
33 changes: 27 additions & 6 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
# Current original-fixture check — 12 November 2026

An original 32-token WordPiece fixture and 48 short inputs match HF tokenizers
0.21.4 exactly. The eight-input currency/CJK/Arabic/Indic regression improved
from 2/8 to 8/8. The cause is the BERT pre-tokenizer's block-based punctuation
approximation: it split £, © and 々 and missed Arabic comma/Indic danda.
This is distinct from normalization and from WordPiece's greedy matching.

The generated predicate probes all 1,112,064 Unicode scalars against the pinned
reference pre-tokenizer, yielding 726 punctuation scalars in 156 ranges.
It pins that component's behavior, not the entire pipeline or future Unicode
versions. `tools/check_wordpiece.py --live` checks frozen IDs against the exact
wheel version; `tools/generate_bert_punctuation.py` checks table identity.

The optional immutable tokenizer JSON replay now passes 195/195 existing tests,
with no fixture skips. On the unchanged 39-input corpus, live reference scores
are BERT 39/39, TinyLlama 39/39 and T5 36/39. T5 still differs on zero-based lines
18, 19 and 30; --model all returns failure. The historical scores below remain
as history. No fixture expectations were altered and no universal/Encoding-field
parity or new speedup is claimed. See docs/WORDPIECE_TASK.md.

---

# Compatibility: differential correctness vs HuggingFace Rust

`parity_proof.pdf` (2026-06-13) states the formal claim
Expand Down Expand Up @@ -109,12 +132,10 @@ any mismatch — timing is not part of the pass criterion.

## Known open gaps (not yet fixed)

- **BERT/WordPiece, 1 remaining mismatch**: a currency/number line
(£15.00 tail — normalized text is byte-identical between Zig and
Rust, so this is confirmed a genuine WordPiece greedy-match
divergence, not a normalizer issue). Not root-caused to the exact
code path yet — needs a WordPiece-algorithm trace, not normalizer
diffing.
- **Historical BERT currency gap — resolved in the pinned 12 November replay.**
Normalized text already agreed; the original 32-token fixture isolated
pre-tokenizer punctuation classification rather than greedy matching.
The unchanged 39-input BERT corpus now passes 39/39 on the pinned fixture.
- **T5/Unigram, 3 remaining mismatches — confirmed cause: `Precompiled`
is silently a no-op.** T5's `tokenizer.json` specifies
`"normalizer": {"type": "Precompiled", "precompiled_charsmap": ...}`
Expand Down
76 changes: 50 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,50 @@ Zig 0.16 tokenizers compatible with the HuggingFace `tokenizer.json`
format. Covers BPE (GPT-2 / Llama / Qwen / Mistral), WordPiece (BERT /
DistilBERT), and Unigram (T5 / mBART / XLM-R) model families.

## Status
## Current bounded task — 12 November 2026

The original 32-token WordPiece fixture now matches pinned Hugging Face
`tokenizers==0.21.4` on all 48 short inputs. The eight-input regression matched
only two inputs before the punctuation repair; all eight now agree. A generated
predicate observes the reference's behavior over all 1,112,064 Unicode scalar
values: 726 punctuation scalars in 156 ranges. Currency symbols and some CJK
letters no longer split as punctuation, while Arabic/Indic punctuation does.

```sh
zig build test --summary all
zig build -Doptimize=ReleaseSafe
python3 -m unittest discover -s tests -p test_diff_check.py
python3 tools/check_wordpiece.py
```

The current local gate passes 166 of 195 Zig tests; 29 real-model/fuzz tests
remain skipped because their separate fixtures are absent. Seven Python gate
fault tests pass. The offline task checks exact token IDs against frozen
reference output; optional live verification uses the pinned wheel and fetches
no models. See [the original fixture contract](docs/WORDPIECE_TASK.md).

Empty dumps, duplicate line IDs, malformed token IDs and matching errors now
fail the comparator. Earlier code reported `0/0` empty dumps as success.

This task covers token IDs for one explicit vocabulary and the pinned BERT
punctuation component. It does not certify BPE, Unigram, general normalization,
offsets, every Encoding field, or current real-model parity. Existing fixture
expectations remain unchanged; no release or visibility change is made.

### Pinned real-model follow-up

Optional `python3 tools/fetch_real_fixtures.py` downloads three immutable,
checksum-verified tokenizer JSON files (about 3.7 MB total; no weights). With
those files, all 195 tests pass. The existing 39-input corpus now matches
BERT 39/39 and TinyLlama 39/39 against the pinned reference. T5 remains 36/39;
`tools/check_real_parity.py --model all` reports the mismatches and fails.
The files stay gitignored; existing real-fixture expectations are unchanged.
See the task contract for exact commands and source identities.

## Historical status and remaining model gaps

**v0.27 — full pipeline, all three model families, 6-subcommand
tokenize CLI, batch-with-types APIs, full HF `Encoding` struct
parity, sub-token offsets, property-fuzz-tested. 193 tests: 164 pass
in a clean clone on Zig 0.16.0 (2026-11-12, macOS aarch64); 29 real-model tests (BERT / T5 / TinyLlama) skip
tokenize CLI, batch-with-types APIs, HF `Encoding` return fields, sub-token offsets, property-fuzz-tested. The current clean-source result is above; 29 real-model tests (BERT / T5 / TinyLlama) skip
because the HF `tokenizer.json` fixtures are not distributed here. To
enable them, place the upstream `tokenizer.json` files in
`tests/fixtures/` under the names the tests expect (e.g.
Expand All @@ -31,33 +69,19 @@ BertNormalizer's lowercase was ASCII-only, its `clean_text` didn't
strip zero-width joiners, its NFD table had zero Hiragana/Katakana
decomposition entries, and NFD decomposition wasn't recursive (needed
for Vietnamese's double-diacritic characters) (BERT → **38/39**).
1 BERT gap (a currency-line WordPiece match, confirmed not a
normalizer issue) and 3 T5 gaps (confirmed cause: T5 uses
The historical BERT currency gap is resolved in the current pinned replay.
Three T5 gaps remain (confirmed cause: T5 uses
SentencePiece's separate `Precompiled`-charsmap normalizer, entirely
unimplemented — falls through to a silent no-op rather than erroring,
because erroring breaks loading T5 at all) remain open. Full detail,
reproduction steps, and the open gaps are in COMPATIBILITY.md — read
that before the PDF.

### Head-to-head vs HuggingFace Rust tokenizers (historical, not remeasured)

These timings were recorded before v0.27 and have not been rerun on the
current commit. Treat them as a lead to reproduce, not a current claim.

| Family | Zig | Rust HF 0.21 | Ratio |
|---|---|---|---|
| BPE+SP (TinyLlama) | ~45 μs | ~46 μs | ~1.0x (parity) |
| **WordPiece (BERT-base-uncased)** | **~15 μs** | **~82 μs** | **~5.3x Zig faster** |
| Unigram (T5-base) | ~38 μs | ~44 μs | ~1.16x Zig faster |

Same 123-byte fixture, same canonical token output, same hardware
(consumer Linux, Ryzen-class, ReleaseFast). Bench harnesses at
`bench/bench_rust_bert/`, `bench/bench_rust_t5/`, `bench/bench_rust/`.
### Historical timing evidence

The WordPiece 5.3x ratio is pure-Zig greedy-longest-match beating HF
Rust on the BERT pipeline. BPE is parity (priority-queue O(n log n)
merge loop matches Rust's optimised path). Unigram is +16% on
Viterbi DP.
The older timing tables remain in STATUS.md. They have not been remeasured in
this acceptance run and are not a current speedup claim. Compatibility failures
must be resolved separately from timing a single successful input.

### Real-tokenizer canonical IDs verified

Expand Down Expand Up @@ -160,7 +184,7 @@ Same code works against BPE, WordPiece, or Unigram tokenizer.json —
## Build

```sh
zig build test # 193 tests (29 skip without HF fixtures)
zig build test # 195 tests (29 skip without HF fixtures)
zig build test-fuzz # standalone fuzz (BERT/T5/TinyLlama × 200 random texts)
zig build tokenize # build tokenize CLI (6 subcommands)
zig build bench # synthetic encode throughput
Expand Down Expand Up @@ -219,7 +243,7 @@ AGPL-3.0-or-later. See `LICENSE`.

```
nix develop # Zig 0.16.0 + jq + curl + gawk + python3(websockets)
zig build test # 193 tests; 164 pass without HF fixtures, 29 skip
zig build test # 195 tests; 166 pass without HF fixtures, 29 skip
```

The repo's `flake.nix` pins exact dep versions (see `STATUS.md`).
Expand Down
13 changes: 13 additions & 0 deletions STATUS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Current acceptance — 12 November 2026

The clean-source baseline passes 164/193 Zig tests with 29 real-fixture skips.
After the punctuation repair and two regressions: 166/195 pass, 29 skip.
Seven differential-gate fault tests and the 48-input original WordPiece task
pass. Current reference: HF tokenizers 0.21.4; token IDs only. The generated
punctuation predicate observes every Unicode scalar (726 positives/156 ranges).
Optional immutable real-tokenizer files run all 195 tests without skips. The
unchanged 39-input corpus now matches BERT and TinyLlama 39/39, while T5 remains
36/39 and the all-model comparison fails visibly. No real-model expectation,
tag, visibility or speed measurement is changed.
See docs/WORDPIECE_TASK.md; the older records below are historical.

# STATUS

**Version:** v0.26
Expand Down
2 changes: 1 addition & 1 deletion build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ pub fn build(b: *std.Build) void {
const diff_mod = b.createModule(.{
.root_source_file = b.path("bench/diff_dump.zig"),
.target = target,
.optimize = .ReleaseFast,
.optimize = optimize,
});
diff_mod.addImport("tokenizers", mod);
const diff_exe = b.addExecutable(.{
Expand Down
4 changes: 4 additions & 0 deletions build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"examples",
"bench",
"tests",
"scripts",
"tools",
"docs",
"selfserve.json",
"build.zig",
"build.zig.zon",
"README.md",
Expand Down
79 changes: 79 additions & 0 deletions docs/WORDPIECE_TASK.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Original WordPiece compatibility exercise

The fixture contains 32 original tokens and 48 original short inputs. It is
small enough to ship, with SHA-256 identities for the vocabulary/pipeline JSON,
corpus and frozen token IDs in tests/fixtures/original-wordpiece.meta.json.
No pretrained tokenizer dump, model weights or external corpus is included.

## Offline acceptance

```sh
zig build test --summary all
zig build -Doptimize=ReleaseSafe
python3 -m unittest discover -s tests -p test_diff_check.py
python3 tools/check_wordpiece.py
```

The checker requires every frozen input, exact successful token IDs, reference
file identities and repeated Zig output bytes. The shared comparator refuses
empty evidence, duplicate line IDs, encoding errors and malformed token IDs.
Its seven fault tests distinguish legitimate empty token sequences from an
empty dump. In the old implementation both empty dumps and matching encoding
errors returned success; the new regression record requires refusal.

## Optional live reference

```sh
python3 -m venv .venv
.venv/bin/python -m pip install --only-binary=:all: -r tools/requirements-oracle.txt
.venv/bin/python tools/check_wordpiece.py --live
.venv/bin/python tools/generate_bert_punctuation.py
```

The deliberately pinned reference is huggingface/tokenizers 0.21.4, not a
claim about the newest release. It is installed as Python bindings over the
Rust implementation; no Cargo bench or model download runs. The upstream BERT
pre-tokenizer uses ASCII punctuation plus its Unicode punctuation predicate:
https://github.com/huggingface/tokenizers/blob/v0.21.4/tokenizers/src/pre_tokenizers/bert.rs

The generator observes the original a<scalar>b probe at every valid Unicode
scalar. It records 726 punctuation scalars in 156 ranges and a SHA-256 of the
ordered little-endian-u32 set. The checked-in table follows that exact reference
rather than whole Unicode blocks. To intentionally regenerate it, use --write
and review the resulting diff; normal verification writes nothing.

## Evidence boundary

The original eight-input regression matched 2/8 before the repair and 8/8
afterward. The 48-input task covers one explicit vocabulary, normalizer,
pre-tokenizer and single-input post-processor. It checks token IDs, not general
BPE/Unigram behavior, offset semantics, pair/batch APIs or every Encoding field.
The exhaustive scalar probe checks the punctuation component only. It does not
certify the separate normalization tables or future upstream versions.

Clean-source Zig acceptance retains 29 missing real-model/fuzz fixture skips.
Real-model fixture expectations and historical scores are not silently changed.
The existing AGPL terms remain intact. The owner made the repository public
during this work; this change does not alter visibility or cut a release.

## Optional pinned real-model replay

```sh
python3 tools/fetch_real_fixtures.py
zig build test --summary all
.venv/bin/python tools/check_real_parity.py --model bert
.venv/bin/python tools/check_real_parity.py --model tinyllama
.venv/bin/python tools/check_real_parity.py --model all
```

The three downloads total about 3.7 MB of tokenizer JSON, with immutable model
revisions and SHA-256 identities in tests/fixtures/real-model-pins.json. They
remain gitignored and their upstream Apache-2.0 terms remain separate. No model
weights are fetched. Existing differing files are refused rather than replaced.

With these files present, the existing suite passes 195/195, including the
previously skipped fixture/fuzz tests. Live reference replay of the existing
39-input corpus now gives BERT 39/39 and TinyLlama 39/39. T5 remains 36/39, with
mismatch lines 18, 19 and 30 (zero based). Consequently --model all returns
nonzero. This is a real remaining normalization gap, not a successful parity
claim. Existing real-fixture test expectations were not changed.
20 changes: 18 additions & 2 deletions scripts/diff_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,19 @@ def load(path):
if not line:
continue
d = json.loads(line)
if not isinstance(d, dict):
raise ValueError("dump row must be an object")
index = d.get("line")
if type(index) is not int or index < 0 or index in out:
raise ValueError("line IDs must be unique nonnegative integers")
if d.get("ok") is not True:
raise ValueError("an encoding error cannot count as parity")
ids = d.get("ids")
if not isinstance(ids, list) or any(type(i) is not int or i < 0 for i in ids):
raise ValueError("successful rows require nonnegative integer token IDs")
out[d["line"]] = d
if not out:
raise ValueError("empty dump is not compatibility evidence")
return out


Expand All @@ -27,8 +39,12 @@ def main():
print("usage: diff_check.py <zig.jsonl> <rust.jsonl> <label>", file=sys.stderr)
sys.exit(2)
zig_path, rust_path, label = sys.argv[1], sys.argv[2], sys.argv[3]
zig = load(zig_path)
rust = load(rust_path)
try:
zig = load(zig_path)
rust = load(rust_path)
except (ValueError, OSError) as error:
print(f"[{label}] invalid evidence: {error}", file=sys.stderr)
sys.exit(1)

lines = sorted(set(zig) | set(rust))
matches = 0
Expand Down
Loading