Skip to content

[MPS] Fix race conditions in MetalShaderLibrary - #167541

Closed
blawrence-ont wants to merge 7 commits into
pytorch:mainfrom
blawrence-ont:race-condition-fix
Closed

blawrence-ont wants to merge 7 commits into
pytorch:mainfrom
blawrence-ont:race-condition-fix

Conversation

@blawrence-ont

@blawrence-ont blawrence-ont commented Nov 11, 2025 •

Copy link
Copy Markdown
Contributor

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):

int main() {
    using UnaryFunc = at::Tensor (*)(const at::Tensor &self);
    const UnaryFunc funcs[] = {
            at::tanh, at::abs,   at::sin, at::cos,  at::tan,   at::asin, at::acos, at::atan,
            at::sqrt, at::rsqrt, at::neg, at::exp2, at::log10, at::log2, at::log,
    };

    const auto input = at::empty({128}, at::TensorOptions().device(at::DeviceType::MPS));
    std::vector<std::thread> threads;
    std::latch latch(std::size(funcs));
    for (auto func : funcs) {
        threads.emplace_back([&, func] {
            latch.arrive_and_wait();
            func(input);
        });
    }
    for (auto &t : threads) {
        t.join();
    }
}

Crashes are typically segfaults or heap corruption errors:

main(42970,0x16d633000) malloc: Double free of object 0x1415077c0
main(42970,0x16d633000) malloc: *** set a breakpoint in malloc_error_break to debug

or, with MTL_DEBUG_LAYER=1 enabled, we get validation layer failures:

-[MTLDebugComputeCommandEncoder setComputePipelineState:]:360: failed assertion `computePipelineState must not be nil.'

This PR adds a mutex guarding the caches and the main MTLLibrary itself 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 throughout ATen/core since there doesn't seem to be a consistent style in the MPS code.

Partially fixes #197805

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.
@pytorch-bot

pytorch-bot Bot commented Nov 11, 2025 •

Copy link
Copy Markdown

🔗 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 (image):

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.

@pytorch-bot pytorch-bot Bot added the release notes: mps Release notes category label Nov 11, 2025
This doesn't get hit in the C++ codepath but might in the python tests.
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Nov 13, 2025
@blawrence-ont blawrence-ont changed the title Fix crashes due to a race condition in the MPS backend [MPS] Fix crashes due to a race condition in the MPS backend Nov 18, 2025

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

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;

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.

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

@blawrence-ont
blawrence-ont requested a review from a team as a code owner November 26, 2025 15:05
@blawrence-ont

Copy link
Copy Markdown
Contributor Author

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.

jltx pushed a commit to jltx/conductor-memory that referenced this pull request Dec 15, 2025
…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)
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Jan 25, 2026
@blawrence-ont

Copy link
Copy Markdown
Contributor Author

@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]>
@malfet malfet changed the title [MPS] Fix crashes due to a race condition in the MPS backend [MPS] Fix race conditions in MetalShaderLibrary Sep 21, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/mps Run MPS tests (subset of trunk) label Sep 21, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

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

@malfet malfet added the topic: bug fixes topic category label Sep 21, 2026
@malfet

malfet commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

Rebased changed to recursive_mutex, and deleted the test, will be replaced by the one in followup PR. So for very long review delay

@malfet

malfet commented Sep 21, 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

malfet added a commit that referenced this pull request Sep 21, 2026
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
malfet added a commit that referenced this pull request Sep 21, 2026
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
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
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
malfet added a commit that referenced this pull request Sep 22, 2026
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
malfet added a commit that referenced this pull request Sep 22, 2026
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
malfet added a commit that referenced this pull request Sep 22, 2026
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
pytorchmergebot pushed a commit that referenced this pull request Sep 23, 2026
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
pytorchmergebot pushed a commit that referenced this pull request Sep 23, 2026
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
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 no-stale open source release notes: mps Release notes category Stale topic: bug fixes topic 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.

[MPS] Process crashes (SIGSEGV/SIGABRT inside Metal) when two Python threads run tensor ops concurrently

6 participants