Repository navigation
Conversation
Co-authored-by: Sealeen Zhang <[email protected]>
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: |
…al_states) for Kimi-K3 Add causal_conv1d_split_qkv_bwd_triton_fn, the backward of the varlen causal conv1d with the [Q | K | V] layout of causal_conv1d_split_qkv. It recomputes the pre-activation, so the forward saves nothing. dweight and dbias are reduced from per-chunk fp32 partials, so the result is deterministic. Add a gfx950 launch config, an fp32 autograd reference test with Kimi-K3 shapes and a benchmark. Co-authored-by: Sealeen Zhang <[email protected]>
Co-authored-by: Sealeen Zhang <[email protected]>
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 |
…950) The old kernel recomputed the pre-activation and SiLU for each of the width output taps of every token. A 64 x 64 tile read 20 shifted x tiles and 12 masked dq/dk/dv tiles with scalar loads, and needed 310-482 VGPRs. Each program now walks the tokens of its chunk one row of BLOCK_N channels at a time. The last width - 1 rows of x and of the pre-activation gradient stay in registers, so x and the output gradient are read once and dx is written once. The next row is loaded before the current one is used. A channel block inside one of q, k, v reads that tensor only. The kernel uses 54 VGPRs. Host side: no torch.arange when cache_indices is None, a [chunk, channel, tap] partial layout that sums straight into the dweight layout, and a two-step fixed-order sum when there are 256 or more chunks. dq, dk and dv must share one dtype. gfx950 config: BLOCK_M 64, BLOCK_N 128, 1 warp, from a sweep of 45 configs on the Kimi-K3 cases. The worst case is within 3% of the per-case best. MI350X (gfx950), bench_causal_conv1d_bwd.py, 2 alternating rounds on one GPU, before -> after (us): TP8, 1 x 8192 437 -> 94 TP8, 2 x 4096 437 -> 95 TP8, varlen 8 x ~2048 778 -> 156 TP8, 1 x 32768 1698 -> 310 TP1, 1 x 4096 1688 -> 308 TP1, 1 x 8192 3363 -> 592 Add a test with token-contiguous x and gradients (no unit channel stride).
There was a problem hiding this comment.
🟡 Changes recommended
The backward kernels retain int32 stride overflow that can cause out-of-bounds accesses, NaN-padding contamination, and uninitialized tail gradients when reusing nums_dict.
3 open issues
What changed in this PR
Adds Triton causal conv1d backward support for Kimi-K3 training, complementing the existing forward kernels and KDA attention backward with convolution weight gradients.
Changes:
- Exports a variable-length, split-QKV backward API returning input, weight, bias, and initial-state gradients.
- Adds a sliding-window kernel with per-chunk gradient partials, fixed-order reduction, and a gfx950 launch config.
- Adds autograd-reference tests and CUDA-graph benchmarks for TP8 and TP1 workloads.
| File | Description |
|---|---|
op_tests/triton_tests/gated_delta_net/test_causal_conv1d_bwd.py |
Tests gradients, layouts, padding, initial states, and schedule reuse. |
op_tests/op_benchmarks/triton/bench_causal_conv1d_bwd.py |
Benchmarks Kimi-K3 workloads with rotating inputs and CUDA graphs. |
aiter/ops/triton/gated_delta_net/causal_conv1d_bwd.py |
Implements the public wrapper, scheduling, allocations, and gradient reduction. |
aiter/ops/triton/gated_delta_net/__init__.py |
Exports the new backward API. |
aiter/ops/triton/configs/gfx950/triton/conv/causal_conv1d_split_qkv_bwd/DEFAULT.json |
Supplies gfx950 launch settings. |
aiter/ops/triton/_triton_kernels/gated_delta_net/prefill/causal_conv1d_bwd_split_qkv.py |
Computes input gradients and partial parameter gradients with a sliding window. |
Review effort: Balanced
| seqlen = tl.load(query_start_loc_ptr + seq + 1) - seq_start | ||
|
|
||
| blk_lo = pid_n * BLOCK_N | ||
| feats = blk_lo + tl.arange(0, BLOCK_N) |
| gin = tl.where(i < n_tok, g, 0.0) | ||
| dw0 += gin * xu | ||
| dw1 += gin * xd1 | ||
| if KERNEL_WIDTH >= 3: | ||
| dw2 += gin * xd2 | ||
| if KERNEL_WIDTH >= 4: | ||
| dw3 += gin * xd3 |
| if end is not None and end < cu_seqlen: | ||
| dx[:, end:].zero_() |
…tail dx fill Three fixes from review, each reproduced on the previous revision: - Channel offsets for x, dx, dq/dk/dv, the initial states and dinitial_states are computed in int64 when the channel stride is not 1. A token-contiguous x in a [36864, 65536] buffer overflowed int32 at channel 32768 and aborted the process with a GPU memory fault. - x is read under the live length of the sequence, as the output gradient already was, so NaN or Inf in the x rows of a padded sequence no longer reach dx, dweight or dbias through 0 * NaN and SiLU. - dx of the tokens after the last sequence is zeroed in the kernel, with the end read on the device. Reusing a nums_dict schedule left those rows uninitialized before; now every path zeroes them, the documented exception is gone, and the plain path drops a query_start_loc[-1].item() host sync. Tests: test_pad_slots_nan, test_large_channel_stride, and tail tokens plus a NaN-poisoned allocator in test_nums_dict_schedule. MI350X (gfx950), bench_causal_conv1d_bwd.py, 2 alternating rounds on one GPU: within 0.5% of the previous revision on every case (TP8 1 x 8192: 93.8 vs 93.6 us; TP1 1 x 8192: 589.8 vs 589.1 us).
…v bwd, pluggable chunk bwd Co-authored-by: Sealeen Zhang <[email protected]>
Add causal_conv1d_split_qkv_bwd_flydsl_fn, the FlyDSL counterpart of causal_conv1d_split_qkv_bwd_triton_fn, with the same arguments, layout and results: dx, dweight, dbias and dinitial_states of the varlen causal conv1d with split q/k/v output. The Triton version stays. - aiter/ops/flydsl/kernels/causal_conv1d_bwd.py: the kernel. Each program owns one (sequence, chunk) of the chunk schedule; each thread owns one or two adjacent channels and walks the chunk plus width - 1 halo rows in an unrolled loop, loading prefetch rows of x and of the output gradient ahead. The q/k/v source is picked once per thread, outside the token loop. Rows past the live length, and all rows of padded sequences, read clamped addresses and select zero, so NaN there reaches no gradient. Offsets are 64-bit. dx of the tokens after the last sequence is zeroed in the kernel from the device copy of the end, so a reused nums_dict schedule needs no host sync. - aiter/ops/flydsl/causal_conv1d_bwd_flydsl.py: the wrapper. Same schedule sources as the Triton wrapper (CausalConvPrefillMetadata, nums_dict, or a schedule built here), fp32 per-chunk dweight/dbias partials summed in a fixed order (deterministic, no atomics). Defaults (block_m 32, 128 threads, prefetch 16, 2 channels per thread) are the best of a 54-config gfx950 sweep on the Kimi-K3 TP8/TP1 shapes. - op_tests/test_flydsl_causal_conv1d_bwd.py: the cases of the Triton test against the same fp32 autograd reference, plus odd channel splits, 1 and 2 channels per thread, and CUDA-graph capture and replay; main() times FlyDSL and Triton on the Kimi-K3 shapes. MI350X (gfx950), flydsl 0.5.3: 46/46 tests pass.
…ositions The unrolled token loop needed 164 VGPRs at block_m 32 and 294 with 146 SGPR spills at block_m 64, and each row spent most of its ~325 instructions on the IEEE exp expansion, an IEEE divide and 64-bit position compares. - Walk the chunk in a runtime loop (scf.for with carried state) over groups of `prefetch` rows, loading the next group before the current one is used, so register use no longer grows with the chunk length (50-62 VGPRs, no spills) and block_m 64 halves the dweight partials. The unrolled loop stays behind runtime_loop=False. - SiLU gradient through the exp2 (afn) + rcp sigmoid of the other FlyDSL kernels (act.sigmoid_batch). - Token positions in int32; 64-bit only in the addresses, with the per-thread channel offsets hoisted out of the loop. - Defaults: block_m 64, 64 threads, prefetch 4, 2 channels per thread. MI350X (gfx950): the 46 FlyDSL tests pass with unchanged tolerances. Preliminary short-timing bench (CUDA graph) vs Triton 21100d0, us: TP8 1x8192 72 vs 92, TP8 1x32768 274 vs 316, TP1 1x4096 272 vs 316, TP1 1x8192 535 vs 607.
brunomazzottiamd
left a comment
There was a problem hiding this comment.
1. This PR changes two backends.
The PR changes Triton and FlyDSL. The repo rule is one backend for each PR, because different teams own these backends.
FlyDSL files (move to a separate PR):
aiter/ops/flydsl/causal_conv1d_bwd_flydsl.pyaiter/ops/flydsl/kernels/causal_conv1d_bwd.pyop_tests/test_flydsl_causal_conv1d_bwd.py
Keep only the Triton files here: the wrapper, the kernel, the config, the test and the benchmark. Open the FlyDSL PR as a stacked PR on top of this one. Ask the FlyDSL owners to review it.
2. Explain why two implementations exist.
Both functions have the same arguments and results. The PR does not say why we need both. Please answer these questions before proceeding with two stacked PRs (Triton and FlyDSL):
- Which implementation is the intended default for callers?
- Which archs does FlyDSL support? The PR shows tests on gfx950 only.
- Will Triton be removed, or will it stay as a fallback? The text "stays in this PR for now" does not say.
- What is the dependency on FlyDSL, and what happens when it is not installed?
3. The "FlyDSL is faster" claim has no firm evidence.
The numbers come from one short run on one GPU. The PR calls them "preliminary", and the formal A/B comparison is "pending". The first FlyDSL version was slower than Triton by 4% to 24%. Add the formal A/B numbers (at least two alternating rounds, same GPU, same method) for the final commit. Also add the accuracy check of the fast sigmoid. Until then, do not claim a speedup.
4. The PR description must describe what will be merged.
The description is a development log. Write one description of the final state to be merged, to avoid confusion. It must have the design, the supported cases, the tests and a performance table that matches the final head commit. Also remove the CURSOR_AGENT_PR_BODY markers and the "Open in Web" and "Open in Cursor" footer.
5. Commits: no AI-agent authorship.
All 8 commits have Cursor Agent as the author. Four of them also have a Co-authored-by trailer. See item 29 of aiter/ops/triton/README.md: remove AI-agent attribution from the commits before the merge. Rewrite the author of every commit to the human who is responsible for the change.


Summary
Add the training backward of the varlen causal conv1d with split q/k/v output:
causal_conv1d_split_qkv_bwd_triton_fn. It givesdx,dweight(the depthwise conv weight gradient),dbiasanddinitial_states. The target is the Kimi-K3 KDA short conv on MI350X / MI355X (gfx950). One backend: Triton.Requirements: ZhangDanyang-AMD/Lumen#35 (row "causal conv1d backward": depthwise
[12288, 1, 4]for each of q, k and v, "Needs Conv1D wgrad").Motivation
mainhas only forward and update (inference) kernels for causal conv1d. Lumen issue #35 lists the conv1d weight gradient as a P0 gap for Kimi-K3 training. The chunk-KDA backward in #6498 does not differentiate the conv weight.Changes
aiter/ops/triton/gated_delta_net/causal_conv1d_bwd.py: new public wrappercausal_conv1d_split_qkv_bwd_triton_fn. It uses the layout ofcausal_conv1d_split_qkv_triton_tile_fn([Triton/Gluon] Updates to causal_conv1d_split_qkv kernel #7028):xis[dim, cu_seqlen]with channels[Q | K | V], and the gradients aredq, dk: [cu_seqlen, k_dim],dv: [cu_seqlen, v_dim]. It accepts the same varlen arguments:query_start_loc,cache_indices,has_initial_state,pad_slot_id, andmetadata(aCausalConvPrefillMetadataor anums_dictschedule). A prefillednums_dictneeds no host sync, so the call can be captured in a graph.dq,dkanddvmust share one dtype.aiter/ops/triton/_triton_kernels/gated_delta_net/prefill/causal_conv1d_bwd_split_qkv.py: new kernel. Each program handles one(sequence, chunk)from the existing chunk schedule and one block ofBLOCK_Nchannels. It walks the chunk one token row at a time and keeps the lastwidth - 1rows ofxand of the pre-activation gradient in registers, soxand the output gradient are read once anddxis written once. It recomputes the pre-activation fromx, so the forward saves nothing. It writes per-chunk fp32 partials ofdweightanddbias, and the host sums them in a fixed order. This makes the result deterministic, with no atomics. Width 2, 3 and 4. SiLU or no activation. Optional bias and initial states. Padded sequences get zero gradients.aiter/ops/triton/configs/gfx950/triton/conv/causal_conv1d_split_qkv_bwd/DEFAULT.json: the gfx950 launch config:BLOCK_M64,BLOCK_N128, 1 warp. It comes from a sweep of 45 configs on the benchmark cases; on every case it is within 3% of the best config for that case. Other archs use the wrapper default, which has the same values.aiter/ops/triton/gated_delta_net/__init__.py: export the new wrapper.op_tests/triton_tests/gated_delta_net/test_causal_conv1d_bwd.py: tests against an fp32 torch autograd reference. This replaces the skipped skeleton from the first commit.op_tests/op_benchmarks/triton/bench_causal_conv1d_bwd.py: benchmark with Kimi-K3 TP8 and TP1 cases (RotatingBufferBench, CUDA graph).No existing code path changes.
FlyDSL version
4faa6bcaddscausal_conv1d_split_qkv_bwd_flydsl_fn(aiter/ops/flydsl/causal_conv1d_bwd_flydsl.py, kernel inaiter/ops/flydsl/kernels/causal_conv1d_bwd.py), and794546aspeeds it up. It takes the same arguments and returns the same results as the Triton function, which stays in this PR for now. Each thread owns one or two adjacent channels and walks its chunk in a runtime loop over groups ofprefetchrows, loading the next group before the current one is used (50-62 VGPRs, no spills). The SiLU gradient uses the exp2 (afn) + rcp sigmoid of the other FlyDSL kernels. It keeps the Triton semantics: varlen chunk schedule (CausalConvPrefillMetadataornums_dict), pad slots with NaN-safe zero gradients, int64 offsets, taildxzeroed in the kernel, and fp32 per-chunkdweight/dbiaspartials summed in a fixed order (deterministic, no atomics, CUDA-graph safe). The defaults (block_m64, 64 threads, prefetch 4, 2 channels per thread) are preliminary.op_tests/test_flydsl_causal_conv1d_bwd.pyruns the cases of the Triton test against the same fp32 autograd reference, plus odd q/k/v splits, 1 and 2 channels per thread, and CUDA-graph capture and replay: 46/46 pass on MI350X (gfx950, flydsl 0.5.3) at794546a, with the tolerances of4faa6bc. The Triton test passed 42/42 at4faa6bc.Preliminary performance of
794546a, one short run on one idle MI350X (RotatingBufferBench, CUDA graph, 200 calls per graph, 5 replays), Triton and FlyDSL in the same run, us:21100d0794546aPending: a formal two-round A/B against Triton
21100d0and FlyDSL4faa6bc, the torch eager comparison, a final config sweep, and the error of the fast sigmoid against the fp32 reference for FlyDSL and Triton. The formal numbers of the first FlyDSL version follow.4faa6bc(first FlyDSL version, unrolled loop) against Triton on one idle MI350X,bench_causal_conv1d_bwd.pymethod (RotatingBufferBench, CUDA graph), two alternating rounds, means in us (the rounds differ by less than 1%). The torch column is the eagertorch.autograd.gradbackward described under Performance, timed with eager launches, where FlyDSL and Triton take the times in parentheses.21100d04faa6bc4faa6bcmatched Triton on the TP8 short-sequence cases and was 13-24% slower on the larger ones: its unrolled token loop needed 164 VGPRs atblock_m32 and 294 with 146 SGPR spills atblock_m64, and each row spent most of its ~325 instructions on the IEEE exp expansion, an IEEE divide and 64-bit position compares.794546aaddresses all three.Performance (if applicable)
Measured on one idle MI350X (gfx950) in a ROCm 7.2.4 container (torch 2.10.0, triton 3.6.0). Lumen issue #35 gives no performance target for this op.
bench_causal_conv1d_bwd.py(RotatingBufferBench, CUDA graph). Before is the first version of this PR (cf3f8fd, one tile per program that recomputes the pre-activation for every tap), after is0db0348. Two rounds, before and after alternating on the same GPU; the table gives the mean of the two rounds, which differ by less than 1%. TB/s counts x and the output gradient read once and dx written once.The review fixes in
21100d0(int64 channel offsets, NaN-safe padded sequences, tail dx fill) were timed the same way against0db0348: every case is within 0.5% (two alternating rounds, means in us):Bandwidth context: at the TP8 1 x 8192 size (75 MB per tensor), torch itself reaches 2.74 TB/s for a read-read-write elementwise op and 3.05 TB/s for a contiguous copy on this GPU (
triton.testing.do_bench); the main kernel of this op runs at about 2.66 TB/s there, and at about 4.0 TB/s on the larger cases, where the torch copies reach 4.1-4.3 TB/s. Splitting each chunk into 2-4 token segments that advance together made the TP8 1 x 8192 case 3-4% faster but the TP1 1 x 8192 and TP8 1 x 32768 cases about 1% slower, so it is not used.Against torch, on the same GPU, at
21100d0, with eager launches timed by CUDA events over 4 rotating inputs (not CUDA graphs, so these numbers differ from the tables above). The torch reference is a bf16 depthwiseF.conv1d(groups=dim, causal padding) plus SiLU. "torch backward" istorch.autograd.gradfor x and the weight with the forward already done. "torch wgrad only" isaten.convolution_backwardwith only the weight gradient. The varlen case is left out: torch needs a loop over the sequences.Testing
Documentation
Dependencies
Breaking Changes
None.
PR Self-Review
Reviewed revision
0db0348
Behavior and intent
This PR adds a new op and changes no existing behavior. Before this PR, AITER had only the forward and the decode update of the causal conv1d. A training step of Kimi-K3 KDA cannot get the gradients of the q, k and v short convs (depthwise weight
[12288, 1, 4]each, Lumen issue #35). Lumen must use a slow eager path for them. The newcausal_conv1d_split_qkv_bwd_triton_fngivesdx,dweight,dbiasanddinitial_statesin one launch, in the[Q | K | V]layout of the forward. The existing forward, update and prefill paths, and their configs, do not change.Validation and unverified scope
Done on MI350X (gfx950), ROCm 7.2.4 container with torch 2.10.0 and triton 3.6.0:
test_causal_conv1d_bwd.pypass at21100d0, including the Kimi-K3 TP8 long sequences and the TP1 cases (12288 channels per tensor). The tests added for the three review findings fail on0db0348: NaN indxwith NaN in padded sequences, nonzero taildxwith a reusednums_dict, and a GPU memory fault that aborts the process with the large channel stride.0db0348passed its 40 tests, and the first version (cf3f8fd) its 39, on the same GPU.bench_causal_conv1d_bwd.pybefore and after, a config sweep for the gfx950 config, and a torch autograd comparison (see Performance).ruff check(0.16.0) andblack --check(26.10.1) pass on the changed files.Not verified:
PR-specific question
Q: Which exact workload keys consume these configuration changes, and what evidence shows that unrelated shapes keep their previous selection?
A: The only config change is the new file
aiter/ops/triton/configs/gfx950/triton/conv/causal_conv1d_split_qkv_bwd/DEFAULT.json, familyCAUSAL_CONV1D_SPLIT_QKV_BWD. It has one key,"any". Only_bwd_config()in the newaiter/ops/triton/gated_delta_net/causal_conv1d_bwd.pyreads it, so only calls ofcausal_conv1d_split_qkv_bwd_triton_fnon gfx950 use it. No existing config file changes (git diff --stat origin/mainshows the new file only), and no other loader reads this family name (grep -rn CAUSAL_CONV1D_SPLIT_QKV_BWD aiter/finds only the new wrapper). So every existing shape keeps its previous selection. The forward familyCAUSAL_CONV1D_SPLIT_QKVis a different directory and does not change.Changed op tests
op_tests/triton_tests/gated_delta_net/test_causal_conv1d_bwd.py(new): comparesdx,dweight,dbiasanddinitial_stateswith an fp32 autograd reference. It covers Kimi-K3 TP8 (1536 channels per tensor, x row stride 6288 or 4608) and TP1 (12288 channels per tensor), varlen batches, zero-length sequences, pad slots (also with NaN in the x and gradient rows of the padded sequences), initial states, widths 2/3/4, activations, bias, unaligned q/k/v splits, token-contiguous x and gradients (no unit channel stride), a token-contiguous x in a[36864, 65536]buffer whose channel offsets pass 2**31 (skipped with less than 8 GiB free), fp32, determinism and thenums_dictschedule (reused, with tail tokens and a NaN-poisoned allocator). No other test covers a causal conv1d backward.op_tests/op_benchmarks/triton/bench_causal_conv1d_bwd.py(new): timescausal_conv1d_split_qkv_bwd_triton_fnwith RotatingBufferBench (CUDA-graph replays over a rotating input pool) on Kimi-K3 cases: TP8 (1536 channels per tensor, x row stride 6288 or 4608, 1 x 8192, 2 x 4096, varlen 8 x ~2048, 1 x 32768) and TP1 (12288 channels per tensor, 1 x 4096 and 1 x 8192). It reports the time and the effective bandwidth. It does not check accuracy; the unit test does that. It shares the input generator_make_inputswith the unit test. No other benchmark covers a causal conv1d backward;bench_causal_conv1d_prefill.pytimes only the forward.