Repository navigation
Implement Gemma 4 E-series MTP centroid embedder (use_ordered_embeddings) - #383
Conversation
|
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 Root cause: the forward is invoked as 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 ( A fix would need to dequantize the tied embedding before the gather/matmul (or gather the packed rows and dequantize them) when 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. |
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>
|
Thanks @mandrael — confirmed and fixed in dc582d6. Your diagnosis was exactly right. For a quantized drafter Fix: the masked embedder now takes the tied embedding module instead of its raw // before: lmHeadWeight.take(selectedCanonical.reshaped([-1]), axis: 0)
tiedEmbedding(selectedCanonical.reshaped([-1]))
Test: added If you're able to re-run against |
|
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 > Root cause. Fix (implemented + verified). Branch: https://github.com/mandrael/mlx-swift-lm/tree/mtp-sliding-window-fix (commit
Results (E4B QAT 4bit target + bf16 assistant drafter, greedy, temp 0):
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. |
|
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: 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 Two things worth calling out in that PR for the reviewers, since they're the real design points:
For comparison it may help to reference how Python Happy to review and test against the E4B QAT target + assistant once it's up. Thanks again! |
|
Confirmed — dc582d6 fixes it. Re-ran (isolated, no other MLX process) with
Gathering the selected rows through the tied embedding module dequantizes correctly for the packed drafter. Thanks for the quick turnaround! |
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>
f805f47 to
2190dd7
Compare
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
…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.
…t-wavefront Build Qwen 3.5 prompt chunks layer by layer for tensor-parallel overlap
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=truecentroid head) as afatalErrorstub,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: truemlx-community/gemma-4-E4B-it-assistant-bf16—use_ordered_embeddings: true(the 26B-A4B / 31B drafters ship
falseand use the tiedlm_headmatmul, whichis 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 thenum_centroidsclusters, keep top-K, gather justthose token rows from the tied embedding, score them, and scatter back to full
vocab with unselected positions masked below the selected minimum.
mask_valueis kept on-device (no
.item()sync in the per-token loop). The 26B/31B path isuntouched.
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_layersloader fix needed to load the E-series targets these drafters pair with.
Checklist
pre-commit run --all-filesto format my codetestMaskedEmbedderSelectedLogitsMatchDense(unit, no checkpoint): with anidentity
token_ordering, selected positions equal the independent denselogit, exactly
topK*vscsurvive, the rest carrymask_value.testMTPE{2,4}BPairFailureModecharacterization tests inMTPIteratorEndToEndDiagnosticTestsare converted to assertion-based...ProducesAcceptedDraftsend-to-end tests.