Repository navigation
Moe refactoring -> reduces repeated small graph construction overhead - #324
Merged
Merged
Conversation
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>
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
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:
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 forSwitchGLU/FusedGateUpSwitchGLU, covering the common: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
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes