Skip to content

Prompt cache: persist model state, wire Qwen3-VL and GLM-OCR restoration, and fail closed - #475

Merged
davidkoski merged 16 commits into
ml-explore:mainfrom
kklimuk:prompt-cache-state
Aug 10, 2026
Merged

davidkoski merged 16 commits into
ml-explore:mainfrom
kklimuk:prompt-cache-state

Conversation

@kklimuk

@kklimuk kklimuk commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

savePromptCache saved KV arrays but dropped LMOutput.State. Qwen vision models and GLM-OCR keep their M-RoPE continuation anchor (ropeDeltas) in that state, outside the KV cache. Restoring only KV therefore succeeded while assigning later text and images different positions from the uninterrupted session.

Before save:  KV cache + ropeDeltas
Saved file:   KV cache
After load:   KV cache + no continuation anchor

Persistence is only half of the fix. A model must also consume the restored state when it prefills a warm suffix, and incomplete cache/state pairs must be rejected instead of silently assuming an anchor of zero.

Scope

Following the split @NivDvir proposed in the review thread, #448 took Qwen2.5-VL and Qwen2-VL and has since merged. This PR is rebased on it and owns the rest: the prompt-cache format and public snapshot API, Qwen3-VL and GLM-OCR consumption, and hardening of the existing Qwen3.5/3.6 path. It does not touch the Qwen2-family files.

Model map

Model Anchor key Consumption owner This PR
Qwen3.5 / 3.6 qwen35.ropeDeltas existing #399 path fail-closed and rank/batch hardening
Qwen3-VL qwen35vl.ropeDeltas this PR warm continuation + windowed prefill + guard
GLM-OCR glmocr.ropeDeltas this PR warm continuation + windowed prefill + guard
Qwen2.5-VL qwen25vl.ropeDeltas #448 (merged) unchanged here
Qwen2-VL qwen2vl.ropeDeltas #448 (merged) unchanged here

What this PR does

1. Restore cache and state as one snapshot

PromptCacheSnapshot keeps the continuation pieces together:

public struct PromptCacheSnapshot {
    public let cache: [KVCache]
    public let metadata: [String: String]
    public let state: LMOutput.State?
}
  • savePromptCache accepts optional model state.
  • loadPromptCacheSnapshot(url:) restores KV, caller metadata, and state.
  • ChatSession.saveCache(to:) persists its current model state with KV.
  • Snapshot-based ChatSession initializers restore both together.
  • PromptCacheSnapshot has a public initializer for in-process cache builders.

2. Store state as safetensors tensors and fail closed in old readers

Array-backed state entries are ordinary safetensors tensors under a reserved namespace. Metadata stores the format version and logical keys; keys are sorted for deterministic layout.

State-bearing cache class names receive a versioned compatibility marker. The snapshot loader understands the marker and restores both pieces. The legacy tuple loader, old Swift readers, and Python readers reject the unknown state-bearing cache class rather than silently loading KV alone.

State-free files retain their existing layout. Unsupported state values and malformed layouts fail before an incomplete destination file is written.

3. Consume restored state in Qwen3-VL and GLM-OCR

Both models now use the carried anchor for warm suffixes and support windowed prefill:

positionOffset = cacheOffset + carriedRopeDelta

They compute explicit M-RoPE position IDs from that offset, prefill the suffix in bounded windows, and return a resume anchor for the following turn.

GLM-OCR additionally needed two underlying fixes:

  • its decode-time rope-delta branch was incorrectly nested under the precomputed-position branch, so an anchor-only resume state fell through to unanchored sequential positions;
  • its text-only path inflated already-batched tokens by another axis and could fail during reshape.

A small performance pass rode along on the touched paths, in case the diff raises eyebrows: Qwen3-VL's deepstack scatter indices are hoisted out of the per-layer loop (they are loop-invariant, and the old per-layer mask lookup forced a GPU→CPU sync per layer), a redundant sum().item() sync in the image merge is gone, and GLM-OCR's three identical per-token M-RoPE rows collapsed into one broadcast on the decode path. All behavior-preserving — the broadcast rows are identical by construction on that branch, and the continuation tests pin the outputs.

4. Fail loudly when continuation state is missing

For the stateful models owned by this branch:

  • throwing prepare paths raise ContinuationStateError.missingState when a warm cache has no anchor;
  • nonthrowing direct decode paths enforce the same invariant with a precondition (the protocol signature cannot throw);
  • unsupported warm batched continuation is rejected rather than silently resetting positions;
  • cold text-only prefill returns an explicit zero anchor so an ordinary live conversation remains valid.

The error directs callers to loadPromptCacheSnapshot(url:), the snapshot-based ChatSession initializer, and state-bearing savePromptCache.

A text-only warm cache without state is rejected too: after KV has been detached from its history, the model cannot prove that the cached prefix contained no media. Existing KV-only files must be rebuilt from the original history.

5. Let continuation state ride through speculative decoding

An earlier revision of this branch declared stateful models ineligible for speculative decoding (requiresContinuationState). That gate is gone — it was solving a problem these models don't have. The state they carry is a position anchor, not an accumulator: decode reads ropeDeltas and positions from cacheOffset + delta, never rewriting the delta. A rejected proposal trims the KV rows and the offset, so the anchor stays correct with no rollback. The state that genuinely cannot be rewound — the MTP drafter's per-position hidden states — rides its own MTPSpeculativeTokenIterator and is untouched here.

Concretely:

  • SpeculativeTokenIterator accepts mainState:, threads it through prefill and every verification pass, and exposes the current value as state — the same contract TokenIterator already had.
  • ChatSession seeds carried state into the speculative iterator and reads the post-prefill state back, so a stateful model keeps its anchor across speculative turns and saveCache persists it.
  • Speculation is skipped — falling back to normal generation and abandoning the draft cache — when the turn carries media, or when a warm main cache has no matching draft cache (a restored snapshot, or any turn after a fallback): the draft cannot catch up without re-prefilling history it doesn't have. Rebuilding the draft cache from the session's token history is a follow-up; see Boundaries.
  • The five cache-taking generate / generateTokens helpers now accept state:, so a snapshot restored outside ChatSession can be continued through the free functions instead of silently dropping its anchor — the exact failure this branch exists to fix.

6. Steer callers away from splitting snapshots

ChatSession(ctx, cache: snapshot.cache) still compiles, so documentation now identifies it as the unsafe split and points callers to promptCache:. The legacy loadPromptCache(url:) API is documented as state-free and rejects state-bearing files rather than dropping their state.

Tests

All model tests use tiny inline random-weight configurations; no model downloads are required.

  • Continuation tests for Qwen3-VL, GLM-OCR, and Qwen3.5 assert that a warm continuation matches a full cold prefill, that windowed prefill matches single-shot (including an image straddling a window boundary, and Qwen3-VL's deepstack slicing), that a cold prefill carries a zero anchor, that state survives a prompt-cache round trip, and that a warm cache arriving without its anchor throws rather than drifting.
  • KV cache tests cover state tensor round trips, deterministic layout, the compatibility marker in both directions, legacy files, malformed layouts, and every supported cache class.
  • ChatSession tests cover snapshot initialization and save/restore, carried state running under speculative decoding, and the two fallbacks — a media turn, and a warm prebuilt cache with no draft cache.

Full package suite: 319 XCTest tests and 401 Swift Testing tests, 0 failures.

Snapshot size

State size depends on what the model returns. A continuation state is generally only the anchor. A cold Qwen3.5 or GLM-OCR prefill may also contain precomputed position IDs, approximately 3 × tokens × 4 bytes—small relative to the KV cache, though still worth trimming in a follow-up.

Boundaries

  • Qwen2.5-VL and Qwen2-VL still fail open. Qwen2.5-VL / Qwen2-VL: windowed prefill + state-threaded warm continuation (wires #420) #448 gave them warm continuation but treats a missing anchor as zero rather than throwing, so a KV-only restore drifts silently there where the models in this PR now refuse. Porting the ContinuationStateError guards across is a follow-up.
  • The free generate helpers seed state in but do not hand the post-turn state back. The Generation stream carries no state, so a caller who needs the next snapshot should drive TokenIterator directly (its state property is public) or use ChatSession. Returning state through the stream's completion info is planned as a follow-up.
  • Speculation does not yet resume after a media turn or a snapshot restore. The draft cache is abandoned on fallback and never rebuilt, so those sessions stay on normal generation. ChatSession already tracks the token history needed to re-prefill a draft; wiring that up (and persisting prompt tokens in snapshots so restores can do the same) is a follow-up.
  • Batched warm continuation is rejected, not supported: the models capture per-row anchors but consume a single scalar. Uniform-offset batched resume (one snapshot expanded to N rows) is a natural follow-up.
  • A restored session appends turns instead of re-rendering the transcript. A snapshot carries KV and model state but not the structured conversation, so later turns append the new message where a live session (since Fix structured ChatSession continuations #472) re-renders the whole thing. On an image-bearing turn a live session rebuilds its cache while a restored one continues warm: positions stay correct, but the prompts differ — and on vision encoders that attend across image boundaries (Qwen2-VL passes mask: .none over the joint patch sequence, and the processor concatenates every image into one tower call) so do the new image's features, since it is encoded alone rather than beside the cached one. Qwen2.5-VL, Qwen3-VL, and GLM-OCR isolate each image and are unaffected. Persisting the transcript would close this, and would also supply the token ids the draft rebuild above needs. Thanks to @NivDvir for flagging the divergence and the vision-encoder narrowing.
  • Provenance-based state reconstruction is not included. Per-image grid provenance is required to rebuild state at an arbitrary radix-cache offset or rescue legacy KV-only files.

Issues and related work

  • Addresses #443.
  • Advances the remaining Qwen3-VL and GLM-OCR items in #420.
  • Builds on #448, now merged, which wired Qwen2.5-VL and Qwen2-VL.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@NivDvir

NivDvir commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Reviewed the full diff, and ran it against real Qwen2.5-VL grounding. Numbers at the bottom.

The compatibility marker is the strongest part of this design.
I built the same fix locally with a metadata format_version and realized it fails open: old readers ignore unknown metadata, skip the state tensors, and silently restore KV-without-state — recreating the exact bug being fixed.
Rewriting the cache class name closes that in old Swift and Python readers both.
The empty-state → legacy-format behavior and failing before the file is written are also right.

One scoping note.
On current main, Qwen2.5-VL and Qwen2-VL prepare still take state _: and ignore it.
For those models a snapshot restore succeeds and the first resumed turn still decodes at wrong positions.
#448 wires the consumption side; the two together close #443 for that family.
Until then "QwenVL" here is effectively Qwen3.5.

Minor: ChatSession(ctx, cache: snapshot.cache) still compiles without the snapshot's state — in-process unbundling the file format can't catch.
Maybe a doc note on the cache: init pointing at promptCache: as the preferred path.

Measured — this PR merged locally onto #448 (clean merge, disjoint file sets), Qwen2.5-VL-7B-Instruct-4bit, temp 0, grounding prompts:

So on this family the PRs compose: #475 persists, #448 consumes, and neither alone closes #443.

@kklimuk

kklimuk commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

@NivDvir working on getting the fixes for the other models in here as well.

@NivDvir

NivDvir commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Heads-up before you write the Qwen2.5-VL / Qwen2-VL side — that's #448, already built and measured (the numbers above ran on #475+#448 merged; disjoint file sets, clean merge).
It's more than minimal state: consumption: windowed prefill with positionIds sliced in lockstep, and continuations whose remainder contains a new image.
The full map on main: only Qwen3.5/3.6 consume restored state. Qwen2.5-VL, Qwen2-VL, Qwen3-VL and GlmOcr all take state _: and ignore it — Qwen3-VL per #420.
Natural split so we don't collide: #448 covers the Qwen2 pair; Qwen3-VL + GlmOcr are unclaimed.
Or carry it all and cherry-pick #448 with attribution — either way I'll re-run the measured comparison on the combined shape.

Restore model continuation state with prompt caches, fail closed when required state is missing, and add warm continuation coverage for Qwen3-VL and GLM-OCR.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@kklimuk

kklimuk commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@NivDvir it grew a bit 😅 .
I followed your advice to let it work together with #448.
A lot of it's is just tests - can remove those if you prefer.

@kklimuk kklimuk changed the title QwenVL: Allow Qwen vision to continue after restoring a prompt cache Prompt cache: persist model state, wire Qwen3-VL and GLM-OCR restoration, and fail closed Jul 30, 2026
Resolves the ChatSession conflicts introduced by the structured
continuation work on main (ml-explore#472):

- the `.kvcache` case gained a `conversation` payload, so the cache- and
  state-taking initializers now pass `conversation: nil` while still
  carrying the snapshot's `LMOutput.State`;
- `defaultGenerationWithoutDraft` returns the new `GenerationRun` value
  rather than the old (stream, task) tuple;
- `saveCache(to:)` destructures the four-element case and keeps
  persisting the model state.

The speculative-decoding admission guard now inspects `preparedInput`
instead of `input`: main's suffix-reuse path can replace `input` with a
token-only `LMInput`, which hides media that the turn actually carries.

Also documents `SpeculativeTokenIterator.init(mainState:)` so
scripts/verify-docs.sh stays clean.

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

Copy link
Copy Markdown
Member

Should I review #448 next so we can get it merged -- would that help?

The blanket "stateful models cannot speculate" rule was too strict. The
state these models carry is a position anchor, not an accumulator: the
decode path reads `ropeDeltas` and never rewrites it, positioning from
`cacheOffset + delta`. A rejected proposal trims the KV rows *and* the
offset, so the anchor stays correct — no rollback needed.

The state that genuinely cannot be rewound is the MTP drafter's
per-position hidden states, and that rides its own
`MTPSpeculativeTokenIterator`, never this one.

So:

- drop `requiresContinuationState` from `LanguageModel` and its three
  model overrides, the `ChatSession` gate, and `SpeculativeDecodingError`;
- `SpeculativeTokenIterator` seeds `mainState` and hands the post-prefill
  state back, as the normal iterator already did. The two
  `preconditionFailure`s that aborted the process when a model produced
  state without declaring the flag are gone with the flag — they were
  reachable today, since Qwen2.5-VL and Qwen2-VL return state from
  `prepare` without declaring it.

Media and cache-alignment still gate speculation: the draft model would
have to prefill the same images.

Also threads `state:` through the five cache-taking `generate` helpers
that build a `TokenIterator` or `SpeculativeTokenIterator`. Restoring a
snapshot and generating through the free functions silently dropped the
anchor — the exact failure this branch exists to fix. The two MTP
helpers are left alone: that iterator owns its state and takes no seed.

Quality pass alongside:

- hoist the deepstack scatter indices out of the per-layer loop
  (Qwen3VL) — they are loop-invariant and were re-uploaded per layer;
- drop a redundant `sum().item()` GPU sync in the image merge, which
  `nonZero` already counts;
- collapse GLM-OCR's three identical per-token M-RoPE rows into one
  broadcast;
- fold `visionInputs` into a single optional tuple and inline two
  single-use derived values.

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

NivDvir commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

@davidkoski Yes — and you already did, thank you. #448-first is the clean order: #475 doesn't touch the Qwen2 model files, so it rebases clean on top.

@kklimuk Keep the tests.
They're the acceptance bar for exactly the silent-position failure class this is about — a warm continuation that compiles, runs, and decodes at wrong positions only fails in tests like these.
The model map in the new description is exactly the split. Thanks for formalizing it.

Once both land I'll re-run the #420 warm/cold grounding comparison on the combined shape against real main — the closing check for #443.

@NivDvir

NivDvir commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Re-ran the comparison on the current head (c980c27 = main with #448 + this PR).
Bottom line: the disk cache works on the shipping shape — all 10 grounding rows parse after a save/restore round trip, and the restore output is byte-identical to my 07-29 run.

One heads-up, not a bug here: since #472, an in-memory session and a restored one diverge on any later image-bearing turn (the in-memory side re-templates the full transcript; a restored session keeps fragment continuation). Might be worth a line in the snapshot docs.

Details or harness available if useful.

kklimuk and others added 2 commits July 31, 2026 08:40
A snapshot carries the cache and model state but not the chat transcript,
so a restored ChatSession appends each new turn rather than re-rendering
the conversation as a history-backed session has since ml-explore#472. The two build
different prompts on a later image-bearing turn: the live session rebuilds
its cache and re-renders earlier messages, the restored one continues warm
from the cached prefix. Positions are correct either way.

The cache: initializers already noted fragment continuation; the
promptCache: initializers added here, which the docs prefer, did not.

Reported by @NivDvir on ml-explore#475.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The branch explained the same invariant in several places at once. The
three-line "a warm cache without its anchor cannot be continued" comment
appeared verbatim above three separate throws, each of which also carries
the reason in ContinuationStateError's own documentation and runtime
message. Drop the inline copies and shorten the message.

Also compresses the two prepareContinuation doc blocks this branch adds
(Qwen3VL, GlmOcr), the SpeculativeTokenIterator.state note, the
ChatSession speculation-gate comments, and the loadPromptCache doc.
Qwen35's block predates this work and is left alone.

Comments only; no behavior change.

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

kklimuk commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

@NivDvir got the comment in!

@NivDvir

NivDvir commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Thanks for adding that — the fragment-continuation note is exactly the right place for it.

One narrowing worth considering for the wording: "positions stay correct; the prompt differs"
holds for Qwen2.5-VL, which builds a real per-frame vision attention mask
(Qwen25VL.swift:641-656). Qwen2-VL has no per-image mask (Qwen2VL.swift:594-601 passes
mask: .none, and :575-577 gives B == 1 for images), so every patch attends to every
other — meaning a restored session that encodes the new image alone gets different vision
features than one encoding it alongside the cached image, at matched positions. So for
Qwen2-VL the two paths differ in more than prompt content.

Tiny random-weight measurement only, and this shouldn't hold the PR — happy to share the
harness if it's useful, or leave it as a follow-up.

@kklimuk

kklimuk commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@NivDvir i’ll fix the comment and merge main in to resolve conflicts! Anything else needed to make it mergeable?

kklimuk and others added 3 commits August 3, 2026 09:15
# Conflicts:
#	Libraries/MLXVLM/Models/Qwen3VL.swift
The note claimed positions stay correct and only the prompt differs. That
holds where the vision tower isolates each image, but Qwen2-VL passes
mask: .none over the joint patch sequence (Qwen2VL.swift:594-601, with
B == 1 for stills) and the processor concatenates every image into one
tower call (:853). Encoding the new image alone therefore yields
different features than encoding it beside the cached one, so more than
the prompt differs there.

Qwen2.5-VL builds a block-diagonal mask from cu_seqlens, and Qwen3-VL and
GLM-OCR attend per image, so those are unaffected.

Reported by @NivDvir on ml-explore#475.

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

kklimuk commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

@NivDvir fixed!

@NivDvir

NivDvir commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Nothing else — you've done both, and the narrowed note reads exactly right. Thanks for turning those around so fast.

I measured the restore path on 07-31 at the then-current head: 10/10 grounding rows parse through the save/load round trip, byte-identical to the 07-29 run. Since then the branch has taken the doc narrowing and main's ChatConventions migration (#502) — neither touches ChatSession, KVCache, Evaluate or the Qwen2 model files, so that measurement still describes this head. CI is green on 693de51d8. Approving, since the repo asks for at least one review and this is ready for one.

@NivDvir NivDvir left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Measured firsthand on 07-31 — save/restore round trip byte-identical, 10/10 grounding rows parse after restore. Changes since land outside the restore path (ChatSession, KVCache, Evaluate and the Qwen2 model files are untouched). CI green on 693de51d8. No blockers from me.

@kklimuk

kklimuk commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

@NivDvir hmm, looks like merging is still sadly blocked:
Screenshot 2026-08-03 at 3 04 03 PM

@NivDvir

NivDvir commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Turns out mine doesn't tick that box — reviewDecision still shows REVIEW_REQUIRED, so the required review has to come from someone with write access. @davidkoski, the restore-path validation is already done and on the record above, so hopefully this is a quick pass whenever you get to it.

# Conflicts:
#	Libraries/MLXLMCommon/Evaluate.swift
#	Libraries/MLXLMCommon/ModelFactory.swift
@kklimuk

kklimuk commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski would love your help!
been merging latest about once per day to make sure this PR is free of conflicts and its getting to be a lot of work. =)

@NivDvir

NivDvir commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Correction to my note above. The head has moved since I approved (693de51d8 → 9bf9ec576), and the upstream merge brings 26f3a48 ("Add custom LogitProcessor injection to GenerateParameters / ChatSession"), which touches ChatSession.swift and Evaluate.swift — two of the four files I said were untouched. That argument doesn't hold as written.

I still expect the 07-31 restore measurement to describe this head: the change is additive plumbing at the sampling layer (components on ChatSession, ChainedLogitProcessor in Evaluate), while the save/load round trip I measured exercises cache and position handling. Happy to re-run it on 9bf9ec576 if you'd rather have that on the record before review.

@davidkoski

Copy link
Copy Markdown
Member

@davidkoski would love your help! been merging latest about once per day to make sure this PR is free of conflicts and its getting to be a lot of work. =)

Yeah, sorry about that -- a lot of work is landing in the KVCache, Evaluate and ChatSession areas. I will review this one in the morning and that will make it easier to rebase and land.

# Conflicts:
#	Libraries/MLXLMCommon/ChatSession.swift
#	Libraries/MLXLMCommon/Evaluate.swift
#	Libraries/MLXLMCommon/KVCache.swift
Comment thread Libraries/MLXVLM/Models/GlmOcr.swift Resolved
Comment thread Libraries/MLXLMCommon/ChatSession.swift Resolved
Comment thread Libraries/MLXLMCommon/ChatSession.swift Resolved
Comment thread Libraries/MLXLMCommon/ChatSession.swift Resolved
kklimuk and others added 4 commits August 6, 2026 20:21
Three issues from @davidkoski's review.

GlmOcr had no unsupportedBatchContinuation guard, unlike Qwen35 and
Qwen3VL. missingState does not cover it: that guard fires when the anchor
is absent, this one when the anchor is present but cannot describe several
rows resuming at different positions. Without it a warm batched
continuation either trapped on getRopeIndex's batchSize precondition
(image path) or silently shared one row's anchor across the batch
(text path).

The promptCache: initializers did not forward `components:`. Every other
ChatSession initializer takes it; ml-explore#401 added the parameter and touched the
cache: initializers, so those picked it up on merge while ours — which the
docs recommend over cache: — silently could not accept a logit processor.

The speculation gate refused a warm main cache with no draft cache, which
is exactly the state reusedMainCacheWithoutDraft exists to repair by
rebuilding both caches from the full input. The gate returned before that
code could run, so speculation never resumed for the rest of a session.
Admit that case explicitly. The gate still refuses a warm cache with no
transcript to rebuild from (a restored snapshot), where the iterator would
throw on mismatched caches rather than fall back.

Tests: a warm batched GlmOcr continuation throws, and speculation resumes
on the text turn after a media turn. The restart test needs
PrefixPreservingTokenizer so turn 2 renders as an exact extension of turn
1 — with an ordinary tokenizer the session rebuilds from cold and never
reaches this path. Both tests were confirmed to fail without their fixes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
# Conflicts:
#	Libraries/MLXLMCommon/ChatSession.swift
#	Libraries/MLXLMCommon/Evaluate.swift
#	Libraries/MLXVLM/Models/GlmOcr.swift
#	Libraries/MLXVLM/Models/Qwen35.swift
#	Libraries/MLXVLM/Models/Qwen3VL.swift
#	Tests/MLXLMTests/Qwen35ContinuationTests.swift
ml-explore#470 replaced `prepare(_:cache:state:windowSize:)` with
`prepare(_:cache:state:prefill:)`; the old form is a deprecated shim. Rather
than ride the shim, Qwen3-VL, GLM-OCR and Qwen3.5 now take `prefill` and drive
their windowed continuation with `PrefillParameters.forEachChunk`, which owns
the loop's cancellation, autorelease pooling and per-chunk progress. Routing
uses `prefill.resolvedStepSize()` in place of the hardcoded 512.

This follows the shape ml-explore#470 gave Qwen2.5-VL: chunk the remainder while
reserving the final position, then one tail forward for the logits. Both
paths return `.logits`, so per the protocol they own the whole progress
sequence and report the terminal `(total, total)`.

Qwen3-VL needed the per-chunk work factored into a local `forward(_:)` so the
chunked body and the reserved tail share it: its deepstack rows are indexed by
visual-token count rather than token index, so `visualStart` has to advance
across both in lockstep with the embeddings, positions and visual indices.

The speculation gate merges into upstream's `requiresMainOnlyContinuation`
rather than staying a compound condition — same shape `.appendSuffixToMain`
already uses, which also drops the draft cache at the site that knows. That
lets `defaultGeneration` go back to upstream's name and body.

New test pins the progress contract for both routes.

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

Cleanup pass over the prompt-cache work. No behavior change intended; the
continuation suites are the safety net and still fail if the carried anchor
is dropped.

Library:
- QwenVL.continuationAnchor / .continuationResumeState own the two halves of
  the anchor invariant (+offset in, -offset out) that GlmOcr, Qwen35, and
  Qwen3VL each restated. The guards now fire in one place and in one order;
  previously the batch and missing-state guards were ordered differently per
  model and Qwen35 placed one inside prepareContinuation.
- Each model resolves the anchor in prepare, before the routing decision, so a
  warm cache fails closed on the single-shot path too. GlmOcr's route gate now
  matches its siblings and stops recomputing inputIds2D.
- GlmOcr and Qwen35 gained the local forward(_:) Qwen3VL already had, so the
  chunk body and the reserved tail cannot drift apart.
- GlmOcr only materializes whole-remainder embeddings when an image needs the
  merge; text-only chunks embed their own slice, bounding peak memory to the
  chunk rather than the prompt.
- Qwen3VL's image merge scatters by the visual indices it already computes,
  dropping a batch*seq*hidden mask download and host loop per image turn.
- ChatSession names the media predicate and the draft-cache condition instead
  of computing one twice and inverting the other inline.
- KVCache derives the class-name marker from the format version, replaces two
  Set round-trips with counts, and records why the marker exists at all.

Tests:
- ContinuationAssertions holds the five model-agnostic equivalences that were
  copied across four suites; each suite now configures it with its token ids.
- The windowed image assertion sweeps step sizes instead of fixing one, since
  balanced chunking derives boundaries from the total and no single size
  reliably splits the image run.

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

kklimuk commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski i think i've done it!

@kklimuk
kklimuk requested a review from davidkoski August 9, 2026 20:22

@davidkoski davidkoski 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.

Changes look good, thank you!

@davidkoski
davidkoski merged commit 4b0b416 into ml-explore:main Aug 10, 2026
2 checks passed
@kklimuk

kklimuk commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski @NivDvir thanks for all your help getting over the line

@davidkoski

Copy link
Copy Markdown
Member

Thank you for the contribution! The community makes this work!

jeethu added a commit to numen-tech/mlx-swift-lm that referenced this pull request Aug 26, 2026
…dvance the KV cache through the backbone seam

Upstream ml-explore#475 made `prepare` fail closed: with a non-empty cache and no
`LMOutput.State` it throws `ContinuationStateError.missingState` instead of
guessing the M-RoPE anchor. Hosts that drive this model through the fork's
`backboneHidden` seam (speculative verify) or that restore a text-only cache
from disk never hold that state, so they could no longer resume a warm cache.

For a text-only sequence the state is fully determined: `getRopeIndex` only
accumulates a non-zero delta across image/video runs, so the offset-relative
`ropeDeltas` a text-only prefill or continuation hands back is always zero.
`textOnlyContinuationState(batchSize:)` synthesizes exactly that, keeping the
`ropeDeltasKey` file-private.

Also adds the `try` that upstream's now-throwing `newCache(parameters:)`
requires in the pre-existing seam test.
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.

3 participants