Skip to content

Reapply "Remove CUDA sync in torch.combinations to improve torch.compile support (#186595)" - #189305

Closed
lgeiger wants to merge 5 commits into
pytorch:mainfrom
lgeiger:reapply-combinations
Closed

lgeiger wants to merge 5 commits into
pytorch:mainfrom
lgeiger:reapply-combinations

Conversation

@lgeiger

@lgeiger lgeiger commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Reapplies #186595 after Meta internal revert. Let me know if there are any failures that require fixing from my end.

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

@lgeiger
lgeiger requested a review from mruberry as a code owner July 8, 2026 21:26
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 14 Cancelled Jobs, 2 Unrelated Failures, 1 Unclassified Failure

As of commit ba411ca with merge base 58b68c9 (image):

NEW FAILURE - The following job has failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Jul 8, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan
  • ciflow/dtensor

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

1 similar comment
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan
  • ciflow/dtensor

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@lgeiger

lgeiger commented Jul 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 Jul 8, 2026
@jansel

jansel commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 3m 26s —— View job


PR Review: #189305

Summary: Reapplies #186595, replacing the masked_select + stack implementation of torch.combinations with nonzero_static + advanced indexing so the output size is computed symbolically (via a binomial-coefficient helper) rather than requiring a device→host sync. The change is correct and the test coverage is appropriate; I found only minor issues.

Full review details

Code Quality

  • aten/src/ATen/native/Itertools.cpp:16-17 — The new includes <ATen/ops/index.h> and <ATen/ops/nonzero_static.h> are appended after stack.h, breaking the otherwise-alphabetical ordering of the per-operator header block (arange, cartesian_prod, combinations, empty, full, meshgrid, stack). Move them into alphabetical position (index.h before meshgrid.h, nonzero_static.h before stack.h). Fix this →

  • Itertools.cpp:27 — The comment // Helper to compute the number of combinations (binomial coefficient) restates what the function name already says. Per the repo style guide (minimize comments, code should be self-documenting), this can be dropped.

Correctness (verified, no change needed)

The whole approach hinges on calculate_num_combinations returning exactly the number of True entries in the triu mask, because nonzero_static pads with fill_value=-1 when the requested size exceeds the actual count. I verified this holds:

  • Strict (with_replacement=false): count = C(n, r), computed via the standard res = res * (n - r + i) / i iterative product where every partial product C(n-r+k, k) is an exact integer, so SymInt floor-division is safe.
  • With replacement: n → n + r - 1, giving C(n+r-1, r), matching the <= mask.
  • r > n strict case (e.g. n=2, r=3): the (n - r + i) term hits 0 early and the result stays 0, matching an all-false mask.

So no -1 padding rows can leak into self.index({indices}). Good.

Testing

  • common_methods_invocations.py:13775-13782 — The added toleranceOverride for ROCm fp16 is not obviously motivated: combinations now performs a pure gather (self.index(...)) with no floating-point arithmetic, so results should be bit-identical to the reference regardless of platform. If this tolerance is a leftover from the original PR's CI rather than a demonstrated ROCm discrepancy, consider removing it or adding a one-line comment/issue link explaining the observed failure. (Low confidence — harmless if kept, but unexplained tolerances tend to mask real regressions later.)

Backward Compatibility

Output dtype/shape/ordering are preserved (row-major triu order, shape [num_combinations, r]), so this is BC. The .contiguous() matches the old stack result's contiguity.

Recommendation: Approve. Correct, well-tested reapply. The only actionable items are the include ordering and a request to justify (or drop) the ROCm fp16 tolerance override.
· branch reapply-combinations

@jbschlosser
jbschlosser requested review from jansel and ngimel July 10, 2026 17:22
@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 10, 2026

@jansel jansel left a comment

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.

address automated feedback from claude

@lgeiger
lgeiger requested a review from jansel July 11, 2026 12:35
@lgeiger

lgeiger commented Jul 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I addressed the feedback and changed the ROCm tolerance override to only apply to the backwards pass which is a bit more scoped.

@ngimel

ngimel commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

This PR has pending changes requested. Please address the comments and update the PR before merging.

@jansel

jansel commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@ngimel

ngimel commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@lgeiger
lgeiger deleted the reapply-combinations branch July 15, 2026 07:06
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

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 triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants