Repository navigation
fix(tokenizer): build a tokenizer from GPT-2 slow files - #3576
Conversation
|
Security and performance review of the GPT-2 slow-tokenizer path. Fixed (MEDIUM, 2c2b3f9): the add_bos_token / add_eos_token post-processor was built from a template string, so a No other issues found. Crafted LOW, not changed: checkpoint-declared specials and in-vocab added tokens are matched in user text, as in transformers and the tokenizer.json path. Verified: |
Nikity/lille-130m-instruct ships vocab.json + merges.txt with tokenizer_class GPT2Tokenizer and no tokenizer.json, and loading it failed with "No tokenizer found" because the vocab.json + merges.txt fallback only accepted Qwen2Tokenizer. Add is_gpt2_slow_tokenizer_dir and build_gpt2_bpe_tokenizer, which build what transformers' GPT2Tokenizer builds: byte-level BPE with no normalizer, ByteLevel(add_prefix_space, trim_offsets, use_regex) pre-tokenizer and decoder, and a ByteLevel post-processor or a BOS TemplateProcessing when add_bos_token is set. add_prefix_space, add_bos_token and bos_token come from tokenizer_config.json. The fallback runs after every other format and after the model-type remote tokenizer fallback, and only when tokenizer_class names GPT-2. The vocab/merges parsing, the dense-id check and the added-token registration move into shared helpers used by the Qwen2 builder too, with no change in Qwen2 behavior. For GPT-2, an added token whose id is inside the base vocab is accepted only when vocab.json maps the same content to that id (Lille's five specials), and refused otherwise. tests/gpt2_slow_tokenizer_parity.rs checks the Lille slow files against a transformers 5.24.1 GPT2Tokenizer fixture (28 prompts, ids and decoded text) and against the mlx-community tokenizer.json. The supported-models entry drops the copy-a-tokenizer.json workaround. Closes #3569
transformers' GPT2Tokenizer registers bos_token, eos_token and unk_token (each defaulting to <|endoftext|>), pad_token and additional_special_tokens as special tokens even when tokenizer_config.json has no added_tokens_decoder. The GPT-2 slow path now does the same for the ones vocab.json holds, reading tokenizer_config.json with special_tokens_map.json as the fallback, so such a checkpoint does not BPE-split <|endoftext|> in text. A named token missing from vocab.json is skipped with a warning instead of getting an invented id. Covered by a unit test and by a Lille parity case with added_tokens_decoder stripped, which matches the same transformers 5.24.1 fixture.
…urces Review follow-up for the GPT-2 slow-tokenizer path. add_eos_token is now honored with the same TemplateProcessing transformers 5.x builds in update_post_processor (bos and eos around $A, and around $B for pairs). A flag whose token is null is dropped with a warning instead of failing the load. special_tokens_map.json is read only when tokenizer_config.json has no added_tokens_decoder, and then overrides the config, as transformers does. A non-empty extra_special_tokens list replaces additional_special_tokens, and the values of a dict extra_special_tokens count as specials too. Named specials are deduplicated with a set. A new unit test checks all of this against what transformers 5.24.1 produces for the same fixture.
The GPT-2 slow-tokenizer path built its add_bos_token / add_eos_token post-processor from the transformers-style template string ("<bos>:0 $A:0 ..."). That parser splits on spaces and `:` and reads a leading `$` as a sequence reference, so a checkpoint whose bos_token or eos_token is `$A` or `$B` put the input sequence into the template twice and silently duplicated every encode, with or without special tokens. A token containing a space or a `:` failed the load.
The template is now assembled from Piece::SpecialToken and Piece::Sequence values, so the token text is never parsed. A new unit test covers `$A`, `$B`, a space and a colon, and fails when the string template is restored.
Refs #3569
6a39af5 to
59d3db3
Compare
#3576 added `tests/gpt2_slow_tokenizer_parity.rs` without the project license header, so the `license headers` job and `test_check_mode_passes_on_the_real_repository` in the Python tooling suite fail on main and on every PR merged against it. This inserts the standard header with `scripts/insert_apache_header.py`; `--check` now passes. No code change.
Summary
Nikity/lille-130m-instructshipsvocab.json+merges.txtwithtokenizer_class: GPT2Tokenizerand notokenizer.json, and loading it failed withNo tokenizer foundbecause the slow-file fallback only acceptedQwen2Tokenizer. This PR builds a tokenizer from GPT-2 slow files.Changes
is_gpt2_slow_tokenizer_dir(GPT2Tokenizer/GPT2TokenizerFast) andbuild_gpt2_bpe_tokenizerinsrc/tokenizer/mod.rs. The builder matches what transformers 5.xGPT2Tokenizerconstructs: byte-level BPE with no normalizer,ByteLevel(add_prefix_space, trim_offsets=true, use_regex=true)pre-tokenizer and decoder, and aByteLevel(trim_offsets=false)post-processor, or, whenadd_bos_tokenoradd_eos_tokenis true, theTemplateProcessingtransformers 5.x builds inupdate_post_processor({bos:0 }$A:0{ eos:0}, pair adds{ bos:1} $B:1{ eos:1}).add_prefix_space,add_bos_tokenandadd_eos_tokencome fromtokenizer_config.jsonand default tofalse. A flag whose token isnullis dropped with a warning, as transformers does; a declared BOS/EOS missing from the vocab is refused rather than given a new id. Lille setsadd_prefix_space: true, which is whyHelloisĠHello(18435).tokenizer_classnames GPT-2, so it does not claim a directory any existing loader handles. A directory with the file pair but no class is still refused.build_slow_byte_level_bpe(vocab/merges parsing,validate_dense_vocab_ids, BPE model),register_slow_added_tokens(sorted batched registration plus the declared-id check) andtokenizer_config_bool. The Qwen2 builder now uses them withInVocabAddedTokens::Refuse, so its behavior and error messages are unchanged and its existing tests pass untouched.InVocabAddedTokens::AcceptSameEntry: an added token whose id is inside the base vocab is accepted only whenvocab.jsonmaps the same content to that id (Lille's five specials at 32763..32767), and refused otherwise with a message naming the conflict.GPT2Tokenizer, the GPT-2 path registersbos_token,eos_token,unk_token(each defaulting to<|endoftext|>),pad_tokenandadditional_special_tokensas special tokens at theirvocab.jsonids whenadded_tokens_decoderdid not already cover them. Without this, a GPT-2 checkpoint lackingadded_tokens_decoderwould BPE-split<|endoftext|>in text. Sources follow transformers 5.x:tokenizer_config.json, plusspecial_tokens_map.json(overriding it) only when the config has noadded_tokens_decoder; a non-emptyextra_special_tokenslist replacesadditional_special_tokens, and a dictextra_special_tokenscontributes its values. A named token missing fromvocab.jsonis skipped with a warning instead of getting an invented id. Checked against transformers: withadded_tokens_decoderremoved from Lille's config,GPT2Tokenizerstill gives the same 28 fixture results, and so does mlxcel.docs/supported-models.md: the copy-a-tokenizer.jsonworkaround sentence for Lille is replaced by a description of the slow-file path and its validation. TheNo tokenizer foundmessage now says whichtokenizer_classvalues the slow-file fallback accepts. No other doc lists the supported tokenizer formats.Chat template and special tokens
The chat template (
chat_template.jinja, usingbos_token/eos_tokenfromtokenizer_config.json) and the<|endoftext|>stop token are resolved independently oftokenizer.json, and the specials split out of rendered text as added special tokens.MLXCEL_DEVICE=cpu mlxcel generate -m <view without tokenizer.json> -p Hello -n 8now printsHello! How can I assist you today. With-t 0,What is the capital of France?gives the identical output (The capital of France is Paris., stopping on EOS) on the slow-only view and on the original directory with itstokenizer.json.Parity
Hello->[18435],Hello, world!->[18435, 11, 995, 0],<|user|>Hi there<|assistant|>->[32766, 15902, 612, 32765],naïve café 123->[12385, 26884, 303, 19945, 2634, 17031].tests/fixtures/lille_tokenizer/transformers_ids.json(generated bytests/fixtures/generate_lille_tokenizer_fixture.pywith transformers 5.24.1 / tokenizers 0.23.3GPT2Tokenizeron the slow files only) holds 28 prompts: unicode (accents, emoji, CJK, Korean, NBSP / em space / zero-width space), whitespace runs, tabs, CRLF and leading/trailing newlines, specials embedded in text and spaced around, empty and whitespace-only inputs, and leading spaces.tests/gpt2_slow_tokenizer_parity.rschecks all 28 for ids without and with special tokens (28/28 and 28/28 match) and for decode with and withoutskip_special_tokens(56/56 match transformers' decoded text, including the prefix spaceadd_prefix_spaceadds).tokenizer.jsoninmlx-community/lille-130m-instruct-8biton all 28 prompts with and without special tokens, and both decode modes: all ids and all decoded strings match, and both report a 32768-entry vocab.Changes during review
An independent review against the transformers 5.24.1 source found no CRITICAL/HIGH issues and four config cases Lille does not hit, now fixed:
add_eos_tokenwas ignored,special_tokens_map.jsonprecedence differed,extra_special_tokenswas not read, andadd_bos_tokenwith anullbos failed the load. Named-special dedup now uses a set.Tests
tokenizer::tests:load_tokenizer_builds_a_gpt2_slow_tokenizer(the issue'swrite_qwen2_slow_tokenizer_dir(&dir, "GPT2Tokenizer")fixture loads, Qwen2 detection still refuses it, a class-less directory still fails),gpt2_slow_tokenizer_honors_prefix_space_bos_and_in_vocab_specials, andgpt2_slow_tokenizer_refuses_conflicting_in_vocab_added_tokens(content missing fromvocab.json, and content mapped to a different id),gpt2_slow_tokenizer_registers_named_specials_from_the_vocab, andgpt2_slow_tokenizer_honors_add_eos_and_the_legacy_special_tokens_map(its expected ids were checked against transformers 5.24.1 on the same toy fixture). The parity file addslille_slow_files_without_added_tokens_decoder_still_split_specials.load_tokenizerfails all three new unit tests and both parity tests (No tokenizer found). Switching GPT-2 toInVocabAddedTokens::Refusefails both Lille parity tests (Added token "<|pad|>" claims id 32763 which is inside the 32768 entry base vocab). Disablingadd_eos_tokenfailsgpt2_slow_tokenizer_honors_add_eos_and_the_legacy_special_tokens_map. Removing the named-special registration failsgpt2_slow_tokenizer_registers_named_specials_from_the_vocabandlille_slow_files_without_added_tokens_decoder_still_split_specials.--features cuda):cargo test --profile test-fast --features cuda --lib tokenizer::(155 passed),cargo test --profile test-fast --features cuda --test gpt2_slow_tokenizer_paritywithMLXCEL_REQUIRE_MODELS=1(3 passed, not skipped),cargo test --profile test-fast --features cuda --bin mlxcel(363 passed),cargo clippy --lib --tests --features cuda -- -D warnings,cargo fmt --all -- --check, and thescripts/cicontract checks. Tokenization is CPU-only, so nothing here is Metal-specific; the Metal build was not run on this host.Closes #3569