Skip to content

[ROCm] Make single-block topk gather deterministic - #199425

Closed
jerrymannil wants to merge 2 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-topk-ordered-gather
Closed

jerrymannil wants to merge 2 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-topk-ordered-gather

Conversation

@jerrymannil

@jerrymannil jerrymannil commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Since #171940, ROCm's single-block gatherTopK reserves output slots with a per-warp atomicAdd, so warp arrival order decides the gather order. With sorted=False, topk can return its indices in a different order from run to run, for any dtype; with sorted=True, tied values can come back in varying order, and phase 2 can keep different tied k-th elements. CUDA's prefix-scan gather is stable. Slices of 256 or fewer take ROCm's warp-level topk path, which is already deterministic, which is why reports start at 257 columns.

This keeps #171940's per-warp ballot counting but replaces the atomic with an ordered exchange: each warp publishes its count to shared memory, one __syncthreads(), then a shuffle scan gives each warp its offset. On MI355X (gfx950) the output was bit-identical to the prefix-scan gather across 384 configs. With #171940's benchmark, the single-block path is about 4% slower than the atomic version and about 1% faster than the pre-#171940 prefix scan.

Fixes #196177

Test Plan

New test_topk_deterministic_ties checks run-to-run stability and, for sorted=False, the expected gather order. Validated on MI355X (gfx950) on base bc31d27, where TensorTopK.cu is identical to this PR's base:

python test/test_sort_and_select.py -k topk
python test/test_torch.py -k topk

The stability check fails on the current kernel and passes with this change. In this PR's CI, test_sort_and_select.py (including the gather-order assertion) passes on CUDA (L4), MI300 and MI350. The rx7900 job only runs inductor tests, so the new test has not run on a wave32 GPU; the kernel compiles for gfx1151.

This PR was authored with the help of Claude (AI assistant).

Submitting on behalf of @jeffdaily

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @xinyazhang

Fixes pytorch#196177.

Since pytorch#171940, the ROCm gatherTopK used by the single-block topk path reserves output slots with one atomicAdd per warp per iteration. Warp arrival order then decides the gather order, which shows up in three ways: with sorted=False the returned indices come back in a different order every run (for any dtype, including fp32 with no ties); with sorted=True the non-stable small sort turns that into a varying order among tied values; and in phase 2 it decides which of several tied k-th elements are kept. CUDA uses exclusiveBinaryPrefixScan there, so CUDA is run-to-run stable. Slices <= 256 take warptopk (stable sort), which is why the reports start at 257 columns.

The fix keeps pytorch#171940's per-warp ballot + popc counting but replaces the atomic reservation with an ordered exchange: lane 0 of each warp publishes its count to shared memory, one __syncthreads(), then a shuffle scan over the per-warp counts gives each warp its exclusive prefix and the iteration total. Results land in ascending input-index order, bit-identical to the prefix-scan gather. The counts are double buffered so one barrier per iteration suffices; because the loop now contains a barrier, the iteration count is rounded up to blockDim.x so every thread runs the same number of iterations, and the phase 2 early exit tests the block-uniform write index.

Alternatives measured on MI355X (gfx950) with the pytorch#171940 benchmark (48 single-block configs, geomean vs the current atomic kernel, 3 interleaved repeats): reverting to the prefix-scan gather +5.5%; the same ordered scheme with a per-thread loop over warp counts +10.4% (serialized LDS loads); this shuffle-scan version +4.2%, which is 1.2% faster than the pre-pytorch#171940 prefix scan. Keeping the atomics leaves topk nondeterministic by design, so this trades about 4% on the single-block path for determinism and CUDA parity. pytorch#171940 measured a 5-6% gain here, not the 10% it reported.

Test Plan:

New test_topk_deterministic_ties (bf16/fp16/fp32; tie-heavy randint inputs, 257 and 1024 columns, k in 8 and 300, all largest/sorted combinations, 10 reruns each). Validated on MI355X (gfx950, ROCm 10.0 / HIP 7.15) on base bc31d27, where TensorTopK.cu is identical to this branch's base:

```
python test/test_sort_and_select.py -k topk -v
python test/test_torch.py -k topk -v
python test/test_sort_and_select.py -k test_topk_deterministic_ties -v
```

The new test fails 3/3 dtypes on the current kernel and passes on this one; the existing topk tests pass. A determinism matrix (bf16/fp16/fp32 x 5 shapes x k in 1, 8, 64 x largest/sorted, 50 reruns each) went from 67/180 nonzero cells to 0/180, and a 384-config dump matched the prefix-scan gather's values and indices exactly. Not built on Windows or on a wave32 GPU.

This change was authored with the help of Claude (AI assistant).
…ted topk gather order in test

This change was authored with the help of Claude (AI assistant).
@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 45cdc04 with merge base ee0d01e (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@pytorch-bot pytorch-bot Bot added the module: rocm AMD GPU support for Pytorch label Oct 2, 2026
@jerrymannil
jerrymannil requested a review from jeffdaily October 2, 2026 01:57
@jerrymannil jerrymannil added ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-mi355 Trigger "default" config CI on ROCm MI355 runners labels Oct 2, 2026
@pytorch-bot

This comment was marked as resolved.

@jerrymannil jerrymannil added ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi355 Trigger "distributed" config CI on ROCm MI355 labels Oct 2, 2026
@pytorch-bot

This comment was marked as resolved.

soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines
inside an excerpt (#197857, #199447, #199471, #199472, #199497). Two turned an
unchanged context line, which also appeared in the `@@` hunk header, into a
fake `-`/`+` pair (#199453, #199461). The worker prompt now says to keep
excerpts short by choosing a shorter run of adjacent lines, never by skipping
or cutting lines, and never to turn unchanged lines or hunk-header text into
changed lines. The validator stays strict: a mismatched excerpt can't be told
apart from an invented one, and a failed run falls back to human triage. The
replay below shows the wording fixes the hunk-header pattern but only partly
helps the other two, so a structural follow-up is still needed.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of three failed runs:
each run's patch at its analyzed head_sha and CODEOWNERS at its workflow_sha.
Outputs were checked with validate_result. Evidence-excerpt failures:

| PR (pattern)                         | old worker.md | new worker.md |
|--------------------------------------|---------------|---------------|
| #199461 (fake -/+ from hunk header)  | 2/3           | 0/3           |
| #197857 (skipped comment lines)      | 4/4           | 2/3           |
| #199425 (cut a long comment line)    | 2/5           | 3/5           |

The remaining failures still drop two comment lines from the middle of an
excerpt (#197857) or stop a long comment line at the end of a sentence
(#199425).

This PR was authored with an AI assistant (Claude Code).

ghstack-source-id: d937117
Pull-Request-resolved: #199428
soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).

ghstack-source-id: 546c754
Pull-Request-resolved: #199428
@jerrymannil jerrymannil added the keep-going Don't stop on first failure, keep running tests until the end label Oct 2, 2026
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
…99428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: #199428
Approved by: https://github.com/janeyx99
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 2, 2026
@jeffdaily jeffdaily added ciflow/rocm-rx7900 Trigger "default" config CI on ROCm RX7900 Radeon (Navi31/gfx1100) GPUs release notes: rocm mandatorylabel and removed ciflow/rocm-mi355 Trigger "default" config CI on ROCm MI355 runners labels Oct 2, 2026
@jeffdaily jeffdaily removed the ciflow/periodic-rocm-mi355 Trigger "distributed" config CI on ROCm MI355 label Oct 2, 2026

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

Approving; validated on gfx950 (determinism matrix, parity with the prefix-scan gather, #171940 benchmark), and CI passes test_sort_and_select on L4, MI300 and MI350.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: periodic-rocm-mi300 / linux-noble-rocm-py3.11-mi300 / test (distributed, 4, 5, linux.rocm.gpu.mi300.4, module:rocm, oncall:distributed), rocm-rx7900 / linux-jammy-rocm-py3.11-rx7900 / test (default, 1, 2, linux.rocm.gpu.rx7900.1)

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

pytorchmergebot pushed a commit that referenced this pull request Oct 7, 2026
…199848)

Performance improvement for topK on ROCm.

#199425 made ROCm's single-block gatherTopK deterministic with an ordered per-warp exchange that costs a barrier and a shuffle scan per gather iteration. On MI355X that left the path 2 to 4% behind the old atomicAdd kernel.

This makes the exchange cheaper and less frequent while keeping the output order and tie choice unchanged. The cross-warp scan uses readlane broadcasts on all non-SPIR-V targets, plus DPP row adds on GFX9; wave32 and SPIR-V keep a shuffle scan. Slices longer than the block run four block-strided sub-iterations per barrier, with two 16-bit counts per LDS word. Elements equal to the k-th value are ranked during phase 1, so phase 2 skips its second pass over the slice unless a thread holds more than two of them.

The kernel was generated with AMD's GEAK optimization workflow driving Claude, against a harness that required output bit-identical to #199425 and compiled every candidate for gfx950, gfx1100, gfx1151 and amdgcnspirv.

With #171940's benchmark, the single-block configurations are 1.09x faster than #199425 on MI355X (gfx950), about 5% ahead of the atomicAdd kernel, and 1.04x faster on Radeon Pro W7800 (gfx1100). Multi-block and sort paths are unchanged.

## Test Plan

`test_topk_deterministic_ties` now also covers slices longer than the block, with both heavy and light ties, which reach the multi-round gather and the phase-2 fallback. Outside the test suite, output was bit-identical to #199425 on 384 seeded configurations on gfx950 and gfx1100.

```
python test/test_sort_and_select.py -k topk
python test/test_torch.py -k topk
```

This PR was authored with the help of Claude (AI assistant).
Author - Jeff Daily <[email protected]>

Pull Request resolved: #199848
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…torch#199428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (pytorch#199436, pytorch#199440, pytorch#199463, pytorch#199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, pytorch#199425). Five skipped lines inside an excerpt
(pytorch#197857, pytorch#199447, pytorch#199471, pytorch#199472, pytorch#199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (pytorch#199453,
pytorch#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (pytorch#199453, pytorch#199461), and the one replay failure
(pytorch#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: pytorch#199428
Approved by: https://github.com/janeyx99
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
Since pytorch#171940, ROCm's single-block `gatherTopK` reserves output slots with a per-warp `atomicAdd`, so warp arrival order decides the gather order. With `sorted=False`, topk can return its indices in a different order from run to run, for any dtype; with `sorted=True`, tied values can come back in varying order, and phase 2 can keep different tied k-th elements. CUDA's prefix-scan gather is stable. Slices of 256 or fewer take ROCm's warp-level topk path, which is already deterministic, which is why reports start at 257 columns.

This keeps pytorch#171940's per-warp ballot counting but replaces the atomic with an ordered exchange: each warp publishes its count to shared memory, one `__syncthreads()`, then a shuffle scan gives each warp its offset. On MI355X (gfx950) the output was bit-identical to the prefix-scan gather across 384 configs. With pytorch#171940's benchmark, the single-block path is about 4% slower than the atomic version and about 1% faster than the pre-pytorch#171940 prefix scan.

Fixes pytorch#196177

## Test Plan

New `test_topk_deterministic_ties` checks run-to-run stability and, for `sorted=False`, the expected gather order. Validated on MI355X (gfx950) on base bc31d27, where `TensorTopK.cu` is identical to this PR's base:

```
python test/test_sort_and_select.py -k topk
python test/test_torch.py -k topk
```

The stability check fails on the current kernel and passes with this change. In this PR's CI, `test_sort_and_select.py` (including the gather-order assertion) passes on CUDA (L4), MI300 and MI350. The rx7900 job only runs inductor tests, so the new test has not run on a wave32 GPU; the kernel compiles for gfx1151.

This PR was authored with the help of Claude (AI assistant).

Submitting on behalf of @jeffdaily

Pull Request resolved: pytorch#199425
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ytorch#199848)

Performance improvement for topK on ROCm.

pytorch#199425 made ROCm's single-block gatherTopK deterministic with an ordered per-warp exchange that costs a barrier and a shuffle scan per gather iteration. On MI355X that left the path 2 to 4% behind the old atomicAdd kernel.

This makes the exchange cheaper and less frequent while keeping the output order and tie choice unchanged. The cross-warp scan uses readlane broadcasts on all non-SPIR-V targets, plus DPP row adds on GFX9; wave32 and SPIR-V keep a shuffle scan. Slices longer than the block run four block-strided sub-iterations per barrier, with two 16-bit counts per LDS word. Elements equal to the k-th value are ranked during phase 1, so phase 2 skips its second pass over the slice unless a thread holds more than two of them.

The kernel was generated with AMD's GEAK optimization workflow driving Claude, against a harness that required output bit-identical to pytorch#199425 and compiled every candidate for gfx950, gfx1100, gfx1151 and amdgcnspirv.

With pytorch#171940's benchmark, the single-block configurations are 1.09x faster than pytorch#199425 on MI355X (gfx950), about 5% ahead of the atomicAdd kernel, and 1.04x faster on Radeon Pro W7800 (gfx1100). Multi-block and sort paths are unchanged.

## Test Plan

`test_topk_deterministic_ties` now also covers slices longer than the block, with both heavy and light ties, which reach the multi-round gather and the phase-2 fallback. Outside the test suite, output was bit-identical to pytorch#199425 on 384 seeded configurations on gfx950 and gfx1100.

```
python test/test_sort_and_select.py -k topk
python test/test_torch.py -k topk
```

This PR was authored with the help of Claude (AI assistant).
Author - Jeff Daily <[email protected]>

Pull Request resolved: pytorch#199848
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>

This branch was previously deployed

1 inactive deployment
bedrock — 45cdc04f Deployed Oct 2, 2026 by janeyx99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-rx7900 Trigger "default" config CI on ROCm RX7900 Radeon (Navi31/gfx1100) GPUs ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged module: rocm AMD GPU support for Pytorch open source release notes: rocm mandatorylabel triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

torch.topk is non-deterministic on ROCm for bfloat16/float16 when the reduced dim exceeds 256

5 participants