Skip to content

Select LFM2-MoE experts in mlx-lm's argpartition order - #830

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
Augustas11:upstream/lfm2moe-expert-order-v2
Nov 26, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
Augustas11:upstream/lfm2moe-expert-order-v2

Conversation

@Augustas11

Copy link
Copy Markdown
Contributor

Proposed changes

Lfm2MoeSparseMoeBlock.route takes the top k experts with argPartition(-scores, kth: k - 1)[.ellipsis, ..<k] (LFM2MoE.swift:361 and :363 on main). mlx-lm's Lfm2MoeSparseMoeBlock uses mx.argpartition(scores, kth=-k, axis=-1)[..., -k:] (mlx_lm/models/lfm2_moe.py:221 and :223 in v0.32.2). On the same scores and without ties, both pick the same experts, but in a different order.

The order matters because weightedExpertSum adds the k expert outputs along that axis (MLXLMCommon/SwitchLayers.swift:13-17, called at LFM2MoE.swift:377). mlx-lm does the same sum at lfm2_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:112 and GPTOSS.swift:75-76 already take the top k in mlx-lm's form.

Why the two orders differ

On the GPU, MLX computes argpartition with the same merge sort as argsort. In mlx/backend/metal/sort.cpp on MLX main, ArgPartition::eval_gpu is commented "We direct arg partition to sort for now" and calls gpu_merge_sort(..., true), the same call ArgSort::eval_gpu makes. 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.metal instantiates sum for bfloat16 with a bfloat16 output type. For a reduction over fewer than 32 rows, reduce.cpp picks col_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 MLX main, 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. On main, route(x).indices is in descending score order, and block(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-A1B config.json has num_experts_per_tok: 4, num_experts: 32 and dtype: bfloat16, so it is in the k > 2, bfloat16 case.

Tests

testExpertOrderMatchesMLXLMInBFloat16 and testBiasedExpertOrderMatchesMLXLMInBFloat16 in Tests/MLXLMTests/LFM2MoeRoutingTests.swift. They use the setup above, with a fixed seed. The second adds an expert_bias of [0, 0, 0.5, 0], so it covers the biased branch, which the released checkpoint uses. Each checks:

  • route(x).indices equals the last 3 of argSort on 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 to weightedExpertSum over the experts in that order, with weights from the unbiased scores.
  • The same experts in descending order give a bfloat16 output that is not equal element by element. This shows the test can tell the two orders apart. With k = 2 the two sums are equal and the previous check would pass for either order.

makeConfig gets a numExpertsPerToken parameter 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) on main at 6759555 with only the new tests added, then with this change:

  • Without the change: 16 tests, 2 skipped, 4 failures. Both new tests fail on the index order (LFM2MoeRoutingTests.swift:164 and :168), and on the output check that follows it.
  • With the change: 16 tests, 2 skipped, 0 failures.

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

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 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 b4cc88a into ml-explore:main Nov 26, 2026
3 checks passed
@Augustas11
Augustas11 deleted the upstream/lfm2moe-expert-order-v2 branch November 27, 2026 00:22
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