Repository navigation
models should not mutate state during eval - #283
Conversation
|
@angelsbrood FYI -- I haven't tested it yet, but something like this |
|
Thanks for the FYI David. I've been digging into gemma4_assistant for #279, and this looks like the mechanism the MTP drafter needs: it would let the target share its last-layer hidden states and per-layer-type K/V with the drafter through the iterator. Two questions before I go further:
Holding off until I hear back. Thanks again! |
I think that would be fine -- the keys would just ned to be more visible than
Possibly -- I know the other draft models were done as normal language models (but I think they were from the mlx-lm side). If it does need to be a new type of model, I think that |
|
Read through This composes with #283: the target writes One question: where would you want Will draft the PR with this shape once you weigh in on placement (and once #283 lands, since the keys depend on it). |
|
I think MLXLMCommon (the protocol) and then the implementations in MLXLLM and MLXVLM. |
|
@davidkoski Heads-up that I've opened a draft PR at #293 consuming this work: three public One observation in case it's useful for the review: the fixed Will leave the draft alone until #283 merges and we rebase onto |
ecefa4e to
706256b
Compare
| }() | ||
|
|
||
| // Quantized cache path | ||
| if let qcache = cache as? QuantizedKVCacheProtocol { |
There was a problem hiding this comment.
This is probably a bigger change than this was meant to be but the following code should probably be unified to a call to a scaledDotProductAttention that checks internally if the cache is of QuantizedKVCacheProtocol rather than duplicating the logic below.
Regarding active sinks, is there a GPT OSS that doesn't have active sinks? In python we ignore that possibility 🤷♂️ We could also just add sinks to the quantizedScaledDotProductAttention it's straightforward.
There was a problem hiding this comment.
Yeah, good question -- maybe I should sync up this implementation with mlx-lm. Either way it needs a change.
There was a problem hiding this comment.
Yeah, simpler to make it just match mlx-lm
| try super.update( | ||
| parameters: parameters, verify: verify, path: path, modulePath: modulePath) | ||
|
|
||
| if parameters["sinks"] != nil { |
There was a problem hiding this comment.
As I mention below we kind of ignore that possibility in python, not sure how important it is.
318a4b6 to
0e8d58f
Compare
|
@angelsbrood FYI merged. Finally have CI back in working order so I am going to start going through these again. |
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>
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>
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>
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>
…meterized GemmaFunctionParser (PR ml-explore#183) keeping the wangqi Gemma4FunctionParser double-brace JSON fallback, LMOutput.State-based M-RoPE position passing (PR ml-explore#283) for Qwen35 and GlmOcr with a canSlicePrecomputed guard, and always-chunked Idefics3 prefill (PR ml-explore#297).
Per davidkoski's ml-explore#238 standard ("people can always go back to the PR the lines came from to see the discussion") applied harder: the two comment blocks I'd kept were both restatements of what the variable names and call structure already say. Brings the comment-line ratio on this PR from ~40% to 0%, in line with the maintainer's own recent PRs (ml-explore#283 2%, ml-explore#235 3%, ml-explore#228 0%).
…eview item 4) davidkoski (L277): "The model can't (well, it _shouldn't_) mutate state during inference -- the one model instance can be used by many chat sessions. See ml-explore#283 for the pattern to cache state like this." Replaces the two instance vars on `Language.LanguageModel` (`_positionIds`, `_ropeDeltas`) with per-call `LMOutput.State` keyed by `positionIdsKey` / `ropeDeltasKey`. The model itself stays a pure function — one instance can now serve concurrent chat sessions without their MROPE states colliding. Touched: - file-level: two `LMOutput.Key<MLXArray>` declarations - `Language.LanguageModel`: removed the two `_*` vars; signature takes `state: LMOutput.State?`; reads + writes via the keys; returns `LMOutput(logits:state:)` so subsequent steps see the same state - `Qwen25VL.inputEmbeddings`: returns `(embeds, positionIds?, ropeDeltas?)` tuple instead of mutating `languageModel._*` - `Qwen25VL.prepare`: seeds `LMOutput.State` from the tuple and passes it to the language model - `Qwen25VL.callAsFunction`: matches the post-ml-explore#283 signature `(LMInput.Text, [KVCache]?, LMOutput.State?) -> LMOutput` Same flow as Qwen3VL post-ml-explore#283.
…eview item 4) davidkoski (L277): "The model can't (well, it _shouldn't_) mutate state during inference -- the one model instance can be used by many chat sessions. See ml-explore#283 for the pattern to cache state like this." Replaces the two instance vars on `Language.LanguageModel` (`_positionIds`, `_ropeDeltas`) with per-call `LMOutput.State` keyed by `positionIdsKey` / `ropeDeltasKey`. The model itself stays a pure function — one instance can now serve concurrent chat sessions without their MROPE states colliding. Touched: - file-level: two `LMOutput.Key<MLXArray>` declarations - `Language.LanguageModel`: removed the two `_*` vars; signature takes `state: LMOutput.State?`; reads + writes via the keys; returns `LMOutput(logits:state:)` so subsequent steps see the same state - `Qwen25VL.inputEmbeddings`: returns `(embeds, positionIds?, ropeDeltas?)` tuple instead of mutating `languageModel._*` - `Qwen25VL.prepare`: seeds `LMOutput.State` from the tuple and passes it to the language model - `Qwen25VL.callAsFunction`: matches the post-ml-explore#283 signature `(LMInput.Text, [KVCache]?, LMOutput.State?) -> LMOutput` Same flow as Qwen3VL post-ml-explore#283.
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>
* models should not mutate state during eval - fixes ml-explore#157 * sync gptoss with mlx-lm -- no missing sinks
…an one image (ml-explore#283) Integrate an isolated non-serving model correction with its regression assertions. Preserve concurrent main changes and promote the resolved recording checks to ordinary assertions. No deployment or serving dependency update.
Proposed changes
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes