Skip to content

[Perf] kimi-k3: Fuse the decode MoE routing for 1-256 rows into one kernel - #48586

Merged
kpham-sgl merged 5 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-fused-decode-routing
Nov 6, 2026
Merged

kpham-sgl merged 5 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-fused-decode-routing

Conversation

@nvpohanh

@nvpohanh nvpohanh commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

[by Claude Code]

Original authors: @nvpohanh, @kpham-sgl, @zcnrex

Port of #48414

In every Kimi-K3 / K3.1 decode MoE layer, a serial chain of small kernels runs between the router and the routed experts. It is route_quant_fused (top-16 of 896 plus the MXFP8 quant), then the padded-row mask, then trtllm-gen's routing kernel inside trtllm_fp4_block_scale_routed_moe, which builds the expert-sorted permutation. #48414 replaces the chain with one kernel for 1-256 rows and any local expert range. The routed MoE then runs only its GEMMs, from that kernel's metadata, through FlashInfer's prepared-routing body. This PR ports that: the kernel with its op and test, the route_quant_handoff / select_experts / KimiK3MoE wiring, and the MXFP4 runner's prepared-routing entry.

This PR differs from #48414 in three ways:

Nothing is left for a later port: every fused-routing hunk of #48414 is in this PR.

Modifications

  • Kernel (kimi_k3_fused_routing.cuh, kernels/ops/moe/kimi_k3_fused_routing.py). It covers the MoE that Kimi-K3 and K3.1 share: 896 experts, top-16 by sigmoid score plus correction bias with no expert groups, and a 3584-wide activation quantized to MXFP8. A static_assert pins these values. It builds in the route_quant_fused.cuh TU.
    • CTAs [0, M) run route_quant_fused's routing body and CTAs [M, 2M) its MXFP8 quant body. Ids, weights and quantized activations are therefore bit-identical to the unfused chain.
    • Each routing CTA sets its row's ids to -1 when the row is padding (num_token_non_padded). It also writes the trtllm-gen expert weights: BF16 up to 64 rows and FP32 above, as the routed call does.
    • The last routing CTA builds the metadata that trtllm-gen's routingPermutation would, using one histogram over the local experts and a block scan. It handles non-local routes (-1), padded rows, the tile of the autotuned tactic, and experts that span several tiles.
    • The routing CTAs fire the PDL trigger right after the top-k select, so the routed MoE's first GEMM launches under the metadata tail. Its griddepcontrol.wait still waits for the whole grid.
  • Runner (flashinfer_trtllm.py).
    • select_trtllm_routed_body looks up the tactic that FlashInfer's autotuner picks for the routed call at this M, using the same runner, inputs and tuning config. It returns that tactic as FlashInfer's DABody, so the GEMM kernels are unchanged. It returns None on SM107 with FlashInfer < 0.7.3.
    • _run_trtllm_prepared_routing_moe runs the GEMMs, and the finalize unless it is deferred, through MoERunner.forward with da_routing_metadata / da_body_workspace.
    • The MXFP4 trtllm-gen SiTU path takes the prepared routing when the handoff published one for its ids.
  • Wiring.
    • KimiK3MoE._forward_routed / _forward_routed_deferred stage the routed-experts layer together with the rows.
    • select_experts binds the padded-row bound. It also records whether its post-processing keeps the router's ids: no expert-location dispatch, no routing override and no shared slots.
    • route_quant_handoff.try_route_quant_fused runs the Kimi-K3 kernel when it covers the call and a prepared body was selected. Otherwise it runs route_quant_fused as before.
    • stage() and clear() reset the whole handoff record, so the new per-layer fields cannot leak into the next layer. This reset and the _publish() helper come from [Perf] [NVIDIA] kimi-k3: Fused NVFP4 routing preparation and prepared FP4 routing at M <= 8 #46484.
  • Fallback. Any miss keeps the unfused chain: another runner, autotuning in progress, more than 256 rows, a different MoE shape, or SM107 with FlashInfer < 0.7.3. No dtype changes.

#46475 / #46484 (both open) fuse the same chain for M <= 8, but only on a layer that holds all 896 experts, so at EP2 (448 local experts) they fall back. This path covers any expert range and 1-256 rows.

Tests

These ran at c10af88 (after merging main) on one B200 with lmsysorg/sglang:dev-cu13 (FlashInfer 0.7.2) and this branch's python/ first on PYTHONPATH:

  • test_kimi_k3_prepared_routing.py: passed in 96 s. It is registered on base-b-kernel-unit / 4-gpu-b200. It compares the prepared body bitwise against the unfused routed call at EP2 rank 1, with:

    • M = 6, 65 and 192;
    • FlashInfer's default and autotuned tactics;
    • finalized output and deferred finalize;
    • 3 padded rows.

    It also asserts that the prepared body ran. Building the metadata for twice FlashInfer's default tile makes all 6 default-tactic subtests fail.

  • test_kimi_k3_fused_routing.py: passed, 9 subtests. They cover M 1-256, padded rows, expert ranges, tiles 8-256, and rows whose experts span two tiles. Outputs are checked bitwise against route_radix + per_token_group_quant, and the metadata against the trtllm-gen contract.

  • test_route_quant_prerequisites.py: 3 passed. These cover the unfused route_quant_fused path.

  • Routed-MoE parity, the full manual script that the test above trims: 240/240 bitwise on the valid rows, and every case went through the prepared body. The script compares the fused path against the unfused chain. Both run through _fused_experts_flashinfer_mxfp4_sm100_trtllm_gen with random MXFP4 weights. It covers:

    • EP2 rank 0 and rank 1 (448 local experts, intermediate 768) and EP1 (896 experts, intermediate 384);
    • M = 1, 6, 12, 24, 48, 64, 65, 96, 192, 256;
    • FlashInfer's default and autotuned tactics;
    • the finalized output, and deferred finalize (expert weights, plus gemm2_out rows matched through expanded_idx_to_permuted_idx);
    • all rows valid, and 3 padded rows.
  • pre-commit: all hooks pass.

End-to-end results come from the Kimi-K3.1 development branch that #48414 was squashed from (GB300, Kimi-K3.1-Pro). They compare fused routing on against off, using that branch's switch. They were not re-run on this branch. Kimi-K3 was not run end to end; its MoE layers have the shapes that the parity script covers.

  • TP8/DCP8: greedy outputs were identical on 4 prompts. GSM8K (sgl-eval 0.1.3, 200 examples, temperature 1.0, top_p 0.95) was 98.5% on vs 99.0% off.
  • TP8/DCP8/EP2 with DFLASH: greedy outputs were identical. GSM8K was 98.0% on vs 97.5% off.

Speed

These numbers are from the development branch on GB300 and were not re-measured here. The setup is a Kimi-K3.1-Pro decode step at aggregated TP8/DCP8/EP2, with DFLASH verifying 6 tokens per request and acceptance pinned at 3.69. Each request has an 8K-token context. The two arms are fused routing off and on, with one server start each.

Requests MoE rows (M) Before (ms) After (ms) Change
1 6 13.51 13.32 -0.20 (-1.4%)
2 12 16.42 15.67 -0.74 (-4.5%)
4 24 19.97 19.49 -0.48 (-2.4%)
8 48 24.75 23.82 -0.93 (-3.8%)
16 96 31.33 30.78 -0.55 (-1.8%)
32 192 41.90 41.59 -0.31 (-0.7%)

A torch profiler trace on rank 0 shows the routing kernels across the 92 MoE layers of one decode step. They take 1.00 / 1.73 / 1.76 ms before and 0.87 / 0.90 / 1.16 ms after, at 1 / 4 / 16 requests. Per-start FlashInfer autotuner tactic choice moves the step time by up to about 0.6 ms, so the changes at 1 and 32 requests are within noise.

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ✅ Run #42205189223
Latest PR Test (Extra): ❌ Run #42205189180
Latest PR Test (AMD ROCm 10): ⏳ Run #42205189042

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

nvpohanh and others added 2 commits November 4, 2026 23:08
… kernel

Raw port from sgl-project#48414 (kimi-k3.1-day-0): its hunks for the K3.1 fused
decode routing, copied byte for byte. One kernel replaces route_quant_fused,
mask_topk_ids_padded_region and the trtllm-gen routing kernel for 1-256
rows and any expert range, and the trtllm-gen MXFP4 runner runs the routed
MoE's GEMMs from its metadata through FlashInfer's prepared-routing body.

Co-authored-by: Khoa Pham <[email protected]>
Co-authored-by: Chunan Zeng <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
FlashInfer 0.7.2, the pinned version, defines _device_support_moe_pdl, so the
defensive getattr only hides a rename (.claude/rules/no-getattr-defensive.md).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@github-actions github-actions Bot added quant LLM Quantization jit-kernel labels Nov 5, 2026
Comment thread python/sglang/srt/environ.py Resolved
Kimi-K3 and K3.1 share the MoE the kernel is specialized for (896
experts, top-16 sigmoid + bias with no groups, 3584-wide latent, MXFP4
trtllm-gen SiTU), so name it for the family: kimi_k31_fused_routing ->
kimi_k3_fused_routing, K31* -> KimiK3*.

Drop SGLANG_K31_FUSED_ROUTING: every case the fused path cannot serve
already falls back to the unfused chain.

On SM107 with FlashInfer < 0.7.3, keep the unfused chain instead of
mirroring that release's Rubin workarounds (no FP4 tile 192, MoE PDL
off). This removes the SM107 tile rule and the call to FlashInfer's
private _device_support_moe_pdl, which 0.7.3 deletes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh nvpohanh changed the title [Perf] kimi-k3.1: Fuse the decode MoE routing for 1-256 rows into one kernel [Perf] kimi-k3: Fuse the decode MoE routing for 1-256 rows into one kernel Nov 5, 2026

@nvpohanh nvpohanh left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[by Claude Code] This review is done by agents. Please feel free to disagree if they do not make sense.

return runner, runner_kwargs


def select_trtllm_routed_body(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[by Claude Code] Severity: style | Confidence: Medium

Issue

No committed test covers the prepared-routing path (select_trtllm_routed_body, _run_trtllm_prepared_routing_moe, and the handoff wiring). test_kimi_k3_fused_routing.py checks only the kernel. This path copies FlashInfer internals: the routed call's MoERunner kwargs, its tuning config, and selectDefaultTileN. If a FlashInfer bump changes one of them, the fused path can silently lose the tuned tactic, or build metadata for a different tile than the body runs. No CI test would fail.

Fix

Commit a trimmed version of the parity script. Compare the prepared and routed paths of _fused_experts_flashinfer_mxfp4_sm100_trtllm_gen at a few M values (for example 6, 65, 192), at EP2 rank 1, with and without deferred finalize. Register it with stage="base-b-kernel-unit", runner_config="4-gpu-b200".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[by Claude Code] Added in c10af88: test/registered/kernels/ops/moe/test_kimi_k3_prepared_routing.py, registered with stage="base-b-kernel-unit", runner_config="4-gpu-b200".

It drives route_quant_handoff the way select_experts does. It then compares the prepared body against the unfused routed call of _fused_experts_flashinfer_mxfp4_sm100_trtllm_gen, bitwise on the valid rows, at EP2 rank 1 (448 local experts):

  • M = 6, 65 and 192 (65 crosses the switch from BF16 to FP32 expert weights);
  • FlashInfer's default tactic first, then the autotuned one;
  • finalized output and deferred finalize;
  • 3 padded rows, whose ids must come back as -1.

It also asserts that _run_trtllm_prepared_routing_moe ran, so a silent fallback to the unfused chain fails too.

On one B200 with FlashInfer 0.7.2 it passes in 96 s. As a check that it catches the tile drift you describe, I made _trtllm_moe_default_tile_n return twice FlashInfer's default tile. All 6 default-tactic subtests then failed, and the 6 autotuned ones still passed.

nvpohanh and others added 2 commits November 6, 2026 01:58
The kernel test checks the fused routing kernel alone. The prepared path
around it copies FlashInfer's routed-call runner kwargs, tuning config
and default tile, so a FlashInfer change there could silently drop the
tuned tactic or run the body at a different tile than the metadata.
Compare the prepared body bitwise with the unfused routed call at EP2
rank 1 for M = 6, 65, 192, default and autotuned tactics, finalized and
deferred, with padded rows, and assert the prepared body actually ran.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nvpohanh

nvpohanh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Nov 6, 2026
@nvpohanh

nvpohanh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@nvpohanh

nvpohanh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, fix the PR title if the title check fails, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@nvpohanh

nvpohanh commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

[by Claude Code] All NV pipelines have passed.

@kpham-sgl
kpham-sgl merged commit 0fc97bc into sgl-project:main Nov 6, 2026
262 of 294 checks passed
DarkSharpness added a commit to DarkSharpness/sglang that referenced this pull request Nov 6, 2026
…Kimi-K3.1 decode MoE kernels

> (auto generated by Claude)

The fused decode routing (sgl-project#48586) makes the route-quant handoff publish plain ids where the decode MoE path reads the packed (id << 16) | bf16(weight) top-k, and build trtllm-gen routing metadata that path never uses. select_trtllm_routed_body now declines those layers (T <= 256), so the handoff keeps the packed form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jit-kernel quant LLM Quantization run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants