Skip to content

Moe refactoring -> reduces repeated small graph construction overhead - #324

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:moe_optimisation
Jun 3, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:moe_optimisation

Conversation

@aleroot

@aleroot aleroot commented May 31, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

This PR reduces repeated small graph construction overhead in shared MoE paths.

Many MoE models combine routed expert outputs with router scores using the same expression:

(outputs * weights[..., .newAxis]).sum(axis: -2)

This PR centralizes that pattern behind a shared compiled helper, weightedExpertSum, and updates MoE model implementations to use it. It also adds a compiled default-SiLU product path for SwitchGLU / FusedGateUpSwitchGLU, covering the common:

silu(gate) * up

case while preserving the existing generic path for custom activations.

The intent is to reduce Swift/MLX dispatch and graph setup overhead in MoE-heavy models without changing model math, weights, quantization, cache behavior, or dependency versions.

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)

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

Nice idea, thank you!

@davidkoski
davidkoski merged commit ef85ed0 into ml-explore:main Jun 3, 2026
2 checks passed
angelsbrood added a commit to angelsbrood/mlx-swift-lm that referenced this pull request Jun 9, 2026
Pulls in 11 upstream commits, including three that touched Gemma4.swift:
- 01b8624 Fix Gemma4Text quantized KV cache attention (ml-explore#237)
- de2fed7 Make Gemma 4 per_layer_model_projection quantizable (ml-explore#309)
- ef85ed0 Optimize shared MoE combine paths (ml-explore#324)

Two conflict hunks in Libraries/MLXVLM/Models/Gemma4.swift:

Hunk 1 (around line 189): Our branch added `enum Gemma4SharedKVState` and
made `gemma4AdjustAttentionMask` module-internal (was `private`) so
Gemma4Assistant.swift can use both. Upstream kept the function `private`
since it doesn't have the drafter consuming these. Resolution: keep
HEAD's enum + non-private declaration.

Hunk 2 (around line 599): Upstream's ml-explore#324 optimized the shared MoE
combine path to use `weightedExpertSum(...)` in place of the manual
`(expertOutput * weights).sum(axis: -2)` pattern. Our branch added a
`Gemma4ScaledLinear` class immediately after that combine code. The two
changes landed within Git's 3-line conflict context. Resolution: take
upstream's optimized combine (including the `topK` reshape without the
trailing-1 dim) AND preserve our `Gemma4ScaledLinear` class definition
that follows it. Net: upstream's perf win + our drafter helper class
both present.

The four Phase A-D commits (55c55b2, c6af858, 9b55aa4, bc2f8e3) sit
on top of this merge with their SHAs preserved — important for the
inline reply comments on PR ml-explore#308 that reference them directly.

Build verified clean (xcodebuild build-for-testing -scheme IntegrationTesting
succeeds with no errors). Test run pending after push.
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…#324)

* style(qwen35): format Qwen35.swift

Format-only: swift format with the repository .swift-format, no code
change. The Lint workflow formats every Swift file a pull request
touches, and Qwen35.swift has not been formatted on main since that
check began, so the next change to the file must carry this first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Run Qwen GDN prompt windows on bit-exact four-row kernels

gated_delta_step gives every value row a whole SIMD group (four state
elements per lane) and pays two 32-lane reductions per row and position,
so Qwen3.5/3.6/3.8 and Qwen3-Next prompt prefill spends most of its
recurrence time on reductions and per-row reloads of q and k.

Unmasked prompt windows of at least 16 positions with Dk = 128 now take one
of two kernels with four value rows per SIMD group:
- gated_delta_step_packed: eight lanes per row. Each lane runs four stock
  lanes' Kahan chains and combines them in simd_sum's ascending butterfly
  order.
- gated_delta_step_rows: the stock lane layout and per-row source,
  simd_sum included, for four rows that share each position's q/k loads.

The prefix cache relies on a dense GDN state being bit-identical whatever
chunk partition produced it, and short windows, decode, MTP verify and
masked updates keep the stock kernel. So a prompt kernel must reproduce
gated_delta_step bit for bit. The packed kernel does only where simd_sum
lowers to that butterfly. On the first prompt window of each kernel
instantiation (dtype and head geometry) the update therefore tries the
candidates in order (packed, then rows) on a fixed 32-position window and
keeps the first whose y and state match the stock kernel's bits on this
GPU, or else the stock kernel.
The probe is one small evaluation per instantiation and process, like the
lazy fused input projection's.

DARKBLOOM_TTFT_GDN_BLOCKED=0 keeps the stock kernel. packed or rows skip
the probe and force a kernel for A/B runs.

Per layer on M5 Ultra (bf16 inputs, fp32 state, interleaved rounds),
stock -> packed / rows:
  Qwen3.5-9B, 35B-A3B (Hk 16, Hv 32)  T=512   0.43 -> 0.29 / 0.35 ms
                                      T=4096  3.16 -> 1.93 / 2.44 ms
  Qwen3.8-27B (Hk 16, Hv 48)          T=512   0.55 -> 0.38 / 0.44 ms
                                      T=4096  3.95 -> 2.33 / 2.87 ms
Both reproduce the stock kernel bit for bit there (all 60 test cases
below), and the probe selects packed for every instantiation. Other GPU
families are untimed; there the probe still keeps the stock bits. At these
shapes the Qwen4 blocked-seq kernel is no faster than stock (1.03x /
0.95x). Upstream MLX's chunked kernels (ml-explore/mlx #4020: simdgroup
C=8 and NAX C=16) reach 1.4-1.8x and are not bit-exact.

GatedDeltaPrefillTests compares both candidates with the stock kernel at
the 9B, 27B and 35B-A3B head geometries for T in {1, 7, 64, 512, 2048}
(bf16 and fp32 inputs, fp32 state), bounds them by a Double reference,
checks that chunk partitions carry the state bit for bit through
gatedDeltaUpdate, keeps decode and the longest MTP verify window
(1 + CBv2MTPConfig.testedMaxDraftTokens positions) on the stock kernel, and
adds an opt-in per-layer timing table (DARKBLOOM_GDN_PREFILL_BENCH=1) for
calibrating other GPUs. fork.yaml describes the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(qwen4): format Qwen4ExpGDNBlocked.swift

Format-only: swift format with the repository .swift-format, no code
change. The formatter re-indents the gdnBlockedHeader string literal
together with its closing delimiter, so the string's value (and the
Metal source) is unchanged. The next commit edits this file's header
comment, and the Lint workflow formats every Swift file a pull request
touches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Correct two GDN kernel-selection comments

Comment-only. The Qwen4 blocked-seq header still said that 27B qwen3_5
stays on the existing kernel; its prompt windows now take the four-row
prompt kernels of GatedDeltaPrefill. The GatedDeltaPrefill documentation
said the probe runs both candidates; it tries them in order and stops at
the first that reproduces the stock kernel's bits, so rows is compiled
and run only when packed is rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Take the GDN prompt-kernel value width from its geometry

GatedDeltaPrefill.kernel took the value head width twice, as valueHeadDim
and inside the geometry it probes, so the dispatch check and the probe
could see different widths. It now reads the width from the geometry.
The mask check moves from matchesGeometry into kernel, as
Qwen4ExpGDNBlockedSeq keeps the mask out of its matchesGeometry.
gatedDeltaUpdate passed the same Dv twice, so every dispatch decision is
unchanged. The kernel sources and the probe are unchanged.

The probe and every parity check rely on GatedDeltaPrefill.bitsEqual, and
no test covered it: a comparator that used == or a tolerance would let the
probe accept a kernel that is not bit-exact, and the parity tests would
still pass. bitsEqualComparesRawBits fails if signed zeros or values one
ulp apart compare equal, or if the same NaN does not. In
chunkPartitionsCarryStateBitwise the carried state is no longer optional,
which removes an unreachable fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Brings ml-explore#322 (Flint), ml-explore#324, ml-explore#326-ml-explore#330 (CBv2 paged/MTP/SDPA, GPT-OSS), ml-explore#325 and the
Nemotron Super fused MTP verify window: SDK main up to the commit d-inference
master pins (889fe3c). Main's later ml-explore#331/ml-explore#332 are left out until the provider
adopts ml-explore#332's streamed tool-call type. Package.swift pins the cluster
mlx-swift 9fe34405 instead of main's 67dc7528; that was the only conflict.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants