Repository navigation
[MPS] Fix race conditions in MetalShaderLibrary - #167541
blawrence-ont wants to merge 7 commits into
Conversation
Also rename them so that any uses are found by compilation errors (and to match the trailing underscore convention in ATen/core).
…reads Also rename it so that any uses are found by compilation errors (and to match the trailing underscore convention in ATen/core).
We've already done a lookup so no need to do it again, and we don't need to copy strings just to append them.
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/167541
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit 7f18423 with merge base c3627d1 ( CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This doesn't get hit in the C++ codepath but might in the python tests.
kurtamohler
left a comment
There was a problem hiding this comment.
Thanks for the fix!
I think this should have a test before merging it. Seems like it should be possible to write a test with the Python threading module.
If the issue doesn't show up in Python for whatever reason, then you could add a C++ test in aten/src/ATen/test/mps_test_metal_library.cpp
| const std::initializer_list<std::string>& params); | ||
| MTLLibrary_t library = nullptr; | ||
| std::mutex library_mutex_; | ||
| MTLLibrary_t library_ = nullptr; |
There was a problem hiding this comment.
nit: Just a thought, if we're changing the name of this variable anyway, maybe we might as well change it to something like cached_library_, since that would make it a little more clear why we have both this variable and the map
Running this in a 2.9.0 venv fails consistently.
|
Accidentally pushed up a bit early since I was still soak testing the test. It's slightly modified from the original repro to trigger the failure more consistently (with torch 2.9.0) and passes on this branch. |
…tive batch sizes - Add MPS stability check with automatic CPU fallback - Add torch.mps.synchronize() calls after embedding operations - Use smaller batch sizes for MPS (64 max vs 256 for CUDA) - Add CONDUCTOR_MEMORY_FORCE_CPU env var to force CPU mode - Document MPS issues and workarounds in INSTALL.md Addresses known PyTorch MPS issues: - Race conditions in MPS backend (pytorch/pytorch#167541) - OpenMP conflicts on M4 chips (pytorch/pytorch#161865)
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
|
@pytorchbot label no-stale |
The branch was cut before `hasFunction`/`functionNames` and `kernelCache` existed. Those are where pytorch#197805 actually crashes: its reports show SIGSEGV in `std::__hash_table::__emplace_unique_key_args` reached from `MetalShaderLibrary::exec_unary_kernel` via `hasFunction`, which this branch's `library_mutex_`/`maps_mutex_` pair does not cover. Resolving the conflicts with main, this replaces the two mutexes with a single recursive one taken across the library handle and all four caches. Recursive because the accessors call one another: `hasFunction` -> `getFunctionNames` -> `getLibrary`, and `getCachedKernelFunctionPtr` -> `getLibrary` + `getLibraryPipelineState`. Per-cache mutexes would mean restructuring those call chains to release before recursing, for no benefit: these are one-time lazy-init paths and the lock is uncontended once a kernel is cached. The member renames are dropped to keep the diff to the guarding itself, and `test_functions_multithreaded.py` is dropped because the multithreaded MPS regression tests need the companion command-encoder fix for pytorch#197805 before they can pass; they land there instead. Note this grows `sizeof(MetalShaderLibrary)`, so out-of-tree C++ extensions built against the previous header need a rebuild. Test Plan: ```bash python test/test_mps.py TestMPS.test_multithreaded_ops TestMPS.test_multithreaded_ops_warm ``` Both tests live in the companion PR. With that PR's encoder fix but without this change, the cold-cache `test_multithreaded_ops` fails 0/5 (SIGSEGV or hang); with both, 6/6 pass on an Apple M4 Max running macOS 26.5. ```bash python test/test_mps.py ``` `failures=2, errors=1` with and without the change, same three pre-existing failures either way. Co-Authored-By: Claude Opus 5 <[email protected]>
MetalShaderLibrary
|
|
|
Rebased changed to recursive_mutex, and deleted the test, will be replaced by the one in followup PR. So for very long review delay |
|
@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 |
MPSStream serializes GPU work through a per-stream serial dispatch queue, and `commandEncoder()`/`endKernelCoalescing()`/`commit()` all mutate the stream's `_commandBuffer` and `_commandEncoder`. Several callers touched that state from the calling thread instead, so a second thread running MPS ops concurrently could have its encoder ended and released mid-use. The result is a SIGSEGV binding a released encoder, "A command encoder is already encoding to this command buffer" when a second encoder is opened on a buffer that still has one, or `_status < MTLCommandBufferStatusCommitted` when encoding into a committed buffer. A thread that aborts while owning the queue also leaves the other thread's `dispatch_sync` waiting forever, so the process sometimes hangs rather than crashes. Two groups of callers are fixed: - arange/linspace/logspace in RangeFactories.mm, both branches of Eye.mm, and RenormKernel.mm took the encoder before entering `dispatch_sync_with_rethrow` and used it inside the block. The `commandEncoder()` call moves inside. Every other caller in the tree already acquires it inside the block, or is a helper only ever invoked from one. - `MPSHooks::deviceSynchronize`, `commitStream` and `getCommandBuffer` drove `endKernelCoalescing()` and commit straight from the calling thread. These are what `torch.mps.synchronize()` and extension code reach, and they are now wrapped in `dispatch_sync_with_rethrow` like the neighbouring `synchronizeAllMPSStreams` already was. The second group is why the regression test uses an explicit `torch.mps.synchronize()`: syncing via `float(tensor)` goes through `copy_and_sync`, which was already correctly queued, and hides the MPSHooks half of the bug. The companion cache-guarding fix for this issue landed as #167541. Fixes #197805 Test Plan: ```bash python test/test_mps.py TestMPS.test_multithreaded_arange ``` 20 runs on each build, Apple M4 Max running macOS 26.5: | build | failures | | --- | --- | | main | 20/20 (SIGABRT) | | main + the RangeFactories/Eye/Renorm half | 20/20 (SIGABRT, SIGSEGV) | | main + both halves | 0/20 | The test was minimized against main: dropping the dtype and unary-op variation left the crash rate unchanged at 20/20, while dropping the `synchronize()` call took warm runs to 0/20, which is what identified the MPSHooks path. ```bash python test/test_mps.py ``` `failures=2, errors=1` with and without the change, same three pre-existing failures either way. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ghstack-source-id: 5f691ae Pull-Request: #197836
MPSStream serializes GPU work through a per-stream serial dispatch queue, and `commandEncoder()`/`endKernelCoalescing()`/`commit()` all mutate the stream's `_commandBuffer` and `_commandEncoder`. Several callers touched that state from the calling thread instead, so a second thread running MPS ops concurrently could have its encoder ended and released mid-use. The result is a SIGSEGV binding a released encoder, "A command encoder is already encoding to this command buffer" when a second encoder is opened on a buffer that still has one, or `_status < MTLCommandBufferStatusCommitted` when encoding into a committed buffer. A thread that aborts while owning the queue also leaves the other thread's `dispatch_sync` waiting forever, so the process sometimes hangs rather than crashes. Two groups of callers are fixed: - arange/linspace/logspace in RangeFactories.mm, both branches of Eye.mm, and RenormKernel.mm took the encoder before entering `dispatch_sync_with_rethrow` and used it inside the block. The `commandEncoder()` call moves inside. Every other caller in the tree already acquires it inside the block, or is a helper only ever invoked from one. - `MPSHooks::deviceSynchronize`, `commitStream` and `getCommandBuffer` drove `endKernelCoalescing()` and commit straight from the calling thread. These are what `torch.mps.synchronize()` and extension code reach, and they are now wrapped in `dispatch_sync_with_rethrow` like the neighbouring `synchronizeAllMPSStreams` already was. The second group is why the regression test uses an explicit `torch.mps.synchronize()`: syncing via `float(tensor)` goes through `copy_and_sync`, which was already correctly queued, and hides the MPSHooks half of the bug. The companion cache-guarding fix for this issue landed as #167541. Fixes #197805 Test Plan: ```bash python test/test_mps.py TestMPS.test_multithreaded_arange ``` 20 runs on each build, Apple M4 Max running macOS 26.5: | build | failures | | --- | --- | | main | 20/20 (SIGABRT) | | main + the RangeFactories/Eye/Renorm half | 20/20 (SIGABRT, SIGSEGV) | | main + both halves | 0/20 | The test was minimized against main: dropping the dtype and unary-op variation left the crash rate unchanged at 20/20, while dropping the `synchronize()` call took warm runs to 0/20, which is what identified the MPSHooks path. ```bash python test/test_mps.py ``` `failures=2, errors=1` with and without the change, same three pre-existing failures either way. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ghstack-source-id: 5f691ae Pull-Request: #197836
MPSStream serializes GPU work through a per-stream serial dispatch queue, and `commandEncoder()`/`endKernelCoalescing()`/`commit()` all mutate the stream's `_commandBuffer` and `_commandEncoder`. Several callers touched that state from the calling thread instead, so a second thread running MPS ops concurrently could have released mid-use, resulting in memory corruption or aborts due to "A command encoder is already encoding to this command buffer" or `_status < MTLCommandBufferStatusCommitted`. A thread that aborts while owning the queue also leaves the other thread's `dispatch_sync` waiting forever, so the process sometimes hangs rather than crashes. Two groups of callers are fixed: - `arange`/`linspace`/`logspace` in RangeFactories.mm, both branches of Eye.mm, and RenormKernel.mm took the encoder before entering `dispatch_sync_with_rethrow` and used it inside the block. The `commandEncoder()` call moves inside. - `MPSHooks::deviceSynchronize` and friends never used `dispatch_sync` The companion cache-guarding fix for this issue landed as #167541. Fixes #197805 Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Pull Request resolved: #197836 Approved by: https://github.com/Skylion007
The guard that landed in #167541 is a `std::recursive_mutex` member. Two problems with that: a member changes `sizeof(MetalShaderLibrary)`, so out-of-tree C++ extensions compiled against the older header break, and the recursion was only needed because the accessors call one another rather than because anything genuinely reenters. Make it a file-static `std::mutex` in OperationUtils.mm, where every accessor that touches `library` or the caches is defined. Callers outside that file reach them through out-of-line functions, so nothing else needs the mutex, and the header goes back to its original layout -- the diff against the pre-#167541 header is a comment only. Dropping recursion means untangling the two chains that nested: - `hasFunction` called `getFunctionNames`, which locks. It now checks the populated flag under the lock, computes the names unlocked, then reacquires to fill the set, re-testing the flag in case another thread got there first. - `getCachedKernelFunctionPtr` called `getLibrary` + `getLibraryPipelineState`, both of which lock. It now looks up under the lock, builds the kernel unlocked and reacquires to insert; `try_emplace` keeps whichever thread won and the loser's kernel is dropped. `getPipelineStateForFunc` never nested: `getLibraryPipelineState(getLibrary(), fname)` evaluates the argument before the call, so those locks are sequential. No behavior change intended; this is the cleanup discussed on #167541. Test Plan: ```bash python test/test_mps.py TestMPS.test_multithreaded_arange python test/test_cpp_extensions_jit.py -k test_mps_extension ``` Both clean with the previous commit in this stack applied, on an Apple M4 Max running macOS 26.5. The extension test matters here specifically because it builds against the installed header, so it catches the layout change. The header change against the pre-#167541 baseline is a comment only, so `sizeof` is unchanged: ```bash git diff c7e434c^ -- aten/src/ATen/native/mps/MetalShaderLibrary.h ``` ```bash python test/test_mps.py ``` `failures=2, errors=1`, the same three pre-existing failures as main. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ghstack-source-id: edeb7f8 Pull-Request: #197837
MPSStream serializes GPU work through a per-stream serial dispatch queue, and `commandEncoder()`/`endKernelCoalescing()`/`commit()` all mutate the stream's `_commandBuffer` and `_commandEncoder`. Several callers touched that state from the calling thread instead, so a second thread running MPS ops concurrently could have its encoder ended and released mid-use: SIGSEGV binding a released encoder, "A command encoder is already encoding to this command buffer" when a second encoder is opened on a buffer that still has one, or `_status < MTLCommandBufferStatusCommitted` when encoding into a committed buffer. A thread that aborts while owning the queue also leaves the other thread's `dispatch_sync` waiting forever, so the process sometimes hangs rather than crashes. arange/linspace/logspace in RangeFactories.mm, both branches of Eye.mm, and RenormKernel.mm took the encoder before entering `dispatch_sync_with_rethrow` and used it inside the block; the `commandEncoder()` call moves inside. Every other caller in the tree already acquires it inside the block, or is a helper only ever invoked from one. The three MPSHooks entry points need splitting rather than one blanket rule, which is what got the first attempt reverted (see below). They have opposite queue-ownership contracts: - `deviceSynchronize()` is reached from `torch.mps.synchronize()` and `torch::mps::synchronize()`. Both callers are off the serial queue, so it takes the queue itself. - `commitStream()` and `getCommandBuffer()` back `torch::mps::commit()` and `get_command_buffer()`, which per torch/mps.h are encoding-time calls the caller drives from inside its own `dispatch_sync()` on `get_dispatch_queue()`. They must not dispatch again, so they assert the contract with `dispatch_assert_queue()` instead. Note `dispatch_assert_queue` is live in release builds, so an extension calling `torch::mps::commit()` or `get_command_buffer()` from outside the queue now traps at the call site rather than racing the encoder. Nothing in tree does this: the only callers are torch/csrc/api/src/mps.cpp, and neither is bound to Python. The MPSHooks half is why the regression test syncs with an explicit `torch.mps.synchronize()`: syncing via `float(tensor)` goes through `copy_and_sync`, which was already correctly queued, and hides it. The companion cache-guarding fix for this issue landed as #167541. Reland of #197836, reverted in 74acb12. The first version wrapped all three hooks in `dispatch_sync`, which made `torch::mps::commit()` and `get_command_buffer()` re-enter the serial queue their caller already owned; libdispatch traps on that, so test_mps_extension failed with SIGTRAP. That test lives in the macos-py3-arm64 default shard, not the mps shard, so it was not covered by the signal the original was merged on. Fixes #197805 Test Plan: ```bash python test/test_cpp_extensions_jit.py -k test_mps_extension python test/test_cpp_extensions_jit.py ``` The first is the test that forced the revert: 0/5 failures now, and the full file is 41 passed / 15 skipped. ```bash python test/test_mps.py TestMPS.test_multithreaded_arange ``` 20 runs on each build, Apple M4 Max running macOS 26.5: | build | failures | | --- | --- | | main | 20/20 (SIGABRT) | | main + the RangeFactories/Eye/Renorm half | 20/20 (SIGABRT, SIGSEGV) | | main + both halves | 0/20 | The test was minimized against main: dropping the dtype and unary-op variation left the crash rate unchanged at 20/20, while dropping the `synchronize()` call took warm runs to 0/20, which is what identified the MPSHooks path. ```bash python test/test_mps.py ``` `failures=2, errors=1` with and without the change, same three pre-existing failures either way. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ghstack-source-id: 18d2b50 Pull-Request: #197836
The guard that landed in #167541 is a `std::recursive_mutex` member. Two problems with that: a member changes `sizeof(MetalShaderLibrary)`, so out-of-tree C++ extensions compiled against the older header break, and the recursion was only needed because the accessors call one another rather than because anything genuinely reenters. Make it a file-static `std::mutex` in OperationUtils.mm, where every accessor that touches `library` or the caches is defined. Callers outside that file reach them through out-of-line functions, so nothing else needs the mutex, and the header goes back to its original layout -- the diff against the pre-#167541 header is a comment only. Dropping recursion means untangling the two chains that nested: - `hasFunction` called `getFunctionNames`, which locks. It now checks the populated flag under the lock, computes the names unlocked, then reacquires to fill the set, re-testing the flag in case another thread got there first. - `getCachedKernelFunctionPtr` called `getLibrary` + `getLibraryPipelineState`, both of which lock. It now looks up under the lock, builds the kernel unlocked and reacquires to insert; `try_emplace` keeps whichever thread won and the loser's kernel is dropped. `getPipelineStateForFunc` never nested: `getLibraryPipelineState(getLibrary(), fname)` evaluates the argument before the call, so those locks are sequential. No behavior change intended; this is the cleanup discussed on #167541. Test Plan: ```bash python test/test_mps.py TestMPS.test_multithreaded_arange python test/test_cpp_extensions_jit.py -k test_mps_extension ``` Both clean with the previous commit in this stack applied, on an Apple M4 Max running macOS 26.5. The extension test matters here specifically because it builds against the installed header, so it catches the layout change. The header change against the pre-#167541 baseline is a comment only, so `sizeof` is unchanged: ```bash git diff c7e434c^ -- aten/src/ATen/native/mps/MetalShaderLibrary.h ``` ```bash python test/test_mps.py ``` `failures=2, errors=1`, the same three pre-existing failures as main. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> ghstack-source-id: edeb7f8 Pull-Request: #197837
MPSStream serializes GPU work through a per-stream serial dispatch queue, and `commandEncoder()`/`endKernelCoalescing()`/`commit()` all mutate the stream's `_commandBuffer` and `_commandEncoder`. Several callers touched that state from the calling thread instead, so a second thread running MPS ops concurrently could have its encoder ended and released mid-use: SIGSEGV binding a released encoder, "A command encoder is already encoding to this command buffer" when a second encoder is opened on a buffer that still has one, or `_status < MTLCommandBufferStatusCommitted` when encoding into a committed buffer. A thread that aborts while owning the queue also leaves the other thread's `dispatch_sync` waiting forever, so the process sometimes hangs rather than crashes. arange/linspace/logspace in RangeFactories.mm, both branches of Eye.mm, and RenormKernel.mm took the encoder before entering `dispatch_sync_with_rethrow` and used it inside the block; the `commandEncoder()` call moves inside. Every other caller in the tree already acquires it inside the block, or is a helper only ever invoked from one. The three MPSHooks entry points need splitting rather than one blanket rule, which is what got the first attempt reverted (see below). They have opposite queue-ownership contracts: - `deviceSynchronize()` is reached from `torch.mps.synchronize()` and `torch::mps::synchronize()`. Both callers are off the serial queue, so it takes the queue itself. - `commitStream()` and `getCommandBuffer()` back `torch::mps::commit()` and `get_command_buffer()`, which per torch/mps.h are encoding-time calls the caller drives from inside its own `dispatch_sync()` on `get_dispatch_queue()`. They must not dispatch again, so they assert the contract with `dispatch_assert_queue()` instead. Note `dispatch_assert_queue` is live in release builds, so an extension calling `torch::mps::commit()` or `get_command_buffer()` from outside the queue now traps at the call site rather than racing the encoder. Nothing in tree does this: the only callers are torch/csrc/api/src/mps.cpp, and neither is bound to Python. The MPSHooks half is why the regression test syncs with an explicit `torch.mps.synchronize()`: syncing via `float(tensor)` goes through `copy_and_sync`, which was already correctly queued, and hides it. The companion cache-guarding fix for this issue landed as #167541. Reland of #197836, reverted in 74acb12. The first version wrapped all three hooks in `dispatch_sync`, which made `torch::mps::commit()` and `get_command_buffer()` re-enter the serial queue their caller already owned; libdispatch traps on that, so test_mps_extension failed with SIGTRAP. That test lives in the macos-py3-arm64 default shard, not the mps shard, so it was not covered by the signal the original was merged on. Fixes #197805 Test Plan: ```bash python test/test_cpp_extensions_jit.py -k test_mps_extension python test/test_cpp_extensions_jit.py ``` The first is the test that forced the revert: 0/5 failures now, and the full file is 41 passed / 15 skipped. ```bash python test/test_mps.py TestMPS.test_multithreaded_arange ``` 20 runs on each build, Apple M4 Max running macOS 26.5: | build | failures | | --- | --- | | main | 20/20 (SIGABRT) | | main + the RangeFactories/Eye/Renorm half | 20/20 (SIGABRT, SIGSEGV) | | main + both halves | 0/20 | The test was minimized against main: dropping the dtype and unary-op variation left the crash rate unchanged at 20/20, while dropping the `synchronize()` call took warm runs to 0/20, which is what identified the MPSHooks path. ```bash python test/test_mps.py ``` `failures=2, errors=1` with and without the change, same three pre-existing failures either way. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Pull Request resolved: #197836 Approved by: https://github.com/Skylion007
The guard that landed in #167541 uses `std::recursive_mutex`, that changes `sizeof(MetalShaderLibrary)` and therefore breaks ABI with existing out-of-tree C++ extensions, and recursive calls were made from other methods within the same class. Make it a file-static `std::mutex` in OperationUtils.mm, where every accessor that touches library caches are defined. Dropping recursion means untangling the two chains that nested: - `hasFunction` called `getFunctionNames`, which locks. It now checks the populated flag under the lock, computes the names unlocked, then reacquires to fill the set, re-testing the flag in case another thread got there first. - `getCachedKernelFunctionPtr` called `getLibrary` + `getLibraryPipelineState`, both of which lock. It now looks up under the lock, builds the kernel unlocked and reacquires to insert; `try_emplace` keeps whichever thread won and the loser's kernel is dropped. `getPipelineStateForFunc` never nested: `getLibraryPipelineState(getLibrary(), fname)` evaluates the argument before the call, so those locks are sequential. No behavior change intended; this is the cleanup discussed on #167541. Authored with the assistance of Claude Code. Co-Authored-By: Claude Opus 5 <[email protected]> Pull Request resolved: #197837 Approved by: https://github.com/Skylion007 ghstack dependencies: #197836
There's a race between threads when executing unary functions with the MPS backend. This is because the caching of newly created pipeline states isn't guarded and hence can be mutated concurrently by multiple threads.
The following program will trigger the race condition (needs to be run in a loop because it doesn't always race, but typically takes less than 5 iterations on my machine):
Crashes are typically segfaults or heap corruption errors:
or, with
MTL_DEBUG_LAYER=1enabled, we get validation layer failures:This PR adds a mutex guarding the caches and the main
MTLLibraryitself since accesses weren't synchronised. To help find cases where these were used unguarded, I've renamed the members (which triggered build errors locally) following the convention found throughoutATen/coresince there doesn't seem to be a consistent style in the MPS code.Partially fixes #197805