Skip to content

Fix duplicate LC_RPATH from macOS libomp embedding on conda/pixi builds - #189704

Closed
zklaus wants to merge 1 commit into
pytorch:mainfrom
zklaus:fix-embed-libomp-dup-rpath
Closed

zklaus wants to merge 1 commit into
pytorch:mainfrom
zklaus:fix-embed-libomp-dup-rpath

Conversation

@zklaus

@zklaus zklaus commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

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:

mock test (ALL CASES PASS)
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")
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

@pytorch-bot

pytorch-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit fdf6272 with merge base b0eccff (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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 topic: not user facing topic category label Jul 13, 2026
@zklaus zklaus added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 13, 2026
@zklaus

zklaus commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

Verified on a real macOS host (26.4.1) with a synthetic clang-built libomp/libtorch_cpu pair, exercising the script before and after the fix:

  • Bug reproduced on disk: the pre-fix script turns rpaths [@loader_path, <env>/omp] into [@loader_path, @loader_path] — confirming install_name_tool -rpath old new writes the duplicate without complaint.
  • Fix verified: same input yields a single @loader_path (env rpath deleted); the rename path is preserved when @loader_path is not already present; a dylib not linked against libomp is left untouched.
  • End-to-end: with libomp staged next to libtorch_cpu (as PostBuildSteps installs it) and the build-time env dir removed, the fixed library dlopens fine and resolves libomp solely via @loader_path.

One precision on the failure mode: on this host, a direct dlopen of the duplicate-carrying dylib was still tolerated, so dyld's duplicate-LC_RPATH rejection is context-dependent (the report's failing load is an indirect @rpath/libtorch_cpu.dylib resolution from _C.so) rather than an unconditional refusal on 15.4+ as the description suggests. The reported error names duplicate LC_RPATH '@loader_path' as the rejection reason either way, and the fix removes the duplicate in all cases.

test transcript
===== CASE 1: conda-style (@loader_path + env rpath), ORIGINAL script =====
  before:
    path @loader_path (offset 12)
    path /var/folders/.../T/tmp.wYddKDIknO/omp (offset 12)
  after ORIGINAL:
    path @loader_path (offset 12)
    path @loader_path (offset 12)
  @loader_path count: 2 <-- BUG REPRODUCED (duplicate)
===== CASE 2: conda-style, FIXED script =====
  after FIXED:
    path @loader_path (offset 12)
  @loader_path count: 1 <-- OK (single)
===== CASE 3: env-rpath only (no @loader_path yet), FIXED script =====
  after FIXED:
    path @loader_path (offset 12)
  @loader_path count: 1 <-- OK (rename path preserved)
===== A: ORIGINAL script + staged libomp -> dlopen =====
  loaded (dyld tolerated duplicate; direct dlopen, unsigned test dylib)
===== B: FIXED script + staged libomp -> dlopen =====
  dlopen: OK

@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 13, 2026
@albanD
albanD requested a review from malfet July 13, 2026 15:53
@hameerabbasi

Copy link
Copy Markdown
Collaborator

cc @malfet I'm the user in question. A review would be appreciated, this is preventing me from building/debugging locally without patching this file.

@hameerabbasi

Copy link
Copy Markdown
Collaborator

@malfet Reminder. I have to keep this diff in a stash to do local development.

@ezyang

ezyang commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude How come we have to delete as opposed to merge

@claude

claude Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 47s —— View job


Why delete rather than merge

Short answer: deleting is the merge. The desired end state is the set union of the rpaths, which is {@loader_path} — @loader_path is already there, so the only thing left to do with the build-time entry is to drop it.

Some detail on why there's no other option:

  • install_name_tool has no merge/dedupe primitive. It exposes exactly three rpath operations: -add_rpath, -delete_rpath, and -rpath old new (rename in place). "Merge these two rpaths" has to be expressed as one of those. Renaming <env>/lib -> @loader_path when @loader_path already exists doesn't collapse the two entries — it writes a second, byte-identical LC_RPATH load command, because -rpath does no duplicate check (verified on a real host in this comment: rpaths went from [@loader_path, <env>/omp] to [@loader_path, @loader_path]). So the rename is the thing that creates the problem; the merge has to be done by deletion.
  • The equivalent-looking alternative is strictly worse. You could -delete_rpath @loader_path and then -rpath <env>/lib @loader_path, which lands in the same single-entry state, but it's two mutations instead of one and has an ordering hazard (if the delete succeeds and the rename fails, the library loses @loader_path entirely).
  • Nothing is lost by dropping it. The whole point of the script is that dyld must not be able to fall back to the build-time libomp directory at runtime, since libomp is installed next to libtorch_cpu.dylib. Both branches converge on the same invariant — the build-time dir is gone, @loader_path is present exactly once. Removing the entry rather than rewriting it is the more direct expression of that.

tools/embed_libomp_macos.py:104 (the rename branch) is kept only for the case where @loader_path is genuinely absent, e.g. -DCMAKE_SKIP_INSTALL_RPATH=ON builds where LDFLAGS-injected rpaths survive but CMake-managed ones are stripped. There, renaming is the one-shot merge.

One caveat worth stating, since it's the only behavioural difference between rename and delete: the rename preserves the position of the build-time entry in the search order, whereas delete leaves resolution to the pre-existing @loader_path, which may sit at a different index. That only matters if some rpath in between also contains a libomp.dylib, which in practice it doesn't (and if it did, resolving to it would be the bug, not the fix).

Nit, unrelated to the question

tools/embed_libomp_macos.py:102-128 — the return 0 inside the loop means only the first rpath that resolves to the libomp dir is handled. If a tree ends up with two spellings of the same dir (the symlink case the .resolve() comparison is there to catch, e.g. Homebrew's opt/libomp alongside the Cellar path), the second survives. Pre-existing behaviour, and harmless-ish since it's not a duplicate string, but now that the fix is -delete_rpath it would be natural to delete every match and only return after the loop.

| Branch: `fix-embed-libomp-dup-rpath`

@ezyang

ezyang commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude How come we delete rpath instead of do nothing?

@claude

claude Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 1m 20s —— View job


Why delete rather than leave it alone

"Do nothing" would fix the duplicate — but it would also silently abandon what the script exists to do. Per its docstring, the goal is that the bundled libomp.dylib (installed next to libtorch_cpu.dylib by cmake/PostBuildSteps.cmake:135) is the sole resolution path at runtime. Leaving the build-time env dir in LC_RPATH keeps the from-source install pointed at the conda/pixi env:

  • Resolution order isn't ours to rely on. dyld walks LC_RPATH entries in order and takes the first hit. In the case that was actually observed the order happened to be [@loader_path, <env>/lib], so the bundled copy wins — but that ordering is an artifact of how CMake happened to emit CMAKE_INSTALL_RPATH vs. the link-path/LDFLAGS-injected entry in that configuration, not a guarantee. If the env entry lands first, you load the env's libomp and the bundling was pointless.
  • When it does win, it's the bug [BE] Add macOS OpenMP embedding to PostBuildSteps #180239 fixed. The install then has a hard dependency on an absolute build-machine directory. pixi/conda envs get re-solved, relocated, and deleted; libomp is also a versioned dylib, so the env's copy can drift from what was linked against. Second-order: two different libomp images in one process (one via @loader_path from another extension, one via the env) is the classic multiple-OpenMP-runtime hang/crash.
  • LC_RPATH is per-image, not per-dependency. The entry we're deleting is a search path for every @rpath/... load command in libtorch_cpu, not just libomp — so leaving it in has blast radius beyond the thing the script is tidying up.
  • It keeps both branches on one invariant. The else branch at tools/embed_libomp_macos.py:119 renames, which is a delete+add in one shot. Making the @loader_path-already-present branch a no-op would mean the script's postcondition depends on which branch it took. As written, both converge on: build-time dir gone, @loader_path present exactly once.

So the minimal change that fixes the duplicate and preserves intent is to drop the entry rather than rewrite it into a copy of one that's already there.

One caveat worth stating (pre-existing, not introduced here)

The rpath being removed is libomp_path.parent, which in a conda/pixi env is $PREFIX/lib — the same directory holding the env's MKL/OpenBLAS. conda-forge dylibs carry @rpath/... install names, so if libtorch_cpu resolves any of those through that rpath, removing it would break them too. That hazard is identical under the old rename branch, so this PR doesn't change it, and the reported symptom was the duplicate rather than a missing MKL — plausibly because the conda toolchain contributes $PREFIX/lib more than once and the return 0 at tools/embed_libomp_macos.py:128 only handles the first match. Worth knowing that the loop's early return is load-bearing in a way it wasn't meant to be; see also the nit in my previous comment about handling every match.

| Branch: `fix-embed-libomp-dup-rpath`

@ezyang

ezyang commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude If this change is buggy, what is the potential blast radius. It clearly affects build from source, how about wheels?

@claude

claude Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 9m 45s —— View job


Blast radius

Short version: wheels do execute this code path, and probably even the exact branch that changed — but the change is provably a no-op on the resulting dyld search set, so the realistic blast radius is "loud build failure," not "silently broken wheel." The larger risk here is a coverage gap: the macOS wheel job doesn't run on this PR without a ciflow tag.

Full analysis

1. What can reach the code at all

cmake/PostBuildSteps.cmake:131 gates the whole block on APPLE AND BUILD_PYTHON AND USE_OPENMP AND OpenMP_FOUND, plus OpenMP_libomp_LIBRARY existing at :134. So:

Surface Reaches it?
Linux / Windows (all wheels, all CI) No — APPLE gate
libtorch-only / C++ dist on macOS No — BUILD_PYTHON gate
macOS builds with USE_OPENMP=0 or no libomp found No
macOS arm64 nightly/release wheels Yes
macOS trunk CI (macos-py3-arm64, mac-mps) Yes — builds via python -m build --wheel then installs dist/*.whl
From-source macOS installs (the reported bug) Yes

The only file ever mutated is <install>/lib/libtorch_cpu.dylib. Nothing else in the tree is touched.

2. Do wheels hit the changed branch?

Yes, most likely. The wheel build (.ci/macwheel/install_libomp.sh) stages a conda-forge libomp at /opt/llvm-openmp and sets its id to an absolute path, so the LC_LOAD_DYLIB is absolute and the -change at tools/embed_libomp_macos.py:86 fires. But CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE (cmake/Dependencies.cmake:16) also puts /opt/llvm-openmp/lib into libtorch_cpu's LC_RPATH, and CMAKE_INSTALL_RPATH (:13) puts @loader_path there — which is exactly the precondition for the new -delete_rpath branch at tools/embed_libomp_macos.py:104.

So the wheel's libtorch_cpu.dylib has almost certainly been shipping with a duplicate @loader_path all along; it never surfaced because delocate-wheel (.ci/macwheel/repair_wheel.py) rewrites/normalizes rpaths afterwards. Same for trunk's macOS jobs, which use the Homebrew libomp under /opt/homebrew/opt/libomp (cmake/Modules/FindOpenMP.cmake:85) — that dir also lands in LC_RPATH, so trunk mac builds exercise the new branch too, just without a delocate pass to paper over the old duplicate.

3. Why the semantic risk is near zero

The two branches converge on the same rpath set. Concretely, for [@loader_path, /other, <env>/lib]:

old (rename):  [@loader_path, /other, @loader_path]
new (delete):  [@loader_path, /other]

The surviving @loader_path is at the same index in both, so nothing that previously resolved can resolve later or differently — the deleted entry was strictly dominated by the @loader_path that already preceded it in the observed layouts. The new code cannot change what dyld finds; it can only remove a load command dyld was going to ignore (or reject). That's a much narrower change than the diff's 24/9 suggests.

The one pre-existing hazard the change inherits rather than introduces: the removed rpath is libomp_path.parent, i.e. $PREFIX/lib in a conda env, which also holds the env's MKL/OpenBLAS. Dropping it could break other @rpath/... loads — but the old rename branch removed that entry equally, so this PR doesn't move the needle.

4. If it is buggy, how does it manifest?

  • Build-time: install(CODE ...) uses COMMAND_ERROR_IS_FATAL ANY (cmake/PostBuildSteps.cmake:162), so a nonzero exit from install_name_tool -delete_rpath fails the install/wheel build hard and visibly. No silent-corruption path. And -delete_rpath takes the same exact-match string the rename branch passed as its old argument, straight from otool output, so the "rpath not found" failure mode isn't newly reachable.
  • Runtime: worst case is Library not loaded: @rpath/libomp.dylib on import torch, i.e. a total, immediate, unmissable failure on the first import — not a subtle numerical or perf regression. A partial/degraded outcome isn't really available here.
  • Wheel-specific: for a shipped wheel it would have to survive delocate and the smoke test in .github/workflows/_binary-test-macos.yml, which installs the wheel into a fresh venv on a fresh runner without /opt/llvm-openmp and imports torch. That's precisely the environment an rpath mistake fails in.

5. The actual risk: test coverage on this PR

generated-macos-arm64-binary-wheel-nightly.yml only triggers on the nightly branch, v*-rc* tags, and ciflow/binaries* — and macOS builds live in trunk.yml / mac-mps.yml, not pull.yml. So by default this PR validates the wheel path not at all. Dr. CI's green tick above is not evidence about the surface this touches.

Recommend tagging before merge:

ciflow/binaries_wheel   # exercises the wheel build + fresh-runner smoke test
ciflow/trunk            # macos-py3-arm64 build + full test suite off the built wheel

If both are green, the wheel exposure is covered by the strongest available signal: an import torch on a machine that doesn't have the build-time libomp directory.

6. Unrelated nit, still open from my earlier comment

tools/embed_libomp_macos.py:128 — the return 0 inside the loop means only the first matching rpath is handled. Now that the fix is -delete_rpath, deleting every match and returning after the loop would be the natural shape. Note this early return is currently load-bearing in a way it wasn't designed to be: it's plausibly why conda users haven't lost their $PREFIX/lib-resolved MKL, since a conda toolchain can contribute that dir more than once. Worth resolving deliberately rather than leaving to chance. Fix this →

| Branch: `fix-embed-libomp-dup-rpath`

@hameerabbasi hameerabbasi added the ciflow/mps Run MPS tests (subset of trunk) label Aug 6, 2026
@ezyang ezyang added the ciflow/binaries_wheel Trigger binary build and upload jobs for wheel on the PR label Aug 6, 2026
@ezyang

ezyang commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@hameerabbasi

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

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

Copy link
Copy Markdown
Collaborator

Successfully rebased fix-embed-libomp-dup-rpath onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix-embed-libomp-dup-rpath && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the fix-embed-libomp-dup-rpath branch from 5b2ff80 to fdf6272 Compare August 7, 2026 06:20
@hameerabbasi

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 5, 8, linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

@hameerabbasi

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: linux-binary-manywheel / libtorch-rocm7_14-shared-with-deps-release-extract

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

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_wheel Trigger binary build and upload jobs for wheel on the PR ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing 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.

6 participants