Skip to content

Commit 7c06ec6

Browse files
prateek9623vcsajjansoumitra-chatterjee-technilapateamd-anchaudh
committed
Resolve accelerator-vendor dependency variants from pyproject.toml
MONAI's dependency lists name the packages published for NVIDIA hardware (cucim-cu*, cupy-cuda*, nvidia-*). None of them install or import on AMD ROCm, so monai[all] and monai[cucim] are unusable there, and Dockerfile.rocm had to grep them back out of the requirements it generated. Rather than add a ROCm-specific escape hatch, introduce a general accelerator-vendor mechanism: when MONAI is built or installed against a given vendor's PyTorch, that vendor's plugin rewrites the dependency lists. The extras keep their upstream names and meanings, and pyproject.toml stays the single, statically readable source of truth. monai/config/vendor_deps.py holds the generic engine -- requirement parsing, substitution, de-duplication, the vendor registry and active_vendor(). It carries no vendor knowledge beyond a one-line detection probe per registry entry. monai/config/vendor_rocm.py is the first plugin, supplying the AMD substitution table, the device extras and the rocm requirement. Supporting another vendor means adding a registry entry and a vendor_<name>.py; setup.py does not change. MONAI_VENDOR forces a vendor by name or disables rewriting with `none`. On a ROCm torch, cucim-cu12/cucim-cu13 become amd-hipcim, cupy-cuda* becomes amd-cupy, and nvidia-ml-py, nni and nvidia-nvimgcodec-cu* are dropped. amd-hipcim ships the cucim namespace and amd-cupy ships cupy, so every optional_import call site works unchanged -- no runtime code changes. Isolation is the point of the design, and is enforced rather than assumed: - setup.py passes distclass only when a vendor is active, so an NVIDIA or CPU build calls setup() exactly as upstream does. - A plugin module is imported only after its registry probe matches, so a build for one vendor never executes another vendor's code. - monai/__init__.py eagerly imports every submodule, which pulled the packaging modules -- and with them a vendor plugin -- into every `import monai` on every machine. They are now excluded. This predates the vendor work. - A vendor that is detected but whose plugin cannot be loaded, or whose contract is malformed, fails the build. Falling back to the unmodified lists would ship NVIDIA packages in a ROCm wheel, which is worse than failing. The contract is checked on load because neither mistake raises where it would be used: `key in substitutions` is a substring test on a string, so a SUBSTITUTIONS that is not a mapping quietly matches nothing, and lookups are canonicalised, so a key that is not already a PEP 503 name can never match either. - pip build isolation resolves torch afresh, and a plain PyPI wheel outranks a vendor build of the same release under PEP 440, so a source install on an AMD machine can be handed a CUDA torch, detect no vendor, and emit CUDA dependencies at exit 0. MONAI now warns when it finds an AMD GPU but no ROCm torch; MONAI_VENDOR=none keeps a deliberate CPU build on that hardware quiet. The rocm requirement pins the ROCm *release*, never the HIP version. These are different numbers: ROCm 10.0 ships HIP 7.15 and ROCm 10.1 ships HIP 7.16, while the rocm package is versioned by the release, so torch.version.hip or hipcc --version yield a requirement no index can satisfy. Detection reads the release from the tree ROCM_PATH/ROCM_HOME point at, then the rocm package installed here, then `rocm-sdk version`, and only then a system install, so an unrelated /opt/rocm cannot shadow the SDK being built against. Reading files rather than probing PATH also keeps detection working under pip build isolation. The requirement requests the libraries, devel and per-arch device features and spans ROCM_SERIES_SPAN minor series. devel is needed after install, not only to build: rocm-sdk-core ships libamdhip64.so.7 but not the unversioned libamdhip64.so, so only the devel tree can satisfy a link, and monai/_extensions JIT-compiles its HIP sources through torch.utils.cpp_extension.load() on first use. The span reflects measurement: amd-cupy, amd-hipcim and a MONAI wheel built for ROCm 10.0 all run on a 10.1 runtime, and a one-minor ceiling made pip backtrack off the real wheel onto a 0.0.2 PyPI placeholder stub -- a silent downgrade rather than an error. Also report the HIP toolkit version in get_gpu_info() on ROCm builds, where torch.version.cuda is None and print_config() showed "CUDA version: None". Only the key name changes; it stays behind the existing Has CUDA guard. Dockerfile.rocm drops the grep filter and the separate amd-hipcim install step, both now redundant, and passes AMD's index to the main install. docs/source/installation.md documents the vendor mechanism and gives the full ROCm recipe, including the two ways to install from source under build isolation. Verified end to end on an AMD Instinct MI355X: a clean environment installing monai[cucim] from this branch resolves amd-hipcim, amd-cupy and a ROCm torch with zero CUDA packages, and cupy, cucim and MONAI transforms, losses and metrics all run on the GPU. Across isolated CPU-only, NVIDIA and ROCm build environments on a host carrying both a system /opt/rocm and /usr/local/cuda, non-vendor builds are unaffected: generated metadata and print_dependencies.py output are identical to dev, no vendor module is imported, and no distclass is passed. Faults injected into the ROCm plugin -- a SyntaxError, raising at import, raising while computing the requirement, and a malformed substitution table -- each fail the ROCm build and leave the CPU and NVIDIA builds byte-identical. Also verified on an NVIDIA H100. Signed-off-by: Prateek Chokse <prateek.chokse@amd.com> Signed-off-by: Nilaykumar K Patel <NilaykumarKantibhai.Patel@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 6e358ab commit 7c06ec6

14 files changed

Lines changed: 1128 additions & 12 deletions

‎Dockerfile.rocm‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,33 +79,34 @@ COPY LICENSE CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md README.md versionee
7979
COPY tests ./tests
8080
COPY monai ./monai
8181

82-
# Use print_dependencies.py rather than -e .[all,testing] to filter CUDA-only packages:
83-
# cucim-cu* pulls in cuda-toolkit (~1.2 GB); nvidia-ml-py fails at import on ROCm; nni depends on it.
82+
# Set HIPCIM_INDEX_URL="" to build without WSI/cucim support.
83+
ARG HIPCIM_INDEX_URL="https://pypi.amd.com/rocm-${ROCM_SERIES}.0/simple/"
84+
85+
# print_dependencies.py resolves the ROCm variants of the GPU imaging stack (amd-hipcim, amd-cupy)
86+
# and drops the NVIDIA-only packages, see monai/config/vendor_deps.py.
8487
# BUILD_MONAI=1 builds the C++/HIP extensions ahead of time; FORCE_CUDA=1 is required because the
8588
# build host has no GPU, so setup.py's `torch.cuda.is_available()` check would otherwise skip them.
8689
# Compilation itself needs only the toolkit and PYTORCH_ROCM_ARCH (set above), not a device.
8790
# pytest is not in the "testing" extra; it is added explicitly for running tests by hand.
8891
RUN python monai/config/print_dependencies.py build-system \
8992
| xargs -d '\n' pip install --no-cache-dir --no-build-isolation \
90-
&& python monai/config/print_dependencies.py all testing \
91-
| grep -vE '^cucim-cu|^nvidia-ml-py|^nni' > /tmp/rocm-requirements-$$.txt \
93+
&& python monai/config/print_dependencies.py all testing > /tmp/rocm-requirements-$$.txt \
94+
&& if [ -z "${HIPCIM_INDEX_URL}" ]; then sed -i '/^amd-hipcim/d' /tmp/rocm-requirements-$$.txt; fi \
9295
&& BUILD_MONAI=1 FORCE_CUDA=1 pip install --no-cache-dir --no-build-isolation \
96+
${HIPCIM_INDEX_URL:+--extra-index-url "${HIPCIM_INDEX_URL}"} \
9397
-r /tmp/rocm-requirements-$$.txt pytest -e . \
9498
&& rm -f /tmp/rocm-requirements-$$.txt
9599

96100
# Required at runtime too: monai.config.deviceconfig gates USE_COMPILED on this variable, so
97101
# without it the extensions built above would be present but never used.
98102
ENV BUILD_MONAI=1
99103

100-
# Set HIPCIM_INDEX_URL="" to build without WSI/cucim support.
101104
# CuImage is imported (not just cucim) because cucim uses lazy_loader -- a bare import
102105
# succeeds even when the native library is unresolvable. Failing here is deliberate: if
103106
# hipCIM was requested, an image where the cucim backends silently do not work is worse
104107
# than no image at all.
105-
ARG HIPCIM_INDEX_URL="https://pypi.amd.com/rocm-${ROCM_SERIES}.0/simple/"
106108
RUN if [ -n "${HIPCIM_INDEX_URL}" ]; then \
107-
pip install --no-cache-dir --extra-index-url "${HIPCIM_INDEX_URL}" "amd-hipcim" \
108-
&& python -c "from cucim import CuImage"; \
109+
python -c "from cucim import CuImage"; \
109110
else \
110111
echo "hipCIM not installed; whole-slide-image (cucim) backends are unavailable."; \
111112
fi

‎docs/source/installation.md‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,81 @@ The `nvimgcodec` extra installs GPU-accelerated DICOM decoding for `NvImgCodecPy
8989
(`pip install 'monai[nvimgcodec]'`). It is Linux-only in the extra definition; CUDA 13 is the
9090
default. CUDA 12 users should install matching `cupy-cuda12x` and `nvidia-nvimgcodec-cu12` wheels.
9191

92+
On AMD ROCm the extras above keep their names. When MONAI is built or installed against a ROCm
93+
build of PyTorch, the CUDA-only distributions they pull in are replaced by their AMD counterparts:
94+
`cucim-cu12`/`cucim-cu13` become [`amd-hipcim`](https://rocm.docs.amd.com/projects/hipCIM/en/latest/)
95+
(hipCIM), `cupy-cuda*` becomes `amd-cupy`, and `nvidia-ml-py`, `nni` and `nvidia-nvimgcodec-cu*` are
96+
dropped. `amd-hipcim` ships the `cucim` Python namespace and `amd-cupy` ships `cupy`, so all existing
97+
MONAI code importing from either (e.g. `WSIReader` with `backend="cucim"`, or `convert_to_cupy`)
98+
works on ROCm without any code changes. The required dependencies additionally gain the AMD GPU
99+
device extras (`torch[device-gfx942,device-gfx950]`) and a `rocm[libraries,devel,device-gfx*]`
100+
requirement, which is what steers pip towards the ROCm build of PyTorch. `devel` is included because
101+
`monai/_extensions` JIT-compiles its HIP sources on first use and the link step needs the ROCm
102+
development tree.
103+
104+
This is driven by a general accelerator-vendor mechanism: `monai/config/vendor_deps.py` holds the
105+
generic rewriting and a registry of vendors, and each vendor contributes a `vendor_<name>.py` plugin
106+
listing its package substitutions. A plugin is imported only once its registry probe matches, so a
107+
build for one vendor never runs another vendor's code, and a build with no vendor detected is left
108+
exactly as declared in `pyproject.toml`. Set `MONAI_VENDOR` to a registered vendor name to force one,
109+
or to `none` to disable rewriting. For ROCm, the GPU architectures come from `GPU_TARGETS` or
110+
`AMDGPU_TARGETS` and the ROCm series from `MONAI_ROCM_SERIES`.
111+
112+
Two AMD package indexes are involved, and neither is on PyPI. The ROCm SDK (`rocm`) and the ROCm
113+
build of PyTorch come from the ROCm wheel index. `amd-hipcim` and `amd-cupy` come from the AMD
114+
extensions index, which is published per ROCm series — at the time of writing, `rocm-10.0.0`. Those
115+
wheels are supported on the series they were built for and the one after it, which is the range the
116+
generated `rocm` requirement allows.
117+
118+
Install the ROCm runtime and PyTorch first, selecting the architecture of your GPU (`gfx942` for
119+
MI300X/MI325X, `gfx950` for MI350X/MI355X), then expand the development tree:
120+
121+
```bash
122+
pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ \
123+
"rocm[libraries,devel,device-gfx942]" "torch[device-gfx942]"
124+
rocm-sdk init
125+
```
126+
127+
`rocm-sdk init` is required: the `rocm-sdk-devel` wheel ships its contents as an archive that this
128+
command expands. Without it the ROCm development tree is absent, and `monai/_extensions` fails to
129+
JIT-compile on first use because the link step cannot find `libamdhip64.so`.
130+
131+
Then install MONAI with both indexes available, so the `rocm` requirement and the AMD imaging
132+
packages can both resolve:
133+
134+
```bash
135+
pip install \
136+
--extra-index-url https://stable.repo.amd.com/rocm/whl-next/ \
137+
--extra-index-url https://pypi.amd.com/rocm-10.0.0/simple/ \
138+
'monai[cucim]'
139+
```
140+
141+
AMD currently publishes the imaging wheels for CPython 3.12 on x86_64 Linux only; on other
142+
interpreters or architectures the install fails with `No matching distribution found for
143+
amd-hipcim`.
144+
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+
164+
`Dockerfile.rocm` in the repo root is the authoritative reference for the complete environment setup
165+
(library paths, compiler flags, `rocm-sdk init`, and the full container recipe).
166+
92167
The `hyena` extra pulls in [`nvsubquadratic`](https://github.com/NVIDIA-BioNeMo/nvSubquadratic),
93168
required by `HyenaNDUNETR` / `HyenaMixer` / `HyenaTransformerBlock` (subquadratic
94169
O(N log N) alternatives to windowed self-attention). Install with
@@ -333,7 +408,7 @@ MONAI itself:
333408
```bash
334409
git clone https://github.com/Project-MONAI/MONAI.git
335410
cd MONAI/
336-
python monai/config/print_dependencies.py \* > requirements.txt
411+
python monai/config/print_dependencies.py all testing > requirements.txt
337412
pip install -r requirements.txt
338413
```
339414

‎monai/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ def filter(self, record):
9494
"(.*(__main__)$)",
9595
"(.*(video_dataset)$)",
9696
"(.*(nnunet).*$)",
97+
# packaging-time only, and a vendor plugin must not be imported on another vendor's hardware
98+
"(^(monai.config.vendor_))",
99+
"(^(monai.config.print_dependencies)$)",
97100
]
98101
)
99102

‎monai/config/check_env.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,11 @@ def check_torch_cuda():
123123
"""
124124
import torch
125125

126-
fprint("CUDA version:", torch.version.cuda)
126+
# `torch.version.cuda` is None on a ROCm build, where the toolkit version is `torch.version.hip`.
127+
if torch.version.hip:
128+
fprint("HIP version:", torch.version.hip)
129+
else:
130+
fprint("CUDA version:", torch.version.cuda)
127131

128132
try:
129133
dcount = torch.cuda.device_count()

‎monai/config/deviceconfig.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,12 @@ def get_gpu_info() -> OrderedDict:
214214
_dict_append(output, "Has CUDA", lambda: bool(torch.cuda.is_available()))
215215

216216
if output["Has CUDA"]:
217-
_dict_append(output, "CUDA version", lambda: torch.version.cuda)
217+
# On a ROCm build `torch.version.cuda` is None and `torch.version.hip` carries the toolkit
218+
# version. Reporting "CUDA version: None" is misleading, so the key name switches with the build.
219+
if torch.version.hip:
220+
_dict_append(output, "HIP version", lambda: torch.version.hip)
221+
else:
222+
_dict_append(output, "CUDA version", lambda: torch.version.cuda)
218223
cudnn_ver = torch.backends.cudnn.version()
219224
_dict_append(output, "cuDNN enabled", lambda: bool(cudnn_ver))
220225
_dict_append(output, "NVIDIA_TF32_OVERRIDE", os.environ.get("NVIDIA_TF32_OVERRIDE"))

‎monai/config/print_dependencies.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,21 @@
1414
be piped to a requirements file to work with pip. All required dependencies are always printed, those for builing are
1515
included in "build-system" is given as an argument, and all optional requirements are included if "*" is given. This
1616
assumes the pyproject.toml file is in the current working directory.
17+
18+
On an accelerator-vendor PyTorch the NVIDIA-only distributions are swapped for that vendor's
19+
equivalents, see ``monai.config.vendor_deps``.
1720
"""
1821

1922
from __future__ import annotations
2023

2124
import sys
2225
from collections.abc import Collection
2326

27+
try:
28+
from .vendor_deps import active_vendor
29+
except ImportError: # run as a script rather than imported from the package
30+
from vendor_deps import active_vendor # type: ignore[no-redef]
31+
2432
BUILD_SYSTEM_KEY = "build-system"
2533
PROJ_KEY = "project"
2634
OPTS_KEY = "optional-dependencies"
@@ -57,10 +65,16 @@ def parse_dependencies(filename: str | None = None, sections: Collection[str] |
5765
opts = proj[OPTS_KEY]
5866
dependencies = list(proj[DEP_KEY])
5967
sections = set(sections or [])
68+
vendor = active_vendor()
69+
70+
if vendor is not None:
71+
dependencies = vendor.apply_to_dependencies(dependencies)
72+
opts = vendor.apply_to_optional_dependencies(opts)
6073

6174
if BUILD_SYSTEM_KEY in sections:
6275
sections.remove(BUILD_SYSTEM_KEY)
63-
dependencies += data[BUILD_SYSTEM_KEY][REQ_KEY]
76+
build_requires = data[BUILD_SYSTEM_KEY][REQ_KEY]
77+
dependencies += vendor.apply_to_dependencies(build_requires) if vendor else build_requires
6478

6579
if "*" in sections:
6680
dependencies += sum(opts.values(), [])

0 commit comments

Comments
 (0)