Skip to content

fix: Gemma 4 coherence — full model, KV sharing, real tokenizer - #44

Merged
ekryski merged 1 commit into
ekryski:alphafrom
TheTom:pr/alpha-gemma4-coherence-fix
Apr 16, 2026
Merged

ekryski merged 1 commit into
ekryski:alphafrom
TheTom:pr/alpha-gemma4-coherence-fix

Conversation

@TheTom

@TheTom TheTom commented Apr 16, 2026

Copy link
Copy Markdown

Summary

Restores end-to-end Gemma 4 correctness and 2.5x prefill speedup on alpha. Fixes three separate bugs that cost us decode coherence after the alpha cleanup.

Root causes

  1. Stripped Gemma4Text.swift — the alpha port dropped ~400 lines of prefill logic (chunked prefill, asyncEval CPU-GPU overlap, prefillMode that skips shared layers during prefill, KV sharing via lastReturnedKeys/lastReturnedValues). Replaced with the full working port from moe.

  2. Pad-token bug — Evaluate.swift used asyncEval for the first decode token, which on Gemma 4 kicks off the second forward pass before prefill's KV writes commit. Output becomes I <pad> <pad> <pad>…. Fix: sync-eval first decode token.

  3. Fake tokenizer — the Benchmarks target had a SimpleJSONTokenizer doing naive whitespace splitting instead of real BPE. Every input was wrong token IDs, every decode was garbage. Fix: use swift-transformers' AutoTokenizer via a TokenizerBridge wrapper.

Files changed

  • Libraries/MLXLLM/Models/Gemma4.swift — restore full port (renamed from Gemma4Text.swift). Inlines GemmaPrefillBridge with @unchecked Sendable.
  • Libraries/MLXLMCommon/KVCache.swift — add lastReturnedKeys/lastReturnedValues to KVCacheSimple + RotatingKVCache (needed for Gemma 4 KV sharing).
  • Libraries/MLXLMCommon/Evaluate.swift — sync-eval first decode token.
  • Package.swift — add swift-transformers 1.3.0 dep.
  • Tests/Benchmarks/InferenceBenchmark.swift — replace SimpleJSONTokenizer with TokenizerBridge around AutoTokenizer.

Gemma 4 E2B perf (M5 Max, NAX enabled)

Ctx Prefill Decode
128 5,583 199.6
256 11,715 198.1
512 17,376 194.5
1024 20,004 195.7
2048 17,193 193.9
4096 13,773 186.5
8192 13,353 179.1

Peak 20K tok/s matches our original April 11 target. Coherent output verified at 128, 1024, and 8192 contexts.

🤖 Generated with Claude Code

Restores end-to-end Gemma 4 correctness + 2.5x prefill speedup on alpha.

Root causes (three separate bugs):
1. Gemma4Text.swift was a stripped-down port missing ~400 lines of prefill
   logic (chunked prefill, asyncEval CPU-GPU overlap, prefillMode that skips
   shared layers during prefill, KV sharing via lastReturnedKeys/Values).
2. Evaluate.swift used asyncEval for first decode token, triggering Gemma 4
   pad-token bug (second forward pass starts before prefill KV writes commit).
3. InferenceBenchmark.swift used a naive SimpleJSONTokenizer (whitespace split)
   instead of real BPE — all token IDs were garbage, decode output was random.

Changes:
- Libraries/MLXLLM/Models/Gemma4.swift: replace Gemma4Text.swift with full
  working port (uses SwitchGLU instead of FusedGateUpSwitchGLU which alpha
  doesn't have). Inlines GemmaPrefillBridge with @unchecked Sendable.
- Libraries/MLXLMCommon/KVCache.swift: add lastReturnedKeys/Values to
  KVCacheSimple and RotatingKVCache (set in update()) — needed for Gemma 4
  KV sharing to avoid redundant peek() slice ops.
- Libraries/MLXLMCommon/Evaluate.swift: sync-eval first decode token
  (eval(y.tokens) instead of asyncEval) — fixes Gemma 4 pad-token bug.
- Package.swift: add swift-transformers 1.3.0 dep for real BPE tokenization.
- Tests/Benchmarks/InferenceBenchmark.swift: replace SimpleJSONTokenizer
  with TokenizerBridge wrapping swift-transformers' AutoTokenizer. Qualify
  ToolSpec/Message to MLXLMCommon to resolve namespace collision.

Gemma 4 E2B performance (M5 Max, NAX enabled):
  128 ctx:  5,583 prefill / 199.6 decode
  256 ctx: 11,715 / 198.1
  512 ctx: 17,376 / 194.5
 1024 ctx: 20,004 / 195.7   <- peak prefill (2.5x baseline)
 2048 ctx: 17,193 / 193.9
 4096 ctx: 13,773 / 186.5
 8192 ctx: 13,353 / 179.1

Coherent output verified at 128, 1024, and 8192 contexts.

Co-Authored-By: tturney1@gmail.com
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@TheTom

TheTom commented Apr 16, 2026

Copy link
Copy Markdown
Author

Full benchmark results (M5 Max, NAX enabled)

Speed — Gemma 4 E2B 4bit, summarization

Ctx Prefill (t/s) Decode (t/s)
128 5,583 199.6
256 11,715 198.1
512 17,376 194.5
1024 20,004 195.7
2048 17,193 193.9
4096 13,773 186.5
8192 13,353 179.1

Peak prefill at 1024 context: 20,004 t/s — matches the April 11 target from the prefill investigation work. Decode holds ~195 t/s through 2K and degrades gently at longer contexts (expected, more attention work per token).

Coherency — verified at 3 context sizes

128 ctx (simple Q&A):

Hello! I am a helpful assistant...

1024 ctx (summarization):

The provided text is an excerpt from The Great Gatsby by F. Scott Fitzgerald. It contains several distinct sections, including a piece of poetry...

8192 ctx (summarization):

This is an excerpt from Nick Carraway's narration in The Great Gatsby by F. Scott Fitzgerald.

All three produce accurate, coherent output with correct author/narrator attribution. No pad-token corruption.

Before this PR (alpha broken)

[BENCH] Output: I <pad> <pad> <pad> <pad> <pad> <pad>...

Every Gemma 4 decode was pad-token corrupted due to asyncEval race + naive SimpleJSONTokenizer. This PR fixes both.

TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Apr 16, 2026
Followup to PR ekryski#44. Two independent fixes for models that were still
broken after the coherence work landed.

## Gemma 4 26B A4B MoE

Root cause: mixed-precision quantization (shared MLP + router are 8-bit,
rest is 4-bit) encoded as per-layer overrides keyed under the VLM-style
path `language_model.model.layers.N.mlp.gate_proj`. The text-only
`Gemma4TextModel` strips `language_model.` from weights but not from the
per-layer quantization dict, so `quantize()` missed the overrides and
built the shared MLP Linears with the default 4-bit group size, producing
shape mismatches like:

    mismatchedSize(down_proj.weight
        expected [2816, 264]
        actual   [2816, 528])

Fix:
- Add `FusedGateUpSwitchGLU` to MLXLMCommon/SwitchLayers.swift — 26B MoE
  ships a single fused `gate_up_proj` weight `[E, 2*H, D]` instead of
  separate `gate_proj`/`up_proj`, matching how the sanitize step already
  concatenates the two into `gate_up_proj`.
- Swap `Gemma4TransformerBlock.experts` from `SwitchGLU` to
  `FusedGateUpSwitchGLU` so the model's Module tree matches the fused
  weight layout.
- Introduce a `sanitize(perLayerQuantization:)` hook on `LanguageModel`
  (default: identity) and wire it through `Load.swift`. Override it in
  `Gemma4TextModel` to strip the `language_model.` prefix from per-layer
  keys, restoring the mixed-precision overrides for the shared MLP and
  router when the text model is loaded stand-alone.

Verified: `mlx-community/gemma-4-26b-a4b-4bit` now loads and generates
coherent output (2+2=4, capital-of-France=Paris), 220 tok/s prefill,
56 tok/s decode at 128 ctx on M5 Max.

## Qwen3.5 GDN decode

Port the fused GatedDeltaNet recurrence back from the moe branch: the
alpha cleanup dropped the `MLXFast.gatedDeltaStepFused` dispatch and
went back to pure ops, which spends ~4–6 separate dispatches per GDN
layer at decode. The fused kernel absorbs rmsNorm(q), rmsNorm(k),
sigmoid(b)→beta, and g = exp(-exp(aLog)*softplus(a+dtBias)) into a
single Metal dispatch and is correct at T=1.

- Add `fusedGatedDeltaUpdate(qRaw, kRaw, v, a, b, aLog, dtBias, …)` in
  GatedDelta.swift that calls `MLXFast.gatedDeltaStepFused`.
- In `Qwen35.swift`, use the fused path at T=1 decode and keep the
  ops-based prefill (pre-computed norms) for T>1, matching the moe
  branch's split. Fused at prefill regresses speed because of register
  pressure; the framework non-fused kernel has a correctness bug at
  T>1, so ops remain the safe prefill path.

Verified: `Qwen3.5-2B-4bit` and `Qwen3.5-9B-4bit` both generate
coherent text; 2B decode 283 tok/s, 9B decode 96 tok/s.

## Regression check

Gemma 4 E2B (uniform 4-bit, no per-layer overrides, not GDN) still
loads and generates cleanly — 1077 tok/s prefill, 202 tok/s decode —
confirming the prefix-strip is a no-op for models without nested
quantization dicts and the fused kernel path is gated by T=1.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Apr 16, 2026
First reference baseline for the inference benchmark suite in
Tests/Benchmarks/InferenceBenchmark.swift. Covers 14 models × 8 context
points (128 → 32k) × swift + bridge paths, plus 8k coherency samples.

Captured on alpha with PR ekryski#44 (Gemma 4 coherence) and PR ekryski#45 (Gemma 4 26B
MoE + Qwen3.5 GDN fused decode) applied, NAX enabled. Method is
`MLX_BENCH_METHOD=summarization`.

Also adds a baselines/README.md describing file naming and methodology
so future baseline runs (M3 Ultra, M5 Pro, etc.) drop in consistently.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: tturney@psyguard.ai
@@ -230,26 +398,6 @@ class Gemma4ProportionalRoPE: Module, OffsetLayer {
}
}

// MARK: - Compiled fused ops

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we be deleting these? Aren't these needed?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not deleted, just moved. GitHub shows the rename from Gemma4Text.swift to Gemma4.swift as all-delete on the left for any line where the new location shifted, which is what you're seeing here.

All three compiled ops still exist in the new file and are still called from the same sites:

  • compiledLogitSoftcap: defined at L653, used at L1204 for final_logit_softcapping
  • compiledGeglu: defined at L659, used at L697 inside Gemma4SharedMLP.callAsFunction
  • compiledGeluMul: defined at L676, used at L873 for PLE gate activation

I also added compiledNormResidual at L670 but left it unused with a note that compile() can't fuse across fast::RMSNorm (opaque custom primitive), so we use MLXFast.rmsNormResidual() instead. Happy to rip that one out if you'd rather not carry dead code.

git diff -M --stat confirms the rename: 498 insertions / 318 deletions inside the renamed file, not a wholesale rewrite.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No that's fine.

@ekryski
ekryski merged commit 3ffdda0 into ekryski:alpha Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants