Skip to content

Batching: Apply a per-row mask to each row of Gemma 2's grouped-query scores - #772

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
ronaldmannak:batching/a0a-gemma2-mask
Nov 18, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
ronaldmannak:batching/a0a-gemma2-mask

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

Gemma 2 computes grouped-query scores as [B, kvHeads, repeats, L, S]. A per-row mask shaped [B, 1, L, S] aligns its batch axis with the key-value heads, applying the wrong row's mask or failing to broadcast. Add the missing head-group axis before applying it.
Expand four-dimensional array masks for grouped-query scores. Other mask shapes and the single-head path retain their behavior.

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: This PR is code extracted from my fork by Fable and Opus

ronaldmannak and others added 3 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>

@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, thank you!

@davidkoski
davidkoski merged commit cb59e9a into ml-explore:main Nov 18, 2026
4 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 21, 2026
Apply the upstream commits dbee7be..cb59e9a (the 18 after 6352907) 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.

- dbee7be Serialize integration tests and their model loading. (ml-explore#760)
- 7dde329 GLM-OCR: count the temporal patch in the pixel budget (ml-explore#783)
- f0d6150 fix: render null tool-call arguments in chat history (ml-explore#780)
- c6c6556 Base Gemma diffusion implementation (ml-explore#352)
- 5ecb13b Add LiquidAI LFM3 text support with extended validation and regression tests (ml-explore#756)
- 7e2c90f Match the DeepSeek-V3 MoE gate to mlx-lm (ml-explore#795)
- 700d8e2 Read r/u prefixes and adjacent string literals in PythonLiteralParser (ml-explore#799)
- c75b537 Keep the DeepSeek-V3 MoE output in the activation dtype (ml-explore#793)
- bc4746e Fix GLM-OCR small images; match smart_resize rounding in QwenVL.targetSize (ml-explore#764)
- b55217c Keep Qwen2-VL vision attention inside each image (ml-explore#755)
- dcfcf79 steering follow up and chat interrupt API (ml-explore#798)
- e589f33 Load Hadamard-rotated ternary checkpoints (prism_hadamard_qwen35) (ml-explore#630)
- cb2bd77 GPT-OSS: clip the SwiGLU with plain Float bounds (ml-explore#792)
- bf5a5d4 Declare measured budget transitions for Muse Glimmer and Qwen3.5 (ml-explore#734)
- 7517abc Let guided generation use the caller's sampler and logit processor (ml-explore#733)
- 5a14024 Refuse LoRA/DoRA on layers the adapters cannot reproduce (ml-explore#800) (ml-explore#803)
- ca661dc Size five float32 test comparisons for TF32 matmuls (ml-explore#802)
- cb59e9a Batching: Apply a per-row mask to each row of Gemma 2's grouped-query scores (ml-explore#772)

Conflict resolutions:
- ml-explore#760: the fork's MTPGreedyVerificationIntegrationTests keeps its fixture
  and moves under ModelLoadingSuite; the fixture loads the target and the
  drafter as one TestModelManager entry. The fork-only MiniMax M3 suites
  drop their private `models` for the shared one. .gitignore keeps both.
- ml-explore#352 diffusion: the edits to the monolithic Evaluate.swift and KVCache.swift
  go into the fork's split files (GenerateParameters, TokenIterators,
  GenerateTokens, GenerationLoop; KVCacheSimple/Chunked, RotatingKVCache,
  QuantizedKVCache). MTPSpeculation.makeTokenIterator builds the
  BlockDiffusionTokenIterator for a diffusion model, and throws
  unsupportedSpeculativeDecoding when a speculation is asked for, so every
  package path (FM executor, recording generate) takes it. ChatSession takes
  the diffusion branch before the fork's MTP eligibility check, with the
  pass's prompt token count; it takes no prompt-end checkpoint. The
  blockDiffusion guard is in the fork's shared private MTP init.
  TurboQuantKVCache saves the head width as a sixth meta-state value; the
  fork's strict prompt-cache validation accepts 5 (old files) or 6 values.
  The upstream KVCacheTests additions go into KVCacheTests and
  KVCacheQuantizationTests; MockMainModel (MLXLMTestSupport) gets
  `capabilities:`. New tests await the fork's async loadWeights.
- ml-explore#756 LFM3: model.validate(tokenizer:) runs before the fork's closed-
  reasoning end guard. The upstream LFM3CheckpointTests await loadWeights.
- ml-explore#755: the doc edit goes into the fork's PromptCacheFile.swift.
- ml-explore#798 interrupt: `.interrupted` and the steering boundary go into the fork's
  GenerationLoop and GenerationResults; TokenLoopHandler keeps
  emitOrCancel with `hasOutput`. Both reasoning-history tests are kept.
- ml-explore#734: the fork's QwenReasoningProtocol.qwen35 (history replay, closed
  thinking-off block) also declares the `.immediate` budget transition;
  upstream's second `qwen35` is folded into it. The family-delta test
  resets the fork's replay and prompt-strategy fields too.
- ml-explore#733: ported into the fork's GuidedDecoder/GuidedGenerationLoop split. A
  caller processor or sampler decodes plainly: guided MTP speculation stays
  greedy-only, so its output stays that of plain greedy decoding.
- ml-explore#802: the speculative log-probability test stays out (ml-explore#774 was dropped).

After the merge (CLAUDE.md):
- No manual `offset +=` after `advance(` in the merged models.
- HybridRecurrentCacheOffsetTests adds prism_hadamard_qwen35 (LLM and VLM
  classes), whose Qwen 3.5 caches include MambaCache.
- LFM3ReferenceTests.testLongContextChunking (gated by
  MLX_LFM3_LONG_CONTEXT) moves ungated to IntegrationTesting as
  LFM3LongContextProfileTests. The env-gated upstream IntegrationTesting
  suites LFM3CheckpointTests and LFM3TokenizerIntegrationTests stay gated.

Tests: MLXLMTests 1227 XCTest and 2459 Swift Testing (3 known issues),
MLXGuidedGenerationTests 85, MLXFoundationModelsTests 537, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 11 pass. Release, IntegrationTesting:
Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests,
PromptCacheSpoolCostAssessmentTests and LFM3LongContextProfileTests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
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