Skip to content

Batching: Use per-row rotary positions and attention scaling in LLM and VLM models - #773

Merged
davidkoski merged 7 commits into
ml-explore:mainfrom
ronaldmannak:batching/a0b-vlm-row-positions
Nov 26, 2026
Merged

davidkoski merged 7 commits into
ml-explore:mainfrom
ronaldmannak:batching/a0b-vlm-row-positions

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

FastVLM, Gemma 3, Gemma 4, Idefics3, LFM2-VL, Pixtral, MuseGlimmer and Qwen 2/2.5 VL apply each cache's scalar or per-row rotary offset (ropeOffset through applyRotaryPosition) instead of the cache's scalar offset.
Gemma 4 carries the owning layer's positions (RoPEOffset) through KV sharing; Gemma4Assistant passes its query offset as .scalar to match the new signature.
Mistral 3 text, Mistral 3 VLM and Nemotron Labs Diffusion apply Llama 4 query scaling per row (batchedLlama4AttentionScale), and clamp the positions of left padding at zero.
Ordinary scalar calls, MuseGlimmer's NoPE layers and explicit Qwen M-RoPE state are unchanged.

This PR depends on #772 and is part of the batching proposal #771

Checklist

  • 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)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: Code extracted from fork by Opus and Astra

ronaldmannak and others added 5 commits November 6, 2026 17:18
Gemma 2 scores grouped queries as [B, kv, repeats, L, S]. A cache whose mask carries one row per sequence, shape [B, 1, L, S], aligned its batch axis with the key-value heads, so row b masked head b of every sequence. Give such a mask the head-group axis before applying it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Benchmarks/DecodeBench times greedy decode of TokenIterator on a local model as a median over rounds, so a change to the decode path can be compared with its base. MLX_SWIFT_LM_PATH points it at another checkout.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Move the per-row mask regression into Gemma2Tests and reuse its tiny model. Extract the standalone decode benchmark from the functional stack for separate review.

Co-authored-by: Codex <noreply@openai.com>
Every model this change edits now has a test in RoPEApplicationTests that
prefills two text rows of different lengths alone, joins their caches in the
stand-in RowOffsetCache and decodes three tokens, comparing each row with the
same sequence continued alone: Gemma 4 (with KV-shared layers), Idefics3,
LFM2-VL, Mistral 3 VLM (with Llama 4 scaling), MuseGlimmer, Pixtral, Qwen 2 VL
and Qwen 2.5 VL, and, in LLMRowPositionTests, Mistral 3 text and Nemotron Labs
Diffusion, whose Llama 4 scaling buckets differ between the rows' positions.
The helper steps through nextTokenLogits so the Qwen models, which have no
plain forward, take the same path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment on lines -165 to +167
let offset = cache?.offset ?? 0
queries = rotaryEmbedding(queries, offset: offset)
keys = rotaryEmbedding(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rotaryEmbedding, to: queries, offset: offset)
keys = applyRotaryPosition(rotaryEmbedding, to: keys, offset: offset)

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 only affect the text only path -- does the image path need a similar change?

Comment on lines -155 to +157
let offset = cache?.offset ?? 0
queries = rotaryEmbedding(queries, offset: offset)
keys = rotaryEmbedding(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rotaryEmbedding, to: queries, offset: offset)
keys = applyRotaryPosition(rotaryEmbedding, to: keys, offset: offset)

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.

See Qwen2VL -- this is the text path, does the image path need the same?

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

Please see my question on the text paths in the qwen models. Otherwise this looks ready to merge. Thanks!

@ronaldmannak

Copy link
Copy Markdown
Contributor Author

@davidkoski fixed. I've also fixed a decode position issue in a second commit

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

Not a PR blocker but a potential gap (future PR if needed):

  • Paligemma and GlmOcr are not using cache.ropeOffset
  • Qwen3VL, Qwen3VLMoE, Qwen35 might have a gap when positionIds are nil

@davidkoski
davidkoski merged commit a2b47a7 into ml-explore:main Nov 26, 2026
4 checks passed
smdesai added a commit to smdesai/mlx-swift-lm that referenced this pull request Nov 28, 2026
Upstream's 27 commits since 7dde329, among them per-row rotary positions
in the LLM and VLM models (ml-explore#773), LFM3 text validation (ml-explore#756), Gemma 4's
warm-cache image attention (ml-explore#813), Gemma 2's per-row mask (ml-explore#772), the
segsum batch mask (ml-explore#829), Hadamard-rotated Qwen3.5 packs (ml-explore#630, ml-explore#835) and
the caller's sampler in guided generation (ml-explore#733).

Conflicts:
- GuidedGenerationLoop.swift: both. The fork's prompt reuse, then
  upstream's logit processor, which sees the whole prompt. maskedArgMax
  becomes maskedSample, taking upstream's processor and sampler, so the
  batched row (BatchedGuidedGeneration, still greedy) and the single loop
  share it.
- QwenVL.swift: both, one mechanism. textBatchPositionIds is now
  upstream's decodePositionIds with no rope delta (each row's
  cache.ropeOffset), as Qwen3VL, Qwen3VLMoE, Qwen3.5 and GlmOcr call it.
- Gemma4.swift (MLXVLM): the same per-row cache.ropeOffset change on both
  sides; the fork's comment kept.
- LFM3.swift (MLXLLM): upstream's tokenizer error, and the marker (now in
  BatchPositionedModels.swift). One LFM3Model and one "lfm3" entry, as
  before: both sides extend upstream's ml-explore#750 model.
- MLXVLM README: both model lists.

Merged without conflict, but reconciled:
- prism_hadamard_qwen35 was registered twice in VLMTypeRegistry (a
  duplicate dictionary key traps at launch). Upstream's loader (ml-explore#630,
  both registries, its tests) replaces the fork's 8de2623 one
  (Qwen35+PrismHadamard.swift, PackedModuleInstalling,
  Qwen35Configuration.hadamardConfig); the same pack carries both
  upstream's manifest and the hadamard.json the fork read.
- prism mlx-swift's MLXNN also defines HadamardQuantizedLinear,
  HadamardQuantizedEmbedding and SignedBlockHadamard: the tests that use
  upstream's name them MLXLMCommon.*.
- SSM.swift segsum: upstream now expands the mask once; the fork's second
  expansion of the same fix is dropped.

BatchPositionedModel: upstream positions rows by cache.ropeOffset across
most models, but not all (PaliGemma, LFM2-DSpark, hybrids without an
attention cache), so the gate stays. MLXLLM's and MLXVLM's
BatchPositionedModels.swift list the models, 38 MLXLLM types and 10
MLXVLM, the fork's six moved there. Each is checked by
BatchedPrefillTests.markedModelsWriteWhatTheyWriteAlone: a tiny model
from the type registry, whose rows, read together or read alone and
joined, choose the tokens and logits they do alone. PaliGemma, which
rotates by the batch cache's one offset, fails it (logits off by 1.6 to
2.8).

Package.swift keeps smdesai/mlx-swift prism-ml.
smdesai added a commit to smdesai/mlx-swift-lm that referenced this pull request Nov 28, 2026
PaliGemma rotated every row of a batch by the cache's one offset, as
MLXVLM's Gemma 4 did before c8cd12c; it now uses each row's
cache.ropeOffset. Rows continuing cached prefixes of different lengths
were rotated to the wrong positions (tiny model: logits off by 0.29 to
6.26; paligemma-3b-mix-448-8bit: other first tokens, logits off by up
to 242).

Seventeen more types already positioned each row by its own offset
(ml-explore#773) but had no padded-row case, so they ran each request alone with
batching on. They are now marked BatchPositionedModel too, 66 types in
all: MLXLLM's afmoe, bailing_moe, bitnet, deepseek_v3, gemma3n,
glm4_moe, glm4_moe_lite, lille-130m, mellum, mimo_v2_flash, minimax and
openelm; MLXVLM's gemma4_unified, glm_ocr, muse_glimmer, qwen3_vl and
qwen3_vl_moe.

BatchedPrefillTests.markedModelsWriteWhatTheyWriteAlone has a tiny case
for each; all 66 pass. Two changes to the harness:
- The alone reference of an M-RoPE model (glm_ocr, qwen3_vl,
  qwen3_vl_moe) continues its cache with a rope delta of zero, as the
  model's prepare gives a prompt without images. Without one, GlmOcr
  and Qwen3VL stop on their warm-cache precondition. Batch rows are
  positioned per row without it.
- Untrained float64 parameters (Bitnet's weight scales) are converted
  to float32 before eval: the GPU doesn't run float64.
wballard added a commit to swissarmyhammer/mlx-swift-lm that referenced this pull request Nov 30, 2026
Apply the upstream commits a2b47a7..026d599 (the 6 after 6759555) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- a2b47a7 Batching: Use per-row rotary positions and attention scaling in LLM and VLM models (ml-explore#773)
- b4cc88a Select LFM2-MoE experts in mlx-lm's argpartition order (ml-explore#830)
- 9e0f27d Expand the segsum batch mask once, as mlx-lm does (ml-explore#829)
- 4d2d8a3 Report the full-vocabulary entropy with token log probabilities (ml-explore#822)
- fa4c14a Attend a rotating cache with a rewind reserve in place (ml-explore#727)
- 026d599 Bonsai 2.5: Rotate Hadamard-quantized activations in one Metal pass (ml-explore#835)

Conflict resolutions:
- ml-explore#773: the Qwen 3.5 VLM decode positions take upstream's
  QwenVL.decodePositionIds; the fork's version differed only by the
  MRopeAxis.count name.
- ml-explore#830: LFM2MoeRoutingTests keeps the fork's removal of the unused
  TokenizerLoaderStub and takes upstream's makeConfig(numExpertsPerToken:).
- ml-explore#822: the Evaluate.swift hunks go into the fork's GenerateParameters.swift
  (GenerateTokenLogProbabilities.entropy) and TokenIterators.swift
  (DeferredTokenLogProbabilities). The speculative log-probability test is
  not taken: the fork's SpeculativeTokenIterator reports no log
  probabilities, and the doc keeps saying so.
- ml-explore#727: the KVCache.swift hunks go into the fork's RotatingKVCache.swift
  (retainedRanges over the fork's rowRanges, so the window mask also leaves
  out vacant rows after a rewind). RotatingKVCache does NOT conform to
  KVCacheAttentionProtocol: the fork's prefill kernel, DeepSeek-V4 and
  Inkling 2 read a conforming cache as one that owns its attention (Inkling 2
  stops with a precondition). attentionWithCacheUpdate calls
  RotatingKVCache.updateAndAttend directly, and passes the fork's sinks
  through. The Qwen MTP drafter attends through PrefillAttentionKernel and
  keeps update(keys:values:). Two tests cover the sinks and the
  non-conformance.

After-merge steps: no merged model adds advance( with a manual offset +=,
no new MambaCache/ArraysCache model type, no environment-gated test.

Tests: all five bundles pass under xctest (MLXLMTests 1272 XCTest + 2865
Swift Testing, MLXGuidedGenerationTests 96, MLXFoundationModelsTests 770,
CXGrammarTests 7, MLXHuggingFaceMacrosTests 11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants