Skip to content

feat: Gemma 4 Unified MTP speculative drafter (gemma4_unified_assistant) - #157

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-154-gemma4-unified-mtp-drafter
Jun 4, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-154-gemma4-unified-mtp-drafter

Conversation

@inureyes

@inureyes inureyes commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Wires the Gemma 4 Unified decode target (LoadedModel::Gemma4Unified) into the existing MTP speculative-decoding stack so it can be accelerated by a gemma4_unified_assistant drafter, mirroring the Gemma 4 VLM MTP path exactly. The MTP drafter model and round loop are reused unchanged; this PR is target-side adapter plumbing, drafter-kind registration, a target↔drafter compatibility guard, tests, and a reproducible benchmark. Follow-up to #151 (its deferred §9 / Phase 7).

What changed (by phase)

P1 — Kind registry + config acceptance (src/lib/mlxcel-core/src/drafter/mod.rs, .../gemma4_assistant/config.rs)

  • drafter_kind_by_model_type() now maps both gemma4_assistant and gemma4_unified_assistant to DrafterKind::Mtp; module-doc DRAFTER_KIND_BY_MODEL_TYPE comments list both spellings.
  • Gemma4AssistantConfig already accepts arbitrary model_type strings, so the gemma4_unified_assistant / gemma4_unified_text spellings parse and normalize unchanged (added a parse test).

P2 — Unified target speculative hooks (src/vision/gemma4_unified.rs)

  • Gemma4UnifiedModel gains forward_with_speculative_sinks, forward_with_speculative_sinks_explicit_cache (batched), rollback_speculative_cache, and speculative_draft_hidden — pure pass-throughs to the inner text_model: Gemma4Wrapper, identical to src/vision/gemma4_vl.rs.

P3 — Unified MTP target adapters (src/models/gemma4_mtp_target.rs)

  • New Gemma4UnifiedMtpTargetAdapter<'a> and Gemma4UnifiedMtpBatchedTargetAdapter<'a>, each wrapping &Gemma4UnifiedModel and building the inner Gemma4MtpTargetAdapter / batched adapter over unified.text_model, mirroring the VL adapters.

P4 — Burst dispatch (src/server/batch/speculative_burst.rs)

  • LoadedModel::Gemma4Unified arms added to the single-stream (run_mtp_burst) and batched (run_mtp_burst_batched) MTP dispatch — both the &dyn LanguageModel target-resolution match and the adapter-construction match — plus the model_variant_label entry and the module-doc target list.

P5 — Compatibility guard (drafter/mod.rs, .../gemma4_assistant/model.rs, dispatch)

  • New Drafter::validate_target_compat default-method hook (no-op for DFlash / InternalMtp), overridden on Gemma4AssistantDraftModel to reject a target whose text hidden size differs from backbone_hidden_size (the 2×backbone concat invariant) and whose vocabulary differs from the drafter text_config.vocab_size, with clear BindFailed messages. The burst dispatch calls it before bind() on both the single-stream and batched paths.

P6 — Tests

  • mlxcel-core: kind resolution (gemma4_unified_assistant → Mtp), unified config parse + normalize, compat-guard accept/reject (hidden-size mismatch, missing embed_tokens).
  • mlxcel: weights-free structural trait-surface pins for both Unified adapters (gemma4_mtp_target_tests.rs), plus a #[ignore]-gated real-model greedy-parity round-trip greedy_parity_mtp_gemma4_unified_12b and a REACHABLE_PAIRINGS entry (gemma-4-12b-it-4bit + gemma-4-12B-it-assistant-4bit) in tests/speculative_parity.rs.

P7 — Benchmark (src/bin/speculative_bench.rs)

  • Activated the deferred BenchKind::Mtp arm: new run_mtp() loads the Unified target, compat-checks + binds the assistant drafter, drives MtpGenerator through Gemma4UnifiedMtpTargetAdapter (with a warm-up), and records real decode tok/s. Added REACHABLE_PAIRINGS baseline + MTP entries for the 12B Unified pair so a sweep computes speedup = MTP ÷ baseline.

Crash fix: quantization-aware UnifiedLinear for pre/post projection (commit 0cc62df)

The drafter's pre_projection and post_projection were loaded as plain (non-quantized) Linear layers. On a 4-bit drafter checkpoint the weight tensors are quantized, so a standard Linear forward crashed immediately. Fixed by replacing both with UnifiedLinear, which auto-detects quantization via the presence of .scales and falls back to plain Linear for bf16 checkpoints — behavior-preserving for the 31B bf16 path, crash-fix for the 4-bit assistant path.

Measured result: ~1.87× decode speedup (satisfies #154 acceptance criterion)

Real-model measurement at temperature 0 on gemma-4-12b-it-4bit target + gemma-4-12B-it-assistant-4bit (4-bit) drafter:

  • MTP output is byte-identical to classic decode at temperature 0 (correctness gate passes).
  • Decode throughput: ≈39 tok/s (baseline) → ≈74 tok/s (MTP) = ~1.87× speedup.
  • Default-on (no env var): the scheduler now runs B=1 MTP automatically when the target cannot batch (supports_batching() == false, e.g. gemma4_unified), which is its only decode path. Batch-capable targets (e.g. the 31B) keep the 31B-calibrated decline, and MLXCEL_ENABLE_MTP_B1=1 still force-enables B=1 MTP on them for parity/debug. (Resolves the follow-up that had been tracked in perf: enable B=1 MTP speculative decoding by default for gemma4_unified (re-calibrate the singleton-window decline guard) #158.)

Reproduce with:

# baseline
MLXCEL_ENABLE_MTP_B1=1 ./target/release/speculative_bench \
    --target <store>/gemma-4-12b-it-4bit --kind none --max-tokens 256 --prompt "<fixed>"
# MTP
MLXCEL_ENABLE_MTP_B1=1 ./target/release/speculative_bench \
    --target <store>/gemma-4-12b-it-4bit \
    --draft <store>/gemma-4-12B-it-assistant-4bit \
    --kind mtp --draft-block-size 4 --max-tokens 256 --prompt "<fixed>"

Reused vs net-new

  • Reused unchanged: Gemma4AssistantDraftModel (centroid head), MtpGenerator / MtpTarget, Gemma4MtpTargetAdapter / Gemma4MtpBatchedTargetAdapter, load_drafter, --draft-kind mtp flags, SpeculativeDispatch::Mtp.
  • Net-new: the registry entry, the four Unified target hooks, the two Unified adapters, the burst-dispatch arms, the validate_target_compat hook + override, the tests, and the activated benchmark path.

Test plan

  • cargo check --lib --tests — clean
  • cargo clippy --lib --tests --bins -- -D warnings — clean
  • cargo test -p mlxcel-core --lib drafter — 132 passed (incl. new kind/config/compat tests)
  • cargo test --lib gemma4_mtp_target — 17 passed (incl. new Unified adapter pins)
  • cargo test --lib gemma4_unified — 21 passed
  • cargo test --lib speculative_burst — 45 passed (dispatch arms unaffected)
  • cargo check --test speculative_parity / cargo check --bin speculative_bench — compile clean
  • Real-model gate: temperature 0 byte-identical output + ~1.87× decode speedup (≈39→74 tok/s) on the 12B Unified pair, engaged by default (no env var)

Closes #154
Closes #158

inureyes added 3 commits June 4, 2026 22:46
Register the Gemma 4 Unified MTP "assistant" drafter so the
gemma4_unified_assistant checkpoint resolves to the existing MTP round loop, and add the target↔drafter compatibility gate the dispatch will call before binding.

Changes:

- drafter_kind_by_model_type() now maps both gemma4_assistant and gemma4_unified_assistant to DrafterKind::Mtp; module-doc DRAFTER_KIND_BY_MODEL_TYPE comments updated to list both spellings.
- New Drafter::validate_target_compat default-method hook (no-op for DFlash / InternalMtp), overridden on Gemma4AssistantDraftModel to reject a target whose text hidden size differs from the drafter backbone_hidden_size (the 2×backbone concat invariant) and whose vocabulary differs from the drafter text_config.vocab_size, with clear BindFailed messages. The vocab arm is best-effort and runs only when the target exposes embed_tokens_module.
- Gemma4AssistantConfig already accepts arbitrary model_type strings, so the gemma4_unified_assistant / gemma4_unified_text spellings parse and normalize unchanged.
- Tests: kind resolution for gemma4_unified_assistant, unified config parse + normalize (backbone_hidden_size 3840, kv-shared promotion), and compat-guard accept/reject (hidden-size mismatch, missing embed_tokens).

Refs #154
Wire the Gemma 4 Unified decode target into the existing MTP speculative-decoding stack, mirroring the Gemma 4 VLM path exactly. The MTP drafter model and round loop are reused unchanged; this is target-side adapter plumbing plus burst-dispatch arms.

Changes:

- Gemma4UnifiedModel (src/vision/gemma4_unified.rs) gains the speculative hooks delegating to its inner text_model: forward_with_speculative_sinks, forward_with_speculative_sinks_explicit_cache (batched), rollback_speculative_cache, and speculative_draft_hidden — pure pass-throughs identical to gemma4_vl.rs.
- New Gemma4UnifiedMtpTargetAdapter and Gemma4UnifiedMtpBatchedTargetAdapter (src/models/gemma4_mtp_target.rs), each wrapping &Gemma4UnifiedModel and building the inner Gemma4MtpTargetAdapter / batched adapter over unified.text_model, mirroring the VL adapters.
- Burst dispatch (src/server/batch/speculative_burst.rs): LoadedModel::Gemma4Unified arms in the single-stream and batched MTP dispatch (target-LM resolution + adapter construction), the validate_target_compat pre-bind compatibility gate on both paths, the model_variant_label entry, and the module-doc target list.
- Tests: structural trait-surface pins for both Unified adapters (weights-free), and a #[ignore]-gated real-model greedy-parity round-trip (greedy_parity_mtp_gemma4_unified_12b) plus a REACHABLE_PAIRINGS entry for gemma-4-12b-it-4bit + gemma-4-12B-it-assistant-4bit in tests/speculative_parity.rs.

Refs #154
Wire the deferred BenchKind::Mtp arm in speculative_bench so it measures the real decode speedup for the Gemma 4 Unified 12B target + gemma4_unified_assistant drafter (issue #154).

Changes:

- New run_mtp() loads the Gemma4Unified target, loads + compat-checks + binds the MTP assistant drafter, and drives MtpGenerator through Gemma4UnifiedMtpTargetAdapter with a warm-up pass, recording real decode tok/s the same way run_baseline does. Mean acceptance length per round is emitted by the round loop's tracing diagnostics during the run.
- bench_one_pairing's Mtp arm and the operator-supplied-path Mtp arm in main now call run_mtp instead of returning a deferred row; the DFlash arm stays deferred with its real blocker note.
- REACHABLE_PAIRINGS gains a Gemma 4 Unified 12B baseline + MTP-assistant pair (gemma-4-12b-it-4bit / gemma-4-12B-it-assistant-4bit, block_size 4) so a sweep computes speedup = MTP ÷ baseline for the measured pair.
- Module/enum docs and the table footer updated to reflect that MTP rows are now real numbers.

Refs #154
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:models Model architectures, weights, loading, metadata labels Jun 4, 2026
inureyes added 3 commits June 4, 2026 23:01
…e UnifiedLinear

The MTP drafter's pre_projection / post_projection were loaded as a plain
(non-quantized) Linear, so a 4-bit assistant drafter (e.g.
gemma-4-12B-it-assistant-4bit) crashed at forward time with a matmul
shape mismatch (unpacked 2*backbone vs packed in/8). Switch both to
UnifiedLinear::from_weights, which auto-detects quantization via the
.scales tensor and runs quantized_matmul, falling back to a plain Linear
for bf16 drafters (e.g. the 31B assistant) — behavior-preserving for the
non-quantized path. Verified on the real gemma-4-12b-it-4bit target +
4-bit assistant: temp-0 output is byte-identical to classic decode and
MLXCEL_ENABLE_MTP_B1=1 yields ~1.87x decode speedup (39 -> 74 tok/s).
…eedup

Updates the MLXCEL_ENABLE_MTP_B1 entry in environment-variables.md to document that it is required to observe the measured ~1.87x decode speedup (39->74 tok/s) on the gemma-4-12b-it-4bit + 4-bit-assistant pair, and explains why the scheduler guard declines singleton MTP by default (calibrated on 31B). References #158 for making B=1 MTP default on the 12B class.
@inureyes

inureyes commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

All checks passing. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 4, 2026
inureyes added 2 commits June 4, 2026 23:41
The scheduler declined every singleton (B=1) MTP burst unless
MLXCEL_ENABLE_MTP_B1=1 was set, a guard calibrated on the Gemma 4 31B
(bf16 assistant) where B=1 acceptance is too low to beat classic decode.
The Gemma 4 Unified target cannot batch (supports_batching() == false), so
B=1 is its only decode path and MTP there is measurably profitable
(~1.87x, byte-identical at temp 0). Gate the decline on
self.model.supports_batching() so batch-capable targets keep the
31B-calibrated behavior while non-batching targets run B=1 MTP by default;
MLXCEL_ENABLE_MTP_B1=1 still force-enables it on batch-capable targets.

Also document the Gemma 4 12B MTP result and method in docs/benchmarks.md
and the benchmark report.

Closes #158
@inureyes
inureyes merged commit 07a5f85 into main Jun 4, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-154-gemma4-unified-mtp-drafter branch June 4, 2026 14:51
@inureyes inureyes added this to the 0.1 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…nt) (lablup#157)

* feat(drafter): register gemma4_unified_assistant MTP kind + compat guard

Register the Gemma 4 Unified MTP "assistant" drafter so the
gemma4_unified_assistant checkpoint resolves to the existing MTP round loop, and add the target↔drafter compatibility gate the dispatch will call before binding.

Changes:

- drafter_kind_by_model_type() now maps both gemma4_assistant and gemma4_unified_assistant to DrafterKind::Mtp; module-doc DRAFTER_KIND_BY_MODEL_TYPE comments updated to list both spellings.
- New Drafter::validate_target_compat default-method hook (no-op for DFlash / InternalMtp), overridden on Gemma4AssistantDraftModel to reject a target whose text hidden size differs from the drafter backbone_hidden_size (the 2×backbone concat invariant) and whose vocabulary differs from the drafter text_config.vocab_size, with clear BindFailed messages. The vocab arm is best-effort and runs only when the target exposes embed_tokens_module.
- Gemma4AssistantConfig already accepts arbitrary model_type strings, so the gemma4_unified_assistant / gemma4_unified_text spellings parse and normalize unchanged.
- Tests: kind resolution for gemma4_unified_assistant, unified config parse + normalize (backbone_hidden_size 3840, kv-shared promotion), and compat-guard accept/reject (hidden-size mismatch, missing embed_tokens).

Refs lablup#154

* feat(speculative): route Gemma4Unified target through MTP burst dispatch

Wire the Gemma 4 Unified decode target into the existing MTP speculative-decoding stack, mirroring the Gemma 4 VLM path exactly. The MTP drafter model and round loop are reused unchanged; this is target-side adapter plumbing plus burst-dispatch arms.

Changes:

- Gemma4UnifiedModel (src/vision/gemma4_unified.rs) gains the speculative hooks delegating to its inner text_model: forward_with_speculative_sinks, forward_with_speculative_sinks_explicit_cache (batched), rollback_speculative_cache, and speculative_draft_hidden — pure pass-throughs identical to gemma4_vl.rs.
- New Gemma4UnifiedMtpTargetAdapter and Gemma4UnifiedMtpBatchedTargetAdapter (src/models/gemma4_mtp_target.rs), each wrapping &Gemma4UnifiedModel and building the inner Gemma4MtpTargetAdapter / batched adapter over unified.text_model, mirroring the VL adapters.
- Burst dispatch (src/server/batch/speculative_burst.rs): LoadedModel::Gemma4Unified arms in the single-stream and batched MTP dispatch (target-LM resolution + adapter construction), the validate_target_compat pre-bind compatibility gate on both paths, the model_variant_label entry, and the module-doc target list.
- Tests: structural trait-surface pins for both Unified adapters (weights-free), and a #[ignore]-gated real-model greedy-parity round-trip (greedy_parity_mtp_gemma4_unified_12b) plus a REACHABLE_PAIRINGS entry for gemma-4-12b-it-4bit + gemma-4-12B-it-assistant-4bit in tests/speculative_parity.rs.

Refs lablup#154

* feat(bench): activate MTP speculative bench for Gemma 4 Unified pair

Wire the deferred BenchKind::Mtp arm in speculative_bench so it measures the real decode speedup for the Gemma 4 Unified 12B target + gemma4_unified_assistant drafter (issue lablup#154).

Changes:

- New run_mtp() loads the Gemma4Unified target, loads + compat-checks + binds the MTP assistant drafter, and drives MtpGenerator through Gemma4UnifiedMtpTargetAdapter with a warm-up pass, recording real decode tok/s the same way run_baseline does. Mean acceptance length per round is emitted by the round loop's tracing diagnostics during the run.
- bench_one_pairing's Mtp arm and the operator-supplied-path Mtp arm in main now call run_mtp instead of returning a deferred row; the DFlash arm stays deferred with its real blocker note.
- REACHABLE_PAIRINGS gains a Gemma 4 Unified 12B baseline + MTP-assistant pair (gemma-4-12b-it-4bit / gemma-4-12B-it-assistant-4bit, block_size 4) so a sweep computes speedup = MTP ÷ baseline for the measured pair.
- Module/enum docs and the table footer updated to reflect that MTP rows are now real numbers.

Refs lablup#154

* fix: drop unused lifetime in unified MTP adapter test helpers

* fix: load gemma4-assistant pre/post projections via quantization-aware UnifiedLinear

The MTP drafter's pre_projection / post_projection were loaded as a plain
(non-quantized) Linear, so a 4-bit assistant drafter (e.g.
gemma-4-12B-it-assistant-4bit) crashed at forward time with a matmul
shape mismatch (unpacked 2*backbone vs packed in/8). Switch both to
UnifiedLinear::from_weights, which auto-detects quantization via the
.scales tensor and runs quantized_matmul, falling back to a plain Linear
for bf16 drafters (e.g. the 31B assistant) — behavior-preserving for the
non-quantized path. Verified on the real gemma-4-12b-it-4bit target +
4-bit assistant: temp-0 output is byte-identical to classic decode and
MLXCEL_ENABLE_MTP_B1=1 yields ~1.87x decode speedup (39 -> 74 tok/s).

* docs: clarify MLXCEL_ENABLE_MTP_B1 is required for 12B unified MTP speedup

Updates the MLXCEL_ENABLE_MTP_B1 entry in environment-variables.md to document that it is required to observe the measured ~1.87x decode speedup (39->74 tok/s) on the gemma-4-12b-it-4bit + 4-bit-assistant pair, and explains why the scheduler guard declines singleton MTP by default (calibrated on 31B). References lablup#158 for making B=1 MTP default on the 12B class.

* style: apply cargo fmt to gemma4_unified MTP drafter code

* perf: run B=1 MTP by default for non-batching targets (gemma4_unified)

The scheduler declined every singleton (B=1) MTP burst unless
MLXCEL_ENABLE_MTP_B1=1 was set, a guard calibrated on the Gemma 4 31B
(bf16 assistant) where B=1 acceptance is too low to beat classic decode.
The Gemma 4 Unified target cannot batch (supports_batching() == false), so
B=1 is its only decode path and MTP there is measurably profitable
(~1.87x, byte-identical at temp 0). Gate the decline on
self.model.supports_batching() so batch-capable targets keep the
31B-calibrated behavior while non-batching targets run B=1 MTP by default;
MLXCEL_ENABLE_MTP_B1=1 still force-enables it on batch-capable targets.

Also document the Gemma 4 12B MTP result and method in docs/benchmarks.md
and the benchmark report.

Closes lablup#158
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

1 participant