Skip to content

feat(mtp): add Gemma 4 assistant drafter - #206

Draft
TheTom wants to merge 1 commit into
ekryski:alphafrom
TheTom:codex/gemma4-mtp-drafter
Draft

TheTom wants to merge 1 commit into
ekryski:alphafrom
TheTom:codex/gemma4-mtp-drafter

Conversation

@TheTom

@TheTom TheTom commented May 13, 2026

Copy link
Copy Markdown

Summary

  • add the Gemma 4 assistant drafter model and MTP speculative decode helpers
  • register gemma4_assistant in the model factory
  • include an MTPSpecDecode benchmark harness

Notes

  • draft PR split from the alpha integration stack
  • based on fresh ekryski:alpha
  • intended to complement, not replace, Eric's existing MTP scaffolding draft

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>
@ekryski ekryski added the feature New feature (auto-applied from feat: prefix) label May 13, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants