Repository navigation
Add Gemma 4 MTP speculative decoding - #308
Conversation
|
@angeloskath — I don't have the org permissions to formally request reviews on this repo, so I'm pinging here. The PR description's Status block also cc's @davidkoski (per a prior thread). Would appreciate your eyes on this when convenient. |
|
FYI @joelnishanth (#269) and @john-rocky (#267) -- these are all efforts and landing gemma4 MTP. I am inclined to go with #308 as I think not introducing a new type of model evaluation is better. The MTP and base model are already tightly coupled, so using the State + keys seems like a reasonable approach to manage the out-of-band communication. We can only land one of these, so if you think there are things missing here please comment or coordinate with @angelsbrood to incorporate. Thank you! |
…m HF dataset Per davidkoski's review on ml-explore#308: the 43 `tools/fixtures/*.safetensors` data files were vendored in-repo so the Rung 1–4 / mask parity tests could run offline. The PR review flagged both the file size and the "integration-style" placement. This commit removes the vendored data and moves the fixture-anchored tests into the existing IntegrationTesting Xcode project (introduced in ml-explore#142, hosts integration tests that fetch real models from HF rather than running on CI). Moved files (entire, no edits beyond fixture rewiring): - `BidirectionalMasksTests.swift` — 8 mask-parity tests - `MTPRung4TokenParityTests.swift` — 3 drafter token-parity tests - `MTPAcceptanceRateTests.swift` — 1 placeholder (full impl deferred) - `MTPQuantizationOnsetTests.swift` — 1 placeholder (full impl deferred) Each moved file now: - Imports `IntegrationTestHelpers` and uses the `downloadDataset(...)` helper added in the previous commit. - Pins the fixture revision to `ae79d3536d023d1fd0db4fa829c1d29adadf7bd1` (the "Initial MTP fixtures, mlx-vlm@d49d428, target=31b-8bit, drafter=31B-bf16" commit on https://huggingface.co/datasets/angelsbrood/gemma4-mtp-fixtures). - Preserves the existing `Issue.record(...)` skip-with-warning pattern for cases where the dataset or checkpoints aren't reachable. Deleted: all 43 `tools/fixtures/{masks,drafter_forward,drafter_block, end_to_end}/*.safetensors` files and the four now-empty subdirectories. Kept: `tools/fixtures/FIXTURE-SCHEMA.md`, `FIXTURE-MANIFEST.json`, `tools/generate_mtp_fixtures.py`, `tools/inspect_drafter_layout.py`, plus a new `tools/fixtures/README.md` pointing readers to the HF dataset and the pinned SHA. Schema, manifest, and generation tooling stay in-repo for reproducibility. `Gemma4AssistantDraftModelTests.swift` and `MTPDrafterModelFactoryTests .swift` mix synthetic-mock and checkpoint/fixture-gated cases; they are split in the next commit so the synthetic half stays in `MLXLMTests` for CI coverage. Verified locally: `swift build` clean, `xcodebuild build-for-testing -scheme IntegrationTesting` succeeds; the moved tests compile against the IntegrationTesting target. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
Thanks for the review. Both points addressed in
Two other things landed in this push:
Resolving both threads. Let me know if anything looks off. |
No worries, I will review. |
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>
The Rung 4 token-parity tests (MTPRung4TokenParityTests.swift) were
invoking Gemma4AssistantDraftModel.draftBlock without first calling
bind(target:), causing a precondition violation at runtime
("bind(target:) must be called before draftBlock"). The bind step
was missing from this test file since its introduction.
The fix loads mlx-community/gemma-4-31b-it-8bit as the target,
binds the drafter against it once per @suite lifetime (module-level
nonisolated(unsafe) cache + @suite(.serialized) so the three case
methods share one bound drafter), and routes all three case methods
through the bound drafter. Test path now mirrors the production
iterator (MTPSpeculativeTokenIterator.bind) exactly.
Cache requirement: both drafter (gemma-4-31B-it-assistant-bf16)
and target (gemma-4-31b-it-8bit) must be present in the HF cache
for Rung 4 to run; absence of either causes the test to record
an Issue and skip, matching the existing precedent for
checkpoint-gated tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three synthetic-mock iterator tests (testMTPSpeculateRoundSmokeWithSynthetics, testMTPIteratorMissingStateFallsBackToPassthrough, testMTPIteratorPendingBufferDrainOrder) seeded their `mainLogitTokens` with `99` as an inert placeholder for prefill positions whose logits the iterator never samples. But the mock's `makeLogits` writes `data[i * vocab + tok] = 100` for every position, and the mock's vocab is `20` — so `tok = 99` produced an out-of-bounds array index and crashed with `Swift/ContiguousArrayBuffer.swift:705: Fatal error: Index out of range` the moment any of these tests ran. The tests had never actually been executed before — same pre-existing-broken-test pattern as the Rung 4 token-parity tests (see prior commit). The production iterator code itself was correct; only the mock test scaffolding was defective. Fix: replace the `99` placeholders with `0` (valid vocab index; positions remain unsampled, so the semantic intent is unchanged). Comments updated to document the `< vocab` constraint on the mock's placeholder tokens. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
CI's Verify documentation step (run #26266924101) failed at docc convert for both MLXLMCommon and MLXVLM. DocC builds each module's documentation archive independently, so bare-name symbol links like ``LanguageModel`` in MLXVLM doc comments cannot resolve to symbols declared in MLXLMCommon. DocC's strict mode also disallows links from public-symbol doc comments to internal-visibility same-module symbols. This commit converts cross-module and internal-visibility ``Symbol`` links to inline `Symbol` formatting, and expands one same-module signature-mismatched link to its full parameter form. Full audit of ``...`` references in all touched files. Verified locally with scripts/verify-docs.sh prior to commit. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a public top-level `downloadDataset(repo:revision:matching:)` helper
that fetches files from a public Hugging Face dataset to a per-revision
local cache (`~/.cache/huggingface/integration-test-datasets/{repo}/
{revision}/`). Lists files via the HF tree API (`?recursive=true`) and
downloads matched files via the resolve endpoint; URLSession follows
redirects to the CDN automatically.
Mirrors the model-download cache-and-skip semantics of the existing
`Downloader`-injected helpers in this module: already-cached files are
reused without a second HTTP fetch, errors throw `IntegrationTestDataset
Error` for callers to catch and `Issue.record(...)` skip rather than
propagate.
Consumed by the migrated fixture-anchored MTP tests in the IntegrationTesting
Xcode project (subsequent commit) to replace in-repo `tools/fixtures/*.
safetensors` data files with on-demand fetch from `angelsbrood/gemma4-mtp-
fixtures`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…m HF dataset Per davidkoski's review on ml-explore#308: the 43 `tools/fixtures/*.safetensors` data files were vendored in-repo so the Rung 1–4 / mask parity tests could run offline. The PR review flagged both the file size and the "integration-style" placement. This commit removes the vendored data and moves the fixture-anchored tests into the existing IntegrationTesting Xcode project (introduced in ml-explore#142, hosts integration tests that fetch real models from HF rather than running on CI). Moved files (entire, no edits beyond fixture rewiring): - `BidirectionalMasksTests.swift` — 8 mask-parity tests - `MTPRung4TokenParityTests.swift` — 3 drafter token-parity tests - `MTPAcceptanceRateTests.swift` — 1 placeholder (full impl deferred) - `MTPQuantizationOnsetTests.swift` — 1 placeholder (full impl deferred) Each moved file now: - Imports `IntegrationTestHelpers` and uses the `downloadDataset(...)` helper added in the previous commit. - Pins the fixture revision to `ae79d3536d023d1fd0db4fa829c1d29adadf7bd1` (the "Initial MTP fixtures, mlx-vlm@d49d428, target=31b-8bit, drafter=31B-bf16" commit on https://huggingface.co/datasets/angelsbrood/gemma4-mtp-fixtures). - Preserves the existing `Issue.record(...)` skip-with-warning pattern for cases where the dataset or checkpoints aren't reachable. Deleted: all 43 `tools/fixtures/{masks,drafter_forward,drafter_block, end_to_end}/*.safetensors` files and the four now-empty subdirectories. Kept: `tools/fixtures/FIXTURE-SCHEMA.md`, `FIXTURE-MANIFEST.json`, `tools/generate_mtp_fixtures.py`, `tools/inspect_drafter_layout.py`, plus a new `tools/fixtures/README.md` pointing readers to the HF dataset and the pinned SHA. Schema, manifest, and generation tooling stay in-repo for reproducibility. `Gemma4AssistantDraftModelTests.swift` and `MTPDrafterModelFactoryTests .swift` mix synthetic-mock and checkpoint/fixture-gated cases; they are split in the next commit so the synthetic half stays in `MLXLMTests` for CI coverage. Verified locally: `swift build` clean, `xcodebuild build-for-testing -scheme IntegrationTesting` succeeds; the moved tests compile against the IntegrationTesting target. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…esting Two test files in `Tests/MLXLMTests/` mixed synthetic-mock cases (no fixture or checkpoint dependency, CI-runnable) with checkpoint or fixture-gated cases. Splitting keeps the synthetic half in `MLXLMTests` so they continue to run on CI, and moves the integration half into the IntegrationTesting Xcode project alongside the four files moved in the previous commit. `MTPDrafterModelFactoryTests.swift`: - Stays in `Tests/MLXLMTests/`: `testGemma4AssistantRegistrationRegistersType`, `testMTPDrafterTypeRegistryUnknownModelTypeThrows`, `testMTPDrafterRegistryContainsBothReferenceCheckpoints`, `testMTPDrafterRegistrySharedStaticAccessors`. - New `MTPDrafterModelFactoryIntegrationTests.swift` in `IntegrationTesting/IntegrationTestingTests/`: `testMTPDrafterFactoryLoadFromDirectoryWhenCheckpointPresent` plus the `NoOpTokenizerLoader` helper it consumes. `Gemma4AssistantDraftModelTests.swift`: - Stays in `Tests/MLXLMTests/`: 4 synthetic tests (config JSON decode, `sanitize` behavior under tied/untied embeddings, instantiation shape) plus the `syntheticConfig(...)` helper. Drops the `@_spi(Testing) import MLXVLM` since `forwardHidden` (the only SPI-Testing symbol) is no longer referenced here. - New `Gemma4AssistantDraftModelIntegrationTests.swift` in `IntegrationTesting/IntegrationTestingTests/`: the 3 checkpoint or fixture-gated tests (`testGemma4AssistantConfigurationDecodesRealCheckpoint`, `testRung1WeightsLoadFrom31BCheckpoint`, `testRung2And3ForwardMatchesFixture31BCase01`), with the Rung 2/3 forward parity test rewired to fetch fixtures via `downloadDataset(...)` from the pinned HF dataset and the `Gemma4AssistantDraftModel. forwardHidden(...)` SPI re-imported under `@_spi(Testing)`. Verified locally: `swift build --build-tests` compiles `MLXLMTests` and all dependent targets clean; `xcodebuild build-for-testing -scheme IntegrationTesting` compiles all moved + new integration test files. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three Phase 2-gate findings, addressed together because they all surface
"the moved tests must run cleanly under the IntegrationTesting Xcode
project's test runner":
1. **`@Test(.disabled(...))` for placeholders.** `MTPAcceptanceRateTests`
and `MTPQuantizationOnsetTests` previously ended with an
`Issue.record("intentionally skipped: ...")` after passing their
checkpoint guards. Swift Testing 1902 treats `Issue.record` as a
failure, not a skip — so when run via `xcodebuild test` (which can
load the MLX metallib, unlike `swift test` CLI) both placeholders
showed as failures rather than the intended skip. Replace the
sentinel `Issue.record` with the `.disabled(reason:)` trait so the
tests report cleanly as skipped with the documented deferral reason.
2. **`@Suite(.serialized) struct Gemma4AssistantIntegrationTests`.** The
three checkpoint/fixture-gated tests in
`Gemma4AssistantDraftModelIntegrationTests.swift` each load the same
31B drafter checkpoint. Run in parallel (Swift Testing default), the
simultaneous `loadWeights(...)` calls produced non-deterministic
numeric divergence in the Rung 2/3 `forwardHidden` parity assertion
(atol=1e-3, rtol=1e-3 breach against the byte-identical fixture).
Wrapping in a `@Suite(.serialized)` struct serializes weight loads
in this file; combined with the existing `@Suite(.serialized) struct
Rung4TokenParityTests`, all three integration test files that load
the drafter now serialize independently.
3. **Bump `fixturesRevision` to `152a8ea4cd9e58da11b0c4b39542d3ad347fce06`.**
The previously pinned `ae79d35...` commit on
`angelsbrood/gemma4-mtp-fixtures` (uploaded 2026-05-13) predated a
later local regeneration of the `drafter_forward/*.safetensors`
fixtures vendored into this branch on 2026-05-21 in `135ef0f`. All 5
`drafter_forward/*` files differed between HF and vendored;
`drafter_block/*`, `masks/*`, `end_to_end/*` matched. Re-uploaded the
newer vendored bytes to HF (commit 152a8ea4...) so the pinned
revision is byte-identical to what previously ran from
`tools/fixtures/`; SHA-256 verified across all 5 files post-upload.
Verified locally via `xcodebuild test`: 15 PASSED + 2 documented
SKIP (.disabled), 0 FAILED, ~6.5s elapsed. Rung 2/3 forward parity
passes byte-identically to the fixture; Rung 4 bit-exact parity
continues to pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three single-line formatting normalizations applied by `pre-commit run --all-files` (swift-format hook): - `IntegrationTestHelpers.swift`: spaced range operator `a ..< b` - `BidirectionalMasksTests.swift`: indented argument continuation - `Gemma4AssistantDraftModelIntegrationTests.swift`: indented array literal Pure style; no semantic change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The MTP iterator was slicing `lastHidden[0..., (-1)..., 0...]` unconditionally on each round — the LAST verify position. mlx-lm Python uses `verify.hidden[:, accepted : accepted + 1, :]` instead, picking the slot that produced the newly-accepted bonus's prediction. The two slices coincide only when `accepted == numDraft` (all drafts accepted); when `accepted < numDraft` the drafter receives hidden from too-far-forward in the verify sequence, silently producing less coherent drafts. The bug's per-round cost compounds over rounds, biting hardest at higher blockSize and longer streams. Track `accepted` across rounds via a new `lastRoundAccepted: Int?` ivar (nil on round 1 → slice last position, matching mlx-lm's round-1 semantic of using the last prompt position; set at end of each `speculateRound()`). The drafter now receives the bonus-slot hidden via the `bonusSlotHidden` parameter. sharedKV is intentionally unchanged: its seq dim is cumulative cache size, not verify-input size, so the existing unsliced pass-through is correct. davidkoski raised this in PR ml-explore#308 review (2026-06-07 comment 1); the sharedKV portion of his hypothesis did not apply on inspection. Empirical impact at temp=0 sky-blue on 31B (gemma-4-31b-it-8bit target + gemma-4-31B-it-assistant-bf16 drafter): bs=4 maxTokens=32: 54.3% → 72.4% (+18.1pp), 13.14 → 15.68 tok/s bs=4 maxTokens=64: 32.3% → 60.6% (+28.3pp), 9.66 → 13.64 tok/s bs=6 maxTokens=64: 17.9% → 29.8% (+11.9pp), 7.10 → 8.60 tok/s The fix's effect grows with stream length at bs=4 — the bug's per-round cost accumulates over rounds, exactly as the mechanism predicts. bs=6 lifts less in absolute terms because the drafter's K=5 per-round multi-token prediction has structural limits beyond the slice fix. Byte-identity at temp=0 is preserved across rainbows, Swift, and sky-blue prompts at maxTokens=32 (the regime where MLX SDPA shape-determinism keeps verify-position predictions aligned with autoregressive baseline). The 64- token prefix-identity in `testMTP31BLongerStreamProducesValidContinuation` also still holds; the empirical SDPA-divergence boundary is unchanged. Adds two acceptance-rate floor tests in MTPIteratorEndToEndDiagnosticTests: `testMTP31BBlockSize4AcceptanceLifted` (rate ≥ 0.45 at bs=4 mt=64, pre-fix 32.3% + ~13pp headroom) and `testMTP31BBlockSize6AcceptanceLifted` (rate ≥ 0.25 at bs=6 mt=64, pre-fix 17.9% + ~7pp headroom). Both demonstrate the fix's mechanism rather than just speculation activity. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`Gemma4AssistantDraftModel.bind(target:)` mutated three ivars (`boundInput‐ Embed`, `boundEmbedScale`, `boundTargetLayerTypes`) without any locking, making drafter instances unsafe to share across iterators. davidkoski raised this in PR ml-explore#308 review (2026-06-07 comments 2/3/7), offering two options: parameter-pass target through `draftBlock(...)` or have `bind()` return a new instance. Took option A — parameter-passing. Protocol change: - Remove `bind(target:)` from `MTPDrafterModel` - Add `target: any LanguageModel` as the first parameter of `draftBlock(...)` - Update protocol docstring: conformers must be stateless wrt target, must not retain references derived from `target` Conformer change (Gemma4AssistantDraftModel): - Remove `boundInputEmbed`, `boundEmbedScale`, `boundTargetLayerTypes` ivars (the third was confirmed dead via grep — written by bind, never read) - Remove `bind(target:)` implementation - Inline-derive `inputEmbed` and `embedScale` from `target` at the top of `draftBlock(target:...)` via one guard-cast + two property accesses. Per- round overhead is negligible (`bs=4 mt=64` tok/s = 14.03, within run-to-run variance of pre-fix 13.64-14.23 measured in Phase A; R-K9 cleared). Iterator change: - Remove `drafter.bind(target: mainModel)` from `init` - Pass `target: mainModel` to `drafter.draftBlock(...)` in `speculateRound()` - Update top-of-file docstring: drafter holds no target-derived state Test surface: - `MockDrafter`/`MockMTPDrafter`: drop `bindCallCount` ivar + `bind(target:)` method; add `target:` to `draftBlock` signature - Delete `testMTPIteratorInitCallsBindOnce` — the "bind-once" contract no longer exists - Remove `#expect(drafter.bindCallCount == 1)` from the iterator plumbing test - Update `testMTPDrafterModelProtocolShape` to drop bind call + assertion, add `target:` to `draftBlock` call - `MTPRung4TokenParityTests`: remove `drafter.bind(target: target)` from `loadRung4Drafter`; pass `target: bound.target` in `draftBlock` call - Stale doc/comment references to `bind(target:)` in Evaluate.swift's `generate(...)` overload and two test files: updated to the new contract Empirical validation: - All 7 active end-to-end MTP tests pass (3 byte-identity, 64-token prefix- identity, quantization-onset, baseline-self-determinism, basic acceptance) - 3 Rung4 token-parity tests pass against Python fixtures (bs=2, bs=4, bs=6) - Acceptance counts bit-identical to Phase A's post-fix run (40/66 at bs=4 mt=64, 36/121 at bs=6 mt=64): the inline derivation produces equivalent drafter inputs to the prior bound-ivars path Net: -41 lines across 8 files. Drafter instances are now safe to share across iterators by construction (no target-derived mutable state remains). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…verify-loop local-copy idiom The MTP iterator's `speculateRound()` already enforces the invariant that the canonical `self.processor.didSample(token:)` fires only for emitted tokens — accepted drafts + the correction at the rejection point. Verify- loop sampling happens on a local copy (`var verifyProcessorCopy = processor`) whose `didSample` mutations stay scoped to that loop via Swift struct value semantics, so rejected-draft sampling never pollutes cross-round state. davidkoski raised a concern in PR ml-explore#308 review (2026-06-07 comment 6) about the verify-loop sampling potentially polluting LogitProcessor state with rejected tokens. On inspection the concern doesn't materialize: the LogitProcessor protocol's four production conformers (RepetitionContext, PresencePenaltyContext, FrequencyPenaltyContext, PenaltyProcessor) are all `struct`s, so the `var` capture in the verify loop produces a true value-copy. The mechanism was just subtle enough at the read site that the load-bearing response is a regression test + code-clarity rename, not a behavioral refactor. (Refactoring the verify loop to remove the local-copy idiom would have introduced a new latent approximation: intra-round verify-position sampling would lose `process()` evolution against in-round prior samples, weakening main's "ground truth" semantics. The current behavior is correct as-is.) Two new regression tests lock the invariant in as executable contract: 1. `MTPSpeculativeTokenIteratorTests.testMTPVerifyLoopDidSampleStaysScoped` `ToLocalCopy` (CI-scoped, synthetic): constructs a real iterator with `MockMainModel` + `MockDrafter`, installs an `EmissionLog` probe via `_setProcessorForTesting`, drains 3 tokens (prepare bonus + accepted draft + correction at the rejection point), and asserts the probe recorded exactly [accepted_draft, correction] — NOT the 4 verify- position samples. If a regression ever removes the local-copy idiom, the probe would grow [9, 1, 2] entries from the rejected positions. 2. `MTPIteratorEndToEndDiagnosticTests.testMTPLogitProcessorReceives` `OnlyEmittedTokens` (end-to-end against 31B target+drafter): constructs the iterator directly, installs an EmissionLog probe, drains the 32-token sky-blue stream, asserts log size is within tight bounds of emitted size (`emitted - 2 ≤ log ≤ emitted + blockSize`) — catches a ~2× regression from verify-loop leakage at this acceptance rate. Includes a content-overlap check that detects the prepare-bonus offset and verifies overlapping prefix matches emitted positionally. Test infrastructure additions: - `MTPSpeculativeTokenIterator._setProcessorForTesting` / `_processorForTesting` accessors at `@_spi(Testing)` scope. Lets regression tests install a recording probe AFTER `init()` — `init` calls `prepare()` which consumes the prepare-time bonus via `processor?.didSample` before any probe could be observable. Code-clarity rename (no behavioral change): - `var verifyProcessor = processor` → `var verifyProcessorCopy = processor` in `speculateRound()`, with a comment block above the binding explaining the local-copy "why": process() may mutate processor state via Swift struct value semantics, but those mutations stay scoped to the verify loop. Canonical state is updated only by the accept loop below. Reply text for koski's comment 6 (Director-drafted, staged for Phase G): > Looked into this carefully. The verify loop uses `var verifyProcessor = > processor`, which by Swift's struct value semantics is a local copy — > mutations to `verifyProcessor.didSample` don't propagate to > `self.processor`. The canonical processor state at `self.processor` only > receives `didSample` calls from the accept loop, which runs over the > actually-emitted tokens (accepted drafts + bonus). So state pollution > from rejected tokens doesn't occur. The pattern is subtle and easy to > misread; added a CI-scoped recording-processor regression test in > <SHA-C> that asserts this invariant directly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…() stall Two problems were entangled in the drafter's positionIds plumbing: 1. `Gemma4AssistantDraftModel.forwardHidden` recovered the position offset via `Int(positionIds[0, 0].item(Int32.self))`, then passed it to the layer as `offset: Int`. `.item()` forces a GPU sync; this fired K-1 times per speculation round inside `draftBlock`'s autoregressive loop, stalling the drafter for no reason — the layer's RoPE path takes an `Int` offset and never needed the `MLXArray` shape. davidkoski flagged the stall in PR ml-explore#308 review (2026-06-07 comment 5). 2. The `createBidirectionalSlidingWindowMask` helper's docstring claimed the dominant MTP case was `queryLen == 1, query_offset == 0` and that non-zero `query_offset` paths "should build the mask inline." On inspection the dominant case actually has non-zero `query_offset` (it equals the main cache offset, which grows past zero after prefill) — but production callers ALWAYS satisfy `slidingKvLen <= slidingWindow` (the target's sliding-attention cache is capped at `slidingWindow` by `RotatingKVCache(maxSize:keep:)`), so the helper's `windowSize >= kvLen` early-exit branch fires and produces an all-zeros mask. The non-degenerate branch — which builds an ABSOLUTE-position mask, not a distance-from-queryOffset mask — is theoretical, unreachable in production, and would silently produce wrong attention if production callers ever lost the cache-cap invariant. Both fixes: - Drop `positionIds: MLXArray` from `MTPDrafterModel.draftBlock(...)` and `Gemma4AssistantDraftModel.forwardHidden(...)`. Add `queryOffset: Int` parameter to both. The iterator passes `cacheOffset` (already a Swift `Int` ivar) directly. - Add a `precondition(slidingKvLen <= textCfg.slidingWindow, ...)` in `forwardHidden` to enforce the invariant explicitly. Loud crash beats silent wrong-mask if the cache policy ever changes. - Rewrite the `createBidirectionalSlidingWindowMask` docstring to describe what the helper actually does (absolute-position predicate in the non- degenerate path) and document the production invariant that callers must satisfy. Phase E (BidirectionalMasks naming cleanup) folded in here — file is already consistent in Swift naming (`queryLen`, `kvLen`, `windowSize`, `queryOffset`); `q_idx`/`k_idx` references kept only in math-formula context. Updated call sites: - `MTPSpeculativeTokenIterator.speculateRound()`: drop `MLXArray(Int32(cacheOffset)).reshaped([1, 1])` materialization; pass `queryOffset: cacheOffset` directly. - `Gemma4Assistant.draftBlock`: pass `queryOffset` through to `forwardHidden(...)` per round. - Both mock conformers (`MockDrafter`, `MockMTPDrafter`): swap `positionIds: MLXArray` → `queryOffset: Int` in protocol conformance. - `MTPRung4TokenParityTests`: fixture loads `inputs/position_ids` as `MLXArray` for Python tooling parity; convert to `Int` at the call site via `Int(positionIds[0, 0].item(Int32.self))`. One-time conversion at test setup is fine — not in the hot path. - `Gemma4AssistantDraftModelIntegrationTests`: same one-time conversion at the call to `forwardHidden`. R-K10 (positionIds drop breaks RoPE silently) ruled out at planning time by confirming Gemma4 layer attention path uses `rope(keys/queries, offset: Int)` — RoPE consumes the `Int` directly, no MLXArray of positions is needed. Empirical validation: bs=4 mt=64 acceptance 60.6% (40/66), tok/s 13.90; bs=6 mt=64 acceptance 29.8% (36/121), tok/s 9.28. Acceptance counts bit-identical to Phase A/B/C runs; tok/s within run-to-run variance (R-K9 still holds — no regression). Rung4 token-parity fixtures pass unchanged (bs=2, bs=4, bs=6), confirming the queryOffset Int path produces the same drafter outputs as the prior MLXArray + .item() path. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pulls in 11 upstream commits, including three that touched Gemma4.swift: - 01b8624 Fix Gemma4Text quantized KV cache attention (ml-explore#237) - de2fed7 Make Gemma 4 per_layer_model_projection quantizable (ml-explore#309) - ef85ed0 Optimize shared MoE combine paths (ml-explore#324) Two conflict hunks in Libraries/MLXVLM/Models/Gemma4.swift: Hunk 1 (around line 189): Our branch added `enum Gemma4SharedKVState` and made `gemma4AdjustAttentionMask` module-internal (was `private`) so Gemma4Assistant.swift can use both. Upstream kept the function `private` since it doesn't have the drafter consuming these. Resolution: keep HEAD's enum + non-private declaration. Hunk 2 (around line 599): Upstream's ml-explore#324 optimized the shared MoE combine path to use `weightedExpertSum(...)` in place of the manual `(expertOutput * weights).sum(axis: -2)` pattern. Our branch added a `Gemma4ScaledLinear` class immediately after that combine code. The two changes landed within Git's 3-line conflict context. Resolution: take upstream's optimized combine (including the `topK` reshape without the trailing-1 dim) AND preserve our `Gemma4ScaledLinear` class definition that follows it. Net: upstream's perf win + our drafter helper class both present. The four Phase A-D commits (55c55b2, c6af858, 9b55aa4, bc2f8e3) sit on top of this merge with their SHAs preserved — important for the inline reply comments on PR ml-explore#308 that reference them directly. Build verified clean (xcodebuild build-for-testing -scheme IntegrationTesting succeeds with no errors). Test run pending after push.
Two cosmetic fixes from the pre-commit swift-format hook: - MTPIteratorEndToEndDiagnosticTests.swift: move the closing `)` of an `Issue.record(...)` call to its own line (multi-line argument list convention). - MTPSpeculativeTokenIteratorTests.swift: reorder imports so the `@_spi(Testing) @testable import MLXLMCommon` falls alphabetically between `MLX` and `MLXNN`, matching swift-format's whole-block alphabetical sort. No behavior change. Build verified clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
CI's "Verify documentation" step (run 27243511262, mac_build_and_test job) caught two doc comments referencing the old MTPDrafterModel.draftBlock signature. Both were stale through the Phase B / Phase D renames: - Evaluate.swift:1613 — referenced `draftBlock(target:lastToken:lastHidden:sharedKV:positionIds:blockSize:sampler:)` but Phase D renamed `positionIds:` to `queryOffset:`. Updated to the current signature. - MTPSpeculativeTokenIterator.swift:11 — top-of-file docstring referenced the pre-Phase-B signature `draftBlock(lastToken:lastHidden:sharedKV:positionIds:blockSize:sampler:)` (no `target:` parameter). Updated to the current signature with both the `target:` param and `queryOffset:` rename. No code change. DocC `docc convert` should now resolve both symbol links. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
| let mainResult = mainModel( | ||
| verifyInput[text: .newAxis], cache: mainCache, state: verifyState) | ||
| let mainLogits = mainResult.logits | ||
| mainState = mainResult.state |
There was a problem hiding this comment.
This saves the various states as the output of mainModel from verifying the tokens, e.g. mtpSharedKVStatesKey
however, see below (309)
There was a problem hiding this comment.
Addressed together with the thread at the trim site below — #308 (comment).
| lastRoundAccepted = accepted | ||
|
|
||
| // Rewind only the main cache by rejected count. Drafter has no cache. | ||
| trimPromptCache(mainCache, numTokens: numDraft - accepted) |
There was a problem hiding this comment.
This trims the cache back to the accepted tokens, but the mtpSharedKVStatesKey still holds the draft values. I think that needs very similar logic to trimPromptCache.
There was a problem hiding this comment.
Confirmed — good catch. The emit happens inside the verify forward, so the snapshot spans the full [bonus, d_1 ... d_n] chunk before acceptance is known, and it crossed the trim boundary untouched: any round following a partial acceptance drafted while cross-attending over the rejected rows. mlx-vlm never has this seam because set_shared_kv() re-derives from the live cache before every draft_block; threading sharedKV as an emitted value (per #283's no-mutation invariant) is where the snapshot acquired a lifetime the cache rewind didn't cover.
Fixed in 34c586c: trimSharedKVState(_:numTokens:) rewinds the snapshot at the same site as trimPromptCache, fed by its return value so the two stay in lockstep, with a debug assertion at draftBlock consumption that per-entry span == cache offset (it held across every 31B integration round). c0f35a6 adds a synthetic regression test that forces a partial acceptance and asserts the span the drafter receives on the following round — it fails with the fix absent (observed span = offset + rejected) and passes at HEAD. Output was never affected (emitted tokens are always the main model's samples against the trimmed cache, and the verify pass gets a fresh state carrying only the emit flag), which is why the byte-identity suites couldn't see it; the observable is acceptance rate.
Re-measured on the hidden-slice validation prompt plus the two cross-prompt byte-identity prompts (maxTokens=64, temperature 0): aggregate acceptance moves 46.4% → 49.1% at blockSize=4 and 23.7% → 36.6% at blockSize=6. Five of six prompt×blockSize cells improve (up to +15.9pp). The exception is the sky-blue prompt at bs=4 (60.6% → 46.8%), which we characterized before posting: the stale rows are the drafter's own rejected tail, sitting at exactly the positions it is about to predict again and fully visible to its bidirectional attention — after a shallow rejection that amounts to a self-lookahead hint, and on that one highly formulaic completion the hint was unusually lucky. A feature-shuffle ablation on the pre-fix tree (stale span kept, phantom content destroyed) reproduces the post-fix trajectory exactly (36/77 at bs=4), so the rejected rows' content was carrying the entire effect, not the span change. Since the reference re-derives shared K/V from the live cache every round, that pre-fix number was inflation from the deviation rather than achievable correct behavior — and conditioning the next draft on tokens the target just rejected isn't semantics we want to keep by accident. If a draft-retry hint is worth having, it should be a deliberate, position-correct design; we're filing a follow-up issue to explore that post-merge.
lastHidden doesn't need the analogous trim — the accepted-index slice from the earlier fix selects by position and never reads the rejected rows.
The verify pass emits mtpSharedKVStatesKey spanning the full [bonus, d_1 ... d_numDraft] chunk — K/V as materialized at forward time, before acceptance is known. trimPromptCache then rewinds the main cache's logical offset by the rejected count, but the snapshot in mainState crossed that boundary untouched: on any round following a partial acceptance, draftBlock cross-attended over up to numDraft-accepted rows of K/V belonging to tokens the main model had just rejected. Output correctness was never affected — emitted tokens are always the main model's own samples against the correctly trimmed cache, and the verify pass receives a fresh state carrying only the emit flag — which is why the byte-identity suites were structurally blind here. The observable is draft quality, and therefore acceptance rate, in rejection-adjacent rounds. The reference implementation never had this seam: mlx-vlm's set_shared_kv() re-derives shared K/V from the target's live (trimmed) cache before every draft_block. Our port threads sharedKV as an emitted value instead, per ml-explore#283's no-mutation invariant; the snapshot acquiring a lifetime the cache rewind didn't cover is the unhandled consequence of that (correct) divergence. Fix: trimSharedKVState(_:numTokens:) slices the trailing rejected rows off the sequence axis of each layer_type's (keys, values) pair, called at the same site as trimPromptCache and fed by its return value — so snapshot and cache stay in lockstep even in the regime where a post-wrap RotatingKVCache makes trimPromptCache report itself untrimmable and no-op. No-op at zero, on nil state, and on an absent key (quantization-onset round). A debug assertion at draftBlock consumption pins the invariant — per-entry sharedKV span == main cache offset — and stands down outside the trimmable regime. mtpLastHiddenStatesKey needs no analogous trim: the accepted-index slice selects by position and never reads rejected rows. Addresses PR ml-explore#308 review comments discussion_r3391133046 and discussion_r3391147261. Co-Authored-By: Claude Fable 5 (1M context) <noreply@anthropic.com>
testMTPSharedKVSpanTrimmedAfterPartialAcceptance scripts the synthetic main model to reject at a known draft position (1 of 3 accepted), then asserts the sharedKV span the mock drafter receives on the following round equals the true sequence length (== cache offset == queryOffset), not that plus the rejected count. The mock main model's state emission is extended to mirror the real emit hook's slice-to-logical-offset behavior: sharedKV spans the mock cache's full offset while lastHidden stays chunk-length, matching Gemma4's emission. The test asserts that fidelity in its own setup (emitted spans [3, 7, 9], each equal to the cache offset at emit time), since without it trimmed and stale state are indistinguishable. The mock drafter now records the per-call sharedKV spans and queryOffset it receives. Also lands the trimSharedKVState contract tests: zero-trim is a no-op (byte-identical), an n-row trim removes exactly the trailing rows on the sequence axis with the retained prefix byte-identical and the hidden entry untouched, and nil-state / absent-key calls are silent no-ops (the quantization-onset round exercises that path in production). Verified to fail with the parent change absent from the working tree: observed round-2 spans ["full_attention": 7, "sliding_attention": 7] against expected 5 (= offset; stale span = offset + 2 rejected), and to pass at HEAD. This is the drafter-conditioning observable that output-equivalence testing cannot see: byte-identity verifies the target path only; the drafter path's state must be asserted directly. Co-Authored-By: Claude Fable 5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
I think this is specific to the PR and should be deleted for the merge.
davidkoski
left a comment
There was a problem hiding this comment.
This is large and pretty complex but I think it is time to merge it and let people use it -- aside from removing the implementation notes, I don't see any issues.
PR-specific implementation notes from the porting research phase; not part of the library surface. The fixture-generation tooling that landed in the same commit (tools/generate_mtp_fixtures.py, tools/inspect_drafter_layout.py) stays — it regenerates the pinned HF fixture dataset. Addresses PR ml-explore#308 review comment discussion_r3392107410. Co-Authored-By: Claude Fable 5 (1M context) <noreply@anthropic.com>
|
Got it— removed in a0aea6a. Thank you for the careful reviews; the sharedKV catch in particular made this better, and the characterization it prompted is interesting enough that I'll file it as a follow-up issue after merge. Looking forward to people using it. |
davidkoski
left a comment
There was a problem hiding this comment.
Thank you for building this! Let's go!
…emma-4-12b-local-validation Brings in ml-explore#308 (Gemma 4 MTP speculative decoding, e145aca), ml-explore#333 (cross- layer KV sharing in no-cache forward), ml-explore#337 (prepare() windowSize), ml-explore#331, ml-explore#332. Conflict resolutions: - LMInput.ProcessedAudio: keep features/mask shape (consumed by Gemma4Unified); main's samples variant had no constructors. - Gemma4TextBackbone/Gemma4TextLanguageModel: union of ml-explore#327's tokenTypeIds and ml-explore#308's emitDrafterState threading; tuple return from ml-explore#308. - Gemma4.prepare image path: keep single full-sequence forward with tokenTypeIds (bidirectional vision overlay can't span chunk boundaries); main's chunked text-only prefill retained. - Dropped hasExplicitCache gating orphaned by ml-explore#333. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Builds on the merge of origin/main (ml-explore#308) into this branch (d07374e): - Gemma4Unified: widen languageModel visibility and add the MTP-aware callAsFunction(_:cache:state:) override reading mtpEmitFlagKey, mirroring ml-explore#308's Gemma4 override byte-for-byte. - Gemma4AssistantDraftModel.draftBlock: accept Gemma4Unified targets (same Gemma4TextLanguageModel backbone) alongside Gemma4. - Register "gemma4_unified_assistant" with the MTP drafter registry (same draft architecture; unified text_config is auto-detected). - New Gemma4UnifiedMTPIntegrationTests pairing the mlx-community/gemma-4-12B-it-4bit target with the gemma-4-12B-it-assistant-bf16 drafter: factory load, accepted-drafts e2e, and MTP-vs-baseline throughput. On-device results (M-series, 3/3 pass, reproduced twice): factual prompt 40/67 = 0.597 acceptance at ~1.08x; creative prompt 62/193 = 0.32 at 0.83-0.84x (net slowdown). No sticky passthrough. The 12B-4bit target step is cheap enough that the drafter's 262k-vocab head dominates at low acceptance; the favorable regime remains larger/slower targets (31B-8bit: 1.586x). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Add Multi-Token Prediction (MTP) speculative decoding for Gemma 4 Implements MTP speculative decoding in MLXLMCommon and MLXVLM: - `MTPDrafterModel` protocol with `draftBlock(target:..., queryOffset:)` contract; `MTPDrafterContext` / `MTPDrafterContainer` mirror the existing `ModelContext` / `ModelContainer` split - `createBidirectionalMask` / `createBidirectionalSlidingWindowMask` helpers for the drafter's attention path - `Gemma4AssistantDraftModel` — 4-layer Q-only drafter cross-attending to the target's pooled full/sliding-attention K/V; loaded via `MTPDrafterModelFactory` with `gemma4_assistant` registry entry - Three `LMOutput.Key` declarations (`mtpLastHiddenStatesKey`, `mtpSharedKVStatesKey`, `mtpEmitFlagKey`) for cross-model state exchange; Gemma4 target wired to emit on opt-in - `MTPSpeculativeTokenIterator` driving the accept/reject round loop; `generate(...)` / `generateTokens(...)` public overloads - `GenerateCompletionInfo` extended with MTP counters (`proposedDraftTokens`, `acceptedDraftTokens`, `passthroughReason`) - Sticky passthrough fallback for mid-stream KV-cache quantization onset - sharedKV snapshot trimmed in lockstep with cache rewind after partial acceptance - Verified hidden sliced at the accepted-bonus position each round (aligns with mlx-lm's `verify.hidden[:, accepted:accepted+1, :]`) - Fixture-anchored tests (masks, drafter forward, Rung 4 token parity) moved to IntegrationTesting; fixtures fetched from `angelsbrood/gemma4-mtp-fixtures` on HF Empirical results at temp=0 (31b-it-8bit + 31B-assistant-bf16): bs=4 mt=64: 60.6% acceptance, 13.6 tok/s bs=6 mt=64: 29.8% acceptance, 8.6 tok/s
Rank-shaped DSA/KDA prefill fixtures, bitwise overlap tests and a per-kernel bench (GLM5NextPrefillPipelineTests). Single-Mac port: GLM5NextDSAOverlapTests and the bench's overlap A/B set GLM5NextDSAAttention.overlapsAbsorbedQueries, which 8b2a251 removes again on ml-explore#308 (its diff reverts 8564baf in all three files), so neither builds at ml-explore#308's head either. They are dropped here; the fixtures, the KDA tests and the rest of the bench are kept (none needs the stage). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 9a32175)
Pool scores 8 per threadgroup, attention 8 heads per threadgroup (132 threadgroups per row instead of 33, same 16-lane softmax tree), a 1,024-thread decode top-k (integer membership), 8-block merge loads in the same block order, and a two-launch cache append that writes fresh buffers (no in-place writes). Also carries the final wiring of the DSA absorbed-query overlap. Bitwise at rows 1 and 3, histories 2K-32K (GLM5NextDSADecodeChainTests + 6 DSA suites). Two M5 Ultra, TP2: plain decode 13.15 -> 12.43 ms a step, MTP depth-2 round 25.4 -> 23.9 ms; tokens identical at 4K and 16K. Single-Mac port: GLM5NextTextCache.swift resolved by hand against this branch's cache. The DSA append kernel and its wiring are kept; the KDA capture window adopted from stage verification (23db6fa, TP-only, not ported) is not taken. KDA/DSA clones keep [.ellipsis] (d42b598 is not ported). As on ml-explore#308, this commit also removes 8564baf's absorbed-query overlap again in all three DSA files, despite the sentence above, so the library matches ml-explore#308's head. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 8b2a251)
…nto the cluster SDK ml-explore#314 carries the bitwise GLM speedups cherry-picked from ml-explore#308, with its own resolutions and qualification fixes: the shared-expert bitwise gate, the MTP charge per chunk, sampled-frame video decoding, step-scratch deferral, the MTP charge test bounds and the strict pool-score tolerance. It also carries main's Nemotron Super stack (ml-explore#312, ml-explore#315, ml-explore#316, ml-explore#317). Where both sides changed the same speedup code, this merge takes ml-explore#314's version and re-applies the cluster-only pieces on top: - the tensor-parallel shard and reduce hooks (bf77bf2, 2cb5efc); - whole-stage MTP verification windows (23db6fa); - fenced HC inputs (624fd05); - the text-stage and final-stage MTP APIs; - the cluster image plans and the paged engine (ml-explore#307). The mlx-swift pin stays at the cluster's 536ea22. The library keeps ml-explore#308's final DSA state, without the absorbed-query overlap. Resolutions: - GLM5NextArtifactLoader: ml-explore#314 plus loadTextStage and loadMTP(stage:). - GLM5NextHyperConnectionNormFusion: ml-explore#314's one-launch HC kernel plus the fenced-input wait and fencedInputs: ["output"] (624fd05). - GLM5NextMTP: ml-explore#314 plus the stage-owned target reference, primeHistory, primeAndPropose and GLM5NextMTPCheckpoint.arrays. - GLM5NextMoE: ml-explore#314's runsPlainQuantizedMatmul gate (0ceec3a). A TP rank builds its MLP from the local configuration, so the gate uses local widths. - GLM5NextMoEPrefillKernel: ml-explore#314. The two sides differed only in formatting. - GLM5NextTextCache: ml-explore#314 plus the KDA captured window (23db6fa). - GLM5NextWeightInventory: ml-explore#314 plus the tensor-parallel shard slice. - NemotronH: main's Super changes plus the ml-explore#307 layer-stage seam. cbv2Forward and cbv2Hidden take inputEmbedding, captureMTP and appliesFinalNorm, in that order: main's order first, then the seam's flag. appliesFinalNorm: false returns the residual before the fused final norm. - MLXVLM GLM5NextProcessor: ml-explore#314's sampled-frame video decoding. It calls the cluster's shared GLM5NextRGBDecoder.render instead of the removed rgb(). - Package.swift: ml-explore#314 and main, with the cluster mlx-swift pin 536ea22. - fork.yaml: ml-explore#314 and main, plus the cluster's GLM paragraph and its final-stage readout section. - docs/glm5-next/README.md: the cluster's text, which contains all of ml-explore#314's. - Tests: - From the cluster: FusedConstruction (stage entries) and HyperConnectionSiteRevision (fenced old source). - StageEntry: ml-explore#314's version (validity suite in KernelTests) plus the cluster's stage bitwise test. - From ml-explore#314: MTP, DSADecodeChain, KDALongConvolution, KDAPrefillKernel, KDAStepGraph, MoEDecodeKernel, RouterKernel and PrismMTPBinding. - PrefillPipelineTests from ml-explore#314. This drops GLM5NextDSAOverlapTests and the bench's overlap A/B, which both set the removed overlapsAbsorbedQueries. - Unit/Models/GLM5NextKernelConstantsTests is removed, because ml-explore#314 moved that suite to Kernel/Layers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d pin mlx-swift ekryski#61 with the batch-invariance switch Package.swift: mlx-swift 3832c0de -> f70ddf7e = Layr-Labs/mlx-swift#61 merged with main 69594861 (89144f9f, which contains ekryski#61's head 3832c0de) + the nested core caa9ed53 (mlx#41 merged with main + MLX_QMV_BATCH_INVARIANT) and mlx-c 73720efb. Main's SDK needs the main-merged mlx-swift API. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cluster SDK: GLM stages, vision parity, and native integration
… batching branch Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Status: New PR against
mainfollowing the merge of #283. The original draft at #293 was auto-closed whenlmoutput-statewas deleted on merge; this is the same set of twelve commits rebased onto currentmain, plus eight follow-up commits (two repair pre-existing test-setup gaps; the remaining six address davidkoski's review feedback on this PR — DocC link resolution + migration of fixture-anchored tests into the IntegrationTesting Xcode project — and are detailed in Verification below). cc @davidkoski per your note about going through these again now that CI is back in working order.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.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. Empirically verified end-to-end bytestMTP31BQuantizationOnsetEngagesPassthrough: with the cache configured to quantize mid-stream, speculation runs at ~78% acceptance pre-quantization, transitions to single-token passthrough mode after quantization onset (withpassthroughReasonpopulated via the Phase 0 plumbing), and completes the token budget with coherent output.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. The fixture set lives at theangelsbrood/gemma4-mtp-fixturesHF dataset (43 files / ~20 MB, generated against target=mlx-community/gemma-4-31b-it-8bitand drafter=mlx-community/gemma-4-31B-it-assistant-bf16), pinned to a specific commit SHA at the test call sites. Fixture-anchored tests live in the IntegrationTesting Xcode project per davidkoski's review feedback, and fetch the dataset on demand viaIntegrationTestHelpers. The schema (FIXTURE-SCHEMA.md), per-file manifest (FIXTURE-MANIFEST.json), and generation tooling (tools/generate_mtp_fixtures.py) remain in-repo attools/fixtures/for reproducibility; the data files themselves are not vendored. 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).End-to-end iterator verification (added 2026-05-23): Above the four-rung fixture ladder, which exercises drafter forward components, the following IntegrationTesting suite exercises the full iterator loop against the 31B target+drafter pair through the high-level
generate(...)API:testMTP31BPairProducesAcceptedDrafts— speculation active, counters reachGenerateCompletionInfo, no passthrough engagementtestMTP31BMatchesBaselineByteIdentical— byte-identical to baseline at maxTokens=32 on the sky-blue prompttestMTP31BMatchesBaselineRainbowsPrompt,testMTP31BMatchesBaselineSwiftPrompt— byte-identical to baseline at maxTokens=32 on two additional prompts (verifies the bonus-yield fix's content-independence)testMTP31BLongerStreamProducesValidContinuation— at maxTokens=128, MTP runs with healthy acceptance and the first 64 tokens are byte-identical to baseline. See "Known limitations" for the numerical-substrate boundary that bounds this assertiontestBaselineSelfDeterminism128— trust anchor; confirms baseline non-speculative generation is itself deterministic at maxTokens=128, a prerequisite for any MTP-vs-baseline comparison to be meaningfultestMTP31BQuantizationOnsetEngagesPassthrough— sticky-passthrough fallback empirically verified under mid-stream KV cache quantization (see Architecture for the numbers)testMTPE2BPairFailureMode,testMTPE4BPairFailureMode(env-gatedTEST_E2B_PAIR/TEST_E4B_PAIR) — E-series drafter failure-mode characterization. Both trap at the documentedGemma4AssistantMaskedEmbedderfatalErrorstub atGemma4Assistant.swift:95; the iterator and surrounding plumbing work as designed. The centroid embedder is the only missing piece for E-series support.Plus CI-scoped (no model loads required):
MTPGenerateLoopTaskContractTestsinMLXLMTests, which drives a mockMTPStatsCollectingiterator through a minimalgenerateLoopTaskreproduction to catch value-type fork regressions at PR-CI scope.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.Test setup corrections (2026-05-21): Two pre-existing test-setup gaps were repaired alongside the rebase, as two trailing commits. (1) The Rung 4 token-parity test (
MTPRung4TokenParityTests) was strengthened to load the full target (mlx-community/gemma-4-31b-it-8bit) and bind the drafter to it viabind(target:)before invokingdraftBlock, matching the production iterator path — the bind step had been missing from the test since its introduction. (2) Three synthetic-mock iterator tests inMTPSpeculativeTokenIteratorTestsused99as an inert placeholder for unused prefill positions, but the mock's vocab is20, so the placeholder caused an out-of-bounds write inside the mock'smakeLogits. In both cases the runtime path was correct in production (MTPSpeculativeTokenIterator.bindwires bind correctly; the iterator's own logic is sound); only the test scaffolding was incomplete. All four Rungs now pass against the fixture set as claimed above, as do the iterator's synthetic smoke tests.Migration to IntegrationTesting (2026-05-22): Per davidkoski's review feedback on this PR, fixture-anchored and checkpoint-dependent tests have been moved out of
MLXLMTestsand into the IntegrationTesting Xcode project, with fixtures fetched on demand from the published HF dataset rather than vendored in-repo. The unit tests that remain inMLXLMTests(synthetic-mock, compile-time, key-roundtrip) run on CI as before. Two test files mixed synthetic and checkpoint/fixture-gated cases and were split rather than moved wholesale:MTPDrafterModelFactoryTests.swift(4 synthetic methods stay; 1 checkpoint-gated load test moves toMTPDrafterModelFactoryIntegrationTests.swift) andGemma4AssistantDraftModelTests.swift(4 synthetic methods stay; 3 checkpoint/fixture-gated methods move toGemma4AssistantDraftModelIntegrationTests.swift). The dataset-fetch path is a new publicdownloadDataset(repo:revision:)helper inIntegrationTestHelpers; fixture revisions are pinned to a specific HF commit SHA at each test call site for byte-exact parity.DocC link resolution fix (2026-05-22): CI's
Verify documentationstep (run #26266924101) surfaced eleven cross-module and internal-visibilitySymbolreferences in MTP doc comments that DocC strict mode could not resolve (each module's documentation archive is built independently, so bare-name symbol links in MLXVLM cannot resolve to MLXLMCommon symbols, and links from public-symbol doc comments to internal-visibility same-module symbols are disallowed). Fixed by demoting unresolvable links to inline code formatting and expanding one signature-mismatched same-module link to its full parameter form. Full audit covers all...references across touched files, not just those CI named.Diagnostic investigation and end-to-end verification (2026-05-23): Following @joelnishanth's 2026-05-22 benchmark surfacing
proposedDraftTokens=0on the E4B pair, a 9-commit investigation resolved his report into a real observability gap plus two pre-existing latent bugs in the iterator's surrounding plumbing.The observability gap: iterator counters (
proposedCount,acceptedCount) existed but weren't plumbed through toGenerateCompletionInfo, so consumers using the high-levelgenerate(...)API couldn't read them. Phase 0 (0140ab2) plumbed three Optional fields —proposedDraftTokens,acceptedDraftTokens,passthroughReason— through the.infoevent and introduced anMTPStatsCollectingprotocol that drafter iterators conform to. Source-compatible: existing call sites that don't supply the new init parameters continue to compile unchanged.The two latent bugs:
For-in value-type copy in
generateLoopTask(Evaluate.swift:1787, fixed in25faa79).for token in iteratorover a value-typed iterator expands tovar __it = iterator.makeIterator()which forks a copy via Sequence's defaultmakeIterator() -> Self; mutations on the copy don't propagate to the outer binding observed at any later downcast. This was a long-standing issue affecting both MTP and non-MTP iterators, surfaced only when Phase 0's downcast at the info-construction site started reading iterator state. Secondary fix as a side effect: the same change makesiterator.tokenCountat the stopReason check truthful, so iterators hitting theirmaxTokensbudget now correctly reportstopReason=.lengthrather than falling through to.cancelled.Prepare-time bonus-token yield omission in
MTPSpeculativeTokenIterator.prepare(input:)(fixed inee86bff). The iterator sampled bonus token(s) during prepare and stored them inyas input to the first speculation round, but never appended them topendingTokens. The consumer of the iterator never saw the bonus tokens; the output stream started 1-2 positions ahead of baseline non-speculative generation depending onPrepareResultshape. Long-standing; not caught by the fixture-based Rung 1–4 tests because they exercise drafter forward components rather than the full iterator-prepare-to-next loop. Surfaced when the post-Phase-4 byte-identity-to-baseline test (testMTP31BMatchesBaselineByteIdenticalin6b320c1) compared the iterator's full output stream against autoregressive baseline at temp=0.End-to-end verification added across 8 active test methods (2 additional env-gated) in
MTPIteratorEndToEndDiagnosticTests(IntegrationTesting), plus a CI-scoped synthetic-loop test inMLXLMTestsfor value-type fork regression coverage without weight loads. Final 31B numbers post-fix: proposed=35, accepted=19, acceptance rate 54.29%, passthrough=none, 13.03 tok/s MTP vs. 8.22 tok/s baseline (1.586× speedup), byte-identical to baseline at maxTokens=32 across three prompts, byte-identical to baseline through the first 64 tokens of maxTokens=128. Full commit list:0140ab2,01fab00,25faa79,ee86bff,6b320c1,75c80d0,7c57408,42d6ad1,61777c8.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/MTPDrafterModelTests.swift,Gemma4AssistantDraftModelTests.swift(synthetic-mock half of the split — config-decode, sanitize, instantiation),Gemma4EmitDrafterStateTests.swift,MTPDrafterModelFactoryTests.swift(synthetic-mock half of the split — registration, registry, factory),MTPSpeculativeTokenIteratorTests.swift,MTPGenerateAPITests.swiftIntegrationTesting/IntegrationTestingTests/BidirectionalMasksTests.swift,MTPRung4TokenParityTests.swift,MTPAcceptanceRateTests.swift(placeholdered),MTPQuantizationOnsetTests.swift(placeholdered),Gemma4AssistantDraftModelIntegrationTests.swift(the fixture/checkpoint-gated half of the splitGemma4AssistantDraftModelTests.swift),MTPDrafterModelFactoryIntegrationTests.swift(the checkpoint-gated half of the splitMTPDrafterModelFactoryTests.swift)RESEARCH-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/— schema (FIXTURE-SCHEMA.md), manifest (FIXTURE-MANIFEST.json), regeneration tooling, andREADME.mdpointing to the published HF dataset. Data files themselves are atangelsbrood/gemma4-mtp-fixtures.Tests/MLXLMTests/MTPStatsCollectingTests.swift— synthetic-mock unit tests for theMTPStatsCollectingprotocol conformance andGenerateCompletionInfofield threadingTests/MLXLMTests/MTPGenerateLoopTaskContractTests.swift— CI-scoped regression test for iterator copy semantics ingenerateLoopTask, no model loads requiredIntegrationTesting/IntegrationTestingTests/MTPIteratorEndToEndDiagnosticTests.swift— full end-to-end iterator test surface (8 active methods, 2 env-gated)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)Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift— public top-leveldownloadDataset(repo:revision:matching:)helper that fetches a public HF dataset snapshot to a per-revision local cache (~/.cache/huggingface/integration-test-datasets/{repo}/{revision}/); consumed by the migrated fixture-anchored testsLibraries/MLXLMCommon/MTPDrafterModel.swift— addedMTPStatsCollectingprotocolLibraries/MLXLMCommon/MTPSpeculativeTokenIterator.swift— conformance toMTPStatsCollecting, storedpassthroughReasonfor observability, fix for prepare-time bonus-token yieldLibraries/MLXLMCommon/Evaluate.swift— three Optional fields added toGenerateCompletionInfo(Optional preserves source compatibility), downcast ingenerateLoopTaskinfo construction, for-in copy-semantics fix at the iterator-consuming loopSupported 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.[bonus, d_1, ..., d_K]) follows a different numerical path than the K+1 single-position autoregressive forwards baseline uses. At temp=0 with argmax sampling, this drift eventually flips a tied or near-tied logit choice and the streams branch. The MTP algorithm's speculation-correctness guarantee — at each emitted position N, the iterator returns what the target would have returned at position N given the iterator's accumulated history through N-1 — is preserved throughout; only independent-baseline byte-identity is bounded by this. BothtestMTP31BMatchesBaselineByteIdentical(32 tokens, three prompts) andtestMTP31BLongerStreamProducesValidContinuation(128 tokens, 64-token prefix) regression-test the empirical boundary on this configuration. Investigation tracked in [upstream MLX issue link TBD post-merge].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