Skip to content

Fix race condition and make CUDA kthvalue deterministic - #165762

Closed
nick-kuhn wants to merge 4 commits into
pytorch:mainfrom
nick-kuhn:feat/kthvalue-kernel-determinism
Closed

nick-kuhn wants to merge 4 commits into
pytorch:mainfrom
nick-kuhn:feat/kthvalue-kernel-determinism

Conversation

@nick-kuhn

@nick-kuhn nick-kuhn commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor

The gatherKthValue kernel had a race condition where multiple threads could write to the same output location without synchronization when duplicate k-th values exist, resulting in non-deterministic output.

Changes:

  • aten/src/ATen/native/cuda/Sorting.cu: Use atomicMin with shared memory to deterministically find minimum index. Add early termination and remove redundant inRange checks. (We have to cast the index to int32_t, but this is already assumed to fit earlier in the kernel.)
  • aten/src/ATen/native/cuda/Sorting.cpp: Remove non-deterministic alert since kthvalue is now deterministic on CUDA.
  • torch/init.py: Remove kthvalue from non-deterministic operations list and remove kthvalue example from use_deterministic_algorithms() docstring.
  • test/test_torch.py: Remove test_nondeterministic_alert_kthvalue since kthvalue no longer raises alerts on CUDA.

Benefits:

  • Deterministic: always returns minimum index when duplicates exist
  • Potential performance improvement on large arrays with repetitions

Test Results:

  • All existing PyTorch tests pass (test_kthvalue)
  • Custom determinism tests confirm consistent results
  • Custom CUDA vs CPU correctness validated across 50+ scenarios
  • Custom performance benchmarks show improvements with no visible regressions

Addresses #165227

The gatherKthValue kernel had a race condition where multiple threads
could write to the same output location without synchronization when
duplicate k-th values exist, resulting in non-deterministic output.

Changes:
- aten/src/ATen/native/cuda/Sorting.cu: Use atomicMin with shared memory
  to deterministically find minimum index. Add early termination and remove
  redundant inRange checks. (We have to cast the index to `int32_t`, but this is already assumed to fit earlier in the kernel.)
- aten/src/ATen/native/cuda/Sorting.cpp: Remove non-deterministic alert
  since kthvalue is now deterministic on CUDA.
- torch/__init__.py: Remove kthvalue from non-deterministic operations list
  and remove kthvalue example from use_deterministic_algorithms() docstring.
- test/test_torch.py: Remove test_nondeterministic_alert_kthvalue since
  kthvalue no longer raises alerts on CUDA.

Benefits:
- Deterministic: always returns minimum index when duplicates exist
- Faster: 10-23% performance improvement on large arrays
- Correct: eliminates undefined behavior from concurrent writes

Test Results:
- All existing PyTorch tests pass (test_kthvalue)
- Custom determinism tests confirm consistent results
- Custom CUDA vs CPU correctness validated across 50+ scenarios
- Custom erformance benchmarks show improvements with no visible regressions
@pytorch-bot

pytorch-bot Bot commented Oct 17, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 17, 2025 •

Copy link
Copy Markdown

CLA Signed

The committers listed above are authorized under a signed CLA.

@mikaylagawarecki mikaylagawarecki added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 17, 2025
@nick-kuhn

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "module: determinism", "release notes: cuda"

@pytorch-bot

pytorch-bot Bot commented Oct 17, 2025

Copy link
Copy Markdown

Didn't find following labels among repository labels: module: determinism,

@pytorch-bot pytorch-bot Bot added the release notes: cuda release notes category label Oct 17, 2025
// Find the index of the k-th highest element
index_t kValueIndex = 0;
bool foundKValue = false;
__shared__ int32_t minIndexFound;

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.

this (and atomic below) won't correctly work when the kernel is launched with index_t = int64_t, for large slices that require 64-bit indexing

@nick-kuhn nick-kuhn Oct 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is already an implicit condition for the radix sort earlier in the kernel and the function currently fails silently if the length exceeds int32. (e.g. see the simple example here). Hence, I didn't attempt to address this case, but maybe one should add an error/warning to the current CUDA implementation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Happy for suggestions on how to proceed.

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 checking! Can you please error out in this case then? Does instantiating with index_t = int64_t ever make sense, or will it only lead to silent wrong results?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I added the error message. The index_t is determined by the total size of the tensor, and can be int64_t, as long as the size of each slice (i.e. the dimension kthvalue is taken along) fits into int32_t (we have to cast back and forth).

Check that slice size does not exceed int32_t max, as this is assumed by the current implementation.
@nick-kuhn
nick-kuhn force-pushed the feat/kthvalue-kernel-determinism branch from 975b1f6 to 999feba Compare October 19, 2025 17:56
@ngimel ngimel added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 24, 2025
@ngimel

ngimel commented Oct 24, 2025

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 pushed a commit that referenced this pull request Oct 7, 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. #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: #199947
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
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: cuda release notes category 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.

6 participants