Repository navigation
Expand the segsum batch mask once, as mlx-lm does - #829
Merged
davidkoski merged 1 commit intoNov 26, 2026
Merged
Conversation
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
approved these changes
Nov 26, 2026
davidkoski
left a comment
Member
There was a problem hiding this comment.
Changes look good, thank you!
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
segsuminSSM.swifttakesxas (B, H, L) and an optional (B, L) mask. It expands the mask to (B, 1, L) inside the firstif letonly (SSM.swift:125-128onmain). The secondif let(:134-140) sees the raw (B, L) mask again, so the pair maskmask[.ellipsis, .newAxis, 0...] * mask[.ellipsis, .newAxis]is (B, L, L). It is then broadcast againstxSegsum, which is (B, H, L, L). The mask's batch axis lines up with the head axis:broadcast_shapes.hof every batch row gets rowh's padding mask.This PR expands the mask once, before both uses, as mlx-lm's
segsumdoes (mlx_lm/models/ssm.py:104-113in v0.32.2 reassignsmask = mx.expand_dims(mask, 1)).How it is reached
The mask comes from
createSSMMask(KVCache.swift:449-454), which returnscache.makeMask(N:)(:1797-1806). That returns a (B, L) mask only when the cache hasleftPaddingor prepared lengths. Both are set through public API:MambaCache(leftPadding:)(KVCache.swift:1889) andprepare(lengths:)(:1754). Mamba2 passes the mask throughssmUpdate(Mamba2.swift:193-204, mask from:248) tossmAttnon prefill (SSM.swift:285), which callssegsum(:184). NemotronH, FalconH1 and GraniteMoeHybrid callssmUpdatetoo.So a caller that builds a left-padded
MambaCachefor a batch of more than one row fails inbroadcast_shapestoday, or gets wrong values when the batch size equals the head count. Plaingenerate()does not: nothing inLibraries/outsideKVCache.swiftsetsleftPaddingor callsprepare(lengths:)on a cache.Minimal reproduction
I worked these out from the shapes in
SSM.swift:125-140. The second one I have also seen onmain(below); the first one I have not observed on its own there.Tests
Two tests in
Tests/MLXLMTests/SSMTests.swift:testSegsumBatchMaskMatchesPerRowSegsumuses B == H == 2. Row 0 is unpadded and row 1 pads its first two positions. Each row of the batched result must matchsegsumon 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.testSegsumBatchMaskBroadcastsAcrossHeadsuses 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. Onmainthis one stops inbroadcast_shapesrather than failing an expectation.I ran
swift test --filter SSMTests(Swift 6.3.3, Apple Silicon) onmainat 6759555 with only the new tests added, then with this change: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 onmain.I ran
swift-format604.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
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.
Augustas from Malibu