Repository navigation
Prompt cache: persist model state, wire Qwen3-VL and GLM-OCR restoration, and fail closed - #475
Conversation
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
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. One scoping note. Minor: 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. |
|
@NivDvir working on getting the fixes for the other models in here as well. |
|
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). |
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>
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>
|
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>
a53d529 to
3cebc63
Compare
|
@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. 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. |
|
Re-ran the comparison on the current head (c980c27 = main with #448 + this PR). 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. |
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>
|
@NivDvir got the comment in! |
|
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" Tiny random-weight measurement only, and this shouldn't hold the PR — happy to share the |
|
@NivDvir i’ll fix the comment and merge main in to resolve conflicts! Anything else needed to make it mergeable? |
# 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>
|
@NivDvir fixed! |
|
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 |
NivDvir
left a comment
There was a problem hiding this comment.
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.
|
@NivDvir hmm, looks like merging is still sadly blocked: |
|
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
|
@davidkoski would love your help! |
|
Correction to my note above. The head has moved since I approved ( I still expect the 07-31 restore measurement to describe this head: the change is additive plumbing at the sampling layer ( |
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
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>
|
@davidkoski i think i've done it! |
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
|
@davidkoski @NivDvir thanks for all your help getting over the line |
|
Thank you for the contribution! The community makes this work! |
…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.

Problem
savePromptCachesaved KV arrays but droppedLMOutput.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.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
qwen35.ropeDeltasqwen35vl.ropeDeltasglmocr.ropeDeltasqwen25vl.ropeDeltasqwen2vl.ropeDeltasWhat this PR does
1. Restore cache and state as one snapshot
PromptCacheSnapshotkeeps the continuation pieces together:savePromptCacheaccepts optional model state.loadPromptCacheSnapshot(url:)restores KV, caller metadata, and state.ChatSession.saveCache(to:)persists its current model state with KV.ChatSessioninitializers restore both together.PromptCacheSnapshothas 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:
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:
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:
preparepaths raiseContinuationStateError.missingStatewhen a warm cache has no anchor;The error directs callers to
loadPromptCacheSnapshot(url:), the snapshot-basedChatSessioninitializer, and state-bearingsavePromptCache.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 readsropeDeltasand positions fromcacheOffset + 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 ownMTPSpeculativeTokenIteratorand is untouched here.Concretely:
SpeculativeTokenIteratoracceptsmainState:, threads it through prefill and every verification pass, and exposes the current value asstate— the same contractTokenIteratoralready had.ChatSessionseeds carried state into the speculative iterator and reads the post-prefill state back, so a stateful model keeps its anchor across speculative turns andsaveCachepersists it.generate/generateTokenshelpers now acceptstate:, so a snapshot restored outsideChatSessioncan 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 topromptCache:. The legacyloadPromptCache(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.
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 × 4bytes—small relative to the KV cache, though still worth trimming in a follow-up.Boundaries
ContinuationStateErrorguards across is a follow-up.generatehelpers seed state in but do not hand the post-turn state back. TheGenerationstream carries no state, so a caller who needs the next snapshot should driveTokenIteratordirectly (itsstateproperty is public) or useChatSession. Returning state through the stream's completion info is planned as a follow-up.ChatSessionalready 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.mask: .noneover 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.Issues and related work