Skip to content

[MPS] Fix bool atomic_add on misaligned storage offsets - #195081

Closed
qflen wants to merge 2 commits into
pytorch:mainfrom
qflen:mps-bool-atomic-misalign
Closed

qflen wants to merge 2 commits into
pytorch:mainfrom
qflen:mps-bool-atomic-misalign

Conversation

@qflen

@qflen qflen commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #195074

scatter_add_, index_add_ and index_put_(accumulate=True) write to the wrong elements when the destination is a torch.bool view whose buffer is bound at a byte offset that is not a multiple of 4. The write lands at the start of the enclosing 4-byte word instead of at the view, so it corrupts memory in front of the view and leaves the intended elements false, with no error and no warning.

Indices set by buf[off:].scatter_add_(0, tensor([0, 2]), ones(2, dtype=bool)) on a 16-element bool tensor. index_add_ and index_put_ behave identically.

storage_offset CPU MPS before MPS after
0 0, 2 0, 2 0, 2
1 1, 3 0, 2 1, 3
2 2, 4 0, 2 2, 4
3 3, 5 0, 2 3, 5

Root cause

A tensor buffer is bound at storage_offset() * element_size() bytes and element_size() is 1 for bool, so a bool view whose storage offset is not a multiple of 4 hands the kernel a metal::atomic<uint> base that is not 4-byte aligned. AtomicType<bool>::atomic_add then computes data + (offset >> 2) against that base and lands on the wrong word.

c97fd51 (#176009) added this same realignment to atomic_add_helper and atomic_binary_op_helper for the other sub-32-bit dtypes. AtomicType<bool>::atomic_add keeps its own copy of the compare-exchange loop and was missed. AtomicType<bool>::atomic_binary_op right below it already delegates to the fixed helper, and uint8 is correct for the same reason.

Fix

Delete the hand-rolled loop and delegate to atomic_add_helper<bool>, which already does the realignment, the packed-word selection and the compare-exchange. After the early return value is always true, so the helper's += stores the same 1 the old = true did.

Test

TestAdvancedIndexing.test_accumulate_misaligned_storage_offset runs the three ops over torch.bool and torch.uint8 at all four storage-offset residues and compares the whole base tensor against CPU, so a write landing outside the view is caught. It goes in test_mps.py rather than next to the #176009 test in test_indexing.py because scatter_add_ has no Bool in its CUDA dispatch (ScatterGatherKernel.cu, AT_DISPATCH_ALL_TYPES_AND2(Half, BFloat16)), so a device-generic version would need a CUDA skip.

python test/test_mps.py -v -k test_accumulate_misaligned_storage_offset

Fails 9 of 24 subtests without the fix (bool at offsets 1, 2 and 3 for each of the three ops), all 24 pass with it. No regressions in test_mps.py TestAdvancedIndexing (89 pass), test_indexing.py -k MPS (146 pass, 13 skipped), or test_mps.py filtered on scatter / index_add / index_put (159 / 22 / 43 pass).

@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ No Failures, 13 Pending

As of commit 8e70972 with merge base 01d43eb (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added the ciflow/mps Run MPS tests (subset of trunk) label Aug 28, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

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

@malfet

malfet commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

Make sense, though I'm curious if existing primitive can be reused (I've added it for other ops, I remember that)

@malfet

malfet commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

@codex review this and see if it can reuse some existing primiitives

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0acfbf9978

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread c10/metal/atomic.h Resolved
@qflen
qflen marked this pull request as ready for review August 28, 2026 04:10
@qflen
qflen requested a review from malfet as a code owner August 28, 2026 04:10
@qflen

qflen commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for review. I see, that checks out. Pushing an edit in a moment after rebuild.

On MPS, scatter_add_, index_add_ and index_put_(accumulate=True) write to the
wrong elements when the destination is a torch.bool view whose buffer is bound
at a byte offset that is not a multiple of 4. The write lands at the start of
the enclosing 4-byte word instead of at the view, corrupting memory in front of
the view and leaving the intended elements false, with no error and no warning.

A tensor buffer is bound at storage_offset() * element_size() bytes and
element_size() is 1 for bool, so such a view hands the kernel a
metal::atomic<uint> base that is not 4-byte aligned. The hand-rolled
AtomicType<bool>::atomic_add then computes data + (offset >> 2) against that
base and lands on the wrong word. c97fd51 (pytorch#176009) added the same
realignment to atomic_add_helper and atomic_binary_op_helper for the other
sub-32-bit dtypes, but this specialization keeps its own copy of the
compare-exchange loop and was missed. AtomicType<bool>::atomic_binary_op right
below it already delegates to the fixed helper, which is also why uint8 is
unaffected.

The fix deletes the hand-rolled loop and delegates to atomic_add_helper<bool>,
which already does the realignment, the packed-word selection and the
compare-exchange. Copying just the realignment across would have left two
implementations of one invariant, which is what let them drift apart. After the
early return value is always true, so the helper's += stores the same 1 the old
"= true" did.

Fixes pytorch#195074

Test Plan:

Build:

```
USE_MPS=1 BUILD_TEST=0 MAX_JOBS=6 USE_CUDA=0 DEBUG=0 pip install -e . -v --no-build-isolation
```

New regression test, which fails on 9 of 24 subtests without the fix (bool at
storage offsets 1, 2 and 3 for each of the three ops) and passes on all 24 with
it:

```
python test/test_mps.py -v -k test_accumulate_misaligned_storage_offset
```

Surrounding suites:

```
python test/test_mps.py -k TestAdvancedIndexing
python test/test_indexing.py -k MPS
```
@qflen
qflen force-pushed the mps-bool-atomic-misalign branch from 0acfbf9 to a7a2037 Compare August 28, 2026 04:15
Comment thread c10/metal/atomic.h Outdated
val.i,
::metal::memory_order_relaxed,
::metal::memory_order_relaxed));
atomic_add_helper<bool>(data, offset, value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is almost correct, please note if someone will create reductions with say 257 true bools into the same value, it causes uint overflow, so this |= is crucial, but luckily we have if constexpr now, so, let me push a small change

atomic_add_helper<bool> accumulates the packed byte with +=, so more than 255
true stores into the same output element wrap the byte back to 0 and the
reduction silently flips to false. Route bool accumulation through
atomic_binary_op_helper with an OR op instead: it reuses the same alignment
fixup and packed compare-exchange but keeps the stored byte normalized no
matter how many times an element is accumulated. Past the early return value is
always true, so the op just returns true.

Authored with the assistance of Claude Code.

Test Plan:

Incremental build of the Metal shaders and libtorch_cpu (no warnings under the
shaders' -Wall -Wextra):

  ninja -C build torch_cpu

Accumulating 300 true values into a single element now yields True, and the
four misaligned bool storage-offset residues match CPU:

  python -c "import torch; o=torch.zeros(1,dtype=torch.bool,device='mps'); \
o.scatter_add_(0, torch.zeros(300,dtype=torch.long,device='mps'), \
torch.ones(300,dtype=torch.bool,device='mps')); print(o.item())"
  python test/test_mps.py -v -k test_accumulate_misaligned_storage_offset

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@malfet malfet added topic: bug fixes topic category release notes: mps Release notes category labels Aug 28, 2026
@malfet

malfet commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@malfet

malfet commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -f "LInt + MPS are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
Fixes pytorch#195074

`scatter_add_`, `index_add_` and `index_put_(accumulate=True)` write to the wrong elements when the destination is a `torch.bool` view whose buffer is bound at a byte offset that is not a multiple of 4. The write lands at the start of the enclosing 4-byte word instead of at the view, so it corrupts memory in front of the view and leaves the intended elements false, with no error and no warning.

Indices set by `buf[off:].scatter_add_(0, tensor([0, 2]), ones(2, dtype=bool))` on a 16-element bool tensor. `index_add_` and `index_put_` behave identically.

| storage_offset | CPU | MPS before | MPS after |
| --- | --- | --- | --- |
| 0 | 0, 2 | 0, 2 | 0, 2 |
| 1 | 1, 3 | 0, 2 | 1, 3 |
| 2 | 2, 4 | 0, 2 | 2, 4 |
| 3 | 3, 5 | 0, 2 | 3, 5 |

## Root cause

A tensor buffer is bound at `storage_offset() * element_size()` bytes and `element_size()` is 1 for bool, so a bool view whose storage offset is not a multiple of 4 hands the kernel a `metal::atomic<uint>` base that is not 4-byte aligned. `AtomicType<bool>::atomic_add` then computes `data + (offset >> 2)` against that base and lands on the wrong word.

c97fd51 (pytorch#176009) added this same realignment to `atomic_add_helper` and `atomic_binary_op_helper` for the other sub-32-bit dtypes. `AtomicType<bool>::atomic_add` keeps its own copy of the compare-exchange loop and was missed. `AtomicType<bool>::atomic_binary_op` right below it already delegates to the fixed helper, and `uint8` is correct for the same reason.

## Fix

Delete the hand-rolled loop and delegate to `atomic_add_helper<bool>`, which already does the realignment, the packed-word selection and the compare-exchange. After the early return `value` is always `true`, so the helper's `+=` stores the same `1` the old `= true` did.

## Test

`TestAdvancedIndexing.test_accumulate_misaligned_storage_offset` runs the three ops over `torch.bool` and `torch.uint8` at all four storage-offset residues and compares the whole base tensor against CPU, so a write landing outside the view is caught. It goes in `test_mps.py` rather than next to the pytorch#176009 test in `test_indexing.py` because `scatter_add_` has no `Bool` in its CUDA dispatch (`ScatterGatherKernel.cu`, `AT_DISPATCH_ALL_TYPES_AND2(Half, BFloat16)`), so a device-generic version would need a CUDA skip.

```
python test/test_mps.py -v -k test_accumulate_misaligned_storage_offset
```

Fails 9 of 24 subtests without the fix (`bool` at offsets 1, 2 and 3 for each of the three ops), all 24 pass with it. No regressions in `test_mps.py TestAdvancedIndexing` (89 pass), `test_indexing.py -k MPS` (146 pass, 13 skipped), or `test_mps.py` filtered on `scatter` / `index_add` / `index_put` (159 / 22 / 43 pass).

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

Co-authored-by: Nikita Shulga <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
Fixes pytorch#195074

`scatter_add_`, `index_add_` and `index_put_(accumulate=True)` write to the wrong elements when the destination is a `torch.bool` view whose buffer is bound at a byte offset that is not a multiple of 4. The write lands at the start of the enclosing 4-byte word instead of at the view, so it corrupts memory in front of the view and leaves the intended elements false, with no error and no warning.

Indices set by `buf[off:].scatter_add_(0, tensor([0, 2]), ones(2, dtype=bool))` on a 16-element bool tensor. `index_add_` and `index_put_` behave identically.

| storage_offset | CPU | MPS before | MPS after |
| --- | --- | --- | --- |
| 0 | 0, 2 | 0, 2 | 0, 2 |
| 1 | 1, 3 | 0, 2 | 1, 3 |
| 2 | 2, 4 | 0, 2 | 2, 4 |
| 3 | 3, 5 | 0, 2 | 3, 5 |

## Root cause

A tensor buffer is bound at `storage_offset() * element_size()` bytes and `element_size()` is 1 for bool, so a bool view whose storage offset is not a multiple of 4 hands the kernel a `metal::atomic<uint>` base that is not 4-byte aligned. `AtomicType<bool>::atomic_add` then computes `data + (offset >> 2)` against that base and lands on the wrong word.

c97fd51 (pytorch#176009) added this same realignment to `atomic_add_helper` and `atomic_binary_op_helper` for the other sub-32-bit dtypes. `AtomicType<bool>::atomic_add` keeps its own copy of the compare-exchange loop and was missed. `AtomicType<bool>::atomic_binary_op` right below it already delegates to the fixed helper, and `uint8` is correct for the same reason.

## Fix

Delete the hand-rolled loop and delegate to `atomic_add_helper<bool>`, which already does the realignment, the packed-word selection and the compare-exchange. After the early return `value` is always `true`, so the helper's `+=` stores the same `1` the old `= true` did.

## Test

`TestAdvancedIndexing.test_accumulate_misaligned_storage_offset` runs the three ops over `torch.bool` and `torch.uint8` at all four storage-offset residues and compares the whole base tensor against CPU, so a write landing outside the view is caught. It goes in `test_mps.py` rather than next to the pytorch#176009 test in `test_indexing.py` because `scatter_add_` has no `Bool` in its CUDA dispatch (`ScatterGatherKernel.cu`, `AT_DISPATCH_ALL_TYPES_AND2(Half, BFloat16)`), so a device-generic version would need a CUDA skip.

```
python test/test_mps.py -v -k test_accumulate_misaligned_storage_offset
```

Fails 9 of 24 subtests without the fix (`bool` at offsets 1, 2 and 3 for each of the three ops), all 24 pass with it. No regressions in `test_mps.py TestAdvancedIndexing` (89 pass), `test_indexing.py -k MPS` (146 pass, 13 skipped), or `test_mps.py` filtered on `scatter` / `index_add` / `index_put` (159 / 22 / 43 pass).

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

Co-authored-by: Nikita Shulga <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) Merged open source release notes: mps Release notes category topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MPS] scatter_add_, index_add_ and index_put_(accumulate=True) write to the wrong elements on a misaligned bool view

4 participants