Repository navigation
fix: Gemma 4 coherence — full model, KV sharing, real tokenizer - #44
Conversation
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>
Full benchmark results (M5 Max, NAX enabled)Speed — Gemma 4 E2B 4bit, summarization
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 sizes128 ctx (simple Q&A):
1024 ctx (summarization):
8192 ctx (summarization):
All three produce accurate, coherent output with correct author/narrator attribution. No pad-token corruption. Before this PR (alpha broken)
Every Gemma 4 decode was pad-token corrupted due to asyncEval race + naive SimpleJSONTokenizer. This PR fixes both. |
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
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 | |||
There was a problem hiding this comment.
Should we be deleting these? Aren't these needed?
There was a problem hiding this comment.
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_softcappingcompiledGeglu: defined at L659, used at L697 insideGemma4SharedMLP.callAsFunctioncompiledGeluMul: 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.
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
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.Pad-token bug —
Evaluate.swiftusedasyncEvalfor the first decode token, which on Gemma 4 kicks off the second forward pass before prefill's KV writes commit. Output becomesI <pad> <pad> <pad>…. Fix: sync-eval first decode token.Fake tokenizer — the Benchmarks target had a
SimpleJSONTokenizerdoing naive whitespace splitting instead of real BPE. Every input was wrong token IDs, every decode was garbage. Fix: useswift-transformers'AutoTokenizervia aTokenizerBridgewrapper.Files changed
Libraries/MLXLLM/Models/Gemma4.swift— restore full port (renamed fromGemma4Text.swift). InlinesGemmaPrefillBridgewith@unchecked Sendable.Libraries/MLXLMCommon/KVCache.swift— addlastReturnedKeys/lastReturnedValuestoKVCacheSimple+RotatingKVCache(needed for Gemma 4 KV sharing).Libraries/MLXLMCommon/Evaluate.swift— sync-eval first decode token.Package.swift— addswift-transformers1.3.0 dep.Tests/Benchmarks/InferenceBenchmark.swift— replaceSimpleJSONTokenizerwithTokenizerBridgearoundAutoTokenizer.Gemma 4 E2B perf (M5 Max, NAX enabled)
Peak 20K tok/s matches our original April 11 target. Coherent output verified at 128, 1024, and 8192 contexts.
🤖 Generated with Claude Code