Skip to content

feat(top-k/bmm): Kimi-K3 routing top-k and MLA absorb bmm kernels - #134

Merged
kyle-256 merged 3 commits into
mainfrom
kyle/k3-bmm-topk-reference
Nov 10, 2026
Merged

kyle-256 merged 3 commits into
mainfrom
kyle/k3-bmm-topk-reference

Conversation

@kyle-256

@kyle-256 kyle-256 commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Kimi-K3's router top-k and its two MLA absorb products have definitions on main, but no kernel serves them. Two of the three cannot even be measured:

  • bmm_no_trans_b_n512_k128 has no baseline: aiter's CK batched gemm takes b only as (batch, n, k).
  • biased_grouped_topk's reference orders tied experts as torch.topk happens to. That order changes under CUDA-graph capture, so no kernel can match it.

This PR fixes both and adds the four kernels.

Scope

  • Code:
    • bmm_baseline runs torch.bmm when b is not transposed. sglang uses torch.bmm for an MLA layer's absorbed w_kc and w_vc products. A transposed b keeps aiter's CK path.
    • The biased_grouped_topk reference uses a stable sort, so tied experts rank lower id first. The contract change is a comment only, so its text and every schema stay unchanged. One new test covers the tie order.
  • Kernels (FlyDSL), each covering every workload of its definition:
    • biased_grouped_topk_renormalize_n_experts896_topk16: n_tokens 8–112 (1d8f70af…) and 893–16384 (375c8083…).
    • bmm_n128_k512: batch 12, m 8–112 (b05425d5…), the w_vc product after the DCP exchange.
    • bmm_no_trans_b_n512_k128: batch 96, m 8–112 (befcfd1f…), the q · w_kc product.

Verification

Environment: this head's code and kernel bytes on main e525989; MI355X gfx950; image lmsysorg/sglang@sha256:1438dd8b…; ROCm 7.15.26333, torch 2.11.0+rocm10.0.0, FlyDSL 0.3.2, Triton 3.8.0, aiter 0.1.21.dev66+gdbd8bf5bd.
Gate overrides: none.

Kernels

contract baseline measured accuracy speedup (mean; published lower bound)
[email protected] aiter 17/17 17/17 2.69–8.58×; 2.000 (cap)
[email protected] n128 k512 aiter CK 13/13 13/13 1.10–2.20×; 1.094–2.000
[email protected] n512 k128, b untransposed torch.bmm 13/13 13/13 1.30–1.53×; 1.300–1.523

These kernels read about 4.4 µs. That is close to the timer's floor for short kernels, so their real ratios are likely higher.

Stress at every Point, each try compared byte for byte with the call alone; 0 differ:

  • the forge driver's --stress;
  • one graph replayed 24 times, with 3 input sets rotated into its buffers;
  • two concurrent calls on different inputs, 20 tries per condition.
Validation log
$ python -m aklr export check
(exit 0)
$ python -m aklr validate --base origin/main --stages audit,bench <the four files>
bench: 1/4 passed flydsl/bmm_no_trans_b_n512_k128/befcfd1f: 13 wl, speedup 1.30x-1.52x, acc ok
bench: 2/4 passed flydsl/bmm_n128_k512/b05425d5: 13 wl, speedup 1.09x-2.20x, acc ok
bench: 3/4 passed flydsl/biased_grouped_topk_renormalize_n_experts896_topk16/1d8f70af: 13 wl, speedup 2.69x-2.78x, acc ok
bench: 4/4 passed flydsl/biased_grouped_topk_renormalize_n_experts896_topk16/375c8083: 4 wl, speedup 3.03x-8.57x, acc ok
validation passed

…pk's reference ranks tied experts lower first

bmm_no_trans_b_n512_k128 (Kimi-K3's q . w_kc absorb, batch 96) had no baseline: aiter's CK batched gemm takes b as
(batch, n, k) only, so validate could not time any workload. The baseline now runs torch.bmm when b is not
transposed, as sglang does for an MLA layer's absorbed w_kc and w_vc products.

biased_grouped_topk's reference took torch.topk's order of equal biased scores, which depends on the algorithm and
changes under CUDA-graph capture, so no kernel can follow it. A stable sort now ranks the lower expert first; the
contract's comment says so (its text, and so every schema, is unchanged). A test covers the tie order.

Copilot AI 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.

🟡 Changes recommended

The BMM baseline produces incorrect biased bf16 results by rounding before bias addition and fails to populate caller-provided output buffers.

4 open issues
What changed in this PR

Adds baseline support for untransposed-B batched matrix multiplication and deterministic tie handling in the grouped top-k reference, addressing two blocked Kimi-K3 definitions.

Changes:

  • Use torch.bmm for untransposed B while retaining aiter’s CK path for transposed B.
  • Rank tied experts by lower ID using a stable sort, with a regression test and comment-only contract clarification.
File Description
tests/​ops/​test_reference.py Adds a regression test for lower-ID-first expert ties.
aklr/​ops/​gemm/​baseline.py Adds the untransposed-B torch.bmm baseline path.
aklr/​ops/​biased_grouped_topk/​reference.py Uses stable sorting to make tied selections deterministic.
aklr/​ops/​biased_grouped_topk/​contract.py Clarifies tie ordering in a comment without changing exported schemas.

Review effort: Max

Comment thread aklr/ops/gemm/baseline.py Outdated
Comment on lines +91 to +93
product = torch.bmm(a, b)
if bias is not None:
product = product + bias[:, None, :]
Comment thread aklr/ops/gemm/baseline.py
"""aiter's CK 16-bit batched gemm, b as (batch, n, k) only."""
"""aiter's CK 16-bit batched gemm when b is (batch, n, k); otherwise torch.bmm, which sglang runs for an MLA
layer's absorbed w_kc and w_vc products and which aiter has no batched gemm for."""
if not trans_b:
Comment thread aklr/ops/gemm/baseline.py Outdated
product = torch.bmm(a, b)
if bias is not None:
product = product + bias[:, None, :]
return product.to(out_dtype or a.dtype)
dtype=DTypeSpec(any_of=(DType.BFLOAT16, DType.FLOAT32)),
# Ties on the biased score are possible: no tie-free bf16 distribution yet.
# Ties on the biased score are possible (no tie-free bf16 distribution yet):
# the lower expert ranks first.
)

Four FlyDSL files for Kimi-K3 definitions that had no kernel: biased_grouped_topk n_experts896 topk16 (n_tokens
8-112 and 893-16384, one file each), bmm_n128_k512 (batch 12) and bmm_no_trans_b_n512_k128 (batch 96), each at
every workload of its definition. AKLR validate on MI355X, mean speedup over the baseline: top-k 2.69-2.78x and
3.03-8.58x, bmm_n128_k512 1.10-2.20x, bmm_no_trans_b 1.30-1.53x; accuracy passed at all 43 workloads, and the
forge driver's --stress, graph replays with new inputs and concurrent calls on different inputs matched the call
alone. Needs the bmm baseline and the top-k tie rule of the commit before it.
@kyle-256 kyle-256 changed the title fix(ops): bmm baseline without a transposed b, and a stable top-k tie order feat(k3): Kimi-K3 routing top-k and MLA absorb bmm kernels Nov 10, 2026
@kyle-256 kyle-256 changed the title feat(k3): Kimi-K3 routing top-k and MLA absorb bmm kernels feat(top): Kimi-K3 routing top-k and MLA absorb bmm kernels Nov 10, 2026
@kyle-256 kyle-256 changed the title feat(top): Kimi-K3 routing top-k and MLA absorb bmm kernels feat(top-k/bmm): Kimi-K3 routing top-k and MLA absorb bmm kernels Nov 10, 2026
torch.bmm rounds the product to the inputs' 16-bit dtype, so a bias added after it can miss the contract's float32
accumulation bound (a review finding). Its only callers, Kimi-K3's MLA absorb products, pass no bias: the path now
raises for one instead of returning a doubly rounded sum.
@kyle-256
kyle-256 merged commit 5b39957 into main Nov 10, 2026
12 checks passed
zhenhuang12 pushed a commit that referenced this pull request Nov 18, 2026
* docs(kb): name the kernel files main holds now, after #168 and #220 renamed them

#168 (kernel.requires) and #220 (aiter in kernel.requires) renamed every kernel file they touched without changing
its code, so the case pages' sources: lines and their text named files main no longer has (kb_reconcile: 0 covered,
100 gone). Each gone file is replaced by the file in its directory whose kernel (entry point and sources) is
byte-identical; where #212 added a second schema of the same kernel, by the one with the same workloads. The
withdrawn 4ea93103 is left for a separate edit.

* docs(kb): mark fused_moe 4ea93103 withdrawn

#153 withdrew it (1.043 over aiter, under the 5% bar). Its sources: line goes, the Points table says so, and S8 pins
the source to the revision before #153 so the citation still resolves.

* docs(kb): GEMM: nt at K=512, bounded-wait fold, ring barrier, cached fold workspace

- small_m.md §6: E134's nt cost at K=512 holds for that forge kernel only;
  #188's direct-to-LDS B stream at the same shape pays 1.66-1.69x with nt
  (E147). The shape does not decide the policy.
- wait_free_fold.md: a waiting fold is safe with a bounded wait, hand-off on
  timeout and a per-call workspace, as #159's FOLD 4/5 (exact under
  contention, two streams and concurrent graphs). Cost and risk: a
  workspace cached per (device, stream), as in #212's Triton n32_k6144, is
  shared by every graph captured on that stream (wrong outputs).
- datapath.md §4: a ring barrier before a DMA refill must also wait
  lgkmcnt(0); #110's n4096_k8192 races under contention without it.
  correctness.md and flydsl/gemm.md point there.

* docs(kb): mHC 4096 Gram form without a clamp; aiter's stage 2 drops b_nt

- cases/mhc_fused_post_pre.md: the hidden-4096 kernel returns NaN when
  the residual streams cancel; clamp the form at 0 like the hidden-7168
  kernel.
- moe/grouped_sorted_tokens.md §4, flydsl/moe.md §4: aiter's mixed stage-2
  builder discards b_nt, so a _bnt2 row loads w2 cached; restoring it took
  #122's fused MoE from 256.8 to 217.5 us at 512 tokens.

* docs(kb): pitfalls: degenerate Points, eager host time, in-place state

- degenerate_points.md (new): Points whose inputs all take a kernel's fast
  path (#201's FlashMLA q8: every request 8 KV rows) score a speedup that
  realistic lengths reverse. attention/measurement.md §8 points there.
- eager_call_host_time.md (new): the graph-replay speedup leaves out a
  @flyc.jit launcher's per-call host time; #134's top-k is 2.8-7.1x in
  replays and 0.18-0.68x of aiter called eagerly.
- state_kept_across_calls.md: form 3, a kernel that skips unchanged state
  stores timed on state replayed in place (#75's GDN decode: 2.40x in
  place, 1.62x with fresh state). triton/gdn.md points there.

* docs(kb): mHC case: the hidden-7168 HIP file #168 renamed, and #202's FlyDSL kernel beside it

* docs(kb): evidence counts from the runs' logs; R2 at batch 4 and 8; aiter's top-k fails the reference at 16384
@kyle-256
kyle-256 deleted the kyle/k3-bmm-topk-reference branch December 3, 2026 02:32

This branch was previously deployed

1 inactive deployment
gpu-trusted — c19a3d97 Deployed Nov 10, 2026 by kyle-256 via prepare-gpu / prepare #554
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants