Skip to content

[BE] Add macOS OpenMP embedding to PostBuildSteps - #180239

Closed
zklaus wants to merge 35 commits into
gh/zklaus/45/basefrom
gh/zklaus/45/head
Closed

zklaus wants to merge 35 commits into
gh/zklaus/45/basefrom
gh/zklaus/45/head

Conversation

@zklaus

@zklaus zklaus commented Apr 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Move the macOS OpenMP embedding step out of setup.py::_embed_libomp
into CMake so the wheel is self-contained under the scikit-build-core
build (gh-180247) as well as the legacy setuptools path.

cmake/PostBuildSteps.cmake installs libomp.dylib (and omp.h for
Inductor) alongside libtorch_cpu.dylib. A small Python helper at
tools/embed_libomp_macos.py, invoked via install(CODE ...),
rewrites libtorch_cpu's LC_LOAD_DYLIB and LC_RPATH so the bundled
libomp is the sole resolution path at runtime; it handles both the
Homebrew (absolute-path load command) and conda (@rpath + build-time
rpath) layouts. The otool / install_name_tool work doesn't
translate cleanly to pure CMake, hence the Python helper.

Co-Generated with Claude Code

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ No Failures, 1 Pending

As of commit 0d57ccb with merge base da74fec (image):
💚 Looks good so far! There are no failures yet. 💚

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

zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 13, 2026
Copy libomp.dylib into the wheel and fix libtorch_cpu rpaths on macOS.
This is a simplified version of setup.py's _embed_libomp; the full
Python implementation stays for setuptools builds.

Co-Generated with [Claude Code](https://claude.com/claude-code)


ghstack-source-id: 976c504
Pull-Request: pytorch#180239
@zklaus
zklaus marked this pull request as ready for review April 14, 2026 18:30
@zklaus zklaus added ciflow/binaries Trigger all binary build and upload jobs on the PR release notes: releng release notes category labels Apr 14, 2026
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 15, 2026
Copy libomp.dylib into the wheel and fix libtorch_cpu rpaths on macOS.
This is a simplified version of setup.py's _embed_libomp; the full
Python implementation stays for setuptools builds.

Co-Generated with [Claude Code](https://claude.com/claude-code)


ghstack-source-id: 976c504
Pull-Request: pytorch#180239
zklaus added a commit to zklaus/pytorch that referenced this pull request Apr 17, 2026
Copy libomp.dylib into the wheel and fix libtorch_cpu rpaths on macOS.
This is a simplified version of setup.py's _embed_libomp; the full
Python implementation stays for setuptools builds.

Co-Generated with [Claude Code](https://claude.com/claude-code)


ghstack-source-id: 976c504
Pull-Request: pytorch#180239
zklaus added 3 commits April 20, 2026 13:41
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
…77644)

Adds `cmake/PostBuildSteps.cmake` with two post-build steps previously handled by `setup.py`'s `build_ext.run()`:

- **`TORCH_STABLE_ONLY` header wrapping** — runs `tools/wrap_headers.py` at install time to add guards to installed headers. Headers wrapped this way error when included with `TORCH_STABLE_ONLY` or `TORCH_TARGET_VERSION` defined.
- **`compile_commands.json` merging** — runs `tools/merge_compile_commands.py` as a build target to combine compile commands from cmake build subdirectories into a single file at the project root.

Both `wrap_headers.py` and `merge_compile_commands.py` are extracted from inline code in `setup.py` into standalone scripts under `tools/`. The corresponding code is removed from `setup.py`'s `build_ext` class (97 lines removed).

This creates the `PostBuildSteps.cmake` module that subsequent PRs (pytorch#180237, pytorch#180238, pytorch#180239) extend with license bundling, Windows DLL bundling, and macOS OpenMP embedding.

Co-Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#177644
Approved by: https://github.com/atalman
zklaus added 2 commits May 17, 2026 01:17
[ghstack-poisoned]
[ghstack-poisoned]
@zklaus zklaus added the ciflow/trunk Trigger trunk jobs on your pull request label May 19, 2026
[ghstack-poisoned]
@zklaus
zklaus requested a review from atalman May 19, 2026 15:28
@atalman atalman changed the title Add macOS OpenMP embedding to PostBuildSteps [BE] Add macOS OpenMP embedding to PostBuildSteps May 19, 2026
@zklaus

zklaus commented May 20, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Windows-arm64 failure unrelated."

@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

pytorchmergebot pushed a commit that referenced this pull request May 20, 2026
)

aotriton's ExternalProject puts the library directly in the source tree
(torch/lib/) without a cmake install() rule, so it is absent from the
installed wheel. Add an install rule so it ends up in torch/lib/ in the
wheel.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #180242
Approved by: https://github.com/atalman
ghstack dependencies: #180239
pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
Move the macOS OpenMP embedding step out of `setup.py::_embed_libomp`
into CMake so the wheel is self-contained under the scikit-build-core
build (pytorchgh-180247) as well as the legacy setuptools path.

`cmake/PostBuildSteps.cmake` installs `libomp.dylib` (and `omp.h` for
Inductor) alongside `libtorch_cpu.dylib`. A small Python helper at
`tools/embed_libomp_macos.py`, invoked via `install(CODE ...)`,
rewrites libtorch_cpu's `LC_LOAD_DYLIB` and `LC_RPATH` so the bundled
libomp is the sole resolution path at runtime; it handles both the
Homebrew (absolute-path load command) and conda (`@rpath` + build-time
rpath) layouts. The `otool` / `install_name_tool` work doesn't
translate cleanly to pure CMake, hence the Python helper.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180239
Approved by: https://github.com/atalman
pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
…rch#180242)

aotriton's ExternalProject puts the library directly in the source tree
(torch/lib/) without a cmake install() rule, so it is absent from the
installed wheel. Add an install rule so it ends up in torch/lib/ in the
wheel.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180242
Approved by: https://github.com/atalman
ghstack dependencies: pytorch#180239
@github-actions
github-actions Bot deleted the gh/zklaus/45/head branch June 20, 2026 02:27
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…77644)

Adds `cmake/PostBuildSteps.cmake` with two post-build steps previously handled by `setup.py`'s `build_ext.run()`:

- **`TORCH_STABLE_ONLY` header wrapping** — runs `tools/wrap_headers.py` at install time to add guards to installed headers. Headers wrapped this way error when included with `TORCH_STABLE_ONLY` or `TORCH_TARGET_VERSION` defined.
- **`compile_commands.json` merging** — runs `tools/merge_compile_commands.py` as a build target to combine compile commands from cmake build subdirectories into a single file at the project root.

Both `wrap_headers.py` and `merge_compile_commands.py` are extracted from inline code in `setup.py` into standalone scripts under `tools/`. The corresponding code is removed from `setup.py`'s `build_ext` class (97 lines removed).

This creates the `PostBuildSteps.cmake` module that subsequent PRs (pytorch#180237, pytorch#180238, pytorch#180239) extend with license bundling, Windows DLL bundling, and macOS OpenMP embedding.

Co-Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#177644
Approved by: https://github.com/atalman
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…77644)

Adds `cmake/PostBuildSteps.cmake` with two post-build steps previously handled by `setup.py`'s `build_ext.run()`:

- **`TORCH_STABLE_ONLY` header wrapping** — runs `tools/wrap_headers.py` at install time to add guards to installed headers. Headers wrapped this way error when included with `TORCH_STABLE_ONLY` or `TORCH_TARGET_VERSION` defined.
- **`compile_commands.json` merging** — runs `tools/merge_compile_commands.py` as a build target to combine compile commands from cmake build subdirectories into a single file at the project root.

Both `wrap_headers.py` and `merge_compile_commands.py` are extracted from inline code in `setup.py` into standalone scripts under `tools/`. The corresponding code is removed from `setup.py`'s `build_ext` class (97 lines removed).

This creates the `PostBuildSteps.cmake` module that subsequent PRs (pytorch#180237, pytorch#180238, pytorch#180239) extend with license bundling, Windows DLL bundling, and macOS OpenMP embedding.

Co-Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#177644
Approved by: https://github.com/atalman
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Move the macOS OpenMP embedding step out of `setup.py::_embed_libomp`
into CMake so the wheel is self-contained under the scikit-build-core
build (pytorchgh-180247) as well as the legacy setuptools path.

`cmake/PostBuildSteps.cmake` installs `libomp.dylib` (and `omp.h` for
Inductor) alongside `libtorch_cpu.dylib`. A small Python helper at
`tools/embed_libomp_macos.py`, invoked via `install(CODE ...)`,
rewrites libtorch_cpu's `LC_LOAD_DYLIB` and `LC_RPATH` so the bundled
libomp is the sole resolution path at runtime; it handles both the
Homebrew (absolute-path load command) and conda (`@rpath` + build-time
rpath) layouts. The `otool` / `install_name_tool` work doesn't
translate cleanly to pure CMake, hence the Python helper.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180239
Approved by: https://github.com/atalman
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…rch#180242)

aotriton's ExternalProject puts the library directly in the source tree
(torch/lib/) without a cmake install() rule, so it is absent from the
installed wheel. Add an install rule so it ends up in torch/lib/ in the
wheel.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180242
Approved by: https://github.com/atalman
ghstack dependencies: pytorch#180239
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…77644)

Adds `cmake/PostBuildSteps.cmake` with two post-build steps previously handled by `setup.py`'s `build_ext.run()`:

- **`TORCH_STABLE_ONLY` header wrapping** — runs `tools/wrap_headers.py` at install time to add guards to installed headers. Headers wrapped this way error when included with `TORCH_STABLE_ONLY` or `TORCH_TARGET_VERSION` defined.
- **`compile_commands.json` merging** — runs `tools/merge_compile_commands.py` as a build target to combine compile commands from cmake build subdirectories into a single file at the project root.

Both `wrap_headers.py` and `merge_compile_commands.py` are extracted from inline code in `setup.py` into standalone scripts under `tools/`. The corresponding code is removed from `setup.py`'s `build_ext` class (97 lines removed).

This creates the `PostBuildSteps.cmake` module that subsequent PRs (pytorch#180237, pytorch#180238, pytorch#180239) extend with license bundling, Windows DLL bundling, and macOS OpenMP embedding.

Co-Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#177644
Approved by: https://github.com/atalman
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Move the macOS OpenMP embedding step out of `setup.py::_embed_libomp`
into CMake so the wheel is self-contained under the scikit-build-core
build (pytorchgh-180247) as well as the legacy setuptools path.

`cmake/PostBuildSteps.cmake` installs `libomp.dylib` (and `omp.h` for
Inductor) alongside `libtorch_cpu.dylib`. A small Python helper at
`tools/embed_libomp_macos.py`, invoked via `install(CODE ...)`,
rewrites libtorch_cpu's `LC_LOAD_DYLIB` and `LC_RPATH` so the bundled
libomp is the sole resolution path at runtime; it handles both the
Homebrew (absolute-path load command) and conda (`@rpath` + build-time
rpath) layouts. The `otool` / `install_name_tool` work doesn't
translate cleanly to pure CMake, hence the Python helper.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180239
Approved by: https://github.com/atalman
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…rch#180242)

aotriton's ExternalProject puts the library directly in the source tree
(torch/lib/) without a cmake install() rule, so it is absent from the
installed wheel. Add an install rule so it ends up in torch/lib/ in the
wheel.

Co-Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#180242
Approved by: https://github.com/atalman
ghstack dependencies: pytorch#180239
pytorchmergebot pushed a commit to zklaus/pytorch that referenced this pull request Aug 7, 2026
Root cause: tools/embed_libomp_macos.py (from pytorch#180239) handles the
conda-style layout by renaming the rpath that points at the build-time
libomp directory to @loader_path. Every torch library already carries
@loader_path via CMAKE_INSTALL_RPATH (cmake/Dependencies.cmake), so the
rename writes a second, identical LC_RPATH into libtorch_cpu.dylib. dyld
on macOS 15.4+ refuses to load an image with duplicate LC_RPATH entries,
so a from-source build in a conda/pixi environment (whose toolchain links
with -Wl,-rpath,$PREFIX/lib, giving the script its rename target) builds
fine but fails at `import torch` with

    Library not loaded: @rpath/libtorch_cpu.dylib
    ... 'torch/lib/libtorch_cpu.dylib' (duplicate LC_RPATH '@loader_path')

The CD wheels never showed this because delocate normalizes rpaths
afterwards, and older dyld tolerated the duplicate silently.

Fix: in the rename branch, when @loader_path is already among the rpaths,
delete the build-time rpath instead of renaming it. The rename is kept for
the (hypothetical) layout without a preexisting @loader_path, and the
add_rpath branch was already guarded.

Workaround for already-built trees, until a rebuild picks this up:
    install_name_tool -delete_rpath @loader_path torch/lib/libtorch_cpu.dylib

## Test plan

All four decision branches exercised with parse_otool/install_name_tool
mocked (conda-style dup case: original script provably issues the rename,
fixed script issues -delete_rpath; env-rpath-only rename preserved;
homebrew load-command rewrite untouched; unlinked no-op):

```
python3 rpath_mock_test.py   # inline in the PR discussion; ALL CASES PASS
```

Real-dylib verification script (clang synthetic libomp/libtorch_cpu pair,
before/after otool -l LC_RPATH counts) prepared for a macOS host; the
remote mac test box was unreachable, and the reporting user's failing
pixi environment (macOS 15.4+, conda clang) reproduces the exact scenario
for confirmation.

```
lintrunner tools/embed_libomp_macos.py   # clean (two pre-existing trunk
                                         # PYREFLY bcomplex32 errors only)
```

Authored with assistance from Claude Code.
pytorchmergebot pushed a commit that referenced this pull request Aug 7, 2026
…ds (#189704)

## Summary

Fixes a macOS import failure for from-source builds in conda/pixi
environments: the build completes, but `import torch` fails with

```
ImportError: dlopen(.../torch/_C.cpython-313-darwin.so, 0x0002): Library not loaded: @rpath/libtorch_cpu.dylib
  Referenced from: .../torch/lib/libtorch_python.dylib
  Reason: tried: ... '.../torch/lib/libtorch_cpu.dylib' (duplicate LC_RPATH '@loader_path'), ...
```

## Root cause

`tools/embed_libomp_macos.py` (from #180239, invoked at install time via
`cmake/PostBuildSteps.cmake`) handles the conda-style layout by renaming the
rpath that points at the build-time libomp directory to `@loader_path`.
Every torch library already carries `@loader_path` via `CMAKE_INSTALL_RPATH`
(`cmake/Dependencies.cmake:13`), so the rename writes a second, identical
`LC_RPATH` into `libtorch_cpu.dylib`. dyld on macOS 15.4+ refuses to load an
image with duplicate `LC_RPATH` entries; older dyld tolerated the duplicate
silently, and the CD wheels never showed it because delocate normalizes
rpaths afterwards.

The triggering configuration is a conda/pixi env providing libomp: the env
lib dir ends up as an rpath on `libtorch_cpu.dylib` (via
`CMAKE_INSTALL_RPATH_USE_LINK_PATH` and/or the conda toolchain's
`-Wl,-rpath,$PREFIX/lib`), which is exactly the rename target.

## Fix

In the rename branch, when `@loader_path` is already among the rpaths,
delete the build-time rpath instead of renaming it. The rename is kept for
layouts without a preexisting `@loader_path` (e.g. builds run with
`-DCMAKE_SKIP_INSTALL_RPATH=ON`, where `LDFLAGS`-injected rpaths survive but
CMake-managed ones are stripped); the `add_rpath` branch was already
guarded.

Workaround for already-built trees until a rebuild picks this up:

```
install_name_tool -delete_rpath @loader_path torch/lib/libtorch_cpu.dylib
```

## Test plan

All four decision branches exercised with `parse_otool` /
`install_name_tool` mocked; the pre-fix script provably issues the
duplicate-creating rename in the conda case, the fixed one issues
`-delete_rpath`:

<details>
<summary>mock test (ALL CASES PASS)</summary>

```python
import importlib.util, sys, tempfile
from pathlib import Path
from unittest import mock

def load(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m

def run_case(script, rpaths, libs, tmp):
    m = load(script, "emb")
    omp_dir = tmp / "omp"; lib_dir = tmp / "lib"
    omp_dir.mkdir(exist_ok=True); lib_dir.mkdir(exist_ok=True)
    (omp_dir / "libomp.dylib").write_bytes(b"x")
    (lib_dir / "libtorch_cpu.dylib").write_bytes(b"x")
    calls = []
    with mock.patch.object(m, "parse_otool", return_value=(rpaths, libs)), \
         mock.patch.object(m.subprocess, "check_call", lambda cmd, *a, **k: calls.append(cmd)), \
         mock.patch.object(sys, "argv", ["x", "--libomp-path", str(omp_dir/"libomp.dylib"), "--lib-dir", str(lib_dir)]):
        m.main()
    return [" ".join(c[:3]) for c in calls]

with tempfile.TemporaryDirectory() as td:
    tmp = Path(td); env_rp = str(tmp / "omp")
    # conda-style (@loader_path + env rpath): fixed script must delete, not rename
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path", env_rp], ["@rpath/libomp.dylib"], tmp)
    assert "-delete_rpath" in c[0], c
    # env rpath only: rename preserved
    c = run_case("tools/embed_libomp_macos.py", [env_rp], ["@rpath/libomp.dylib"], tmp)
    assert "-rpath" in c[0], c
    # homebrew abs load command, @loader_path present: only the -change rewrite
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path"], [str(tmp/"omp"/"libomp.dylib")], tmp)
    assert len(c) == 1 and "-change" in c[0], c
    # not linked against libomp: untouched
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path"], ["@rpath/libc++.dylib"], tmp)
    assert c == [], c
print("ALL CASES PASS")
```

</details>

```
lintrunner tools/embed_libomp_macos.py   # clean
```

Reported by a user building viable/strict `84cc6889912` in a pixi env on
macOS 15.4+; that environment reproduces the failure and can confirm the
fix end-to-end.

This PR was authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #189704
Approved by: https://github.com/ezyang
ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
…ds (pytorch#189704)

## Summary

Fixes a macOS import failure for from-source builds in conda/pixi
environments: the build completes, but `import torch` fails with

```
ImportError: dlopen(.../torch/_C.cpython-313-darwin.so, 0x0002): Library not loaded: @rpath/libtorch_cpu.dylib
  Referenced from: .../torch/lib/libtorch_python.dylib
  Reason: tried: ... '.../torch/lib/libtorch_cpu.dylib' (duplicate LC_RPATH '@loader_path'), ...
```

## Root cause

`tools/embed_libomp_macos.py` (from pytorch#180239, invoked at install time via
`cmake/PostBuildSteps.cmake`) handles the conda-style layout by renaming the
rpath that points at the build-time libomp directory to `@loader_path`.
Every torch library already carries `@loader_path` via `CMAKE_INSTALL_RPATH`
(`cmake/Dependencies.cmake:13`), so the rename writes a second, identical
`LC_RPATH` into `libtorch_cpu.dylib`. dyld on macOS 15.4+ refuses to load an
image with duplicate `LC_RPATH` entries; older dyld tolerated the duplicate
silently, and the CD wheels never showed it because delocate normalizes
rpaths afterwards.

The triggering configuration is a conda/pixi env providing libomp: the env
lib dir ends up as an rpath on `libtorch_cpu.dylib` (via
`CMAKE_INSTALL_RPATH_USE_LINK_PATH` and/or the conda toolchain's
`-Wl,-rpath,$PREFIX/lib`), which is exactly the rename target.

## Fix

In the rename branch, when `@loader_path` is already among the rpaths,
delete the build-time rpath instead of renaming it. The rename is kept for
layouts without a preexisting `@loader_path` (e.g. builds run with
`-DCMAKE_SKIP_INSTALL_RPATH=ON`, where `LDFLAGS`-injected rpaths survive but
CMake-managed ones are stripped); the `add_rpath` branch was already
guarded.

Workaround for already-built trees until a rebuild picks this up:

```
install_name_tool -delete_rpath @loader_path torch/lib/libtorch_cpu.dylib
```

## Test plan

All four decision branches exercised with `parse_otool` /
`install_name_tool` mocked; the pre-fix script provably issues the
duplicate-creating rename in the conda case, the fixed one issues
`-delete_rpath`:

<details>
<summary>mock test (ALL CASES PASS)</summary>

```python
import importlib.util, sys, tempfile
from pathlib import Path
from unittest import mock

def load(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m

def run_case(script, rpaths, libs, tmp):
    m = load(script, "emb")
    omp_dir = tmp / "omp"; lib_dir = tmp / "lib"
    omp_dir.mkdir(exist_ok=True); lib_dir.mkdir(exist_ok=True)
    (omp_dir / "libomp.dylib").write_bytes(b"x")
    (lib_dir / "libtorch_cpu.dylib").write_bytes(b"x")
    calls = []
    with mock.patch.object(m, "parse_otool", return_value=(rpaths, libs)), \
         mock.patch.object(m.subprocess, "check_call", lambda cmd, *a, **k: calls.append(cmd)), \
         mock.patch.object(sys, "argv", ["x", "--libomp-path", str(omp_dir/"libomp.dylib"), "--lib-dir", str(lib_dir)]):
        m.main()
    return [" ".join(c[:3]) for c in calls]

with tempfile.TemporaryDirectory() as td:
    tmp = Path(td); env_rp = str(tmp / "omp")
    # conda-style (@loader_path + env rpath): fixed script must delete, not rename
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path", env_rp], ["@rpath/libomp.dylib"], tmp)
    assert "-delete_rpath" in c[0], c
    # env rpath only: rename preserved
    c = run_case("tools/embed_libomp_macos.py", [env_rp], ["@rpath/libomp.dylib"], tmp)
    assert "-rpath" in c[0], c
    # homebrew abs load command, @loader_path present: only the -change rewrite
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path"], [str(tmp/"omp"/"libomp.dylib")], tmp)
    assert len(c) == 1 and "-change" in c[0], c
    # not linked against libomp: untouched
    c = run_case("tools/embed_libomp_macos.py", ["@loader_path"], ["@rpath/libc++.dylib"], tmp)
    assert c == [], c
print("ALL CASES PASS")
```

</details>

```
lintrunner tools/embed_libomp_macos.py   # clean
```

Reported by a user building viable/strict `84cc6889912` in a pixi env on
macOS 15.4+; that environment reproduces the failure and can confirm the
fix end-to-end.

This PR was authored with the assistance of Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#189704
Approved by: https://github.com/ezyang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/binaries Trigger all binary build and upload jobs on the PR ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: releng release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants