Skip to content

[Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) - #8740

Open
huizzhan wants to merge 68 commits into
mainfrom
cursor/kimi-k3-kda-chunk-bwd-7e9c
Open

huizzhan wants to merge 68 commits into
mainfrom
cursor/kimi-k3-kda-chunk-bwd-7e9c

Conversation

@huizzhan

@huizzhan huizzhan commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

KDA chunk delta-rule backward for Kimi-K3 shapes (96 heads x 128, hidden 7168). The Triton backward (from #6498) is the default and the reference. bwd_backend="flydsl" runs every backward stage on FlyDSL.

Source

Changes

  • Triton (aiter/ops/triton/...kimi_delta_attn/*): the [Triton/Gluon] KDA: add the chunk_delta_attn backward pass #6498 backward, with no head-count restriction. It is the default.
  • FlyDSL backend (chunk_kimi_delta_attn(..., bwd_backend="flydsl") / chunk_delta_attn_bwd(..., backend="flydsl")):
    • Forward intermediates are recomputed by the Triton forward prologue (chunk_delta_attn_fwd_prepare). With chunk_kimi_delta_attn(..., save_fwd=True) the forward keeps them instead.
    • The forward-state recurrence (h, v_new): dense calls use a KDA kernel that keeps the state in registers (with few states it shares one launch with dhu); varlen calls use the K5 kernel's IS_VARLEN path. Both are read in their native layouts.
    • New FlyDSL kernels in aiter/ops/flydsl/kernels/kda_chunk_bwd.py:
      • dav: dAqk and dv.
      • dhu: reverse state gradient, dh0, dv2.
      • wy_dqkg: inter-chunk dq/dk/dg, WY dv/dbeta, dAkk.
      • intra: intra-chunk terms, plus the in-kernel q/k l2norm backward and beta-sigmoid backward.
      • gate_cumsum: reverse cumsum, plus the gate activation backward with dA_log / ddt_bias partials (softplus and Kimi lower_bound forms).
    • The contractions run on MFMA (bf16 operands, fp32 accumulation), with LDS-staged operands.
    • Taken on gfx950 for bf16, K=V=128, chunk 64, no GVA; all other calls fall back to Triton.
    • Varlen (cu_seqlens, B=1) on every stage:
      • The per-chunk kernels map programs through chunk_indices, so chunks stop at sequence edges.
      • dhu keeps one state per (sequence, head), starting at chunk_offsets.
      • Gradients past cu_seqlens[-1] are zero, as in Triton.
      • Varlen calls are CUDA / HIP graph capturable: the schedule tables are built on the device, a captured graph replays correctly for any cu_seqlens contents with the same N and total T, and captured calls skip the padding chunks.
    • AITER_KDA_FLYDSL_CHECK=1 checks each stage's outputs and raises on the first non-finite value, naming the stage.
  • [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 contract (aiter/ops/flydsl/kda_chunk_bwd.py):
    • chunk_kda_bwd_flydsl(do, 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, cu_seqlens=None, lower_bound=None, safe_gate=None) -> (dq, dk, dv, dg, dbeta, dA_log, ddt_bias).
    • lower_bound selects K3's safe gate g = lb * sigmoid(exp(A_log) * (z + dt_bias)). safe_gate defaults to lower_bound is not None.
    • CHUNK_BWD_FUSES = {qk_l2norm, gate, beta_sigmoid}; register_with_kda_layer() installs it via register_chunk_bwd.
    • All I/O is token-major [B, T, H, D], so [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 / [FlyDSL] [MI350X] causal conv1d backward support for Kimi-K3 #8726 pass and consume tensors without copies.
  • Tests:
    • op_tests/test_kda_chunk_bwd.py: triton vs flydsl (flydsl on gfx950) against the fp32 torch reference, with a perf table.
      • -s (b, t, varlen): 1×1000, 1×2048, plus the Lumen#35 timing shapes 1×8192, 2×4096, 1×32768 and varlen 8×2048.
      • -H 96/48/32/16/12 (K3 TP1/2/8 and the issue's H32/H16); D=128, bf16.
      • -m plain|kimi: kimi is the issue's safe_gate setting (l2norm + lower_bound=-5 gate + beta sigmoid in kernel).
      • The reference runs one sequence and head group at a time (≤ ~32 GB), so 1×32768×H96 fits one GPU. It was checked on CPU against the token-by-token reference (varlen + kimi, ≤1e-7).
    • pytest:
      • 96-head cases.
      • test_backward_flydsl_matches_triton: h0 variants with dht, T=100/1000, dense and random-length varlen.
      • test_backward_flydsl_lumen_shapes: the Lumen#35 shapes at the issue's heads and H96, varlen 8×2048 included.
      • test_chunk_bwd_contract_flydsl: 12 combos vs Triton, crossing l2norm × gate (off / softplus / safe gate lower_bound=-5) × beta sigmoid, with dA_log / ddt_bias checked.
      • The forward-prepare hook, save_fwd and forward intermediates.

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_bwd.py: 600 passed, 0 failed (both backends vs the fp32 reference).
  • test_chunk_delta_attn_bwd.py -k "flydsl or save_fwd or fwd_intermediates": 38 passed, 2 skipped.
  • FlyDSL and Triton have the same relL2 against fp32 for every gradient (ratio 1.000).
  • Varlen graph capture: 34 cases, all bit-identical to eager.
  • Performance at f4ddc7b8 (later commits leave the FlyDSL backward bit-identical). Eager, whole backward including the Triton recompute, Triton and FlyDSL alternated in the same session, median of 3, in us:
Shape (kimi mode) Triton FlyDSL Triton / FlyDSL
H96 T1000 865.5 751.3 1.15x
H96 T2048 1698.7 1426.5 1.19x
H96 T8192 6480.0 5402.1 1.20x
H96 varlen 8x2048 12759.3 10042.6 1.27x
H12 B2 T4096 928.5 811.4 1.14x
H32 B2 T4096 2249.6 1931.0 1.16x
H12 varlen 2x4096 989.3 893.2 1.11x
H32 T1000 347.3 357.5 0.97x

17 of 18 measured shapes are not slower than Triton; H32 T1000 is the exception, where both backends are at the host-launch floor (about 350 us). Under graph capture, varlen is 1.08–1.23x faster.

TODO

  • GPU validation of the FlyDSL backward (op_test, pytest, Lumen#35 table) and the merge with current main
  • MFMA for the FlyDSL contractions
  • FlyDSL forward prologue: [Triton/Gluon] [HIP] [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 #8744 registers chunk_kda_fwd_prepare_flydsl as an opt-in forward-prepare backend
  • Rerun the K3 Tiny-L13 full-model check with [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739's fused layer backward (register_with_kda_layer) on the current head (last run at 36/n)
  • One-backend-per-PR: decide whether to split the FlyDSL part into a stacked PR on top of the Triton one
  • Not planned here: gfx942 support (the stage kernels stage up to about 147 KB of LDS; gfx942 has 64 KB)

PR Self-Review

Reviewed revision

42fdaad42fbcf4282b7ee9792f450acd7a0f5f91

Behavior and intent

  • Adds the KDA chunk delta-rule backward used by chunk_kimi_delta_attn for Kimi-K3 shapes. The Triton backward (port of [Triton/Gluon] KDA: add the chunk_delta_attn backward pass #6498) is the default and the reference.
  • FlyDSL is opt-in: chunk_kimi_delta_attn(..., bwd_backend="flydsl") or chunk_delta_attn_bwd(..., backend="flydsl"). Every backward stage (dav, dhu, wy_dqkg, intra, gate_cumsum) and the forward-state recurrence (GDN K5 / KDA fwd_h) then run on FlyDSL. The forward intermediates are recomputed by the Triton prologue, or reused with save_fwd=True.
  • Varlen (cu_seqlens, B = 1) is supported on every stage. Varlen calls are CUDA / HIP graph capturable: schedule tables are built on the device, and captured calls skip the padding chunks.
  • aiter/ops/flydsl/kda_chunk_bwd.py also provides the [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 chunk-bwd contract (chunk_kda_bwd_flydsl, CHUNK_BWD_FUSES, register_with_kda_layer).
  • Callers that do not pass a FlyDSL backend get the Triton backward.

Validation and unverified scope

Validated on gfx950 (MI355X), bf16, K = V = 128. The numbers are from f4ddc7b8. aaa39263 (ruff / black clean-up), 7b40ccb7 (merge of current main) and 42fdaad4 (Copilot review fixes) leave the FlyDSL backward bit-identical to it (bullets below).

  • op_tests/test_kda_chunk_bwd.py: exit 0. dq/dk/dv/dg/dbeta pass checkAllclose (atol = rtol = 0.05) against the fp32 torch reference for both backends (600 passed, 0 failed).
  • test_chunk_delta_attn_bwd.py -k "flydsl or save_fwd or fwd_intermediates": 38 passed, 2 skipped. -k flydsl with AITER_KDA_FLYDSL_CONC_REC=0, and with all three FlyDSL scheduling switches off: 37 passed each.
  • Accuracy against fp32: FlyDSL and Triton have the same relL2 for every gradient (ratio 1.000). dq/dk are about 3.7e-3, dv/dg about 4.0e-3 and dbeta about 3.8e-3 (kimi mode: B1 T1000, B2 T2048, varlen 3x700). Per-stage alignment with Triton passes.
  • Graph capture: tested on 3 varlen shapes × 2 dhu variants. The checks were capture/replay, replay with other sequence lengths, and empty sequences at the start, middle and end. All 34 cases are bit-identical to eager.
  • Performance (eager, same session, Triton time / FlyDSL time, whole backward including the Triton recompute):
    • H96: 1.15–1.27x.
    • 17 of 18 shapes are not slower than Triton. H32 T1000 is 0.97x; both backends are at the host-launch floor (about 350 us) there.
    • Graph, varlen: 1.08–1.23x.
  • aaa39263 vs f4ddc7b8: all 7 outputs are torch.equal on 7 shapes (dense and varlen, H96 and H12) in eager, bounded (captured schedule) and save_fwd mode. ruff check . and black --check are clean. pytest gave the same result as above.
  • 7b40ccb7 merges main (4052b38a) and keeps [Triton/Gluon] [gfx950/1250] FlashKDA updates #8043's new chunk_kimi_delta_attn arguments next to bwd_backend / save_fwd. Against aaa39263, all 7 outputs are torch.equal on the same 7 shapes in eager, bounded and save_fwd mode: main's Triton forward changes do not touch the prologue that the backward recomputes with. Rerun on the merge: op test 600 passed, the pytest subsets as above, relL2 ratio 1.000, per-stage alignment, the 34 graph cases, and test_chunk_delta_attn_fwd.py (29 passed). With flydsl 0.5.5 (main's pin; the other gates use 0.5.3, the toolchain of the earlier numbers): op test 600 passed, pytest subset 38 passed.
  • 42fdaad4 addresses the Copilot review: launch handles keyed by device, fork/join events cached per thread, eager calls with cu_seqlens[-1] < T routed to Triton (new test test_backward_flydsl_short_cu_seqlens), non-finite tuner errors skipped, bench_chunk_delta_attn_bwd.py moved to RotatingBufferBench, and two test fixes. Against 7b40ccb7, all 7 outputs are torch.equal on the same 7 shapes in eager, bounded and save_fwd mode, and captured replays on the 3 varlen shapes are bit-identical to eager. Op test 600 passed; pytest subset 39 passed, 2 skipped. Eager time is within 0.5% of 7b40ccb7 on the three host-bound shapes (T1000 H12, varlen 3x700, varlen 2x4096; medians of 6 interleaved rounds).
  • Still unverified:
    • Other architectures. FlyDSL is never selected off gfx950; the Triton backward was only run on gfx950.
    • Dense calls under graph capture (only the varlen shapes were captured).
    • More than one GPU: the per-device handle keys were not exercised, since the gate runs one GPU per job.
    • Concurrent callers on several threads: a 4-thread repro (100 concurrent calls) showed no mismatch before or after the per-thread events, so that change has no failing case behind it.
    • Graph capture with cu_seqlens[-1] < T: nothing is checked under capture, so the tail gradients are left unwritten; cu_seqlens[-1] == T is a documented requirement there.
    • The K3 Tiny-L13 full-model check (9 KDA layers; loss, logits and 138 gradients vs Triton) was last run at 36/n, not on this head.
    • The 6 cases of test_chunk_delta_attn_bwd.py that run main's FlashKDA Gluon forward (test_backward[flash], [flash_varlen_vfirst], [wide_recurrences], [k3_96_heads], test_backward_flash_matches_default, test_backward_partial_requires_grad) and the K = 128 shapes of bench_chunk_delta_attn_bwd.py do not compile with the test machine's Triton 3.6.0 (AMDMFMALayout has no _flatten_ir), the same before and after the merge. They were not run here.

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 bwd_backend="flydsl" (or backend="flydsl" to chunk_delta_attn_bwd).
  • Even then, kda_bwd_flydsl_supported must hold: get_gfx_runtime() == "gfx950", K == V == 128, chunk_size == 64, H == HV (no GVA), bf16 inputs, and B == 1 when cu_seqlens is given; eager varlen calls also need cu_seqlens[-1] == T. Any other call runs the Triton backward with the same output contract.
  • Reasons for the limits:
    • The stage kernels stage up to about 147 KB of LDS per workgroup (gfx950 has 160 KB, gfx942 64 KB).
    • The K5 recurrence bakes in BT = 64 and K = 128.
  • Unknown backend names raise ValueError, as does a varlen call to the FlyDSL entry point with B != 1.
  • When an input requires grad, the inference-only arguments (out, state_cache, out_gate / norm_weight and the prefill checkpoints) raise ValueError, whatever the backend.

Changed op tests

  • op_tests/test_kda_chunk_bwd.py: the op test. It runs Triton and FlyDSL against an fp32 torch reference (from [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739's chunk_kda_torch) at model-scale shapes: the Lumen#35 timing shapes up to 1×32768 and varlen 8×2048, H 96/48/32/16/12, plain and kimi gate settings. It also prints the perf table. It is the only test that checks long sequences against an fp32 reference.
  • op_tests/triton_tests/kimi_delta_attn/test_chunk_delta_attn_bwd.py: pytest unit tests at small T.
    • Triton backward: vs a reference, vs FLA, vs the flash path, partial requires_grad, and rejection of inference-only arguments.
    • FlyDSL vs Triton: initial state / dht variants, dense and random-length varlen, the Lumen#35 shapes, and the 12 [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 contract combinations (l2norm × gate × beta sigmoid, with dA_log / ddt_bias).
    • The forward-prepare hook, and save_fwd / forward intermediates.
    • It covers API paths and options that the op test does not.
  • op_tests/op_benchmarks/flydsl/bench_kda_chunk_bwd.py: a benchmark with no assertions. It times the two backends directly, without autograd or the reference. Options: per-stage profile and save_fwd.
  • op_tests/op_benchmarks/triton/bench_chunk_delta_attn_bwd.py: a Triton-only benchmark in the Triton suite. It times the autograd forward and backward of chunk_kimi_delta_attn across shapes.
  • op_tests/tuning_tests/test_config_shape_collision.py: one entry, AITER_CONFIG_KDA_CHUNK_BWD / kda_chunk_bwd_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 8740 --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.

cursoragent and others added 5 commits November 26, 2026 08:39
Squashed from #6498 (branch zain/kda/bwd, head 966a494),
FLA chunk_kda_bwd Triton port by Micky774.

Co-authored-by: Micky774 <[email protected]>
Co-authored-by: Sealeen Zhang <[email protected]>
Add op_tests/test_kda_chunk_bwd.py (aiter-op-test structure): K3 shapes
(H=96/48/12 x 128) graded against an fp32 chunked torch reference adapted
from #8739, with a us/TFLOPS/TB/s summary table. Add 96-head cases to the

Co-authored-by: Sealeen Zhang <[email protected]>
#6498 pytest suite.
fast_launch moved to aiter/ops/triton/utils in #8061; the #6498 import path
no longer exists on main (also fixes ruff I001).

Co-authored-by: Sealeen Zhang <[email protected]>
Co-authored-by: Sealeen Zhang <[email protected]>
chunk_kimi_delta_attn(bwd_backend="flydsl") recomputes the backward's
forward chunk-state recurrence (h, v_new) on the FlyDSL GDN K5 kernel
(chunk_gated_delta_h, USE_GK, token-major w/u) instead of the Triton fwd_h;
dhu, wy_dqkg, intra and the gate/l2norm/beta backward stay Triton. Falls
back to Triton outside bf16, K=V=128, chunk 64, non-varlen.

op_tests/test_kda_chunk_bwd.py benchmarks and grades both backends; the
pytest suite checks flydsl against triton at H=96.

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor cursor Bot mentioned this pull request Nov 26, 2026
12 of 19 tasks
bwd_backend="flydsl" now runs every backward stage on FlyDSL:
- chunk-state recurrence on the GDN K5 kernel, read in its native layouts
  (h [B,NT,H,V,K], v_new [B,H,T,V]); the two transpose copies are gone.
- new kernels in aiter/ops/flydsl/kernels/kda_chunk_bwd.py: dav, dhu,
  wy_dqkg, intra (+ in-kernel l2norm and beta-sigmoid backward) and
  gate_cumsum (+ gate activation backward, dA_log/dt_bias partials).
Forward intermediates are still recomputed by the Triton fwd prologue.
gfx950, bf16, K=V=128, chunk 64, no GVA, non-varlen; Triton otherwise.

chunk_kda_bwd_flydsl implements #8739's register_chunk_bwd 7-tuple
contract with fuses {qk_l2norm, gate, beta_sigmoid}; register_with_kda_layer()
installs it. All kernels compile offline for gfx950 (no spills, LDS <= 147 KB);
not run on a GPU yet.

Co-authored-by: Sealeen Zhang <[email protected]>
In the last (partial) chunk, padded rows j >= nvalid hold g = 0, so the
intra dkt exponent g[j] - g[r] was large and positive for a strongly decaying
gate (gate in kernel / lower_bound) and exp2 overflowed; 0 * inf then gave
NaN in dk/dg. Mask padded rows in both intra loops and clamp every decay
exponent to <= 0 (causal pairs are <= 0 by construction).

Add AITER_KDA_FLYDSL_CHECK=1 to name the first stage that writes a
non-finite value. Tests: normalize q/k when the contract test runs without
the in-kernel l2norm (unnormalized keys diverge, which was the remaining
contract failures), and cover T=100 (full chunk + 36-token tail).

Co-authored-by: Sealeen Zhang <[email protected]>
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]>
…shapes

FlyDSL varlen: the per-chunk stages (dav, wy_dqkg, intra, gate_cumsum) map
programs through chunk_indices, so chunks stop at sequence edges; dhu runs
one state per (sequence, head) from chunk_offsets; the K5 recurrence uses
its IS_VARLEN path. Outputs past cu_seqlens[-1] are zero, as in Triton.
chunk_kda_bwd_flydsl (the #8739 contract) also takes cu_seqlens.

op_test: -s (b, t, varlen) shapes with the Lumen#35 timing shapes (1x8192,
2x4096, 1x32768, varlen 8x2048), heads 96/48/32/16/12, and -m plain|kimi
(kimi = l2norm + lower_bound gate + beta sigmoid + safe_gate in kernel).
The fp32 reference runs per sequence and head group so 1x32768xH96 fits one
GPU; checked on CPU against the token-by-token reference (varlen, kimi).
pytest: FlyDSL vs Triton on the Lumen#35 shapes and on random-length varlen
with h0/dht.

Co-authored-by: Sealeen Zhang <[email protected]>
@huizzhan
huizzhan added this pull request to stack #8751 November 26, 2026 09:47
cursoragent and others added 9 commits November 26, 2026 09:48
chunk_kda_bwd_flydsl takes lower_bound and safe_gate (default: lower_bound
is not None), so #8739 can fuse K3's gate g = lb * sigmoid(exp(A_log) *
(z + dt_bias)); gate_cumsum already implements that backward (dA_log,
ddt_bias). The contract test adds a safe-gate column (12 combos vs Triton).

Co-authored-by: Sealeen Zhang <[email protected]>
compile_wy_dqkg_mfma runs every wy_dqkg contraction (dq/dk/dw, dA, dvb,
dkgb, the dAkk sandwich) on 16x16x16 bf16 MFMA (4 waves along M) from
bf16 LDS operands, staging each [64, 64] fp32 result through LDS so the
elementwise epilogue keeps the FMA kernel's thread ownership. Operands are
the bf16 values Triton feeds tl.dot. 136 KB LDS, 0 spills on gfx950.

AITER_KDA_FLYDSL_MFMA=0 selects the FMA kernels; AITER_KDA_FLYDSL_PROFILE=1
logs per-stage times.

Co-authored-by: Sealeen Zhang <[email protected]>
compile_dav_mfma: dAqk = do v_new^T and dv = mask(Aqk)^T do on 16x16x16
bf16 MFMA (77 KB LDS, 2 workgroups per CU on gfx950).
compile_dhu_mfma: per chunk, dv2 = dv + kg dh^T and the state update
scale * qg^T do - w^T dv2 as two 64-row K halves on MFMA; the fp32 state
stays in registers and scale applies after the dot as in Triton (88 KB LDS).
Both follow AITER_KDA_FLYDSL_MFMA (default on); 0 spills.

Co-authored-by: Sealeen Zhang <[email protected]>
compile_intra_mfma: one wave per 16-row sub-chunk; between sub-chunks the
decay factors through the sub-chunk pivot (both exponents <= 0), so dq2/dk2
(earlier sub-chunks) and dkt (later sub-chunks) become fp32 16x16x4 MFMA
products with lane-gathered fp32 operands, as Triton keeps them fp32. Pairs
inside a sub-chunk stay elementwise, 16 per row instead of 64 (4x fewer
exp2). q/k stage as bf16 (exact) to fit a fp32 staging tile: 129 KB LDS,
0 spills. Follows AITER_KDA_FLYDSL_MFMA.

Co-authored-by: Sealeen Zhang <[email protected]>
…load loop

The MFMA wy_dqkg computed dgk[k] = sum_v h[k, v] dh[k, v] after dh had
replaced h in LDS, re-reading h from global in a 128-iteration runtime loop:
one dependent global-load latency per iteration, ~100 us per program. Stage
dh row-wise per thread pair instead and accumulate h * dh from the h still in
LDS before overwriting it; the pair combines with one lane shuffle.

Co-authored-by: Sealeen Zhang <[email protected]>
…ges' staging

_stage(_src(tensor, base), ...) loads 16 contiguous bytes per instruction
(8 bf16 / 4 fp32) instead of one element. Used by every staging copy of the
MFMA dav, dhu, wy_dqkg and intra kernels, including wy_dqkg's transposed h
snapshot and its fused dh/dgk pass: wy_dqkg's staging drops from ~350 scalar
global loads per thread to 34 dwordx4. 0 spills; LDS unchanged.

Co-authored-by: Sealeen Zhang <[email protected]>
…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]>
…-K3 / K3.1 CSVs)

Tunables: dhu_bv (MFMA dhu V block, now 16/32/64), fwd_h_bv (K5 recurrence V
block, 0 = its rule) and prepare (forward-recompute backend). The FlyDSL
backward resolves each from: explicit argument > tuned config > default.

New config family AITER_CONFIG_KDA_CHUNK_BWD (aiter/jit/core.py), keyed on
the untuned header gfx,cu_num,N,T,H,varlen; canonical kda_chunk_bwd_{tuned,
untuned}.csv ship header-only, and model_configs/ splits the shapes with no
overlap: kimi_k3 = H 96/48/32/16 at T <= 8192 + varlen 8x2048; kimi_k3.1 =
H 96/24/12 at T 16384/32768/65536 + H 24/12 at the short shapes. Tuned
files are header-only until the GPU sweep; the family is added to the
shape-collision guard.

csrc/kda_chunk_bwd/kda_chunk_bwd_tune.py sweeps the tunables per untuned row
(Kimi safe-gate inputs), drops candidates whose gradients drift from the
default config, and merges the fastest row per shape into the tuned CSV.

Co-authored-by: Sealeen Zhang <[email protected]>
#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]>
cursoragent and others added 5 commits November 26, 2026 12:26
op_tests/op_benchmarks/flydsl/bench_kda_chunk_bwd.py times
chunk_kda_bwd_flydsl_full against chunk_delta_attn_bwd (direct calls, both
including the forward recompute) on Kimi-K3 safe-gate inputs, default H96 at
T 1000/2048/8192 plus varlen 8x2048, and prints one profiled FlyDSL call's
per-stage times per shape. --prepare compares registered prepare backends.

Co-authored-by: Sealeen Zhang <[email protected]>
The wy_dqkg epilogue now owns 32 contiguous columns per thread (seg * 32 + e)
instead of every fourth one, so its per-row global traffic is vectorized:
q/k/g/g_last rows load as dwordx4 (24 instead of ~130 scalar loads) and
dq/dk/dg/dv_out store as dwordx4 (28 instead of ~130 scalar stores). The
[64, 128] MFMA results are read from the staging tile in that ownership;
row/column reductions and every formula are unchanged. 0 spills.

Co-authored-by: Sealeen Zhang <[email protected]>
Same ownership change as wy_dqkg: each thread owns 32 contiguous columns, so
intra's inter-chunk dq/dk/dg inputs, raw q/k (l2norm backward) and
dq2/dk2/dg2 outputs move as dwordx4 (56 vector loads, 16 vector stores, from
~160 scalar loads and ~96 scalar stores). Row reductions span the same 4
lanes; formulas unchanged. VGPRs 354 -> 277, 0 spills.

Co-authored-by: Sealeen Zhang <[email protected]>
…r CU)

The MFMA dhu staged its two state-update products in two fp32 tiles; they now
take turns in one, cutting LDS from 88 KB to 78.6 KB at the default bv=32 so
two workgroups fit a gfx950 CU and all 4 x 96 programs of an H96 call are
resident at once instead of in two rounds. Same math, two more barriers per
K half.

Also fix dhu_bv=16, which did not build: its 64 x 16 do^T tile is not a whole
number of 256-thread vector rounds, and _stage now takes the scalar path for
such ragged tiles instead of a runtime branch outside the kernel body. bv
16 / 32 / 64 now compile (66 / 79 / 104 KB LDS).

Co-authored-by: Sealeen Zhang <[email protected]>
With 32 contiguous columns per thread, intra's per-row LDS reads (g, k, q of
row r and of each row j in the diagonal sub-chunk loops) become b128 reads:
8 / 4 instructions per 32 fp32 / bf16 values instead of 32. The diagonal
loops are the serial part of intra, and it is LDS-latency bound at one
workgroup per CU. Same values, same arithmetic order.

Co-authored-by: Sealeen Zhang <[email protected]>
cursoragent and others added 6 commits November 30, 2026 17:23
…ogue

dq is final after the decay scaling: store it there (in flight under the
dA / dkgb products) and keep only q * dq for dg. Bit-identical outputs.
rocprofv3 kernel trace (us, median of 13): T1000 173.1 -> 170.3,
T2048 329.8 -> 320.7, T8192 1266.2 -> 1237.3, B8 T2048 varlen 2562 -> 2566.
…umn reduction

dk is final once dkgb is in registers: store it before the cross-wave
column sum that dg waits on. Bit-identical outputs. rocprofv3 kernel trace
(us, median of 13): T1000 170.3 -> 169.5, T2048 320.7 -> 316.6,
T8192 1237.3 -> 1215.5, B8 T2048 varlen 2566 -> 2449.
…before the dA products

The next item staging loads move from before dAkk to before dA += dw kg^T,
so they are in flight under dA2 / dkgb / the dk-dg epilogue / dAkk.
Bit-identical outputs; SGPR spills 50 -> 16. rocprofv3 kernel trace (us,
median of 13): T1000 169.5 -> 163.6, T2048 316.6 -> 311.2,
T8192 1215.5 -> 1205.9, B8 T2048 varlen 2449 -> 2346.
…el for many states

compile_dhu_mfma_wcol: each wave owns 16 V columns of the block and every K /
chunk row, so dh and dv2 never leave registers (kg @ dh and w^T dv2 take
their B operand straight from the other product's accumulator: an MFMA C
fragment is the B fragment of the same rows), one barrier pair per chunk
publishes the prefetched kg / qg / w tiles (conflict-free b64 / b128 LDS
writes), do / dv / dv2 go through range-checked buffer descriptors instead
of row branches. 54 KB LDS and waves_per_eu = 2 (no spills) fit two
workgroups per CU. It loses while every program has a CU of its own, so the
host picks it only when (V / bv) * N * H > CUs.

Kernel trace, dhu median us (3 runs): B8 T2048 varlen 1061 -> 1019-1021
(Triton 840); T1000 95, T2048 183, T8192 696 unchanged (base kernel).
Gates: 38 flydsl tests, test_kda_chunk_bwd.py, m_l2 1.000 and scaled align
PASS on both paths (wcol forced via AITER_KDA_FLYDSL_DHU_WCOL=1 and the
align test with compile_dhu_mfma -> wcol: same dhu ULPs as base).
…cts or masks, branch-free dv2 stores

compile_dhu_mfma: the transposed qg^T / w^T tile writes now spread a
quarter-wave over 16 token rows of one column group (b64 writes 8 bytes
apart instead of on one bank); rows past the chunk keep row 0's values
instead of per-element zero selects (every product they reach meets a
zeroed do / dv2 row or feeds a dropped dv2 row); dv2 is stored through a
range-checked buffer descriptor, so rows past the chunk are dropped by the
hardware instead of a branch per row.

Kernel trace, dhu median us (3 runs): T1000 95 -> 89-90, T2048 183 ->
176-179, T8192 696 -> 669-671; B8 T2048 varlen (wcol kernel) 1018-1022
unchanged. Gates: 38 flydsl tests, test_kda_chunk_bwd.py, m_l2 1.000,
scaled align PASS (dhu ULPs unchanged).
…ead_b64_tr_b16

compile_dhu_mfma_wcol stores the prefetched qg / w tiles row-major (b128
rows, like kg) and builds the A fragments of qg^T do and w^T dv2 with the
gfx950 transposing LDS read (LDSReadTrans16_64b): no 2-byte column
scatter of the transposed tiles. Same values.

Kernel trace, dhu median us (3 runs): B8 T2048 varlen 1018-1022 ->
916-919 (Triton 840); dense shapes (base kernel) unchanged: T1000 89-90,
T2048 176-177, T8192 667-671. Gates: 38 flydsl tests,
test_kda_chunk_bwd.py, m_l2 1.000, scaled align PASS; with the wcol kernel
forced (AITER_KDA_FLYDSL_DHU_WCOL=1, align test on wcol) also 38 passed,
m_l2 1.000, align PASS, dhu ULPs unchanged.
Comment on lines +1612 to +1623
return dict(
i_bh=i_bh,
h=h,
t0=t0,
nvalid=nvalid,
tok=tok,
hk=(tok * H + fx.Int64(h)) * K,
hv=(tok * H + fx.Int64(h)) * V,
state=(fx.Int64(i_c) * H + fx.Int64(h)) * (K * V),
a_off=(tok * H + fx.Int64(h)) * BT,
vn_off=(fx.Int64(i_bh) * fx.Int64(T) + fx.Int64(t0)) * V,
)

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] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

Suggested change
return dict(
i_bh=i_bh,
h=h,
t0=t0,
nvalid=nvalid,
tok=tok,
hk=(tok * H + fx.Int64(h)) * K,
hv=(tok * H + fx.Int64(h)) * V,
state=(fx.Int64(i_c) * H + fx.Int64(h)) * (K * V),
a_off=(tok * H + fx.Int64(h)) * BT,
vn_off=(fx.Int64(i_bh) * fx.Int64(T) + fx.Int64(t0)) * V,
)
return {
"i_bh": i_bh,
"h": h,
"t0": t0,
"nvalid": nvalid,
"tok": tok,
"hk": (tok * H + fx.Int64(h)) * K,
"hv": (tok * H + fx.Int64(h)) * V,
"state": (fx.Int64(i_c) * H + fx.Int64(h)) * (K * V),
"a_off": (tok * H + fx.Int64(h)) * BT,
"vn_off": (fx.Int64(i_bh) * fx.Int64(T) + fx.Int64(t0)) * V,
}

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 aaa3926: rewritten as a dict literal. Outputs are bit-identical to the previous head.

def run(a, lda, b_, ldb, kd, acc=None):
"""One [64, 64] product into ``acc`` (a fresh one if None)."""
if const_expr(acc is None):
acc = mma.acc(c_tile)

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 mma

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.

Intended, marked # noqa: B023 in aaa3926. The closure is traced within the same iteration of the scf.for body that defines it, so it sees that iteration's values. A comment above the closures says so.

"""One [64, 64] product into ``acc`` (a fresh one if None)."""
if const_expr(acc is None):
acc = mma.acc(c_tile)
mma.gemm(acc, a, lda, b_, ldb, 64, kd)

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 mma

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.

Intended, marked # noqa: B023 in aaa3926. The closure is traced within the same iteration of the scf.for body that defines it, so it sees that iteration's values. A comment above the closures says so.

"""A [64, 128] product (two N = 64 halves) -> columns ``seg * CPT + e``."""
out = [_zero()] * CPT
for half in range_constexpr(2):
mma.store(run(a, lda, b_half(half), ldb, kd), c_tile)

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 mma

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.

Intended, marked # noqa: B023 in aaa3926. The closure is traced within the same iteration of the scf.for body that defines it, so it sees that iteration's values. A comment above the closures says so.

for half in range_constexpr(2):
mma.store(run(a, lda, b_half(half), ldb, kd), c_tile)
gpu.barrier()
mine = (seg // (RL // 2)) == half

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 seg

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.

Intended, marked # noqa: B023 in aaa3926. The closure is traced within the same iteration of the scf.for body that defines it, so it sees that iteration's values. A comment above the closures says so.

h = i_bh % H
tid = fx.thread_idx.x
kr = tid // 2 # state row (K)
sc = tid % 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] <F841> reported by reviewdog 🐶
Local variable sc is assigned to but never used

Suggested change
sc = tid % 2
tid % 2

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.

Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.

tid = fx.thread_idx.x
kr = tid // 2 # state row (K)
sc = tid % 2
r = tid // 4 # chunk row for dv2

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] <F841> reported by reviewdog 🐶
Local variable r is assigned to but never used

Suggested change
r = tid // 4 # chunk row for dv2
tid // 4 # chunk row for dv2

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.

Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.

kr = tid // 2 # state row (K)
sc = tid % 2
r = tid // 4 # chunk row for dv2
seg = tid % 4

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] <F841> reported by reviewdog 🐶
Local variable seg is assigned to but never used

Suggested change
seg = tid % 4
tid % 4

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.

Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.

pos0 = tile_pos(0)
loaded = tile_load(pos0[0], pos0[1])
for u in range_constexpr(TPW):
t0_u, nv_u, live_u = pos0 if u == 0 else pos_n

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] <RUF059> reported by reviewdog 🐶
Unpacked variable live_u is never used

Suggested change
t0_u, nv_u, live_u = pos0 if u == 0 else pos_n
t0_u, nv_u, _live_u = pos0 if u == 0 else pos_n

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 aaa3926: renamed to _live_u.

pos0 = tile_pos(0)
loaded = tile_load(pos0[0], pos0[1])
for u in range_constexpr(TPW):
t0_u, nv_u, live_u = pos0 if u == 0 else pos_n

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] <F821> reported by reviewdog 🐶
Undefined name pos_n

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 aaa3926: pos_n is now seeded with pos0 before the tile loop. This was not a runtime bug: the old pos0 if u == 0 else pos_n never read pos_n at u == 0, and later iterations read the value set in the previous one. Outputs are bit-identical.


cp8 = fx.make_copy_atom(fx.rocdl.BufferCopy128b(), BF)
cpf4 = fx.make_copy_atom(fx.rocdl.BufferCopy128b(), fx.Float32)
cp4 = fx.make_copy_atom(fx.rocdl.BufferCopy64b(), BF)

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] <F841> reported by reviewdog 🐶
Local variable cp4 is assigned to but never used

Suggested change
cp4 = fx.make_copy_atom(fx.rocdl.BufferCopy64b(), BF)
fx.make_copy_atom(fx.rocdl.BufferCopy64b(), BF)

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.

Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.

(H * V, 8, 1),
)
g_q = tid % (K // 4)
vn_v = _flat(vn, vn_base)

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] <F841> reported by reviewdog 🐶
Local variable vn_v is assigned to but never used

Suggested change
vn_v = _flat(vn, vn_base)
_flat(vn, vn_base)

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.

Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.

)
)
gpu.barrier()
res = yield acc2 + nxt

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] <F841> reported by reviewdog 🐶
Local variable res is assigned to but never used

Suggested change
res = yield acc2 + nxt
yield acc2 + nxt

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 and marked # noqa: F841 in aaa3926. res = yield ... is FlyDSL's loop-carried yield form inside an scf.for, so the assignment stays.

…es; dhu V block by state count

With few states (small H, short batch) fwd_h and dhu are serial walks over
the chunks whose grids leave most CUs idle, and they ran back to back.

- dhu V block: pick the narrowest of 16 / 32 whose grid still fits the CUs,
  else keep 64 (H96 is unchanged). The products are per V column, so the
  outputs do not depend on bv. AITER_KDA_FLYDSL_DHU_AUTO_BV=0 turns it off.
- dav gets compile-time compute_da / compute_dv flags (as Triton's dav
  kernel). dv does not read v_new, so dav's dv part and dhu now run on the
  main stream while fwd_h runs on a side stream; dav's dA part follows the
  join. Only when both grids fit the CUs together, the sequences have at
  least 32 chunks and B*T*H >= 32768 (shorter calls are host bound, where
  the extra launch and waits cost more than the overlap saves).
  AITER_KDA_FLYDSL_CONC_REC=0 turns it off.

Outputs are bit-identical to 43/n on all tested shapes (torch.equal);
pytest, op_test (600 passed), m_l2 (relL2 ratio 1.000 for every gradient)
and the align gate pass.

Eager, gfx950, Triton / FlyDSL us (median of 3):
  B1 T1000 H12      358.5 /  350.8
  B1 T1000 H32      357.5 /  354.8
  B2 T4096 H12      928.5 /  847.3
  B2 T4096 H16     1178.5 / 1143.5
  B1 T4096 H12      567.2 /  563.4
  B1 T8192 H16     1324.5 / 1200.3
  varlen 2x4096 H12 989.2 /  916.2
  B1 T8192 H96     6486.7 / 5353.4   (unchanged)
…few-state dense calls

With few states each recurrence leaves most CUs idle and dhu reads dv, not
v_new, so the two run side by side. 44/n did that on a side stream, but the
cross-stream fork / join costs ~20 us of host time per call (gfx950), which
the T2048 shapes could not pay. compile_fwd_h_dhu now puts both in one
launch instead: the first workgroups run the fwd_h body, the rest the dhu
body, over one LDS union (fwd_h's share padded to a multiple of the XCD
count, so both keep their own XCD placement). The kernel bodies of
compile_fwd_h_mfma / compile_dhu_mfma are factored out unchanged and their
own kernels call them. Dense calls whose fwd_h (bv 64) + dhu grid fits the
CUs take it (dav dv part, fused launch, dav dA part: the launch count of the
sequenced path); varlen keeps the side stream. AITER_KDA_FLYDSL_FUSED_REC=0
restores the side stream.

The dhu loop also loads the next chunk's dv tile only after the dv2 pass,
so it needs no copy at the loop edge (that copy waited for every load in
flight).

Outputs are bit-exact vs 44/n on 14 shapes (dense and varlen, H8 to H96).
Eager, gfx950, Triton / FlyDSL us: B1 T2048 H12 353 / 344, H16 367 / 349,
T4096 H8 430 / 419; H96 unchanged (T8192 6479 / 5338).
The eager varlen schedule is built on the host (prepare_chunk_indices
.tolist(), the K5 prologue's .item() check) and cached on the cu_seqlens
tensor, so a capture either failed or, after a warmup with the same
tensor, baked that schedule in: a replay with other cu_seqlens contents
returned wrong gradients (the Triton bwd behaves the same way).

Under capture the schedule is now built on the device in one launch. The
grids cover the bound ceil(T / 64) + N - 1 chunks and the padding chunks
read in-bounds rows and write nothing, so a replay is bit-exact vs eager
for any cu_seqlens contents with the same N and T, empty sequences
included. Eager calls keep the exact schedule and block choices.

- Varlen dA_log / dt_bias gradients are summed by a fixed-order kernel
  over the real chunks only (eager and capture), so they no longer depend
  on the row count. vs the previous torch sums: relL2 <= 2.6e-7; dq, dk,
  dv, dg, dbeta and all dense outputs are unchanged bit for bit.
- dhu (both kernels) and the K5 one-chunk-ahead prefetch no longer read
  out of bounds for an empty varlen sequence.
A captured varlen call launches its stages for the chunk-count bound
ceil(T / 64) + N - 1. The padding chunks did full work: one more wave of
intra workgroups (its grid is ceil(NT / 2) per head), more persistent
wy_dqkg iterations, and padding gate_cumsum programs. On GPU-bound shapes
the graph replay was 1-4% slower than eager.

The device table builder now writes the real chunk count into one extra
chunk_indices row; the stages read it on the device:
- wy_dqkg walks only the real (chunk, head) items, so its work split
  matches the eager one;
- intra: a workgroup whose tiles are all padding skips its body;
- gate_cumsum: a padding chunk skips its body.
This is a compile-time variant (bounded, set only for captured calls), so
the eager kernels are unchanged. dav keeps running its padding chunks with
no valid rows: wrapping its body made it slower. The Triton prepare gets
chunk_indices[:NT].

Graph replay matches eager bit for bit (34 checks: 3 varlen shapes x 2 dhu
variants, changed and empty sequences), and the eager outputs match the
previous commit bit for bit. Graph replay, same-card alternating A/B
(MI355X, median of 3): H12 varlen 2x4096 924.8 -> 879.4 us (now below
eager, 889 us), H96 varlen 8x2048 10481.1 -> 10402.5 us, H12 varlen 3x700
unchanged (301.1 / 302.2 us).
@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] Kimi-K3 KDA chunk backward (96 heads) [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) Dec 4, 2026
@aiter-bot

aiter-bot commented Dec 4, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 42fdaad42fbc · 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.

Drop unused locals (i_bh, kr/sc/r/seg, cp4, vn_v), use a dict literal, seed pos_n before the tile loop, and mark the trace-time closures (B023) and the scf.for yields (F841) as intended. Black-format kda_chunk_bwd.py and chunk_gated_delta_h.py.

Outputs are bit-identical to the previous head (eager, bounded and save_fwd, 7 shapes).

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

Shared synchronization events can race across concurrent calls, and device-agnostic launcher caching can reuse compiled handles on the wrong GPU.

7 open issues
What changed in this PR

Adds training backward support to chunked Kimi Delta Attention, with Triton as the default and an optional gfx950 FlyDSL backend for Kimi-K3.

Changes:

  • Connects autograd, backward backend selection and optional forward-intermediate reuse.
  • Adds FlyDSL scheduling, recurrence optimizations and tuning support.
  • Adds gradient tests and benchmarks covering 96 heads, variable-length sequences and fused activations.
File Description
op_tests/​tuning_tests/​test_config_shape_collision.py Checks the new tuning family for duplicate shapes.
op_tests/​triton_tests/​kimi_delta_attn/​test_chunk_delta_attn_bwd.py Adds backward correctness and backend parity tests.
op_tests/​test_kda_chunk_bwd.py Adds Kimi-K3 reference checks and timing sweeps.
op_tests/​op_benchmarks/​triton/​bench_chunk_delta_attn_bwd.py Benchmarks forward and backward separately.
op_tests/​op_benchmarks/​flydsl/​bench_kda_chunk_bwd.py Compares backend and saved-intermediate timings.
csrc/​kda_chunk_bwd/​kda_chunk_bwd_tune.py Tunes FlyDSL configurations per shape.
aiter/​ops/​triton/​kimi_delta_attn/​chunk_delta_attn.py Adds autograd and backward options.
aiter/​ops/​triton/​kimi_delta_attn/​__init__.py Updates package documentation for backward support.
aiter/​ops/​triton/​configs/​gfx950/​triton/​attention/​chunk_delta_attn/​DEFAULT.json Adds backward launch configurations.
aiter/​ops/​triton/​_triton_kernels/​kimi_delta_attn/​chunk_fwd.py Extracts shared forward preparation for recomputation.
aiter/​ops/​triton/​_triton_kernels/​kimi_delta_attn/​__init__.py Exports the backward entry point.
aiter/​ops/​triton/​_triton_kernels/​common/​l2norm.py Adds a shared normalization-gradient helper.
aiter/​ops/​flydsl/​kernels/​gdr_prefill/​chunk_gated_delta_h.py Adds optional remapping and prefetch paths.
aiter/​ops/​flydsl/​kda_chunk_bwd.py Implements FlyDSL backward orchestration and adapters.
aiter/​jit/​core.py Registers the backward tuning configuration.
aiter/​configs/​model_configs/​kda_chunk_bwd_untuned_kimi_k3.csv Lists Kimi-K3 tuning shapes.
aiter/​configs/​model_configs/​kda_chunk_bwd_untuned_kimi_k3.1.csv Lists Kimi-K3.1 tuning shapes.
aiter/​configs/​model_configs/​kda_chunk_bwd_tuned_kimi_k3.csv Adds an empty model tuning table.
aiter/​configs/​model_configs/​kda_chunk_bwd_tuned_kimi_k3.1.csv Adds an empty model tuning table.
aiter/​configs/​kda_chunk_bwd_untuned.csv Defines the untuned configuration schema.
aiter/​configs/​kda_chunk_bwd_tuned.csv Defines the canonical tuned configuration schema.

Review effort: Balanced

Comment thread aiter/ops/flydsl/kda_chunk_bwd.py Outdated
Comment on lines +171 to +181
def _side_stream(device):
"""A side stream and two reusable events (fork, join) for the device.
A wait takes the event's last record at enqueue time, so reuse is safe."""
key = torch.device(device).index
if key not in _SIDE_STREAMS:
_SIDE_STREAMS[key] = (
torch.cuda.Stream(device=device),
torch.cuda.Event(),
torch.cuda.Event(),
)
return _SIDE_STREAMS[key]

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 42fdaad: the side stream and its fork/join events are now cached per thread (threading.local), so concurrent callers on different threads never share an event. Within one thread, host calls are serialized, and wait_event captures the event's latest record when it is enqueued, so reusing the pair there is safe and avoids creating two events per call. A 4-thread repro (one stream per thread, 100 concurrent chunk_kda_bwd_flydsl_full calls on the concurrent route, compared with solo runs) showed no mismatch either before or after the change, so this fix rests on the event semantics, not on an observed failure. Eager and graph-replay outputs are bit-identical to the previous head.

Comment on lines +656 to +657
_run_compiled(
compile_fwd_h_mfma(H, h0 is not None, is_varlen, BV, _NUM_XCDS),

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 42fdaad: every _run_compiled launch in kda_chunk_bwd.py now passes specialization_key=<device index>, so each device gets its own launch handle (these launchers are not AOT-bound). On each route the launchers always get tensors of the same rank and dtype, so the device was the only missing key. This could not be reproduced on our gate, which runs one GPU per job; outputs on the default shapes are bit-identical to the previous head.

Comment on lines +643 to +644
elif is_varlen:
NT, chunk_offsets, kernel_cu, N, _ = _resolve_prologue(cu_seqlens, BT, 0, 0, T)

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 T=1000, cu_seqlens=[0, 900]: Triton returns zero gradients for the tail tokens, while eager FlyDSL raised ValueError from _resolve_prologue. Fixed in 42fdaad for eager calls: kda_bwd_flydsl_supported now takes cu_seqlens / T and keeps such calls on the Triton backward. It reuses the cached prologue lookup, so no extra host sync is added. New test: test_backward_flydsl_short_cu_seqlens. Under graph capture nothing can be read back, so cu_seqlens[-1] == T remains a documented requirement of chunk_kda_bwd_flydsl_full there; whether to zero-fill the tail under capture (extra memsets on every call) is still open.

Comment on lines +101 to +102
d = (b.float() - a.float()).square().mean().sqrt()
worst = max(worst, (d / (a.float().square().mean().sqrt() + 1e-8)).item())

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 42fdaad: candidates whose error is not finite are now skipped (not math.isfinite(err) or err > args.max_err).

Comment on lines +127 to +128
fwd_ms = triton.testing.do_bench(fwd, warmup=0, rep=args.rep_ms)
bwd_ms = triton.testing.do_bench(bwd, warmup=0, rep=args.rep_ms)

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 42fdaad: the benchmark now uses RotatingBufferBench with an input generator (fresh leaves and do per pool entry) and the shared --rot-bufs-* / --graph-* CLI flags. The backward is captured together with its forward (so autograd's backward runs on the capture stream) and reported as (forward + backward) − forward.

Comment thread op_tests/test_kda_chunk_bwd.py Outdated
from aiter.ops.triton.kimi_delta_attn import chunk_kimi_delta_attn
from aiter.test_common import benchmark, checkAllclose, run_perftest

torch.set_default_device("cuda")

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 42fdaad: removed torch.set_default_device("cuda"); every tensor the test creates now names its device explicitly.


def test_flydsl_fwd_prepare_hook(monkeypatch):
"""A registered prepare runs only when selected, by argument or environment."""
pytest.importorskip("flydsl")

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 42fdaad: the test now skips when the runtime GPU is not gfx950, since the FlyDSL backward kernels need gfx950's LDS.

Resolves the chunk_kimi_delta_attn signature and docstring conflict with #8043 by keeping both sides: main's out_gate / norm_weight / norm_eps / checkpoint_* / cu_seqlens_cpu, then bwd_backend / save_fwd.

main's entry point was forward-only; with the backward here, the fused output norm and the prefill checkpoints join out / state_cache as inference-only arguments, rejected when an input requires grad (test extended).
- Key compiled FlyDSL handles by device index.
- Cache the side stream and fork/join events per thread so concurrent
  callers never share an event.
- Keep eager calls whose cu_seqlens[-1] < T on the Triton backward
  (the FlyDSL kernels require cu_seqlens[-1] == T); add a test.
- Tuner: skip candidates with a non-finite error.
- Benchmark: use RotatingBufferBench and the shared rot-bufs / graph
  CLI flags; capture the backward together with its forward.
- Tests: skip the FlyDSL prepare-hook test off gfx950; drop the global
  default device in test_kda_chunk_bwd.py.

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