Repository navigation
fix(diffusion_gemma): demote tool-parser markers from special tokens at load - #789
Merged
inureyes merged 2 commits intoJul 13, 2026
Merged
Conversation
…at load DiffusionGemma checkpoints ship the tool-parser and reasoning-channel markers `<|tool_call>`, `<tool_call|>`, `<|"|>`, `<|channel>`, `<channel|>` as `special: true` added tokens in tokenizer.json. Confirmed against the real checkpoint (models/diffusiongemma-26b-a4b-it-4bit/tokenizer.json): all five ship special at ids 48, 49, 52, 100, 101, and tokenizer_config.json's added_tokens_decoder is empty, so this checkpoint loads through the HuggingFace tokenizer.json arm of load_tokenizer, not SentencePiece. Because decode(ids, skip_special_tokens=true) strips special tokens, the server tool-call parser never saw the markers in generated text. load_tokenizer's HuggingFace arm now routes diffusion_gemma and diffusion_gemma_text checkpoints (matching the model_type strings in models/detection.rs) through a new build_diffusion_gemma_tokenizer, which demotes the five markers before the tokenizer is deserialized. This has to happen in the raw JSON, not as a post-load mutation: tokenizers 0.22.2's AddedVocabulary::special_tokens_set is insert-only, so re-adding a token's content with special: false via Tokenizer::add_tokens after load can never clear the flag, and AddedVocabulary's Deserialize path rebuilds the vocabulary from scratch by replaying add_tokens over each added_tokens entry's own special field. The demotion only touches markers that are both present and currently special, so a future checkpoint shipping a subset is handled without error. Every other model type keeps the exact same Tokenizer::from_file call as before. infer_thinking_markers and resolve_thinking_token_ids resolve the <|channel> / <channel|> pair via token_to_id lookups, never the special flag, so the reasoning-channel detection is unaffected by demotion; the server-side strip_thinking pass is a literal text match over decoded output and never looked at the flag either. Added unit coverage for the JSON transform, the model_type gate, a synthetic-tokenizer round trip proving skip_special_tokens=true now retains the markers (with a control assertion that an un-demoted build still strips them), a tool-call parse of the resulting text through server::tool_calls::parse_tool_calls, a thinking-channel extraction check after demotion, an end-to-end load_tokenizer test confirming a non-diffusion_gemma model is unaffected, and a real-checkpoint test loading models/diffusiongemma-26b-a4b-it-4bit directly. Validated against the real checkpoint end to end: a release build's mlxcel generate produced coherent output, and mlxcel-server correctly parsed a live get_weather tool call the model emitted for a /v1/chat/completions request with tools, previously undeliverable because the markers were stripped before the parser ever ran. Closes #778
…gemma gate The gate returns false for a checkpoint with no config.json or a config.json without model_type, keeping those on the unchanged Tokenizer::from_file path. Pin both cases so the graceful fallback cannot regress into a panic or an accidental demotion.
3 tasks
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…at load (lablup#789) ## Summary DiffusionGemma checkpoints ship the tool-parser and reasoning-channel markers `<|tool_call>`, `<tool_call|>`, `<|"|>`, `<|channel>`, `<channel|>` as `special: true` added tokens in `tokenizer.json`. A special token is stripped by `decode(ids, skip_special_tokens=true)`, so the server's tool-call parser (`src/server/tool_calls/parser.rs`) never sees the markers in generated text. This demotes the five markers to non-special at tokenizer load time for the DiffusionGemma family, so they still encode atomically but survive skip-special decode. ## Premise check (confirmed) I inspected `models/diffusiongemma-26b-a4b-it-4bit/tokenizer.json` directly. Its `added_tokens` array flags all five markers `special: true`: `<|tool_call>` (id 48), `<tool_call|>` (id 49), `<|"|>` (id 52), `<|channel>` (id 100), `<channel|>` (id 101). `tokenizer_config.json`'s `added_tokens_decoder` is empty, so this checkpoint loads through the HuggingFace `tokenizer.json` arm of `load_tokenizer` (`src/tokenizer/mod.rs`), not the SentencePiece path. `config.json`'s `model_type` is exactly `diffusion_gemma`. ## What changed - `src/tokenizer/mod.rs`: added `demote_tool_parser_markers` (pure JSON transform over a parsed `tokenizer.json` document), `build_diffusion_gemma_tokenizer` (reads the file, demotes, then deserializes via `Tokenizer::from_bytes`), and `is_diffusion_gemma_model` (gates on `config.json`'s `model_type` being `diffusion_gemma` or `diffusion_gemma_text`, matching `src/models/detection.rs`). - `load_tokenizer`'s HuggingFace arm now calls `build_diffusion_gemma_tokenizer` instead of `Tokenizer::from_file` when the model type matches; every other model type is unaffected (identical `Tokenizer::from_file` call as before). - The demotion happens in the raw JSON, before `Tokenizer::from_bytes` deserializes it, not via a post-load mutation of an already-constructed `tokenizers::Tokenizer`. I verified (and documented in the code) that a post-load approach cannot work in this crate version: `tokenizers` 0.22.2's `AddedVocabulary::special_tokens_set` is insert-only, so re-adding the same token content with `special: false` via `Tokenizer::add_tokens` after load never clears the flag; `AddedVocabulary`'s `Deserialize` path rebuilds the vocabulary from scratch by replaying `add_tokens` over each `added_tokens` entry's own `special` field, so the only reliable point to flip the flag is the JSON itself, before that rebuild runs. - Only markers that are both present and currently special in the source document are touched, so a future checkpoint shipping a subset of the five (or none) is handled without error. ## Thinking-channel interaction `src/tokenizer/mod.rs::infer_thinking_markers` and `src/server/thinking_budget.rs::resolve_thinking_token_ids` both resolve `<|channel>` / `<channel|>` purely via `token_to_id` vocabulary lookups, never via the special flag, so demotion does not affect marker resolution. The server-side reasoning extraction in `src/server/tool_calls/parser.rs::strip_thinking` is a literal substring match over decoded text and also never inspected the special flag. Added `diffusion_gemma_thinking_channel_survives_demotion`, which builds a demoted tokenizer, encodes and decodes a `<|channel>thought reasoning here<channel|>The weather is sunny.` sequence, confirms `infer_thinking_markers` still resolves the pair, and confirms `parse_tool_calls` still strips the reasoning block and returns only the trailing content. ## Tests - `demote_tool_parser_markers_flips_special_flag_for_present_markers`, `demote_tool_parser_markers_is_a_noop_when_absent`, `demote_tool_parser_markers_skips_already_non_special_markers`: unit coverage of the pure JSON transform. - `is_diffusion_gemma_model_matches_both_config_variants`: gating on `model_type`. - `diffusion_gemma_tokenizer_survives_skip_special_decode_round_trip`: builds a synthetic DiffusionGemma-shaped tokenizer.json, demotes it, reloads via `Tokenizer::from_bytes`, and confirms `decode(ids, skip_special_tokens=true)` retains the markers; includes a control assertion that an un-demoted build of the same JSON still strips them, so the test is not vacuous. - `diffusion_gemma_tool_call_output_parses_after_demotion`: feeds the decoded (marker-retaining) text through `server::tool_calls::parse_tool_calls` and confirms it parses as a Gemma4-format tool call (mirrors the existing `parse_gemma4_format` test). - `diffusion_gemma_thinking_channel_survives_demotion`: see above. - `load_tokenizer_demotes_markers_only_for_diffusion_gemma_model_type`: end-to-end through the real `load_tokenizer` entry point with two temp checkpoints, one `diffusion_gemma` (markers demoted) and one `gemma3` (markers untouched, still stripped), proving a non-DiffusionGemma model is unaffected. - `real_diffusion_gemma_checkpoint_demotes_and_retains_markers`: loads the actual `models/diffusiongemma-26b-a4b-it-4bit` checkpoint through the production `load_tokenizer` path and confirms all five real marker token ids survive `decode(..., skip_special_tokens=true)`. ## Validation - `cargo test --lib tokenizer::`: 53 passed, 5 ignored (unrelated real-model tests gated on other checkpoints), 0 failed. - `cargo test --lib server::tool_calls`: 225 passed, 0 failed (existing parser/stream-filter suite unaffected). - `cargo clippy --lib --tests -- -D warnings`: clean. - `cargo fmt --all -- --check`: clean. - Real checkpoint (unit test): loaded `models/diffusiongemma-26b-a4b-it-4bit`'s actual tokenizer.json through `load_tokenizer` and confirmed `<|tool_call>` (48), `<tool_call|>` (49), `<|"|>` (52), `<|channel>` (100), `<channel|>` (101) all decode as their literal text under `skip_special_tokens=true`, where before this change they were stripped to empty strings. - Real checkpoint (CLI): built the release binary (`cargo build --release --features metal,accelerate`) and ran `mlxcel generate -m models/diffusiongemma-26b-a4b-it-4bit -p "What is the capital of France?" -n 40`; output was coherent (`The capital of France is **Paris**.`), confirming the demotion does not disturb normal generation. - Real checkpoint (server, full stack): started `mlxcel-server -m models/diffusiongemma-26b-a4b-it-4bit`, confirmed the startup log emits `demoted DiffusionGemma tool-parser markers from special to non-special added tokens ... markers=["<|tool_call>", "<tool_call|>", "<|\"|>", "<|channel>", "<channel|>"]`, then sent a `/v1/chat/completions` request with a `get_weather` tool and the prompt "What is the current weather in Tokyo? Use the get_weather tool to find out." The model actually emitted a genuine tool call and the server parsed it correctly end to end: `finish_reason: "tool_calls"`, `function.name: "get_weather"`, `function.arguments: "{\"location\":\"Tokyo\"}"`. This is the acceptance criterion ("tool-augmented generation on DiffusionGemma parses tool calls") exercised live against the real checkpoint, not just a synthetic string. Closes lablup#778
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
DiffusionGemma checkpoints ship the tool-parser and reasoning-channel markers
<|tool_call>,<tool_call|>,<|"|>,<|channel>,<channel|>asspecial: trueadded tokens intokenizer.json. A special token is stripped bydecode(ids, skip_special_tokens=true), so the server's tool-call parser (src/server/tool_calls/parser.rs) never sees the markers in generated text. This demotes the five markers to non-special at tokenizer load time for the DiffusionGemma family, so they still encode atomically but survive skip-special decode.Premise check (confirmed)
I inspected
models/diffusiongemma-26b-a4b-it-4bit/tokenizer.jsondirectly. Itsadded_tokensarray flags all five markersspecial: true:<|tool_call>(id 48),<tool_call|>(id 49),<|"|>(id 52),<|channel>(id 100),<channel|>(id 101).tokenizer_config.json'sadded_tokens_decoderis empty, so this checkpoint loads through the HuggingFacetokenizer.jsonarm ofload_tokenizer(src/tokenizer/mod.rs), not the SentencePiece path.config.json'smodel_typeis exactlydiffusion_gemma.What changed
src/tokenizer/mod.rs: addeddemote_tool_parser_markers(pure JSON transform over a parsedtokenizer.jsondocument),build_diffusion_gemma_tokenizer(reads the file, demotes, then deserializes viaTokenizer::from_bytes), andis_diffusion_gemma_model(gates onconfig.json'smodel_typebeingdiffusion_gemmaordiffusion_gemma_text, matchingsrc/models/detection.rs).load_tokenizer's HuggingFace arm now callsbuild_diffusion_gemma_tokenizerinstead ofTokenizer::from_filewhen the model type matches; every other model type is unaffected (identicalTokenizer::from_filecall as before).Tokenizer::from_bytesdeserializes it, not via a post-load mutation of an already-constructedtokenizers::Tokenizer. I verified (and documented in the code) that a post-load approach cannot work in this crate version:tokenizers0.22.2'sAddedVocabulary::special_tokens_setis insert-only, so re-adding the same token content withspecial: falseviaTokenizer::add_tokensafter load never clears the flag;AddedVocabulary'sDeserializepath rebuilds the vocabulary from scratch by replayingadd_tokensover eachadded_tokensentry's ownspecialfield, so the only reliable point to flip the flag is the JSON itself, before that rebuild runs.Thinking-channel interaction
src/tokenizer/mod.rs::infer_thinking_markersandsrc/server/thinking_budget.rs::resolve_thinking_token_idsboth resolve<|channel>/<channel|>purely viatoken_to_idvocabulary lookups, never via the special flag, so demotion does not affect marker resolution. The server-side reasoning extraction insrc/server/tool_calls/parser.rs::strip_thinkingis a literal substring match over decoded text and also never inspected the special flag. Addeddiffusion_gemma_thinking_channel_survives_demotion, which builds a demoted tokenizer, encodes and decodes a<|channel>thought reasoning here<channel|>The weather is sunny.sequence, confirmsinfer_thinking_markersstill resolves the pair, and confirmsparse_tool_callsstill strips the reasoning block and returns only the trailing content.Tests
demote_tool_parser_markers_flips_special_flag_for_present_markers,demote_tool_parser_markers_is_a_noop_when_absent,demote_tool_parser_markers_skips_already_non_special_markers: unit coverage of the pure JSON transform.is_diffusion_gemma_model_matches_both_config_variants: gating onmodel_type.diffusion_gemma_tokenizer_survives_skip_special_decode_round_trip: builds a synthetic DiffusionGemma-shaped tokenizer.json, demotes it, reloads viaTokenizer::from_bytes, and confirmsdecode(ids, skip_special_tokens=true)retains the markers; includes a control assertion that an un-demoted build of the same JSON still strips them, so the test is not vacuous.diffusion_gemma_tool_call_output_parses_after_demotion: feeds the decoded (marker-retaining) text throughserver::tool_calls::parse_tool_callsand confirms it parses as a Gemma4-format tool call (mirrors the existingparse_gemma4_formattest).diffusion_gemma_thinking_channel_survives_demotion: see above.load_tokenizer_demotes_markers_only_for_diffusion_gemma_model_type: end-to-end through the realload_tokenizerentry point with two temp checkpoints, onediffusion_gemma(markers demoted) and onegemma3(markers untouched, still stripped), proving a non-DiffusionGemma model is unaffected.real_diffusion_gemma_checkpoint_demotes_and_retains_markers: loads the actualmodels/diffusiongemma-26b-a4b-it-4bitcheckpoint through the productionload_tokenizerpath and confirms all five real marker token ids survivedecode(..., skip_special_tokens=true).Validation
cargo test --lib tokenizer::: 53 passed, 5 ignored (unrelated real-model tests gated on other checkpoints), 0 failed.cargo test --lib server::tool_calls: 225 passed, 0 failed (existing parser/stream-filter suite unaffected).cargo clippy --lib --tests -- -D warnings: clean.cargo fmt --all -- --check: clean.models/diffusiongemma-26b-a4b-it-4bit's actual tokenizer.json throughload_tokenizerand confirmed<|tool_call>(48),<tool_call|>(49),<|"|>(52),<|channel>(100),<channel|>(101) all decode as their literal text underskip_special_tokens=true, where before this change they were stripped to empty strings.cargo build --release --features metal,accelerate) and ranmlxcel generate -m models/diffusiongemma-26b-a4b-it-4bit -p "What is the capital of France?" -n 40; output was coherent (The capital of France is **Paris**.), confirming the demotion does not disturb normal generation.mlxcel-server -m models/diffusiongemma-26b-a4b-it-4bit, confirmed the startup log emitsdemoted DiffusionGemma tool-parser markers from special to non-special added tokens ... markers=["<|tool_call>", "<tool_call|>", "<|\"|>", "<|channel>", "<channel|>"], then sent a/v1/chat/completionsrequest with aget_weathertool and the prompt "What is the current weather in Tokyo? Use the get_weather tool to find out." The model actually emitted a genuine tool call and the server parsed it correctly end to end:finish_reason: "tool_calls",function.name: "get_weather",function.arguments: "{\"location\":\"Tokyo\"}". This is the acceptance criterion ("tool-augmented generation on DiffusionGemma parses tool calls") exercised live against the real checkpoint, not just a synthetic string.Closes #778