Repository navigation
Add Gemma 4 MTP speculative decoding - #293
Closed
angelsbrood wants to merge 13 commits into
Closed
angelsbrood wants to merge 13 commits into
angelsbrood wants to merge 13 commits into
Conversation
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>
3 of 4 tasks
davidkoski
force-pushed
the
lmoutput-state
branch
from
May 18, 2026 15:58
ecefa4e to
706256b
Compare
davidkoski
force-pushed
the
lmoutput-state
branch
from
May 22, 2026 00:17
318a4b6 to
0e8d58f
Compare
3 of 4 tasks
Contributor
Author
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>
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.
Proposed changes
Adds Gemma 4 Multi-Token Prediction (MTP) speculative decoding. Introduces an
MTPDrafterModelprotocol in MLXLMCommon refiningBaseLanguageModel, registersgemma4_assistantas the first concrete drafter implementation, threads cross-model state through three publicLMOutput.Keydeclarations, and adds anMTPSpeculativeTokenIteratorparallel to the existingSpeculativeTokenIterator. Tracks #279.Opening as a draft against
lmoutput-statebecause the implementation depends on #283's typed-keyLMOutput.StateAPI. Will rebase tomainonce #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 newMTPDrafterModelprotocol inLibraries/MLXLMCommon/MTPDrafterModel.swiftrefinesBaseLanguageModel(so weight loading and sanitize hooks are inherited) and defines its own forward signature. Drafters are loaded viaMTPDrafterModelFactory, registered intoMTPDrafterTypeRegistry, and driven byMTPSpeculativeTokenIterator.Cross-model state passthrough uses three public
LMOutput.Keydeclarations in MLXLMCommon:mtpEmitFlagKey: Bool,mtpLastHiddenStatesKey: MLXArray, andmtpSharedKVStatesKey: [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-levelGemma4.callAsFunction(_:cache:state:)override reads the flag and threads it through to the backbone, which writes the last-layer hidden state and per-layer_typeshared K/V into the state on the way out. The emit flag is itself aLMOutput.Key<Bool>rather than a function parameter becauseLanguageModel.callAsFunction(_:cache:state:)has a fixed protocol signature; threading the flag throughLMOutput.Stateunifies the mechanism — the state-bag carries both tensor payloads and the control signal that triggers them.MTPSpeculativeTokenIteratorincludes a sticky passthrough fallback. When the target's emit hook returnsnilshared K/V — which happens once quantization onset converts the regular K/V cache toQuantizedKVCache, 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 akvSharedOnly: Boolflag onGemma4TextAttention.init(which skips construction ofkProj/vProj/kNorm/vNorm, declared Optional@ModuleInfo) let the drafter compose its own decoder layers from existing target-side modules.Gemma4.swiftdiff: +53/−26. The non-kvSharedOnlyregression 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:
generateLoopTaskandTokenLoopHandlerfromprivatetointernalto reuse the existing generation infrastructure, and exposes pre-logit hidden states via a newforwardMTP()method onGemma4TextModel. This PR consumes theLMOutput.StateAPI from models should not mutate state during eval #283 instead, threading drafter state through the dictionary-backed typed-key state-bag (threeLMOutput.Keydeclarations, 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.mlx-vlm@d49d428with 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.The masked-embedder path is the dimension on which #269 has more implemented than this PR; conversely this PR carries the empty-checkpoint
fatalErrorstub 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 atangelsbrood/gemma4-mtp-fixtures— 43 files / ~20 MB, generated against target=mlx-community/gemma-4-31b-it-8bitand drafter=mlx-community/gemma-4-31B-it-assistant-bf16. The same 43-file fixture set is vendored in-repo attools/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:
RESEARCH-NOTES.mdmatches the checkpoint verbatim across both 31B and 26B-A4B drafter siblings (48 keys each, identical layout, shapes differ).atol=1e-3, rtol=1e-3.draftBlocklogits match Python fixtures at the same tolerance.draftBlockat 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 testCLI is not a working verification surface for this repository —CONTRIBUTING.mdnotes "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 inMLXLMTestswithIssue.record+ early-return because they requireMLXHuggingFace's#huggingFaceTokenizerLoader()which is not inMLXLMTests' dependency closure; the full end-to-end measurement will live in a downstream integration test.Files
New:
Libraries/MLXLMCommon/MTPDrafterModel.swift—MTPDrafterModelprotocol,MTPDrafterContext,MTPDrafterContainer, three publicLMOutput.KeydeclarationsLibraries/MLXLMCommon/MTPSpeculativeTokenIterator.swift— iterator with sticky passthrough fallbackLibraries/MLXLMCommon/MTPDrafterModelFactory.swift—MTPDrafterTypeRegistry,MTPDrafterRegistry,MTPDrafterModelFactoryLibraries/MLXLMCommon/BidirectionalMasks.swift—createBidirectionalMaskandcreateBidirectionalSlidingWindowMaskhelpersLibraries/MLXVLM/Models/Gemma4Assistant.swift—Gemma4AssistantConfiguration,Gemma4AssistantMaskedEmbedder,Gemma4AssistantDraftInner,Gemma4AssistantDraftModelLibraries/MLXVLM/Gemma4AssistantRegistration.swift—registerModelTypecall 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.swiftRESEARCH-NOTES.md— architectural Q&A with file:line citations against canonical Python (HF Transformersgemma4_assistant, mlx-vlm drafter), plus full 48-key weight inventories for both reference drafter checkpointstools/inspect_drafter_layout.py,tools/generate_mtp_fixtures.pytools/fixtures/— 43 fixture data files (~20 MB) plusFIXTURE-SCHEMA.mdandFIXTURE-MANIFEST.json. Vendored in-repo so the Rung 1–4 tests run offline against a frozen reference; content is byte-identical to theangelsbrood/gemma4-mtp-fixturesHF dataset for cross-verification.Modified:
Libraries/MLXLMCommon/Evaluate.swift— two newgenerate(...)overloads (one returningAsyncStream<Generation>, one returningAsyncStream<TokenGeneration>), taking anmtpDrafterparameter,blockSize: Int = 4defaultLibraries/MLXVLM/Models/Gemma4.swift— visibility bumps on internal building blocks (the cascade reached 16 symbols onceGemma4TextLanguageModel,Gemma4TextBackbone, thelanguageModelaccessor, and four MLP/router types were pulled along by what they reference),kvSharedOnly: Boolflag onGemma4TextAttention.init, emit hooks inGemma4TextBackbone.callAsFunctionandGemma4TextLanguageModel.callAsFunction, new top-levelGemma4.callAsFunction(_:cache:state:)override (+53/−26)Supported model pairs
mlx-community/gemma-4-31b-it-8bitmlx-community/gemma-4-31B-it-assistant-bf16mlx-community/gemma-4-26B-A4B-it-bf16mlx-community/gemma-4-26B-A4B-it-assistant-bf16mlx-community/gemma-4-31B-it-bf16mlx-community/gemma-4-31B-it-assistant-bf16E-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-bf16siblings on themlx-communityorg.Known limitations
Gemma4AssistantMaskedEmbedder.callAsFunctionis afatalErrorstub. Both reference checkpoints haveuse_ordered_embeddings=falseand ship with zeromasked_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. ChoosingfatalErrorover an unverified implementation matches the verification posture of the rest of the PR._speculative_walk_batchis out of scope.MLXLMTestspendingMLXHuggingFacein the test target's dependency closure. The passthrough fallback logic itself is unit-tested with synthetic state.Checklist
pre-commit run --all-filespassesAcknowledgments
Thanks to @davidkoski for #283 — the typed-key
LMOutput.StateAPI is the foundation this PR builds on; without it, the cross-model state passthrough would have required something much uglier.References
angelsbrood/gemma4-mtp-fixturesgemma4_assistant, mlx-vlmspeculative/drafters/gemma4_assistantat SHAd49d428