Repository navigation
Description
Summary
The #683 quality gate (teacher-forced perplexity via the new examples/perplexity.rs, merged in PR #685) exposed that the gemma-4 family's text modeling in mlxcel is severely degraded while every other family is healthy on the identical corpus and harness. This is a correctness bug in the gemma-4 forward path (or its checkpoint loading), not a quantization artifact, and it is almost certainly the same root cause as the known temp-0 greedy pad-collapse on gemma-4-12b-it noted during PR #682 validation.
Measured (GB10, docs-corpus ~62k tokens, chunked teacher-forced NLL, fresh caches per chunk)
| model | perplexity | verdict |
|---|---|---|
| qwen3.5-9b-4bit | 7.0 | healthy |
| gemma-3-4b-it-4bit | 15.3 | healthy (gemma-3 port is fine) |
| llama-3.1-8b-4bit | 24.8 | healthy |
| gemma-4-e4b-it-4bit | 50.0 | degraded (mild; per-layer-input sub-arch) |
| gemma-4-31b-it-4bit | 317 | severely degraded |
| gemma-4-12b-it-4bit | ~12,000 to 29,000 | catastrophic (uniform-random over the 262k vocab would be ppl ~262k / nll 12.48; measured nll 9.4 to 10.3) |
Context-length scan on gemma-4-12b: nll is flat-bad from the shortest chunks (32 tokens: nll 9.44; 64: 9.69; 128-512: ~10.3), while the gemma-3 control shows the normal improving-with-context pattern (64: 34.2 -> 512: 15.2). A 32-token chunk exercises no sliding window, no rotating cache, no long-range RoPE, so the defect is in the per-token forward itself: candidate suspects are the embed sqrt(hidden) scale, sandwich-norm wiring (pre/post attention and MLP order), QK-norm epsilon or placement, v_norm (RMSNormNoScale on values), layer_scalar application, final norm or lm_head wiring, logit softcapping, and local/global RoPE theta assignment. Severity ordering (e4b 50 / 31b 317 / 12b 12k) may indicate the bug scales with depth or differs across the dense vs per-layer-input sub-paths.
Why this went unnoticed
All prior gemma-4 validation was throughput (#672/#676/#679 prefill, #675/#680/#683 decode) plus SELF-consistency token-identity A/Bs (two code paths of the same build compared against each other), which a systematically wrong forward passes perfectly. The temp-0 pad-collapse WAS visible during #682 validation but was classified as a pre-existing checkpoint quirk; the perplexity gate now shows it is one symptom of a real defect.
Reproduction
cargo run --release --features cuda --example perplexity -- models/gemma-4-12b-it-4bit CORPUS.txt 64 8 (any English text file works; compare with models/gemma-3-4b-it-4bit on the same file). Pad-collapse repro: mlxcel generate -m models/gemma-4-12b-it-4bit -p "What is a prime number?" -n 32 --temp 0 emits 1-2 tokens then <pad> spam.
Fix direction
Bisect the dense gemma-4 block against the gemma-3 implementation (which is healthy and structurally close) and against the model card / reference implementation of the gemma-4 architecture: verify norm placement and (1+w) offsets, QK-norm, v_norm, layer_scalar, attention scale (query_pre_attn_scalar), local/global rope thetas, sliding pattern, final norm and lm_head tying, and logit softcap. A single mis-wired scalar or norm reproduces exactly this signature (locally plausible next-token echo, catastrophic NLL, EOS/pad inflation). After the fix, greedy behavior should stop pad-collapsing and ppl should land near gemma-3's on the same corpus; then the #683 quantization quality frontier must be re-run since all its quality conclusions are void on the broken forward.
Impact
- All gemma-4 dense text serving quality (12b/31b and likely the whole family to varying degrees).
- The perf(cuda/gemma4): decode is bound by 8-bit MLP weight bytes plus a near-saturated dual CPU/GPU pipeline; qmm kernels are healthy #683 quality gate is blocked on this; its throughput measurements (uniform 4-bit 1.6x etc.) remain valid.
- Secondary finding from the same session, for a separate smaller issue if wanted: the gemma-4 MLP loader infers per-module bits at the GLOBAL group_size only, so checkpoints with mixed bits WITHIN one MLP (down_proj 8-bit + gate/up 4-bit) fail to load (
[quantized_matmul] shapes of weight and scales are incompatible ... w.shape() == (3840,3840) and scales.shape() == (3840,240) with group_size=64 and bits=4), and per-modulegroup_size: 32overrides are misread as bits=2 (expanded quantized matrix (7680, 15360) computed from shape (15360,480) with group_size=64, bits=2).
Related
- perf(cuda/gemma4): decode is bound by 8-bit MLP weight bytes plus a near-saturated dual CPU/GPU pipeline; qmm kernels are healthy #683 (quality/throughput frontier, blocked on this), PR tools: requantization script and perplexity harness #685 (perplexity harness), PR perf(gemma4): cut decode-path primitive count on CUDA (#680) #682 (pad-collapse first noted), fix: gemma-4 long-prompt prefill OOMs on CUDA because attention materializes O(heads*L^2) scores instead of using flash SDPA #672/fix(cuda/attention): bound long-prompt prefill memory for flash-ineligible models #676/fix(cache): unbreak rotating-cache chunked prefill and default the CLI prefill to chunked #679 (gemma-4 prefill work, unaffected claims)
Activity
inureyes commentedon Jul 7, 2026
Refined diagnosis: #686 is TWO independent bugs, and generation could never catch either
Investigation with the new
examples/perplexity.rs(chunks=1 = single clean chunk-0 forward, no harness complications) localized the problem precisely.Bug 1: gemma-4 tokenizer.json ships a BOS-less post-processor (real, affects production raw-text paths)
gemma-4-12b
tokenizer.jsonhaspost_processor.single = [{Sequence: A}](passthrough), while the healthy gemma-3-4b has[{SpecialToken: <bos>}, {Sequence: A}]. So every raw-text path (CLIgenerate,/v1/completions, teacher-forced scoring) ran with NO BOS. Chat-template paths were unaffected because the Gemma 4 chat template emits{{ bos_token }}itself. Measured cost of the missing BOS on the docs corpus: gemma-3-4b ~3.6 nats/token, gemma-4-12b ~6.6 nats/token. This is a checkpoint packaging omission that mlxcel should repair at tokenizer-load time.Bug 2: a position-dependent forward bug (the dominant issue; still open)
Even with BOS present, on a single clean chunk-0 prefill gemma-4-12b's cumulative teacher-forced NLL rises without bound as the scored sequence grows, converging toward uniform-random (ln(vocab)=ln(262144)=12.48):
Per-token NLL is ~2 up to position ~128, then jumps to ~7-9 and climbs to ~12.5 (random) by position ~1000. gemma-3 stays flat at every length. This is why generation looked fine: it only reads the LAST position's logits (
forward_last_logits), and short structured chat turns stay in the low-position regime; teacher-forced scoring over every position is the first thing that exercised the broken high-position predictions. All prior gemma-4 validation was generation or self-consistency A/Bs, both blind to this.The break is NOT the tokenizer, NOT attention-kernel choice (#675 A/B was ~1.0x), and NOT the flag-path prefill mask (DENSE_PREFILL_MASK_MAX_TOKENS=4096, so these lengths use the dense mask). The prime suspect is the gemma-4 global/full_attention layer path (8 of 48 layers, every 6th), which is the only exotic surface: global_head_dim 512 (vs sliding 256), proportional RoPE (rope_type "proportional", partial_rotary_factor 0.25, theta 1e6), attention_k_eq_v true, num_global_key_value_heads 1. Sliding layers use the same plain full-rotary theta-10000 path as healthy gemma-3.
Plan
Fix bug 1 (tokenizer BOS repair at load, guarded against double-BOS and against touching correct exports like gemma-3), then bisect bug 2 in the global-layer path. Severity gradient across variants (12b catastrophic, 31b ppl ~1900, e4b ppl ~58) tracks how heavily each uses the global-layer config. The #683 quantization quality frontier stays blocked until bug 2 is fixed.
inureyes commentedon Jul 7, 2026
Investigation complete: Bug 1 fixed in mlxcel; Bug 2 proven NOT an mlxcel forward bug
Bug 1 (tokenizer BOS) — real mlxcel bug, fixed
The Gemma 4
tokenizer.jsonships a passthroughpost_processor(single: [{Sequence: A}]) instead of the Gemma 3 style[{SpecialToken: <bos>}, {Sequence: A}], so every raw-text encode path ran BOS-less.ensure_bos_post_processor()(insrc/tokenizer/mod.rs) now installs the standard<bos> $ATemplateProcessing at load, guarded by an encode probe so correct exports (Gemma 3) are untouched, and by the existingadd_special = !prompt.starts_with("<bos>")guard in the CLI and server so the chat-template path (which already emits<bos>) never double-BOSes. This affects onlyadd_special=trueraw-text encoding; the chat path is byte-identical before and after.Bug 2 (position-dependent forward degradation) — NOT in mlxcel
Exhaustive bisection shows mlxcel's gemma-4 forward is faithful. It is bit-for-bit consistent with two independent reference implementations, and all three produce the identical rising-perplexity curve on the shipped checkpoint.
Single-forward teacher-forced NLL, gemma-4-12b-it-4bit, on the docs corpus (chunks=1):
gemma4_textref (GPU)The
mlx_lmreference is a completely separate Python codebase; it matches mlxcel to within 0.05 nats at every length. Controls stay flat on the same harness and corpus (gemma-3-4b: 1.52 → 3.63; qwen3.5-9b: 1.10 → 2.55), so mlxcel's forward and the harness are correct for healthy models.Bisection trail (each a full chunk-0 sweep):
ProportionalRoPE(verified by hand and pinned by a new reference-value test); the compiled full-headinf-tail path equals the reference pack/rotate/unpack algorithm.rotated_dims(long-wavelength) instead ofhead_dimmade it WORSE (nll@512 8.40 → 9.35), confirming the shipped÷head_dimnormalization (matching the references) is correct and not the lever.sqrt(hidden)scale, final softcap, and the masks (create_causal_mask,create_sliding_window_prefill_maskfor l < window) all match the reference line-for-line.Root-cause characterization: the 8 full-attention (global) layers use proportional RoPE (
partial_rotary_factor 0.25,theta 1e6, exponent normalized by the fullhead_dim = 512). That compresses the 128 rotated dimensions to a maximum wavelength of ~188 positions, so those layers cannot resolve query/key distance beyond ~188 tokens. Per-token NLL is healthy to ~128-188 then climbs to random by ~1000, exactly matching this wavelength. This is a property of the checkpoint's documented architecture as understood by the entire MLX ecosystem (mlxcel,mlx_lm.models.gemma4_text,mlx_vlm.models.gemma4.languageare all identical here). The checkpoint genuinely uses this architecture (weights carryq_norm/k_norm, k_eq_v, nov_projon global layers, norelative_k_proj/per_dim_scale). HFtransformershas NOgemma4_unifiedtext modeling (itsgemma4is a different architecture that does not match these weights), so there is no authoritative reference available here that produces a flat curve to target.Conclusion and scope
mlx_lmandmlx_vlm. Correcting it (if the true post-cutoff gemma-4_unified proportional RoPE differs) belongs upstream in the shared architecture definition, not in a faithful port. Recommend a separate upstream-tracking issue.Data:
benchmarks/cuda_gb10_gemma4_quality_686_2026-07-07.csv.test(gemma4): pin proportional-RoPE math, harden ppl harness (#686)
fix(gemma4): render thinking-off closed channel by default (#686)
inureyes commentedon Jul 7, 2026
Correction: #686's user-visible bug IS an mlxcel bug (chat-template rendering), now fixed
My earlier comment concluded the forward was faithful and the remaining problem was upstream. The forward finding stands, but it was a red herring for the user-visible symptom. Follow-up investigation (running Apple's mlx_lm reference for GENERATION, not just perplexity) localized the real bug.
The user-visible bug (temp-0 pad-collapse) = chat-template rendering (fixed in PR #687)
The Gemma 4
chat_template.jinjageneration prompt is<|turn>model\n<|channel>thought\n<channel|>(CLOSED thought channel, model answers directly) for the non-thinking default, and bare<|turn>model\nforenable_thinking=true.transformersrenders the CLOSED scaffold by default and the model answers correctly (e.g. "Paris"). mlxcel instead forcedenable_thinking=truefor this template family (thehas_thinkingheuristic, mlx-lm PR #1114) AND appended an OPEN<|channel>thought\nmarker viapatch_gemma4_generation_prompt, producing a thinking-on prompt (bare turn + open channel) that drives quantized Gemma 4 into an open reasoning channel and greedy-collapses to<pad>.Fix: keep the thinking-off default for the Gemma-4 thinking-channel template (
wants_thinking_default_off()guards the PR #1114 flip in generate/startup) and remove the open-channel post-render patch. mlxcel's rendered prompt is now byte-identical to transformers for default,enable_thinking=false(both CLOSED), andenable_thinking=true(bare), verified by token-id parity (France and sky prompts: first16 + last8 ids match, closed-channel ending id 101). First generated token is now correct (France to "Paris").The forward is faithful (retained finding)
mlxcel's gemma-4 prefill matches Apple's mlx_lm
gemma4_textwithin 0.05 nats at every length; the elevated raw-document perplexity is shared by mlx_lm (instruct checkpoint on OOD raw text), not an mlxcel bug. Proportional RoPE is equivalent to the reference and pinned by a new test.Newly discovered, still open: gemma-4 KV-cache decode collapse
Even with the byte-identical prompt, mlxcel's gemma-4 KV-cache decode collapses to
<pad>after a few tokens, while Apple mlx_lm's KV-cache decode is coherent on the same model+prompt and mlxcel's gemma-3 decode is coherent. Isolation:MLXCEL_DISABLE_SINGLE_QUERY_MASKLESS=1lengthens the coherent run (2 to 24 tokens on uniform-4bit) and the 8-bit MLP GEMV shortens it further (24 to 6 on mixed-quant), so the single-query maskless decode-attention path is the dominant contributor plus a secondary quantized-GEMV factor. This is a decode-kernel (forward-path) issue, separate from the chat template; it needs a dedicated follow-up. PR #687 fixes the chat template (necessary) but this decode bug must also be resolved before #686's pad-collapse is fully gone.fix(gemma4): render thinking-off closed channel to fix chat pad-colla…
inureyes commentedon Jul 7, 2026
Split for tracking. The chat-template rendering bug and the tokenizer BOS omission (the first-token pad-collapse and the raw-text BOS-less path) are fixed by PR #687 (merged). The remaining, separately-confirmed defect, gemma-4 decode collapsing to after 1-3 tokens (single-query maskless attention plus a quantized-GEMV factor; mlx_lm decodes coherently on the same prompt), is now tracked in #688. This issue stays open until #688 lands, since gemma-4 is not usable end to end until the decode path is fixed.
inureyes commentedon Jul 7, 2026
Resolved. gemma-4 is now usable end to end on CUDA. The three constituent bugs are all fixed and merged:
Verified: gemma-4-12b-it-4bit CLI decode is deterministic and coherent (byte-identical across runs, matching the Apple mlx_lm reference trajectory), and the server /v1/chat/completions returns coherent output. Controls (gemma-3, qwen3.5, llama) are unaffected.
Two follow-ups remain, documented in PR #689 and out of scope here: root-causing the underlying CUDA-graph ordering hazard so graph capture can be re-enabled for gemma-4 (recovering the ~2.3% decode cost), and gemma-3's separately-observed latent (non-collapsing) head_dim-256 sdpa_vector nondeterminism under graphs. The forward and proportional RoPE were confirmed faithful to mlx_lm; the earlier catastrophic-perplexity framing was a measurement artifact (elevated raw-document perplexity shared by the reference for an instruct checkpoint). Closing.
fix(cli): render Gemma 4 audio user turn after the prompt text (#798)
fix(server): define tools only when the request sends them (#1598)
fix(gemma4): render thinking-off closed channel to fix chat pad-colla…
fix(cli): render Gemma 4 audio user turn after the prompt text (lablu…