Skip to content

tokenizer: the gemma4 model and pre-tokenizer, BPE over metaspace text as the reference runs it - #241

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-tokenizer
Oct 15, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-tokenizer

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #59 (plan and PR order in #190), E2: the gemma4 tokenizer that EmbeddingGemma 2's vocabulary needs.

What and why

Release notes: Under the hood: the tokenizer reads gemma4 vocabularies (EmbeddingGemma 2); no served model uses one yet.

EmbeddingGemma 2 ships its vocabulary as tokenizer.ggml.model = gemma4, and the tokenizer crate loaded only gpt2. This PR adds the gemma4 model and the gemma4 pre-tokenizer, so Tokenizer::from_gguf opens the released file and its ids match mainline llama.cpp's llama-tokenize on every case tried. The EmbeddingGemma 2 reader on main (#238) lists pre-tokenizer gemma4 in its coverage until runs_pre_tokenizer("gemma4") is true, which this PR makes it.

The port follows mainline src/llama-vocab.cpp and src/unicode.cpp:

  • Model gemma4 (vocab.rs): mainline always sets the pre-tokenizer to gemma4 for this model and does not use tokenizer.ggml.pre, which the released file does not carry. Its special-id defaults are all null. A BOS is always added under the gemma4 pre-tokenizer, whatever add_bos_token says. EOS follows add_eos_token.
  • Pre-tokenizer gemma4 (pretok.rs): the regex [^\n]+|[\n]+, which mainline runs as unicode_regex_split_custom_newlines. It cuts runs of U+000A from runs of everything else, and \r is not a newline here. It is a new row in Pre::NAMES, so runs_pre_tokenizer("gemma4") is true and the refusal message lists it.
  • Spelling (bpe.rs, lib.rs): mainline's byte_encode = false and escape_whitespaces = true for this pre-tokenizer. Pre::spelling gives it, as Pre::ignore_merges gives that flag, and Bpe::new takes it along with the vocabulary's token attributes. encode writes each U+0020 as U+2581 before the split (no other space character); Metaspace starts symbols at UTF-8 characters (unicode_len_utf8), and falls back to the <0xXX> token of each byte when a finished symbol is not a token. A word made only of newlines that is itself a token is that token (mainline's gemma4 branch in llm_tokenizer_bpe_session::tokenize). It goes through the same whole_token lookup in the vocabulary's own map that ignore_merges uses.
  • Decoding (decode.rs): a NORMAL token's piece is its text with U+2581 written as a space (llama_unescape_whitespace). BYTE and CONTROL pieces were already right.

These inputs now get a named error or a defined result, where mainline asserts or loses input and main panics:

  • A header that asks for a BOS and names no BOS id in range is Error::Missing("tokenizer.ggml.bos_token_id"), and the same for EOS with tokenizer.ggml.eos_token_id. Mainline's append_bos and append_eos assert there. With gemma4's null defaults the token would otherwise be dropped without a word. The check runs for every model. For gpt2 it fires where no default id applies: a glm4 vocabulary, which has no default BOS and which main encoded without one, and a vocabulary of 11 tokens or fewer (the next item). All six byte-level files below load; none of them asks for a BOS or an EOS (add_bos false add_eos false), so neither check touches them.
  • A gpt2 vocabulary has the default BOS and EOS 11 only when it has more than 11 tokens. On main the EOS default is 11 at any size, and loading a vocabulary of 11 tokens or fewer panics on that index (the gpt2 EOS row of the FAIL-first table below puts main's default back). Such a vocabulary now has no default id: it loads with no BOS or EOS, or the check above refuses it when the header asks for one.
  • A metaspace vocabulary is Error::MissingByteToken when one of the 256 <0xXX> fallback tokens is missing or is not of the BYTE type. Mainline skips a missing byte token in the fallback and the input byte is lost; the released file has all 256.
  • Bpe::word panics by name on a word longer than u32::MAX bytes, which its u32 symbol links cannot index; the links are converted with try_from. A gemma4 word is a whole line, so this length is reachable in principle.

Otherwise the byte-level path computes what it did: the same ids on six real byte-level vocabularies, below.

The model is a table in vocab.rs (Model::NAMES, which the refusal message lists). A later model is a row there plus its own tokenizer; a SentencePiece model such as EmbeddingGemma 1 (tokenizer.ggml.model = llama) needs mainline's score-based merge, which Bpe does not run. Model::NAMES and Pre::NAMES are read through the same two functions in lib.rs, named and names.

docs/contrib/new-model.md (section 2) said the tokenizer took gpt2 only and listed the pre-tokenizers. It now names both models and gemma4, and the section's line references point at the moved lines. The Layout line in AGENTS.md still calls the crate byte-level BPE; a separate one-line PR changes it after this one lands.

Code shape

  • No second copy. The metaspace path is a second arm inside the one Bpe::word merge loop; the merge queue, the staleness check, the whole-token lookup and the partition are shared. The pre-tokenizer is a row in the one Pre::NAMES table, and the model and pre-tokenizer tables share one lookup.
  • Model code holds only architecture facts. Everything added is the reference's per-name tokenizer behavior: the spelling, the split, the BOS rule and the special-id defaults.
  • Dead code is gone.
  • No silent failure. An unknown tokenizer.ggml.model is still Error::UnsupportedModel, and its message lists the models the crate runs. A BOS or EOS the header asks for but cannot name is Error::Missing, a gpt2 vocabulary too small for the default id 11 gets no default, a metaspace vocabulary whose byte fallback token is missing or not of the BYTE type is Error::MissingByteToken, and a word too long for the symbol links panics with its length.
  • Comments state what is true now. tools/check-comments.sh is ok.
  • No relaxed gate.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": Model::NAMES needs the lookup and the name list that Pre::of and Pre::names (crates/tokenizer/src/pretok.rs:350,355 at main) run over Pre::NAMES. Both tables now go through named and names (crates/tokenizer/src/lib.rs), which take the table, and the two Pre methods are gone.

What I ran

The head is 254dad73, one commit on 5e837723. Each result below names the commit it ran at. The card-side runs used a DGX Spark (aarch64 Linux, driver 595.84) in the dev container; the static checks ran on an Apple Silicon Mac.

just contrib-check --tier t0 on a DGX Spark at 254dad73:

test-bloomery-tokenizer rc=0 0s
DONE tier=t0 total=82 red=0 wall=269s

just mac-static on the Mac at 254dad73, base 5e837723:

mac-static: fmt-check rc 0 in 11 s — rustfmt diff blocks: 0
mac-static: lint rc 0 in 23 s — mac-check: lint ^warning: 41 = the ratchet 41 in tools/lint-ratchet.txt
mac-static: combos rc 0 in 27 s — mac-check: combos rc 0; 23 shapes run, 0 red, 26 skipped (scoped)
mac-static: ok

The eleven check-* steps are rc 0, check-comments among them.

gemma4_encodes_as_the_reference writes a small gemma4 vocabulary to a GGUF header (6 CONTROL tokens with <turn|> and <|channel|> among them, 1 USER_DEFINED token, the 256 byte tokens, 15 NORMAL tokens, 5 merges, add_bos_token false; one header names tokenizer.ggml.pre = qwen2, which the gemma4 model does not read). The expected ids follow mainline's code path for each input, not this crate's output. It checks:

  • the refusals: no BOS id; no EOS id; an EOS id out of range; <0xBC> missing from the byte tokens;
  • add_eos_token false with no EOS id, which loads and adds only the BOS;
  • one case per encoding step, and these edges: a two-byte and a four-byte character that are tokens (é, 😀), a literal U+2581 in the input (same ids as a space, and it decodes to a space, so it does not round-trip), CRLF before a newline run, newline and space runs longer than any whole token in the vocabulary, U+00A0 and U+3000 (not respelled, so they fall back to bytes), invalid UTF-8 (one U+FFFD per bad byte, as unicode_cpts_from_utf8 reads it), <|channel|> and a USER_DEFINED token cut out without special parsing, and a CONTROL token cut out only with it.

gemma4_requires_byte_token_attributes writes a gemma4 header with a BOS id and all 256 <0xXX> texts. It is Error::MissingByteToken when the file has no token types (every token NORMAL), when <0xBC> alone is NORMAL and when <0xBC> alone is UNUSED.

gpt2_defaults_stay_in_vocab writes gpt2 headers of 1 and of 11 tokens with no BOS or EOS id. Asking for a BOS is Error::Missing("tokenizer.ggml.bos_token_id"), asking for an EOS is Error::Missing("tokenizer.ggml.eos_token_id"), and asking for neither loads with no BOS, no EOS and no end-of-generation token.

gemma4_cases pins the split. FAIL-first, each mutant planted alone, and the unchanged head passes the same tests. The first 17 rows ran at b09542b4 on the Mac and the next three at 975a3c2f on a DGX Spark, against gemma4_cases and gemma4_encodes_as_the_reference. The three gpt2 rows ran at 0df24362 on a DGX Spark against gpt2_defaults_stay_in_vocab, and the last row on a DGX Spark against gemma4_requires_byte_token_attributes, with the BYTE check removed from 254dad73:

Mutant First red assertion
no U+2581 respelling "a b": [a, <0x20>, b] instead of [a, ▁b]
no newline-word lookup "a\n\n\nb": [a, \n, \n, \n, b] instead of [a, \n\n\n, b]
add_bos_token read as written the header with no BOS id loads, since nothing asks for a BOS
one symbol per byte "a b": [a, <0xE2>, <0x96>, <0x81>, b] instead of [a, ▁b]
byte-level pieces in decoding the decoded text holds an [UNK_BYTE_0xe29681▁b] marker instead of "a b"
no BOS-id check the header with no BOS id loads
no EOS-id check the header with no EOS id loads
EOS-id check also when add_eos_token is false the add_eos_token = false header with no EOS id is refused
a missing byte token skipped in the fallback the vocabulary without <0xBC> loads
U+00A0 and U+3000 respelled as well "a b": [a, ▁b] instead of [a, <0xC2>, <0xA0>, b]
a newline word cut greedily into whole tokens "\n\n\n\n": [\n\n\n, \n] instead of four \n
\r counted as a newline gemma4_cases: "a\n\nb\r\n" splits b from \r\n; the CRLF row of the encode test is red too
USER_DEFINED tokens cut only with special parsing "a<|channel|>b" without special parsing: 11 byte and letter ids instead of [a, <|channel|>, b]
no USER_DEFINED override for <|channel|> the same row
ties to the rightmost pair five spaces: [▁, ▁▁▁▁] instead of [▁▁▁▁, ▁]
one U+FFFD per truncated sequence "a\xF0\x9F b": one U+FFFD's three bytes instead of two U+FFFD's six
U+2581 not written back as a space a literal U+2581 decodes to "a▁b" instead of "a b"
a two-byte character started as two symbols "é": two byte tokens instead of [é]
a four-byte character started as one symbol per byte "😀": four byte tokens instead of [😀]
the file's tokenizer.ggml.pre read for gemma4 pre() is "qwen2" instead of "gemma4"
gpt2's BOS default 11 at any vocabulary size the 1-token header that asks for a BOS loads instead of missing metadata key tokenizer.ggml.bos_token_id
gpt2's EOS default 11 at any vocabulary size, as on main loading the 1-token header panics: index out of bounds: the len is 1 but the index is 11
both gpt2 bounds as n >= 11 loading the 11-token header panics: index out of bounds: the len is 11 but the index is 11
fallback tokens taken without the BYTE check gemma4_requires_byte_token_attributes panics at crates/tokenizer/src/lib.rs:534: assertion left == right failed

The word-length panic has no test: it needs a word of 4 GiB.

The two comparisons below ran at 254dad73.

Both comparisons ran bloomery-tokenize on a copy of each file's GGUF header (every metadata key, no tensors), which is all the tokenizer reads.

Against the reference: mainline llama.cpp at 6868a52cb337450658006ad2f9281c2eb63f1666, llama-tokenize (it loads only the vocabulary) on embeddinggemma-2-Q8_0.gguf from ggml-org/embeddinggemma-2-GGUF (revision bfcd298762cc34d0357ece5ebdd31791a3a374d8, sha256 2188ac1deca4b77dffefd603c2776a9d76d9d74ec01841392982ebb840b09135). 26 texts: English prose and queries, Korean, Japanese and Chinese, Python, Rust, JSON, HTML, emoji with ZWJ and flags, gemma special-token text, whitespace runs, only spaces, only newlines, the empty string, one character, Unicode normalization cases, rare words, a repeated word and a 1,500-word passage (1,734 ids). Each text in both parse modes (default and --no-parse-special), with BOS and EOS as llama-tokenize adds them. The mainline ids, then this branch's, compared id for id:

llama-tokenize -m embeddinggemma-2-Q8_0.gguf -f <case>.txt --no-escape --ids --log-disable [--no-parse-special]
bloomery-tokenize -m embeddinggemma-2-Q8_0.gguf -f <case>.txt --ids [--no-parse-special]
cases 26 comparisons 52 different 0

The reference's ids, without BOS and EOS, decode back to the source text for all 26 cases (bloomery-tokenize --decode). The synthetic test covers a literal U+2581, invalid UTF-8, CR, U+00A0 and U+3000 on its small vocabulary; cases for them on the real vocabulary belong with the oracle PR's set.

bloomery-tokenize --info on that file: add_bos true add_eos true, eog [1, 50, 106] (<eos>, <|tool_response>, <turn|>), special_overlap None, ambiguous_roles [], merges_off_vocab 0. </s> (212) stays NORMAL, as mainline makes it when <|tool_response> is an end-of-generation token.

The byte-level path, main against this branch: bloomery-tokenize built at main 9e9c2cc8 and at 254dad73, run on the same texts in both parse modes and compared id for id. Six byte-level files: DeepSeek-V4.1-Flash Q3_K_M first shard (joyai-llm), Qwen3-30B-A3B-Instruct-2507 Q4_K_M (qwen2), GLM-5.3-Flash UD-Q4_K_XL first shard (glm4), and three qwen35 files: Qwen3.8-Flash-Next UD-Q4_K_XL first shard, Qwen3.6-35B-A3B Q4_K_M and clef-flash Q8_0. 30 texts: the 26 above, README.md, crates/tokenizer/src/pretok.rs, docs/oracle.md (Korean) and crates/tokenizer/tests/cases.txt.

vocabularies 6 texts 30 comparisons 360 different 0

BLOOMERY_BOX_LOCAL=1 just gate-tokenizer on an RTX 5090 at 254dad73 and at the base 5e837723:

# head 254dad73
test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: FAILED. 0 passed; 10 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.24s
GATE RED (exit 101)
# base 5e837723
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: FAILED. 0 passed; 10 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.23s
GATE RED (exit 101)

The gate is red on both sides with the same 10 hw tests: 4 stop at a model file that is not on that machine (GLM-5.3-Flash and Nemotron 3 Nano 4B, two tests each), and 6 at the ref-tokenizer-v41, ref-tokenizer-qwen3moe and ref-tokenizer-qwen38 sets, which are not there either. The library tests differ only by the four new ones at 254dad73: pretok::tests::gemma4_cases, tests::gemma4_encodes_as_the_reference, tests::gpt2_defaults_stay_in_vocab and tests::gemma4_requires_byte_token_attributes.

This PR adds no gemma4 hw gate or reference set; no pixtral file was at hand for the comparison above. The EmbeddingGemma 2 oracle PR (E3 of #190) adds the gemma4 vocabulary to the tokenizer oracle; its set ref-tokenizer-gemma4 (just dump-ref-tokenizer gemma4) holds the mainline ids. The gemma4 row in gate-tokenizer and its tokenizer family, which read that set, come in a follow-up PR after this one merges. Until then, the gemma4 vocabulary is covered by the 26-case comparison above and the synthetic tests.

What I ran into

None of this blocks the PR.

  • The header has no tokenizer.ggml.pre, and the model crate's shared reader requires it. chat_of (crates/model/src/arch/mod.rs) refuses a file without the key, and coverage then asks tokenizer::runs_pre_tokenizer about the name it holds. For this file the name has to come from the tokenizer model, as mainline and this crate take it. The EmbeddingGemma 2 reader from model, models: gemma-embedding2's header reader, with an EncoderSpec on ModelSpec #238 takes it that way and records it as a default, and its coverage item pre-tokenizer gemma4 goes away with this PR.

Hardware (if the change is for a machine)

None. The tokenizer is host code.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added documentation Improvements or additions to documentation model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja labels Oct 15, 2026
github-actions[bot]
github-actions Bot previously approved these changes Oct 15, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: The new spelling path preserves merge ordering and rejects missing required Gemma4 special ids and byte tokens.

Checked

Duplicates: 14 new functions, types and constants checked; no proven duplicate. Dryer reported no candidate pairs.
Complexity: Bpe::word 18 → 28, Vocab::load 21 → 30, and Bpe::new 9 → 14. Existing functions gained spelling/model branches and validation; the merge loop retains one owner.
Silent failure: 8 candidate sites followed to consumers. Missing lookups reach named errors or the defined spelling fallback; UTF-8 symbol lengths come from re-encoded codepoints.
Tests, static mutation review: dropping the whole-token branch at crates/tokenizer/src/bpe.rs:226 fails ignore_merges_takes_a_whole_token_no_merge_reaches; counting CR as a newline at crates/tokenizer/src/pretok.rs:407 fails gemma4_cases; dropping space respelling at crates/tokenizer/src/lib.rs:145 fails gemma4_encodes_as_the_reference on "a b". That test also asserts BOS, EOS and missing-byte refusals.
Gates: no pins moved, cases removed or gate lists changed.
Escape catalog: C1–C4 do not match this diff.
Adversarial: empty input, multibyte merges, stale merge entries, malformed Gemma4 headers and concurrent encodes checked against bounds, validation and per-call scratch.

Notes

Validation here was static; tests were not run. The PR reports passing host tests and reference comparisons. Its real-file tokenizer gates lack required model files; the Gemma4 oracle is deferred to a follow-up.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

…t as the reference runs it

tokenizer.ggml.model = gemma4 (EmbeddingGemma 2) loads. The model always
runs the gemma4 pre-tokenizer, whatever the file names, defaults no special
ids and always adds a BOS. That pre-tokenizer cuts a fragment into runs of
newlines and runs of the rest, after each space becomes U+2581. Bpe takes a
Spelling: byte-level as before, or metaspace, where symbols start as UTF-8
characters, a word of newlines that is a token stays whole, and a symbol
that is no token falls back to <0xXX> tokens. Decoding writes U+2581 back
as a space. runs_pre_tokenizer("gemma4") is true through the one table.

A header that asks for a BOS or an EOS it cannot name is refused, for any
model, where the reference asserts. A metaspace vocabulary without all 256
<0xXX> tokens is refused, so the fallback never drops a byte. A word too
long for the u32 symbol links panics by name. The model and pre-tokenizer
name tables share one lookup. A synthetic gemma4 vocabulary test holds each
step and edge, FAIL-first per step.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: No must-fix finding remains in the changed code. The new checks reject missing required BOS/EOS IDs and incomplete metaspace byte tables.

Non-blocking

⚠ Pin escape order for overlong UTF-8: crates/tokenizer/src/lib.rs:145
The lenient decoder accepts C0 A0 as U+0020, which the new loop then changes to U+2581. Compare b"a\xC0\xA0b" with mainline and add its expected IDs to the existing case table. The truncated-sequence case does not pin this normalization order.

Checked

The BPE merge loop remains shared. The changed tests assert missing BOS/EOS and byte-token refusals, the small-vocabulary bounds, metaspace respelling, and newline behavior. Diagnostics report no duplicate pairs; C1–C4 do not match this diff. No ledger lessons are in force.

Notes

Rust tests were not rerun here. The PR reports T0 green and gate-tokenizer red on both commits because model files and reference sets are absent. The Gemma4 oracle gate is deferred with a stated follow-up. No nvidia-smi line is supplied.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

Filed outside this PR: #256

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant