Skip to content

Expand the segsum batch mask once, as mlx-lm does - #829

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
Augustas11:upstream/ssm-segsum-batch-mask-v2
Nov 26, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
Augustas11:upstream/ssm-segsum-batch-mask-v2

Conversation

@Augustas11

Copy link
Copy Markdown
Contributor

Proposed changes

segsum in SSM.swift takes x as (B, H, L) and an optional (B, L) mask. It expands the mask to (B, 1, L) inside the first if let only (SSM.swift:125-128 on main). The second if let (:134-140) sees the raw (B, L) mask again, so the pair mask mask[.ellipsis, .newAxis, 0...] * mask[.ellipsis, .newAxis] is (B, L, L). It is then broadcast against xSegsum, which is (B, H, L, L). The mask's batch axis lines up with the head axis:

  • B == 1: broadcasts and is correct.
  • B > 1, H > 1, B != H: fails in broadcast_shapes.
  • B > 1, H == 1: broadcasts to (B, B, L, L), the wrong shape. Not a realistic Mamba2 config.
  • B == H > 1: broadcasts without an error, and gives wrong values. Head h of every batch row gets row h's padding mask.

This PR expands the mask once, before both uses, as mlx-lm's segsum does (mlx_lm/models/ssm.py:104-113 in v0.32.2 reassigns mask = mx.expand_dims(mask, 1)).

How it is reached

The mask comes from createSSMMask (KVCache.swift:449-454), which returns cache.makeMask(N:) (:1797-1806). That returns a (B, L) mask only when the cache has leftPadding or prepared lengths. Both are set through public API: MambaCache(leftPadding:) (KVCache.swift:1889) and prepare(lengths:) (:1754). Mamba2 passes the mask through ssmUpdate (Mamba2.swift:193-204, mask from :248) to ssmAttn on prefill (SSM.swift:285), which calls segsum (:184). NemotronH, FalconH1 and GraniteMoeHybrid call ssmUpdate too.

So a caller that builds a left-padded MambaCache for a batch of more than one row fails in broadcast_shapes today, or gets wrong values when the batch size equals the head count. Plain generate() does not: nothing in Libraries/ outside KVCache.swift sets leftPadding or calls prepare(lengths:) on a cache.

Minimal reproduction

let x = MLXRandom.normal([2, 2, 4])  // (B, H, L) with B == H
let mask = MLXArray([1, 1, 1, 1, 0, 0, 1, 1].map { Float($0) }, [2, 4])

let batched = segsum(x, mask: mask)
let row0 = segsum(x[0 ..< 1], mask: mask[0 ..< 1])
// On main: batched[0, 1] is -inf wherever row 1 is padded, but row0 has no -inf.

_ = segsum(MLXRandom.normal([2, 3, 5]), mask: MLXArray.ones([2, 5]))
// On main: fails in broadcast_shapes, (2, 5, 5) against (2, 3, 5, 5).

I worked these out from the shapes in SSM.swift:125-140. The second one I have also seen on main (below); the first one I have not observed on its own there.

Tests

Two tests in Tests/MLXLMTests/SSMTests.swift:

  • testSegsumBatchMaskMatchesPerRowSegsum uses B == H == 2. Row 0 is unpadded and row 1 pads its first two positions. Each row of the batched result must match segsum on that row alone, positions of -inf included. A single-row call is correct before and after this change, so it serves as the reference. With more than one head this is the only case where the old code gives wrong values without an error.
  • testSegsumBatchMaskBroadcastsAcrossHeads uses B = 2, H = 3. It checks the output shape, that an all-ones mask equals no mask, and that row 1's padded columns are -inf in every head. On main this one stops in broadcast_shapes rather than failing an expectation.

I ran swift test --filter SSMTests (Swift 6.3.3, Apple Silicon) on main at 6759555 with only the new tests added, then with this change:

  • Without the change, the run stopped with Fatal error: [broadcast_shapes] Shapes (2,5,5) and (2,3,5,5) cannot be broadcast (ops.cpp:4554). Swift Testing runs the cases in parallel, so the abort also ended the other four tests, the B == H test among them. I have not seen that one fail on its own on main.
  • With the change, all 5 tests in the suite pass.

I ran swift-format 604.0.0 with the repository configuration on the two changed files. CI pins 603.0.0, so the checklist box below stays unticked.

Checklist

Put an x in the boxes that apply.

  • 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: Developed with AI coding assistance, including the tests. I reviewed the code and the reasoning.

Augustas from Malibu

segsum expanded the (B, L) mask to (B, 1, L) inside the first if-let
only, so the second use built the pair mask from the raw mask: (B, L, L)
against xSegsum's (B, H, L, L). With B > 1, H > 1 and B != H that fails
in broadcast_shapes. With B == H it broadcasts against the heads
instead, and head h of every batch row gets row h's padding mask. With
H == 1 and B > 1 it broadcasts to a (B, B, L, L) result.

mlx-lm's segsum reassigns the expanded mask and uses it in both places.
Do the same. Add tests that compare a B == H batch against per-row
segsum calls, and check the B != H shape and padded positions.

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

@davidkoski
davidkoski merged commit 9e0f27d into ml-explore:main Nov 26, 2026
3 checks passed
@Augustas11
Augustas11 deleted the upstream/ssm-segsum-batch-mask-v2 branch November 27, 2026 00:22
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.
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