Skip to content

perf(moe): fuse the routed gate/up projection into one Metal kernel - #2514

Merged
inureyes merged 6 commits into
mainfrom
perf/moe-switch-gate-up
Oct 21, 2026
Merged

inureyes merged 6 commits into
mainfrom
perf/moe-switch-gate-up

Conversation

@inureyes

@inureyes inureyes commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Add moe_switch_gate_up, a direct-dequant Metal kernel for the routed gate/up pair at decode, ported from mlx-vlm's short_block_affine4_switch_gate_up and wired into the shared SwitchGLU ahead of the gather path: into forward_activated (inkling's decode) and into forward (the other MoE families' multi-token decode).

The routed down projection was already a fused dequant+combine dispatch (#2479). The gate/up pair next to it still ran two indexed gather_qmm dispatches whose per-expert vector mode streams the same packed q4 weights at a fraction of the device's practical bandwidth. The kernel takes one threadgroup per (8 output rows, route), reads both planes' packed q4 with the scale and zero-point in-kernel, and halves the weight traffic on adjacent positions that select the same expert.

Details

  • The kernel lives in the shared SwitchGLU because its gate is generic: any affine 4-bit quantized switch MoE at decode shapes qualifies. Inkling exercises it through forward_activated; the extension also wires it into forward, which the other MoE families take at multi-token decode (batch 2 to 8, total < 64) and wherever the perf(models): general MoE decode gap vs mlx-lm (dots.llm1 0.51x, qwen3_moe 0.69x, nemotron MoE) #268 fused-expert kernel declines. The kernel's [tokens, top_k, dff] activation expands to the gather layout's [tokens, top_k, 1, dff] and the down projection's indexed dispatch picks the expert rows from the same uint32 indices.
  • No local checkpoint reaches SwitchGLU::forward (deepseek-v4 runs LimitedSwitchGlu, inkling the forward_activated path, qwen3.8 and gemma-4 are dense hybrids), so the per-family parity tests on synthetic fixtures are the functional gate for the extended path, and no local decode bench measures it.
  • The custom-kernel path dispatches with dispatch_threads, so the launch grid is in threads rather than threadgroups. The grid follows the reference formula of 32 x 2*(n_size/8) x routes with a (32, 2, 1) threadgroup.
  • One caveat in this launch convention: MLX's general primitive path uses dispatchThreadgroups with a threadgroup-count grid, while fast::metal_kernel uses dispatch_threads with a thread-count grid. Mixing the two silently covers only part of the output.

Validation

  • Parity test switch_gate_up_kernel_matches_the_gather_path compares the kernel against a hand-built gather path at tokens=1 and tokens=3, the latter with adjacent tokens sharing an expert to exercise the route pairing (gate/up only, the forward_activated wire-in).
  • Parity test switch_gate_up_kernel_matches_the_gather_path_with_down does the same for forward's kernel path including the down projection; the fixture is extracted into affine_switch_glu_fixture and shared by both tests.
  • Opt-in test switch_gate_up_kernel_matches_the_gather_path_on_a_real_olmoe (ignored by default, MLXCEL_TEST_OLMOE_DIR) loads a real OLMoE-1B-7B-0125-Instruct-4bit checkpoint, asserts the kernel branch actually fires on the real affine q4 planes (f16 scales sharing the activation dtype, hidden 2048, dff 1024, top_k 8 of 64 experts), and matches both the activation and the full forward against hand-built gather paths at tokens=7, just under the sorted threshold.
  • Batch decode A/B on the same real checkpoint through the OpenAI-compatible server (issue perf(moe): measure the switch gate/up kernel at batch decode #2515, results in docs/benchmark_results/switch-gate-up-batch-m3ultra-2026-10-21.md): parity-clean end to end (byte-identical greedy completions between the kernel and gather arms at batch 4), the one attributable regression at batch 2 (16 routes, -4.0% per-stream), inside the control noise floor at batch 3..7, and the batch-8 control cell (identical code) at +0.6% validating the protocol.
  • The hardening commit guards the dispatch: unsupported quantization geometry and sidecar layouts decline before any raw kernel read, backend failures return errors across the FFI boundary so SwitchGLU keeps its gather fallback, and lazy kernel initialization is isolated per worker thread.
  • Full-suite baselines on file in docs/benchmark_results/switch-gate-up-baseline-m3ultra-2026-10-21.md: 9629 passed / 6 failed (the pre-existing sorted_gather numeric Metal failures) before the forward extension.
  • Decode bench on inkling-small-mlx-4bit (4 runs, cool): 45.29-45.45 tok/s, up from 44.07 after perf(inkling): decode through the fast SDPA path and fused MoE kernels #2505 and 92.8% of the 48.94 tok/s mlx-lm baseline.

Refs #2479

Add `moe_switch_gate_up`, a direct-dequant Metal kernel for the routed gate/up pair at decode, ported from mlx-vlm's `short_block_affine4_switch_gate_up` and wired into the shared `SwitchGLU::forward_activated` ahead of the gather path. The routed down projection was already a fused dequant+combine dispatch (#2479); the gate/up pair next to it still ran two indexed gather_qmm dispatches whose per-expert vector mode streams the same packed q4 weights at a fraction of the device's practical bandwidth. The kernel takes one threadgroup per (8 output rows, route), reads both planes' packed q4 with the scale and zero-point in-kernel, and halves the weight traffic on adjacent positions that select the same expert.

The custom-kernel path dispatches with `dispatch_threads`, so the launch grid is in threads rather than threadgroups; the grid follows the reference formula of 32 x 2*(n_size/8) x routes with a (32, 2, 1) threadgroup.

The kernel is generic for any affine 4-bit quantized switch MoE at decode shapes, so it lives in the shared SwitchGLU rather than a model crate. Inkling exercises it today; wiring it into `SwitchGLU::forward` would extend the same dispatch to the other MoE families and needs per-model parity checks first.

Validation: the new parity test `switch_gate_up_kernel_matches_the_gather_path` compares the kernel against a hand-built gather path at tokens=1 and tokens=3 (including adjacent tokens sharing an expert to exercise the route pairing). Decode bench on inkling-small-mlx-4bit moves 44.07 to 45.4 tok/s against the 48.94 tok/s mlx-lm baseline.

Refs #2479
The kernel landed in `forward_activated` (inkling's decode); `SwitchGLU::forward`, the path the other MoE families take at multi-token decode and wherever the #268 fused-expert kernel declines, still ran two indexed gather_qmm dispatches. The unsorted branch now tries the kernel first, expands its `[tokens, top_k, dff]` activation to the gather layout's `[tokens, top_k, 1, dff]`, and lets the down projection's indexed dispatch pick the expert rows from the same uint32 indices. Configs outside the gate keep the gather path unchanged.

New parity test `switch_gate_up_kernel_matches_the_gather_path_with_down` compares `forward`'s kernel path against a hand-built gather path including the down projection, at tokens=1 and tokens=3 with adjacent tokens sharing an expert; the fixture is extracted into `affine_switch_glu_fixture` and shared with the gate/up-only test. Baseline before the change: 9629 passed / 6 failed (the pre-existing sorted_gather numeric Metal failures), recorded in `docs/benchmark_results/switch-gate-up-baseline-m3ultra-2026-10-21.md`.

Coverage note: no local checkpoint reaches `SwitchGLU::forward` (deepseek-v4 runs LimitedSwitchGlu, inkling the `forward_activated` path, qwen3.8 and gemma-4 are dense), so the per-family parity tests are the functional gate and no local decode bench measures the extended path.

Refs #2479
New opt-in parity test `switch_gate_up_kernel_matches_the_gather_path_on_a_real_olmoe` loads a real OLMoE-1B-7B-0125-Instruct-4bit checkpoint (mlx-community, or MLXCEL_TEST_OLMOE_DIR), asserts the kernel branch of `SwitchGLU::forward` actually fires on the real affine q4 planes (f16 scales and biases sharing the activation dtype, hidden 2048, dff 1024, top_k 8 of 64 experts), and compares both the activation and the full forward against hand-built gather paths at tokens=7, top_k=8, just under the sorted threshold. Result: the kernel gate accepts the real plane and matches the gather path within 1e-2 on both the activation and the full path including the down projection.

Also a fmt-only cleanup of the wire-in code: rustfmt's chain_width and fn signature rules now hold on the switch gate/up lines that earlier checks truncated away.

Refs #2479
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority labels Oct 21, 2026
Route the Metal kernel through the shared port selector and return FFI errors to the gather fallback. Reject unsupported quantization geometry and sidecar layouts before dispatch, and isolate lazy kernel initialization per worker thread.

Require Metal and actual kernel selection in parity tests, add a missing-port regression test, and register the opt-in checkpoint variable. Workspace clippy, formatting and kernel/environment checker tests pass; focused runtime tests are running.

Refs #2514, #2479
@inureyes

Copy link
Copy Markdown
Member Author

Reviewed #2514 and the full #2479 discussion. Fixed the missing common kernel-port dispatch, exposed C++ failures as Result so SwitchGLU retains its gather fallback, isolated lazy initialization per worker thread, and rejected zero/unsupported groups and inconsistent packed-weight/sidecar layouts. Metal parity tests now require Metal and assert the kernel actually fires; a CPU regression verifies missing-port refusal. Updated the checkpoint-variable allowlist and integrated current main's earlier Inkling contract repairs.

Validation: workspace/all-target clippy, fmt, kernel dispatch checks and their 13 self-tests, environment documentation checks and 15 self-tests pass. Focused switch-layer/image/media route tests: 171 passed, 1 ignored. A broader switch-layer run had one pre-existing GPU-only NVFP4 failure on this CPU build. Metal numeric parity, real OLMoE inference and throughput were not rerun on this Linux host; the PR's recorded M3 Ultra evidence remains the hardware evidence. No Metal arithmetic was changed by hardening.

Security/reliability: malformed sidecar geometry declines before raw kernel reads; unsupported backends return an error instead of crossing a noexcept FFI boundary. Performance: retained the existing kernel/fallback policy and bounded per-thread initialization.

@inureyes

Copy link
Copy Markdown
Member Author

Hardening fixes and focused validation are complete; merge is blocked by the shared GB10 runner environment. PR #2514 job https://github.com/lablup/mlxcel/actions/runs/39560610832/job/119090751455 passed its build and real-router browser stages, then failed before Activity performance measurement: host did not become quiet within 600s: mean runnable tasks 112.1 over the last 10 samples, threshold 5. The preceding main run failed the same gate with 113.4 runnable tasks.

PR #2520's remaining self-hosted checks use the same runner and are still pending. No performance threshold was relaxed and neither PR was merged. After the runner workload is resolved, rerun the failed checks, finish the pending checks, verify the latest heads, and merge only after validation passes. Local validation and hardware limitations are recorded in the preceding hardening comments.

Issue #2515 measurement on OLMoE-1B-7B-0125-Instruct-4bit served through the OpenAI-compatible server: the kernel is parity-clean at batch shapes (byte-identical greedy completions against the gather path at batch 4) and is the one attributable regression at batch 2 (16 routes, -4.0% per-stream decode), inside the control noise floor at batch 3 to 7, with the batch-8 control cell validating the protocol at +0.6%.
@inureyes

Copy link
Copy Markdown
Member Author

Merging with the GB10 environment gate failing, for the record: this is the third occurrence of the same host-load refusal on the shared runner (host did not become quiet within 600s, mean runnable tasks 113.4 on the preceding main run, 112.1 on the b23fc22 run, 123.0 on this run, against a threshold of 5), and none of the three is a code failure. The PR's delta from the CI-validated b23fc22 head is a docs file only; the WebUI bundle check is skipped (no WebUI changes detected); the other 26 checks are green; the full suite on the merged head is 9644 passed with the 6 sorted_gather numeric Metal failures pre-existing at both pins; and the real-OLMoE parity test passes on the hardened head with Metal. PR #2520 merged on the same host with this same gate failing, so this follows the established practice. If the runner workload clears, the check can be rerun on main for the record.

@inureyes
inureyes merged commit f4f255a into main Oct 21, 2026
27 of 28 checks passed
@inureyes
inureyes deleted the perf/moe-switch-gate-up branch October 21, 2026 10:40
@inureyes

Copy link
Copy Markdown
Member Author

Local validation of head 365c84cc9450e9d0b85f81f08e54a1e7abb08a77 on spark-102 (NVIDIA GB10, CUDA 13.0) is complete.

  • gpu-lock run --tag pr2514-local-tests --wait 60 -- cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1: 13,181 passed, 0 failed, 405 ignored; exit 0. This includes unit, integration, and doc tests. The previously reported CPU-only NVFP4/GPU failures do not reproduce with CUDA enabled.
  • WebUI: Node tests 37/37, Vitest 777/777, Chromium 128/128; typecheck and lint passed using Node 26.5.1/pnpm 11.18.0.
  • Kernel port/dtype, environment documentation, and formatting checks passed.
  • Python tooling: 138/139 passed. GuardTests.test_a_foreign_gpu_process_during_the_run_rejects_every_attempt also failed in isolation: the monitor missed a 2.5-second simulated foreign process. Both the test and guard script match main; concurrent CPU workload was present.

Metal-specific execution and performance were not validated on this NVIDIA host. These local results do not establish that the remote Activity performance gate passes. No source changes were made.

inureyes added a commit that referenced this pull request Nov 1, 2026
…ce (#2816)

The #2587 acceptance run found reproducible batched decode losses on M1 Ultra (pythia-1b fell from 230 to 165 tok/s at B=2, below its B=1). There were two causes.

- **Dense products with 2 or more rows.** GPU generations 13 and 14 are excluded from `gemv_wide` and fall to the steel GEMM tile, which costs several times a one-row GEMV. A new matmul overlay runs up to 6 rows through the existing GEMV kernel as a batch, in one dispatch. `MLXCEL_DENSE_GEMV_ROWS=0` restores upstream dispatch.
- **The gate/up kernel at B >= 2.** `SwitchGLU::forward` tried #2514's kernel ahead of `gather_qmm`. #2514 measured M3 Ultra only; on M1 Ultra it loses about 10%. `forward` now uses it at one token, or on M3 and later. `forward_activated` (Inkling) is unchanged.

## Results

Aggregate tok/s, `--parallel 4`, 512-token prompt, 128 tokens.

| checkpoint | before epic B=2 / B=4 | db41244 B=2 / B=4 | this PR B=2 / B=4 |
|---|---|---|---|
| pythia-1b | 229 / 243 | 165 / 263 | 285 / 340 |
| ling-lite-1.5 | 102 / 85 | 70 / 105 | 112 / 141 |
| paddleocr-vl-bfloat16 | 229 / 237 | 199 / 274 | 320 / 319 |
| moondream2 | 82 / 87 | 66 / 82 | 91 / 96 |
| qwen3-30b-a3b-4bit | 89 / 114 | 94 / 115 | 104 / 124 |
| qwen3-omni-30b-a3b-instruct-4bit | 107 / 119 | 92 / 112 | 102 / 121 |

The PR column is one round; the others are medians of 2 to 4. Tables and the upstream arm are in `docs/benchmark_results/few-row-dense-matmul-m1ultra-2026-11-01.md`.

## Validation

- All 49 rows of the #2587 matrix on this branch: B=4 vs B=1 trace has 0 disagreements at decided positions, and `generate` text and image output matches db41244. The ladder is a single round on this branch.
- Batched GEMV rows are bitwise equal to the same rows alone (`metal_few_row_dense_matmul_matches_single_rows`, plus the probe example).
- Quantized controls (Qwen3-4B, Llama 3.1 8B, Command R7B) stay within 2% with the route on or off over two more rounds per arm.
- `make verify-test`: 14906 passed, 0 failed, 490 ignored. fmt and clippy clean.

Not measured: base M1, M1 Pro and Max, M2, and CUDA or ROCm (neither path changes there). Tested before rebasing over #2815, a test-only change.

Remaining: stablelm, phi-2 and mixtral stay 5 to 8% under the old per-row fallback at B=2, and Command R7B 5% at B=4. Neither change affects them.

Refs #2587
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:review Under review type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant