Skip to content

[MPS] Fix index_reduce atomic misalignment for sub-32-bit types - #176009

Closed
malfet wants to merge 3 commits into
gh/malfet/738/basefrom
gh/malfet/738/head
Closed

malfet wants to merge 3 commits into
gh/malfet/738/basefrom
gh/malfet/738/head

Conversation

@malfet

@malfet malfet commented Feb 27, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.

[ghstack-poisoned]
@malfet
malfet requested a review from kulinseth as a code owner February 27, 2026 19:52
@pytorch-bot

pytorch-bot Bot commented Feb 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 2823ab7 with merge base ee154ef (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 ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels Feb 27, 2026
malfet added a commit that referenced this pull request Feb 27, 2026
For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic<uint> (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.


ghstack-source-id: 41c36b5
Pull-Request: #176009
@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label Feb 27, 2026

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

Ho interesting. Thanks!

[ghstack-poisoned]
malfet added a commit that referenced this pull request Mar 2, 2026
For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic<uint> (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.


ghstack-source-id: e9d92fa
Pull-Request: #176009
[ghstack-poisoned]
malfet added a commit that referenced this pull request Mar 2, 2026
For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic<uint> (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.

ghstack-source-id: 4efd592
Pull-Request: #176009
@malfet malfet added the topic: bug fixes topic category label Mar 2, 2026
@malfet

malfet commented Mar 2, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@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

postmath pushed a commit to postmath/pytorch that referenced this pull request Mar 3, 2026
…rch#176009)

For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic<uint> (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.
Pull Request resolved: pytorch#176009
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#176161
EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
…rch#176009)

For sub-32-bit types (half, bfloat16, int8, int16), index_reduce uses
atomic<uint> (4-byte) compare-exchange to implement thread-safe
reductions. When the result tensor has a storage offset that isn't
4-byte aligned (e.g. bfloat16 with odd storage_offset gives a 2-byte
misaligned buffer pointer), the atomic operations hit undefined
behavior and silently fail.

Fix by detecting the misalignment in the kernel via pointer-to-integer
cast, backing the pointer up to the nearest aligned boundary, and
compensating in the element offset passed to atomic_binary_op.

Authored with Claude.
Pull Request resolved: pytorch#176009
Approved by: https://github.com/albanD
ghstack dependencies: pytorch#176161
@github-actions
github-actions Bot deleted the gh/malfet/738/head branch April 2, 2026 02:23
qflen added a commit to qflen/pytorch that referenced this pull request Aug 28, 2026
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
```
pytorchmergebot pushed a commit that referenced this pull request Aug 28, 2026
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).

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

Co-authored-by: Nikita Shulga <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
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) ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: mps Release notes category topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants