Skip to content

Make CUDA median(dim) deterministic among tied values - #199947

Closed
pablo-garay wants to merge 1 commit into
pytorch:mainfrom
ROCm:jeffdaily/median-first-index-on-ties
Closed

pablo-garay wants to merge 1 commit into
pytorch:mainfrom
ROCm:jeffdaily/median-first-index-on-ties

Conversation

@pablo-garay

Copy link
Copy Markdown
Contributor

gatherMedian, shared by CUDA and ROCm, lets every thread that finds a value equal to the median write its index to the same output, so median(dim) and nanmedian(dim) return whichever index lands last, which can change from run to run when the median value repeats. #165762 fixed the same race in gatherKthValue.

This applies the same fix: matching threads take an atomicMin on a shared index and thread 0 writes the result after a barrier, so CUDA returns the first occurrence of the median value, as kthvalue does. The shared index is 64-bit because median, unlike kthvalue, allows slices longer than INT32_MAX.

Since the op is now deterministic, this removes its nondeterminism alert and its entry in the use_deterministic_algorithms docs, and replaces the alert test with one that checks the first-occurrence index. The alert is removed from the eager path and from the meta function, which is shared with mode; CUDA mode never had an eager alert, so that was a meta-only over-alert. The median docstrings now say CUDA returns the first occurrence and describe how the full-reduction gradient differs from median(dim).

Cost on MI355X: about 1 to 2% slower, or 4 to 8% when most elements tie with the median, the same as kthvalue.

Test Plan

Validated on ROCm (MI355X, gfx950); not run on NVIDIA. The new test_median_dim_index_is_first_occurrence covers contiguous and strided slices, a NaN row and an all-NaN row, for median and nanmedian; it fails on all four dtypes without the kernel change and passes with it.

python test/test_reductions.py -k median
python test/test_torch.py -k median
python test/test_torch.py -k nondeterministic_alert
python test/test_ops.py -k median
python test/test_meta.py -k median

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

gatherMedian, shared by CUDA and ROCm, lets every thread that finds a value equal to the median write its index to the same output, so median(dim) and nanmedian(dim) return whichever index lands last, which can change from run to run when the median value repeats. pytorch#165762 fixed the same race in gatherKthValue.

This applies the same fix: matching threads take an atomicMin on a shared index and thread 0 writes the result after a barrier, so CUDA returns the first occurrence of the median value, as kthvalue does. The shared index is 64-bit because median, unlike kthvalue, allows slices longer than INT32_MAX.

Since the op is now deterministic, this removes its nondeterminism alert and its entry in the use_deterministic_algorithms docs, and replaces the alert test with one that checks the first-occurrence index. The alert is removed from the eager path and from the meta function, which is shared with mode; CUDA mode never had an eager alert, so that was a meta-only over-alert. The median docstrings now say CUDA returns the first occurrence and describe how the full-reduction gradient differs from median(dim).

Cost on MI355X: about 1 to 2% slower, or 4 to 8% when most elements tie with the median, the same as kthvalue.

## Test Plan

Validated on ROCm (MI355X, gfx950); not run on NVIDIA. The new test_median_dim_index_is_first_occurrence covers contiguous and strided slices, a NaN row and an all-NaN row, for median and nanmedian; it fails on all four dtypes without the kernel change and passes with it.

    python test/test_reductions.py -k median
    python test/test_torch.py -k median
    python test/test_torch.py -k nondeterministic_alert
    python test/test_ops.py -k median
    python test/test_meta.py -k median

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

pytorch-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit ab4db06 with merge base 8d1d972 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 labels Oct 6, 2026
@jeffdaily
jeffdaily marked this pull request as ready for review October 7, 2026 15:04
@jeffdaily jeffdaily added release notes: rocm mandatorylabel release notes: cuda release notes category labels Oct 7, 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.

LGTM. median(dim) now returns the first occurrence of the median on CUDA/ROCm, mirroring the kthvalue fix in #165762; CI is green.

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

cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
gatherMedian, shared by CUDA and ROCm, lets every thread that finds a value equal to the median write its index to the same output, so median(dim) and nanmedian(dim) return whichever index lands last, which can change from run to run when the median value repeats. pytorch#165762 fixed the same race in gatherKthValue.

This applies the same fix: matching threads take an atomicMin on a shared index and thread 0 writes the result after a barrier, so CUDA returns the first occurrence of the median value, as kthvalue does. The shared index is 64-bit because median, unlike kthvalue, allows slices longer than INT32_MAX.

Since the op is now deterministic, this removes its nondeterminism alert and its entry in the use_deterministic_algorithms docs, and replaces the alert test with one that checks the first-occurrence index. The alert is removed from the eager path and from the meta function, which is shared with mode; CUDA mode never had an eager alert, so that was a meta-only over-alert. The median docstrings now say CUDA returns the first occurrence and describe how the full-reduction gradient differs from median(dim).

Cost on MI355X: about 1 to 2% slower, or 4 to 8% when most elements tie with the median, the same as kthvalue.

## Test Plan

Validated on ROCm (MI355X, gfx950); not run on NVIDIA. The new test_median_dim_index_is_first_occurrence covers contiguous and strided slices, a NaN row and an all-NaN row, for median and nanmedian; it fails on all four dtypes without the kernel change and passes with it.

```
python test/test_reductions.py -k median
python test/test_torch.py -k median
python test/test_torch.py -k nondeterministic_alert
python test/test_ops.py -k median
python test/test_meta.py -k median
```

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

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

Co-authored-by: Jeff Daily <[email protected]>
jeffdaily added a commit to ROCm/pytorch that referenced this pull request Oct 12, 2026
Picks up pytorch#199848 and pytorch#199947, which postdate the branch base. Clean merge, no conflicts.
pytorchmergebot pushed a commit that referenced this pull request Oct 12, 2026
## 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).

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

Co-authored-by: Jeff Daily <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Oct 15, 2026
## 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).

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

Co-authored-by: Jeff Daily <[email protected]>
torchxpubot pushed a commit to intel/torch-xpu-ops that referenced this pull request Nov 3, 2026
…`test_torch.py` (#5943)

## Summary
After pytorch/pytorch#197120 was merged,
`test/test_torch.py` instantiates its device-type tests with
`allow_xpu=True`, so we can now run the upstream file via
`XPUImportCtx`.
The wrapper imports the upstream test classes, instantiates them for XPU
only, and restores the XPU coverage upstream doesn't have yet. Each
restore links its issue, so it can be dropped once the matching upstream
change lands.

Fixes: #5839

## XPU coverage restored in the wrapper
- `test_scatter_reduce_*` (#5376)
- `test_masked_scatter` (#5286)
- `test_nondeterministic_alert_histc` (#5304)
- `test_split_with_sizes_copy_out`, non-empty cases (#5661)
- `test_terminate_handler_on_crash` (#5309)
- `test_memory_format_cpu_and_cuda_ops`,
`test_addcmul_cuda_errors_with_cpu_scalars` (CUDA-only upstream)
- `@dtypesIfXPU` lists of `test_bernoulli_p`, `test_bernoulli_self`,
`test_diff`, `test_addcdiv`, `test_multinomial_cpu`,
`test_from_sequence`

Not restored, because upstream removed or moved them:
`test_nondeterministic_alert_median` (pytorch/pytorch#199947) and
`TestTorch::test_bf16_supported_on_cpu` (now in the CPU-only
`TestTorchCPU`).

## Coverage comparison
B580, pytorch 06413cc8b6c + torch-xpu-ops 73a6552,
`PYTORCH_TEST_WITH_SLOW=1`, run from `test/xpu` as in CI. BEFORE = old
`test_torch_xpu.py` with its skip list; AFTER = the `XPUImportCtx`
wrapper.

|  | BEFORE | AFTER | CHANGE |
| - | - | - | - |
| PASSED | 879 | 1081 | 202 |
| FAILED | 1 | 0 | -1 |
| SKIPPED | 52 | 106 | 54 |
| TOTAL | 932 | 1187 | 255 |

- BEFORE matches the Nightly op_ut result exactly.
- Every test that passed BEFORE still passes AFTER, except the two not
restored (a few were renamed upstream, e.g. `test_cdist_cuda_backward` →
`test_cdist_device_backward`).
- Newly passing tests include
`test_cpp_warnings_have_python_context_xpu` (#5839). About 170 of the
new passes are tests the old copy didn't have.
- Almost all of the new skips are new upstream `@onlyCUDA` tests
(`test_copy_strided_chunk_*`, `test_copy_transpose_tiled_*`).

This branch is being deployed

1 in progress deployment
bedrock — ab4db066 Deployed Oct 7, 2026 by jeffdaily
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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 open source release notes: cuda release notes category release notes: rocm mandatorylabel

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants