Skip to content

[ROCm] Speed up radixSelect with a register-resident path - #200328

Closed
apakbin wants to merge 6 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-radixselect-regs
Closed

apakbin wants to merge 6 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-radixselect-regs

Conversation

@apakbin

@apakbin apakbin commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Supported by @jeffdaily

Summary

radixSelect finds the k-th value for topk, kthvalue, median and nanmedian. Its ROCm version re-reads the slice (from global memory, or from its 3 KB shared-memory cache once the candidates fit) on every 2-bit radix pass, and spends two barriers per pass combining per-warp counts, so the single-block kernels are dominated by its serial latency.

This keeps slices of up to REGS_MAX_E x blockDim elements in registers for the whole selection, loaded and converted once (REGS_MAX_E is 20 on GFX9 and 14 elsewhere, which keeps wave32 kernels at 16 waves per SIMD). 1-byte types off GFX9 keep the general path, which was faster for them on gfx1100. For k <= 16 from either end, a pre-pass bounds the answer with the per-wave maxima and ranks the few candidates directly, falling back to the radix walk when too many keys tie. On GFX9 the per-pass count combine uses one barrier with DPP adds; other targets keep the two-barrier combine, which is cheaper there with 32 warps per block. The general path, still used for 8-byte types and longer slices, also gets cheaper. Only ROCm code in SortingRadixSelect.cuh changes.

A note at the top of the register-path section explains which path runs for which dtype, slice length and k, lists the steps of the register path (labeled sections of radixSelectRegs), and maps them to the test cases. The features, in suggested review order:

Feature Lines (approx.) What it does Covered by
Path choice, in radixSelect's ROCm branch 20 Picks the register path and its rows per thread E from the dtype and slice length test_select_ties_at_dtype_extremes (slice lengths at each E boundary; uint8/int8 take the general path on wave32)
Register path, steps 1 and 4: load once, radix walk over the held keys, one-time compaction of the survivors 400 Removes the per-pass re-read and re-convert; most of the speedup the new test and the existing topk, kthvalue and median tests
Step 2, k = 1 (or n): one block-wide max reduction 20 Answers without a radix walk the new test, k = 1 and n
Step 3, k <= 16 from either end: threshold pre-pass 290 Answers small k from a few candidates; heavy ties fall back to the walk the new test: k = 2 to 17 and mirrors, few-distinct-value rows, 8-bit ties at the maximum
GFX9 only: 16-bin counting with DPP and LDS atomics 170 Halves the passes on wave64 every register-path test on GFX9
General path: one-barrier findPattern, remaining count in registers, no refill once done 190 Faster 8-byte types and long slices the existing topk, kthvalue and median tests

The register path was generated with AMD's GEAK optimization workflow driving Claude, then ported, fixed for signed and 64-bit index types, 8-byte types and wave32 shared-memory bounds, tuned for wave32 on gfx1100, and documented for review.

Geomean speedup over main, single-block configurations of #171940's topk benchmark (48) and of a kthvalue/median matrix (24 each):

topk kthvalue median
MI355X (gfx950) 2.14x 3.20x 2.90x
Radeon Pro W7800 (gfx1100) 1.43x* 1.68x 1.67x

* gfx1100 topk was measured with #199848's gather on both sides.

On gfx950, int64 and float64 kthvalue and median are 1.36x and 1.44x faster. Multi-block and sort paths are unchanged. No benchmarked single-block configuration is slower than main on either GPU.

Test Plan

New test_select_ties_at_dtype_extremes checks topk, kthvalue, median and nanmedian values exactly against CPU for seven dtypes, with ties at the dtype minimum, maximum and NaN, contiguous and strided slices at each register-path size, k at each step boundary, small-k candidate counts at both ends of each of the pre-pass's ranking methods, and tie-heavy rows that overflow the small-k pre-pass. Outside the test suite, returned values were bit-identical to main on 12,198 configurations (nine dtypes, slices of 257 to 300,000 elements, random, tie-heavy and special values, contiguous and strided), and a randomized comparison against CPU over the same edges matched main on every case, on gfx950 and gfx1100. Indices are unchanged: topk and kthvalue derive them from the selected value, and since #199947 median and nanmedian return the first occurrence of the median value, so identical values give identical indices.

python test/test_sort_and_select.py -k topk
python test/test_sort_and_select.py -k kthvalue
python test/test_sort_and_select.py -k test_select_ties_at_dtype_extremes
python test/test_reductions.py -k median
python test/test_ops.py -k _topk_cuda
python test/test_ops.py -k _kthvalue_cuda
python test/test_ops.py -k _median_cuda

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

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

radixSelect finds the k-th value for topk, kthvalue, median and nanmedian. Its ROCm version re-reads the slice (from global memory, or from its 3 KB shared-memory cache once the candidates fit) on every 2-bit radix pass, and spends two barriers per pass combining per-warp counts, so the single-block kernels are dominated by its serial latency.

This keeps slices of up to REGS_MAX_E x blockDim elements in registers for the whole selection, loaded and converted once (REGS_MAX_E is 20 on GFX9 and 14 elsewhere, which keeps wave32 kernels at 16 waves per SIMD). 1-byte types off GFX9 keep the general path, which was faster for them on gfx1100. For k <= 16 from either end, a pre-pass bounds the answer with the per-wave maxima and ranks the few candidates directly, falling back to the radix walk when too many keys tie. On GFX9 the per-pass count combine uses one barrier with DPP adds; other targets keep the two-barrier combine, which is cheaper there with 32 warps per block. The general path, still used for 8-byte types and longer slices, also gets cheaper. Only ROCm code in SortingRadixSelect.cuh changes.

A note at the top of the register-path section explains which path runs for which dtype, slice length and k, lists the steps of the register path (labeled sections of radixSelectRegs), and maps them to the test cases. The features, in suggested review order:

| Feature | Lines (approx.) | What it does | Covered by |
|---|---|---|---|
| Path choice, in radixSelect's ROCm branch | 20 | Picks the register path and its rows per thread E from the dtype and slice length | test_select_ties_at_dtype_extremes (slice lengths at each E boundary; uint8/int8 take the general path on wave32) |
| Register path, steps 1 and 4: load once, radix walk over the held keys, one-time compaction of the survivors | 400 | Removes the per-pass re-read and re-convert; most of the speedup | the new test and the existing topk, kthvalue and median tests |
| Step 2, k = 1 (or n): one block-wide max reduction | 20 | Answers without a radix walk | the new test, k = 1 and n |
| Step 3, k <= 16 from either end: threshold pre-pass | 290 | Answers small k from a few candidates; heavy ties fall back to the walk | the new test: k = 2 to 17 and mirrors, few-distinct-value rows, 8-bit ties at the maximum |
| GFX9 only: 16-bin counting with DPP and LDS atomics | 170 | Halves the passes on wave64 | every register-path test on GFX9 |
| General path: one-barrier findPattern, remaining count in registers, no refill once done | 190 | Faster 8-byte types and long slices | the existing topk, kthvalue and median tests |

The register path was generated with AMD's GEAK optimization workflow driving Claude, then ported, fixed for signed and 64-bit index types, 8-byte types and wave32 shared-memory bounds, tuned for wave32 on gfx1100, and documented for review.

Geomean speedup over main, single-block configurations of pytorch#171940's topk benchmark (48) and of a kthvalue/median matrix (24 each):

| | topk | kthvalue | median |
|---|---|---|---|
| MI355X (gfx950) | 2.14x | 3.20x | 2.90x |
| Radeon Pro W7800 (gfx1100) | 1.43x* | 1.68x | 1.67x |

\* gfx1100 topk was measured with pytorch#199848's gather on both sides.

On gfx950, int64 and float64 kthvalue and median are 1.36x and 1.44x faster. Multi-block and sort paths are unchanged. No benchmarked single-block configuration is slower than main on either GPU.

## Test Plan

New test_select_ties_at_dtype_extremes checks topk, kthvalue and median values against CPU with ties at the dtype minimum and maximum, slice lengths at the register-path limits, k at each step boundary, and tie-heavy rows that overflow the small-k pre-pass. Outside the test suite, returned values were bit-identical to main on 12,198 configurations (nine dtypes, slices of 257 to 300,000 elements, random, tie-heavy and special values, contiguous and strided), and a randomized comparison against CPU over the same edges matched main on every case, on gfx950 and gfx1100. topk and kthvalue indices are unchanged; median and nanmedian tie indices already vary between runs on main.

```
python test/test_sort_and_select.py -k topk
python test/test_sort_and_select.py -k kthvalue
python test/test_sort_and_select.py -k test_select_ties_at_dtype_extremes
python test/test_reductions.py -k median
python test/test_ops.py -k _topk_cuda
python test/test_ops.py -k _kthvalue_cuda
python test/test_ops.py -k _median_cuda
```

This PR was authored with the help of Claude (AI assistant).
Review follow-up. Comment-only changes in SortingRadixSelect.cuh (the compiled code is unchanged): the all-ones key is NaN for floating types and the maximum only for integers, the 16-bin count needs a 32-bit index_t, the packed counters and RegKey packing apply to the types they actually cover, the DPP lane descriptions match the code, and REGS_SMALL_K describes the threshold step.

test_select_ties_at_dtype_extremes now compares exactly (atol=0, rtol=0), adds bfloat16, NaN ties with nanmedian, and the slice lengths 4096 and 20480, and compares topk values unsorted so that GPU sort order for NaN does not enter.

Test Plan

```
python test/test_sort_and_select.py -k test_select_ties_at_dtype_extremes
```

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

pytorch-bot Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit 9324e58 with merge base 34faf6b (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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 8, 2026
Picks up pytorch#199848 and pytorch#199947, which postdate the branch base. Clean merge, no conflicts.
@jeffdaily jeffdaily added the release notes: rocm mandatorylabel label Oct 9, 2026
test_select_ties_at_dtype_extremes only used contiguous slices, so the register path's row-by-row load for strided slices with more than one row per thread was never run: the existing cases with more than 1024 elements all take loadChunks. It now also selects along dim 0 of (n, 3) tensors (stride 3) at n = 4096, 4097, 10241 and 20480, which take 4, 10 and 20 rows per thread on wave64 (4, 10, 14 and the general path on wave32), and checks kthvalue, topk, median and nanmedian exactly against CPU.

It also pins down step 3's three ranking methods (at most 16, at most 64, or at most CAP candidates, after which the walk decides). h distinct values in elements 0 to h - 1, which wave 0 holds in every load layout, sit above c spread copies of 60, so for kEff = 2 the threshold is 60 and the candidate count is h + c. Counts 17, 64, 65, 160, 161, 192 and 193 cover both ends of the 64 and CAP ranges on wave64 (CAP = 192 at 10 rows per thread) and wave32 (CAP = 160). A mirrored second row takes step 3 from the other end of the order. The register-path note in SortingRadixSelect.cuh mentions both additions.

On gfx950 the additions take about 0.5 s over all seven dtypes (3.0 s to 3.5 s for the test). Device printf instrumentation in a scratch build confirmed the new cases reach the strided rows-per-thread 4, 10 and 20 loads and step 3 with the intended counts. Shifting the strided load by one element fails all seven dtypes of the extended test while the previous version of the test passes; ranking one too deep in the 64 and CAP methods makes the step-3 kthvalue checks fail at every count from 17 to 192.

Test Plan:

```
python test/test_sort_and_select.py -k test_select_ties_at_dtype_extremes
python test/test_sort_and_select.py -k topk -k kthvalue
python test/test_reductions.py -k median
```

Written with Claude.
radixSelectRegs' lanesBelow and the single-block topk gather's laneRank (from pytorch#199848) are the same mbcnt helper. TensorTopK.cu includes SortingRadixSelect.cuh, so this keeps one copy there under the name laneRank and drops the one in TensorTopK.cu. No behavior change: the gfx950 device code object in libtorch_hip.so is byte-identical with and without this commit.

Test Plan:

```
python test/test_sort_and_select.py -k topk -k kthvalue
python test/test_ops.py -k _median_cuda -k _topk_cuda -k _kthvalue_cuda
```

Written with Claude.
@jeffdaily jeffdaily added ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/trunk Trigger trunk jobs on your pull request labels Oct 12, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 12, 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 Oct 12, 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/trunk
  • ciflow/rocm-mi300
  • ciflow/rocm-mi200

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.

@jeffdaily
jeffdaily marked this pull request as ready for review October 12, 2026 22:07
jeffdaily
jeffdaily previously approved these changes Oct 12, 2026
@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@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 12, 2026
@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: Auto Request Review

Details for Dev Infra team Raised by workflow job

@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

@izaitsevfb

Copy link
Copy Markdown
Contributor

✴️ iz2: The new ROCm helpers in aten/src/ATen/native/cuda/SortingRadixSelect.cuh call max and min unqualified inside namespace at::native (26 calls between lines 978 and 1526, starting in waveMax). If <ATen/ATen.h> or <torch/torch.h> is included before this header, those names resolve to ATen's Tensor overloads and the ROCm build fails with "no matching function for call to 'max'". OSS CI never includes the header that way, but Meta-internal ROCm builds do, so this PR is being reverted. Qualifying the calls as ::max and ::min, which is what they resolve to in OSS builds today, should fix it. You can reland once that is in.
@pytorchbot revert -m "Breaks Meta-internal ROCm builds, unqualified max and min in SortingRadixSelect.cuh" -c ghfirst

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

pytorchmergebot added a commit that referenced this pull request Oct 13, 2026
…00328)"

This reverts commit a6338be.

Reverted #200328 on behalf of https://github.com/izaitsevfb due to Breaks Meta-internal ROCm builds, unqualified max and min in SortingRadixSelect.cuh ([comment](#200328 (comment)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@apakbin your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Oct 13, 2026
@pytorch-bot
pytorch-bot Bot dismissed jeffdaily’s stale review October 13, 2026 17:37

This PR was reopened (likely due to being reverted), so your approval was removed. Please request another review.

pytorch#200328 was reverted because the new ROCm helpers in SortingRadixSelect.cuh call max and min unqualified inside namespace at::native. When <ATen/ATen.h> or <torch/torch.h> is included first, unqualified lookup stops at the at::native::max and at::native::min Tensor overloads, so the HIP global overloads are never considered and the build fails with "no matching function for call to 'max'". OSS never includes the header in that order; Meta-internal ROCm builds do.

All 26 calls in the header are now ::max and ::min, the overloads they already resolve to in OSS, so the generated code is unchanged. Three unqualified min calls in the topk gather in TensorTopK.cu (from pytorch#199848) have the same problem when the whole file is compiled after ATen.h and are qualified the same way. No other unqualified call in these files collides with an ATen operator name.

Test Plan

On gfx950 (wave64, GFX9 branches) and gfx1100 (wave32, non-GFX9 branches): built with `pip install -e . -v --no-build-isolation`, then compiled the hipified TensorTopK and Sorting sources with the build's own compile flags plus -fsyntax-only, preceded by <ATen/ATen.h>, <ATen/NativeFunctions.h> and <torch/torch.h>. Before the change this fails with the errors from the revert; after it, both compile clean. TensorTopK objects are byte-identical before and after (ignoring the per-compile cuid). Tests, all passing:

```
python test/test_sort_and_select.py -k topk
python test/test_sort_and_select.py -k kthvalue
python test/test_sort_and_select.py -k test_select_ties_at_dtype_extremes
python test/test_reductions.py -k median
python test/test_ops.py -k _topk_cuda
python test/test_ops.py -k _kthvalue_cuda
python test/test_ops.py -k _median_cuda
```

Authored with Claude.
@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@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 3 checks: rocm-mi300 / linux-noble-rocm-py3.11-mi300 / test (default, 4, 8, linux.rocm.gpu.mi300.1), rocm-mi200 / linux-jammy-rocm-py3.11-mi200 / test (default, 10, 10, linux.rocm.gpu.mi210.1), trunk / linux-noble-rocm-py3.11-mi350 / test (default, 5, 8, amd-dpx-linux.rocm.gpu.gfx950.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

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 ci-no-td Do not run TD on this PR ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/trunk Trigger trunk jobs on your pull request Merged module: rocm AMD GPU support for Pytorch open source release notes: rocm mandatorylabel Reverted 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.

5 participants