Skip to content

[HIP] [JIT] Add fused_indexed_gated_residual for diffusion transformer blocks - #6417

Merged
junhaha666 merged 6 commits into
ROCm:mainfrom
Shan2L:hip/fused-indexed-gated-residual
Dec 3, 2026
Merged

junhaha666 merged 6 commits into
ROCm:mainfrom
Shan2L:hip/fused-indexed-gated-residual

Conversation

@Shan2L

@Shan2L Shan2L commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

A diffusion transformer block ends each attention and MLP branch with a gated residual add:

out[m] = residual[m] + gate[indices[m]] * x[m]

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++ with aiter_tensor_t operands 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

  • Torch-free module (aiter_tensor_t, compile_ops(..., develop=True), torch_exclude): module_fused_indexed_gated_residual. Its only GPU-side dependency is libamdhip64; the C++ entry point is declared in csrc/include/fused_indexed_gated_residual.h.
  • One thread handles 16 bytes of a row (8 bf16 values) with vector loads and stores. Rows that are narrow, misaligned or have unaligned strides fall back to a scalar path.
  • The gate row is read per token straight from the table, which stays in cache; it is never materialised.
  • Rows may be strided (only unit stride along N is required).
  • out may alias residual or x, so the kernel uses no __restrict__ on them.
  • Offsets are 64-bit.
  • The math is done in fp32. round_intermediate=True rounds gate * x to 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=off and without denormal flushing, like torch's elementwise kernels, so round_intermediate=False is also exact against an fp32 reference.
  • bf16 rounding is round-to-nearest-even, and NaN becomes the canonical quiet NaN, as in c10::BFloat16.
  • Supported dtype: bf16, the one the tests cover. Indices: int32 or int64.
  • All operands must be GPU tensors on one device.
  • Inputs are validated in Python and raise ValueError, including an out whose rows overlap. The C++ checks stay as a backstop, but AITER_CHECK aborts in the pybind path.

Test Plan

op_tests/test_fused_indexed_gated_residual.py. CI runs it as python3 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:

  • bf16 × 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.
  • Bit-exact checks: against the eager torch expression with round_intermediate=True, and against the fp32 reference without it.
  • One row per table entry.
  • out= and in-place out=residual.
  • Strided rows: every operand a view into a wider buffer, with row stride 2N+8 (vectorized path) at column offsets 0 and 8, and an odd stride/offset that breaks 16-byte alignment and must take the scalar path.
  • int32 indices.
  • NaN/Inf/overflow inputs match eager.
  • Empty input.
  • Timing (run_perftest): eager, HIP and Triton on the same operands with round_intermediate=True, each output checked against eager bit for bit (checkAllclose with atol=rtol=0, then torch.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, --layout and --scattered select 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:

M layout eager HIP Triton (main) HIP / Triton
16384 contiguous 2055.8 us 867.0 us 907.7 us 0.955
16384 rows padded to N+8 2058.4 us 871.4 us 1133.5 us 0.769
16384 stride N+1, offset 1 2397.4 us 1035.9 us 1209.8 us 0.856
65536 contiguous 8154.4 us 3496.5 us 3628.8 us 0.964
65536 rows padded to N+8 8134.7 us 3507.2 us 4832.3 us 0.726
65536 stride N+1, offset 1 9621.9 us 4424.9 us 5243.6 us 0.844

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, builds csrc/kernels/fused_indexed_gated_residual.cu with hipcc and 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 module module_fused_indexed_gated_residual). It computes out[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++ through aiter_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

  • Validated on gfx1201 (Radeon AI PRO R9700), image 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.
  • Mutation checks (earlier revision, same tests): making the vectorized path ignore x's row stride fails the two vectorized strided cases.
  • The op-test timings were cross-checked with torch.cuda.Event timing in alternating rounds; the HIP / Triton ratios agree within 2%.
  • C++-only build and run as described in Test Result.
  • Unverified: gfx942 / gfx950 correctness beyond CI, and any timing on MI hardware (none available to me). Out-of-range indices are not checked; see the next section.

PR-specific question

  • Architecture: arch-neutral HIP (no arch-specific instructions); built for whatever GPU_ARCHS lists.
  • Dtype: bf16 only. Other dtypes raise ValueError in the Python wrapper, and the C++ side checks again with AITER_CHECK. Indices may be int32 or int64.
  • Shape and path selection:
    • Vectorized path (16 bytes = 8 bf16 per thread): taken only when N % 8 == 0, every row stride is a multiple of 8, and every base pointer is 16-byte aligned.
    • Scalar path: everything else.
    • Required for both: unit stride along N, contiguous indices, all operands on one device.
    • Offsets are 64-bit.
  • Invariant against unsupported inputs: the wrapper validates rank, shape, dtype, device and strides before launch and raises ValueError, including an out whose rows overlap (M > 1 and out.stride(0) < N); padded row strides and the in-place alias out=residual stay valid. The C++ entry point repeats the shape, dtype and stride checks as a backstop.
  • Caller contract: every index must lie in [0, G). This is documented, not checked, because a check needs a device-to-host sync on every call and breaks graph capture. The merged Triton op behaves the same way.

Changed op tests

  • op_tests/test_fused_indexed_gated_residual.py (new): covers the new op.

    • Bit-exact against eager torch (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.
    • Vectorized and scalar strided views (test_strided_rows).
    • As a script, it also times eager, HIP and Triton on the same inputs and rounding, for contiguous, padded and unaligned rows. This replaces the standalone HIP benchmark of the earlier revision.

    No existing test covers this op, so it is not redundant.

@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 (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 6417 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

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 stop the title rewrites; labels stay in sync either way.

@github-actions github-actions Bot changed the title [HIP] Add fused_indexed_gated_residual for diffusion transformer blocks [HIP] [JIT] Add fused_indexed_gated_residual for diffusion transformer blocks Oct 12, 2026
@zufayu
zufayu requested a review from junhaha666 October 13, 2026 01:41
@Shan2L

Shan2L commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@junhaha666, the Triton implementation (#6416) was merged yesterday. Is the HIP implementation in this PR still wanted? It has the same interface and, with round_intermediate=True, is bit-identical to torch. It still merges cleanly into main.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 5, 2026
@Shan2L

Shan2L commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Hi @junhaha666 Soft reminder, could you please take you time to give a look at this PR? Thanks very much. ^ ^

@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 6, 2026
@Shan2L

Shan2L commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

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.

@junhaha666

Copy link
Copy Markdown
Contributor

@aiter-bot review

@aiter-bot

Copy link
Copy Markdown

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 aiter-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ROCm/aiter PR #6417 — [HIP] [JIT] Add fused_indexed_gated_residual for diffusion transformer blocks

Review (advisory): ⚠️ NEEDS WORK
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

⚠️ [verified] The diff no longer applies to the merge target: the hunk appending 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] Every timing in the PR is author-run on gfx1201 (Radeon AI PRO R9700) against the eager expression, and no measurement of csrc/kernels/fused_indexed_gated_residual.cu exists on gfx942 or gfx950 — the archs CI tests and the archs a MiniMax-H3 block actually runs on; the perf stage could not run (the triaged target exposes no benchmark entry point) and this box could not hand-run the standalone bench, so the 2.31–2.37x claim is unmeasured on every target arch. Author must land a gfx942/gfx950 timing of op_tests/op_benchmarks/hip/bench_fused_indexed_gated_residual.py (CI run or maintainer box) before merge.

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

Shan2L and others added 3 commits November 25, 2026 09:44
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]>
@Shan2L
Shan2L force-pushed the hip/fused-indexed-gated-residual branch from b1721e2 to 8df08be Compare November 25, 2026 01:53
@Shan2L

Shan2L commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I rebased onto current main and added one commit:

  1. Rebase: the only conflict was in csrc/include/rocm_ops.hpp. FUSED_INDEXED_GATED_RESIDUAL_PYBIND now comes after GDR_DECODE_PACKED_BF16_PYBIND. All 35 tests in op_tests/test_fused_indexed_gated_residual.py pass on gfx1201 (Radeon AI PRO R9700).

  2. Index range: the docstring now states that every index must be in [0, G) and that the caller is responsible for this. The merged Triton version ([Triton/Gluon] Add fused_indexed_gated_residual for diffusion transformer blocks #6416) behaves the same way. A range check in the wrapper would force a device-to-host sync on every call and would break graph capture.

  3. Strided vectorized rows: test_strided_and_unaligned_rows is replaced by test_strided_rows, where every operand is a view into a wider buffer:

    • row stride 2N+8 (a multiple of 8 but not of N) at column offsets 0 and 8, which runs the vectorized path;
    • odd stride and offset, which runs the scalar path.

    To check that the new cases test the right thing, I broke the vectorized path on purpose so that it ignores x's row stride. The two new vectorized cases failed and the old test still passed.

  4. gfx942 / gfx950 timing: I don't have MI hardware. Could a maintainer run python3 op_tests/op_benchmarks/hip/bench_fused_indexed_gated_residual.py on an MI box, or tell me which CI label covers this?

  5. Two backends: I measured this HIP kernel against the merged Triton kernel in the same process on gfx1201 (N=5376, G=9, round_intermediate=True, best of 3 interleaved rounds):

    M HIP (us) Triton (us) HIP / Triton bitwise equal
    114660 6135 6349 0.966 yes
    57330 3142 3187 0.986 yes
    28665 1531 1591 0.962 yes
    14333 770 804 0.958 yes
    4144 223 233 0.957 yes

    Scattered indices give the same ratios (0.957–0.965). Both kernels reach about 600 of 640 GB/s, so the HIP version is only 1.5–4% faster. If you would rather keep one implementation, I'm happy to close this PR and leave Triton as the only one. If a torch-free HIP path is useful to you, I can instead move it behind a backend= argument, as mhc_fused_post_pre does, so that aiter.fused_indexed_gated_residual no longer means "HIP on every arch". Please let me know which you prefer.

@aiter-bot

aiter-bot commented Nov 25, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision d3e7fb1b363e · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

Adds a new public op, `aiter.fused_indexed_gated_residual` (HIP, JIT module `module_fused_indexed_gated_residual`). It computes `out[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++ through `aiter_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

- Validated on gfx1201 (Radeon AI PRO R9700), image `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 d3e7fb1b.
- Mutation checks (earlier revision, same tests): making the vectorized path ignore `x`'s row stride fails the two vectorized strided cases.
- The op-test timings were cross-checked with `torch.cuda.Event` timing in alternating rounds; the HIP / Triton ratios agree within 2%.
- C++-only build and run as described in Test Result.
- Unverified: gfx942 / gfx950 correctness beyond CI, and any timing on MI hardware (none available to me). Out-of-range indices are not checked; see the next section.

PR-specific question

- Architecture: arch-neutral HIP (no arch-specific instructions); built for whatever `GPU_ARCHS` lists.
- Dtype: bf16 only. Other dtypes raise `ValueError` in the Python wrapper, and the C++ side checks again with `AITER_CHECK`. Indices may be int32 or int64.
- Shape and path selection:
  - Vectorized path (16 bytes = 8 bf16 per thread): taken only when N % 8 == 0, every row stride is a multiple of 8, and every base pointer is 16-byte aligned.
  - Scalar path: everything else.
  - Required for both: unit stride along N, contiguous indices, all operands on one device.
  - Offsets are 64-bit.
- Invariant against unsupported inputs: the wrapper validates rank, shape, dtype, device and strides before launch and raises `ValueError`, including an `out` whose rows overlap (M > 1 and `out.stride(0) < N`); padded row strides and the in-place alias `out=residual` stay valid. The C++ entry point repeats the shape, dtype and stride checks as a backstop.
- Caller contract: every index must lie in [0, G). This is documented, not checked, because a check needs a device-to-host sync on every call and breaks graph capture. The merged Triton op behaves the same way.

Changed op tests

- `op_tests/test_fused_indexed_gated_residual.py` (new): covers the new op.
  - Bit-exact against eager torch (`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.
  - Vectorized and scalar strided views (`test_strided_rows`).
  - As a script, it also times eager, HIP and Triton on the same inputs and rounding, for contiguous, padded and unaligned rows. This replaces the standalone HIP benchmark of the earlier revision.

  No existing test covers this op, so it is not redundant.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@junhaha666

junhaha666 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

@Shan2L Two new findings from reviewing the latest revision (8df08be1f), separate from the issues already discussed:

  1. Reject internally overlapping output rows.

    An output created with torch.empty((1, N), ...).expand(M, N) has stride (0, 1) and currently passes validation. Multiple rows then write to the same addresses. I reproduced incorrect and nondeterministic results on gfx950 in both scalar and vectorized paths.

    Please reject overlapping output rows before launch (e.g. M > 1, N > 0, and out.stride(0) < N) and add a rejection test, while retaining valid padded row strides and exact in-place aliases.

  2. Use consistent rounding in the benchmark.

    bench_fused_indexed_gated_residual.py calls the HIP op with the default round_intermediate=False, whereas the eager baseline rounds the product to BF16 before the add. This differs from the benchmark configuration described in the PR.

    Please explicitly pass round_intermediate=True and check output equality before timing. On gfx950, a 512 × 5376 case had 355,756 elements differing from eager with the default setting; with True, the outputs matched exactly.

…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.
@Shan2L

Shan2L commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @junhaha666, both points are right. Fixed in f80227c:

  1. Overlapping output rows. The wrapper now rejects out when M > 1, N > 0 and out.stride(0) < N, before launch. Padded row strides and the exact in-place alias out=residual are still accepted and still covered by test_strided_rows and test_out_parameter_and_in_place_update. The new test_rejects_overlapping_output_rows covers a broadcast output (torch.empty((1, N)).expand(M, N), row stride 0) and a short row stride (N // 2). Removing the check makes exactly that test fail; the suite is 36 passed on gfx1201.

  2. Benchmark rounding. bench_fused_indexed_gated_residual.py now calls the op with round_intermediate=True and checks torch.equal against the eager expression before timing, exiting if they differ. Re-run on gfx1201 (R9700), run-of-index and scattered indices: all sizes bit-identical to eager, and the timings are within 1% of the previous table (114660 x 5376: 6.15 ms vs 14.27 ms eager, 2.32x; 14333 x 5376: 0.77 ms vs 1.83 ms, 2.37x). The table in the description now shows these numbers.

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.

@Shan2L

Shan2L commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

The same two fixes for the merged Triton op (#6416) are in #8681: it rejects overlapping output rows, and the benchmark now uses round_intermediate=True with an equality check against eager before timing.

Shan2L added a commit to Shan2L/aiter that referenced this pull request Nov 26, 2026
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 added a commit to Shan2L/aiter that referenced this pull request Nov 26, 2026
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]>
@junhaha666

Copy link
Copy Markdown
Contributor

@Shan2L Thanks for the implementation and for addressing the earlier review comments. I have two remaining suggestions before merging:

  1. Keep the op tests focused on GPU accuracy and performance.

    Please remove the three exception-path tests in op_tests/test_fused_indexed_gated_residual.py: test_rejects_mismatched_inputs, test_rejects_unsupported_dtypes_and_devices, and test_rejects_overlapping_output_rows. Keep the runtime validation, including the overlapping-output check, and retain the GPU accuracy coverage.

    Please also integrate the HIP/Triton performance comparison into the repository's standard op-test/benchmark workflow so that both implementations can be evaluated with the same inputs and rounding semantics.

  2. Clarify the reason for maintaining an additional HIP backend.

    A torch-free C++/HIP execution path could be a useful reason to retain this implementation. Could you clarify whether that is the intended use case? If the main motivation is performance, the current measurements do not show a consistent advantage over the existing Triton implementation across shapes and layouts, so they do not yet support a general switch to HIP.

    Please make the intended benefit explicit in the PR description.

… 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]>
@Shan2L

Shan2L commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@junhaha666 Thanks, both points are addressed in 70cd4a2.

1. Op tests. test_rejects_mismatched_inputs, test_rejects_unsupported_dtypes_and_devices and test_rejects_overlapping_output_rows are removed; the wrapper keeps all of that validation, including the overlap check. The GPU accuracy tests are unchanged (33 pass on gfx1201).

The HIP/Triton comparison is now part of the op test, so CI's python3 op_tests/test_fused_indexed_gated_residual.py runs it after the accuracy tests. It times eager, HIP and Triton with run_perftest on the same operands and with round_intermediate=True, checks both outputs against eager bit for bit (checkAllclose with atol=rtol=0), and prints a summary table. It covers three layouts: contiguous rows, rows padded to N+8, and rows with stride N+1 at offset 1. -m, -n, -g, --layout and --scattered select the cases. The standalone op_tests/op_benchmarks/hip/bench_fused_indexed_gated_residual.py is removed.

2. Why keep a HIP backend. Yes, the intended use is the torch-free C++/HIP path. The module is built with torch_exclude and its only GPU-side dependency is libamdhip64. I checked that it is usable without Python: a standalone C++ program that includes csrc/include/fused_indexed_gated_residual.h and compiles csrc/kernels/fused_indexed_gated_residual.cu with hipcc, with no Python, PyTorch or Triton, matches a host reference of the eager rounding exactly. I don't know of an in-tree C++ caller today, so whether that is worth a second backend is your call.

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

@junhaha666

Copy link
Copy Markdown
Contributor

@Shan2L need update branch to pass CI

@Shan2L

Shan2L commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@junhaha666 Updated the branch with main (merge commit d3e7fb1, no conflicts). The reviewed revision in the description now points to it.

@junhaha666
junhaha666 merged commit e50914d into ROCm:main Dec 3, 2026
75 of 76 checks passed
sumin-hong added a commit to moreh-dev/rocm-aiter that referenced this pull request Dec 3, 2026
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]>
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.

3 participants