Skip to content

[Triton/Gluon] Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue - #5606

Merged
valarLip merged 11 commits into
ROCm:mainfrom
karverma-amd:karverma/fused-gdn-prefill-qkvz-clean
Sep 28, 2026
Merged

valarLip merged 11 commits into
ROCm:mainfrom
karverma-amd:karverma/fused-gdn-prefill-qkvz-clean

Conversation

@karverma-amd

@karverma-amd karverma-amd commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

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 that
work 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_proj consumes are emitted by the epilogue launch, so
there 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 the
single-token recurrent update.

Design

  • Reported, not asserted. 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.gluon but fail to compile it, so the gate is a
    version check, not just an import probe). Callers fall back to the four-kernel
    chain instead of crashing.
  • Lazy tile import on the dispatch path, so the module and the support predicate
    stay importable on any platform (older Triton, non-gfx950, CUDA).
  • Prefill spans a wide token range, so it dispatches one of four autotuned M-tile
    schedules
    over the covered region (tokens ∈ [1024, 16384], batch ∈ [1, 64]).
  • Constraints inherited from the epilogue: head_k_dim == head_v_dim == 128, group
    size 128, num_v_heads == 2·num_k_heads.
(normalized_bf16, conv_state, delta_state, quantized_fp8, scales) = fused_gdn_prefill_qkvz(
    projected_qkvz, projected_ba, conv_state, delta_state,
    cache_indices, cu_seqlens, has_initial_state,
    conv_weight, conv_bias, a_log, dt_bias, norm_weight,
    scale=head_k_dim ** -0.5, eps=norm.eps,
)   # conv_state / delta_state advanced in place

Files changed (9 files, +4655)

File + What
aiter/ops/triton/gated_delta_net/fused_gdn_prefill_qkvz.py 308 Public op + _supported() gate + tile
dispatch (_select_tile_key)
aiter/ops/triton/_gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz/ 3761 4 Gluon M-tile schedules
(_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 | Export fused_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.py

Result on MI355X (Triton 3.8): 9 passed — all 4 M-tiles compile+run+match the
reference, both has_initial_state paths, determinism, and the unsupported-reason
path. Numerics: fp8 activation ~1.3–7% (fp8 level), conv_state exact, recurrent
state ~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):

shape k:v:b:s m 4-kernel chain (ms) fused (ms) speedup
4:8:1:4096 4096 0.691 0.222 3.1×
4:8:2:4096 8192 0.834 0.302 2.8×
4:8:4:2048 8192 0.782 0.287 2.7×
4:8:1:8192 8192 0.867 0.324 2.7×
4:8:1:2048 2048 0.616 0.215 2.9×
4:8:2:1024 2048 0.677 0.176 3.8×
4:8:8:1024 8192 0.744 0.209 3.6×
4:8:2:8192 16384 1.072 0.509 2.1×

(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:

metric stock fused Δ
Median TTFT (ms) 647.9 471.6 −27%
Input throughput (tok/s) 92.8k 125.4k +35%
GSM8K 0.955 0.950 parity

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.

@karverma-amd
karverma-amd requested a review from a team September 17, 2026 00:17
@github-actions github-actions Bot changed the title Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant … [Triton/Gluon] Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant … Sep 17, 2026
@karverma-amd karverma-amd changed the title [Triton/Gluon] Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant … Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue Sep 17, 2026
@github-actions

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: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; main branch always runs both MI35X and MI300X
multigpu 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: 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 5606 --add-label <label>

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 opt this PR out.

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.

🔵 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 %pk therefore 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=False test only compares normalized output, even though this path also updates conv_state and 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 returned conv_state with ref_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_seqlens is 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.

@github-actions github-actions Bot changed the title Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue [Triton/Gluon] Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue Sep 17, 2026
karverma-amd and others added 3 commits September 17, 2026 15:27
…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]>
@karverma-amd
karverma-amd force-pushed the karverma/fused-gdn-prefill-qkvz-clean branch from 91cb1f4 to 7734b8f Compare September 17, 2026 16:40
@karverma-amd

Copy link
Copy Markdown
Contributor Author

Thanks for the review — rebased onto current main (now mergeable) and worked through the findings. On-device validated on MI355X (Triton 3.8): the op tests pass 9/9 across all four M-tiles, black + ruff clean.

Addressed

  • Support-gate dispatch-safety (the main cluster): fused_gdn_prefill_qkvz_supported now validates the full contract the fixed-stride tiles assume, so a mismatched call falls back instead of reading out of bounds — exact baked topology (k=4/v=8, head_dim 128), packed projection widths ([T,3072]/[T,16]), conv_weight [2048,4] and conv_bias [2048] shapes, contiguity + single-device for every consumed tensor, and a_log/dt_bias/norm_weight shape+dtype. The three parameter checks are 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 and any detection failure is reported as unsupported, so the module stays importable on CPU-only / non-ROCm workers.
  • make_kernel_repr: added to every launchable Gluon entry across the four tiles (including the variable-grid / selection-launched ones) with its constexpr schedule keys.
  • torch-free kernel modules: moved the torch/triton host orchestration out of each _gluon_kernels tile into a per-tile launcher next to the wrapper (_gdn_prefill_launch_<key>.py); the tiles are now Gluon-only. _load_tile imports only the dispatched tile's launcher, preserving the lazy/import-safe behavior.
  • Conventions: absolute imports for the new tile package; module-level CUDA-skip marker on the test; corrected the "single launch" docstring and added a full Args/Returns/state-contract section. The four tile modules were also run through Black (they predated the repo's Black pre-check), which accounts for the bulk of the tile diff — no logic change.

Intentionally not changed (following the nearest sibling rather than the suggestion)

  • Tuning in JSON: the closest sibling, _gluon_kernels/gfx950/chunk_delta_attn/flash_kda_k1.py, keeps its schedule constants in-source (_NUM_WARPS, launch params) rather than in the config tree, so I kept these tiles consistent with it. Happy to externalize if you'd prefer a different convention here.
  • Test directory: the sibling decode test op_tests/triton_tests/test_fused_kda_decode_unified.py is flat under triton_tests/ (not in a gated_delta_net/ subdir), so I left this test flat to match.

karverma-amd and others added 2 commits September 17, 2026 16:57
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]>
@vgokhale

Copy link
Copy Markdown
Contributor

Review: PR #5606 — Add fused Qwen3-Next GDN prefill (gfx950 Gluon) with fp8 group-quant epilogue

Thanks 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-rule

1. repr decorator — pass. Every launched Gluon kernel across all four tiles carries a config-aware @gluon.jit(repr=_<name>_repr); I cross-checked the [grid](...) launch sites against the repr'd kernels and they match. The bare @gluon.jit device helpers (_add, _inverse, _matrix_product, _load_packed_operand, …) are inlined and correctly omit repr.

2. unit tests — pass (strong). test_fused_gdn_prefill_qkvz.py validates against an independent pure-torch fp32 sequential-scan reference (deliberately not the chunked algorithm — the right call for catching a bug in the algorithm under test), with fail-hard torch.testing.assert_close on norm / conv / delta and the dequantized fp8 activations, parametrized to hit all four tiles and asserting each dispatches to the correct tile. Determinism (bitwise, atol=0) and a support-gate test are included. One ask: the two heavy 12289-token tiles are slow-marked — please confirm CI actually runs them so they don't rot.

3. benchmarks — pass. bench_fused_gdn_prefill_qkvz.py is present with a proper bytes-moved model. It would be stronger if it also timed the four-kernel baseline this replaces, since the entire justification is dropped intermediate HBM traffic — a side-by-side would make the win concrete.

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 _select_tile_key(tokens, batch), so this does not use the config-driven tuning system (configs/<arch>/…/DEFAULT.json) the rule points at. I recognize the per-band tuning here is structural (different algorithms/schedules), not just tile-size params, so it genuinely can't be reduced to JSON the way a GEMM tile can — but it's still a deviation worth acknowledging explicitly.

5. no duplicate kernels — the main tension. Two parts:

  • Fused vs. the chain it replaces: fine. The general causal_conv1d_split_qkv / fused_gdn_gating / chunk_gated_delta_rule / gated_rmsnorm kernels remain for fallback; this adds a specialized fused path (like flash-attn vs. unfused attention), not a duplicate.
  • Internal: the four tile files (907 + 1235 + 821 + 1425 ≈ 4,400 lines) are four implementations of the same GDN-prefill math. To be fair, they are not copy-paste — each has entirely different function names and decompositions (_four_diagonal_inverses/_propagate_segments vs _build_group_maps/_recurrence_compact vs _solve_diagonal_blocks…), i.e. distinct byte-faithful tuned schedules ported per token-band. So it isn't lazy duplication. But under the rule's wording ("same or almost same functionality"), four independent implementations of identical math is exactly the case it's meant to flag. See the structural note below.

6. no local activation helpers — soft pass. SiLU / sigmoid / softplus are inlined via Gluon primitives (gl.div_rn(x, 1+libdevice.exp(-x)), 1/(1+gl.exp(-x)), gl.where(av<=20, gl.log(1+gl.exp(av)), av)), not defined as local reusable functions, so there's nothing to move to utils — and the existing activation.py helpers are triton (tl.), unusable from @gluon.jit. Mild note: the same activation math is re-inlined in each of the four tiles, which compounds the point above and argues for a shared Gluon activation-utils module down the line.

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 assessment

Engineering quality is high. Support is reported, not asserted (fused_gdn_prefill_qkvz_supported gates gfx950 + Triton ≥ 3.8 + an exact shape/dtype contract); Gluon/HIP imports are lazy so the module stays importable on any platform; arch detection is guarded so it can't raise at import; tile modules are strictly torch-free with host orchestration split into separate launchers; and the hardcoded Qwen3-Next topology is protected by a rejecting gate rather than reading out of bounds. This is careful, production-minded work.

Two things I'd like resolved before merge:

  1. The four-implementation maintenance surface (rules 4 + 5 together). 4,400 lines of four structurally different implementations of the same delta-scan math is a large, risky surface: a math fix or spec change has to be re-derived four ways, correctness argued four times, and the variants can silently drift. The perf case for freezing per-band tuned schedules is real, but could you share (a) roughly how much perf is won versus a single parametrized Gluon kernel that accepts some loss, and (b) how the four variants will be kept in sync as the GDN math evolves? I'd like this to be a conscious, documented decision rather than an implicit one.

  2. It isn't wired into a caller yet, and the fallback is caller-enforced. fused_gdn_prefill_qkvz is exported, but nothing in-tree calls it, and on an unsupported shape the wrapper raises ValueError — the docstring pushes the "check _supported, else use the four-kernel chain" responsibility onto the caller. So "replaces the four-kernel path" is aspirational for now (no in-repo switch), and a future caller that skips the gate will crash rather than fall back. That's a reasonable scoping (kernel PR separate from the integration), but please state it explicitly and confirm the consuming integration will use the gate.

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.

Verdict

Rules 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]>
@karverma-amd

Copy link
Copy Markdown
Contributor Author

Thanks — addressed all three in the latest push. Summary below; code/doc changes in
fused_gdn_prefill_qkvz.py (module docstring) and test_fused_gdn_prefill_qkvz.py.

1. Four-tile maintenance surface

(b) How they stay in sync. The four schedules aren't four hand-derived rewrites
of the delta-scan math — they're ported autotuner output (the Artemis MI355 v1
kernel-pack), one specialization per token/batch band. They share a single contract:
for any covered shape the result must match one ref_gdn_prefill reference, and
test_matches_reference parametrizes every tile against it. A math/spec change
lands in that one reference; CI then fails any tile that drifts. So the source of
truth is the reference, not four parallel edits — I've written this into the module
docstring ("Keeping the four tiles in sync"). If a future math change is large enough
that re-porting four tiles is a real burden, the honest fix is to re-run the
upstream autotuner and re-import, which is how the four were produced in the first
place.

(a) Perf vs a single parametrized kernel — measured. First, correctness: the four
tiles are numerically interchangeable — running any tile off its band matches the
dispatched tile to a norm-relative error of ~1e-5…7e-5 (bf16/fp8 accumulation noise from
a different chunk schedule, well inside the tolerance the op tests already accept). So a
single kernel across the whole range is viable; the split is a perf choice, not a
correctness one. Then I forced the most general tile (m3072_16384, already the
dispatch's wide-region fallback) across the sweep and timed it against the per-band
dispatch on identical inputs (gfx950, CUDA-graph replay, median of 5, two runs, <1%
spread):

  b  seqlen  tokens          dispatch  disp_us single_us  loss%   norm-rel vs dispatch
  1    1024    1024        m1024_3071    91.7     74.9    -18.5    1.3e-05
  1    2048    2048        m1024_3071   141.6    105.3    -25.5    7.5e-05
  1    3072    3072       m3072_16384   129.3    129.3     0.0    (same tile)
  3    2048    6144       m3072_16384   203.4    203.3    -0.1    (same tile)
  1    8192    8192       m3072_16384   272.4    271.7    -0.2    (same tile)
  1   12288   12288       m3072_16384   378.6    378.9     0.0    (same tile)
  1   16384   16384 m12289_16384_b1_5   455.4    486.1    +6.7    3.7e-05
  4    3072   12288       m3072_16384   384.7    382.7    -0.5    (same tile)
  8    1600   12800m12289_16384_b6_15   302.0    292.3    -3.2    3.3e-05
  3    4096   12288       m3072_16384   364.5    366.4    +0.5    (same tile)

Reading it:

  • Most of the covered space is already one kernel. m3072_16384 is what the
    dispatch selects for the whole 3072–12288 band and for 12289+ at batch ≥16 — 6 of the
    10 sampled shapes. So "four kernels" is really one general kernel + three edge
    specializations
    ; there's no dispatch cost over the bulk of the range.
  • The specialization win is bounded: ≤ ~7%. Forcing the general tile onto the top of
    the range costs +6.7% at 16384 (vs m12289_16384_b1_5) and +3.2% at the batched 12800
    case. That is the perf the extra tiles actually buy on these equal-length shapes.
  • But the split still earns its place on ragged prefill, which is why I'm not
    collapsing it.
    A deeper sweep with variable-length seqlens (realistic prefill, not
    equal-split) flips the winner: m3072_16384 wins the ragged mid-range by up to ~19%,
    while m12289_16384_b1_5 wins equal-length high-token. No single tile is universally
    best, and the dispatch keys only on (tokens, batch), not raggedness — so a
    blanket single kernel would regress real ragged workloads, not just cost ≤7% at the top.

So the honest tradeoff: the tiles are interchangeable for correctness, and consolidating
to one would shed ~3 files but (i) give up ≤7% at the high-token equal-length points and
(ii) regress ragged mid-range by up to ~19%, which the dispatch can't recover because it
can't see raggedness. That's why I kept the autotuner's per-band split. If you'd still
prefer a single parametrized kernel that eats that loss for a smaller surface, it's a
clean follow-up (the interchangeability result means it's safe to try) — happy to, but
it's a design change, not a correctness fix.

2. Slow-marked tiles rotting

Confirmed they run — and I removed the misleading mark. aiter CI invokes
pytest -v op_tests/triton_tests/ with only explicit per-case --deselect; there is
no -m "not slow" filter anywhere, and pytest.mark.slow isn't used by any other test
in the repo, so the mark deselected nothing and just implied these might be skipped.
The two 12289-token cases are now unconditional params, which is what actually
guarantees CI executes them. Updated the comment to say so explicitly.

3. Integration clarity / ValueError vs fallback

Made the contract explicit in the module docstring ("Not adopted in-tree yet"):
aiter's own GDN prefill path does not call this op; it's for an external caller
(sglang) to opt into, and the fallback to the four-kernel chain is the caller's
responsibility. The intended flow is probe fused_gdn_prefill_qkvz_supported(...) →
run the fused op on True, run the existing chain on (False, reason). The
ValueError in fused_gdn_prefill_qkvz only fires for a caller that skipped that
probe — it flags misuse, it is not a shape-dispatch fallback — so a supported-gated
caller never hits it.

@vgokhale

Copy link
Copy Markdown
Contributor

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

  • Not fewer lines. The four schedules are byte-faithful ported autotuner output; keep the bodies verbatim, keep the per-band codegen, keep the perf.
  • Not merging the algorithms into one function. They're structurally different (I checked — only _multiply and _update_conv_state names overlap across tiles; everything else is unique), and hand-weaving four generated programs together would risk drifting from the byte-faithful port.

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 about

The 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 fused_gdn_prefill_qkvz/ subpackage, plus four separate host launchers (_gdn_prefill_launch_m*.py) sitting next to the wrapper. To understand or change the op you have to know to open eight files across two directories.

The dispatch doesn't need that fragmentation. The selector is already constexpr-able (or config-JSON-able): a TILE: gl.constexpr branch — or the existing _select_tile_key picker — chooses the schedule with the untaken branches dead-code-eliminated at JIT time, so each specialization compiles identically to today. Zero perf cost.

The cheap fix

Consolidate, don't merge:

  • Put the four tile bodies in one tile module (each schedule stays its own set of functions, verbatim).
  • Put the four host launchers in one launcher module.
  • Keep _select_tile_key as the picker, now dispatching among functions in those modules.

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]>
@karverma-amd

Copy link
Copy Markdown
Contributor Author

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

  • Not fewer lines. The four schedules are byte-faithful ported autotuner output; keep the bodies verbatim, keep the per-band codegen, keep the perf.
  • Not merging the algorithms into one function. They're structurally different (I checked — only _multiply and _update_conv_state names overlap across tiles; everything else is unique), and hand-weaving four generated programs together would risk drifting from the byte-faithful port.

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 about

The 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 fused_gdn_prefill_qkvz/ subpackage, plus four separate host launchers (_gdn_prefill_launch_m*.py) sitting next to the wrapper. To understand or change the op you have to know to open eight files across two directories.

The dispatch doesn't need that fragmentation. The selector is already constexpr-able (or config-JSON-able): a TILE: gl.constexpr branch — or the existing _select_tile_key picker — chooses the schedule with the untaken branches dead-code-eliminated at JIT time, so each specialization compiles identically to today. Zero perf cost.

The cheap fix

Consolidate, don't merge:

  • Put the four tile bodies in one tile module (each schedule stays its own set of functions, verbatim).
  • Put the four host launchers in one launcher module.
  • Keep _select_tile_key as the picker, now dispatching among functions in those modules.

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).


Done @vgokhale — consolidated in 43d13de.

  • One tile module: _gluon_kernels/gfx950/gated_delta_net/fused_gdn_prefill_qkvz.py (the four tile*.py + the package
    init collapsed into it, same dotted import path).
  • One launcher module: gated_delta_net/_gdn_prefill_launch.py (the four gdn_prefill_launch.py collapsed into
    it).

All four schedules now sit side by side in each file, clearly banner-delimited. _select_tile_key is unchanged and
still the dispatcher; _load_tile just imports the single launcher module and picks the per-key entry. Kernels and
host bodies are byte-identical to before, so same kernels / same perf — net −93 lines, only from dropping the
duplicated per-file headers/docstrings/precision-config blocks.

The one place I couldn't keep names literally verbatim is where a shared namespace forced a collision — flagging so
it's visible in review:

  • Tiles: m12289_16384_b6_15's _multiply and _update_conv_state (+ its _repr) get a _b6_15 suffix (they collided with
    b1_5 / m1024_3071); every other schedule keeps its names bare and unchanged.
  • Launchers: the identical FP8PrecisionConfig + FP8_E4M3_FN are hoisted once (with a PrecisionConfig alias so
    m1024_3071's body stays verbatim); each schedule's public entry becomes gdn_prefill_group_fp8_quant
    so all four
    coexist.

Every other line of every schedule is unchanged. Re-validated on MI355X (gfx950, Triton 3.8): all four schedules
dispatch to the right entry and match ref_gdn_prefill across the full test_fused_gdn_prefill_qkvz.py case set,
including the renamed b6_15.

karverma-amd and others added 2 commits September 23, 2026 19:41
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]>
@vgokhale

Copy link
Copy Markdown
Contributor

Follow-up: fold _gdn_prefill_launch.py into the wrapper

The four-tile consolidation is great — that resolved the "scattered across eight files" concern cleanly. One structural thing remains: aiter/ops/triton/gated_delta_net/_gdn_prefill_launch.py is an extra file outside the canonical layout, which is kernel (_gluon_kernels/gfx950/...) + wrapper (ops/triton/...) + unit test + benchmark. The launcher is a fifth file — it's host (torch/triton) orchestration, i.e. wrapper-layer code, split out of the wrapper.

Why it was split, and why it doesn't need to be

The reason for the split is import-safety: the wrapper must import and run fused_gdn_prefill_qkvz_supported() on any platform (Triton < 3.8, non-gfx950, CUDA) so callers can probe the gate and fall back, but the launch code imports the Gluon kernel module at top level, which isn't importable without triton.experimental.gluon. So the Gluon import has to be deferred to dispatch time.

That's a real constraint, but it needs a lazy import boundary, not a separate file — and this is already a solved problem in the repo.

Precedent: the bf16 GEMM (gemm/basic/gemm_a16w16.py)

It does gluon-on-gfx1250 with a triton fallback, entirely inside the wrapper, with no launcher module:

_GLUON_SUPPORTED_ARCHS = ("gfx1250",)
def _is_gluon_available():
    return any(a in get_arch() for a in _GLUON_SUPPORTED_ARCHS)
...
backend = "gluon" if _is_gluon_available() else "triton"
...
if backend == "gluon":
    from aiter.ops.triton._gluon_kernels.gfx1250.gemm.basic.gemm_a16w16_persistent import (...)  # lazy, inside the branch
    ...  # buffer allocs, config unpack, splitk, kernel launch — all inline in the wrapper

So the pattern is: kernels in _gluon_kernels/gfx<arch>/…; the wrapper branches on get_arch(), and on the supported arch it lazily imports the Gluon kernels inside the branch and does the buffer-alloc + launch inline. The wrapper stays import-safe on non-gluon platforms because the Gluon import only fires when the gluon branch runs. There is no *_launch file.

That gives the exact import-safety guarantee _gdn_prefill_launch.py was created for, without the extra file.

Suggested change

Fold the launcher into the wrapper following gemm_a16w16:

  • Gate the gluon path on get_arch() == "gfx950" (mirroring _is_gluon_available()), keeping the existing _select_tile_key as the per-(tokens, batch) picker.
  • Move the four gdn_prefill_group_fp8_quant_<key> launch routines into the wrapper module as helper functions, each doing its Gluon import lazily inside the function (as the wrapper already does for _arch_supported).
  • Delete _gdn_prefill_launch.py.

The only difference from gemm_a16w16 is volume — this op's orchestration is ~1,250 lines (four schedules × a 6-launch pipeline) versus ~60 lines for the single-launch GEMM — so the wrapper grows to ~1,700 lines. That's fine; the launch routines stay as separate helper functions in the same module, selected by the arch/_select_tile_key branch. End state is the canonical four files — kernel (gluon/gfx950) + wrapper (dispatch + inline launch helpers) + test + bench — matching how the bf16 GEMM already handles gluon-vs-triton.

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]>
@karverma-amd

Copy link
Copy Markdown
Contributor Author

Done @vgokhale : _gdn_prefill_launch.py is gone; its four schedule launchers now live in the wrapper, following the
gemm/basic/gemm_a16w16.py pattern.

  • The four gdn_prefill_group_fp8_quant_ helpers (plus _run_chunked_delta / _Schedule / _schedule /FP8PrecisionConfig) moved into fused_gdn_prefill_qkvz.py, right after _select_tile_key, which stays the dispatcher
    (load_tile now just returns the module-local gdn_prefill_group_fp8_quant).
  • Each helper imports its Gluon kernels lazily inside the function body — exactly as gemm_a16w16 lazy-imports its Gluon
    kernels inside the supported-arch branch — so the module (and the fused_gdn_prefill_qkvz_supported probe on the
    fallback path) stays importable on older Triton / non-gfx950 / CPU. import triton is safe everywhere; only
    triton.experimental.gluon + the gfx950 kernel modules are gated, and those only load once a tile is dispatched.
  • Wrapper is now ~1.7k lines, back to the canonical kernel + wrapper + test + bench layout.

@valarLip
valarLip merged commit 7ccb9bb into ROCm:main Sep 28, 2026
84 of 85 checks passed
@Boss2002n
Boss2002n requested a lite review from Copilot September 28, 2026 05:14

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.

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 High severity · 2 Low severity

Open (3)
Resolved since last review (26)

And 6 more resolved.

Comment on lines +1573 to +1574
if cache_indices.dtype is not torch.int32:
return False, f"cache_indices must be int32, got {cache_indices.dtype}"
Comment on lines +442 to +445
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,
Comment on lines +477 to +481
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:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants