Skip to content

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.

fix(rocm): hide the Windows iGPU whatever the device settings say, and bound the probe

Alexander Eichhorn5eb216b4abe4
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdx
index 86bb4bd152..cd42839c8c 100644
--- a/docs/src/content/docs/start-here/system-requirements.mdx
+++ b/docs/src/content/docs/start-here/system-requirements.mdx
@@ -180,10 +180,12 @@ 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`. 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.
+ it from ROCm at startup (by setting `HIP_VISIBLE_DEVICES`) unless you set `HIP_VISIBLE_DEVICES`,
+ `CUDA_VISIBLE_DEVICES` or `ROCR_VISIBLE_DEVICES` yourself: 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, and nothing
+ can run on it. Device names such as `cuda:1` in `device`, `generation_devices` and the settings then
+ count the discrete GPUs only, and naming the integrated GPU is refused with an error. 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.py
index 654bfb7af3..02cc434f3c 100644
--- a/invokeai/app/run_app.py
+++ b/invokeai/app/run_app.py
@@ -73,7 +73,7 @@ def run_app() -> None:
# 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)
+ hide_integrated_gpus_on_rocm_windows(logger)
# Configure the torch CUDA memory allocator.
# NOTE: It is important that this happens before torch is imported.
diff --git a/invokeai/app/util/rocm_integrated_gpu.py b/invokeai/app/util/rocm_integrated_gpu.py
index 0607240d4c..5f4dc87131 100644
--- a/invokeai/app/util/rocm_integrated_gpu.py
+++ b/invokeai/app/util/rocm_integrated_gpu.py
@@ -11,50 +11,96 @@ kernel launched on the iGPU itself, even `torch.randn`, crashed the process with
`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.
+
+The iGPU is hidden whatever `device` and `generation_devices` say, so that `cuda:N` means the same GPU everywhere: the
+settings UI lists, validates and saves devices in the numbering torch reports after hiding, and hiding only while both
+are `auto` would renumber them on the next start. No setting can usefully name the iGPU anyway: no kernel runs on it.
"""
import json
import logging
import os
+import queue
import subprocess
import sys
-from typing import Optional, Union
+import threading
+from typing import Optional
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")
+# The child prints its answer and leaves without Python's shutdown. HIP's own teardown can still hang on Windows while
+# its DLLs unload, so the probe takes the answer as soon as the line arrives and ends the child itself.
_PROBE = (
- "import json, torch; "
+ "import json, os, sys, torch; "
"print(json.dumps([bool(getattr(torch.cuda.get_device_properties(i), 'is_integrated', False)) "
- "for i in range(torch.cuda.device_count())]))"
+ "for i in range(torch.cuda.device_count())])); "
+ "sys.stdout.flush(); os._exit(0)"
)
-_PROBE_TIMEOUT_SECONDS = 120
+# Measured 1.6-2.4 s on an RX 9060 XT with a warm torch import; the margin is for a cold import of torch and its ROCm
+# libraries after a reboot. A shorter limit would buy little: a HIP that hangs while enumerating devices (seen after a
+# driver fault) hangs this process too, as soon as it imports torch.
+_PROBE_TIMEOUT_SECONDS = 60
+# A child stuck in a driver call cannot be ended at all (seen after a driver fault); it is left behind after this.
+_EXIT_WAIT_SECONDS = 5
+
+
+class ProbeFailed(Exception):
+ """The child process could not say which GPUs are integrated."""
-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."""
+def probe_integrated_flags() -> list[bool]:
+ """`is_integrated` of every device HIP enumerates, asked in a child process. Raises `ProbeFailed` with the reason."""
try:
- result = subprocess.run(
+ child = subprocess.Popen(
[sys.executable, "-c", _PROBE],
- capture_output=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
text=True,
- timeout=_PROBE_TIMEOUT_SECONDS,
+ errors="replace",
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
- except (OSError, subprocess.SubprocessError):
- return None
- if result.returncode != 0:
- return None
+ except (OSError, subprocess.SubprocessError) as e:
+ raise ProbeFailed(f"could not start it ({e})") from e
+ answers: "queue.Queue[Optional[list[bool]]]" = queue.Queue()
+ threading.Thread(target=_read_answer, args=(child, answers), daemon=True).start()
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]
+ flags = answers.get(timeout=_PROBE_TIMEOUT_SECONDS)
+ if flags is None:
+ # The output ended without an answer; let the child finish so its exit code can say why.
+ _wait_for_exit(child)
+ except queue.Empty:
+ raise ProbeFailed(f"no answer within {_PROBE_TIMEOUT_SECONDS} s") from None
+ finally:
+ if child.poll() is None:
+ child.kill()
+ _wait_for_exit(child)
+ if flags is None:
+ raise ProbeFailed(f"it exited with code {child.returncode}" if child.returncode else "it gave no answer")
+ return flags
+
+
+def _read_answer(child: subprocess.Popen, answers: "queue.Queue[Optional[list[bool]]]") -> None:
+ """Put the first JSON list the child prints, skipping anything else; None once its output ends without one."""
+ assert child.stdout is not None
+ for line in child.stdout:
+ try:
+ flags = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(flags, list):
+ answers.put([bool(flag) for flag in flags])
+ return
+ answers.put(None)
+
+
+def _wait_for_exit(child: subprocess.Popen) -> None:
+ try:
+ child.wait(timeout=_EXIT_WAIT_SECONDS)
+ except subprocess.TimeoutExpired:
+ pass
def discrete_device_visibility(flags: list[bool]) -> Optional[str]:
@@ -73,27 +119,26 @@ 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:
+def hide_integrated_gpus_on_rocm_windows(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.
+ Only when no visibility variable is set: one that is chose the devices already. 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.")
+ try:
+ flags = probe_integrated_flags()
+ except ProbeFailed as e:
+ logger.warning(
+ f"ROCm on Windows: could not ask HIP which GPUs are integrated ({e}); leaving all of them visible. An "
+ "integrated GPU can then make Windows report tens of GB of shared GPU memory, and generating on it fails. "
+ "Set HIP_VISIBLE_DEVICES to the discrete GPUs to choose them yourself."
+ )
return
visible = discrete_device_visibility(flags)
if visible is None:
@@ -101,7 +146,7 @@ def hide_integrated_gpus_on_rocm_windows(
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."
+ f"ROCm on Windows: hiding integrated GPU(s) {hidden} from HIP (HIP_VISIBLE_DEVICES={visible}), so `cuda:N` "
+ "counts the discrete GPUs only. While HIP can see an integrated GPU, 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/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py
index d8edb6ada5..4024924603 100644
--- a/invokeai/backend/util/devices.py
+++ b/invokeai/backend/util/devices.py
@@ -1,3 +1,4 @@
+import sys
import threading
from collections import Counter, defaultdict
from functools import wraps
@@ -28,6 +29,17 @@ def _xpu_is_available() -> bool:
return hasattr(torch, "xpu") and torch.xpu.is_available()
+def _unusable_rocm_windows_igpu(device: torch.device) -> bool:
+ """Whether `device` is an integrated GPU next to a discrete one under ROCm on Windows.
+
+ Any kernel launched there crashed the process with an access violation (measured: Ryzen gfx1036 beside an RX 9060
+ XT), so naming it is refused with a clear error. An APU on its own is left alone: it is all the machine has.
+ """
+ if sys.platform != "win32" or torch.version.hip is None or device_is_integrated(device) is not True:
+ return False
+ return any(device_is_integrated(torch.device("cuda", i)) is False for i in range(torch.cuda.device_count()))
+
+
def device_is_integrated(device: torch.device) -> Optional[bool]:
"""Return True/False if ``device`` is an integrated GPU, or None if it cannot be determined.
@@ -304,7 +316,8 @@ class TorchDevice:
Two deliberate limits: a device whose type cannot be determined is kept (the probe returns
None, and narrowing on a guess is worse than the status quo), and a machine whose only GPU
is integrated keeps it -- otherwise there would be nothing to generate on. An explicit
- `generation_devices` list is unaffected, so an iGPU can still be opted into.
+ `generation_devices` list is unaffected, so an iGPU can still be opted into -- except under
+ ROCm on Windows, where no kernel runs on one (see `_unusable_rocm_windows_igpu`).
"""
integrated: list[torch.device] = []
remaining: list[torch.device] = []
@@ -357,6 +370,13 @@ class TorchDevice:
f"generation_devices requested '{device_str}', but only {torch.cuda.device_count()} "
f"CUDA device(s) are available (valid indices 0-{torch.cuda.device_count() - 1})."
)
+ if _unusable_rocm_windows_igpu(device):
+ raise ValueError(
+ f"generation_devices requested '{device_str}', which is an integrated GPU; under ROCm on "
+ "Windows nothing can run on it. Name a discrete GPU or use 'auto'. Invoke hides the integrated "
+ "GPU at startup, so device numbers count the discrete GPUs only, unless that failed (see the "
+ "startup log) or HIP_VISIBLE_DEVICES was set to include it."
+ )
elif device.type == "xpu":
if not _xpu_is_available():
raise ValueError(f"generation_devices requested '{device_str}', but no XPU device is available.")
diff --git a/tests/app/util/test_rocm_integrated_gpu.py b/tests/app/util/test_rocm_integrated_gpu.py
index b0f1c7c3ee..7a28e47aa3 100644
--- a/tests/app/util/test_rocm_integrated_gpu.py
+++ b/tests/app/util/test_rocm_integrated_gpu.py
@@ -2,7 +2,7 @@
import logging
import os
-import subprocess
+import time
from unittest.mock import MagicMock, patch
import pytest
@@ -10,6 +10,7 @@ import pytest
from invokeai.app.util import rocm_integrated_gpu
from invokeai.app.util.rocm_integrated_gpu import (
VISIBILITY_ENV_VARS,
+ ProbeFailed,
discrete_device_visibility,
hide_integrated_gpus_on_rocm_windows,
probe_integrated_flags,
@@ -34,32 +35,54 @@ 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 _child_runs(monkeypatch: pytest.MonkeyPatch, code: str, timeout: float = 60) -> None:
+ """Make the probe start a real child running `code` instead of asking torch."""
+ monkeypatch.setattr(rocm_integrated_gpu, "_PROBE", code)
+ monkeypatch.setattr(rocm_integrated_gpu, "_PROBE_TIMEOUT_SECONDS", timeout)
-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]
+def test_probe_skips_what_the_child_prints_before_its_answer(monkeypatch: pytest.MonkeyPatch):
+ _child_runs(monkeypatch, "print('W1002 flop_counter.py:29] triton not found'); print('1'); print('[false, true]')")
+ assert probe_integrated_flags() == [False, True]
+
+
+def test_an_answer_followed_by_a_hang_on_exit_returns_at_once(monkeypatch: pytest.MonkeyPatch):
+ """HIP's teardown can hang after the answer (seen on Windows); startup must not wait out the timeout for it."""
+ _child_runs(monkeypatch, "import sys, time; print('[false, true]'); sys.stdout.flush(); time.sleep(600)")
+ started = time.monotonic()
+ assert probe_integrated_flags() == [False, True]
+ assert time.monotonic() - started < 30
@pytest.mark.parametrize(
- "outcome",
+ ("code", "timeout", "reason"),
[
- _completed("", returncode=1),
- _completed("not json\n"),
- _completed('{"devices": 2}\n'),
- _completed(""),
- subprocess.TimeoutExpired(cmd="python", timeout=120),
- OSError("no interpreter"),
+ ("import sys; sys.exit(3)", 60, "exited with code 3"),
+ ("print('not json')", 60, "gave no answer"),
+ ("print('{\"devices\": 2}')", 60, "gave no answer"),
+ ("import time; time.sleep(600)", 1, "no answer within 1 s"),
],
- ids=["child-failed", "garbage", "not-a-list", "empty", "timeout", "oserror"],
+ ids=["child-failed", "garbage", "not-a-list", "hangs-before-answering"],
)
-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 test_probe_says_why_the_child_could_not_answer(monkeypatch: pytest.MonkeyPatch, code, timeout, reason):
+ _child_runs(monkeypatch, code, timeout)
+ with pytest.raises(ProbeFailed, match=reason):
+ probe_integrated_flags()
+
+
+def test_probe_says_when_the_child_cannot_start(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(rocm_integrated_gpu.sys, "executable", "Z:/no/such/python.exe")
+ with pytest.raises(ProbeFailed, match="could not start it"):
+ probe_integrated_flags()
+
+
+def test_the_real_probe_answers_and_exits(monkeypatch: pytest.MonkeyPatch):
+ """The probe code itself, in a real child: it prints a JSON list and exits (without a ROCm GPU, maybe [])."""
+ # A cold torch import on a busy CI runner may take longer than startup should wait; this tests the code, not speed.
+ monkeypatch.setattr(rocm_integrated_gpu, "_PROBE_TIMEOUT_SECONDS", 300)
+ flags = probe_integrated_flags()
+ assert isinstance(flags, list)
+ assert all(isinstance(flag, bool) for flag in flags)
@pytest.fixture
@@ -75,10 +98,12 @@ def windows_rocm(monkeypatch: pytest.MonkeyPatch):
monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising=False)
-def _hide(flags, device="auto", generation_devices="auto"):
+def _hide(flags):
+ """Run the startup step with the probe answering `flags`, or failing when `flags` is an exception."""
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)
+ kwargs = {"side_effect": flags} if isinstance(flags, BaseException) else {"return_value": flags}
+ with patch(f"{MODULE}.probe_integrated_flags", **kwargs) as probe:
+ hide_integrated_gpus_on_rocm_windows(logger)
return logger, probe
@@ -89,14 +114,19 @@ def test_the_ryzen_igpu_next_to_a_radeon_is_hidden(windows_rocm):
assert "HIP_VISIBLE_DEVICES=0" in logger.info.call_args.args[0]
- "flags", [[False], [False, False], [True], None], ids=["one", "two-discrete", "apu", "unknown"]
-)
[email protected]("flags", [[False], [False, False], [True]], ids=["one", "two-discrete", "apu"])
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
+def test_a_failed_probe_leaves_every_gpu_visible_and_says_so(windows_rocm):
+ logger, _ = _hide(ProbeFailed("no answer within 60 s"))
+ assert "HIP_VISIBLE_DEVICES" not in os.environ
+ logger.warning.assert_called_once()
+ assert "no answer within 60 s" in logger.warning.call_args.args[0]
+
+
@pytest.mark.parametrize("var", VISIBILITY_ENV_VARS)
def test_a_visibility_variable_already_set_wins(windows_rocm, var):
windows_rocm.setenv(var, "1")
@@ -105,17 +135,6 @@ def test_a_visibility_variable_already_set_wins(windows_rocm, var):
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])
diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.py
index 651aa586a2..d40a57bb2f 100644
--- a/tests/backend/util/test_devices.py
+++ b/tests/backend/util/test_devices.py
@@ -1011,3 +1011,34 @@ def test_a_forced_empty_cache_runs_past_a_busy_peer_and_its_wrapper(monkeypatch)
assert calls == []
assert TorchDevice.empty_cache(force=True) is True
assert calls == ["torch"]
+
+
+def _explicit_cuda_devices(integrated_map: dict[int, bool | None], requested: list[str], platform: str, hip):
+ with (
+ patch("invokeai.backend.util.devices.sys.platform", platform),
+ patch("invokeai.backend.util.devices.torch.version.hip", hip),
+ patch("invokeai.backend.util.devices.torch.cuda.is_available", return_value=True),
+ patch("invokeai.backend.util.devices.torch.cuda.device_count", return_value=len(integrated_map)),
+ patch("invokeai.backend.util.devices.torch.cuda.get_device_properties", _cuda_properties(integrated_map)),
+ ):
+ return TorchDevice.get_generation_devices(requested)
+
+
+def test_naming_the_igpu_beside_a_radeon_on_windows_rocm_is_refused():
+ """Every kernel on it crashed the process (Ryzen gfx1036 beside an RX 9060 XT); refuse it with a reason instead."""
+ with pytest.raises(ValueError, match="integrated GPU"):
+ _explicit_cuda_devices({0: True, 1: False}, ["cuda:0"], "win32", "7.15.26333")
+
+
+ ("integrated_map", "requested", "platform", "hip"),
+ [
+ ({0: True, 1: False}, ["cuda:1"], "win32", "7.15.26333"), # the discrete card
+ ({0: True}, ["cuda:0"], "win32", "7.15.26333"), # an APU on its own
+ ({0: True, 1: False}, ["cuda:0"], "linux", "7.15.26333"), # ROCm on Linux
+ ({0: True, 1: False}, ["cuda:0"], "win32", None), # CUDA
+ ],
+ ids=["discrete", "apu-alone", "linux-rocm", "cuda"],
+)
+def test_an_explicit_device_is_kept_unless_it_is_that_igpu(integrated_map, requested, platform, hip):
+ assert _explicit_cuda_devices(integrated_map, requested, platform, hip) == [torch.device(requested[0])]