Repository navigation
fix(gemma4): render thinking-off closed channel to fix chat pad-collapse (#686) - #687
Merged
Merged
Conversation
Gemma 4 tokenizer.json ships a passthrough post_processor (single: [{Sequence: A}]) instead of the Gemma 3 style [{SpecialToken: <bos>}, {Sequence: A}], so every raw-text encode path (CLI generate, /v1/completions, teacher-forced perplexity scoring) silently ran with no leading <bos>. On the #686 docs corpus this costs gemma-3-4b about 3.6 nats/token and gemma-4-12b about 6.6 nats/token of teacher-forced NLL.
ensure_bos_post_processor() installs the standard `<bos> $A` TemplateProcessing at tokenizer load when tokenizer_config declares a Gemma tokenizer class (or an explicit add_bos_token: true), add_bos_token is not explicitly false, the configured bos_token resolves to a vocab id, and an encode probe shows the loaded post-processor does not already insert it. The probe leaves correct exports (Gemma 3) untouched, and the existing add_special = !prompt.starts_with("<bos>") guard in the CLI and server keeps the chat-template path (which already emits <bos>) from double-BOSing, so only add_special=true raw-text encoding changes; the chat path is byte-identical.
Refs #686.
Adds a reference-value test asserting the compiled full-head proportional-RoPE fast path (the inf-tail mx.fast.rope shortcut used on Gemma 4 full-attention layers) is numerically identical to the mlx-vlm / mlx-lm ProportionalRoPE pack/rotate/unpack algorithm, for the exact global-layer config (head_dim 512, partial_rotary_factor 0.25, theta 1e6) at offsets 0, 5, 130, and 500. This pins the verified math so it cannot silently regress, which the identity and generation A/B tests demonstrably did not catch (issue #686). Hardens examples/perplexity.rs: documents that MAX_CHUNKS=1 is the reference-clean single-forward measurement (each chunk is scored as an independent BOS-anchored fresh sequence, so multi-chunk numbers are pessimistic and not a continuous-context corpus perplexity), keeps the per-chunk model-owned-state reset and the per-position shape assertion, and aborts on a non-finite chunk NLL instead of silently averaging it into the mean. Records the #686 quality measurements (mlxcel vs the independent mlx_lm gemma4_text reference, the uniform-4bit variant, the rope-normalization probe, and the gemma-3 / qwen3.5 controls) in benchmarks/cuda_gb10_gemma4_quality_686_2026-07-07.csv. Refs #686.
The user-visible #686 symptom (temp-0 greedy chat emitting a token or two then <pad> spam) is a mlxcel chat-template rendering bug, not a forward or RoPE defect. The gemma-4 forward and proportional RoPE are faithful to Apple's mlx_lm reference (teacher-forced perplexity matches within 0.05 nats); the elevated raw-document perplexity is shared by mlx_lm and is just an instruct checkpoint scored on out-of-distribution raw text, not a bug. Root cause: the Gemma 4 chat_template.jinja renders `<|turn>model\n<|channel>thought\n<channel|>` (a CLOSED empty thinking channel that makes the model answer directly) when `not enable_thinking | default(false)`, and a bare `<|turn>model\n` when thinking is enabled. transformers renders the CLOSED scaffold by default. mlxcel instead forced `enable_thinking=true` for this template family (the tokenizer `has_thinking` heuristic, mlx-lm PR #1114) AND appended an OPEN `<|channel>thought\n` marker via a post-render patch, so the interactive default became a thinking-on prompt that drives quantized Gemma 4 into an open reasoning channel and greedy-collapses to <pad>. Fix: `ChatTemplateProcessor::wants_thinking_default_off()` detects the Gemma 4 thinking-channel template (both the `<|channel>thought` marker and the `not enable_thinking` guard), and the generate/startup thinking-default hooks skip the PR #1114 flip for it, keeping the transformers-matching thinking-off default. The post-render `patch_gemma4_generation_prompt` (which appended the OPEN channel for thinking=true, diverging from transformers' bare ending) is removed, so minijinja's faithful render flows through untouched. mlxcel's rendered prompt is now byte-identical to transformers for all three cases (default and enable_thinking=false render the CLOSED scaffold; enable_thinking=true renders bare), verified by token-id parity on the France and sky prompts (first16 + last8 ids match the reference exactly). Qwen3 and other single-token `<think>` families are unaffected. Refs #686.
inureyes
force-pushed
the
fix/686-gemma4-forward-quality
branch
from
July 7, 2026 09:58
7268aef to
63ac68d
Compare
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…pse (lablup#686) (lablup#687) * fix(tokenizer): add Gemma BOS post-processor for BOS-less exports (lablup#686) Gemma 4 tokenizer.json ships a passthrough post_processor (single: [{Sequence: A}]) instead of the Gemma 3 style [{SpecialToken: <bos>}, {Sequence: A}], so every raw-text encode path (CLI generate, /v1/completions, teacher-forced perplexity scoring) silently ran with no leading <bos>. On the lablup#686 docs corpus this costs gemma-3-4b about 3.6 nats/token and gemma-4-12b about 6.6 nats/token of teacher-forced NLL. ensure_bos_post_processor() installs the standard `<bos> $A` TemplateProcessing at tokenizer load when tokenizer_config declares a Gemma tokenizer class (or an explicit add_bos_token: true), add_bos_token is not explicitly false, the configured bos_token resolves to a vocab id, and an encode probe shows the loaded post-processor does not already insert it. The probe leaves correct exports (Gemma 3) untouched, and the existing add_special = !prompt.starts_with("<bos>") guard in the CLI and server keeps the chat-template path (which already emits <bos>) from double-BOSing, so only add_special=true raw-text encoding changes; the chat path is byte-identical. Refs lablup#686. * test(gemma4): pin proportional-RoPE math, harden ppl harness (lablup#686) Adds a reference-value test asserting the compiled full-head proportional-RoPE fast path (the inf-tail mx.fast.rope shortcut used on Gemma 4 full-attention layers) is numerically identical to the mlx-vlm / mlx-lm ProportionalRoPE pack/rotate/unpack algorithm, for the exact global-layer config (head_dim 512, partial_rotary_factor 0.25, theta 1e6) at offsets 0, 5, 130, and 500. This pins the verified math so it cannot silently regress, which the identity and generation A/B tests demonstrably did not catch (issue lablup#686). Hardens examples/perplexity.rs: documents that MAX_CHUNKS=1 is the reference-clean single-forward measurement (each chunk is scored as an independent BOS-anchored fresh sequence, so multi-chunk numbers are pessimistic and not a continuous-context corpus perplexity), keeps the per-chunk model-owned-state reset and the per-position shape assertion, and aborts on a non-finite chunk NLL instead of silently averaging it into the mean. Records the lablup#686 quality measurements (mlxcel vs the independent mlx_lm gemma4_text reference, the uniform-4bit variant, the rope-normalization probe, and the gemma-3 / qwen3.5 controls) in benchmarks/cuda_gb10_gemma4_quality_686_2026-07-07.csv. Refs lablup#686. * fix(gemma4): render thinking-off closed channel by default (lablup#686) The user-visible lablup#686 symptom (temp-0 greedy chat emitting a token or two then <pad> spam) is a mlxcel chat-template rendering bug, not a forward or RoPE defect. The gemma-4 forward and proportional RoPE are faithful to Apple's mlx_lm reference (teacher-forced perplexity matches within 0.05 nats); the elevated raw-document perplexity is shared by mlx_lm and is just an instruct checkpoint scored on out-of-distribution raw text, not a bug. Root cause: the Gemma 4 chat_template.jinja renders `<|turn>model\n<|channel>thought\n<channel|>` (a CLOSED empty thinking channel that makes the model answer directly) when `not enable_thinking | default(false)`, and a bare `<|turn>model\n` when thinking is enabled. transformers renders the CLOSED scaffold by default. mlxcel instead forced `enable_thinking=true` for this template family (the tokenizer `has_thinking` heuristic, mlx-lm PR lablup#1114) AND appended an OPEN `<|channel>thought\n` marker via a post-render patch, so the interactive default became a thinking-on prompt that drives quantized Gemma 4 into an open reasoning channel and greedy-collapses to <pad>. Fix: `ChatTemplateProcessor::wants_thinking_default_off()` detects the Gemma 4 thinking-channel template (both the `<|channel>thought` marker and the `not enable_thinking` guard), and the generate/startup thinking-default hooks skip the PR lablup#1114 flip for it, keeping the transformers-matching thinking-off default. The post-render `patch_gemma4_generation_prompt` (which appended the OPEN channel for thinking=true, diverging from transformers' bare ending) is removed, so minijinja's faithful render flows through untouched. mlxcel's rendered prompt is now byte-identical to transformers for all three cases (default and enable_thinking=false render the CLOSED scaffold; enable_thinking=true renders bare), verified by token-id parity on the France and sky prompts (first16 + last8 ids match the reference exactly). Qwen3 and other single-token `<think>` families are unaffected. Refs lablup#686.
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
Corrected diagnosis of #686. The user-visible symptom (temp-0 greedy chat on gemma-4-12b emitting a token or two then
<pad>spam) is an mlxcel chat-template rendering bug, now fixed. The earlier perplexity investigation was accurate that the gemma-4 forward and proportional RoPE are faithful to Apple's mlx_lm reference, but that was a red herring for the user symptom: elevated raw-document perplexity is shared by mlx_lm (an instruct checkpoint scored on out-of-distribution raw text), while the real interactive bug lives in how mlxcel rendered the chat prompt. This PR fixes the chat-template rendering, keeps the tokenizer BOS repair and the proportional-RoPE reference test, and documents a separately-discovered gemma-4 decode-path issue that remains.The real bug (fixed): Gemma-4 thinking-channel default
The Gemma 4
chat_template.jinjarenders the generation prompt as<|turn>model\n<|channel>thought\n<channel|>(a CLOSED empty thought channel, so the model answers directly) whennot enable_thinking | default(false), and a bare<|turn>model\n(the model opens its own reasoning) when thinking is enabled.transformers.apply_chat_templatewith noenable_thinkingkwarg renders the CLOSED scaffold and the reference then generates the correct answer.mlxcel diverged two ways: (1) the tokenizer
has_thinkingheuristic (mlx-lm PR #1114) forcedenable_thinking=truefor this template family because it exposes multi-token<|channel>thought/<channel|>markers, and (2)patch_gemma4_generation_promptthen appended an OPEN<|channel>thought\nmarker for thinking=true. The combination made the interactive default a thinking-on prompt (bare model turn + open channel), which drives quantized Gemma 4 into an open reasoning channel that greedy-collapses to<pad>.Fix:
ChatTemplateProcessor::wants_thinking_default_off()detects the Gemma-4 thinking-channel template (requires both the<|channel>thoughtmarker and thenot enable_thinkingguard, so Qwen3's<think>path never matches), and thecommands::generateandserver::startupthinking-default hooks skip the PR #1114 flip for it, keeping the transformers-matching thinking-off default. The post-renderpatch_gemma4_generation_prompt(which diverged from transformers by appending the open channel for thinking=true) is removed, so minijinja's faithful render flows through untouched. mlxcel's rendered prompt is now byte-identical to transformers for all three cases (default andenable_thinking=falserender the CLOSED scaffold;enable_thinking=truerenders bare), verified by token-id parity on the France and sky prompts (first16 and last8 token ids match the reference exactly, both ending in the closed-channel token id101).Also fixed / kept
Bug 1 (tokenizer BOS): the Gemma 4 tokenizer.json ships a passthrough post-processor, so raw-text encode paths ran BOS-less;
ensure_bos_post_processor()installs the standard<bos> $Atemplate at load, guarded so correct exports and the chat path are untouched. This is independent of the chat-template fix and independently valuable.Proportional-RoPE reference test: pins that the compiled full-head fast path equals the mlx-vlm / mlx-lm
ProportionalRoPEpack/rotate/unpack algorithm, so the (verified-correct) global-layer RoPE cannot silently regress.Forward is faithful (finding retained, reframed)
mlxcel's gemma-4 prefill forward matches the independent mlx_lm
gemma4_textreference within 0.05 nats at every scored length (128/256/512), and controls (gemma-3-4b, qwen3.5-9b) stay flat on the same harness. The proportional RoPE is mathematically equivalent to the reference and pinned by the new test. So the forward is NOT the user-visible bug, and per the review direction it is not modified here.Remaining work (separate, newly discovered): gemma-4 KV-cache decode collapse
With the now-byte-identical prompt, the FIRST generated token is correct (France to "Paris", sky to "The"), but mlxcel's gemma-4 KV-cache decode still collapses to
<pad>after a few tokens, while Apple mlx_lm's KV-cache decode on the same model + prompt is coherent ("...Rayleigh scattering, where Earth's atmosphere scatters shorter blue and violet wavelengths...") and mlxcel's gemma-3 decode is coherent. Isolation:MLXCEL_DISABLE_SINGLE_QUERY_MASKLESS=1sharply lengthens the coherent run (2 to 24 tokens on uniform-4bit), and the 8-bit MLP GEMV shortens it further (24 to 6 on the mixed-quant checkpoint), so the single-query maskless decode-attention path is the dominant contributor with a secondary quantized-GEMV factor. This is a decode-kernel issue in the forward path (out of this PR's scope, which explicitly does not touch the forward) and warrants a dedicated follow-up. The chat-template fix here is necessary but not sufficient to fully eliminate the pad-collapse.Test plan
Refs #686 (partial: fixes the chat-template and tokenizer aspects; the decode-path collapse is tracked separately and #686 stays open until it lands)