Repository navigation
[Triton/Gluon] Optimize gfx1250 KDA decode with cached launch and packed write-back - #7916
Liang-jianhao97 wants to merge 10 commits into
Conversation
Select a JSON write-back config for supported BF16 paged decode with FP32 state. Reuse the existing recurrence and add a short launch entry with an exact specialization cache, current-stream launches and hook fallback. Use a 4D register layout, clause-free b64 whole-line state stores, staged output and spread chunks. Keep full gating, normalization and state math. Keep slot zero valid and skip negative slots, including multi-token stores. Validation on d07 B0: 27 new public API tests passed; selected existing regressions plus the new tests passed 69 with 12 expected dtype skips. Black, Ruff, compileall and diff checks passed. RotatingBufferBench pool1 and pool16 smoke tests passed. Standard direct-public-call do_bench measured 9.574/14.823 us versus main 37.416/37.656 us, geometric mean 3.151x.
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
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 |
Accept gfx1250-strict in the write-back selector and KDA test markers. Use the gfx1250 configuration tree for both compiler targets, including the test config fixture. Keep the native compiler target unchanged. Validation on g21-10: 27 write-back tests and 66 selected existing KDA tests passed, with 12 expected BF16-state skips. Black, Ruff and diff checks passed. RotatingBufferBench pool1 and pool16 smoke tests passed. Two direct public-call do_bench runs measured 14.82-14.86 us fixed and 14.90-14.94 us with 16 rotating states. The main control uses the same strict config-path correction; geometric-mean speedup was 2.18-2.22x.
There was a problem hiding this comment.
🟡 Changes recommended
The multi-token fallback can read a padding slot and write outside the state tensor, while cached dispatch ignores the disable flag and INFO logging rejects supported strided indices.
3 open issues
What changed in this PR
This PR optimizes gfx1250 paged KDA decode within the existing public API. It adds cached launches and packed state write-back for supported BF16 inputs with FP32 state.
Changes:
- Add write-back dispatch, JSON tuning, and a compiled-launch cache.
- Optimize state and output access with a 4D register layout and packed stores.
- Add correctness tests and fixed/rotating-state benchmarks.
| File | Description |
|---|---|
op_tests/triton_tests/attention/test_kda.py |
Enable existing regressions for gfx1250-strict. |
op_tests/triton_tests/attention/test_kda_writeback.py |
Test write-back results, cached launches, and fallback cases. |
op_tests/op_benchmarks/triton/bench_kda_writeback.py |
Compare generic and write-back paths with rotating buffers. |
aiter/ops/triton/configs/gfx1250/gluon/attention/kda_decode/DEFAULT.json |
Add the write-back tuning bucket. |
aiter/ops/triton/attention/kda.py |
Integrate write-back selection into the public wrapper. |
aiter/ops/triton/attention/kda_writeback.py |
Add input checks and cached host launches. |
aiter/ops/triton/_gluon_kernels/gfx1250/attention/kda_decode.py |
Implement optimized write-back and recurrence fallback. |
Review effort: Balanced
| # Reuse the general recurrence when a sequence has multiple tokens. | ||
| fused_recurrent_kda_packed_decode_kernel( |
There was a problem hiding this comment.
Fixed in fad165e. The one-token path now returns None unless every sequence length is 0 or 1 (_one_token_sequences in kda_one_token.py). Flat indices with length > 1 never reach the one-token kernel. The generic packed kernel handles them with its existing index handling. test_longer_flat_sequence_is_not_one_token covers the cu_seqlens=[0,0,2,3] case from this thread.
| if ( | ||
| _ARCH in ("gfx1250", "gfx1250-strict") | ||
| and config is None | ||
| and not _LOG_INFO |
There was a problem hiding this comment.
Partly addressed. The one-token path accepts flat indices with stride(0) != 1 and passes the stride to the kernel (stride_indices_seq). test_one_token_cached_launch_strides_and_sizes covers stride 2. I did not change the generic path: it keeps its existing requirement of dense indices (ssm_state_indices.stride(-1) == 1). Strided indices that do not fit the one-token path still fail there, as before.
| storages = [x.untyped_storage() if x is not None else None for x in tensors] | ||
| if out is not None: | ||
| optr = storages[7].data_ptr() | ||
| if any(s.data_ptr() == optr for s in storages[:7] + storages[8:]): | ||
| return None | ||
| else: | ||
| out = tensors[7] = torch.empty_like(v) | ||
| storages[7] = out.untyped_storage() | ||
| global _launcher | ||
| if _launcher is None: | ||
| _launcher = _WritebackLauncher() | ||
| _launcher.launch(tensors, storages) |
There was a problem hiding this comment.
Fixed in fad165e. _config checks the flag before the cache: explicit overrides with use_one_token_decode false return None, and load_one_token_config returns None when the bucket flag is false, so the cached default is never used in that case. I have not added a unit test for the flag-off path yet; the benchmark exercises it.
The fast path is selected only for length-0/1 sequences, and longer sequences stay on the generic kernel. Co-authored-by: Cursor <[email protected]>
The length check uses itertools.pairwise, which is what ruff 0.16.0 reports on this PR. Co-authored-by: Cursor <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
…slots. Ordinary gfx1250 decode still uses the one-token kernel. A state fork or speculative verify can load one slot and store another, including slot 0 and negative slots, without clobbering the checkpoint. Co-authored-by: Cursor <[email protected]>
…chmark. Move ssm_state_indices_in in try_kda_one_token_decode to a keyword-only argument so existing positional callers that pass out keep working. Fix a nested-if lint issue in fused_recurrent_kda, format the new test, and add bench_kda_atom.py comparing one-token, generic, and the ATOM entry (same slots, split tensors, state fork) on gfx1250. Co-authored-by: Cursor <[email protected]>
Fold the separate one-token and ATOM benches into bench_kda's shape and metric table, including a state-fork column that reads a disjoint slot. Co-authored-by: Cursor <[email protected]>
With inplace_final_state=False, ATOM keeps the state after each token at that token's index in a new [T, HV, V, K] tensor. The entry now allocates this tensor and passes it to fused_recurrent_kda as state_out. Before, the paged path raised a ValueError. Kimi-K3 passes beta as a view into the fused in_proj row. The kernels read beta with its token stride, so the entry no longer copies a beta whose last dimension has unit stride.
ATOM's KDA gating entry now comes with the gating kernel in its own PR and no longer runs through fused_recurrent_kda. Drop kda_atom.py and its test, the separate read and write slot tables, the ATOM slot rules in the packed kernel and the split-index one-token path. kda_decode.py, kda.py and kda_one_token.py are back to bb3b586. bench_kda keeps the one_token and generic backends. --timing rotating replays a CUDA graph over a RotatingBufferBench pool, so each call reads a cold state as in a decode step.
|
No activity for 15 days, so this is now labelled |
…7916 @ 7e2f22e, head 2026-11-16T05:44:05Z) Applied as the diff 8bbce0d..7e2f22e (8 files) onto the rebased 1116 tree; PR state: open, author Liang-jianhao97, base main. (cherry picked from commit becedb0) Rebase onto main 12-03: main #8061 moved fast_launch from _triton_kernels/kimi_delta_attn/ to utils/fast_launch.py and already takes the ordinary path while a launch hook is set (this PR's _launch_hooks_idle). The old file stays deleted; this PR's other fast_launch change, falling back to the ordinary launch when CompiledKernel.run raises TypeError (launcher ABI changed), is ported into utils/fast_launch.py as a per-wrapper disable. kda_one_token.py and test_kda_one_token.py import utils.fast_launch. bench_kda.py keeps main's gating / recurrent case backends (#7990) and adds this PR's one_token / generic backends, --padded, and a shape check per family; --timing rotating takes both families.


Summary
Add a one-token gfx1250 decode path for paged KDA. It uses a cached launch through the shared
fast_launchhelper, a 4D register layout, packed whole-line state stores, and LDS-staged output. Full gating, q/k normalization, FP32 state updates, and the public API are unchanged.Motivation
The public interface adds host dispatch overhead for small decode workloads, and the existing state and output access patterns leave performance on gfx1250 unused for the single-token case. This change targets that case. Longer sequences keep using the existing packed kernel.
Changes
kda_one_token.py, which dispatches to a one-token kernel only when every sequence length is 0 or 1. Any other sequence length returnsNoneand the call uses the generic packed kernel.one_tokenbucket inDEFAULT.jsonviause_one_token_decode.config=Noneenables it for supported gfx1250 inputs. An explicitconfigkeeps the generic path unless it setsuse_one_token_decode.fast_launchhelper:compiled.runraisesTypeError(Triton ABI mismatch), disable the cached path for the process and fall back to ordinary JIT.gl.storewhengl.inline_asmis unavailable.cu_seqlenson the host, which synchronizes the device. During CUDA graph capture this check is skipped, so captured batches must already have sequence lengths of 0 or 1.sigmoid()as the generic kernel.lower_bound * log2(e) / 2is a compile-time constant.Performance
Hardware: gfx1250
Software: PyTorch 2.11.0+rocm (HIP 7.16)
Workload: M=72, H=HV=12, K=V=128, BF16 q/k/v/g/beta, FP32 V-first state, int32 paged indices, in-place state updates, fused q/k normalization and gate/beta sigmoid,
lower_bound=-5, default scale. Tuned configuration: BV=32, CH=16, SK=16, two warps, one buffer.Public-interface timing (
triton.do_bench, L2 invalidated before each sample)These numbers include public-interface host dispatch overhead. They are not isolated GPU-kernel or model-throughput measurements.
CUDA graph replay (
RotatingBufferBench, no cache invalidation)Graph replay times exclude host dispatch. Use these to compare the generic and one-token kernels against each other, not against the table above.
A cross-architecture comparison against gfx950 is intentionally omitted here. The workload and software stack differ, so a single ratio would overstate what this change does.
One-token vs generic kernel by batch size (H = 12, cold state)
CUDA graph replay of the public
fused_recurrent_kdafor ordinary decode (T = 1, in place, one slot table) on gfx1250, in therocm/fw-bringup-mlperf:gfx1250-atom-20261106-dsv41container. RotatingBufferBench rotates through input sets that span at least 196 MB (its gfx1250 default), so each call reads a state that is not in cache, as in a decode step where the other layers run between two calls of one layer. Median of 3 runs x 5 replays. M is the number of sequences. The generic column passesconfig={"use_one_token_decode": False}. Measured withbench_kda.py --timing rotating, added in #7990, which does not change these two kernels.Testing
Validated on gfx1250 with
pytest:op_tests/triton_tests/attention/test_kda_one_token.py: 29 passedop_tests/triton_tests/attention/test_kda.pyandop_tests/triton_tests/kimi_delta_attn/test_fast_launch.py: 265 passed, 31 skippedop_tests/triton_tests/kimi_delta_attn/test_flash_kda.pyandop_tests/triton_tests/attention/test_kda.py: 337 passed, 36 skippedSkip reasons: no published K2 candidates; gfx950-only K1 schedule and pass C; bf16 state requires gfx950.
Black and Ruff were not run for this revision. Python compilation and
git diff --checkpass.Unverified: MI250X, MI300X, other software stacks, and end-to-end model throughput.
Documentation
The public wrapper docstring describes the one-token path, the
configsemantics, and the generic fallback. The public function signature is unchanged. No user-guide or performance-guide changes are included, because the performance results are specific to the tested workload.Dependencies
Breaking Changes
None. The public function signature is unchanged. Unsupported inputs use the generic path, and explicit configurations keep control of path selection.
Reviewed revision
bb3b586
Behavior and intent
Supported gfx1250 decode calls with every sequence length equal to 0 or 1 were paying repeated host dispatch and using scalar state and output access. The public wrapper now selects the one-token kernel for that case. Longer sequences stay on the existing packed kernel, whose configuration buckets are unchanged.
Configuration keys
The only new JSON key is
one_tokeninaiter/ops/triton/configs/gfx1250/gluon/attention/kda_decode/DEFAULT.json.load_one_token_configis the only reader.get_kda_configstill selectsfused,t_gt1_seq_heads_geq_3072,t_gt1_seq_heads_geq_384,t_gt1_default,t1_seq_heads_256_to_512, anddefaultfromavg_T, sequence count,HV,K,V, and the fused flag. Those bucket contents are unchanged. A call that fails the one-token predicate returnsNonebefore that bucket is used, so other shapes keep the previous selection.test_longer_sequence_uses_generic_recurrenceandtest_one_token_fallbackcover that boundary.Validation and unverified scope
On gfx1250, PyTorch 2.11.0+rocm, HIP 7.16:
pytest op_tests/triton_tests/attention/test_kda_one_token.py -q: 29 passedpytest op_tests/triton_tests/attention/test_kda.py op_tests/triton_tests/kimi_delta_attn/test_fast_launch.py -q: 265 passed, 31 skippedpytest op_tests/triton_tests/kimi_delta_attn/test_flash_kda.py op_tests/triton_tests/attention/test_kda.py -q: 337 passed, 36 skippedSkip reasons: no published K2 candidates; gfx950-only K1 schedule and pass C; bf16 state requires gfx950.
black==26.3.0 --checkandruff==0.16.0 checkpass on the changed Python files.git diff --checkpasses.Unverified: MI250X, MI300X, other software stacks, and end-to-end model throughput. The
fast_launchTypeError fallback has no direct unit test.PR-specific question
During CUDA graph capture the host cannot read
cu_seqlens, so the one-token length check is skipped and captured batches are assumed to have sequence lengths of 0 or 1. Is this contract acceptable for ATOM decode graphs, or should capture require an explicit caller flag?Changed op tests
op_tests/triton_tests/attention/test_kda_one_token.py: Checks the one-token path against an independent reference and asserts that the public wrapper selects it. Existing KDA tests compare against a generic reference and do not prove which kernel ran, so they do not cover cache reuse, current-stream launch, launch hooks, state offsets above 4 GiB, the flat-index length check, or the missing-inline_asmfallback.op_tests/triton_tests/attention/test_kda.py: Addsgfx1250-strictto the arch skip marks and resolves configs witharch="gfx1250"under strict mode. Without this, the existing suite does not run on the native strict target. The assertions themselves are unchanged.op_tests/op_benchmarks/triton/bench_kda_one_token.py: Compares generic and one-token decode through the public interface withRotatingBufferBench. No existing benchmark launches this kernel or reports the two pool sizes.