Repository navigation
Conversation
First Swift-native port of Google's Gemma 4 MTP drafter for
speculative decoding. Independent implementation matching the
algorithm in mlx-vlm's mlx_vlm/speculative/drafters/gemma4_assistant/.
Files added:
- Libraries/MLXLLM/Models/Gemma4Assistant.swift
- Gemma4AssistantConfiguration (Codable, mirrors the HF
Gemma4AssistantConfig shape with nested text_config)
- Gemma4DrafterAttention: Q-only attention module — the drafter
checkpoint ships only q_proj / q_norm / o_proj per layer because
every layer is is_kv_shared_layer=True. K/V come from the
parent's last full-attention and last sliding-attention layer
caches via setSharedKV().
- Gemma4DrafterDecoderLayer + DrafterMLP wrappers using the Q-only
attention and the standard Gemma 4 RMSNormResidual ffn pattern
- Gemma4AssistantInner (4 layers + norm + tied embed_tokens)
- Gemma4AssistantModel (LLMModel-conforming with stub prepare()
that fatalErrors — the model is driven via runMTPSpeculative,
not the standard generate path)
- bind(parentEmbedding:embedScale:): wires the drafter to the
parent's input embedding so the drafter can embed last-accepted
tokens through the parent's vocabulary
- setSharedKV(fullAttn:slidingAttn:kvOffset:position:): per-block
shared K/V hand-off from parent
- draftBlock(lastBonus:hidden:blockSize:) returns an MLXArray
[1, blockSize-1] of Int32 candidate tokens. The drafter loop
keeps tokens as MLXArrays the entire way through so the autograph
fuses end-to-end and the caller syncs once per round.
- bidirectionalSWAMask + buildBlockMasks helpers (mask cached per
block; queryOffset and KV layout are both constant across the
block_size-1 steps within a block).
- extractDrafterSharedKV helper: pulls parent's last full + last
sliding K/V out of the cache list, accounting for KV-sharing
donor mappings.
- sanitize(weights:): drops tied lm_head and the masked_embedding
keys (the latter only applies to E2B/E4B variants — masked
embedder is not yet ported).
- Libraries/MLXLLM/Models/MTPSpec.swift
- runMTPSpeculative driver: prefill parent on prompt → loop
(extract shared K/V → drafter.draftBlock → parent verify K
tokens in one parallel forward → greedy accept/reject → trim
parent cache → thread parent's last hidden into next round's
drafter input) → emit accepted tokens
- MTPInfo struct: prefill_s, decode_s, proposed_total,
accepted_total, acceptanceRate
- Optional MTP_PROFILE=1 instrumentation: per-phase ms breakdown
(draft / verify / sync / cache_trim / total) printed at end of run
- Libraries/MLXLLM/LLMModelFactory.swift
- Registers gemma4_assistant model_type so the drafter loads
cleanly through LLMModelFactory.shared.loadContainer
- Libraries/MLXLLM/Models/Gemma4.swift
- lmHead made public so callers (the MTP iterator specifically)
can apply the parent's LM head to the inner forward's hidden
output for verification logits
- Tests/Benchmarks/MTPSpecDecode.swift
- Benchmark harness on Gemma 4 31B + 31B-it-assistant (and 26B-A4B
+ drafter, switchable). Sweeps numDraftTokens k=1/2/3/4/6/8 and
reports decode tps + speedup vs no-drafter baseline + acceptance
rate. Optional MTP_DRAFTER_4BIT=1 quantizes the drafter to
4-bit affine (group=64) at load via MLXNN.quantize — saves ~40%
of drafter step time AND raises acceptance rate (drafter quant
noise aligns with target quant noise → fewer rejections).
Numbers on M5 Max with 4-bit drafter at k=2 (block_size 3):
41.7 tps best / 40.2 tps stable / 1.50× over single-token decode
baseline of 27-28 tps. Acceptance ~132% (counts target-bonus on
fully-matched rounds). On par with community Python mlx-vlm.
Algorithm correctness: byte-identical greedy output to no-drafter
baseline (same temperature=0.0, same logits, same argmax).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4 tasks done
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
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
Notes