Skip to content

[Triton/Gluon] Add fused_indexed_gated_residual for diffusion transformer blocks - #6416

Merged
azaidy merged 3 commits into
ROCm:mainfrom
Shan2L:triton/fused-indexed-gated-residual
Oct 19, 2026
Merged

azaidy merged 3 commits into
ROCm:mainfrom
Shan2L:triton/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, every token carries an index into a small table of gate vectors, one row per (modality, timestep) combination. #4659 added fused_rmsnorm_indexed_adaln for the opening step; this PR adds the matching closing step, fused_indexed_gated_residual.

In torch the expression is three kernels: gate[indices] is gathered and materialised at [M, N], multiplied by x (another [M, N] temporary), then added to residual. It is memory bound, and most of its traffic is temporaries the math does not need.

Technical Details

  • One program owns a [BLOCK_M, BLOCK_N] tile; residual and x are read once and out is written once.
  • The gate row is gathered per token from the table, which stays in cache. When every row of a block shares one index (the usual case: packed sequences are laid out in runs of one modality), a single [BLOCK_N] row is loaded and broadcast instead of a [BLOCK_M, BLOCK_N] gather. This is the same trick as in fused_rmsnorm_indexed_adaln.
  • Rows may be strided, so x can be a column slice of a fused projection; only unit stride along N is required.
  • out may be residual, giving an in-place update of the residual stream.
  • Offsets are 64-bit, because M * N passes 2^31 for long video sequences.
  • The math is done in fp32. round_intermediate=True rounds gate * x to the output dtype before the add, as the unfused expression does. The result is then bit-identical to residual + gate[indices] * x in eager torch. The launch disables fp fusion; otherwise the compiler can contract the rounded product back into an FMA and silently drop that rounding (seen on gfx1201).
  • Supported dtypes: bf16, fp16 and fp32. Indices: int32 or int64.

Test Plan

op_tests/triton_tests/fusions/test_fused_indexed_gated_residual.py, 91 tests:

  • bf16/fp16/fp32 × round_intermediate × 7 shapes, including a single token, fewer rows than BLOCK_M, N not a multiple of BLOCK_N, and a row narrower than one tile. Each shape runs with both run-of-index and scattered indices.
  • round_intermediate=True is checked bit-exact against the eager torch expression.
  • The uniform-index broadcast branch and the gather branch must agree bit for bit. Two identical table rows reach the same gate both ways.
  • One row per table entry, so a kernel that broadcast row 0 would fail.
  • out= and in-place out=residual.
  • Strided rows.
  • int32 indices.
  • Shape and dtype rejections.

Test Result

All 91 pass on gfx1201 (Radeon AI PRO R9700). No MI hardware was available to me, so gfx942/gfx950 coverage comes from CI.

Timing on gfx1201, bf16, at MiniMax-H3 shapes (N = 5376, a 9-row gate table, round_intermediate=True). M is the token count per rank at Ulysses 1/2/4/8 for a 15 s, 1344x768 clip.

M x N torch residual + gate[idx] * x fused speedup effective bandwidth
114660 x 5376 14.26 ms 6.33 ms 2.25x 584 GB/s
57330 x 5376 7.17 ms 3.17 ms 2.26x 583 GB/s
28665 x 5376 3.61 ms 1.59 ms 2.27x 582 GB/s
14333 x 5376 1.82 ms 0.80 ms 2.28x 578 GB/s

The fused output is bit-identical to the torch expression at every size. Effective bandwidth counts 3 x M x N x 2 bytes, against a 640 GB/s peak.

A HIP implementation of the same op, with the same interface and results, is #6417 (one backend per PR).

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.

…rmer blocks

out[m] = residual[m] + gate[indices[m]] * x[m]: the gated residual add that
closes an attention or MLP branch of a DiT block, the counterpart of
fused_rmsnorm_indexed_adaln. The gate table row is gathered per token (or
broadcast when a block of tokens shares an index) instead of being
materialised at [M, N], and the product is not written and re-read.
round_intermediate=True reproduces the eager expression bit for bit.

Signed-off-by: Sylvan Liu <[email protected]>
@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 6416 --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.

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.

🟡 Changes recommended

Unsupported inputs are insufficiently validated, tuning is hardcoded, and the required benchmark is missing.

4 open findings
What changed in this PR

Adds a memory-efficient Triton kernel for indexed gated residual updates in diffusion transformer blocks.

Changes:

  • Adds the fused kernel and public wrapper.
  • Covers dtype, shape, indexing, striding, rounding, and in-place scenarios.
File Description
aiter/​ops/​triton/​fusions/​fused_indexed_gated_residual.py Validates inputs and launches the kernel.
aiter/​ops/​triton/​_triton_kernels/​fusions/​fused_indexed_gated_residual.py Implements fused indexed gating and residual addition.
op_tests/​triton_tests/​fusions/​test_fused_indexed_gated_residual.py Adds correctness and API tests.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@vgokhale vgokhale 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.

Review: PR #6416 — fused_indexed_gated_residual

The kernel is well built. It computes out[m] = residual[m] + gate[indices[m]] * x[m] in one pass, with a repr, an int64 guard on the flattened index, a uniform-index broadcast fast path, and a round_intermediate option that matches the unfused rounding. The tests are well anchored: an independent reference, a test that the uniform fast path equals the scattered path, a test that every index is honoured, and an out=/in-place test. Comments are short.

Three points before merge.

1. Rule 6: share the indexed-gather with the sibling kernel

This kernel re-implements the per-token table gather that fused_rmsnorm_indexed_adaln already has, in the same fusions/ directory. The copied parts are the first-row fill for masked lanes (first = tl.load(idx_ptr + row_block * BLOCK_M), then other=first) and the uniform-index broadcast (tl.min(idx) == tl.max(idx) collapses the [BLOCK_M, BLOCK_N] gather to one row). Both kernels have this code.

These two are the open and close halves of the same diffusion-transformer block, so they will stay paired. Please factor the per-token indexed gather (with the uniform-broadcast fast path) into one shared Triton device helper, and call it from both fused_rmsnorm_indexed_adaln and this kernel. The gate/residual math stays here; only the gather moves to the helper.

2. Rule 3: add a benchmark

There is no benchmark. The whole point of this kernel is to save bandwidth by fusing the gather, the multiply, and the add. Please add bench_fused_indexed_gated_residual.py and report the fused time against the unfused residual + gate[indices] * x (the gather materialised at [M, N], product written and re-read), so the saving is measured, not assumed.

3. Test dtypes: drop fp16, and fp32 unless it is the reference

The dtype parameter is [torch.bfloat16, torch.float16, torch.float32]. aiter targets bf16; fp16 is not a target, so please remove it. Keep fp32 only if the test uses it as the high-precision reference; if it is tested as a production output dtype, drop it too. bf16 is the one to keep.

Summary

Good kernel: correct math, repr, int64 guard, the uniform fast path, and a test that pins it. Not a duplicate — no existing kernel does residual + gate[idx] * x. Before merge: factor the indexed gather into a shared helper with fused_rmsnorm_indexed_adaln (rule 6), add a benchmark (rule 3), and drop fp16 (and fp32 unless it is the reference) from the test.

@zufayu
zufayu requested review from a team and Boss2002n October 13, 2026 01:41
… tiles to config, add benchmark

- Factor the per-token table gather and its uniform-index broadcast into
  _triton_kernels/fusions/indexed_table.py and call it from both
  fused_rmsnorm_indexed_adaln and fused_indexed_gated_residual. Both kernels
  give bit-identical output before and after.
- Move BLOCK_M, BLOCK_N and num_warps into
  configs/<arch>/triton/fusions/fused_indexed_gated_residual/DEFAULT.json for
  gfx942, gfx950 and gfx1201; gfx1250 is seeded byte-identical from gfx950.
  The values are the previous Python constants.
- Validate the residual dtype (bf16/fp16/fp32), the gate dtype, and that all
  operands are CUDA tensors on one device.
- Tests run bf16 only and cover the new checks.
- Add bench_fused_indexed_gated_residual.py: fused against
  residual + gate[indices] * x.

Signed-off-by: Sylvan Liu <[email protected]>
@Shan2L

Shan2L commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@vgokhale Thanks for the review. Addressed in 9bd5ac8:

  1. The per-token gather now lives in _triton_kernels/fusions/indexed_table.py: _load_block_indices (first-row fill for tail lanes and the uniform check) and _gather_indexed_rows (one broadcast row when the block is uniform, a [BLOCK_M, BLOCK_N] gather otherwise). Both fused_rmsnorm_indexed_adaln and this kernel call it. Both kernels give bit-identical output to before on 12 shapes, and both test files pass.

  2. Added op_tests/op_benchmarks/triton/bench_fused_indexed_gated_residual.py, fused against residual + gate[indices] * x. bf16, N = 5376 (MiniMax-H3), gfx1201:

    M fused (us) eager (us) speedup
    1024 130 146 1.12x
    4096 395 603 1.53x
    16384 1088 2176 2.00x
    57330 3343 7260 2.17x
    114660 6506 14343 2.20x

    At 114660 rows the fused kernel reaches 568 GB/s over its 3 arrays; eager runs at 602 GB/s but moves 7. Scattered indices give the same times.

  3. Tests are bf16 only now; test_every_index_is_honoured moved from fp32 to bf16 as well.

The tests cover bf16 only, so reject the other dtypes instead of accepting
untested ones.

Signed-off-by: Sylvan Liu <[email protected]>
@Shan2L

Shan2L commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Can this PR be merged now? Thanks!

@Shan2L

Shan2L commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

The two failing Triton shards (3 and 7) timed out during pip install before any test ran. Could someone re-run them? Thanks!

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