Skip to content

fix: Gemma 4 26B MoE mixed-precision + Qwen3.5 GDN fused decode - #45

Merged
ekryski merged 2 commits into
ekryski:alphafrom
TheTom:pr/alpha-26b-moe-qwen35-gdn
Apr 16, 2026
Merged

ekryski merged 2 commits into
ekryski:alphafrom
TheTom:pr/alpha-26b-moe-qwen35-gdn

Conversation

@TheTom

@TheTom TheTom commented Apr 16, 2026

Copy link
Copy Markdown

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-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 Linear modules with the default 4-bit group size. Loading the 4bit safetensors then failed:

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.
  • Introduce an optional sanitize(perLayerQuantization:) hook on LanguageModel (default: identity) and call it from Load.swift. Override it in Gemma4TextModel to strip the language_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.gatedDeltaStepFused dispatch, 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.

  • Add fusedGatedDeltaUpdate(qRaw, kRaw, v, a, b, aLog, dtBias, …) in GatedDelta.swift that dispatches 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. 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.
  • Regression check: 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

  • Build MLXLLM cleanly (release)
  • Load + generate Gemma 4 26B A4B 4bit
  • Load + generate Qwen3.5 2B 4bit
  • Load + generate Qwen3.5 9B 4bit
  • Gemma 4 E2B 4bit still clean (no regression on uniform-quant non-GDN models)
  • swift test --filter MLXLMTests ResolveTests / ToolTests green

Stacked 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

TheTom and others added 2 commits April 16, 2026 00:50
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
@ekryski
ekryski merged commit a5352fa 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