Skip to content

bug(gemma4): dense gemma-4 text modeling is catastrophically degraded (ppl ~12k vs gemma-3's 15 on the same corpus); likely root of the temp-0 pad-collapse #686

Closed

Description

@inureyes

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-module group_size: 32 overrides are misread as bits=2 (expanded quantized matrix (7680, 15360) computed from shape (15360,480) with group_size=64, bits=2).

Related

Activity

  1. added
    status:ready
    type:bug
    priority:critical
    area:models
    status:in-progress
    and removed
    status:ready
    on Jul 7, 2026
  2. inureyes commented on Jul 7, 2026

    @inureyes
    MemberAuthor

    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.json has post_processor.single = [{Sequence: A}] (passthrough), while the healthy gemma-3-4b has [{SpecialToken: <bos>}, {Sequence: A}]. So every raw-text path (CLI generate, /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):

    scored length gemma-4-12b nll gemma-3-4b nll (control)
    128 3.47 ~1.5-2.6
    256 5.71 2.83
    512 8.40 3.53
    1024 10.31 3.63
    1536 11.06 3.39

    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.

  3. added
    status:review
    and removed
    status:in-progress
    on Jul 7, 2026
  4. inureyes commented on Jul 7, 2026

    @inureyes
    MemberAuthor

    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.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 ran BOS-less. ensure_bos_post_processor() (in src/tokenizer/mod.rs) now installs the standard <bos> $A TemplateProcessing at load, guarded by an encode probe so correct exports (Gemma 3) are untouched, and by the existing add_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 only add_special=true raw-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):

    scored length mlxcel (GPU) mlx_lm gemma4_text ref (GPU)
    128 3.450 3.434
    256 5.712 5.677
    512 8.403 8.355
    1024 10.308 (matches trend)

    The mlx_lm reference 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):

    • Proportional RoPE is mathematically equivalent to the mlx-vlm / mlx-lm reference ProportionalRoPE (verified by hand and pinned by a new reference-value test); the compiled full-head inf-tail path equals the reference pack/rotate/unpack algorithm.
    • Forcing the proportional-RoPE exponent to normalize by rotated_dims (long-wavelength) instead of head_dim made it WORSE (nll@512 8.40 → 9.35), confirming the shipped ÷head_dim normalization (matching the references) is correct and not the lever.
    • Quantization scheme is not the cause: the uniform-4bit requant shows the same curve (nll@512 8.22 vs mixed-quant 8.40).
    • Scale (1.0), q/k/v-norm, k_eq_v, single global KV head broadcast, embed sqrt(hidden) scale, final softcap, and the masks (create_causal_mask, create_sliding_window_prefill_mask for 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 full head_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.language are all identical here). The checkpoint genuinely uses this architecture (weights carry q_norm/k_norm, k_eq_v, no v_proj on global layers, no relative_k_proj/per_dim_scale). HF transformers has NO gemma4_unified text modeling (its gemma4 is 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

    Data: benchmarks/cuda_gb10_gemma4_quality_686_2026-07-07.csv.

  5. inureyes commented on Jul 7, 2026

    @inureyes
    MemberAuthor

    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.jinja generation prompt is <|turn>model\n<|channel>thought\n<channel|> (CLOSED thought channel, model answers directly) for the non-thinking default, and bare <|turn>model\n for enable_thinking=true. transformers renders the CLOSED scaffold by default and the model answers correctly (e.g. "Paris"). mlxcel instead forced enable_thinking=true for this template family (the has_thinking heuristic, mlx-lm PR #1114) AND appended an OPEN <|channel>thought\n marker via patch_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), and enable_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_text within 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=1 lengthens 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.

  6. inureyes commented on Jul 7, 2026

    @inureyes
    MemberAuthor

    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.

  7. inureyes commented on Jul 7, 2026

    @inureyes
    MemberAuthor

    Resolved. gemma-4 is now usable end to end on CUDA. The three constituent bugs are all fixed and merged:

    1. Tokenizer BOS omission (raw-text paths ran BOS-less) — PR fix(gemma4): render thinking-off closed channel to fix chat pad-collapse (#686) #687.
    2. Chat-template thinking-channel rendering (first token collapsed to a meta-reasoning token then pad) — PR fix(gemma4): render thinking-off closed channel to fix chat pad-collapse (#686) #687.
    3. Decode-path CUDA-graph read-before-write race (decode collapsed to pad after 1-3 tokens, nondeterministically) — PR fix(gemma4): disable CUDA graphs for decode graph-race collapse (#688) #689 (issue bug(gemma4/cuda): decode collapses to <pad> after 1-3 tokens (single-query maskless attention + quantized GEMV); mlx_lm decodes coherently #688), fixed by disabling CUDA graph capture for gemma-4 at load, hoisted to the main thread and covering the pipeline-parallel path.

    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.

  8. self-assigned this
    on Jul 8, 2026
  9. added
    status:done
    and removed
    status:review
    on Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:criticalstatus:donetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions