Skip to content

[Triton/Gluon] KDA: add the chunk_delta_attn backward pass - #6498

Open
Micky774 wants to merge 3 commits into
mainfrom
zain/kda/bwd
Open

Micky774 wants to merge 3 commits into
mainfrom
zain/kda/bwd

Conversation

@Micky774

Copy link
Copy Markdown
Contributor

Makes chunk_kimi_delta_attn differentiable w.r.t. q, k, v, g, beta, A_log, dt_bias and initial_state.

Changes

  • _triton_kernels/kimi_delta_attn/chunk_bwd.py:
    • Backward kernels ported from fla's chunk_kda_bwd.
    • chunk_delta_attn_bwd recomputes the default pipeline's intermediates from the saved inputs, so the forward can still take FlashKDA.
  • When there are too few states to fill the GPU, the recomputed forward recurrence and dhu share one launch.
  • bwd_intra folds the l2norm and beta-sigmoid backward into its epilogue when it can.
  • remap_xcd is applied to the recurrence and intra kernels.
  • gfx950 tiles live in chunk_delta_attn/DEFAULT.json, with fallbacks in code for other archs.
  • out / state_cache remain inference-only and raise when grad is required. disable_recompute is accepted and ignored.

Tests

test_chunk_delta_attn_bwd.py checks gradients against autograd through the fp32 token recurrence. It covers:

  • FlashKDA-eligible inputs, safe_gate, softplus with GVA, K=256, precomputed gate, varlen, V-first state, and wide recurrences.
  • FlashKDA vs default forward.
  • Partial requires_grad.
  • Parity with fla's chunk_kda.

All 146 KDA tests pass on MI355X (1 skipped).

Perf (MI355X, training fwd + bwd, µs)

shape fla chunk_kda this PR
1x8192 H32, safe_gate 3823 2745
2x4096 H16, safe_gate 2006 1462
1x32768 H16, safe_gate 9718 5784
varlen 8x2048 H16, safe_gate 2896 2507
  • The backward alone is 0.62–0.95× of fla's.

🤖 Generated with Claude Code

chunk_kimi_delta_attn is now differentiable w.r.t. q, k, v, g, beta, A_log,
dt_bias and initial_state. When an input requires grad it runs under an
autograd function that saves only the inputs; the backward recomputes the
default pipeline's intermediates (fla's disable_recompute=False), whichever
path ran the forward.

- _triton_kernels/kimi_delta_attn/chunk_bwd.py: backward kernels after fla's
  chunk_kda_bwd (dAv, dhu, WY dq/dk/dg, intra, reverse gate cumsum + gate
  activation, l2norm, beta sigmoid), launched through fast_launch
- With too few states to fill the GPU, the recomputed forward recurrence and
  dhu share one launch; dhu reads qg from the recompute
- bwd_intra finishes the l2norm and dbeta (beta sigmoid included) in its
  epilogue with the in-kernel l2norm, no GVA and K <= 128
- dhu, the fused recurrence and bwd_intra renumber program ids with
  remap_xcd so programs sharing loads stay on one XCD
- Launch tiles published for gfx950 under CHUNK_DELTA_ATTN
- out / state_cache stay inference-only and are rejected with grad
- Tests: gradients vs autograd through the fp32 token recurrence
  (FlashKDA-eligible, safe_gate, softplus + GVA, K=256, precomputed gate,
  varlen, V-first state, wide recurrences), FlashKDA vs default forward,
  partial requires_grad, and parity with fla's chunk_kda

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Micky774
Micky774 requested review from a team and a balanced review from Copilot October 13, 2026 19:16
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
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 gfx1201 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 6498 --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.

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

A long-sequence int32 offset can corrupt gradients, and several required kernel conventions and benchmark coverage are missing.

5 open findings
What changed in this PR

Adds differentiable backward support for chunked Kimi Delta Attention.

Changes:

  • Adds recomputing Triton backward kernels and autograd integration.
  • Adds gfx950 tuning configurations.
  • Adds gradient-parity and dispatch tests.
File Description
op_tests/​triton_tests/​kimi_delta_attn/​test_chunk_delta_attn_bwd.py Adds backward correctness tests.
aiter/​ops/​triton/​kimi_delta_attn/​chunk_delta_attn.py Integrates PyTorch autograd.
aiter/​ops/​triton/​kimi_delta_attn/​__init__.py Updates public documentation.
aiter/​ops/​triton/​configs/​gfx950/​triton/​attention/​chunk_delta_attn/​DEFAULT.json Adds backward tuning entries.
aiter/​ops/​triton/​_triton_kernels/​kimi_delta_attn/​chunk_bwd.py Implements backward kernels and launch pipeline.
aiter/​ops/​triton/​_triton_kernels/​kimi_delta_attn/​__init__.py Exports the backward implementation.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.


last_idx = min((i_t + 1) * BT, T) - 1
b_gk_last1 = tl.load(
gk + (bos + last_idx) * H * K + i_h * K + o_k1,

import functools

import torch
return dy * rstd - tl.sum(dy * y, axis=1)[:, None] * y * rstd


@triton.jit
return dx


def chunk_delta_attn_bwd(
import torch
import torch.nn.functional as F

from aiter.ops.triton._triton_kernels.kimi_delta_attn import chunk_fwd
@@ -0,0 +1,2071 @@
# SPDX-License-Identifier: MIT

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.

Kernels should have repr decorator function (@triton.jit(repr=...), use make_kernel_repr)

There should also be a benchmark file associated to the new kernel

from aiter.ops.triton.utils._triton.pid_preprocessing import remap_xcd


@triton.jit

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.

this could move to a shared helper file (common/utils)?

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 7, 2026
@micmelesse

Copy link
Copy Markdown
Contributor

@Micky774 Can you rebase please?

- chunk_delta_attn.py: main no longer packs q, k, v, g in the wrapper
  (gfx1250 FlashKDA reads them at their own stride). The backward assumes
  contiguous saved inputs, so pack them on the autograd path only.
- chunk_bwd.py: pid_preprocessing moved to _triton_kernels/common/ (#6505).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 11, 2026 20:16
@aiter-bot

aiter-bot commented Nov 11, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 966a494eed9f · 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 exact workload keys consume these configuration changes, and what evidence shows that unrelated shapes keep their previous selection?
  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 — missing ### Reviewed revision in the PR description
  • FAIL — missing ### Behavior and intent in the PR description
  • FAIL — missing ### Validation and unverified scope in the PR description
  • FAIL — missing ### PR-specific question in the PR description
  • FAIL — missing ### Changed op tests in the PR description
  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — Behavior and intent has no substantive answer
  • FAIL — Validation and unverified scope has no substantive answer
  • FAIL — PR-specific question has no substantive answer
  • FAIL — changed op test not explained in Changed op tests: op_tests/op_benchmarks/triton/bench_chunk_delta_attn_bwd.py
  • FAIL — changed op test not explained in Changed op tests: op_tests/triton_tests/kimi_delta_attn/test_chunk_delta_attn_bwd.py
  • FAIL — Changed op tests must explain why each changed op test is necessary and non-redundant

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

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.

b_h4 += tl.load(p_h0_4, mask=m_h4, other=0.0).to(tl.float32)

for i_t in range(NT):
o_t = i_t * BT + tl.arange(0, BT)
Comment on lines +490 to +491
@triton.jit
def _fwd_h_body(
Comment on lines +1507 to +1510
_FALLBACK_CONFIGS = {
"chunk_delta_attn_bwd_kernel_dav": triton.Config(
{"BV": 64}, num_warps=4, num_stages=2
),
@micmelesse

micmelesse commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

@Micky774 Can you address the lint errors, copilot review and also review from @omuhamma?

@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 12, 2026
- Fix int32 overflow in _fwd_h_body: token offsets scaled by H*K and the
  gate index wrapped past 2**31 / (H*K) tokens (dq, dk, dg wrong after
  token 262144 at H=64, K=128). Chunk starts now go into int64 pointers.
- Give each backward kernel a config-aware repr (make_kernel_repr).
- Move the L2 norm backward device helper to _triton_kernels/common/l2norm.py.
- Share the forward preparation (activations, gate cumsum, intra) between
  the forward and the backward recompute: chunk_delta_attn_fwd_prepare.
- Add bench_chunk_delta_attn_bwd.py.
- Test: give the gradient tensors an explicit dtype.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 12, 2026 16:29
@Micky774

Copy link
Copy Markdown
Contributor Author

@Micky774 Can you address the lint errors, copilot review and also review from @omuhamma?

Updated now to account for all review comments thus far. Note that a couple of the copilot ones are out of scope or inapplicable, but I've addressed the remaining ones.

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

A critical guard omission allows state_cache to be updated without autograd tracking when it is the only input requiring gradients.

9 open issues
3 previously missed issues

In code that hasn't changed since last review

High severity Reject gradient-bearing state_cache and out buffers

aiter/​ops/​triton/​kimi_delta_attn/​chunk_delta_attn.py:334

When only state_cache requires grad, this tuple excludes it, so the inference-only guard is skipped and the cache is updated without autograd tracking. Reject gradient-bearing state_cache and out buffers before this check.

Medium severity Use shared device queries for XCD and SM counts

aiter/​ops/​triton/​_triton_kernels/​kimi_delta_attn/​chunk_bwd.py:1638

The fixed eight-XCD count misses supported four- and six-XCD devices, and _num_cus repeats an existing device query. Use get_num_xcds and get_num_sms from utils/device_info.py with the input device selected at launch time, as required by the shared-helper rule in aiter/ops/triton/README.md:25-28.

Medium severity Cache chunk indices for both forward and backward sizes

aiter/​ops/​triton/​kimi_delta_attn/​chunk_delta_attn.py:82

For FlashKDA varlen calls with chunk_size=None, forward requests size 32 and backward requests size 64, so the single-entry prepare_chunk_indices cache misses on every pass and repeats its .tolist() host sync. Keep a bounded cache for both (cu_seqlens, chunk_size) keys so training can reuse the indices after warmup.

3 resolved since last review

Review effort: Balanced

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)
# ---------------------------------------------------------------------------

# Launchable anywhere; the measured tiles are published per arch under the
# CHUNK_DELTA_ATTN config, keyed by kernel name. The recurrences have a narrow

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.

configs should be kept in json

q, k, v, g = (t.contiguous() for t in (q, k, v, g))

# ------------------------------------------------------------------
# Step 0 — Optional QK L2 normalization (matches FLA API)

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.

why remove this functionality ?

cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
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]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
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.
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
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]>
@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Dec 3, 2026

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

Labels

stale The PR hasn't been updated in 2 weeks Triton/Gluon

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants