Skip to content

Batch Qwen VL image rows with per-row decoder state - #101

Open
ronaldmannak wants to merge 2 commits into
claude/a4-batch-token-iteratorfrom
claude/qwen-vl-image-batching
Open

ronaldmannak wants to merge 2 commits into
claude/a4-batch-token-iteratorfrom
claude/qwen-vl-image-batching

Conversation

@ronaldmannak

Copy link
Copy Markdown
Owner

Stacked on #91

No issue: requested by the maintainer. A leaf on #91, like #93; nothing stacks on it.

What changed

  • Full inputs: BatchTokenIterator.insert(inputs:) and insert(input:) queue full LMInputs, such as prompts with images. Each is prefilled whole through the model's prepare, into a fresh cache. Before, the iterator took token prompts only.

  • BatchedGenerationStateProviding (new, MLXLMCommon) lets a model's decoder state follow rows through batched decoding:

    • the state merges in row order when rows join;
    • it is selected with the caches' indices when rows leave;
    • the iterator evaluates it with the caches.

    Models that do not conform keep the single-row rule (modelStateRequiresSingleRow). Before, Qwen VL image prompts, whose prefill leaves rope deltas, could only run alone.

  • Conformers: Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE and Qwen3.5 VL (and Qwen3.5-MoE, a subclass) conform.

    • Their state is each row's rope delta. A row without one, such as a text-only prefill, takes zero, which continues its positions from its cache offset.
    • Merging drops prefill-only keys, such as Qwen 3.5's precomputed positions.
  • Decode positions: each row now continues from its own offset, the batch cache's per-row RoPE offset, in all five models (QwenVL.decodePositionIds). Before, they used the scalar cache offset, so ragged rows got wrong positions.

  • MROPE broadcast: Qwen2-VL and Qwen2.5-VL now broadcast MROPE cos/sin as [batch, 1, seq, dim]. Before it was [1, batch, seq, dim], which fails against [batch, heads, seq, dim] queries for more than one row.

Why a new protocol: it has five conformers today. It sits at the boundary between the generic iterator and model-owned state, which the iterator cannot merge or filter without a model contract. It ports BatchedGenerationStateProviding from fork commit 1bfd6f4 (used by PicoCore ml-explore#201) onto the current batch API.

Evidence

The new tests are in RoPEApplicationTests.swift, suite QwenVLBatchedImageTests. They use tiny random-weight models for six families. Qwen 3.5 runs on the GPU, because its linear attention is Metal-only; the others run on the CPU.

  • rowsMatchSingles: image and text rows of unequal lengths and different image grids (4 and 2 merged tokens) are each prefilled alone, then decode as a batch, with two late joins and a removal. Each row's logits match the row continued alone on the same tokens.
    • The tolerance is 1e-4 on the CPU and 1e-2 on the GPU.
    • Measured on the GPU, every family differs from its single runs by 2e-3 to 7e-3 (logits up to about 5), including the families that agree within 1e-4 on the CPU.
    • The tiny Qwen 3.5-MoE routes every token to both of its two experts. A top-1 choice between near-tied experts flipped under GPU rounding and changed one row's output wholesale (error 1.39), which is a test-model artifact rather than a position error.
  • iteratorRowsMatchSingles: the same inputs through BatchTokenIterator, with two rows inserted while the first two decode. The greedy tokens match TokenIterator for every row.

Each test fails without the change it guards:

  • Iterator: without its state change, the image rows end in .failed, so their tokens never match.
  • Qwen 2 VL broadcast: with the old [1, batch, seq, dim] broadcast, the batched forward fails: [broadcast_shapes] Shapes (2,4,1,16) and (1,2,1,16) cannot be broadcast.
  • Qwen 3.5 positions: with Qwen 3.5's old scalar offset, its rows' logits differ beyond the GPU tolerance (16 issues).

Focused suites at b5fcb40 (with #91's head merged in):

xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchTokenIteratorTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests \
  -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/QwenVLBatchedImageTests
** TEST SUCCEEDED **
Suite BatchTokenIteratorTests passed after 4.296 seconds.
Suite BatchedVLMPositionTests passed after 1.107 seconds.
Suite QwenVLBatchedImageTests passed after 3.025 seconds.
Suite QwenVLBatchedPositionTests passed after 0.842 seconds.
Test run with 57 tests in 4 suites passed after 4.296 seconds.

The full MLXLMTests bundle at 3e4bd4b, the change before #91's latest commits were merged in:

Executed 975 tests, with 8 tests skipped and 0 failures (0 unexpected) in 134.202 (134.409) seconds
Test run with 1640 tests in 134 suites failed after 31.533 seconds with 6 issues (including 2 known issues).
Failing tests:
	EmbeddingGemmaMaskTests.leftPadding()
	-[LFM2DSparkMetalTests rotatingHybridCacheMatchesGreedyAcrossWindow(promptLength:useMoE:)]

These are the known failures on this machine: G7 left padding, LFM2-DSpark promptLength: 3, and the two MiniCPM5 known issues. swift-format reports every changed file clean.

Not done on purpose

  • Warm prefix reuse with decoder state: insert(inputs:) takes cold requests only, with no supplied cache. Resuming a row on a cached prefix that carries rope deltas is a later follow-up.
  • Images on resumable models: a ResumablePrefillModel prefills the input's tokens chunk by chunk. None of the Qwen VL models is resumable, so their image rows always take the whole-prompt prepare path.
  • Videos: video inputs use the same rope-delta state but are not covered by these tests.
  • Per-row state size: not ported from 1bfd6f4 (generationStateBytesPerRow). Nothing here uses it.
  • MTP state: Qwen 3.5's MTP drafter keys are dropped on merge. Batched decoding does not run speculative drafting.

Test changes

None of the existing tests change. Added: QwenVLBatchedImageTests (rowsMatchSingles, iteratorRowsMatchSingles, six families each) and the QwenVLImageFamily builders in RoPEApplicationTests.swift.

🤖 Generated with Claude Code

ronaldmannak and others added 2 commits November 8, 2026 18:35
BatchTokenIterator took token prompts only and refused a second row
whenever a row's prefill returned model state, so Qwen VL image prompts,
whose prefill leaves rope deltas, ran alone. Their decode positions also
used the scalar cache offset, and Qwen 2 and 2.5 VL broadcast MROPE
cos/sin as [1, batch, seq, dim], which fails for more than one row.

- BatchTokenIterator.insert(inputs:) and insert(input:) queue full
  LMInputs, such as prompts with images. Each is prefilled whole through
  the model's prepare into a fresh cache.
- BatchedGenerationStateProviding (MLXLMCommon): a model's decoder state
  merges in row order when rows join and is selected with the caches'
  indices when rows leave. The iterator evaluates it with the caches.
  Models that do not conform keep the single-row rule.
- Qwen2VL, Qwen25VL, Qwen3VL, Qwen3VLMoE and Qwen35 (and Qwen35MoE)
  conform. Their state is each row's rope delta; a row without one, such
  as a text-only prefill, takes zero. Prefill-only keys (Qwen35's
  precomputed positions) are dropped on merge.
- Decode positions use each row's own offset, from the batch cache's
  per-row rope offset (QwenVL.decodePositionIds), in all five models.
- Qwen2VL and Qwen25VL broadcast MROPE cos/sin as [batch, 1, seq, dim].

QwenVLBatchedImageTests (six families, tiny random weights; Qwen 3.5 on
the GPU for its Metal-only linear attention):
- rowsMatchSingles: image and text rows of unequal lengths and grids,
  prefilled alone, decode as a batch with two late joins and a removal;
  each row's logits match the row continued alone (1e-4 on the CPU,
  1e-2 on the GPU, where every family differs from single runs by
  2e-3 to 7e-3).
- iteratorRowsMatchSingles: through BatchTokenIterator, with two rows
  inserted while the first decode, greedy tokens match TokenIterator.
Without the iterator change the image rows end in .failed; with the old
Qwen 2 VL broadcast the batched forward fails to broadcast; with Qwen
3.5's old scalar offset its rows' logits differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T04:46:52.250973Z b5fcb40 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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.

1 participant