Skip to content

[Triton/Gluon] Optimize gfx1250 KDA decode with cached launch and packed write-back - #7916

Open
Liang-jianhao97 wants to merge 10 commits into
mainfrom
feat/gfx1250-kda-packed-writeback
Open

Liang-jianhao97 wants to merge 10 commits into
mainfrom
feat/gfx1250-kda-packed-writeback

Conversation

@Liang-jianhao97

@Liang-jianhao97 Liang-jianhao97 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add a one-token gfx1250 decode path for paged KDA. It uses a cached launch through the shared fast_launch helper, 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

  • Add kda_one_token.py, which dispatches to a one-token kernel only when every sequence length is 0 or 1. Any other sequence length returns None and the call uses the generic packed kernel.
  • Select the one-token configuration from the one_token bucket in DEFAULT.json via use_one_token_decode. config=None enables it for supported gfx1250 inputs. An explicit config keeps the generic path unless it sets use_one_token_decode.
  • Launch through the shared fast_launch helper:
    • Cache compiled launches by integer and non-tensor argument values, tensor dtype, 16-byte alignment, and storage size.
    • Use the current stream on every launch.
    • Use ordinary JIT while launch hooks are registered.
    • If compiled.run raises TypeError (Triton ABI mismatch), disable the cached path for the process and fall back to ordinary JIT.
    • This helper is also used by flash_kda and the gfx1250 K1/K2 kernels, so these behaviors apply there too.
  • Use a 4D register layout for b64 state loads and b32 token loads.
  • Store state with clause-free b64 whole-line stores and the required operand waits. Fall back to gl.store when gl.inline_asm is unavailable.
  • Stage output in LDS, mask replicated output-store lanes, and spread each program's chunks across the head's rows.
  • On the eager path, the one-token check reads cu_seqlens on 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.
  • Empty sequences and negative slots produce no store. Slot zero is a valid slot.
  • Sigmoid for the one-token path uses the same tanh-based sigmoid() as the generic kernel. lower_bound * log2(e) / 2 is 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.

Hardware Workload Before After Bandwidth(After) Change
gfx1250 M72 decode, fixed state 16.416 µs 9.574 μs 12 TB/s 1.68x
gfx1250 M72 decode, 16 rotating states 24.656 µs 14.823 μs 8TB/s 1.7x

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.

State pool Generic packed kernel One-token kernel Speedup
1 (fixed state) 16.69 µs 5.81 µs 2.87×
16 (rotating states) 16.74 µs 11.94 µs 1.40×

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_kda for ordinary decode (T = 1, in place, one slot table) on gfx1250, in the rocm/fw-bringup-mlperf:gfx1250-atom-20261106-dsv41 container. 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 passes config={"use_one_token_decode": False}. Measured with bench_kda.py --timing rotating, added in #7990, which does not change these two kernels.

M Generic packed kernel One-token kernel Speedup
1 2.64 µs 2.32 µs 1.14x
16 5.41 µs 4.43 µs 1.22x
72 16.69 µs 11.69 µs 1.43x
256 48.95 µs 32.16 µs 1.52x

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

Validated on gfx1250 with pytest:

  • op_tests/triton_tests/attention/test_kda_one_token.py: 29 passed
  • op_tests/triton_tests/attention/test_kda.py and op_tests/triton_tests/kimi_delta_attn/test_fast_launch.py: 265 passed, 31 skipped
  • op_tests/triton_tests/kimi_delta_attn/test_flash_kda.py and op_tests/triton_tests/attention/test_kda.py: 337 passed, 36 skipped

Skip 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 --check pass.

Unverified: MI250X, MI300X, other software stacks, and end-to-end model throughput.

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

The public wrapper docstring describes the one-token path, the config semantics, 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

  • No new third-party dependencies added
  • New dependencies are listed and justified below

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_token in aiter/ops/triton/configs/gfx1250/gluon/attention/kda_decode/DEFAULT.json. load_one_token_config is the only reader. get_kda_config still selects fused, t_gt1_seq_heads_geq_3072, t_gt1_seq_heads_geq_384, t_gt1_default, t1_seq_heads_256_to_512, and default from avg_T, sequence count, HV, K, V, and the fused flag. Those bucket contents are unchanged. A call that fails the one-token predicate returns None before that bucket is used, so other shapes keep the previous selection. test_longer_sequence_uses_generic_recurrence and test_one_token_fallback cover 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 passed
  • pytest op_tests/triton_tests/attention/test_kda.py op_tests/triton_tests/kimi_delta_attn/test_fast_launch.py -q: 265 passed, 31 skipped
  • pytest op_tests/triton_tests/kimi_delta_attn/test_flash_kda.py op_tests/triton_tests/attention/test_kda.py -q: 337 passed, 36 skipped

Skip reasons: no published K2 candidates; gfx950-only K1 schedule and pass C; bf16 state requires gfx950.

black==26.3.0 --check and ruff==0.16.0 check pass on the changed Python files. git diff --check passes.

Unverified: MI250X, MI300X, other software stacks, and end-to-end model throughput. The fast_launch TypeError 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_asm fallback.
  • op_tests/triton_tests/attention/test_kda.py: Adds gfx1250-strict to the arch skip marks and resolves configs with arch="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 with RotatingBufferBench. No existing benchmark launches this kernel or reports the two pool sizes.

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.
@Liang-jianhao97
Liang-jianhao97 requested a review from a team November 13, 2026 06:48
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 7916 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@github-actions github-actions Bot changed the title Optimize gfx1250 KDA decode with cached launch and packed write-back [Triton/Gluon] Optimize gfx1250 KDA decode with cached launch and packed write-back Nov 13, 2026
@aiter-bot

aiter-bot commented Nov 13, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 7e2f22ece089 · 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 — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — changed op test not explained in Changed op tests: op_tests/op_benchmarks/triton/bench_kda.py

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

codex and others added 2 commits November 13, 2026 15:09
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.

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

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

Comment on lines +1370 to +1371
# Reuse the general recurrence when a sequence has multiple tokens.
fused_recurrent_kda_packed_decode_kernel(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 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.

Comment thread aiter/ops/triton/attention/kda.py Outdated
if (
_ARCH in ("gfx1250", "gfx1250-strict")
and config is None
and not _LOG_INFO

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +163 to +174
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 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.

@zufayu
zufayu requested review from a team, Dewei-Wang-sh and vgokhale November 14, 2026 00:28
Liang-jianhao97 and others added 2 commits November 14, 2026 02:04
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]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 7916 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

Liang-jianhao97 and others added 3 commits November 14, 2026 08:48
…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.
@Liang-jianhao97
Liang-jianhao97 removed this pull request from stack #7991 November 16, 2026 07:18
@github-actions

github-actions Bot commented Dec 2, 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 2, 2026
gbyu-amd pushed a commit that referenced this pull request Dec 3, 2026
…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.

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