Repository navigation
Select LFM2-MoE experts in mlx-lm's argpartition order - #830
Merged
davidkoski merged 1 commit intoNov 26, 2026
Merged
Conversation
Lfm2MoeSparseMoeBlock took the top k with argPartition(-scores, kth: k - 1)[..<k]. mlx-lm's Lfm2MoeSparseMoeBlock uses argpartition(scores, kth=-k)[..., -k:]. On the same scores and without ties both select the same experts, but in a different order: on the GPU, MLX computes argpartition with the same sort as argsort, so the old form gives the top k in descending score order and mlx-lm's in ascending order. weightedExpertSum adds the expert outputs in that order, so with k > 2 and bfloat16 activations the sum can round differently from mlx-lm's. Use mlx-lm's expression in both branches. Add tests with k = 3 and a bfloat16 expert MLP, with and without expert_bias, that check the routed order against argsort and the block output against the sum in that order, and that the reverse order gives a different bfloat16 output.
davidkoski
approved these changes
Nov 26, 2026
davidkoski
left a comment
Member
There was a problem hiding this comment.
Change looks good, thank you!
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
Lfm2MoeSparseMoeBlock.routetakes the top k experts withargPartition(-scores, kth: k - 1)[.ellipsis, ..<k](LFM2MoE.swift:361and:363onmain). mlx-lm'sLfm2MoeSparseMoeBlockusesmx.argpartition(scores, kth=-k, axis=-1)[..., -k:](mlx_lm/models/lfm2_moe.py:221and:223in v0.32.2). On the same scores and without ties, both pick the same experts, but in a different order.The order matters because
weightedExpertSumadds the k expert outputs along that axis (MLXLMCommon/SwitchLayers.swift:13-17, called atLFM2MoE.swift:377). mlx-lm does the same sum atlfm2_moe.py:233. With k > 2 and bfloat16 activations, adding the same terms in another order can round differently.This PR uses mlx-lm's expression in both branches, the biased and the plain one. Like #795 for the DeepSeek-V3 gate, it is a change to match mlx-lm.
MLXVLM/Models/Gemma4Assistant.swift:112andGPTOSS.swift:75-76already take the top k in mlx-lm's form.Why the two orders differ
On the GPU, MLX computes
argpartitionwith the same merge sort asargsort. Inmlx/backend/metal/sort.cppon MLXmain,ArgPartition::eval_gpuis commented "We direct arg partition to sort for now" and callsgpu_merge_sort(..., true), the same callArgSort::eval_gpumakes. So mlx-lm's expression gives the top k in ascending score order. The old Swift expression gives them in descending order.The bfloat16 sum keeps a bfloat16 accumulator.
reduce.metalinstantiatessumfor bfloat16 with a bfloat16 output type. For a reduction over fewer than 32 rows,reduce.cpppickscol_reduce_small(kernels/reduction/reduce_col.h). With up to 8 rows each thread reads one row and thread 0 adds them in row order in the output type, so k = 3 and k = 4 are summed one after another. I read these files on MLXmain, not the exact version this package resolves.Minimal reproduction
A block with 4 experts,
num_experts_per_tok: 3, a float32 gate, a bfloat16 expert MLP and 64 bfloat16 tokens. Onmain,route(x).indicesis in descending score order, andblock(x)differs from the same weighted sum taken in mlx-lm's ascending order. The new test builds exactly this.The released
LiquidAI/LFM2-8B-A1Bconfig.jsonhasnum_experts_per_tok: 4,num_experts: 32anddtype: bfloat16, so it is in the k > 2, bfloat16 case.Tests
testExpertOrderMatchesMLXLMInBFloat16andtestBiasedExpertOrderMatchesMLXLMInBFloat16inTests/MLXLMTests/LFM2MoeRoutingTests.swift. They use the setup above, with a fixed seed. The second adds anexpert_biasof[0, 0, 0.5, 0], so it covers the biased branch, which the released checkpoint uses. Each checks:route(x).indicesequals the last 3 ofargSorton the selection scores (with the bias added in the second test), which is what mlx-lm's expression gives on the GPU.block(x)is bfloat16 and is equal element by element toweightedExpertSumover the experts in that order, with weights from the unbiased scores.makeConfiggets anumExpertsPerTokenparameter for this. The default stays 2, so the other tests are unchanged. The existing bias tests compare expert sets, so before this the biased branch's order was not pinned by any test.What this does not show: I have not run a real LFM2-MoE checkpoint, so I make no claim about token output. The test also assumes the default GPU device. It does not cover the CPU
argpartition, whose order I have not checked. This change aligns the summation order only. Swift computes the routing scores and the normalised weights in float32 (LFM2MoE.swift:355,:366-370), where mlx-lm keeps the gate dtype (lfm2_moe.py:216,:226-230). With a bfloat16 gate the selected order and the weights can therefore still differ from mlx-lm. I have not compared the block output with mlx-lm's.I ran
swift test --filter LFM2MoeRoutingTests(Swift 6.3.3, Apple Silicon) onmainat 6759555 with only the new tests added, then with this change:LFM2MoeRoutingTests.swift:164and:168), and on the output check that follows it.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