From 39e6790f201bcacb6a5c223fed20e298bb65262b Mon Sep 17 00:00:00 2001 From: Samuel Reeder Date: Tue, 24 Nov 2026 17:35:22 +0000 Subject: [PATCH] feat(setup): reuse prebuilt wheel hipDNN, MIOpen, and hipBLASLt plugins by default --- docs/setup.md | 11 +- setup_env.py | 250 +++++++++++++++++++++++++++++++---- tests/unit/test_setup_env.py | 226 +++++++++++++++++++++++++++++++ 3 files changed, 456 insertions(+), 31 deletions(-) diff --git a/docs/setup.md b/docs/setup.md index b1dd61d..63d39b6 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -34,9 +34,13 @@ stages are: `--reuse-artifacts`. 6. `Provider descriptor artifacts`: `dvc pull` the DVC-tracked kernel-ingestor descriptors. Skipped with `--reuse-artifacts`. -7. `hipDNN and provider plugins`: build hipDNN and the MIOpen, hipBLASLt and - hip-kernel providers, and install them into the ROCm SDK prefix. With - `--reuse-artifacts`, only check that hipDNN is in the prefix. +7. `hipDNN and provider plugins`: reuse prebuilt hipDNN, MIOpen and hipBLASLt + binaries from the ROCm SDK prefix when present and matched to the pinned + `rocm-libraries` commit, building only `hip-kernel-provider` (for rocKE and + the kernel ingestor on Linux; skipped on Windows when all plugins are + prebuilt). Pass `--build-from-source` (or `--rocm-libraries-ref`) to build + hipDNN and every provider from source. With `--reuse-artifacts`, only check + that hipDNN CMake configs exist in the prefix or toolchain. 8. `hipDNN Python bindings`: build `hipdnn_frontend` against that prefix. With `--reuse-artifacts`, build nothing and instead check that the venv has the `hipdnn_frontend` package, without importing it (its native @@ -74,6 +78,7 @@ The setup prints the prefix as `Using hipDNN/ROCm prefix: ...`. | `--gpu-arch GPU_ARCH` | GPU architecture for the ROCm PyTorch nightly and the build. See [GPU architecture](#gpu-architecture). | | `--rocm-prefix ROCM_PREFIX` | ROCm and hipDNN prefix for the binding and provider builds. This prefix has priority over the venv ROCm SDK. | | `--reuse-artifacts` | Reuse an installed hipDNN prefix and `hipdnn_frontend` package without building them. `rocm`, `cpu` and `none` need a pre-existing venv with matching PyTorch (`none`: no torch) and reject `--clean` before workspace changes. `existing` keeps the installed torch. CUDA-only setup needs no hipDNN bindings. | +| `--build-from-source` | Build hipDNN and all provider plugins (MIOpen, hipBLASLt and hip-kernel) from source instead of reusing prebuilt hipDNN, MIOpen and hipBLASLt binaries from the ROCm SDK prefix. Implied by `--rocm-libraries-ref`. | | `--no-aiter` | Skip the `AITER` stage. Only `--runtime aiter` needs it. | | `--clean` | Delete and create again the venv, and delete the hipDNN, provider and binding build directories. Not allowed with `--torch-mode existing`. | | `--rocm-libraries-ref SHA` | Full 40-character `rocm-libraries` commit to fetch when `rocm-libraries/` is absent. Default: matched to `--rocm-version` (`latest` or explicit), else `rocm_libraries_commit` from `rocm-pin.json`. Abbreviated SHAs and branch names are rejected. | diff --git a/setup_env.py b/setup_env.py index e26020c..dc1bc38 100755 --- a/setup_env.py +++ b/setup_env.py @@ -66,6 +66,28 @@ / "kernel_ingestor_engine" / "descriptors" ) +SUPERBUILD_ALL_COMPONENTS = ( + "hipdnn", + "miopen-provider", + "hipblaslt-provider", + "hip-kernel-provider", +) +SUPERBUILD_HYBRID_COMPONENTS = ("hip-kernel-provider",) +# Subtrees whose prebuilt wheel binaries are reused in hybrid mode; local +# edits under any of these trigger a full source build instead. +_PREBUILT_ROCM_LIBRARIES_SUBDIRS = ( + "projects/hipdnn", + "dnn-providers/miopen-provider", + "dnn-providers/hipblaslt-provider", +) + +_PREBUILT_HIPDNN_CMAKE_CONFIGS = ( + "lib/cmake/hipdnn_frontend/hipdnn_frontendConfig.cmake", + "lib/cmake/hipdnn_backend/hipdnn_backendConfig.cmake", + "lib/cmake/hipdnn_data_sdk/hipdnn_data_sdkConfig.cmake", + "lib/cmake/hipdnn_flatbuffers_sdk/hipdnn_flatbuffers_sdkConfig.cmake", + "lib/cmake/hipdnn_plugin_sdk/hipdnn_plugin_sdkConfig.cmake", +) AITER_DIR = SCRIPT_DIR / "aiter" # AITER submodules that its JIT compiles against: the CK headers and the CK @@ -1129,6 +1151,16 @@ def build_parser() -> argparse.ArgumentParser: "the installed torch; CUDA-only setups need no hipDNN bindings." ), ) + parser.add_argument( + "--build-from-source", + action="store_true", + help=( + "Build hipDNN and all provider plugins (MIOpen, hipBLASLt and " + "hip-kernel) from source instead of reusing prebuilt hipDNN, " + "MIOpen and hipBLASLt binaries from the ROCm SDK prefix. " + "Implied by --rocm-libraries-ref." + ), + ) parser.add_argument( "--no-aiter", dest="aiter", @@ -1205,6 +1237,7 @@ class Setup: def __init__(self, args: argparse.Namespace) -> None: self.torch_mode = args.torch_mode self.reuse_artifacts = args.reuse_artifacts + self.build_from_source = args.build_from_source self.with_aiter = args.aiter self.auto_yes = args.yes self.clean = args.clean @@ -1222,6 +1255,7 @@ def __init__(self, args: argparse.Namespace) -> None: self.current_stage = "preflight" self.n_stages = 0 self._stage_index = 0 + self._rocm_libraries_matches_pin = True self.do_build = not self.reuse_artifacts and self.torch_mode != "cuda" @@ -1350,6 +1384,7 @@ def ensure_rocm_libraries_checkout(self) -> None: # sparse clone would otherwise go unnoticed. head = git_output(["-C", str(ROCM_LIBRARIES_DIR), "rev-parse", "HEAD"]) if pinned and head != ref: + self._rocm_libraries_matches_pin = False if source == "quartz": therock_note = ( f" (matched to TheRock {therock_commit[:12]})" @@ -1368,6 +1403,8 @@ def ensure_rocm_libraries_checkout(self) -> None: f"{ref[:12]}. Check out that commit in rocm-libraries/ " "or delete the directory to fetch it." ) + if self._rocm_libraries_has_prebuilt_edits(): + self._rocm_libraries_matches_pin = False if not (ROCM_LIBRARIES_DIR / "CMakePresets.json").is_file(): warn( "rocm-libraries/CMakePresets.json is missing (a non-cone " @@ -1439,6 +1476,24 @@ def _rocm_libraries_is_sparse() -> bool: except subprocess.CalledProcessError: return False + @staticmethod + def _rocm_libraries_has_prebuilt_edits() -> bool: + """True when rocm-libraries/ has local changes under any prebuilt tree.""" + try: + out = git_output( + [ + "-C", + str(ROCM_LIBRARIES_DIR), + "status", + "--porcelain", + "--", + *_PREBUILT_ROCM_LIBRARIES_SUBDIRS, + ] + ) + except subprocess.CalledProcessError: + return False + return bool(out.strip()) + @staticmethod def _pinned_submodule_commit(name: str, fallback_note: str) -> str: """The commit this repository pins for submodule ``name``. @@ -1887,6 +1942,92 @@ def prefix_has_hipdnn(self, prefix: str) -> bool: and self.hipdnn_backend_config_path(prefix).is_file() ) + def prefixes_have_hipdnn(self, *prefixes: str) -> bool: + return any(self.prefix_has_hipdnn(p) for p in prefixes if p) + + @staticmethod + def _prefixes_have_prebuilt_hipdnn_sdk( + install_prefix: str, toolchain_prefix: str + ) -> bool: + """True when all hipDNN SDK CMake configs exist in either prefix.""" + roots = tuple(Path(p) for p in (install_prefix, toolchain_prefix) if p) + return all( + any((root / rel).is_file() for root in roots) + for rel in _PREBUILT_HIPDNN_CMAKE_CONFIGS + ) + + @staticmethod + def _prefix_has_prebuilt_plugins( + install_prefix: str, *, include_hip_kernel: bool = False + ) -> bool: + """True when install_prefix already holds prebuilt hipDNN + plugins.""" + root = Path(install_prefix) + if IS_WINDOWS: + required = [ + root / "bin" / "hipdnn_backend.dll", + root / "bin" / "hipdnn_plugins" / "engines" / "miopen_plugin.dll", + root / "bin" / "hipdnn_plugins" / "engines" / "hipblaslt_plugin.dll", + ] + if include_hip_kernel: + required.append( + root + / "bin" + / "hipdnn_plugins" + / "engines" + / "hip_kernel_provider.dll" + ) + else: + required = [ + root / "lib" / "libhipdnn_backend.so", + root / "lib" / "hipdnn_plugins" / "engines" / "libmiopen_plugin.so", + root / "lib" / "hipdnn_plugins" / "engines" / "libhipblaslt_plugin.so", + ] + if include_hip_kernel: + required.append( + root + / "lib" + / "hipdnn_plugins" + / "engines" + / "libhip_kernel_provider.so" + ) + return all(path.exists() for path in required) + + def select_superbuild_components( + self, install_prefix: str, toolchain_prefix: str + ) -> Tuple[str, ...]: + """Components to build in rocm-libraries (empty = skip superbuild). + + Defaults to hybrid mode when the ROCm prefix/toolchain already ships + hipDNN, MIOpen and hipBLASLt plugins matching the pinned commit: Linux + rebuilds only hip-kernel-provider (for rocKE + kernel ingestor), and + Windows skips the superbuild when hip_kernel_provider.dll is present + and no --cmake-arg was passed. Falls back to the full superbuild on + --build-from-source, --rocm-libraries-ref, local edits/mismatched HEAD + in rocm-libraries/, or a prefix without prebuilt hipDNN/plugins. + """ + if self.build_from_source or self.rocm_libraries_ref: + return SUPERBUILD_ALL_COMPONENTS + if not self._rocm_libraries_matches_pin: + print( + "rocm-libraries/ differs from the pinned wheel commit or has " + "local edits; building hipDNN and all providers from source." + ) + return SUPERBUILD_ALL_COMPONENTS + if not ( + self._prefixes_have_prebuilt_hipdnn_sdk(install_prefix, toolchain_prefix) + and self._prefix_has_prebuilt_plugins(install_prefix) + ): + return SUPERBUILD_ALL_COMPONENTS + if ( + IS_WINDOWS + and not self.extra_cmake_args + and self._prefix_has_prebuilt_plugins( + install_prefix, include_hip_kernel=True + ) + ): + return () + return SUPERBUILD_HYBRID_COMPONENTS + def resolve_installed_rocm_prefix(self) -> str: if self.rocm_prefix: return self.rocm_prefix @@ -2294,6 +2435,7 @@ def rocke_args(self, toolchain_prefix: str) -> list[str]: "-DHIPKERNELPROVIDER_ENABLE_ROCKE=ON", "-DHIPDNN_ENABLE_KERNEL_INGESTOR=ON", "-DHIPKERNELPROVIDER_KPACK_ALLOW_FETCH=ON", + "-DROCKE_INSTALL_TEST_GPU_REFERENCES=OFF", f"-DPython3_EXECUTABLE={self.py}", # The ingestor headers' std::stable_sort trips libstdc++ 12's # deprecated get_temporary_buffer under the wheel clang's -Werror @@ -2339,38 +2481,88 @@ def _reset_build_dir(self, build_dir: Path, configure_args: list) -> None: build_dir.mkdir(parents=True, exist_ok=True) record.write_text(json.dumps(wanted) + "\n") - def build_superbuild(self, install_prefix: str, toolchain_prefix: str) -> None: + def build_superbuild( + self, + install_prefix: str, + toolchain_prefix: str, + components: Optional[Tuple[str, ...]] = None, + ) -> None: + if components is None: + components = self.select_superbuild_components( + install_prefix, toolchain_prefix + ) + if not components: + print( + f"Using prebuilt hipDNN and provider plugins from {install_prefix}; " + "skipping C++ superbuild." + ) + return + cmake = self.cmake if not shutil.which("ninja"): fail("ninja not found on PATH.") build_dir = ROCM_LIBRARIES_DIR / "build" prefix_path, program_path = self._cmake_paths(install_prefix, toolchain_prefix) - configure_args = [ - "--preset", - "hipdnn-providers-all", - "-GNinja", - f"-DROCM_PATH={toolchain_prefix}", - f"-DCMAKE_PREFIX_PATH={prefix_path}", - f"-DCMAKE_PROGRAM_PATH={program_path}", - f"-DCMAKE_INSTALL_PREFIX={install_prefix}", - "-DROCM_LIBS_ENABLE_COMPONENTS=hipdnn;miopen-provider;" - "hipblaslt-provider;hip-kernel-provider", - *self.hip_arch_args, - "-DHIPDNN_SKIP_TESTS=ON", - "-DHIPDNN_ENABLE_SDPA=ON", - "-DMIOPENPROVIDER_SKIP_TESTS=ON", - "-DHIPKERNELPROVIDER_ENABLE_TESTS=OFF", - "-DENABLE_ASM_SDPA_ENGINE=ON", - *self.rocke_args(toolchain_prefix), - "-DENABLE_CLANG_FORMAT=OFF", - "-DENABLE_CLANG_TIDY=OFF", - # LAST, so a caller's -D overrides a default above rather than - # being silently overridden by it. - *self.extra_cmake_args, - ] + if components == SUPERBUILD_HYBRID_COMPONENTS: + # Configure hip-kernel-provider standalone against the prebuilt + # hipDNN SDK rather than through the rocm-libraries root superbuild: + # the root CMakeLists prepends cmake/modules/ ahead of + # dnn-providers/cmake/, shadowing CheckToolVersion.cmake when + # hipdnn is omitted. + configure_args = [ + "-S", + str(ROCM_LIBRARIES_DIR / "dnn-providers" / "hip-kernel-provider"), + "-B", + str(build_dir), + "-GNinja", + "-DCMAKE_BUILD_TYPE=Release", + f"-DCMAKE_TOOLCHAIN_FILE={ROCM_LIBRARIES_DIR / 'cmake/toolchains/rocm-clang.cmake'}", + f"-DROCM_PATH={toolchain_prefix}", + f"-DCMAKE_PREFIX_PATH={prefix_path}", + f"-DCMAKE_PROGRAM_PATH={program_path}", + f"-DCMAKE_INSTALL_PREFIX={install_prefix}", + *self.hip_arch_args, + "-DHIPKERNELPROVIDER_ENABLE_TESTS=OFF", + "-DENABLE_ASM_SDPA_ENGINE=ON", + *self.rocke_args(toolchain_prefix), + "-DENABLE_CLANG_FORMAT=OFF", + "-DENABLE_CLANG_TIDY=OFF", + # LAST, so a caller's -D overrides a default above rather than + # being silently overridden by it. + *self.extra_cmake_args, + ] + else: + configure_args = [ + "--preset", + "hipdnn-providers-all", + "-GNinja", + f"-DROCM_PATH={toolchain_prefix}", + f"-DCMAKE_PREFIX_PATH={prefix_path}", + f"-DCMAKE_PROGRAM_PATH={program_path}", + f"-DCMAKE_INSTALL_PREFIX={install_prefix}", + f"-DROCM_LIBS_ENABLE_COMPONENTS={';'.join(components)}", + *self.hip_arch_args, + "-DHIPDNN_SKIP_TESTS=ON", + "-DHIPDNN_ENABLE_SDPA=ON", + "-DMIOPENPROVIDER_SKIP_TESTS=ON", + "-DHIPKERNELPROVIDER_ENABLE_TESTS=OFF", + "-DENABLE_ASM_SDPA_ENGINE=ON", + *self.rocke_args(toolchain_prefix), + "-DENABLE_CLANG_FORMAT=OFF", + "-DENABLE_CLANG_TIDY=OFF", + # LAST, so a caller's -D overrides a default above rather than + # being silently overridden by it. + *self.extra_cmake_args, + ] self._reset_build_dir(build_dir, configure_args) - print(f"Building hipDNN and providers to {install_prefix}...") + if components == SUPERBUILD_ALL_COMPONENTS: + print(f"Building hipDNN and providers to {install_prefix}...") + else: + print( + f"Using prebuilt hipDNN, MIOpen and hipBLASLt plugins from " + f"{install_prefix}; building {', '.join(components)}..." + ) run( [cmake, *configure_args], cwd=ROCM_LIBRARIES_DIR, @@ -2460,7 +2652,7 @@ def build_hipdnn(self) -> None: toolchain_prefix = self.toolchain_prefix if self.do_build: self.build_superbuild(install_prefix, toolchain_prefix) - elif not self.prefix_has_hipdnn(install_prefix): + elif not self.prefixes_have_hipdnn(install_prefix, toolchain_prefix): fail( "--reuse-artifacts was passed, but hipDNN CMake configs " f"were not found under {install_prefix}.", @@ -2482,8 +2674,8 @@ def build_hipdnn(self) -> None: self.env["ROCM_PATH"] = install_prefix if not IS_WINDOWS: - # Install prefix first: the ROCm devel wheel ships its own, older - # libhipdnn_backend.so, which must not shadow the one just built. + # Install prefix first so freshly built or wheel runtime libraries + # in install_prefix/lib take precedence over toolchain_prefix/lib. lib_dirs = tuple( str(Path(prefix) / "lib") for prefix in (install_prefix, toolchain_prefix) @@ -2910,6 +3102,8 @@ def main(argv=None) -> int: ) if args.rocm_version and args.torch_mode != "rocm": parser.error("--rocm-version needs --torch-mode rocm") + if args.build_from_source and args.reuse_artifacts: + parser.error("--build-from-source cannot be combined with --reuse-artifacts") setup = Setup(args) try: return setup.run() diff --git a/tests/unit/test_setup_env.py b/tests/unit/test_setup_env.py index fc2d317..7468720 100644 --- a/tests/unit/test_setup_env.py +++ b/tests/unit/test_setup_env.py @@ -2589,3 +2589,229 @@ def test_rocke_install_honours_no_editable( package_dirs = {name: str(rocke / name) for name in ("platform", "library")} assert calls == [tuple(package_dirs.get(a, a) for a in call) for call in expected] + + +# --- hybrid prebuilt hipDNN mode -------------------------------------------- + + +def _populate_prebuilt_hipdnn( + setup_env, + install_prefix: Path, + toolchain_prefix: Path, + *, + windows: bool = False, + include_hip_kernel: bool = True, +) -> None: + for rel in setup_env._PREBUILT_HIPDNN_CMAKE_CONFIGS: + cfg = toolchain_prefix / rel + cfg.parent.mkdir(parents=True, exist_ok=True) + cfg.write_text("") + if not windows: + comgr = toolchain_prefix / "lib" / "libamd_comgr.so.3" + comgr.parent.mkdir(parents=True, exist_ok=True) + comgr.write_text("") + if windows: + files = [ + install_prefix / "bin" / "hipdnn_backend.dll", + install_prefix / "bin" / "hipdnn_plugins" / "engines" / "miopen_plugin.dll", + install_prefix + / "bin" + / "hipdnn_plugins" + / "engines" + / "hipblaslt_plugin.dll", + ] + if include_hip_kernel: + files.append( + install_prefix + / "bin" + / "hipdnn_plugins" + / "engines" + / "hip_kernel_provider.dll" + ) + else: + files = [ + install_prefix / "lib" / "libhipdnn_backend.so", + install_prefix + / "lib" + / "hipdnn_plugins" + / "engines" + / "libmiopen_plugin.so", + install_prefix + / "lib" + / "hipdnn_plugins" + / "engines" + / "libhipblaslt_plugin.so", + ] + if include_hip_kernel: + files.append( + install_prefix + / "lib" + / "hipdnn_plugins" + / "engines" + / "libhip_kernel_provider.so" + ) + for path in files: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("") + + +def test_hybrid_mode_linux_builds_only_hip_kernel_provider( + setup_env, tmp_path, monkeypatch +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix) + monkeypatch.setattr(setup_env, "IS_WINDOWS", False) + monkeypatch.setattr(setup_env, "ROCM_LIBRARIES_DIR", tmp_path / "rl") + monkeypatch.setattr(setup_env, "require_working_cmake", lambda: "cmake") + monkeypatch.setattr(setup_env.shutil, "which", lambda name: name) + commands = [] + monkeypatch.setattr( + setup_env, "run", lambda cmd, **kwargs: commands.append(list(cmd)) + ) + + setup = _setup(setup_env, tmp_path) + monkeypatch.setattr(setup, "_build_env", lambda: {}) + setup.build_superbuild(str(install_prefix), str(toolchain_prefix)) + + assert commands[0][1:3] == [ + "-S", + str(tmp_path / "rl" / "dnn-providers" / "hip-kernel-provider"), + ] + assert "--preset" not in commands[0] + assert len(commands) == 3 # configure, build, install + + +def test_hybrid_mode_windows_skips_superbuild_when_all_plugins_prebuilt( + setup_env, tmp_path, monkeypatch +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix, windows=True) + monkeypatch.setattr(setup_env, "IS_WINDOWS", True) + commands = [] + monkeypatch.setattr( + setup_env, "run", lambda cmd, **kwargs: commands.append(list(cmd)) + ) + + setup = _setup(setup_env, tmp_path) + setup.build_superbuild(str(install_prefix), str(toolchain_prefix)) + + assert commands == [] + + +@pytest.mark.parametrize( + "extra_argv, include_hip_kernel", + [ + ((), False), + (("--cmake-arg", "ENABLE_ASM_SDPA_ENGINE=OFF"), True), + ], +) +def test_hybrid_mode_windows_builds_hip_kernel_provider_when_needed( + setup_env, tmp_path, monkeypatch, extra_argv, include_hip_kernel +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn( + setup_env, + install_prefix, + toolchain_prefix, + windows=True, + include_hip_kernel=include_hip_kernel, + ) + monkeypatch.setattr(setup_env, "IS_WINDOWS", True) + setup = _setup(setup_env, tmp_path, *extra_argv) + + assert setup.select_superbuild_components( + str(install_prefix), str(toolchain_prefix) + ) == ("hip-kernel-provider",) + + +@pytest.mark.parametrize( + "extra_argv", + [ + ("--build-from-source",), + ("--rocm-libraries-ref", "a" * 40), + ], +) +def test_explicit_source_flags_force_full_superbuild( + setup_env, tmp_path, monkeypatch, extra_argv +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix) + monkeypatch.setattr(setup_env, "IS_WINDOWS", False) + setup = _setup(setup_env, tmp_path, *extra_argv) + + assert ( + setup.select_superbuild_components(str(install_prefix), str(toolchain_prefix)) + == setup_env.SUPERBUILD_ALL_COMPONENTS + ) + + +def test_local_rocm_libraries_divergence_forces_full_superbuild( + setup_env, tmp_path, monkeypatch +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix) + monkeypatch.setattr(setup_env, "IS_WINDOWS", False) + setup = _setup(setup_env, tmp_path) + setup._rocm_libraries_matches_pin = False + + assert ( + setup.select_superbuild_components(str(install_prefix), str(toolchain_prefix)) + == setup_env.SUPERBUILD_ALL_COMPONENTS + ) + + +def test_missing_prebuilt_plugin_falls_back_to_full_superbuild( + setup_env, tmp_path, monkeypatch +) -> None: + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix) + ( + install_prefix / "lib" / "hipdnn_plugins" / "engines" / "libmiopen_plugin.so" + ).unlink() + monkeypatch.setattr(setup_env, "IS_WINDOWS", False) + setup = _setup(setup_env, tmp_path) + + assert ( + setup.select_superbuild_components(str(install_prefix), str(toolchain_prefix)) + == setup_env.SUPERBUILD_ALL_COMPONENTS + ) + + +def test_build_from_source_and_reuse_artifacts_rejected(setup_env, tmp_path) -> None: + with pytest.raises(SystemExit) as exc: + setup_env.main( + [ + "--workspace", + str(tmp_path / "ws"), + "--build-from-source", + "--reuse-artifacts", + ] + ) + assert exc.value.code == 2 + + +def test_reuse_artifacts_accepts_hipdnn_configs_in_toolchain_prefix( + setup_env, tmp_path, monkeypatch +) -> None: + """Hybrid mode leaves CMake configs in rocm-sdk-devel (toolchain_prefix).""" + install_prefix = tmp_path / "libs" + toolchain_prefix = tmp_path / "devel" + _populate_prebuilt_hipdnn(setup_env, install_prefix, toolchain_prefix) + monkeypatch.setattr(setup_env, "IS_WINDOWS", False) + setup = _setup(setup_env, tmp_path, "--reuse-artifacts") + monkeypatch.setattr(setup, "select_binding_prefix", lambda: str(install_prefix)) + setup.__dict__["toolchain_prefix"] = str(toolchain_prefix) + monkeypatch.setattr(setup, "write_activate_local", lambda *a, **kw: None) + + setup.build_hipdnn() + + assert setup.install_prefix == str(install_prefix) + assert setup.plugin_engines_dir == ( + install_prefix / "lib" / "hipdnn_plugins" / "engines" + )