Repository navigation
[Triton/Gluon] Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue - #5606
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
There was a problem hiding this comment.
🔵 Needs a closer look
Unresolved critical validation and dispatch-safety issues remain in the public support gate.
Pull request overview
Adds a gfx950/Triton 3.8+ Gluon fused Qwen3-Next GDN prefill path with FP8 group quantization.
Changes:
- Adds support gating and four specialized tile schedules.
- Implements fused convolution, scan, state updates, normalization, and quantization.
- Adds correctness tests and performance benchmarks.
File summaries
| File | Summary |
|---|---|
op_tests/triton_tests/test_fused_gdn_prefill_qkvz.py |
Reference-based correctness tests |
op_tests/op_benchmarks/triton/bench_fused_gdn_prefill_qkvz.py |
Latency and bandwidth benchmark |
aiter/ops/triton/gated_delta_net/fused_gdn_prefill_qkvz.py |
Public API, validation, and dispatch |
aiter/ops/triton/gated_delta_net/__init__.py |
Public export |
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/_tile_m3072_16384.py |
Mid-range token Gluon schedule |
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/_tile_m12289_16384_b6_15.py |
Higher-batch long-token schedule |
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/_tile_m12289_16384_b1_5.py |
Low-batch long-token schedule |
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/_tile_m1024_3071.py |
Small/medium-token schedule |
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/__init__.py |
Tile package exports |
Review details
Suppressed comments (3)
op_tests/op_benchmarks/triton/bench_fused_gdn_prefill_qkvz.py:73
- This benchmark labels the result as achieved HBM bandwidth, but the traffic model starts with only compulsory input/output and state bytes while the operation spills large intermediate buffers between launches. The printed TB/s and
%pktherefore do not represent achieved HBM bandwidth. Rename the metric to compulsory-traffic bandwidth or include scratch traffic in the model.
def bytes_moved(m, batch, num_k_heads, head_dim):
"""Compulsory traffic for one launch (fp8 epilogue always on)."""
num_v_heads = 2 * num_k_heads
channels = 2 * num_k_heads * head_dim + num_v_heads * head_dim
total = m * num_k_heads * (2 * head_dim + 4 * head_dim) * 2 # packed qkvz, bf16
op_tests/triton_tests/test_fused_gdn_prefill_qkvz.py:375
- The
has_initial_state=Falsetest only compares normalized output, even though this path also updatesconv_stateand is specifically intended to ignore the poisoned history pool. A kernel could produce the right output while writing an incorrect final window and still pass; also compare the returnedconv_statewithref_conv.
norm, *_ = _run_kernel(inp)
torch.testing.assert_close(norm.float(), ref_norm.float(), atol=ATOL, rtol=0)
op_tests/triton_tests/test_fused_gdn_prefill_qkvz.py:308
- Every multi-sequence case here uses identical sequence lengths, so no test exercises ragged boundaries, unaligned sequence starts, or per-sequence state carry even though
cu_seqlensis a central contract of this prefill op. Add a mixed-length case that crosses a chunk/tile boundary.
pytest.param([1024], "m1024_3071", id="m1024_b1"),
pytest.param([1024, 1024], "m1024_3071", id="m2048_b2"),
pytest.param([3072], "m3072_16384", id="m3072_b1"),
pytest.param([2048, 2048, 2048], "m3072_16384", id="m6144_b3"),
pytest.param([12289], "m12289_16384_b1_5", marks=pytest.mark.slow, id="m12289_b1"),
pytest.param(
[1600] * 8, "m12289_16384_b6_15", marks=pytest.mark.slow, id="m12800_b8"
- Files reviewed: 9/9 changed files
- Comments generated: 26
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…epilogue A single fused op for the Qwen3-Next gated delta-net *prefill* chain (causal_conv1d_split_qkv -> fused gating -> fp32 chunked delta scan -> gated RMSNorm -> per-head group-128 FP8 quant), replacing the four-kernel path with a tight set of Gluon launches that fuse the work intra-kernel and drop the intermediate HBM traffic. The FP8 activations a block-FP8 out_proj consumes are emitted by the epilogue launch (no separate quant kernel). Support is reported, not asserted: fused_gdn_prefill_qkvz_supported gates on gfx950, Triton >= 3.8 (Gluon dialect), and an in-range (tokens, batch)/dtype contract, so callers fall back to the four-kernel chain instead of crashing. Prefill spans a wide token range, so it dispatches one of four autotuned M-tile schedules. The Gluon/HIP tiles import lazily on dispatch, keeping the module and the support predicate importable on any platform. Tests: pure-torch fp32 sequential-scan reference (deliberately not the chunked algorithm) at the kernel's bf16 rounding boundaries; 9/9 pass on MI355X (gfx950, Triton 3.8). Includes an op benchmark. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Dispatch-safety: fused_gdn_prefill_qkvz_supported() now validates the full contract the fixed-stride Gluon tiles assume, so a mismatched call falls back instead of reading out of bounds: - exact baked topology (k_heads=4, v_heads=8, head_dim=128) via delta_state/ conv_state shapes -- rejects any other 2:1 head layout the tiles can't index; - packed projection widths (qkvz [tokens, 3072], ba [tokens, 16]); - conv_weight [2048, 4] and conv_bias [2048] shapes (not just non-None); - contiguity and single-device for every consumed tensor; - a_log/dt_bias/norm_weight shape+dtype when supplied (kept keyword-only so the existing (..., conv_bias, quant_dtype) positional contract is unchanged). Import-safety: architecture detection is imported and called lazily inside the gate (via _arch_supported) and any detection failure is reported as unsupported, so the module stays importable on CPU-only / non-ROCm workers. Profiling/naming: every launchable Gluon entry across the four M-tiles now has a make_kernel_repr with its constexpr schedule keys, so compiled-artifact and profiler names identify the specialization (matches the flash_kda sibling). Conventions: absolute imports for the new tile package; module-level CUDA skip marker on the test (matches the fused_kda decode sibling); corrected the "single launch" wording in the public docstring and added a full Args/Returns section documenting the shapes, dtypes and in-place state contract. Formatting: the four tile modules were also run through Black -- they predated the repo's Black pre-check (pre-checks.yaml runs `black --check .` over the whole tree) and were not conformant, which accounts for the bulk of the tile diff; the reformat carries no logic change. Validated on MI355X (Triton 3.8): op tests 9/9 pass across all four M-tiles; black + ruff clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Kernel modules under _gluon_kernels/ are meant to hold only @gluon.jit code (matches the flash_kda sibling). Each of the four M-tile modules mixed torch/ triton host code (buffer allocation + the kernel-launch sequence, plus the FP8 precision config) in with its Gluon kernels. Relocate that host orchestration to a per-tile launcher module next to the public wrapper -- aiter/ops/triton/gated_delta_net/_gdn_prefill_launch_<key>.py -- which imports the kernels from the (now torch-free) tile module. The wrapper's _load_tile imports the launcher for the dispatched tile, so only that tile's launcher (and its Gluon module) is imported on the dispatch path, preserving the lazy-import / import-safety behavior. No kernel logic or numerics change; the host code moved verbatim. The tile-package __init__ no longer re-exports host entries (the wrapper reaches the launchers directly). Validated on MI355X (Triton 3.8): op tests 9/9 pass across all four M-tiles; tiles verified torch-free; black + ruff clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
91cb1f4 to
7734b8f
Compare
|
Thanks for the review — rebased onto current Addressed
Intentionally not changed (following the nearest sibling rather than the suggestion)
|
The repo's blocking style pre-checks pin newer tools than were used originally (CI installs black 26.5.1 and ruff 0.16.0, whose default rule set is wider). Bring the PR's files into line with both: - black 26.5.1: reformat the op benchmark (it predated the Black pre-check). - ruff C408: rewrite dict() calls as literals (test/bench input builders). - ruff ISC004: parenthesize the gate's multi-line f-string messages. - ruff UP006/UP045: PEP 585/604 annotations (tuple/`X | None`) in the wrapper. - ruff RUF059/SIM102: name unused unpacked vars `_` and collapse nested ifs in the tiles (behavior-preserving -- short-circuit `and`, unused values). - ruff BLE001: keep the arch-detection probe's broad except (defensive: any failure => unsupported) with a scoped noqa. Re-validated on MI355X (Triton 3.8): op tests 9/9 across all four M-tiles; `black --check` and `ruff check` clean under the pinned CI versions. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review: PR #5606 — Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogueThanks for this. I went through all 13 files. Overall the kernel quality, safety engineering, and test strength are high; my substantive concerns are structural (rules 4 and 5) and are things I'd like an explicit maintainer decision on rather than a silent pass. Details below, organized by the repo's kernel rules first, then the broader points. Rule-by-rule1. repr decorator — pass. Every launched Gluon kernel across all four tiles carries a config-aware 2. unit tests — pass (strong). 3. benchmarks — pass. 4. right folder + config for tuning — partial. Folder placement is correct. But there is no config JSON: "tuning" is four frozen tile files selected by a hardcoded 5. no duplicate kernels — the main tension. Two parts:
6. no local activation helpers — soft pass. SiLU / sigmoid / softplus are inlined via Gluon primitives ( 7. succinct comments — pass. No oversized (>4-line) inline comment blocks in any tile file. Module/function docstrings are detailed but justified for a kernel this intricate. Broader assessmentEngineering quality is high. Support is reported, not asserted ( Two things I'd like resolved before merge:
Specialization, eyes-open. ~6,800 lines serving exactly one model config (K_HEADS=4, V_HEADS=8, HEAD_DIM=128, 2048 conv channels, 3072-wide qkvz). Any topology change needs new kernels. A deliberate, safely-gated perf trade — just noting this is a single-shape asset, not a general GDN prefill. VerdictRules 1, 2, 3, 6, 7 pass — 2 and the safety engineering notably well. Rule 4 is a partial deviation (tuning baked into source + hardcoded dispatch, no config JSON) and rule 5 is genuinely stressed by the four same-math implementations. Both are defensible for a perf-critical, ported Gluon fused op, but both deserve an explicit call rather than a silent pass. I'm in favor of the kernel on quality and test strength, conditioned on: (a) a stated rationale for four frozen variants vs. one parametrized kernel plus a sync/ownership plan; (b) confirmation the two slow-marked tiles run in CI; and (c) clarity that the fused path isn't yet adopted in-tree and the fallback is the caller's responsibility. |
…nc note Responds to PR ROCm#5606 review (three conditional items): * Test tiles no longer marked `slow`. aiter CI runs `pytest op_tests/triton_tests/` with no `-m "not slow"` filter and no other test uses the mark, so it deselected nothing and only implied the two 12289-token tiles might be skipped. Making them unconditional params is what guarantees CI executes them, so they can't rot. * Module docstring now states explicitly that this op is not adopted in aiter's in-tree GDN path and the fallback is the caller's responsibility (probe `_supported()` -> four-kernel chain on False); the `ValueError` flags misuse after a skipped probe, not a shape-dispatch fallback. * Module docstring documents how the four M-tile schedules stay in sync: they are ported autotuner output pinned to one `ref_gdn_prefill` reference that every tile is parametrized against, so a math change lands in the reference and CI fails any drifting tile. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Thanks — addressed all three in the latest push. Summary below; code/doc changes in 1. Four-tile maintenance surface(b) How they stay in sync. The four schedules aren't four hand-derived rewrites (a) Perf vs a single parametrized kernel — measured. First, correctness: the four Reading it:
So the honest tradeoff: the tiles are interchangeable for correctness, and consolidating 2. Slow-marked tiles rottingConfirmed they run — and I removed the misleading mark. aiter CI invokes 3. Integration clarity / ValueError vs fallbackMade the contract explicit in the module docstring ("Not adopted in-tree yet"): |
Follow-up on the four-tile structure (rule 5)Thanks for the sync-note and CI changes — the slow-tile coverage and the fallback/in-tree contract are both genuinely addressed. I want to sharpen my earlier note on the four tile schedules, because I framed it wrong the first time and the actual ask is much cheaper than "rewrite it as one kernel." What I'm not asking for
So the perf/codegen concerns I raised before don't apply, and I withdraw the "this can't be config-driven / four files are forced" framing — that was too strong. What rule 5 is actually aboutThe point of "no duplicate kernels" isn't LOC — it's a single canonical place to look for a given op. Today "the fused GDN prefill kernel" is spread across eight files: four tile bodies in the The dispatch doesn't need that fragmentation. The selector is already The cheap fixConsolidate, don't merge:
Same LOC, same kernels, same perf — but "the kernel" and "its host orchestration" each become one file where all four schedules sit side by side. That's the "single place to look" the rule is after, and it also naturally restores the rule-4 story (the schedule becomes a config/constexpr selection rather than a hardcoded four-file layout). |
…er module
Follow-up to vgokhale's rule-5 note on the four-tile structure. Collapse the four
per-schedule tile modules into a single tile module and the four per-schedule host
launchers into a single launcher module, so "the kernel" and its host orchestration
each live in one canonical place with all four schedules side by side.
Same kernels, same perf: every schedule's @gluon.jit bodies and host launchers are
byte-identical to before. The only edits are the minimal disambiguations a shared
namespace forces:
- tiles: b6_15's _multiply / _update_conv_state[_repr] carry a _b6_15 suffix
(they collided with b1_5 / m1024_3071); all other schedules keep bare names.
- launchers: the one shared FP8PrecisionConfig + FP8_E4M3_FN are hoisted once
(with a _PrecisionConfig alias so m1024_3071 stays verbatim); each schedule's
public entry becomes gdn_prefill_group_fp8_quant_<key> so all four coexist.
- _load_tile now imports the single launcher module and getattrs the per-key entry.
_select_tile_key is unchanged and still the dispatcher. Net -93 lines (dropped the
duplicated per-file headers/docstrings/config blocks).
Validated on MI355X (gfx950, Triton 3.8): all four schedules dispatch to the right
entry and match the ref_gdn_prefill reference (test_fused_gdn_prefill_qkvz.py, all
6 cases incl. the renamed b6_15).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Done @vgokhale — consolidated in 43d13de.
All four schedules now sit side by side in each file, clearly banner-delimited. _select_tile_key is unchanged and The one place I couldn't keep names literally verbatim is where a shared namespace forced a collision — flagging so
Every other line of every schedule is unchanged. Re-validated on MI355X (gfx950, Triton 3.8): all four schedules |
Blank-line normalization only around the schedule section banners in the merged tile + launcher modules; no executable content changed (git diff --ignore-blank- lines is empty). Fixes the pre-checks black/ruff CI jobs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up: fold
|
Address review: remove the separate _gdn_prefill_launch.py and move its four schedule launchers into fused_gdn_prefill_qkvz.py, following the gemm/basic/gemm_a16w16.py precedent. Each launcher lazily imports its Gluon kernels inside the function body, so the wrapper -- and the fused_gdn_prefill_qkvz_supported probe on the caller's fallback path -- stays importable on older Triton / non-gfx950 / CPU; only triton.experimental.gluon and the gfx950 kernel modules are gated, loading once a tile is dispatched. _select_tile_key remains the dispatcher (_load_tile returns the module-local gdn_prefill_group_fp8_quant_<key>). Restores the canonical kernel + wrapper + test + bench layout. Schedule bodies are unchanged (AST-identical to the old launcher modulo the injected lazy imports); pytest test_fused_gdn_prefill_qkvz.py passes 9/9 across all four tiles on gfx950 (MI355X). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Done @vgokhale : _gdn_prefill_launch.py is gone; its four schedule launchers now live in the wrapper, following the
|
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Add bounds and offset validation, move tuning parameters into configuration, and expand or relocate the test coverage.
Review effort: Lite
Findings: 1
Open (3)
Resolved since last review (26)
The gate only checks that the listed tensors are CUDA tensors; it does not require them to be on… The gate only checks that a bias object is non-None; it never checksconv_bias.shape. A short… The support predicate accepts any 128-dimensional 2:1 topology, but every tile hard-codes 8 value… The support predicate derives onlytokensandbatchfrom these inputs and never validates the… The top-levelarch_infoimport executes driver detection during module import…make_inputsallocates CUDA tensors before_require_supportedcan skip the test. On a CPU-only… This call to the support predicate omitsa_log,dt_bias, andnorm_weight, so their device,…_convolve_slidingis launched directly below, so it is a new launchable Gluon entry kernel, but…_prepare_tokensis launched directly below, so it is a new launchable Gluon entry kernel, but it…_prepare_qkv_windowis launched directly below, so it is a new launchable Gluon entry kernel, but…_prepare_inputs_tiledis launched directly below, so it is a new launchable Gluon entry kernel,… This new test file adds an ad-hoc__main__runner, which the test conventions prohibit because… The test module repeats the same incorrect single-launch description; the implementation is a… The new kernel test is flat atop_tests/triton_tests/, while the kernel is in the… The new public operation's docstring still omits the input shapes/dtypes, ragged state/index… This public docstring describes the implementation as a single Gluon launch, but the implementation… The new export uses a relative import, but the Triton tree's import rule requires absolute… This tile embeds shape-dependent scheduling decisions and launch tuning (bt,snapshot_outputs,… This new_gluon_kernelsmodule importstorchfor host allocations and annotations. Kernel… The batch-dependenttoken_block,value_block,recur_warps, and related launch choices are…
And 6 more resolved.
| if cache_indices.dtype is not torch.int32: | ||
| return False, f"cache_indices must be int32, got {cache_indices.dtype}" |
| C=32 if batch >= 16 or 5 <= batch <= 7 else 64, | ||
| BV=64 if batch >= 16 else (8 if batch <= 2 else 16), | ||
| WM=1 if batch >= 16 else 4, | ||
| S=segment_chunks, |
| def _schedule(m: int, batch: int) -> _Schedule: | ||
| wide = batch == 2 and m >= 16384 | ||
| if 2 < batch < 8 and m <= 4096: | ||
| segment = 0 | ||
| elif batch <= 4 and m <= 4096: |



A single fused op for the Qwen3-Next gated delta-net prefill chain (causal_conv1d_split_qkv -> fused gating -> fp32 chunked delta scan -> gated RMSNorm -> per-head group-128 FP8 quant), replacing the four-kernel path with a tight set of Gluon launches that fuse the work intra-kernel and drop the intermediate HBM traffic. The FP8 activations a block-FP8 out_proj consumes are emitted by the epilogue launch (no separate quant kernel).
Support is reported, not asserted: fused_gdn_prefill_qkvz_supported gates on gfx950, Triton >= 3.8 (Gluon dialect), and an in-range (tokens, batch)/dtype contract, so callers fall back to the four-kernel chain instead of crashing. Prefill spans a wide token range, so it dispatches one of four autotuned M-tile schedules. The Gluon/HIP tiles import lazily on dispatch, keeping the module and the support predicate importable on any platform.
Tests: pure-torch fp32 sequential-scan reference (deliberately not the chunked algorithm) at the kernel's bf16 rounding boundaries; 9/9 pass on MI355X (gfx950, Triton 3.8). Includes an op benchmark.
Motivation
The Qwen3-Next GDN (gated delta-net) prefill is a four-kernel chain today:
causal_conv1d_split_qkv→ fused gating → the fp32 chunked delta-rule scan →gated RMSNorm + per-head group-128 FP8 quant. Four launches means the large
intermediate tensors (split qkv, conv output, gated core) round-trip through HBM
between every step.
This PR adds a single fused Gluon op,
fused_gdn_prefill_qkvz, that folds thatwork intra-kernel: split + conv + SiLU + QK-norm + gating-prep in one launch, the
fp32 chunked scan, and a gated-RMSNorm + group-128 FP8-quant epilogue. The win
is the intra-launch fusion and the dropped intermediate HBM traffic. The FP8
activations a block-FP8
out_projconsumes are emitted by the epilogue launch, sothere is no separate quantization kernel.
This is the prefill sibling of the decode kernel (#5520): same
Qwen3-Next GDN math, but it consumes ragged variable-length batches
(
cu_seqlens+has_initial_state) and runs the fp32 chunked scan instead of thesingle-token recurrent update.
Design
fused_gdn_prefill_qkvz_supported(...) -> (bool, reason)gates on gfx950 (CDNA buffer addressing / inline asm / explicit register
layouts) and Triton ≥ 3.8 (the tiles are the Gluon dialect; some ROCm 3.7
builds import
triton.experimental.gluonbut fail to compile it, so the gate is aversion check, not just an import probe). Callers fall back to the four-kernel
chain instead of crashing.
stay importable on any platform (older Triton, non-gfx950, CUDA).
schedules over the covered region (
tokens ∈ [1024, 16384],batch ∈ [1, 64]).head_k_dim == head_v_dim == 128, groupsize 128,
num_v_heads == 2·num_k_heads.Files changed (9 files, +4655)
aiter/ops/triton/gated_delta_net/fused_gdn_prefill_qkvz.py_supported()gate + tile_select_tile_key)aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/_tile_m1024_3071,_tile_m3072_16384,_tile_m12289_16384_b1_5,_tile_m12289_16384_b6_15) + package__init__|
|
aiter/ops/triton/gated_delta_net/__init__.py| 6 | Exportfused_gdn_prefill_qkvz/_supported||
op_tests/triton_tests/test_fused_gdn_prefill_qkvz.py| 416 | Correctness vs pure-torch fp32 reference ||
op_tests/op_benchmarks/triton/bench_fused_gdn_prefill_qkvz.py| 164 | Latency benchmark |Accuracy — run command
Correctness is checked against a pure-torch fp32 sequential-scan reference
(deliberately not the chunked algorithm the kernel uses, so agreement is
meaningful), matched to the kernel's bf16 rounding boundaries. Needs a gfx950 +
Triton ≥ 3.8 ROCm environment.
# from the aiter checkout, on an MI350-series (gfx950) host: python3 -m pytest -q op_tests/triton_tests/test_fused_gdn_prefill_qkvz.pyResult on MI355X (Triton 3.8): 9 passed — all 4 M-tiles compile+run+match the
reference, both
has_initial_statepaths, determinism, and the unsupported-reasonpath. Numerics: fp8 activation ~1.3–7% (fp8 level),
conv_stateexact, recurrentstate ~0.4%.
Perf
Kernel vs the four-kernel chain it replaces (MI355X, num_k=4 / num_v=8 /
head=128; latency ms, median; speedup of the fused kernel):
(2.1–3.8× faster; widest at small-seq/large-batch where launch overhead dominates,
narrowest at m=16384 where it is compute-bound.)
End-to-end through sglang (Qwen3-Next-80B FP8, MI355X, TP4), prefill-focused
(ISL 6144 / OSL 8) so TTFT surfaces the prefill win:
A balanced 1k/1k concurrency sweep (1→32) is TTFT-neutral-to-better (−12–16% at low
concurrency, −2–6% at high), decode-neutral (TPOT identical), GSM8K parity
(0.953 / 0.950). The sglang consumer wiring is a companion PR.