Repository navigation
feat: Gemma 4 Unified MTP speculative drafter (gemma4_unified_assistant) - #157
Merged
Merged
Conversation
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
…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.
Member
Author
PR Finalization CompleteSummary
All checks passing. Ready for merge. |
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Wires the Gemma 4 Unified decode target (
LoadedModel::Gemma4Unified) into the existing MTP speculative-decoding stack so it can be accelerated by agemma4_unified_assistantdrafter, 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 bothgemma4_assistantandgemma4_unified_assistanttoDrafterKind::Mtp; module-docDRAFTER_KIND_BY_MODEL_TYPEcomments list both spellings.Gemma4AssistantConfigalready accepts arbitrarymodel_typestrings, so thegemma4_unified_assistant/gemma4_unified_textspellings parse and normalize unchanged (added a parse test).P2 — Unified target speculative hooks (
src/vision/gemma4_unified.rs)Gemma4UnifiedModelgainsforward_with_speculative_sinks,forward_with_speculative_sinks_explicit_cache(batched),rollback_speculative_cache, andspeculative_draft_hidden— pure pass-throughs to the innertext_model: Gemma4Wrapper, identical tosrc/vision/gemma4_vl.rs.P3 — Unified MTP target adapters (
src/models/gemma4_mtp_target.rs)Gemma4UnifiedMtpTargetAdapter<'a>andGemma4UnifiedMtpBatchedTargetAdapter<'a>, each wrapping&Gemma4UnifiedModeland building the innerGemma4MtpTargetAdapter/ batched adapter overunified.text_model, mirroring the VL adapters.P4 — Burst dispatch (
src/server/batch/speculative_burst.rs)LoadedModel::Gemma4Unifiedarms added to the single-stream (run_mtp_burst) and batched (run_mtp_burst_batched) MTP dispatch — both the&dyn LanguageModeltarget-resolution match and the adapter-construction match — plus themodel_variant_labelentry and the module-doc target list.P5 — Compatibility guard (
drafter/mod.rs,.../gemma4_assistant/model.rs, dispatch)Drafter::validate_target_compatdefault-method hook (no-op for DFlash / InternalMtp), overridden onGemma4AssistantDraftModelto reject a target whose text hidden size differs frombackbone_hidden_size(the2×backboneconcat invariant) and whose vocabulary differs from the draftertext_config.vocab_size, with clearBindFailedmessages. The burst dispatch calls it beforebind()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, missingembed_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-tripgreedy_parity_mtp_gemma4_unified_12band aREACHABLE_PAIRINGSentry (gemma-4-12b-it-4bit+gemma-4-12B-it-assistant-4bit) intests/speculative_parity.rs.P7 — Benchmark (
src/bin/speculative_bench.rs)BenchKind::Mtparm: newrun_mtp()loads the Unified target, compat-checks + binds the assistant drafter, drivesMtpGeneratorthroughGemma4UnifiedMtpTargetAdapter(with a warm-up), and records real decode tok/s. AddedREACHABLE_PAIRINGSbaseline + 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_projectionandpost_projectionwere loaded as plain (non-quantized)Linearlayers. On a 4-bit drafter checkpoint the weight tensors are quantized, so a standardLinearforward crashed immediately. Fixed by replacing both withUnifiedLinear, which auto-detects quantization via the presence of.scalesand falls back to plainLinearfor 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 0ongemma-4-12b-it-4bittarget +gemma-4-12B-it-assistant-4bit(4-bit) drafter: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, andMLXCEL_ENABLE_MTP_B1=1still 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:
Reused vs net-new
Gemma4AssistantDraftModel(centroid head),MtpGenerator/MtpTarget,Gemma4MtpTargetAdapter/Gemma4MtpBatchedTargetAdapter,load_drafter,--draft-kind mtpflags,SpeculativeDispatch::Mtp.validate_target_compathook + override, the tests, and the activated benchmark path.Test plan
cargo check --lib --tests— cleancargo clippy --lib --tests --bins -- -D warnings— cleancargo 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 passedcargo test --lib speculative_burst— 45 passed (dispatch arms unaffected)cargo check --test speculative_parity/cargo check --bin speculative_bench— compile cleantemperature 0byte-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