Repository navigation
Make topk deterministic under deterministic algorithms - #186653
sanketpurandare wants to merge 1 commit into
Conversation
🔗 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 SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ❌ 2 New FailuresAs of commit b98c024 with merge base fa4b665 ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
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
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
|
TopK perf benchmark details I ran the same CUDA-event microbenchmark on the parent and on this PR. The benchmark measures 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:
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:
Parent default vs current default:
|
| // See Note [Enabling Deterministic Operations] | ||
| const bool deterministic = at::globalContext().deterministicAlgorithms(); | ||
|
|
||
| #if defined(USE_ROCM) |
There was a problem hiding this comment.
rcom uses stable full sort in deterministic mode because its gather path can reserve tie slots through atomics.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Yes with deterministic mode we were being silently non determ
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
nit maybe leave this coment I think its helpful
There was a problem hiding this comment.
Left as is on top
| ) | ||
|
|
||
| @onlyCUDA | ||
| def test_topk_deterministic_tie_breaking_cuda_multiblock(self, device): |
There was a problem hiding this comment.
can we confirm stable=True preserves index order for equal keys for 129 <= k <= 4096, or add a tied-value test with k > 128?
There was a problem hiding this comment.
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.
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
db03709 to
fa4b665
Compare
9655984 to
b98c024
Compare
|
@pytorchbot merge -i |
Merge startedYour 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 |
|
@pytorchmergebot revert -m "failing some internal ads tests - see D108014200 for signal" -c ghfirst |
|
@pytorchbot successfully started a revert job. Check the current status here. |
…)" 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)))
|
@sanketpurandare your PR has been successfully reverted. |
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.
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.
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
…ch#186653)" This reverts commit 1100802. Reverted pytorch#186653 on behalf of https://github.com/wdvr due to failing some internal ads tests - see D108014200 for signal ([comment](pytorch#186653 (comment)))
…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]>
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
…ch#186653)" This reverts commit 1100802. Reverted pytorch#186653 on behalf of https://github.com/wdvr due to failing some internal ads tests - see D108014200 for signal ([comment](pytorch#186653 (comment)))
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
…ch#186653)" This reverts commit 1100802. Reverted pytorch#186653 on behalf of https://github.com/wdvr due to failing some internal ads tests - see D108014200 for signal ([comment](pytorch#186653 (comment)))
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
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