Skip to content

[Perf] kimi-k3.1: Per-M decode GEMM tactics and side-stream attention GEMMs - #49478

Merged
kpham-sgl merged 6 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-port-decode-gemm-tactics
Nov 11, 2026
Merged

kpham-sgl merged 6 commits into
sgl-project:mainfrom
nvpohanh:pohanh/k31-port-decode-gemm-tactics

Conversation

@nvpohanh

@nvpohanh nvpohanh commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

[by Claude Code]

Original authors: @nvpohanh, @DarkSharpness, @yhyang201

Port of #48414

The Kimi-K3.1 branch (#48414, kimi-k3.1-day-0) routes K3.1's decode and DFLASH-verify dense BF16 GEMMs to TGV with per-M tactics. #49411 already brought the kernel half to main: the register_tgv_m_ranges registry and the per-call tactic of cutedsl_bf16_gemm. No model registers ranges on main yet, so dispatch there is unchanged. This PR ports the model half. It was developed as radixark/sglang-k31#159 and reworked onto one m-range registry in radixark/sglang-k31#213.

Motivation

Kimi-K3.1 TP8 DFLASH verify runs its dense BF16 linears at M = 6 x bs = 72-288 rows (decode bs 12-48). There, the current picks are cuBLAS or the TGV ladder. In a GB300 decode trace at 12-48 requests, the attention blocks' dense GEMMs looked slow:

  • KDA qkvg took 20.2 / 26.3 us, o_proj 9.4-10.2 us, and the MLA output gate g_proj 23.8-27.5 us on the main stream above 128 tokens.
  • An isolated sweep (every TGV tactic, cuBLAS, cuBLASLt, FlashInfer mm_bf16; weights rotated past L2) showed most picks already near the roofline. The real cost is placement:
    • The KDA [f_a | b] GEMM runs as cuBLAS split-K (about 180 CTAs plus a reduce) on the attention side stream, and waits for SMs behind the qkvg GEMM.
    • Above 128 tokens, the MLA g_proj and the KDA [f_a | b] -> f_b GEMMs leave the side stream and land on the critical path.

Modifications

All in models/kimi_k3.py, plus one env var:

  • _K31_TGV_M_RANGES (any SM10x): the four K=7168 dense shapes take TGV up to 64 decode rows. These are KDA fused qkvg, the merged MoE front, MLA q_a / shared gate_up / output gate, and MLA fused q_a + kv_a. On B300 at m = 64, the MoE front takes 16.0 vs 19.4 us and KDA qkvg 16.3 vs 19.6 us.
  • _K31_GB300_TGV_M_RANGES, registered only under _k31_gb300_tuning (K3.1, SM103, SGLANG_K31_DECODE_GEMM_TACTICS on): fixed TGV tactics measured on GB300. They cover KDA qkvg at 72-96 rows, MLA qkv_a at 72-288, MLA g_proj at 72-288, o_proj at 72-84, and the TP-sharded latent-up slice (k3_ar_fusion.slice_gemm, [Perf] kimi-k3.1: TP-shard the decode MoE front and latent-up tail #48584) at 84-156.
  • Side-stream [f_a | b]. On the KDA attention side stream only, the [f_a | b] GEMM runs as a 12-16 CTA TGV (_K31_GB300_BFA_SIDE_TGV_M_RANGES, built once with the merged weight), so it streams beside the wide [q,k,v,g] GEMM instead of waiting for SMs. The ranges are not registered globally, so every other caller of (144, 7168) keeps its pick.
  • _k3_side_stream_max_tokens. The MLA output gate and the KDA [f_a | b] -> f_b stay on the attention side stream up to 288 rows under the GB300 tuning. Elsewhere it stays 128 on Blackwell and 64 on other GPUs, as on main.
  • SGLANG_K31_DECODE_GEMM_TACTICS (default on). Setting it to 0 drops the GB300 tables and the side-stream TGV, and restores the 128-row limit.

Dtypes are unchanged: BF16 weights, activations and outputs with FP32 accumulation. TGV and cuBLAS differ only in K-reduction order. Side-stream placement changes no math: same kernels, same inputs, joined before use.

Differences from the source (#48414 at kimi-k3.1-day-0): test_kimi_k3_bfa_overlap.py::test_bfa_weight_reload_preserves_buffers (#43675) reaches _merge_bfa_weights through a SimpleNamespace owner. The method now reads self.config, so the owner gets a non-K3.1 config. The model code is identical to the source.

Accuracy Tests

Numerics only; there is no model-level change beyond GEMM reduction order. Measured on GB300 against an FP32 reference:

  • Max |diff| between TGV and cuBLAS is 0.031 on outputs of std 1.7 (at most 1 BF16 ulp at |x| >= 4).
  • The results are bitwise identical for qkvg at 72-96 rows, o_proj at 72-84, the latent-up slice, and g_proj at 240-288.
  • The FP32-reference error is the same for both picks at every point.

Speed Tests and Profiling

Fixed-batch decode. 2 x GB300, agg TP8/DCP8/EP2, DFLASH 6, simulated acceptance 4.12, pinned FlashInfer MoE tactics. The same image with and without the change, interleaved on the same nodes:

requests (verify rows) context before (ms) with this change (ms)
20 (120) 128K 30.02 29.28 (-0.74, four pairs, each -0.50 to -0.88)
36 (240) 128K 39.23 38.65 (-0.58)
8 (48), control: no kernel change at 48 rows 128K mean +0.20 (noise)

nsys (same job):

  • KDA attention block 58.3 -> 51.9 us at 20 requests and 79.4 -> 73.0 us at 36 requests, x 68 layers.
  • MLA attention block 186.1 -> 181.3 us and 274.9 -> 258.6 us, x 24 layers.
  • At 240 rows, g_proj moves from the main stream after the DCP combine (cuBLAS, 24.4-24.9 us) to the side stream (TGV, 19.8 us, fully hidden).

End to end. Kimi-K3.1 FP4 (test-weight checkpoint, acceptance-length override) on GB300 with an AgentX agentic trace, 1P2D with TP8/DCP8/EP2 decode workers, concurrency 56, two runs per arm. Removing this change:

  • made the decode step 1.16% slower at batch 9-44 (its 72-288 rows), and 0.22% faster at batch 1-8;
  • moved P90 tok/s/user -2.24% and tok/s/GPU -0.41%.

A small decode gain where it acts.

Tests

Run in lmsysorg/sglang:dev-cu13 on one L40S GPU, with the tree under test first on PYTHONPATH:

  • test_kimi_k31_decode_gemm_tactics.py (new, CPU: registry merge and overlap rejection) and test_kimi_k3_bfa_overlap.py: 13 passed, 1 skipped, 51 subtests passed. The skipped case is the side-stream TGV [f_a | b] under graph capture and replay at 72 / 144 / 264 rows; it needs SM10x, so the file is now also registered on 4-gpu-b200. On GB300 the source recorded 6/6 for that file.
  • test_kimi_k3_{bfa_overlap,expert_placement,packed_modules_mapping,pipeline_layers}.py: this branch 17 passed / 1 skipped; main 17 passed.
  • pre-commit run --all-files is clean.

Not run on this branch: a GPU run on SM10x. The timings above come from the source branch.

Checklist

Co-authored-by: Ziyi Xu [email protected]
Co-authored-by: Yuhao Yang [email protected]

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ❌ Run #42952322450
Latest PR Test (Extra): ❌ Run #42952322083
Latest PR Test (AMD ROCm 10): ❌ Run #42952322339

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

… GEMMs

Kimi-K3.1 TP8 DFLASH verify runs its dense BF16 linears at M = 6 x bs =
72-288 rows (decode bs 12-48), where the current picks are cuBLAS or the
TGV ladder, and two attention side-stream GEMMs stop at 128 tokens. Main
has the TGV m-range registry (register_tgv_m_ranges, sgl-project#49411) but no model
registers ranges yet.

- _K31_TGV_M_RANGES: the K=7168 dense shapes take TGV up to 64 decode rows
  on any SM10x (KDA fused qkvg, merged MoE front, MLA q_a / shared gate_up /
  output gate, MLA fused q_a + kv_a).
- _K31_GB300_TGV_M_RANGES, registered only under _k31_gb300_tuning (K3.1,
  SM103, SGLANG_K31_DECODE_GEMM_TACTICS on): fixed TGV tactics measured on
  GB300 for KDA qkvg 72-96, MLA qkv_a 72-288, MLA g_proj 72-288, o_proj
  72-84 and the TP-sharded latent-up slice 84-156.
- The KDA [f_a | b] GEMM takes a few-CTA TGV on the attention side stream
  only (_K31_GB300_BFA_SIDE_TGV_M_RANGES, built once with the merged
  weight), so it streams beside the wide [q,k,v,g] GEMM; no other caller
  of the shape picks it up.
- _k3_side_stream_max_tokens: the MLA output gate and the KDA [f_a | b] ->
  f_b stay on the attention side stream up to 288 rows under the GB300
  tuning, 128 elsewhere on Blackwell and 64 otherwise.
- SGLANG_K31_DECODE_GEMM_TACTICS=0 restores the generic picks and the
  128-row side streams.

BF16 weights, activations and outputs with FP32 accumulation, as before;
TGV vs cuBLAS differ only in reduction order.

Tests: test_kimi_k31_decode_gemm_tactics.py (CPU: registry merge and
overlap rejection), test_kimi_k3_bfa_overlap.py (GPU: side-stream TGV
[f_a | b] under graph capture and replay at 72 / 144 / 264 rows; also
registered on 4-gpu-b200 so the SM10x case runs).

Co-authored-by: Ziyi Xu <[email protected]>
Co-authored-by: Yuhao Yang <[email protected]>
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.

@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.

Comment thread python/sglang/srt/models/kimi_k3.py Outdated
self.config = config
self.quant_config = quant_config
if is_kimi_k31(config):
from sglang.kernels.ops.gemm.cutedsl_bf16_gemm import (

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: functional | Confidence: High

Issue

KimiK3LinearForCausalLM.__init__ now imports cutedsl_bf16_gemm for every Kimi-K3.1 config, on every platform. That module imports cuda.bindings.driver and cutlass at the top. The ROCm image installs pyproject_other.toml (srt_hip), which has neither package, so K3.1 model construction on ROCm fails with ModuleNotFoundError. Before this PR, K3.1 init did not import this module.

Example

The MI35x nightly K3.1-Pro tests (test_kimi_k31_pro_eval_mi35x.py, test_kimi_k31_pro_perf_mi35x.py) build this model and reach this branch.

Fix

Register only when TGV can run, for example if is_kimi_k31(config) and get_bf16_gemm_backend().is_cutedsl():. The scheduler sets the BF16 backend before it builds the model, and initialize_bf16_gemm_config already limits cutedsl to SM100/SM103.

Comment thread python/sglang/srt/models/kimi_k3.py Outdated
hide up to 288 verify rows."""
if not get_platform().is_blackwell:
return 64
return 288 if _k31_gb300_tuning(config) else 128

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: perf | Confidence: Medium

Issue

_k3_side_stream_max_tokens returns 288 whenever _k31_gb300_tuning(config) is true. It does not check that the side-stream GEMMs got a TGV pick. The TGV picks need the cutedsl BF16 backend and the measured TP8 shapes. Without them, [f_a | b] and the MLA g_proj run on the side stream at 129-288 rows with the old kernels. The docstring says the 128 limit exists because the overlap only adds sync overhead there.

Example

GB300 with --bf16-gemm-backend torch, or an attention-TP size other than 8. Then the [f_a | b] weight is not (144, 7168) and g_proj is not (1536, 7168).

Fix

Add get_bf16_gemm_backend().is_cutedsl() to _k31_gb300_tuning. Raise _bfa_bs_limit to 288 only when _bfa_side_tgv_m_ranges matched the weight shape, and raise _gate_bs_limit only when the g_proj shape is in _K31_GB300_TGV_M_RANGES.

Comment thread python/sglang/srt/models/kimi_k3.py Outdated
(2112, 7168): ((1, 64, None),), # MLA fused q_a + kv_a
}

# GB300 (SM103) TP8 decode / DFLASH-verify rows (M = 6 x graph bs) where a fixed

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

The comments above _K31_TGV_M_RANGES, _K31_GB300_TGV_M_RANGES, and _K31_GB300_BFA_SIDE_TGV_M_RANGES hold per-shape microsecond tables. That is PR-body content, and it makes the tables hard to read. It has also drifted from the code: it says MLA g_proj takes TGV at M 72-288, but (1536, 7168) covers only 72-192 and 240-288. It says MLA qkv_a takes TGV at 72-288 with a tie at 144, but (2112, 7168) skips 121-131, 133-155, and 241-263.

Fix

Keep one line per table on where the numbers came from, for example "Measured on GB300 TP8, CUDA graph, cold HBM; re-tune when TGV changes." Keep the one constraint in the side table: run alone, the few-CTA tactics lose, so it is not registered globally. Move the timings to the PR body.

for m in (121, 289):
assert not cg._model_takes_tgv(m, n, k)
assert cg._pick_tactic(m, n, k) == ladder[m]
# The side-stream [f_a | b] tactics stay off the global registry.

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: High

Issue

This block does not test what its comment says. The test registers _K31_TGV_M_RANGES and _K31_GB300_TGV_M_RANGES by hand, so the check only proves those two dicts lack (144, 7168). It never runs the registration in KimiK3LinearForCausalLM.__init__. If that code also registered _K31_GB300_BFA_SIDE_TGV_M_RANGES, or ignored SGLANG_K31_DECODE_GEMM_TACTICS=0, this test would still pass. No test covers _k31_gb300_tuning or _k3_side_stream_max_tokens.

Fix

Move the registration into a helper such as _register_k31_tgv_m_ranges(config). Test it on CPU with override_platform(device_sm=103) and envs.SGLANG_K31_DECODE_GEMM_TACTICS.override(False), and assert which shapes land in cg._MODEL_TGV_M_RANGES.

@kpham-sgl

Copy link
Copy Markdown
Collaborator

/rerun-test test_kimi_k3_bfa_overlap.py test_cutedsl_bf16_gemm.py test_unquant_apply_with_addend.py test_kimi_k3_b300.py test_kimi_k3_b300_low_latency.py

@github-actions

This comment has been minimized.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🚀 1-gpu-5090 (2 tests): ✅ View workflow run

cd test/ && python3 registered/unit/models/test_kimi_k3_bfa_overlap.py  # base-b
cd test/ && python3 registered/unit/layers/quantization/test_unquant_apply_with_addend.py  # base-b

🚀 4-gpu-b200 (2 tests): ✅ View workflow run

cd test/ && python3 registered/unit/models/test_kimi_k3_bfa_overlap.py  # base-b
cd test/ && python3 registered/kernels/ops/gemm/test_cutedsl_bf16_gemm.py  # base-b-kernel-unit

🚀 8-gpu-b300 (2 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_kimi_k3_b300.py  # extra-b
cd test/ && python3 registered/e2e/models/test_kimi_k3_b300_low_latency.py  # extra-b

@kpham-sgl

Copy link
Copy Markdown
Collaborator

/rerun-test test_kimi_k3_bfa_overlap.py test_cutedsl_bf16_gemm.py test_unquant_apply_with_addend.py test_kimi_k3_b300.py test_kimi_k3_b300_low_latency.py

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🚀 4-gpu-b200 (2 tests): ✅ View workflow run

cd test/ && python3 registered/unit/models/test_kimi_k3_bfa_overlap.py  # base-b
cd test/ && python3 registered/kernels/ops/gemm/test_cutedsl_bf16_gemm.py  # base-b-kernel-unit

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/unit/layers/quantization/test_unquant_apply_with_addend.py  # base-b

🚀 8-gpu-b300 (2 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_kimi_k3_b300.py  # extra-b
cd test/ && python3 registered/e2e/models/test_kimi_k3_b300_low_latency.py  # extra-b

@kpham-sgl
kpham-sgl merged commit 6685123 into sgl-project:main Nov 11, 2026
109 of 127 checks passed
@bingxche

Copy link
Copy Markdown
Collaborator

@nvpohanh AMD CI jobs started failing after this PR was merged, and #49929 proposes a fix. Could you review it?

cc @kpham-sgl (merged, co-author, reviewed), @DarkSharpness (co-author), @yhyang201 (co-author)

KimiK3LinearForCausalLM.init now imports the CuTe DSL cutedsl_bf16_gemm module unconditionally; it needs cuda.bindings/cutlass, which the ROCm image lacks, so the Kimi-K3.1-Pro server exits with ModuleNotFoundError: No module named 'cuda' in the MI35x nightly on rocm10 and rocm720.

The last passing run was on 418f4db7 and the first failing run on b174f4bb; this PR's commit 66851239 is between them.

Failing jobs (2):

If this PR isn't the cause, please say so here so the attribution can be corrected.

Posted automatically by amd-bot, the AMD CI monitor. Confidence: HIGH.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants