Repository navigation
Conversation
🔗 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 PendingAs of commit 8e70972 with merge base 01d43eb ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
Make sense, though I'm curious if existing primitive can be reused (I've added it for other ops, I remember that) |
|
@codex review this and see if it can reuse some existing primiitives |
There was a problem hiding this comment.
💡 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".
|
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 ```
0acfbf9 to
a7a2037
Compare
| val.i, | ||
| ::metal::memory_order_relaxed, | ||
| ::metal::memory_order_relaxed)); | ||
| atomic_add_helper<bool>(data, offset, value); |
There was a problem hiding this comment.
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]>
|
@pytorchbot merge |
|
This PR needs to be approved by an authorized maintainer before merge. |
|
@pytorchbot merge -f "LInt + MPS are green" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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]>
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]>
Fixes #195074
scatter_add_,index_add_andindex_put_(accumulate=True)write to the wrong elements when the destination is atorch.boolview 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_andindex_put_behave identically.Root cause
A tensor buffer is bound at
storage_offset() * element_size()bytes andelement_size()is 1 for bool, so a bool view whose storage offset is not a multiple of 4 hands the kernel ametal::atomic<uint>base that is not 4-byte aligned.AtomicType<bool>::atomic_addthen computesdata + (offset >> 2)against that base and lands on the wrong word.c97fd51 (#176009) added this same realignment to
atomic_add_helperandatomic_binary_op_helperfor the other sub-32-bit dtypes.AtomicType<bool>::atomic_addkeeps its own copy of the compare-exchange loop and was missed.AtomicType<bool>::atomic_binary_opright below it already delegates to the fixed helper, anduint8is 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 returnvalueis alwaystrue, so the helper's+=stores the same1the old= truedid.Test
TestAdvancedIndexing.test_accumulate_misaligned_storage_offsetruns the three ops overtorch.boolandtorch.uint8at all four storage-offset residues and compares the whole base tensor against CPU, so a write landing outside the view is caught. It goes intest_mps.pyrather than next to the #176009 test intest_indexing.pybecausescatter_add_has noBoolin its CUDA dispatch (ScatterGatherKernel.cu,AT_DISPATCH_ALL_TYPES_AND2(Half, BFloat16)), so a device-generic version would need a CUDA skip.Fails 9 of 24 subtests without the fix (
boolat offsets 1, 2 and 3 for each of the three ops), all 24 pass with it. No regressions intest_mps.py TestAdvancedIndexing(89 pass),test_indexing.py -k MPS(146 pass, 13 skipped), ortest_mps.pyfiltered onscatter/index_add/index_put(159 / 22 / 43 pass).