Repository navigation
[HIP] [JIT] Add fused_indexed_gated_residual for diffusion transformer blocks - #6417
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
|
@junhaha666, the Triton implementation (#6416) was merged yesterday. Is the HIP implementation in this PR still wanted? It has the same interface and, with |
|
No activity for 15 days, so this is now labelled |
|
Hi @junhaha666 Soft reminder, could you please take you time to give a look at this PR? Thanks very much. ^ ^ |
|
Hi @junhaha666, a short follow-up: since the Triton version (#6416) is merged, would you prefer that I close this HIP version? Either answer is fine, I just want to avoid leaving a stale PR in your queue. |
|
@aiter-bot review |
|
aiter-bot — queued behind 9 review(s); expect to start in about 3.2 h. The box reviews one PR at a time. |
aiter-bot
left a comment
There was a problem hiding this comment.
ROCm/aiter PR #6417 — [HIP] [JIT] Add fused_indexed_gated_residual for diffusion transformer blocks
Review (advisory):
Validation (deterministic): NOT RUN — auto-validation disabled on this box (REVIEW_AUTO_VALIDATE=0) and no report supplied; a manual run is also blocked here (CPU-only torch, all 8 GPUs at 95–96% VRAM), and the PR is stale against the merge target, so a head-matched run needs a rebase first. Target: op_tests/test_fused_indexed_gated_residual.py.
Perf (advisory): NOT RUN — the perf stage found no benchmark entry point on the triaged target (the PR's bench script is standalone, not a harness the stage can drive), and this box has no ROCm-capable torch or idle GPU for a hand run; the PR's own 2.31–2.37x numbers are author-run, head-only vs eager, on gfx1201 only.
Size: 575 lines / 9 files
Design (advisory): ship the HIP kernel as the public aiter.fused_indexed_gated_residual unconditionally on every arch, alongside the already-merged Triton implementation of the same op (#6416), with no backend dispatch between them
Human: recommend sumin-hong review whether aiter should carry two fused_indexed_gated_residual backends now that the Triton one (#6416) is merged, and whether the public aiter name should unconditionally mean the HIP kernel on every arch or dispatch between backends as mhc's backend parameter does
FUSED_INDEXED_GATED_RESIDUAL_PYBIND to csrc/include/rocm_ops.hpp treats line 2896 as end-of-file, but main has since appended GDR_DECODE_PACKED_BF16_PYBIND there and merged the Triton twin of this op in between — so the PR needs a rebase, and any green CI on it describes a tree that has moved. Author must rebase onto current main and re-run the suite before these findings are re-checked.
📝 [verified] Neither the wrapper nor the kernel bounds-checks indices: aiter/ops/fused_indexed_gated_residual.py validates shape, dtype, device and strides but not range, and the kernel computes gate + indices[r] * gate_stride unchecked — where the eager gate[indices] it replaces raises an index error, a negative or ≥ G index silently reads out of bounds and writes garbage. Author must validate the index range in the wrapper or document in-range indices as a caller contract.
📝 [verified] test_strided_and_unaligned_rows in op_tests/test_fused_indexed_gated_residual.py never hands the vectorized path a strided operand: the sliced x has row stride 3·640+1 = 1921, not a multiple of 8, so both offset cases take the scalar fallback — the vector path's address math for a strided-but-aligned row stride is untested, and a bug there passes the whole suite. Author must add a case whose row stride is a multiple of 8 but not N (e.g. a slice of a 2N-wide buffer).
out[m] = residual[m] + gate[indices[m]] * x[m] for fp32/fp16/bf16 rows: the gated residual add that closes an attention or MLP branch of a DiT block. One pass with 16-byte vector access (scalar fallback for unaligned or narrow rows); the gate table row is gathered per token instead of being materialised at [M, N]. round_intermediate=True matches the eager expression bit for bit. Torch-free module (aiter_tensor_t), JIT built with -ffp-contract=off and denormals kept, like torch. Signed-off-by: Sylvan Liu <[email protected]>
…nchmark - Accept bf16 only and drop the fp16/fp32 instantiations, so every accepted dtype is tested. - Reject CPU operands and operands on another device, in the wrapper (raises ValueError) and in the kernel entry. - Tests run bf16 only and cover the new checks. - Add op_tests/op_benchmarks/hip/bench_fused_indexed_gated_residual.py: fused against residual + gate[indices] * x. Signed-off-by: Sylvan Liu <[email protected]>
…, test strided vectorized rows
b1721e2 to
8df08be
Compare
|
Thanks for the review. I rebased onto current main and added one commit:
|
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
|
@Shan2L Two new findings from reviewing the latest revision (
|
…enchmark the eager-rounded path An out tensor whose rows overlap (e.g. torch.empty((1, N)).expand(M, N), row stride 0) passed validation, and rows then raced on the same addresses. Reject M > 1 with out.stride(0) < N before launch; padded row strides and exact in-place aliases stay valid. New test covers a broadcast and a short-stride output. The benchmark timed the op with the default round_intermediate=False against an eager baseline that rounds the product first. Pass round_intermediate=True, as described in the PR, and check that the output equals eager before timing.
|
Thanks @junhaha666, both points are right. Fixed in f80227c:
The merged Triton op (#6416) has the same missing overlap check, and its benchmark uses the same default rounding; I have a fix for both ready and can open it as a separate PR. |
An out tensor whose rows overlap (e.g. torch.empty((1, N)).expand(M, N), row stride 0) passed validation, and rows then raced on the same addresses. Reject M > 1 with out.stride(0) < N; padded row strides and exact in-place aliases stay valid. Found in review of the HIP version (ROCm#6417). Signed-off-by: Sylvan Liu <[email protected]>
An out tensor whose rows overlap (e.g. torch.empty((1, N)).expand(M, N), row stride 0) passed validation, and rows then raced on the same addresses. Reject M > 1 with out.stride(0) < N; padded row strides and exact in-place aliases stay valid. Found in review of the HIP version (ROCm#6417). Signed-off-by: Sylvan Liu <[email protected]>
|
@Shan2L Thanks for the implementation and for addressing the earlier review comments. I have two remaining suggestions before merging:
|
… test Drop the three exception-path tests; the wrapper keeps the validation, including the overlapping-output check. Running the op test as a script now also times the eager expression, this HIP op and the Triton op on the same inputs with round_intermediate=True, checks both against eager bit for bit, and prints a summary table. The standalone HIP benchmark is removed. Signed-off-by: Sylvan Liu <[email protected]>
|
@junhaha666 Thanks, both points are addressed in 70cd4a2. 1. Op tests. The HIP/Triton comparison is now part of the op test, so CI's 2. Why keep a HIP backend. Yes, the intended use is the torch-free C++/HIP path. The module is built with Performance is not the reason, and I agree it doesn't justify a general switch to HIP. One finding from the new comparison is worth separating out, though. On gfx1201 the merged Triton kernel is much slower than HIP at some row widths (HIP / Triton time at M = 16384, contiguous: N = 5376 0.955, N = 1536 0.54, N = 8192 0.23; N = 5376 with rows padded to N+8, M = 4096 to 113102: 0.69–0.79). The cause is the Triton kernel's grid, not anything HIP-specific: row blocks were the fastest grid index, so programs that run together read one 256-column stripe of many rows. Swapping that order brings Triton to 584–597 GB/s for every N from 1536 to 8192, against 597–610 GB/s for HIP. The fix is a separate PR, #8924. With it, the two backends are within 1–4% of each other on gfx1201 for contiguous and padded rows. The PR description now states the torch-free path as the benefit and includes these numbers. I have no MI hardware, so all timings are from gfx1201 (Radeon AI PRO R9700). |
|
@Shan2L need update branch to pass CI |
|
@junhaha666 Updated the branch with main (merge commit d3e7fb1, no conflicts). The reviewed revision in the description now points to it. |
Merge upstream main 7c0f525 and retain the paged MQA registration with new upstream operators, including fused_indexed_gated_residual (ROCm#6417). Keep the current header and JIT registrations outside this operator intact. Include ROCm#8790's MoE dispatch snapshot refresh, absent from the old head. The paged kernel, wrapper, runtime architecture gate, native ABI and op test are unchanged. CPU adapter checks (24), source/registration comparisons, Black 26.10.1, Ruff 0.16.0 and changed-line clang-format 18.1.8 passed. No new local GPU, ISA, model, benchmark or E2E run was performed. Co-authored-by: OpenAI Codex <[email protected]> Signed-off-by: Sumin Hong <[email protected]>
Motivation
A diffusion transformer block ends each attention and MLP branch with a gated residual add:
As with the AdaLN modulation at the start of the branch (
fused_rmsnorm_indexed_adaln, #4659), every token carries an index into a small table of gate vectors, one row per (modality, timestep) combination. In torch the expression is three memory-bound kernels plus two [M, N] temporaries: the gathered gate and the product.The Triton implementation of this op is already merged (#6416). This PR adds a HIP implementation with the same interface and results,
aiter.fused_indexed_gated_residual, for callers that cannot use the Triton one: it is a torch-free module that depends only on the HIP runtime. The kernel source compiles and runs from C++ withaiter_tensor_toperands and no Python, PyTorch or Triton (verified below). Performance is not the reason: once #8924 lands, the two implementations are within 1–4% of each other on gfx1201 for contiguous and padded rows (see Test Result).Technical Details
aiter_tensor_t,compile_ops(..., develop=True),torch_exclude):module_fused_indexed_gated_residual. Its only GPU-side dependency islibamdhip64; the C++ entry point is declared incsrc/include/fused_indexed_gated_residual.h.outmay aliasresidualorx, so the kernel uses no__restrict__on them.round_intermediate=Trueroundsgate * xto the output dtype before the add, as the eager expression does, and the result is then bit-identical to torch. The module is built with-ffp-contract=offand without denormal flushing, like torch's elementwise kernels, soround_intermediate=Falseis also exact against an fp32 reference.c10::BFloat16.ValueError, including anoutwhose rows overlap. The C++ checks stay as a backstop, butAITER_CHECKaborts in the pybind path.Test Plan
op_tests/test_fused_indexed_gated_residual.py. CI runs it aspython3 op_tests/test_fused_indexed_gated_residual.py, which runs the accuracy tests (pytest, 33 tests) and then times the eager expression, this HIP op and the Triton op on the same inputs:round_intermediate× 6 shapes, including a single token and N not a multiple of the vector width. Each shape runs with both run-of-index and scattered indices.round_intermediate=True, and against the fp32 reference without it.out=and in-placeout=residual.run_perftest): eager, HIP and Triton on the same operands withround_intermediate=True, each output checked against eager bit for bit (checkAllclosewithatol=rtol=0, thentorch.equal), for three operand layouts: contiguous, rows padded to N+8 (16-byte aligned, HIP vectorized path), and rows offset by one element with stride N+1 (HIP scalar path).-m,-n,-g,--layoutand--scatteredselect the cases; the default is N = 5376, M = 4096 / 16384 / 65536.Test Result
All 33 accuracy tests pass on gfx1201 (Radeon AI PRO R9700). No MI hardware was available to me, so gfx942/gfx950 coverage comes from CI.
Timing on gfx1201 from the op test (
python3 op_tests/test_fused_indexed_gated_residual.py, bf16, N = 5376, G = 9, run-of-index indices,round_intermediate=True; all outputs bit-identical to eager). Triton is the merged kernel on main:The gap at padded rows, and the much larger one at power-of-two row widths (contiguous N = 8192: HIP 1323.6 us vs Triton 5773.6 us at M = 16384), is not a property of the HIP kernel. The Triton kernel's grid made row blocks the fastest index, so programs that run together read one column stripe of many rows. #8924 makes column blocks the fastest index; with it, Triton runs at 584–597 GB/s at M = 16384 for N = 1536 to 8192 with contiguous rows and rows padded by 8 or 16 elements, against 597–610 GB/s for HIP. I did not time the fixed Triton kernel on the stride N+1 layout.
C++ without Python: a standalone program that includes only
csrc/include/fused_indexed_gated_residual.h, buildscsrc/kernels/fused_indexed_gated_residual.cuwithhipccand links nothing but the HIP runtime matched a host reference of the eager rounding exactly (0 mismatches at [4096, 5376], [1000, 5376] and [333, 320]).AI assistance: this change was developed with the help of an AI coding assistant (GitHub Copilot). All tests and timings above were run on the listed hardware.
PR Self-Review
Reviewed revision
d3e7fb1
Behavior and intent
Adds a new public op,
aiter.fused_indexed_gated_residual(HIP, JIT modulemodule_fused_indexed_gated_residual). It computesout[m] = residual[m] + gate[indices[m]] * x[m]in one pass. No existing kernel's behaviour changes. The Triton op with the same interface was merged in #6416. This PR adds a torch-free HIP version of it, callable from C++ throughaiter_tensor_t. With #8924, the two are within 1–4% of each other on gfx1201 for contiguous and padded rows, so this PR does not propose switching the default to HIP.Validation and unverified scope
rocm/pytorch:rocm10.1.0_ubuntu24.04_py3.12_pytorch_release_2.14.0,python3 op_tests/test_fused_indexed_gated_residual.py: 33 passed, then the timing table above, at d3e7fb1.x's row stride fails the two vectorized strided cases.torch.cuda.Eventtiming in alternating rounds; the HIP / Triton ratios agree within 2%.PR-specific question
GPU_ARCHSlists.ValueErrorin the Python wrapper, and the C++ side checks again withAITER_CHECK. Indices may be int32 or int64.ValueError, including anoutwhose rows overlap (M > 1 andout.stride(0) < N); padded row strides and the in-place aliasout=residualstay valid. The C++ entry point repeats the shape, dtype and stride checks as a backstop.Changed op tests
op_tests/test_fused_indexed_gated_residual.py(new): covers the new op.round_intermediate=True) and against an fp32 reference (False), across 6 shapes × run-of-index / scattered indices; includes M=1 and N not a multiple of 8, which forces the scalar path.out=and in-place updates, int32 indices, NaN/Inf/overflow, empty input.test_strided_rows).No existing test covers this op, so it is not redundant.