Skip to content

feat(gemm): Kimi-K3 dense bf16 GEMM kernels and the routes from aiter's and K3's GEMM calls - #159

Merged
kyle-256 merged 1 commit into
mainfrom
kyle/k3-gemm
Nov 13, 2026
Merged

kyle-256 merged 1 commit into
mainfrom
kyle/k3-gemm

Conversation

@kyle-256

Copy link
Copy Markdown
Collaborator

Kimi-K3 dense bf16 GEMM on MI355X: FlyDSL kernels, and routes that bring K3's GEMM calls to gemm.

Kernels: 9 [email protected] files, 49 points. Speedup over aiter, measured by AKLR validate on MI355X in the CI image (sglang 0.5.22):

(n, k) points speedup
n3648 k7168 22 1.01–1.82×
n7168 k512 11 1.02–1.54×
n7168 k768 6 1.03–1.10×
n7168 k1536 3 1.06–1.10×
n7168 k3584 3 1.02–1.08×
n7168 k4224 3 1.01–1.07×
n8448 k7168 1 1.09×

Points under 1.05 are not served.

  • Small m: split-K with an in-launch fold (bounded wait, each split folds its own share), 16-byte C stores.
  • Large m: up to 88 accumulator fragments per wave without spills (MFMAs past 64 fragments as inline asm), tile chosen per point by racing.

Routes: aklr/plugins/aiter (new) turns aiter's tgemm.mm and Triton gemm_a16w16 calls into gemm calls for both plugins; sglang 0.5.22 routes on them (aiter_calls.py) and on K3's lm_head and DSpark draft torch GEMMs; vLLM's tgemm.mm route goes through the same function.

Base: main. The GEMM, fused_moe and MLA decode PRs each add aklr/plugins/aiter and sglang's aiter_calls.py holding only their own functions; whichever lands later rebases (import lines).

End to end

Kimi-K3 on 8× MI355X, sglang 0.5.22 as the cookbook's MI355X cell (TP8, DCP8 a2a, aiter attention, fp8 KV, DSPARK block 7, ReplaySSM). Prompts are cut from a fixed corpus of Python source, the same every run. This PR off ([email protected]) vs on, every other K3 PR on in both, same server flags otherwise; the 100K rows and the 200K/500K rows come from two MI355X nodes, each row's off and on from the same node:

case decode step, off → on prefill, off → on on runs
ISL 100K, C=1 22.61 → 22.01 ms (1.027×) 5.70 → 5.73 s (0.994×) 4
ISL 100K, C=2 25.79 → 25.28 ms (1.020×) 5.70 → 5.71 s (0.997×) 4
ISL 200K, C=1 23.20 → 22.76 ms (1.020×) 12.58 → 13.00 s (0.967×) 2
ISL 200K, C=2 26.79 → 26.76 ms (1.001×) 12.40 → 12.39 s (1.001×) 2
ISL 500K, C=1 25.82 → 25.35 ms (1.019×) 38.50 → 38.45 s (1.001×) 2
ISL 500K, C=2 29.91 → 29.33 ms (1.020×) 38.53 → 38.49 s (1.001×) 2

Commands: SGLANG_USE_AITER=1 SGLANG_AITER_K3_OPT=1 AITER_FLYDSL_FORCE=1 AITER_SITUV2_A8W4=1 SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION=1 AKLR_SGLANG_PLUGIN=1 sglang serve --model-path Kimi-K3 --tp-size 8 --dcp-size 8 --dcp-comm-backend a2a --prefill-attention-backend aiter --decode-attention-backend aiter --kv-cache-dtype fp8_e4m3 --mem-fraction-static 0.85 --mamba-full-memory-ratio 7.97 --speculative-algorithm DSPARK --speculative-draft-model-path Kimi-K3-DSpark --speculative-dspark-block-size 7 --enable-linear-replayssm-spec. Each case flushes the cache and times each prompt's prefill (max_tokens=1), then decodes 1000 tokens for its C requests at once from the cached prompts; the decode step is decode time × accept length / tokens.

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

Missing behavioral coverage for route guards and dtype forwarding, unnecessary allocations before fallback, and skipped result-affecting default checks remain unresolved.

6 open issues
What changed in this PR

Adds MI355X FlyDSL kernels for Kimi-K3 dense bf16 GEMMs and connects SGLang and vLLM calls to AKLR’s existing gemm op.

Changes:

  • Adds shape-specific GEMM implementations with split-K and large-tile execution paths.
  • Introduces shared aiter adapters and SGLang routes for K3 projections and lm-head processing.
  • Extends route checks and adapter tests, and updates plugin documentation.
File Description
tests/​plugins/​sglang/​test_hook.py Checks registration and signatures for the new routes.
tests/​plugins/​aiter/​test_routes.py Tests adapter forwarding and fallback behavior.
tests/​plugins/​aiter/​__init__.py Adds the aiter test package.
aklr/​plugins/​vllm/​layers/​gemm.py Reuses the shared aiter GEMM adapter.
aklr/​plugins/​sglang/​models/​kimi_k3_torch_gemm.py Routes K3’s torch GEMM projections to AKLR.
aklr/​plugins/​sglang/​models/​dspark_torch_gemm.py Routes the DSpark draft’s unquantized lm-head GEMM.
aklr/​plugins/​sglang/​layers/​logits_processor_torch_gemm.py Routes plain lm-head GEMMs while preserving specialized branches.
aklr/​plugins/​sglang/​aiter_calls.py Declares SGLang routes for aiter GEMM calls.
aklr/​plugins/​sglang/​__init__.py Registers the new GEMM route modules.
aklr/​plugins/​README.md Documents shared aiter adapters and route layout.
aklr/​plugins/​aiter/​tuned_gemm.py Translates tuned GEMM arguments and rejects scaled calls.
aklr/​plugins/​aiter/​triton_gemm.py Translates Triton GEMM arguments and rejects unsupported operations.
aklr/​plugins/​aiter/​__init__.py Exports the shared GEMM adapters.
aklr/​ops/​gemm/​impls/​flydsl/​gemm_n8448_k7168/​392a1cb2a3cf08a7.json Adds the n8448/k7168 bf16 kernel and workload.
aklr/​ops/​gemm/​impls/​flydsl/​gemm_n7168_k4224/​05eed43ddd1d5162.json Adds tiled bf16 GEMMs for n7168/k4224.
aklr/​ops/​gemm/​impls/​flydsl/​gemm_n7168_k3584/​e7d85194d0cf3001.json Adds tiled bf16 GEMMs for n7168/k3584.
aklr/​ops/​gemm/​impls/​flydsl/​gemm_n7168_k1536/​55f744a71325d94b.json Adds HGEMM and tiled paths for n7168/k1536.

Review effort: Max

Comment on lines +24 to +29
(hasattr(lm_head, "set_lora") and hasattr(lm_head, "apply_lora"))
or should_apply_lm_head_quant_method(lm_head, getattr(lm_head, "quant_method", None))
or not hasattr(lm_head, "weight")
or self.use_fp32_lm_head
or use_intel_amx_backend(lm_head)
or self.rl_on_policy_target is not None
):
return FallbackReason.OUT_OF_CONTRACT
weight = lm_head.weight
return gemm(hidden_states.to(weight.dtype), weight)
Comment on lines +24 to +27
if should_apply_lm_head_quant_method(lm_head, lm_head.quant_method):
return FallbackReason.OUT_OF_CONTRACT
weight = lm_head.weight
return gemm(hidden.to(weight.dtype), weight)
Comment on lines +20 to +22
if out_dtype is None and out is not None:
out_dtype = out.dtype
return gemm(x, weight, out_dtype=out_dtype, out=out)
Comment thread tests/plugins/sglang/test_hook.py Outdated
Comment on lines +64 to +66
# aiter's defaults are aiter's enums, which route modules cannot import
defaults = not target.startswith("aiter.")
assert parameters(route, defaults=defaults) == parameters(pkgutil.resolve_name(target), defaults=defaults)
},
{
"path": "kernel.py",
"content": "\"\"\"bf16 GEMM family out = a @ b.T (+ bias).\n\nSmall-m shapes with n = 3648, k = 7168 run a FlyDSL split-K kernel in one launch: A and B tiles stream into\nXOR-swizzled LDS rings through buffer_load ... lds DMA, MFMA 16x16x32 accumulates in fp32, every split stores its fp32\npartial plane, and the split that arrives last on a launch-tagged per-tile counter sums the planes in split order and\nrounds once to bf16 (no workgroup waits on another). The large-m shapes in _TILED run tiled.py's four-wave tile, up\nto 320x256 outputs per workgroup (persistent on whole rounds of tiles of at most 64 accumulator fragments per wave, K\nsplit two ways below half a round); m = 893, k = 1536 runs hgemm.py's two-workgroups-per-CU tile; every other shape\nruns torch.matmul.\n\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir import ir\nfrom flydsl._mlir.dialects import arith as std_arith\nfrom flydsl._mlir.dialects import llvm\nfrom flydsl._mlir.dialects import rocdl as rocdl_d\nfrom flydsl.expr import arith, const_expr, gpu, range_constexpr, rocdl\nfrom flydsl.expr.typing import T, Vector\n\nfrom .hgemm import compiled as _hgemm\nfrom .tiled import compiled as _tiled\n\n# (m, n, k) -> (tile_m, tile_n, m_waves, n_waves, stages, split_k, b_policy)\n_CONFIGS = {\n (320, 3648, 7168): (128, 192, 2, 4, 3, 4, \"sc0\"),\n (400, 3648, 7168): (160, 192, 2, 4, 3, 4, \"sc0\"),\n (480, 3648, 7168): (160, 192, 2, 4, 3, 4, \"sc0\"),\n (520, 3648, 7168): (96, 192, 2, 4, 4, 2, \"sc0\"),\n (600, 3648, 7168): (160, 192, 2, 4, 3, 3, \"sc0\"),\n}\n\n# (m, n, k) -> tiled.py's four-wave tile: BM x BN tiles in groups of GROUP_N column (ROW_GROUPS: row) blocks; SPLIT 2\n# below half a round; past 64 accumulator fragments, next fragments read late (LATE_READS), one tile per workgroup on\n# whole rounds (ONE_TILE), and at 88 fragments A rows read JIT_A rows ahead of their MFMAs\n_TILED = {\n (2048, 3648, 7168): dict(BM=256, BN=256, GROUP_N=5, SPLIT=2),\n (2732, 6016, 7168): dict(BM=320, BN=224, GROUP_N=9),\n (2732, 6144, 7168): dict(BM=288, BN=256, GROUP_N=4),\n (2732, 7168, 1536): dict(BM=320, BN=256, GROUP_N=4, LATE_READS=8),\n (2732, 7168, 3584): dict(BM=320, BN=256, GROUP_N=4, LATE_READS=8),\n (2732, 7168, 4224): dict(BM=320, BN=256, GROUP_N=4),\n (9397, 2112, 7168): dict(BM=224, BN=352, GROUP_N=6, LATE_READS=4),\n (9397, 6016, 7168): dict(BM=224, BN=256, GROUP_N=3, ROW_GROUPS=True),\n (9397, 6144, 7168): dict(BM=320, BN=256, GROUP_N=6),\n (9397, 7168, 3584): dict(BM=352, BN=256, GROUP_N=4, LATE_READS=4, JIT_A=2),\n (9397, 7168, 4224): dict(BM=352, BN=256, GROUP_N=7, JIT_A=2),\n (16384, 3648, 7168): dict(BM=256, BN=320, GROUP_N=12, LATE_READS=8, ONE_TILE=True),\n (16384, 6144, 7168): dict(BM=320, BN=256, GROUP_N=6),\n (16384, 7168, 3584): dict(BM=256, BN=256, GROUP_N=7),\n (16384, 7168, 4224): dict(BM=256, BN=256, GROUP_N=7),\n (16384, 8448, 7168): dict(BM=256, BN=352, GROUP_N=3, ONE_TILE=True, JIT_A=2),\n}\n\n# (m, n, k) -> hgemm.py's tile arguments: (tile_m, tile_n, tile_k, stages, m_waves, n_waves, C store cache policy)\n_HGEMM = {\n (893, 7168, 1536): (128, 128, 64, 2, 2, 2, 2),\n}\n\n_SC01 = 17 # sc0 | sc1: device-coherent access past the non-coherent caches\n_CNT_LINE = 128 # bytes per tile counter: one cache line each\n_TAG_MUL = 0x9E3779B97F4A7C15 # odd: mixes the queue address into the dispatch id\n_TAG_MASK = (1 << 55) - 1\n\n\ndef _as_i32(v):\n if isinstance(v, int):\n return fx.arith.constant(v)\n v = fx.arith.unwrap(v)\n t = v.type\n if isinstance(t, ir.IntegerType):\n if t.width == 32:\n return v\n if t.width > 32:\n return std_arith.TruncIOp(T.i32, v).result\n return std_arith.ExtSIOp(T.i32, v).result\n return std_arith.IndexCastOp(T.i32, v).result\n\n\ndef _rsrc(tensor, num_records_bytes):\n buf = rocdl.make_buffer_tensor(tensor, max_size=False, num_records_bytes=num_records_bytes)\n return fx.arith.unwrap(rocdl.get_buffer_rsrc(fx.get_iter(buf)))\n\n\ndef _aux(v):\n return ir.IntegerAttr.get(T.i32, v)\n\n\ndef _bload(res_ty, rsrc, byte_off, aux=0):\n return rocdl_d.RawPtrBufferLoadOp(res_ty, rsrc, _as_i32(byte_off), fx.arith.constant(0), aux=_aux(aux)).result\n\n\ndef _bstore(data, rsrc, byte_off, aux=0):\n rocdl_d.RawPtrBufferStoreOp(\n fx.arith.unwrap(data), rsrc, _as_i32(byte_off), fx.arith.constant(0), aux=_aux(aux)\n )\n\n\ndef _lds_ptr(addr_i64):\n v = fx.arith.unwrap(addr_i64)\n return llvm.IntToPtrOp(ir.Type.parse(\"!llvm.ptr<3>\"), v).result\n\n\ndef _gep(base_ptr, byte_offset=None, static_byte_offset=0):\n base_ptr = fx.arith.unwrap(base_ptr)\n i8 = ir.IntegerType.get_signless(8)\n if byte_offset is None:\n return llvm.GEPOp(base_ptr.type, base_ptr, [], [int(static_byte_offset)], i8, None).result\n off = fx.arith.unwrap(byte_offset)\n return llvm.GEPOp(base_ptr.type, base_ptr, [off], [-(2**31)], i8, None).result\n\n\ndef _i64c(v):\n return std_arith.ConstantOp(T.i64, ir.IntegerAttr.get(T.i64, v)).result\n\n\[email protected]\ndef _build(m, n, k, BM, BN, WM, WN, STAGES, SPLIT, BPOL, BK=64):\n WAVES = WM * WN\n THREADS = WAVES * 64\n WARP_M = BM // WM\n WARP_N = BN // WN\n MS = WARP_M // 16\n NS = WARP_N // 16\n assert MS * 16 * WM == BM and NS * 16 * WN == BN\n NF = MS * NS\n N_BLOCKS = n // BN\n assert N_BLOCKS * BN == n\n M_BLOCKS = (m + BM - 1) // BM\n TILES = M_BLOCKS * N_BLOCKS\n assert k % BK == 0\n KBLK = k // BK\n LOOPS = KBLK // SPLIT\n REM = KBLK % SPLIT\n assert LOOPS >= STAGES >= 2\n K_STEPS = BK // 32\n KV = BK // 8\n A_CH = BM * KV\n B_CH = BN * KV\n C_CH = BM * BN // 8\n A_DMA = (A_CH + THREADS - 1) // THREADS\n B_DMA = (B_CH + THREADS - 1) // THREADS\n C_VECS = (C_CH + THREADS - 1) // THREADS\n for ch in (A_CH, B_CH, C_CH):\n assert ch % 64 == 0 and ch >= THREADS\n A_TAIL = (A_CH - (A_DMA - 1) * THREADS) // 64\n B_TAIL = (B_CH - (B_DMA - 1) * THREADS) // 64\n WAIT = A_DMA - (A_TAIL < WAVES) + B_DMA - (B_TAIL < WAVES)\n assert (STAGES - 2) * (A_DMA + B_DMA) < 63\n C_XV = BN // 8\n PART = BM * BN\n PROD = TILES * SPLIT\n plane_bytes = SPLIT * TILES * PART * 4\n ws_bytes = plane_bytes + TILES * _CNT_LINE\n ws_numel = ws_bytes // 4\n GRID = (TILES, SPLIT, 1)\n\n AS_ELEMS = STAGES * BM * BK\n BS_ELEMS = STAGES * BN * BK\n CS_ELEMS = BM * BN\n FLAG_ELEM = max(AS_ELEMS + BS_ELEMS, CS_ELEMS)\n LDS_ELEMS = FLAG_ELEM + 64\n\n @fx.struct\n class SharedStorage:\n buf: fx.Array[fx.BFloat16, LDS_ELEMS, 16]\n\n @flyc.kernel(known_block_size=[THREADS, 1, 1])\n def gemm_family_splitk(A: fx.Tensor, B: fx.Tensor, C: fx.Tensor, W: fx.Tensor):\n bf16x8 = fx.Vector.make_type(8, fx.BFloat16)\n a_rsrc = _rsrc(A, m * k * 2)\n b_rsrc = _rsrc(B, n * k * 2)\n c_rsrc = _rsrc(C, m * n * 2)\n w_rsrc = _rsrc(W, ws_bytes)\n lds = fx.SharedAllocator().allocate(SharedStorage)\n a_lds_ptr = lds.buf.peek().ptr\n b_lds_ptr = a_lds_ptr + fx.Int64(AS_ELEMS)\n c_lds_ptr = a_lds_ptr\n a_lds_i64 = fx.Int64(fx.ptrtoint(a_lds_ptr))\n b_lds_i64 = fx.Int64(fx.ptrtoint(b_lds_ptr))\n flag_lds = _gep(_lds_ptr(a_lds_i64), static_byte_offset=FLAG_ELEM * 2)\n\n tid = fx.thread_idx.x\n wid = tid // 64\n lane = tid % 64\n bid = fx.block_idx.x\n s_idx = fx.block_idx.y\n # (tile, split) pairs dispatch round-robin over 8 XCDs: each XCD takes a contiguous tile-major run, so the\n # splits of one tile start together on one XCD and reach the fold at about the same time\n lin = bid + s_idx * TILES\n x_q, x_r = PROD // 8, PROD % 8\n xcd = lin % 8\n logical = xcd * x_q + arith.select(xcd < x_r, xcd, x_r) + lin // 8\n s_idx = logical % SPLIT\n tile_id = logical // SPLIT\n # tiles that share a B column strip are adjacent, so they land on one XCD\n block_n = tile_id // M_BLOCKS\n block_m = tile_id % M_BLOCKS\n m_off = block_m * BM\n n_off = block_n * BN\n if const_expr(REM == 0):\n ks_begin = _as_i32(s_idx * (LOOPS * BK))\n n_iter = LOOPS - (STAGES - 1)\n else:\n # the first REM splits take one extra k-block\n s_i = fx.Int32(s_idx)\n ks_begin = _as_i32((s_i * LOOPS + arith.select(s_i < fx.Int32(REM), s_i, fx.Int32(REM))) * BK)\n n_iter = arith.index_cast(\n T.index, _as_i32(arith.select(s_i < fx.Int32(REM), fx.Int32(LOOPS + 1), fx.Int32(LOOPS)) - fx.Int32(STAGES - 1))\n )\n\n def kpos(j):\n return ks_begin + _as_i32(fx.Int32(j) * BK)\n\n warp_m = wid // WN * WARP_M\n warp_n = wid % WN * WARP_N\n frag_r = lane % 16\n frag_k = lane // 16 * 8\n\n warp_offset = rocdl.readfirstlane(T.i64, arith.index_cast(T.i64, fx.Index(wid) * fx.Index(64 * 16)))\n wid_s = None\n if const_expr(A_TAIL < WAVES or B_TAIL < WAVES):\n wid_s = fx.Int32(rocdl.readfirstlane(T.i32, _as_i32(wid)))\n\n def barrier(vmcnt):\n llvm.InlineAsmOp(None, [], f\"s_waitcnt vmcnt({vmcnt})\\n\\ts_barrier\", \"\", has_side_effects=True)\n\n def dma(rsrc, lds_ptr, goff, pol=\"sc0\"):\n llvm.InlineAsmOp(\n None,\n [lds_ptr, goff, rsrc],\n f\"s_mov_b32 m0, $0\\n\\tbuffer_load_dwordx4 $1, $2, 0 offen {pol} lds\",\n \"s,v,s\",\n has_side_effects=True,\n )\n\n def dma_tile(rsrc, lds_i64, rows, row_off, row_lim, count, tail, k_off, stage, pol=\"sc0\"):\n lds_p = None\n for ii in range_constexpr(count):\n gtid = THREADS * ii + tid\n r = gtid // KV\n col_bytes = (gtid % KV * 16) ^ (r % KV * 16)\n row = row_off + r\n if const_expr(row_lim is not None):\n row = arith.select(\n arith.cmpi(arith.CmpIPredicate.ult, fx.Index(row), fx.Index(row_lim)),\n fx.Index(row),\n fx.Index(0),\n )\n goff = _as_i32(fx.Index(row) * fx.Index(k * 2)) + _as_i32(k_off * 2) + _as_i32(col_bytes)\n if const_expr(lds_p is None):\n base = lds_i64 + fx.Int64(arith.index_cast(T.i64, fx.Index(stage) * fx.Index(rows * BK * 2)))\n lds_p = _gep(_lds_ptr(base), warp_offset)\n else:\n lds_p = _gep(lds_p, static_byte_offset=THREADS * 16)\n if const_expr(ii == count - 1 and tail < WAVES):\n if wid_s < fx.Int32(tail):\n dma(rsrc, lds_p, goff, pol)\n else:\n dma(rsrc, lds_p, goff, pol)\n\n def dma_a(k_off, stage):\n dma_tile(a_rsrc, a_lds_i64, BM, m_off, m if M_BLOCKS * BM > m else None, A_DMA, A_TAIL, k_off, stage)\n\n def dma_b(k_off, stage):\n dma_tile(b_rsrc, b_lds_i64, BN, n_off, None, B_DMA, B_TAIL, k_off, stage, BPOL)\n\n def lds_frag(base_ptr, rows, stage, row, kcol):\n col_bytes = (kcol * 2) ^ (row % KV * 16)\n off = fx.Int64(stage) * (rows * BK) + fx.Int64(row) * BK + fx.Int64(col_bytes // 2)\n return fx.ptr_load(base_ptr + off, result_type=bf16x8)\n\n def compute(stage, frags):\n s = fx.Index(stage)\n out = [x for x in frags]\n for kk in range_constexpr(K_STEPS):\n kcol = kk * 32 + frag_k\n b_fr = [lds_frag(b_lds_ptr, BN, s, warp_n + j * 16 + frag_r, kcol) for j in range_constexpr(NS)]\n a_fr = [lds_frag(a_lds_ptr, BM, s, warp_m + i * 16 + frag_r, kcol) for i in range_constexpr(MS)]\n rocdl.sched_barrier(0)\n for i in range_constexpr(MS):\n for j in range_constexpr(NS):\n out[i * NS + j] = rocdl.mfma_f32_16x16x32_bf16(\n T.vec(4, T.f32), [a_fr[i], b_fr[j], out[i * NS + j], 0, 0, 0]\n )\n return out\n\n def hot_loop_scheduler():\n for _ in range_constexpr(B_DMA + A_DMA):\n rocdl.sched_vmem(1)\n for _ in range_constexpr(K_STEPS):\n for _ in range_constexpr(NS + MS):\n rocdl.sched_dsrd(1)\n for _ in range_constexpr(MS):\n rocdl.sched_mfma(NS)\n rocdl.sched_barrier(0)\n\n acc0 = [arith.constant_vector(0.0, T.vec(4, T.f32))] * NF\n\n def mainloop():\n for st in range_constexpr(STAGES - 1):\n dma_b(kpos(st), st)\n dma_a(kpos(st), st)\n rocdl.sched_barrier(0)\n init_state = [fx.Int32(0), arith.constant(0, index=True)] + acc0\n for bki, state in range(0, n_iter, 1, init=init_state):\n k_offset = state[0]\n cur = fx.Index(state[1])\n frags = state[2:]\n nxt = (cur + 1) % STAGES\n wst = (cur + STAGES - 1) % STAGES\n barrier((STAGES - 2) * WAIT)\n dma_b(kpos(k_offset + (STAGES - 1)), wst)\n dma_a(kpos(k_offset + (STAGES - 1)), wst)\n new = compute(cur, frags)\n hot_loop_scheduler()\n results = yield [k_offset + fx.Int32(1), nxt] + new\n cur = fx.Index(results[1])\n m_frags = results[2:]\n for st in range_constexpr(STAGES - 1):\n barrier((STAGES - 2 - st) * WAIT)\n m_frags = compute(cur, m_frags)\n cur = (cur + 1) % STAGES\n return m_frags\n\n c_frags = mainloop()\n\n # fragment-major planes: (split, tile, wave, frag, lane) x f32x4\n frag_base = (tile_id * WAVES + wid) * NF\n\n def plane_off(sp, f):\n return ((sp * (TILES * WAVES * NF) + frag_base + f) * 64 + lane) * 16\n\n for f in range_constexpr(NF):\n _bstore(Vector(c_frags[f]), w_rsrc, plane_off(s_idx, f), _SC01)\n rocdl.s_waitcnt(vmcnt=0)\n gpu.barrier()\n\n if tid == fx.Int32(0):\n # launch tag: dispatch id plus queue address bits (ids restart on another queue)\n did = llvm.call_intrinsic(T.i64, \"llvm.amdgcn.dispatch.id\", [], [], [])\n qp = llvm.call_intrinsic(ir.Type.parse(\"!llvm.ptr<4>\"), \"llvm.amdgcn.queue.ptr\", [], [], [])\n qpi = llvm.PtrToIntOp(T.i64, qp).result\n tag = std_arith.AndIOp(\n std_arith.AddIOp(did, std_arith.MulIOp(qpi, _i64c(_TAG_MUL - (1 << 64))).result).result,\n _i64c(_TAG_MASK),\n ).result\n tag_base = std_arith.ShLIOp(tag, _i64c(8)).result\n wptr = fx.to_llvm_ptr(fx.get_iter(W))\n cnt_off = std_arith.ExtSIOp(T.i64, _as_i32(tile_id * _CNT_LINE + plane_bytes)).result\n cptr = _gep(wptr, cnt_off)\n cur = llvm.LoadOp(\n T.i64, cptr, alignment=8, ordering=llvm.AtomicOrdering.monotonic, syncscope=\"agent\"\n ).result\n stale = std_arith.CmpIOp(\n std_arith.CmpIPredicate.ne, std_arith.ShRUIOp(cur, _i64c(8)).result, tag\n ).result\n # a word from another launch is reset to this launch's tag with count 0; a word that already holds the\n # tag is left alone (its expected value is one no tagged word can hold)\n expect = std_arith.SelectOp(stale, cur, _i64c(-1)).result\n llvm.cmpxchg(\n cptr,\n expect,\n tag_base,\n llvm.AtomicOrdering.monotonic,\n llvm.AtomicOrdering.monotonic,\n syncscope=\"agent\",\n alignment=8,\n )\n old = llvm.atomicrmw(\n llvm.AtomicBinOp.add,\n cptr,\n _i64c(1),\n llvm.AtomicOrdering.monotonic,\n syncscope=\"agent\",\n alignment=8,\n )\n last = std_arith.CmpIOp(\n std_arith.CmpIPredicate.eq, old, std_arith.OrIOp(tag_base, _i64c(SPLIT - 1)).result\n ).result\n llvm.StoreOp(std_arith.ExtUIOp(T.i32, last).result, flag_lds, alignment=4)\n gpu.barrier()\n is_last = fx.Int32(llvm.LoadOp(T.i32, flag_lds, alignment=4).result)\n\n def fold_sums(own_sp):\n sums = []\n for f in range_constexpr(NF):\n tot = None\n for sp in range_constexpr(SPLIT):\n if const_expr(sp == own_sp):\n v = Vector(c_frags[f])\n else:\n v = Vector(_bload(T.f32x4, w_rsrc, plane_off(fx.Int32(sp), f), _SC01))\n tot = v if tot is None else tot + v\n sums.append(tot)\n return sums\n\n def write_c(sums):\n gpu.barrier()\n c_m = lane // 16 * 4\n c_n = lane % 16\n for i in range_constexpr(MS):\n for j in range_constexpr(NS):\n cast = sums[i * NS + j].to(fx.BFloat16)\n for e in range_constexpr(4):\n row = warp_m + i * 16 + c_m + e\n col = warp_n + j * 16 + c_n\n fx.ptr_store(cast[e], c_lds_ptr + fx.Int64(row * BN + col))\n gpu.barrier()\n for i in range_constexpr(C_VECS):\n g = THREADS * i + tid\n r = g // C_XV\n cc = g % C_XV * 8\n row = m_off + r\n if const_expr(i == C_VECS - 1 and C_CH % THREADS != 0):\n row = arith.select(g < fx.Int32(C_CH), fx.Int32(row), fx.Int32(m))\n if row < fx.Int32(m):\n v = fx.ptr_load(c_lds_ptr + fx.Int64(r * BN + cc), result_type=bf16x8)\n _bstore(v, c_rsrc, (row * n + n_off + cc) * 2)\n\n # one uniform branch per split index: the folder keeps its own partial in registers, reads the other\n # planes, and still adds in split order, so every folder produces the same bits\n sel = is_last * (fx.Int32(s_idx) + fx.Int32(1))\n for so in range_constexpr(SPLIT):\n if sel == fx.Int32(so + 1):\n write_c(fold_sums(so))\n\n @flyc.jit\n def launch(A: fx.Tensor, B: fx.Tensor, C: fx.Tensor, W: fx.Tensor, stream: fx.Stream):\n gemm_family_splitk(A, B, C, W).launch(grid=GRID, block=(THREADS, 1, 1), stream=stream)\n\n return launch, ws_numel\n\n\[email protected]\ndef _plan(m, n, k):\n cfg = _CONFIGS.get((m, n, k))\n if cfg is None:\n return None\n return _build(m, n, k, *cfg)\n\n\ndef run(*, a, b, trans_b, bias, out_dtype, out):\n plan = None\n tiled = None\n hgemm = None\n if (\n trans_b\n and bias is None\n and a.dtype == torch.bfloat16\n and b.dtype == torch.bfloat16\n and out.dtype == torch.bfloat16\n and a.is_contiguous()\n and b.is_contiguous()\n and out.is_contiguous()\n ):\n shape = (a.shape[0], b.shape[0], a.shape[1])\n plan = _plan(*shape)\n if shape in _TILED:\n tiled = _tiled(*shape, **_TILED[shape])\n if shape in _HGEMM:\n hgemm = _hgemm(*shape, *_HGEMM[shape])\n if hgemm is not None:\n hgemm(a, b, out, stream=fx.Stream(torch.cuda.current_stream(a.device)))\n return\n if tiled is not None:\n fn, ws_numel = tiled\n ws = torch.empty((ws_numel,), dtype=torch.float32, device=a.device) if ws_numel else out\n fn(a, b, out, ws, fx.Stream(torch.cuda.current_stream(a.device)))\n return\n if plan is None:\n torch.matmul(a, b.t() if trans_b else b, out=out)\n if bias is not None:\n out.add_(bias)\n return\n launch, ws_numel = plan\n ws = torch.empty((ws_numel,), dtype=torch.float32, device=a.device)\n launch(a, b, out, ws, stream=fx.Stream(torch.cuda.current_stream(a.device)))\n"
…'s and K3's GEMM calls

Kimi-K3 dense bf16 GEMM on MI355X: FlyDSL kernels, and routes that bring K3's GEMM calls to `gemm`.
@kyle-256
kyle-256 merged commit 24f36f2 into main Nov 13, 2026
16 checks passed
@kyle-256
kyle-256 deleted the kyle/k3-gemm branch November 13, 2026 14:37
zhenhuang12 pushed a commit that referenced this pull request Nov 14, 2026
- aiter's SwiGLU MoE reaches fused_moe only where aiter rounds its activations as fused_moe does (#160).
- A sglang route whose target needs a package that is not installed is left unhooked instead of ending sglang's
  start (#160). The lm_head routes hand gemm the hidden states as they are; the Triton GEMM route takes the K3
  image's aiter's persistent option (#159). vLLM's GEMM warmup records no workload and builds only the weight shapes
  of the rank's model and drafter (#165).
- Attention residual, sglang and vLLM: masked lanes score -inf; one lane stores each LDS partial; sums of squares
  past float32 are summed again scaled (decode kernels, on a uniform rare path, the common path as before) or
  prescaled by 2**-32 (prefill kernels); vLLM's mix without an output norm is weighted by normalized weights
  (#162, #176).
- kimi_k3_attn_res: RMS weights may be any finite value; the reference widens each chunk only and returns the prefix
  unscored with no bank row (#176). Route tests, GPU range regressions, the vLLM baseline's parity with vLLM's
  kernel, and two more vLLM Points.
zhenhuang12 added a commit that referenced this pull request Nov 16, 2026
…ts call

A schema's workload now carries `models`: the models whose serving makes that very call, sorted,
each once, lowercase (`kimi-k3`, `deepseek-v4-pro`, `glm-5.2`). The file's `models`, right after
`op_type`, is their union, written by `schema_text` and so checked on parse: the file shows at a
glance which models it is for, and each workload which of them calls it. The uuid hashes neither,
so no file moves; the schema_version stays 5.

A workload without `models` still parses (a base from before this change is read as it is), and
`schema_errors` refuses it (E10), so `export check` and audit require it of every committed and
changed file. `OpContract.narrow` keeps its signature; `workload_for` takes the models.

`python -m aklr export` takes `--model`: a new file's workloads carry it, and a committed file the
calls reach is listed with the called workloads that do not name it.

All 698 committed schemas (4606 workloads) are labelled. A workload takes the model named by the
commit that added it, in AKLR or, for AKLR's initial commit, in SIKL (whose main is that commit);
a kernel added later at an existing Point takes the Point's models. Where one scenario holds
workloads of several commits, they are told apart:
- flash_mla sparse decode and fp8_paged_mqa_logits (64 heads): SIKL #71's are deepseek-v4-flash,
  SIKL #83's deepseek-v4-pro; the three 262144-row ones of #96 ("DSV4") name both.
- deepseek_v2_fp8_moe at model_dim 6144: #46's are glm-5.2, #124's and #181's glm-5.3.
- gemm_n7168_k512: #159's multiples of 7 (DSPARK's draft) are kimi-k3.
Workloads from SIKL #52, which gave the pre-existing definitions their default sweep, take the
model of the commit that added the definition: SIKL #50 (DeepSeek-V4-Flash's schema set), #35 and
#47 (Kimi-K3). The definitions of SIKL #18 and #36 name no model and are labelled by their shapes,
as the owner reviewed: hidden-6144 GEMMs and MoE as glm-5.2, gemm_a8w8_blockwise_scaled_n3072_k1536
as deepseek-r1, gemm_n7168_k512's sweep as glm-5.2 and kimi-k3, the hidden-6144 norms as glm-5.2
and glm-5.3. By the owner's choice, DeepSeek-R1's workloads also name deepseek-v3, the DSA indexer
ones name glm-5.2 and glm-5.3, and gemm_n4096_k2048 and gemm_n512_k4096 also name qwen3.5. The
Qwen3.5 gated-attention decode workloads (qkv_dim 4608) also name qwen3-next, whose TP2 route
falls through to that op (#78).
kyle-256 added a commit that referenced this pull request Nov 16, 2026
… activation rounding, sglang without aiter (#197)

* fix(plugins): fixes from Copilot's reviews of the merged Kimi-K3 PRs

- aiter's SwiGLU MoE reaches fused_moe only where aiter rounds its activations as fused_moe does (#160).
- A sglang route whose target needs a package that is not installed is left unhooked instead of ending sglang's
  start (#160). The lm_head routes hand gemm the hidden states as they are; the Triton GEMM route takes the K3
  image's aiter's persistent option (#159). vLLM's GEMM warmup records no workload and builds only the weight shapes
  of the rank's model and drafter (#165).
- Attention residual, sglang and vLLM: masked lanes score -inf; one lane stores each LDS partial; sums of squares
  past float32 are summed again scaled (decode kernels, on a uniform rare path, the common path as before) or
  prescaled by 2**-32 (prefill kernels); vLLM's mix without an output norm is weighted by normalized weights
  (#162, #176).
- kimi_k3_attn_res: RMS weights may be any finite value; the reference widens each chunk only and returns the prefix
  unscored with no bank row (#176). Route tests, GPU range regressions, the vLLM baseline's parity with vLLM's
  kernel, and two more vLLM Points.

* test(plugins): drop the finite-input attention-residual tests

Their 36 sglang and 18 vLLM cases each loaded every committed schema (about 23 s on the CI
node) and stopped the unit tests at their 25-minute limit.

* fix(plugins): keep the no-norm attention residual within its VGPRs

The rare path for a sum of squares past float32 loaded all nine rows at once
for its mix. That pushed the 896-thread kernel past its 128 VGPRs, so the
common path spilled its rows to scratch (47 VGPRs, 192 bytes) and ran at
0.76x of the baseline. Without a norm the rare path now loads one row at a
time, with a scheduling barrier between rows of the mix: 120 VGPRs and no
scratch, about 1.9x again on all four workloads.
zhenhuang12 added a commit that referenced this pull request Nov 17, 2026
…ts call

A schema's workload now carries `models`: the models whose serving makes that very call, sorted,
each once, lowercase (`kimi-k3`, `deepseek-v4-pro`, `glm-5.2`). The file's `models`, right after
`op_type`, is their union, written by `schema_text` and so checked on parse: the file shows at a
glance which models it is for, and each workload which of them calls it. The uuid hashes neither,
so no file moves; the schema_version stays 5.

A workload without `models` still parses (a base from before this change is read as it is), and
`schema_errors` refuses it (E10), so `export check` and audit require it of every committed and
changed file. `OpContract.narrow` keeps its signature; `workload_for` takes the models.

`python -m aklr export` takes `--model`: a new file's workloads carry it, and a committed file the
calls reach is listed with the called workloads that do not name it.

All 705 committed schemas (4668 workloads) are labelled. A workload takes the model named by the
commit that added it, in AKLR or, for AKLR's initial commit, in SIKL (whose main is that commit);
a kernel added later at an existing Point takes the Point's models. Where one scenario holds
workloads of several commits, they are told apart:
- flash_mla sparse decode and fp8_paged_mqa_logits (64 heads): SIKL #71's are deepseek-v4-flash,
  SIKL #83's deepseek-v4-pro; the three 262144-row ones of #96 ("DSV4") name both.
- deepseek_v2_fp8_moe at model_dim 6144: #46's are glm-5.2, #124's and #181's glm-5.3.
- gemm_n7168_k512: #159's multiples of 7 (DSPARK's draft) are kimi-k3.
Workloads from SIKL #52, which gave the pre-existing definitions their default sweep, take the
model of the commit that added the definition: SIKL #50 (DeepSeek-V4-Flash's schema set), #35 and
#47 (Kimi-K3). The definitions of SIKL #18 and #36 name no model and are labelled by their shapes,
as the owner reviewed: hidden-6144 GEMMs and MoE as glm-5.2, gemm_a8w8_blockwise_scaled_n3072_k1536
as deepseek-r1, gemm_n7168_k512's sweep as glm-5.2 and kimi-k3, the hidden-6144 norms as glm-5.2
and glm-5.3. By the owner's choice, DeepSeek-R1's workloads also name deepseek-v3, the DSA indexer
ones name glm-5.2 and glm-5.3, and gemm_n4096_k2048 and gemm_n512_k4096 also name qwen3.5. The
Qwen3.5 gated-attention decode workloads (qkv_dim 4608) also name qwen3-next, whose TP2 route
falls through to that op (#78).

Rebased onto main at #235: the files main rewrote (#169, #197, #217) keep their Points' models
under the new uuids and paths, and #212's seven GEMM files, at Points new to the tree, are glm-5.2.
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

This branch was previously deployed

1 inactive deployment
gpu-trusted — b7d190f4 Deployed Nov 13, 2026 by kyle-256 via prepare-gpu / prepare #712
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