Repository navigation
feat(plugins): add Qwen3.5 GDN decode kernels: grouped FP8 at 64 rows, BF16 output at 11 sizes - #75
Conversation
…t at 64 rows One schema on [email protected] at n_tokens 64, a Gluon kernel created by OpenAI for MI355X (gfx950): one launch runs the Conv1D update and normalizes Q/K, a second runs the delta rule on pairs of value heads, the gated RMSNorm and the per-head E4M3FN quantization. Main's GDN route tries this op before [email protected], so once CI qualifies the Point it serves the FP8 checkpoint's 64-row decode, which the BF16 kernel serves today. The kernel writes the caller's values and scales; its BF16 normalized tensor stays per-call scratch. n_slots 127: each drawn input set holds the one -1 padding row with probability 1/2. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Eleven schemas on [email protected], at 1, 2, 4, 8, 16, 32, 64, 96, 128, 192 and 256 rows: Gluon kernels created by OpenAI for MI355X (gfx950), written for the Qwen3.5 MXFP4 checkpoint, whose GDN layers stay in BF16. Main's GDN route reaches [email protected] today on the FP8 checkpoint only, where the FP8 op declines: at 96 and 192 rows (no FP8 schema), at 64 rows beside the existing BF16 schema, and at any Point the FP8 op is not qualified for. The MXFP4 checkpoint is not served until the route takes unquantized projections. Each kernel writes the caller's normalized output; the 1-row one keeps its cache-period-aligned buffer for the recurrent core alone. n_slots is 2N - 1: each drawn input set holds the one -1 padding row with probability 1/2. Co-Authored-By: Claude Opus 5.5 <[email protected]>
zhenhuang12
left a comment
There was a problem hiding this comment.
Verified the latest successful CI run for this head and inspected the change scope. Unit tests and audit passed. GPU validation passed with zero accuracy failures. Performance demotions remain subject to the normal dispatch gate. Approving for the requested squash merge; this does not claim additional end-to-end model validation.
There was a problem hiding this comment.
🟡 Changes recommended
Critical FP32 softplus cancellation across the decode paths suppresses required state decay for valid inputs, producing state errors far beyond the allowed tolerance.
12 open issues
Use stable softplus in _decode_gates · New Use stable softplus in _coefficients · New Use stable softplus in _recurrent · New Preserve the negative softplus tail in _gate_values · New Preserve the negative softplus tail in _coefficients · New Use stable softplus in the 96-row path · New Preserve decay in _recurrent_norm with stable softplus · New Preserve the negative softplus tail in _gate_values · New Use stable softplus in _decay_beta · New Use stable softplus in _gates · New Preserve the negative softplus tail in _recurrent · New Preserve the negative softplus tail in _gate_values · New
What changed in this PR
Adds 12 batch-specialized Gluon kernel schemas for Qwen3.5 GDN decode on MI355X, using the existing contracts and dispatch paths.
Changes:
- Add grouped FP8 output at 64 rows and BF16 output at 11 batch sizes from 1–256 rows.
- Fuse convolution, recurrent-state updates, and gated normalization into one or two launches, writing caller-provided outputs.
- Declare gfx950 targeting, Triton ≥3.8, and OpenAI provenance without changing contracts or routes.
CI reports all 12 Points passing correctness and performance gates. End-to-end serving performance was not independently verified.
| File | Description |
|---|---|
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/f72c09526cbd0c56.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/efa0df00c780a4a6.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/caf6795cf26e5d0d.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/caa6bfbe5226d564.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/a18b5dac1bfc64a1.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/996d6b34c60d0c48.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/4f52a10b3298920b.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/266e22be899b41d5.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/160456b3a455b4dd.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_n_v_heads16_key_dim128_value_dim128_conv_dim3072/01bbeb5c39019086.json | Updated as part of this pull request. |
| aklr/plugins/sglang/models/qwen3_5/impls/triton/gdn_decode_group_fp8_quant_n_v_heads16_key_dim128_value_dim128_conv_dim3072/6a916a64be4b2ce9.json | Updated as part of this pull request. |
Review effort: Max
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with grouped E4M3FN output for MI355X (gfx950), scheduled for 64 rows.\n\nGluon GDN decode with mixed-precision scratch and streaming state updates.\"\"\"\n\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\[email protected]\ndef _prepare_decode(\n projected, history, indices, weight, prepared_qk, prepared_v, scale,\n KH: gl.constexpr, VH: gl.constexpr, D: gl.constexpr,\n HEADS: gl.constexpr, PACK: gl.constexpr,\n HEAD_MAJOR: gl.constexpr = False, EARLY_ZERO: gl.constexpr = False,\n):\n \"\"\"Convolve one head per wave and normalize shared Q/K vectors once.\"\"\"\n if HEAD_MAJOR:\n token = gl.program_id(1)\n block_head = gl.program_id(0)\n else:\n token = gl.program_id(0)\n block_head = gl.program_id(1)\n channels: gl.constexpr = (2 * KH + VH) * D\n width: gl.constexpr = channels + VH * D\n layout: gl.constexpr = gl.BlockedLayout([1, PACK], [1, 64], [HEADS, 1], [1, 0])\n channel_head = block_head * HEADS + gl.arange(0, HEADS, gl.SliceLayout(1, layout))\n d = gl.arange(0, D, gl.SliceLayout(0, layout))\n col = channel_head[:, None] * D + d[None, :]\n slot = gl.load(indices + token).to(gl.int64)\n if EARLY_ZERO:\n if slot < 0:\n if block_head < 2 * KH // HEADS:\n gl.store(prepared_qk + token * (2 * KH * D) + col, 0.0)\n else:\n gl.store(prepared_v + token * (VH * D) + col - 2 * KH * D, 0.0)\n return\n conv = gl.full((HEADS, D), 0.0, gl.float32, layout)\n if slot >= 0:\n offset = (slot * channels + col) * 3\n x = gl.load(projected + token * width + col)\n h0 = gl.load(history + offset)\n h1 = gl.load(history + offset + 1)\n h2 = gl.load(history + offset + 2)\n w0 = gl.load(weight + col * 4)\n w1 = gl.load(weight + col * 4 + 1)\n w2 = gl.load(weight + col * 4 + 2)\n w3 = gl.load(weight + col * 4 + 3)\n # Round each BF16 product before the ordered FP32 accumulation.\n acc = gl.full((HEADS, D), 0.0, gl.float32, layout)\n acc += h0 * w0\n acc += h1 * w1\n acc += h2 * w2\n acc += x * w3\n conv = (acc / (1.0 + gl.exp(-acc))).to(gl.bfloat16).to(gl.float32)\n gl.store(history + offset, h1)\n gl.store(history + offset + 1, h2)\n gl.store(history + offset + 2, x)\n if block_head < 2 * KH // HEADS:\n conv = conv / gl.sqrt(gl.sum(conv * conv, 1) + 1.0e-6)[:, None]\n if block_head < KH // HEADS:\n conv *= scale\n gl.store(prepared_qk + token * (2 * KH * D) + col, conv)\n else:\n gl.store(prepared_v + token * (VH * D) + col - 2 * KH * D, conv)\n\n\[email protected]\ndef _decode_gates(ba, a_log, dt_bias, token, head, VH: gl.constexpr):\n a = gl.load(ba + token * (2 * VH) + VH + head).to(gl.float32)\n b = gl.load(ba + token * (2 * VH) + head).to(gl.float32)\n log_a = gl.load(a_log + head)\n bias = gl.load(dt_bias + head).to(gl.float32)\n softplus_input = a + bias\n softplus = gl.where(\n softplus_input <= 20.0,\n gl.log(1.0 + gl.exp(softplus_input)),\n softplus_input,\n )\n decay = gl.exp(-gl.exp(log_a) * softplus)\n beta = (1.0 / (1.0 + gl.exp(-b))).to(gl.bfloat16).to(gl.float32)\n return decay, beta\n\n\[email protected]\ndef _update_norm_quant(\n prepared_qk, prepared_v, ba, a_log, dt_bias,\n state_pool, indices, projected, weight,\n output, quantized, scales, eps,\n KH: gl.constexpr, VH: gl.constexpr, D: gl.constexpr,\n TOKEN_GROUP: gl.constexpr, EARLY_EPILOGUE: gl.constexpr, OUT_VEC: gl.constexpr,\n GATE_FIRST: gl.constexpr,\n):\n \"\"\"One workgroup owns a complete recurrent head and quantization group.\"\"\"\n program = gl.program_id(0)\n token = program // (VH * TOKEN_GROUP) * TOKEN_GROUP + program % TOKEN_GROUP\n head = program % (VH * TOKEN_GROUP) // TOKEN_GROUP\n row = token * VH + head\n key_head = head // (VH // KH)\n key_warps: gl.constexpr = 1 if gl.num_warps() == 4 else 2\n state_layout: gl.constexpr = gl.BlockedLayout(\n [2, 4], [4, 16], [gl.num_warps() // key_warps, key_warps], [1, 0],\n )\n kk = gl.arange(0, D, layout=gl.SliceLayout(0, state_layout))\n vv = gl.arange(0, D, layout=gl.SliceLayout(1, state_layout))\n channels: gl.constexpr = (2 * KH + VH) * D\n width: gl.constexpr = channels + VH * D\n slot = gl.load(indices + token).to(gl.int64)\n output_layout: gl.constexpr = gl.BlockedLayout(\n [OUT_VEC], [64], [gl.num_warps()], [0]\n )\n col = gl.arange(0, D, layout=output_layout)\n if EARLY_EPILOGUE:\n norm_weight = gl.load(weight + col).to(gl.float32)\n gate = gl.load(projected + token * width + channels + head * D + col).to(gl.float32)\n if slot < 0:\n result = gl.full((D,), 0.0, gl.float32, gl.SliceLayout(1, state_layout))\n else:\n if GATE_FIRST:\n decay, beta = _decode_gates(ba, a_log, dt_bias, token, head, VH)\n state_offset = (slot * VH + head) * D * D + vv[:, None] * D + kk[None, :]\n state = gl.load(state_pool + state_offset, cache_modifier=\".cg\")\n base = prepared_qk + token * (2 * KH * D)\n q = gl.load(base + key_head * D + kk)\n k = gl.load(base + KH * D + key_head * D + kk)\n v = gl.load(prepared_v + row * D + vv).to(gl.float32)\n if not GATE_FIRST:\n decay, beta = _decode_gates(ba, a_log, dt_bias, token, head, VH)\n state *= decay\n v -= gl.sum(state * k[None, :], 1)\n v *= beta\n state += v[:, None] * k[None, :]\n result = gl.sum(state * q[None, :], 1)\n gl.store(state_pool + state_offset, state, cache_modifier=\".cs\")\n core = gl.convert_layout(result.to(gl.bfloat16), output_layout).to(gl.float32)\n if not EARLY_EPILOGUE:\n norm_weight = gl.load(weight + col).to(gl.float32)\n gate = gl.load(projected + token * width + channels + head * D + col).to(gl.float32)\n variance = gl.sum(core * core, 0) / D\n norm = core * gl.rsqrt(variance + eps)\n norm *= norm_weight\n norm *= gate * (1.0 / (1.0 + gl.exp(-gate)))\n rounded_norm = norm.to(gl.bfloat16)\n gl.store(output + row * D + col, rounded_norm)\n value = rounded_norm.to(gl.float32)\n maximum = gl.max(gl.abs(value), 0)\n quant_scale = gl.maximum(maximum, 1.0e-10) * (1.0 / 448.0)\n scaled = value * (1.0 / quant_scale)\n clipped = gl.inline_asm_elementwise(\n \"v_med3_f32 $0, $1, $2, $3\", constraints=\"=v,v,v,v\",\n args=[scaled, -448.0, 448.0], dtype=gl.float32, is_pure=True, pack=1,\n )\n fp8_value = clipped.to(quantized.dtype.element_ty, fp_downcast_rounding=\"rtne\")\n gl.store(quantized + row * D + col, fp8_value)\n gl.store(scales + row, quant_scale)\n\n\[email protected]\ndef _update_paired_norm_quant(\n prepared_qk, prepared_v, ba, a_log, dt_bias,\n state_pool, indices, projected, weight,\n output, quantized, scales, eps,\n KH: gl.constexpr, VH: gl.constexpr, D: gl.constexpr,\n NARROW_STATE: gl.constexpr,\n):\n \"\"\"Two adjacent heads share Q/K; two waves own each complete state.\"\"\"\n program = gl.program_id(0)\n gl.assume(program >= 0)\n token = program // (VH // 2)\n first_head = (program % (VH // 2)) * 2\n key_head = first_head // (VH // KH)\n state_layout: gl.constexpr = gl.BlockedLayout(\n [1, 4, 4], [1, 4, 16], [2, 1, 2], [2, 1, 0],\n )\n head_layout: gl.constexpr = gl.SliceLayout(1, gl.SliceLayout(2, state_layout))\n value_layout: gl.constexpr = gl.SliceLayout(0, gl.SliceLayout(2, state_layout))\n key_layout: gl.constexpr = gl.SliceLayout(0, gl.SliceLayout(1, state_layout))\n head = first_head + gl.arange(0, 2, layout=head_layout)\n vv = gl.arange(0, D, layout=value_layout)\n kk = gl.arange(0, D, layout=key_layout)\n channels: gl.constexpr = (2 * KH + VH) * D\n width: gl.constexpr = channels + VH * D\n slot = gl.load(indices + token)\n if not NARROW_STATE:\n slot = slot.to(gl.int64)\n\n if slot < 0:\n result = gl.full((2, D), 0.0, gl.float32, gl.SliceLayout(2, state_layout))\n else:\n # Use int32 only when the complete state-pool element offset fits.\n state_offset = (\n (slot * VH + head[:, None, None]) * D * D\n + vv[None, :, None] * D + kk[None, None, :]\n )\n state = gl.load(state_pool + state_offset, cache_modifier=\".cg\")\n base = prepared_qk + token * (2 * KH * D)\n q = gl.load(base + key_head * D + kk)\n k = gl.load(base + KH * D + key_head * D + kk)\n v = gl.load(\n prepared_v + (token * VH + head[:, None]) * D + vv[None, :]\n ).to(gl.float32)\n decay, beta = _decode_gates(ba, a_log, dt_bias, token, head, VH)\n state *= decay[:, None, None]\n v -= gl.sum(state * k[None, None, :], 2)\n v *= beta[:, None]\n state += v[:, :, None] * k[None, None, :]\n result = gl.sum(state * q[None, None, :], 2)\n gl.store(state_pool + state_offset, state, cache_modifier=\".cs\")\n\n output_layout: gl.constexpr = gl.BlockedLayout(\n [1, 2], [1, 64], [2, 2], [1, 0],\n )\n out_head = first_head + gl.arange(0, 2, gl.SliceLayout(1, output_layout))\n col = gl.arange(0, D, gl.SliceLayout(0, output_layout))\n core = gl.convert_layout(result.to(gl.bfloat16), output_layout).to(gl.float32)\n norm_weight = gl.load(weight + col).to(gl.float32)\n gate = gl.load(\n projected + token * width + channels + out_head[:, None] * D + col[None, :]\n ).to(gl.float32)\n variance = gl.sum(core * core, 1) / D\n norm = core * gl.rsqrt(variance + eps)[:, None]\n norm *= norm_weight[None, :]\n norm *= gate * (1.0 / (1.0 + gl.exp(-gate)))\n rounded_norm = norm.to(gl.bfloat16)\n rows = token * VH + out_head\n gl.store(output + rows[:, None] * D + col[None, :], rounded_norm)\n\n # Quantization consumes the same rounded BF16 values returned above.\n value = rounded_norm.to(gl.float32)\n maximum = gl.max(gl.abs(value), 1)\n quant_scale = gl.maximum(maximum, 1.0e-10) * (1.0 / 448.0)\n scaled = value * (1.0 / quant_scale[:, None])\n clipped = gl.inline_asm_elementwise(\n \"v_med3_f32 $0, $1, $2, $3\", constraints=\"=v,v,v,v\",\n args=[scaled, -448.0, 448.0], dtype=gl.float32, is_pure=True, pack=1,\n )\n fp8_value = clipped.to(quantized.dtype.element_ty, fp_downcast_rounding=\"rtne\")\n gl.store(quantized + rows[:, None] * D + col[None, :], fp8_value)\n gl.store(scales + rows, quant_scale)\n\n\ndef gdn_fused_decode_group_fp8_quant(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *,\n scale: float,\n eps: float,\n quantized: torch.Tensor,\n scales: torch.Tensor,\n) -> None:\n tokens, projected_width = projected_qkvz.shape\n _, v_heads, head_v_dim, head_k_dim = delta_state.shape\n assert head_k_dim == head_v_dim == 128\n channels = projected_width - v_heads * head_v_dim\n k_heads = (channels - v_heads * head_v_dim) // (2 * head_k_dim)\n device = projected_qkvz.device\n prepared_qk = torch.empty(\n (tokens, 2 * k_heads * head_k_dim), device=device, dtype=torch.float32\n )\n prepared_v = torch.empty(\n (tokens, v_heads * head_v_dim), device=device, dtype=torch.bfloat16\n )\n normalized = torch.empty(\n (tokens, v_heads, head_v_dim), device=device, dtype=torch.bfloat16\n )\n small_batch = tokens <= 32\n prepare_heads = 1 if tokens <= 64 else 4\n prepare_pack = 1 if small_batch else 2\n head_major = not small_batch\n head_blocks = (2 * k_heads + v_heads) // prepare_heads\n prepare_grid = (head_blocks, tokens) if head_major else (tokens, head_blocks)\n _prepare_decode[prepare_grid](\n projected_qkvz, conv_state, cache_indices, conv_weight,\n prepared_qk, prepared_v, scale,\n k_heads, v_heads, head_k_dim, prepare_heads, prepare_pack,\n head_major, not small_batch, num_warps=prepare_heads,\n )\n if not small_batch and v_heads % (2 * k_heads) == 0:\n # Every valid slot addresses [0, delta_state.numel() - 1]. Larger\n # pools retain full-width addressing, including the slot multiplication.\n narrow_state = delta_state.numel() <= 2**31\n _update_paired_norm_quant[(tokens * v_heads // 2,)](\n prepared_qk, prepared_v, projected_ba, a_log, dt_bias,\n delta_state, cache_indices, projected_qkvz, norm_weight,\n normalized, quantized, scales, eps,\n k_heads, v_heads, head_k_dim, narrow_state, num_warps=4,\n )\n else:\n _update_norm_quant[(tokens * v_heads,)](\n prepared_qk, prepared_v, projected_ba, a_log, dt_bias,\n delta_state, cache_indices, projected_qkvz, norm_weight,\n normalized, quantized, scales, eps,\n k_heads, v_heads, head_k_dim,\n TOKEN_GROUP=8 if tokens == 32 else 1,\n EARLY_EPILOGUE=small_batch, OUT_VEC=1 if small_batch else 2,\n GATE_FIRST=small_batch, num_warps=4 if small_batch else 2,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n values,\n scales,\n):\n gdn_fused_decode_group_fp8_quant(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n quantized=values,\n scales=scales,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 128 rows.\n\nMI355 GDN decode with grouped convolution and pipelined state transport.\n\nEach CTA owns one token/key-head group and its four value-head recurrences.\nB128/B136 fetch the first state tile after convolution, before loading Q/K and\ncoefficients. B192 overlaps 32-row tiles; B256 uses 64-row tiles and also\nprefetches the next head across the current head's final tile and epilogue.\n\nSlot indirection is evaluated on every call, including graph replay. BF16\nrounding boundaries and recurrence arithmetic are preserved. State/history\nstores are omitted only when their exact bit patterns are unchanged.\n\"\"\"\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\n\[email protected]\ndef _or_combine(a, b):\n return a | b\n\n\[email protected]\ndef _coefficients(ba, a_log, dt_bias, token, head, V_HEADS: gl.constexpr):\n a = gl.load(ba + token * 2 * V_HEADS + V_HEADS + head).to(gl.float32)\n b = gl.load(ba + token * 2 * V_HEADS + head).to(gl.float32)\n bias = gl.load(dt_bias + head).to(gl.float32)\n al = gl.load(a_log + head)\n x = a + bias\n softplus = gl.where(x <= 20.0, gl.log(1.0 + gl.exp(x)), x)\n decay = gl.exp(-gl.exp(al) * softplus)\n beta = (1.0 / (1.0 + gl.exp(-b))).to(gl.bfloat16).to(gl.float32)\n return decay, beta\n\n\[email protected]\ndef _group_convolve(projected, history, weight, token, slot, key_head, scale,\n CHANNELS: gl.constexpr, WIDTH: gl.constexpr,\n K_HEADS: gl.constexpr, RATIO: gl.constexpr,\n DIM: gl.constexpr, WARPS: gl.constexpr,\n PACKED: gl.constexpr):\n # Eight complete wave-local heads; the last two are masked. Every physical\n # history word has one owner, including with 16 waves and 64 lanes.\n layout: gl.constexpr = gl.BlockedLayout([2], [64], [WARPS], [0])\n BLOCK: gl.constexpr = 8 * DIM\n xidx = gl.arange(0, BLOCK, layout=layout)\n r = xidx // DIM\n channel = gl.where(r < 2, (r * K_HEADS + key_head) * DIM + xidx % DIM,\n (2 * K_HEADS + key_head * RATIO + r - 2) * DIM + xidx % DIM)\n live = r < 2 + RATIO\n # With WARPS > 8, duplicates need an explicit ordering before any history\n # overwrite. The 8-wave specialization has no replicated global reads.\n if PACKED:\n pl: gl.constexpr = gl.BlockedLayout([1], [64], [WARPS], [0])\n pair_idx = gl.arange(0, BLOCK // 2, layout=pl)\n pr = pair_idx // (DIM // 2)\n pair = gl.where(pr < 2, (pr * K_HEADS + key_head) * (DIM // 2) + pair_idx % (DIM // 2),\n (2 * K_HEADS + key_head * RATIO + pr - 2) * (DIM // 2) + pair_idx % (DIM // 2))\n hp = history.to(gl.pointer_type(gl.uint32)) + slot * CHANNELS * 3 // 2 + pair * 3\n h01 = gl.load(hp, pr < 2 + RATIO, 0)\n h20 = gl.load(hp + 1, pr < 2 + RATIO, 0)\n h12 = gl.load(hp + 2, pr < 2 + RATIO, 0)\n h0 = gl.reshape(gl.join(h01.to(gl.uint16), (h20 >> 16).to(gl.uint16)), (BLOCK,)).to(gl.bfloat16, bitcast=True)\n h1 = gl.reshape(gl.join((h01 >> 16).to(gl.uint16), h12.to(gl.uint16)), (BLOCK,)).to(gl.bfloat16, bitcast=True)\n h2 = gl.reshape(gl.join(h20.to(gl.uint16), (h12 >> 16).to(gl.uint16)), (BLOCK,)).to(gl.bfloat16, bitcast=True)\n h0 = gl.convert_layout(h0, layout)\n h1 = gl.convert_layout(h1, layout)\n h2 = gl.convert_layout(h2, layout)\n else:\n hp = history + (slot * CHANNELS + channel) * 3\n h0 = gl.load(hp, live, 0)\n h1 = gl.load(hp + 1, live, 0)\n h2 = gl.load(hp + 2, live, 0)\n x = gl.load(projected + token * WIDTH + channel, live, 0)\n w = gl.load(weight.to(gl.pointer_type(gl.uint64)) + channel, live, 0)\n w0 = w.to(gl.uint16).to(gl.bfloat16, bitcast=True)\n w1 = (w >> 16).to(gl.uint16).to(gl.bfloat16, bitcast=True)\n w2 = (w >> 32).to(gl.uint16).to(gl.bfloat16, bitcast=True)\n w3 = (w >> 48).to(gl.uint16).to(gl.bfloat16, bitcast=True)\n acc = gl.full((BLOCK,), 0.0, gl.float32, layout)\n acc += (h0 * w0).to(gl.float32)\n acc += (h1 * w1).to(gl.float32)\n acc += (h2 * w2).to(gl.float32)\n acc += (x * w3).to(gl.float32)\n value = (acc / (1.0 + gl.exp(-acc))).to(gl.bfloat16).to(gl.float32)\n if WARPS > 8:\n gl.barrier()\n if PACKED:\n x0, x1 = gl.split(gl.reshape(x.to(gl.bfloat16).to(gl.uint16, bitcast=True), (BLOCK // 2, 2)))\n x0 = gl.convert_layout(x0, pl).to(gl.uint32)\n x1 = gl.convert_layout(x1, pl).to(gl.uint32)\n next01 = (h01 >> 16) | (h20 << 16)\n next20 = x0 | (h12 << 16)\n next12 = (h12 >> 16) | (x1 << 16)\n gl.store(hp, next01, (pr < 2 + RATIO) & (next01 != h01))\n gl.store(hp + 1, next20, (pr < 2 + RATIO) & (next20 != h20))\n gl.store(hp + 2, next12, (pr < 2 + RATIO) & (next12 != h12))\n else:\n gl.store(hp, h1, live & (h1.to(gl.uint16, bitcast=True) != h0.to(gl.uint16, bitcast=True)))\n gl.store(hp + 1, h2, live & (h2.to(gl.uint16, bitcast=True) != h1.to(gl.uint16, bitcast=True)))\n gl.store(hp + 2, x, live & (x.to(gl.uint16, bitcast=True) != h2.to(gl.uint16, bitcast=True)))\n rows = gl.reshape(value, (8, DIM))\n normalized = rows / gl.sqrt(gl.sum(rows * rows, 1) + 1.e-6)[:, None]\n norm = gl.reshape(normalized, (BLOCK,))\n norm = gl.where(r == 0, norm * scale, norm)\n return gl.where(r < 2, norm, value)\n\n\[email protected]\ndef _load_state_tile(state_base, offsets, head, tile, CACHE: gl.constexpr, STREAM: gl.constexpr):\n # Cache admission is fixed by the batch specialization, not by state values.\n if CACHE == 0:\n state = gl.amd.cdna4.buffer_load(state_base, offsets, cache=STREAM)\n elif CACHE == 4:\n if head % 4 == 0:\n state = gl.amd.cdna4.buffer_load(state_base, offsets, cache=\".ca\")\n else:\n state = gl.amd.cdna4.buffer_load(state_base, offsets, cache=STREAM)\n else:\n if tile % 2 == 0:\n state = gl.amd.cdna4.buffer_load(state_base, offsets, cache=\".ca\")\n else:\n state = gl.amd.cdna4.buffer_load(state_base, offsets, cache=STREAM)\n return state\n\n\[email protected]\ndef _fused_pipeline(projected, ba, history, state_pool, indices, conv_weight,\n a_log, dt_bias, norm_weight, output, scale, eps,\n CHANNELS: gl.constexpr, WIDTH: gl.constexpr,\n K_HEADS: gl.constexpr, V_HEADS: gl.constexpr, DIM: gl.constexpr,\n TILE: gl.constexpr, WARPS: gl.constexpr, TOKEN_GROUP: gl.constexpr,\n CACHE: gl.constexpr, STREAM: gl.constexpr, GRAN: gl.constexpr,\n PACKED: gl.constexpr, OUT_SPT: gl.constexpr,\n UNROLL: gl.constexpr, LATE_WEIGHT: gl.constexpr,\n TOKENS: gl.constexpr, STRIDE: gl.constexpr, EARLY_GATE: gl.constexpr,\n SPT: gl.constexpr, LANES: gl.constexpr, ROW_SPT: gl.constexpr, CROSS_HEAD: gl.constexpr, LOOKAHEAD: gl.constexpr, PREFETCH_CONV: gl.constexpr):\n p = gl.program_id(0).to(gl.uint32)\n token = p // (TOKEN_GROUP * K_HEADS) * TOKEN_GROUP + p % TOKEN_GROUP\n kh = p // TOKEN_GROUP % K_HEADS\n if STRIDE != 1:\n token = (token * STRIDE) % TOKENS\n slot = gl.load(indices + token).to(gl.int64)\n RATIO: gl.constexpr = V_HEADS // K_HEADS\n layout: gl.constexpr = gl.BlockedLayout([ROW_SPT, SPT], [64 // LANES, LANES], [WARPS, 1], [1, 0])\n kk = gl.arange(0, DIM, layout=gl.SliceLayout(0, layout))\n row = gl.arange(0, TILE, layout=gl.SliceLayout(1, layout))\n full: gl.constexpr = gl.BlockedLayout([OUT_SPT], [64], [WARPS], [0])\n col = gl.arange(0, DIM, layout=full)\n if not LATE_WEIGHT:\n weight = gl.load(norm_weight + col).to(gl.float32)\n if slot >= 0:\n first_offsets = row[:, None] * DIM + kk[None, :]\n first_base = state_pool + (slot * V_HEADS + kh * RATIO) * DIM * DIM\n if PREFETCH_CONV:\n state_look = _load_state_tile(first_base, first_offsets, kh * RATIO, 0, CACHE, STREAM)\n conv = _group_convolve(projected, history, conv_weight, token, slot, kh, scale,\n CHANNELS, WIDTH, K_HEADS, RATIO, DIM, WARPS, PACKED)\n buf = gl.allocate_shared_memory(gl.float32, (8 * DIM,), gl.SwizzledSharedLayout(1, 1, 1, [0]), conv)\n if not PREFETCH_CONV:\n state_look = _load_state_tile(first_base, first_offsets, kh * RATIO, 0, CACHE, STREAM)\n q = buf.slice(0, DIM).load(gl.SliceLayout(0, layout))\n k = buf.slice(DIM, DIM).load(gl.SliceLayout(0, layout))\n projections = gl.allocate_shared_memory(gl.bfloat16, (DIM,), gl.SwizzledSharedLayout(1, 1, 1, [0]))\n for h_base in range(0, RATIO, UNROLL):\n for h_inner in gl.static_range(UNROLL):\n h = h_base + h_inner\n head = kh * RATIO + h\n if EARLY_GATE:\n gate = gl.load(projected + token * WIDTH + CHANNELS + head * DIM + col).to(gl.float32)\n gate = gate * (1.0 / (1.0 + gl.exp(-gate)))\n decay, beta = _coefficients(ba, a_log, dt_bias, token, head, V_HEADS)\n state_base = state_pool + (slot * V_HEADS + head) * DIM * DIM\n if LOOKAHEAD and not CROSS_HEAD and h != 0:\n state_look = _load_state_tile(state_base, first_offsets, head, 0, CACHE, STREAM)\n for tile in gl.static_range(DIM // TILE):\n vv = tile * TILE + row\n offsets = vv[:, None] * DIM + kk[None, :]\n if LOOKAHEAD or (tile == 0 and (CROSS_HEAD or h == 0)):\n state = state_look\n else:\n state = _load_state_tile(state_base, offsets, head, tile, CACHE, STREAM)\n if LOOKAHEAD and tile + 1 < DIM // TILE:\n state_look = _load_state_tile(state_base, offsets + TILE * DIM, head, tile + 1, CACHE, STREAM)\n if CROSS_HEAD and tile == DIM // TILE - 1:\n if h + 1 < RATIO:\n next_base = state_pool + (slot * V_HEADS + head + 1) * DIM * DIM\n state_look = _load_state_tile(next_base, first_offsets, head + 1, 0, CACHE, STREAM)\n v = buf.gather((2 + h) * DIM + tile * TILE + row, 0)\n old = state\n state *= decay\n v -= gl.sum(state * k[None, :], 1)\n v *= beta\n state += v[:, None] * k[None, :]\n changed = old.to(gl.uint32, bitcast=True) ^ state.to(gl.uint32, bitcast=True)\n group_changed = gl.reduce(gl.reshape(changed, (TILE, DIM // GRAN, GRAN)), 2, _or_combine) != 0\n changed_mask = gl.reshape(gl.broadcast(group_changed[:, :, None], gl.reshape(changed, (TILE, DIM // GRAN, GRAN)))[0], (TILE, DIM))\n gl.amd.cdna4.buffer_store(state, state_base, offsets, changed_mask, cache=\".wt\")\n core = gl.sum(state * q[None, :], 1).to(gl.bfloat16)\n projections.slice(tile * TILE, TILE).store(core)\n core = projections.load(full).to(gl.float32)\n if LATE_WEIGHT:\n weight = gl.load(norm_weight + col).to(gl.float32)\n if not EARLY_GATE:\n gate = gl.load(projected + token * WIDTH + CHANNELS + head * DIM + col).to(gl.float32)\n gate = gate * (1.0 / (1.0 + gl.exp(-gate)))\n variance = gl.sum(core * core, 0) / DIM\n core = core * gl.rsqrt(variance + eps)\n core *= weight\n core *= gate\n gl.store(output + (token * V_HEADS + head) * DIM + col, core)\n else:\n for h in gl.static_range(RATIO):\n head = kh * RATIO + h\n gate = gl.load(projected + token * WIDTH + CHANNELS + head * DIM + col).to(gl.float32)\n gate = gate * (1.0 / (1.0 + gl.exp(-gate)))\n if LATE_WEIGHT:\n weight = gl.load(norm_weight + col).to(gl.float32)\n core = gl.full((DIM,), 0.0, gl.float32, full)\n core = core * gl.rsqrt(eps)\n core *= weight\n core *= gate\n gl.store(output + (token * V_HEADS + head) * DIM + col, core)\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *,\n scale: float,\n eps: float,\n output: torch.Tensor,\n) -> None:\n tokens, width = projected_qkvz.shape\n _, v_heads, dim, _ = delta_state.shape\n channels = width - v_heads * dim\n k_heads = (channels - v_heads * dim) // (2 * dim)\n warps = 8\n group = {128: 8, 136: 8, 192: 4, 256: 32}.get(tokens, 1)\n stride = {128: 5, 136: 3, 192: 5}.get(tokens, 1)\n _fused_pipeline[(tokens * k_heads,)](\n projected_qkvz, projected_ba, conv_state, delta_state, cache_indices,\n conv_weight, a_log, dt_bias, norm_weight, output, scale, eps,\n channels, width, k_heads, v_heads, dim,\n TILE=64 if tokens == 256 else 32, WARPS=warps, TOKEN_GROUP=group,\n CACHE=4 if tokens < 192 else 5,\n STREAM=\".cv\" if tokens < 192 else \".cg\", GRAN=8,\n PACKED=True, OUT_SPT=2 if tokens in (136, 192) else 1,\n UNROLL=4, LATE_WEIGHT=True, TOKENS=tokens, STRIDE=stride,\n EARLY_GATE=tokens != 256, SPT=4, LANES=16,\n ROW_SPT=1, CROSS_HEAD=tokens == 256, LOOKAHEAD=tokens >= 192,\n PREFETCH_CONV=tokens == 192,\n num_warps=warps, waves_per_eu=0,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n output=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 32 rows.\n\nBatch-specialized MI355 GDN decode, with exact state and BF16 boundaries.\n\nGeometry: four Q/K heads, sixteen V heads, and 128 channels per head.\nB16 uses full-state recurrence, producer-side gates, and exact assembly-assisted\nfour-word dirty predicates. B32/B96 stream two 64-row state tiles per head;\nB32 uses compact planar scratch and eight-token workgroup groups. B96 uses\nhead-major Q/K/V records with a 1024-word pitch to improve scratch locality.\nB64 fuses four value heads sharing Q/K into one CTA, streaming 32 state rows\nat a time. Its 256 CTAs avoid the scheduling tail that this grouping has at\nB96. B96 uses a two-stage path with per-head global-load base pointers\nand direct BF16 LDS readout staging. B64 overlaps its initial state load\nwith coefficient evaluation and loads gates before the final state tile.\n\nEvery invocation uses the live slot map. Negative slots produce zero output\nwithout touching state. Dirty predicates compare every bit in each group;\nthey only suppress writes that would leave the state unchanged.\n\"\"\"\n\nfrom typing import NamedTuple\n\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\nclass _Schedule(NamedTuple):\n \"\"\"Independent tuning knobs for the two-kernel path; pitches are FP32 words.\"\"\"\n rows: int\n row_pack: int\n columns: int\n scratch_words: int\n load_cache: str\n store_cache: str\n dirty_words: int\n flat_grid: bool = False\n pregate: bool = False\n asm_dirty: bool = False\n readout_first: bool = True\n global_loads: bool = False\n token_group: int = 0\n waves: int = 0\n head_record: int = 0\n\n\n_SCHEDULES = {\n 16: _Schedule(\n rows=128, row_pack=1, columns=8, scratch_words=4096,\n load_cache=\".cv\", store_cache=\".wb\", dirty_words=4,\n flat_grid=True, pregate=True, asm_dirty=True, readout_first=False,\n ),\n 32: _Schedule(\n rows=64, row_pack=2, columns=16, scratch_words=2048,\n load_cache=\".cv\", store_cache=\".wt\", dirty_words=4,\n token_group=8, waves=2,\n ),\n 96: _Schedule(\n rows=64, row_pack=2, columns=16, scratch_words=4096,\n load_cache=\".cg\", store_cache=\".wb\", dirty_words=16,\n global_loads=True, head_record=1024,\n ),\n}\n\n\[email protected]\ndef _bf16_low(x):\n return x.to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _bf16_high(x):\n return (x >> 16).to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _conv4(h0, h1, h2, x, w0, w1, w2, w3):\n # Each convolution product rounds to BF16 before the FP32 sum.\n y = (h0 * w0).to(gl.bfloat16).to(gl.float32)\n y += (h1 * w1).to(gl.bfloat16).to(gl.float32)\n y += (h2 * w2).to(gl.bfloat16).to(gl.float32)\n y += (x * w3).to(gl.bfloat16).to(gl.float32)\n return (y / (1.0 + gl.exp(-y))).to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _convolve_packed(\n h0, h1, h2, x, w0, w1, w2, w3,\n JOIN: gl.constexpr, OUTPUT: gl.constexpr,\n):\n \"\"\"Two BF16 channels packed into three history and four weight words.\"\"\"\n ya = _conv4(\n _bf16_low(h0),\n _bf16_high(h0),\n _bf16_low(h1),\n _bf16_low(x),\n _bf16_low(w0),\n _bf16_high(w0),\n _bf16_low(w1),\n _bf16_high(w1),\n )\n yb = _conv4(\n _bf16_high(h1),\n _bf16_low(h2),\n _bf16_high(h2),\n _bf16_high(x),\n _bf16_low(w2),\n _bf16_high(w2),\n _bf16_low(w3),\n _bf16_high(w3),\n )\n ya = gl.convert_layout(ya, gl.SliceLayout(2, JOIN))\n yb = gl.convert_layout(yb, gl.SliceLayout(2, JOIN))\n y = gl.join(ya, yb).reshape((h0.shape[0], 2 * h0.shape[1]))\n return gl.convert_layout(y, OUTPUT)\n\n\[email protected]\ndef _next_history(h0, h1, h2, x):\n # [a0,a1,a2,b0,b1,b2] -> [a1,a2,xa,b1,b2,xb], packed two BF16s per word.\n n0 = (h0 >> 16) | (h1 << 16)\n n1 = (x & 0xFFFF) | (h2 << 16)\n n2 = (h2 >> 16) | (x & 0xFFFF0000)\n return n0, n1, n2, (n0 != h0) | (n1 != h1) | (n2 != h2)\n\n\[email protected]\ndef _scratch_row(C, token, QK: gl.constexpr, STRIDE: gl.constexpr):\n # Planar records contain Q/K FP32 followed by V BF16.\n # Pregated records append 2048 FP32 gate values after the first 2048 words.\n qk = C + token * STRIDE\n return qk, (qk + QK).to(gl.pointer_type(gl.bfloat16))\n\n\[email protected]\ndef _packed_conv(\n QKVZ,\n CS,\n IDX,\n W,\n C,\n scale,\n P: gl.constexpr,\n TOKENS: gl.constexpr,\n):\n CHANNELS: gl.constexpr = 3072\n WIDTH: gl.constexpr = 5120\n K: gl.constexpr = 128\n KH: gl.constexpr = 4\n TC: gl.constexpr = 4\n gl.static_assert(P.scratch_words >= (4096 if P.pregate else 2048))\n token = gl.program_id(0)\n group = gl.program_id(1)\n L: gl.constexpr = gl.BlockedLayout([1, 1], [1, 64], [TC, 1], [1, 0])\n JO: gl.constexpr = gl.BlockedLayout([1, 1, 2], [1, 64, 1], [TC, 1, 1], [1, 0, 2])\n O: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [TC, 1], [1, 0])\n tile = group * TC + gl.arange(0, TC, gl.SliceLayout(1, L))\n pair = gl.arange(0, K // 2, gl.SliceLayout(0, L))\n pidx = tile[:, None] * (K // 2) + pair[None, :]\n slot = gl.load(IDX + token).to(gl.int64)\n if slot >= 0:\n hist = CS.to(gl.pointer_type(gl.uint32)) + (slot * (CHANNELS // 2) + pidx) * 3\n h0 = gl.load(hist)\n h1 = gl.load(hist + 1)\n h2 = gl.load(hist + 2)\n x = gl.load(QKVZ.to(gl.pointer_type(gl.uint32)) + token * (WIDTH // 2) + pidx)\n wp = W.to(gl.pointer_type(gl.uint32)) + pidx * 4\n w0 = gl.load(wp)\n w1 = gl.load(wp + 1)\n w2 = gl.load(wp + 2)\n w3 = gl.load(wp + 3)\n y = _convolve_packed(h0, h1, h2, x, w0, w1, w2, w3, JO, O)\n ot = group * TC + gl.arange(0, TC, gl.SliceLayout(1, O))\n if group * TC < 2 * KH:\n y = y / gl.sqrt(gl.sum(y * y, 1)[:, None] + 1.0e-6)\n y = gl.where(ot[:, None] < KH, y * scale, y)\n n0, n1, n2, dirty = _next_history(h0, h1, h2, x)\n ki = gl.arange(0, K, gl.SliceLayout(0, O))\n cp, vp = _scratch_row(C, token, 2 * KH * K, P.scratch_words)\n if group * TC < 2 * KH:\n if P.head_record:\n # Head-major records match the head-major recurrent launch.\n offset = (ot[:, None] % KH) * (TOKENS * P.head_record)\n offset += token * P.head_record\n offset += gl.where(ot[:, None] < KH, 0, K)\n gl.store(C + offset + ki[None, :], y)\n else:\n gl.store(cp + ot[:, None] * K + ki[None, :], y)\n else:\n if P.head_record:\n hv = ot[:, None] - 2 * KH\n offset = (hv // 4) * (2 * TOKENS * P.head_record)\n offset += token * (2 * P.head_record) + 4 * K + (hv % 4) * K\n gl.store(C.to(gl.pointer_type(gl.bfloat16)) + offset + ki[None, :], y)\n else:\n gl.store(vp + (ot[:, None] - 2 * KH) * K + ki[None, :], y)\n if P.pregate:\n if group * TC >= 2 * KH:\n head = ot - 2 * KH\n z = gl.load(\n QKVZ + token * WIDTH + CHANNELS + head[:, None] * K + ki[None, :]\n ).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(cp + 2048 + head[:, None] * K + ki[None, :], gate)\n # Commit history after the producer record is complete.\n gl.store(hist, n0, dirty)\n gl.store(hist + 1, n1, dirty)\n gl.store(hist + 2, n2, dirty)\n\n\[email protected]\ndef _load_gate(QKVZ, W, C, token, head, E: gl.constexpr, P: gl.constexpr):\n eo = gl.arange(0, 128, E)\n if P.pregate:\n gate = gl.load(C + token * P.scratch_words + 2048 + head * 128 + eo)\n else:\n z = gl.load(QKVZ + token * 5120 + 3072 + head * 128 + eo).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n w = gl.load(W + eo).to(gl.float32)\n return gate, w\n\n\[email protected]\ndef _gated_rms(core, gate, weight, eps: gl.constexpr):\n axis: gl.constexpr = len(core.shape) - 1\n r = gl.rsqrt(gl.sum(core * core, axis) / 128 + eps)\n if axis > 0:\n r = gl.expand_dims(r, axis)\n y = core * r\n y *= weight\n y *= gate\n return y\n\n\[email protected]\ndef _store_changed_state(\n DS,\n offsets,\n old_bits,\n state,\n CACHE: gl.constexpr,\n WORDS: gl.constexpr,\n ASM_DIRTY: gl.constexpr = False,\n):\n \"\"\"Skip a group only when every old and new FP32 bit pattern matches.\"\"\"\n gl.static_assert(WORDS >= 2 and 128 % WORDS == 0)\n rows: gl.constexpr = state.numel // 128\n state = state.reshape((rows, 128))\n offsets = offsets.reshape((rows, 128))\n old_bits = old_bits.reshape((rows, 128))\n new_bits = state.to(gl.uint32, bitcast=True)\n ol, oh = gl.split(old_bits.reshape((rows, 64, 2)))\n nl, nh = gl.split(new_bits.reshape((rows, 64, 2)))\n old_pairs = ol.to(gl.uint64) | (oh.to(gl.uint64) << 32)\n new_pairs = nl.to(gl.uint64) | (nh.to(gl.uint64) << 32)\n if ASM_DIRTY:\n # Two exact 64-bit comparisons cover each lane's four adjacent words.\n # Early-clobber prevents the predicate result from aliasing a live pair.\n gl.static_assert(WORDS == 4)\n op0, op1 = gl.split(old_pairs.reshape((rows, 32, 2)))\n np0, np1 = gl.split(new_pairs.reshape((rows, 32, 2)))\n dirty = gl.inline_asm_elementwise(\n \"v_cmp_ne_u64_e64 vcc, $1, $3\\n\"\n \"v_cndmask_b32 $0, 0, 1, vcc\\n\"\n \"v_cmp_ne_u64_e64 vcc, $2, $4\\n\"\n \"v_cndmask_b32 $0, $0, 1, vcc\",\n \"=&v,v,v,v,v,~{vcc}\",\n [op0, op1, np0, np1],\n dtype=gl.int32,\n is_pure=True,\n pack=1,\n ) != 0\n else:\n dirty = gl.max(\n (old_pairs != new_pairs)\n .reshape((rows, 128 // WORDS, WORDS // 2)).to(gl.int32), 2\n ) != 0\n groups = old_bits.reshape((rows, 128 // WORDS, WORDS))\n dirty = gl.convert_layout(dirty, gl.SliceLayout(2, groups.type.layout))\n mask, _ = gl.broadcast(dirty[:, :, None], groups)\n gl.amd.cdna3.buffer_store(\n state, DS, offsets, mask.reshape((rows, 128)), cache=CACHE\n )\n\n\[email protected]\ndef _advance_state(\n DS, offsets, state, q, k, v, decay, beta,\n READOUT_FIRST: gl.constexpr,\n STORE_CACHE: gl.constexpr,\n DIRTY_WORDS: gl.constexpr,\n ASM_DIRTY: gl.constexpr = False,\n):\n \"\"\"Q/K and decay are broadcast over state; the final axis is always K.\"\"\"\n axis: gl.constexpr = len(state.shape) - 1\n old_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v -= gl.sum(state * k, axis)\n v *= beta\n state += gl.expand_dims(v, axis) * k\n if READOUT_FIRST:\n core = gl.sum(state * q, axis).to(gl.bfloat16)\n _store_changed_state(\n DS, offsets, old_bits, state, STORE_CACHE, DIRTY_WORDS, ASM_DIRTY\n )\n if not READOUT_FIRST:\n core = gl.sum(state * q, axis).to(gl.bfloat16)\n return core\n\n\[email protected]\ndef _recurrent(\n C,\n BA,\n AL,\n DT,\n DS,\n IDX,\n OUT,\n QKVZ,\n W,\n eps: gl.constexpr,\n TOKENS: gl.constexpr,\n P: gl.constexpr,\n):\n ROWS: gl.constexpr = P.rows\n th = gl.program_id(0).to(gl.uint32)\n # Both grids are head-major. The flat B16 mapping keeps address lowering\n # bounded; an equivalent two-dimensional launch is slower on MI355.\n if P.token_group:\n # Tile the head-major grid across a small batch group. The map is a\n # bijection, so each invocation still owns exactly one token/head pair.\n token = (th // (16 * P.token_group)) * P.token_group + th % P.token_group\n head = (th // P.token_group) % 16\n elif P.flat_grid:\n token = (th // (16 * TOKENS)) * TOKENS + th % TOKENS\n head = (th % (16 * TOKENS)) // TOKENS\n else:\n token = th\n head = gl.program_id(1).to(gl.uint32)\n th = token * 16 + head\n kh = head // 4\n COLS: gl.constexpr = P.columns\n L: gl.constexpr = gl.BlockedLayout(\n [P.row_pack, 4], [64 // COLS, COLS], [4, 1], [1, 0]\n )\n gl.static_assert(ROWS == 64 or ROWS == 128)\n gl.static_assert(P.row_pack * (64 // COLS) * 4 <= ROWS)\n E: gl.constexpr = gl.BlockedLayout([2], [64], [4], [0])\n ko = gl.arange(0, 128, gl.SliceLayout(0, L))\n vo = gl.arange(0, ROWS, gl.SliceLayout(1, L))\n slot = gl.load(IDX + token)\n if slot < 0:\n zero = gl.full((ROWS,), 0, gl.float32, gl.SliceLayout(1, L))\n gl.store(OUT + th * 128 + vo, zero)\n if ROWS == 64:\n gl.store(OUT + th * 128 + 64 + vo, zero)\n else:\n so = vo[:, None] * 128 + ko[None, :]\n if P.global_loads:\n # Per-head address base for global reads; writes stay bit-exact.\n state_base = DS + slot * 262144 + head * 16384\n state = gl.load(state_base + so, cache_modifier=P.load_cache)\n else:\n state_base = DS\n so += slot * 262144 + head * 16384\n state = gl.amd.cdna3.buffer_load(state_base, so, cache=P.load_cache)\n cp, vp = _scratch_row(C, token, 1024, P.scratch_words)\n if P.head_record:\n qp = C + kh * (TOKENS * P.head_record) + token * P.head_record\n q = gl.load(qp + ko)\n k = gl.load(qp + 128 + ko)\n vp = (qp + 256).to(gl.pointer_type(gl.bfloat16)) + (head % 4) * 128\n else:\n q = gl.load(cp + kh * 128 + ko)\n k = gl.load(cp + 512 + kh * 128 + ko)\n vp += head * 128\n v = gl.load(vp + vo).to(gl.float32)\n a = gl.load(BA + token * 32 + 16 + head).to(gl.float32)\n b = gl.load(BA + token * 32 + head).to(gl.float32)\n al = gl.load(AL + head)\n dt = gl.load(DT + head).to(gl.float32)\n x = a + dt\n sp = gl.where(x <= 20.0, gl.log(1.0 + gl.exp(x)), x)\n decay_log = -gl.exp(al) * sp\n beta = (1.0 / (1.0 + gl.exp(-b))).to(BA.dtype.element_ty).to(gl.float32)\n decay = gl.exp(decay_log)\n if ROWS == 128:\n gate, w = _load_gate(QKVZ, W, C, token, head, E, P)\n core = _advance_state(\n state_base,\n so,\n state,\n q[None, :],\n k[None, :],\n v,\n decay,\n beta,\n P.readout_first,\n P.store_cache,\n P.dirty_words,\n P.asm_dirty,\n )\n if ROWS == 64:\n if P.head_record:\n # Preserve the BF16 boundary while avoiding a register transpose.\n readout = gl.allocate_shared_memory(\n gl.bfloat16, [128], gl.SwizzledSharedLayout(1, 1, 1, [0])\n )\n readout.slice(0, 64, 0).store(core)\n gate, w = _load_gate(QKVZ, W, C, token, head, E, P)\n so += 8192\n if P.global_loads:\n state = gl.load(state_base + so, cache_modifier=P.load_cache)\n else:\n state = gl.amd.cdna3.buffer_load(state_base, so, cache=P.load_cache)\n v = gl.load(vp + 64 + vo).to(gl.float32)\n core1 = _advance_state(\n state_base, so, state, q[None, :], k[None, :], v, decay, beta,\n P.readout_first, P.store_cache, P.dirty_words, P.asm_dirty,\n )\n if P.head_record:\n readout.slice(64, 64, 0).store(core1)\n core = readout.load(E)\n else:\n core = gl.join(core, core1).trans(1, 0).reshape((128,))\n core = gl.convert_layout(core, gl.SliceLayout(1, L))\n core = gl.convert_layout(core.to(gl.float32), E)\n eo = gl.arange(0, 128, E)\n y = _gated_rms(core, gate, w, eps)\n gl.store(OUT + th * 128 + eo, y)\n\n\[email protected]\ndef _grouped_fused64(\n QKVZ, BA, CS, DS, IDX, CW, AL, DT, W, OUT, scale: gl.constexpr, eps: gl.constexpr\n):\n # A CTA exclusively owns one Q/K pair, four V histories, and four states.\n token = gl.program_id(0)\n kh = gl.program_id(1)\n ROWS: gl.constexpr = 32\n NW: gl.constexpr = 8\n COLS: gl.constexpr = 8\n RP: gl.constexpr = 1\n P: gl.constexpr = gl.BlockedLayout([1, 1], [1, 64], [NW, 1], [1, 0])\n J: gl.constexpr = gl.BlockedLayout([1, 1, 2], [1, 64, 1], [NW, 1, 1], [1, 0, 2])\n O: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [NW, 1], [1, 0])\n L: gl.constexpr = gl.BlockedLayout(\n [1, RP, 4], [1, 64 // COLS, COLS], [4, NW // 4, 1], [2, 1, 0]\n )\n H: gl.constexpr = gl.SliceLayout(1, gl.SliceLayout(2, L))\n K: gl.constexpr = gl.SliceLayout(0, gl.SliceLayout(1, L))\n V: gl.constexpr = gl.SliceLayout(2, L)\n E: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [4, NW // 4], [1, 0])\n heads = kh * 4 + gl.arange(0, 4, H)\n eo = gl.arange(0, 128, gl.SliceLayout(0, E))\n eh = kh * 4 + gl.arange(0, 4, gl.SliceLayout(1, E))\n slot = gl.load(IDX + token)\n if slot < 0:\n gl.store(\n OUT + token * 2048 + eh[:, None] * 128 + eo[None, :],\n gl.full((4, 128), 0, gl.bfloat16, E),\n )\n else:\n ch = gl.arange(0, 8, gl.SliceLayout(1, P))\n tile = gl.where(ch < 4, 8 + kh * 4 + ch, gl.where(ch % 2 == 0, kh, 4 + kh))\n pair = gl.arange(0, 64, gl.SliceLayout(0, P))\n pidx = tile[:, None] * 64 + pair[None, :]\n hist = CS.to(gl.pointer_type(gl.uint32)) + (slot.to(gl.int64) * 1536 + pidx) * 3\n mask = (ch[:, None] < 4) | (ch[:, None] >= 6)\n wp = CW.to(gl.pointer_type(gl.uint32)) + pidx * 4\n # The two unused waves read immutable weights as dummy history. This\n # permits vectorized unconditional loads without reading another wave's\n # concurrently updated history. Their LDS rows are never consumed.\n read_hist = gl.where(mask, hist, wp)\n h0 = gl.load(read_hist)\n h1 = gl.load(read_hist + 1)\n h2 = gl.load(read_hist + 2)\n x = gl.load(QKVZ.to(gl.pointer_type(gl.uint32)) + token * 2560 + pidx)\n w0 = gl.load(wp)\n w1 = gl.load(wp + 1)\n w2 = gl.load(wp + 2)\n w3 = gl.load(wp + 3)\n y = _convolve_packed(h0, h1, h2, x, w0, w1, w2, w3, J, O)\n cy = gl.arange(0, 8, gl.SliceLayout(1, O))\n normalized = y / gl.sqrt(gl.sum(y * y, 1)[:, None] + 1.0e-6)\n normalized = gl.where(cy[:, None] == 6, normalized * scale, normalized)\n y = gl.where(cy[:, None] >= 6, normalized, y)\n # V0..V3 occupy rows 0..3, Q/K occupy rows 6/7; 4/5 are padding.\n sm = gl.allocate_shared_memory(\n gl.float32, [8, 128], gl.SwizzledSharedLayout(1, 1, 1, [1, 0]), y\n )\n n0, n1, n2, dirty = _next_history(h0, h1, h2, x)\n dirty = mask & dirty\n gl.store(hist, n0, dirty)\n gl.store(hist + 1, n1, dirty)\n gl.store(hist + 2, n2, dirty)\n q = sm.slice(6, 1, 0).load(gl.SliceLayout(1, L)).reshape((128,))\n q = gl.convert_layout(q, K)\n k = sm.slice(7, 1, 0).load(gl.SliceLayout(1, L)).reshape((128,))\n k = gl.convert_layout(k, K)\n ko = gl.arange(0, 128, K)\n vr = gl.arange(0, ROWS, gl.SliceLayout(0, V))\n first_offsets = (\n slot * 262144 + heads[:, None, None] * 16384\n + vr[None, :, None] * 128 + ko[None, None, :]\n )\n # Start state traffic before the independent coefficient arithmetic.\n first_state = gl.amd.cdna3.buffer_load(DS, first_offsets, cache=\".cg\")\n a = gl.load(BA + token * 32 + 16 + heads).to(gl.float32)\n b = gl.load(BA + token * 32 + heads).to(gl.float32)\n al = gl.load(AL + heads)\n dt = gl.load(DT + heads).to(gl.float32)\n sx = a + dt\n sp = gl.where(sx <= 20.0, gl.log(1.0 + gl.exp(sx)), sx)\n decay = gl.exp(-gl.exp(al) * sp)\n beta = (1.0 / (1.0 + gl.exp(-b))).to(gl.bfloat16).to(gl.float32)\n cores = gl.allocate_shared_memory(\n gl.bfloat16, [4, 128], gl.SwizzledSharedLayout(1, 1, 1, [1, 0])\n )\n # Synchronous LDS staging bounds state and readout register lifetimes.\n for chunk in gl.static_range(128 // ROWS):\n if chunk == 3:\n # Hide gate and norm-weight latency behind the final update.\n z = gl.load(QKVZ + token * 5120 + 3072 + eh[:, None] * 128 + eo[None, :]).to(\n gl.float32\n )\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n w = gl.load(W + eo).to(gl.float32)\n rows = chunk * ROWS + vr\n offsets = (\n slot * 262144\n + heads[:, None, None] * 16384\n + rows[None, :, None] * 128\n + ko[None, None, :]\n )\n if chunk == 0:\n state = first_state\n else:\n state = gl.amd.cdna3.buffer_load(DS, offsets, cache=\".cg\")\n v = sm.slice(0, 4, 0).slice(chunk * ROWS, ROWS, 1).load(V)\n core = _advance_state(\n DS, offsets, state, q[None, None, :], k[None, None, :], v,\n decay[:, None, None], beta[:, None], True, \".wb\", 16,\n )\n cores.slice(chunk * ROWS, ROWS, 1).store(core)\n core = cores.load(E).to(gl.float32)\n y = _gated_rms(core, gate, w[None, :], eps)\n gl.store(OUT + token * 2048 + eh[:, None] * 128 + eo[None, :], y)\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *,\n scale: float,\n eps: float,\n out: torch.Tensor,\n) -> None:\n tokens = projected_qkvz.shape[0]\n if tokens == 64:\n _grouped_fused64[(tokens, 4)](\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n out,\n scale,\n eps,\n num_warps=8,\n waves_per_eu=0,\n )\n return\n policy = _SCHEDULES[tokens]\n scratch_words = policy.scratch_words\n conv = torch.empty(\n (tokens, scratch_words), device=projected_qkvz.device, dtype=torch.float32\n )\n _packed_conv[(tokens, 6)](\n projected_qkvz,\n conv_state,\n cache_indices,\n conv_weight,\n conv,\n scale,\n P=policy,\n TOKENS=tokens,\n num_warps=4,\n )\n grid = (tokens * 16,) if policy.flat_grid or policy.token_group else (tokens, 16)\n _recurrent[grid](\n conv,\n projected_ba,\n a_log,\n dt_bias,\n delta_state,\n cache_indices,\n out,\n projected_qkvz,\n norm_weight,\n eps,\n TOKENS=tokens,\n P=policy,\n num_warps=4,\n waves_per_eu=policy.waves,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n out=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 1 row.\n\nTwo-launch Gluon GDN decode for MI355.\n\nThe launch boundary is the global history read/commit barrier. Both launches\nread live slot indices, including negative padding slots, on every replay.\nState stores are elided only when every updated FP32 bit in a 64-byte\nsegment matches the loaded state. B1/B2/B4 similarly omit unchanged history\nwrites. B8 uses a flat QKV producer and prefetches Q before store-mask\nreduction. All elision decisions preserve signed zeros and NaN payloads.\n\"\"\"\nfrom typing import NamedTuple\n\nimport torch\nimport triton\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\nclass _Schedule(NamedTuple):\n rows: int\n key_lanes: int\n warps: int\n query_mode: str\n history_chunk: int\n history_vector: int\n norm_vector: int\n state_store: str = \".cs\"\n wide_conv: bool = True\n state_group: int = 0\n history_mode: str = \"base\"\n state_load: str = \"\"\n pool_relative: bool = False\n flat_producer: bool = False\n early_query: bool = False\n waves_per_eu: int = 0\n\n\n_SCHEDULES = {\n 1: _Schedule(8, 16, 2, \"register\", 128, 1, 1,\n wide_conv=False, history_mode=\"linear_word\", state_group=16),\n 2: _Schedule(16, 16, 4, \"qkv_lds\", 128, 2, 1,\n history_mode=\"elide_quad\", state_group=16, state_load=\".cg\",\n pool_relative=True, waves_per_eu=4),\n 4: _Schedule(32, 8, 4, \"qkv_lds\", 256, 1, 2,\n state_store=\".wt\", state_group=16, history_mode=\"elide_word\"),\n 8: _Schedule(32, 8, 4, \"qkv_lds\", 256, 2, 2,\n state_store=\"\", state_group=16, state_load=\".cg\",\n flat_producer=True, early_query=True, waves_per_eu=2),\n}\n\n\[email protected]\ndef _exp(x):\n return gl.exp2(x * 1.4426950408889634)\n\n\[email protected]\ndef _or_bits(a, b):\n return a | b\n\n\[email protected]\ndef _convolve_read(\n X, History, Weight, token, slot, channel, valid,\n CHANNELS: gl.constexpr, Z_CHANNELS: gl.constexpr, WIDE: gl.constexpr,\n):\n if WIDE:\n hist = History + slot.to(gl.int64) * (CHANNELS * 3) + channel.to(gl.int64) * 3\n weight = Weight + channel.to(gl.int64) * 4\n xp = X + token.to(gl.int64) * (CHANNELS + Z_CHANNELS) + channel.to(gl.int64)\n else:\n hist = History + (slot * CHANNELS + channel) * 3\n weight = Weight + channel * 4\n xp = X + token * (CHANNELS + Z_CHANNELS) + channel\n x = gl.load(xp, valid, other=0)\n h0 = gl.load(hist, valid, other=0)\n h1 = gl.load(hist + 1, valid, other=0)\n h2 = gl.load(hist + 2, valid, other=0)\n w0 = gl.load(weight, valid, other=0)\n w1 = gl.load(weight + 1, valid, other=0)\n w2 = gl.load(weight + 2, valid, other=0)\n w3 = gl.load(weight + 3, valid, other=0)\n acc = gl.full(channel.shape, 0, gl.float32, channel.type.layout)\n acc += (h0.to(gl.float32) * w0.to(gl.float32)).to(gl.bfloat16)\n acc += (h1.to(gl.float32) * w1.to(gl.float32)).to(gl.bfloat16)\n acc += (h2.to(gl.float32) * w2.to(gl.float32)).to(gl.bfloat16)\n acc += (x.to(gl.float32) * w3.to(gl.float32)).to(gl.bfloat16)\n value = acc * (1.0 / (1.0 + _exp(-acc)))\n return value.to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _gate_values(BA, ALog, DtBias, token, head, VH: gl.constexpr):\n a = gl.load(BA + token * 2 * VH + VH + head).to(gl.float32)\n b = gl.load(BA + token * 2 * VH + head).to(gl.float32)\n a_log = gl.load(ALog + head)\n bias = gl.load(DtBias + head).to(gl.float32)\n softplus_in = a + bias\n softplus = gl.where(softplus_in <= 20.0, gl.log(1.0 + _exp(softplus_in)), softplus_in)\n decay = _exp(-_exp(a_log) * softplus)\n beta = (1.0 / (1.0 + _exp(-b))).to(gl.bfloat16).to(gl.float32)\n return decay, beta\n\n\[email protected]\ndef _normalize_columns(values):\n invnorm = 1.0 / gl.sqrt(gl.sum(values * values, 0) + 1e-06)\n return values * invnorm[None, :]\n\n\[email protected]\ndef _stage_columns(values):\n SIZE: gl.constexpr = values.shape[0] * values.shape[1]\n return gl.allocate_shared_memory(\n gl.float32, (SIZE,), gl.SwizzledSharedLayout(1, 1, 1, [0]),\n values.permute((1, 0)).reshape((SIZE,)))\n\n\[email protected]\ndef _prepare_tiled_qkv(\n X, BA, History, Weight, ALog, DtBias, token, slot, head, vidx, vmask, scale,\n KH: gl.constexpr, VH: gl.constexpr, K: gl.constexpr, V: gl.constexpr,\n BK: gl.constexpr, S: gl.constexpr,\n):\n khead = head // (VH // KH)\n NW: gl.constexpr = gl.num_warps()\n QW: gl.constexpr = min(NW, max(1, gl.cdiv(BK, 128)))\n layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [QW, NW // QW], [0, 1])\n ki = gl.arange(0, BK, gl.SliceLayout(1, layout))\n kind = gl.arange(0, 2, gl.SliceLayout(0, layout))\n channels = (khead + kind[None, :] * KH) * K + ki[:, None]\n C: gl.constexpr = 2 * KH * K + VH * V\n v = _convolve_read(X, History, Weight, token, slot, 2 * KH * K + head * V + vidx,\n vmask, C, VH * V, S.wide_conv)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n qk = _convolve_read(X, History, Weight, token, slot, channels, ki[:, None] < K,\n C, VH * V, S.wide_conv)\n qk = _normalize_columns(qk)\n if S.query_mode == \"qk_lds\":\n qk = gl.where(kind[None, :] == 0, qk * scale, qk)\n return qk, v, decay, beta\n\n\[email protected]\ndef _stage_qkv(\n X, History, Weight, token, slot, head,\n KH: gl.constexpr, VH: gl.constexpr, K: gl.constexpr, V: gl.constexpr,\n BK: gl.constexpr, S: gl.constexpr,\n):\n if S.flat_producer:\n flat_layout: gl.constexpr = gl.BlockedLayout([2], [64], [4], [0])\n idx = gl.arange(0, 4 * BK, flat_layout)\n ci = idx % BK\n kind = idx // BK\n khead = head // (VH // KH)\n C: gl.constexpr = 2 * KH * K + VH * V\n channel_base = gl.where(kind < 2, (khead + kind * KH) * K, 2 * KH * K + head * V)\n channels = channel_base + ci\n qkv = _convolve_read(X, History, Weight, token, slot, channels, ci < K,\n C, VH * V, True)\n matrix = qkv.reshape((4, BK))\n invnorm = 1.0 / gl.sqrt(gl.sum(matrix * matrix, 1) + 1e-06)\n qkv = gl.where(kind < 2, (matrix * invnorm[:, None]).reshape((4 * BK,)), qkv)\n return gl.allocate_shared_memory(\n gl.float32, (4 * BK,), gl.SwizzledSharedLayout(1, 1, 1, [0]), qkv)\n else:\n conv_layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [1, 4], [0, 1])\n ci = gl.arange(0, BK, gl.SliceLayout(1, conv_layout))\n kind = gl.arange(0, 4, gl.SliceLayout(0, conv_layout))\n khead = head // (VH // KH)\n C: gl.constexpr = 2 * KH * K + VH * V\n channel_base = gl.where(kind[None, :] < 2,\n (khead + kind[None, :] * KH) * K,\n 2 * KH * K + head * V)\n channel_base = gl.multiple_of(channel_base, [K, K])\n channels = channel_base + ci[:, None]\n qkv = _convolve_read(X, History, Weight, token, slot, channels, ci[:, None] < K,\n C, VH * V, True)\n qkv = gl.where(kind[None, :] < 2, _normalize_columns(qkv), qkv)\n return _stage_columns(qkv)\n\n\[email protected]\ndef _recurrent(\n X, BA, History, State, Slots, Weight, ALog, DtBias, Core, scale,\n T: gl.constexpr, KH: gl.constexpr, VH: gl.constexpr,\n K: gl.constexpr, V: gl.constexpr, BK: gl.constexpr, S: gl.constexpr,\n):\n BV: gl.constexpr = S.rows\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n COOPERATIVE: gl.constexpr = S.query_mode == \"qkv_lds\"\n LATE_Q: gl.constexpr = S.query_mode != \"register\"\n CACHE: gl.constexpr = S.state_load\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * BV + gl.arange(0, BV, gl.SliceLayout(1, layout))\n gl.static_assert(V % BV == 0, \"Each CTA must own complete value tiles\")\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n if slot < 0:\n gl.store(Core + row * V + vidx, 0.0, vmask)\n return\n if S.pool_relative:\n # The host proves the complete pool fits below the buffer mask sentinel.\n state_base = State\n offsets = ((slot * VH + head) * V + vidx[:, None]) * K + kidx[None, :]\n else:\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n mask = vmask[:, None] & (kidx[None, :] < K)\n state = gl.amd.cdna4.buffer_load(state_base, offsets, mask, other=0, cache=CACHE)\n\n if COOPERATIVE:\n gl.static_assert(NW == 4 and BK == K and K == V and BK % BV == 0)\n staged = _stage_qkv(X, History, Weight, token, slot, head,\n KH, VH, K, V, BK, S)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n if S.flat_producer:\n k = staged.gather(BK + kidx, axis=0)\n v = staged.gather(2 * BK + vidx, axis=0)\n else:\n k = staged.slice(BK, BK).load(gl.SliceLayout(0, layout))\n v = staged._reinterpret(\n shape=(4 * BK // BV, BV), layout=gl.SwizzledSharedLayout(1, 1, 1, [0])\n ).index(2 * BK // BV + tile).load(gl.SliceLayout(1, layout))\n else:\n qk, v, decay, beta = _prepare_tiled_qkv(\n X, BA, History, Weight, ALog, DtBias, token, slot, head, vidx, vmask,\n scale, KH, VH, K, V, BK, S)\n if LATE_Q:\n staged = _stage_columns(qk)\n k = staged.slice(BK, BK).load(gl.SliceLayout(0, layout))\n else:\n split_layout: gl.constexpr = gl.BlockedLayout([4, 2], [KL, 64 // KL], [1, NW], [0, 1])\n q, k = gl.split(gl.convert_layout(qk, split_layout))\n q *= scale\n q = gl.convert_layout(q, gl.SliceLayout(0, layout))\n k = gl.convert_layout(k, gl.SliceLayout(0, layout))\n\n if S.state_group:\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n if LATE_Q and S.early_query:\n # Overlap the LDS read with bitwise store-mask reduction.\n q = staged.slice(0, BK).load(gl.SliceLayout(0, layout))\n if S.state_group:\n # Reduce XORs over disjoint 64-byte segments; never skip computation.\n GROUP: gl.constexpr = S.state_group\n gl.static_assert(BK % GROUP == 0)\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n mask = ((changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))).reshape((BV, BK))\n if LATE_Q:\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n if not S.early_query:\n q = staged.slice(0, BK).load(gl.SliceLayout(0, layout))\n result = gl.sum(state * q[None, :], 1)\n if COOPERATIVE:\n result *= scale\n if not LATE_Q:\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n gl.store(Core + row * V + vidx, result.to(gl.bfloat16), vmask)\n\n\[email protected]\ndef _commit_history(X, History, token, slot, role,\n C: gl.constexpr, VH: gl.constexpr,\n V: gl.constexpr, S: gl.constexpr):\n CHUNK: gl.constexpr = S.history_chunk\n HP: gl.constexpr = S.history_vector\n if S.history_mode == \"elide_quad\":\n # Four channels occupy three uint64 words; repack only BF16 fields.\n L: gl.constexpr = gl.BlockedLayout([HP], [64], [1], [0])\n quad = (role - VH) * (CHUNK // 4) + gl.arange(0, CHUNK // 4, L)\n hp = History.to(gl.pointer_type(gl.uint64)) + (slot * (C // 4) + quad) * 3\n xp = X.to(gl.pointer_type(gl.uint64)) + token * ((C + VH * V) // 4) + quad\n h0 = gl.load(hp)\n h1 = gl.load(hp + 1)\n h2 = gl.load(hp + 2)\n x = gl.load(xp)\n n0 = ((h0 >> 16) & 0xffffffff) | ((x & 0xffff) << 32) | (h1 << 48)\n n1 = ((h1 >> 16) & 0x0000ffff0000ffff) | (x & 0xffff0000) | (h2 << 48)\n n2 = ((x >> 32) & 0xffff) | ((h2 >> 16) & 0x0000ffffffff0000) | (x & 0xffff000000000000)\n gl.store(hp, n0, n0 != h0)\n gl.store(hp + 1, n1, n1 != h1)\n gl.store(hp + 2, n2, n2 != h2)\n elif S.history_mode == \"linear_word\":\n # Contiguous uint32 workers own disjoint words of the shifted history.\n L: gl.constexpr = gl.BlockedLayout([HP], [64], [1], [0])\n idx = gl.arange(0, CHUNK * 2, L)\n word = (role - VH) * (CHUNK * 3 // 2) + idx\n valid = idx < CHUNK * 3 // 2\n hp = History.to(gl.pointer_type(gl.uint32)) + slot * (C * 3 // 2) + word\n xp = X.to(gl.pointer_type(gl.uint32)) + token * ((C + VH * V) // 2) + word // 3\n old = gl.load(hp, valid, other=0)\n nxt = gl.load(hp + 1, valid & (idx % 3 != 2), other=0)\n x = gl.load(xp, valid, other=0)\n lo = gl.where(idx % 3 == 1, x & 65535, old >> 16)\n hi = gl.where(idx % 3 == 2, x & 4294901760, nxt << 16)\n updated = lo | hi\n gl.store(hp, updated, valid & (updated != old))\n elif S.history_mode == \"elide_word\":\n L: gl.constexpr = gl.BlockedLayout([HP], [64], [1], [0])\n pair = (role - VH) * (CHUNK // 2) + gl.arange(0, CHUNK // 2, L)\n hp = History.to(gl.pointer_type(gl.uint32)) + (slot * (C // 2) + pair) * 3\n xp = X.to(gl.pointer_type(gl.uint32)) + token * ((C + VH * V) // 2) + pair\n h0 = gl.load(hp)\n h1 = gl.load(hp + 1)\n h2 = gl.load(hp + 2)\n x = gl.load(xp)\n n0 = (h0 >> 16) | (h1 << 16)\n n1 = (x & 65535) | (h2 << 16)\n n2 = (h2 >> 16) | (x & 4294901760)\n # Two channels occupy three uint32 words. Shifting their BF16 fields\n # preserves the exact bits, including signed zero and NaN payloads.\n gl.store(hp, n0, n0 != h0)\n gl.store(hp + 1, n1, n1 != h1)\n gl.store(hp + 2, n2, n2 != h2)\n else:\n idx = gl.arange(0, CHUNK, gl.BlockedLayout([HP], [64], [1], [0]))\n channel = (role - VH) * CHUNK + idx\n gl.static_assert(C % CHUNK == 0, \"History workers own complete chunks\")\n valid = gl.full((CHUNK,), True, gl.int1, gl.BlockedLayout([HP], [64], [1], [0]))\n hp = History + (slot * C + channel) * 3\n x = gl.load(X + token * (C + VH * V) + channel, valid, other=0)\n h1 = gl.load(hp + 1, valid, other=0)\n h2 = gl.load(hp + 2, valid, other=0)\n gl.store(hp, h1, valid)\n gl.store(hp + 1, h2, valid)\n gl.store(hp + 2, x, valid)\n\n\[email protected]\ndef _finish(X, History, Slots, Core, NormWeight, Out, eps,\n C: gl.constexpr, VH: gl.constexpr,\n V: gl.constexpr, BLOCK: gl.constexpr, S: gl.constexpr):\n NP: gl.constexpr = S.norm_vector\n token = gl.program_id(0)\n role = gl.program_id(1)\n slot = gl.load(Slots + token)\n if role < VH:\n idx = gl.arange(0, BLOCK, gl.BlockedLayout([NP], [64], [1], [0]))\n row = token * VH + role\n if slot < 0:\n gl.store(Out + row * V + idx, 0, idx < V)\n else:\n core = gl.load(Core + row * V + idx, idx < V, other=0).to(gl.float32)\n variance = gl.sum(core * core, 0) / V\n normalized = core * gl.rsqrt(variance + eps)\n normalized *= gl.load(NormWeight + idx, idx < V, other=0).to(gl.float32)\n z = gl.load(X + token * (C + VH * V) + C + role * V + idx, idx < V, other=0).to(gl.float32)\n normalized *= z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(Out + row * V + idx, normalized, idx < V)\n elif slot >= 0:\n _commit_history(X, History, token, slot, role, C, VH, V, S)\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *, scale: float, eps: float, output: torch.Tensor,\n) -> None:\n tokens = projected_qkvz.shape[0]\n _, v_heads, v_dim, k_dim = delta_state.shape\n channels = conv_state.shape[1]\n k_heads = (channels - v_heads * v_dim) // (2 * k_dim)\n # Place the small core/output buffer halfway through a 16-KiB cache period.\n # The returned view is contiguous and retains its owning GPU allocation.\n output_elements = tokens * v_heads * v_dim\n storage = torch.empty((output_elements + 8192,), device=projected_qkvz.device, dtype=torch.bfloat16)\n output_offset = ((8192 - storage.data_ptr()) % 16384) // 2\n core = storage[output_offset:output_offset + output_elements].view(tokens, v_heads, v_dim)\n schedule = _SCHEDULES[tokens]\n if schedule.pool_relative and delta_state.numel() * delta_state.element_size() > (1 << 31):\n schedule = schedule._replace(pool_relative=False)\n _recurrent[(tokens * v_heads, triton.cdiv(v_dim, schedule.rows))](\n projected_qkvz, projected_ba, conv_state, delta_state, cache_indices,\n conv_weight, a_log, dt_bias, core, scale, tokens, k_heads, v_heads,\n k_dim, v_dim, triton.next_power_of_2(k_dim), schedule,\n num_warps=schedule.warps, num_stages=1, waves_per_eu=schedule.waves_per_eu)\n _finish[(tokens, v_heads + triton.cdiv(channels, schedule.history_chunk))](\n projected_qkvz, conv_state, cache_indices, core, norm_weight, output, eps,\n channels, v_heads, v_dim, triton.next_power_of_2(v_dim), schedule,\n num_warps=1)\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n output=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 192 rows.\n\nMI355 Gluon GDN decode: shared math, two measured execution schedules.\n\nGeometry: four Q/K heads, sixteen V heads, 128 channels per head. Each\nconvolution wave owns 128 channels, including all three history words for\nevery BF16 channel pair. Each recurrent CTA owns complete, disjoint heads.\n\nB136 prepares an 8-KiB record per token: 1024 FP32 Q/K values followed by\n2048 BF16 V values. Other batches stage Q/K and four V heads in LDS, then\nstream two 64-row state tiles per head with one-tile lookahead. The schedule\ntable controls traversal, layout, exact-store grouping and cache policy.\n\nLive slot indirection and coefficients are never cached across invocations.\nNegative slots bypass both mutable pools. BF16 rounding after convolution,\nbeta and recurrent readout is part of the numerical contract.\n\"\"\"\nfrom typing import NamedTuple\n\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\nclass _Schedule(NamedTuple):\n token_group: int\n k_lanes: int\n v_rows: int\n dirty_words: int\n stream_tiles: int # Bit 2*head+half selects .cg instead of .ca.\n buffer_conv: bool\n\n\n# Eight waves and 64-row recurrent tiles for every schedule.\n_GROUPED_SCHEDULES = {\n 128: _Schedule(16, 16, 2, 4, 0x00, False),\n 192: _Schedule(4, 16, 2, 8, 0x30, True),\n 256: _Schedule(4, 8, 1, 4, 0x55, False),\n}\n\n\[email protected]_function\ndef _channel_layout(values_per_lane, warps):\n return gl.BlockedLayout([values_per_lane], [64], [warps], [0])\n\n\[email protected]_function\ndef _state_layout(k_lanes, v_rows):\n return gl.BlockedLayout([v_rows, 4], [64 // k_lanes, k_lanes], [8, 1], [1, 0])\n\n\[email protected]\ndef _token_head(HEADS: gl.constexpr, GROUP: gl.constexpr):\n program = gl.program_id(0).to(gl.uint32)\n token = program // (HEADS * GROUP) * GROUP + program % GROUP\n head = program // GROUP % HEADS\n return token, head\n\n\[email protected]\ndef _conv_offsets(index, first, ELEMENTS: gl.constexpr, GROUPED: gl.constexpr):\n \"\"\"Map either consecutive rows or [Q, K, V0, V1, V2, V3, pad, pad].\"\"\"\n if GROUPED:\n row = index // ELEMENTS\n head = gl.where(row == 0, first,\n gl.where(row == 1, 4 + first, 8 + first * 4 + row - 2))\n return head * ELEMENTS + index % ELEMENTS, row < 6\n else:\n return first * ELEMENTS + index, True\n\n\[email protected]\ndef _interleave_bf16(even, odd, BLOCK: gl.constexpr, LAYOUT: gl.constexpr):\n pairs = gl.join(even.to(gl.uint16).to(gl.bfloat16, bitcast=True),\n odd.to(gl.uint16).to(gl.bfloat16, bitcast=True))\n return gl.convert_layout(gl.reshape(pairs, (BLOCK,)), LAYOUT)\n\n\[email protected]\ndef _convolve(projected, history, weight, token, slot, first,\n ROWS: gl.constexpr, GROUPED: gl.constexpr, BUFFER: gl.constexpr):\n \"\"\"One wave per row: no replicated readers racing history shifts.\"\"\"\n gl.static_assert((GROUPED and ROWS == 8) or (not GROUPED and (ROWS == 1 or ROWS == 2 or ROWS == 4)))\n block: gl.constexpr = 128 * ROWS\n layout: gl.constexpr = _channel_layout(2, ROWS)\n pairs: gl.constexpr = _channel_layout(1, ROWS)\n weights: gl.constexpr = _channel_layout(8, ROWS)\n channel, valid = _conv_offsets(gl.arange(0, block, layout), first, 128, GROUPED)\n if BUFFER:\n x = gl.amd.cdna4.buffer_load(projected, token * 5120 + channel, valid, other=0)\n else:\n x = gl.load(projected + token * 5120 + channel, valid, other=0)\n pair, pair_valid = _conv_offsets(gl.arange(0, block // 2, pairs), first, 64, GROUPED)\n words = history.to(gl.pointer_type(gl.uint32))\n if BUFFER:\n offset = slot.to(gl.int32) * 4608 + pair * 3\n a = gl.amd.cdna4.buffer_load(words, offset, pair_valid, other=0)\n b = gl.amd.cdna4.buffer_load(words, offset + 1, pair_valid, other=0)\n c = gl.amd.cdna4.buffer_load(words, offset + 2, pair_valid, other=0)\n else:\n offset = slot * 4608 + pair * 3\n a = gl.load(words + offset, pair_valid, other=0)\n b = gl.load(words + offset + 1, pair_valid, other=0)\n c = gl.load(words + offset + 2, pair_valid, other=0)\n # Words encode [e0,e1], [e2,o0], [o1,o2] for even/odd channels.\n h0 = _interleave_bf16(a, b >> 16, block, layout)\n h1 = _interleave_bf16(a >> 16, c, block, layout)\n h2 = _interleave_bf16(b, c >> 16, block, layout)\n wi, weight_valid = _conv_offsets(gl.arange(0, block * 4, weights), first, 512, GROUPED)\n if BUFFER:\n weight_value = gl.amd.cdna4.buffer_load(weight, wi, weight_valid, other=0)\n else:\n weight_value = gl.load(weight + wi, weight_valid, other=0)\n w02, w13 = gl.split(gl.reshape(weight_value, (block, 2, 2)))\n w0, w2 = gl.split(w02)\n w1, w3 = gl.split(w13)\n taps = (gl.convert_layout(w0, layout), gl.convert_layout(w1, layout),\n gl.convert_layout(w2, layout), gl.convert_layout(w3, layout))\n values = (h0, h1, h2, x)\n value = gl.full((block,), 0, gl.float32, layout)\n for tap in gl.static_range(4):\n # BF16 product rounding precedes the ordered FP32 accumulation.\n value += (values[tap] * taps[tap]).to(gl.float32)\n activated = (value / (1.0 + gl.exp(-value))).to(gl.bfloat16)\n xe, xo = gl.split(gl.reshape(x, (block // 2, 2)))\n xe = gl.convert_layout(xe, pairs).to(gl.uint16, bitcast=True).to(gl.uint32)\n xo = gl.convert_layout(xo, pairs).to(gl.uint16, bitcast=True).to(gl.uint32)\n old = (a, b, c)\n new = (a >> 16 | b << 16, xe | c << 16, c >> 16 | xo << 16)\n for word in gl.static_range(3):\n # Independent predicates are required for the three packed words.\n changed = pair_valid & (new[word] != old[word])\n if BUFFER:\n gl.amd.cdna4.buffer_store(new[word], words, offset + word, changed)\n else:\n gl.store(words + offset + word, new[word], changed)\n return activated.to(gl.float32)\n\n\[email protected]\ndef _coefficients(ba, a_log, dt_bias, token, head):\n a = gl.load(ba + token * 32 + 16 + head).to(gl.float32)\n b = gl.load(ba + token * 32 + head).to(gl.float32)\n log_value = gl.load(a_log + head)\n bias = gl.load(dt_bias + head).to(gl.float32)\n s = a + bias\n softplus = gl.where(s <= 20.0, gl.log(1.0 + gl.exp(s)), s)\n decay = gl.exp(-gl.exp(log_value) * softplus)\n beta = (1.0 / (1.0 + gl.exp(-b))).to(gl.bfloat16).to(gl.float32)\n return decay, beta\n\n\[email protected]\ndef _store_changed(state, original, base, offsets, DIRTY: gl.constexpr):\n \"\"\"Suppress only bit-identical groups; preserve signed zero and NaN bits.\"\"\"\n groups = gl.reshape(state, (64, 128 // DIRTY, DIRTY))\n old0, old1 = gl.split(gl.reshape(original.to(gl.uint32, bitcast=True), (64, 64, 2)))\n new0, new1 = gl.split(gl.reshape(state.to(gl.uint32, bitcast=True), (64, 64, 2)))\n old_pair = old0.to(gl.uint64) | (old1.to(gl.uint64) << 32)\n new_pair = new0.to(gl.uint64) | (new1.to(gl.uint64) << 32)\n changed = (old_pair != new_pair).to(gl.int32)\n dirty = gl.max(gl.reshape(changed, (64, 128 // DIRTY, DIRTY // 2)), 2) != 0\n dirty = gl.convert_layout(dirty, gl.SliceLayout(2, groups.type.layout))\n mask = gl.reshape(gl.broadcast(dirty[:, :, None], groups)[0], (64, 128))\n gl.amd.cdna4.buffer_store(state, base, offsets, mask=mask, cache=\".wt\")\n\n\[email protected]\ndef _update_tile(original, base, offsets, q, k, v, decay, beta, DIRTY: gl.constexpr):\n state = original * decay\n residual = (v - gl.sum(state * k[None, :], 1)) * beta\n state += residual[:, None] * k[None, :]\n _store_changed(state, original, base, offsets, DIRTY)\n return gl.sum(state * q[None, :], 1).to(gl.bfloat16)\n\n\[email protected]\ndef _rms_gate(core, weight, z, eps):\n value = core.to(gl.float32)\n value *= gl.rsqrt(gl.sum(value * value, 0) / 128 + eps)\n value *= weight\n return value * (z * (1.0 / (1.0 + gl.exp(-z))))\n\n\[email protected]\ndef _padding_output(projected, norm_weight, output, token, head, col, eps):\n core = gl.full((128,), 0, gl.bfloat16, col.type.layout)\n weight = gl.load(norm_weight + col).to(gl.float32)\n z = gl.load(projected + token * 5120 + 3072 + head * 128 + col).to(gl.float32)\n gl.store(output + (token * 16 + head) * 128 + col, _rms_gate(core, weight, z, eps))\n\n\[email protected]\ndef _join_halves(first, second, LAYOUT: gl.constexpr):\n core = gl.reshape(gl.permute(gl.join(first, second), (1, 0)), (128,))\n return gl.convert_layout(core, LAYOUT)\n\n\[email protected]\ndef _prepare_mixed(projected, history, ids, conv_weight, ba, a_log, dt_bias,\n prepared, factors, scale, ROWS: gl.constexpr, GROUP: gl.constexpr):\n token, group = _token_head(24 // ROWS, GROUP)\n first_row = group * ROWS\n slot = gl.load(ids + token).to(gl.int64)\n if slot < 0:\n return\n layout: gl.constexpr = _channel_layout(2, ROWS)\n col = gl.arange(0, 128 * ROWS, layout)\n value = _convolve(projected, history, conv_weight, token, slot, first_row, ROWS, False, True)\n matrix: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [ROWS, 1], [1, 0])\n if first_row < 8:\n rows = gl.convert_layout(gl.reshape(value, (ROWS, 128)), matrix)\n rows = rows / gl.sqrt(gl.sum(rows * rows, 1) + 1e-06)[:, None]\n value = gl.convert_layout(gl.reshape(rows, (128 * ROWS,)), layout)\n if first_row < 4:\n value *= scale\n gl.store(prepared + token * 2048 + first_row * 128 + col, value)\n else:\n head = first_row - 8 + gl.arange(0, ROWS, gl.SliceLayout(1, matrix))\n decay, beta = _coefficients(ba, a_log, dt_bias, token, head)\n gl.store(factors + token * 32 + head, decay)\n gl.store(factors + token * 32 + 16 + head, beta)\n vptr = (prepared + token * 2048 + 1024).to(gl.pointer_type(gl.bfloat16))\n gl.store(vptr + (first_row - 8) * 128 + col, value)\n\n\[email protected]\ndef _prepared_decode(prepared, factors, projected, norm_weight, output, state_pool, ids, eps):\n token, head = _token_head(16, 8)\n slot = gl.load(ids + token).to(gl.int64)\n layout: gl.constexpr = _state_layout(8, 1)\n norm_layout: gl.constexpr = _channel_layout(2, 8)\n kk = gl.arange(0, 128, gl.SliceLayout(0, layout))\n vv = gl.arange(0, 64, gl.SliceLayout(1, layout))\n col = gl.arange(0, 128, norm_layout)\n if slot < 0:\n _padding_output(projected, norm_weight, output, token, head, col, eps)\n return\n offsets0 = vv[:, None] * 128 + kk[None, :]\n q = gl.load(prepared + token * 2048 + head // 4 * 128 + kk)\n k = gl.load(prepared + token * 2048 + 512 + head // 4 * 128 + kk)\n decay = gl.load(factors + token * 32 + head)\n beta = gl.load(factors + token * 32 + 16 + head)\n base = state_pool + (slot * 16 + head) * 16384\n vptr = (prepared + token * 2048 + 1024).to(gl.pointer_type(gl.bfloat16))\n z = gl.load(projected + token * 5120 + 3072 + head * 128 + col).to(gl.float32)\n weight = gl.load(norm_weight + col).to(gl.float32)\n for part in gl.static_range(2):\n row = vv + part * 64\n offsets = offsets0 + part * 8192\n original = gl.amd.cdna4.buffer_load(base, offsets, cache=\".ca\")\n v = gl.load(vptr + head * 128 + row).to(gl.float32)\n core = _update_tile(original, base, offsets, q, k, v, decay, beta, 8)\n if part == 0:\n first = core\n core = _join_halves(first, core, norm_layout)\n gl.store(output + (token * 16 + head) * 128 + col, _rms_gate(core, weight, z, eps))\n\n\[email protected]\ndef _grouped_decode(projected, history, ids, conv_weight, ba, a_log, dt_bias,\n norm_weight, output, state_pool, scale, eps,\n GROUP: gl.constexpr, K_LANES: gl.constexpr, V_ROWS: gl.constexpr,\n DIRTY: gl.constexpr, STREAM_TILES: gl.constexpr,\n BUFFER_CONV: gl.constexpr):\n gl.static_assert(8 * V_ROWS * (64 // K_LANES) <= 64,\n \"State readers must not be replicated across waves\")\n token, k_head = _token_head(4, GROUP)\n slot = gl.load(ids + token).to(gl.int64)\n layout: gl.constexpr = _state_layout(K_LANES, V_ROWS)\n norm_layout: gl.constexpr = _channel_layout(2, 8)\n kk = gl.arange(0, 128, gl.SliceLayout(0, layout))\n vv = gl.arange(0, 64, gl.SliceLayout(1, layout))\n col = gl.arange(0, 128, norm_layout)\n staging = gl.allocate_shared_memory(\n gl.float32, (8, 128), gl.SwizzledSharedLayout(1, 1, 1, [0]))\n if slot < 0:\n for vh in range(4):\n _padding_output(projected, norm_weight, output, token, k_head * 4 + vh, col, eps)\n return\n # Keep the pool-wide address 64-bit; only head-local buffer offsets are 32-bit.\n prefetch_base = state_pool + (slot * 16 + k_head * 4) * 128 * 128\n prefetch_offsets = vv[:, None] * 128 + kk[None, :]\n lookahead = gl.amd.cdna4.buffer_load(\n prefetch_base, prefetch_offsets, cache=\".cg\" if STREAM_TILES & 1 else \".ca\")\n ready = _convolve(projected, history, conv_weight, token, slot, k_head, 8, True, BUFFER_CONV)\n matrix: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [8, 1], [1, 0])\n row_index = gl.arange(0, 8, gl.SliceLayout(1, matrix))\n rows = gl.reshape(ready, (8, 128))\n normalized = rows / gl.sqrt(gl.sum(rows * rows, 1) + 1e-06)[:, None]\n ready = gl.where(row_index[:, None] < 2, normalized, rows)\n staging._reinterpret(shape=(1024,)).store(gl.reshape(ready, (1024,)))\n q = staging.index(0).load(gl.SliceLayout(0, layout)) * scale\n k = staging.index(1).load(gl.SliceLayout(0, layout))\n for vh in gl.static_range(4):\n head = k_head * 4 + vh\n decay, beta = _coefficients(ba, a_log, dt_bias, token, head)\n base = state_pool + (slot * 16 + head) * 128 * 128\n weight = gl.load(norm_weight + col).to(gl.float32)\n z = gl.load(projected + token * 5120 + 3072 + head * 128 + col).to(gl.float32)\n for part in gl.static_range(2):\n row = vv + part * 64\n offsets = row[:, None] * 128 + kk[None, :]\n original = lookahead\n # One lookahead only: deeper pipelines increase register pressure.\n if part == 0 or vh < 3:\n if part == 0:\n next_base = base\n next_offsets = offsets + 8192\n else:\n next_base = base + 16384\n next_offsets = vv[:, None] * 128 + kk[None, :]\n lookahead = gl.amd.cdna4.buffer_load(\n next_base, next_offsets,\n cache=\".cg\" if STREAM_TILES & (1 << (2 * vh + part + 1)) else \".ca\")\n v = staging.index(vh + 2)._reinterpret(shape=(2, 64)).index(part).load(\n gl.SliceLayout(1, layout))\n core = _update_tile(original, base, offsets, q, k, v, decay, beta, DIRTY)\n if part == 0:\n first = core\n core = _join_halves(first, core, norm_layout)\n gl.store(output + (token * 16 + head) * 128 + col, _rms_gate(core, weight, z, eps))\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *, scale: float, eps: float, output: torch.Tensor,\n) -> None:\n tokens = projected_qkvz.shape[0]\n if tokens == 136:\n prepared = torch.empty((tokens, 2048), device=projected_qkvz.device, dtype=torch.float32)\n factors = torch.empty((tokens, 32), device=projected_qkvz.device, dtype=torch.float32)\n _prepare_mixed[tokens * 24,](\n projected_qkvz, conv_state, cache_indices, conv_weight,\n projected_ba, a_log, dt_bias, prepared, factors, scale,\n ROWS=1, GROUP=8, num_warps=1)\n _prepared_decode[tokens * 16,](\n prepared, factors, projected_qkvz, norm_weight, output,\n delta_state, cache_indices, eps, num_warps=8, waves_per_eu=4)\n else:\n schedule = _GROUPED_SCHEDULES[tokens]\n _grouped_decode[tokens * 4,](\n projected_qkvz, conv_state, cache_indices, conv_weight,\n projected_ba, a_log, dt_bias, norm_weight, output, delta_state, scale, eps,\n GROUP=schedule.token_group, K_LANES=schedule.k_lanes, V_ROWS=schedule.v_rows,\n DIRTY=schedule.dirty_words, STREAM_TILES=schedule.stream_tiles,\n BUFFER_CONV=schedule.buffer_conv, num_warps=8)\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n output=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 8 rows.\n\nTwo-launch Gluon GDN decode for MI355.\n\nB8 uses two prefetched 32-row state fragments per CTA, sharing Q/K/V preparation\nwithout keeping a whole 64-row update live. Other batches retain their own\nschedules. The launch boundary protects old history reads; state tiles have\nexclusive writers and exact bitwise store elision. Slots remain live on replay.\n\"\"\"\nfrom typing import NamedTuple\nimport torch\nimport triton\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\nclass _Schedule(NamedTuple):\n rows: int\n key_lanes: int\n warps: int\n history_chunk: int\n history_vector: int\n norm_vector: int\n state_store: str = '.cs'\n wide_conv: bool = True\n state_group: int = 0\n pool_offsets: bool = False\n\n_SCHEDULES = {\n 1: _Schedule(8, 16, 2, 64, 4, 1, wide_conv=False, state_group=16, pool_offsets=True),\n 2: _Schedule(16, 16, 4, 128, 2, 1, state_group=16, pool_offsets=True),\n 4: _Schedule(32, 8, 4, 256, 2, 2, state_store='', state_group=16, pool_offsets=True),\n 8: _Schedule(64, 8, 4, 256, 2, 2, state_group=16, pool_offsets=True),\n}\n\[email protected]\ndef _exp(x):\n return gl.exp2(x * 1.4426950408889634)\n\[email protected]\ndef _or_bits(a, b):\n return a | b\n\[email protected]\ndef _convolve_read(X, History, Weight, token, slot, channel, valid,\n CHANNELS: gl.constexpr, Z_CHANNELS: gl.constexpr, WIDE: gl.constexpr):\n if WIDE:\n hist = History + slot.to(gl.int64) * (CHANNELS * 3) + channel.to(gl.int64) * 3\n weight = Weight + channel.to(gl.int64) * 4\n xp = X + token.to(gl.int64) * (CHANNELS + Z_CHANNELS) + channel.to(gl.int64)\n else:\n hist = History + (slot * CHANNELS + channel) * 3\n weight = Weight + channel * 4\n xp = X + token * (CHANNELS + Z_CHANNELS) + channel\n x = gl.load(xp, valid, other=0)\n h0 = gl.load(hist, valid, other=0)\n h1 = gl.load(hist + 1, valid, other=0)\n h2 = gl.load(hist + 2, valid, other=0)\n w0 = gl.load(weight, valid, other=0)\n w1 = gl.load(weight + 1, valid, other=0)\n w2 = gl.load(weight + 2, valid, other=0)\n w3 = gl.load(weight + 3, valid, other=0)\n acc = gl.full(channel.shape, 0, gl.float32, channel.type.layout)\n acc += (h0.to(gl.float32) * w0.to(gl.float32)).to(gl.bfloat16)\n acc += (h1.to(gl.float32) * w1.to(gl.float32)).to(gl.bfloat16)\n acc += (h2.to(gl.float32) * w2.to(gl.float32)).to(gl.bfloat16)\n acc += (x.to(gl.float32) * w3.to(gl.float32)).to(gl.bfloat16)\n value = acc * (1.0 / (1.0 + _exp(-acc)))\n return value.to(gl.bfloat16).to(gl.float32)\n\[email protected]\ndef _gate_values(BA, ALog, DtBias, token, head, VH: gl.constexpr):\n a = gl.load(BA + token * 2 * VH + VH + head).to(gl.float32)\n b = gl.load(BA + token * 2 * VH + head).to(gl.float32)\n a_log = gl.load(ALog + head)\n bias = gl.load(DtBias + head).to(gl.float32)\n softplus_in = a + bias\n softplus = gl.where(softplus_in <= 20.0, gl.log(1.0 + _exp(softplus_in)), softplus_in)\n decay = _exp(-_exp(a_log) * softplus)\n beta = (1.0 / (1.0 + _exp(-b))).to(gl.bfloat16).to(gl.float32)\n return (decay, beta)\n\[email protected]\ndef _normalize_columns(values):\n invnorm = 1.0 / gl.sqrt(gl.sum(values * values, 0) + 1e-06)\n return values * invnorm[None, :]\n\[email protected]\ndef _stage_columns(values):\n SIZE: gl.constexpr = values.shape[0] * values.shape[1]\n return gl.allocate_shared_memory(gl.float32, (SIZE,), gl.SwizzledSharedLayout(1, 1, 1, [0]),\n values.permute((1, 0)).reshape((SIZE,)))\n\[email protected]\ndef _prepare_tiled_qkv(X, BA, History, Weight, ALog, DtBias, token, slot, head,\n vidx, vmask, scale, KH: gl.constexpr, VH: gl.constexpr,\n K: gl.constexpr, V: gl.constexpr, BK: gl.constexpr, S: gl.constexpr):\n khead = head // (VH // KH)\n NW: gl.constexpr = gl.num_warps()\n QW: gl.constexpr = min(NW, max(1, gl.cdiv(BK, 128)))\n layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [QW, NW // QW], [0, 1])\n ki = gl.arange(0, BK, gl.SliceLayout(1, layout))\n kind = gl.arange(0, 2, gl.SliceLayout(0, layout))\n channels = (khead + kind[None, :] * KH) * K + ki[:, None]\n C: gl.constexpr = 2 * KH * K + VH * V\n v = _convolve_read(X, History, Weight, token, slot, 2 * KH * K + head * V + vidx,\n vmask, C, VH * V, S.wide_conv)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n qk = _convolve_read(X, History, Weight, token, slot, channels, ki[:, None] < K,\n C, VH * V, S.wide_conv)\n qk = _normalize_columns(qk)\n return (qk, v, decay, beta)\n\[email protected]\ndef _stage_qkv(X, History, Weight, token, slot, head, KH: gl.constexpr, VH: gl.constexpr,\n K: gl.constexpr, V: gl.constexpr, BK: gl.constexpr, S: gl.constexpr):\n conv_layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [1, 4], [0, 1])\n ci = gl.arange(0, BK, gl.SliceLayout(1, conv_layout))\n kind = gl.arange(0, 4, gl.SliceLayout(0, conv_layout))\n khead = head // (VH // KH)\n C: gl.constexpr = 2 * KH * K + VH * V\n channel_base = gl.where(kind[None, :] < 2, (khead + kind[None, :] * KH) * K, 2 * KH * K + head * V)\n channel_base = gl.multiple_of(channel_base, [K, K])\n channels = channel_base + ci[:, None]\n qkv = _convolve_read(X, History, Weight, token, slot, channels, ci[:, None] < K, C, VH * V, True)\n qkv = gl.where(kind[None, :] < 2, _normalize_columns(qkv), qkv)\n return _stage_columns(qkv)\n\[email protected]\ndef _recurrent_small(X, BA, History, State, Slots, Weight, ALog, DtBias, Core,\n scale: gl.constexpr, T: gl.constexpr, KH: gl.constexpr,\n VH: gl.constexpr, K: gl.constexpr, V: gl.constexpr,\n BK: gl.constexpr, S: gl.constexpr):\n BV: gl.constexpr = S.rows\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n CACHE: gl.constexpr = ''\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * BV + gl.arange(0, BV, gl.SliceLayout(1, layout))\n gl.static_assert(V % BV == 0, 'Each CTA must own complete value tiles')\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n if slot < 0:\n gl.store(Core + row * V + vidx, 0.0, vmask)\n return\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n if S.pool_offsets:\n state_base = State\n offsets += (slot * VH + head) * (V * K)\n mask = vmask[:, None] & (kidx[None, :] < K)\n state = gl.amd.cdna4.buffer_load(state_base, offsets, mask, other=0, cache=CACHE)\n qk, v, decay, beta = _prepare_tiled_qkv(X, BA, History, Weight, ALog, DtBias,\n token, slot, head, vidx, vmask, scale, KH, VH, K, V, BK, S)\n split_layout: gl.constexpr = gl.BlockedLayout([4, 2], [KL, 64 // KL], [1, NW], [0, 1])\n q, k = gl.split(gl.convert_layout(qk, split_layout))\n q *= scale\n q = gl.convert_layout(q, gl.SliceLayout(0, layout))\n k = gl.convert_layout(k, gl.SliceLayout(0, layout))\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n GROUP: gl.constexpr = S.state_group\n gl.static_assert(BK % GROUP == 0)\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n mask = ((changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))).reshape((BV, BK))\n result = gl.sum(state * q[None, :], 1)\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n gl.store(Core + row * V + vidx, result.to(gl.bfloat16), vmask)\n\[email protected]\ndef _recurrent(X, BA, History, State, Slots, Weight, ALog, DtBias, Core,\n scale, T: gl.constexpr, KH: gl.constexpr, VH: gl.constexpr,\n K: gl.constexpr, V: gl.constexpr, BK: gl.constexpr, S: gl.constexpr):\n BV: gl.constexpr = S.rows\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n CACHE: gl.constexpr = '.cg'\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * BV + gl.arange(0, BV, gl.SliceLayout(1, layout))\n gl.static_assert(V % BV == 0, 'Each CTA must own complete value tiles')\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n result = gl.full((BV,), 0, gl.float32, gl.SliceLayout(1, layout))\n if slot >= 0:\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n if S.pool_offsets:\n state_base = State\n offsets += (slot * VH + head) * (V * K)\n mask = vmask[:, None] & (kidx[None, :] < K)\n state = gl.amd.cdna4.buffer_load(state_base, offsets, mask, other=0, cache=CACHE)\n gl.static_assert(NW == 4 and BK == K and (K == V) and (BK % BV == 0))\n staged = _stage_qkv(X, History, Weight, token, slot, head, KH, VH, K, V, BK, S)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n k = staged.slice(BK, BK).load(gl.SliceLayout(0, layout))\n v = (staged._reinterpret(shape=(4 * BK // BV, BV), layout=gl.SwizzledSharedLayout(1, 1, 1, [0]))\n .index(2 * BK // BV + tile).load(gl.SliceLayout(1, layout)))\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n GROUP: gl.constexpr = S.state_group\n gl.static_assert(BK % GROUP == 0)\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n mask = ((changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))).reshape((BV, BK))\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n q = staged.slice(0, BK).load(gl.SliceLayout(0, layout))\n result = gl.sum(state * q[None, :], 1)\n result *= scale\n gl.store(Core + row * V + vidx, result.to(gl.bfloat16), vmask)\n\[email protected]\ndef _recurrent_split(X, BA, History, State, Slots, Weight, ALog, DtBias, Core,\n scale, T: gl.constexpr, KH: gl.constexpr, VH: gl.constexpr,\n K: gl.constexpr, V: gl.constexpr, BK: gl.constexpr, S: gl.constexpr):\n # Two fragments share preparation; the next state load overlaps the first update.\n BV: gl.constexpr = S.rows // 2\n gl.static_assert(V % S.rows == 0 and BK == K and K == V)\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * (2 * BV) + gl.arange(0, BV, gl.SliceLayout(1, layout))\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n if slot < 0:\n gl.store(Core + row * V + vidx, 0, vmask)\n gl.store(Core + row * V + vidx + BV, 0, vmask)\n return\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n if S.pool_offsets:\n state_base = State\n offsets += (slot * VH + head) * (V * K)\n mask = vmask[:, None] & (kidx[None, :] < K)\n first = gl.amd.cdna4.buffer_load(state_base, offsets, mask, other=0, cache='.cg')\n staged = _stage_qkv(X, History, Weight, token, slot, head, KH, VH, K, V, BK, S)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n k = staged.slice(BK, BK).load(gl.SliceLayout(0, layout))\n second = gl.amd.cdna4.buffer_load(state_base, offsets + BV * K, mask, other=0, cache='.cg')\n GROUP: gl.constexpr = S.state_group\n for f in gl.static_range(2):\n if f == 0:\n state = first\n else:\n state = second\n v = (staged._reinterpret(shape=(4 * BK // BV, BV), layout=gl.SwizzledSharedLayout(1, 1, 1, [0]))\n .index(2 * BK // BV + tile * 2 + f).load(gl.SliceLayout(1, layout)))\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n smask = ((changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))).reshape((BV, BK))\n gl.amd.cdna4.buffer_store(state, state_base, offsets + f * BV * K, smask, cache=S.state_store)\n q = staged.slice(0, BK).load(gl.SliceLayout(0, layout))\n result = gl.sum(state * q[None, :], 1) * scale\n gl.store(Core + row * V + vidx + f * BV, result.to(gl.bfloat16), vmask)\n\[email protected]\ndef _commit_history(X, History, token, slot, role, C: gl.constexpr,\n VH: gl.constexpr, V: gl.constexpr, S: gl.constexpr):\n CHUNK: gl.constexpr = S.history_chunk\n HP: gl.constexpr = S.history_vector\n idx = gl.arange(0, CHUNK, gl.BlockedLayout([HP], [64], [1], [0]))\n channel = (role - VH) * CHUNK + idx\n gl.static_assert(C % CHUNK == 0, 'History workers own complete chunks')\n valid = gl.full((CHUNK,), True, gl.int1, gl.BlockedLayout([HP], [64], [1], [0]))\n hp = History + (slot * C + channel) * 3\n x = gl.load(X + token * (C + VH * V) + channel, valid, other=0)\n h1 = gl.load(hp + 1, valid, other=0)\n h2 = gl.load(hp + 2, valid, other=0)\n h0 = gl.load(hp, valid, other=0)\n old0 = h0.to(gl.uint16, bitcast=True)\n old1 = h1.to(gl.uint16, bitcast=True)\n old2 = h2.to(gl.uint16, bitcast=True)\n new2 = x.to(gl.uint16, bitcast=True)\n valid = valid & ((old0 != old1) | (old1 != old2) | (old2 != new2))\n gl.store(hp, h1, valid)\n gl.store(hp + 1, h2, valid)\n gl.store(hp + 2, x, valid)\n\[email protected]\ndef _finish(X, History, Slots, Core, NormWeight, Out, eps,\n C: gl.constexpr, VH: gl.constexpr, V: gl.constexpr, BLOCK: gl.constexpr, S: gl.constexpr):\n NP: gl.constexpr = S.norm_vector\n token = gl.program_id(0)\n role = gl.program_id(1)\n slot = gl.load(Slots + token)\n if role < VH:\n idx = gl.arange(0, BLOCK, gl.BlockedLayout([NP], [64], [1], [0]))\n row = token * VH + role\n if slot < 0:\n gl.store(Out + row * V + idx, 0, idx < V)\n else:\n core = gl.load(Core + row * V + idx, idx < V, other=0).to(gl.float32)\n variance = gl.sum(core * core, 0) / V\n normalized = core * gl.rsqrt(variance + eps)\n normalized *= gl.load(NormWeight + idx, idx < V, other=0).to(gl.float32)\n z = gl.load(X + token * (C + VH * V) + C + role * V + idx, idx < V, other=0).to(gl.float32)\n normalized *= z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(Out + row * V + idx, normalized, idx < V)\n elif slot >= 0:\n _commit_history(X, History, token, slot, role, C, VH, V, S)\n\ndef gdn_fused_decode(projected_qkvz: torch.Tensor, projected_ba: torch.Tensor,\n conv_state: torch.Tensor, delta_state: torch.Tensor,\n cache_indices: torch.Tensor, conv_weight: torch.Tensor,\n a_log: torch.Tensor, dt_bias: torch.Tensor, norm_weight: torch.Tensor,\n *, scale: float, eps: float, output: torch.Tensor) -> None:\n tokens = projected_qkvz.shape[0]\n _, v_heads, v_dim, k_dim = delta_state.shape\n channels = conv_state.shape[1]\n k_heads = (channels - v_heads * v_dim) // (2 * k_dim)\n schedule = _SCHEDULES[tokens]\n if delta_state.numel() * delta_state.element_size() >= 2**31:\n schedule = schedule._replace(pool_offsets=False)\n recurrent = _recurrent_small if tokens == 1 else _recurrent_split if tokens == 8 else _recurrent\n recurrent[tokens * v_heads, triton.cdiv(v_dim, schedule.rows)](\n projected_qkvz, projected_ba, conv_state, delta_state, cache_indices,\n conv_weight, a_log, dt_bias, output, scale, tokens, k_heads, v_heads,\n k_dim, v_dim, triton.next_power_of_2(k_dim), schedule,\n num_warps=schedule.warps, num_stages=1)\n _finish[tokens, v_heads + triton.cdiv(channels, schedule.history_chunk)](\n projected_qkvz, conv_state, cache_indices, output, norm_weight, output, eps,\n channels, v_heads, v_dim, triton.next_power_of_2(v_dim), schedule, num_warps=1)\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n output=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 64 rows.\n\nExact MI355 GDN decode with batch-specialized state schedules.\n\nB16 uses eight-token recurrent groups. B32/B96 retain two 64-row state tiles.\nB64 fuses four value heads and precomputes FP32 SiLU gates alongside convolution,\nthen stages the gates in LDS until the final readout. This overlaps gate work\nwith the first state fetch without keeping the gates live across state updates.\n\nSlot lookup remains device-side on every invocation, including graph replay.\nNegative slots write zero output without accessing history, scratch or state.\nState-store suppression compares exact bits, including the sign of zero.\n\"\"\"\nfrom typing import NamedTuple\n\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\nclass _StateSchedule(NamedTuple):\n rows: int\n row_pack: int\n columns: int\n load_cache: str\n store_cache: str\n dirty_words: int\n readout_first: bool = True\n asm_dirty: bool = False\n global_loads: bool = False\n waves: int = 0\n\n\n_SCHEDULES = {\n 16: _StateSchedule(rows=128, row_pack=1, columns=8,\n load_cache=\".cv\", store_cache=\".wb\", dirty_words=4,\n readout_first=False, asm_dirty=True),\n 32: _StateSchedule(rows=64, row_pack=2, columns=16,\n load_cache=\".cv\", store_cache=\".wt\", dirty_words=4, waves=2),\n 96: _StateSchedule(rows=64, row_pack=2, columns=16,\n load_cache=\".cg\", store_cache=\".wb\", dirty_words=16,\n global_loads=True),\n}\n\n\[email protected]\ndef _bf16_low(x):\n return x.to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _bf16_high(x):\n return (x >> 16).to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _conv4(h0, h1, h2, x, w0, w1, w2, w3):\n y = (h0 * w0).to(gl.bfloat16).to(gl.float32)\n y += (h1 * w1).to(gl.bfloat16).to(gl.float32)\n y += (h2 * w2).to(gl.bfloat16).to(gl.float32)\n y += (x * w3).to(gl.bfloat16).to(gl.float32)\n return (y / (1.0 + gl.exp(-y))).to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _convolve_packed(QKVZ, W, token, pairs, hist, owned,\n JOIN: gl.constexpr, OUTPUT: gl.constexpr):\n wp = W.to(gl.pointer_type(gl.uint32)) + pairs * 4\n # Padding waves read immutable weights, not another wave's live history.\n read_hist = gl.where(owned, hist, wp)\n h0 = gl.load(read_hist)\n h1 = gl.load(read_hist + 1)\n h2 = gl.load(read_hist + 2)\n x = gl.load(QKVZ.to(gl.pointer_type(gl.uint32)) + token * 2560 + pairs)\n w0 = gl.load(wp)\n w1 = gl.load(wp + 1)\n w2 = gl.load(wp + 2)\n w3 = gl.load(wp + 3)\n ya = _conv4(_bf16_low(h0), _bf16_high(h0), _bf16_low(h1), _bf16_low(x),\n _bf16_low(w0), _bf16_high(w0), _bf16_low(w1), _bf16_high(w1))\n yb = _conv4(_bf16_high(h1), _bf16_low(h2), _bf16_high(h2), _bf16_high(x),\n _bf16_low(w2), _bf16_high(w2), _bf16_low(w3), _bf16_high(w3))\n ya = gl.convert_layout(ya, gl.SliceLayout(2, JOIN))\n yb = gl.convert_layout(yb, gl.SliceLayout(2, JOIN))\n y = gl.join(ya, yb).reshape((h0.shape[0], 2 * h0.shape[1]))\n y = gl.convert_layout(y, OUTPUT)\n return y, (hist, h0, h1, h2, x)\n\n\[email protected]\ndef _commit_history(history, owned):\n hist, h0, h1, h2, x = history\n n0 = (h0 >> 16) | (h1 << 16)\n n1 = (x & 0xFFFF) | (h2 << 16)\n n2 = (h2 >> 16) | (x & 0xFFFF0000)\n dirty = owned & ((n0 != h0) | (n1 != h1) | (n2 != h2))\n gl.store(hist, n0, dirty)\n gl.store(hist + 1, n1, dirty)\n gl.store(hist + 2, n2, dirty)\n\n\[email protected]\ndef _packed_conv(QKVZ, CS, IDX, W, C, scale, TOKENS: gl.constexpr,\n PREGATE: gl.constexpr):\n CHANNELS: gl.constexpr = 3072\n WIDTH: gl.constexpr = 5120\n K: gl.constexpr = 128\n KH: gl.constexpr = 4\n TC: gl.constexpr = 4\n token = gl.program_id(0)\n group = gl.program_id(1)\n L: gl.constexpr = gl.BlockedLayout([1, 1], [1, 64], [TC, 1], [1, 0])\n JO: gl.constexpr = gl.BlockedLayout([1, 1, 2], [1, 64, 1], [TC, 1, 1], [1, 0, 2])\n O: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [TC, 1], [1, 0])\n tile = group * TC + gl.arange(0, TC, gl.SliceLayout(1, L))\n pair = gl.arange(0, K // 2, gl.SliceLayout(0, L))\n pidx = tile[:, None] * (K // 2) + pair[None, :]\n slot = gl.load(IDX + token).to(gl.int64)\n if slot >= 0:\n hist = CS.to(gl.pointer_type(gl.uint32)) + (slot * 1536 + pidx) * 3\n y, history = _convolve_packed(\n QKVZ, W, token, pidx, hist, True, JO, O,\n )\n ot = group * TC + gl.arange(0, TC, gl.SliceLayout(1, O))\n if group * TC < 2 * KH:\n y = y / gl.sqrt(gl.sum(y * y, 1)[:, None] + 1.0e-6)\n y = gl.where(ot[:, None] < KH, y * scale, y)\n ki = gl.arange(0, K, gl.SliceLayout(0, O))\n cp = C + token * 1024\n if group * TC < 2 * KH:\n offset = (ot[:, None] % KH) * (TOKENS * 1024)\n offset += gl.where(ot[:, None] < KH, 0, K)\n gl.store(cp + offset + ki[None, :], y)\n else:\n hv = ot[:, None] - 2 * KH\n vp = cp.to(gl.pointer_type(gl.bfloat16))\n offset = (hv // 4) * (2 * TOKENS * 1024) + 4 * K + (hv % 4) * K\n gl.store(vp + offset + ki[None, :], y)\n if PREGATE:\n z = gl.load(QKVZ + token * WIDTH + CHANNELS + hv * K + ki[None, :]).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(cp + (hv // 4) * (TOKENS * 1024) + 512 + (hv % 4) * K + ki[None, :], gate)\n _commit_history(history, True)\n\n\[email protected]\ndef _decay_beta(BA, AL, DT, token, head, BETA_FIRST: gl.constexpr = True):\n a = gl.load(BA + token * 32 + 16 + head).to(gl.float32)\n b = gl.load(BA + token * 32 + head).to(gl.float32)\n al = gl.load(AL + head)\n dt = gl.load(DT + head).to(gl.float32)\n x = a + dt\n sp = gl.where(x <= 20.0, gl.log(1.0 + gl.exp(x)), x)\n decay_log = -gl.exp(al) * sp\n if not BETA_FIRST:\n decay = gl.exp(decay_log)\n beta = (1.0 / (1.0 + gl.exp(-b))).to(BA.dtype.element_ty).to(gl.float32)\n if BETA_FIRST:\n decay = gl.exp(decay_log)\n return decay, beta\n\n\[email protected]\ndef _load_state(DS, offsets, P: gl.constexpr):\n if P.global_loads:\n return gl.load(DS + offsets, cache_modifier=P.load_cache)\n return gl.amd.cdna3.buffer_load(DS, offsets, cache=P.load_cache)\n\n\[email protected]\ndef _load_gate(QKVZ, W, token, head, E: gl.constexpr):\n eo = gl.arange(0, 128, E)\n z = gl.load(QKVZ + token * 5120 + 3072 + head * 128 + eo).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n w = gl.load(W + eo).to(gl.float32)\n return gate, w\n\n\[email protected]\ndef _gated_rms(core, gate, weight, eps: gl.constexpr):\n axis: gl.constexpr = len(core.shape) - 1\n r = gl.rsqrt(gl.sum(core * core, axis) / 128 + eps)\n if axis > 0:\n r = gl.expand_dims(r, axis)\n y = core * r\n y *= weight\n y *= gate\n return y\n\n\[email protected]\ndef _store_changed_state(DS, offsets, old_bits, state, CACHE: gl.constexpr,\n WORDS: gl.constexpr, ASM_DIRTY: gl.constexpr = False):\n gl.static_assert(WORDS >= 2 and 128 % WORDS == 0)\n rows: gl.constexpr = state.numel // 128\n state = state.reshape((rows, 128))\n offsets = offsets.reshape((rows, 128))\n old_bits = old_bits.reshape((rows, 128))\n new_bits = state.to(gl.uint32, bitcast=True)\n ol, oh = gl.split(old_bits.reshape((rows, 64, 2)))\n nl, nh = gl.split(new_bits.reshape((rows, 64, 2)))\n old_pairs = ol.to(gl.uint64) | (oh.to(gl.uint64) << 32)\n new_pairs = nl.to(gl.uint64) | (nh.to(gl.uint64) << 32)\n if ASM_DIRTY:\n gl.static_assert(WORDS == 4)\n op0, op1 = gl.split(old_pairs.reshape((rows, 32, 2)))\n np0, np1 = gl.split(new_pairs.reshape((rows, 32, 2)))\n dirty = gl.inline_asm_elementwise(\n \"v_cmp_ne_u64_e64 vcc, $1, $3\\n\"\n \"v_cndmask_b32 $0, 0, 1, vcc\\n\"\n \"v_cmp_ne_u64_e64 vcc, $2, $4\\n\"\n \"v_cndmask_b32 $0, $0, 1, vcc\",\n \"=&v,v,v,v,v,~{vcc}\", [op0, op1, np0, np1],\n dtype=gl.int32, is_pure=True, pack=1,\n ) != 0\n else:\n dirty = gl.max((old_pairs != new_pairs).reshape((rows, 128 // WORDS, WORDS // 2)).to(gl.int32), 2) != 0\n groups = old_bits.reshape((rows, 128 // WORDS, WORDS))\n dirty = gl.convert_layout(dirty, gl.SliceLayout(2, groups.type.layout))\n mask, _ = gl.broadcast(dirty[:, :, None], groups)\n gl.amd.cdna3.buffer_store(state, DS, offsets, mask.reshape((rows, 128)), cache=CACHE)\n\n\[email protected]\ndef _advance_state(DS, offsets, state, q, k, v, decay, beta,\n READOUT_FIRST: gl.constexpr, STORE_CACHE: gl.constexpr,\n DIRTY_WORDS: gl.constexpr, ASM_DIRTY: gl.constexpr = False):\n axis: gl.constexpr = len(state.shape) - 1\n old_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v -= gl.sum(state * k, axis)\n v *= beta\n state += gl.expand_dims(v, axis) * k\n if READOUT_FIRST:\n core = gl.sum(state * q, axis).to(gl.bfloat16)\n _store_changed_state(DS, offsets, old_bits, state, STORE_CACHE, DIRTY_WORDS, ASM_DIRTY)\n if not READOUT_FIRST:\n core = gl.sum(state * q, axis).to(gl.bfloat16)\n return core\n\n\[email protected]\ndef _recurrent(C, BA, AL, DT, DS, IDX, OUT, QKVZ, W, eps: gl.constexpr,\n TOKENS: gl.constexpr, P: gl.constexpr):\n ROWS: gl.constexpr = P.rows\n th = gl.program_id(0).to(gl.uint32)\n if ROWS == 128:\n token = (th // 128) * 8 + th % 8\n head = (th // 8) % 16\n else:\n token = th\n head = gl.program_id(1).to(gl.uint32)\n th = token * 16 + head\n kh = head // 4\n COLS: gl.constexpr = P.columns\n L: gl.constexpr = gl.BlockedLayout([P.row_pack, 4], [64 // COLS, COLS], [4, 1], [1, 0])\n gl.static_assert(ROWS == 64 or ROWS == 128)\n gl.static_assert(P.row_pack * (64 // COLS) * 4 <= ROWS)\n E: gl.constexpr = gl.BlockedLayout([2], [64], [4], [0])\n ko = gl.arange(0, 128, gl.SliceLayout(0, L))\n vo = gl.arange(0, ROWS, gl.SliceLayout(1, L))\n slot = gl.load(IDX + token)\n if slot < 0:\n zero = gl.full((ROWS,), 0, gl.float32, gl.SliceLayout(1, L))\n gl.store(OUT + th * 128 + vo, zero)\n if ROWS == 64:\n gl.store(OUT + th * 128 + 64 + vo, zero)\n else:\n so = vo[:, None] * 128 + ko[None, :]\n if P.global_loads:\n state_base = DS + slot * 262144 + head * 16384\n else:\n state_base = DS\n so += slot * 262144 + head * 16384\n state = _load_state(state_base, so, P)\n qp = C + token * 1024 + kh * (TOKENS * 1024)\n q = gl.load(qp + ko)\n k = gl.load(qp + 128 + ko)\n vp = (qp + 256).to(gl.pointer_type(gl.bfloat16)) + (head % 4) * 128\n v = gl.load(vp + vo).to(gl.float32)\n decay, beta = _decay_beta(BA, AL, DT, token, head)\n if ROWS == 128:\n eo = gl.arange(0, 128, E)\n gate = gl.load(qp + 512 + (head % 4) * 128 + eo)\n w = gl.load(W + eo).to(gl.float32)\n if ROWS == 64:\n readout = gl.allocate_shared_memory(gl.bfloat16, [128], gl.SwizzledSharedLayout(1, 1, 1, [0]))\n for chunk in gl.static_range(128 // ROWS):\n if chunk > 0:\n gate, w = _load_gate(QKVZ, W, token, head, E)\n so += ROWS * 128\n state = _load_state(state_base, so, P)\n v = gl.load(vp + ROWS + vo).to(gl.float32)\n core = _advance_state(\n state_base, so, state, q[None, :], k[None, :], v, decay, beta,\n P.readout_first, P.store_cache, P.dirty_words, P.asm_dirty,\n )\n if ROWS == 64:\n readout.slice(chunk * ROWS, ROWS, 0).store(core)\n if ROWS == 64:\n core = readout.load(E)\n core = gl.convert_layout(core.to(gl.float32), E)\n eo = gl.arange(0, 128, E)\n y = _gated_rms(core, gate, w, eps)\n gl.store(OUT + th * 128 + eo, y)\n\n\[email protected]\ndef _grouped_fused64(\n QKVZ, BA, CS, DS, IDX, CW, AL, DT, W, OUT, scale: gl.constexpr, eps: gl.constexpr\n):\n token = gl.program_id(0)\n kh = gl.program_id(1)\n ROWS: gl.constexpr = 32\n CHUNKS: gl.constexpr = 128 // ROWS\n NW: gl.constexpr = 8\n COLS: gl.constexpr = 8\n RP: gl.constexpr = 1\n P: gl.constexpr = gl.BlockedLayout([1, 1], [1, 64], [NW, 1], [1, 0])\n J: gl.constexpr = gl.BlockedLayout([1, 1, 2], [1, 64, 1], [NW, 1, 1], [1, 0, 2])\n O: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [NW, 1], [1, 0])\n L: gl.constexpr = gl.BlockedLayout([1, RP, 4], [1, 64 // COLS, COLS], [4, NW // 4, 1], [2, 1, 0])\n H: gl.constexpr = gl.SliceLayout(1, gl.SliceLayout(2, L))\n K: gl.constexpr = gl.SliceLayout(0, gl.SliceLayout(1, L))\n V: gl.constexpr = gl.SliceLayout(2, L)\n E: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [4, NW // 4], [1, 0])\n heads = kh * 4 + gl.arange(0, 4, H)\n eo = gl.arange(0, 128, gl.SliceLayout(0, E))\n eh = kh * 4 + gl.arange(0, 4, gl.SliceLayout(1, E))\n slot = gl.load(IDX + token)\n if slot < 0:\n gl.store(OUT + token * 2048 + eh[:, None] * 128 + eo[None, :], gl.full((4, 128), 0, gl.bfloat16, E))\n else:\n ko = gl.arange(0, 128, K)\n vr = gl.arange(0, ROWS, gl.SliceLayout(0, V))\n first_offsets = (slot * 262144 + heads[:, None, None] * 16384\n + vr[None, :, None] * 128 + ko[None, None, :])\n state = gl.amd.cdna3.buffer_load(DS, first_offsets, cache=\".cg\")\n ch = gl.arange(0, 8, gl.SliceLayout(1, P))\n tile = gl.where(ch < 4, 8 + kh * 4 + ch, gl.where(ch % 2 == 0, kh, 4 + kh))\n pair = gl.arange(0, 64, gl.SliceLayout(0, P))\n pidx = tile[:, None] * 64 + pair[None, :]\n hist = CS.to(gl.pointer_type(gl.uint32)) + (slot.to(gl.int64) * 1536 + pidx) * 3\n owned = (ch[:, None] < 4) | (ch[:, None] >= 6)\n y, history = _convolve_packed(\n QKVZ, CW, token, pidx, hist, owned, J, O,\n )\n cy = gl.arange(0, 8, gl.SliceLayout(1, O))\n normalized = y / gl.sqrt(gl.sum(y * y, 1)[:, None] + 1.0e-6)\n normalized = gl.where(cy[:, None] == 6, normalized * scale, normalized)\n y = gl.where(cy[:, None] >= 6, normalized, y)\n sm = gl.allocate_shared_memory(gl.float32, [8, 128], gl.SwizzledSharedLayout(1, 1, 1, [1, 0]), y)\n z = gl.load(QKVZ + token * 5120 + 3072 + eh[:, None] * 128 + eo[None, :]).to(gl.float32)\n gate_value = z * (1.0 / (1.0 + gl.exp(-z)))\n # Shared descriptors insert the required cross-wave visibility barriers.\n gate_mem = gl.allocate_shared_memory(gl.float32,[4,128],gl.SwizzledSharedLayout(1,1,1,[1,0]),gate_value)\n _commit_history(history, owned)\n q = sm.slice(6, 1, 0).load(gl.SliceLayout(1, L)).reshape((128,))\n q = gl.convert_layout(q, K)\n k = sm.slice(7, 1, 0).load(gl.SliceLayout(1, L)).reshape((128,))\n k = gl.convert_layout(k, K)\n decay, beta = _decay_beta(BA, AL, DT, token, heads, BETA_FIRST=False)\n cores = gl.allocate_shared_memory(gl.bfloat16, [4, 128], gl.SwizzledSharedLayout(1, 1, 1, [1, 0]))\n for chunk in gl.static_range(CHUNKS):\n rows = chunk * ROWS + vr\n offsets = (slot * 262144 + heads[:, None, None] * 16384\n + rows[None, :, None] * 128 + ko[None, None, :])\n current = state\n if chunk + 1 < CHUNKS:\n state = gl.amd.cdna3.buffer_load(DS, offsets + ROWS * 128, cache=\".cg\")\n with gl.amd.warp_pipeline_stage(\"state_load\"):\n pass\n v = sm.slice(0, 4, 0).slice(chunk * ROWS, ROWS, 1).load(V)\n core = _advance_state(\n DS, offsets, current, q[None, None, :], k[None, None, :], v,\n decay[:, None, None], beta[:, None], True, \".wb\", 16,\n )\n cores.slice(chunk * ROWS, ROWS, 1).store(core)\n with gl.amd.warp_pipeline_stage(\"state_update\"):\n pass\n core = cores.load(E).to(gl.float32)\n gate = gate_mem.load(E)\n w = gl.load(W + eo).to(gl.float32)\n y = _gated_rms(core, gate, w[None, :], eps)\n gl.store(OUT + token * 2048 + eh[:, None] * 128 + eo[None, :], y)\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *,\n scale: float,\n eps: float,\n out: torch.Tensor,\n) -> None:\n tokens = projected_qkvz.shape[0]\n if tokens == 64:\n _grouped_fused64[(tokens, 4)](\n projected_qkvz, projected_ba, conv_state, delta_state, cache_indices,\n conv_weight, a_log, dt_bias, norm_weight, out, scale, eps,\n num_warps=8, waves_per_eu=0,\n )\n return\n\n policy = _SCHEDULES[tokens]\n conv = torch.empty((4, tokens, 1024), device=projected_qkvz.device, dtype=torch.float32)\n _packed_conv[(tokens, 6)](\n projected_qkvz, conv_state, cache_indices, conv_weight, conv, scale,\n TOKENS=tokens, PREGATE=policy.rows == 128, num_warps=4,\n )\n grid = (tokens * 16,) if policy.rows == 128 else (tokens, 16)\n _recurrent[grid](\n conv, projected_ba, a_log, dt_bias, delta_state, cache_indices, out,\n projected_qkvz, norm_weight, eps, TOKENS=tokens, P=policy,\n num_warps=4, waves_per_eu=policy.waves,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n out=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 4 rows.\n\nReplay-safe GDN decode: shared arithmetic, two latency-tuned schedules.\n\nB1/B4: one wave per eight state rows. B2: two waves per sixteen rows.\nSmall batches finish with RMS + deferred history shift.\nB8: one wave per convolution head, then eight waves per full recurrent head.\nSlots are always device-loaded. Padding never reads or writes either pool.\n\"\"\"\nimport torch\nimport triton\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\[email protected]\ndef _conv_silu(h0, h1, h2, x, w0, w1, w2, w3):\n \"\"\"Four ordered FP32 adds, with a BF16 boundary on each product and SiLU.\"\"\"\n acc = gl.full(x.shape, 0, gl.float32, x.type.layout)\n acc += (h0.to(gl.float32) * w0.to(gl.float32)).to(gl.bfloat16).to(gl.float32)\n acc += (h1.to(gl.float32) * w1.to(gl.float32)).to(gl.bfloat16).to(gl.float32)\n acc += (h2.to(gl.float32) * w2.to(gl.float32)).to(gl.bfloat16).to(gl.float32)\n acc += (x.to(gl.float32) * w3.to(gl.float32)).to(gl.bfloat16).to(gl.float32)\n return (acc / (1.0 + gl.exp(-acc))).to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _unpack_weights(weights, L: gl.constexpr):\n \"\"\"The tap axis is register-local; split it without a lane shuffle.\"\"\"\n even, odd = gl.split(weights.reshape(weights.shape[:-1] + (2, 2)))\n a0, a2 = gl.split(even)\n a1, a3 = gl.split(odd)\n return (gl.convert_layout(a0, L), gl.convert_layout(a1, L),\n gl.convert_layout(a2, L), gl.convert_layout(a3, L))\n\n\[email protected]\ndef _gates(BA, ALog, Bias, token, heads, VH: gl.constexpr):\n \"\"\"Accept scalar, paired, or full-head indices without changing arithmetic.\"\"\"\n av = gl.load(BA + token * 2 * VH + VH + heads).to(gl.float32)\n bv = gl.load(BA + token * 2 * VH + heads).to(gl.float32)\n al = gl.load(ALog + heads)\n bias = gl.load(Bias + heads).to(gl.float32)\n sp = av + bias\n sp = gl.where(sp <= 20.0, gl.log(1.0 + gl.exp(sp)), sp)\n decay = gl.exp(-gl.exp(al) * sp)\n beta = (1.0 / (1.0 + gl.exp(-bv))).to(gl.bfloat16).to(gl.float32)\n return decay, beta\n\n\[email protected]\ndef _recur(state, q, k, value, decay, beta):\n \"\"\"Rows are values, columns are keys; return FP32 state and BF16 core.\"\"\"\n state *= decay\n value -= gl.sum(state * k[None, :], 1)\n value *= beta\n state += value[:, None] * k[None, :]\n return state, gl.sum(state * q[None, :], 1).to(gl.bfloat16)\n\n\[email protected]\ndef _gated_rms(core, gate_input, weight, eps, V: gl.constexpr):\n core = core.to(gl.float32)\n variance = gl.sum(core * core, 0) / V\n normalized = core * gl.rsqrt(variance + eps)\n normalized *= weight.to(gl.float32)\n z = gate_input.to(gl.float32)\n return normalized * (z * (1.0 / (1.0 + gl.exp(-z))))\n\n\[email protected]\ndef _prepare(X, BA, H, IDX, W, ALOG, BIAS, MIX, AB, scale,\n KH: gl.constexpr, VH: gl.constexpr, K: gl.constexpr,\n V: gl.constexpr, BLOCK: gl.constexpr):\n \"\"\"Disjoint Q/K/V heads shift their own history; one extra role prepares gates.\"\"\"\n token = gl.program_id(0).to(gl.uint32)\n group = gl.program_id(1).to(gl.uint32)\n C: gl.constexpr = 2 * KH * K + VH * V\n P: gl.constexpr = C + VH * V\n L: gl.constexpr = gl.BlockedLayout([2], [64], [1], [0])\n r = gl.arange(0, BLOCK, L)\n slot = gl.load(IDX + token).to(gl.int64)\n if slot < 0:\n return\n if group == 2 * KH + VH:\n AL: gl.constexpr = gl.BlockedLayout([1], [64], [1], [0])\n heads = gl.arange(0, VH, AL)\n decay, beta = _gates(BA, ALOG, BIAS, token, heads, VH)\n gl.store(AB + (token * VH + heads) * 2, decay)\n gl.store(AB + (token * VH + heads) * 2 + 1, beta)\n return\n c = gl.where(group < 2 * KH, group * K, 2 * KH * K + (group - 2 * KH) * V) + r\n valid = r < gl.where(group < 2 * KH, K, V)\n x = gl.load(X + token * P + c, valid, other=0)\n hp = H + (slot * C + c) * 3\n h0 = gl.load(hp, valid, other=0)\n h1 = gl.load(hp + 1, valid, other=0)\n h2 = gl.load(hp + 2, valid, other=0)\n WL: gl.constexpr = gl.BlockedLayout([2, 4], [64, 1], [1, 1], [1, 0])\n cc = gl.convert_layout(c, gl.SliceLayout(1, WL))\n cm = gl.convert_layout(valid, gl.SliceLayout(1, WL))\n taps = gl.arange(0, 4, gl.SliceLayout(0, WL))\n weights = gl.load(W + cc[:, None] * 4 + taps[None, :], cm[:, None], other=0)\n w0, w1, w2, w3 = _unpack_weights(weights, L)\n vals = _conv_silu(h0, h1, h2, x, w0, w1, w2, w3)\n gl.store(hp, h1, valid)\n gl.store(hp + 1, h2, valid)\n gl.store(hp + 2, x, valid)\n if group < 2 * KH:\n vals = vals / gl.sqrt(gl.sum(vals * vals, 0) + 1.0e-6)\n if group < KH:\n vals *= scale\n gl.store(MIX + token * C + c, vals, valid)\n\n\[email protected]\ndef _decode_epilogue(X, MIX, AB, S, IDX, NW, OUT, eps,\n KH: gl.constexpr, VH: gl.constexpr, K: gl.constexpr,\n V: gl.constexpr, BK: gl.constexpr, BV: gl.constexpr, B: gl.constexpr):\n pid = gl.program_id(0).to(gl.uint32)\n token, head = pid % B, pid // B\n th = token * VH + head\n kh = head // (VH // KH)\n C: gl.constexpr = 2 * KH * K + VH * V\n P: gl.constexpr = C + VH * V\n L: gl.constexpr = gl.BlockedLayout([4, 4], [4, 16], [8, 1], [1, 0])\n ks = gl.arange(0, BK, gl.SliceLayout(0, L))\n vs = gl.arange(0, BV, gl.SliceLayout(1, L))\n slot = gl.load(IDX + token).to(gl.int64)\n if slot < 0:\n gl.store(OUT + th * V + vs,\n gl.full((BV,), 0, gl.float32, gl.SliceLayout(1, L)), vs < V)\n return\n NL: gl.constexpr = gl.BlockedLayout([2], [64], [8], [0])\n columns = gl.arange(0, BV, NL)\n weight = gl.load(NW + columns, columns < V, other=0)\n gate_input = gl.load(X + token * P + C + head * V + columns, columns < V, other=0)\n base = S + (slot * VH + head) * V * K\n off = vs[:, None] * K + ks[None, :]\n valid = (vs[:, None] < V) & (ks[None, :] < K)\n state = gl.amd.cdna4.buffer_load(base, off, valid, other=0, cache=\"\")\n q = gl.load(MIX + token * C + kh * K + ks, ks < K, other=0)\n k = gl.load(MIX + token * C + KH * K + kh * K + ks, ks < K, other=0)\n v = gl.load(MIX + token * C + 2 * KH * K + head * V + vs, vs < V, other=0)\n decay = gl.load(AB + th * 2)\n beta = gl.load(AB + th * 2 + 1)\n state, core = _recur(state, q, k, v, decay, beta)\n gl.amd.cdna4.buffer_store(state, base, off, valid, cache=\".wt\")\n core = gl.convert_layout(core, NL)\n normalized = _gated_rms(core, gate_input, weight, eps, V)\n gl.store(OUT + th * V + columns, normalized, columns < V)\n\n\[email protected]\ndef _finish_tiles(X, History, Indices, Core, Weight, Out, eps):\n \"\"\"Output roles own complete heads; history roles own disjoint channel blocks.\"\"\"\n VH: gl.constexpr = 16\n V: gl.constexpr = 128\n C: gl.constexpr = 3072\n P: gl.constexpr = 5120\n token = gl.program_id(0).to(gl.uint32)\n role = gl.program_id(1).to(gl.uint32)\n slot = gl.load(Indices + token).to(gl.int64)\n L: gl.constexpr = gl.BlockedLayout([2], [64], [1], [0])\n r = gl.arange(0, V, L)\n if role < VH:\n if slot < 0:\n gl.store(Out + (token * VH + role) * V + r, 0)\n else:\n core = gl.load(Core + (token * VH + role) * V + r).to(gl.float32)\n z = gl.load(X + token * P + C + role * V + r).to(gl.float32)\n weight = gl.load(Weight + r).to(gl.float32)\n norm = _gated_rms(core, z, weight, eps, V)\n gl.store(Out + (token * VH + role) * V + r, norm)\n elif slot >= 0:\n c = (role - VH) * V + r\n hp = History + (slot * C + c) * 3\n h1 = gl.load(hp + 1)\n h2 = gl.load(hp + 2)\n x = gl.load(X + token * P + c)\n gl.store(hp, h1)\n gl.store(hp + 1, h2)\n gl.store(hp + 2, x)\n\n\[email protected]\ndef _qk_convolve(X, History, Weight, token, slot, key_head, scale, NW: gl.constexpr):\n \"\"\"Register-local taps; the two-wave schedule computes Q and K separately.\"\"\"\n if NW == 1:\n L: gl.constexpr = gl.BlockedLayout([2, 2], [64, 1], [NW, 1], [0, 1])\n else:\n L: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [NW // 2, 2], [0, 1])\n r = gl.arange(0, 128, gl.SliceLayout(1, L))\n branch = gl.arange(0, 2, gl.SliceLayout(0, L))\n c = key_head * 128 + r[:, None] + branch[None, :] * 512\n x = gl.load(X + token * 5120 + c).to(gl.float32)\n hp = History + (slot * 3072 + c) * 3\n h0 = gl.load(hp).to(gl.float32)\n h1 = gl.load(hp + 1).to(gl.float32)\n h2 = gl.load(hp + 2).to(gl.float32)\n if NW == 1:\n WL: gl.constexpr = gl.BlockedLayout([2, 2, 4], [64, 1, 1], [NW, 1, 1], [2, 0, 1])\n else:\n WL: gl.constexpr = gl.BlockedLayout([2, 1, 4], [64, 1, 1], [NW // 2, 2, 1], [2, 0, 1])\n cc = gl.convert_layout(c, gl.SliceLayout(2, WL))\n tap = gl.arange(0, 4, gl.SliceLayout(0, gl.SliceLayout(0, WL)))\n weights = gl.load(Weight + cc[:, :, None] * 4 + tap[None, :][None, :, :])\n w0, w1, w2, w3 = _unpack_weights(weights, L)\n qk = _conv_silu(h0, h1, h2, x, w0, w1, w2, w3)\n qk /= gl.sqrt(gl.sum(qk * qk, 0)[None, :] + 1.0e-6)\n if NW != 1:\n # Exchange normalized Q/K between waves before the recurrent row work.\n # convert_layout supplies the required shared-memory synchronization.\n SPLIT: gl.constexpr = gl.BlockedLayout([2, 2], [64, 1], [NW, 1], [0, 1])\n qk = gl.convert_layout(qk, SPLIT)\n q, k = gl.split(qk)\n return q * scale, k\n\n\[email protected]\ndef _value_convolve(X, History, Weight, token, slot, c):\n x = gl.load(X + token * 5120 + c)\n hp = History + (slot * 3072 + c) * 3\n h0 = gl.load(hp)\n h1 = gl.load(hp + 1)\n h2 = gl.load(hp + 2)\n w0 = gl.load(Weight + c * 4)\n w1 = gl.load(Weight + c * 4 + 1)\n w2 = gl.load(Weight + c * 4 + 2)\n w3 = gl.load(Weight + c * 4 + 3)\n return _conv_silu(h0, h1, h2, x, w0, w1, w2, w3)\n\n\[email protected]\ndef _fused_tiles(X, BA, History, State, Indices, ConvWeight, ALog, Bias,\n Core, scale, B: gl.constexpr, ROWS: gl.constexpr):\n \"\"\"Wave-local state rows; B2 dedicates separate waves to Q and K.\"\"\"\n NW: gl.constexpr = 2 if B == 2 else 1\n pid = gl.program_id(0).to(gl.uint32)\n token = pid % B\n head = (pid // B) % 16\n tile = pid // (B * 16)\n th = token * 16 + head\n key_head = head // 4\n L: gl.constexpr = gl.BlockedLayout([1, 4], [8, 8], [NW, 1], [1, 0])\n ki = gl.arange(0, 128, gl.SliceLayout(0, L))\n vi = tile * ROWS + gl.arange(0, ROWS, gl.SliceLayout(1, L))\n slot = gl.load(Indices + token).to(gl.int64)\n if slot < 0:\n gl.store(Core + th * 128 + vi, 0)\n return\n # Overlap the state fetch with independent convolution and gate work.\n base = State + (slot * 16 + head) * 16384\n offset = vi[:, None] * 128 + ki[None, :]\n state = gl.amd.cdna4.buffer_load(base, offset, cache='.cg')\n if B <= 2:\n vv = vi\n else:\n VL: gl.constexpr = gl.BlockedLayout([1], [64], [NW], [0])\n vv = tile * ROWS + gl.arange(0, ROWS, VL)\n value = _value_convolve(X, History, ConvWeight, token, slot, 1024 + head * 128 + vv)\n value = gl.convert_layout(value, gl.SliceLayout(1, L))\n if B <= 2:\n # Pairing neighboring heads keeps transcendental gate work vectorized.\n GL: gl.constexpr = gl.BlockedLayout([1], [64], [NW], [0])\n heads = (head // 2) * 2 + gl.arange(0, 2, GL)\n else:\n heads = head\n decay, beta = _gates(BA, ALog, Bias, token, heads, 16)\n if B <= 2:\n pick = gl.full((1,), head % 2, gl.int32, GL)\n decay = gl.sum(gl.gather(decay, pick, 0), 0)\n beta = gl.sum(gl.gather(beta, pick, 0), 0)\n q, k = _qk_convolve(X, History, ConvWeight, token, slot, key_head, scale, NW)\n q = gl.convert_layout(q, gl.SliceLayout(0, L))\n k = gl.convert_layout(k, gl.SliceLayout(0, L))\n state, core = _recur(state, q, k, value, decay, beta)\n gl.amd.cdna4.buffer_store(state, base, offset, cache='.cs' if B <= 2 else '.wt')\n gl.store(Core + th * 128 + vi, core)\n\n\ndef gdn_fused_decode(projected_qkvz: torch.Tensor, projected_ba: torch.Tensor,\n conv_state: torch.Tensor, delta_state: torch.Tensor,\n cache_indices: torch.Tensor, conv_weight: torch.Tensor,\n a_log: torch.Tensor, dt_bias: torch.Tensor,\n norm_weight: torch.Tensor, *, scale: float,\n eps: float, out: torch.Tensor) -> None:\n \"\"\"Update selected cache rows in place, including changed-slot graph replay.\"\"\"\n tokens = projected_qkvz.shape[0]\n _, vh, v, k = delta_state.shape\n channels = conv_state.shape[1]\n kh = (channels - vh * v) // (2 * k)\n if tokens <= 4 and (kh, vh, k, v) == (4, 16, 128, 128):\n # B2 shares Q/K work across sixteen rows while retaining 256 CTAs.\n # B1/B4 favor independent eight-row waves.\n tile_rows = 16 if tokens == 2 else 8\n waves = 2 if tokens == 2 else 1\n core = torch.empty_like(out)\n _fused_tiles[(tokens * vh * (v // tile_rows),)](\n projected_qkvz, projected_ba, conv_state, delta_state, cache_indices,\n conv_weight, a_log, dt_bias, core, scale, tokens, tile_rows,\n num_warps=waves, waves_per_eu=4 if tokens == 2 else 0)\n # The launch boundary protects all repeated Q/K history readers from\n # the unique history writers, without counters or cross-CTA waits.\n _finish_tiles[(tokens, vh + channels // 128)](\n projected_qkvz, conv_state, cache_indices, core, norm_weight, out,\n eps, num_warps=1)\n return\n mix = torch.empty((tokens, channels), device=projected_qkvz.device, dtype=torch.float32)\n ab = torch.empty((tokens, vh, 2), device=projected_qkvz.device, dtype=torch.float32)\n _prepare[(tokens, 2 * kh + vh + 1)](\n projected_qkvz, projected_ba, conv_state, cache_indices,\n conv_weight, a_log, dt_bias, mix, ab, scale,\n kh, vh, k, v, triton.next_power_of_2(max(k, v)), num_warps=1)\n _decode_epilogue[(tokens * vh,)](\n projected_qkvz, mix, ab, delta_state, cache_indices, norm_weight, out, eps,\n kh, vh, k, v, triton.next_power_of_2(k), triton.next_power_of_2(v), tokens, num_warps=8,\n waves_per_eu=4)\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n out=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 16 rows.\n\nMI355 fused GDN decode for the 16/32/64/96-token, 128-wide workloads.\n\nThe producer owns BF16 history pairs and emits normalized FP32 Q/K, BF16 V,\nand (for B16) FP32 SiLU gates. The consumer recomputes every recurrent value.\nIt omits a 16-byte store only when all four old/new FP32 bit patterns match.\nSlot indirection is read on-device on every invocation, including graph replay.\nThe B96 consumer rotates head issue order between its two token groups while\nretaining whole-head ownership. Other batch schedules and all numerical\noperations remain unchanged.\n\"\"\"\n\nimport torch\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\[email protected]\ndef _bf16_low(x):\n return x.to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _bf16_high(x):\n return (x >> 16).to(gl.uint16).to(gl.bfloat16, bitcast=True).to(gl.float32)\n\n\[email protected]\ndef _conv4(h0, h1, h2, x, w0, w1, w2, w3):\n y = (h0 * w0).to(gl.bfloat16).to(gl.float32)\n y += (h1 * w1).to(gl.bfloat16).to(gl.float32)\n y += (h2 * w2).to(gl.bfloat16).to(gl.float32)\n y += (x * w3).to(gl.bfloat16).to(gl.float32)\n return (y / (1.0 + gl.exp(-y))).to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _scratch_row(C, token, QK: gl.constexpr, STRIDE: gl.constexpr):\n stride: gl.constexpr = STRIDE\n qk = C + token * stride\n return qk, (qk + QK).to(gl.pointer_type(gl.bfloat16))\n\n\[email protected]\ndef _packed_conv(QKVZ, CS, IDX, W, C, scale, CHANNELS: gl.constexpr,\n WIDTH: gl.constexpr, K: gl.constexpr, KH: gl.constexpr,\n TC: gl.constexpr, PREGATE: gl.constexpr, STRIDE: gl.constexpr):\n token = gl.program_id(0)\n group = gl.program_id(1)\n L: gl.constexpr = gl.BlockedLayout([1, 1], [1, 64], [TC, 1], [1, 0])\n JO: gl.constexpr = gl.BlockedLayout([1, 1, 2], [1, 64, 1], [TC, 1, 1], [1, 0, 2])\n O: gl.constexpr = gl.BlockedLayout([1, 2], [1, 64], [TC, 1], [1, 0])\n tile = group * TC + gl.arange(0, TC, gl.SliceLayout(1, L))\n pair = gl.arange(0, K // 2, gl.SliceLayout(0, L))\n pidx = tile[:, None] * (K // 2) + pair[None, :]\n slot = gl.load(IDX + token).to(gl.int64)\n if slot >= 0:\n hist = CS.to(gl.pointer_type(gl.uint32)) + (slot * (CHANNELS // 2) + pidx) * 3\n h0 = gl.load(hist)\n h1 = gl.load(hist + 1)\n h2 = gl.load(hist + 2)\n x = gl.load(QKVZ.to(gl.pointer_type(gl.uint32)) + token * (WIDTH // 2) + pidx)\n wp = W.to(gl.pointer_type(gl.uint32)) + pidx * 4\n w0 = gl.load(wp)\n w1 = gl.load(wp + 1)\n w2 = gl.load(wp + 2)\n w3 = gl.load(wp + 3)\n ya = _conv4(_bf16_low(h0), _bf16_high(h0), _bf16_low(h1), _bf16_low(x),\n _bf16_low(w0), _bf16_high(w0), _bf16_low(w1), _bf16_high(w1))\n yb = _conv4(_bf16_high(h1), _bf16_low(h2), _bf16_high(h2), _bf16_high(x),\n _bf16_low(w2), _bf16_high(w2), _bf16_low(w3), _bf16_high(w3))\n ya = gl.convert_layout(ya, gl.SliceLayout(2, JO))\n yb = gl.convert_layout(yb, gl.SliceLayout(2, JO))\n y = gl.join(ya, yb).reshape((TC, K))\n y = gl.convert_layout(y, O)\n ot = group * TC + gl.arange(0, TC, gl.SliceLayout(1, O))\n if group * TC < 2 * KH:\n y = y / gl.sqrt(gl.sum(y * y, 1)[:, None] + 1.0e-6)\n y = gl.where(ot[:, None] < KH, y * scale, y)\n # A thread owns all three packed words for a disjoint channel pair.\n n0 = (h0 >> 16) | (h1 << 16)\n n1 = (x & 0xffff) | (h2 << 16)\n n2 = (h2 >> 16) | (x & 0xffff0000)\n dirty = (n0 != h0) | (n1 != h1) | (n2 != h2)\n gl.store(hist, n0, dirty)\n gl.store(hist + 1, n1, dirty)\n gl.store(hist + 2, n2, dirty)\n ki = gl.arange(0, K, gl.SliceLayout(0, O))\n cp, vp = _scratch_row(C, token, 2 * KH * K, STRIDE)\n if group * TC < 2 * KH:\n gl.store(cp + ot[:, None] * K + ki[None, :], y)\n else:\n gl.store(vp + (ot[:, None] - 2 * KH) * K + ki[None, :], y)\n if PREGATE and group * TC >= 2 * KH:\n head = ot - 2 * KH\n zo = head[:, None] * K + ki[None, :]\n z = gl.load(QKVZ + token * WIDTH + CHANNELS + zo).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(cp + 2048 + zo, gate)\n\n\[email protected]\ndef _load_gate(QKVZ, W, C, token, head, E: gl.constexpr,\n PREGATE: gl.constexpr, STRIDE: gl.constexpr):\n eo = gl.arange(0, 128, E)\n if PREGATE:\n gate = gl.load(C + token * STRIDE + 2048 + head * 128 + eo)\n else:\n z = gl.load(QKVZ + token * 5120 + 3072 + head * 128 + eo).to(gl.float32)\n gate = z * (1.0 / (1.0 + gl.exp(-z)))\n w = gl.load(W + eo).to(gl.float32)\n return gate, w\n\n\[email protected]\ndef _dirty_quad_sgpr(old, new):\n oev, ood = gl.split(old.reshape((128, 32, 2, 2)))\n nev, nod = gl.split(new.reshape((128, 32, 2, 2)))\n o0, o2 = gl.split(oev)\n o1, o3 = gl.split(ood)\n n0, n2 = gl.split(nev)\n n1, n3 = gl.split(nod)\n o01 = o0.to(gl.uint64) | (o1.to(gl.uint64) << 32)\n o23 = o2.to(gl.uint64) | (o3.to(gl.uint64) << 32)\n n01 = n0.to(gl.uint64) | (n1.to(gl.uint64) << 32)\n n23 = n2.to(gl.uint64) | (n3.to(gl.uint64) << 32)\n # Combine the two lane masks in SGPRs before materializing one predicate.\n # The second output reserves the temporary SGPR pair; VCC is clobbered.\n dirty, _lane_mask = gl.inline_asm_elementwise(\n \"v_cmp_eq_u64_e64 $1, $2, $4;\\n\"\n \"v_cmp_eq_u64_e64 vcc, $3, $5;\\n\"\n \"s_and_b64 vcc, vcc, $1;\\n\"\n \"v_cndmask_b32_e64 $0, 1, 0, vcc;\",\n constraints=\"=&v,=&s,v,v,v,v,~{vcc}\", args=[o01, o23, n01, n23],\n dtype=(gl.uint32, gl.uint64), is_pure=True, pack=1)\n return dirty != 0\n\n\[email protected]\ndef _dirty_native(old, new):\n ol, oh = gl.split(old.reshape((128, 64, 2)))\n nl, nh = gl.split(new.reshape((128, 64, 2)))\n op = ol.to(gl.uint64) | (oh.to(gl.uint64) << 32)\n np = nl.to(gl.uint64) | (nh.to(gl.uint64) << 32)\n pair_dirty = (op != np).reshape((128, 32, 2))\n return gl.max(pair_dirty.to(gl.int32), 2) != 0\n\n\[email protected]\ndef _recurrent(C, BA, AL, DT, DS, IDX, OUT, QKVZ, W, eps: gl.constexpr,\n NW: gl.constexpr, RP: gl.constexpr,\n EP: gl.constexpr, READOUT_FIRST: gl.constexpr, ASM_DIRTY: gl.constexpr,\n GATE_FIRST: gl.constexpr, GROUP: gl.constexpr,\n PREGATE: gl.constexpr, STRIDE: gl.constexpr,\n ROTATE: gl.constexpr):\n th = gl.program_id(0).to(gl.uint32)\n if GROUP == 0:\n token = th\n head = gl.program_id(1).to(gl.uint32)\n else:\n token = (th // (16 * GROUP)) * GROUP + th % GROUP\n head = (th % (16 * GROUP)) // GROUP\n if ROTATE:\n # Reuse the flat grid's token-group quotient to rotate head issue order.\n head = head ^ ((th // (16 * GROUP)) * 8)\n th = token * 16 + head\n kh = head // 4\n L: gl.constexpr = gl.BlockedLayout([RP, 4], [8, 8], [NW, 1], [1, 0])\n E: gl.constexpr = gl.BlockedLayout([EP], [64], [NW], [0])\n ko = gl.arange(0, 128, gl.SliceLayout(0, L))\n vo = gl.arange(0, 128, gl.SliceLayout(1, L))\n slot = gl.load(IDX + token)\n if slot < 0:\n gl.store(OUT + th * 128 + vo, gl.full((128,), 0, gl.float32, gl.SliceLayout(1, L)))\n else:\n so = vo[:, None] * 128 + ko[None, :]\n so += slot * 262144 + head * 16384\n state = gl.amd.cdna3.buffer_load(DS, so, cache=\".cv\")\n old_bits = state.to(gl.uint32, bitcast=True)\n cp, vp = _scratch_row(C, token, 1024, STRIDE)\n q = gl.load(cp + kh * 128 + ko)\n k = gl.load(cp + 512 + kh * 128 + ko)\n v = gl.load(vp + head * 128 + vo).to(gl.float32)\n a = gl.load(BA + token * 32 + 16 + head).to(gl.float32)\n b = gl.load(BA + token * 32 + head).to(gl.float32)\n al = gl.load(AL + head)\n dt = gl.load(DT + head).to(gl.float32)\n x = a + dt\n sp = gl.where(x <= 20.0, gl.log(1.0 + gl.exp(x)), x)\n decay_log = -gl.exp(al) * sp\n beta = (1.0 / (1.0 + gl.exp(-b))).to(BA.dtype.element_ty).to(gl.float32)\n decay = gl.exp(decay_log)\n if GATE_FIRST:\n gate, w = _load_gate(QKVZ, W, C, token, head, E, PREGATE, STRIDE)\n state *= decay\n v -= gl.sum(state * k[None, :], 1)\n if not GATE_FIRST:\n gate, w = _load_gate(QKVZ, W, C, token, head, E, PREGATE, STRIDE)\n v *= beta\n state += v[:, None] * k[None, :]\n if READOUT_FIRST:\n core = gl.sum(state * q[None, :], 1).to(gl.bfloat16)\n bits_changed = old_bits ^ state.to(gl.uint32, bitcast=True)\n chunks = bits_changed.reshape((128, 32, 4))\n if ASM_DIRTY:\n dirty = _dirty_quad_sgpr(old_bits, state.to(gl.uint32, bitcast=True))\n dirty = gl.convert_layout(dirty, gl.SliceLayout(2, chunks.type.layout))\n else:\n dirty = _dirty_native(old_bits, state.to(gl.uint32, bitcast=True))\n dirty = gl.convert_layout(dirty, gl.SliceLayout(2, chunks.type.layout))\n mask = (dirty[:, :, None] | ((chunks & 0) != 0)).reshape((128, 128))\n gl.amd.cdna3.buffer_store(state, DS, so, mask, cache=\".wt\")\n if not READOUT_FIRST:\n core = gl.sum(state * q[None, :], 1).to(gl.bfloat16)\n core = gl.convert_layout(core.to(gl.float32), E)\n eo = gl.arange(0, 128, E)\n variance = gl.sum(core * core, 0) / 128\n r = gl.rsqrt(variance + eps)\n y = core * r\n y *= w\n y *= gate\n gl.store(OUT + th * 128 + eo, y)\n\n\n\ndef gdn_fused_decode(projected_qkvz: torch.Tensor, projected_ba: torch.Tensor,\n conv_state: torch.Tensor, delta_state: torch.Tensor,\n cache_indices: torch.Tensor, conv_weight: torch.Tensor,\n a_log: torch.Tensor, dt_bias: torch.Tensor, norm_weight: torch.Tensor,\n *, scale: float, eps: float, out: torch.Tensor) -> None:\n tokens, width = projected_qkvz.shape\n _, vh, v, k = delta_state.shape\n channels = width - vh * v\n kh = (channels - vh * v) // (2 * k)\n pregate = tokens == 16\n small = tokens <= 32\n scratch_words = 2 * kh * k + vh * v // 2 + (vh * v if pregate else 0)\n conv = torch.empty((tokens, scratch_words), device=projected_qkvz.device, dtype=torch.float32)\n # Two-wave producers improve CTA coverage at B16 and B64.\n tc = 2 if tokens in (16, 64) else 4\n _packed_conv[(tokens, channels // (tc * k))](\n projected_qkvz, conv_state, cache_indices, conv_weight, conv, scale,\n channels, width, k, kh, tc, PREGATE=pregate, STRIDE=scratch_words,\n num_warps=tc,\n )\n waves = 4 if small else 8\n group = {16: 16, 32: 32, 64: 0, 96: 48}[tokens]\n grid = (tokens, vh) if group == 0 else (tokens * vh,)\n _recurrent[grid](\n conv, projected_ba, a_log, dt_bias, delta_state, cache_indices, out,\n projected_qkvz, norm_weight, eps,\n NW=waves, RP=2 if tokens == 32 else 1, EP=2 if small else 1,\n READOUT_FIRST=tokens != 16, ASM_DIRTY=False, GATE_FIRST=small,\n GROUP=group, PREGATE=pregate, STRIDE=scratch_words, ROTATE=tokens == 96,\n num_warps=waves, waves_per_eu=0 if small else 4,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n out=normalized,\n )\n" |
| "sources": [ | ||
| { | ||
| "path": "kernel.py", | ||
| "content": "# Created by OpenAI\n\"\"\"Qwen3.5 GDN decode with BF16 output for MI355X (gfx950), scheduled for 2 rows.\n\nTwo-launch Gluon GDN decode for MI355.\n\nThe launch boundary is the global history read/commit barrier. Both launches\nread live slot indices, including negative padding slots, on every replay.\nState stores are elided only when every FP32 bit in a 64-byte segment matches.\nHistory writes are also suppressed when their BF16 bits match exactly.\nB2 uses four cooperative Q/K/V producer waves; B1 retains register-resident Q.\nNeither optimization changes the computed output or state ownership.\n\"\"\"\n\nfrom typing import NamedTuple\nimport torch\nimport triton\nfrom triton.experimental import gluon\nfrom triton.experimental.gluon import language as gl\n\n\nclass _Schedule(NamedTuple):\n rows: int\n key_lanes: int\n warps: int\n history_chunk: int\n history_vector: int\n norm_vector: int\n state_store: str = \".cs\"\n wide_conv: bool = True\n state_group: int = 0\n pool_offsets: bool = False\n\n\n_SCHEDULES = {\n 1: _Schedule(\n 8, 16, 2, 64, 4, 1, wide_conv=False, state_group=16, pool_offsets=True\n ),\n 2: _Schedule(16, 16, 4, 128, 2, 1, state_group=16, pool_offsets=True),\n 4: _Schedule(\n 32, 8, 4, 256, 2, 2, state_store=\"\", state_group=16, pool_offsets=True\n ),\n 8: _Schedule(32, 8, 4, 256, 2, 2, state_group=16, pool_offsets=True),\n}\n\n\[email protected]\ndef _exp(x):\n return gl.exp2(x * 1.4426950408889634)\n\n\[email protected]\ndef _or_bits(a, b):\n return a | b\n\n\[email protected]\ndef _convolve_read(\n X,\n History,\n Weight,\n token,\n slot,\n channel,\n valid,\n CHANNELS: gl.constexpr,\n Z_CHANNELS: gl.constexpr,\n WIDE: gl.constexpr,\n):\n if WIDE:\n hist = History + slot.to(gl.int64) * (CHANNELS * 3) + channel.to(gl.int64) * 3\n weight = Weight + channel.to(gl.int64) * 4\n xp = X + token.to(gl.int64) * (CHANNELS + Z_CHANNELS) + channel.to(gl.int64)\n else:\n hist = History + (slot * CHANNELS + channel) * 3\n weight = Weight + channel * 4\n xp = X + token * (CHANNELS + Z_CHANNELS) + channel\n x = gl.load(xp, valid, other=0)\n h0 = gl.load(hist, valid, other=0)\n h1 = gl.load(hist + 1, valid, other=0)\n h2 = gl.load(hist + 2, valid, other=0)\n w0 = gl.load(weight, valid, other=0)\n w1 = gl.load(weight + 1, valid, other=0)\n w2 = gl.load(weight + 2, valid, other=0)\n w3 = gl.load(weight + 3, valid, other=0)\n acc = gl.full(channel.shape, 0, gl.float32, channel.type.layout)\n acc += (h0.to(gl.float32) * w0.to(gl.float32)).to(gl.bfloat16)\n acc += (h1.to(gl.float32) * w1.to(gl.float32)).to(gl.bfloat16)\n acc += (h2.to(gl.float32) * w2.to(gl.float32)).to(gl.bfloat16)\n acc += (x.to(gl.float32) * w3.to(gl.float32)).to(gl.bfloat16)\n value = acc * (1.0 / (1.0 + _exp(-acc)))\n return value.to(gl.bfloat16).to(gl.float32)\n\n\[email protected]\ndef _gate_values(BA, ALog, DtBias, token, head, VH: gl.constexpr):\n a = gl.load(BA + token * 2 * VH + VH + head).to(gl.float32)\n b = gl.load(BA + token * 2 * VH + head).to(gl.float32)\n a_log = gl.load(ALog + head)\n bias = gl.load(DtBias + head).to(gl.float32)\n softplus_in = a + bias\n softplus = gl.where(\n softplus_in <= 20.0, gl.log(1.0 + _exp(softplus_in)), softplus_in\n )\n decay = _exp(-_exp(a_log) * softplus)\n beta = (1.0 / (1.0 + _exp(-b))).to(gl.bfloat16).to(gl.float32)\n return (decay, beta)\n\n\[email protected]\ndef _normalize_columns(values):\n invnorm = 1.0 / gl.sqrt(gl.sum(values * values, 0) + 1e-06)\n return values * invnorm[None, :]\n\n\[email protected]\ndef _stage_columns(values):\n SIZE: gl.constexpr = values.shape[0] * values.shape[1]\n return gl.allocate_shared_memory(\n gl.float32,\n (SIZE,),\n gl.SwizzledSharedLayout(1, 1, 1, [0]),\n values.permute((1, 0)).reshape((SIZE,)),\n )\n\n\[email protected]\ndef _prepare_tiled_qkv(\n X,\n BA,\n History,\n Weight,\n ALog,\n DtBias,\n token,\n slot,\n head,\n vidx,\n vmask,\n scale,\n KH: gl.constexpr,\n VH: gl.constexpr,\n K: gl.constexpr,\n V: gl.constexpr,\n BK: gl.constexpr,\n S: gl.constexpr,\n):\n khead = head // (VH // KH)\n NW: gl.constexpr = gl.num_warps()\n QW: gl.constexpr = min(NW, max(1, gl.cdiv(BK, 128)))\n layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [QW, NW // QW], [0, 1])\n ki = gl.arange(0, BK, gl.SliceLayout(1, layout))\n kind = gl.arange(0, 2, gl.SliceLayout(0, layout))\n channels = (khead + kind[None, :] * KH) * K + ki[:, None]\n C: gl.constexpr = 2 * KH * K + VH * V\n v = _convolve_read(\n X,\n History,\n Weight,\n token,\n slot,\n 2 * KH * K + head * V + vidx,\n vmask,\n C,\n VH * V,\n S.wide_conv,\n )\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n qk = _convolve_read(\n X,\n History,\n Weight,\n token,\n slot,\n channels,\n ki[:, None] < K,\n C,\n VH * V,\n S.wide_conv,\n )\n qk = _normalize_columns(qk)\n return (qk, v, decay, beta)\n\n\[email protected]\ndef _stage_qkv(\n X,\n History,\n Weight,\n token,\n slot,\n head,\n KH: gl.constexpr,\n VH: gl.constexpr,\n K: gl.constexpr,\n V: gl.constexpr,\n BK: gl.constexpr,\n S: gl.constexpr,\n):\n conv_layout: gl.constexpr = gl.BlockedLayout([2, 1], [64, 1], [1, 4], [0, 1])\n ci = gl.arange(0, BK, gl.SliceLayout(1, conv_layout))\n kind = gl.arange(0, 4, gl.SliceLayout(0, conv_layout))\n khead = head // (VH // KH)\n C: gl.constexpr = 2 * KH * K + VH * V\n channel_base = gl.where(\n kind[None, :] < 2, (khead + kind[None, :] * KH) * K, 2 * KH * K + head * V\n )\n channel_base = gl.multiple_of(channel_base, [K, K])\n channels = channel_base + ci[:, None]\n qkv = _convolve_read(\n X, History, Weight, token, slot, channels, ci[:, None] < K, C, VH * V, True\n )\n qkv = gl.where(kind[None, :] < 2, _normalize_columns(qkv), qkv)\n return _stage_columns(qkv)\n\n\[email protected]\ndef _recurrent_small(\n X,\n BA,\n History,\n State,\n Slots,\n Weight,\n ALog,\n DtBias,\n Core,\n scale: gl.constexpr,\n T: gl.constexpr,\n KH: gl.constexpr,\n VH: gl.constexpr,\n K: gl.constexpr,\n V: gl.constexpr,\n BK: gl.constexpr,\n S: gl.constexpr,\n):\n BV: gl.constexpr = S.rows\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n CACHE: gl.constexpr = \"\"\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * BV + gl.arange(0, BV, gl.SliceLayout(1, layout))\n gl.static_assert(V % BV == 0, \"Each CTA must own complete value tiles\")\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n if slot < 0:\n gl.store(Core + row * V + vidx, 0.0, vmask)\n return\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n if S.pool_offsets:\n state_base = State\n offsets += (slot * VH + head) * (V * K)\n mask = vmask[:, None] & (kidx[None, :] < K)\n state = gl.amd.cdna4.buffer_load(state_base, offsets, mask, other=0, cache=CACHE)\n qk, v, decay, beta = _prepare_tiled_qkv(\n X,\n BA,\n History,\n Weight,\n ALog,\n DtBias,\n token,\n slot,\n head,\n vidx,\n vmask,\n scale,\n KH,\n VH,\n K,\n V,\n BK,\n S,\n )\n split_layout: gl.constexpr = gl.BlockedLayout(\n [4, 2], [KL, 64 // KL], [1, NW], [0, 1]\n )\n q, k = gl.split(gl.convert_layout(qk, split_layout))\n q *= scale\n q = gl.convert_layout(q, gl.SliceLayout(0, layout))\n k = gl.convert_layout(k, gl.SliceLayout(0, layout))\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n GROUP: gl.constexpr = S.state_group\n gl.static_assert(BK % GROUP == 0)\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n mask = (\n (changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))\n ).reshape((BV, BK))\n result = gl.sum(state * q[None, :], 1)\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n gl.store(Core + row * V + vidx, result.to(gl.bfloat16), vmask)\n\n\[email protected]\ndef _recurrent(\n X,\n BA,\n History,\n State,\n Slots,\n Weight,\n ALog,\n DtBias,\n Core,\n scale,\n T: gl.constexpr,\n KH: gl.constexpr,\n VH: gl.constexpr,\n K: gl.constexpr,\n V: gl.constexpr,\n BK: gl.constexpr,\n S: gl.constexpr,\n):\n BV: gl.constexpr = S.rows\n KL: gl.constexpr = S.key_lanes\n NW: gl.constexpr = gl.num_warps()\n CACHE: gl.constexpr = \".cg\"\n pid = gl.program_id(0)\n tile = gl.program_id(1)\n gl.assume(pid >= 0)\n gl.assume(tile >= 0)\n token = pid % T\n head = pid // T\n row = token * VH + head\n layout: gl.constexpr = gl.BlockedLayout([1, 4], [64 // KL, KL], [NW, 1], [1, 0])\n kidx = gl.arange(0, BK, gl.SliceLayout(0, layout))\n vidx = tile * BV + gl.arange(0, BV, gl.SliceLayout(1, layout))\n gl.static_assert(V % BV == 0, \"Each CTA must own complete value tiles\")\n vmask = gl.full((BV,), True, gl.int1, gl.SliceLayout(1, layout))\n slot = gl.load(Slots + token)\n result = gl.full((BV,), 0, gl.float32, gl.SliceLayout(1, layout))\n if slot >= 0:\n state_base = State + (slot.to(gl.int64) * VH + head) * (V * K)\n offsets = vidx[:, None] * K + kidx[None, :]\n if S.pool_offsets:\n state_base = State\n offsets += (slot * VH + head) * (V * K)\n mask = vmask[:, None] & (kidx[None, :] < K)\n state = gl.amd.cdna4.buffer_load(\n state_base, offsets, mask, other=0, cache=CACHE\n )\n gl.static_assert(NW == 4 and BK == K and (K == V) and (BK % BV == 0))\n staged = _stage_qkv(X, History, Weight, token, slot, head, KH, VH, K, V, BK, S)\n decay, beta = _gate_values(BA, ALog, DtBias, token, head, VH)\n k = staged.slice(BK, BK).load(gl.SliceLayout(0, layout))\n v = (\n staged._reinterpret(\n shape=(4 * BK // BV, BV), layout=gl.SwizzledSharedLayout(1, 1, 1, [0])\n )\n .index(2 * BK // BV + tile)\n .load(gl.SliceLayout(1, layout))\n )\n original_bits = state.to(gl.uint32, bitcast=True)\n state *= decay\n v = (v - gl.sum(state * k[None, :], 1)) * beta\n state += v[:, None] * k[None, :]\n GROUP: gl.constexpr = S.state_group\n gl.static_assert(BK % GROUP == 0)\n changed = state.to(gl.uint32, bitcast=True) ^ original_bits\n changed = gl.reduce(changed.reshape((BV, BK // GROUP, GROUP)), 2, _or_bits)\n mask = (\n (changed[:, :, None] != 0) & mask.reshape((BV, BK // GROUP, GROUP))\n ).reshape((BV, BK))\n gl.amd.cdna4.buffer_store(state, state_base, offsets, mask, cache=S.state_store)\n q = staged.slice(0, BK).load(gl.SliceLayout(0, layout))\n result = gl.sum(state * q[None, :], 1)\n result *= scale\n gl.store(Core + row * V + vidx, result.to(gl.bfloat16), vmask)\n\n\[email protected]\ndef _commit_history(\n X,\n History,\n token,\n slot,\n role,\n C: gl.constexpr,\n VH: gl.constexpr,\n V: gl.constexpr,\n S: gl.constexpr,\n):\n CHUNK: gl.constexpr = S.history_chunk\n HP: gl.constexpr = S.history_vector\n idx = gl.arange(0, CHUNK, gl.BlockedLayout([HP], [64], [1], [0]))\n channel = (role - VH) * CHUNK + idx\n gl.static_assert(C % CHUNK == 0, \"History workers own complete chunks\")\n valid = gl.full((CHUNK,), True, gl.int1, gl.BlockedLayout([HP], [64], [1], [0]))\n hp = History + (slot * C + channel) * 3\n x = gl.load(X + token * (C + VH * V) + channel, valid, other=0)\n h1 = gl.load(hp + 1, valid, other=0)\n h2 = gl.load(hp + 2, valid, other=0)\n h0 = gl.load(hp, valid, other=0)\n old0 = h0.to(gl.uint16, bitcast=True)\n old1 = h1.to(gl.uint16, bitcast=True)\n old2 = h2.to(gl.uint16, bitcast=True)\n new2 = x.to(gl.uint16, bitcast=True)\n valid = valid & ((old0 != old1) | (old1 != old2) | (old2 != new2))\n gl.store(hp, h1, valid)\n gl.store(hp + 1, h2, valid)\n gl.store(hp + 2, x, valid)\n\n\[email protected]\ndef _finish(\n X,\n History,\n Slots,\n Core,\n NormWeight,\n Out,\n eps,\n C: gl.constexpr,\n VH: gl.constexpr,\n V: gl.constexpr,\n BLOCK: gl.constexpr,\n S: gl.constexpr,\n):\n NP: gl.constexpr = S.norm_vector\n token = gl.program_id(0)\n role = gl.program_id(1)\n slot = gl.load(Slots + token)\n if role < VH:\n idx = gl.arange(0, BLOCK, gl.BlockedLayout([NP], [64], [1], [0]))\n row = token * VH + role\n if slot < 0:\n gl.store(Out + row * V + idx, 0, idx < V)\n else:\n core = gl.load(Core + row * V + idx, idx < V, other=0).to(gl.float32)\n variance = gl.sum(core * core, 0) / V\n normalized = core * gl.rsqrt(variance + eps)\n normalized *= gl.load(NormWeight + idx, idx < V, other=0).to(gl.float32)\n z = gl.load(\n X + token * (C + VH * V) + C + role * V + idx, idx < V, other=0\n ).to(gl.float32)\n normalized *= z * (1.0 / (1.0 + gl.exp(-z)))\n gl.store(Out + row * V + idx, normalized, idx < V)\n elif slot >= 0:\n _commit_history(X, History, token, slot, role, C, VH, V, S)\n\n\ndef gdn_fused_decode(\n projected_qkvz: torch.Tensor,\n projected_ba: torch.Tensor,\n conv_state: torch.Tensor,\n delta_state: torch.Tensor,\n cache_indices: torch.Tensor,\n conv_weight: torch.Tensor,\n a_log: torch.Tensor,\n dt_bias: torch.Tensor,\n norm_weight: torch.Tensor,\n *,\n scale: float,\n eps: float,\n output: torch.Tensor,\n) -> None:\n tokens = projected_qkvz.shape[0]\n _, v_heads, v_dim, k_dim = delta_state.shape\n channels = conv_state.shape[1]\n k_heads = (channels - v_heads * v_dim) // (2 * k_dim)\n schedule = _SCHEDULES[tokens]\n if delta_state.numel() * delta_state.element_size() >= 2**31:\n schedule = schedule._replace(pool_offsets=False)\n recurrent = _recurrent_small if tokens == 1 else _recurrent\n recurrent[tokens * v_heads, triton.cdiv(v_dim, schedule.rows)](\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n output,\n scale,\n tokens,\n k_heads,\n v_heads,\n k_dim,\n v_dim,\n triton.next_power_of_2(k_dim),\n schedule,\n num_warps=schedule.warps,\n num_stages=1,\n )\n _finish[tokens, v_heads + triton.cdiv(channels, schedule.history_chunk)](\n projected_qkvz,\n conv_state,\n cache_indices,\n output,\n norm_weight,\n output,\n eps,\n channels,\n v_heads,\n v_dim,\n triton.next_power_of_2(v_dim),\n schedule,\n num_warps=1,\n )\n\n\ndef run(\n *,\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale,\n eps,\n normalized,\n):\n gdn_fused_decode(\n projected_qkvz,\n projected_ba,\n conv_state,\n delta_state,\n cache_indices,\n conv_weight,\n a_log,\n dt_bias,\n norm_weight,\n scale=scale,\n eps=eps,\n output=normalized,\n )\n" |
* 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

Why
Qwen3.5 GDN decode on MI355X gets 12 Gluon kernels created by OpenAI, each running the decode in one or two launches between the projections:
Scope
requires: triton>=3.8,kernel.author: openai, each source starting with# Created by OpenAI.[email protected]atn_tokens64.[email protected], one per Point at 1, 2, 4, 8, 16, 32, 64, 96, 128, 192 and 256 rows.cd00c50e…(1.461x), and dispatch serves the better measured one.out_projis unquantized BF16, not block FP8, so_takes_fp8_groupsfails. A separate PR, feat(plugins): serve Qwen3.5 GDN decode with unquantized projections on the BF16 op #76, adds the route branch for unquantized projections. Either PR can merge first, and the MXFP4 checkpoint is served once both are in.values/scales, ornormalized. The FP8 kernel's BF16 normalized tensor stays a per-call scratch.runentry.Tradeoffs
out_projthen runs; if the FP8 kernel is slower, drop its schema.n_slotsis 2N − 1 for N rows. It can be any size and dispatch ignores it. The bench draws inputs on the GPU, so which sets hold the contract's one-1padding row cannot be chosen. At 2N − 1 slots each set holds it with probability 1/2.Verification
Environment: head
4be027e, Mac CPU only: Python 3.12.11, torch 2.8.0 (CPU), no Triton, SGLang or AITER. GPU validation is this head's CI run withci:gpu.Gate overrides: none
Kernels
ci:gpu), 1 Pointci:gpu), 11 PointsCPU checks on this head:
python -m aklr export check: exit 0.pytest -q tests/plugins/sglang tests/ops: 179 passed, 62 skipped, as onmain.pytest -q tests: 55 failed, 599 passed, 161 skipped, 1 error. The FAILED/ERROR set is identical tomain's, all environment-only.pre-commit run --files <schemas>: passed.max(amax, 1e-10) * (1/448).out_of_contract, and N ± 1 rows giveno_workload.Validation log (CPU: audit only; bench is this head's CI)
Not run
validate --base origin/main --stages audit,bench) on MI355X: no local GPU. It is this head's CI run withci:gpu.pytest -m gpu).AKLR_SGLANG_PLUGIN=1. The route has not run these kernels inside a real SGLang graph capture.Risk
Affects: Qwen3.5 attention-TP4 GDN decode on MI355X.
If wrong:
failed: with ±2 ulp noise on exp, rsqrt and division, the BF16 model exceeded thenormalizedbound in 2 of 99 Point/set draws, 4.1x at 128 rows and 1.1x at 256. In both, the BF16 rounding of beta (0.42 float32 ulp from a midpoint) flips, and cancellation in the core enlarges the 1-ulp change in one output element. This holds for any kernel on[email protected].Undo:
[email protected]sends 64 rows back to the BF16 op, together with every other Point of that op onmain(the BF16 op or SGLang there).[email protected]turns the BF16 op off,main's schema included.git revert, which drops only these schemas.🤖 Generated with Claude Code