Skip to content

Implement Gemma 4 E-series MTP centroid embedder (use_ordered_embeddings) - #383

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
GoodOlClint:pr/gemma4-eseries-embedder
Jul 15, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
GoodOlClint:pr/gemma4-eseries-embedder

Conversation

@GoodOlClint

Copy link
Copy Markdown
Contributor

Proposed changes

Completes Gemma 4 MTP speculative decoding for the E-series drafters.

#308 landed Gemma 4 MTP but left Gemma4AssistantMaskedEmbedder.callAsFunction
(the use_ordered_embeddings=true centroid head) as a fatalError stub,
citing the absence of a checkpoint with that flag to verify against. The
published E-series drafters ship exactly that flag:

  • mlx-community/gemma-4-E2B-it-assistant-bf16 — use_ordered_embeddings: true
  • mlx-community/gemma-4-E4B-it-assistant-bf16 — use_ordered_embeddings: true

(the 26B-A4B / 31B drafters ship false and use the tied lm_head matmul, which
is why they worked in #308). So E-series MTP trapped at the stub.

This implements the centroid-routed sparse LM head, ported from mlx-vlm's
masked_embedder.py: score the num_centroids clusters, keep top-K, gather just
those token rows from the tied embedding, score them, and scatter back to full
vocab with unselected positions masked below the selected minimum. mask_value
is kept on-device (no .item() sync in the per-token loop). The 26B/31B path is
untouched.

Everything around the stub (config decode, module construction, weight loading,
sanitize, the forward call site) already existed from #308 — this is just the
missing forward.

Tracks #279. Complements (and is independent of) the num_kv_shared_layers
loader fix needed to load the E-series targets these drafters pair with.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code
  • I have added tests that prove my feature works
    • testMaskedEmbedderSelectedLogitsMatchDense (unit, no checkpoint): with an
      identity token_ordering, selected positions equal the independent dense
      logit, exactly topK*vsc survive, the rest carry mask_value.
    • The env-gated testMTPE{2,4}BPairFailureMode characterization tests in
      MTPIteratorEndToEndDiagnosticTests are converted to assertion-based
      ...ProducesAcceptedDrafts end-to-end tests.
  • Documentation updates — n/a

@GoodOlClint
GoodOlClint marked this pull request as ready for review June 30, 2026 13:42
@mandrael

mandrael commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Tried this against a quantized E-series assistant drafter and hit a shape crash in the new masked-embedder forward — flagging in case it's in scope for this PR.

Repro: target mlx-community/gemma-4-E4B-it-qat-4bit, drafter mlx-community/gemma-4-E4B-it-qat-assistant-mxfp4, loaded via loadWeights(..., quantization:). The first drafter forward throws:

[reshape] Cannot reshape array of size 131072 into shape (1,1,4096,256)

Root cause: the forward is invoked as maskedEmbedding(h, lmHeadWeight: model.embedTokens.weight). For a quantized drafter, model.embedTokens is a QuantizedEmbedding, so .weight is the packed representation ([vocab, hidden/8] = [262144, 32] at 4-bit with hidden 256), not the dequantized [vocab, hidden]. The subsequent lmHeadWeight.take(selectedCanonical.reshaped([-1]), axis: 0).reshaped([b, l, n, hiddenSize]) then gathers rows of width 32 and cannot reshape to hiddenSize = 256 (131072 = 4096 × 32 vs. the expected 4096 × 256). Even with the reshape relaxed, the .min() and the matmul against h would operate on packed data.

Every mlx-community E-series assistant ships quantized variants (mxfp4 / 4/5/6/8-bit) next to bf16, so this path is hit whenever the drafter is loaded quantized. The bf16 drafter works fine (...-qat-assistant-bf16) — its .weight is already [vocab, hidden] — so this is specific to the quantized case.

A fix would need to dequantize the tied embedding before the gather/matmul (or gather the packed rows and dequantize them) when model.embedTokens is quantized. Happy to help test.

For what it's worth: with the bf16 drafter, the E4B target + assistant runs end-to-end and speculative decoding is lossless (byte-identical greedy output), so the forward logic itself looks correct — it's only the quantized-embedding input that breaks.

GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Jul 1, 2026
Gemma4AssistantMaskedEmbedder.callAsFunction took the tied embedding's raw
`.weight`. For a quantized drafter `model.embedTokens` is a QuantizedEmbedding
whose `.weight` is packed `[vocab, H·bits/32]`, so the gather + reshape-to-H
threw ([reshape] Cannot reshape array of size 131072 into shape (1,1,4096,256))
on the first drafter forward. Every mlx-community E-series assistant ships
quantized, so this fired whenever the drafter was loaded quantized; only the
bf16 drafter (whose `.weight` is already dense) worked.

Take the tied embedding *module* and gather rows through its forward, which
returns dense rows for a plain Embedding and dequantized rows for a
QuantizedEmbedding. Reported by @mandrael.

Tests:
- testMaskedEmbedderQuantizedTiedEmbedding: new regression pin — with a
  QuantizedEmbedding tied weight, selected logits match the dense logit over
  the dequantized rows; the old raw-.weight path crashed here.
- Both masked-embedder pins now set token_ordering via update(parameters:)
  instead of assigning the @ParameterInfo array directly (which fatalErrors),
  so they actually execute on Metal.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@GoodOlClint

Copy link
Copy Markdown
Contributor Author

Thanks @mandrael — confirmed and fixed in dc582d6.

Your diagnosis was exactly right. For a quantized drafter model.embedTokens is a QuantizedEmbedding, so .weight is the packed representation ([vocab, hidden·bits/32]), and feeding that raw weight into the gather + reshaped([b, l, n, hiddenSize]) blows up (131072 = 4096×32 packed vs. the expected 4096×256). The bf16 drafter worked only because its .weight is already dense.

Fix: the masked embedder now takes the tied embedding module instead of its raw .weight, and gathers rows through the module's forward:

// before: lmHeadWeight.take(selectedCanonical.reshaped([-1]), axis: 0)
tiedEmbedding(selectedCanonical.reshaped([-1]))

Embedding.callAsFunction returns dense rows for a plain embedding and dequantized rows for a QuantizedEmbedding, so both paths yield [N, hidden] and the subsequent .min()/matmul run on real values — no separate dequantize branch needed.

Test: added testMaskedEmbedderQuantizedTiedEmbedding, a no-network pin that builds a QuantizedEmbedding tied weight and asserts the selected logits match the dense logit computed over the dequantized rows (the old raw-.weight path crashed here). Runs on Metal.

If you're able to re-run against mlx-community/gemma-4-E4B-it-qat-assistant-mxfp4, I'd appreciate the confirmation — but the packed-weight path is now handled. Thanks again for the precise repro.

@mandrael

mandrael commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Bug D (follow-up to the quantized-drafter report above): MTP speculative decoding crashes / goes lossy once the context exceeds the sliding window.

Symptom. With an E-series target + assistant drafter, any context > slidingWindow (512 for E4B) trips the drafter precondition sliding KV length … exceeds slidingWindow in Gemma4Assistant.forwardHidden. With that precondition removed, generation keeps running but the output silently diverges from the no-drafter baseline at temperature 0 — wrong tokens get accepted as "verified".

Root cause. RotatingKVCache.isTrimmable == offset < maxCacheSize. Once a sliding-window cache wraps, the rewind in MTPSpeculativeTokenIterator (trimPromptCache(mainCache, numTokens: rejected)) no-ops and returns 0, so rejected draft tokens stay in the sliding caches and corrupt every subsequent target forward. The drafter precondition just turns that silent corruption into a loud crash. (Python mlx-lm guards the same combination generically: ValueError: Speculative decoding requires a trimmable prompt cache.)

Fix (implemented + verified). Branch: https://github.com/mandrael/mlx-swift-lm/tree/mtp-sliding-window-fix (commit 542d231, based on main + #384 + #383):

  • Gemma4TextLanguageModel.newCache puts sliding layers on a new SlidingWindowMaskKVCache (a KVCacheSimple subclass): full history — always trimmable, temporally ordered — with the window enforced via createCausalMask(n:offset:windowSize:) in a makeMask override that mirrors the RotatingKVCache thresholds. Excluded from KV quantization (parity with RotatingKVCache).
  • The drafter gets an offset-aware createBidirectionalSlidingWindowMask(queryLen:kvLen:windowSize:queryOffset:dtype:) that windows by distance from queryOffset over the temporally ordered shared-KV pool (the existing absolute-position variant masks [0, windowSize), which is wrong once the pool outgrows the window).
  • RoPE offsets are cache-class independent (cache.offset is never capped; the capping in RotatingKVCache lives only in its mask), so target logits are unchanged by the swap.

Results (E4B QAT 4bit target + bf16 assistant drafter, greedy, temp 0):

  • 888-token prompt (previously: crash): MTP output byte-identical to baseline, 2.76× (26.3 → 72.5 tok/s).
  • ~3.9k-token prompt: identical, 2.35×.
  • Plain path (no drafter), old vs. new cache at 888 tokens: byte-identical, same speed.
  • Memory cost of the uncapped sliding KV: +160 MB at ~3.9k tokens for E4B.

Trade-off: sliding KV now grows with sequence length instead of being capped. A capped alternative would need a post-wrap-trimmable ring buffer, but overwritten entries are unrecoverable, so a strict rewind is impossible there by construction.

Happy to open a PR if that's useful.

@GoodOlClint

Copy link
Copy Markdown
Contributor Author

This is a great catch, and thank you for the thorough writeup + verified fix — please do open it as its own PR.

I confirmed the root cause independently: RotatingKVCache.isTrimmable is offset < maxCacheSize, so once a sliding cache wraps past its window it stops being trimmable and trimPromptCache(...) no-ops — rejected draft tokens then linger in the sliding caches and corrupt every subsequent target forward, exactly as you describe. The drafter precondition just surfaces the otherwise-silent divergence. Nice diagnosis.

It's a distinct concern from this PR (masked embedder) and from #384 (KV-shared loader), so I'd suggest opening it as a separate PR to ml-explore/mlx-swift-lm, stacked on #383 + #384 — note the dependency in the description so the maintainers can sequence the merges. That keeps each change independently reviewable and keeps you as the author of your fix.

Two things worth calling out in that PR for the reviewers, since they're the real design points:

  • the memory trade-off (sliding KV now grows with sequence length; you measured ~+160 MB at ~3.9k tokens for E4B) vs. the capped ring-buffer alternative that can't support a strict rewind by construction; and
  • that RoPE offsets are cache-class independent so target logits are unchanged by the swap — your byte-identical greedy results are the evidence for that.

For comparison it may help to reference how Python mlx-lm guards the same combination (the requires a trimmable prompt cache ValueError) — reviewers will likely want to know whether this should be a generic guard in the iterator in addition to the Gemma4 sliding-cache swap.

Happy to review and test against the E4B QAT target + assistant once it's up. Thanks again!

@mandrael

mandrael commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Confirmed — dc582d6 fixes it. Re-ran (isolated, no other MLX process) with mlx-community/gemma-4-E4B-it-qat-assistant-mxfp4 as the drafter (the packed-weight QuantizedEmbedding tied weight), mlx-community/gemma-4-E4B-it-qat-4bit target, greedy, temp 0:

  • 174-token prompt (under the sliding window — isolates the masked-embedder path): no crash on the first drafter forward, where the old raw-.weight path threw [reshape] Cannot reshape array of size 131072 into shape (1,1,4096,256). MTP output byte-identical to the no-drafter baseline. 2.64× (25.6 → 67.5 tok/s).
  • 888-token prompt (over the sliding window, so it also exercises the trimmable-cache rewind): identical, 2.54× (26.0 → 66.2 tok/s).
  • 3038-token prompt (well past the window): identical, 2.52× (25.3 → 63.6 tok/s).

Gathering the selected rows through the tied embedding module dequantizes correctly for the packed drafter. Thanks for the quick turnaround!

GoodOlClint and others added 2 commits July 9, 2026 13:13
Gemma4AssistantMaskedEmbedder.callAsFunction was a fatalError stub; the
E2B/E4B drafters ship use_ordered_embeddings=true and route their logits
through it, so the whole E-series MTP path trapped. Port the centroid-routed
sparse LM head from mlx-vlm masked_embedder.py: score the 2048 clusters, keep
top-K, gather just those token rows from the tied embedding, score them, and
scatter back to full vocab with unselected positions masked below the selected
minimum. mask_value kept on-device (no .item() sync in the per-token loop).

The 26B-A4B/31B drafters ship use_ordered_embeddings=false and are unaffected
(tied lm_head matmul path).

Verification:
- testMaskedEmbedderSelectedLogitsMatchDense: no-network correctness pin —
  with identity token_ordering, selected positions equal the independent dense
  logit, exactly topK*vsc survive, the rest carry mask_value. Runs on Metal.
- The two TEST_E{2,4}B_PAIR-gated integration tests are converted from
  expecting the fatalError trap to asserting healthy speculation
  (proposed>0, accepted>0, no passthrough).

Tracks ml-explore#279.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Gemma4AssistantMaskedEmbedder.callAsFunction took the tied embedding's raw
`.weight`. For a quantized drafter `model.embedTokens` is a QuantizedEmbedding
whose `.weight` is packed `[vocab, H·bits/32]`, so the gather + reshape-to-H
threw ([reshape] Cannot reshape array of size 131072 into shape (1,1,4096,256))
on the first drafter forward. Every mlx-community E-series assistant ships
quantized, so this fired whenever the drafter was loaded quantized; only the
bf16 drafter (whose `.weight` is already dense) worked.

Take the tied embedding *module* and gather rows through its forward, which
returns dense rows for a plain Embedding and dequantized rows for a
QuantizedEmbedding. Reported by @mandrael.

Tests:
- testMaskedEmbedderQuantizedTiedEmbedding: new regression pin — with a
  QuantizedEmbedding tied weight, selected logits match the dense logit over
  the dequantized rows; the old raw-.weight path crashed here.
- Both masked-embedder pins now set token_ordering via update(parameters:)
  instead of assigning the @ParameterInfo array directly (which fatalErrors),
  so they actually execute on Metal.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@GoodOlClint
GoodOlClint force-pushed the pr/gemma4-eseries-embedder branch from f805f47 to 2190dd7 Compare July 9, 2026 18:14

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Changes look good, thank you!

@davidkoski
davidkoski merged commit 2a2bdf4 into ml-explore:main Jul 15, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…ngs) (ml-explore#383)

Implement Gemma 4 E-series MTP centroid embedder, then fix it for quantized drafters

Gemma4AssistantMaskedEmbedder.callAsFunction was a fatalError stub, trapping the whole E-series MTP path (E2B/E4B drafters use `use_ordered_embeddings=true`). Ported the centroid-routed sparse LM head from mlx-vlm's masked_embedder.py: score 2048 clusters, keep top-K, gather those token rows from the tied embedding, score them, and scatter back to full vocab with unselected positions masked below the selected minimum. mask_value stays on-device (no `.item()` sync in the per-token loop). 26B-A4B/31B drafters (`use_ordered_embeddings=false`) are unaffected.

Follow-up fix: the initial version gathered rows from the tied embedding's raw `.weight`, which is packed for a `QuantizedEmbedding` (the format every mlx-community E-series assistant actually ships in), causing a reshape crash on first drafter forward — only unquantized bf16 drafters worked. Fixed by gathering rows through the embedding module's forward instead of its raw weight, so both plain and quantized embeddings return correctly shaped (dequantized) rows.

Tests:
- `testMaskedEmbedderSelectedLogitsMatchDense` — correctness pin against dense logits with identity token_ordering.
- TEST_E{2,4}B_PAIR integration tests updated to assert healthy speculation instead of the old fatalError trap.
- `testMaskedEmbedderQuantizedTiedEmbedding` — regression pin for quantized tied embeddings (crashes on the old raw-`.weight` path).
- Both pins now set `token_ordering` via `update(parameters:)` rather than direct `@ParameterInfo` assignment.

Tracks ml-explore#279. Reported by @mandrael.
@GoodOlClint
GoodOlClint deleted the pr/gemma4-eseries-embedder branch August 1, 2026 16:44
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…t-wavefront

Build Qwen 3.5 prompt chunks layer by layer for tensor-parallel overlap
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.

3 participants