Skip to content

perf(inkling): decode through the fast SDPA path and fused MoE kernels - #2505

Merged
inureyes merged 4 commits into
mainfrom
perf/inkling-fused-decode
Oct 20, 2026
Merged

inureyes merged 4 commits into
mainfrom
perf/inkling-fused-decode

Conversation

@inureyes

Copy link
Copy Markdown
Member

Closes #2479.

What this does

Three pieces, in order:

  1. chore: bump the pinned MLX upstream commit to bff10220 and refresh the three backend overlays to that tree (mlxcel-marked hunks re-applied).
  2. fix(inkling): decode attention was wired to a composed SDPA (matmul + softmax + matmul, the only caller of that path in the tree, dating from feat(speculative): add Inkling native MTP #1540). mlx.core.softmax promotes to float32, which poisoned the whole residual stream: every bfloat16 projection promoted its weights per decode token, and the fused MoE down-combine kernel's scales-dtype gate refused every call. This is the root cause of the perf(moe): profile the batch-1 decode gap on M3 Ultra after #2310 #2479 gap. The layer now goes through MLX's fast::scaled_dot_product_attention (same signature, nullable mask), keeping the query dtype end to end.
  3. feat(inkling): port the fused batch-1 decode structure from the reference implementation: one routing kernel (top-K with correction-bias selection, shared-expert weights pre-broadcast) and one down-projection kernel with in-kernel q4/g64 dequant and folded weighted sum. The route kernel runs whenever the GPU backend is Metal and MLXCEL_INKLING_MOE_KERNEL is not 0; the down-combine kernel additionally gates on batch <= 8, top_k <= 8, 4-bit group-64 affine with a 2048-unpacked-input 3-D down weight, and expert scales matching the activation dtype. NVFP4 and ModelOpt-sidecar planes stay on the gather path.

Results

inkling-small-mlx-4bit, M3 Ultra, 100 decode tokens, caffeinated, fastest of 3 runs:

before after
decode 8.10 tok/s (16% of baseline) 44.02 tok/s (90% of baseline)
prefill 122.6 ms 48.3 ms

mlx-lm baseline on the same checkpoint: 48.94 tok/s. The remaining ~10% is diffuse, consistent with the per-op execution overhead pattern documented for Gemma3n (#762).

Validation

  • mlxcel-core full suite: 2144 passed; the 2 cache::paged_detach failures are pre-existing on main and unrelated (verified by stash).
  • New parity tests: the routing kernel matches graph routing (indices equal, weights within 2%, shared-expert gamma bit-identical), and the full one-token affine MoE matches the gather reference through the down-combine kernel.

Bump the pinned MLX upstream commit from 243bdf09 to bff10220 and refresh the three backend overlays to that tree.

The refresh re-applies only the mlxcel-marked hunks on top of the wholesale overlay replacement; the ROCm CORE_RESIDUAL.diff and UPSTREAM markers record the residual. Rebuilt cleanly on Metal and smoke-tested at 227 tok/s on inkling-0.6b.
The Inkling decoder layer was wired to a composed SDPA (matmul + softmax + matmul in mlx_cxx_bridge.cpp) instead of MLX's fast::scaled_dot_product_attention, and it was the only caller of that composed path in the tree, dating from #1540 when the layer was created.

mlx.core.softmax promotes to float32 regardless of the input dtype, so the composed path poisoned the whole residual stream: attention output, both short convs and the MoE inputs all ran in float32 while the expert scales are bfloat16. Two consequences: every bfloat16 projection promoted its weights to float32 per decode token, and the fused MoE down-combine kernel's scales-dtype gate (scales.dtype == x.dtype, the same condition the reference implementation checks) refused every call.

Switching to the fast kernel (same signature, nullable mask) keeps the query dtype end to end. On inkling-small-mlx-4bit, M3 Ultra, 100-token decode moves from 8.10 to 44.02 tok/s and prefill from 122.6 ms to 48.3 ms.

Refs #2479.
… kernels

Port the fused batch-1 decode structure from the reference implementation: one routing kernel (top-K with correction-bias selection, softmax over logsigmoid of the K routed plus shared logits, shared-expert weights pre-broadcast) and one down-projection kernel with in-kernel q4/g64 dequant and folded weighted sum. The previous ops chain ran about 4,600 small kernels per batch-1 decode token and was GPU-bound.

The route kernel runs whenever the resolved GPU backend is Metal and MLXCEL_INKLING_MOE_KERNEL is not 0. The down-combine kernel additionally gates on batch <= 8, top_k <= 8, 4-bit group-64 affine quantization with a 3-D down weight whose unpacked input dim is 2048, and expert scales matching the activation dtype; models outside that shape stay on the existing paths. NVFP4 experts and planes carrying ModelOpt gate/out scale sidecars stay on the gather path, and SwitchGLU gains the sorted and indexed activation forward plus quantized down parts the kernel needs.

Parity tests cover the routing kernel against graph routing (indices equal, weights within 2 percent, gamma bit-identical) and the full one-token affine MoE through the down-combine kernel against the gather reference.

On inkling-small-mlx-4bit, M3 Ultra, with the SDPA fix, 100-token decode reaches 44.02 tok/s against the 48.94 tok/s mlx-lm baseline.

Refs #2479.
…code

# Conflicts:
#	src/lib/mlxcelverse/overlays/rocm/CORE_RESIDUAL.diff
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority labels Oct 20, 2026
@inureyes
inureyes merged commit 0ee9f01 into main Oct 20, 2026
20 of 28 checks passed
@inureyes
inureyes deleted the perf/inkling-fused-decode branch October 20, 2026 23:08
inureyes added a commit that referenced this pull request Oct 21, 2026
The fail-loudly default case added by #2505 left its throw without a semicolon, so every CUDA build failed to compile the fetched MLX source at scaled_dot_product_attention.cu(502). CPU-only builds never process the cuda overlay, which is why default-feature gates did not catch it.
inureyes added a commit that referenced this pull request Oct 21, 2026
Adopts the review findings on PR #2516: the down-combine kernel now gates on the actual fast-route launch success instead of the env+backend gate, so a gate/backend disagreement goes straight to the graph path instead of attempting a launch that would refuse the same way, and the two launcher doc comments state that production consumes the Err through the fallback rather than only through a direct call. Refs #2505.
inureyes added a commit that referenced this pull request Oct 21, 2026
Bilingual technical report for the contract-breakage repair PR (#2505 leftovers): kernel-port routing, env-var docs, fmt.
inureyes added a commit that referenced this pull request Oct 21, 2026
* fix: repair the three contract breakages left by PR #2505

PR #2505 merged while CI was frozen and left three repo-wide contract breakages.

- The Inkling MoE decode launchers reached their Metal kernel holders directly; both now declare KernelPorts tables and route through mlxcel::select_kernel_port, and the cxx bridge declares them -> Result<()> so the refusal reaches Rust as an Err instead of ending the process on a noexcept extern (pattern per src/lib/mlxcelverse/kernels/kernel_port.h, issues #1801 and #1885). The InklingSparseMoe::forward call sites fall back to the graph routing chain and the gather path on Err.
- MLXCEL_INKLING_MOE_KERNEL was read in src but neither documented nor allowlisted; it is an operator rollback toggle and is now documented on docs/environment-variables.md in the Hardware and kernel diagnostic section, per issue #1140's convention.
- cargo fmt --all -- --check violations in src/models/inkling/mlp.rs and src/models/switch_layers.rs fixed mechanically.

Verified with make verify-kernel-port-dispatch verify-python-tooling verify-fmt, cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warnings, and the inkling lib-test filter under gpu-lock on GB10.

* fix(inkling): gate down-combine on fast-route success, precise Err docs

Adopts the review findings on PR #2516: the down-combine kernel now gates on the actual fast-route launch success instead of the env+backend gate, so a gate/backend disagreement goes straight to the graph path instead of attempting a launch that would refuse the same way, and the two launcher doc comments state that production consumes the Err through the fallback rather than only through a direct call. Refs #2505.

* docs: add PR 2516 technical report

Bilingual technical report for the contract-breakage repair PR (#2505 leftovers): kernel-port routing, env-var docs, fmt.
adrysn added a commit that referenced this pull request Oct 21, 2026
Adds direct unit tests for `serialized_json_len_saturating` and the `LruKey` `Ord` tiebreak chain in `store_budget.rs`, which had no coverage. Test-only; no production code changed, no CHANGELOG entry.

- JSON length matches `serde_json::to_vec` for scalars, escapes, non-ASCII and nested values, and returns `usize::MAX` for a failing `Serialize` and non-string map keys.
- `LruKey` ordering is pinned per level (last_accessed, sequence, id) using one base `Instant` plus offsets, with a full sort, `partial_cmp`/`cmp` agreement and equal keys.

Validation: `server::store_budget_tests` (9 passed) and `clippy -p mlxcel --lib --tests -D warnings` are clean. `cargo fmt --check` passes after merging main (#2516 fixed the earlier fmt diffs from #2505).

Closes #1662
inureyes added a commit that referenced this pull request Oct 21, 2026
Port mlx-vlm's short_block_affine4_switch_gate_up as moe_switch_gate_up, a direct-dequant Metal kernel for the routed gate/up pair at decode, and wire it 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, batch 2..7 where total < 64). 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 scale and zero-point in-kernel, and halves the weight traffic on adjacent positions that select the same expert.

A hardening pass 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.

Batch decode A/B on a real OLMoE-1B-7B-0125-Instruct-4bit checkpoint through the OpenAI-compatible server (issue #2515, results in docs/benchmark_results/switch-gate-up-batch-m3ultra-2026-10-21.md): 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.

Validated: synthetic fixture parity at tokens=1/3 with the parity tests requiring the kernel, a real-OLMoE opt-in test (affine q4 planes, tokens=7) passing on the hardened head, a missing-port CPU regression, full suite 9644 passed with the 6 sorted_gather numeric failures pre-existing on Metal (they skip on CI, which has no GPU backend); on inkling-small-mlx-4bit, M3 Ultra, 4 cool runs: 45.29 to 45.45 tok/s, up from 44.07 after #2505 and 92.8% of the 48.94 tok/s mlx-lm baseline.

Refs #2479, #2515.
daemyung-lablup added a commit to daemyung-lablup/mlxcel that referenced this pull request Oct 22, 2026
…QMM kernels off wave64

A `--features rocm` build failed on main since lablup#2505: the 3-way merge of
upstream's AsStrided::eval_gpu into the core overlay
mlx/backend/gpu/primitives.cpp kept only its CUDA branch and Metal #else,
so the ROCm build included mlx/backend/metal/device.h. The overlay now has
an MLX_USE_ROCM branch that registers the contiguous copy on the ROCm
command encoder (LOCAL_FIXES.md item 51).

qmm_wmma_dense_kernel and gather_qmv_wmma_prefill_kernel split their
128-thread block into four 32-lane warps (tid >> 5, tid & 31), but were
selected on every has_native_wmma arch, including gfx908, gfx90a and
gfx942. On a 64-lane wavefront two warps share one wavefront and the
rocWMMA fragments mix both tiles: on an MI300X (gfx942, ROCm 7.14)
Qwen3-0.6B-4bit decoded only "!". Both dispatch sites now require the
hardware wavefront width (device_warp_size(), which
MLX_ROCM_FORCE_WARP_SIZE does not move) to be 32, and no knob can force
them onto a wave64 device (LOCAL_FIXES.md item 50). Wave32 (RDNA) is
unchanged.

The ROCm route tests assumed the fused kernel exists: on a wave64 device
rocm_qmm_dequant_cache skips its three bf16 WMMA cases, and rocm_qmm_env
expects the dense route and skips the ceiling cases, whose variable is
read only when the fused kernel is a candidate.
@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.

perf(moe): profile the batch-1 decode gap on M3 Ultra after #2310

1 participant