Skip to content

[ROCm][inductor] gfx1250 TDM support for flex attention forward and decode - #197329

Closed
glen-amd wants to merge 3 commits into
pytorch:mainfrom
glen-amd:tdm/split-pr3
Closed

glen-amd wants to merge 3 commits into
pytorch:mainfrom
glen-amd:tdm/split-pr3

Conversation

@glen-amd

@glen-amd glen-amd commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Third of the gfx1250 Tensor Data Mover series, after #191166 (dense mm/addmm)
and #196525 (generic descriptor codegen).

Selects TDM descriptors for the FlexAttention forward and decode kernels on
gfx1250. It reuses the existing USE_TMA kernel option rather than adding an
AMD-specific switch, because both backends render the same descriptor branch of
the templates.

USE_TMA gfx1250 forward/decode
omitted descriptors when the capability, dtype, layout and block checks pass
False pointer path
True descriptors, still subject to those checks; falls back when ineligible

CUDA and XPU behavior is unchanged, and backward is untouched. The operand
policy shared with the dense MM path is factored into
_tdm_operand_policy_violation; rank, orientation, block rules and hint
preparation stay with each caller, so the flex gate keeps proving alignment
symbolically while dense MM keeps its hint-based admission and exact guards.

Test plan: the host-side gate tests pass. All device paths are unrun —
TestFlexAttentionTDMEndToEnd requires gfx1250, and the CUDA/XPU selection test
requires a TMA-capable device. The commit message records the exact commands and
limitations.

Generated and cross-reviewed with Claude Opus 5 and GPT-6 Astra.

🤖 Generated with Claude Code

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben

…ecode

Select AMD tensor-data-mover descriptors for the FlexAttention forward and
decode kernels on gfx1250. This reuses the existing USE_TMA kernel option
rather than adding an AMD-specific switch, because both backends render the
same descriptor branch of the templates. Descriptors are chosen automatically
when the capability, dtype, layout and block checks pass; an explicit
USE_TMA=False still forces the pointer path, and an explicit True that fails
the NVIDIA TMA check remains eligible for the TDM check. Backward is unchanged.

Review torch/_inductor/utils.py first: it adds use_flex_tdm_descriptor and
factors the operand policy it shares with the dense MM path into
_tdm_operand_policy_violation, leaving rank, orientation, block rules and hint
preparation with each caller. The two flex lowerings then consume it, and the
option documentation and tests follow.

The flex gate proves alignment symbolically instead of resolving hints, so it
installs no layout guards and needs no commitment phase; the dense MM path
keeps its hint-based admission and exact guards.

Test Plan:

The four host-side gate tests pass. This checkout is not built, so they were
run by splicing the diff's helpers onto an installed CPU wheel
(torch 2.14.0+cu130) rather than through the test runner. The equivalent
invocation is:

```
python test/run_test.py --include inductor/test_flex_attention \
  -k TestFlexAttentionTDMOptions
```

A negative control that splices the parent commit instead fails all four,
confirming the tests bind to this change. The dense TDM host tests produce an
identical pass/error set before and after the shared-policy refactor.

NOT RUN: every device path. TestFlexAttentionTDMEndToEnd requires gfx1250, and
test_tma_with_customer_kernel_options_selection requires a TMA-capable CUDA or
XPU device. Neither lintrunner nor spin was available in this environment; only
the repository-pinned ruff 0.14.4 was run over the five changed files.

This change was authored with the assistance of an AI coding agent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197329

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (4 Unrelated Failures)

As of commit 3e3e37e with merge base e89334f (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: inductor module: rocm AMD GPU support for Pytorch labels Sep 16, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Sep 16, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@glen-amd
glen-amd marked this pull request as ready for review September 16, 2026 22:27
@glen-amd
glen-amd requested a review from drisspg as a code owner September 16, 2026 22:27
@glen-amd

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "ciflow/trunk" "ciflow/pull" "ciflow/h100" "ciflow/b200" "ciflow/xpu" "ciflow/rocm" "ciflow/rocm-mi300" "ciflow/inductor-rocm" "release notes: rocm"

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

The ciflow label(s) ciflow/trunk, ciflow/pull, ciflow/h100, ciflow/b200, ciflow/xpu, ciflow/rocm, ciflow/rocm-mi300, ciflow/inductor-rocm will be added, but CI won't be triggered until the workflows are approved (scroll to the bottom of this page).

Please ping one of the reviewers if you do not have access to approve and run workflows.

@pytorch-bot pytorch-bot Bot added ciflow/b200 ciflow/h100 ciflow/inductor-rocm Trigger "inductor" config CI on ROCm ciflow/pull ciflow/rocm ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/trunk Trigger trunk jobs on your pull request ciflow/xpu Run XPU CI tasks release notes: rocm mandatorylabel labels Sep 17, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

Unknown label ciflow/inductor-rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/rocm-rx7900
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

Unknown label ciflow/rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/rocm-rx7900
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

@jeffdaily jeffdaily left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for splitting this out. I read the whole diff and ran what I could locally. Two things up front so they are not lost in the list: I am fine with the fact that we have no gfx1250 in CI and that the device tests cannot run there, and I am taking your word that you exercised them on hardware. Everything below is from reading the code, plus a few things I checked on a gfx90a ROCm 7.14 box.

What I confirmed locally: the four TestFlexAttentionTDMOptions tests pass through the real test runner on a ROCm build (4 passed in 3.27s), and with _gfx1250_device_prereqs forced true the gate wiring from both lowerings is correct, block shapes and all: fp16 head_dim 64 admitted as [(128,64),(64,64),(64,64)], head_dim 33 and head_dim 32 rejected, fp32 head_dim 64 admitted, decode admitted as [(64,64),(64,64)].

Blocking

1. USE_TMA falsy values other than False now select descriptors. flex_attention.py:500 and flex_decoding.py:408 use tma_requested is not False, which is identity against the False singleton, so anything else falsy falls through to the TDM gate. I confirmed this by recording gate calls through a real torch.compile:

kernel_options TDM gate consulted
{} 1
{"USE_TMA": False} 0
{"USE_TMA": 0} 1
{"USE_TMA": None} 1
{"USE_TMA": True} 1

Nothing coerces the value on the way in: _apply_kernel_options only copies the dict and validates BACKEND, and _sanitize_kernel_options_for_triton only pops BACKEND. NotRequired[bool] is not enforced at runtime. On main, USE_TMA=0 reached the Jinja {%- if USE_TMA %} and got the pointer path; with this change, on gfx1250, someone writing 0 to turn descriptors off turns them on. The new docstring also says "Setting False forces the pointer path", which is only true for the singleton. Please switch to a truthiness test (if tma_requested is None or tma_requested:) and add a falsy-non-False row to the option matrix; neither the TDM matrix nor the new CUDA one covers it today.

2. The gate drops can_use_tma's innermost-extent rule, and a test depends on that. can_use_tma requires sizes[-1] * itemsize % 16 == 0 (utils.py:2388-2391); use_flex_tdm_descriptor never constrains sizes[-1] at all, and the rules block at utils.py:465-480 does not explain the omission. _head_dim_tail builds head_dim 65, a 130-byte declared extent, and test_tdm_flex_padded_head_dim_correctness_and_selection asserts the descriptor path is taken. I confirmed the gate does admit it, with a 128-element block over a 65-element extent. That matters because the descriptor branch has no equivalent of load_checked_2d's other=0.0 (templates/utilities.py.jinja:53-56) and qk = tl.dot(q, k) reduces over the full QK_HEAD_DIM_ROUNDED, so a non-zero overhang corrupts every score, not just the masked ones. Head_dim 96 already exercises block overhang under TMA; a 130-byte extent is specifically what can_use_tma would refuse. Can you point at where TDM permits a non-16-byte-multiple innermost extent, or otherwise add the rule?

Should fix

3. can_use_tma is consulted before the TDM branch and can bypass it. has_triton_tma_device() puts its HIP exclusion only inside the CUDA arm; has_triton_cpu_backend() is a separate disjunct. On a gfx1250 host with a Triton build that registers the cpu backend, can_use_tma can return True, USE_TMA gets set under NVIDIA's rules, and use_flex_tdm_descriptor is never reached, so the ROCm 7.14 floor, the amd.supports_tdm probe and the 128-byte policy are all skipped. Your own comment above test_tma_with_customer_kernel_options_selection documents exactly this aggregate for test gating. A stock ROCm build reports backends ['amd', 'nvidia'], so this is unlikely in practice, but checking _gfx1250_device_prereqs first is cheap and matches the reasoning you already wrote down.

4. Forward and decode disagree on where the gate runs. Forward calls it at flex_attention.py:501, before the SPARSE_*_BLOCK_SIZE % BLOCK_* continue at :540; decode calls it at flex_decoding.py:409, after the equivalent continue at :388. Since the gate ends in _descriptor_shapes_fit_in_int32(..., add_guards=True), the forward can install an Le(size, int32_max) guard and bump symbol_guard_counter on a dynamic-shape graph where every config is then discarded. It is one bound rather than a specialization, so the impact is small, but decode has it right; please make forward match.

5. No config gate. use_flex_tdm_descriptor gates only on _gfx1250_device_prereqs, while the two sibling gates in this series each sit behind a config flag (config.triton.enable_persistent_tma_matmul, and config.triton.use_tensor_descriptor plus config.assume_aligned_inputs). I understand the argument in the test comment that capability is the only enablement boundary, but a caller that does not own the flex_attention call site has no supported way to force the pointer path, and per item 1 USE_TMA=0 is not that way either. A config.triton flag also gives us a one-line lever when something regresses on gfx1250 and we are debugging at a distance.

6. only_for=("cuda",) disappears silently off CUDA. At test_flex_attention.py:11381 this is hardcoded where the four neighbouring calls pass test_device. On a CPU-only, XPU-only or MPS-only build the base list is empty, so no class is generated and instantiate_device_type_tests deletes the generic class and its methods: zero tests, and no skipped record in the report XML. With only_for=test_device the local device's class is always instantiated and then skips visibly via the class-level skipUnless(running_on_tdm_device(), ...). Given how much we rely on those XMLs to tell coverage from absence, please take the visible skip.

7. Tolerances. _TDM_TOLERANCES uses bare dict(atol=..., rtol=...) where the file already has Tolerances = namedtuple("Tolerances", ["atol", "rtol"]) at :101; it doubles as the dtype parametrization list via list(_TDM_TOLERANCES) instead of the @dtypes/@dtypesIfCUDA decorators the file uses elsewhere (the class is registered through instantiate_device_type_tests, so those were available); and fp32 gets the tightest tolerance of the three at 2e-3, while the file's own _check_out uses fudge_factor = 10.0 for fp32 against 1.1 for fp16/bf16, with the comment about being less accurate than the float32 computation because of the online softmax. The reference here is an uncompiled flex_attention(...), that same unfused path, under set_float32_matmul_precision("high"). If anything in this class flakes later, I would bet on that row.

Cleanups

8. block_shapes is optional but always supplied. Both production callers pass a literal list matching the operand count with 2-tuples throughout, so the not matrices short-circuit, the None fill, the length-mismatch AssertionError, the len(block_shape) != 2 reject and the else sizes[-1] arm of innermost are unreachable outside the mocked tests. That mode is also weaker, since it skips the 128-byte block-width rule, so leaving it reachable invites a future caller onto the unchecked path. Make it required and drop those branches.

9. Duplicated test scaffolding. FakeSizeVars is byte-identical at :608-619 and :803-814, each followed by a near-duplicate make_qkv, and a third variant already lives at test_max_autotune.py:6377-6385. The class is also of two minds about what it fakes: :604 and :789 use bare mock.Mock() operands, :675 and :744 use real Buffer/FixedLayout against a real GraphLowering. The dense-TDM suite this is modeled on argues in a comment at test_max_autotune.py:6183 for real IR, precisely because bare mocks can make a gate short-circuit at the dtype check and pass an assertion vacuously. Pick one and hoist the helper to module level.

10. Two subsumed instances. test_tdm_flex_forward_correctness_and_selection at fp16 is the same operands, same assertion and same reference as test_tdm_flex_use_tma_option[TRITON, {}], and the decode one likewise duplicates [TRITON_DECODE, {}]. Only their bf16/fp32 instances are unique. Each instance costs two compiles, since the uncompiled reference call compiles with the eager backend, so folding the fp16 rows into the matrix is free coverage-wise.

11. Minor. _tdm_operand_compatible now computes a rejection reason via _tdm_operand_policy_violation and throws it away; the flex path logs its reasons and the dense MM path could too, now that the string exists.

One last thing, offered as a suggestion rather than a request: 592 of the 798 added lines are tests, and several carry multi-paragraph docstrings re-arguing rationale that the rules block at utils.py:465-480 already states once. Between that and the dead block_shapes=None mode, the 220-line functional change is harder to find than it needs to be. Trimming would help the next reviewer.

This review was drafted with an AI assistant (Claude Code).

@glen-amd

glen-amd commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks — this was a thorough read, and most of it lands.

First, a correction to the record: please don't take my word that the device tests were exercised on hardware. They were not. The PR body and commit message both say every device path is unrun; I have no gfx1250 access. Only the host gate tests have run, and via an extracted-source harness against a CPU wheel, not the real runner. Your gfx90a run is the first real-runner evidence on this branch.

Taken: 1, 3, 4, 5, 6, 8, 9, 10, 11, plus trimming.

Two notes where the suggested fix needed adjusting:

  • 1. tma_requested is None or tma_requested isn't sufficient — it re-enables explicit None, which took the pointer path before. Using bool(cur_kernel_options.get("USE_TMA", True)) so omission means auto and False/0/None all mean pointer. Matrix rows added for each.
  • 3. Probing the TDM prereqs first doesn't help when they're false. Routing ROCm exclusively instead (HIP build + device type cuda), so can_use_tma can't claim the path at all.

2 — I'd rather not add the rule. TDM has no 16-byte-multiple requirement on the logical extent; make_tensor_descriptor constrains the block extent, not the tensor extent, and a descriptor load bounds-checks and zero-fills beyond the logical shape (core.py). Upstream's own gfx1250 suite asserts exactly this: test_gluon_gfx1250.py sets the logical inner extent to INNER_BLOCK - 3, loads a full-width block, and requires the overhang to be zero — across fp16. So head_dim 65 should be correct, and adding TMA's rule would reject it. I've documented that in the rules block. Caveat: that's source evidence, and the padded-head test is precisely what hasn't run on gfx1250 — if it fails there, this becomes a real defect and the rule goes in.

7. Taking the namedtuple and @dtypes. Holding fp32 at 2e-3 for now: _check_out's 10.0 is a fudge on mean-abs-error against a float64 golden, not an element-wise tolerance, so it isn't directly transferable. Happy to loosen once there's a measurement.

Separately, a local review found an issue this comment doesn't cover: decode passes an int64 kv_base_offset to the K/V descriptor loads when operand numel forces INDEX_DTYPE=tl.int64, which Triton rejects. Fixed by narrowing the coordinate.

Pushing shortly.

Reply drafted with AI assistants (Claude Opus-5 + GPT-6 Astra); the code changes and evidence above were reviewed by me.

Review feedback on the option contract, backend routing and test scaffolding,
plus one defect found locally.

Read torch/_inductor/kernel/flex/flex_attention.py first. Two things change
there. The request is now captured as bool(get("USE_TMA", True)) rather than an
identity test against False: USE_TMA is typed bool but never validated at
runtime, and every falsy value took the pointer path before this feature
existed, so `is not False` let USE_TMA=0 turn descriptors on. A default of True
means "absent", so omission keeps automatic selection while False, 0 and None
all force pointer loads. Selection also moves below the tile-divisibility
rejection, matching decode, so a config that is about to be discarded cannot
install descriptor range bounds.

ROCm is then routed exclusively. has_triton_tma_device() excludes HIP only
inside its CUDA arm, so on a ROCm host its XPU or Triton-CPU-backend arms can
make it true; can_use_tma would then set USE_TMA under NVIDIA's rules and the
ROCm floor, gfx1250 probe and operand policy would never run. flex_decoding.py
takes the same two changes.

utils.py adds config.triton.enable_flex_tdm (default on) as a kill switch for
callers that do not own the flex_attention() call site, makes block_shapes
required, and records why the gate deliberately omits can_use_tma's 16-byte
rule on the logical innermost extent: Triton constrains the block extent, not
the tensor extent, and a descriptor load bounds-checks and zero-fills past the
logical shape, which is what admits FP16 head_dim 65.

common.py.jinja narrows the K/V descriptor coordinates to int32. Decode derives
that offset from a program id cast to INDEX_DTYPE, and INDEX_DTYPE is int64
whenever an operand exceeds 2**31 elements even though every descriptor
dimension fits int32, so Triton rejected the 64-bit coordinate.

Test Plan:

Host gate tests, six of six:

```
python test/run_test.py --include inductor/test_flex_attention \
  -k TestFlexAttentionTDMOptions
```

Splicing the parent commit's utils.py instead fails the config-flag test, and
splicing the pre-PR base fails all six. The dense TDM host tests are unchanged
either side of the shared-policy logging change.

The two regression tests added for this review were built to fail without their
fix: the generic-probe test passes USE_TMA=True, without which the old selector
short-circuited before consulting the probe and the assertion held for an
unrelated reason; the coordinate test denies 32-bit indexing so int64 codegen is
actually produced, and matches per operand, since one shared substring accepted
a fix applied to K but not V.

NOT RUN: every device path, unchanged from the parent commit. Neither
lintrunner nor spin was available here; only the repository-pinned ruff 0.14.4
was run over the changed files.

This change was authored with the assistance of an AI coding agent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@glen-amd
glen-amd requested a review from jeffdaily September 18, 2026 19:19

@jeffdaily jeffdaily left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Everything I raised is addressed, and the two places you pushed back you were right. Approving.

Re-verified locally on f59e25f, spliced into a ROCm 7.14 / gfx90a build and restored after: the six host gate tests pass through the runner (6 passed in 3.24s), and the probe that originally found the option bug now reports the gate consulted zero times for USE_TMA=0 and USE_TMA=None and once for omission and True.

Two notes on your corrections. On the innermost extent, I checked the Triton we pin rather than your linked commit and it holds there too: semantic.py:1852-1890 constrains only rank, stride length, a 16-byte innermost block extent and a unit innermost stride, with padding_option defaulting to zero; test_gluon_gfx1250.py:1923-1960 slices to INNER_BLOCK - 3 and asserts the overhang reads zero across the float dtypes; and compiler.py:243 only rewrites descriptors to pointers when supports_tdm is false, so the tl. path reaches the same lowering on gfx1250. Withdrawn, and thanks for documenting it in the rules block. On only_for, your version is better than what I suggested: I missed that test_device can carry "cpu" alongside "cuda" and that running_on_tdm_device() is host-global, so on a gfx1250 host my suggestion would have cleared the class skip and run these on CPU. (test_device[0],) is right.

Three non-blocking follow-ups, either here or later, your call:

  • test_tdm_flex_decode_narrows_descriptor_coordinates sits inside the running_on_tdm_device()-gated class, so it never runs in CI, but the bug it covers is in the shared common.py.jinja and is reachable on NVIDIA with an explicit USE_TMA=True. Your technique for it, patching can_use_32bit_indexing to false, is backend-agnostic and would work unchanged next to test_tma_with_customer_kernel_options_selection. That would give the fix real CI coverage on CUDA and XPU.
  • The new comment above the coordinate narrowing says the dimensions are already bounded to int32 by the descriptor gate. That is true on the TDM path but not on the CUDA arm of can_use_tma, which imposes no size bound, and the code is shared. The backend-independent reason is that make_tensor_descriptor coerces the descriptor shape to int32 itself (semantic.py:1873), so a coordinate past int32 was already invalid.
  • The USE_TMA docstring in torch/nn/attention/flex_attention.py is still accurate but does not mention config.triton.enable_flex_tdm, which is the switch a caller who cannot reach kernel_options actually needs. Worth a sentence.

Also, item 10 in my review, the fp16 instances of the two *_correctness_and_selection tests being subsumed by the use_tma_option matrix, is listed as taken in your reply but looks unchanged in the push. Not worth another round on its own.

Holding off on merge until the XPU, CUDA inductor and ROCm inductor shards report, since those are what actually exercise the cross-backend selection test. The device paths remain unrun and that is understood and accepted on my side.

Reply drafted with an AI assistant (Claude Code); the Triton source checks and the local test and probe runs above I ran and confirmed myself.

@glen-amd

Copy link
Copy Markdown
Contributor Author

@jeffdaily - Can we merge? Thank.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

jataylo pushed a commit to ROCm/pytorch that referenced this pull request Oct 15, 2026
Backport of the gfx1250 Tensor Data Mover (TDM) Inductor support to
release/2.14.

Upstream PRs (landed on pytorch/pytorch `main`):
- pytorch#191166 (`6ee9ad6564b`): dense
mm/addmm
- pytorch#196525 (`0b5ae20834c`):
generic pointwise/reduction descriptor codegen
- pytorch#197329 (`3727c0c8773`): flex
attention forward/decode

The following summary was prepared with AI assistance (Claude Opus 5.5
and GPT-6 Astra) from a per-file comparison against the upstream commits
and from my October 7 test run. I have reviewed it:

> **Differences from a pure cherry-pick**
>
> *Release adaptations (conflict resolutions):*
> - `kernel/mm.py`: keeps release's
`blackwell_ws_persistent_device_tma_mm_template`. TDM is added as an
extra candidate next to the ordinary persistent template, as upstream
does; it does not replace it.
> - `testing/_internal/inductor_utils.py`: keeps release's
`HAS_MULTIGPU` and adds `running_on_tdm_device`.
> - `utils.py`: `tma_inner_dim` already exists in upstream's parent, and
the new TDM code calls it. It is added here and also reused in
`can_use_tma` in place of the old inline stride-one scan.
`TRITON_FLOAT8_DTYPES` and `_tma_descriptor_max_offset_fits_in_int32`
were unrelated upstream context that release lacks; they are not TDM
code dropped by this backport.
> - `heuristics/template/triton.py`: `_rocm_version_tuple` is kept as
upstream introduced it, but upstream's switch of the Origami
ROCm-version gate to that helper is not taken. Release's existing
Origami policy (`config.rocm.origami` only) is unchanged. The ROCm 10.0
Origami cutoff (pytorch#193843) predates TDM and is not part of this backport.
> - Test mocks use release's `strict_sum_rblock` /
`has_strict_sum_multirow_reduction` names.
> - Six files are byte-identical to a clean merge of the three upstream
commits: `config.py`, `kernel/flex/flex_attention.py`,
`kernel/flex/flex_decoding.py`, `kernel/flex/templates/common.py.jinja`,
`nn/attention/flex_attention.py`, `utils/_triton.py`.
>
> *Local hardening (not in upstream):*
> - `codegen/triton.py:2980`: `and torch.version.hip is None` on the
unforced CUDA branch of `TMACompatibilityChecker.can_use_tma`. This
makes backend routing explicit and skips the CUDA capability query on
HIP. `has_triton_stable_tma_api()` already rejects plain HIP, so this is
not a behavior change for ordinary MI300/MI350/gfx1250 configurations.
The guard only matters when that helper is true for another backend or
is mocked. Covered by `test_failed_amd_gate_preserves_backend_routing`.
> - `heuristics/template/triton.py:2414–2515`, Origami fallback:
> - An empty preprocessed pool skips selector construction. TDM
templates then yield nothing, and non-TDM templates use the regular
generator.
> - A `RuntimeError` from `OrigamiMatmulSelector(...)` whose message
starts with `Attempting to retrieve hardware constants for unsupported
architecture:` falls back to the regular generator. Every other error
propagates.
> - That message text was verified in the `rocm-origami==0.0.3` source.
It has not been verified for the CI pin `0.0.2`.
> - This affects every ROCm Triton GEMM template that reaches Origami,
not just TDM.
> - Covered by `test_tdm_real_preprocessing_handles_empty_pool`,
`test_origami_unsupported_hardware_uses_regular_configs` and
`test_origami_unexpected_selector_error_propagates`.
>
> *Tests:*
> - Following this repo's test guidance (`CLAUDE.md`: `assertEqual` for
tensor comparisons, `instantiate_device_type_tests` for device
numerics), 24 `torch.testing.assert_close` calls became `assertEqual`
with the same explicit `atol`/`rtol`.
> - `TestTDMEndToEnd` is now instantiated per device. On ROCm the class
is therefore `TestTDMEndToEndCUDA`, and tests take a `device` argument.
> - New `test_tdm_dense_dtypes_layouts_and_scaling` is a 48-case matrix:
fp16/bf16/fp32 × 4 operand orientations × storage offset {0, 16 B} ×
{mm, addmm with alpha=0.5/beta=-0.25}. It forces the `mm_persistent_tdm`
candidate and checks descriptor codegen and numerics.
> - The second commit fixes keyword-only `Buffer(...)` construction in a
test helper.
>
> **Test results (2026-10-07, MI455X A0 / gfx1250, ROCm 10.2 nightly,
PyTorch built from release/2.14 at `c299f659`, with this PR's package
files overlaid)**
>
> | Suite | Collected | Passed | Failed |
> | --- | ---: | ---: | ---: |
> | `TestTDMConfigDenseAndGeneric` | 34 | 34 | 0 |
> | `TestTensorDescriptorCompatibility` | 15 | 15 | 0 |
> | `TestFlexAttentionTDMOptions` | 6 | 6 | 0 |
> | `TestTDMEndToEndCUDA` | 62 | 61 | 1 |
> | `TestFlexAttentionTDMEndToEndCUDA` | 35 | 35 | 0 |
>
> - All 48 dense-matrix cases passed.
> - **Compiler used:** Triton `ROCm/triton@669b31ac` (the 2.14 pin),
rebuilt against LLVM `5f07f818` plus llvm/llvm-project#214885 (the
gfx125x `needs-tdm-drain` workaround). The stock pin lacks that LLVM
fix, and the release's capability probes do not check for it.
> - **The one failure** is
`test_tdm_generic_reduction_loop_partial_tail_cuda`, an fp32 `[512,
1500].sum(dim=1)`. The assertion is in Triton's AMD lowering, and static
analysis traces it to a Triton bug rather than this PR's code:
> - The reduction's 1D TDM output store has a 4-element block, and the
kernel runs `num_warps=8`.
> - Triton's `tdmGetWarpDistribution` gives that block 8 warps, so each
warp's share rounds to zero. Lowering then asserts
`layout.getNumInDims() == indices.size()` (`Utility.cpp:301`).
> - Matches the crash fixed upstream by triton-lang/triton#11749 (issue
pytorch#11748); not yet confirmed by a rerun with that fix. The fix is in
ROCm/triton `release/3.9.x` but not in `release/internal/3.8.x`, the
line the 2.14 pin is on.
> - The saved MLIR reproduces the assertion in `triton-opt` without a
GPU. The same reduction without descriptors passes.
>
> On 2026-10-11 the branch was updated by merging release/2.14 at
`87e0d36` (new head `121919f`). The PR's 13 files are byte-identical to
the tested `a7a9d50`, and none of the 8 merged release commits touch
them, so these results still apply to this PR's code.
>
> Commands (from the PR's test tree, against the installed wheel):
> ```
> python -m pytest test/inductor/test_max_autotune.py -k
'TestTDMConfigDenseAndGeneric or TestTensorDescriptorCompatibility'
> python -m pytest test/inductor/test_flex_attention.py -k
TestFlexAttentionTDMOptions
> python -m pytest test/inductor/test_max_autotune.py -k TestTDMEndToEnd
# selects TestTDMEndToEndCUDA
> python -m pytest test/inductor/test_flex_attention.py -k
TestFlexAttentionTDMEndToEnd
> ```
>
> **Not yet qualified**
> - The reduction failure is expected to need triton-lang/triton#11749
in the 2.14 Triton pin; confirm by rerunning with all assertions
unchanged after the pin moves. The 2.14 Triton also needs
llvm/llvm-project#214885.
> - The final shipping Triton artifact has not been tested; the run
above used a locally rebuilt wheel.
> - ROCm 10.1 is not covered.
> - Origami enabled is untested. rocm-origami was not installed in the
test environment, and `rocm-origami` 0.0.2 (the CI pin) and 0.0.3 have
no gfx1250 hardware entry. Because release has no ROCm 10.0 Origami
cutoff, enabling it on ROCm 10.x also needs the Python package and the
native library it loads to be shown compatible.
> - No performance comparison, and no CUDA/XPU runs.
> - CI on the current head `121919f` (as on the previous head
`a7a9d50`): 8 check runs, all skipped (6 NVIDIA sm90 CUDA jobs plus
`get-label-type` and `capture`). No ROCm CI job ran, and there are no
commit statuses.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 ciflow/h100 ciflow/inductor ciflow/inductor-rocm Trigger "inductor" config CI on ROCm ciflow/pull ciflow/rocm ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request ciflow/xpu Run XPU CI tasks Merged module: inductor module: rocm AMD GPU support for Pytorch open source release notes: rocm mandatorylabel

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants