Repository navigation
fix: Gemma 4 26B MoE mixed-precision + Qwen3.5 GDN fused decode - #45
Merged
Merged
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>
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
3 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Followup to #44. Two independent fixes for models that were still broken on alpha 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) is encoded as per-layer overrides keyed under the VLM-style path
language_model.model.layers.N.mlp.gate_proj. The text-onlyGemma4TextModelstripslanguage_model.from weights but not from the per-layer quantization dict, soquantize()missed the overrides and built the shared MLPLinearmodules with the default 4-bit group size. Loading the4bitsafetensors then failed:Fix:
FusedGateUpSwitchGLUtoMLXLMCommon/SwitchLayers.swift— 26B MoE ships a single fusedgate_up_projweight[E, 2*H, D]instead of separategate_proj/up_proj, matching how the sanitize step already concatenates the two intogate_up_proj.Gemma4TransformerBlock.expertsfromSwitchGLUtoFusedGateUpSwitchGLU.sanitize(perLayerQuantization:)hook onLanguageModel(default: identity) and call it fromLoad.swift. Override it inGemma4TextModelto strip thelanguage_model.prefix from per-layer keys so mixed-precision overrides apply when the text model is loaded stand-alone.Qwen3.5 GDN decode
Port the fused GatedDeltaNet recurrence back from the moe branch: the alpha cleanup dropped the
MLXFast.gatedDeltaStepFuseddispatch, so every GDN decode step spent ~4–6 separate dispatches on rmsNorm / g / beta / step. 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.fusedGatedDeltaUpdate(qRaw, kRaw, v, a, b, aLog, dtBias, …)inGatedDelta.swiftthat dispatchesMLXFast.gatedDeltaStepFused.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. The fused kernel regresses prefill speed due to register pressure, and the framework non-fused kernel has a correctness bug at T>1, so ops remain the safe prefill path.Verification
mlx-community/gemma-4-26b-a4b-4bit— loads, coherent output (2+2=4, capital-of-France=Paris), 220 tok/s prefill / 56 tok/s decode @ 128 ctx (M5 Max).mlx-community/Qwen3.5-2B-4bit— 484 tok/s prefill / 283 tok/s decode, coherent.mlx-community/Qwen3.5-9B-4bit— 185 tok/s prefill / 96 tok/s decode, coherent.mlx-community/gemma-4-e2b-it-4bit(uniform 4-bit, no per-layer dict, not GDN) still at 1077 tok/s prefill / 202 tok/s decode, coherent.Test plan
MLXLLMcleanly (release)swift test --filter MLXLMTestsResolveTests / ToolTests greenStacked on #44 — merge that first. Nothing here depends on #44's Gemma 4 coherence commit structurally, but they touch the same files so a clean rebase may be needed after #44 lands.
🤖 Generated with Claude Code