Repository navigation
tokenizer: the gemma4 model and pre-tokenizer, BPE over metaspace text as the reference runs it - #241
Conversation
There was a problem hiding this comment.
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.
975a3c2 to
254dad7
Compare
There was a problem hiding this comment.
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
|
The review is done and the contribution check passed, so I'm merging this. |
Part of #59 (plan and PR order in #190), E2: the
gemma4tokenizer that EmbeddingGemma 2's vocabulary needs.What and why
Release notes: Under the hood: the tokenizer reads
gemma4vocabularies (EmbeddingGemma 2); no served model uses one yet.EmbeddingGemma 2 ships its vocabulary as
tokenizer.ggml.model = gemma4, and the tokenizer crate loaded onlygpt2. This PR adds thegemma4model and thegemma4pre-tokenizer, soTokenizer::from_ggufopens the released file and its ids match mainline llama.cpp'sllama-tokenizeon every case tried. The EmbeddingGemma 2 reader on main (#238) listspre-tokenizer gemma4in its coverage untilruns_pre_tokenizer("gemma4")is true, which this PR makes it.The port follows mainline
src/llama-vocab.cppandsrc/unicode.cpp:gemma4(vocab.rs): mainline always sets the pre-tokenizer togemma4for this model and does not usetokenizer.ggml.pre, which the released file does not carry. Its special-id defaults are all null. A BOS is always added under thegemma4pre-tokenizer, whateveradd_bos_tokensays. EOS followsadd_eos_token.gemma4(pretok.rs): the regex[^\n]+|[\n]+, which mainline runs asunicode_regex_split_custom_newlines. It cuts runs of U+000A from runs of everything else, and\ris not a newline here. It is a new row inPre::NAMES, soruns_pre_tokenizer("gemma4")is true and the refusal message lists it.bpe.rs,lib.rs): mainline'sbyte_encode = falseandescape_whitespaces = truefor this pre-tokenizer.Pre::spellinggives it, asPre::ignore_mergesgives that flag, andBpe::newtakes it along with the vocabulary's token attributes.encodewrites each U+0020 as U+2581 before the split (no other space character);Metaspacestarts 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 inllm_tokenizer_bpe_session::tokenize). It goes through the samewhole_tokenlookup in the vocabulary's own map thatignore_mergesuses.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:
Error::Missing("tokenizer.ggml.bos_token_id"), and the same for EOS withtokenizer.ggml.eos_token_id. Mainline'sappend_bosandappend_eosassert there. With gemma4's null defaults the token would otherwise be dropped without a word. The check runs for every model. Forgpt2it fires where no default id applies: aglm4vocabulary, 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.gpt2vocabulary 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.Error::MissingByteTokenwhen 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::wordpanics by name on a word longer thanu32::MAXbytes, which itsu32symbol links cannot index; the links are converted withtry_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, whichBpedoes not run.Model::NAMESandPre::NAMESare read through the same two functions inlib.rs,namedandnames.docs/contrib/new-model.md(section 2) said the tokenizer tookgpt2only 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 inAGENTS.mdstill calls the crate byte-level BPE; a separate one-line PR changes it after this one lands.Code shape
Bpe::wordmerge loop; the merge queue, the staleness check, the whole-token lookup and the partition are shared. The pre-tokenizer is a row in the onePre::NAMEStable, and the model and pre-tokenizer tables share one lookup.tokenizer.ggml.modelis stillError::UnsupportedModel, and its message lists the models the crate runs. A BOS or EOS the header asks for but cannot name isError::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 isError::MissingByteToken, and a word too long for the symbol links panics with its length.tools/check-comments.shis ok.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.Duplication found or removed (
path:line), or "none":Model::NAMESneeds the lookup and the name list thatPre::ofandPre::names(crates/tokenizer/src/pretok.rs:350,355at main) run overPre::NAMES. Both tables now go throughnamedandnames(crates/tokenizer/src/lib.rs), which take the table, and the twoPremethods are gone.What I ran
The head is
254dad73, one commit on5e837723. 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 t0on a DGX Spark at254dad73:just mac-staticon the Mac at254dad73, base5e837723:The eleven
check-*steps are rc 0,check-commentsamong them.gemma4_encodes_as_the_referencewrites 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_tokenfalse; one header namestokenizer.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:<0xBC>missing from the byte tokens;add_eos_tokenfalse with no EOS id, which loads and adds only the BOS;é,😀), 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, asunicode_cpts_from_utf8reads 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_attributeswrites a gemma4 header with a BOS id and all 256<0xXX>texts. It isError::MissingByteTokenwhen the file has no token types (every token NORMAL), when<0xBC>alone is NORMAL and when<0xBC>alone is UNUSED.gpt2_defaults_stay_in_vocabwritesgpt2headers of 1 and of 11 tokens with no BOS or EOS id. Asking for a BOS isError::Missing("tokenizer.ggml.bos_token_id"), asking for an EOS isError::Missing("tokenizer.ggml.eos_token_id"), and asking for neither loads with no BOS, no EOS and no end-of-generation token.gemma4_casespins the split. FAIL-first, each mutant planted alone, and the unchanged head passes the same tests. The first 17 rows ran atb09542b4on the Mac and the next three at975a3c2fon a DGX Spark, againstgemma4_casesandgemma4_encodes_as_the_reference. The three gpt2 rows ran at0df24362on a DGX Spark againstgpt2_defaults_stay_in_vocab, and the last row on a DGX Spark againstgemma4_requires_byte_token_attributes, with the BYTE check removed from254dad73:"a b":[a, <0x20>, b]instead of[a, ▁b]"a\n\n\nb":[a, \n, \n, \n, b]instead of[a, \n\n\n, b]add_bos_tokenread as written"a b":[a, <0xE2>, <0x96>, <0x81>, b]instead of[a, ▁b][UNK_BYTE_0xe29681▁b]marker instead of"a b"add_eos_tokenis falseadd_eos_token = falseheader with no EOS id is refused<0xBC>loads"a b":[a, ▁b]instead of[a, <0xC2>, <0xA0>, b]"\n\n\n\n":[\n\n\n, \n]instead of four\n\rcounted as a newlinegemma4_cases:"a\n\nb\r\n"splitsbfrom\r\n; the CRLF row of the encode test is red too"a<|channel|>b"without special parsing: 11 byte and letter ids instead of[a, <|channel|>, b]<|channel|>[▁, ▁▁▁▁]instead of[▁▁▁▁, ▁]"a\xF0\x9F b": one U+FFFD's three bytes instead of two U+FFFD's six"a▁b"instead of"a b""é": two byte tokens instead of[é]"😀": four byte tokens instead of[😀]tokenizer.ggml.preread for gemma4pre()is"qwen2"instead of"gemma4"missing metadata key tokenizer.ggml.bos_token_idindex out of bounds: the len is 1 but the index is 11n >= 11index out of bounds: the len is 11 but the index is 11gemma4_requires_byte_token_attributespanics atcrates/tokenizer/src/lib.rs:534:assertionleft == rightfailedThe word-length panic has no test: it needs a word of 4 GiB.
The two comparisons below ran at
254dad73.Both comparisons ran
bloomery-tokenizeon 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) onembeddinggemma-2-Q8_0.gguffromggml-org/embeddinggemma-2-GGUF(revisionbfcd298762cc34d0357ece5ebdd31791a3a374d8, sha2562188ac1deca4b77dffefd603c2776a9d76d9d74ec01841392982ebb840b09135). 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 asllama-tokenizeadds them. The mainline ids, then this branch's, compared id for id: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 --infoon 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-tokenizebuilt at main9e9c2cc8and at254dad73, 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 threeqwen35files: 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) andcrates/tokenizer/tests/cases.txt.BLOOMERY_BOX_LOCAL=1 just gate-tokenizeron an RTX 5090 at254dad73and at the base5e837723: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-qwen3moeandref-tokenizer-qwen38sets, which are not there either. The library tests differ only by the four new ones at254dad73:pretok::tests::gemma4_cases,tests::gemma4_encodes_as_the_reference,tests::gpt2_defaults_stay_in_vocabandtests::gemma4_requires_byte_token_attributes.This PR adds no gemma4 hw gate or reference set; no
pixtralfile was at hand for the comparison above. The EmbeddingGemma 2 oracle PR (E3 of #190) adds the gemma4 vocabulary to the tokenizer oracle; its setref-tokenizer-gemma4(just dump-ref-tokenizer gemma4) holds the mainline ids. The gemma4 row ingate-tokenizerand 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.
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 askstokenizer::runs_pre_tokenizerabout 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 itempre-tokenizer gemma4goes away with this PR.Hardware (if the change is for a machine)
None. The tokenizer is host code.
AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.