Skip to content

fix(gemma4): render thinking-off closed channel to fix chat pad-collapse (#686) - #687

Merged
inureyes merged 3 commits into
mainfrom
fix/686-gemma4-forward-quality
Jul 7, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/686-gemma4-forward-quality

Conversation

@inureyes

@inureyes inureyes commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

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.jinja renders the generation prompt as <|turn>model\n<|channel>thought\n<channel|> (a CLOSED empty thought channel, so the model answers directly) when not enable_thinking | default(false), and a bare <|turn>model\n (the model opens its own reasoning) when thinking is enabled. transformers.apply_chat_template with no enable_thinking kwarg renders the CLOSED scaffold and the reference then generates the correct answer.

mlxcel diverged two ways: (1) the tokenizer has_thinking heuristic (mlx-lm PR #1114) forced enable_thinking=true for this template family because it exposes multi-token <|channel>thought / <channel|> markers, and (2) patch_gemma4_generation_prompt then appended an OPEN <|channel>thought\n marker 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>thought marker and the not enable_thinking guard, so Qwen3's <think> path never matches), and the commands::generate and server::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 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 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 and last8 token ids match the reference exactly, both ending in the closed-channel token id 101).

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> $A template 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 ProportionalRoPE pack/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_text reference 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=1 sharply 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

  • cargo test -p mlxcel --features cuda --lib chat_template (89 passed; new tests pin the closed-channel default, the bare thinking=true render, and no post-render patch)
  • cargo test -p mlxcel-core --features cuda --lib rope_proportional (5 passed)
  • token-id parity: mlxcel rendered prompt == transformers for France and sky (first16 + last8 ids identical, closed-channel ending id 101)
  • mlxcel gemma-4-12b first token now correct (France to "Paris") instead of the pre-fix "The user is asking..." meta-reasoning collapse

Refs #686 (partial: fixes the chat-template and tokenizer aspects; the decode-path collapse is tracked separately and #686 stays open until it lands)

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.
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:critical Requires immediate attention area:models Model architectures, weights, loading, metadata status:review Under review labels Jul 7, 2026
inureyes added 2 commits July 7, 2026 18:56
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
inureyes force-pushed the fix/686-gemma4-forward-quality branch from 7268aef to 63ac68d Compare July 7, 2026 09:58
@inureyes inureyes changed the title fix(tokenizer): add Gemma BOS post-processor; scope gemma-4 long-context regression to upstream (#686) fix(gemma4): render thinking-off closed channel to fix chat pad-collapse (#686) Jul 7, 2026
@inureyes
inureyes merged commit 7ce3e19 into main Jul 7, 2026
4 checks passed
@inureyes
inureyes deleted the fix/686-gemma4-forward-quality branch July 7, 2026 11:02
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 6, 2026
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.
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 priority:critical Requires immediate attention 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.

1 participant