Skip to content

feat(flydsl): FlashMLA decode kernel with paged bf16 KV cache for 96 heads, 8 query tokens - #201

Merged
zhenhuang12 merged 1 commit into
mainfrom
shepherd/flash-mla-with-kvcache-causal-bf16-lse-has-block-table-has-c-39b645e3
Nov 14, 2026
Merged

zhenhuang12 merged 1 commit into
mainfrom
shepherd/flash-mla-with-kvcache-causal-bf16-lse-has-block-table-has-c-39b645e3

Conversation

@zhenhuang12

Copy link
Copy Markdown
Collaborator

Why

The FlashMLA decode contract for causal bf16 attention over a paged bf16 KV pool (query length 8, 96 heads, page size 1, with LSE, block table and cu_seqlens_k) had no kernel. A shepherd KernelForge campaign built one in FlyDSL, starting from AKLR's baseline. It runs as one launch, with one wave per (request, query position, 16 heads):

  • Each wave first assumes its request holds exactly 8 KV rows at 8 b. It reads those block-table entries speculatively, clamped into the table and the pool, and stores the result.
  • A request that does not fit that guess is recomputed in 8-row chunks with an online softmax.
  • Each KV row is loaded once per wave.

Scope

  • One kernel file, f6f727be6a8dd6e8.json, beside the unchanged kernel-less schema 619f746e7a2290bf.json. Its workloads are its 11 batch sizes (1–14). kernel.requires pins flydsl>=0.3.2.
  • No contract or code change. The knowledge KernelForge distilled for aklr-kb is not in this PR (see Not run).

Verification

Environment: head d3f74d7 (parent 1541453bf), validated merged into main e914c3e02 (merge 08553ce); MI355X gfx950 ×1, image lmsysorg/sglang@sha256:1438dd8b…7e5f (v0.5.22-rocm10-mi35x), ROCm 7.15.26333, torch 2.11.0+rocm10.0.0, FlyDSL 0.3.2, AITER at dbd8bf5bd (CI's AKLR_BASELINE_AITER). The evidence comes from this head merged into the validation base, not from the head alone. Freshness from e914c3e02 to main e914c3e02: no relevant change.
Gate overrides: none

Kernels

contract baseline measured accuracy (bound) speedup
[email protected] aklr.ops.mla.baseline.flash_mla_with_kvcache_baseline 11/11 11/11 (worst violation fraction 0.0) 1.2583 – 2.0

Lower bound of the graph/baseline ratio over 16 rounds per Point, all passed: batch 1 and 2 at 2.0, the validator's clamp (their smallest round ratio is about 2.55); batch 3–5 1.26–1.29; batch 6–14 1.69–1.89. driver.py --stress (forge_task, made in the validator): stress: PASS. python -m aklr export check: no output, exit 0.

KernelForge's own ablation (worker-measured, not AKLR's ruler) found both kept rounds paying: the single fused launch (+142.9% over the search's start) and loading each KV row once per wave (+4.4%).

Validation log
$ python -m aklr validate --base e914c3e02ea4a28d1a1a1afeda277922ecc3d71f --stages audit,bench --devices 0 <the kernel file>
[15:45:25] validate: collecting schemas and platform
[15:45:27] validate: 2026-11-13, head 08553cedccb0, base e914c3e02ea4, MI355X gfx950 x1
[15:45:27] audit: started (stage 1/2)
[15:45:27] audit: checking 1 schemas
[15:45:27] audit: checking changes against base e914c3e02ea4
[15:45:27] audit: passed, findings: 0, 0:00:00
[15:45:27] bench: started (stage 2/2)
[15:45:27] bench: reading 1 schemas
[15:45:27] bench: 1 batches (1 schemas), 11 workloads, 1 devices
[15:47:18] bench: 1/1 passed flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be: 11 wl, speedup 1.26x-2.56x, acc ok
[15:47:18] bench: 11 workloads
[15:47:18] bench:   outcome                         workloads
[15:47:18] bench:   passed                                 11
[15:47:18] bench:   speedup  best 2.56x, median 1.69x, worst 1.26x  (workloads with a speedup value)
[15:47:18] bench:   accuracy FAIL 0, ok 11, not measured 0
[15:47:18] bench: passed, findings: 0, 0:01:51
validation passed: <validate>/report/report.md

AKLR validation: passed

head 08553cedccb0 · base e914c3e02ea4 · MI355X gfx950 ×1 · rocm 7.15.26333 · torch 2.11.0+rocm10.0.0 · flydsl 0.3.2

stage status findings elapsed seconds
audit passed 0 0.5
bench passed 0 111.1

bench

schema axes verdict graph/baseline graph/incumbent
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=1,n_pages=8,table_width=8,n_offsets=2 passed 2.0000 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=2,n_pages=16,table_width=16,n_offsets=3 passed 2.0000 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=3,n_pages=24,table_width=24,n_offsets=4 passed 1.2583 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=4,n_pages=32,table_width=32,n_offsets=5 passed 1.2661 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=5,n_pages=40,table_width=40,n_offsets=6 passed 1.2928 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=6,n_pages=48,table_width=48,n_offsets=7 passed 1.7080 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=7,n_pages=56,table_width=56,n_offsets=8 passed 1.6856 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=8,n_pages=64,table_width=64,n_offsets=9 passed 1.6916 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=10,n_pages=80,table_width=80,n_offsets=11 passed 1.6924 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=12,n_pages=96,table_width=96,n_offsets=13 passed 1.8932 -
flydsl/flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/f6f727be batch=14,n_pages=112,table_width=112,n_offsets=15 passed 1.8754 -

Not run

  • GPU CI on this head (ci:gpu not added: not authorized for this automation).
  • The aklr-kb patch KernelForge's distill proposed is unreviewed and held back.
  • The recompute path: every workload gives each request exactly 8 KV rows, so validation timed and checked only the speculative path. A request with another KV length runs the chunked online-softmax path, which no Point covers.
  • Open PR feat(contract): every schema names the models whose serving calls it #194 (models on every schema) edits this input schema. Once it merges, this kernel file needs models and this evidence is stale: revalidate then.

Risk

Affects: [email protected] calls matching this schema (causal, bf16 KV, query length 8, 96 heads, page size 1) on gfx950.
If wrong: wrong attention output or LSE, or slower than the baseline. The highest risk is requests whose KV length is not 8 or that do not start at row 8 b. They take the recompute path, which this validation never reached; reviewers should check it, or add such a workload. Speculative reads are clamped into the block table and the pool.
Undo: [email protected] turns the op off; otherwise git revert (deletes the kernel file only).

@zhenhuang12
zhenhuang12 force-pushed the shepherd/flash-mla-with-kvcache-causal-bf16-lse-has-block-table-has-c-39b645e3 branch from d3f74d7 to cb2f195 Compare November 13, 2026 23:35
@zhenhuang12
zhenhuang12 marked this pull request as ready for review November 13, 2026 23:36
Copilot AI max review requested due to automatic review settings November 13, 2026 23:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The kernel can launch on the wrong device or stream in multi-GPU use, and unresolved numerical and scale-specialization defects can produce incorrect results or fail graph capture.

6 open issues
What changed in this PR

Adds a FlyDSL kernel for AKLR’s previously kernel-less FlashMLA decode schema: causal attention over paged bf16 KV storage with eight query tokens and 96 heads.

Changes:

  • Implements fused attention output and log-sum-exp computation in one launch, sharing KV row loads within each wave.
  • Targets MI355X/gfx950 and requires FlyDSL ≥0.3.2.
  • Includes 11 workloads across batch sizes 1–14; these Points require exactly eight KV rows per request.
File Description
aklr/​ops/​mla/​impls/​flydsl/​flash_mla_with_kvcache_causal_bf16_lse_has_block_table_has_cu_seqlens_k_kv_cache_bfloat16_query_length8_n_heads96_page_size1/​f6f727be6a8dd6e8.json Embeds the kernel, hardware target, dependency requirement, and workload definitions.

Review effort: Max

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The launch takes the stream from the current device. The serving engines AKLR plugs into (sglang, vLLM) call torch.cuda.set_device per rank before any op, so the current device is q.device for them. Device binding as a rule for all kernels would be a repository-wide change rather than something to do in this kernel PR. No change here.

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

P is rounded to bf16 before the PV MFMA as in FlashAttention/FlashMLA, the production kernels this contract's baseline runs. The bf16 MFMA takes bf16 operands, so an fp32 P would need a different, slower instruction mix. Cancellation between value rows is limited by bf16 P the same way there. The contract's check on the definition's init distribution is what CI validation enforces on every workload. No change.

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This needs |q·k| near 2^64, far outside what bf16 attention scores reach after RMSNorm'd projections. Pre-scaling by log2(e) before the max subtraction is the standard exp2 formulation, used by FlashAttention as well. The contract's init distribution, which CI validation checks, does not produce such logits. No change.

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Same class: the fp32 accumulator of unnormalized P·V overflows only when sum(p_i·v_i) passes 2^128 before normalization, which needs values near 2^120. Online-softmax kernels (FlashAttention, FlashMLA) accumulate the same way. No change.

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Right about the mechanism: dispatch validates scalars but does not key on them, so a new (sm_scale, kv_scale) pair first seen inside a graph capture would compile there. The result cannot be wrong, though: _build is cached by both scales, so each pair gets its own kernel. In serving the pair is a per-model constant. sm_scale is 1/sqrt(d_qk), and kv_scale is 1.0 for this bf16 KV cache. All 11 workloads carry the same pair, and engines run their eager warmup with it before capture. Passing the scales at run time would change the kernel's hot loop and need a new measurement, so this PR keeps them specialized. Keying dispatch on specializing scalars is a dispatch-level change, out of scope here.

"sources": [
{
"path": "kernel.py",
"content": "\"\"\"FlyDSL causal dense MLA over a paged bf16 KV pool (query_length 8, 96 heads, page size 1) in one launch,\none wave per (request, query position, 16 heads). Each wave first assumes its request holds exactly CH rows at\nCH b and stores that; a request that does not fit is recomputed in CH-row chunks with an online softmax.\"\"\"\n\nimport functools\n\nimport flydsl.compiler as flyc\nimport flydsl.expr as fx\nimport torch\nfrom flydsl._mlir.dialects import llvm as _llvm\nfrom flydsl.expr import math as fmath\nfrom flydsl.expr import range_constexpr, rocdl\nfrom flydsl.expr.typing import BFloat16, Float32, Int16, Int32, T\nfrom flydsl.expr.typing import Vector as Vec\n\nNHEAD = 96\nQLEN = 8\nDQK = 576\nDV = 512\nQBLK = DQK // 32 # k-steps of the logit MFMA\nNPV = DV // 32 # pairs of 16-dim value tiles\nCH = 8 # KV rows a chunk\nROWE = DV + 8 # LDS row stride in bf16 elements (1040 B: rows land 16 B apart in the banks)\nNHT = NHEAD // 16\nLOG2E = 1.4426950408889634\nLN2 = 0.6931471805599453\nNEGBIG = -1.0e30\n\n\[email protected]\ndef _build(sm_scale, kv_scale, batch, width, npool):\n \"\"\"Compile the kernel for one batch and table width (scales folded in as constants).\"\"\"\n scale2 = float(sm_scale) * float(kv_scale) * LOG2E\n vscale = float(kv_scale)\n\n @fx.struct\n class Shared:\n \"\"\"LDS: the chunk's CH value rows (the MFMA's rows 8..15 read rows 0..7 again, against zero P).\"\"\"\n\n vt: fx.Array[BFloat16, CH * ROWE, 16]\n\n def _swap(x, wide):\n \"\"\"(x, x of lane ^ 16) (wide: ^ 32) in some order, by one permlane swap.\"\"\"\n xi = fx.Float32(x).bitcast(Int32).ir_value()\n op = rocdl.permlane32_swap if wide else rocdl.permlane16_swap\n st = op(_llvm.StructType.get_literal([T.i32, T.i32]), xi, xi, False, False)\n return [fx.Int32(_llvm.extractvalue(T.i32, st, [k])).bitcast(Float32) for k in range(2)]\n\n def _hi(x):\n \"\"\"x of lane + 32 (for lanes below 32): the second result of permlane32_swap.\"\"\"\n return _swap(x, True)[1]\n\n def _allmax(x):\n o = _swap(x, False)\n x = o[0].maximumf(o[1])\n o = _swap(x, True)\n return o[0].maximumf(o[1])\n\n def _allsum(x):\n o = _swap(x, False)\n x = o[0] + o[1]\n o = _swap(x, True)\n return o[0] + o[1]\n\n def _tidx(i):\n \"\"\"A block_table index, clamped into the table only when the speculative read can run past it.\"\"\"\n if width >= batch * CH:\n return i\n return (i < fx.Int32(width)).select(i, fx.Int32(width - 1))\n\n @flyc.kernel\n def mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t):\n t = fx.Int32(fx.block_idx.x)\n lane = fx.thread_idx.x\n lr = lane % 16\n lg = lane // 16\n b = t // (QLEN * NHT)\n rem = t - b * (QLEN * NHT)\n qpos = rem // NHT\n h0 = (rem - qpos * NHT) * 16\n\n lds = fx.SharedAllocator().allocate(Shared).peek()\n vp = lds.vt.ptr\n\n qp = fx.get_iter(q_t)\n kvp = fx.get_iter(kv_t)\n btp = fx.get_iter(bt_t)\n cup = fx.get_iter(cu_t)\n\n key = lr % CH\n # Speculative table entries CH b .. CH b + CH - 1 as wave-uniform loads; each lane picks its row's.\n tb = []\n for k in range_constexpr(CH):\n tv = fx.Int32(fx.ptr_load(fx.add_offset(btp, _tidx(b * CH + k))))\n # readfirstlane keeps the loads scalar (LLVM would fold the selects into one vector load).\n tb.append(fx.Int32(rocdl.readfirstlane(T.i32, tv.ir_value())))\n slot_s = tb[0]\n for k in range_constexpr(1, CH):\n slot_s = (key == fx.Int32(k)).select(tb[k], slot_s)\n # Clamp the pool row: the speculative chunk runs unconditionally, also when the guess is wrong.\n slot_s = (slot_s < fx.Int32(0)).select(fx.Int32(0), slot_s)\n slot_s = (slot_s > fx.Int32(npool - 1)).select(fx.Int32(npool - 1), slot_s)\n rt = fx.Int32(fx.ptr_load(fx.add_offset(cup, b)))\n re = fx.Int32(fx.ptr_load(fx.add_offset(cup, b + fx.Int32(1))))\n # Q as the logit MFMA's B operand: lane holds head h0 + lr, dims 32 ks + 8 lg .. + 7.\n qbase = ((b * QLEN + qpos) * NHEAD + h0 + lr) * DQK + 8 * lg\n qv = [fx.ptr_load(fx.add_offset(qp, qbase + 32 * ks), T.bf16x8) for ks in range(QBLK)]\n\n ln = re - rt\n ln = (ln < fx.Int32(0)).select(fx.Int32(0), ln)\n nvalid = ln - fx.Int32(QLEN - 1) + qpos # causal: the first ln - QLEN + qpos + 1 rows\n nvalid = (nvalid < fx.Int32(0)).select(fx.Int32(0), nvalid)\n nch = (nvalid + fx.Int32(CH - 1)) // CH\n slow = (rt != b * CH) | (ln != fx.Int32(CH))\n\n tr_atom = fx.make_copy_atom(rocdl.cdna4.LDSReadTrans16_64b(), BFloat16)\n tr_layout = fx.make_layout(4, 1)\n # Transposed value read: lane (lg, lr) gives row 4 lg + lr // 4, dims 8 (lr % 4) + 4 u + 32 p .. + 3;\n # the MFMA's row 4 lg + i then holds dim 32 p + 8 lg + 4 u + i.\n rbase = ((lg % 2) * 4 + lr // 4) * ROWE + (lr % 4) * 8\n half = lr // CH\n wbase = key * ROWE + 32 * half + 8 * lg\n\n def pv_read(off):\n src = fx.make_view(fx.add_offset(vp, rbase + off), tr_layout)\n dst = fx.make_rmem_tensor(tr_layout, BFloat16)\n fx.copy(tr_atom, src, dst)\n return Vec(dst.load())\n\n def chunk(c, slot, st, nv):\n \"\"\"Fold chunk c (rows CH c .. of the query's live rows; slot is this lane's pool row) into st.\"\"\"\n # Lane (lg, lr) loads a distinct 16 B of row lr % CH; as the A operand, MFMA rows 8..15 carry\n # the odd k-steps of rows 0..7: sa[0] keeps rows 0..7 of even steps, sa[1] rows 8..15 of odd ones.\n kb = slot * DQK + 32 * half + 8 * lg\n kv = [fx.ptr_load(fx.add_offset(kvp, kb + 64 * j), T.bf16x8) for j in range(QBLK // 2)]\n sa = [Vec.filled(4, 0.0, Float32), Vec.filled(4, 0.0, Float32)]\n for ks in range_constexpr(QBLK):\n sa[ks % 2] = Vec(rocdl.mfma_f32_16x16x32_bf16(T.f32x4, [kv[ks // 2], qv[ks], sa[ks % 2]]))\n fx.barrier() # the previous chunk's value reads are done\n for j in range_constexpr(NPV // 2):\n fx.ptr_store(Vec(kv[j]), fx.add_offset(vp, wbase + 64 * j))\n fx.barrier()\n mprev = fx.Float32(st[0])\n sprev = fx.Float32(st[1])\n acc = [Vec(st[2 + n]) for n in range(2 * NPV)]\n r0 = fx.Int32(c * CH) + 4 * lg # lane holds logits of rows r0 + i (lg < 2) of head h0 + lr\n sv = []\n for i in range_constexpr(4):\n s = fx.Float32(sa[0][i]) + _hi(fx.Float32(sa[1][i]))\n ok = (lg < fx.Int32(2)) & (r0 + fx.Int32(i) < nv)\n sv.append(ok.select(s * scale2, fx.Float32(NEGBIG)))\n ml = sv[0].maximumf(sv[1]).maximumf(sv[2].maximumf(sv[3]))\n mnew = _allmax(ml).maximumf(mprev)\n alpha = fmath.exp2(mprev - mnew, fastmath=\"afn\")\n pv = [\n (sv[i] > fx.Float32(NEGBIG)).select(fmath.exp2(sv[i] - mnew, fastmath=\"afn\"), fx.Float32(0.0))\n for i in range(4)\n ]\n psum = _allsum((pv[0] + pv[1]) + (pv[2] + pv[3]))\n snew = sprev * alpha + psum\n pb = Vec.from_elements(pv, Float32).to(BFloat16).bitcast(Int16)\n a4 = Vec.from_elements([alpha] * 4, Float32)\n out = []\n for n in range_constexpr(2 * NPV):\n p, u = n // 2, n % 2\n va = pv_read(32 * p + 4 * u).bitcast(Int16)\n out.append(Vec(rocdl.mfma_f32_16x16x16bf16_1k(T.f32x4, [va, pb, Vec(acc[n] * a4)])))\n return [mnew, snew] + out\n\n def finish(res):\n \"\"\"Normalize and store the lane's head's lse and its 16 output dims of each value-tile pair.\"\"\"\n mrun = fx.Float32(res[0])\n srun = fx.Float32(res[1])\n live = srun > fx.Float32(0.0)\n inv = live.select(fx.Float32(vscale) / srun, fx.Float32(0.0))\n lsev = live.select((mrun + fmath.log2(srun)) * LN2, fx.Float32(float(\"-inf\")))\n row = (b * QLEN + qpos) * NHEAD + h0 + lr\n if lane < fx.Int32(16):\n fx.ptr_store(Vec.from_elements([lsev], Float32), fx.add_offset(fx.get_iter(lse_t), row))\n ofp = fx.get_iter(out_t)\n i8 = Vec.from_elements([inv] * 8, Float32)\n for p in range_constexpr(NPV):\n a0 = Vec(res[2 + 2 * p])\n a1 = Vec(res[3 + 2 * p])\n o8 = a0.shuffle(a1, [0, 1, 2, 3, 4, 5, 6, 7])\n fx.ptr_store(Vec(o8 * i8).to(BFloat16), fx.add_offset(ofp, row * DV + 32 * p + 8 * lg))\n\n init = [fx.Float32(NEGBIG), fx.Float32(0.0)] + [Vec.filled(4, 0.0, Float32) for _ in range(2 * NPV)]\n finish(chunk(0, slot_s, init, qpos + fx.Int32(1)))\n if slow:\n for ci, st in range(fx.Int32(0), nch, fx.Int32(1), init=init):\n c = fx.Int32(ci)\n cidx = c * CH + key\n cidx = (cidx < nvalid).select(cidx, fx.Int32(0))\n slot = fx.Int32(fx.ptr_load(fx.add_offset(btp, rt + cidx)))\n nst = chunk(c, slot, st, nvalid)\n res = yield nst\n finish(res)\n\n @flyc.jit\n def launch_all(q_t, kv_t, bt_t, cu_t, out_t, lse_t, stream: fx.Stream):\n mla_kernel(q_t, kv_t, bt_t, cu_t, out_t, lse_t).launch(\n grid=(batch * QLEN * NHT, 1, 1), block=(64, 1, 1), stream=stream\n )\n\n def launch(q, kv_cache, block_table, cu_seqlens_k, output, lse):\n launch_all(\n q.view(-1),\n kv_cache.view(-1),\n block_table.view(-1),\n cu_seqlens_k.view(-1),\n output.view(-1),\n lse.view(-1),\n fx.Stream(torch.cuda.current_stream()),\n )\n\n return launch\n\n\ndef run(\n *,\n q,\n kv_cache,\n causal,\n kv_cache_format,\n return_lse,\n kv_cache_layout,\n sparse_indices,\n sparse_lens,\n extra_kv_cache,\n extra_sparse_indices,\n extra_sparse_lens,\n block_table,\n cache_seqlens,\n cu_seqlens_k,\n head_dim_v,\n sm_scale,\n sinks,\n kv_scale,\n output,\n lse,\n):\n \"\"\"Write the causal dense MLA of this request batch into output and lse.\"\"\"\n fn = _build(\n float(sm_scale),\n float(kv_scale),\n q.shape[0],\n block_table.numel(),\n kv_cache.shape[0] * kv_cache.shape[1],\n )\n fn(q, kv_cache, block_table, cu_seqlens_k, output, lse)\n"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

NEGBIG (-1e30) marks masked positions. A finite logit below -1e30 needs q·k near 2^100, and after the max subtraction exp2 of it is exactly 0 in fp32, so dropping it changes nothing unless every visible logit is that low. That would mean inputs around 2^56 again, outside the contract's init distribution. No change.

…heads, 8 query tokens

Optimized by a shepherd KernelForge campaign (shp44-mla-fmkv-q8h96) from frozen workspace commit f5aac5504839f373da7d3efec3f9774058b040c1.
@zhenhuang12
zhenhuang12 force-pushed the shepherd/flash-mla-with-kvcache-causal-bf16-lse-has-block-table-has-c-39b645e3 branch from cb2f195 to 5f3bf0a Compare November 14, 2026 03:31
@zhenhuang12
zhenhuang12 merged commit a04d54f into main Nov 14, 2026
16 checks passed
zhenhuang12 pushed a commit that referenced this pull request Nov 18, 2026
* docs(kb): name the kernel files main holds now, after #168 and #220 renamed them

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

* docs(kb): mark fused_moe 4ea93103 withdrawn

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

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

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

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

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

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

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

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

* docs(kb): evidence counts from the runs' logs; R2 at batch 4 and 8; aiter's top-k fails the reference at 16384

This branch was previously deployed

1 inactive deployment
gpu-trusted — 5f3bf0aa Deployed Nov 14, 2026 by zhenhuang12 via prepare-gpu / prepare #820
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