Skip to content

Commit 732a952

Browse files
prateek9623vcsajjansoumitra-chatterjee-technilapateamd-anchaudh
committed
Warn when vendor hardware is present but its torch is not
pip builds in an isolated environment that resolves torch afresh, and a plain PyPI torch outranks a vendor build of the same release under PEP 440. A source install on an AMD machine therefore gets a CUDA torch in the build environment, detects no vendor, and emits the unmodified CUDA dependency lists -- succeeding silently. Observed on an MI355X: `pip install "monai[cucim] @ git+..."` resolved cucim-cu13, cupy-cuda13x and torch 2.14.1+cu130, exit 0. The VendorPluginError guard does not cover this. It fires when a vendor is detected and its plugin then fails; here nothing is detected at all, which is indistinguishable from a legitimate CPU build. Registrations gain an optional hardware probe, used only for this warning and never to select a plugin. For ROCm it reads the amdgpu compute nodes under /sys/class/kfd, ignoring node 0, which is the host CPU. MONAI_VENDOR=none returns before the check, so a deliberate CPU build on vendor hardware stays quiet. Metadata is unchanged in every case: the probe reports, it never rewrites. docs/source/installation.md gains the two working recipes for source installs: --no-build-isolation in an environment that already has a ROCm torch, or MONAI_VENDOR with MONAI_ROCM_SERIES under isolation. Signed-off-by: Prateek Chokse <prateek.chokse@amd.com> Co-authored-by: Vikas C Sajjan <Vikas.CSajjan@amd.com> Co-authored-by: Soumitra Chatterjee <Soumitra.Chatterjee@amd.com> Co-authored-by: Nilaykumar K Patel <NilaykumarKantibhai.Patel@amd.com> Co-authored-by: Anik Chaudhuri <Anik.Chaudhuri@amd.com>
1 parent dea4034 commit 732a952

3 files changed

Lines changed: 122 additions & 2 deletions

File tree

‎docs/source/installation.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,25 @@ AMD currently publishes the imaging wheels for CPython 3.12 on x86_64 Linux only
142142
interpreters or architectures the install fails with `No matching distribution found for
143143
amd-hipcim`.
144144

145+
Installing from source or from a git URL needs one extra step. `pip` builds in an isolated
146+
environment that resolves `torch` afresh, and a plain PyPI `torch` outranks a ROCm build of the same
147+
release, so the build can see a CUDA torch and emit CUDA dependencies on an AMD machine. MONAI warns
148+
when it finds an AMD GPU but no ROCm torch. Either build without isolation, in an environment that
149+
already has ROCm torch:
150+
151+
```bash
152+
pip install --no-build-isolation \
153+
--extra-index-url https://stable.repo.amd.com/rocm/whl-next/ \
154+
--extra-index-url https://pypi.amd.com/rocm-10.0.0/simple/ \
155+
'monai[cucim] @ git+https://github.com/Project-MONAI/MONAI'
156+
```
157+
158+
or keep isolation and name the vendor and series explicitly:
159+
160+
```bash
161+
MONAI_VENDOR=rocm MONAI_ROCM_SERIES=10.0 pip install ...
162+
```
163+
145164
`Dockerfile.rocm` in the repo root is the authoritative reference for the complete environment setup
146165
(library paths, compiler flags, `rocm-sdk init`, and the full container recipe).
147166

‎monai/config/vendor_deps.py‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
import os
4646
import re
4747
import sys
48+
import warnings
4849
from collections.abc import Callable
4950
from dataclasses import dataclass
5051
from typing import Any
@@ -95,17 +96,43 @@ def _torch_version_attr(attr: str) -> str:
9596
return ""
9697

9798

99+
KFD_TOPOLOGY_NODES = "/sys/class/kfd/kfd/topology/nodes"
100+
101+
102+
def _amd_gpu_present() -> bool:
103+
"""True when the amdgpu driver exposes a GPU compute node. Node 0 is the host CPU."""
104+
try:
105+
nodes = sorted(os.scandir(KFD_TOPOLOGY_NODES), key=lambda node: node.name)
106+
except OSError:
107+
return False
108+
for node in nodes:
109+
try:
110+
with open(os.path.join(node.path, "properties")) as handle:
111+
text = handle.read()
112+
except OSError:
113+
continue
114+
match = re.search(r"^gfx_target_version (\d+)", text, re.M)
115+
if match and match.group(1) != "0":
116+
return True
117+
return False
118+
119+
98120
@dataclass(frozen=True)
99121
class _Registration:
100-
"""A vendor plugin and the cheap probe deciding whether to load it."""
122+
"""A vendor plugin, the cheap probe deciding whether to load it, and an optional probe for the
123+
vendor's hardware used only to warn when that hardware is present but its PyTorch is not.
124+
"""
101125

102126
module: str
103127
detect: Callable[[], bool]
128+
hardware: Callable[[], bool] | None = None
104129

105130

106131
# Probes must stay trivial and must not import the plugin module: they run on every build, including
107132
# builds for other vendors. Add new vendors here and in the matching ``vendor_<name>.py``.
108-
REGISTRY: dict[str, _Registration] = {"rocm": _Registration("vendor_rocm", lambda: bool(_torch_version_attr("hip")))}
133+
REGISTRY: dict[str, _Registration] = {
134+
"rocm": _Registration("vendor_rocm", lambda: bool(_torch_version_attr("hip")), _amd_gpu_present)
135+
}
109136

110137
# name, optional "[extras]", then everything else (version specifiers, markers, URLs).
111138
_REQUIREMENT = re.compile(r"\s*(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[(?P<extras>[^]]*)\])?(?P<rest>.*)", re.S)
@@ -207,4 +234,24 @@ def active_vendor() -> ActiveVendor | None:
207234
for name, registration in REGISTRY.items():
208235
if registration.detect():
209236
return _load(name)
237+
_warn_hardware_without_vendor()
210238
return None
239+
240+
241+
def _warn_hardware_without_vendor() -> None:
242+
"""Warn when a vendor's hardware is present but the torch this build sees is not its build.
243+
244+
Under ``pip`` build isolation the build environment resolves ``torch`` afresh, and a generic
245+
PyPI wheel outranks a vendor build under PEP 440, so a source install on vendor hardware can
246+
otherwise emit another vendor's dependencies without a word.
247+
"""
248+
for name, registration in REGISTRY.items():
249+
if registration.hardware is not None and registration.hardware():
250+
warnings.warn(
251+
f"{name} hardware is present, but the torch this build sees is not a {name} build, "
252+
f"so {name} dependencies were not applied. Build against a {name} torch (for a "
253+
f"source install, `pip install --no-build-isolation` in an environment that already "
254+
f"has one), or set MONAI_VENDOR={name} to apply them regardless.",
255+
stacklevel=3,
256+
)
257+
return

‎tests/config/test_vendor_deps.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@
1111

1212
from __future__ import annotations
1313

14+
import tempfile
1415
import types
1516
import unittest
17+
import warnings
18+
from pathlib import Path
1619
from unittest.mock import patch
1720

1821
from monai.config import vendor_deps
@@ -137,5 +140,56 @@ def test_explicit_vendor_that_cannot_load_is_fatal(self):
137140
active_vendor()
138141

139142

143+
class TestHardwareWithoutVendor(unittest.TestCase):
144+
"""``pip`` build isolation can hand the build a generic torch while sitting on vendor hardware."""
145+
146+
def test_warns_when_hardware_present_but_torch_is_not(self):
147+
probe = vendor_deps._Registration("vendor_rocm", lambda: False, lambda: True)
148+
with (
149+
patch.dict("os.environ", {}, clear=True),
150+
patch.dict(vendor_deps.REGISTRY, {"rocm": probe}, clear=True),
151+
self.assertWarnsRegex(UserWarning, "rocm hardware is present"),
152+
):
153+
self.assertIsNone(active_vendor())
154+
155+
def test_silent_when_hardware_absent(self):
156+
probe = vendor_deps._Registration("vendor_rocm", lambda: False, lambda: False)
157+
with (
158+
patch.dict("os.environ", {}, clear=True),
159+
patch.dict(vendor_deps.REGISTRY, {"rocm": probe}, clear=True),
160+
warnings.catch_warnings(record=True) as caught,
161+
):
162+
warnings.simplefilter("always")
163+
self.assertIsNone(active_vendor())
164+
self.assertEqual([], [str(w.message) for w in caught])
165+
166+
def test_silent_when_the_vendor_is_active(self):
167+
probe = vendor_deps._Registration("vendor_rocm", lambda: True, lambda: True)
168+
with (
169+
patch.dict("os.environ", {}, clear=True),
170+
patch.dict(vendor_deps.REGISTRY, {"rocm": probe}, clear=True),
171+
warnings.catch_warnings(record=True) as caught,
172+
):
173+
warnings.simplefilter("always")
174+
self.assertEqual("rocm", active_vendor().name)
175+
self.assertEqual([], [str(w.message) for w in caught])
176+
177+
def test_gpu_probe_ignores_the_cpu_node(self):
178+
with tempfile.TemporaryDirectory() as root:
179+
nodes = Path(root)
180+
(nodes / "0").mkdir()
181+
(nodes / "0" / "properties").write_text("cpu_cores_count 128\ngfx_target_version 0\n")
182+
with patch.object(vendor_deps, "KFD_TOPOLOGY_NODES", str(nodes)):
183+
self.assertFalse(vendor_deps._amd_gpu_present())
184+
(nodes / "1").mkdir()
185+
(nodes / "1" / "properties").write_text("cpu_cores_count 0\ngfx_target_version 90500\n")
186+
with patch.object(vendor_deps, "KFD_TOPOLOGY_NODES", str(nodes)):
187+
self.assertTrue(vendor_deps._amd_gpu_present())
188+
189+
def test_gpu_probe_without_the_amdgpu_driver(self):
190+
with patch.object(vendor_deps, "KFD_TOPOLOGY_NODES", "/nonexistent-kfd"):
191+
self.assertFalse(vendor_deps._amd_gpu_present())
192+
193+
140194
if __name__ == "__main__":
141195
unittest.main()

0 commit comments

Comments
 (0)