Skip to content

models should not mutate state during eval - #283

Merged
davidkoski merged 2 commits into
mainfrom
lmoutput-state
May 22, 2026
Merged

davidkoski merged 2 commits into
mainfrom
lmoutput-state

Conversation

@davidkoski

Copy link
Copy Markdown
Member

Proposed changes

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@davidkoski
davidkoski requested a review from angeloskath May 12, 2026 22:58
@davidkoski

Copy link
Copy Markdown
Member Author

@angelsbrood FYI -- I haven't tested it yet, but something like this

@angelsbrood

Copy link
Copy Markdown
Contributor

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:

  1. My usage would be cross-model— target writes state keys on its forward, drafter reads them on its own forward. GlmOcr and Qwen35 in models should not mutate state during eval #283 look intra-model (each reads keys it wrote itself). The mechanism handles cross-model fine, but I wanted to flag it in case you'd want a different API surface for that, or bake constraints into models should not mutate state during eval #283 before it lands.
  2. Reading the canonical Python (HF modeling_gemma4_assistant.py and Blaizzy's mlx-vlm port), the drafter is structurally not a LanguageModel— forward takes (inputs_embeds, shared_kv_states, position_ids), it loads via a separate load_drafter(kind="mtp"), and it exposes a K-step draft_block the iterator calls directly. My instinct is a parallel MTPDrafterModel protocol and DrafterTypeRegistry rather than fitting it into LanguageModel. Does that sound right, or would you steer it differently?

Holding off until I hear back. Thanks again!

@davidkoski

Copy link
Copy Markdown
Member Author
  1. My usage would be cross-model— target writes state keys on its forward, drafter reads them on its own forward. GlmOcr and Qwen35 in models should not mutate state during eval #283 look intra-model (each reads keys it wrote itself). The mechanism handles cross-model fine, but I wanted to flag it in case you'd want a different API surface for that, or bake constraints into models should not mutate state during eval #283 before it lands.

I think that would be fine -- the keys would just ned to be more visible than private. These states that I was adding were internal to the model so private makes sense here. I think returning out-of-band data this way (via public or at least package scoped) keys makes sense.

  1. Reading the canonical Python (HF modeling_gemma4_assistant.py and Blaizzy's mlx-vlm port), the drafter is structurally not a LanguageModel— forward takes (inputs_embeds, shared_kv_states, position_ids), it loads via a separate load_drafter(kind="mtp"), and it exposes a K-step draft_block the iterator calls directly. My instinct is a parallel MTPDrafterModel protocol and DrafterTypeRegistry rather than fitting it into LanguageModel. Does that sound right, or would you steer it differently?

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 BaseLanguageModel provides the required loading support (see how it is used by EmbeddingModel). So this is a possibility.

@angelsbrood

Copy link
Copy Markdown
Contributor

Read through BaseLanguageModel and how EmbeddingModel uses it— yes, this works better than the parallel-registry shape I was tentatively imagining. The drafter would conform to BaseLanguageModel and gain its own task protocol the way EmbeddingModel does:

public protocol MTPDrafterModel: BaseLanguageModel {
    func bind(target: any LanguageModel)
    func draftBlock(
        lastToken: MLXArray, hidden: MLXArray,
        sharedKV: [String: (MLXArray, MLXArray)],
        positionIds: MLXArray,
        blockSize: Int, sampler: Sampler
    ) -> MLXArray
}

This composes with #283: the target writes gemma4Assistant.lastHiddenStates and gemma4Assistant.sharedKVStates keys (public per your "out-of-band" guidance), the MTP iterator reads them off LMOutput.state and threads them as method args into draftBlock per round. The drafter doesn't carry transient round-state as ivars— only bind-time setup (target's embed table reference, scale) which is set once and never mutated during eval. Aligns with #283's invariant.

One question: where would you want MTPDrafterModel to live? Three options I see: in MLXLMCommon alongside LanguageModel, in MLXLLM, or in a new MLXDrafters library parallel to MLXEmbedders. The last is the most literal parallel to the EmbeddingModel precedent, but it does add a library for what's currently a single model type. Happy to go where you'd prefer.

Will draft the PR with this shape once you weigh in on placement (and once #283 lands, since the keys depend on it).

@davidkoski

Copy link
Copy Markdown
Member Author

I think MLXLMCommon (the protocol) and then the implementations in MLXLLM and MLXVLM.

@angelsbrood angelsbrood mentioned this pull request May 17, 2026
3 of 4 tasks
@angelsbrood

angelsbrood commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

@davidkoski Heads-up that I've opened a draft PR at #293 consuming this work: three public LMOutput.Key declarations (emit flag, last hidden state, shared K/V) threading state across the target → iterator → drafter boundary for Gemma 4 MTP speculative decoding.

One observation in case it's useful for the review: the fixed LanguageModel.callAsFunction(_:cache:state:) signature made LMOutput.State the natural carrier for the emit-flag control signal as well as the tensor payloads. What would have been two mechanisms (state-bag for tensors, function parameter for the flag) ended up as one. The typed Key<T> subscript pattern carries both cleanly.

Will leave the draft alone until #283 merges and we rebase onto main. Happy to share what surfaced during use if it's useful to your review push. Thanks for getting the foundation up.

@angeloskath angeloskath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}()

// Quantized cache path
if let qcache = cache as? QuantizedKVCacheProtocol {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good question -- maybe I should sync up this implementation with mlx-lm. Either way it needs a change.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, simpler to make it just match mlx-lm

Comment thread Libraries/MLXLLM/Models/GPTOSS.swift Outdated
try super.update(
parameters: parameters, verify: verify, path: path, modulePath: modulePath)

if parameters["sinks"] != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mention below we kind of ignore that possibility in python, not sure how important it is.

@davidkoski
davidkoski merged commit 3f9c86f into main May 22, 2026
2 checks passed
@davidkoski
davidkoski deleted the lmoutput-state branch May 22, 2026 00:23
@davidkoski

Copy link
Copy Markdown
Member Author

@angelsbrood FYI merged. Finally have CI back in working order so I am going to start going through these again.

angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request May 22, 2026
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>
angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request May 22, 2026
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>
@angelsbrood angelsbrood mentioned this pull request May 22, 2026
3 of 4 tasks
angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request May 22, 2026
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>
angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request May 22, 2026
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>
wangqi pushed a commit to wangqi/mlx-swift-lm that referenced this pull request May 23, 2026
…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).
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request May 27, 2026
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%).
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request May 27, 2026
…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.
davidkoski pushed a commit to NivDvir/mlx-swift-lm that referenced this pull request Jun 1, 2026
…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.
angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request Jun 10, 2026
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>
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
* models should not mutate state during eval

- fixes ml-explore#157

* sync gptoss with mlx-lm -- no missing sinks
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Qwen 3.5 VLM model crashes on subsequent requests with manual KV cache prefix matching

3 participants