Skip to content

[ROCm] Make amdsmi discovery robust to TheRock ROCm wheels layout - #188724

Closed
amdfaa wants to merge 1 commit into
pytorch:mainfrom
amdfaa:amdfaa/amdsmi-therock-discovery
Closed

amdfaa wants to merge 1 commit into
pytorch:mainfrom
amdfaa:amdfaa/amdsmi-therock-discovery

Conversation

@amdfaa

@amdfaa amdfaa commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On a TheRock-wheels ROCm build, import torch aborts during
_C._initExtension with KeyError: 'libamd_smi.so'. This is the downstream
follow-up to the _preload_rocm_deps() work (#188454) for the TheRock wheels
world: once librocm_sysdeps is preloaded, the next thing that breaks
import torch is amdsmi discovery.

Failure log

Run 28524549808 /
job 84592180921
(rocm-preview distributed shard, head e112afd4ced):

/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/__init__.py", line 2646, in <module>
    _C._initExtension(_manager_path())
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/__init__.py", line 24, in <module>
    from .amdsmi_interface import amdsmi_init
  File ".../site-packages/amdsmi/amdsmi_interface.py", line 32, in <module>
    from . import amdsmi_wrapper
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
                                   ~~~~~~~~~~^^^^^^^^^^^^^^^^^
KeyError: 'libamd_smi.so'

Root cause

The amdsmi python binding's find_smi_library() tries several locations for
libamd_smi.so. On TheRock wheels all of them miss:

  • a relative parent×4/lib/libamd_smi.so.26 assuming the wrapper lives under
    _rocm_sdk_core/share/amd_smi/amdsmi, but TheRock installs the wrapper in
    site-packages/amdsmi, so the relative path miscomputes;
  • $ROCM_HOME/$ROCM_PATH lib/libamd_smi.so — env is unset in the direct
    python preflight;
  • bare libamd_smi.so via the loader path — LD_LIBRARY_PATH/ldconfig unset,
    and this can't match the versioned .so.26 anyway;
  • the wrapper dir / cwd.

All miss, so amdsmi_wrapper.py line 218 does _libraries['libamd_smi.so']
and raises KeyError. torch's existing _amdsmi_cdll_hook only rewrote names
whose basename was exactly libamd_smi.so, only added an extra path when
ROCM_HOME/ROCM_PATH was set, and the surrounding import amdsmi guard only
tolerated ModuleNotFoundError — so a half-installed amdsmi (python package
present, .so undiscoverable) was fatal to import torch. The
/opt/rocm tarball world is unaffected because ROCM_PATH=/opt/rocm is set and
apt amd-smi-lib ships an unversioned /opt/rocm/lib/libamd_smi.so symlink.

Fix (two parts, torch-side, mirrors _preload_rocm_deps() philosophy)

  1. Make _amdsmi_cdll_hook TheRock-aware (torch/cuda/__init__.py):
    locate _rocm_sdk_core via importlib.util.find_spec and append its
    lib/libamd_smi.so* (glob, incl. versioned sonames like libamd_smi.so.26)
    as last-resort candidate paths; match names whose basename starts with
    libamd_smi.so (not just exact) so amdsmi's bare CDLL("libamd_smi.so") is
    redirected to the real versioned file. Existing ROCM_HOME/ROCM_PATH
    behavior is preserved; the TheRock lookup is guarded to Linux and no-ops
    otherwise.
  2. Make a non-discoverable amdsmi non-fatal: broaden the guard so
    KeyError/OSError (not just ModuleNotFoundError) degrade gracefully to
    _HAS_AMDSMI=False instead of killing import torch, matching the existing
    missing-module path (_get_amdsmi_handler still raises a clear
    ModuleNotFoundError chained from the original error when actually used).

Test plan

  • Static: python -c "import ast; ast.parse(open('torch/cuda/__init__.py').read())" passes.
  • Simulated the discovery + match logic off-target: with a fake
    _rocm_sdk_core/lib/libamd_smi.so.26 on sys.path, find_spec + glob
    discovers the versioned soname and basename.startswith("libamd_smi.so")
    matches both libamd_smi.so and libamd_smi.so.26 while rejecting unrelated
    libs; with the package absent, discovery returns [] (no-op).
  • ROCm CI on this PR (TheRock/rocm-preview shards) validates the end-to-end
    import torch fix on a real build.

Made with Cursor

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang

On TheRock ROCm wheels, `import torch` aborts with
`KeyError: 'libamd_smi.so'`: the amdsmi python package installs the native
library as a versioned soname under `_rocm_sdk_core/lib` (e.g.
`libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate
when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset. Its wrapper then
does `_libraries['libamd_smi.so']`, raising `KeyError`, which escapes the
existing guard (only `ModuleNotFoundError` was tolerated) and kills
`import torch`.

Two-part torch-side hardening (mirrors the `_preload_rocm_deps()` philosophy):

1. Make `_amdsmi_cdll_hook` TheRock-aware: locate `_rocm_sdk_core` via
   `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl.
   versioned sonames) as last-resort candidate paths; match names whose
   basename starts with `libamd_smi.so` so amdsmi's bare
   `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing
   `ROCM_HOME`/`ROCM_PATH` behavior is preserved; guarded to Linux.

2. Make a non-discoverable amdsmi non-fatal: a half-installed amdsmi (python
   package present, `.so` undiscoverable) now degrades to `_HAS_AMDSMI=False`
   instead of aborting `import torch`, matching the existing missing-module
   path.

Downstream follow-up to `_preload_rocm_deps()` (pytorch#188454) for the TheRock
wheels world.

Made with Cursor
@amdfaa
amdfaa requested review from Aidyn-A, eqy and syed-ahmed as code owners July 1, 2026 19:38
@pytorch-bot

pytorch-bot Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 72 Cancelled Jobs, 13 Pending

As of commit d68d84a with merge base a7dae7f (image):

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

@pytorch-bot pytorch-bot Bot added the module: rocm AMD GPU support for Pytorch label Jul 1, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 1, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@amdfaa

amdfaa commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Folding this change into #188454 so that a single PR carries both torch-source import-discovery fixes for the TheRock wheels world:

  • torch/__init__.py — _preload_rocm_deps() (the librocm_sysdeps fix), and
  • torch/cuda/__init__.py — the amdsmi / libamd_smi.so discovery fix from this PR (cherry-picked, unchanged).

#188454 already carries the ciflow/rocm-preview label, so its CI validates both fixes together on the actual TheRock preview path. Closing this PR in favor of #188454.

Made with Cursor

@amdfaa amdfaa closed this Jul 1, 2026
pytorchmergebot pushed a commit that referenced this pull request Jul 8, 2026
…oad_rocm_deps`) (#188454)

## Summary

This PR makes PyTorch ROCm/TheRock wheels **self-contained**: it fixes the two `import torch` failures that occur on the wheel (`_rocm_sdk_*` site-packages) layout, so `import torch` works without `LD_LIBRARY_PATH` or a sourced ROCm env (e.g. the ROCm distributed preflight `python .ci/pytorch/rocm_preflight.py`, which never sources `/etc/rocm_env.sh`).

Both fixes live in torch **source**, so they travel with any build (including a bare `python -m build` in a TheRock env), not just CI-produced wheels. This is the **minimal, consolidated PR** carrying **both** import-discovery fixes — a **two-file** diff (`torch/__init__.py` + `torch/cuda/__init__.py`).

Both changes are **no-ops on the traditional tarball `/opt/rocm` install**: each early-returns when the wheel package's `_rocm_sdk_core` is absent, so non-wheel ROCm CI (apt/`/opt/rocm`, whose libs are already on the loader path), CUDA, and CPU builds are unaffected.

## Fixes

### 1. `torch/__init__.py` — `_preload_rocm_deps()`

Fixes `ImportError: librocm_sysdeps_liblzma.so.5: cannot open shared object file` at `from torch._C import *`

- Adds `_preload_rocm_deps()`, the ROCm analogue of `_preload_cuda_deps()` (which handles the `nvidia-*-cu12` wheels). At import time, **before** `import torch._C`, it locates the `rocm` pip package's `_rocm_sdk_core` via `importlib.util.find_spec` (the same anchor `torch.utils.cpp_extension._find_rocm_home()` uses) and `ctypes.CDLL`-preloads (`RTLD_GLOBAL`) the vendored sysdeps (`librocm_sysdeps_*`) and core ROCm runtime libs from `_rocm_sdk_core/lib` and `_rocm_sdk_core/lib/rocm_sysdeps/lib`. Wired into `_load_global_deps()`.
- Guarded to no-op on non-Linux, on non-ROCm builds (`torch.version.hip is None` → CUDA/CPU), and on OS-managed ROCm where `_rocm_sdk_core` is absent (the apt/`/opt/rocm` path).

### 2. `torch/cuda/__init__.py` — amdsmi / `libamd_smi.so` discovery hook + non-fatal guard

Fixes the *next* failure that surfaces once `_preload_rocm_deps()` gets `import torch` past the `librocm_sysdeps` error: `KeyError: 'libamd_smi.so'` raised from the `amdsmi` Python binding at `import amdsmi` (inside `_C._initExtension`)

On TheRock wheels the amdsmi package installs the native library as a versioned soname under `_rocm_sdk_core/lib` (e.g. `libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset; its wrapper then does `_libraries['libamd_smi.so']` → `KeyError`, which escaped the existing guard (only `ModuleNotFoundError` was tolerated) and killed `import torch`. Two-part torch-side hardening:

- Make `_amdsmi_cdll_hook` **TheRock-aware**: locate `_rocm_sdk_core` via `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl. versioned sonames) as last-resort candidate paths; match names whose basename **starts with** `libamd_smi.so` so amdsmi's bare `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing `ROCM_HOME`/`ROCM_PATH` behavior preserved; guarded to Linux.
- Make a non-discoverable amdsmi **non-fatal**: broaden the guard so `KeyError`/`OSError` degrade to `_HAS_AMDSMI=False` instead of aborting `import torch`, matching the existing missing-module path.

## Consolidation note

The amdsmi discovery fix (#2 above) originally shipped as standalone PR #188724. That PR has been **closed** and folded into this PR so **both** import-discovery fixes travel together in a single minimal two-file change.

Scope note: the TheRock tarball→wheels migration and the earlier CI-only RPATH/ldconfig workarounds are **not** part of this PR. The wheels migration is tracked separately by #188429, which rebases on top of this change.

## Validation (TheRock wheel path) — PASSED

Validated end-to-end by **temporarily** stacking Ethan's wheels-migration PR #188429 (which adds the `rocm-preview` wheel CI) on top of the two source fixes and running `ciflow/rocm-preview` (run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341)) on the stacked head. The temporary stack was then **removed**, so this PR remains the minimal two-file source diff.

- **`build-osdc` (TheRock wheel-path build): SUCCESS** — [job 84742887851](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84742887851).
- **`import torch` works on the `_rocm_sdk_*` wheel layout** — proven by the passing shard [`test (default, 5/6)` job 84772673709](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673709), which imports torch and prints the HIP 7.14 / MIOpen 3.5.2 build config.
- **No** `ImportError: librocm_sysdeps*` (incl. `librocm_sysdeps_liblzma`) and **no** `KeyError: 'libamd_smi.so'` anywhere in the run → **both** fixes are validated on the **real TheRock wheel path**.
- Remaining rocm-preview shard failures were **unrelated** to this PR — test-content failures (`test_CTCLoss_cudnn_cuda`, `test_cxx_flags` `RuntimeError map::at`, `test_hip_device_count`, `test_lazy_imports_are_lazy`) and infra (`ROCm pre-flight: no GPUs visible to the container` on the distributed shards).
- Run: https://github.com/pytorch/pytorch/actions/runs/28581558341

### rocm-preview distributed shards (register fat binary failed)

Reference/evidence for the `register fat binary failed` (`code_object.cpp:1038`) investigation — the rocm-preview (TheRock wheel-path) distributed shards from run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341) (`linux-noble-rocm-preview-py3.12-gfx942`), all FAILED:

- distributed 1/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673683 (`test (distributed, 1, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 2/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673678 (`test (distributed, 2, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 3/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673727 (`test (distributed, 3, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)

<details>
<summary>Failure log the amdsmi fix addresses (pre-fix, run 28524549808)</summary>

```
/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
KeyError: 'libamd_smi.so'
```

</details>

## Notes: amdsmi discovery + fat-binary logs

- **Bare `CDLL("libamd_smi.so")`** comes from amdsmi's own `find_smi_library()` (unversioned candidate), not torch; torch's `_amdsmi_cdll_hook` intercepts it and retries the versioned `_rocm_sdk_core/lib/libamd_smi.so*`.
- **Not just preload amdsmi via `_rocm_core_libs`:** amdsmi resolves by exact filename, so an RTLD_GLOBAL versioned `libamd_smi.so.26` won't satisfy it, and eager-preloading a non-`DT_NEEDED` lib reintroduces the ODR double-load the hook prevents — the CDLL-redirect hook is the correct fix.
- **`E0702 … code_object.cpp:1038 register fat binary failed` is not caused by this PR:** it's emitted by the HIP/clr C++ runtime, appears ambiently (~4,774×/run across rocm-preview gfx942 jobs incl. the distributed shards above), and is non-fatal — a pre-existing TheRock rocm-preview build/toolchain matter, orthogonal to these two Python-only changes.
- **Fix-plan pointer (fat-binary):** prove pre-existing on a PR-free `main` rocm-preview baseline → localize via `AMD_LOG_LEVEL=3/4` → scoped clr-log suppress/demote (escalate to clr/comgr pin or `PYTORCH_ROCM_ARCH` only on a real running-arch failure) → validate via `ciflow/rocm-preview`. Belongs in the build/CI layer, not torch source. Tracked in ROCm/frameworks-internal #17160.

## Test plan

- [x] Validate on the TheRock wheel path via `ciflow/rocm-preview` (see **Validation** above).
- [x] `ast.parse` both changed files (`torch/__init__.py`, `torch/cuda/__init__.py`).
- [x] Confirm CUDA and CPU builds are unaffected (both fixes no-op when `torch.version.hip is None` / `_rocm_sdk_core` absent).

Fixes #188561

Made with Cursor

Pull Request resolved: #188454
Approved by: https://github.com/jeffdaily
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…oad_rocm_deps`) (pytorch#188454)

## Summary

This PR makes PyTorch ROCm/TheRock wheels **self-contained**: it fixes the two `import torch` failures that occur on the wheel (`_rocm_sdk_*` site-packages) layout, so `import torch` works without `LD_LIBRARY_PATH` or a sourced ROCm env (e.g. the ROCm distributed preflight `python .ci/pytorch/rocm_preflight.py`, which never sources `/etc/rocm_env.sh`).

Both fixes live in torch **source**, so they travel with any build (including a bare `python -m build` in a TheRock env), not just CI-produced wheels. This is the **minimal, consolidated PR** carrying **both** import-discovery fixes — a **two-file** diff (`torch/__init__.py` + `torch/cuda/__init__.py`).

Both changes are **no-ops on the traditional tarball `/opt/rocm` install**: each early-returns when the wheel package's `_rocm_sdk_core` is absent, so non-wheel ROCm CI (apt/`/opt/rocm`, whose libs are already on the loader path), CUDA, and CPU builds are unaffected.

## Fixes

### 1. `torch/__init__.py` — `_preload_rocm_deps()`

Fixes `ImportError: librocm_sysdeps_liblzma.so.5: cannot open shared object file` at `from torch._C import *`

- Adds `_preload_rocm_deps()`, the ROCm analogue of `_preload_cuda_deps()` (which handles the `nvidia-*-cu12` wheels). At import time, **before** `import torch._C`, it locates the `rocm` pip package's `_rocm_sdk_core` via `importlib.util.find_spec` (the same anchor `torch.utils.cpp_extension._find_rocm_home()` uses) and `ctypes.CDLL`-preloads (`RTLD_GLOBAL`) the vendored sysdeps (`librocm_sysdeps_*`) and core ROCm runtime libs from `_rocm_sdk_core/lib` and `_rocm_sdk_core/lib/rocm_sysdeps/lib`. Wired into `_load_global_deps()`.
- Guarded to no-op on non-Linux, on non-ROCm builds (`torch.version.hip is None` → CUDA/CPU), and on OS-managed ROCm where `_rocm_sdk_core` is absent (the apt/`/opt/rocm` path).

### 2. `torch/cuda/__init__.py` — amdsmi / `libamd_smi.so` discovery hook + non-fatal guard

Fixes the *next* failure that surfaces once `_preload_rocm_deps()` gets `import torch` past the `librocm_sysdeps` error: `KeyError: 'libamd_smi.so'` raised from the `amdsmi` Python binding at `import amdsmi` (inside `_C._initExtension`)

On TheRock wheels the amdsmi package installs the native library as a versioned soname under `_rocm_sdk_core/lib` (e.g. `libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset; its wrapper then does `_libraries['libamd_smi.so']` → `KeyError`, which escaped the existing guard (only `ModuleNotFoundError` was tolerated) and killed `import torch`. Two-part torch-side hardening:

- Make `_amdsmi_cdll_hook` **TheRock-aware**: locate `_rocm_sdk_core` via `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl. versioned sonames) as last-resort candidate paths; match names whose basename **starts with** `libamd_smi.so` so amdsmi's bare `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing `ROCM_HOME`/`ROCM_PATH` behavior preserved; guarded to Linux.
- Make a non-discoverable amdsmi **non-fatal**: broaden the guard so `KeyError`/`OSError` degrade to `_HAS_AMDSMI=False` instead of aborting `import torch`, matching the existing missing-module path.

## Consolidation note

The amdsmi discovery fix (#2 above) originally shipped as standalone PR pytorch#188724. That PR has been **closed** and folded into this PR so **both** import-discovery fixes travel together in a single minimal two-file change.

Scope note: the TheRock tarball→wheels migration and the earlier CI-only RPATH/ldconfig workarounds are **not** part of this PR. The wheels migration is tracked separately by pytorch#188429, which rebases on top of this change.

## Validation (TheRock wheel path) — PASSED

Validated end-to-end by **temporarily** stacking Ethan's wheels-migration PR pytorch#188429 (which adds the `rocm-preview` wheel CI) on top of the two source fixes and running `ciflow/rocm-preview` (run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341)) on the stacked head. The temporary stack was then **removed**, so this PR remains the minimal two-file source diff.

- **`build-osdc` (TheRock wheel-path build): SUCCESS** — [job 84742887851](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84742887851).
- **`import torch` works on the `_rocm_sdk_*` wheel layout** — proven by the passing shard [`test (default, 5/6)` job 84772673709](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673709), which imports torch and prints the HIP 7.14 / MIOpen 3.5.2 build config.
- **No** `ImportError: librocm_sysdeps*` (incl. `librocm_sysdeps_liblzma`) and **no** `KeyError: 'libamd_smi.so'` anywhere in the run → **both** fixes are validated on the **real TheRock wheel path**.
- Remaining rocm-preview shard failures were **unrelated** to this PR — test-content failures (`test_CTCLoss_cudnn_cuda`, `test_cxx_flags` `RuntimeError map::at`, `test_hip_device_count`, `test_lazy_imports_are_lazy`) and infra (`ROCm pre-flight: no GPUs visible to the container` on the distributed shards).
- Run: https://github.com/pytorch/pytorch/actions/runs/28581558341

### rocm-preview distributed shards (register fat binary failed)

Reference/evidence for the `register fat binary failed` (`code_object.cpp:1038`) investigation — the rocm-preview (TheRock wheel-path) distributed shards from run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341) (`linux-noble-rocm-preview-py3.12-gfx942`), all FAILED:

- distributed 1/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673683 (`test (distributed, 1, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 2/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673678 (`test (distributed, 2, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 3/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673727 (`test (distributed, 3, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)

<details>
<summary>Failure log the amdsmi fix addresses (pre-fix, run 28524549808)</summary>

```
/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
KeyError: 'libamd_smi.so'
```

</details>

## Notes: amdsmi discovery + fat-binary logs

- **Bare `CDLL("libamd_smi.so")`** comes from amdsmi's own `find_smi_library()` (unversioned candidate), not torch; torch's `_amdsmi_cdll_hook` intercepts it and retries the versioned `_rocm_sdk_core/lib/libamd_smi.so*`.
- **Not just preload amdsmi via `_rocm_core_libs`:** amdsmi resolves by exact filename, so an RTLD_GLOBAL versioned `libamd_smi.so.26` won't satisfy it, and eager-preloading a non-`DT_NEEDED` lib reintroduces the ODR double-load the hook prevents — the CDLL-redirect hook is the correct fix.
- **`E0702 … code_object.cpp:1038 register fat binary failed` is not caused by this PR:** it's emitted by the HIP/clr C++ runtime, appears ambiently (~4,774×/run across rocm-preview gfx942 jobs incl. the distributed shards above), and is non-fatal — a pre-existing TheRock rocm-preview build/toolchain matter, orthogonal to these two Python-only changes.
- **Fix-plan pointer (fat-binary):** prove pre-existing on a PR-free `main` rocm-preview baseline → localize via `AMD_LOG_LEVEL=3/4` → scoped clr-log suppress/demote (escalate to clr/comgr pin or `PYTORCH_ROCM_ARCH` only on a real running-arch failure) → validate via `ciflow/rocm-preview`. Belongs in the build/CI layer, not torch source. Tracked in ROCm/frameworks-internal pytorch#17160.

## Test plan

- [x] Validate on the TheRock wheel path via `ciflow/rocm-preview` (see **Validation** above).
- [x] `ast.parse` both changed files (`torch/__init__.py`, `torch/cuda/__init__.py`).
- [x] Confirm CUDA and CPU builds are unaffected (both fixes no-op when `torch.version.hip is None` / `_rocm_sdk_core` absent).

Fixes pytorch#188561

Made with Cursor

Pull Request resolved: pytorch#188454
Approved by: https://github.com/jeffdaily
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
…oad_rocm_deps`) (pytorch#188454)

## Summary

This PR makes PyTorch ROCm/TheRock wheels **self-contained**: it fixes the two `import torch` failures that occur on the wheel (`_rocm_sdk_*` site-packages) layout, so `import torch` works without `LD_LIBRARY_PATH` or a sourced ROCm env (e.g. the ROCm distributed preflight `python .ci/pytorch/rocm_preflight.py`, which never sources `/etc/rocm_env.sh`).

Both fixes live in torch **source**, so they travel with any build (including a bare `python -m build` in a TheRock env), not just CI-produced wheels. This is the **minimal, consolidated PR** carrying **both** import-discovery fixes — a **two-file** diff (`torch/__init__.py` + `torch/cuda/__init__.py`).

Both changes are **no-ops on the traditional tarball `/opt/rocm` install**: each early-returns when the wheel package's `_rocm_sdk_core` is absent, so non-wheel ROCm CI (apt/`/opt/rocm`, whose libs are already on the loader path), CUDA, and CPU builds are unaffected.

## Fixes

### 1. `torch/__init__.py` — `_preload_rocm_deps()`

Fixes `ImportError: librocm_sysdeps_liblzma.so.5: cannot open shared object file` at `from torch._C import *`

- Adds `_preload_rocm_deps()`, the ROCm analogue of `_preload_cuda_deps()` (which handles the `nvidia-*-cu12` wheels). At import time, **before** `import torch._C`, it locates the `rocm` pip package's `_rocm_sdk_core` via `importlib.util.find_spec` (the same anchor `torch.utils.cpp_extension._find_rocm_home()` uses) and `ctypes.CDLL`-preloads (`RTLD_GLOBAL`) the vendored sysdeps (`librocm_sysdeps_*`) and core ROCm runtime libs from `_rocm_sdk_core/lib` and `_rocm_sdk_core/lib/rocm_sysdeps/lib`. Wired into `_load_global_deps()`.
- Guarded to no-op on non-Linux, on non-ROCm builds (`torch.version.hip is None` → CUDA/CPU), and on OS-managed ROCm where `_rocm_sdk_core` is absent (the apt/`/opt/rocm` path).

### 2. `torch/cuda/__init__.py` — amdsmi / `libamd_smi.so` discovery hook + non-fatal guard

Fixes the *next* failure that surfaces once `_preload_rocm_deps()` gets `import torch` past the `librocm_sysdeps` error: `KeyError: 'libamd_smi.so'` raised from the `amdsmi` Python binding at `import amdsmi` (inside `_C._initExtension`)

On TheRock wheels the amdsmi package installs the native library as a versioned soname under `_rocm_sdk_core/lib` (e.g. `libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset; its wrapper then does `_libraries['libamd_smi.so']` → `KeyError`, which escaped the existing guard (only `ModuleNotFoundError` was tolerated) and killed `import torch`. Two-part torch-side hardening:

- Make `_amdsmi_cdll_hook` **TheRock-aware**: locate `_rocm_sdk_core` via `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl. versioned sonames) as last-resort candidate paths; match names whose basename **starts with** `libamd_smi.so` so amdsmi's bare `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing `ROCM_HOME`/`ROCM_PATH` behavior preserved; guarded to Linux.
- Make a non-discoverable amdsmi **non-fatal**: broaden the guard so `KeyError`/`OSError` degrade to `_HAS_AMDSMI=False` instead of aborting `import torch`, matching the existing missing-module path.

## Consolidation note

The amdsmi discovery fix (pytorch#2 above) originally shipped as standalone PR pytorch#188724. That PR has been **closed** and folded into this PR so **both** import-discovery fixes travel together in a single minimal two-file change.

Scope note: the TheRock tarball→wheels migration and the earlier CI-only RPATH/ldconfig workarounds are **not** part of this PR. The wheels migration is tracked separately by pytorch#188429, which rebases on top of this change.

## Validation (TheRock wheel path) — PASSED

Validated end-to-end by **temporarily** stacking Ethan's wheels-migration PR pytorch#188429 (which adds the `rocm-preview` wheel CI) on top of the two source fixes and running `ciflow/rocm-preview` (run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341)) on the stacked head. The temporary stack was then **removed**, so this PR remains the minimal two-file source diff.

- **`build-osdc` (TheRock wheel-path build): SUCCESS** — [job 84742887851](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84742887851).
- **`import torch` works on the `_rocm_sdk_*` wheel layout** — proven by the passing shard [`test (default, 5/6)` job 84772673709](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673709), which imports torch and prints the HIP 7.14 / MIOpen 3.5.2 build config.
- **No** `ImportError: librocm_sysdeps*` (incl. `librocm_sysdeps_liblzma`) and **no** `KeyError: 'libamd_smi.so'` anywhere in the run → **both** fixes are validated on the **real TheRock wheel path**.
- Remaining rocm-preview shard failures were **unrelated** to this PR — test-content failures (`test_CTCLoss_cudnn_cuda`, `test_cxx_flags` `RuntimeError map::at`, `test_hip_device_count`, `test_lazy_imports_are_lazy`) and infra (`ROCm pre-flight: no GPUs visible to the container` on the distributed shards).
- Run: https://github.com/pytorch/pytorch/actions/runs/28581558341

### rocm-preview distributed shards (register fat binary failed)

Reference/evidence for the `register fat binary failed` (`code_object.cpp:1038`) investigation — the rocm-preview (TheRock wheel-path) distributed shards from run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341) (`linux-noble-rocm-preview-py3.12-gfx942`), all FAILED:

- distributed 1/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673683 (`test (distributed, 1, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 2/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673678 (`test (distributed, 2, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 3/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673727 (`test (distributed, 3, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)

<details>
<summary>Failure log the amdsmi fix addresses (pre-fix, run 28524549808)</summary>

```
/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
KeyError: 'libamd_smi.so'
```

</details>

## Notes: amdsmi discovery + fat-binary logs

- **Bare `CDLL("libamd_smi.so")`** comes from amdsmi's own `find_smi_library()` (unversioned candidate), not torch; torch's `_amdsmi_cdll_hook` intercepts it and retries the versioned `_rocm_sdk_core/lib/libamd_smi.so*`.
- **Not just preload amdsmi via `_rocm_core_libs`:** amdsmi resolves by exact filename, so an RTLD_GLOBAL versioned `libamd_smi.so.26` won't satisfy it, and eager-preloading a non-`DT_NEEDED` lib reintroduces the ODR double-load the hook prevents — the CDLL-redirect hook is the correct fix.
- **`E0702 … code_object.cpp:1038 register fat binary failed` is not caused by this PR:** it's emitted by the HIP/clr C++ runtime, appears ambiently (~4,774×/run across rocm-preview gfx942 jobs incl. the distributed shards above), and is non-fatal — a pre-existing TheRock rocm-preview build/toolchain matter, orthogonal to these two Python-only changes.
- **Fix-plan pointer (fat-binary):** prove pre-existing on a PR-free `main` rocm-preview baseline → localize via `AMD_LOG_LEVEL=3/4` → scoped clr-log suppress/demote (escalate to clr/comgr pin or `PYTORCH_ROCM_ARCH` only on a real running-arch failure) → validate via `ciflow/rocm-preview`. Belongs in the build/CI layer, not torch source. Tracked in ROCm/frameworks-internal pytorch#17160.

## Test plan

- [x] Validate on the TheRock wheel path via `ciflow/rocm-preview` (see **Validation** above).
- [x] `ast.parse` both changed files (`torch/__init__.py`, `torch/cuda/__init__.py`).
- [x] Confirm CUDA and CPU builds are unaffected (both fixes no-op when `torch.version.hip is None` / `_rocm_sdk_core` absent).

Fixes pytorch#188561

Made with Cursor

Pull Request resolved: pytorch#188454
Approved by: https://github.com/jeffdaily
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…oad_rocm_deps`) (pytorch#188454)

## Summary

This PR makes PyTorch ROCm/TheRock wheels **self-contained**: it fixes the two `import torch` failures that occur on the wheel (`_rocm_sdk_*` site-packages) layout, so `import torch` works without `LD_LIBRARY_PATH` or a sourced ROCm env (e.g. the ROCm distributed preflight `python .ci/pytorch/rocm_preflight.py`, which never sources `/etc/rocm_env.sh`).

Both fixes live in torch **source**, so they travel with any build (including a bare `python -m build` in a TheRock env), not just CI-produced wheels. This is the **minimal, consolidated PR** carrying **both** import-discovery fixes — a **two-file** diff (`torch/__init__.py` + `torch/cuda/__init__.py`).

Both changes are **no-ops on the traditional tarball `/opt/rocm` install**: each early-returns when the wheel package's `_rocm_sdk_core` is absent, so non-wheel ROCm CI (apt/`/opt/rocm`, whose libs are already on the loader path), CUDA, and CPU builds are unaffected.

## Fixes

### 1. `torch/__init__.py` — `_preload_rocm_deps()`

Fixes `ImportError: librocm_sysdeps_liblzma.so.5: cannot open shared object file` at `from torch._C import *`

- Adds `_preload_rocm_deps()`, the ROCm analogue of `_preload_cuda_deps()` (which handles the `nvidia-*-cu12` wheels). At import time, **before** `import torch._C`, it locates the `rocm` pip package's `_rocm_sdk_core` via `importlib.util.find_spec` (the same anchor `torch.utils.cpp_extension._find_rocm_home()` uses) and `ctypes.CDLL`-preloads (`RTLD_GLOBAL`) the vendored sysdeps (`librocm_sysdeps_*`) and core ROCm runtime libs from `_rocm_sdk_core/lib` and `_rocm_sdk_core/lib/rocm_sysdeps/lib`. Wired into `_load_global_deps()`.
- Guarded to no-op on non-Linux, on non-ROCm builds (`torch.version.hip is None` → CUDA/CPU), and on OS-managed ROCm where `_rocm_sdk_core` is absent (the apt/`/opt/rocm` path).

### 2. `torch/cuda/__init__.py` — amdsmi / `libamd_smi.so` discovery hook + non-fatal guard

Fixes the *next* failure that surfaces once `_preload_rocm_deps()` gets `import torch` past the `librocm_sysdeps` error: `KeyError: 'libamd_smi.so'` raised from the `amdsmi` Python binding at `import amdsmi` (inside `_C._initExtension`)

On TheRock wheels the amdsmi package installs the native library as a versioned soname under `_rocm_sdk_core/lib` (e.g. `libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset; its wrapper then does `_libraries['libamd_smi.so']` → `KeyError`, which escaped the existing guard (only `ModuleNotFoundError` was tolerated) and killed `import torch`. Two-part torch-side hardening:

- Make `_amdsmi_cdll_hook` **TheRock-aware**: locate `_rocm_sdk_core` via `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl. versioned sonames) as last-resort candidate paths; match names whose basename **starts with** `libamd_smi.so` so amdsmi's bare `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing `ROCM_HOME`/`ROCM_PATH` behavior preserved; guarded to Linux.
- Make a non-discoverable amdsmi **non-fatal**: broaden the guard so `KeyError`/`OSError` degrade to `_HAS_AMDSMI=False` instead of aborting `import torch`, matching the existing missing-module path.

## Consolidation note

The amdsmi discovery fix (pytorch#2 above) originally shipped as standalone PR pytorch#188724. That PR has been **closed** and folded into this PR so **both** import-discovery fixes travel together in a single minimal two-file change.

Scope note: the TheRock tarball→wheels migration and the earlier CI-only RPATH/ldconfig workarounds are **not** part of this PR. The wheels migration is tracked separately by pytorch#188429, which rebases on top of this change.

## Validation (TheRock wheel path) — PASSED

Validated end-to-end by **temporarily** stacking Ethan's wheels-migration PR pytorch#188429 (which adds the `rocm-preview` wheel CI) on top of the two source fixes and running `ciflow/rocm-preview` (run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341)) on the stacked head. The temporary stack was then **removed**, so this PR remains the minimal two-file source diff.

- **`build-osdc` (TheRock wheel-path build): SUCCESS** — [job 84742887851](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84742887851).
- **`import torch` works on the `_rocm_sdk_*` wheel layout** — proven by the passing shard [`test (default, 5/6)` job 84772673709](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673709), which imports torch and prints the HIP 7.14 / MIOpen 3.5.2 build config.
- **No** `ImportError: librocm_sysdeps*` (incl. `librocm_sysdeps_liblzma`) and **no** `KeyError: 'libamd_smi.so'` anywhere in the run → **both** fixes are validated on the **real TheRock wheel path**.
- Remaining rocm-preview shard failures were **unrelated** to this PR — test-content failures (`test_CTCLoss_cudnn_cuda`, `test_cxx_flags` `RuntimeError map::at`, `test_hip_device_count`, `test_lazy_imports_are_lazy`) and infra (`ROCm pre-flight: no GPUs visible to the container` on the distributed shards).
- Run: https://github.com/pytorch/pytorch/actions/runs/28581558341

### rocm-preview distributed shards (register fat binary failed)

Reference/evidence for the `register fat binary failed` (`code_object.cpp:1038`) investigation — the rocm-preview (TheRock wheel-path) distributed shards from run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341) (`linux-noble-rocm-preview-py3.12-gfx942`), all FAILED:

- distributed 1/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673683 (`test (distributed, 1, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 2/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673678 (`test (distributed, 2, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 3/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673727 (`test (distributed, 3, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)

<details>
<summary>Failure log the amdsmi fix addresses (pre-fix, run 28524549808)</summary>

```
/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
KeyError: 'libamd_smi.so'
```

</details>

## Notes: amdsmi discovery + fat-binary logs

- **Bare `CDLL("libamd_smi.so")`** comes from amdsmi's own `find_smi_library()` (unversioned candidate), not torch; torch's `_amdsmi_cdll_hook` intercepts it and retries the versioned `_rocm_sdk_core/lib/libamd_smi.so*`.
- **Not just preload amdsmi via `_rocm_core_libs`:** amdsmi resolves by exact filename, so an RTLD_GLOBAL versioned `libamd_smi.so.26` won't satisfy it, and eager-preloading a non-`DT_NEEDED` lib reintroduces the ODR double-load the hook prevents — the CDLL-redirect hook is the correct fix.
- **`E0702 … code_object.cpp:1038 register fat binary failed` is not caused by this PR:** it's emitted by the HIP/clr C++ runtime, appears ambiently (~4,774×/run across rocm-preview gfx942 jobs incl. the distributed shards above), and is non-fatal — a pre-existing TheRock rocm-preview build/toolchain matter, orthogonal to these two Python-only changes.
- **Fix-plan pointer (fat-binary):** prove pre-existing on a PR-free `main` rocm-preview baseline → localize via `AMD_LOG_LEVEL=3/4` → scoped clr-log suppress/demote (escalate to clr/comgr pin or `PYTORCH_ROCM_ARCH` only on a real running-arch failure) → validate via `ciflow/rocm-preview`. Belongs in the build/CI layer, not torch source. Tracked in ROCm/frameworks-internal pytorch#17160.

## Test plan

- [x] Validate on the TheRock wheel path via `ciflow/rocm-preview` (see **Validation** above).
- [x] `ast.parse` both changed files (`torch/__init__.py`, `torch/cuda/__init__.py`).
- [x] Confirm CUDA and CPU builds are unaffected (both fixes no-op when `torch.version.hip is None` / `_rocm_sdk_core` absent).

Fixes pytorch#188561

Made with Cursor

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

## Summary

This PR makes PyTorch ROCm/TheRock wheels **self-contained**: it fixes the two `import torch` failures that occur on the wheel (`_rocm_sdk_*` site-packages) layout, so `import torch` works without `LD_LIBRARY_PATH` or a sourced ROCm env (e.g. the ROCm distributed preflight `python .ci/pytorch/rocm_preflight.py`, which never sources `/etc/rocm_env.sh`).

Both fixes live in torch **source**, so they travel with any build (including a bare `python -m build` in a TheRock env), not just CI-produced wheels. This is the **minimal, consolidated PR** carrying **both** import-discovery fixes — a **two-file** diff (`torch/__init__.py` + `torch/cuda/__init__.py`).

Both changes are **no-ops on the traditional tarball `/opt/rocm` install**: each early-returns when the wheel package's `_rocm_sdk_core` is absent, so non-wheel ROCm CI (apt/`/opt/rocm`, whose libs are already on the loader path), CUDA, and CPU builds are unaffected.

## Fixes

### 1. `torch/__init__.py` — `_preload_rocm_deps()`

Fixes `ImportError: librocm_sysdeps_liblzma.so.5: cannot open shared object file` at `from torch._C import *`

- Adds `_preload_rocm_deps()`, the ROCm analogue of `_preload_cuda_deps()` (which handles the `nvidia-*-cu12` wheels). At import time, **before** `import torch._C`, it locates the `rocm` pip package's `_rocm_sdk_core` via `importlib.util.find_spec` (the same anchor `torch.utils.cpp_extension._find_rocm_home()` uses) and `ctypes.CDLL`-preloads (`RTLD_GLOBAL`) the vendored sysdeps (`librocm_sysdeps_*`) and core ROCm runtime libs from `_rocm_sdk_core/lib` and `_rocm_sdk_core/lib/rocm_sysdeps/lib`. Wired into `_load_global_deps()`.
- Guarded to no-op on non-Linux, on non-ROCm builds (`torch.version.hip is None` → CUDA/CPU), and on OS-managed ROCm where `_rocm_sdk_core` is absent (the apt/`/opt/rocm` path).

### 2. `torch/cuda/__init__.py` — amdsmi / `libamd_smi.so` discovery hook + non-fatal guard

Fixes the *next* failure that surfaces once `_preload_rocm_deps()` gets `import torch` past the `librocm_sysdeps` error: `KeyError: 'libamd_smi.so'` raised from the `amdsmi` Python binding at `import amdsmi` (inside `_C._initExtension`)

On TheRock wheels the amdsmi package installs the native library as a versioned soname under `_rocm_sdk_core/lib` (e.g. `libamd_smi.so.26`), which amdsmi's own `find_smi_library()` fails to locate when `$ROCM_HOME`/`$ROCM_PATH` and the loader path are unset; its wrapper then does `_libraries['libamd_smi.so']` → `KeyError`, which escaped the existing guard (only `ModuleNotFoundError` was tolerated) and killed `import torch`. Two-part torch-side hardening:

- Make `_amdsmi_cdll_hook` **TheRock-aware**: locate `_rocm_sdk_core` via `importlib.util.find_spec` and add its `lib/libamd_smi.so*` (glob, incl. versioned sonames) as last-resort candidate paths; match names whose basename **starts with** `libamd_smi.so` so amdsmi's bare `CDLL("libamd_smi.so")` is redirected to the real versioned file. Existing `ROCM_HOME`/`ROCM_PATH` behavior preserved; guarded to Linux.
- Make a non-discoverable amdsmi **non-fatal**: broaden the guard so `KeyError`/`OSError` degrade to `_HAS_AMDSMI=False` instead of aborting `import torch`, matching the existing missing-module path.

## Consolidation note

The amdsmi discovery fix (#2 above) originally shipped as standalone PR pytorch#188724. That PR has been **closed** and folded into this PR so **both** import-discovery fixes travel together in a single minimal two-file change.

Scope note: the TheRock tarball→wheels migration and the earlier CI-only RPATH/ldconfig workarounds are **not** part of this PR. The wheels migration is tracked separately by pytorch#188429, which rebases on top of this change.

## Validation (TheRock wheel path) — PASSED

Validated end-to-end by **temporarily** stacking Ethan's wheels-migration PR pytorch#188429 (which adds the `rocm-preview` wheel CI) on top of the two source fixes and running `ciflow/rocm-preview` (run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341)) on the stacked head. The temporary stack was then **removed**, so this PR remains the minimal two-file source diff.

- **`build-osdc` (TheRock wheel-path build): SUCCESS** — [job 84742887851](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84742887851).
- **`import torch` works on the `_rocm_sdk_*` wheel layout** — proven by the passing shard [`test (default, 5/6)` job 84772673709](https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673709), which imports torch and prints the HIP 7.14 / MIOpen 3.5.2 build config.
- **No** `ImportError: librocm_sysdeps*` (incl. `librocm_sysdeps_liblzma`) and **no** `KeyError: 'libamd_smi.so'` anywhere in the run → **both** fixes are validated on the **real TheRock wheel path**.
- Remaining rocm-preview shard failures were **unrelated** to this PR — test-content failures (`test_CTCLoss_cudnn_cuda`, `test_cxx_flags` `RuntimeError map::at`, `test_hip_device_count`, `test_lazy_imports_are_lazy`) and infra (`ROCm pre-flight: no GPUs visible to the container` on the distributed shards).
- Run: https://github.com/pytorch/pytorch/actions/runs/28581558341

### rocm-preview distributed shards (register fat binary failed)

Reference/evidence for the `register fat binary failed` (`code_object.cpp:1038`) investigation — the rocm-preview (TheRock wheel-path) distributed shards from run [28581558341](https://github.com/pytorch/pytorch/actions/runs/28581558341) (`linux-noble-rocm-preview-py3.12-gfx942`), all FAILED:

- distributed 1/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673683 (`test (distributed, 1, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 2/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673678 (`test (distributed, 2, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)
- distributed 3/3: https://github.com/pytorch/pytorch/actions/runs/28581558341/job/84772673727 (`test (distributed, 3, 3, linux.rocm.gpu.gfx942.4, module:rocm, oncall:distributed)`)

<details>
<summary>Failure log the amdsmi fix addresses (pre-fix, run 28524549808)</summary>

```
/var/lib/jenkins/workspace/libamd_smi.so: cannot open shared object file: No such file or directory
Unable to find libamd_smi.so library try installing amd-smi-lib from your package manager
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/.ci/pytorch/rocm_preflight.py", line 21, in <module>
    import torch
  File ".../site-packages/torch/cuda/__init__.py", line 114, in <module>
    import amdsmi  # type: ignore[import]
  File ".../site-packages/amdsmi/amdsmi_wrapper.py", line 218, in <module>
    amdsmi_free_name_value_pairs = _libraries['libamd_smi.so'].amdsmi_free_name_value_pairs
KeyError: 'libamd_smi.so'
```

</details>

## Notes: amdsmi discovery + fat-binary logs

- **Bare `CDLL("libamd_smi.so")`** comes from amdsmi's own `find_smi_library()` (unversioned candidate), not torch; torch's `_amdsmi_cdll_hook` intercepts it and retries the versioned `_rocm_sdk_core/lib/libamd_smi.so*`.
- **Not just preload amdsmi via `_rocm_core_libs`:** amdsmi resolves by exact filename, so an RTLD_GLOBAL versioned `libamd_smi.so.26` won't satisfy it, and eager-preloading a non-`DT_NEEDED` lib reintroduces the ODR double-load the hook prevents — the CDLL-redirect hook is the correct fix.
- **`E0702 … code_object.cpp:1038 register fat binary failed` is not caused by this PR:** it's emitted by the HIP/clr C++ runtime, appears ambiently (~4,774×/run across rocm-preview gfx942 jobs incl. the distributed shards above), and is non-fatal — a pre-existing TheRock rocm-preview build/toolchain matter, orthogonal to these two Python-only changes.
- **Fix-plan pointer (fat-binary):** prove pre-existing on a PR-free `main` rocm-preview baseline → localize via `AMD_LOG_LEVEL=3/4` → scoped clr-log suppress/demote (escalate to clr/comgr pin or `PYTORCH_ROCM_ARCH` only on a real running-arch failure) → validate via `ciflow/rocm-preview`. Belongs in the build/CI layer, not torch source. Tracked in ROCm/frameworks-internal pytorch#17160.

## Test plan

- [x] Validate on the TheRock wheel path via `ciflow/rocm-preview` (see **Validation** above).
- [x] `ast.parse` both changed files (`torch/__init__.py`, `torch/cuda/__init__.py`).
- [x] Confirm CUDA and CPU builds are unaffected (both fixes no-op when `torch.version.hip is None` / `_rocm_sdk_core` absent).

Fixes pytorch#188561

Made with Cursor

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

Labels

ciflow/trunk Trigger trunk jobs on your pull request module: rocm AMD GPU support for Pytorch open source

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants