Skip to content

[Perf][FlyDSL] Add gdn_prepare: a fused intra-chunk GDN prefill prepare kernel - #4598

Merged
yiijin merged 8 commits into
ROCm:mainfrom
yiijin:gdn_prepare
Aug 14, 2026
Merged

yiijin merged 8 commits into
ROCm:mainfrom
yiijin:gdn_prepare

Conversation

@yiijin

@yiijin yiijin commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The GDN prefill prepare stage (cumsum, gated KKT, triangular inverse, WY w/u) runs as separate Triton kernels that hand off a ~256MB fp32 A_raw intermediate through HBM, which the next kernel immediately re-reads. On long-context shapes, the triangular inverse can also become a separate launch and account for ~44% of the stage's GPU time.

Fusing all four stages keeps the block-triangular matrix in registers/shared storage, removes the intermediate, and reduces launch overhead.

Technical Details

The K1–K6 labels below denote logical pipeline stages, not necessarily individual kernel launches:

  • K1 — gate cumsum: chunk_local_cumsum
  • K2 — gated KKT / A_raw construction: chunk_scaled_dot_kkt_fwd
  • K3 — triangular inverse: solve_tril
  • K4 — WY w/u recomputation: recompute_w_u_fwd
  • K5 — inter-chunk hidden-state recurrence: Triton, HIP, or FlyDSL chunk_gated_delta_rule_fwd_h*
  • K6 — final chunk output computation: chunk_fwd_o_opt_vk

The Triton vk path fuses K1+K2 and conditionally K3+K4. This PR fuses K1–K4 while leaving K5 and K6 unchanged.

  • Adds a fused FlyDSL kernel covering K1–K4 in one launch:
    • gate cumsum
    • gated KKT
    • triangular inverse
    • WY w/u
  • Computes the triangular inverse in-kernel through Neumann squaring.
  • Does not materialize the fp32 A_raw [B, T, H, BT] intermediate.
  • Built on the FlyDSL 0.3.0 API using MMA atoms, layout views, fx.Vector, and buffer descriptors.
  • Produces head-major w/u [B, H, T, K/V] and g_cumsum [B, H, T], matching the existing vk contract.
  • Controlled by use_prepare_flydsl, independently of the Triton, HIP, or FlyDSL hidden-state backend.
  • Supports bf16, K=V=128, BT=64, GQA (H % Hg == 0), dense input, packed varlen input, and decode-prefixed batches.
  • The pipeline falls back to the Triton prepare path for unsupported configurations. Direct wrapper calls validate and reject unsupported inputs.
  • Varlen launches use reusable host-resident prefill_metadata for the maximum per-sequence chunk count, avoiding per-forward device-to-host reads. Without a schedule, the pipeline warns and falls back to Triton.

Test Plan

Run the standardized correctness and performance sweep:

PYTHONPATH=. python3 op_tests/test_gdn_prepare.py

Post-rebase smoke command:

PYTHONPATH=. python3 op_tests/test_gdn_prepare.py \
  -b 1 \
  -s dense_tail \
  --pipeline-shapes dense_tail \
  --hidden-backends triton flydsl hip \
  --use-exp2 true false

The test covers:

  • Direct prepare_flydsl and prepare_triton candidates against an fp32 torch algebraic reference.
  • End-to-end pipeline comparison with Triton, FlyDSL, and HIP hidden-state backends.
  • Dense, non-aligned tail, packed varlen, GQA, and decode-prefix cases.
  • Both natural-log and exp2 prepare output domains.
  • Preallocated model-facing output buffers.
  • Output shape, dtype, contiguity, and final-state contracts.
  • Unsupported dtype/device/shape handling.
  • Missing-schedule warning and Triton fallback.
  • Scheduled varlen execution without host synchronization.
  • Markdown tables reporting us, TFLOPS, TB/s, and err for every candidate.

Test Result

Post-rebase validation on gfx942:

  • Direct prepare smoke: both exponent modes passed with err=0.
  • Pipeline smoke: Triton, FlyDSL, and HIP hidden-state backends passed with err=0.
  • Main-side conflict-resolution tests: 8 passed.
  • Ruff formatting, lint, Python syntax, and git diff --check passed.

The standardized test emits separate markdown summaries for:

  1. Direct prepare performance and correctness.
  2. End-to-end pipeline performance and correctness.

Implementations compared

Name What it is Path
triton ori Unfused reference chain, four kernels _triton_kernels/gated_delta_rule/utils/
triton vk / prepare_triton Current production prepare path selected by use_prepare_flydsl=False chunk_gated_delta_rule_opt_vk → chunk_gated_delta_rule_fwd_opt_vk
flydsl / prepare_flydsl This PR, one fused prepare kernel aiter/ops/flydsl/kernels/gdn_prepare.py
opus HIP gdn_chunk_prepare implementation from #4016 PR #4016

The two vk variants

fused_solve_tril_recompute_w_u selects between fusing K3+K4 and running them separately:

use_split = NT > 32

This is controlled by AITER_SOLVE_TRIL_RECOMPUTE_FUSE_NT_MAX and can be overridden with AITER_SOLVE_TRIL_RECOMPUTE_FORCE=fused|split.

With BT=64, the default crossover is T=2048.

Configuration T=2048, NT=32 T=4096, NT=64
Launches 2 3
K1+K2 10.1 us 16.3 us
K3 included in K3+K4 43.0 us
K4 included in K3+K4 27.4 us
Total prepare GPU time 47.9 us 86.7 us

In the split regime, the standalone triangular-inverse launch accounts for approximately 44–50% of the prepare-stage GPU time. The fused FlyDSL implementation removes that launch.

Performance

Across the measured dense, GQA, and varlen shapes on gfx942 and gfx950, the FlyDSL prepare kernel is 1.77–3.18x faster than the Triton vk path, with a 2.50x geometric-mean speedup.

gfx942

model H T ori vk flydsl fly/vk
35B-tp1 32 1024 184.2 135.8 61.0 2.23x
35B-tp1 32 2048 308.1 220.0 100.7 2.19x
35B-tp1 32 4096 549.5 452.0 187.8 2.41x
35B-tp1 32 8192 1065.2 865.2 360.4 2.40x
35B-tp1 32 16384 2286.2 1858.8 704.5 2.64x
35B-tp1 32 32768 4613.7 3753.3 1391.0 2.70x
35B-tp1 32 65536 9329.3 7515.7 2764.1 2.72x
35B-tp2 16 1024 110.3 74.0 41.9 1.77x
35B-tp2 16 8192 582.0 456.7 187.5 2.44x
35B-tp2 16 65536 4707.4 3743.2 1389.6 2.69x
FULL-tp1 64 1024 309.6 214.0 101.4 2.11x
FULL-tp1 64 8192 2349.2 1899.2 703.7 2.70x
FULL-tp1 64 65536 20110.3 15271.3 5508.2 2.77x

gfx950

model H T ori vk flydsl fly/vk
35B-tp1 32 1024 47.3 41.0 18.0 2.28x
35B-tp1 32 2048 64.1 51.7 25.1 2.06x
35B-tp1 32 4096 92.8 88.6 35.8 2.48x
35B-tp1 32 8192 186.4 176.3 66.1 2.67x
35B-tp1 32 16384 393.7 356.3 131.8 2.70x
35B-tp1 32 32768 781.7 723.2 266.8 2.71x
35B-tp1 32 65536 1656.7 1482.4 649.9 2.28x
35B-tp2 16 1024 40.0 34.5 14.9 2.32x
35B-tp2 16 8192 98.6 93.0 37.3 2.49x
35B-tp2 16 65536 717.1 713.1 262.7 2.71x
FULL-tp1 64 1024 63.0 52.6 24.5 2.14x
FULL-tp1 64 8192 372.7 366.0 125.0 2.93x
FULL-tp1 64 65536 3110.1 2897.8 1257.3 2.30x

GQA

Hg=16, H=32, K=V=128.

gfx942

B T vk flydsl Speedup
1 2560 284.1 120.8 2.35x
1 8192 866.1 359.4 2.41x
1 16384 1796.9 703.5 2.55x
1 32768 3651.5 1387.1 2.63x
4 8192 3505.2 1387.7 2.53x

gfx950

B T vk flydsl Speedup
1 2560 64.4 27.7 2.33x
1 8192 168.2 56.1 3.00x
1 16384 337.0 115.6 2.92x
1 32768 670.6 261.3 2.57x
4 8192 699.2 252.1 2.77x

Varlen

Packed varlen with cached prefill_metadata, Hg=16, H=32.

gfx942

seq_lens T vk flydsl Speedup
[128, 300, 600, 1024] 2052 251.3 107.9 2.33x
[512] * 8 4096 450.3 184.3 2.44x
[4096, 2048, 1024, 512, 256, 128] 8064 857.9 379.2 2.26x
[8192, 4096, 2048, 1024] 15360 1675.1 686.2 2.44x

gfx950

seq_lens T vk flydsl Speedup
[128, 300, 600, 1024] 2052 79.5 29.7 2.68x
[512] * 8 4096 99.8 31.4 3.18x
[4096, 2048, 1024, 512, 256, 128] 8064 180.4 63.3 2.85x
[8192, 4096, 2048, 1024] 15360 314.7 116.1 2.71x

Submission Checklist

@yiijin
yiijin requested review from a team and a lite review from Copilot August 6, 2026 07:00
@github-actions

github-actions Bot commented Aug 6, 2026

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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
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 4598 --add-label <label>

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.

Pull request overview

This PR adds an optional FlyDSL-backed fused “prepare” path for Gated-DeltaNet (GDN) prefill that combines K1..K4 (cumsum, gated KKT, triangular inverse, and WY w/u) into a single kernel, wiring it into the existing Triton “vk” pipeline behind a new use_prepare_flydsl flag and adding coverage for dense + varlen/GQA cases.

Changes:

  • Introduces a new fused FlyDSL kernel (gdn_prepare) plus a torch-facing host wrapper (gdn_prepare_fwd_flydsl) and support predicate (gdn_prepare_flydsl_supported).
  • Adds a new use_prepare_flydsl kwarg to the vk chunk GDR pipeline, with automatic fallback to Triton when unsupported.
  • Adds prepare_max_seq_chunks() to support rectangular varlen grids and adds new/expanded tests for the fused prepare path.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
op_tests/test_gated_delta_rule.py Adds end-to-end vk pipeline tests that compare use_prepare_flydsl on/off across dense + varlen/GQA and backend sweeps.
op_tests/flydsl_tests/test_flydsl_gdn_prepare.py New unit tests for the fused FlyDSL prepare kernel vs a PyTorch reference and vs Triton K1+K2.
aiter/ops/triton/gated_delta_net/gated_delta_rule.py Adds and forwards the use_prepare_flydsl kwarg to the vk implementation.
aiter/ops/triton/_triton_kernels/gated_delta_rule/utils/index.py Adds prepare_max_seq_chunks() helper (cached) for varlen grid sizing.
aiter/ops/triton/_triton_kernels/gated_delta_rule/utils/init.py Exports prepare_max_seq_chunks.
aiter/ops/triton/_triton_kernels/gated_delta_rule/prefill/chunk.py Implements the use_prepare_flydsl branch and fallback logic to call the fused FlyDSL wrapper.
aiter/ops/flydsl/linear_attention_prefill_kernels.py Adds host wrapper/support predicate for fused prepare, including varlen scheduling and anti-camping grid padding.
aiter/ops/flydsl/kernels/gdn_prepare.py Adds the new fused FlyDSL kernel implementation (K1..K4).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread op_tests/test_gated_delta_rule.py Resolved
@yiijin yiijin changed the title Gdn prepare [Perf][FlyDSL] Add gdn_prepare: a fused intra-chunk GDN prefill prepare kernel Aug 6, 2026
Comment thread aiter/ops/flydsl/kernels/gdn_prepare.py Resolved
Comment thread aiter/ops/flydsl/kernels/gdn_prepare.py Resolved
@yiijin
yiijin force-pushed the gdn_prepare branch 10 times, most recently from 8d5d96d to 0e6cf33 Compare August 12, 2026 01:59
@yiijin
yiijin force-pushed the gdn_prepare branch 2 times, most recently from f3c4725 to 27cbb6c Compare August 12, 2026 06:15
huizzhan pushed a commit that referenced this pull request Aug 12, 2026
The Triton prefill path runs cumsum+KKT and solve+recompute-w/u as two
kernels that hand off through an `A_raw [B, T, H, BT]` fp32 intermediate
(~256MB at production shapes), so the second kernel re-reads from HBM what
the first just wrote. Fusing the four stages keeps that block-triangular
matrix in registers/LDS and never materializes it, and does the triangular
inverse in-register via Neumann squaring, so the standalone
`merge_16x16_to_64x64_inverse` launch -- ~44-50% of the stage's GPU time on
the shapes where vk splits it out -- disappears entirely.

Selection sits behind `use_prepare_flydsl` (default off) and is independent
of the K5 choice: the kernel writes w/u head-major [B, H, T, K/V] and
g_cumsum head-major [B, H, T] in the same exponent domain as the Triton
pair, so the Triton, HIP, and FlyDSL hidden-state backends all consume it
unchanged. Requests outside the supported slice (bf16, K=V=128, BT=64,
CDNA, <2**31 flat elements) fall back to the Triton pair rather than
failing, and fp16 k/v are rejected explicitly because the kernel emits
bf16 w/u. GQA (`H % Hg == 0`) and varlen packed batches are supported.

Varlen needs the longest sequence's chunk count to size the rectangular
launch grid. That comes off the host-resident prefill schedule rather than
a device read of `cu_seqlens`, so `gdn_prepare_fwd_flydsl` refuses a varlen
batch without `prefill_metadata` and `chunk_gated_delta_rule_fwd_opt_vk`
warns and runs the Triton prepare pair when the caller supplies neither
`seq_lens_cpu` nor `prefill_metadata` -- no caller silently regresses and
the steady-state forward stays sync-free.

Squashed cherry-pick of #4598 (7 commits, f3c4725).

Co-authored-by: Cursor <[email protected]>
yiijin and others added 3 commits August 13, 2026 10:17
The Triton prefill path runs cumsum+KKT and solve+recompute-w/u as two
kernels that hand off through an `A_raw [B, T, H, BT]` fp32 intermediate
(~256MB at production shapes), so the second kernel re-reads from HBM what
the first just wrote. Fusing the four stages keeps that block-triangular
matrix in registers/LDS and never materializes it.

Selection sits behind `use_prepare_flydsl` (default off) and is independent
of the K5 choice: the kernel writes w/u head-major [B, H, T, K/V] and
g_cumsum head-major [B, H, T] in the same exponent domain as the Triton
pair, so the Triton, HIP, and FlyDSL hidden-state backends all consume it
unchanged. Requests outside the supported slice (bf16, K=V=128, CDNA) fall
back to the Triton pair rather than failing, and fp16 k/v are rejected
explicitly because the kernel emits bf16 w/u.

Varlen needs the longest sequence's chunk count to size the rectangular
launch grid, which `prepare_max_seq_chunks` derives from the already-cached
chunk offsets so the D2H happens once per shape instead of once per forward;
with `prefill_metadata` supplied the steady-state forward stays sync-free.

Co-authored-by: Cursor <[email protected]>
0.3.0 removes `expr.buffer_ops`, `expr.vector` and `utils.smem_allocator` from
the public surface, so the kernel now goes through the supported abstractions:
`fx.Vector` for vectors, layout views for LDS addressing, buffer-descriptor
`ptr_load`/`ptr_store` for globals, and MMA atoms plus `fx.gemm` in place of the
raw `mfma_f32_16x16x16bf16_1k` intrinsic. Numerics are unchanged and the MFMA
count is identical (120 `v_mfma`); total instructions drop 1810 -> 1701 and LDS
ops 311 -> 287, with VGPR 58 -> 64 keeping occupancy at 8 waves/SIMD.

Two `_LTensor` details are load-bearing rather than stylistic: a dynamic row
offset carries no divisibility, so a layout view is lowered at the value type's
natural alignment, which over-promises on a row stride that does not provide it.
Vector stores therefore narrow to the widest chunk the stride guarantees, and
the fp32 tile readers go element-wise; the backend re-fuses both. The accumulator
fragment fill also has to live in a helper, because in the kernel body the AST
rewriter turns those loops into `scf.for` and the dynamic element offsets then
stop `fly-promote-regmem-to-vectorssa` from lifting the fragments out of scratch.

Host side, the XCD count and the CDNA probe now key on the tensor's own device
ordinal instead of a hardcoded 0 behind a process-wide cache, so a non-default
device no longer reads device 0's properties. The support predicate additionally
rejects shapes at or above 2**31 flattened elements, which the launch ABI's C
`int` sizes cannot describe, so those fall back to the Triton pair instead of
failing in the struct packer.

Co-authored-by: Cursor <[email protected]>
… front

`gdn_prepare_flydsl_supported` checked the dtype and the head dim of both
operands but the device of only `k`, so a `v` on the host or on another card
was reported as supported. `chunk.py` selects the fused path off that predicate
alone, so the mismatch surfaced inside the launch rather than as a fallback to
the Triton pair.

The wrapper now gates on the predicate itself instead of restating it: reaching
`compile_gdn_prepare` with an unsupported head dim or a non-CDNA device raises a
hard assert, and reaching the launch with a cross-device operand faults, neither
of which tells a direct caller what to fix. The bf16 check stays ahead of the
gate so fp16 keeps its targeted message -- accepting it would hand K5 an `h`
derived from `k.dtype` and a `v_new` derived from bf16 `u`, i.e. mixed precision
in K6 instead of an error.

The sync-debug-mode test also restores the mode it found rather than assuming it
started at "default", so it no longer clobbers a caller's setting.

Co-authored-by: Cursor <[email protected]>
yiijin and others added 5 commits August 13, 2026 10:18
Use native tiled-copy and fragment APIs to remove redundant wrappers while preserving the kernel's synchronization and layout contracts.

Co-authored-by: Cursor <[email protected]>
`psf/black@stable` formats the whole tree, and gdn_prepare.py was the only file
out of 991 it would reformat, so the previous commit turned the style check red.
Reformatting it is the fix.

The wraps around compile-time constants go along with it. `_try_coerce_rhs`
already accepts Python ints and floats and `from_python_value` maps anything in
the i32 range to `Int32`, so `lane % fx.Int32(16)` and `lane % 16` build the same
expression -- including where the constant reaches a layout stride, which the
compiler was already folding. The file had been inconsistent about this:
`_load_fp32_tile` was called both with bare tile offsets and with wrapped ones
for the same parameter. What stays wrapped is the casts that introduce a type
from a raw value (`gpu.thread_id`, `gpu.block_id`, `rocdl.exp2`, the two varlen
fragment reads) plus `zero_f`.

The final ISA is byte-identical and `w`/`u`/`g_cumsum` are bitwise unchanged,
compared against the tree as it stood before either change.

Co-authored-by: Cursor <[email protected]>
The fused prepare sizes its rectangular launch grid by the longest sequence's
chunk count. Deriving that from the device `cu_seqlens` costs a device-to-host
read, and `prepare_max_seq_chunks` only amortized it per shape rather than
removing it, so a batch whose shape had not been seen yet still blocked once
per layer per forward. Take the count off the host-resident prefill schedule
instead and drop that helper: `gdn_prepare_fwd_flydsl` refuses a varlen batch
without `prefill_metadata`, and `chunk_gated_delta_rule_fwd_opt_vk` warns and
runs the Triton prepare pair when the caller supplies neither `seq_lens_cpu`
nor `prefill_metadata`, so no caller silently regresses. That warning sits
behind the support predicate, so it only fires when the schedule is the one
thing missing rather than shadowing an unsupported dtype or head dim.

Drop the XCD abstraction from the anti-camping grid padding. What the padding
needs is an odd `grid_x`, which `_pad_grid_x_odd` says directly without
exposing a die count, and the arch check now goes through the repo's
`chip_info.get_gfx_runtime` instead of parsing `gcnArchName` by hand.

Name the pipeline stages after the kernels that implement them rather than
K1..K6, and trim the comments this PR added that restated the code or pinned
down hardware details.

Trim the prepare tests from 33 cases to 22. `use_exp2` only rescales g_cumsum
by log2(e) and leaves w/u bit-identical, so the natlog variant rides on the
varlen case instead of doubling the shape sweep, and the dense shapes the unit
tests already check against both oracles are no longer repeated end to end.
The new precondition is covered on both sides: the wrapper raises, and the
`opt_vk` entry point warns and still matches the Triton result.

Co-authored-by: Cursor <[email protected]>
Only promote the missing-schedule warning so unrelated Triton deprecation warnings do not fail the prepare fallback test.

Co-authored-by: Cursor <[email protected]>
Move prepare and pipeline coverage into a top-level benchmark with consistent correctness and performance reporting.

Co-authored-by: Cursor <[email protected]>
@yiijin
yiijin merged commit cd8e5f8 into ROCm:main Aug 14, 2026
58 of 59 checks passed
huizzhan added a commit that referenced this pull request Aug 25, 2026
The prepare kernel itself reached mainline through #4598 and was
stabilized by #4952, so this branch keeps only the test coverage those
PRs did not carry over: the standalone unit tests and the end-to-end
use_prepare_flydsl cases.

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants