Skip to content

Make topk deterministic under deterministic algorithms - #186653

Closed
sanketpurandare wants to merge 1 commit into
gh/sanketpurandare/2/basefrom
gh/sanketpurandare/2/head
Closed

sanketpurandare wants to merge 1 commit into
gh/sanketpurandare/2/basefrom
gh/sanketpurandare/2/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

  • Rebuilt PyTorch from source with CUDA enabled.

  • python -m py_compile test/test_sort_and_select.py torch/init.py torch/_torch_docs.py

  • python test/test_sort_and_select.py -k topk_deterministic

  • python test/test_sort_and_select.py -k topk

  • git diff --check HEAD^

  • lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/init.py torch/_torch_docs.py

cc @manuelcandales @angelayi

@pytorch-bot

pytorch-bot Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures

As of commit b98c024 with merge base fa4b665 (image):

NEW FAILURES - The following jobs have failed:

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

sanketpurandare added a commit that referenced this pull request Jun 8, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

ghstack-source-id: ea49395

Pull Request resolved: #186653
sanketpurandare added a commit that referenced this pull request Jun 8, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

ghstack-source-id: 1810e45

Pull Request resolved: #186653
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

TopK perf benchmark details

I ran the same CUDA-event microbenchmark on the parent and on this PR. The benchmark measures torch.topk(x, k, dim=-1, largest=True, sorted=...) with 30 warmup iterations and 100 timed iterations.

Note: the benchmark was captured just before the final ghstack hash rewrite. The measured trees correspond to the same parent/current code after ghstack rewrote the commits.

Summary:

  • sorted=False: deterministic mode is effectively unchanged in this benchmark set. Median current-build overhead was +0.03%.
  • sorted=True: deterministic mode pays the expected stable selected-output sort cost. Median current-build overhead was +3.24%; max in these cases was +8.8% for small k=8 router-like shapes.
  • Current default mode vs parent default mode did not show a regression in this run. The parent/current numbers are noisy, but current was generally faster in this sample.

Benchmark script:

import torch

assert torch.cuda.is_available()
print(f"version,{torch.__version__},{torch.version.git_version}")
print("case,dtype,pattern,shape,k,sorted,deterministic,ms")

def make(shape, dtype, pattern):
    if pattern == "random":
        torch.manual_seed(123)
        return torch.randn(shape, device="cuda", dtype=dtype)
    if pattern == "ties":
        return torch.ones(shape, device="cuda", dtype=dtype)
    raise AssertionError(pattern)

def bench(x, k, sorted_flag, deterministic, iters=100, warmup=30):
    torch.use_deterministic_algorithms(deterministic)
    for _ in range(warmup):
        torch.topk(x, k, dim=-1, largest=True, sorted=sorted_flag)
    torch.cuda.synchronize()
    start = torch.cuda.Event(enable_timing=True)
    end = torch.cuda.Event(enable_timing=True)
    start.record()
    for _ in range(iters):
        torch.topk(x, k, dim=-1, largest=True, sorted=sorted_flag)
    end.record()
    torch.cuda.synchronize()
    return start.elapsed_time(end) / iters

cases = [
    ("router_small", (8192, 256), 8, "random"),
    ("router_large", (32768, 256), 8, "random"),
    ("mb_many_rows", (4096, 1024), 8, "random"),
    ("mb_threshold_random", (2, 20000), 128, "random"),
    ("mb_threshold_ties", (2, 20000), 128, "ties"),
    ("large_selected_random", (2, 10000), 5000, "random"),
    ("large_selected_ties", (2, 10000), 5000, "ties"),
    ("mb_large_selected_ties", (2, 20000), 5000, "ties"),
]

try:
    for dtype in (torch.float32, torch.bfloat16):
        for name, shape, k, pattern in cases:
            x = make(shape, dtype, pattern)
            for sorted_flag in (True, False):
                for deterministic in (False, True):
                    ms = bench(x, k, sorted_flag, deterministic)
                    print(
                        f"{name},{dtype},{pattern},{shape},{k},"
                        f"{sorted_flag},{deterministic},{ms:.6f}"
                    )
finally:
    torch.use_deterministic_algorithms(False)

Current PR: deterministic vs non-deterministic mode, same build:

case dtype sorted non-det ms det ms det delta
router_small float32 True 0.108579 0.118125 +8.8%
router_small float32 False 0.099021 0.099123 +0.1%
router_large float32 True 0.401357 0.433250 +7.9%
router_large float32 False 0.376444 0.376551 +0.0%
mb_many_rows float32 True 0.149117 0.153001 +2.6%
mb_many_rows float32 False 0.141713 0.141844 +0.1%
mb_threshold_random float32 True 0.069677 0.069638 -0.1%
mb_threshold_random float32 False 0.061834 0.061900 +0.1%
mb_threshold_ties float32 True 0.068635 0.068539 -0.1%
mb_threshold_ties float32 False 0.061158 0.061167 +0.0%
large_selected_random float32 True 0.133212 0.137570 +3.3%
large_selected_random float32 False 0.046561 0.046510 -0.1%
large_selected_ties float32 True 0.137249 0.141561 +3.1%
large_selected_ties float32 False 0.060200 0.060210 +0.0%
mb_large_selected_ties float32 True 0.138883 0.143342 +3.2%
mb_large_selected_ties float32 False 0.061447 0.061566 +0.2%
router_small bfloat16 True 0.106375 0.115198 +8.3%
router_small bfloat16 False 0.097390 0.097549 +0.2%
router_large bfloat16 True 0.398425 0.423512 +6.3%
router_large bfloat16 False 0.371554 0.371678 +0.0%
mb_many_rows bfloat16 True 0.103100 0.106240 +3.0%
mb_many_rows bfloat16 False 0.095460 0.095652 +0.2%
mb_threshold_random bfloat16 True 0.051110 0.051128 +0.0%
mb_threshold_random bfloat16 False 0.044936 0.045016 +0.2%
mb_threshold_ties bfloat16 True 0.050277 0.049968 -0.6%
mb_threshold_ties bfloat16 False 0.045700 0.045429 -0.6%
large_selected_random bfloat16 True 0.103699 0.107917 +4.1%
large_selected_random bfloat16 False 0.038894 0.038883 -0.0%
large_selected_ties bfloat16 True 0.100977 0.105220 +4.2%
large_selected_ties bfloat16 False 0.038315 0.038268 -0.1%
mb_large_selected_ties bfloat16 True 0.106492 0.111162 +4.4%
mb_large_selected_ties bfloat16 False 0.046114 0.045442 -1.5%

Parent default vs current default:

case dtype sorted parent ms current ms delta
router_small float32 True 0.125955 0.108579 -13.8%
router_small float32 False 0.103136 0.099021 -4.0%
router_large float32 True 0.453744 0.401357 -11.5%
router_large float32 False 0.429144 0.376444 -12.3%
mb_many_rows float32 True 0.158976 0.149117 -6.2%
mb_many_rows float32 False 0.145781 0.141713 -2.8%
mb_threshold_random float32 True 0.081499 0.069677 -14.5%
mb_threshold_random float32 False 0.062721 0.061834 -1.4%
mb_threshold_ties float32 True 0.070491 0.068635 -2.6%
mb_threshold_ties float32 False 0.080370 0.061158 -23.9%
large_selected_random float32 True 0.149584 0.133212 -10.9%
large_selected_random float32 False 0.049428 0.046561 -5.8%
large_selected_ties float32 True 0.153702 0.137249 -10.7%
large_selected_ties float32 False 0.060164 0.060200 +0.1%
mb_large_selected_ties float32 True 0.150855 0.138883 -7.9%
mb_large_selected_ties float32 False 0.069135 0.061447 -11.1%
router_small bfloat16 True 0.106422 0.106375 -0.0%
router_small bfloat16 False 0.110398 0.097390 -11.8%
router_large bfloat16 True 0.460187 0.398425 -13.4%
router_large bfloat16 False 0.428820 0.371554 -13.4%
mb_many_rows bfloat16 True 0.116715 0.103100 -11.7%
mb_many_rows bfloat16 False 0.099891 0.095460 -4.4%
mb_threshold_random bfloat16 True 0.059557 0.051110 -14.2%
mb_threshold_random bfloat16 False 0.051181 0.044936 -12.2%
mb_threshold_ties bfloat16 True 0.052889 0.050277 -4.9%
mb_threshold_ties bfloat16 False 0.051166 0.045700 -10.7%
large_selected_random bfloat16 True 0.106556 0.103699 -2.7%
large_selected_random bfloat16 False 0.042153 0.038894 -7.7%
large_selected_ties bfloat16 True 0.113215 0.100977 -10.8%
large_selected_ties bfloat16 False 0.038270 0.038315 +0.1%
mb_large_selected_ties bfloat16 True 0.120620 0.106492 -11.7%
mb_large_selected_ties bfloat16 False 0.050073 0.046114 -7.9%

@sanketpurandare sanketpurandare added module: core aten Related to change to the Core ATen opset ciflow/op-benchmark Trigger microbenchmark for operations. ciflow/torchtitan Run TorchTitan integration tests labels Jun 8, 2026
// See Note [Enabling Deterministic Operations]
const bool deterministic = at::globalContext().deterministicAlgorithms();

#if defined(USE_ROCM)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why the rocm speical case?

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.

rcom uses stable full sort in deterministic mode because its gather path can reserve tie slots through atomics.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

hmmm so this will likely be a big perf hit?

what used to happen with deterministic mode? we would just silently be non determ right? if so I think thats find and worth the hit

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.

Yes with deterministic mode we were being silently non determ

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 a comment explaining the rocm case and kept the full stable-sort fallback scoped to rocm deterministic mode only. Default mode is unchanged, and nvidia deterministic mode still uses gather + stable sort of the selected top-k outputs rather than full sorting the input.

queue[j].second = j;
}

// we want nan to be sorted as top for numpy compatibility

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit maybe leave this coment I think its helpful

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.

Left as is on top

)

@onlyCUDA
def test_topk_deterministic_tie_breaking_cuda_multiblock(self, device):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can we confirm stable=True preserves index order for equal keys for 129 <= k <= 4096, or add a tied-value test with k > 128?

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.

Added a multiblock deterministic tie test for k covering [128, 129, 4096]. It uses all-equal inputs and checks that both largest/smallest sorted topk return indices arange(k), so it covers stable tie-breaking beyond the small-sort path.

Comment thread test/test_sort_and_select.py Resolved
@sanketpurandare sanketpurandare removed the ciflow/op-benchmark Trigger microbenchmark for operations. label Jun 8, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- Rebuilt PyTorch from source with CUDA enabled.

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- python test/test_sort_and_select.py -k topk_deterministic

- python test/test_sort_and_select.py -k topk

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

ghstack-source-id: c9b6207

Pull Request resolved: #186653
@sanketpurandare
sanketpurandare force-pushed the gh/sanketpurandare/2/base branch from db03709 to fa4b665 Compare June 9, 2026 00:28
@sanketpurandare
sanketpurandare force-pushed the gh/sanketpurandare/2/head branch from 9655984 to b98c024 Compare June 9, 2026 00:28
@sanketpurandare sanketpurandare added release notes: cuda release notes category ciflow/trunk Trigger trunk jobs on your pull request labels Jun 9, 2026
@sanketpurandare

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test-osdc (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8)

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

@wdvr

wdvr commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

@pytorchmergebot revert -m "failing some internal ads tests - see D108014200 for signal" -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 Jun 11, 2026
…)"

This reverts commit 1100802.

Reverted #186653 on behalf of https://github.com/wdvr due to failing some internal ads tests - see D108014200 for signal ([comment](#186653 (comment)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@sanketpurandare your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Jun 11, 2026
sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Jun 12, 2026
Reverts #3600

Upstream PyTorch PR: pytorch/pytorch#186653 was
reverted due to failing internal tests. They have been using `topk`
under the deterministic algorithms context incorrectly. So this change
altered their numerics which was expected, but I will need to convince
them that it is the right step forward. So reverting this for now, will
reland when upstream op is landed.
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jun 12, 2026
Reverts pytorch#3600

Upstream PyTorch PR: pytorch/pytorch#186653 was
reverted due to failing internal tests. They have been using `topk`
under the deterministic algorithms context incorrectly. So this change
altered their numerics which was expected, but I will need to convince
them that it is the right step forward. So reverting this for now, will
reland when upstream op is landed.
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- Rebuilt PyTorch from source with CUDA enabled.

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- python test/test_sort_and_select.py -k topk_deterministic

- python test/test_sort_and_select.py -k topk

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

Pull Request resolved: pytorch#186653
Approved by: https://github.com/drisspg
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
malfet pushed a commit that referenced this pull request Jun 15, 2026
…gorithms (#186653)" (#187349)

Revert "Make topk deterministic under deterministic algorithms (#186653)"

This reverts commit 1100802.

Reverted #186653 on behalf of https://github.com/wdvr due to failing some internal ads tests - see D108014200 for signal ([comment](#186653 (comment)))

(cherry picked from commit ca8348e)

Co-authored-by: PyTorch MergeBot <[email protected]>
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- Rebuilt PyTorch from source with CUDA enabled.

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- python test/test_sort_and_select.py -k topk_deterministic

- python test/test_sort_and_select.py -k topk

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

Pull Request resolved: pytorch#186653
Approved by: https://github.com/drisspg
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
When torch.use_deterministic_algorithms(True) is enabled, make topk resolve tied values with stable index tie-breaking.

CPU topk now compares by value and then index in deterministic mode. CUDA keeps the existing top-k selection path and uses stable sorting for the selected top-k outputs so threshold ties preserve input-index order without falling back to a full sort on NVIDIA. ROCm uses stable sort in deterministic mode because its current top-k gather reserves tie slots through atomics.

This gives deterministic mode a topk behavior analogous to scatter_add: fast default kernels remain available, while deterministic mode uses stable algorithms when requested.

Test Plan:

- Rebuilt PyTorch from source with CUDA enabled.

- python -m py_compile test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

- python test/test_sort_and_select.py -k topk_deterministic

- python test/test_sort_and_select.py -k topk

- git diff --check HEAD^

- lintrunner --config=.lintrunner.toml --skip=PYREFLY aten/src/ATen/native/TopKImpl.h aten/src/ATen/native/cuda/TensorTopK.cpp test/test_sort_and_select.py torch/__init__.py torch/_torch_docs.py

Pull Request resolved: pytorch#186653
Approved by: https://github.com/drisspg
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: core aten Related to change to the Core ATen opset release notes: cuda release notes category Reverted Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants