Skip to content

feat: Gemma 4 Unified MTP speculative drafter (gemma4_unified_assistant) with measured speedup #154

Closed

Description

@inureyes

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_ordering tensors); 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/ — Gemma4AssistantDraftModel already implements the [token_embed ‖ target_hidden] input at 2 × 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_ordering top-k→vocab expansion), plus the full Drafter trait (bind, set_shared_kv, draft_block, batched variants, sanitize). The gemma4_unified_assistant checkpoint loads with this same class.
  • MTP round loop: MtpGenerator + the MtpTarget trait (src/lib/mlxcel-core/src/speculative/mtp/, prefill_and_seed → verify_forward → verify_finalize), load_drafter, and the Drafter boxing.
  • Server burst dispatch: src/server/batch/speculative_burst.rs already drives MtpGenerator for LoadedModel::Gemma4 and LoadedModel::Gemma4VLM via Gemma4MtpTargetAdapter / Gemma4VLMtpTargetAdapter (text-only decode; vision rejected).
  • Flags/dispatch: --draft-model, --draft-kind mtp, --num-draft-tokens, --draft-block-size and SpeculativeDispatch::Mtp (src/cli/speculative_args.rs, src/server/speculative_dispatch.rs).
  • The VLM adapter is the exact template: Gemma4VLMtpTargetAdapter::new simply constructs Gemma4MtpTargetAdapter::new_with_block_size(&vlm.text_model, …), and Gemma4VLModel exposes forward_with_speculative_sinks / rollback_speculative_cache by delegating to its inner text_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 to m.insert("gemma4_assistant", DrafterKind::Mtp)), add m.insert("gemma4_unified_assistant", DrafterKind::Mtp). Update the module-doc DRAFTER_KIND_BY_MODEL_TYPE comment.
  • Ensure Gemma4AssistantConfig (src/lib/mlxcel-core/src/drafter/gemma4_assistant/config.rs) parses/normalizes a checkpoint whose model_type is gemma4_unified_assistant (and whose text_config.model_type is gemma4_unified_text) — accept both assistant model_type spellings 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 inner text_model: Gemma4Wrapper, mirroring src/vision/gemma4_vl.rs: forward_with_speculative_sinks, forward_with_speculative_sinks_explicit_cache (batched), rollback_speculative_cache, and the speculative_draft_hidden final-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, add Gemma4UnifiedMtpTargetAdapter<'a> and Gemma4UnifiedMtpBatchedTargetAdapter<'a>, mirroring Gemma4VLMtpTargetAdapter / Gemma4VLMtpBatchedTargetAdapter: each wraps &Gemma4UnifiedModel and constructs the inner Gemma4MtpTargetAdapter / batched adapter over unified.text_model.

Phase 4 — Burst dispatch

  • In src/server/batch/speculative_burst.rs, add LoadedModel::Gemma4Unified(unified) => … arms to the single-stream and batched MTP dispatch (next to the Gemma4 / Gemma4VLM arms) and to the &dyn LanguageModel match. 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/centroid token_ordering is 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_kind on a gemma4_unified_assistant config → DrafterKind::Mtp (mirror the gemma4_assistant test).
  • Config parse: Gemma4AssistantConfig from a gemma4_unified_assistant dict (backbone_hidden_size 3840, text_config.model_type gemma4_unified_text, kv-shared normalization).
  • Adapter: build Gemma4UnifiedMtpTargetAdapter over a tiny synthetic unified target and exercise prefill_and_seed / verify_forward / verify_finalize (mirror gemma4_assistant + VL adapter tests). Structural trait-surface pins ship weights-free in gemma4_mtp_target_tests.rs; the full forward-driving greedy-parity round-trip ships #[ignore]-gated in tests/speculative_parity.rs (greedy_parity_mtp_gemma4_unified_12b).

Phase 7 — Benchmark wiring

  • Activate the deferred BenchKind::Mtp arm in src/bin/speculative_bench.rs for the unified pair: construct Gemma4UnifiedMtpTargetAdapter + MtpGenerator and record tok_per_sec + speedup_vs_baseline (+ acceptance length). Add a REACHABLE_PAIRINGS entry for gemma-4-12b-it-4bit (baseline) and the same target + gemma-4-12B-it-assistant-4bit drafter (MTP).

Non-goals (out of scope)

  • Wiring the offline mlxcel generate --draft-kind mtp round 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-draft

Metrics 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_assistant drafter loads and runs as an MTP drafter against a Gemma4Unified target through the server path and the benchmark.
  • temperature 0 MTP 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 / Gemma4VLM MTP 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

  1. added
    type:enhancement
    priority:high
    area:models
    on Jun 4, 2026
  2. self-assigned this
    on Jun 4, 2026
  3. added
    status:ready
    status:in-progress
    status:review
    status:done
    and removed
    status:ready
    status:in-progress
    status:review
    on Jun 4, 2026
  4. added this to the 0.1 milestone on Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:highstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions