Skip to content

Qwen2.5-VL / Qwen2-VL: windowed prefill + state-threaded warm continuation (wires #420) - #448

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
NivDvir:fix/qwen25vl-mrope-state-wiring
Jul 30, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
NivDvir:fix/qwen25vl-mrope-state-wiring

Conversation

@NivDvir

@NivDvir NivDvir commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Qwen2.5-VL / Qwen2-VL: windowed prefill + state-threaded warm continuation (wires #420)

Proposed changes

#399 added windowed prefill and state-threaded warm cross-turn continuation to
Qwen3.5/3.6, fixing multi-turn M-RoPE drift for that family. It also widened
LanguageModel.prepare to thread an optional LMOutput.State, but the
remaining Qwen VLMs listed in #420 were only updated to accept and ignore that
state (state _:). This PR wires the same mechanism through Qwen2.5-VL and
Qwen2-VL, so a warm KV cache is continued from its anchor instead of
recomputing M-RoPE positions from zero.

Without this, a warm continuation (multi-turn chat, tool-call restart, restored
prompt cache) silently recomputes positions from scratch: the post-image text
tail is placed at cacheOffset + arange instead of cacheOffset + ropeDelta + arange, dropping the delta the image accumulated. On dense single-image
grounding at temperature 0 this surfaces as degenerate output.

Mirroring #399 exactly (not a bespoke path):

  • getRopeIndex gains an offset-aware positionOffset (default 0), applied
    to the text-only positions, the image llmPositions, and the returned rope
    delta — so a new image's diverging t/h/w indices are computed from the warm
    cache's anchor rather than zero. Same shape as Qwen3-VL's getRopeIndex.
  • prepare now consumes the incoming state and delegates to a new
    prepareContinuation when the cache is already warmed (offset > 0) or the
    prompt is longer than windowSize (default 512). The continuation runs the
    vision tower + image→token merge once over the remainder, computes the
    remainder's M-RoPE positions once from the seeded position anchor (cache offset
    plus the rope delta carried in state), then drives the language model forward
    in chunks of windowSize — bounding the full-attention scratch to
    [heads, chunk, L] instead of [heads, L, L]. The windowed loop uses
    asyncEval per chunk + a trailing eval, matching the Gemma3 chunked-prefill
    pattern.
  • The returned resume state carries getRopeIndex delta − cacheOffset, so a
    caller threading state end-to-end continues the following turn through the
    existing decode reconstruction branch. Decode stays caller-owned.
  • The single-shot prepare path now passes token ids (rather than a
    pre-embedded tensor) on the text-only branch, so a 2-D [1, seq] text
    continuation — what a warm text turn produces — is handled without the prior
    [.newAxis, .ellipsis] rank inflation. Image single-shot behaviour is
    unchanged.

The vision-embedding preamble is factored into small shared helpers
(gatherVisionInputs, mergedVisionEmbeds) used by both prepare and
prepareContinuation. Batched inputs keep the single-shot path.

Qwen3-VL is intentionally left for a follow-up. Its prepare threads
per-layer deepstack features and a visual mask into the language model; a
windowed continuation would have to slice those in lockstep with the embeddings
and positions, which is beyond the drop-in Qwen3.5/2.5/2 pattern. Wiring it would
be structural surgery, so it is out of scope here and its #420 box stays
unchecked.

Tests

New Tests/MLXLMTests/Qwen25VLContinuationTests.swift mirrors
Qwen35ContinuationTests, run against tiny random-weight configs for both
wired models (no downloads, CI-safe). Per model:

  • Warm text continuation ≡ full prefill — prefix in cache, remainder
    prefilled on top; bounded against a token-by-token decode noise floor.
  • Warm image continuation ≡ full prefill — image in turn 1, rope delta
    threaded into turn 2's prefill via state.
  • Image-mid continuation resume state — three turns, image in the middle
    turn; the post-image resume state must position turn 3 correctly.
  • Windowed prefill ≡ single-shot (plain text) — windowSize: 8 vs one shot.
  • Windowed image prefill ≡ single-shot — image straddling the window
    boundary, the hard case for chunked slicing.

All 10 pass. The full MLXLMTests suite is green via
xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation,
and swift-format is clean.

#420 checklist

Grounding validation (real weights)

Ran mlx-community/Qwen2.5-VL-7B-Instruct-4bit (temp 0) on 10 GUI-grounding rows
(3 canonical + 7 dense screenshots), each asked twice: COLD (fresh session, single
turn) and WARM (turn 2 of a live session whose turn 1 grounded a different image,
state threaded between turns).

config warm turns with a parseable box warm empty/degenerate
main (343cae3) 0/10 10/10 — empty fences, or prose describing the cached turn-1 image
this branch 10/10 0/10

Warm coordinates track the cold single-shot within a few pixels on clean rows;
where they diverge the model is legitimately attending to turn-1 conversational
context — the controlled random-weight tests above are the positional-correctness
check (warm ≡ full prefill on logits), and this run is the end-to-end usability
check on real weights.

…ation

Wires the ml-explore#399 mechanism through Qwen2.5-VL and Qwen2-VL per the ml-explore#420
checklist: getRopeIndex gains an offset-aware positionOffset, prepare
consumes the incoming LMOutput.State and delegates warm/oversized
prompts to a chunked prepareContinuation anchored at the carried rope
delta, and the returned resume state threads the following turn through
the existing decode reconstruction. Adds random-weight continuation
tests for both models mirroring Qwen35ContinuationTests.
@NivDvir

NivDvir commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

One thing worth calling out from the diff: this removes the note in Qwen2VL.swift that explained chunked prefill was intentionally omitted, because chunking the embeddings without slicing positionIds in lockstep would feed wrong M-RoPE positions. That concern is addressed rather than ignored — prepareContinuation slices positions together with the embeddings (positionIds[0..., 0..., start ..< end]), which is what makes the chunked path safe for M-RoPE here. Happy to restore a short version of that note in the code if you'd prefer it stay.

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

Change looks good to me, thank you!

@NivDvir

NivDvir commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @davidkoski! That helps a lot — together with #475 this closes #443 across the whole Qwen family. Happy to follow up on anything post-merge.

@davidkoski
davidkoski merged commit a2736d4 into ml-explore:main Jul 30, 2026
2 checks passed
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.

2 participants