Skip to content

[inductor] Harden VecISA dlopen probe (timeout, no import torch) - #183515

Closed
jeffdaily wants to merge 12 commits into
mainfrom
jeffdaily/inductor-vec-isa-probe-timeout
Closed

jeffdaily wants to merge 12 commits into
mainfrom
jeffdaily/inductor-vec-isa-probe-timeout

Conversation

@jeffdaily

@jeffdaily jeffdaily commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

The dlopen probe in cpu_vec_isa.check_build runs python -c <script>; cdll.LoadLibrary(<.so>) to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

  1. The subprocess.check_call had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in test_torchinductor_opinfo_properties (shards 5/15 and 9/15).
  2. The script did import torch inside the child to bring libtorch_cpu into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

  • Skip import torch in the child on Linux only, where it is both the fix for the observed hang and safe to validate: the parent prepends <torch>/lib to LD_LIBRARY_PATH so the dynamic linker resolves libtorch_cpu for the test .so automatically. macOS and Windows keep import torch in the child (the pre-rework behavior):
    • macOS: the env approach cannot work -- SIP strips DYLD_LIBRARY_PATH from spawned children and the test .so's @rpath dependency on libtorch_cpu.dylib is unresolvable from the parent env.
    • Windows: a find_spec + os.add_dll_directory scheme is plausible, but the Windows CI build is currently red on an unrelated pip/requirements-ci infra flake, so that path cannot actually be exercised. Rather than ship an unvalidated loader change (which is how the macOS breakage slipped in), keep Windows on the proven import until it can be tested.
  • Switch subprocess.check_call to subprocess.run(timeout=60, check=True) so the child is killed on TimeoutExpired (check_call leaks it). TimeoutExpired returns False with a warning; CalledProcessError still fails fast.

On Linux the probe drops from ~2.1s to ~0.3s per spawn locally; macOS/Windows keep the import. An earlier revision of this PR also cached the result in a .load_ok marker, but that marker belonged to #181617, which has since been reverted on main; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing @functools.cache on __bool__impl).

Two regression tests in test_codecache.py cover the timeout path (returns False, emits warning) and the LD_LIBRARY_PATH prepend behavior.

Note: an earlier landing of this PR was auto-reverted because dropping import torch on macOS broke CPU vectorized codegen (test_neg_index_cpu on macos-py3-arm64): the DYLD_LIBRARY_PATH / preload-by-path approach does not work under SIP. macOS now imports torch in the child, and -- since Windows CI can't currently validate a loader change -- Windows does too, making the no-import path a Linux-only optimization.

Authored by Claude.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @mlazos

The dlopen probe in cpu_vec_isa.check_build runs `python -c "import
torch; cdll.LoadLibrary(<.so>)"` to verify the compiler+runtime can
load a tiny vec-ISA test library. The subprocess.check_call had no
timeout, so a stuck `import torch` in the child hung the parent test
process for the full 30-minute CI budget. Saw it twice on ROCm MI355
in test_torchinductor_opinfo_properties (shards 5/15 and 9/15).

Add a 60s timeout and one retry on TimeoutExpired (2 attempts total).
A transient stall recovers on the retry; persistent stalls give up
after 120s and report the ISA as unavailable. Hard failures
(CalledProcessError) still fail fast; only timeouts retry.

Authored by Claude.
@jeffdaily
jeffdaily requested review from eellison and jansel May 13, 2026 05:55
@pytorch-bot

pytorch-bot Bot commented May 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 New Failures, 2 Unrelated Failures

As of commit a212116 with merge base 1449fa4 (image):

NEW FAILURES - The following jobs have failed:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@jansel

jansel commented May 13, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented May 13, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 35s —— View job


Review of PR #183515

  • Read changed files and understand the diff
  • Review logic, error handling, and edge cases
  • Post review feedback

Overall: The motivation is solid — an unbounded subprocess blocking CI for 30 minutes is a real problem and the fix is in the right direction. A few issues to address:


Bug: check_call does not kill the child on timeout

This is the main concern. subprocess.check_call with timeout internally calls Popen(...).wait(timeout=timeout). When the timeout fires, CPython raises TimeoutExpired but does not kill the child process. The timed-out python -c "import torch; ..." process keeps running in the background.

On retry, you spawn a second child while the first is still alive. If the hang is persistent, you end up with two zombie-ish processes consuming resources, neither of which is killed when you return False.

The fix is to use subprocess.run() (or Popen directly) and explicitly kill the child on timeout. Something like:

result = subprocess.run(
    probe_cmd,
    cwd=output_dir,
    stderr=subprocess.DEVNULL,
    env=python_subprocess_env(),
    timeout=60,
)
result.check_returncode()

subprocess.run kills the child and waits for it on TimeoutExpired before re-raising. If you stay with check_call, you'd need manual Popen + proc.kill() + proc.wait() in the except TimeoutExpired block.

Nit: remaining calculation is fragile

remaining = 1 - attempt
...
if remaining == 0:
    return False

This works for exactly 2 attempts but is a bit indirect. If someone bumps range(2) to range(3), the remaining calculation still works, but the coupling between the loop bound and the hardcoded 1 is subtle. A more readable pattern:

max_attempts = 2
for attempt in range(max_attempts):
    try:
        ...
        break
    except subprocess.TimeoutExpired:
        warnings.warn(
            f"VecISA dlopen probe for {self} hung after 60s "
            f"(attempt {attempt + 1}/{max_attempts})",
            stacklevel=2,
        )
else:
    # All attempts exhausted
    return False

The for/else pattern is idiomatic Python for "loop completed without break" and avoids the manual remaining-count bookkeeping. It also naturally handles any number of retries.

Minor: stacklevel=2 may not point to the right frame

stacklevel=2 in warnings.warn targets the caller of the current function. Since check_build is called from __bool__impl (line 166) which is called from __bool__ (line 163), stacklevel=2 would point at __bool__impl. That's fine for internal debugging, just noting it's not pointing at user code. Not a blocker.

Docstring linter grandfather change looks correct

The line-number bump in docstring_linter-grandfather.json (119 → 141) matches the added lines. Looks correct.


Summary: The approach is right, but please switch from check_call to subprocess.run (or manual Popen with kill) to avoid leaking child processes on timeout. The for/else pattern would also clean up the retry logic. After that, this looks good to land.

@jansel jansel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

address automated feedback from claude

Switch the VecISA dlopen probe from subprocess.check_call to
subprocess.run(check=True). check_call's timeout only does Popen.wait
and leaves a hung child running; subprocess.run kills the child and
waits before re-raising TimeoutExpired, so the retry doesn't stack a
second hung process on top of the first.

Also replace the manual `remaining = 1 - attempt` bookkeeping with a
for/else loop and a max_attempts constant, which is more idiomatic and
scales if we ever bump the retry count.

Authored by Claude.
@jeffdaily
jeffdaily requested a review from jansel May 13, 2026 15:13
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@jansel addressed the claude review

@jansel jansel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a faster way we could do the ISA check? Burning a few sec to import torch in a subproc seems pretty bad.

@jeffdaily

Copy link
Copy Markdown
Collaborator Author

Sentinel cache, keyed by the same codecache fingerprint (compiler + ISA flags + torch version) that already keys the compiled .so on disk. After a successful probe, touch output_path + ".loadok"; subsequent processes with the same fingerprint hit os.path.isfile() and skip the subprocess entirely. That eliminates the warm-path cost, which is the common case in CI: @functools.cache only short-circuits within one process, so every fresh pytest worker re-pays today.

Keeping the 60s timeout/retry as defense in depth for the cold cache, where the hang we saw on MI355 can occur.

After a successful probe, touch a sentinel file next to the compiled .so.
Subsequent processes with the same codecache fingerprint (compiler + ISA
flags + torch version) hit os.path.isfile() and skip the subprocess
entirely. functools.cache on __bool__impl only short-circuits within one
process, so every fresh pytest worker re-pays the multi-second `import
torch` cost today; this makes it a one-time cost per host/build.

The 60s timeout/retry from the prior commit stays as defense in depth
for the cold-cache path, where the hang observed on MI355 can occur.

Authored by Claude.
@jeffdaily jeffdaily changed the title [inductor] Bound VecISA dlopen probe with timeout and retry [inductor] Harden VecISA dlopen probe (timeout, retry, cache) May 13, 2026
@jeffdaily
jeffdaily requested a review from jansel May 13, 2026 23:34
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@jansel what do you think of the last set of changes?

@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 14, 2026
@malfet

malfet commented May 14, 2026

Copy link
Copy Markdown
Collaborator

I've plumbed all cpuinfo machinery, so one can call torch.cpu.get_capabilities().. But I think what this tests is that compiler actually produces a working library, and the are no way to check it short of compiling and loading the library

But this could probably be monkey-patched for CI, as we know compiler always works there

@jansel

jansel commented May 14, 2026

Copy link
Copy Markdown
Contributor

Could we make the subproc not import torch?

@malfet

malfet commented May 14, 2026

Copy link
Copy Markdown
Collaborator

May be another separate idea - I don't think every invocation of torch needs to run a test whether host compiler is functional. It could be done once and cached, same as we cache any other compiler artifacts, but this could be done as part of separate PR, and focus this one on some sort of retriabilty/error recovery or other way around

jeffdaily added 2 commits May 19, 2026 05:10
The probe child was paying multi-second `import torch` startup on every
spawn and hung under load on ROCm MI355 CI. Drop the import: on
Linux/macOS the parent prepends torch's lib dir to LD_LIBRARY_PATH /
DYLD_LIBRARY_PATH so the dynamic linker resolves libtorch_cpu
automatically; on Windows the child self-discovers the lib dir via
importlib.util.find_spec (which does not execute torch/__init__.py) and
registers it via os.add_dll_directory before LoadLibrary. The 60s
timeout, one retry, and kill-on-timeout from the earlier commit on this
branch are kept as defense in depth for any future child hang (e.g. a
static initializer in the .so itself).

Also drops the .loadok sentinel cache from the earlier commit on this
branch. PR #181617 has since landed an equivalent .load_ok marker on
main, so the warm-path concern is handled upstream and the rebase will
keep that outer guard.

Adds regression tests in test_codecache.py covering the timeout-retry
exhaustion path and the LD/DYLD prepend behavior.

Authored by Claude.
…c-isa-probe-timeout

# Conflicts:
#	torch/_inductor/cpu_vec_isa.py
@jeffdaily jeffdaily changed the title [inductor] Harden VecISA dlopen probe (timeout, retry, cache) [inductor] Harden VecISA dlopen probe (timeout, retry, no import torch) May 19, 2026
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@jansel @malfet updated again, please let me know what you think.

@jansel

jansel commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

khushi-411 pushed a commit to khushi-411/pytorch that referenced this pull request Jun 1, 2026
…orch#183515)

The dlopen probe in `cpu_vec_isa.check_build` runs `python -c <script>; cdll.LoadLibrary(<.so>)` to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

1. The `subprocess.check_call` had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in `test_torchinductor_opinfo_properties` (shards 5/15 and 9/15).
2. The script did `import torch` inside the child to bring `libtorch_cpu` into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

- Drop `import torch` from the probe script. On Linux/macOS the parent prepends `<torch>/lib` to `LD_LIBRARY_PATH` / `DYLD_LIBRARY_PATH` so the dynamic linker resolves `libtorch_cpu` automatically. On Windows `ctypes.cdll.LoadLibrary` ignores those vars, so the child self-discovers torch via `importlib.util.find_spec` (which does not execute `torch/__init__.py`) and registers the lib dir via `os.add_dll_directory` before `LoadLibrary`.
- Switch `subprocess.check_call` to `subprocess.run(timeout=60, check=True)` so the child is killed on `TimeoutExpired` (`check_call` leaks it). `TimeoutExpired` returns `False` with a warning; `CalledProcessError` still fails fast.

The probe drops from ~2.1s to ~0.3s per spawn locally. An earlier revision of this PR also cached the result in a `.load_ok` marker, but that marker belonged to pytorch#181617, which has since been reverted on `main`; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing `@functools.cache` on `__bool__impl`).

Two regression tests in `test_codecache.py` cover the timeout path (returns False, emits warning) and the LD/DYLD prepend behavior.

Authored by Claude.

Pull Request resolved: pytorch#183515
Approved by: https://github.com/jansel
khushi-411 pushed a commit to khushi-411/pytorch that referenced this pull request Jun 1, 2026
…ch) (pytorch#183515)"

This reverts commit 3b6a253.

Reverted pytorch#183515 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#183515 (comment)))
@github-actions
github-actions Bot deleted the jeffdaily/inductor-vec-isa-probe-timeout branch July 2, 2026 02:28
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#183515)

The dlopen probe in `cpu_vec_isa.check_build` runs `python -c <script>; cdll.LoadLibrary(<.so>)` to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

1. The `subprocess.check_call` had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in `test_torchinductor_opinfo_properties` (shards 5/15 and 9/15).
2. The script did `import torch` inside the child to bring `libtorch_cpu` into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

- Drop `import torch` from the probe script. On Linux/macOS the parent prepends `<torch>/lib` to `LD_LIBRARY_PATH` / `DYLD_LIBRARY_PATH` so the dynamic linker resolves `libtorch_cpu` automatically. On Windows `ctypes.cdll.LoadLibrary` ignores those vars, so the child self-discovers torch via `importlib.util.find_spec` (which does not execute `torch/__init__.py`) and registers the lib dir via `os.add_dll_directory` before `LoadLibrary`.
- Switch `subprocess.check_call` to `subprocess.run(timeout=60, check=True)` so the child is killed on `TimeoutExpired` (`check_call` leaks it). `TimeoutExpired` returns `False` with a warning; `CalledProcessError` still fails fast.

The probe drops from ~2.1s to ~0.3s per spawn locally. An earlier revision of this PR also cached the result in a `.load_ok` marker, but that marker belonged to pytorch#181617, which has since been reverted on `main`; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing `@functools.cache` on `__bool__impl`).

Two regression tests in `test_codecache.py` cover the timeout path (returns False, emits warning) and the LD/DYLD prepend behavior.

Authored by Claude.

Pull Request resolved: pytorch#183515
Approved by: https://github.com/jansel
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ch) (pytorch#183515)"

This reverts commit 3b6a253.

Reverted pytorch#183515 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#183515 (comment)))
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#183515)

The dlopen probe in `cpu_vec_isa.check_build` runs `python -c <script>; cdll.LoadLibrary(<.so>)` to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

1. The `subprocess.check_call` had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in `test_torchinductor_opinfo_properties` (shards 5/15 and 9/15).
2. The script did `import torch` inside the child to bring `libtorch_cpu` into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

- Skip `import torch` in the child **on Linux only**, where it is both the fix for the observed hang and safe to validate: the parent prepends `<torch>/lib` to `LD_LIBRARY_PATH` so the dynamic linker resolves `libtorch_cpu` for the test `.so` automatically. macOS and Windows keep `import torch` in the child (the pre-rework behavior):
  - **macOS**: the env approach cannot work -- SIP strips `DYLD_LIBRARY_PATH` from spawned children and the test `.so`'s `@rpath` dependency on `libtorch_cpu.dylib` is unresolvable from the parent env.
  - **Windows**: a `find_spec` + `os.add_dll_directory` scheme is plausible, but the Windows CI build is currently red on an unrelated pip/`requirements-ci` infra flake, so that path cannot actually be exercised. Rather than ship an unvalidated loader change (which is how the macOS breakage slipped in), keep Windows on the proven import until it can be tested.
- Switch `subprocess.check_call` to `subprocess.run(timeout=60, check=True)` so the child is killed on `TimeoutExpired` (`check_call` leaks it). `TimeoutExpired` returns `False` with a warning; `CalledProcessError` still fails fast.

On Linux the probe drops from ~2.1s to ~0.3s per spawn locally; macOS/Windows keep the import. An earlier revision of this PR also cached the result in a `.load_ok` marker, but that marker belonged to pytorch#181617, which has since been reverted on `main`; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing `@functools.cache` on `__bool__impl`).

Two regression tests in `test_codecache.py` cover the timeout path (returns False, emits warning) and the `LD_LIBRARY_PATH` prepend behavior.

Note: an earlier landing of this PR was auto-reverted because dropping `import torch` on macOS broke CPU vectorized codegen (`test_neg_index_cpu` on `macos-py3-arm64`): the `DYLD_LIBRARY_PATH` / preload-by-path approach does not work under SIP. macOS now imports torch in the child, and -- since Windows CI can't currently validate a loader change -- Windows does too, making the no-import path a Linux-only optimization.

Authored by Claude.

Pull Request resolved: pytorch#183515
Approved by: https://github.com/jansel
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#183515)

The dlopen probe in `cpu_vec_isa.check_build` runs `python -c <script>; cdll.LoadLibrary(<.so>)` to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

1. The `subprocess.check_call` had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in `test_torchinductor_opinfo_properties` (shards 5/15 and 9/15).
2. The script did `import torch` inside the child to bring `libtorch_cpu` into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

- Drop `import torch` from the probe script. On Linux/macOS the parent prepends `<torch>/lib` to `LD_LIBRARY_PATH` / `DYLD_LIBRARY_PATH` so the dynamic linker resolves `libtorch_cpu` automatically. On Windows `ctypes.cdll.LoadLibrary` ignores those vars, so the child self-discovers torch via `importlib.util.find_spec` (which does not execute `torch/__init__.py`) and registers the lib dir via `os.add_dll_directory` before `LoadLibrary`.
- Switch `subprocess.check_call` to `subprocess.run(timeout=60, check=True)` so the child is killed on `TimeoutExpired` (`check_call` leaks it). `TimeoutExpired` returns `False` with a warning; `CalledProcessError` still fails fast.

The probe drops from ~2.1s to ~0.3s per spawn locally. An earlier revision of this PR also cached the result in a `.load_ok` marker, but that marker belonged to pytorch#181617, which has since been reverted on `main`; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing `@functools.cache` on `__bool__impl`).

Two regression tests in `test_codecache.py` cover the timeout path (returns False, emits warning) and the LD/DYLD prepend behavior.

Authored by Claude.

Pull Request resolved: pytorch#183515
Approved by: https://github.com/jansel
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch) (pytorch#183515)"

This reverts commit 3b6a253.

Reverted pytorch#183515 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#183515 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#183515)

The dlopen probe in `cpu_vec_isa.check_build` runs `python -c <script>; cdll.LoadLibrary(<.so>)` to verify the compiler+runtime can load a tiny vec-ISA test library. Two problems:

1. The `subprocess.check_call` had no timeout, so a stuck child hung the parent test process for the full 30-minute CI budget. Saw it twice on ROCm MI355 in `test_torchinductor_opinfo_properties` (shards 5/15 and 9/15).
2. The script did `import torch` inside the child to bring `libtorch_cpu` into the process, paying multi-second startup per spawn. That import is what was hanging under load.

Fix the root cause and add defense in depth:

- Skip `import torch` in the child **on Linux only**, where it is both the fix for the observed hang and safe to validate: the parent prepends `<torch>/lib` to `LD_LIBRARY_PATH` so the dynamic linker resolves `libtorch_cpu` for the test `.so` automatically. macOS and Windows keep `import torch` in the child (the pre-rework behavior):
  - **macOS**: the env approach cannot work -- SIP strips `DYLD_LIBRARY_PATH` from spawned children and the test `.so`'s `@rpath` dependency on `libtorch_cpu.dylib` is unresolvable from the parent env.
  - **Windows**: a `find_spec` + `os.add_dll_directory` scheme is plausible, but the Windows CI build is currently red on an unrelated pip/`requirements-ci` infra flake, so that path cannot actually be exercised. Rather than ship an unvalidated loader change (which is how the macOS breakage slipped in), keep Windows on the proven import until it can be tested.
- Switch `subprocess.check_call` to `subprocess.run(timeout=60, check=True)` so the child is killed on `TimeoutExpired` (`check_call` leaks it). `TimeoutExpired` returns `False` with a warning; `CalledProcessError` still fails fast.

On Linux the probe drops from ~2.1s to ~0.3s per spawn locally; macOS/Windows keep the import. An earlier revision of this PR also cached the result in a `.load_ok` marker, but that marker belonged to pytorch#181617, which has since been reverted on `main`; this PR no longer carries it, so the probe runs once per process (cached in-process by the existing `@functools.cache` on `__bool__impl`).

Two regression tests in `test_codecache.py` cover the timeout path (returns False, emits warning) and the `LD_LIBRARY_PATH` prepend behavior.

Note: an earlier landing of this PR was auto-reverted because dropping `import torch` on macOS broke CPU vectorized codegen (`test_neg_index_cpu` on `macos-py3-arm64`): the `DYLD_LIBRARY_PATH` / preload-by-path approach does not work under SIP. macOS now imports torch in the child, and -- since Windows CI can't currently validate a loader change -- Windows does too, making the no-import path a Linux-only optimization.

Authored by Claude.

Pull Request resolved: pytorch#183515
Approved by: https://github.com/jansel
cennn pushed a commit to SandAI-org/MagiCompiler that referenced this pull request Aug 9, 2026
PT 2.12's cpu_vec_isa.check_build() spawns a subprocess to dlopen a
test .so, protected by a filelock under /tmp/torchinductor_root.
In fresh containers the probe can fail with FileNotFoundError during
lock release — a known upstream issue (pytorch/pytorch#183515,
pytorch/pytorch#134667).

The official workaround is TORCHINDUCTOR_VEC_ISA_OK=1, which tells
Inductor to assume AVX support without running the probe at all.
This replaces the previous mkdir + Python warmup hack.
jiahy0825 pushed a commit to SandAI-org/MagiCompiler that referenced this pull request Aug 10, 2026
* Support PyTorch 2.12 compatibility

* Add PyTorch 2.9/2.12 dual-version AOT compatibility

Introduce _aot_compat.py shim that abstracts away the AOT API
differences between PyTorch 2.9 (CompileArtifacts) and 2.12
(AOTCompiledFunction), so load/save/extract work on both versions.

Update magi_compiler_base.py to use the shim instead of calling
version-specific APIs directly.

Add pytest.mark.skipif decorators to tests that document
version-specific upstream behavior (skipped on 2.12 where
_OpPickleData no longer raises for unknown ops, skipped on 2.9
where upstream fixes landed in 2.12 only).

Tested in isolated containers:
  - nvcr.io/nvidia/pytorch:25.10-py3 (2.9): 61 passed, 3 skipped
  - nvcr.io/nvidia/pytorch:26.05-py3 (2.12): 61 passed, 3 skipped

* Add containerized CI with dual PyTorch version testing

Migrate from bare-metal runner CI to container-based testing,
following athena's _ci_pipeline.yml pattern for style consistency.

Changes:
- Dockerfile: parameterize BASE_IMAGE (default 25.10-py3), install
  MagiCompiler + test deps inside image, skip pinned triton to
  preserve each base image's built-in version
- _ci_pipeline.yml: reusable build+test workflow (build Docker image,
  push to CCR, run tests inside container)
- integration_test.yml: parallel matrix testing on PyTorch 2.9
  (nvcr.io/nvidia/pytorch:25.10-py3) and 2.12 (26.05-py3)
- merge_test.yml: post-merge testing on both versions

* Fix Dockerfile: install test deps with transitive dependencies

- Add .dockerignore to exclude .git, __pycache__, build artifacts
- Replace --no-deps with proper dependency filtering: install all
  test deps except torchvision (requires torch>=2.12) and torchtitan
  (installed separately with --no-deps)
- Add graphviz system package required by tests

* Fix CI runner label: magi_compiler_ci -> magi-compiler

The self-hosted runner is registered with the label magi-compiler
(matching the original integration_test.yml), not magi_compiler_ci.

* docs: update PyTorch version requirement to 2.9.x / 2.12.x

Update README.md badge and requirements, install.md, and zh_CN
locale to reflect dual PyTorch version support.

* refactor: move _aot_compat imports to module top level

Move load_aot_artifacts, save_aot_artifacts, extract_aot_artifacts_from_fn
imports from inline (inside methods) to the top-level import block.

* refactor: split version-specific tests into _pt29/_pt212 variants

- test_compile_artifacts: split 4 tests into 8 (pt29/pt212 pairs) with
  version-appropriate assertions and skipif decorators
- test_piecewise_deferred_assert_scope: restore pt29 NameError expectation
  as xfail (incidentally fixed by later commits) + pt212 passes variant
- test_unbacked_symbol_guard: split legacy_view test into pt29 (expects
  guard error) and pt212 (compiles successfully)
- test_inductor_cache_reuse: skip entire class — expected autograd cache
  counters differ between PT 2.9 and 2.12, needs recalibration

* style: apply pre-commit formatting (black, isort, pretty-format-yaml)

* fix: use ARG-based proxy in Dockerfile instead of --mount=type=secret

The CI passes proxy via --build-arg but the Dockerfile read it from
--mount=type=secret, causing git fetch to hang without proxy access.
Switch to ARG http_proxy/https_proxy pattern matching athena.

* fix: pin setuptools<82 to satisfy torch 2.12 requirement

* perf: slim down Dockerfile for CI — remove flash-attn, CUTLASS cmake, ffmpeg

Removed:
- flash-attention 3 build from source (~5min compile, zero test references)
- CUTLASS cmake build (headers-only clone is sufficient for EVT codegen)
- ffmpeg (no test references)
- build-essential, cmake, ninja-build system packages (not needed at runtime)
- syntax=docker/dockerfile:1.7 directive (no longer using --mount=type=secret)

Kept:
- CUTLASS headers clone (used by EVT-fusion codegen path)
- graphviz (required by depyf/test visualization)

* perf: optimize Dockerfile layer ordering and merge pip installs

- Merge all pip installs (upgrade + core deps + test deps) into one
  RUN before COPY source, so deps are cached on code-only changes
- Merge apt-get + CUTLASS clone into one system layer
- Only COPY . and pip install -e . re-run on code changes

* refactor: split apt-get and CUTLASS clone into separate layers

* fix: replace container: directive with docker run in test job

The GitHub Actions container: directive fails on the magi-compiler
self-hosted runner (temp script mount issue). Switch to explicit
docker run which gives full control over mounts and avoids the
/__w/_temp path mapping problem.

* fix: use container: directive with athena-new runner for test job

The magi-compiler runner fails with container: (Docker-in-Docker temp
script mount issue). Switch test job to athena-new runner which is
known to support container: jobs correctly. Build job stays on
magi-compiler.

* fix: add tyro dependency for torchtitan in Dockerfile

torchtitan==0.2.0 was installed with --no-deps to avoid pulling a newer
torch, but its transitive dependency tyro was missing, causing
test_fsdp_overlap_e2e tests to fail with ModuleNotFoundError.

* fix: use magi-compiler runner for test job instead of athena-new

athena-new runner is dedicated to athena CI and will not pick up
MagiCompiler jobs. Both build and test jobs now use magi-compiler.

* fix: add NCCL_NVLS_ENABLE=0 and --shm-size=2g to CI test container

- NCCL_NVLS_ENABLE=0: disable NVLink SHARP to avoid Fabric Manager
  errors in container environment (CUDA error 802)
- --shm-size=2g: ensure sufficient shared memory for multi-rank tests
- Prepare /tmp/torchinductor_root cache dir before tests to prevent
  filelock race conditions in PyTorch Inductor CPU vec ISA checks

* refactor: remove unnecessary Prepare environment step from CI

The mkdir for /tmp/torchinductor_root was added speculatively to fix
FileNotFoundError in cpu_vec_isa.check_build(), but the issue is likely
runner-specific (only appeared on magi-compiler, not athena-new) and
this step does not address the root cause.

Keep NCCL_NVLS_ENABLE=0 which is the correct fix for NCCL 2.30+ in
containers without full Fabric Manager access.

* fix: cap ND tiling max_tiles=2 on PT 2.12, relax conv perf threshold

ND tiling: PT 2.12 Inductor generates invalid 3D-grid reduction kernels
when max_tiles=3 — program_id(2) refers to a grid dimension that does
not exist in the launch config. Root cause is Inductor codegen, not
Triton (Triton 3.7 handles program_id(2) correctly when grid is 3D).
Cap max_tiles at 2 on PT >= 2.12; keep 3 on PT 2.9 where it works.
Verified: magi_compile + ND tiling workaround passes on both PT versions.

Conv perf: lower threshold from 1.20x to 1.05x to reduce CI flakiness
from GPU clock/thermal variance across runs.

* test: add GPU integration tests for max_tiles=3 Inductor codegen bug

Add three tests to test_nd_tiling_workaround.py:

- test_max_tiles_3_crashes_on_pt212: reproduces the PT 2.12 Inductor bug
  where max_tiles=3 + tile_reductions=True generates a Triton kernel
  referencing program_id(2) on a 2D launch grid (assert the error)
- test_max_tiles_2_compiles_successfully: verifies the fix (max_tiles=2)
  compiles correctly on all PT versions
- test_nd_tiling_pass_uses_safe_max_tiles_on_pt212: verifies the pass
  itself picks max_tiles=2 on PT >= 2.12

Also update _assert_injected to be version-aware (expect max_tiles=2 on
PT 2.12 instead of 3).

* style: apply black formatting to test_nd_tiling_workaround.py

* fix: restore torchinductor cache dir prep, skip ND tiling perf on PT 2.12

- Add Prepare environment step (mkdir -p /tmp/torchinductor_root) to CI
  test job, fixing 6 InductorError: FileNotFoundError on early tests
- Skip test_nd_tiling_workaround_speedup on PT >= 2.12 because max_tiles=2
  (required to avoid Inductor codegen bug) reduces tiling granularity

* test: skip collective profile accuracy test on PT >= 2.12

PT 2.12 Inductor generates different scheduler node counts across ranks
for the same all_gather graph, causing cross-rank key-set mismatch and
analytical fallback (ratio=0.34 vs 0.5-2.0 tolerance).

* fix: set TORCHINDUCTOR_VEC_ISA_OK=1 to skip ISA probe filelock race

PT 2.12's cpu_vec_isa.check_build() spawns a subprocess to dlopen a
test .so, protected by a filelock under /tmp/torchinductor_root.
In fresh containers the probe can fail with FileNotFoundError during
lock release — a known upstream issue (pytorch/pytorch#183515,
pytorch/pytorch#134667).

The official workaround is TORCHINDUCTOR_VEC_ISA_OK=1, which tells
Inductor to assume AVX support without running the probe at all.
This replaces the previous mkdir + Python warmup hack.

* fix: use stable cache dir + warmup to fully prevent ISA filelock race

TORCHINDUCTOR_VEC_ISA_OK=1 only short-circuits VecISA.__bool__impl,
but VecAVX512 subclass __bool__ still calls check_build() for BF16
extension, hitting the same filelock race on /tmp.

Two-pronged fix:
- TORCHINDUCTOR_CACHE_DIR=/app/.inductor_cache (stable, not /tmp tmpfs)
- Pre-test warmup step runs pick_vec_isa() to populate cache once

* fix: backport ISA probe caching in conftest to prevent filelock race

Instead of env-var workarounds (TORCHINDUCTOR_CACHE_DIR, VEC_ISA_OK),
cache check_build() results in-memory via conftest.py — equivalent to
upstream PR #181617's .load_ok markers which PT 2.12 lacks.

- Patch VecISA.check_build with dict-based memoization
- Warm up all ISA probes once at collection time via pick_vec_isa()
- Remove TORCHINDUCTOR_VEC_ISA_OK and TORCHINDUCTOR_CACHE_DIR from CI
- Remove the separate warmup step (conftest handles it in-process)

* fix: cleanup_cache only removes magi-owned subdirs, preserves inductor_cache/

Root cause: the autouse cleanup_cache fixture called shutil.rmtree on the
entire cache_root_dir (~/.cache/magi_compiler/), which includes Inductor's
inductor_cache/ subdirectory.  Inductor's async compiler holds FileLock
objects inside that directory; deleting the lock file while still held
causes FileNotFoundError on fcntl.flock(fd, LOCK_UN) in Linux overlayfs
containers (the exact CI failure on PT 2.12).

Fix: only delete MagiCompiler-owned subdirs (magi_cache/, magi_depyf/),
leaving inductor_cache/ untouched so async lock release succeeds.

Also adds test_cleanup_filelock_race.py with minimal reproduction and fix
verification.

* style: apply pre-commit fixes to test_cleanup_filelock_race.py

Add copyright header, remove unused import, fix black formatting.

* ci: temporarily skip pt29 to fast-validate pt212 filelock fix

* fix: patch filelock._release to survive overlayfs FileNotFoundError

Root cause: Docker overlayfs can cause fcntl.flock(fd, LOCK_UN) to raise
FileNotFoundError on unlinked inodes.  This affects every Inductor
filelock path (ISA probe via cpu_vec_isa.check_build, code cache via
codecache.load_async, async compile).

Fix: monkey-patch filelock._unix.UnixFileLock._release in conftest.py
to catch FileNotFoundError and safely close the fd.  This is more robust
than previous attempts (ISA caching, cache dir relocation) because it
covers ALL filelock code paths.

* fix: restore full cache cleanup + keep filelock patch

The selective cleanup (preserving inductor_cache/) caused matmul epilogue
fusion tests to fail due to stale Inductor cache state between tests.

Restore the original shutil.rmtree(cache_root_dir) behavior to ensure
clean state per test, while keeping the filelock._release patch to
handle the overlayfs FileNotFoundError that rmtree triggers.

Also fix test_cleanup_filelock_race.py cleanup to use shutil.rmtree
instead of os.unlink (lock file may already be gone on overlayfs).

* ci: restore pt29 test after pt212 filelock fix verified

* docs: add upstream references to filelock workaround in conftest

Add links to filelock#494, #495, #513 and pytorch#134384 explaining
why _release() raises FileNotFoundError on overlayfs and why the
monkey-patch is needed (upstream fixed _acquire but not _release).

* fix: pin filelock<3.19 to avoid overlayfs FileNotFoundError

filelock >= 3.19 calls unlink() in _release() before flock(LOCK_UN),
which raises FileNotFoundError on Docker overlayfs (the CI container
filesystem).  Versions < 3.19 explicitly preserve lock files on release.

This replaces the previous monkey-patch approach with a clean dependency
pin — no runtime code changes needed.

Ref: tox-dev/filelock#494

* ci: restore pt29 after filelock<3.19 fix verified on pt212

* refactor: centralize PT version detection into envs.py

Move TORCH_VERSION / IS_PT_212 from scattered per-file definitions
into magi_compiler.utils.envs, eliminating 7 duplicate copies.

Also restore test_symbolic_unification.py to original is_compiling()
guard form and split bad_order cache check into _pt29 (u0/u1/u2)
and _pt212 (s-prefixed symbols) variants, verified via experiment.

* fix: split bad_order test for PT 2.9/2.12, add negative test

PT 2.12 + magi_compile two-level compile: is_compiling() guard
is insufficient to prevent symbolic unification when first call
has zero-token modalities. Add ModalityDispatcherMockV2Fixed
using @torch.compiler.disable() wrapper.

- test_bad_order_pt29: OuterModel (is_compiling guard) + u-symbol cache check
- test_bad_order_pt212: OuterModelFixed (@torch.compiler.disable)
- test_is_compiling_guard_insufficient_pt212: negative test asserting
  the is_compiling() approach fails on PT 2.12

Verified on both PT 2.9 (cenn-3) and PT 2.12 (dev__260804).

* fix: version-conditional conv perf threshold (1.20 PT2.9, 1.05 PT2.12)

PT 2.12 torch.compile baseline is faster, narrowing the channels-last
speedup from ~1.2x to ~1.1x. Use IS_PT_212 to keep the original 1.20
threshold on PT 2.9 and relax to 1.05 on PT 2.12.

Measured on H100 (3 runs each):
  PT 2.9:  1.23x, 1.24x, 1.27x  → threshold 1.20 (unchanged)
  PT 2.12: 1.09x, 1.10x, 1.11x  → threshold 1.05

* fix: restore original cache counters, skip only on PT 2.12

Revert training autograd_miss to 1 (the correct PT 2.9 value).
Replace unconditional @pytest.mark.skip with skipif(IS_PT_212)
so PT 2.9 runs the test normally.

* docs: add PT 2.9/2.12 version-split commentary to test_compile_artifacts

Document the three behavioral differences between PyTorch versions
in the module docstring and at each split point:
1. View tensor bad reducer (Patch A)
2. Third-party op serialization (Patch B+C)
3. Unknown op handling (Patch C)

* simplify: remove --no-deps torchtitan hack from Dockerfile

torchtitan==0.2.0 dependencies (including torchdata) resolve cleanly
on both PT 2.9 and 2.12 NVIDIA base images — verified with dry-run.
No need for --no-deps + manual tyro install.

* simplify: remove triton/torchvision from requirements, drop grep hacks

triton and torchvision are tightly coupled to the torch version and
must be pre-installed (e.g. via NVIDIA NGC base image). Pinning them
in requirements causes version conflicts on dual-version CI:
- triton==3.7.1 replaces NVIDIA-patched builds
- torchvision==0.27.1 pulls in torch==2.12.1, destroying PT 2.9 env

Dockerfile now does a straightforward pip install of both requirements
files with no grep filters.

* fix: shrink transformer training test to avoid OOM on shared GPUs

The test only verifies that magi_compile training runs and updates
parameters — no need for a 1024-hidden, 4096-seqlen model.
Reduce to tiny config (hidden=64, seq=32, batch=2) to use <100 MiB
instead of multiple GiB.

---------

Co-authored-by: xlycae <[email protected]>
Co-authored-by: cenn <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Aug 13, 2026
The ROCm manywheel repair step renames bundled ROCm libs to bare .so filenames and rewrites NEEDED references to match. #182696 ported this from build_common.sh to repair_wheel.py and collapsed the shell script's two phases (copy every DEPS_LIST lib into torch/lib, then run replace_needed_sofiles for every soname) into a single per-lib loop that copies a lib and immediately rewrites references to it. replace_needed only visits files present in the wheel at call time, so references from a bundled lib to any lib listed earlier in ROCM_SO_FILES are never rewritten: the dependent has not been copied in yet when its dependency's rewrite pass runs. The 2.13.0+rocm7.2 wheel ships 27 such dangling NEEDED entries (libhiprtc.so -> libamd_comgr.so.3, librocblas.so -> libamdhip64.so.7, libmagma.so -> libhipblas.so.3, ...). Most resolve at runtime by luck (the bundled file keeps its versioned SONAME, so a copy already loaded under that SONAME satisfies the ref) or from a system ROCm install via ldconfig, which is why this went unnoticed until the cold dlopen introduced by #183515 hit the libamd_comgr.so.3 ref on a machine with no ROCm (#189194).

The fix restores the two-phase structure: copy all bundled libs (and their bare-name dlopen symlinks from #189110) first, then run the rewrite passes. A new check_no_dangling_bundled_needed pass then fails the build if any lib in torch/lib still references a versioned soname whose stem is bundled but whose exact name is not shipped, so a future ordering or list regression breaks the build instead of shipping a wheel that silently depends on a system ROCm install.

This complements #189900, which makes the inductor VecISA probe recover from such wheels at runtime; this change makes newly built wheels self-contained again.

Test Plan:

Ran the real repair_wheel() from before and after the change on a minimal fake torch wheel bundling this host's actual ROCm libs in the regression order (libhsa-runtime64 listed before libroctracer64, which NEEDs libhsa-runtime64.so.1): the old code ships the stale versioned ref with no error, the new code rewrites it to libhsa-runtime64.so and the new check passes. Aimed check_no_dangling_bundled_needed at the torch/lib of the actual torch==2.13.0+rocm7.2 wheel (installed from download.pytorch.org/whl/test/rocm7.2): it fails the build listing all 27 dangling references, including the libamd_comgr.so.3 ones from #189194.

```
python validate_repair_wheel.py  # A/B harness driving repair_wheel() from both revisions
```

Authored with Claude (AI assistant).
pytorchmergebot pushed a commit that referenced this pull request Aug 13, 2026
The ROCm manywheel build bundles the ROCm runtime into torch/lib under unversioned filenames (libamd_comgr.so, libamdhip64.so, ...) and rewrites consumers' DT_NEEDED entries to match, but some entries are missed: in the 2.13.0+rocm7.2 wheel, libhiprtc.so, librocprofiler-sdk.so, and librocroller.so still reference libamd_comgr.so.3, a filename that does not exist in the wheel. After `import torch` this is harmless: the bundled libamd_comgr.so is already loaded and registered under its unchanged SONAME libamd_comgr.so.3, so those references resolve against the in-process copy. A cold dlopen has no such copy, so on a machine without a system ROCm install the load fails (a ROCm docker image masks the bug because /opt/rocm provides libamd_comgr.so.3 via ldconfig). #183515 changed the VecISA dlopen probe child from `import torch` + dlopen to a cold dlopen with `LD_LIBRARY_PATH=<torch>/lib`, so on such a machine every `check_build` fails and inductor reports "Can't detect vectorized ISA for CPU".

The fix keeps the fast no-import path but retries after `import torch` if the cold dlopen raises OSError, so whatever loading semantics the wheel relies on are in effect before the second attempt. This also covers the same class of failure for TheRock-based ROCm wheels (ROCm libs preloaded from separate rocm-sdk packages with no rpath) and the latent CUDA case where torch and the nvidia wheels are installed into different site-packages roots and the `$ORIGIN`-relative rpaths dangle (the case `_preload_cuda_deps` exists for). The 60s probe timeout from #183515 still bounds the child either way, so the CI hang that change addressed stays fixed. The missed DT_NEEDED rewrites are arguably a wheel packaging bug worth fixing at the source, but the probe fallback repairs wheels already shipped and does not hardcode any packaging layout into inductor.

Fixes #189194

Test Plan:

Reproduced the failure with the actual 2.13.0+rocm7.2 test wheel in a venv on a ROCm host, using the glibc loader's --inhibit-cache to get the loader semantics of a machine with no system ROCm:

```
pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/test/rocm7.2
# build the real VecISA probe .so via CppBuilder, then:
env -u LD_LIBRARY_PATH /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 --inhibit-cache --library-path <venv>/torch/lib python -c "<probe script>"
```

The pre-fix probe script fails with "OSError: libamd_comgr.so.3: cannot open shared object file" (the exact #189194 failure); the fixed script succeeds via the import torch fallback.

New regression test simulates the layout without needing a ROCm wheel: a probe .so that DT_NEEDEDs libc10.so with no rpath fails to cold-load when LD_LIBRARY_PATH is stripped, and the probe script must recover by importing torch:

```
python test/inductor/test_codecache.py TestVecISACheckBuild
```

All four tests in the class pass on a Linux x86_64 ROCm build, and the fast path still detects VecAVX2 end to end through `valid_vec_isa_list()` without importing torch in the child.

Authored with Claude (AI assistant).
pytorchmergebot pushed a commit that referenced this pull request Aug 14, 2026
…re (#189900)

Fixes #189194

The ROCm manywheel build bundles the ROCm runtime into torch/lib under unversioned filenames (libamd_comgr.so, libamdhip64.so, ...) and rewrites consumers' DT_NEEDED entries to match, but some entries are missed: in the 2.13.0+rocm7.2 wheel, libhiprtc.so, librocprofiler-sdk.so, and librocroller.so still reference libamd_comgr.so.3, a filename that does not exist in the wheel. After `import torch` this is harmless: the bundled libamd_comgr.so is already loaded and registered under its unchanged SONAME libamd_comgr.so.3, so those references resolve against the in-process copy. A cold dlopen has no such copy, so on a machine without a system ROCm install the load fails (a ROCm docker image masks the bug because /opt/rocm provides libamd_comgr.so.3 via ldconfig). #183515 changed the VecISA dlopen probe child from `import torch` + dlopen to a cold dlopen with `LD_LIBRARY_PATH=<torch>/lib`, so on such a machine every `check_build` fails and inductor reports "Can't detect vectorized ISA for CPU". Thanks to @karthickai and @atalman for bisecting to #183515 on the issue.

The fix keeps the fast no-import path but retries after `import torch` if the cold dlopen raises OSError, so whatever loading semantics the wheel relies on are in effect before the second attempt. This also covers the same class of failure for TheRock-based ROCm wheels (ROCm libs preloaded from separate rocm-sdk packages with no rpath) and the latent CUDA case where torch and the nvidia wheels land in different site-packages roots and the `$ORIGIN`-relative rpaths dangle. The 60s probe timeout from #183515 still bounds the child either way, so the CI hang that change addressed stays fixed. The missed DT_NEEDED rewrites are arguably a wheel packaging bug worth fixing at the source, but the probe fallback repairs wheels already shipped and does not hardcode packaging layout into inductor.

Reproduced and validated with the actual 2.13.0+rocm7.2 test wheel in a venv, using the glibc loader's `--inhibit-cache` to emulate a machine with no system ROCm: the pre-fix probe script fails with `OSError: libamd_comgr.so.3: cannot open shared object file` and the fixed script succeeds. The new regression test simulates the layout without needing a ROCm wheel:

```
python test/inductor/test_codecache.py TestVecISACheckBuild
```

This PR was authored with Claude (AI assistant).

Pull Request resolved: #189900
Approved by: https://github.com/atalman
pytorchmergebot pushed a commit that referenced this pull request Aug 14, 2026
#189906)

The ROCm manywheel repair step renames bundled ROCm libs to bare `.so` filenames and rewrites NEEDED references to match. #182696 ported this from build_common.sh to repair_wheel.py and collapsed the shell script's two phases (copy every DEPS_LIST lib into torch/lib, then run replace_needed_sofiles for every soname) into a single per-lib loop that copies a lib and immediately rewrites references to it. `replace_needed` only visits files present in the wheel at call time, so references from a bundled lib to any lib listed earlier in ROCM_SO_FILES are never rewritten: the dependent has not been copied in yet when its dependency's rewrite pass runs. The 2.13.0+rocm7.2 wheel ships 27 such dangling NEEDED entries (`libhiprtc.so -> libamd_comgr.so.3`, `librocblas.so -> libamdhip64.so.7`, `libmagma.so -> libhipblas.so.3`, ...). Most resolve at runtime by luck (the bundled file keeps its versioned SONAME, so a copy already loaded under that SONAME satisfies the ref) or from a system ROCm install via ldconfig, which is why this went unnoticed until the cold dlopen introduced by #183515 hit the `libamd_comgr.so.3` ref on a machine with no ROCm (#189194).

The fix restores the two-phase structure: copy all bundled libs (and their bare-name dlopen symlinks from #189110) first, then run the rewrite passes. A new `check_no_dangling_bundled_needed` pass then fails the build if any lib in torch/lib still references a versioned soname whose stem is bundled but whose exact name is not shipped, so a future ordering or list regression breaks the build instead of shipping a wheel that silently depends on a system ROCm install.

This complements #189900, which makes the inductor VecISA probe recover from such wheels at runtime; this change makes newly built wheels self-contained again.

Validated by running the real `repair_wheel()` from before and after the change on a minimal fake torch wheel bundling actual ROCm libs in the regression order (libhsa-runtime64 listed before libroctracer64, which NEEDs libhsa-runtime64.so.1): the old code ships the stale versioned ref with no error, the new code rewrites it to libhsa-runtime64.so and the new check passes. Aiming `check_no_dangling_bundled_needed` at the torch/lib of the actual torch==2.13.0+rocm7.2 wheel fails the build listing all 27 dangling references, including the `libamd_comgr.so.3` ones from #189194.

This PR was authored with Claude (AI assistant).

Pull Request resolved: #189906
Approved by: https://github.com/atalman, https://github.com/jithunnair-amd
atalman pushed a commit that referenced this pull request Aug 17, 2026
#193600)

[ROCm] Rewrite bundled-lib NEEDED entries after all libs are copied in (#189906)

The ROCm manywheel repair step renames bundled ROCm libs to bare `.so` filenames and rewrites NEEDED references to match. #182696 ported this from build_common.sh to repair_wheel.py and collapsed the shell script's two phases (copy every DEPS_LIST lib into torch/lib, then run replace_needed_sofiles for every soname) into a single per-lib loop that copies a lib and immediately rewrites references to it. `replace_needed` only visits files present in the wheel at call time, so references from a bundled lib to any lib listed earlier in ROCM_SO_FILES are never rewritten: the dependent has not been copied in yet when its dependency's rewrite pass runs. The 2.13.0+rocm7.2 wheel ships 27 such dangling NEEDED entries (`libhiprtc.so -> libamd_comgr.so.3`, `librocblas.so -> libamdhip64.so.7`, `libmagma.so -> libhipblas.so.3`, ...). Most resolve at runtime by luck (the bundled file keeps its versioned SONAME, so a copy already loaded under that SONAME satisfies the ref) or from a system ROCm install via ldconfig, which is why this went unnoticed until the cold dlopen introduced by #183515 hit the `libamd_comgr.so.3` ref on a machine with no ROCm (#189194).

The fix restores the two-phase structure: copy all bundled libs (and their bare-name dlopen symlinks from #189110) first, then run the rewrite passes. A new `check_no_dangling_bundled_needed` pass then fails the build if any lib in torch/lib still references a versioned soname whose stem is bundled but whose exact name is not shipped, so a future ordering or list regression breaks the build instead of shipping a wheel that silently depends on a system ROCm install.

This complements #189900, which makes the inductor VecISA probe recover from such wheels at runtime; this change makes newly built wheels self-contained again.

Validated by running the real `repair_wheel()` from before and after the change on a minimal fake torch wheel bundling actual ROCm libs in the regression order (libhsa-runtime64 listed before libroctracer64, which NEEDs libhsa-runtime64.so.1): the old code ships the stale versioned ref with no error, the new code rewrites it to libhsa-runtime64.so and the new check passes. Aiming `check_no_dangling_bundled_needed` at the torch/lib of the actual torch==2.13.0+rocm7.2 wheel fails the build listing all 27 dangling references, including the `libamd_comgr.so.3` ones from #189194.

This PR was authored with Claude (AI assistant).

Pull Request resolved: #189906
Approved by: https://github.com/atalman, https://github.com/jithunnair-amd

(cherry picked from commit 4973620)

Co-authored-by: Jeff Daily <[email protected]>
atalman pushed a commit that referenced this pull request Aug 17, 2026
…re (#193601)

[ROCm] Retry VecISA dlopen probe with import torch on cold load failure (#189900)

Fixes #189194

The ROCm manywheel build bundles the ROCm runtime into torch/lib under unversioned filenames (libamd_comgr.so, libamdhip64.so, ...) and rewrites consumers' DT_NEEDED entries to match, but some entries are missed: in the 2.13.0+rocm7.2 wheel, libhiprtc.so, librocprofiler-sdk.so, and librocroller.so still reference libamd_comgr.so.3, a filename that does not exist in the wheel. After `import torch` this is harmless: the bundled libamd_comgr.so is already loaded and registered under its unchanged SONAME libamd_comgr.so.3, so those references resolve against the in-process copy. A cold dlopen has no such copy, so on a machine without a system ROCm install the load fails (a ROCm docker image masks the bug because /opt/rocm provides libamd_comgr.so.3 via ldconfig). #183515 changed the VecISA dlopen probe child from `import torch` + dlopen to a cold dlopen with `LD_LIBRARY_PATH=<torch>/lib`, so on such a machine every `check_build` fails and inductor reports "Can't detect vectorized ISA for CPU". Thanks to @karthickai and @atalman for bisecting to #183515 on the issue.

The fix keeps the fast no-import path but retries after `import torch` if the cold dlopen raises OSError, so whatever loading semantics the wheel relies on are in effect before the second attempt. This also covers the same class of failure for TheRock-based ROCm wheels (ROCm libs preloaded from separate rocm-sdk packages with no rpath) and the latent CUDA case where torch and the nvidia wheels land in different site-packages roots and the `$ORIGIN`-relative rpaths dangle. The 60s probe timeout from #183515 still bounds the child either way, so the CI hang that change addressed stays fixed. The missed DT_NEEDED rewrites are arguably a wheel packaging bug worth fixing at the source, but the probe fallback repairs wheels already shipped and does not hardcode packaging layout into inductor.

Reproduced and validated with the actual 2.13.0+rocm7.2 test wheel in a venv, using the glibc loader's `--inhibit-cache` to emulate a machine with no system ROCm: the pre-fix probe script fails with `OSError: libamd_comgr.so.3: cannot open shared object file` and the fixed script succeeds. The new regression test simulates the layout without needing a ROCm wheel:

```
python test/inductor/test_codecache.py TestVecISACheckBuild
```

This PR was authored with Claude (AI assistant).

Pull Request resolved: #189900
Approved by: https://github.com/atalman

(cherry picked from commit 74e49c1)

Co-authored-by: Jeff Daily <[email protected]>
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…re (pytorch#189900)

Fixes pytorch#189194

The ROCm manywheel build bundles the ROCm runtime into torch/lib under unversioned filenames (libamd_comgr.so, libamdhip64.so, ...) and rewrites consumers' DT_NEEDED entries to match, but some entries are missed: in the 2.13.0+rocm7.2 wheel, libhiprtc.so, librocprofiler-sdk.so, and librocroller.so still reference libamd_comgr.so.3, a filename that does not exist in the wheel. After `import torch` this is harmless: the bundled libamd_comgr.so is already loaded and registered under its unchanged SONAME libamd_comgr.so.3, so those references resolve against the in-process copy. A cold dlopen has no such copy, so on a machine without a system ROCm install the load fails (a ROCm docker image masks the bug because /opt/rocm provides libamd_comgr.so.3 via ldconfig). pytorch#183515 changed the VecISA dlopen probe child from `import torch` + dlopen to a cold dlopen with `LD_LIBRARY_PATH=<torch>/lib`, so on such a machine every `check_build` fails and inductor reports "Can't detect vectorized ISA for CPU". Thanks to @karthickai and @atalman for bisecting to pytorch#183515 on the issue.

The fix keeps the fast no-import path but retries after `import torch` if the cold dlopen raises OSError, so whatever loading semantics the wheel relies on are in effect before the second attempt. This also covers the same class of failure for TheRock-based ROCm wheels (ROCm libs preloaded from separate rocm-sdk packages with no rpath) and the latent CUDA case where torch and the nvidia wheels land in different site-packages roots and the `$ORIGIN`-relative rpaths dangle. The 60s probe timeout from pytorch#183515 still bounds the child either way, so the CI hang that change addressed stays fixed. The missed DT_NEEDED rewrites are arguably a wheel packaging bug worth fixing at the source, but the probe fallback repairs wheels already shipped and does not hardcode packaging layout into inductor.

Reproduced and validated with the actual 2.13.0+rocm7.2 test wheel in a venv, using the glibc loader's `--inhibit-cache` to emulate a machine with no system ROCm: the pre-fix probe script fails with `OSError: libamd_comgr.so.3: cannot open shared object file` and the fixed script succeeds. The new regression test simulates the layout without needing a ROCm wheel:

```
python test/inductor/test_codecache.py TestVecISACheckBuild
```

This PR was authored with Claude (AI assistant).

Pull Request resolved: pytorch#189900
Approved by: https://github.com/atalman
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
pytorch#189906)

The ROCm manywheel repair step renames bundled ROCm libs to bare `.so` filenames and rewrites NEEDED references to match. pytorch#182696 ported this from build_common.sh to repair_wheel.py and collapsed the shell script's two phases (copy every DEPS_LIST lib into torch/lib, then run replace_needed_sofiles for every soname) into a single per-lib loop that copies a lib and immediately rewrites references to it. `replace_needed` only visits files present in the wheel at call time, so references from a bundled lib to any lib listed earlier in ROCM_SO_FILES are never rewritten: the dependent has not been copied in yet when its dependency's rewrite pass runs. The 2.13.0+rocm7.2 wheel ships 27 such dangling NEEDED entries (`libhiprtc.so -> libamd_comgr.so.3`, `librocblas.so -> libamdhip64.so.7`, `libmagma.so -> libhipblas.so.3`, ...). Most resolve at runtime by luck (the bundled file keeps its versioned SONAME, so a copy already loaded under that SONAME satisfies the ref) or from a system ROCm install via ldconfig, which is why this went unnoticed until the cold dlopen introduced by pytorch#183515 hit the `libamd_comgr.so.3` ref on a machine with no ROCm (pytorch#189194).

The fix restores the two-phase structure: copy all bundled libs (and their bare-name dlopen symlinks from pytorch#189110) first, then run the rewrite passes. A new `check_no_dangling_bundled_needed` pass then fails the build if any lib in torch/lib still references a versioned soname whose stem is bundled but whose exact name is not shipped, so a future ordering or list regression breaks the build instead of shipping a wheel that silently depends on a system ROCm install.

This complements pytorch#189900, which makes the inductor VecISA probe recover from such wheels at runtime; this change makes newly built wheels self-contained again.

Validated by running the real `repair_wheel()` from before and after the change on a minimal fake torch wheel bundling actual ROCm libs in the regression order (libhsa-runtime64 listed before libroctracer64, which NEEDs libhsa-runtime64.so.1): the old code ships the stale versioned ref with no error, the new code rewrites it to libhsa-runtime64.so and the new check passes. Aiming `check_no_dangling_bundled_needed` at the torch/lib of the actual torch==2.13.0+rocm7.2 wheel fails the build listing all 27 dangling references, including the `libamd_comgr.so.3` ones from pytorch#189194.

This PR was authored with Claude (AI assistant).

Pull Request resolved: pytorch#189906
Approved by: https://github.com/atalman, https://github.com/jithunnair-amd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: inductor Reverted 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