Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(rocm): hide integrated GPUs from HIP on Windows before torch initializes it
Alexander Eichhorna25b63f3cecc
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdxindex 08845c6d1f..86bb4bd152 100644--- a/docs/src/content/docs/start-here/system-requirements.mdx+++ b/docs/src/content/docs/start-here/system-requirements.mdx@@ -179,8 +179,11 @@ systems ROCm 10 supports. AMD lists Windows 11; the Invoke team has run it on Wi:::note[Integrated graphics]ROCm lists the Radeon graphics built into Ryzen CPUs as a GPU of its own. When a discrete GPU is- present, Invoke leaves the integrated one out of `generation_devices: auto`; list it in- `generation_devices` to generate on it anyway.+ present, Invoke leaves the integrated one out of `generation_devices: auto`. On Windows it also hides+ it from ROCm at startup (by setting `HIP_VISIBLE_DEVICES`), as long as `device` and+ `generation_devices` are `auto` and no `HIP_VISIBLE_DEVICES` is set: while ROCm can see the+ integrated GPU, Task Manager shows tens of GB of shared GPU memory for Invoke that is not really in+ use. Set `HIP_VISIBLE_DEVICES` yourself to choose the devices.::::::note[Wide-head attention runs on the math kernel]diff --git a/invokeai/app/run_app.py b/invokeai/app/run_app.pyindex ad806d5971..654bfb7af3 100644--- a/invokeai/app/run_app.py+++ b/invokeai/app/run_app.py@@ -69,6 +69,12 @@ def run_app() -> None:logger = InvokeAILogger.get_logger(config=app_config)+ # Before torch is imported anywhere: HIP reads its device list once, when torch initializes it, and an explicit+ # allocator configuration below imports torch. Runs a short child process on Windows ROCm.+ from invokeai.app.util.rocm_integrated_gpu import hide_integrated_gpus_on_rocm_windows++ hide_integrated_gpus_on_rocm_windows(app_config.device, app_config.generation_devices, logger)+# Configure the torch CUDA memory allocator.# NOTE: It is important that this happens before torch is imported.if app_config.pytorch_cuda_alloc_conf:diff --git a/invokeai/app/util/rocm_integrated_gpu.py b/invokeai/app/util/rocm_integrated_gpu.pynew file mode 100644index 0000000000..0607240d4c--- /dev/null+++ b/invokeai/app/util/rocm_integrated_gpu.py@@ -0,0 +1,107 @@+"""Hide integrated GPUs from HIP on Windows ROCm, before torch initializes it.++HIP on Windows enumerates the Radeon graphics of a Ryzen CPU next to a discrete card. Generation leaves it out of+`generation_devices: auto` (see `TorchDevice._auto_generation_devices`), but its mere visibility costs: measured with+an RX 9060 XT and the gfx1036 iGPU of a Ryzen 7900, with torch 2.12+rocm7.14.1 as with 2.13.0+rocm10.0.0 and without+any Invoke code, the process's first HIP context on the discrete card shows 17.9 GiB of shared GPU memory and its first+kernel launch another 17.9 GiB. None of it is RAM or commit charge, but it is the counter Windows reports paging in,+so Task Manager shows 36 GiB of shared GPU memory and Invoke's paging check reads it as memory pushed out of VRAM. Any+kernel launched on the iGPU itself, even `torch.randn`, crashed the process with an access violation.++`HIP_VISIBLE_DEVICES` avoids all of it, but HIP reads it once, when it initializes, and only HIP can tell which device+is integrated. So a short child process asks torch -- reading device properties creates no context, so the child+maps nothing -- and this process sets the variable before importing torch itself.+"""++import json+import logging+import os+import subprocess+import sys+from typing import Optional, Union++from invokeai.app.util.torch_cuda_allocator import _installed_torch_is_rocm++# Every variable HIP narrows its device list by. One already set means someone chose the devices; leave them be.+VISIBILITY_ENV_VARS = ("HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES")++_PROBE = (+ "import json, torch; "+ "print(json.dumps([bool(getattr(torch.cuda.get_device_properties(i), 'is_integrated', False)) "+ "for i in range(torch.cuda.device_count())]))"+)+_PROBE_TIMEOUT_SECONDS = 120+++def probe_integrated_flags() -> Optional[list[bool]]:+ """`is_integrated` of every device HIP enumerates, asked in a child process; None if the child cannot answer."""+ try:+ result = subprocess.run(+ [sys.executable, "-c", _PROBE],+ capture_output=True,+ text=True,+ timeout=_PROBE_TIMEOUT_SECONDS,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if result.returncode != 0:+ return None+ try:+ # torch may print warnings first; the answer is the last line.+ flags = json.loads(result.stdout.strip().splitlines()[-1])+ except (ValueError, IndexError):+ return None+ if not isinstance(flags, list):+ return None+ return [bool(flag) for flag in flags]+++def discrete_device_visibility(flags: list[bool]) -> Optional[str]:+ """The `HIP_VISIBLE_DEVICES` value that hides the integrated GPUs, or None when there is nothing to hide.++ Nothing to hide when no GPU is integrated, and nothing *may* be hidden when every GPU is: an APU on its own is+ what the machine generates on.+ """+ discrete = [str(index) for index, integrated in enumerate(flags) if not integrated]+ if not discrete or len(discrete) == len(flags):+ return None+ return ",".join(discrete)+++def _torch_is_imported() -> bool:+ return "torch" in sys.modules+++def hide_integrated_gpus_on_rocm_windows(+ device: str, generation_devices: Union[str, list[str]], logger: logging.Logger+) -> None:+ """Set `HIP_VISIBLE_DEVICES` to the discrete GPUs when HIP on Windows also enumerates an integrated one.++ Only when nothing chose the devices already: no visibility variable is set, and `device` and `generation_devices`+ are both `auto` -- an explicit `cuda:N` counts in HIP's full enumeration, which hiding a device would renumber.+ Must run before torch is imported.+ """+ if sys.platform != "win32" or any(os.environ.get(var) for var in VISIBILITY_ENV_VARS):+ return+ if device != "auto" or generation_devices != "auto":+ return+ if not _installed_torch_is_rocm():+ return+ if _torch_is_imported():+ logger.warning("ROCm on Windows: torch was imported before integrated GPUs could be hidden from it.")+ return+ flags = probe_integrated_flags()+ if flags is None:+ logger.debug("ROCm on Windows: could not ask HIP which GPUs are integrated; leaving all of them visible.")+ return+ visible = discrete_device_visibility(flags)+ if visible is None:+ return+ hidden = [index for index, integrated in enumerate(flags) if integrated]+ os.environ["HIP_VISIBLE_DEVICES"] = visible+ logger.info(+ f"ROCm on Windows: hiding integrated GPU(s) {hidden} from HIP (HIP_VISIBLE_DEVICES={visible}). While HIP can "+ "see one, Windows reports tens of GB of shared GPU memory for Invoke that is not really in use. Set "+ "HIP_VISIBLE_DEVICES yourself to choose the devices."+ )diff --git a/tests/app/util/test_rocm_integrated_gpu.py b/tests/app/util/test_rocm_integrated_gpu.pynew file mode 100644index 0000000000..b0f1c7c3ee--- /dev/null+++ b/tests/app/util/test_rocm_integrated_gpu.py@@ -0,0 +1,134 @@+"""Hiding integrated GPUs from HIP on Windows ROCm before torch initializes it."""++import logging+import os+import subprocess+from unittest.mock import MagicMock, patch++import pytest++from invokeai.app.util import rocm_integrated_gpu+from invokeai.app.util.rocm_integrated_gpu import (+ VISIBILITY_ENV_VARS,+ discrete_device_visibility,+ hide_integrated_gpus_on_rocm_windows,+ probe_integrated_flags,+)++MODULE = "invokeai.app.util.rocm_integrated_gpu"+++ ("flags", "expected"),+ [+ ([False, True], "0"),+ ([True, False], "1"),+ ([False, True, False], "0,2"),+ ([False, False], None),+ # An APU on its own is what the machine generates on.+ ([True], None),+ ([], None),+ ],+)+def test_discrete_device_visibility(flags, expected):+ assert discrete_device_visibility(flags) == expected+++def _completed(stdout: str, returncode: int = 0) -> subprocess.CompletedProcess:+ return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")+++def test_probe_reads_the_last_line_past_torch_warnings():+ stdout = "W1002 flop_counter.py:29] triton not found\n[false, true]\n"+ with patch(f"{MODULE}.subprocess.run", return_value=_completed(stdout)):+ assert probe_integrated_flags() == [False, True]+++ "outcome",+ [+ _completed("", returncode=1),+ _completed("not json\n"),+ _completed('{"devices": 2}\n'),+ _completed(""),+ subprocess.TimeoutExpired(cmd="python", timeout=120),+ OSError("no interpreter"),+ ],+ ids=["child-failed", "garbage", "not-a-list", "empty", "timeout", "oserror"],+)+def test_probe_answers_none_when_the_child_cannot(outcome):+ kwargs = {"side_effect": outcome} if isinstance(outcome, BaseException) else {"return_value": outcome}+ with patch(f"{MODULE}.subprocess.run", **kwargs):+ assert probe_integrated_flags() is None+++def windows_rocm(monkeypatch: pytest.MonkeyPatch):+ """Windows, a ROCm torch not yet imported, no visibility variable set."""+ for var in VISIBILITY_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setattr(rocm_integrated_gpu.sys, "platform", "win32")+ monkeypatch.setattr(rocm_integrated_gpu, "_installed_torch_is_rocm", lambda: True)+ monkeypatch.setattr(rocm_integrated_gpu, "_torch_is_imported", lambda: False)+ yield monkeypatch+ # hide_integrated_gpus_on_rocm_windows writes os.environ directly.+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising=False)+++def _hide(flags, device="auto", generation_devices="auto"):+ logger = MagicMock(spec=logging.Logger)+ with patch(f"{MODULE}.probe_integrated_flags", return_value=flags) as probe:+ hide_integrated_gpus_on_rocm_windows(device, generation_devices, logger)+ return logger, probe+++def test_the_ryzen_igpu_next_to_a_radeon_is_hidden(windows_rocm):+ """The measured machine: RX 9060 XT at 0, Ryzen iGPU (gfx1036) at 1."""+ logger, _ = _hide([False, True])+ assert os.environ["HIP_VISIBLE_DEVICES"] == "0"+ assert "HIP_VISIBLE_DEVICES=0" in logger.info.call_args.args[0]+++ "flags", [[False], [False, False], [True], None], ids=["one", "two-discrete", "apu", "unknown"]+)+def test_nothing_is_hidden_without_an_igpu_next_to_a_discrete_gpu(windows_rocm, flags):+ _hide(flags)+ assert "HIP_VISIBLE_DEVICES" not in os.environ++[email protected]("var", VISIBILITY_ENV_VARS)+def test_a_visibility_variable_already_set_wins(windows_rocm, var):+ windows_rocm.setenv(var, "1")+ _, probe = _hide([False, True])+ probe.assert_not_called()+ assert os.environ[var] == "1"+++ ("device", "generation_devices"),+ [("cuda:1", "auto"), ("auto", ["cuda:0", "cuda:1"])],+ ids=["legacy-device", "explicit-list"],+)+def test_explicit_device_indices_are_not_renumbered(windows_rocm, device, generation_devices):+ """`cuda:N` counts in HIP's full enumeration; hiding a device would point it at another GPU."""+ _, probe = _hide([False, True], device=device, generation_devices=generation_devices)+ probe.assert_not_called()+++def test_other_platforms_and_builds_are_left_alone(windows_rocm):+ windows_rocm.setattr(rocm_integrated_gpu.sys, "platform", "linux")+ _, probe = _hide([False, True])+ probe.assert_not_called()++ windows_rocm.setattr(rocm_integrated_gpu.sys, "platform", "win32")+ windows_rocm.setattr(rocm_integrated_gpu, "_installed_torch_is_rocm", lambda: False)+ _, probe = _hide([False, True])+ probe.assert_not_called()+++def test_too_late_once_torch_is_imported(windows_rocm):+ windows_rocm.setattr(rocm_integrated_gpu, "_torch_is_imported", lambda: True)+ logger, probe = _hide([False, True])+ probe.assert_not_called()+ logger.warning.assert_called_once()