Repository navigation
Description
Follow-up to #151 (its deferred §9 / Phase 7). Adds MTP speculative decoding for the Gemma 4 Unified decode target using the gemma4_unified_assistant drafter, and — required — measures the real-model decode speedup end-to-end.
Summary
Wire the Gemma 4 Unified target (ModelType::Gemma4Unified / LoadedModel::Gemma4Unified) into the existing MTP speculative-decoding stack so it can be accelerated by a gemma4_unified_assistant drafter, then quantify the improvement on real models.
The MTP drafter model and the MTP round loop already exist in the runtime and are reused as-is. The work here is almost entirely target-side adapter plumbing that mirrors the Gemma 4 VLM MTP path, plus drafter-kind registration, a compatibility check, tests, and a reproducible benchmark.
Reference models (already in the local store)
- Target:
mlx-community/gemma-4-12b-it-4bit(model_type: gemma4_unified, text hidden size 3840) - Drafter:
mlx-community/gemma-4-12B-it-assistant-4bit
Drafter checkpoint shape (Gemma4UnifiedAssistantForCausalLM, model_type: gemma4_unified_assistant):
backbone_hidden_size: 3840(consumes the target's last backbone hidden state)- small text stack:
hidden_size 1024,num_hidden_layers 4,num_kv_shared_layers 4,head_dim 256,global_head_dim 512, layer types[sliding ×3, full],sliding_window 1024 - centroid LM head:
num_centroids 2048,centroid_intermediate_top_k 32,tie_word_embeddings true,use_ordered_embeddings false - weight prefixes:
model.embed_tokens,model.layers.{0..3},model.norm,pre_projection,post_projection(+ centroid/token_orderingtensors);eos_token_id 1,suppress_tokens [eoi, eoa]
What already works (reuse, do not rebuild)
- MTP drafter model:
src/lib/mlxcel-core/src/drafter/gemma4_assistant/—Gemma4AssistantDraftModelalready implements the[token_embed ‖ target_hidden]input at2 × backbone_hidden_size,pre_projection/post_projection, the 4-layer stack with shared K/V cross-attention, and the centroid LM head (MaskedEmbedder,num_centroids/centroid_intermediate_top_k,token_orderingtop-k→vocab expansion), plus the fullDraftertrait (bind,set_shared_kv,draft_block, batched variants,sanitize). Thegemma4_unified_assistantcheckpoint loads with this same class. - MTP round loop:
MtpGenerator+ theMtpTargettrait (src/lib/mlxcel-core/src/speculative/mtp/,prefill_and_seed→verify_forward→verify_finalize),load_drafter, and theDrafterboxing. - Server burst dispatch:
src/server/batch/speculative_burst.rsalready drivesMtpGeneratorforLoadedModel::Gemma4andLoadedModel::Gemma4VLMviaGemma4MtpTargetAdapter/Gemma4VLMtpTargetAdapter(text-only decode; vision rejected). - Flags/dispatch:
--draft-model,--draft-kind mtp,--num-draft-tokens,--draft-block-sizeandSpeculativeDispatch::Mtp(src/cli/speculative_args.rs,src/server/speculative_dispatch.rs). - The VLM adapter is the exact template:
Gemma4VLMtpTargetAdapter::newsimply constructsGemma4MtpTargetAdapter::new_with_block_size(&vlm.text_model, …), andGemma4VLModelexposesforward_with_speculative_sinks/rollback_speculative_cacheby delegating to its innertext_model(src/vision/gemma4_vl.rs).
Gap analysis
| Aspect | Status | Action |
|---|---|---|
Drafter model (Gemma4AssistantDraftModel, centroid head) |
✅ reusable | none |
MTP loop (MtpGenerator / MtpTarget), load_drafter, flags, SpeculativeDispatch::Mtp |
✅ reusable | none |
Drafter-kind registry knows gemma4_unified_assistant |
✅ done | add map entry |
Gemma4AssistantConfig accepts the gemma4_unified_assistant model_type |
✅ done | accepts arbitrary model_type strings |
Gemma4UnifiedModel exposes speculative hooks |
✅ done | delegate to text_model |
Gemma4UnifiedMtpTargetAdapter (+ batched) |
✅ done | mirror VL adapters |
Burst dispatch arm for LoadedModel::Gemma4Unified |
✅ done | add arms |
Target↔drafter compatibility check (backbone_hidden_size 3840, vocab) |
✅ done | Drafter::validate_target_compat |
| Benchmark measures the unified MTP pair | ✅ done | BenchKind::Mtp activated for this pair |
Implementation plan
Phase 1 — Drafter-kind registration & config acceptance
- In
drafter_kind_by_model_type()(src/lib/mlxcel-core/src/drafter/mod.rs, next tom.insert("gemma4_assistant", DrafterKind::Mtp)), addm.insert("gemma4_unified_assistant", DrafterKind::Mtp). Update the module-docDRAFTER_KIND_BY_MODEL_TYPEcomment. - Ensure
Gemma4AssistantConfig(src/lib/mlxcel-core/src/drafter/gemma4_assistant/config.rs) parses/normalizes a checkpoint whosemodel_typeisgemma4_unified_assistant(and whosetext_config.model_typeisgemma4_unified_text) — accept both assistantmodel_typespellings rather than hard-rejecting.
Phase 2 — Unified target speculative hooks
- On
Gemma4UnifiedModel(src/vision/gemma4_unified.rs), add the speculative hooks by delegating to the innertext_model: Gemma4Wrapper, mirroringsrc/vision/gemma4_vl.rs:forward_with_speculative_sinks,forward_with_speculative_sinks_explicit_cache(batched),rollback_speculative_cache, and thespeculative_draft_hiddenfinal-norm helper. During text decode no multimodal merge occurs, so these delegate straight through; the (optionally multimodal) prefill still flows through the unified forward that seeds the cache + first hidden.
Phase 3 — Unified MTP target adapters
- In
src/models/gemma4_mtp_target.rs, addGemma4UnifiedMtpTargetAdapter<'a>andGemma4UnifiedMtpBatchedTargetAdapter<'a>, mirroringGemma4VLMtpTargetAdapter/Gemma4VLMtpBatchedTargetAdapter: each wraps&Gemma4UnifiedModeland constructs the innerGemma4MtpTargetAdapter/ batched adapter overunified.text_model.
Phase 4 — Burst dispatch
- In
src/server/batch/speculative_burst.rs, addLoadedModel::Gemma4Unified(unified) => …arms to the single-stream and batched MTP dispatch (next to theGemma4/Gemma4VLMarms) and to the&dyn LanguageModelmatch. Update the module-doc target list.
Phase 5 — Compatibility guard
- Before binding, validate the pairing: drafter
backbone_hidden_size(3840) equals the target's text hidden size, and the vocab/centroidtoken_orderingis consistent with the target vocab. Fail with a clear, actionable error on mismatch (mirror the existing MTP compatibility-rejection behavior). Add a unit test for the reject path.
Phase 6 — Tests
- Kind resolution:
resolve_drafter_kindon agemma4_unified_assistantconfig →DrafterKind::Mtp(mirror thegemma4_assistanttest). - Config parse:
Gemma4AssistantConfigfrom agemma4_unified_assistantdict (backbone_hidden_size 3840,text_config.model_type gemma4_unified_text, kv-shared normalization). - Adapter: build
Gemma4UnifiedMtpTargetAdapterover a tiny synthetic unified target and exerciseprefill_and_seed/verify_forward/verify_finalize(mirrorgemma4_assistant+ VL adapter tests). Structural trait-surface pins ship weights-free ingemma4_mtp_target_tests.rs; the full forward-driving greedy-parity round-trip ships#[ignore]-gated intests/speculative_parity.rs(greedy_parity_mtp_gemma4_unified_12b).
Phase 7 — Benchmark wiring
- Activate the deferred
BenchKind::Mtparm insrc/bin/speculative_bench.rsfor the unified pair: constructGemma4UnifiedMtpTargetAdapter+MtpGeneratorand recordtok_per_sec+speedup_vs_baseline(+ acceptance length). Add aREACHABLE_PAIRINGSentry forgemma-4-12b-it-4bit(baseline) and the same target +gemma-4-12B-it-assistant-4bitdrafter (MTP).
Non-goals (out of scope)
- Wiring the offline
mlxcel generate --draft-kind mtpround loop (today it returns a deferred-path error for all targets — a separate, target-agnostic item). Measurement here uses the server path and the benchmark, both of which run the MTP loop. - Multimodal (image/audio) speculative decode: the drafter accelerates text decode; prompts may still be multimodal, but draft/verify operate on text tokens.
Measurement — required, on real models
This issue is not complete without a measured speedup on mlx-community/gemma-4-12b-it-4bit (target) + mlx-community/gemma-4-12B-it-assistant-4bit (drafter). Capture the numbers in the PR body.
A. Reproducible benchmark (primary). Using the extended speculative_bench:
# baseline (no drafter)
./target/release/speculative_bench --target <store>/mlx-community/gemma-4-12b-it-4bit \
--kind none --max-tokens 256 --prompt "<fixed prompt>"
# MTP speculative
./target/release/speculative_bench --target <store>/mlx-community/gemma-4-12b-it-4bit \
--draft <store>/mlx-community/gemma-4-12B-it-assistant-4bit \
--kind mtp --draft-block-size 4 --max-tokens 256 --prompt "<fixed prompt>"B. Production path (cross-check). The server burst loop:
mlxcel serve -m mlx-community/gemma-4-12b-it-4bit \
--model-draft mlx-community/gemma-4-12B-it-assistant-4bit --draft-kind mtp --draft-block-size 4
# time a fixed-length /v1/chat/completions (temperature 0) vs the same server with no --model-draftMetrics to record (table in the PR): for the baseline and for MTP at --draft-block-size ∈ {3, 4, 5}, on ≥2 prompts (a short Q&A and a longer generation):
- baseline decode tok/s
- MTP decode tok/s
- speedup = MTP ÷ baseline (the improvement margin)
- mean acceptance length (accepted draft tokens per verification step) / acceptance rate
Correctness gate (separate from speed): at temperature 0, MTP-accelerated output must be token-identical to the baseline target output (MTP speculative decoding is exactness-preserving). Verify token-for-token for the measured prompts.
Acceptance criteria
- A
gemma4_unified_assistantdrafter loads and runs as an MTP drafter against aGemma4Unifiedtarget through the server path and the benchmark. temperature 0MTP output is token-identical to the non-speculative target output on the measured prompts.- A measured decode speedup > 1.0× is demonstrated and the actual tok/s, speedup ratio, and acceptance length are recorded in the PR (block-size sweep + ≥2 prompts). If no speedup appears, the acceptance rate / target-drafter alignment must be investigated and explained before closing.
- The compatibility guard rejects a mismatched target↔drafter pair with a clear error.
- New unit tests (kind resolution, config parse, adapter round-trip, compat reject) pass; existing
gemma4/Gemma4VLMMTP paths are unaffected.
Key touchpoints
| Area | File | Note |
|---|---|---|
| Drafter-kind map | src/lib/mlxcel-core/src/drafter/mod.rs |
add gemma4_unified_assistant → Mtp |
| Drafter model (reuse) | src/lib/mlxcel-core/src/drafter/gemma4_assistant/ |
Gemma4AssistantDraftModel, Gemma4AssistantConfig, centroid MaskedEmbedder |
| Unified target hooks | src/vision/gemma4_unified.rs |
delegate to text_model (mirror src/vision/gemma4_vl.rs) |
| MTP target adapters | src/models/gemma4_mtp_target.rs |
new Gemma4UnifiedMtpTargetAdapter (+ batched), mirror VL adapters |
| Burst dispatch | src/server/batch/speculative_burst.rs |
add LoadedModel::Gemma4Unified arms |
| Round loop / target trait (reuse) | src/lib/mlxcel-core/src/speculative/mtp/ |
MtpGenerator, MtpTarget |
| Flags/dispatch (reuse) | src/cli/speculative_args.rs, src/server/speculative_dispatch.rs |
--draft-kind mtp, --draft-block-size |
| Benchmark | src/bin/speculative_bench.rs |
activate BenchKind::Mtp; add unified REACHABLE_PAIRINGS |
Activity
feat: Gemma 4 Unified MTP speculative drafter (gemma4_unified_assista…
feat: Gemma 4 Unified MTP speculative drafter (gemma4_unified_assista…