Skip to content

perf(moe): route granite-4.0-h single-token MoE through the fused kernel - #2283

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-2245-granite-fused-moe
Oct 13, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-2245-granite-fused-moe

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

GraniteMoeHybridMoE::forward always ran SwitchGLU::forward plus moe_weighted_sum (the gather_qmm path), so the fused single-token decode MoE kernel (#268, ROCm port #2065) never ran for granite-4.0-h; the #2061 profile measured the fallback MoE at 25.4% of decode GPU time on gfx1151.

What changed

  • At one routed token with MLXCEL_FUSED_MOE on, GraniteMoeHybridMoE::forward calls SwitchGLU::forward_fused_kernel with the router top-k indices and f32 softmax scores and reshapes the result to [1, hidden_dim]; on None or more than one token the gather path is kept.

  • The shared expert and router are unchanged; forward_fused_kernel declines unsupported configs itself, so no extra gating.

  • The Used by list on forward_fused_kernel and the reach statement in the gfx1151 decode profile doc are updated.

  • A reproduction test drives the production forward at one token and asserts its output is bit-exact the fused-kernel computation and not the gather computation; it fails without the routing and passes with it (verified by forcing the fused branch off on gfx1151).

Test plan

  • cargo test --profile test-fast --features rocm granitemoehybrid -- --test-threads=1: 12 passed, 0 failed, including the new routing test and the fused-kernel parity test.

  • logit_trace of granite-4.0-h-tiny-4bit with MLXCEL_FUSED_MOE=0 vs default: 0 of 96 positions mismatched, 0 decided mismatches at gap 2.0.

  • Guarded decode throughput on gfx1151 (three interleaved runs per arm): fused 105.0/105.7/105.2 tok/s vs fallback 95.9/96.2/95.3 tok/s (1211 to 1220 ms vs 1331 to 1344 ms per 128 generated tokens), about 10% faster and well beyond run-to-run spread, so the default stays on.

  • make verify-rocm passes locally; hosted CI is down and the local gate is the merge gate. The branch also carries a mechanical expect_err fix for the clippy 1.97 err_expect lint that has been failing verify-clippy-rocm on main since fc45284.

Closes #2245

GraniteMoeHybridMoE::forward always called SwitchGLU::forward plus moe_weighted_sum, the gather_qmm path, so the fused single-token decode MoE kernel (#268, ROCm port #2065) never ran for granite-4.0-h and every decode step paid the fallback (25.4% of decode GPU time on gfx1151 per the #2061 profile).

Follow the Mixtral pattern: at one token with MLXCEL_FUSED_MOE on, call SwitchGLU::forward_fused_kernel with the router's top-k indices and f32 softmax scores (which already equal renormalized top-k softmax), and reshape the result to [1, hidden_dim]; on None or more than one token keep the gather path. The shared expert and router are unchanged; forward_fused_kernel already declines unsupported configs.

Also expose build_feed_forward/FeedForward/GraniteMoeHybridMoE.switch_mlp at pub(crate) so the granite test module can load a real quantized block, add a Used by list on forward_fused_kernel, and update the #2065 reach statement in the gfx1151 decode profile doc.

Validated on gfx1151: the new granitemoehybrid fused-kernel parity test passes, and logit_trace of granite-4.0-h-tiny-4bit with MLXCEL_FUSED_MOE=0 vs default agrees at 0 of 96 positions (0 decided mismatches at gap 2.0).

Refs #2245
The fused-kernel parity test added with the routing fix calls SwitchGLU::forward_fused_kernel directly, so it passes without the fix too: the method pre-existed and the routing in GraniteMoeHybridMoE::forward is what issue #2245 changed. Add a reproduction test that drives the production forward at one token and asserts its output is bit-exact the fused-kernel computation and not the gather computation, with both candidates built from the block own router outputs; without the routing it fails at the bit-exact assert, verified by forcing the fused branch off on gfx1151.

Also expose GraniteMoeHybridMoE.router and ::forward and GraniteMoeHybridMLP at pub(crate) for the test module; the FeedForward exposure from the routing commit made pub(crate) FeedForward::Dense reach the private GraniteMoeHybridMLP, which cargo build flagged as private_interfaces.

Refs #2245
Clippy 1.97.0 denies err().expect() under the workspace -D warnings gate, so verify-clippy-rocm failed on main since fc45284 shipped the yaml parser replacement; the three test call sites move to expect_err, a mechanical rewrite with no behavior change. Carried on this branch because the local gate is the merge gate while hosted CI is down.
@inureyes
inureyes merged commit a1c5826 into main Oct 13, 2026
27 checks passed
@inureyes
inureyes deleted the fix/issue-2245-granite-fused-moe branch October 13, 2026 01:58
inureyes added a commit that referenced this pull request Oct 22, 2026
…#2538)

## Summary

The granite-4.0-h decode regression on GB10 was not the fused MoE kernel being slow on sm_121. MLX builds every `mx.fast.cuda_kernel` with `use_disk_cache=false`, so each process NVRTC-compiled the fused gate-up and down pair again inside its first decode step (about 1.2 s, counted by `decode_tok_per_sec`). The issue's "32% slower than gather" was that fixed cost read as a per-token rate. Per token the fused kernel is the faster path on GB10 for every family measured.

No per-device routing policy is added, and the `MLXCEL_FUSED_MOE` default is unchanged on every device: the data showed no per-device property to key on (lfm2 lost 31% at `-n 256` for the same reason), and turning the kernel off on sm_121 would have given up a 6-17% decode win.

- `jit_module.cpp` overlay: custom kernels are written to `MLX_PTX_CACHE_DIR` like built-in ones (the module name already keys on a hash of the full source). Cache files are written to a process-unique temporary, closed and checked, then renamed into place, and the `.ptx` is published only after its kernel map, so a concurrent reader never loads a partial entry. The cache self-heals: an empty `.ptx`, a short read or a malformed kernel map is a miss, and a cached entry that fails to load is removed, recompiled and republished once before the original error path. A cache directory that cannot be created or written leaves the cache cold instead of throwing.
- `GraniteMoeHybridMoE::forward` routes through `forward_routed(x, try_fused)`; the #2283 test is now a forced fused arm, a forced gather arm, and a test that `forward` follows the gate. None skips under `MLXCEL_FUSED_MOE=0`.
- New `tests/cuda_custom_kernel_disk_cache.rs`: fails on main's overlay, passes here, requires a second process on the same cache to compile nothing and to match the first process's output bit for bit, and requires a third process on a damaged cache (empty gate-up `.ptx`, malformed down-kernel map) to recompile, match, and leave a complete entry.

## Measurement (GB10 sm_121, kernel 7.0.0-1019-nvidia, driver 580.178.04, `MLX_CUDA_ARCHITECTURES=121`, test-fast, `-n 256`, interleaved, null arm)

| model | fixed, default | fixed, `=0` | main, default | null floor |
|---|---|---|---|---|
| granite-4.0-h-tiny (n=7) | 89.20 | 81.63 | 53.63 | -1.2..+0.7% |
| lfm2-8b-a1b (n=5) | 109.65 | 102.25 | 70.74 | -0.3..+2.3% |
| qwen3-30b-a3b (n=5) | 56.20 | 46.56 | 45.05 | not run |

Method, per-run numbers and the intercept/slope fit: `docs/benchmark_results/fused-moe-jit-cache-gb10-2026-10-22.md`.

## Test plan

- [x] `granitemoehybrid` lib tests (17), also with `MLXCEL_FUSED_MOE=0`; `switch_layers::` (57); `fused_moe` (4), all on CUDA with `--test-threads=1`
- [x] `cuda_custom_kernel_disk_cache`: red with the overlay reverted, green with it
- [x] `cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings`, `cargo fmt --all --check`, `scripts/ci/check_env_var_docs.py`

## Changes during review

- Review (83df448): the publish step checked each temporary before closing it and published the `.ptx` even when its map failed; it now closes before checking and gates the `.ptx` on the map, and the temporary name uses the process id.
- Security review (5b8c4d2, af9d047): extending the cache to the fused decode kernels meant a bad entry would break decode permanently, so the read rejects empty or malformed entries and a failed load after a hit recompiles once (unloading the first module handle). No new code-injection surface: custom kernels already read the cache before this PR, only the write was skipped. Pre-existing cache trust and keying gaps (owner check on the temp-dir fallback, compute capability not in the key) are left to #2539.

Unverified: the retry branch for a non-empty, well-formed entry that `cuModuleLoadDataEx` rejects (no test plants one; it reuses the cold path's compile-and-publish); ROCm and Metal (the overlay is CUDA-only), `mlxcel-server` steady state, release-profile absolute numbers, the overlay on a Windows CUDA build, and the #626/#712 `FUSED_MOE_MAX_DFF_CUDA` provenance (measured with `mlxcel-bench-decode`, whose warmup most likely absorbed the compile; re-measurement tracked in #2540). Follow-up for the pre-existing cache trust and keying gaps: #2539.

Closes #2492
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
@inureyes inureyes added area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:performance Performance improvements labels Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(moe): route granite-4.0-h single-token MoE through the fused kernel

1 participant