Skip to content

fix(tokenizer): build a tokenizer from GPT-2 slow files - #3576

Merged
inureyes merged 5 commits into
mainfrom
fix/3569-gpt2-slow-tokenizer
Nov 30, 2026
Merged

inureyes merged 5 commits into
mainfrom
fix/3569-gpt2-slow-tokenizer

Conversation

@inureyes

@inureyes inureyes commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Summary

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 slow-file fallback only accepted Qwen2Tokenizer. This PR builds a tokenizer from GPT-2 slow files.

Changes

  • is_gpt2_slow_tokenizer_dir (GPT2Tokenizer / GPT2TokenizerFast) and build_gpt2_bpe_tokenizer in src/tokenizer/mod.rs. The builder matches what transformers 5.x GPT2Tokenizer constructs: byte-level BPE with no normalizer, ByteLevel(add_prefix_space, trim_offsets=true, use_regex=true) pre-tokenizer and decoder, and a ByteLevel(trim_offsets=false) post-processor, or, when add_bos_token or add_eos_token is true, the TemplateProcessing transformers 5.x builds in update_post_processor ({bos:0 }$A:0{ eos:0}, pair adds { bos:1} $B:1{ eos:1}). add_prefix_space, add_bos_token and add_eos_token come from tokenizer_config.json and default to false. A flag whose token is null is dropped with a warning, as transformers does; a declared BOS/EOS missing from the vocab is refused rather than given a new id. Lille sets add_prefix_space: true, which is why Hello is ĠHello (18435).
  • The GPT-2 fallback is tried after every other format and after the model-type remote tokenizer fallback (moondream3), and only when tokenizer_class names 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.
  • Shared helpers: 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) and tokenizer_config_bool. The Qwen2 builder now uses them with InVocabAddedTokens::Refuse, so its behavior and error messages are unchanged and its existing tests pass untouched.
  • GPT-2 uses InVocabAddedTokens::AcceptSameEntry: 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 at 32763..32767), and refused otherwise with a message naming the conflict.
  • Named specials: like GPT2Tokenizer, the GPT-2 path registers bos_token, eos_token, unk_token (each defaulting to <|endoftext|>), pad_token and additional_special_tokens as special tokens at their vocab.json ids when added_tokens_decoder did not already cover them. Without this, a GPT-2 checkpoint lacking added_tokens_decoder would BPE-split <|endoftext|> in text. Sources follow transformers 5.x: tokenizer_config.json, plus special_tokens_map.json (overriding it) only when the config has no added_tokens_decoder; a non-empty extra_special_tokens list replaces additional_special_tokens, and a dict extra_special_tokens contributes its values. A named token missing from vocab.json is skipped with a warning instead of getting an invented id. Checked against transformers: with added_tokens_decoder removed from Lille's config, GPT2Tokenizer still gives the same 28 fixture results, and so does mlxcel.
  • docs/supported-models.md: the copy-a-tokenizer.json workaround sentence for Lille is replaced by a description of the slow-file path and its validation. The No tokenizer found message now says which tokenizer_class values the slow-file fallback accepts. No other doc lists the supported tokenizer formats.

Chat template and special tokens

The chat template (chat_template.jinja, using bos_token / eos_token from tokenizer_config.json) and the <|endoftext|> stop token are resolved independently of tokenizer.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 8 now prints Hello! 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 its tokenizer.json.

Parity

  • The issue's four reference encodings from transformers 5.24.1 match exactly: 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 by tests/fixtures/generate_lille_tokenizer_fixture.py with transformers 5.24.1 / tokenizers 0.23.3 GPT2Tokenizer on 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.rs checks all 28 for ids without and with special tokens (28/28 and 28/28 match) and for decode with and without skip_special_tokens (56/56 match transformers' decoded text, including the prefix space add_prefix_space adds).
  • The same test compares the slow build against the tokenizer.json in mlx-community/lille-130m-instruct-8bit on 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_token was ignored, special_tokens_map.json precedence differed, extra_special_tokens was not read, and add_bos_token with a null bos failed the load. Named-special dedup now uses a set.

Tests

  • New unit tests in tokenizer::tests: load_tokenizer_builds_a_gpt2_slow_tokenizer (the issue's write_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, and gpt2_slow_tokenizer_refuses_conflicting_in_vocab_added_tokens (content missing from vocab.json, and content mapped to a different id), gpt2_slow_tokenizer_registers_named_specials_from_the_vocab, and gpt2_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 adds lille_slow_files_without_added_tokens_decoder_still_split_specials.
  • Revert checks: disabling the GPT-2 fallback in load_tokenizer fails all three new unit tests and both parity tests (No tokenizer found). Switching GPT-2 to InVocabAddedTokens::Refuse fails both Lille parity tests (Added token "<|pad|>" claims id 32763 which is inside the 32768 entry base vocab). Disabling add_eos_token fails gpt2_slow_tokenizer_honors_add_eos_and_the_legacy_special_tokens_map. Removing the named-special registration fails gpt2_slow_tokenizer_registers_named_specials_from_the_vocab and lille_slow_files_without_added_tokens_decoder_still_split_specials.
  • Run on spark-102 (GB10, CUDA, --features cuda): cargo test --profile test-fast --features cuda --lib tokenizer:: (155 passed), cargo test --profile test-fast --features cuda --test gpt2_slow_tokenizer_parity with MLXCEL_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 the scripts/ci contract checks. Tokenization is CPU-only, so nothing here is Metal-specific; the Metal build was not run on this host.

Closes #3569

@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modeltype:text Text-only language model status:review Under review status:done Completed and removed status:review Under review labels Nov 30, 2026
@inureyes

Copy link
Copy Markdown
Member Author

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 bos_token or eos_token of $A or $B became a second sequence reference and silently duplicated every encode (with or without special tokens), and a token containing a space or : failed the load. The template is now built from structured pieces. A new unit test gpt2_slow_tokenizer_template_treats_bos_eos_text_literally fails with the string template restored.

No other issues found. Crafted vocab.json, merges.txt, and added_tokens_decoder inputs all return errors rather than panicking: u32::MAX or negative ids, sparse or duplicate ids, empty content, duplicate added content, malformed merge lines, non-object configs, and non-string token values. Allocations are linear in file size, and added-token registration stays batched. The Qwen2 path behaves as before: Refuse keeps the old rejection, and only the error text was refactored. GPT-2 detection runs last in load_tokenizer, so other loaders are unaffected.

LOW, not changed: checkpoint-declared specials and in-vocab added tokens are matched in user text, as in transformers and the tokenizer.json path. tokenizer_config.json is parsed about six times per load, which costs little. The fixture generator and parity test only read local files and write the fixture.

Verified: --lib tokenizer:: (156 passed), --test gpt2_slow_tokenizer_parity with MLXCEL_REQUIRE_MODELS=1 (3 passed), --bin mlxcel (363 passed), clippy -D warnings, fmt, and the CI contract scripts.

inureyes added a commit that referenced this pull request Nov 30, 2026
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
@inureyes
inureyes force-pushed the fix/3569-gpt2-slow-tokenizer branch from 6a39af5 to 59d3db3 Compare November 30, 2026 02:24
@inureyes
inureyes marked this pull request as ready for review November 30, 2026 02:24
@inureyes
inureyes merged commit 840ad4c into main Nov 30, 2026
18 of 20 checks passed
@inureyes
inureyes deleted the fix/3569-gpt2-slow-tokenizer branch November 30, 2026 02:25
inureyes added a commit that referenced this pull request Nov 30, 2026
#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.
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(tokenizer): build a tokenizer from GPT-2 slow files (vocab.json + merges.txt)

1 participant