Skip to content

[Triton/Gluon] [HIP] [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 - #8744

Open
huizzhan wants to merge 49 commits into
cursor/kimi-k3-kda-chunk-bwd-7e9cfrom
cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b
Open

huizzhan wants to merge 49 commits into
cursor/kimi-k3-kda-chunk-bwd-7e9cfrom
cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b

Conversation

@huizzhan

@huizzhan huizzhan commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

This adds a FlyDSL backend for the chunk_kimi_delta_attn forward at Kimi-K3 shapes (H=96×128, bf16, chunk 64, gfx950). Triton stays the default and the reference.

Changes

  • aiter/ops/flydsl/kernels/kda_chunk_fwd.py and kernels/kda_fwd_affine.py add the FlyDSL forward kernels. The contractions run on MFMA (bf16 operands, fp32 accumulation).
    • intra16 works on 16-token tiles. It computes:
      • the chunk-local log2 gate cumsum, optionally with the in-kernel gate. That is -exp(A_log)·softplus(g+dt_bias), or lower_bound·sigmoid(exp(A_log)·(g+dt_bias)) when lower_bound is set;
      • the in-kernel q/k L2 norm and beta sigmoid;
      • Aqk and Akk, and the inverse of each 16x16 diagonal block of (I+L);
      • w/u/qg/kg.
    • The h/v_new/final-state recurrence takes one of three routes, chosen per call:
      • rec16 keeps the state in registers, advances it every 16 tokens and computes the output in the same kernel;
      • affine16 (dense calls with few states) builds per-segment state maps in parallel and scans them;
      • the GDN K5 kernel (chunk_gated_delta_h, per-channel gk), the same call [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740 makes, followed by a separate output kernel (o = scale·qg·h + Aqk·v_new).
  • aiter/ops/flydsl/kda_chunk_fwd.py has the entry points:
    • chunk_kda_fwd_flydsl(q,k,v,g,beta,scale,chunk_size,*,use_qk_l2norm_in_kernel,use_gate_in_kernel,A_log,dt_bias,use_beta_sigmoid_in_kernel,lower_bound,initial_state,output_final_state,state_v_first,cu_seqlens,config,return_intermediates,max_seqlen) -> (o, final_state). The flag names are the ones in [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739's register_chunk_bwd contract. return_intermediates=True also returns the 10-tuple that the FlyDSL backward takes in save_fwd mode.
    • chunk_kda_fwd_prepare_flydsl(...) returns (q, k, beta, g_cumsum, w, u, qg, kg, Aqk, Akk), the same tuple as the chunk_delta_attn_fwd_prepare that [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740 recomputes with, and accepts its keywords. Aqk and Akk are fp32; Triton's are bf16. It is registered as an opt-in forward-prepare backend of the FlyDSL backward.
    • All tensors are token-major [B,T,H,D].
    • Varlen (cu_seqlens, B=1) is supported. Varlen calls are CUDA / HIP graph capturable: under capture the chunk schedule is built on the device, so a captured graph replays correctly for any cu_seqlens contents with the same N and total T.
  • The route and block sizes come from a tuned CSV (AITER_CONFIG_KDA_CHUNK_FWD_FLYDSL, gfx950, Kimi-K3 / K3.1 shapes), with a default config for other shapes. A tuner is included.
  • Backend switch: chunk_kimi_delta_attn(..., fwd_backend="flydsl"). Calls outside the supported set raise ValueError instead of silently falling back to Triton.
  • op_tests/test_kda_chunk_fwd.py checks o and the final state against an fp32 token-by-token recurrence, and reports the FlyDSL vs Triton difference. It covers dense and varlen (including empty sequences and partial chunks at sequence boundaries), the Lumen#35 shapes up to 1×32768, H=96/48/32/16/12, token- and channel-major layouts, and three modes: kimi (fused gate with lower_bound=-5, L2 norm and beta sigmoid in kernel), kimi_state (adds a V-first h0 and the final state) and plain. It also checks the intermediates against Triton's.

Limits

  • gfx950 only (intra stages about 128 KB of LDS; gfx950 has 160 KB), bf16 q/k/v, K=V=128, chunk 64, H==HV, B=1 with varlen, no out or state_cache. The final state is fp32.
  • safe_gate is accepted and has no effect. The decay is computed exactly, or split per 16-token block, in fp32, so there is no sub-chunk reference point.
  • Shapes outside the tuned CSV run with the default config; their speed was not measured.
  • [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 has no forward registration hook, so it would call chunk_kda_fwd_flydsl directly.

Validation

On gfx950 (MI355X), bf16, K=V=128. The gates and the unverified scope are listed in the Self-Review below.

  • op_tests/test_kda_chunk_fwd.py exits 0 on the default route and with each recurrence route forced. test_chunk_delta_attn_fwd.py: 29 passed. test_chunk_delta_attn_bwd.py -k flydsl: 39 passed.
  • relL2 of o vs Triton is 3.3e-3 to 3.7e-3 (FlashKDA vs Triton: 5.4e-3 to 5.6e-3).
  • Performance at b221d11f (later commits are formatting only). Graph end to end, the three backends measured in the same session, median of 6, in us:
Shape Triton FlyDSL Triton / FlyDSL FlashKDA FlashKDA / FlyDSL
H96 T1000 321 110 2.92x 224 2.04x
H96 T2048 657 213 3.09x 410 1.93x
H96 T8192 2455 758 3.24x 1320 1.74x
H96 varlen 8x2048 4538 1415 3.21x 3110 2.20x
H12 T1K 127 63 2.01x 67 1.06x
H12 T4K 293 110 2.68x 120 1.09x
H12 T16K 1178 292 4.03x 401 1.37x
H12 varlen 16x1K 629 211 2.98x 232 1.10x

GPU commands (single MI350X/MI355X):

python3 op_tests/test_kda_chunk_fwd.py
python3 op_tests/test_kda_chunk_fwd.py -m kimi -H 96 -s 1x1000

PR Self-Review

Reviewed revision

7416f7ebaa990824434ced850a0728caaec63bdd

Behavior and intent

  • Adds a FlyDSL forward for chunk_kimi_delta_attn at Kimi-K3 shapes. It is opt-in with fwd_backend="flydsl"; Triton stays the default and the reference.
  • Kernels:
    • intra16 (gate cumsum, in-kernel q/k L2 norm and beta sigmoid, Aqk / Akk, the (I+L)^-1 solve, w/u/qg/kg on 16-token tiles).
    • Recurrence, chosen per call (tuned CSV or default): register-resident rec16 with the output fused in, chunk-parallel affine16 for few states, or the GDN K5 kernel.
    • The output, fused into the recurrence or as a separate kernel.
  • Dense and varlen (cu_seqlens, B = 1). Varlen calls are CUDA / HIP graph capturable.
  • chunk_kda_fwd_prepare_flydsl returns the same 10-tuple as Triton's chunk_delta_attn_fwd_prepare. It is registered as an opt-in forward-prepare backend of the FlyDSL backward in [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740.
  • Stacked on [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740 (base branch cursor/kimi-k3-kda-chunk-bwd-7e9c).

Validation and unverified scope

Validated on gfx950 (MI355X), bf16, K = V = 128. The numbers are from b221d11f. ee0e03fa and 84169a83 are formatting only: ee0e03fa reorders two imports and reformats one assert in op_tests/test_kda_chunk_fwd.py, and 84169a83 runs black and adds noqa (B023, SIM102) in the three FlyDSL forward files, with an unchanged AST. 84169a83 was rerun on GPU against b221d11f: o, the final state and the intermediates tuple are torch.equal on every route (default, affine, K5, register, fused; 12 cases each), 102 graph replay cases are bit-identical to eager, and the op test exits 0. 7416f7eb addresses the Copilot review (bullet below).

  • op_tests/test_kda_chunk_fwd.py: exit 0 on the default route, including 40 empty-sequence rows. Forcing each recurrence route (affine, K5, register, fused) also exits 0.
  • test_chunk_delta_attn_fwd.py: 29 passed. test_chunk_delta_attn_bwd.py -k flydsl: 39 passed, including the FlyDSL backward fed with FlyDSL forward intermediates.
  • Accuracy:
    • relL2 of o vs Triton is 3.3e-3 to 3.7e-3 on H8 / H96 / H12, dense and varlen (FlashKDA vs Triton: 5.4e-3 to 5.6e-3). maxabs ≤ 7.3e-4.
    • Against the fp32 token-by-token recurrence, the FlyDSL error is about 1.14x Triton's (gate threshold 1.25x).
  • Bit-exact gates on every pushed revision: graph replay vs eager on every route, and new code with its switch off vs the previous revision.
  • Performance (graph end to end, same session, median, Triton time / FlyDSL time): H96 2.92–3.24x, H12 2.01–4.03x. FlyDSL is also faster than FlashKDA on all 8 measured shapes: 1.74–2.20x at H96, 1.06–1.37x at H12.
  • 7416f7eb (Copilot review): launch handles keyed by device, and by the state's rank where affine (3-D) and other routes (4-D) share a launcher; shape checks on every operand of chunk_kda_fwd_flydsl; the MFMA diagonal tiles only for lower_bound in [-5, 0); two spare rows in the rsolve beta buffer for the unclamped prefetch; and test fixes (checkAllclose for intermediates and gradients). Against 84169a83: o, the final state and the intermediates tuple are torch.equal on every route (12 cases each), 102 graph replay cases are bit-identical to eager, and the op test passes on all 7 default shapes × 3 modes (after the beta-buffer change, rerun on 1x1000, 3x1000v and 8x2048v). A varlen fused call followed by an affine call, which failed with IndexError on 84169a83, now runs and matches Triton. lower_bound = -10 / -20 now gives relL2 3.7e-3 to 4.1e-3 against the fp32 recurrence (Triton about 4e-3; 84169a83: 0.23–0.83). Eager time against 84169a83 (medians of 6 interleaved rounds): T1000 H12 69.4 vs 68.4 us (the new shape checks, about 1 us on the host), other shapes within ±0.7%.
  • Still unverified:
    • Other architectures (FlyDSL is never selected off gfx950).
    • Shapes outside the tuned CSV run with the default config; their speed was not measured.
    • More than one GPU: the per-device handle keys were not exercised, since the gate runs one GPU per job.
    • Changing cu_seqlens in place between calls: the varlen schedule cached on the tensor is reused, as with the Triton forward's cache, so callers must pass a new tensor when the lengths change.
    • This branch is not yet merged with the updated base ([Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740 at 7b40ccb7, which merges main). Combined with it, fwd_backend="flydsl" would not yet reject [Triton/Gluon] [gfx950/1250] FlashKDA updates #8043's out_gate / norm_weight / checkpoint arguments; that needs a follow-up once the base is merged in.

PR-specific question

Which arch / dtype / shape selects the new kernels, and what keeps unsupported inputs out?

  • No call selects FlyDSL by default. It runs only when the caller passes fwd_backend="flydsl".
  • Then:
    • chunk_kimi_delta_attn rejects out and state_cache with ValueError.
    • chunk_kda_fwd_flydsl raises ValueError unless kda_fwd_flydsl_supported holds: get_gfx_runtime() == "gfx950", K == V == 128, chunk_size None or 64, H == HV (no GVA), bf16 q/k/v of one dtype.
    • Varlen with B != 1, a missing A_log with use_gate_in_kernel=True, and any operand whose shape does not match q's [B, T, H] and K = V = 128 (including initial_state [N, H, 128, 128]) also raise.
    • Unsupported calls fail loudly instead of silently falling back.
  • Reasons for the limits: intra stages about 128 KB of LDS (gfx950 has 160 KB), and K5 bakes in BT = 64 and K = 128.
  • The FlyDSL backward uses chunk_kda_fwd_prepare_flydsl only when it is selected (prepare="flydsl" or AITER_KDA_BWD_PREPARE=flydsl).

Changed op tests

  • op_tests/test_kda_chunk_fwd.py: the op test.
    • test_kda_chunk_fwd: o and the final state vs an fp32 token-by-token recurrence, and FlyDSL vs Triton, over H, T, dense / varlen, plain / kimi / kimi_state modes and token- / channel-major layouts.
    • test_kda_chunk_fwd_intermediates: the prepare tuple vs Triton's intermediates, and the FlyDSL backward fed with them vs its own recompute.
    • test_kda_chunk_fwd_empty_seq: varlen with empty sequences, per route, with and without an initial state.
    • Together they cover the forward's correctness, which no existing test does.
  • op_tests/op_benchmarks/flydsl/bench_kda_chunk_fwd.py: a benchmark with no assertions. It times FlyDSL against Triton per shape, reports their max |diff|, and can print per-stage FlyDSL times (intra / k5 / output).
  • op_tests/tuning_tests/test_config_shape_collision.py: one entry, AITER_CONFIG_KDA_CHUNK_FWD_FLYDSL / kda_chunk_fwd_flydsl_tuned. The new tuned CSV gets the same duplicate-shape check as the other config families.
Open in Web Open in Cursor 

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 8744 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…-import, FlyDSL GEMMs for g_proj bwd

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor cursor Bot mentioned this pull request Nov 26, 2026
12 of 19 tasks
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch from 60a6a73 to 378b480 Compare November 26, 2026 09:47
@cursor
cursor Bot changed the base branch from main to cursor/kimi-k3-kda-chunk-bwd-7e9c November 26, 2026 09:47
@huizzhan
huizzhan added this pull request to stack #8751 November 26, 2026 09:47
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch 3 times, most recently from 2a8bfe8 to 66bec98 Compare November 26, 2026 10:13
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch 3 times, most recently from fd1db51 to c801cdd Compare November 26, 2026 10:28
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…ton)

register_fwd_prepare(name, fn) installs a forward-intermediate recompute with
the Triton chunk_delta_attn_fwd_prepare signature and 10-tuple result (e.g.
#8744's FlyDSL prepare). It runs only when selected with prepare=name (also
on chunk_kda_bwd_flydsl) or AITER_KDA_BWD_PREPARE=name; unknown names raise
rather than silently falling back. Test: test_flydsl_fwd_prepare_hook.

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch from f4a3452 to d4a37e2 Compare November 26, 2026 10:33
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
#8744's FlyDSL prepare returns fp32 Aqk/Akk from torch.empty, so Akk's upper
triangle need not be zero as Triton's (zero-filled) one is. wy_dqkg (MFMA and
FMA) staged the full Akk tile into its products; it now keeps only s <= t, as
dav already does for Aqk. fp32 Aqk/Akk are otherwise handled per dtype (16-
byte loads, bf16 MFMA operands); all fp32 variants compile.

Tests: test_flydsl_fp32_prepare_outputs registers a prepare that returns fp32
Aqk/Akk with NaN upper triangles (dense and varlen) and must match the Triton
prepare; test_backward_flydsl_prepare_flydsl checks prepare="flydsl" against
the Triton backward (runs where #8744's kda_chunk_fwd is present).

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch from 06c87fc to fb0cd43 Compare November 26, 2026 10:37
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch 2 times, most recently from 76bd85e to cb10900 Compare November 26, 2026 12:52
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
) into kda-integration

Conflicts: the chunk-fwd files (add/add against the older #8744 copy) take
cb10900's version. chunk_delta_attn.py also takes it: the auto-merge kept
fwd_backend from both #8739's and #8744's parameter order (a duplicate
argument, SyntaxError); the two versions differ only in that order.

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…s chunk fwd files and chunk_delta_attn.py)

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…ith a shape check, falling back to Triton with the reason in LAST_PIECES and the log; note the save_fwd Triton-intermediates override

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…ve_fwd intermediates)

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch from 13275a2 to d591912 Compare November 26, 2026 13:08
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…/Akk) when selected, Triton disable_recompute otherwise; save_fwd self-check graded vs an fp32 reference, self-checks no longer abort main; stub plumbing test

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…raded self-check, non-aborting self-checks; #8744 13275a2) into kda-integration

Conflicts in op_tests/test_kda_fused_layer_bwd.py:
- test_kda_save_fwd_matches_recompute takes #8739's new signature
  (chunk_bwd=); #8754's config_name_of and #8757's MXFP8 tests are kept
- main(): #8739's non-aborting self-checks; #8757's
  test_kda_mxfp8_weight_cache joins them the same way (logged and recorded
  in SELF_CHECK_FAILURES instead of raising)

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
@cursor
cursor Bot force-pushed the cursor/kimi-k3-kda-chunk-fwd-flydsl-4a4b branch from c632635 to f4f84cd Compare November 26, 2026 13:22
Comment thread op_tests/test_kda_chunk_fwd.py Outdated
Comment on lines +258 to +262
from aiter.ops.flydsl.kda_chunk_bwd import chunk_kda_bwd_flydsl
from aiter.ops.flydsl import kda_chunk_fwd as fwd_mod
from aiter.ops.flydsl.kda_chunk_fwd import chunk_kda_fwd_flydsl
from aiter.ops.triton._triton_kernels.kimi_delta_attn import chunk_delta_attn_fwd

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <I001> reported by reviewdog 🐶
Import block is un-sorted or un-formatted

Suggested change
from aiter.ops.flydsl.kda_chunk_bwd import chunk_kda_bwd_flydsl
from aiter.ops.flydsl import kda_chunk_fwd as fwd_mod
from aiter.ops.flydsl.kda_chunk_fwd import chunk_kda_fwd_flydsl
from aiter.ops.triton._triton_kernels.kimi_delta_attn import chunk_delta_attn_fwd
from aiter.ops.flydsl import kda_chunk_fwd as fwd_mod
from aiter.ops.flydsl.kda_chunk_bwd import chunk_kda_bwd_flydsl
from aiter.ops.flydsl.kda_chunk_fwd import chunk_kda_fwd_flydsl
from aiter.ops.triton._triton_kernels.kimi_delta_attn import chunk_delta_attn_fwd

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ee0e03f: imports sorted, and the file is black-formatted. Test-only change.

…e 3)

compile_intra16 forms only the diagonal 16x16 blocks (head-major mx / Aqk) and compile_recurrence16 advances the state every 16 tokens, applying (I + L_II)^-1 per tile. Default AITER_KDA_FWD_RSOLVE=3 on the fused route with the lower_bound gate; elsewhere, or with AITER_KDA_FWD_INTRA16=0, it runs as rsolve 1.
Comment on lines +1311 to +1318
if rv:
if l4 == 0:
stg(
_flat(bt, fx.Int64(i_bh) * fx.Int64(T + BT) + fx.Int64(t0)),
r,
beta_r,
F32,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <SIM102> reported by reviewdog 🐶
Use a single if statement instead of nested if statements

Suggested change
if rv:
if l4 == 0:
stg(
_flat(bt, fx.Int64(i_bh) * fx.Int64(T + BT) + fx.Int64(t0)),
r,
beta_r,
F32,
)
if rv and l4 == 0:
stg(
_flat(bt, fx.Int64(i_bh) * fx.Int64(T + BT) + fx.Int64(t0)),
r,
beta_r,
F32,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept the nested if as written and added # noqa: SIM102 in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

for mt in range_constexpr(MT):
acc_h = fx.Vector.filled(4, 0.0, fx.Float32)
for ks in range_constexpr(NS):
a_op = lload4(buf + QG_OFF + a_w + (mt * 16 * LQ + ks * 16) * 2)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable buf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

out_part is traced inside this iteration of the loop body, so the late binding is intended. Added # noqa: B023 on each use in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

a_op = lload4(buf + QG_OFF + a_w + (mt * 16 * LQ + ks * 16) * 2)
acc_h = fx.Vector(
rocdl.mfma_f32_16x16x16bf16_1k(
TT.f32x4, [a_op, sb[ks].bitcast(I16), acc_h, 0, 0, 0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable sb

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

out_part is traced inside this iteration of the loop body, so the late binding is intended. Added # noqa: B023 on each use in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

)
acc_v = fx.Vector.filled(4, 0.0, fx.Float32)
for js in range_constexpr(MT):
a_op = lload4(buf + a_a + (mt * 16 * LT + js * 16) * 2)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable buf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

out_part is traced inside this iteration of the loop body, so the late binding is intended. Added # noqa: B023 on each use in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

a_op = lload4(buf + a_a + (mt * 16 * LT + js * 16) * 2)
acc_v = fx.Vector(
rocdl.mfma_f32_16x16x16bf16_1k(
TT.f32x4, [a_op, gated[js], acc_v, 0, 0, 0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable gated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

out_part is traced inside this iteration of the loop body, so the late binding is intended. Added # noqa: B023 on each use in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

fx.ptr_store(
(acc_h[p] * scale + acc_v[p]).to(BF),
lptr(
buf + OS_OFF + ((mt * 16 + l4 * 4 + p) * LV + cl) * 2,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable buf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

out_part is traced inside this iteration of the loop body, so the late binding is intended. Added # noqa: B023 on each use in 84169a8 (formatting only; the AST is unchanged and the fwd bit-exact gate passed on every route).

… exceeds the CUs

compile_recurrence16 takes nbuf (1 / 2 LDS stages of a chunk's tiles). With one
stage the next chunk's tiles are written after the chunk's barrier, so a
workgroup holds half the LDS and two fit per CU. The host picks nbuf=1 when
(V / bv) * N * H workgroups exceed the CU count (AITER_KDA_FWD_R16_NBUF forces
1 / 2). Outputs are bit-identical to nbuf=2.

Tested on GPU (gfx950): bit-exact vs the previous commit on 8 shapes with
nbuf auto / 1 / 2; graph equivalence checks pass.
Full gate (op_tests, pytest, timing): untested on GPU.
compile_affine_scan(use_h0, store_fs, bv, nm) splits a state's V columns into
16-column waves and its rows into nm groups; each step stages the segment's A
and the bf16 entry state in LDS and runs the row MFMAs from there, so a scan
step costs about a third of the old one. Default AITER_KDA_FWD_SCAN=16x4
("<bv>x<nm>"); 64x1 is the previous layout and gives identical outputs.

Tested on GPU (gfx950): bit-exact vs the previous commit on 8 shapes, default
and 64x1.
Full gate (op_tests, pytest, timing): untested on GPU.
With the lower_bound gate and one dense sequence, the affine route now runs on
the rsolve=3 intra's outputs: compile_recurrence16(ab=True) builds the segment
maps per 16-token tile, compile_affine_scan chains them, and
compile_recurrence16 replays the segments from their entry states with the
fused output. AITER_KDA_FWD_AFFINE16=0 returns to the rsolve 0 affine route.

Tested on GPU (gfx950): bit-exact vs the previous commit on 8 shapes;
AFFINE16=0 is bit-exact vs the commit before affine16.
Full gate (op_tests, pytest, timing): untested on GPU.
…airs

fp32x4 -> bf16 operands of the per-tile solve go through two v_cvt_pk_bf16_f32
instead of four element conversions and repacks (_pk_bf16x4). Same rounding
(RNE), bit-identical outputs.

Tested on GPU (gfx950): bit-exact vs the previous commit on 8 shapes; graph
equivalence checks pass.
Full gate (op_tests, pytest, timing): untested on GPU.
_affine_fused passed the entry states as a 5-D view for B > 1 and 3-D for
B = 1. _run_compiled reuses a launcher's first compiled callable, which fixes
the rank of every tensor argument, so a B = 1 call after a B > 1 one failed in
the argument fill (IndexError). Reshape to [B * n_seg * H, V, K] (same rows,
[b][seg][h]) in both cases.

Status: untested on GPU (the GPU host was unreachable when this was
committed).
…ds early

compile_recurrence16(lds_pf=True) reads a 16-token tile's LDS operands (w,
beta, factors, kg^T, decay, qg, Aqk) during the previous tile's MFMA chain.
AITER_KDA_FWD_R16_PF=0 restores the in-order loads. Bit-identical outputs.

Status: untested on GPU as committed. An equivalent build (same rec16 code, with the
next commit's intra16 change) was bit-exact on 8 shapes; graph kernel totals
(us), previous commit -> this: H12 T4K 112 -> 110, T16K 318 -> 307, varlen
16x1K 220 -> 218, H96 T8192 851 -> 791, H96 varlen 8x2048 1385 -> 1383.
Each wave reads its L_II into registers before writing (I + L_II)^-1, so the
inverse reuses the L_II buffer: 52 KB of LDS per workgroup instead of 56 KB.
Bit-identical outputs; same speed at the current 242 VGPRs (2 waves/SIMD).

Status: untested on GPU as committed. An equivalent build (plus an unused
waves_per_eu knob, removed here) was bit-exact on 8 shapes.
Drop the precomputed gt/gm/qg/kg/kb register lists: each output is
formed 8 columns at a time and written to LDS right away, and the
tile total and split (rows 15 / 7) are re-read with DPP where used.
Only q, k and the cumsum stay live, so intra16 goes from 242 to 155
VGPRs with no spills (2 -> 3 waves/SIMD with the 52KB LDS). Output is
bit-identical. intra16 kernel time drops 4-8% (H96 T8192 331 -> 310us,
H96 varlen 8x2048 698 -> 661us, H12 T16K 92 -> 85us).
Each wave of intra16 only touches its own LDS (its staged rows and its
L_II), and a wave sees its own LDS accesses in order, so the two
workgroup barriers only made the waves wait for each other. Drop them
and stage qg / kg / w one after another in one buffer per wave (LDS
52KB -> 20KB). Output is bit-identical; intra16 is 2-6% faster (H96
varlen 8x2048 657 -> 628us). AITER_KDA_FWD_I16_WAVE_LOCAL=0 restores
the barriers.
compile_intra16(lean=True), the new default (AITER_KDA_FWD_I16_LEAN=0
restores the previous code):

- The DPP moves of the tile cumsum and the row broadcasts use bound_ctrl
  with a poison old operand instead of a zero old, which LLVM materialized
  with a v_mov before each of the 192 moves.
- Rows past the end of the chunk load row 0 and skip the per-element
  zeroing of q / k / g / dt_bias. Their outputs are never stored, a valid
  row's Aqk / L entries and solve read only valid rows, and their gate is
  still zeroed, so the tile's total stays exact.

intra16 drops from 2848 to 2554 instructions (166 -> 161 VGPRs); the
outputs are bit-identical to the previous code.
The intra16 solve is a serial 16-step chain, and each step's 4-lane row sum
used two ds_swizzle_b32 (LDS cross-lane moves). Use DPP quad permutes
(xor 1, xor 2) instead: the same values added in the same order, without
the LDS round trips. ISA: 2554 -> 2515 instructions, ds_swizzle 32 -> 0,
VGPR unchanged; outputs bit-identical.

AITER_KDA_FWD_I16_DPPSUM=0 restores the swizzle path.
@huizzhan
huizzhan marked this pull request as ready for review December 4, 2026 06:22
@huizzhan
huizzhan requested a review from a team December 4, 2026 06:22
@github-actions github-actions Bot changed the title [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 [Triton/Gluon] [HIP] [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 Dec 4, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot December 4, 2026 06:33
Test-only formatting: no change to what the test runs or checks.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unchecked tensor shapes and beta prefetch bounds permit out-of-bounds reads, while unsafe MFMA gate handling can produce incorrect results.

7 open issues
What changed in this PR

Adds an opt-in FlyDSL KDA chunk-forward backend for Kimi-K3 on gfx950, while keeping Triton as the default. It complements the related backward and fused-layer work.

Changes:

  • Adds forward dispatch, variable-length scheduling, saved intermediates, and affine recurrence.
  • Adds tuning infrastructure and Kimi-K3 configuration tables.
  • Adds correctness tests and backend benchmarks.
File Description
op_tests/​tuning_tests/​test_config_shape_collision.py Registers configuration collision checks.
op_tests/​test_kda_chunk_fwd.py Tests outputs, states, intermediates, and empty sequences.
op_tests/​op_benchmarks/​flydsl/​bench_kda_chunk_fwd.py Compares backend timings.
csrc/​kda_chunk_fwd/​kda_chunk_fwd_flydsl_tune.py Tunes forward configurations per shape.
aiter/​ops/​triton/​kimi_delta_attn/​chunk_delta_attn.py Adds forward backend selection.
aiter/​ops/​flydsl/​kernels/​kda_fwd_affine.py Adds affine recurrence kernels.
aiter/​ops/​flydsl/​kda_chunk_fwd.py Implements forward orchestration and scheduling.
aiter/​jit/​core.py Registers the tuning configuration family.
aiter/​configs/​model_configs/​kda_chunk_fwd_flydsl_untuned_kimi_k3.csv Lists Kimi-K3 tuning shapes.
aiter/​configs/​model_configs/​kda_chunk_fwd_flydsl_untuned_kimi_k3.1.csv Lists Kimi-K3.1 tuning shapes.
aiter/​configs/​model_configs/​kda_chunk_fwd_flydsl_tuned_kimi_k3.csv Stores Kimi-K3 tuned settings.
aiter/​configs/​model_configs/​kda_chunk_fwd_flydsl_tuned_kimi_k3.1.csv Stores Kimi-K3.1 tuned settings.
aiter/​configs/​kda_chunk_fwd_flydsl_untuned.csv Defines the untuned table schema.
aiter/​configs/​kda_chunk_fwd_flydsl_tuned.csv Defines the tuned table schema.

Review effort: Balanced

Comment thread aiter/ops/flydsl/kda_chunk_fwd.py Outdated
Comment on lines +519 to +522
diag = bool(
use_gate_in_kernel
and lower_bound is not None
and (diag_mfma is None or bool(diag_mfma))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed: with lower_bound=-10, the FlyDSL output had relL2 0.23–0.66 against the fp32 recurrence (0.51–0.83 at -20), while Triton (safe_gate=False) stays at about 4e-3. Fixed in 7416f7e: the MFMA diagonal tiles (and the 16-row intra) are used only for lower_bound in [-5, 0); any other gate takes the fp32 path. With the fix, -10 and -20 give 3.7e-3 to 4.1e-3, the same as Triton. The default lower_bound=-5 path is unchanged: outputs are bit-identical to the previous head.

Comment thread aiter/ops/flydsl/kda_chunk_fwd.py Outdated
mx = bt = None
if rsolve:
mx = torch.empty(a_shape, device=dev, dtype=bf)
bt = torch.empty(B * H, T + BT, **f32)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed by reading the indexing: the prepare kernel prefetches two chunks of beta without clamping, so with T = 1000 it reads up to index 1151 of a T + BT = 1064-entry row, which runs past the end of the buffer on the last (b, h) row. Fixed in 7416f7e: bt keeps its T + BT row pitch but is carved out of an allocation with 2 * BT extra floats at the end, so the prefetch stays inside the allocation. The kernel is unchanged and the prefetched tail rows are never used, so outputs are bit-identical to the previous head.

V=v.shape[-1],
chunk_size=chunk_size,
dtype=q.dtype,
) or not (k.dtype == v.dtype == q.dtype):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7416f7e: chunk_kda_fwd_flydsl now checks k / v / g against [B, T, H, 128], beta against [B, T, H], the sizes of A_log (H) and dt_bias (H * 128), and initial_state against [N, H, 128, 128], and raises ValueError before any launch. A test script feeding each wrong shape gets the ValueError.

Comment on lines +375 to +377
if cached is not None and cached[0] == T:
self.__dict__.update(cached[1])
return

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed: after changing cu_seqlens in place from [0, 64, 128] to [0, 32, 128], the next FlyDSL call reuses the varlen schedule cached on the tensor, and its output differs from a call with a new tensor (relL2 7.7e-1). We are keeping the contract of the Triton forward, whose tensor_cache also caches per tensor object: when the sequence lengths change, callers pass a new cu_seqlens tensor. The PR description now states this. Keying the cache on cu_seqlens._version would catch in-place edits at little cost, but it changes _resolve_prologue, which the GDN K5 path shares, so it is left for a separate PR.

Comment on lines +746 to +747
_run_compiled(
kernel,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed on the previous head: in one process, a varlen rec="fused" call with a 4-D initial_state, followed by a dense rec="affine" call, failed in the affine16 replay with IndexError: tuple index out of range (FlyDSL's argument fill in _run_compiled). The replay reused the launch handle compiled for 4-D states, but it passes 3-D states. Fixed in 7416f7e: every KDA launch now keys its compiled handle by device index, and the launchers that take states of both ranks also key by the state's rank. The K5 call (_get_or_compile_opt) is GDN's AOT-bound launcher and is keyed the same way as on main. After the fix, the sequence fused → affine → fused runs, the last output is bit-identical to the first, and both match Triton (relL2 4.6e-3). Outputs on the default shapes are bit-identical to the previous head.

Comment thread op_tests/test_kda_chunk_fwd.py Outdated
Comment on lines +202 to +203
if name != "triton":
raise

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7416f7e: an exception from the Triton backend is now only skipped when a FlyDSL candidate is also being tested; otherwise it is re-raised.

Comment thread op_tests/test_kda_chunk_fwd.py Outdated
Comment on lines +318 to +319
rel = ((a - r).abs().max() / r.abs().max().clamp_min(1e-6)).item()
assert rel < 2e-2, f"{n}: max rel err {rel:.3g}"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7416f7e: the intermediate and gradient comparisons now use checkAllclose (rtol = atol = 2e-2, error ratio at most 1e-3; Aqk / Akk compared on the lower triangle), and the error ratios are recorded in the summary table.

Formatting only (identical AST): black on kda_chunk_fwd.py, kernels/kda_chunk_fwd.py and kernels/kda_fwd_affine.py. The B023 closure is traced within its loop iteration and the nested if is kept as written, so both get noqa.
@aiter-bot

aiter-bot commented Dec 4, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 7416f7ebaa99 · mode shadow

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

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

- Key compiled FlyDSL handles by device index, and by the state's rank
  where a launcher is shared by 3-D (affine) and 4-D states.
- Check k / v / g / beta / A_log / dt_bias / initial_state shapes in
  chunk_kda_fwd_flydsl before any launch.
- Use the MFMA diagonal tiles only for lower_bound in [-5, 0); other
  gates keep the fp32 path.
- Give the rsolve beta buffer two spare rows for the unclamped
  two-chunk prefetch.
- Test: skip a Triton failure only when a FlyDSL candidate is tested;
  compare intermediates and gradients with checkAllclose.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants