Repository navigation
Conversation
Co-authored-by: Sealeen Zhang <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
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]>
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]>
…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]>
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]>
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]>
…head on long latency-bound shapes
…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.
| 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, | ||
| ) |
There was a problem hiding this comment.
Unnecessary dict() call (rewrite as a literal)
| 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, | |
| } |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
| 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 |
There was a problem hiding this comment.
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.
…tate in registers (dense)
|
|
||
| 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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Removed the unused local in aaa3926. Outputs are bit-identical to the previous head.
| ) | ||
| ) | ||
| gpu.barrier() | ||
| res = yield acc2 + nxt |
There was a problem hiding this comment.
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).
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
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).
There was a problem hiding this comment.
🟡 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
Use per-call fork and join events for concurrent calls · New Include the input device in the compiled-launch cache key · New Preserve support for cu_seqlens ending before T · New Reject non-finite errors before ranking tuner candidates · New Use rotating buffers for do_bench benchmarks · New Avoid changing the global default device · New Skip this backend-specific test unless the runtime is gfx950 · New
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
| 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] |
There was a problem hiding this comment.
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.
| _run_compiled( | ||
| compile_fwd_h_mfma(H, h0 is not None, is_varlen, BV, _NUM_XCDS), |
There was a problem hiding this comment.
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.
| elif is_varlen: | ||
| NT, chunk_offsets, kernel_cu, N, _ = _resolve_prologue(cu_seqlens, BT, 0, 0, T) |
There was a problem hiding this comment.
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.
| d = (b.float() - a.float()).square().mean().sqrt() | ||
| worst = max(worst, (d / (a.float().square().mean().sqrt() + 1e-8)).item()) |
There was a problem hiding this comment.
Fixed in 42fdaad: candidates whose error is not finite are now skipped (not math.isfinite(err) or err > args.max_err).
| 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) |
There was a problem hiding this comment.
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.
| 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") |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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.


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
chunk_kda_bwdTriton port, branchzain/kda/bwd@966a494), withCo-authored-by: Micky774. Thefast_launchimport is moved toaiter.ops.triton.utils([Triton/Gluon] Move fast_launch to utils and key what Triton specializes on #8061).kernels/gdr_prefill/chunk_gated_delta_h.py,USE_GK).chunk_kda_torchin [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739. This PR is [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739's chunk sub-module.Changes
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.chunk_kimi_delta_attn(..., bwd_backend="flydsl")/chunk_delta_attn_bwd(..., backend="flydsl")):chunk_delta_attn_fwd_prepare). Withchunk_kimi_delta_attn(..., save_fwd=True)the forward keeps them instead.h,v_new): dense calls use a KDA kernel that keeps the state in registers (with few states it shares one launch withdhu); varlen calls use the K5 kernel'sIS_VARLENpath. Both are read in their native layouts.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 Kimilower_boundforms).cu_seqlens, B=1) on every stage:chunk_indices, so chunks stop at sequence edges.dhukeeps one state per (sequence, head), starting atchunk_offsets.cu_seqlens[-1]are zero, as in Triton.cu_seqlenscontents with the same N and total T, and captured calls skip the padding chunks.AITER_KDA_FLYDSL_CHECK=1checks each stage's outputs and raises on the first non-finite value, naming the stage.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_boundselects K3's safe gateg = lb * sigmoid(exp(A_log) * (z + dt_bias)).safe_gatedefaults tolower_bound is not None.CHUNK_BWD_FUSES = {qk_l2norm, gate, beta_sigmoid};register_with_kda_layer()installs it viaregister_chunk_bwd.[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.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.-H96/48/32/16/12 (K3 TP1/2/8 and the issue's H32/H16); D=128, bf16.-m plain|kimi:kimiis the issue's safe_gate setting (l2norm +lower_bound=-5gate + beta sigmoid in kernel).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 gatelower_bound=-5) × beta sigmoid, with dA_log / ddt_bias checked.save_fwdand 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.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: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
mainchunk_kda_fwd_prepare_flydslas an opt-in forward-prepare backendregister_with_kda_layer) on the current head (last run at 36/n)PR Self-Review
Reviewed revision
42fdaad42fbcf4282b7ee9792f450acd7a0f5f91Behavior and intent
chunk_kimi_delta_attnfor 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.chunk_kimi_delta_attn(..., bwd_backend="flydsl")orchunk_delta_attn_bwd(..., backend="flydsl"). Every backward stage (dav,dhu,wy_dqkg,intra,gate_cumsum) and the forward-state recurrence (GDN K5 / KDAfwd_h) then run on FlyDSL. The forward intermediates are recomputed by the Triton prologue, or reused withsave_fwd=True.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.pyalso 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).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 currentmain) and42fdaad4(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 passcheckAllclose(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 flydslwithAITER_KDA_FLYDSL_CONC_REC=0, and with all three FlyDSL scheduling switches off: 37 passed each.dhuvariants. 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.aaa39263vsf4ddc7b8: all 7 outputs aretorch.equalon 7 shapes (dense and varlen, H96 and H12) in eager, bounded (captured schedule) andsave_fwdmode.ruff check .andblack --checkare clean. pytest gave the same result as above.7b40ccb7mergesmain(4052b38a) and keeps [Triton/Gluon] [gfx950/1250] FlashKDA updates #8043's newchunk_kimi_delta_attnarguments next tobwd_backend/save_fwd. Againstaaa39263, all 7 outputs aretorch.equalon the same 7 shapes in eager, bounded andsave_fwdmode: 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, andtest_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.42fdaad4addresses the Copilot review: launch handles keyed by device, fork/join events cached per thread, eager calls withcu_seqlens[-1] < Trouted to Triton (new testtest_backward_flydsl_short_cu_seqlens), non-finite tuner errors skipped,bench_chunk_delta_attn_bwd.pymoved toRotatingBufferBench, and two test fixes. Against7b40ccb7, all 7 outputs aretorch.equalon the same 7 shapes in eager, bounded andsave_fwdmode, 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% of7b40ccb7on the three host-bound shapes (T1000 H12, varlen 3x700, varlen 2x4096; medians of 6 interleaved rounds).cu_seqlens[-1] < T: nothing is checked under capture, so the tail gradients are left unwritten;cu_seqlens[-1] == Tis a documented requirement there.test_chunk_delta_attn_bwd.pythat 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 ofbench_chunk_delta_attn_bwd.pydo not compile with the test machine's Triton 3.6.0 (AMDMFMALayouthas 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?
bwd_backend="flydsl"(orbackend="flydsl"tochunk_delta_attn_bwd).kda_bwd_flydsl_supportedmust hold:get_gfx_runtime() == "gfx950",K == V == 128,chunk_size == 64,H == HV(no GVA), bf16 inputs, andB == 1whencu_seqlensis given; eager varlen calls also needcu_seqlens[-1] == T. Any other call runs the Triton backward with the same output contract.ValueError, as does a varlen call to the FlyDSL entry point withB != 1.out,state_cache,out_gate/norm_weightand the prefill checkpoints) raiseValueError, 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'schunk_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.requires_grad, and rejection of inference-only arguments.save_fwd/ forward intermediates.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 andsave_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 ofchunk_kimi_delta_attnacross 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.