Repository navigation
[Triton/Gluon] Add fused Kimi-K3 KDA whole-layer ops (gfx950, TP8) - #6550
karverma-amd wants to merge 7 commits into
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
There was a problem hiding this comment.
🟡 Changes recommended
Decode drops supported tail rows, tensor checks leave unsafe inputs accepted, and tests and benchmarks are missing.
8 open findings
Recurrence grid skips the final row for non-divisible batch sizes · New Require state_indices on the input device · New Validate output tensor shape, dtype, device, and contiguity · New Require contiguous initial-state flags · New Require cache metadata and tensors on qkv device · New Guard architecture probing with lazy imports · New Add decode tests and benchmark · New Add prefill tests and benchmark · New
What changed in this PR
Adds model-specific Kimi-K3 Delta Attention operations to AITER’s Gluon backend for gfx950 with TP8.
Changes:
- Adds ragged prefill with in-place cache updates.
- Adds decode projections, recurrence, and rank-local output projection.
- Adds public wrappers with support predicates and lazy kernel imports.
| File | Description |
|---|---|
aiter/ops/triton/kimi_delta_attn/fused_layer_prefill.py |
Prefill validation and dispatch. |
aiter/ops/triton/kimi_delta_attn/fused_layer_decode.py |
Decode validation and batch routing. |
aiter/ops/triton/kimi_delta_attn/__init__.py |
Public operation exports. |
aiter/ops/triton/_gluon_kernels/gfx950/kimi_delta_attn/fused_kda_layer_prefill.py |
Chunked prefill pipeline and cache updates. |
aiter/ops/triton/_gluon_kernels/gfx950/kimi_delta_attn/fused_kda_layer_decode.py |
Decode schedules and output projection. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| ): | ||
|
|
||
| m = x.shape[0] | ||
| group = 8 |
| if tuple(state_indices.shape) != (m,) or not state_indices.is_contiguous(): | ||
| return False, f"cache indices must be contiguous [{m}]" |
| f"kimi_kda_fused_layer_decode does not support this call: {reason}" | ||
| ) | ||
|
|
||
| tile = _load_tile(_select_tile_key(x.shape[0])) |
| or tuple(has_initial_state.shape) != (sequences,) | ||
| ): | ||
| return False, f"has_initial_state must be bool [{sequences}]" |
| ): | ||
| return False, f"has_initial_state must be bool [{sequences}]" | ||
|
|
||
| return True, "" |
|
|
||
| import torch | ||
|
|
||
| from aiter.ops.triton.utils._triton.arch_info import get_arch |
| return True, "" | ||
|
|
||
|
|
||
| def kimi_kda_fused_layer_decode( |
| return True, "" | ||
|
|
||
|
|
||
| def kimi_kda_fused_layer_prefill( |
Whole rank-local Kimi Delta Attention layer kernels for Kimi-K3 on
MI355X (gfx950):
- Prefill: ragged-batch gated-delta core (forget-B + beta sigmoid +
causal conv + fp32 chunked gated-delta scan + gated RMSNorm), single
Gluon launch; caller applies o_proj.
- Decode: whole-layer fused step (QKVG/beta-forget-A projections + conv
+ single-token gated-delta recurrence + gated RMSNorm + fused O matmul)
returning the rank-local O partial for the caller's TP reduce.
Public wrappers expose kimi_kda_fused_layer_{prefill,decode} with
*_supported() predicates (gfx950 + Triton >= 3.8 gate, lazy tile import,
fail-closed), mirroring the fused_gdn_prefill_qkvz pattern. Decode
dispatch routes by batch range to {m64, m256}, chosen from an on-device
tile-vs-tile bake-off across every real decode tier (the two general
schedules dominate; the per-size variants are never fastest and the
serial catch-all is 2-8x slower at large m).
Kernels ported from the validated Artemis Kimi-K3 MI355X TP8 pack.
52e407a to
4b44303
Compare
…tests Decode: - Gate m>64 on divisibility by the m256 recurrence group (8): the schedule tiles the recurrence as `m // group`, so a non-multiple m would silently skip its tail rows. Non-divisible m now falls back to native. (Every real cuda-graph decode tier above 64 is a multiple of 8; m64 tiles per-row and needs no such guard.) - Validate output_tensor shape/dtype/device/contiguity before the kernel writes it. - Require state_indices on the input device. Prefill: - Require conv/temporal cache, cache indices, cu_seqlens and has_initial_state on the qkv device. - Require a contiguous has_initial_state. Both: - Probe the GPU arch lazily and fail closed if it can't be read, so the module stays importable on a CPU-only / non-ROCm host. Tests/bench: - Add decode + prefill tests (dispatch table incl. the divisibility guard, fail-closed gates, on-device run/in-place/determinism, output_tensor rejection) and a latency benchmark. 28 pass on gfx950. Repo-rule compliance (aiter/ops/triton rules 5, 10, 20, 29): - Move the host launch functions into the public wrappers so the Gluon tile modules are torch-free (rule 10); each launcher imports its tile kernels lazily, mirroring the fused_gdn_prefill_qkvz layout. Launchers run at cuda-graph capture, so the lazy import adds no decode-replay overhead. - Give each launched tile kernel a make_kernel_repr repr= (rule 5), so traces name the compiled variant by its shape/tile/path-flag keys. - Call the public `shared_memory_descriptor.reinterpret` (not the private `_reinterpret`) in the m256 tiles, matching every other aiter Gluon kernel and the ROCm Triton 3.8 wheel aiter CI uses; the private name is absent there. Validated 28/28 against that exact wheel (git7cb7b059). - Clear the ruff 0.16.0 findings on the changed files: collapse single-child nested ifs, drop a dead local and an unused unpack, and rename the ambiguous `O` kernel argument to `OUT`. All 28 gfx950 tests still pass after the refactor.
4b44303 to
4a0592b
Compare
…initial-state + cache updates Addresses Copilot review: - Put the fused-layer test in op_tests/triton_tests/kimi_delta_attn/ to match the wrapper folder (Triton test rule 1), not attention/. - Assert the conv/recurrent caches change in place on decode and prefill. - Add a prefill variant that sets has_initial_state to exercise the initial-state path.
|
Addressed the feedback. - Thread: decode — “Require state_indices on the input device” (
|
|
|
||
| @on_device | ||
| @pytest.mark.parametrize("m", [1, 8, 32, 64, 96, 128, 192, 256]) | ||
| def test_decode_runs_inplace_deterministic(m): |
There was a problem hiding this comment.
What is the purpose of this test? It is not comparing to a reference. Comparing to itself seems meaningless?
| @@ -0,0 +1,1691 @@ | |||
| """Selected kda layer decode schedules and shared helpers.""" | |||
There was a problem hiding this comment.
the duplicated device math is a large maintenance surface. A fix
to a shared helper does not reach this copy. This is the "no duplicate kernels,
common functions go to utils" convention.
This is reimplementing conv1d, GD scan, rmsnorm etc.
The decode and prefill Gluon kernels each defined a local sigmoid (exp2- and exp-form). Replace both with the shared common.utils.sigmoid, as gfx950/attention/kda_decode.py already does. The import also installs the reinterpret compat shim from common.utils (it aliases shared_memory_descriptor._reinterpret to reinterpret on the Triton 3.8 wheel that lacks the new name). The m256 decode schedule calls .reinterpret, so without the shared import the m256 tiles (m=96/128/192/ 256) fail to compile on Triton 3.8. The decode kernel now imports it, so those tiles compile. Decode latencies are unchanged.
Replace the decode and prefill *_runs_inplace_deterministic tests, which only compared the kernel to itself, with correctness checks against an independent reference built from the native aiter ops the fused kernels replace. Decode: QKVG/forget projections + native fused_kda_decode + O matmul. Prefill: native causal_conv1d_split_qkv (+SiLU) + chunk_kimi_delta_attn + gated RMSNorm. Both keep the in-place / aliasing contract asserts and add assert_close on the output (and the in-place state update). The references match to ~1e-4 over every covered shape and both initial-state paths.
|
Thanks @vgokhale. Addressed both points. Tests — compare to a reference, not to themselvesYou're right that the
Both keep the in-place / aliasing contract asserts; the Duplicated device math — shared helpers, plus a real bug it surfacedFolded the two local sigmoid copies (decode That import also surfaced a real bug: the decode kernel called On conv1d / GD-scan / gated-RMSNorm specifically: I looked at hoisting these too, but each is fused into its schedule's tiling and data movement — per-row (m64), grouped (m256), and chunked-ragged with prefix gather/scatter (prefill) — with the reductions on different axes and Gluon layouts. A single shared helper would either not fit all three schedules or give back the hand-tuned latency the separate schedules exist for, and they're Gluon so they can't call the existing Triton conv/rmsnorm device helpers anyway. I kept the genuinely-shared scalar math (the activation + the shim) shared and left the layout-bound tiling per schedule. Happy to revisit if you have a specific extraction in mind. |
omuhamma
left a comment
There was a problem hiding this comment.
Can you attach some performance numbers to this? There are some very similar files that exist in aiter for KDA. The main difference I can spot from your chunked kernel compared to the others is that qkv are before the CONV is applied. The decode KDA looks very similar to me
Flash KDA: #6177
Chunk KDA: https://github.com/ROCm/aiter/blob/main/aiter/ops/triton/attention/chunk_kda.py
Decode KDA: https://github.com/ROCm/aiter/blob/main/aiter/ops/triton/attention/kda.py
|
Thanks @omuhamma — numbers below, plus how this differs from the existing KDA ops. How this differs from Decode / Chunk / Flash KDA
This PR fuses the whole rank-local layer into a single launch per path: So the decode kernel here looks similar to 1. Op-level: fused vs. the native path it replacesSame component sequence the correctness test validates against ( Decode (µs/call):
Prefill (µs/call):
Fused decode is 1.6–2.0× the native path; fused prefill 3.7–4.7× (prefill gains more — the chunked mixer + conv + norm are heavier relative to the projections, so more is saved by fusing). 2. End-to-end (Kimi-K3, sglang, TP8 MI355X)The op-level win dilutes at the model level because the KDA layer is only a slice of total decode/prefill time. Speedup = native-unfused / this-PR (>1.0 = faster):
+4–9% end-to-end in 10/11 points. The one regression is 5K/500 @ C256 (native ~3.4% faster): at max concurrency the layer is already saturated, so fusion's launch-overhead savings stop paying off. GSM8K parity held across both arms (0.95x). |
Times the single fused decode/prefill kernel against the native aiter path it replaces (the same component sequence test_kimi_kda_fused_layer.py validates against), with projection matmuls at bf16 production precision. Answers 'why a separate op': decode 1.6-2.0x, prefill 3.7-4.7x over the unfused path on gfx950/MI355X. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
35a77a9 to
924c483
Compare
|
Could you compare your numbers directly with the other pull requests I listed? You could get claude to run the same config on both, it would be easier to compare then Apologies on the lack of clarification on the earlier comment |
|
Thanks @omuhamma — ran them all on one MI355X with one harness. One thing to flag up front that makes the comparison read oddly if I don't: the ops aren't measuring the same thing. FlashKDA (#6177), All numbers below: gfx950 MI355X, H=12, head_dim=128 (Kimi-K3 TP8), Prefill (B=1 sequence of T tokens)
Decode (batch rows, 1 token each)
How to read it
|
|
I am currently working on optimizing the singular kernels (flash kda mainly), for prefill its a better idea to optimize the singular kernels since typically prefill chunks are so large that fusing wont get the best of gains for it For decode the whole layer op fusion can be useful, at the moment we need to compare more numbers in model runs before knowing what is better. The numbers at the moment look like decode (separate gemm and kda) is performing better but it is hard to tell since they dont compare directly 1:1 |
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
|
I think we can close this PR, monokernels are to be done inside serving frameworks and fusing all prefill ops together will typically give no gain since these are large ops (not KLL bound), its better to optimize the kernels themselves. |
|
Closing — on current Kimi-K3 TP8 the whole-layer fused decode now benchmarks at parity with the base per-kernel KDA |



Summary
Adds fused Kimi-K3 KDA (Kimi Delta Attention) whole-layer Gluon ops for MI355X (gfx950), TP8:
o_proj.New files (no existing code touched):
Design
kimi_kda_fused_layer_{prefill,decode}with*_supported()predicates — gfx950 + Triton ≥ 3.8 gate, lazy tile import (module stays importable on CPU / old Triton / non-gfx950), fail-closed (report, don't assert), mirroringfused_gdn_prefill_qkvz.{m64, m256}(m ≤ 64 → m64,m > 64 → m256), chosen from an on-device tile-vs-tile bake-off across every real decode tier: the two general schedules are correct over their range and within a few µs of the per-tier best, while the per-size variants are never fastest and the serial catch-all is 2–8× slower at largem. Decode batches are exact single tokens (no ragged lengths), so the split is unambiguous.Provenance & validation
Kernels ported from the validated Artemis Kimi-K3 MI355X TP8 pack. On MI355X (gfx950, Triton 3.8):
blackclean;ruffadvisory remainder is confined to the hand-tuned Gluon tiles (kept byte-faithful).