Skip to content

Add Gemma 4 MTP speculative decoding - #293

Closed
angelsbrood wants to merge 13 commits into
ml-explore:lmoutput-statefrom
angelsbrood:gemma4-assistant
Closed

angelsbrood wants to merge 13 commits into
ml-explore:lmoutput-statefrom
angelsbrood:gemma4-assistant

Conversation

@angelsbrood

Copy link
Copy Markdown
Contributor

Proposed changes

Adds Gemma 4 Multi-Token Prediction (MTP) speculative decoding. Introduces an MTPDrafterModel protocol in MLXLMCommon refining BaseLanguageModel, registers gemma4_assistant as the first concrete drafter implementation, threads cross-model state through three public LMOutput.Key declarations, and adds an MTPSpeculativeTokenIterator parallel to the existing SpeculativeTokenIterator. Tracks #279.

Opening as a draft against lmoutput-state because the implementation depends on #283's typed-key LMOutput.State API. Will rebase to main once #283 merges; review requests deferred until then.

Architecture

The drafter does not fit LanguageModel. Its forward signature differs in fundamental ways: it has no own KV cache; it cross-attends to the target's last full-attention and last sliding-attention layers via a [String: (MLXArray, MLXArray)] shared K/V dict; its position IDs are constant within a drafting round; and it requires a bind-time reference to the target to borrow input embeddings. The new MTPDrafterModel protocol in Libraries/MLXLMCommon/MTPDrafterModel.swift refines BaseLanguageModel (so weight loading and sanitize hooks are inherited) and defines its own forward signature. Drafters are loaded via MTPDrafterModelFactory, registered into MTPDrafterTypeRegistry, and driven by MTPSpeculativeTokenIterator.

Cross-model state passthrough uses three public LMOutput.Key declarations in MLXLMCommon: mtpEmitFlagKey: Bool, mtpLastHiddenStatesKey: MLXArray, and mtpSharedKVStatesKey: [String: (MLXArray, MLXArray)]. The iterator pre-populates the emit-flag key on every main-model call to signal that the target should write drafter state; the target's top-level Gemma4.callAsFunction(_:cache:state:) override reads the flag and threads it through to the backbone, which writes the last-layer hidden state and per-layer_type shared K/V into the state on the way out. The emit flag is itself a LMOutput.Key<Bool> rather than a function parameter because LanguageModel.callAsFunction(_:cache:state:) has a fixed protocol signature; threading the flag through LMOutput.State unifies the mechanism — the state-bag carries both tensor payloads and the control signal that triggers them.

MTPSpeculativeTokenIterator includes a sticky passthrough fallback. When the target's emit hook returns nil shared K/V — which happens once quantization onset converts the regular K/V cache to QuantizedKVCache, or any other condition that breaks the regular-K/V invariant — the iterator transparently switches to single-token main-model generation for the remainder of the stream. The drafter is never invoked again on that iterator instance. MTP with mid-stream quantization onset degrades gracefully rather than crashing or producing incorrect outputs; bf16-drafter-against-quantized-target streams give up the speedup but preserve correctness.

On the target side, the drafter reuses existing Gemma4TextAttention, Gemma4TextDecoderLayer, and norm building blocks rather than duplicating them. Visibility on those types and a kvSharedOnly: Bool flag on Gemma4TextAttention.init (which skips construction of kProj/vProj/kNorm/vNorm, declared Optional @ModuleInfo) let the drafter compose its own decoder layers from existing target-side modules. Gemma4.swift diff: +53/−26. The non-kvSharedOnly regression suite is bit-identical before and after; existing Gemma 4 generation paths are not perturbed.

Relationship to existing work

#269 targets the same scope — Gemma 4 MTP speculative decoding — and predates this PR by ~9 days. The two implementations diverge on three substantive axes worth surfacing for reviewers:

  1. Foundation. Add Gemma 4 MTP assistant model and native MTP speculative decoding #269 widens generateLoopTask and TokenLoopHandler from private to internal to reuse the existing generation infrastructure, and exposes pre-logit hidden states via a new forwardMTP() method on Gemma4TextModel. This PR consumes the LMOutput.State API from models should not mutate state during eval #283 instead, threading drafter state through the dictionary-backed typed-key state-bag (three LMOutput.Key declarations, no per-call ivar mutation on the model). The "models should not mutate state during eval" invariant of models should not mutate state during eval #283 is honored throughout.
  2. Verification. This PR is fixture-anchored against mlx-vlm@d49d428 with a four-rung ladder culminating in byte-identical token-ID parity at temperature=0. Add Gemma 4 MTP assistant model and native MTP speculative decoding #269 lists a test plan as an unchecked checklist.
  3. Quantization onset. This PR includes the sticky passthrough fallback described above, which preserves correctness when the main model's cache transitions to quantized mid-stream. Add Gemma 4 MTP assistant model and native MTP speculative decoding #269 does not address this case.

The masked-embedder path is the dimension on which #269 has more implemented than this PR; conversely this PR carries the empty-checkpoint fatalError stub honestly rather than shipping centroid logic without a verification fixture.

The overlap is real and acknowledged here so reviewers don't have to discover it independently.

Verification

Fixture-anchored against mlx-vlm@d49d428. Reference dataset published at angelsbrood/gemma4-mtp-fixtures — 43 files / ~20 MB, generated against target=mlx-community/gemma-4-31b-it-8bit and drafter=mlx-community/gemma-4-31B-it-assistant-bf16. The same 43-file fixture set is vendored in-repo at tools/fixtures/ so the Rung 1–4 tests run offline against a known-good frozen reference; schema (FIXTURE-SCHEMA.md), manifest (FIXTURE-MANIFEST.json), and the generation tooling sit alongside. Regeneration is deterministic (verified across runs).

Verification proceeds in four rungs, each gating the next:

  • Rung 1 — Load / shape. Drafter checkpoint loads with no missing or unexpected weight keys after sanitize. Weight-key inventory in RESEARCH-NOTES.md matches the checkpoint verbatim across both 31B and 26B-A4B drafter siblings (48 keys each, identical layout, shapes differ).
  • Rung 2 — Per-layer activations. Drafter forward with synthetic inputs produces activations matching Python fixtures at atol=1e-3, rtol=1e-3.
  • Rung 3 — Logit parity. Greedy draftBlock logits match Python fixtures at the same tolerance.
  • Rung 4 — Token-for-token cross-runtime parity. Greedy draftBlock at temperature=0 produces byte-identical token-ID sequences to the Python reference across three block sizes (2, 4, 6).

All four rungs pass in Xcode against the fixture set. swift test CLI is not a working verification surface for this repository — CONTRIBUTING.md notes "swift test does not work yet — use xcodebuild instead," and the metallib initialization failure that affects CLI runs predates this branch and is not introduced here. Full-target acceptance-rate and quantization-onset integration tests are placeholdered in MLXLMTests with Issue.record + early-return because they require MLXHuggingFace's #huggingFaceTokenizerLoader() which is not in MLXLMTests' dependency closure; the full end-to-end measurement will live in a downstream integration test.

Files

New:

  • Libraries/MLXLMCommon/MTPDrafterModel.swift — MTPDrafterModel protocol, MTPDrafterContext, MTPDrafterContainer, three public LMOutput.Key declarations
  • Libraries/MLXLMCommon/MTPSpeculativeTokenIterator.swift — iterator with sticky passthrough fallback
  • Libraries/MLXLMCommon/MTPDrafterModelFactory.swift — MTPDrafterTypeRegistry, MTPDrafterRegistry, MTPDrafterModelFactory
  • Libraries/MLXLMCommon/BidirectionalMasks.swift — createBidirectionalMask and createBidirectionalSlidingWindowMask helpers
  • Libraries/MLXVLM/Models/Gemma4Assistant.swift — Gemma4AssistantConfiguration, Gemma4AssistantMaskedEmbedder, Gemma4AssistantDraftInner, Gemma4AssistantDraftModel
  • Libraries/MLXVLM/Gemma4AssistantRegistration.swift — registerModelType call site for "gemma4_assistant"
  • Tests/MLXLMTests/BidirectionalMasksTests.swift, MTPDrafterModelTests.swift, Gemma4AssistantDraftModelTests.swift, Gemma4EmitDrafterStateTests.swift, MTPDrafterModelFactoryTests.swift, MTPSpeculativeTokenIteratorTests.swift, MTPGenerateAPITests.swift, MTPRung4TokenParityTests.swift, MTPAcceptanceRateTests.swift, MTPQuantizationOnsetTests.swift
  • RESEARCH-NOTES.md — architectural Q&A with file:line citations against canonical Python (HF Transformers gemma4_assistant, mlx-vlm drafter), plus full 48-key weight inventories for both reference drafter checkpoints
  • tools/inspect_drafter_layout.py, tools/generate_mtp_fixtures.py
  • tools/fixtures/ — 43 fixture data files (~20 MB) plus FIXTURE-SCHEMA.md and FIXTURE-MANIFEST.json. Vendored in-repo so the Rung 1–4 tests run offline against a frozen reference; content is byte-identical to the angelsbrood/gemma4-mtp-fixtures HF dataset for cross-verification.

Modified:

  • Libraries/MLXLMCommon/Evaluate.swift — two new generate(...) overloads (one returning AsyncStream<Generation>, one returning AsyncStream<TokenGeneration>), taking an mtpDrafter parameter, blockSize: Int = 4 default
  • Libraries/MLXVLM/Models/Gemma4.swift — visibility bumps on internal building blocks (the cascade reached 16 symbols once Gemma4TextLanguageModel, Gemma4TextBackbone, the languageModel accessor, and four MLP/router types were pulled along by what they reference), kvSharedOnly: Bool flag on Gemma4TextAttention.init, emit hooks in Gemma4TextBackbone.callAsFunction and Gemma4TextLanguageModel.callAsFunction, new top-level Gemma4.callAsFunction(_:cache:state:) override (+53/−26)

Supported model pairs

Target Drafter Status in this PR
mlx-community/gemma-4-31b-it-8bit mlx-community/gemma-4-31B-it-assistant-bf16 Primary; fixture-anchored
mlx-community/gemma-4-26B-A4B-it-bf16 mlx-community/gemma-4-26B-A4B-it-assistant-bf16 Architecturally supported; not fixture-anchored
mlx-community/gemma-4-31B-it-bf16 mlx-community/gemma-4-31B-it-assistant-bf16 Architecturally supported; would re-tighten Rung 2/3 tolerances

E-series targets (gemma-4-E2B-it, gemma-4-E4B-it) are architecturally supported but not exercised by the fixture set in this PR; both have published -assistant-bf16 siblings on the mlx-community org.

Known limitations

  • Gemma4AssistantMaskedEmbedder.callAsFunction is a fatalError stub. Both reference checkpoints have use_ordered_embeddings=false and ship with zero masked_embedding.* weight keys, so the centroid-narrowing path is never exercised by the fixture set or by either currently-published reference checkpoint. The module is declared correctly for weight loading (so a future checkpoint with the flag enabled would load with no key mismatches); the forward implementation can land in a follow-up when a verifiable checkpoint surfaces. Choosing fatalError over an unverified implementation matches the verification posture of the rest of the PR.
  • Quantized drafter weights deferred — bf16 only initially. Drafters are small enough (~78M params for E-series, ~0.4B–0.5B for the larger pairs) that this is acceptable for a first PR.
  • Batched MTP deferred — single-batch only. mlx-vlm's _speculative_walk_batch is out of scope.
  • Audio path unaffected — the target's audio components remain filtered in sanitize today; this drafter is text-only.
  • Quantized cache during a drafting stream is covered by the sticky passthrough fallback described above. The drafter is bypassed when fallback activates; correctness is preserved, the MTP speedup is not.
  • Acceptance-rate floor and full-target quantization-onset integration tests are placeholdered in MLXLMTests pending MLXHuggingFace in the test target's dependency closure. The passthrough fallback logic itself is unit-tested with synthetic state.

Checklist

  • CONTRIBUTING document read
  • pre-commit run --all-files passes
  • Tests added (ten new test files; Rungs 1–4 covered; full-target integration tests placeholdered with documented gating)
  • Documentation updates — happy to add a README section or wherever convention dictates if reviewers want one

Acknowledgments

Thanks to @davidkoski for #283 — the typed-key LMOutput.State API is the foundation this PR builds on; without it, the cross-model state passthrough would have required something much uglier.

References

davidkoski and others added 13 commits May 12, 2026 15:57
Foundation API in MLXLMCommon for Multi-Token Prediction speculative
drafters. The protocol refines `BaseLanguageModel` (mirroring
`EmbeddingModel`'s relationship to it) so drafters inherit weight
loading and `sanitize` hooks while defining a different forward
contract: a single `draftBlock(...)` call yields K-1 candidate tokens
from a constant position, consuming the target's last hidden state and
per-`layer_type` shared K/V as method arguments. The drafter is bound
to its target once via `bind(target:)`; that call caches read-only
references to the target's input embeddings, embed scale, and layer-
type metadata. No mutation during eval — consistent with PR ml-explore#283.

`MTPDrafterContext` is a lightweight, non-Sendable record (model,
config); cross-domain access goes through `MTPDrafterContainer`, a
`final class : Sendable` wrapping `SerialAccessContainer`. Mirrors the
existing `ModelContext` / `ModelContainer` split.

Public state keys for cross-model state exchange are deliberately
omitted — they land in a later commit, after the protocol surface has
been validated independently against PR ml-explore#283's `LMOutput.State` API.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds `createBidirectionalMask` and
`createBidirectionalSlidingWindowMask` for the MTP drafter's attention
path. The existing `createAttentionMask` helper produces causal masks;
MTP drafters need bidirectional ones because their query window
attends fully to the target's pooled K/V (no causal restriction within
the query block) and the sliding-attention layers need a
window-of-last-N-positions mask rather than a causal triangle.

The SWA helper matches the HF "first-w-attended-after-flip" fixture
convention used by `tools/generate_mtp_fixtures.py`. For the dominant
MTP case `queryLen=1, queryOffset=0` this is identical to the runtime
distance formula `(dist > -window) & (dist < window)` used by mlx-vlm
at `masks.py:117-118`; fixture-parity tests verify byte-identity.

Tests in `Tests/MLXLMTests/BidirectionalMasksTests.swift` cover shape,
all-zeros invariant for non-windowed masks, SWA cutoff behavior, and
byte-identical comparison to fixtures generated by
`tools/generate_mtp_fixtures.py` (16 cases). Tests skip gracefully via
`Issue.record` when fixtures aren't present, supporting CI runs that
don't include the fixture-generation step.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Drops `private` from thirteen symbols in `Gemma4.swift` so they can be
consumed by `Gemma4Assistant.swift` (the upcoming MTP drafter, same
MLXVLM target). Each newly-visible symbol carries a doc comment
explaining the cross-file reuse:

    /// Module-internal — also consumed by Gemma4Assistant.swift.

Symbols bumped: `Gemma4SharedKVState`, `Gemma4TextAttention`,
`Gemma4TextDecoderLayer`, `Gemma4TextBackbone`, `Gemma4TextLanguageModel`,
`Gemma4TextMLP`, `Gemma4TextRouter`, `Gemma4TextExperts`,
`Gemma4ScaledLinear`, `Gemma4RMSNormZeroShift`, `Gemma4RMSNormNoScale`,
`gemma4AdjustAttentionMask`, `gemma4DefaultTextRopeParameters`, plus
`Gemma4.languageModel` accessor. The cascade types
(`Gemma4TextMLP`/`Router`/`Experts`/`ScaledLinear`) come along because
the explicitly-named decoder-layer and backbone reference them in
typed properties; making the holders internal forces the held types
internal too.

Also adds a `kvSharedOnly: Bool = false` parameter to
`Gemma4TextAttention.init` and propagates it through
`Gemma4TextDecoderLayer.init`. When `true`, the K-projection, V-
projection, K-norm, and V-norm are skipped at construction — the
drafter's Q-only layers cross-attend to target's pooled K/V and don't
need their own K/V projections. The corresponding `@ModuleInfo`
properties migrate from non-Optional to Optional (`kProj`, `kNorm`,
`vNorm`; `vProj` was already Optional). The non-`kvSharedOnly` path
adds a `guard let kProj, let kNorm, let vNorm` at the top of the
local-KV branch — assertion-equivalent because constructing without
those modules and without `sharedKV` is a configuration bug.

Non-`kvSharedOnly` behavior is bit-identical to the prior code path;
the existing 6-param `SpeculativeDecodingTests` suite passes
unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…DraftModel

Implements the Gemma 4 MTP drafter as `Gemma4AssistantDraftModel`
conforming to `MTPDrafterModel`. Four-layer Q-only assistant that
cross-attends to the target's last full_attention and sliding_attention
K/V pools, pre/post-projects between the drafter's `text_config.
hidden_size` and the target's `backbone_hidden_size`, and emits a
batch of K-1 candidate tokens per `draftBlock(...)` call via an
autoregressive loop over `forwardHidden`.

Components:

- `Gemma4AssistantConfiguration` — drafter's own `text_config` plus
  the backbone-hidden-size pin, tie/lm_head flags, and the
  use-ordered-embeddings switch and centroid params for the
  `MaskedEmbedder` path.

- `Gemma4AssistantMaskedEmbedder` — module structure complete
  (centroid `Linear` + token-ordering `MLXArray` buffer) so weight
  loading works for any checkpoint that opts in via
  `use_ordered_embeddings=true`. `callAsFunction` is a `fatalError`
  placeholder pending a verifiable checkpoint: both reference drafters
  (31B-assistant-bf16 and 26B-A4B-assistant-bf16) have
  `use_ordered_embeddings=false` and zero `masked_embedding.*` weight
  keys, so the centroid path is never exercised by the existing
  fixture set.

- `Gemma4AssistantDraftInner` — `embed_tokens` / `layers` / `norm`
  wrapper that matches the Python checkpoint's key layout. Decoder
  layers are constructed with `kvSharedOnly: true` (introduced in the
  prior commit) so K/V projections are absent.

- `Gemma4AssistantDraftModel` — pre/post projections, optional
  `lm_head` (absent when `tie_word_embeddings=true`), bind-time
  references to the target's `embed_tokens` and `embed_scale`, and
  the `draftBlock(...)` round-loop. `bind(target:)` dispatches via
  `as? Gemma4` — only the top-level VLM conforms to `LanguageModel`,
  so the three-level walk in mlx-vlm's Python `bind` collapses to a
  single cast in Swift.

- `forwardHidden(...)` is exposed at `@_spi(Testing) public` scope so
  fixture-parity tests can compare per-call activations against
  Python without going through the autoregressive `draftBlock`.

Tests in `Tests/MLXLMTests/Gemma4AssistantDraftModelTests.swift`
cover config decoding, sanitize behavior, mock-protocol conformance,
weight loading from the 31B-assistant-bf16 checkpoint (Rung 1), and
byte-identical activation parity with the `tools/fixtures/
drafter_forward/*.safetensors` Python references (Rung 2/3, `rtol=
1e-3, atol=1e-3`). Checkpoint-gated tests skip via `XCTSkip` when the
HF snapshot isn't present locally.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`RESEARCH-NOTES.md` answers the architectural questions A–P from the
PLAN with file:line citations from HF Transformers and mlx-vlm at the
pinned SHA `d49d428`. Includes the exhaustive 48-key `safetensors`
weight inventories for both the 31B-assistant-bf16 and 26B-A4B-
assistant-bf16 reference checkpoints, which the Swift
`@ModuleInfo(key:)` annotations were designed against.

`tools/inspect_drafter_layout.py` is the Python helper that dumps the
checkpoint weight-key inventory (the script that produced the answer
to question N).

`tools/generate_mtp_fixtures.py` is the fixture-generation script
that produces the four fixture suites:

- `tools/fixtures/masks/` (33 cases) — bidirectional and SWA mask
  references at `queryLen × kvLen × windowSize` grid points.
- `tools/fixtures/drafter_forward/` (5 cases) — drafter-only forward
  references for `last_hidden` and `logits` activation parity.
- `tools/fixtures/drafter_block/` (3 cases) — drafter `draftBlock`
  end-to-end token references at `blockSize ∈ {2, 4, 6}`, greedy.
- `tools/fixtures/end_to_end/` (2 cases) — full target+drafter token-
  ID sequences for Rung 4 token-parity verification.

Fixtures total 43 files / 20 MB. All four suites have been
regenerated cleanly after the `_forward_hidden` NaN bug fix (the
script now calls `ctx.drafter.set_shared_kv(...)` before invoking the
drafter for `drafter_forward` cases, mirroring the block path that
already did so). `FIXTURE-SCHEMA.md` and `FIXTURE-MANIFEST.json` in
`tools/fixtures/` document the per-suite schemas and metadata.

Acceptance rates at temperature=0 for the two `end_to_end/` cases
land at 0.944 (constrained-completion prompt) and 0.627 (open-content
prompt), both well above the PLAN §11 production floor of 0.30.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The fixture-generation script in `tools/generate_mtp_fixtures.py`
depends on a uv-managed Python environment. The corresponding
project files (`.python-version`, `pyproject.toml`, `uv.lock`,
`main.py`, `.venv/`) live at the repo root for developer convenience
but reference an absolute path to a local mlx-vlm checkout
(`/Users/.../mlx-vlm`) and are not reproducible across machines.
Gitignore them so they don't leak into commits.

`tools/generate_mtp_fixtures.py` documents the regeneration recipe;
contributors who want to rerun the script can recreate the uv
environment from the script's docstring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Appends three public ``LMOutput/Key`` declarations to the foundation
API for MTP speculative decoding:

- ``mtpLastHiddenStatesKey`` — `Key<MLXArray>`. The target model
  writes its post-final-norm hidden state (pre-lm_head, pre-softcap)
  here on each forward call when the iterator opts in. The
  ``MTPSpeculativeTokenIterator`` reads it and threads it to the
  drafter's `draftBlock` as `lastHidden`.

- ``mtpSharedKVStatesKey`` — `Key<[String: (MLXArray, MLXArray)]>`.
  The target writes one `(keys, values)` tuple per `layer_type`
  (`"full_attention"`, `"sliding_attention"`) drawn from the last
  layer of each type. The iterator reads it and threads it to the
  drafter as `sharedKV`.

- ``mtpEmitFlagKey`` — `Key<Bool>`. The iterator sets this on the
  ``LMOutput/State`` it passes into the main model on each call to
  opt the target into emitting the two state-output keys above. An
  absent key reads as `nil` (treated as `false`), so non-MTP callers
  are unaffected and the protocol ABI is preserved — no new
  parameter on ``LanguageModel/callAsFunction(_:cache:state:)`` is
  required.

Public scope is required because the writer (target's model file in
MLXVLM) and reader (iterator in MLXLMCommon) live in different
modules. The single-model file-private `LMOutput.Key` pattern used by
`GlmOcr.swift` and `Qwen35.swift` would not work here.

Tests in `Tests/MLXLMTests/MTPDrafterModelTests.swift` cover key
round-trips for each declared key, the absent-key-reads-as-nil
contract for the emit flag, and key distinctness on the same `State`.
Sample-element assertions force `MLXArray` eval and so depend on
the MLX metal library being loadable — works in Xcode test runs;
`swift test` from the CLI on M5 Pro hits a known
`Failed to load the default metallib` error during eval, which also
affects existing Phase A tests and is environmental rather than a
test defect.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the MTP speculative-decoding state-emit path through the
Gemma 4 target model. Three coordinated changes in `Gemma4.swift`:

1. `Gemma4TextBackbone.callAsFunction` gains an
   `emitDrafterState: Bool = false` parameter and returns a
   `(hidden, sharedKV?)` tuple instead of bare `MLXArray`. When the
   flag is true, after the final norm the function walks the per-layer
   `intermediates` from end backward, collecting the first `.regular`
   K/V pair encountered for each unique `layer_type`
   (`"full_attention"`, `"sliding_attention"`). Quantized cases are
   skipped — if both layer types can't be covered with regular K/V,
   the returned `sharedKV` is nil and the iterator falls back to
   single-token generation (documented R8/R13 limitation; quantized
   MTP is a follow-up PR).

2. `Gemma4TextLanguageModel.callAsFunction` gains the same parameter,
   destructures the new backbone tuple, and constructs the returned
   `LMOutput` with state populated only when `emitDrafterState=true`
   AND `sharedKV` is non-nil. Otherwise returns `LMOutput(logits:)`
   with state nil — preserving bit-identical behavior on the
   non-emit path.

3. `Gemma4.callAsFunction(_:cache:state:)` is added as an override of
   the `LanguageModel` protocol method (which would otherwise fall
   through to the default protocol-extension implementation that
   discards `state`). The override reads `mtpEmitFlagKey` from the
   incoming state — the iterator pre-populates this on every call —
   and threads through as `emitDrafterState`. ABI of the protocol
   method is unchanged; non-MTP callers passing `state: nil` (or
   `LMOutput.State()` without the flag) get exactly the prior
   behavior.

Tests in `Tests/MLXLMTests/Gemma4EmitDrafterStateTests.swift` cover:

- `testGemma4TextEmitFalseReturnsNoStateBySynthetic` — default and
  explicit `emit=false` return `LMOutput.state == nil`.
- `testGemma4TextEmitTrueWithBothLayerTypesPopulatesStateBySynthetic`
  — both keys populated with shapes matching the synthetic 2-layer
  config.
- `testGemma4TextEmitTrueWithMissingLayerTypeReturnsNilSharedKV` —
  1-layer-only config returns state nil (graceful incomplete-coverage).
- `testGemma4TextEmitDisabledIsBitIdenticalRegressionBySynthetic` —
  default-arg path and explicit `emitDrafterState: false` produce
  bit-identical logits.

Synthetic-config tests use random-initialized 2-layer
`Gemma4TextLanguageModel` instances built via
`@testable import MLXVLM` — no real Gemma 4 weights required, and
test runtime is sub-second per case in Xcode.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The round-loop iterator that drives MTP speculative decoding. Mirrors
the existing ``SpeculativeTokenIterator`` (`Evaluate.swift:733`) with
these structural differences:

- No `draftCache` or `draftY` — the drafter has no own KV cache and
  holds no transient token state between calls. Every per-round input
  (`lastToken`, `lastHidden`, `sharedKV`, `positionIds`) is threaded
  as a method argument.

- Drafter `bind(target:)` is called exactly once in `init`.
  ``MTPDrafterModel``'s contract specifies that bound references are
  read-only during eval (consistent with PR ml-explore#283's no-mutation
  invariant).

- A single ``MTPDrafterModel/draftBlock(...)`` call yields all `K-1`
  candidate tokens per round (not a `K`-step autoregressive loop).
  Position is constant for the round (`mainCache.offset`).

- Every call into the main model pre-populates its incoming
  ``LMOutput/State`` with ``mtpEmitFlagKey`` set to `true`, opting the
  target into emitting ``mtpLastHiddenStatesKey`` and
  ``mtpSharedKVStatesKey``. The iterator reads those keys back from
  the returned `state` and threads them to the next round's
  `draftBlock`.

- Sticky passthrough fallback when the target stops emitting drafter
  state. This handles R8 (quantized KV caches don't carry regular
  `(MLXArray, MLXArray)` tuples) and R13 (mid-generation quantization
  onset must not crash). Once `passthrough` is set, `next()` runs
  single-token generation against the main model only and the drafter
  is never invoked again.

`prepare(...)` runs the main model's prefill, then if drafter state
isn't present in the prefill output (because `LanguageModel.prepare`
doesn't currently thread state), runs one extra forward call with the
just-sampled bonus token and `mtpEmitFlagKey = true` to prime
`mainState`. Cost: one additional token's forward pass at startup;
acceptable.

The accept/reject + cache-trim hot path is structurally identical to
`SpeculativeTokenIterator.speculateRound` (`Evaluate.swift:891-918`),
with `numDraft = blockSize - 1` and the draft-cache trim line
removed.

Tests in `Tests/MLXLMTests/MTPSpeculativeTokenIteratorTests.swift`:

- `testMTPSpeculateRoundSmokeWithSynthetics` — full smallest-unit-of-work
  test with mock main model and drafter; verifies one round of
  speculation produces the expected accept-prefix + correction.
- `testMTPIteratorInitCallsBindOnce` — `bind(target:)` invariant.
- `testMTPIteratorMissingStateFallsBackToPassthrough` — drafter is
  never invoked when target omits state; iterator completes via
  single-token fallback.
- `testMTPIteratorPendingBufferDrainOrder` — accepted tokens are
  yielded in main-model order, not drafter-prediction order.

CLI `swift test` runs hit the environmental
`Failed to load the default metallib` error on the first MLX-kernel
eval (same as existing Phase A tests); test logic is verifiable in
Xcode.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires drafters into the loading pipeline. Three new files:

`Libraries/MLXLMCommon/MTPDrafterModelFactory.swift`:

- `MTPDrafterTypeRegistry` — enum holding a shared
  `ModelTypeRegistry<any MTPDrafterModel>`. Empty at bootstrap; downstream
  modules register their drafter types via `await registerModelType(...)`
  at app launch.
- `MTPDrafterRegistry` — `AbstractModelRegistry` subclass with the two
  reference checkpoint configurations:
  `mlx-community/gemma-4-26B-A4B-it-assistant-bf16` and
  `mlx-community/gemma-4-31B-it-assistant-bf16`.
- `MTPDrafterModelFactory` — `GenericModelFactory` with `ContextType =
  MTPDrafterContext` and `ContainerType = MTPDrafterContainer`. `_load`
  reads `config.json`, instantiates via `typeRegistry.createModel(...)`,
  calls `loadWeights(...)` (which routes through the drafter's
  `sanitize`), and returns the context. No tokenizer is loaded — drafters
  borrow their target's tokenizer.

`Libraries/MLXVLM/Gemma4AssistantRegistration.swift`:

- `Gemma4AssistantRegistration.register()` — `async` (because
  `ModelTypeRegistry` is an actor) registration of the
  `"gemma4_assistant"` model type pointing at the
  `Gemma4AssistantDraftModel` initializer.

The MLXLMCommon-side registry can't seed itself with the
`gemma4_assistant` creator because the implementation type lives in
MLXVLM — importing it into MLXLMCommon would form a circular
dependency. Documented in the type-registry doc-comment.

Tests in `Tests/MLXLMTests/MTPDrafterModelFactoryTests.swift`:

- `testGemma4AssistantRegistrationRegistersType` — registration round-
  trip; `createModel(...)` returns a `Gemma4AssistantDraftModel`.
- `testMTPDrafterTypeRegistryUnknownModelTypeThrows` — confirms an
  unknown model type throws `ModelFactoryError.unsupportedModelType`.
- `testMTPDrafterRegistryContainsBothReferenceCheckpoints` — both 26B-A4B
  and 31B configs registered.
- `testMTPDrafterRegistrySharedStaticAccessors` — static accessor names
  align with their HF IDs.
- `testMTPDrafterFactoryLoadFromDirectoryWhenCheckpointPresent` —
  checkpoint-gated end-to-end load via `factory.loadContainer(...)`.

The non-checkpoint-dependent tests pass cleanly from `swift test` CLI
(no MLX kernel eval required).

PLAN correction noted: registration is async, and the method is named
`registerModelType` (not `register`); PLAN v3.1 §8's sketch shows
synchronous `.shared.register(...)` which was incorrect. Risk R10 is
moot — the public registration entry point already exists at
`Libraries/MLXLMCommon/Registries/ModelTypeRegistry.swift:20`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ve decoding

Public entry points that drive MTP speculative decoding. Append two
overloads to ``Libraries/MLXLMCommon/Evaluate.swift`` mirroring the
existing `draftModel`-taking speculative overloads (lines 1424-1455,
1566-1594):

- `generate(input:cache:parameters:context:mtpDrafter:blockSize:wiredMemoryTicket:)`
  -> `AsyncStream<Generation>`. Yields chunks with tool-call parsing
  via ``TextToolTokenLoopHandler``.

- `generateTokens(input:cache:parameters:context:mtpDrafter:blockSize:wiredMemoryTicket:)`
  -> `AsyncStream<TokenGeneration>`. Yields raw token IDs via
  ``RawTokenLoopHandler``.

Both delegate to ``MTPSpeculativeTokenIterator`` and ``generateLoopTask``.
`blockSize` defaults to 4 (mirrors mlx-vlm's example configs; HF model
cards also use 6 — callers can override).

The MTP `generate` overload is disambiguated from the existing classic-
speculative overload by parameter name: `mtpDrafter` vs `draftModel`.
Both default `blockSize` and `numDraftTokens` to small values so
callers don't strictly need to specify them; the call sites are still
recommended to be explicit.

Tests in `Tests/MLXLMTests/MTPGenerateAPITests.swift` cover the public
surface:

- `testMTPGenerateOverloadIsCallableSurface` and
  `testMTPGenerateTokensOverloadIsCallableSurface` — compile-time
  checks that the function signatures exist with the documented param
  order and types.
- `testMTPGenerateUsesBlockSizeDefaultOfFour` — confirms the function
  is callable without supplying `blockSize` (the default applies).

All three pass cleanly from `swift test` CLI (no MLX kernel eval).
End-to-end stream-yields-tokens validation lives in the verification
suite (`MTPRung4TokenParityTests`, `MTPAcceptanceRateTests`), which
runs against real Gemma 4 checkpoints when available.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…t tests

Verification suite for the full MTP speculative-decoding pipeline.

`Tests/MLXLMTests/MTPRung4TokenParityTests.swift`:

- Three checkpoint-gated tests that load `Gemma4AssistantDraftModel`
  from the 31B-assistant-bf16 checkpoint and run `draftBlock(...)` with
  fixture inputs from `tools/fixtures/drafter_block/case_0{1,2,3}_block{2,4,6}.safetensors`.
  Assert bit-identical token-ID parity with Python reference. PLAN
  §11 Rung 4 is bit-exact: greedy = argmax = deterministic, no
  tolerance.

`Tests/MLXLMTests/MTPAcceptanceRateTests.swift`:

- `testAcceptanceRateFloor64TokenBlock4Temp0` documents the PLAN §11
  / R12 floor of >= 0.30 acceptance rate. Gates on the presence of
  both 31B-assistant-bf16 drafter and 31b-it-8bit target checkpoints.
  The full target+drafter integration requires
  `#huggingFaceTokenizerLoader()` from MLXHuggingFace (not currently
  in MLXLMTests' dependency closure), so the test records the
  remaining-work scope and skips. The acceptance-rate measurement
  itself runs in a downstream app/integration test where the tokenizer
  loader is wired in.

`Tests/MLXLMTests/MTPQuantizationOnsetTests.swift`:

- `testMTPMidGenerationKVQuantizationCompletesWithoutCrash` documents
  the PLAN R13 verification plan: with `kvBits=4, quantizedKVStart=32`
  the main cache transitions to `QuantizedKVCache` mid-generation, the
  target's emit-hook returns `sharedKV: nil`, and the iterator's
  passthrough fallback engages. The passthrough fallback logic itself
  is unit-tested in
  `MTPSpeculativeTokenIteratorTests.testMTPIteratorMissingStateFallsBackToPassthrough`
  with synthetic state. The full-target end-to-end path is skipped
  for the same MLXHuggingFace-dependency reason and recorded as
  remaining integration work.

Rung 4 tests pass cleanly in Xcode against the 31B drafter checkpoint
when present. CLI `swift test` runs hit the environmental
`Failed to load the default metallib` error on the first MLX kernel
eval (same as all other Phase A tests with real-checkpoint paths).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@angelsbrood

Copy link
Copy Markdown
Contributor Author

For future readers: this PR was auto-closed when lmoutput-state was deleted on merge of #283. Continued at #308.

div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
… TF32 (the resource lookup half landed in ml-explore#298)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants