Skip to content

Remove CUDA sync in torch.combinations to improve torch.compile support - #186595

Closed
lgeiger wants to merge 7 commits into
pytorch:mainfrom
lgeiger:combinations-compile
Closed

lgeiger wants to merge 7 commits into
pytorch:mainfrom
lgeiger:combinations-compile

Conversation

@lgeiger

@lgeiger lgeiger commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Currently torch.combinations causes a CUDA sync due to masked_select being data dependent. This PR changes the implementation to statically compute the number of combinations and uses nonzero_static to compute the indices with a statically known shape.

I did some quick benchmarks on CPU and GPU with the following script. Performance on CPU and GPU is much better, especially for large inputs. ~~GPU memory usage in eager mode is slightly larger, but significantly lower when compiled since we don't have a graph break anymore.~~fixed below

Full Benchmarking script

import torch
import time
import pandas as pd

def run_benchmark(device, n_sizes, r_values, num_runs=5, warmups=2, compiled=False):
    results = []

    def run_comb(x, r):
        return torch.combinations(x, r=r)

    func = torch.compile(run_comb) if compiled else run_comb

    for n in n_sizes:
        for r in r_values:
            x = torch.randn(n, device=device)
            for _ in range(warmups):
                _ = func(x, r=r)

            memory_used = None
            if device.startswith("cuda"):
                torch.cuda.reset_peak_memory_stats(device)
                _ = func(x, r=r)
                torch.cuda.synchronize(device)
                memory_used = torch.cuda.max_memory_allocated(device) / (1024 * 1024)  # convert bytes to MB

            start_time = time.perf_counter()
            for _ in range(num_runs):
                _ = func(x, r=r)
                if device.startswith("cuda"):
                    torch.cuda.synchronize(device)
            end_time = time.perf_counter()
            execution_time = (end_time - start_time) / num_runs * 1000  # ms

            device_str = f"{device.upper()} (compiled)" if compiled else f"{device.upper()} (eager)"
            results.append({
                "Device": device_str,
                "N": n,
                "R": r,
                "Num Combinations": torch.combinations(x, r=r).shape[0],
                "Execution Time (ms)": f"{execution_time:.3f}",
                "Memory Usage (MB)": f"{memory_used:.3f}" if memory_used is not None else "N/A",
            })

    return results

if __name__ == "__main__":
    n_sizes = [100, 200, 300]

    print("Benchmarking on CPU (eager)...")
    cpu_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=False)
    print("Benchmarking on CPU (compiled)...")
    cpu_compiled_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=True)

    cuda_results = []
    cuda_compiled_results = []
    if torch.cuda.is_available():
        print("Benchmarking on CUDA (eager)...")
        cuda_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=False)
        print("Benchmarking on CUDA (compiled)...")
        cuda_compiled_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=True)

    all_results = cpu_results + cpu_compiled_results + cuda_results + cuda_compiled_results
    df = pd.DataFrame(all_results)

    df = df.sort_values(by=["Device", "R", "N"])

    print("\nBenchmark Results:")
    print(df.to_string(index=False))

main:

         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.096               N/A
 CPU (compiled) 200  2             19900               0.229               N/A
 CPU (compiled) 300  2             44850               0.384               N/A
 CPU (compiled) 100  3            161700               2.692               N/A
 CPU (compiled) 200  3           1313400             110.978               N/A
 CPU (compiled) 300  3           4455100             392.575               N/A
    CPU (eager) 100  2              4950               0.074               N/A
    CPU (eager) 200  2             19900               0.229               N/A
    CPU (eager) 300  2             44850               0.338               N/A
    CPU (eager) 100  3            161700              13.006               N/A
    CPU (eager) 200  3           1313400             109.279               N/A
    CPU (eager) 300  3           4455100             387.542               N/A
CUDA (compiled) 100  2              4950               0.206             0.162
CUDA (compiled) 200  2             19900               0.199             0.647
CUDA (compiled) 300  2             44850               0.205             1.457
CUDA (compiled) 100  3            161700               0.274             8.358
CUDA (compiled) 200  3           1313400               0.340            67.753
CUDA (compiled) 300  3           4455100               0.835           229.690
CUDA (compiled) 100  4           3921225               2.845           335.668
CUDA (compiled) 200  4          64684950              55.691          5474.059
CUDA (compiled) 300  4         330791175             282.391         27914.657
   CUDA (eager) 100  2              4950               0.180             0.162
   CUDA (eager) 200  2             19900               0.167             0.647
   CUDA (eager) 300  2             44850               0.174             1.457
   CUDA (eager) 100  3            161700               0.244             8.358
   CUDA (eager) 200  3           1313400               0.316            67.753
   CUDA (eager) 300  3           4455100               0.818           229.690
   CUDA (eager) 100  4           3921225               2.821           335.668
   CUDA (eager) 200  4          64684950              55.851          5474.059
   CUDA (eager) 300  4         330791175             283.848         27914.657

This PR: (see better benchmarks below)

         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.131               N/A
 CPU (compiled) 200  2             19900               0.276               N/A
 CPU (compiled) 300  2             44850               0.461               N/A
 CPU (compiled) 100  3            161700               1.839               N/A
 CPU (compiled) 200  3           1313400              24.267               N/A
 CPU (compiled) 300  3           4455100              84.516               N/A
    CPU (eager) 100  2              4950               0.073               N/A
    CPU (eager) 200  2             19900               0.216               N/A
    CPU (eager) 300  2             44850               0.412               N/A
    CPU (eager) 100  3            161700               3.078               N/A
    CPU (eager) 200  3           1313400              24.326               N/A
    CPU (eager) 300  3           4455100              87.258               N/A
CUDA (compiled) 100  2              4950               0.105             0.152
CUDA (compiled) 200  2             19900               0.100             0.608
CUDA (compiled) 300  2             44850               0.100             1.371
CUDA (compiled) 100  3            161700               0.109             7.403
CUDA (compiled) 200  3           1313400               0.149            60.124
CUDA (compiled) 300  3           4455100               0.351           203.940
CUDA (compiled) 100  4           3921225               1.510           275.838
CUDA (compiled) 200  4          64684950              24.367          4487.048
CUDA (compiled) 300  4         330791175             138.127         22867.187
   CUDA (eager) 100  2              4950               0.111             0.228
   CUDA (eager) 200  2             19900               0.100             0.912
   CUDA (eager) 300  2             44850               0.121             2.055
   CUDA (eager) 100  3            161700               0.121            11.104
   CUDA (eager) 200  3           1313400               0.137            90.186
   CUDA (eager) 300  3           4455100               0.465           305.910
   CUDA (eager) 100  4           3921225               1.599           359.667
   CUDA (eager) 200  4          64684950              28.038          5922.086
   CUDA (eager) 300  4         330791175             199.538         30284.839

/cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @ezyang @ngimel
Fixes #74324

@lgeiger
lgeiger requested a review from mruberry as a code owner June 8, 2026 12:11
@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/186595

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

❌ 1 New Failure

As of commit 87cf6cc with merge base 08467ff (image):

NEW FAILURE - The following job has failed:

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

@pytorch-bot pytorch-bot Bot added the ciflow/dtensor Run DTensor specific tests label Jun 8, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@lgeiger

lgeiger commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: cuda"

@pytorch-bot pytorch-bot Bot added the release notes: cuda release notes category label Jun 8, 2026
@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 8, 2026
@zou3519
zou3519 requested review from eqy and ngimel June 8, 2026 14:07

@eqy eqy 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.

Where does the extra memory usage come from, is it from the index_select call? (and so would only be present with autograd enabled)?

@lgeiger

lgeiger commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Where does the extra memory usage come from, is it from the index_select call? (and so would only be present with autograd enabled)?

@eqy I did a quick memory profile and indeed the extra memory usage is coming from index_select and the extra index handling. EDIT: the extra memory usage comes from indices.flatten() which causes a copy since indices are non-contiguous.

I switched to a simple index op in 1f86596 which performs much better in eager mode and fixes the memory usage increase though performance within compile seems to be slightly worse:

This PR plain index:

         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.098               N/A
 CPU (compiled) 200  2             19900               0.231               N/A
 CPU (compiled) 300  2             44850               0.430               N/A
 CPU (compiled) 100  3            161700               1.999               N/A
 CPU (compiled) 200  3           1313400              25.058               N/A
 CPU (compiled) 300  3           4455100              92.568               N/A
    CPU (eager) 100  2              4950               0.099               N/A
    CPU (eager) 200  2             19900               0.296               N/A
    CPU (eager) 300  2             44850               0.445               N/A
    CPU (eager) 100  3            161700               3.197               N/A
    CPU (eager) 200  3           1313400              24.443               N/A
    CPU (eager) 300  3           4455100              80.598               N/A
CUDA (compiled) 100  2              4950               0.093             0.152
CUDA (compiled) 200  2             19900               0.096             0.608
CUDA (compiled) 300  2             44850               0.094             1.371
CUDA (compiled) 100  3            161700               0.113             7.403
CUDA (compiled) 200  3           1313400               0.141            60.124
CUDA (compiled) 300  3           4455100               0.365           203.940
CUDA (compiled) 100  4           3921225               1.521           275.838
CUDA (compiled) 200  4          64684950              25.559          4487.048
CUDA (compiled) 300  4         330791175             145.004         22867.187
   CUDA (eager) 100  2              4950               0.086             0.152
   CUDA (eager) 200  2             19900               0.086             0.608
   CUDA (eager) 300  2             44850               0.086             1.371
   CUDA (eager) 100  3            161700               0.091             7.403
   CUDA (eager) 200  3           1313400               0.124            60.124
   CUDA (eager) 300  3           4455100               0.337           203.940
   CUDA (eager) 100  4           3921225               1.433           275.838
   CUDA (eager) 200  4          64684950              25.390          4487.048
   CUDA (eager) 300  4         330791175             128.544         22867.187

Overall this is now much faster and uses less memory than on main.

@jansel

jansel commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, are they related to this PR?

@claude

claude Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 34s —— View job


CI failure analysis

I pulled the logs for the three reported failures. Here's the breakdown:

1. inductor / ... test_comprehensive_combinations_cuda_float32 — ❌ Related to this PR

This is a real failure caused by your change. The test fails with a stride mismatch:

AssertionError: Significant strides mismatch at leaf 0, dim 0:
(2, 1) != (1, 3) for shape torch.Size([3, 2])

The opinfo harness (check_model_gpu → _assert_same_significant_strides) requires Inductor's output layout to match eager. For sample index 9 (n=3, r=2 → 3 combinations), eager returns a contiguous [3, 2] tensor with strides (2, 1), but the Inductor-compiled version produces the transposed layout (1, 3).

This comes from the new self.index({indices}) formulation: indices has shape [num_combinations, r], and Inductor is free to pick a different (column-major) layout for the advanced-index result than eager's contiguous one. The previous masked_select + view path always produced a contiguous result, so the check passed before.

Options to fix:

  • Make the result layout deterministic, e.g. return self.index({indices}).contiguous() (simplest, but adds a copy), or
  • Reshape so the gather produces a contiguous layout matching eager, or
  • If the differing-but-valid stride is acceptable, add combinations to the inductor opinfo stride-check skip list (test/inductor/test_torchinductor_opinfo.py) — but fixing the layout is preferable to skipping the check.

2. torchtitan-test (both ..._features_integration and ..._models_integration) — ✅ NOT related (infra)

Both jobs failed during environment setup, not in any test. The pip install of torchao/torchcomms from the nightly index hit a network error:

ERROR: Could not install packages due to an OSError:
HTTPSConnectionPool(host='files.pythonhosted.org', port=443):
Max retries exceeded ... ConnectionResetError(104, 'Connection reset by peer')
...
subprocess.CalledProcessError: Command '[... pip install --pre torchao torchcomms
--index-url https://download.pytorch.org/whl/nightly/cu130]' returned non-zero exit status 1.

The generic [OSDC] Step script exited with code 1 message is just the wrapper reporting the failed setup step. This is transient infra/network flakiness and unrelated to your change — it should clear on a re-run.

3. inductor (1, 2) FLAKY shard — ✅ NOT related

Already classified by Dr. CI as infra-flaky (no log / failing log classifier).


Summary

Failure Related? Cause
test_comprehensive_combinations_cuda_float32 Yes Inductor output stride (1,3) vs eager (2,1) from the new index gather
torchtitan ×2 No Network error installing torchao/torchcomms nightly wheels
inductor (1,2) flaky No Infra flakiness

The only one that needs action is the inductor stride check. Fix this →
· inductor failure · torchtitan failure

@lgeiger

lgeiger commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

49a5b09 ensures that the output of combinations in eager mode is also contiguous which should fix CI. This makes the CUDA eager path a tiny bit slower and use a bit more memory but still an improvement over what's on main.

         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.113               N/A
 CPU (compiled) 200  2             19900               0.270               N/A
 CPU (compiled) 300  2             44850               0.395               N/A
 CPU (compiled) 100  3            161700               2.103               N/A
 CPU (compiled) 200  3           1313400              21.555               N/A
 CPU (compiled) 300  3           4455100              71.162               N/A
    CPU (eager) 100  2              4950               0.077               N/A
    CPU (eager) 200  2             19900               0.183               N/A
    CPU (eager) 300  2             44850               0.345               N/A
    CPU (eager) 100  3            161700               2.504               N/A
    CPU (eager) 200  3           1313400              18.495               N/A
    CPU (eager) 300  3           4455100              67.251               N/A
CUDA (compiled) 100  2              4950               0.096             0.152
CUDA (compiled) 200  2             19900               0.086             0.608
CUDA (compiled) 300  2             44850               0.099             1.371
CUDA (compiled) 100  3            161700               0.115             7.403
CUDA (compiled) 200  3           1313400               0.138            60.124
CUDA (compiled) 300  3           4455100               0.358           203.940
CUDA (compiled) 100  4           3921225               1.500           276.005
CUDA (compiled) 200  4          64684950              25.004          4488.034
CUDA (compiled) 300  4         330791175             142.115         22867.714
   CUDA (eager) 100  2              4950               0.097             0.190
   CUDA (eager) 200  2             19900               0.090             0.760
   CUDA (eager) 300  2             44850               0.106             1.713
   CUDA (eager) 100  3            161700               0.105             9.253
   CUDA (eager) 200  3           1313400               0.138            75.155
   CUDA (eager) 300  3           4455100               0.398           254.925
   CUDA (eager) 100  4           3921225               1.499           299.667
   CUDA (eager) 200  4          64684950              26.546          4936.058
   CUDA (eager) 300  4         330791175             147.229         25237.894

@lgeiger

lgeiger commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

7519406 should fix CI

@lgeiger

lgeiger commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -r

Sorry for the delay in merging, I wasn't aware that I have the permissions to simply ask the merge bot to trigger a merge 🤖 🙏

I really appreciate the fast review Natalia!

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 30, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased combinations-compile onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout combinations-compile && git pull --rebase)

@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

@lgeiger
lgeiger deleted the combinations-compile branch July 5, 2026 10:40
@meta-codesync

meta-codesync Bot commented Jul 8, 2026

Copy link
Copy Markdown

@pytorchbot revert -m="Diff reverted internally" -c="ghfirst"

This Pull Request has been reverted by a revert inside Meta. To re-land this change, please open another pull request, assign the same reviewers, fix the CI failures that caused the revert and make sure that the failing CI runs on the PR by applying the proper ciflow label (e.g., ciflow/trunk).)

@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 Jul 8, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@lgeiger your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Jul 8, 2026
@lgeiger

lgeiger commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Any details on why this was reverted?

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…upport (pytorch#186595)

Currently `torch.combinations` causes a CUDA sync due to `masked_select` being data dependent. This PR changes the implementation to statically compute the number of combinations and uses `nonzero_static` to compute the indices with a statically known shape.

I did some quick benchmarks on CPU and GPU with the following script. Performance on CPU and GPU is much better, especially for large inputs. ~~GPU memory usage in eager mode is slightly larger, but significantly lower when compiled since we don't have a graph break anymore.~~fixed below

<details><summary>Full Benchmarking script</summary>
<p>

```python
import torch
import time
import pandas as pd

def run_benchmark(device, n_sizes, r_values, num_runs=5, warmups=2, compiled=False):
    results = []

    def run_comb(x, r):
        return torch.combinations(x, r=r)

    func = torch.compile(run_comb) if compiled else run_comb

    for n in n_sizes:
        for r in r_values:
            x = torch.randn(n, device=device)
            for _ in range(warmups):
                _ = func(x, r=r)

            memory_used = None
            if device.startswith("cuda"):
                torch.cuda.reset_peak_memory_stats(device)
                _ = func(x, r=r)
                torch.cuda.synchronize(device)
                memory_used = torch.cuda.max_memory_allocated(device) / (1024 * 1024)  # convert bytes to MB

            start_time = time.perf_counter()
            for _ in range(num_runs):
                _ = func(x, r=r)
                if device.startswith("cuda"):
                    torch.cuda.synchronize(device)
            end_time = time.perf_counter()
            execution_time = (end_time - start_time) / num_runs * 1000  # ms

            device_str = f"{device.upper()} (compiled)" if compiled else f"{device.upper()} (eager)"
            results.append({
                "Device": device_str,
                "N": n,
                "R": r,
                "Num Combinations": torch.combinations(x, r=r).shape[0],
                "Execution Time (ms)": f"{execution_time:.3f}",
                "Memory Usage (MB)": f"{memory_used:.3f}" if memory_used is not None else "N/A",
            })

    return results

if __name__ == "__main__":
    n_sizes = [100, 200, 300]

    print("Benchmarking on CPU (eager)...")
    cpu_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=False)
    print("Benchmarking on CPU (compiled)...")
    cpu_compiled_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=True)

    cuda_results = []
    cuda_compiled_results = []
    if torch.cuda.is_available():
        print("Benchmarking on CUDA (eager)...")
        cuda_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=False)
        print("Benchmarking on CUDA (compiled)...")
        cuda_compiled_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=True)

    all_results = cpu_results + cpu_compiled_results + cuda_results + cuda_compiled_results
    df = pd.DataFrame(all_results)

    df = df.sort_values(by=["Device", "R", "N"])

    print("\nBenchmark Results:")
    print(df.to_string(index=False))
```

</p>
</details>

**main:**
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.096               N/A
 CPU (compiled) 200  2             19900               0.229               N/A
 CPU (compiled) 300  2             44850               0.384               N/A
 CPU (compiled) 100  3            161700               2.692               N/A
 CPU (compiled) 200  3           1313400             110.978               N/A
 CPU (compiled) 300  3           4455100             392.575               N/A
    CPU (eager) 100  2              4950               0.074               N/A
    CPU (eager) 200  2             19900               0.229               N/A
    CPU (eager) 300  2             44850               0.338               N/A
    CPU (eager) 100  3            161700              13.006               N/A
    CPU (eager) 200  3           1313400             109.279               N/A
    CPU (eager) 300  3           4455100             387.542               N/A
CUDA (compiled) 100  2              4950               0.206             0.162
CUDA (compiled) 200  2             19900               0.199             0.647
CUDA (compiled) 300  2             44850               0.205             1.457
CUDA (compiled) 100  3            161700               0.274             8.358
CUDA (compiled) 200  3           1313400               0.340            67.753
CUDA (compiled) 300  3           4455100               0.835           229.690
CUDA (compiled) 100  4           3921225               2.845           335.668
CUDA (compiled) 200  4          64684950              55.691          5474.059
CUDA (compiled) 300  4         330791175             282.391         27914.657
   CUDA (eager) 100  2              4950               0.180             0.162
   CUDA (eager) 200  2             19900               0.167             0.647
   CUDA (eager) 300  2             44850               0.174             1.457
   CUDA (eager) 100  3            161700               0.244             8.358
   CUDA (eager) 200  3           1313400               0.316            67.753
   CUDA (eager) 300  3           4455100               0.818           229.690
   CUDA (eager) 100  4           3921225               2.821           335.668
   CUDA (eager) 200  4          64684950              55.851          5474.059
   CUDA (eager) 300  4         330791175             283.848         27914.657
```

**This PR:** (see better benchmarks below)
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.131               N/A
 CPU (compiled) 200  2             19900               0.276               N/A
 CPU (compiled) 300  2             44850               0.461               N/A
 CPU (compiled) 100  3            161700               1.839               N/A
 CPU (compiled) 200  3           1313400              24.267               N/A
 CPU (compiled) 300  3           4455100              84.516               N/A
    CPU (eager) 100  2              4950               0.073               N/A
    CPU (eager) 200  2             19900               0.216               N/A
    CPU (eager) 300  2             44850               0.412               N/A
    CPU (eager) 100  3            161700               3.078               N/A
    CPU (eager) 200  3           1313400              24.326               N/A
    CPU (eager) 300  3           4455100              87.258               N/A
CUDA (compiled) 100  2              4950               0.105             0.152
CUDA (compiled) 200  2             19900               0.100             0.608
CUDA (compiled) 300  2             44850               0.100             1.371
CUDA (compiled) 100  3            161700               0.109             7.403
CUDA (compiled) 200  3           1313400               0.149            60.124
CUDA (compiled) 300  3           4455100               0.351           203.940
CUDA (compiled) 100  4           3921225               1.510           275.838
CUDA (compiled) 200  4          64684950              24.367          4487.048
CUDA (compiled) 300  4         330791175             138.127         22867.187
   CUDA (eager) 100  2              4950               0.111             0.228
   CUDA (eager) 200  2             19900               0.100             0.912
   CUDA (eager) 300  2             44850               0.121             2.055
   CUDA (eager) 100  3            161700               0.121            11.104
   CUDA (eager) 200  3           1313400               0.137            90.186
   CUDA (eager) 300  3           4455100               0.465           305.910
   CUDA (eager) 100  4           3921225               1.599           359.667
   CUDA (eager) 200  4          64684950              28.038          5922.086
   CUDA (eager) 300  4         330791175             199.538         30284.839
```
/cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @ezyang @ngimel
Fixes pytorch#74324
Pull Request resolved: pytorch#186595
Approved by: https://github.com/ngimel, https://github.com/jansel
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…upport (pytorch#186595)

Currently `torch.combinations` causes a CUDA sync due to `masked_select` being data dependent. This PR changes the implementation to statically compute the number of combinations and uses `nonzero_static` to compute the indices with a statically known shape.

I did some quick benchmarks on CPU and GPU with the following script. Performance on CPU and GPU is much better, especially for large inputs. ~~GPU memory usage in eager mode is slightly larger, but significantly lower when compiled since we don't have a graph break anymore.~~fixed below

<details><summary>Full Benchmarking script</summary>
<p>

```python
import torch
import time
import pandas as pd

def run_benchmark(device, n_sizes, r_values, num_runs=5, warmups=2, compiled=False):
    results = []

    def run_comb(x, r):
        return torch.combinations(x, r=r)

    func = torch.compile(run_comb) if compiled else run_comb

    for n in n_sizes:
        for r in r_values:
            x = torch.randn(n, device=device)
            for _ in range(warmups):
                _ = func(x, r=r)

            memory_used = None
            if device.startswith("cuda"):
                torch.cuda.reset_peak_memory_stats(device)
                _ = func(x, r=r)
                torch.cuda.synchronize(device)
                memory_used = torch.cuda.max_memory_allocated(device) / (1024 * 1024)  # convert bytes to MB

            start_time = time.perf_counter()
            for _ in range(num_runs):
                _ = func(x, r=r)
                if device.startswith("cuda"):
                    torch.cuda.synchronize(device)
            end_time = time.perf_counter()
            execution_time = (end_time - start_time) / num_runs * 1000  # ms

            device_str = f"{device.upper()} (compiled)" if compiled else f"{device.upper()} (eager)"
            results.append({
                "Device": device_str,
                "N": n,
                "R": r,
                "Num Combinations": torch.combinations(x, r=r).shape[0],
                "Execution Time (ms)": f"{execution_time:.3f}",
                "Memory Usage (MB)": f"{memory_used:.3f}" if memory_used is not None else "N/A",
            })

    return results

if __name__ == "__main__":
    n_sizes = [100, 200, 300]

    print("Benchmarking on CPU (eager)...")
    cpu_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=False)
    print("Benchmarking on CPU (compiled)...")
    cpu_compiled_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=True)

    cuda_results = []
    cuda_compiled_results = []
    if torch.cuda.is_available():
        print("Benchmarking on CUDA (eager)...")
        cuda_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=False)
        print("Benchmarking on CUDA (compiled)...")
        cuda_compiled_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=True)

    all_results = cpu_results + cpu_compiled_results + cuda_results + cuda_compiled_results
    df = pd.DataFrame(all_results)

    df = df.sort_values(by=["Device", "R", "N"])

    print("\nBenchmark Results:")
    print(df.to_string(index=False))
```

</p>
</details>

**main:**
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.096               N/A
 CPU (compiled) 200  2             19900               0.229               N/A
 CPU (compiled) 300  2             44850               0.384               N/A
 CPU (compiled) 100  3            161700               2.692               N/A
 CPU (compiled) 200  3           1313400             110.978               N/A
 CPU (compiled) 300  3           4455100             392.575               N/A
    CPU (eager) 100  2              4950               0.074               N/A
    CPU (eager) 200  2             19900               0.229               N/A
    CPU (eager) 300  2             44850               0.338               N/A
    CPU (eager) 100  3            161700              13.006               N/A
    CPU (eager) 200  3           1313400             109.279               N/A
    CPU (eager) 300  3           4455100             387.542               N/A
CUDA (compiled) 100  2              4950               0.206             0.162
CUDA (compiled) 200  2             19900               0.199             0.647
CUDA (compiled) 300  2             44850               0.205             1.457
CUDA (compiled) 100  3            161700               0.274             8.358
CUDA (compiled) 200  3           1313400               0.340            67.753
CUDA (compiled) 300  3           4455100               0.835           229.690
CUDA (compiled) 100  4           3921225               2.845           335.668
CUDA (compiled) 200  4          64684950              55.691          5474.059
CUDA (compiled) 300  4         330791175             282.391         27914.657
   CUDA (eager) 100  2              4950               0.180             0.162
   CUDA (eager) 200  2             19900               0.167             0.647
   CUDA (eager) 300  2             44850               0.174             1.457
   CUDA (eager) 100  3            161700               0.244             8.358
   CUDA (eager) 200  3           1313400               0.316            67.753
   CUDA (eager) 300  3           4455100               0.818           229.690
   CUDA (eager) 100  4           3921225               2.821           335.668
   CUDA (eager) 200  4          64684950              55.851          5474.059
   CUDA (eager) 300  4         330791175             283.848         27914.657
```

**This PR:** (see better benchmarks below)
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.131               N/A
 CPU (compiled) 200  2             19900               0.276               N/A
 CPU (compiled) 300  2             44850               0.461               N/A
 CPU (compiled) 100  3            161700               1.839               N/A
 CPU (compiled) 200  3           1313400              24.267               N/A
 CPU (compiled) 300  3           4455100              84.516               N/A
    CPU (eager) 100  2              4950               0.073               N/A
    CPU (eager) 200  2             19900               0.216               N/A
    CPU (eager) 300  2             44850               0.412               N/A
    CPU (eager) 100  3            161700               3.078               N/A
    CPU (eager) 200  3           1313400              24.326               N/A
    CPU (eager) 300  3           4455100              87.258               N/A
CUDA (compiled) 100  2              4950               0.105             0.152
CUDA (compiled) 200  2             19900               0.100             0.608
CUDA (compiled) 300  2             44850               0.100             1.371
CUDA (compiled) 100  3            161700               0.109             7.403
CUDA (compiled) 200  3           1313400               0.149            60.124
CUDA (compiled) 300  3           4455100               0.351           203.940
CUDA (compiled) 100  4           3921225               1.510           275.838
CUDA (compiled) 200  4          64684950              24.367          4487.048
CUDA (compiled) 300  4         330791175             138.127         22867.187
   CUDA (eager) 100  2              4950               0.111             0.228
   CUDA (eager) 200  2             19900               0.100             0.912
   CUDA (eager) 300  2             44850               0.121             2.055
   CUDA (eager) 100  3            161700               0.121            11.104
   CUDA (eager) 200  3           1313400               0.137            90.186
   CUDA (eager) 300  3           4455100               0.465           305.910
   CUDA (eager) 100  4           3921225               1.599           359.667
   CUDA (eager) 200  4          64684950              28.038          5922.086
   CUDA (eager) 300  4         330791175             199.538         30284.839
```
/cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @ezyang @ngimel
Fixes pytorch#74324
Pull Request resolved: pytorch#186595
Approved by: https://github.com/ngimel, https://github.com/jansel
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…upport (pytorch#186595)

Currently `torch.combinations` causes a CUDA sync due to `masked_select` being data dependent. This PR changes the implementation to statically compute the number of combinations and uses `nonzero_static` to compute the indices with a statically known shape.

I did some quick benchmarks on CPU and GPU with the following script. Performance on CPU and GPU is much better, especially for large inputs. ~~GPU memory usage in eager mode is slightly larger, but significantly lower when compiled since we don't have a graph break anymore.~~fixed below

<details><summary>Full Benchmarking script</summary>
<p>

```python
import torch
import time
import pandas as pd

def run_benchmark(device, n_sizes, r_values, num_runs=5, warmups=2, compiled=False):
    results = []

    def run_comb(x, r):
        return torch.combinations(x, r=r)

    func = torch.compile(run_comb) if compiled else run_comb

    for n in n_sizes:
        for r in r_values:
            x = torch.randn(n, device=device)
            for _ in range(warmups):
                _ = func(x, r=r)

            memory_used = None
            if device.startswith("cuda"):
                torch.cuda.reset_peak_memory_stats(device)
                _ = func(x, r=r)
                torch.cuda.synchronize(device)
                memory_used = torch.cuda.max_memory_allocated(device) / (1024 * 1024)  # convert bytes to MB

            start_time = time.perf_counter()
            for _ in range(num_runs):
                _ = func(x, r=r)
                if device.startswith("cuda"):
                    torch.cuda.synchronize(device)
            end_time = time.perf_counter()
            execution_time = (end_time - start_time) / num_runs * 1000  # ms

            device_str = f"{device.upper()} (compiled)" if compiled else f"{device.upper()} (eager)"
            results.append({
                "Device": device_str,
                "N": n,
                "R": r,
                "Num Combinations": torch.combinations(x, r=r).shape[0],
                "Execution Time (ms)": f"{execution_time:.3f}",
                "Memory Usage (MB)": f"{memory_used:.3f}" if memory_used is not None else "N/A",
            })

    return results

if __name__ == "__main__":
    n_sizes = [100, 200, 300]

    print("Benchmarking on CPU (eager)...")
    cpu_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=False)
    print("Benchmarking on CPU (compiled)...")
    cpu_compiled_results = run_benchmark("cpu", n_sizes, [2, 3], compiled=True)

    cuda_results = []
    cuda_compiled_results = []
    if torch.cuda.is_available():
        print("Benchmarking on CUDA (eager)...")
        cuda_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=False)
        print("Benchmarking on CUDA (compiled)...")
        cuda_compiled_results = run_benchmark("cuda", n_sizes, [2, 3, 4], compiled=True)

    all_results = cpu_results + cpu_compiled_results + cuda_results + cuda_compiled_results
    df = pd.DataFrame(all_results)

    df = df.sort_values(by=["Device", "R", "N"])

    print("\nBenchmark Results:")
    print(df.to_string(index=False))
```

</p>
</details>

**main:**
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.096               N/A
 CPU (compiled) 200  2             19900               0.229               N/A
 CPU (compiled) 300  2             44850               0.384               N/A
 CPU (compiled) 100  3            161700               2.692               N/A
 CPU (compiled) 200  3           1313400             110.978               N/A
 CPU (compiled) 300  3           4455100             392.575               N/A
    CPU (eager) 100  2              4950               0.074               N/A
    CPU (eager) 200  2             19900               0.229               N/A
    CPU (eager) 300  2             44850               0.338               N/A
    CPU (eager) 100  3            161700              13.006               N/A
    CPU (eager) 200  3           1313400             109.279               N/A
    CPU (eager) 300  3           4455100             387.542               N/A
CUDA (compiled) 100  2              4950               0.206             0.162
CUDA (compiled) 200  2             19900               0.199             0.647
CUDA (compiled) 300  2             44850               0.205             1.457
CUDA (compiled) 100  3            161700               0.274             8.358
CUDA (compiled) 200  3           1313400               0.340            67.753
CUDA (compiled) 300  3           4455100               0.835           229.690
CUDA (compiled) 100  4           3921225               2.845           335.668
CUDA (compiled) 200  4          64684950              55.691          5474.059
CUDA (compiled) 300  4         330791175             282.391         27914.657
   CUDA (eager) 100  2              4950               0.180             0.162
   CUDA (eager) 200  2             19900               0.167             0.647
   CUDA (eager) 300  2             44850               0.174             1.457
   CUDA (eager) 100  3            161700               0.244             8.358
   CUDA (eager) 200  3           1313400               0.316            67.753
   CUDA (eager) 300  3           4455100               0.818           229.690
   CUDA (eager) 100  4           3921225               2.821           335.668
   CUDA (eager) 200  4          64684950              55.851          5474.059
   CUDA (eager) 300  4         330791175             283.848         27914.657
```

**This PR:** (see better benchmarks below)
```
         Device   N  R  Num Combinations Execution Time (ms) Memory Usage (MB)
 CPU (compiled) 100  2              4950               0.131               N/A
 CPU (compiled) 200  2             19900               0.276               N/A
 CPU (compiled) 300  2             44850               0.461               N/A
 CPU (compiled) 100  3            161700               1.839               N/A
 CPU (compiled) 200  3           1313400              24.267               N/A
 CPU (compiled) 300  3           4455100              84.516               N/A
    CPU (eager) 100  2              4950               0.073               N/A
    CPU (eager) 200  2             19900               0.216               N/A
    CPU (eager) 300  2             44850               0.412               N/A
    CPU (eager) 100  3            161700               3.078               N/A
    CPU (eager) 200  3           1313400              24.326               N/A
    CPU (eager) 300  3           4455100              87.258               N/A
CUDA (compiled) 100  2              4950               0.105             0.152
CUDA (compiled) 200  2             19900               0.100             0.608
CUDA (compiled) 300  2             44850               0.100             1.371
CUDA (compiled) 100  3            161700               0.109             7.403
CUDA (compiled) 200  3           1313400               0.149            60.124
CUDA (compiled) 300  3           4455100               0.351           203.940
CUDA (compiled) 100  4           3921225               1.510           275.838
CUDA (compiled) 200  4          64684950              24.367          4487.048
CUDA (compiled) 300  4         330791175             138.127         22867.187
   CUDA (eager) 100  2              4950               0.111             0.228
   CUDA (eager) 200  2             19900               0.100             0.912
   CUDA (eager) 300  2             44850               0.121             2.055
   CUDA (eager) 100  3            161700               0.121            11.104
   CUDA (eager) 200  3           1313400               0.137            90.186
   CUDA (eager) 300  3           4455100               0.465           305.910
   CUDA (eager) 100  4           3921225               1.599           359.667
   CUDA (eager) 200  4          64684950              28.038          5922.086
   CUDA (eager) 300  4         330791175             199.538         30284.839
```
/cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @ezyang @ngimel
Fixes pytorch#74324
Pull Request resolved: pytorch#186595
Approved by: https://github.com/ngimel, https://github.com/jansel
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 1, 2026
## Motivation

#189102 bumped the gradient tolerances for
`test_comprehensive_combinations_cuda_float16` after #186595 / #189305
reimplemented `torch.combinations` on top of `index_put`, whose fp16 backward
Inductor accumulates in fp16. That PR only added the override to
`inductor_override_kwargs["cuda"]`; `inductor_override_kwargs["xpu"]` is a
separate dict and never got the equivalent entry, leaving XPU on the default
fp16 gradient tolerance (`atol=1e-5, rtol=1e-3`), which is too tight for the
fp16 accumulation rounding. Result: #195071
(`test_comprehensive_combinations_xpu_float16`) was disabled on 2026-08-27.

## Root cause on the failing sample

Sample 17: `input=(4,) fp16, r=4, with_replacement=True` -> output `(35, 4)`.
Each of the 4 inputs is copied into 35 output slots, so its gradient is the sum
of 35 fp16 contributions.

Forward is bit-identical between eager and Inductor; only the backward differs.
Inductor lowers the `index_put(accumulate=True)` backward to a single fp16
atomic scatter (`triton_poi_fused_index_put_new_zeros_1`):

```python
tmp6 = tl.load(in_ptr1 + (x0), xmask).to(tl.float32)
tl.atomic_add(out_ptr0 + (tl.broadcast_to(tmp4, [XBLOCK])), tmp6, xmask, sem='relaxed')
```

`out_ptr0` is `*fp16`, so the 35 additions per slot round to fp16 on every step,
in hardware-scheduling order. The XPU aten `index_put` accumulates in higher
precision and rounds once:

```
# accumulate 100 x 0.0002 into an fp16 slot initialised to 1.0 (exact = 1.02)
eager    index_put_(accumulate=True) -> 1.01953125
inductor same op                     -> 1.0          (== naive fp16 read-add-write)
```

Against an fp64 reference on the failing sample:

```
grad(input):
  eager    vs ref-fp64: max_rel = 3.65e-04
  inductor vs ref-fp64: max_rel = 3.99e-03
  inductor vs eager   : max_rel = 1.6e-03 .. 4.9e-03 across runs (>> default rtol=1e-3)
```

The run-to-run spread comes from the nondeterministic atomic order: the same
input produced 14 distinct fp16 results in 20 Inductor runs, vs 1 for eager.
This is intrinsic fp16 accumulation rounding, not a correctness bug on either
side, and matches the situation upstream addressed on CUDA in #189102.

## Fix

Add the same `(combinations, f16)` override that #189102 added for CUDA to
`inductor_override_kwargs["xpu"]`. Observed max abs diff is 1.22e-03 against an
allowance of `2e-3 + 0.01 * 0.5 ~= 7e-3`, i.e. about 5.7x headroom.

## Test plan

Nightly wheel `torch==2.15.0.dev20260830+xpu`, triton-xpu 3.8.0, on Intel Arc
B390. Run from the pytorch checkout root:

```
PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=17 TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# before: FAILED  Tensor-likes are not close! 1/4 mismatched,
#                 rel 1.066e-03 > 1e-03 allowed
# after:  OK
```

All samples, three consecutive runs:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# OK / OK / OK
```

All dtypes, cpu and xpu:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    -k test_comprehensive_combinations -v
```
```
# Ran 14 tests    OK (skipped=2)
```

Fixes #195071

_Note: authored with AI assistance._

Pull Request resolved: #195403
Approved by: https://github.com/etaf, https://github.com/jansel
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…195403)

## Motivation

pytorch#189102 bumped the gradient tolerances for
`test_comprehensive_combinations_cuda_float16` after pytorch#186595 / pytorch#189305
reimplemented `torch.combinations` on top of `index_put`, whose fp16 backward
Inductor accumulates in fp16. That PR only added the override to
`inductor_override_kwargs["cuda"]`; `inductor_override_kwargs["xpu"]` is a
separate dict and never got the equivalent entry, leaving XPU on the default
fp16 gradient tolerance (`atol=1e-5, rtol=1e-3`), which is too tight for the
fp16 accumulation rounding. Result: pytorch#195071
(`test_comprehensive_combinations_xpu_float16`) was disabled on 2026-08-27.

## Root cause on the failing sample

Sample 17: `input=(4,) fp16, r=4, with_replacement=True` -> output `(35, 4)`.
Each of the 4 inputs is copied into 35 output slots, so its gradient is the sum
of 35 fp16 contributions.

Forward is bit-identical between eager and Inductor; only the backward differs.
Inductor lowers the `index_put(accumulate=True)` backward to a single fp16
atomic scatter (`triton_poi_fused_index_put_new_zeros_1`):

```python
tmp6 = tl.load(in_ptr1 + (x0), xmask).to(tl.float32)
tl.atomic_add(out_ptr0 + (tl.broadcast_to(tmp4, [XBLOCK])), tmp6, xmask, sem='relaxed')
```

`out_ptr0` is `*fp16`, so the 35 additions per slot round to fp16 on every step,
in hardware-scheduling order. The XPU aten `index_put` accumulates in higher
precision and rounds once:

```
# accumulate 100 x 0.0002 into an fp16 slot initialised to 1.0 (exact = 1.02)
eager    index_put_(accumulate=True) -> 1.01953125
inductor same op                     -> 1.0          (== naive fp16 read-add-write)
```

Against an fp64 reference on the failing sample:

```
grad(input):
  eager    vs ref-fp64: max_rel = 3.65e-04
  inductor vs ref-fp64: max_rel = 3.99e-03
  inductor vs eager   : max_rel = 1.6e-03 .. 4.9e-03 across runs (>> default rtol=1e-3)
```

The run-to-run spread comes from the nondeterministic atomic order: the same
input produced 14 distinct fp16 results in 20 Inductor runs, vs 1 for eager.
This is intrinsic fp16 accumulation rounding, not a correctness bug on either
side, and matches the situation upstream addressed on CUDA in pytorch#189102.

## Fix

Add the same `(combinations, f16)` override that pytorch#189102 added for CUDA to
`inductor_override_kwargs["xpu"]`. Observed max abs diff is 1.22e-03 against an
allowance of `2e-3 + 0.01 * 0.5 ~= 7e-3`, i.e. about 5.7x headroom.

## Test plan

Nightly wheel `torch==2.15.0.dev20260830+xpu`, triton-xpu 3.8.0, on Intel Arc
B390. Run from the pytorch checkout root:

```
PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=17 TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# before: FAILED  Tensor-likes are not close! 1/4 mismatched,
#                 rel 1.066e-03 > 1e-03 allowed
# after:  OK
```

All samples, three consecutive runs:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# OK / OK / OK
```

All dtypes, cpu and xpu:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    -k test_comprehensive_combinations -v
```
```
# Ran 14 tests    OK (skipped=2)
```

Fixes pytorch#195071

_Note: authored with AI assistance._

Pull Request resolved: pytorch#195403
Approved by: https://github.com/etaf, https://github.com/jansel
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…195403)

## Motivation

pytorch#189102 bumped the gradient tolerances for
`test_comprehensive_combinations_cuda_float16` after pytorch#186595 / pytorch#189305
reimplemented `torch.combinations` on top of `index_put`, whose fp16 backward
Inductor accumulates in fp16. That PR only added the override to
`inductor_override_kwargs["cuda"]`; `inductor_override_kwargs["xpu"]` is a
separate dict and never got the equivalent entry, leaving XPU on the default
fp16 gradient tolerance (`atol=1e-5, rtol=1e-3`), which is too tight for the
fp16 accumulation rounding. Result: pytorch#195071
(`test_comprehensive_combinations_xpu_float16`) was disabled on 2026-08-27.

## Root cause on the failing sample

Sample 17: `input=(4,) fp16, r=4, with_replacement=True` -> output `(35, 4)`.
Each of the 4 inputs is copied into 35 output slots, so its gradient is the sum
of 35 fp16 contributions.

Forward is bit-identical between eager and Inductor; only the backward differs.
Inductor lowers the `index_put(accumulate=True)` backward to a single fp16
atomic scatter (`triton_poi_fused_index_put_new_zeros_1`):

```python
tmp6 = tl.load(in_ptr1 + (x0), xmask).to(tl.float32)
tl.atomic_add(out_ptr0 + (tl.broadcast_to(tmp4, [XBLOCK])), tmp6, xmask, sem='relaxed')
```

`out_ptr0` is `*fp16`, so the 35 additions per slot round to fp16 on every step,
in hardware-scheduling order. The XPU aten `index_put` accumulates in higher
precision and rounds once:

```
# accumulate 100 x 0.0002 into an fp16 slot initialised to 1.0 (exact = 1.02)
eager    index_put_(accumulate=True) -> 1.01953125
inductor same op                     -> 1.0          (== naive fp16 read-add-write)
```

Against an fp64 reference on the failing sample:

```
grad(input):
  eager    vs ref-fp64: max_rel = 3.65e-04
  inductor vs ref-fp64: max_rel = 3.99e-03
  inductor vs eager   : max_rel = 1.6e-03 .. 4.9e-03 across runs (>> default rtol=1e-3)
```

The run-to-run spread comes from the nondeterministic atomic order: the same
input produced 14 distinct fp16 results in 20 Inductor runs, vs 1 for eager.
This is intrinsic fp16 accumulation rounding, not a correctness bug on either
side, and matches the situation upstream addressed on CUDA in pytorch#189102.

## Fix

Add the same `(combinations, f16)` override that pytorch#189102 added for CUDA to
`inductor_override_kwargs["xpu"]`. Observed max abs diff is 1.22e-03 against an
allowance of `2e-3 + 0.01 * 0.5 ~= 7e-3`, i.e. about 5.7x headroom.

## Test plan

Nightly wheel `torch==2.15.0.dev20260830+xpu`, triton-xpu 3.8.0, on Intel Arc
B390. Run from the pytorch checkout root:

```
PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=17 TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# before: FAILED  Tensor-likes are not close! 1/4 mismatched,
#                 rel 1.066e-03 > 1e-03 allowed
# after:  OK
```

All samples, three consecutive runs:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    TestInductorOpInfoXPU.test_comprehensive_combinations_xpu_float16
```
```
# OK / OK / OK
```

All dtypes, cpu and xpu:

```
TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 \
    python test/inductor/test_torchinductor_opinfo.py \
    -k test_comprehensive_combinations -v
```
```
# Ran 14 tests    OK (skipped=2)
```

Fixes pytorch#195071

_Note: authored with AI assistance._

Pull Request resolved: pytorch#195403
Approved by: https://github.com/etaf, https://github.com/jansel
pytorchmergebot pushed a commit that referenced this pull request Oct 31, 2026
…stency (#202803)

Fixes #202798
Fixes #188985

## Agent details (if applicable)

Written with Claude Code (AI assistant). I reviewed it and ran the commands on my M4 Pro (macOS 27.0.1).

The backward of `combinations` is `IndexBackward0`, i.e. `index_put(accumulate=True)`, which sums the fp16 gradients of repeated elements in a different order on MPS than on CPU. Both are equally close to a float64 reference, but they can differ from each other by up to 4e-3 relative, more than the default fp16 tolerance (rtol=1e-3). See #202798 for the numbers.

This started with #186595 (landed 2026-07-05 as 5b84db3, reverted, then relanded 2026-07-15 as #189305 / 41d3568), which is when #188985 was filed. That PR replaced `meshgrid` + `masked_select` + `stack` with `self.index(nonzero_static(mask))`. Before it, the gradient for each repeated element came from expand's backward, a `sum` reduction that accumulates in fp32 on both CPU and MPS and rounds to fp16 once, so the two backends agreed exactly. After it, the backward goes through `index_put_(accumulate=True)`, which rounds to fp16 after every add. CPU does this serially in a fixed order (`cpu/IndexKernel.cpp`), and MPS does it with compare-and-swap fp16 atomics in whatever order the threads land (`AtomicType<half>` in `c10/metal/atomic.h`). Over 2000 seeds of the failing sample (`n=2, r=4, with_replacement=True`), the old formulation gives identical CPU and MPS grads every time, while the current one fails rtol=1e-3 in 6.7% of seeds (worst relative difference 2.2e-3). The same change also made fp16/bf16 `combinations` grads somewhat less accurate on every backend, which is out of scope here.

This adds `combinations` to `FP16_LOW_PRECISION_LIST`, which already has `_unsafe_masked_index_put_accumulate` (the same accumulating `index_put`) for the same reason. Making MPS follow CPU's order instead would need a slower kernel that is no more accurate: even the exact sum, rounded once to fp16, fails the default tolerance against CPU in 37% of random test runs. The new tolerance still catches real accumulation bugs: a simulated lost atomic add is caught in every test run. The forward is exact indexing, so the looser tolerance hides nothing there. Closing #188985 re-enables the test in CI.

Test plan:

```
python test/test_mps.py -k combinations
```

`test_output_grad_match_combinations_mps_float16` fails on main and passes with this change. All 12 `combinations` tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #202803
Approved by: https://github.com/malfet

Co-authored-by: Claude Opus 5.5 <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…stency (pytorch#202803)

Fixes pytorch#202798
Fixes pytorch#188985

## Agent details (if applicable)

Written with Claude Code (AI assistant). I reviewed it and ran the commands on my M4 Pro (macOS 27.0.1).

The backward of `combinations` is `IndexBackward0`, i.e. `index_put(accumulate=True)`, which sums the fp16 gradients of repeated elements in a different order on MPS than on CPU. Both are equally close to a float64 reference, but they can differ from each other by up to 4e-3 relative, more than the default fp16 tolerance (rtol=1e-3). See pytorch#202798 for the numbers.

This started with pytorch#186595 (landed 2026-07-05 as 5b84db3, reverted, then relanded 2026-07-15 as pytorch#189305 / 41d3568), which is when pytorch#188985 was filed. That PR replaced `meshgrid` + `masked_select` + `stack` with `self.index(nonzero_static(mask))`. Before it, the gradient for each repeated element came from expand's backward, a `sum` reduction that accumulates in fp32 on both CPU and MPS and rounds to fp16 once, so the two backends agreed exactly. After it, the backward goes through `index_put_(accumulate=True)`, which rounds to fp16 after every add. CPU does this serially in a fixed order (`cpu/IndexKernel.cpp`), and MPS does it with compare-and-swap fp16 atomics in whatever order the threads land (`AtomicType<half>` in `c10/metal/atomic.h`). Over 2000 seeds of the failing sample (`n=2, r=4, with_replacement=True`), the old formulation gives identical CPU and MPS grads every time, while the current one fails rtol=1e-3 in 6.7% of seeds (worst relative difference 2.2e-3). The same change also made fp16/bf16 `combinations` grads somewhat less accurate on every backend, which is out of scope here.

This adds `combinations` to `FP16_LOW_PRECISION_LIST`, which already has `_unsafe_masked_index_put_accumulate` (the same accumulating `index_put`) for the same reason. Making MPS follow CPU's order instead would need a slower kernel that is no more accurate: even the exact sum, rounded once to fp16, fails the default tolerance against CPU in 37% of random test runs. The new tolerance still catches real accumulation bugs: a simulated lost atomic add is caught in every test run. The forward is exact indexing, so the looser tolerance hides nothing there. Closing pytorch#188985 re-enables the test in CI.

Test plan:

```
python test/test_mps.py -k combinations
```

`test_output_grad_match_combinations_mps_float16` fails on main and passes with this change. All 12 `combinations` tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#202803
Approved by: https://github.com/malfet

Co-authored-by: Claude Opus 5.5 <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…stency (pytorch#202803)

Fixes pytorch#202798
Fixes pytorch#188985

## Agent details (if applicable)

Written with Claude Code (AI assistant). I reviewed it and ran the commands on my M4 Pro (macOS 27.0.1).

The backward of `combinations` is `IndexBackward0`, i.e. `index_put(accumulate=True)`, which sums the fp16 gradients of repeated elements in a different order on MPS than on CPU. Both are equally close to a float64 reference, but they can differ from each other by up to 4e-3 relative, more than the default fp16 tolerance (rtol=1e-3). See pytorch#202798 for the numbers.

This started with pytorch#186595 (landed 2026-07-05 as 5b84db3, reverted, then relanded 2026-07-15 as pytorch#189305 / 41d3568), which is when pytorch#188985 was filed. That PR replaced `meshgrid` + `masked_select` + `stack` with `self.index(nonzero_static(mask))`. Before it, the gradient for each repeated element came from expand's backward, a `sum` reduction that accumulates in fp32 on both CPU and MPS and rounds to fp16 once, so the two backends agreed exactly. After it, the backward goes through `index_put_(accumulate=True)`, which rounds to fp16 after every add. CPU does this serially in a fixed order (`cpu/IndexKernel.cpp`), and MPS does it with compare-and-swap fp16 atomics in whatever order the threads land (`AtomicType<half>` in `c10/metal/atomic.h`). Over 2000 seeds of the failing sample (`n=2, r=4, with_replacement=True`), the old formulation gives identical CPU and MPS grads every time, while the current one fails rtol=1e-3 in 6.7% of seeds (worst relative difference 2.2e-3). The same change also made fp16/bf16 `combinations` grads somewhat less accurate on every backend, which is out of scope here.

This adds `combinations` to `FP16_LOW_PRECISION_LIST`, which already has `_unsafe_masked_index_put_accumulate` (the same accumulating `index_put`) for the same reason. Making MPS follow CPU's order instead would need a slower kernel that is no more accurate: even the exact sum, rounded once to fp16, fails the default tolerance against CPU in 37% of random test runs. The new tolerance still catches real accumulation bugs: a simulated lost atomic add is caught in every test run. The forward is exact indexing, so the looser tolerance hides nothing there. Closing pytorch#188985 re-enables the test in CI.

Test plan:

```
python test/test_mps.py -k combinations
```

`test_output_grad_match_combinations_mps_float16` fails on main and passes with this change. All 12 `combinations` tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#202803
Approved by: https://github.com/malfet

Co-authored-by: Claude Opus 5.5 <[email protected]>
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/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: cuda release notes category 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.

torch.combinations requires unnecessary CUDA sync

7 participants