Repository navigation
[FlyDSL] [gfx950] Add gdn fused prefill kernel - #6496
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
There was a problem hiding this comment.
🟡 Changes recommended
Missing auxiliary-tensor device checks and tracking-index length validation can allow invalid GPU memory accesses.
2 open issues
What changed in this PR
Adds a fused FlyDSL Gated DeltaNet prefill path for gfx950, keeping recurrent state on chip to reduce kernel launches and intermediate memory traffic.
Changes:
- Adds a support gate, in-place state updates, and optional snapshots.
- Adds correctness checks and latency measurements.
- Renames the prefill kernel package and updates imports.
| File | Description |
|---|---|
op_tests/test_gdn_fused_prefill.py |
Adds reference checks and benchmarks. |
aiter/ops/triton/gated_delta_net/gated_delta_rule.py |
Changes a backend name in documentation only. |
aiter/ops/flydsl/linear_attention_prefill_kernels.py |
Updates kernel imports. |
aiter/ops/flydsl/kernels/gdn_prefill/gdn_prepare.py |
Relocates the prepare kernel. |
aiter/ops/flydsl/kernels/gdn_prefill/gdn_fused_prefill.py |
Implements fused prefill. |
aiter/ops/flydsl/kernels/gdn_prefill/chunk_gated_delta_h.py |
Relocates the hidden-state kernel. |
aiter/ops/flydsl/kernels/gdn_prefill/__init__.py |
Exports the fused compiler. |
aiter/ops/flydsl/gdn_fused_prefill.py |
Adds the public wrapper and support checks. |
aiter/aot/flydsl/chunk_gdn_h.py |
Updates the ahead-of-time compiler import. |
.claude/skills/review-pr/triage.py |
Updates a package name in a comment. |
Review effort: Balanced
NOT READY FOR HUMAN REVIEWPR 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 |
Why the existing behavior is insufficient. The existing prefill path (
Unverified / out of scope:
What behavior would each changed op test fail on before this PR, and why is that coverage not already provided by an existing canonical test?
None of this is covered by an existing canonical test:
Changed op tests
|
huizzhan
left a comment
There was a problem hiding this comment.
Thanks for the PR. Keeping the per-head state on chip across chunks and folding l2norm / prepare / h / o into a single launch is a nice design. I walked through the LDS write/read ordering across phases (double-buffered kbuf, p_s, fac, vt, ap, rhs/vn/vd/td) and did not find a WAR/RAW hazard; the tail-token masking (rq = rk = 0 driving the exp2 arguments to -inf) also looks NaN-safe. A few points I would like to see addressed before merge.
Major
1. Padding slots (cache_indices < 0) read and write slot 0, and race with each other.
slot = (slot < 0).select(0, slot) makes a padded sequence load slot 0, run the whole recurrence, and store the result back to slot 0. With two or more -1 entries in one batch, several workgroups read-modify-write slot 0 concurrently (nondeterministic). If the serving stack does not reserve slot 0 as a dummy slot, this also corrupts a real sequence's state. The test only uses a single -1, so it cannot catch this.
Suggestion: early-exit the workgroup when idx < 0 (no o write, no pool write), matching the usual PAD_SLOT_ID handling in FLA/vLLM. Alternatively, document that slot 0 must be reserved and add a test with multiple -1 entries.
2. No has_initial_state / zero-init path.
The kernel always loads the initial state from the pool, so callers must zero the slot of every new sequence with an extra launch, which is easy to forget. Please consider an optional per-sequence has_initial_state flag, or at least document this contract. The docstring should also state that cache_indices must be unique within a batch.
3. Occupancy / grid fill for small N * H; no comparison with the existing path.
By my count the LDS footprint is about 89 KB per WG (qk 52 KB, s 8.5 KB, ap 8.5 KB, rhs/vn/vd 12 KB, ...), so only 1 WG (2 waves/SIMD) fits per CU on gfx950. The grid is (VD / BV) * N * H = 4 * N * H, and chunks are serialized inside a WG:
- Qwen3.8 dense 4k (N=1, H=48): 192 WGs on 256 CUs.
- TP8 (H=8) single long sequence: 32 WGs.
The test prints us but does not compare against flydsl_gdr_prefill or the Triton path. Could you add same-GPU A/B numbers for the shapes in the test plus small-N*H / long-sequence cases? If the fused kernel loses there, gdn_fused_prefill_supported (or the caller) should gate on it. BV=16 (2x WGs) may also be worth trying for small grids.
4. Renaming kernels/gdr_prefill to kernels/gdn_prefill breaks external imports.
The in-repo references are updated, but downstream code importing aiter.ops.flydsl.kernels.gdr_prefill will fail with ModuleNotFoundError. Please either move the rename to a separate PR or keep a thin gdr_prefill/__init__.py shim that re-exports and emits a DeprecationWarning. Please also double-check that no other gdr_prefill references remain on main (op_tests, AOT lists, docs).
Minor
- No AOT entry. Given the amount of
range_constexprunrolling, the first JIT compile per(H, Hg, HAS_TRACK, scale)will happen inside the serving process. Anaiter/aot/flydsl/entry similar tochunk_gdn_h.pywould help. - Accuracy check is loose and global. A single rel-L2 < 2e-2 over all tokens (comment says ~4e-3 observed) can hide large errors on short sequences (1/63/65 tokens) or individual tokens. Suggest a per-sequence rel-L2 and/or a max-abs bound, plus a comparison against the existing multi-kernel FlyDSL path (the bf16 state copy feeding
k @ S^T/q @ S^Tmay drift on long sequences). Also,torch.stack([])raises if no sequence is tracked; it is not hit by the current shapes, but it is fragile. - Group 1 loads an unused copy of the state (
s_initis loaded by all 8 waves and carried as loop state). This doubles the pool read traffic and costs VGPRs. Could the load be restricted towh == 0? - The
_MAX_I32check does not cover theg/betaspans. It is harmless in practice, but cheap to add for consistency. - Buffer resources use the default
num_recordsfor q/k/v/g/beta/pool (views created withn=1); onlyosets it explicitly. A short comment, or explicit records everywhere, would make the bounds behavior clearer. - o rows outside
cu_seqlens[-1]are left uninitialized (new_empty). Worth a line in the docstring.
Nits
_exp,_sel, and thelaneargument of_wave_scanare unused.- Phase numbering jumps from 1 to 3.
- The module docstring's
oformula omitsscaleon the intra-chunk term; the code applies it viaF_EQ. _log2wrapsrocdl.log(v_log_f32is log2); a short comment would avoid confusion.- Commits 7 and 8 ("revert changes") cancel each other out; please squash on merge.
Note: this review is based on reading the diff only; I have not run the kernel.
huizzhan
left a comment
There was a problem hiding this comment.
Follow-up on point 3 of my earlier review (grid fill and the comparison with the existing path).
The latency table in the description covers Qwen3.8 (H=48, Hg=16) at 1x16K, 1x32K and one 7-sequence varlen batch. The GDN prefill shapes the repo already tracks for Qwen3.5 are much wider, and none of them have before/after numbers:
aiter/configs/model_configs/qwen3_5_397b_chunk_gdn_h_opt_untuned.csv: (H, Hg) = (64, 16), (32, 8), (16, 4), (8, 2), each withis_varlenFalse and True.aiter/configs/model_configs/qwen3_5_35b_chunk_gdn_h_opt_tuned.csv: (H, Hg) = (32, 16), (16, 8), (8, 4), (4, 2).- The matching tuned tables sweep
T_flatfrom 1024 to 65536 andNfrom 1 to 64.
Those tables were measured on gfx942 and only time the h stage, so they cannot be compared with the fused kernel directly. Could you add a same-GPU (gfx950) before/after table for these shapes, measured per layer end to end (fused vs chunk_gated_delta_rule_opt_vk with the best h backend)? Please include per-shape us, the speedup, and o / final-state rel_l2.
The cases I care most about are small N * H with long sequences, because the fused grid is 4 * N * H workgroups, at about 89 KB LDS each (1 WG per CU), and the chunks run serially inside a WG:
| H / Hg | N | T | Fused WGs (256 CUs) |
|---|---|---|---|
| 4 / 2 | 1 | 32K, 64K | 16 |
| 8 / 2, 8 / 4 | 1 | 16K, 32K, 64K | 32 |
| 16 / 4, 16 / 8 | 1 | 32K, 64K | 64 |
| 8 / 2 | 2, 4 | 16K, 32K | 64 to 128 |
Also please include one large N * H varlen point (e.g. H=64, N=16, T=32K) as a control.
If the fused kernel is slower than the existing path on some of these, it would help to state that in the description and gate on it, either in gdn_fused_prefill_supported or in a documented caller-side rule (for example a minimum N * H, or BV=16 for small grids). That way callers do not pick the fused path where it regresses.
Single-kernel FlyDSL Gated DeltaNet chunked prefill (BT=64) for gfx950: one launch covers q/k l2norm, the prepare stage, the hidden-state recurrence and the output, keeping each workgroup's state slice on chip and updating the bf16 state pool in place. - aiter/ops/flydsl/gdn_fused_prefill.py: gdn_fused_prefill_fwd and the gdn_fused_prefill_supported gate (operand checks; with max_seqlen it also rejects batches the multi-kernel path runs faster). Optional has_initial_state and track_state/track_chunk_idx; padded rows (cache_indices < 0) are skipped; BV picked from the grid size. - aiter/ops/flydsl/kernels/gdr_prefill/gdn_fused_prefill.py: the kernel. - aiter/aot/flydsl/gdn_fused_prefill.py: AOT entry (OpKind.GDN_FUSED_PREFILL) for every BV/track/init variant of the Qwen3.8 / Qwen3.5 head shapes. - op_tests/test_gdn_fused_prefill.py: per-sequence accuracy against an fp32 recurrence, padding/init/track contracts, and an A/B against chunk_gated_delta_rule_opt_vk. - op_tests/op_benchmarks/flydsl/bench_gdn_fused_prefill.py: fused vs opt_vk sweep over the Qwen3.5 tuned-table grid. Co-Authored-By: Claude <[email protected]>
e67372f to
64a09ed
Compare
Nits.
|
Measured on gfx950 (MI355X), one GDN layer, fused vs chunk_gated_delta_rule_opt_vk with the fastest h backend (Triton/FlyDSL/HIP) per shape. Shapes cover the Qwen3.5 tuned-table grid (177 points, equal-length varlen). Times are summed device time; speedup = opt_vk / fused. Reproduce with python -m op_tests.op_benchmarks.flydsl.bench_gdn_fused_prefill. Your focus cases ┌───────┬─────┬─────┬──────┬──────────┬───────────┬─────────┬────────┐ All 177 points, per head shape (routed = following the gate) ┌───────┬──────────────┬───────────────┬────────────────┐ As you expected, fused loses with small N·H and long sequences. gdn_fused_prefill_supported(..., max_seqlen=...) sends those shapes to opt_vk: for equal lengths the rule reduces to max_seqlen <= 1024 or N·H >= 24. Every shape it keeps on fused is faster (worst 1.10x). With routing, no shape regresses and the geomean is 1.33x, against 1.29x and a 0.59x worst case for always-fused. Accuracy: fused ≤ 3.4e-3 / 3.1e-3 (o / state rel-L2) vs opt_vk ≤ 5.0e-3 / 6.7e-3. |
huizzhan
left a comment
There was a problem hiding this comment.
Thanks for addressing the review feedback and providing the Qwen3.5 CSV-shape A/B results.
Please update the PR description to reflect the current implementation and the results already reported:
- API behavior: replace the outdated “negative cache indices map to slot 0” description with the new padding-skip behavior. Document
has_initial_stateand explain that callers must passmax_seqlento enable the performance gate. - Performance results: incorporate the follow-up benchmark summary and link the full 177-point results. Include the measured revision, hardware/software versions, and reproduction command. State the small-grid regressions, fallback rule, and routed speedup; distinguish summed device time from CUDA-event elapsed time and note the equal-length varlen coverage.
- Validation record: replace the remaining placeholders with actual results and complete the repository’s self-review sections for the current revision, including the new benchmark script and remaining unverified scope.
These description updates do not require additional code changes or rerunning the benchmarks already reported—just consolidate the existing evidence and clarify the caller contract.
Non-blocking follow-up: shape-aware kernel selection. The current heuristic is a useful conservative gate, but it does not necessarily select the fastest implementation for each shape. Consider extending it with an offline-tuned dispatch table that compares the fused BV=16/BV=32 variants and the opt_vk h backends, then selects the fastest correctness-validated candidate for each covered workload. The dispatch key should capture the relevant architecture/CU count, H/Hg, batch size, token count, sequence-length characteristics, and optional state/tracking modes. In particular, validate uneven varlen batches rather than relying only on equal-length results. Keep a safe fallback for unseen workloads and avoid benchmarking on the serving request path. This is a future optimization suggestion, not a requirement for merging this PR.
Updated, thank you |


Summary
Adds
gdn_fused_prefill_fwd, a single-kernel FlyDSL implementation of Gated DeltaNet (GDN) varlen chunked prefill for gfx950 Qwen3.8. This kernel covers q/k l2norm, the prepare stage, the hidden-state recurrence and the output, and it updates the bf16 state pool in place. The op is opt-in: no existing op changes behavior, and no in-tree dispatcher calls it yet.Motivation
The existing prefill path (
chunk_gated_delta_rule_opt_vk) takes 8 launches per layer (l2norm ×2, gdn_prepare, fwd_h, fwd_o and 3 elementwise ops). It also writes every per-chunk statehto HBM and reads it back for the output stage. For Qwen3.8-Flash-Next TP1 at 16K tokens, that is 1 launch / 797 µs instead of 8 launches / 1267–1299 µs (summed device time).Changes
aiter/ops/flydsl/gdn_fused_prefill.py(new):gdn_fused_prefill_fwdandgdn_fused_prefill_supported.aiter/ops/flydsl/kernels/gdr_prefill/gdn_fused_prefill.py(new): the kernel. It is exported from the existingkernels/gdr_prefillpackage, which is not renamed.aiter/aot/flydsl/gdn_fused_prefill.py(new), registered incommon.pyand listed in the README. It precompiles every BV / track /has_initial_statevariant for the Qwen3.8 and Qwen3.5 head shapes at TP1–8, defaultscaleonly.op_tests/test_gdn_fused_prefill.pyandop_tests/op_benchmarks/flydsl/bench_gdn_fused_prefill.py(new).Caller contract
cache_indices: one pool slot per sequence. Non-negative entries must be unique within a batch. A negative entry marks a padding row: its workgroup exits without writing any pool slot, track row ororow.has_initial_state(optional, [N] bool/int): False rows start from a zero state and ignore their slot's contents (NaN-safe). Their final state is still written to the slot. WithNone, every slot is loaded, so the caller must zero a new sequence's slot first.track_state/track_chunk_idx(optional): row n receives the fp32 state before chunktrack_chunk_idx[n]. Rows with a negative or out-of-range index are left untouched.ois freshly allocated. Rows outside[cu_seqlens[0], cu_seqlens[-1])and rows of padding sequences are left uninitialized.gdn_fused_prefill_supported(q, k, v, g, beta, ssm_states, max_seqlen=None):max_seqlen, the longest sequence in the batch. It then also rejects batches unlessmax_seqlen <= 1024 or H * T >= 24 * max_seqlen; for equal-length batches this isN * H >= 24. Callers that omitmax_seqlenget no protection from the regressions below.gdn_fused_prefill_fwdchecks operands only and raisesValueErroron unsupported ones.Performance
Setup: revision
a0abafac0501, MI355X (gfx950, 256 CUs), ROCm 10.0.0, torch 2.11.0+rocm10.0.0, FlyDSL 0.4.1 (the repo pin), Triton 3.8.0. One GDN layer; fused vschunk_gated_delta_rule_opt_vkwith the fastesthbackend per shape.Qwen3.5 tuned-table grid, 177 points. Full results, one row per point: #6496 (comment)
Reproduce from the repo root:
max_seqlenpassed, the gate sends all 31 to opt_vk. Every shape it keeps on fused is faster (worst 1.10x). It is conservative: 9 shapes where fused is up to 1.17x faster still go to opt_vk.usis summed device time of all kernels in the layer (torch profiler); speedups above use it. The benchmark also records per-call CUDA-event elapsed time, which includes launch gaps. On that measure the routed geomean is 1.36x and the worst kept shape is 1.17x.Other shapes:
Model shapes, including uneven varlen (
python op_tests/test_gdn_fused_prefill.py; device time; opt_vk = faster of the triton/flydslhbackends; rel_l2 is the worst sequence vs an fp32 token-by-token recurrence):qwen38_dense_4kqwen38_dense_16kqwen38_varlenqwen38_tp8_16kqwen35_tp8_tailqwen35_tp8_16kqwen35_tp8_batchqwen35_tp2_varlenqwen35_tp2_long_mixedAccuracy over the 177 points (worst sequence vs an fp32 chunked recurrence): fused o 3.36e-3 / state 3.06e-3; opt_vk o 5.00e-3 / state 6.70e-3.
All 177 points