Repository navigation
[Perf][FlyDSL] Add gdn_prepare: a fused intra-chunk GDN prefill prepare kernel - #4598
Merged
Merged
Conversation
Contributor
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
|
Contributor
There was a problem hiding this comment.
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_flydslkwarg 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.
huizzhan
reviewed
Aug 6, 2026
huizzhan
reviewed
Aug 6, 2026
yiijin
force-pushed
the
gdn_prepare
branch
10 times, most recently
from
August 12, 2026 01:59
8d5d96d to
0e6cf33
Compare
yiijin
requested review from
Dewei-Wang-sh,
azaidy and
vgokhale
as code owners
August 12, 2026 01:59
yiijin
force-pushed
the
gdn_prepare
branch
2 times, most recently
from
August 12, 2026 06:15
f3c4725 to
27cbb6c
Compare
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]>
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]>
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]>
coderfeli
approved these changes
Aug 13, 2026
1 task done
1 task
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]>
3 of 4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_rawintermediate 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–K6labels below denote logical pipeline stages, not necessarily individual kernel launches:chunk_local_cumsumA_rawconstruction:chunk_scaled_dot_kkt_fwdsolve_trilw/urecomputation:recompute_w_u_fwdchunk_gated_delta_rule_fwd_h*chunk_fwd_o_opt_vkThe Triton vk path fuses K1+K2 and conditionally K3+K4. This PR fuses K1–K4 while leaving K5 and K6 unchanged.
w/uA_raw [B, T, H, BT]intermediate.fx.Vector, and buffer descriptors.w/u [B, H, T, K/V]andg_cumsum [B, H, T], matching the existing vk contract.use_prepare_flydsl, independently of the Triton, HIP, or FlyDSL hidden-state backend.K=V=128,BT=64, GQA (H % Hg == 0), dense input, packed varlen input, and decode-prefixed batches.prefill_metadatafor 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:
Post-rebase smoke command:
The test covers:
prepare_flydslandprepare_tritoncandidates against an fp32 torch algebraic reference.exp2prepare output domains.us,TFLOPS,TB/s, anderrfor every candidate.Test Result
Post-rebase validation on gfx942:
err=0.err=0.8 passed.git diff --checkpassed.The standardized test emits separate markdown summaries for:
Implementations compared
_triton_kernels/gated_delta_rule/utils/use_prepare_flydsl=Falsechunk_gated_delta_rule_opt_vk→chunk_gated_delta_rule_fwd_opt_vkaiter/ops/flydsl/kernels/gdn_prepare.pygdn_chunk_prepareimplementation from #4016The two vk variants
fused_solve_tril_recompute_w_uselects between fusing K3+K4 and running them separately:This is controlled by
AITER_SOLVE_TRIL_RECOMPUTE_FUSE_NT_MAXand can be overridden withAITER_SOLVE_TRIL_RECOMPUTE_FORCE=fused|split.With
BT=64, the default crossover isT=2048.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
gfx950
GQA
Hg=16,H=32,K=V=128.gfx942
gfx950
Varlen
Packed varlen with cached
prefill_metadata,Hg=16,H=32.gfx942
[128, 300, 600, 1024][512] * 8[4096, 2048, 1024, 512, 256, 128][8192, 4096, 2048, 1024]gfx950
[128, 300, 600, 1024][512] * 8[4096, 2048, 1024, 512, 256, 128][8192, 4096, 2048, 1024]Submission Checklist