Skip to content

feat(plugins): Kimi-K3's attention residual on vLLM, its route and FlyDSL kernels - #176

Merged
kyle-256 merged 1 commit into
mainfrom
kyle/k3v-attn-res
Nov 13, 2026
Merged

kyle-256 merged 1 commit into
mainfrom
kyle/k3v-attn-res

Conversation

@kyle-256

Copy link
Copy Markdown
Collaborator

vLLM runs Kimi-K3's attention residual (models/kimi_k3/amd/ops/attn_res.py) 187 times a decode
step: before attention and before the MLP of each of the 93 layers, and once before the final
norm. [email protected] states every call it makes: 0 to 8 bank rows read, the pending layer
output folded into the prefix in place, the prefix written as the next bank row, the output
norm optional, the score weight the product of two bf16 weights. The baseline is vLLM's Triton
kernel with its launch configuration (copied, Apache-2.0, so that it runs without vLLM). The
route replaces the attn_res that _apply_attn_res calls and falls back on the fp8 output (a
linear taking per-token fp8 input, which Kimi-K3's MXFP4 checkpoint does not have).

One schema per call combination vLLM makes for Kimi-K3 (hidden 7168, 8 bank rows): 1 to 8 rows
with the addend and the output norm (170 of the 187 calls a decode step), with the bank write
(7), without the addend (8), and the last layer's mix without a norm (1); workloads 3, 6, 9 and
12 tokens (1 to 4 requests of 3 decode tokens). One kernel source: a workgroup of 896 threads
per token, with a helper workgroup on the same XCD loading the token's bank rows into L2; the
row count is fixed per build and the token count is a kernel argument.

Speedup over vLLM's Triton kernel (validate on MI355X, every workload within the bounds, none
demoted): 1.22x to 1.97x, geometric mean 1.65x; at 3 tokens the 186 calls a decode step take
0.89 ms instead of 1.51 ms. The first layer's call (no bank row, 1 a step) stays on vLLM's
kernel: both sit at the launch floor there (1.00x).

Base: main.

End to end

Kimi-K3 on 8× MI355X, vLLM 0.33.0rc1.dev910 (TP8, fp8 KV, aiter's SiTUv2 a4w4 MoE, DSpark with 2 speculative tokens, full CUDA graphs up to 24 tokens). ISL 100K, 1000 output tokens, prompts cut from a fixed corpus of Python source. This PR off ([email protected]) vs on, every other K3 change for vLLM on in both, same flags otherwise, one node; on is the mean of two all-on runs; two rounds. Decode step = decode time × accept length / tokens; the prefill does not change.

case decode step, off → on (round 1) round 2
C=1 16.86 → 16.52 ms (1.021×) 16.71 → 16.24 ms (1.029×)
C=2 20.36 → 19.46 ms (1.046×) 19.79 → 19.16 ms (1.033×)
C=4 25.58 → 24.79 ms (1.032×) 24.79 → 24.51 ms (1.011×)

Command: VLLM_ROCM_USE_AITER=1 VLLM_ROCM_USE_AITER_MOE_SITUV2=a4w4 VLLM_ROCM_AITER_MLA_ASM_PADDING=asm AKLR_VLLM_PLUGIN=1 vllm serve Kimi-K3 --trust-remote-code --tensor-parallel-size 8 --kv-cache-dtype fp8 --max-num-seqs 4 --max-model-len 1048576 --enable-prefix-caching --language-model-only --compilation-config '{"mode":3,"cudagraph_mode":"FULL_AND_PIECEWISE","max_cudagraph_capture_size":24}' --speculative-config '{"model":"Kimi-K3-DSpark","num_speculative_tokens":2,"method":"dspark","attention_backend":"TRITON_MLA"}'.

Copilot AI max review requested due to automatic review settings November 13, 2026 00:15
@kyle-256 kyle-256 changed the title feat(plugins): Kimi-K3's attention residual on vLLM ([email protected]), its route and FlyDSL kernels feat(plugins): Kimi-K3's attention residual on vLLM, its route and FlyDSL kernels Nov 13, 2026

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

Unresolved overflow defects in the kernels, baseline, and reference produce incorrect or non-finite outputs for valid finite bfloat16 inputs.

11 open issues
What changed in this PR

Adds Kimi-K3 attention-residual support to AKLR’s vLLM plugin, targeting faster decode on MI355X while preserving vLLM fallbacks for unsupported calls.

Changes:

  • Defines the operation contract, float64 reference, and copied vLLM Triton baseline.
  • Adds vLLM routing and specialized FlyDSL kernels for residual-bank mixing.
  • Registers the model plugin and extends schema-name and small-Point test fixtures.
File Description
tests/​plugins/​vllm/​names.txt Records expected Kimi-K3 schema names.
tests/​plugins/​vllm/​cases.py Adds small attention-residual test Points.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​reference.py Implements float64 reference math and state updates.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows7_no_add_hidden_size7168_n_bank_rows8/​2b45e451a0356326.json Publishes the seven-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows6_no_add_hidden_size7168_n_bank_rows8/​a7db5c8b5b9a9105.json Publishes the six-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows5_no_add_hidden_size7168_n_bank_rows8/​52b6e948150d2155.json Publishes the five-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows4_no_add_hidden_size7168_n_bank_rows8/​764d12dfe5fcca5c.json Publishes the four-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows3_no_add_hidden_size7168_n_bank_rows8/​7c802588d99a5195.json Publishes the three-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows2_no_add_hidden_size7168_n_bank_rows8/​114f2a9decd14b8b.json Publishes the two-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_rows1_no_add_hidden_size7168_n_bank_rows8/​2431a4cc0541423a.json Publishes the one-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_no_norm_hidden_size7168_n_bank_rows8/​d1ee7c9606354bf8.json Publishes the final mix variant without output normalization.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​impls/​flydsl/​kimi_k3_attn_res_no_add_hidden_size7168_n_bank_rows8/​d1ee6da396592256.json Publishes the eight-row, no-addend kernel variant.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​contract.py Defines operands, mutations, call variants, and tolerances.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​baseline.py Adapts the copied vLLM baseline to AKLR’s interface.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​api.py Exposes dispatch and translates vLLM calls with fallbacks.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​_triton.py Copies the upstream kernel and nonquantized launcher.
aklr/​plugins/​vllm/​models/​kimi_k3/​attn_res/​__init__.py Exports the attention-residual API.
aklr/​plugins/​vllm/​models/​kimi_k3/​__init__.py Exposes the Kimi-K3 operation package.
aklr/​plugins/​vllm/​models/​__init__.py Registers Kimi-K3 alongside existing model plugins.

Review effort: Max

eviction_policy="evict_first",
).to(tl.float32)
values = tl.where(is_prefix[:, None], updated_prefix[None, :], block_values)
reciprocal_std = tl.rsqrt(tl.sum(values * values, axis=1) * (1.0 / hidden_size) + eps)
_ROWS = ("n_tokens", "hidden_size")
_EXACT = ToleranceBound(absolute_tolerance=0, relative_tolerance=0)
# about [0.5, 1.5]
_NORM_WEIGHT_DISTRIBUTION = LogUniformDistribution(log2_lo="-1", log2_hi="0.58")
"sources": [
{
"path": "kernel.py",
"content": "\"\"\"Kimi-K3's attention residual as vLLM calls it, for hidden size 7168, in FlyDSL for gfx950.\n\nOne workgroup per token, 896 threads (14 waves), each thread owning 8 contiguous hidden columns, handled as four column\npairs in packed fp32. The buffers arrive as preloaded pointers. p is the prefix, or bf16(prefix + addend) stored back\nto the prefix in place; with write_bank p also goes to bank row n_valid_rows. The rows scored are the n_valid_rows\nbank rows, then p. Each score weight pair is the product of the two bf16 weights, exact in fp32. Each row's two\nper-thread partials (dot with the score weight, sum of squares) are reduce-scattered inside each wave (permlane\nswaps, then DPP), exchanged through LDS and summed over the waves in a fixed order by every wave alike. Lanes below\nthe row count hold one row's score each; the softmax runs across those lanes and its unnormalised weights go to\nscalar registers for the mix, their sum Z in a fixed order. With a norm weight, the mix's mean square (second LDS\nexchange) absorbs Z; without one the mix is divided by Z. With no bank row the mix is p itself. Every reduction runs\nin a fixed order, so the output is bitwise deterministic.\n\nEach token's workgroup has a helper workgroup on the same XCD (8 workgroup ids later) that only loads the token's\nbank rows, so that the token's own requests for them, issued ~0.3 us after its first loads, hit the shared L2. The\nhelper waits for nobody and nobody waits for it. The token count is a kernel argument: one build serves every count\nwhose grid (16 workgroups per 8 tokens) it was built for.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\n\nimport torch\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nfrom flydsl._mlir import ir as _ir\nfrom flydsl._mlir.dialects import arith as _arith\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl._mlir.dialects import math as _math\nfrom flydsl._mlir.dialects import memref as _memref\nfrom flydsl._mlir.dialects import rocdl as _rocdl\nfrom flydsl._mlir.dialects import scf as _scf\nfrom flydsl._mlir.dialects import vector as _vector\nfrom flydsl.compiler.kernel_function import CompilationContext\nfrom flydsl.expr.gpu import lds_space as _lds_space\nfrom flydsl.utils.smem_allocator import SmemAllocator\n\nD = 7168\nWAVE = 64\nVEC = 8 # hidden columns per thread\nNTHR = D // VEC # 896\nNW = NTHR // WAVE # 14\nWPAD = 16 # waves per LDS slot row (14 used)\nLDS1 = 32 * WPAD # slot s (dot of row s, or sum of squares of row s - 2 * H2), wave w at s * WPAD + w\nLDS2 = WPAD # the sums of squares of the second exchange, one per wave\nXCDS = 8 # workgroups b and b + 8 run on the same XCD\nHELPERS = 1 # helper workgroups per token\nGROUP = (1 + HELPERS) * XCDS # 8 tokens' workgroups, then their helpers, 8 at a time\nHELP_SLEEP = 12 # s_sleep units (64 cycles) before the token's bank-row loads\n_LOG2E = 1.4426950408889634\n_INV_D = 1.0 / D\n\n_DPP_XOR1 = 0xB1 # quad_perm [1,0,3,2]\n_DPP_XOR2 = 0x4E # quad_perm [2,3,0,1]\n_DPP_HMIRROR = 0x141 # row_half_mirror (xor 4 once quads are uniform)\n_DPP_ROR8 = 0x128 # row_ror:8 (xor 8 inside a 16-lane row)\n_DPP_ALL = (_DPP_XOR1, _DPP_XOR2, _DPP_HMIRROR, _DPP_ROR8)\n\n\ndef _f32(v):\n return fx.Float32(v)\n\n\ndef _rsq(x):\n return fx.Float32(fx.rocdl.rsq(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _exp2(x):\n return fx.Float32(fx.rocdl.exp2(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _dpp(v, ctrl):\n return fx.Float32(fx.rocdl.update_dpp(\n _ir.F32Type.get(), fx.as_ir_value(v), fx.as_ir_value(v), ctrl, 0xF, 0xF, True))\n\n\ndef _permute_pair(a, b, bit):\n \"\"\"(a_low | b_low, a_high | b_high) across the 32-lane (bit 5) or 16-lane (bit 4) split.\"\"\"\n i32 = _ir.IntegerType.get_signless(32)\n ai = _arith.BitcastOp(i32, fx.as_ir_value(a)).result\n bi = _arith.BitcastOp(i32, fx.as_ir_value(b)).result\n op = _rocdl.permlane16_swap if bit == 4 else _rocdl.permlane32_swap\n pair = op(_ir.Type.parse(\"!llvm.struct<(i32, i32)>\"), ai, bi, False, True)\n vals = [_llvm.ExtractValueOp(i32, pair, [i]).result for i in range(2)]\n return [fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), v).result) for v in vals]\n\n\ndef _scatter(vals, bit):\n \"\"\"Reduce-scatter step: lanes with ``bit`` clear end with the low half summed, lanes with it set the high half.\"\"\"\n h = (len(vals) + 1) // 2\n lo = vals[:h]\n hi = vals[h:] + [None] * (2 * h - len(vals))\n out = []\n for k in range(h):\n hk = _f32(0.0) if hi[k] is None else hi[k]\n a, b = _permute_pair(lo[k], hk, bit)\n out.append(a + b)\n return out\n\n\ndef _wave_allsum(v):\n for ctrl in _DPP_ALL:\n v = v + _dpp(v, ctrl)\n for bit in (4, 5):\n a, b = _permute_pair(v, v, bit)\n v = a + b\n return v\n\n\ndef _readlane(v, j):\n i32 = _ir.IntegerType.get_signless(32)\n bits = _arith.BitcastOp(i32, fx.as_ir_value(v)).result\n r = fx.rocdl.readlane(i32, bits, j)\n return fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), fx.as_ir_value(r)).result)\n\n\ndef _as_index(v):\n v = fx.as_ir_value(v)\n if isinstance(v.type, _ir.IntegerType):\n v = _arith.IndexCastOp(_ir.IndexType.get(), v).result\n return v\n\n\ndef _scf_if(cond, then_fn):\n \"\"\"scf.if without results on a condition: ``then_fn`` emits the guarded ops.\"\"\"\n op = _scf.IfOp(fx.as_ir_value(cond), [], has_else=False)\n with _ir.InsertionPoint(op.regions[0].blocks[0]):\n then_fn()\n _scf.YieldOp([])\n\n\ndef _lds_st(lds, v, idx):\n _memref.store(fx.as_ir_value(v), lds, [_as_index(idx)])\n\n\ndef _lds_ld(lds, idx):\n return fx.Float32(_memref.load(lds, [_as_index(idx)]))\n\n\ndef _lds_ld4(lds, idx):\n \"\"\"Four consecutive LDS floats from a 16 B aligned index.\"\"\"\n return _vector.load(_vt(4, _ir.F32Type.get()), lds, [_as_index(idx)])\n\n\ndef _vt(n, elem):\n return _ir.VectorType.get([n], elem)\n\n\ndef _bf_pair(vec, k):\n \"\"\"Columns 2k, 2k+1 of an 8 x bf16 vector, as a 2 x bf16 vector.\"\"\"\n return _vector.extract_strided_slice(_vt(2, _ir.BF16Type.get()), fx.as_ir_value(vec), [2 * k], [2], [1])\n\n\ndef _f_pair(bf2):\n return _arith.ExtFOp(_vt(2, _ir.F32Type.get()), bf2).result\n\n\ndef _to_bf_pair(f2):\n return _arith.TruncFOp(_vt(2, _ir.BF16Type.get()), f2).result\n\n\ndef _pk_add(a, b):\n return _arith.AddFOp(a, b).result\n\n\ndef _pk_mul(a, b):\n return _arith.MulFOp(a, b).result\n\n\ndef _pk_fma(a, b, c):\n return _math.fma(a, b, c)\n\n\ndef _hsum(v2):\n return _f32(_vector.extract(v2, [], [0])) + _f32(_vector.extract(v2, [], [1]))\n\n\ndef _splat2(x):\n return _vector.broadcast(_vt(2, _ir.F32Type.get()), fx.as_ir_value(x))\n\n\ndef _sum_sq(x):\n \"\"\"A row's sum of squares over the thread's 8 columns (v_pk_fma_f32 on the widened pairs).\"\"\"\n s2 = _pk_mul(x[0], x[0])\n for k in range(1, 4):\n s2 = _pk_fma(x[k], x[k], s2)\n return _hsum(s2)\n\n\ndef _concat8(pairs):\n \"\"\"Four 2-element vectors into one 8-element vector.\"\"\"\n a = _vector.shuffle(pairs[0], pairs[1], [0, 1, 2, 3])\n b = _vector.shuffle(pairs[2], pairs[3], [0, 1, 2, 3])\n return _vector.shuffle(a, b, list(range(8)))\n\n\ndef _opaque(v, bits, side_effects=False):\n \"\"\"v unchanged through an empty asm tied to its input (no instruction): LLVM cannot fold across it, and with\n side_effects it stays before the next barrier.\"\"\"\n ity = _ir.IntegerType.get_signless(bits)\n x = _llvm.BitcastOp(ity, v).result\n y = _llvm.InlineAsmOp(ity, [x], \"\", \"=v,0\", has_side_effects=side_effects).result\n return _llvm.BitcastOp(v.type, y).result\n\n\ndef _rsrc(ptr):\n return fx.rocdl.get_buffer_rsrc(fx.rocdl.make_buffer_ptr(ptr))\n\n\ndef _i32(v):\n return fx.as_ir_value(fx.Int32(v))\n\n\ndef _load16(rsrc, voff, soff, elem, n, aux=0):\n \"\"\"16 bytes at voff + soff (bytes) as an n x elem vector.\"\"\"\n raw = fx.rocdl.raw_ptr_buffer_load(_vt(4, _ir.IntegerType.get_signless(32)), rsrc, _i32(voff), _i32(soff), aux=aux)\n return fx.Vector(_vector.bitcast(_vt(n, elem), raw), (n,), fx.BFloat16 if n == 8 else fx.Float32)\n\n\ndef _store16(rsrc, voff, soff, value):\n raw = _vector.bitcast(_vt(4, _ir.IntegerType.get_signless(32)), fx.as_ir_value(value))\n _rocdl.raw_ptr_buffer_store(raw, rsrc, _i32(voff), _i32(soff),\n aux=_ir.IntegerAttr.get(_ir.IntegerType.get_signless(32), 2))\n\n\ndef _block_sum(lds, v, lane, wave):\n \"\"\"v summed over the workgroup's 14 waves in a fixed order, in every lane (the second LDS exchange).\"\"\"\n s = _wave_allsum(v)\n _scf_if(lane == 0, lambda: _lds_st(lds, s, LDS1 + wave))\n fx.gpu.barrier()\n # Lane j of each 16-lane row reads wave j's sum (0 past the 14 waves); the row's DPP sum is the total.\n j = lane & 15\n tot = (j < NW).select(_lds_ld(lds, LDS1 + j), _f32(0.0))\n for ctrl in _DPP_ALL:\n tot = tot + _dpp(tot, ctrl)\n return tot\n\n\ndef _token(cfg, t, lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps):\n \"\"\"One token's workgroup: the whole computation for token ``t``.\"\"\"\n nbank, nb, write, add, norm = cfg\n nr = nb + 1\n h2 = (nr + 1) // 2\n r_prefix = _rsrc(prefix)\n r_bank = _rsrc(bank)\n r_out = _rsrc(out)\n\n tid = fx.thread_idx.x\n lane = tid % WAVE\n wave = tid // WAVE\n hb = tid * (VEC * 2) # this thread's byte offset in a bf16 row\n tb = t * (D * 2) # the token's row, bytes (wave-uniform)\n bf16 = _ir.BF16Type.get()\n\n # The token's first loads: the prefix, the addend and the score weights; then the bank rows, after the helper's\n # requests for them went out.\n xa = _load16(r_prefix, hb, tb, bf16, 8, 2)\n xb = _load16(_rsrc(addend), hb, tb, bf16, 8, 2) if add else None\n if nb:\n wa = _load16(_rsrc(snw), hb, 0, bf16, 8)\n wb = _load16(_rsrc(spw), hb, 0, bf16, 8)\n if HELPERS and HELP_SLEEP:\n _llvm.InlineAsmOp(None, [], f\"s_sleep {HELP_SLEEP}\", \"~{memory}\", has_side_effects=True)\n fx.rocdl.sched_barrier(0)\n braw = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8, 2) for r in range(nb)]\n nwr = _load16(_rsrc(nw), hb, 0, bf16, 8) if norm else None\n # The output pointer and the two scalars do not fit the 14 preloaded SGPRs (the token count and six pointers do);\n # using the scalars here makes their s_load wait while the data loads are in flight, instead of after the first\n # barrier where LLVM would sink it.\n _llvm.InlineAsmOp(None, [fx.as_ir_value(score_eps), fx.as_ir_value(norm_eps)], \"; $0 $1\", \"s,s\",\n has_side_effects=True)\n\n # p as four bf16 pairs: prefix + addend rounded to bf16 (through an empty asm, or LLVM folds widen(round(x))\n # into a per-element round and shift instead of reusing the pair), stored back to the prefix; or the prefix.\n if add:\n pb2 = [_opaque(_to_bf_pair(_pk_add(_f_pair(_bf_pair(xa, k)), _f_pair(_bf_pair(xb, k)))), 32)\n for k in range(4)]\n _store16(r_prefix, hb, tb, _concat8(pb2))\n else:\n pb2 = [_bf_pair(xa, k) for k in range(4)]\n if write:\n _store16(r_bank, hb, (t * nbank + nb) * (D * 2), xa if not add else _concat8(pb2))\n pf = [_f_pair(b) for b in pb2]\n nwf = [_f_pair(_bf_pair(nwr, k)) for k in range(4)] if norm else None\n\n if nb == 0:\n # one source: its softmax weight is exactly 1, the mix is p\n if norm:\n inv2 = _splat2(_rsq(fx.math.fma(_block_sum(lds, _sum_sq(pf), lane, wave), _f32(_INV_D), norm_eps)))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(pf[k], inv2), nwf[k])) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n else:\n _store16(r_out, hb, tb, xa if not add else _concat8(pb2))\n return\n\n cwp = [_pk_mul(_f_pair(_bf_pair(wa, k)), _f_pair(_bf_pair(wb, k))) for k in range(4)]\n rows = [[_f_pair(_bf_pair(braw[r], k)) for k in range(4)] for r in range(nb)] + [pf]\n\n dots = []\n sss = []\n for r in range(nr):\n x = rows[r]\n d = _pk_mul(x[0], cwp[0])\n for k in range(1, 4):\n d = _pk_fma(x[k], cwp[k], d)\n dots.append(_hsum(d))\n sss.append(_sum_sq(x))\n\n # Wave reduce-scatter: bit 5 splits dots / sums of squares, bit 4 splits each into h2 + (nr - h2) (+ pad).\n vals = _scatter(dots + sss, 5)\n vals = _scatter(vals, 4)\n for ctrl in _DPP_ALL:\n vals = [v + _dpp(v, ctrl) for v in vals]\n q = lane >> 4\n\n def _partials_to_lds():\n for k in range(h2):\n _lds_st(lds, vals[k], (q * h2 + k) * WPAD + wave)\n\n _scf_if((lane & 15) == 0, _partials_to_lds)\n fx.gpu.barrier()\n\n # Every wave sums the 14 waves' partials in the same fixed order: lane (j, q) adds waves 4q..4q+3 of row j,\n # then the four lane groups are summed across lane bits 4 and 5. Lanes j < nr hold row j's totals.\n j = lane & 15\n last = q == 3 # its waves 14 and 15 do not exist\n\n def _four_waves(slot):\n v = _lds_ld4(lds, slot * WPAD + q * 4)\n e = [_f32(_vector.extract(v, [], [i])) for i in range(4)]\n e[2] = last.select(_f32(0.0), e[2])\n e[3] = last.select(_f32(0.0), e[3])\n return (e[0] + e[1]) + (e[2] + e[3])\n\n # Swap-add across bit 4 reduce-scatters (dots to lanes with bit 4 clear, sums of squares to the others), a\n # swap-add across bit 5 completes both, and a last swap hands every lane its row's pair.\n a, b = _permute_pair(_four_waves(j), _four_waves(j + 2 * h2), 4)\n tot = a + b\n a, b = _permute_pair(tot, tot, 5)\n tot = a + b\n dsum, ssum = _permute_pair(tot, tot, 4)\n valid = lane < nr\n score = dsum * _rsq(fx.math.fma(ssum, _f32(_INV_D), score_eps))\n sc = valid.select(score, _f32(-3.0e38))\n mx = sc\n for ctrl in _DPP_ALL:\n mx = fx.Float32(_arith.MaximumFOp(fx.as_ir_value(mx), fx.as_ir_value(_dpp(mx, ctrl))).result)\n ex = valid.select(_exp2((sc - mx) * _f32(_LOG2E)), _f32(0.0))\n # The mix uses the unnormalised exponentials e_r, their sum Z taken in row order.\n wts = [_readlane(ex, r) for r in range(nr)]\n z = wts[0]\n for w in wts[1:]:\n z = z + w\n\n wv = [_splat2(w) for w in wts]\n mix = []\n for k in range(4):\n m = _pk_mul(rows[0][k], wv[0])\n for r in range(1, nr):\n m = _pk_fma(rows[r][k], wv[r], m)\n mix.append(m)\n if norm:\n # rsqrt(sum (mix / Z)^2 / D + eps) / Z = rsqrt(sum mix^2 / D + eps Z^2)\n tsq = _block_sum(lds, _sum_sq(mix), lane, wave)\n scale = _splat2(_rsq(fx.math.fma(tsq, _f32(_INV_D), norm_eps * (z * z))))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(mix[k], scale), nwf[k])) for k in range(4)]\n else:\n scale = _splat2(_f32(1.0) / z)\n outs = [_to_bf_pair(_pk_mul(mix[k], scale)) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n\n\ndef _prefetch(cfg, t, bank, h):\n \"\"\"A helper workgroup on the token's XCD: load its bank rows, as the token's workgroup will, so that the\n workgroup's later requests hit the shared L2 instead of memory. The loads allocate in L2 (default policy, not\n nt); an empty asm consumes them.\"\"\"\n nbank, nb = cfg[0], cfg[1]\n r_bank = _rsrc(bank)\n hb = fx.thread_idx.x * (VEC * 2)\n bf16 = _ir.BF16Type.get()\n rows = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8) for r in range(nb) if r % HELPERS == h]\n if not rows:\n return\n acc = _f_pair(_bf_pair(rows[0], 0))\n for v in rows[1:]:\n acc = _pk_add(acc, _f_pair(_bf_pair(v, 0)))\n _llvm.InlineAsmOp(None, [fx.as_ir_value(_hsum(acc))], \"; $0\", \"v\", has_side_effects=True)\n\n\ndef _make(cfg, grid):\n nb = cfg[1]\n alloc = SmemAllocator(None, arch=\"gfx950\", global_sym_name=\"kimi_k3_attn_res_lds\")\n alloc.ptr = (LDS1 + LDS2) * 4\n\n @flyc.kernel\n def k_kimi_k3_attn_res(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n ):\n lds_ty = _ir.MemRefType.get([LDS1 + LDS2], _ir.F32Type.get(), memory_space=_lds_space())\n lds = _memref.view(lds_ty, alloc.get_base(),\n _arith.ConstantOp(_ir.IndexType.get(), 0).result, sizes=[])\n args = (lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps)\n b = fx.Int32(fx.block_idx.x)\n if fx.const_expr(nb > 0 and HELPERS > 0):\n # groups of 8 tokens' workgroups, then their helpers, 8 at a time; past n_tokens all idle\n t = (b // GROUP) * XCDS + b % XCDS\n role = (b // XCDS) % (1 + HELPERS)\n live = t < n_tokens\n _scf_if(live & (role == 0), lambda: _token(cfg, t, *args))\n for h in fx.range_constexpr(HELPERS):\n _scf_if(live & (role == h + 1), lambda h=h: _prefetch(cfg, t, bank, h))\n else:\n _scf_if(b < n_tokens, lambda: _token(cfg, b, *args))\n\n @flyc.jit\n def launch(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n stream: fx.Stream = fx.Stream(None),\n ):\n alloc.finalized = False\n ctx = CompilationContext.get_current()\n with _ir.InsertionPoint(ctx.gpu_module_body):\n alloc.finalize()\n k_kimi_k3_attn_res(n_tokens, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps).launch(\n grid=(grid, 1, 1), block=(NTHR, 1, 1), stream=stream)\n\n opts = {\"amdgpu-kernarg-preload-count\": 8, \"vectorize-slp\": False}\n return flyc.compile[{\"llvm_options\": opts}](launch)\n\n\[email protected]\ndef _launch_for(n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm, grid):\n return _make((n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm), grid)\n\n\ndef _grid(n_tokens, n_valid_rows):\n if n_valid_rows == 0 or HELPERS == 0:\n return n_tokens\n return GROUP * -(-n_tokens // XCDS)\n\n\ndef run(*, prefix, bank, score_norm_weight, score_proj_weight, n_valid_rows, write_bank, addend, norm_weight,\n score_eps, norm_eps, out_dtype, out):\n \"\"\"out, and p into the prefix with an addend and into the bank with write_bank, written in place.\"\"\"\n n_tokens, hidden_size = prefix.shape\n n_bank_rows = bank.shape[1]\n assert hidden_size == D and n_tokens * n_bank_rows * D * 2 < 2**31\n fn = _launch_for(n_bank_rows, n_valid_rows, write_bank, addend is not None, norm_weight is not None,\n _grid(n_tokens, n_valid_rows))\n tensors = (prefix, prefix if addend is None else addend, bank, score_norm_weight, score_proj_weight,\n prefix if norm_weight is None else norm_weight, out)\n ptrs = [flyc.from_c_void_p(fx.Int32, x.data_ptr()) for x in tensors]\n fn(n_tokens, *ptrs, score_eps, norm_eps, fx.Stream(torch._C._cuda_getCurrentRawStream(prefix.device.index)))\n"
"sources": [
{
"path": "kernel.py",
"content": "\"\"\"Kimi-K3's attention residual as vLLM calls it, for hidden size 7168, in FlyDSL for gfx950.\n\nOne workgroup per token, 896 threads (14 waves), each thread owning 8 contiguous hidden columns, handled as four column\npairs in packed fp32. The buffers arrive as preloaded pointers. p is the prefix, or bf16(prefix + addend) stored back\nto the prefix in place; with write_bank p also goes to bank row n_valid_rows. The rows scored are the n_valid_rows\nbank rows, then p. Each score weight pair is the product of the two bf16 weights, exact in fp32. Each row's two\nper-thread partials (dot with the score weight, sum of squares) are reduce-scattered inside each wave (permlane\nswaps, then DPP), exchanged through LDS and summed over the waves in a fixed order by every wave alike. Lanes below\nthe row count hold one row's score each; the softmax runs across those lanes and its unnormalised weights go to\nscalar registers for the mix, their sum Z in a fixed order. With a norm weight, the mix's mean square (second LDS\nexchange) absorbs Z; without one the mix is divided by Z. With no bank row the mix is p itself. Every reduction runs\nin a fixed order, so the output is bitwise deterministic.\n\nEach token's workgroup has a helper workgroup on the same XCD (8 workgroup ids later) that only loads the token's\nbank rows, so that the token's own requests for them, issued ~0.3 us after its first loads, hit the shared L2. The\nhelper waits for nobody and nobody waits for it. The token count is a kernel argument: one build serves every count\nwhose grid (16 workgroups per 8 tokens) it was built for.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\n\nimport torch\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nfrom flydsl._mlir import ir as _ir\nfrom flydsl._mlir.dialects import arith as _arith\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl._mlir.dialects import math as _math\nfrom flydsl._mlir.dialects import memref as _memref\nfrom flydsl._mlir.dialects import rocdl as _rocdl\nfrom flydsl._mlir.dialects import scf as _scf\nfrom flydsl._mlir.dialects import vector as _vector\nfrom flydsl.compiler.kernel_function import CompilationContext\nfrom flydsl.expr.gpu import lds_space as _lds_space\nfrom flydsl.utils.smem_allocator import SmemAllocator\n\nD = 7168\nWAVE = 64\nVEC = 8 # hidden columns per thread\nNTHR = D // VEC # 896\nNW = NTHR // WAVE # 14\nWPAD = 16 # waves per LDS slot row (14 used)\nLDS1 = 32 * WPAD # slot s (dot of row s, or sum of squares of row s - 2 * H2), wave w at s * WPAD + w\nLDS2 = WPAD # the sums of squares of the second exchange, one per wave\nXCDS = 8 # workgroups b and b + 8 run on the same XCD\nHELPERS = 1 # helper workgroups per token\nGROUP = (1 + HELPERS) * XCDS # 8 tokens' workgroups, then their helpers, 8 at a time\nHELP_SLEEP = 12 # s_sleep units (64 cycles) before the token's bank-row loads\n_LOG2E = 1.4426950408889634\n_INV_D = 1.0 / D\n\n_DPP_XOR1 = 0xB1 # quad_perm [1,0,3,2]\n_DPP_XOR2 = 0x4E # quad_perm [2,3,0,1]\n_DPP_HMIRROR = 0x141 # row_half_mirror (xor 4 once quads are uniform)\n_DPP_ROR8 = 0x128 # row_ror:8 (xor 8 inside a 16-lane row)\n_DPP_ALL = (_DPP_XOR1, _DPP_XOR2, _DPP_HMIRROR, _DPP_ROR8)\n\n\ndef _f32(v):\n return fx.Float32(v)\n\n\ndef _rsq(x):\n return fx.Float32(fx.rocdl.rsq(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _exp2(x):\n return fx.Float32(fx.rocdl.exp2(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _dpp(v, ctrl):\n return fx.Float32(fx.rocdl.update_dpp(\n _ir.F32Type.get(), fx.as_ir_value(v), fx.as_ir_value(v), ctrl, 0xF, 0xF, True))\n\n\ndef _permute_pair(a, b, bit):\n \"\"\"(a_low | b_low, a_high | b_high) across the 32-lane (bit 5) or 16-lane (bit 4) split.\"\"\"\n i32 = _ir.IntegerType.get_signless(32)\n ai = _arith.BitcastOp(i32, fx.as_ir_value(a)).result\n bi = _arith.BitcastOp(i32, fx.as_ir_value(b)).result\n op = _rocdl.permlane16_swap if bit == 4 else _rocdl.permlane32_swap\n pair = op(_ir.Type.parse(\"!llvm.struct<(i32, i32)>\"), ai, bi, False, True)\n vals = [_llvm.ExtractValueOp(i32, pair, [i]).result for i in range(2)]\n return [fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), v).result) for v in vals]\n\n\ndef _scatter(vals, bit):\n \"\"\"Reduce-scatter step: lanes with ``bit`` clear end with the low half summed, lanes with it set the high half.\"\"\"\n h = (len(vals) + 1) // 2\n lo = vals[:h]\n hi = vals[h:] + [None] * (2 * h - len(vals))\n out = []\n for k in range(h):\n hk = _f32(0.0) if hi[k] is None else hi[k]\n a, b = _permute_pair(lo[k], hk, bit)\n out.append(a + b)\n return out\n\n\ndef _wave_allsum(v):\n for ctrl in _DPP_ALL:\n v = v + _dpp(v, ctrl)\n for bit in (4, 5):\n a, b = _permute_pair(v, v, bit)\n v = a + b\n return v\n\n\ndef _readlane(v, j):\n i32 = _ir.IntegerType.get_signless(32)\n bits = _arith.BitcastOp(i32, fx.as_ir_value(v)).result\n r = fx.rocdl.readlane(i32, bits, j)\n return fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), fx.as_ir_value(r)).result)\n\n\ndef _as_index(v):\n v = fx.as_ir_value(v)\n if isinstance(v.type, _ir.IntegerType):\n v = _arith.IndexCastOp(_ir.IndexType.get(), v).result\n return v\n\n\ndef _scf_if(cond, then_fn):\n \"\"\"scf.if without results on a condition: ``then_fn`` emits the guarded ops.\"\"\"\n op = _scf.IfOp(fx.as_ir_value(cond), [], has_else=False)\n with _ir.InsertionPoint(op.regions[0].blocks[0]):\n then_fn()\n _scf.YieldOp([])\n\n\ndef _lds_st(lds, v, idx):\n _memref.store(fx.as_ir_value(v), lds, [_as_index(idx)])\n\n\ndef _lds_ld(lds, idx):\n return fx.Float32(_memref.load(lds, [_as_index(idx)]))\n\n\ndef _lds_ld4(lds, idx):\n \"\"\"Four consecutive LDS floats from a 16 B aligned index.\"\"\"\n return _vector.load(_vt(4, _ir.F32Type.get()), lds, [_as_index(idx)])\n\n\ndef _vt(n, elem):\n return _ir.VectorType.get([n], elem)\n\n\ndef _bf_pair(vec, k):\n \"\"\"Columns 2k, 2k+1 of an 8 x bf16 vector, as a 2 x bf16 vector.\"\"\"\n return _vector.extract_strided_slice(_vt(2, _ir.BF16Type.get()), fx.as_ir_value(vec), [2 * k], [2], [1])\n\n\ndef _f_pair(bf2):\n return _arith.ExtFOp(_vt(2, _ir.F32Type.get()), bf2).result\n\n\ndef _to_bf_pair(f2):\n return _arith.TruncFOp(_vt(2, _ir.BF16Type.get()), f2).result\n\n\ndef _pk_add(a, b):\n return _arith.AddFOp(a, b).result\n\n\ndef _pk_mul(a, b):\n return _arith.MulFOp(a, b).result\n\n\ndef _pk_fma(a, b, c):\n return _math.fma(a, b, c)\n\n\ndef _hsum(v2):\n return _f32(_vector.extract(v2, [], [0])) + _f32(_vector.extract(v2, [], [1]))\n\n\ndef _splat2(x):\n return _vector.broadcast(_vt(2, _ir.F32Type.get()), fx.as_ir_value(x))\n\n\ndef _sum_sq(x):\n \"\"\"A row's sum of squares over the thread's 8 columns (v_pk_fma_f32 on the widened pairs).\"\"\"\n s2 = _pk_mul(x[0], x[0])\n for k in range(1, 4):\n s2 = _pk_fma(x[k], x[k], s2)\n return _hsum(s2)\n\n\ndef _concat8(pairs):\n \"\"\"Four 2-element vectors into one 8-element vector.\"\"\"\n a = _vector.shuffle(pairs[0], pairs[1], [0, 1, 2, 3])\n b = _vector.shuffle(pairs[2], pairs[3], [0, 1, 2, 3])\n return _vector.shuffle(a, b, list(range(8)))\n\n\ndef _opaque(v, bits, side_effects=False):\n \"\"\"v unchanged through an empty asm tied to its input (no instruction): LLVM cannot fold across it, and with\n side_effects it stays before the next barrier.\"\"\"\n ity = _ir.IntegerType.get_signless(bits)\n x = _llvm.BitcastOp(ity, v).result\n y = _llvm.InlineAsmOp(ity, [x], \"\", \"=v,0\", has_side_effects=side_effects).result\n return _llvm.BitcastOp(v.type, y).result\n\n\ndef _rsrc(ptr):\n return fx.rocdl.get_buffer_rsrc(fx.rocdl.make_buffer_ptr(ptr))\n\n\ndef _i32(v):\n return fx.as_ir_value(fx.Int32(v))\n\n\ndef _load16(rsrc, voff, soff, elem, n, aux=0):\n \"\"\"16 bytes at voff + soff (bytes) as an n x elem vector.\"\"\"\n raw = fx.rocdl.raw_ptr_buffer_load(_vt(4, _ir.IntegerType.get_signless(32)), rsrc, _i32(voff), _i32(soff), aux=aux)\n return fx.Vector(_vector.bitcast(_vt(n, elem), raw), (n,), fx.BFloat16 if n == 8 else fx.Float32)\n\n\ndef _store16(rsrc, voff, soff, value):\n raw = _vector.bitcast(_vt(4, _ir.IntegerType.get_signless(32)), fx.as_ir_value(value))\n _rocdl.raw_ptr_buffer_store(raw, rsrc, _i32(voff), _i32(soff),\n aux=_ir.IntegerAttr.get(_ir.IntegerType.get_signless(32), 2))\n\n\ndef _block_sum(lds, v, lane, wave):\n \"\"\"v summed over the workgroup's 14 waves in a fixed order, in every lane (the second LDS exchange).\"\"\"\n s = _wave_allsum(v)\n _scf_if(lane == 0, lambda: _lds_st(lds, s, LDS1 + wave))\n fx.gpu.barrier()\n # Lane j of each 16-lane row reads wave j's sum (0 past the 14 waves); the row's DPP sum is the total.\n j = lane & 15\n tot = (j < NW).select(_lds_ld(lds, LDS1 + j), _f32(0.0))\n for ctrl in _DPP_ALL:\n tot = tot + _dpp(tot, ctrl)\n return tot\n\n\ndef _token(cfg, t, lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps):\n \"\"\"One token's workgroup: the whole computation for token ``t``.\"\"\"\n nbank, nb, write, add, norm = cfg\n nr = nb + 1\n h2 = (nr + 1) // 2\n r_prefix = _rsrc(prefix)\n r_bank = _rsrc(bank)\n r_out = _rsrc(out)\n\n tid = fx.thread_idx.x\n lane = tid % WAVE\n wave = tid // WAVE\n hb = tid * (VEC * 2) # this thread's byte offset in a bf16 row\n tb = t * (D * 2) # the token's row, bytes (wave-uniform)\n bf16 = _ir.BF16Type.get()\n\n # The token's first loads: the prefix, the addend and the score weights; then the bank rows, after the helper's\n # requests for them went out.\n xa = _load16(r_prefix, hb, tb, bf16, 8, 2)\n xb = _load16(_rsrc(addend), hb, tb, bf16, 8, 2) if add else None\n if nb:\n wa = _load16(_rsrc(snw), hb, 0, bf16, 8)\n wb = _load16(_rsrc(spw), hb, 0, bf16, 8)\n if HELPERS and HELP_SLEEP:\n _llvm.InlineAsmOp(None, [], f\"s_sleep {HELP_SLEEP}\", \"~{memory}\", has_side_effects=True)\n fx.rocdl.sched_barrier(0)\n braw = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8, 2) for r in range(nb)]\n nwr = _load16(_rsrc(nw), hb, 0, bf16, 8) if norm else None\n # The output pointer and the two scalars do not fit the 14 preloaded SGPRs (the token count and six pointers do);\n # using the scalars here makes their s_load wait while the data loads are in flight, instead of after the first\n # barrier where LLVM would sink it.\n _llvm.InlineAsmOp(None, [fx.as_ir_value(score_eps), fx.as_ir_value(norm_eps)], \"; $0 $1\", \"s,s\",\n has_side_effects=True)\n\n # p as four bf16 pairs: prefix + addend rounded to bf16 (through an empty asm, or LLVM folds widen(round(x))\n # into a per-element round and shift instead of reusing the pair), stored back to the prefix; or the prefix.\n if add:\n pb2 = [_opaque(_to_bf_pair(_pk_add(_f_pair(_bf_pair(xa, k)), _f_pair(_bf_pair(xb, k)))), 32)\n for k in range(4)]\n _store16(r_prefix, hb, tb, _concat8(pb2))\n else:\n pb2 = [_bf_pair(xa, k) for k in range(4)]\n if write:\n _store16(r_bank, hb, (t * nbank + nb) * (D * 2), xa if not add else _concat8(pb2))\n pf = [_f_pair(b) for b in pb2]\n nwf = [_f_pair(_bf_pair(nwr, k)) for k in range(4)] if norm else None\n\n if nb == 0:\n # one source: its softmax weight is exactly 1, the mix is p\n if norm:\n inv2 = _splat2(_rsq(fx.math.fma(_block_sum(lds, _sum_sq(pf), lane, wave), _f32(_INV_D), norm_eps)))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(pf[k], inv2), nwf[k])) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n else:\n _store16(r_out, hb, tb, xa if not add else _concat8(pb2))\n return\n\n cwp = [_pk_mul(_f_pair(_bf_pair(wa, k)), _f_pair(_bf_pair(wb, k))) for k in range(4)]\n rows = [[_f_pair(_bf_pair(braw[r], k)) for k in range(4)] for r in range(nb)] + [pf]\n\n dots = []\n sss = []\n for r in range(nr):\n x = rows[r]\n d = _pk_mul(x[0], cwp[0])\n for k in range(1, 4):\n d = _pk_fma(x[k], cwp[k], d)\n dots.append(_hsum(d))\n sss.append(_sum_sq(x))\n\n # Wave reduce-scatter: bit 5 splits dots / sums of squares, bit 4 splits each into h2 + (nr - h2) (+ pad).\n vals = _scatter(dots + sss, 5)\n vals = _scatter(vals, 4)\n for ctrl in _DPP_ALL:\n vals = [v + _dpp(v, ctrl) for v in vals]\n q = lane >> 4\n\n def _partials_to_lds():\n for k in range(h2):\n _lds_st(lds, vals[k], (q * h2 + k) * WPAD + wave)\n\n _scf_if((lane & 15) == 0, _partials_to_lds)\n fx.gpu.barrier()\n\n # Every wave sums the 14 waves' partials in the same fixed order: lane (j, q) adds waves 4q..4q+3 of row j,\n # then the four lane groups are summed across lane bits 4 and 5. Lanes j < nr hold row j's totals.\n j = lane & 15\n last = q == 3 # its waves 14 and 15 do not exist\n\n def _four_waves(slot):\n v = _lds_ld4(lds, slot * WPAD + q * 4)\n e = [_f32(_vector.extract(v, [], [i])) for i in range(4)]\n e[2] = last.select(_f32(0.0), e[2])\n e[3] = last.select(_f32(0.0), e[3])\n return (e[0] + e[1]) + (e[2] + e[3])\n\n # Swap-add across bit 4 reduce-scatters (dots to lanes with bit 4 clear, sums of squares to the others), a\n # swap-add across bit 5 completes both, and a last swap hands every lane its row's pair.\n a, b = _permute_pair(_four_waves(j), _four_waves(j + 2 * h2), 4)\n tot = a + b\n a, b = _permute_pair(tot, tot, 5)\n tot = a + b\n dsum, ssum = _permute_pair(tot, tot, 4)\n valid = lane < nr\n score = dsum * _rsq(fx.math.fma(ssum, _f32(_INV_D), score_eps))\n sc = valid.select(score, _f32(-3.0e38))\n mx = sc\n for ctrl in _DPP_ALL:\n mx = fx.Float32(_arith.MaximumFOp(fx.as_ir_value(mx), fx.as_ir_value(_dpp(mx, ctrl))).result)\n ex = valid.select(_exp2((sc - mx) * _f32(_LOG2E)), _f32(0.0))\n # The mix uses the unnormalised exponentials e_r, their sum Z taken in row order.\n wts = [_readlane(ex, r) for r in range(nr)]\n z = wts[0]\n for w in wts[1:]:\n z = z + w\n\n wv = [_splat2(w) for w in wts]\n mix = []\n for k in range(4):\n m = _pk_mul(rows[0][k], wv[0])\n for r in range(1, nr):\n m = _pk_fma(rows[r][k], wv[r], m)\n mix.append(m)\n if norm:\n # rsqrt(sum (mix / Z)^2 / D + eps) / Z = rsqrt(sum mix^2 / D + eps Z^2)\n tsq = _block_sum(lds, _sum_sq(mix), lane, wave)\n scale = _splat2(_rsq(fx.math.fma(tsq, _f32(_INV_D), norm_eps * (z * z))))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(mix[k], scale), nwf[k])) for k in range(4)]\n else:\n scale = _splat2(_f32(1.0) / z)\n outs = [_to_bf_pair(_pk_mul(mix[k], scale)) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n\n\ndef _prefetch(cfg, t, bank, h):\n \"\"\"A helper workgroup on the token's XCD: load its bank rows, as the token's workgroup will, so that the\n workgroup's later requests hit the shared L2 instead of memory. The loads allocate in L2 (default policy, not\n nt); an empty asm consumes them.\"\"\"\n nbank, nb = cfg[0], cfg[1]\n r_bank = _rsrc(bank)\n hb = fx.thread_idx.x * (VEC * 2)\n bf16 = _ir.BF16Type.get()\n rows = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8) for r in range(nb) if r % HELPERS == h]\n if not rows:\n return\n acc = _f_pair(_bf_pair(rows[0], 0))\n for v in rows[1:]:\n acc = _pk_add(acc, _f_pair(_bf_pair(v, 0)))\n _llvm.InlineAsmOp(None, [fx.as_ir_value(_hsum(acc))], \"; $0\", \"v\", has_side_effects=True)\n\n\ndef _make(cfg, grid):\n nb = cfg[1]\n alloc = SmemAllocator(None, arch=\"gfx950\", global_sym_name=\"kimi_k3_attn_res_lds\")\n alloc.ptr = (LDS1 + LDS2) * 4\n\n @flyc.kernel\n def k_kimi_k3_attn_res(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n ):\n lds_ty = _ir.MemRefType.get([LDS1 + LDS2], _ir.F32Type.get(), memory_space=_lds_space())\n lds = _memref.view(lds_ty, alloc.get_base(),\n _arith.ConstantOp(_ir.IndexType.get(), 0).result, sizes=[])\n args = (lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps)\n b = fx.Int32(fx.block_idx.x)\n if fx.const_expr(nb > 0 and HELPERS > 0):\n # groups of 8 tokens' workgroups, then their helpers, 8 at a time; past n_tokens all idle\n t = (b // GROUP) * XCDS + b % XCDS\n role = (b // XCDS) % (1 + HELPERS)\n live = t < n_tokens\n _scf_if(live & (role == 0), lambda: _token(cfg, t, *args))\n for h in fx.range_constexpr(HELPERS):\n _scf_if(live & (role == h + 1), lambda h=h: _prefetch(cfg, t, bank, h))\n else:\n _scf_if(b < n_tokens, lambda: _token(cfg, b, *args))\n\n @flyc.jit\n def launch(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n stream: fx.Stream = fx.Stream(None),\n ):\n alloc.finalized = False\n ctx = CompilationContext.get_current()\n with _ir.InsertionPoint(ctx.gpu_module_body):\n alloc.finalize()\n k_kimi_k3_attn_res(n_tokens, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps).launch(\n grid=(grid, 1, 1), block=(NTHR, 1, 1), stream=stream)\n\n opts = {\"amdgpu-kernarg-preload-count\": 8, \"vectorize-slp\": False}\n return flyc.compile[{\"llvm_options\": opts}](launch)\n\n\[email protected]\ndef _launch_for(n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm, grid):\n return _make((n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm), grid)\n\n\ndef _grid(n_tokens, n_valid_rows):\n if n_valid_rows == 0 or HELPERS == 0:\n return n_tokens\n return GROUP * -(-n_tokens // XCDS)\n\n\ndef run(*, prefix, bank, score_norm_weight, score_proj_weight, n_valid_rows, write_bank, addend, norm_weight,\n score_eps, norm_eps, out_dtype, out):\n \"\"\"out, and p into the prefix with an addend and into the bank with write_bank, written in place.\"\"\"\n n_tokens, hidden_size = prefix.shape\n n_bank_rows = bank.shape[1]\n assert hidden_size == D and n_tokens * n_bank_rows * D * 2 < 2**31\n fn = _launch_for(n_bank_rows, n_valid_rows, write_bank, addend is not None, norm_weight is not None,\n _grid(n_tokens, n_valid_rows))\n tensors = (prefix, prefix if addend is None else addend, bank, score_norm_weight, score_proj_weight,\n prefix if norm_weight is None else norm_weight, out)\n ptrs = [flyc.from_c_void_p(fx.Int32, x.data_ptr()) for x in tensors]\n fn(n_tokens, *ptrs, score_eps, norm_eps, fx.Stream(torch._C._cuda_getCurrentRawStream(prefix.device.index)))\n"
"sources": [
{
"path": "kernel.py",
"content": "\"\"\"Kimi-K3's attention residual as vLLM calls it, for hidden size 7168, in FlyDSL for gfx950.\n\nOne workgroup per token, 896 threads (14 waves), each thread owning 8 contiguous hidden columns, handled as four column\npairs in packed fp32. The buffers arrive as preloaded pointers. p is the prefix, or bf16(prefix + addend) stored back\nto the prefix in place; with write_bank p also goes to bank row n_valid_rows. The rows scored are the n_valid_rows\nbank rows, then p. Each score weight pair is the product of the two bf16 weights, exact in fp32. Each row's two\nper-thread partials (dot with the score weight, sum of squares) are reduce-scattered inside each wave (permlane\nswaps, then DPP), exchanged through LDS and summed over the waves in a fixed order by every wave alike. Lanes below\nthe row count hold one row's score each; the softmax runs across those lanes and its unnormalised weights go to\nscalar registers for the mix, their sum Z in a fixed order. With a norm weight, the mix's mean square (second LDS\nexchange) absorbs Z; without one the mix is divided by Z. With no bank row the mix is p itself. Every reduction runs\nin a fixed order, so the output is bitwise deterministic.\n\nEach token's workgroup has a helper workgroup on the same XCD (8 workgroup ids later) that only loads the token's\nbank rows, so that the token's own requests for them, issued ~0.3 us after its first loads, hit the shared L2. The\nhelper waits for nobody and nobody waits for it. The token count is a kernel argument: one build serves every count\nwhose grid (16 workgroups per 8 tokens) it was built for.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\n\nimport torch\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nfrom flydsl._mlir import ir as _ir\nfrom flydsl._mlir.dialects import arith as _arith\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl._mlir.dialects import math as _math\nfrom flydsl._mlir.dialects import memref as _memref\nfrom flydsl._mlir.dialects import rocdl as _rocdl\nfrom flydsl._mlir.dialects import scf as _scf\nfrom flydsl._mlir.dialects import vector as _vector\nfrom flydsl.compiler.kernel_function import CompilationContext\nfrom flydsl.expr.gpu import lds_space as _lds_space\nfrom flydsl.utils.smem_allocator import SmemAllocator\n\nD = 7168\nWAVE = 64\nVEC = 8 # hidden columns per thread\nNTHR = D // VEC # 896\nNW = NTHR // WAVE # 14\nWPAD = 16 # waves per LDS slot row (14 used)\nLDS1 = 32 * WPAD # slot s (dot of row s, or sum of squares of row s - 2 * H2), wave w at s * WPAD + w\nLDS2 = WPAD # the sums of squares of the second exchange, one per wave\nXCDS = 8 # workgroups b and b + 8 run on the same XCD\nHELPERS = 1 # helper workgroups per token\nGROUP = (1 + HELPERS) * XCDS # 8 tokens' workgroups, then their helpers, 8 at a time\nHELP_SLEEP = 12 # s_sleep units (64 cycles) before the token's bank-row loads\n_LOG2E = 1.4426950408889634\n_INV_D = 1.0 / D\n\n_DPP_XOR1 = 0xB1 # quad_perm [1,0,3,2]\n_DPP_XOR2 = 0x4E # quad_perm [2,3,0,1]\n_DPP_HMIRROR = 0x141 # row_half_mirror (xor 4 once quads are uniform)\n_DPP_ROR8 = 0x128 # row_ror:8 (xor 8 inside a 16-lane row)\n_DPP_ALL = (_DPP_XOR1, _DPP_XOR2, _DPP_HMIRROR, _DPP_ROR8)\n\n\ndef _f32(v):\n return fx.Float32(v)\n\n\ndef _rsq(x):\n return fx.Float32(fx.rocdl.rsq(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _exp2(x):\n return fx.Float32(fx.rocdl.exp2(_ir.F32Type.get(), fx.as_ir_value(x)))\n\n\ndef _dpp(v, ctrl):\n return fx.Float32(fx.rocdl.update_dpp(\n _ir.F32Type.get(), fx.as_ir_value(v), fx.as_ir_value(v), ctrl, 0xF, 0xF, True))\n\n\ndef _permute_pair(a, b, bit):\n \"\"\"(a_low | b_low, a_high | b_high) across the 32-lane (bit 5) or 16-lane (bit 4) split.\"\"\"\n i32 = _ir.IntegerType.get_signless(32)\n ai = _arith.BitcastOp(i32, fx.as_ir_value(a)).result\n bi = _arith.BitcastOp(i32, fx.as_ir_value(b)).result\n op = _rocdl.permlane16_swap if bit == 4 else _rocdl.permlane32_swap\n pair = op(_ir.Type.parse(\"!llvm.struct<(i32, i32)>\"), ai, bi, False, True)\n vals = [_llvm.ExtractValueOp(i32, pair, [i]).result for i in range(2)]\n return [fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), v).result) for v in vals]\n\n\ndef _scatter(vals, bit):\n \"\"\"Reduce-scatter step: lanes with ``bit`` clear end with the low half summed, lanes with it set the high half.\"\"\"\n h = (len(vals) + 1) // 2\n lo = vals[:h]\n hi = vals[h:] + [None] * (2 * h - len(vals))\n out = []\n for k in range(h):\n hk = _f32(0.0) if hi[k] is None else hi[k]\n a, b = _permute_pair(lo[k], hk, bit)\n out.append(a + b)\n return out\n\n\ndef _wave_allsum(v):\n for ctrl in _DPP_ALL:\n v = v + _dpp(v, ctrl)\n for bit in (4, 5):\n a, b = _permute_pair(v, v, bit)\n v = a + b\n return v\n\n\ndef _readlane(v, j):\n i32 = _ir.IntegerType.get_signless(32)\n bits = _arith.BitcastOp(i32, fx.as_ir_value(v)).result\n r = fx.rocdl.readlane(i32, bits, j)\n return fx.Float32(_arith.BitcastOp(_ir.F32Type.get(), fx.as_ir_value(r)).result)\n\n\ndef _as_index(v):\n v = fx.as_ir_value(v)\n if isinstance(v.type, _ir.IntegerType):\n v = _arith.IndexCastOp(_ir.IndexType.get(), v).result\n return v\n\n\ndef _scf_if(cond, then_fn):\n \"\"\"scf.if without results on a condition: ``then_fn`` emits the guarded ops.\"\"\"\n op = _scf.IfOp(fx.as_ir_value(cond), [], has_else=False)\n with _ir.InsertionPoint(op.regions[0].blocks[0]):\n then_fn()\n _scf.YieldOp([])\n\n\ndef _lds_st(lds, v, idx):\n _memref.store(fx.as_ir_value(v), lds, [_as_index(idx)])\n\n\ndef _lds_ld(lds, idx):\n return fx.Float32(_memref.load(lds, [_as_index(idx)]))\n\n\ndef _lds_ld4(lds, idx):\n \"\"\"Four consecutive LDS floats from a 16 B aligned index.\"\"\"\n return _vector.load(_vt(4, _ir.F32Type.get()), lds, [_as_index(idx)])\n\n\ndef _vt(n, elem):\n return _ir.VectorType.get([n], elem)\n\n\ndef _bf_pair(vec, k):\n \"\"\"Columns 2k, 2k+1 of an 8 x bf16 vector, as a 2 x bf16 vector.\"\"\"\n return _vector.extract_strided_slice(_vt(2, _ir.BF16Type.get()), fx.as_ir_value(vec), [2 * k], [2], [1])\n\n\ndef _f_pair(bf2):\n return _arith.ExtFOp(_vt(2, _ir.F32Type.get()), bf2).result\n\n\ndef _to_bf_pair(f2):\n return _arith.TruncFOp(_vt(2, _ir.BF16Type.get()), f2).result\n\n\ndef _pk_add(a, b):\n return _arith.AddFOp(a, b).result\n\n\ndef _pk_mul(a, b):\n return _arith.MulFOp(a, b).result\n\n\ndef _pk_fma(a, b, c):\n return _math.fma(a, b, c)\n\n\ndef _hsum(v2):\n return _f32(_vector.extract(v2, [], [0])) + _f32(_vector.extract(v2, [], [1]))\n\n\ndef _splat2(x):\n return _vector.broadcast(_vt(2, _ir.F32Type.get()), fx.as_ir_value(x))\n\n\ndef _sum_sq(x):\n \"\"\"A row's sum of squares over the thread's 8 columns (v_pk_fma_f32 on the widened pairs).\"\"\"\n s2 = _pk_mul(x[0], x[0])\n for k in range(1, 4):\n s2 = _pk_fma(x[k], x[k], s2)\n return _hsum(s2)\n\n\ndef _concat8(pairs):\n \"\"\"Four 2-element vectors into one 8-element vector.\"\"\"\n a = _vector.shuffle(pairs[0], pairs[1], [0, 1, 2, 3])\n b = _vector.shuffle(pairs[2], pairs[3], [0, 1, 2, 3])\n return _vector.shuffle(a, b, list(range(8)))\n\n\ndef _opaque(v, bits, side_effects=False):\n \"\"\"v unchanged through an empty asm tied to its input (no instruction): LLVM cannot fold across it, and with\n side_effects it stays before the next barrier.\"\"\"\n ity = _ir.IntegerType.get_signless(bits)\n x = _llvm.BitcastOp(ity, v).result\n y = _llvm.InlineAsmOp(ity, [x], \"\", \"=v,0\", has_side_effects=side_effects).result\n return _llvm.BitcastOp(v.type, y).result\n\n\ndef _rsrc(ptr):\n return fx.rocdl.get_buffer_rsrc(fx.rocdl.make_buffer_ptr(ptr))\n\n\ndef _i32(v):\n return fx.as_ir_value(fx.Int32(v))\n\n\ndef _load16(rsrc, voff, soff, elem, n, aux=0):\n \"\"\"16 bytes at voff + soff (bytes) as an n x elem vector.\"\"\"\n raw = fx.rocdl.raw_ptr_buffer_load(_vt(4, _ir.IntegerType.get_signless(32)), rsrc, _i32(voff), _i32(soff), aux=aux)\n return fx.Vector(_vector.bitcast(_vt(n, elem), raw), (n,), fx.BFloat16 if n == 8 else fx.Float32)\n\n\ndef _store16(rsrc, voff, soff, value):\n raw = _vector.bitcast(_vt(4, _ir.IntegerType.get_signless(32)), fx.as_ir_value(value))\n _rocdl.raw_ptr_buffer_store(raw, rsrc, _i32(voff), _i32(soff),\n aux=_ir.IntegerAttr.get(_ir.IntegerType.get_signless(32), 2))\n\n\ndef _block_sum(lds, v, lane, wave):\n \"\"\"v summed over the workgroup's 14 waves in a fixed order, in every lane (the second LDS exchange).\"\"\"\n s = _wave_allsum(v)\n _scf_if(lane == 0, lambda: _lds_st(lds, s, LDS1 + wave))\n fx.gpu.barrier()\n # Lane j of each 16-lane row reads wave j's sum (0 past the 14 waves); the row's DPP sum is the total.\n j = lane & 15\n tot = (j < NW).select(_lds_ld(lds, LDS1 + j), _f32(0.0))\n for ctrl in _DPP_ALL:\n tot = tot + _dpp(tot, ctrl)\n return tot\n\n\ndef _token(cfg, t, lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps):\n \"\"\"One token's workgroup: the whole computation for token ``t``.\"\"\"\n nbank, nb, write, add, norm = cfg\n nr = nb + 1\n h2 = (nr + 1) // 2\n r_prefix = _rsrc(prefix)\n r_bank = _rsrc(bank)\n r_out = _rsrc(out)\n\n tid = fx.thread_idx.x\n lane = tid % WAVE\n wave = tid // WAVE\n hb = tid * (VEC * 2) # this thread's byte offset in a bf16 row\n tb = t * (D * 2) # the token's row, bytes (wave-uniform)\n bf16 = _ir.BF16Type.get()\n\n # The token's first loads: the prefix, the addend and the score weights; then the bank rows, after the helper's\n # requests for them went out.\n xa = _load16(r_prefix, hb, tb, bf16, 8, 2)\n xb = _load16(_rsrc(addend), hb, tb, bf16, 8, 2) if add else None\n if nb:\n wa = _load16(_rsrc(snw), hb, 0, bf16, 8)\n wb = _load16(_rsrc(spw), hb, 0, bf16, 8)\n if HELPERS and HELP_SLEEP:\n _llvm.InlineAsmOp(None, [], f\"s_sleep {HELP_SLEEP}\", \"~{memory}\", has_side_effects=True)\n fx.rocdl.sched_barrier(0)\n braw = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8, 2) for r in range(nb)]\n nwr = _load16(_rsrc(nw), hb, 0, bf16, 8) if norm else None\n # The output pointer and the two scalars do not fit the 14 preloaded SGPRs (the token count and six pointers do);\n # using the scalars here makes their s_load wait while the data loads are in flight, instead of after the first\n # barrier where LLVM would sink it.\n _llvm.InlineAsmOp(None, [fx.as_ir_value(score_eps), fx.as_ir_value(norm_eps)], \"; $0 $1\", \"s,s\",\n has_side_effects=True)\n\n # p as four bf16 pairs: prefix + addend rounded to bf16 (through an empty asm, or LLVM folds widen(round(x))\n # into a per-element round and shift instead of reusing the pair), stored back to the prefix; or the prefix.\n if add:\n pb2 = [_opaque(_to_bf_pair(_pk_add(_f_pair(_bf_pair(xa, k)), _f_pair(_bf_pair(xb, k)))), 32)\n for k in range(4)]\n _store16(r_prefix, hb, tb, _concat8(pb2))\n else:\n pb2 = [_bf_pair(xa, k) for k in range(4)]\n if write:\n _store16(r_bank, hb, (t * nbank + nb) * (D * 2), xa if not add else _concat8(pb2))\n pf = [_f_pair(b) for b in pb2]\n nwf = [_f_pair(_bf_pair(nwr, k)) for k in range(4)] if norm else None\n\n if nb == 0:\n # one source: its softmax weight is exactly 1, the mix is p\n if norm:\n inv2 = _splat2(_rsq(fx.math.fma(_block_sum(lds, _sum_sq(pf), lane, wave), _f32(_INV_D), norm_eps)))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(pf[k], inv2), nwf[k])) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n else:\n _store16(r_out, hb, tb, xa if not add else _concat8(pb2))\n return\n\n cwp = [_pk_mul(_f_pair(_bf_pair(wa, k)), _f_pair(_bf_pair(wb, k))) for k in range(4)]\n rows = [[_f_pair(_bf_pair(braw[r], k)) for k in range(4)] for r in range(nb)] + [pf]\n\n dots = []\n sss = []\n for r in range(nr):\n x = rows[r]\n d = _pk_mul(x[0], cwp[0])\n for k in range(1, 4):\n d = _pk_fma(x[k], cwp[k], d)\n dots.append(_hsum(d))\n sss.append(_sum_sq(x))\n\n # Wave reduce-scatter: bit 5 splits dots / sums of squares, bit 4 splits each into h2 + (nr - h2) (+ pad).\n vals = _scatter(dots + sss, 5)\n vals = _scatter(vals, 4)\n for ctrl in _DPP_ALL:\n vals = [v + _dpp(v, ctrl) for v in vals]\n q = lane >> 4\n\n def _partials_to_lds():\n for k in range(h2):\n _lds_st(lds, vals[k], (q * h2 + k) * WPAD + wave)\n\n _scf_if((lane & 15) == 0, _partials_to_lds)\n fx.gpu.barrier()\n\n # Every wave sums the 14 waves' partials in the same fixed order: lane (j, q) adds waves 4q..4q+3 of row j,\n # then the four lane groups are summed across lane bits 4 and 5. Lanes j < nr hold row j's totals.\n j = lane & 15\n last = q == 3 # its waves 14 and 15 do not exist\n\n def _four_waves(slot):\n v = _lds_ld4(lds, slot * WPAD + q * 4)\n e = [_f32(_vector.extract(v, [], [i])) for i in range(4)]\n e[2] = last.select(_f32(0.0), e[2])\n e[3] = last.select(_f32(0.0), e[3])\n return (e[0] + e[1]) + (e[2] + e[3])\n\n # Swap-add across bit 4 reduce-scatters (dots to lanes with bit 4 clear, sums of squares to the others), a\n # swap-add across bit 5 completes both, and a last swap hands every lane its row's pair.\n a, b = _permute_pair(_four_waves(j), _four_waves(j + 2 * h2), 4)\n tot = a + b\n a, b = _permute_pair(tot, tot, 5)\n tot = a + b\n dsum, ssum = _permute_pair(tot, tot, 4)\n valid = lane < nr\n score = dsum * _rsq(fx.math.fma(ssum, _f32(_INV_D), score_eps))\n sc = valid.select(score, _f32(-3.0e38))\n mx = sc\n for ctrl in _DPP_ALL:\n mx = fx.Float32(_arith.MaximumFOp(fx.as_ir_value(mx), fx.as_ir_value(_dpp(mx, ctrl))).result)\n ex = valid.select(_exp2((sc - mx) * _f32(_LOG2E)), _f32(0.0))\n # The mix uses the unnormalised exponentials e_r, their sum Z taken in row order.\n wts = [_readlane(ex, r) for r in range(nr)]\n z = wts[0]\n for w in wts[1:]:\n z = z + w\n\n wv = [_splat2(w) for w in wts]\n mix = []\n for k in range(4):\n m = _pk_mul(rows[0][k], wv[0])\n for r in range(1, nr):\n m = _pk_fma(rows[r][k], wv[r], m)\n mix.append(m)\n if norm:\n # rsqrt(sum (mix / Z)^2 / D + eps) / Z = rsqrt(sum mix^2 / D + eps Z^2)\n tsq = _block_sum(lds, _sum_sq(mix), lane, wave)\n scale = _splat2(_rsq(fx.math.fma(tsq, _f32(_INV_D), norm_eps * (z * z))))\n outs = [_to_bf_pair(_pk_mul(_pk_mul(mix[k], scale), nwf[k])) for k in range(4)]\n else:\n scale = _splat2(_f32(1.0) / z)\n outs = [_to_bf_pair(_pk_mul(mix[k], scale)) for k in range(4)]\n _store16(r_out, hb, tb, _concat8(outs))\n\n\ndef _prefetch(cfg, t, bank, h):\n \"\"\"A helper workgroup on the token's XCD: load its bank rows, as the token's workgroup will, so that the\n workgroup's later requests hit the shared L2 instead of memory. The loads allocate in L2 (default policy, not\n nt); an empty asm consumes them.\"\"\"\n nbank, nb = cfg[0], cfg[1]\n r_bank = _rsrc(bank)\n hb = fx.thread_idx.x * (VEC * 2)\n bf16 = _ir.BF16Type.get()\n rows = [_load16(r_bank, hb, (t * nbank + r) * (D * 2), bf16, 8) for r in range(nb) if r % HELPERS == h]\n if not rows:\n return\n acc = _f_pair(_bf_pair(rows[0], 0))\n for v in rows[1:]:\n acc = _pk_add(acc, _f_pair(_bf_pair(v, 0)))\n _llvm.InlineAsmOp(None, [fx.as_ir_value(_hsum(acc))], \"; $0\", \"v\", has_side_effects=True)\n\n\ndef _make(cfg, grid):\n nb = cfg[1]\n alloc = SmemAllocator(None, arch=\"gfx950\", global_sym_name=\"kimi_k3_attn_res_lds\")\n alloc.ptr = (LDS1 + LDS2) * 4\n\n @flyc.kernel\n def k_kimi_k3_attn_res(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n ):\n lds_ty = _ir.MemRefType.get([LDS1 + LDS2], _ir.F32Type.get(), memory_space=_lds_space())\n lds = _memref.view(lds_ty, alloc.get_base(),\n _arith.ConstantOp(_ir.IndexType.get(), 0).result, sizes=[])\n args = (lds, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps)\n b = fx.Int32(fx.block_idx.x)\n if fx.const_expr(nb > 0 and HELPERS > 0):\n # groups of 8 tokens' workgroups, then their helpers, 8 at a time; past n_tokens all idle\n t = (b // GROUP) * XCDS + b % XCDS\n role = (b // XCDS) % (1 + HELPERS)\n live = t < n_tokens\n _scf_if(live & (role == 0), lambda: _token(cfg, t, *args))\n for h in fx.range_constexpr(HELPERS):\n _scf_if(live & (role == h + 1), lambda h=h: _prefetch(cfg, t, bank, h))\n else:\n _scf_if(b < n_tokens, lambda: _token(cfg, b, *args))\n\n @flyc.jit\n def launch(\n n_tokens: fx.Int32,\n prefix: fx.Pointer,\n addend: fx.Pointer,\n bank: fx.Pointer,\n snw: fx.Pointer,\n spw: fx.Pointer,\n nw: fx.Pointer,\n out: fx.Pointer,\n score_eps: fx.Float32,\n norm_eps: fx.Float32,\n stream: fx.Stream = fx.Stream(None),\n ):\n alloc.finalized = False\n ctx = CompilationContext.get_current()\n with _ir.InsertionPoint(ctx.gpu_module_body):\n alloc.finalize()\n k_kimi_k3_attn_res(n_tokens, prefix, addend, bank, snw, spw, nw, out, score_eps, norm_eps).launch(\n grid=(grid, 1, 1), block=(NTHR, 1, 1), stream=stream)\n\n opts = {\"amdgpu-kernarg-preload-count\": 8, \"vectorize-slp\": False}\n return flyc.compile[{\"llvm_options\": opts}](launch)\n\n\[email protected]\ndef _launch_for(n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm, grid):\n return _make((n_bank_rows, n_valid_rows, write_bank, has_addend, has_norm), grid)\n\n\ndef _grid(n_tokens, n_valid_rows):\n if n_valid_rows == 0 or HELPERS == 0:\n return n_tokens\n return GROUP * -(-n_tokens // XCDS)\n\n\ndef run(*, prefix, bank, score_norm_weight, score_proj_weight, n_valid_rows, write_bank, addend, norm_weight,\n score_eps, norm_eps, out_dtype, out):\n \"\"\"out, and p into the prefix with an addend and into the bank with write_bank, written in place.\"\"\"\n n_tokens, hidden_size = prefix.shape\n n_bank_rows = bank.shape[1]\n assert hidden_size == D and n_tokens * n_bank_rows * D * 2 < 2**31\n fn = _launch_for(n_bank_rows, n_valid_rows, write_bank, addend is not None, norm_weight is not None,\n _grid(n_tokens, n_valid_rows))\n tensors = (prefix, prefix if addend is None else addend, bank, score_norm_weight, score_proj_weight,\n prefix if norm_weight is None else norm_weight, out)\n ptrs = [flyc.from_c_void_p(fx.Int32, x.data_ptr()) for x in tensors]\n fn(n_tokens, *ptrs, score_eps, norm_eps, fx.Stream(torch._C._cuda_getCurrentRawStream(prefix.device.index)))\n"
Comment on lines +42 to +44
rows = torch.cat((bank[tokens, :valid], prefix[tokens, None]), dim=1)
scores = (rows @ score_weight) * (rows.square().mean(dim=-1) + args["score_eps"]).rsqrt()
mix = (torch.softmax(scores, dim=-1)[..., None] * rows).sum(dim=1)
Comment on lines +178 to +182
# Source tiling helps decode, while one-source tiles scale better for prefill.
if num_tokens >= 256 or num_blocks <= 1:
block_l, num_warps = 1, 4
else:
block_l, num_warps = 4, 8
Comment on lines +30 to +33
@vllm_route(
"vllm.models.kimi_k3.amd.linear._apply_attn_res",
"vllm.models.kimi_k3.amd.linear.attn_res",
versions=("0.33.0rc1.dev910",),
Comment on lines +52 to +53
if quant_dtype is not None or block_write_idx not in (-1, num_blocks):
return FallbackReason.OUT_OF_CONTRACT
Comment on lines +39 to +41
attrs={"n_valid_rows": 3, "write_bank": True, "has_addend": False, "has_norm": True},
layout_variant_name="row_major",
),
…@1.0), its route and FlyDSL kernels

vLLM runs Kimi-K3's attention residual (models/kimi_k3/amd/ops/attn_res.py) 187 times a decode
step: before attention and before the MLP of each of the 93 layers, and once before the final
norm. [email protected] states every call it makes: 0 to 8 bank rows read, the pending layer
output folded into the prefix in place, the prefix written as the next bank row, the output
norm optional, the score weight the product of two bf16 weights. The baseline is vLLM's Triton
kernel with its launch configuration (copied, Apache-2.0, so that it runs without vLLM). The
route replaces the attn_res that _apply_attn_res calls and falls back on the fp8 output (a
linear taking per-token fp8 input, which Kimi-K3's MXFP4 checkpoint does not have).

One schema per call combination vLLM makes for Kimi-K3 (hidden 7168, 8 bank rows): 1 to 8 rows
with the addend and the output norm (170 of the 187 calls a decode step), with the bank write
(7), without the addend (8), and the last layer's mix without a norm (1); workloads 3, 6, 9 and
12 tokens (1 to 4 requests of 3 decode tokens). One kernel source: a workgroup of 896 threads
per token, with a helper workgroup on the same XCD loading the token's bank rows into L2; the
row count is fixed per build and the token count is a kernel argument.

Speedup over vLLM's Triton kernel (validate on MI355X, every workload within the bounds, none
demoted): 1.22x to 1.97x, geometric mean 1.65x; at 3 tokens the 186 calls a decode step take
0.89 ms instead of 1.51 ms. The first layer's call (no bank row, 1 a step) stays on vLLM's
kernel: both sit at the launch floor there (1.00x).
@kyle-256
kyle-256 merged commit dbce20c into main Nov 13, 2026
16 checks passed
@kyle-256
kyle-256 deleted the kyle/k3v-attn-res 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.
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.

This branch was previously deployed

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