Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Reserve host RAM for AMD unified-memory APUs on the ROCm probe (#8131)

Daniel Han6e0beb238ce3
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 42ecf2dd66f..52c6ef79d00 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -4496,10 +4496,7 @@ class LlamaCppBackend:
# must agree, else an inherited ROCR mask reads back as "no mask",
# ordinal 0 is labelled physical 0, and the child's new ROCR pin
# re-exposes the GPU the inherited mask was hiding.
- is_rocm = (
- getattr(torch.version, "hip", None) is not None
- or "rocm" in getattr(torch, "__version__", "").lower()
- )
+ is_rocm = LlamaCppBackend._torch_is_rocm(torch)
except Exception:
is_rocm = False
if is_rocm:
@@ -4752,44 +4749,70 @@ class LlamaCppBackend:
return requested > n_layers
@staticmethod
- def _amd_apu_wants_unified_memory(gpu_indices = None) -> bool:
- """True only for AMD unified-memory APUs (gfx1150/gfx1151/gfx1152), where
- GGML_CUDA_ENABLE_UNIFIED_MEMORY lets llama.cpp use shared system RAM (it
- hurts discrete GPUs). gpu_indices (PHYSICAL ids) scopes the check to the
- selected GPUs, so a dGPU on a mixed host is not treated as unified-memory;
- None means every visible GPU."""
+ def _torch_is_rocm(torch) -> bool:
+ """Whether this torch is a ROCm build. AMD SDK wheels leave
+ ``version.hip`` unset and only encode "rocm" in ``__version__``."""
+ return (
+ getattr(torch.version, "hip", None) is not None
+ or "rocm" in getattr(torch, "__version__", "").lower()
+ )
+
+ @staticmethod
+ def _rocm_unified_memory_gpu_ids() -> set[int]:
+ """PHYSICAL ids of visible ROCm GPUs whose "VRAM" is shared system RAM.
+
+ Delegates to the training worker's classifier so both paths agree on what
+ an APU is: it reads the driver's own ``is_integrated`` first, then the
+ arch-name spellings, then the Radeon name table, because AMD SDK wheels
+ may populate none of the arch attributes. Empty off ROCm and on error, so
+ every caller keeps its discrete-GPU default.
+ """
try:
import torch
- if getattr(torch.version, "hip", None) is None:
- return False
+ if not LlamaCppBackend._torch_is_rocm(torch):
+ return set()
if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
- return False
+ return set()
+ from core.training.worker import _rocm_classify_unified_memory
+
# Map visible ordinal -> physical id via the active ROCm mask (HIP,
# then ROCR, then CUDA), mirroring _get_gpu_memory's ROCm branch.
physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
- arch_by_id: dict[int, str] = {}
+ unified: set[int] = set()
for ordinal in range(torch.cuda.device_count()):
try:
- _arch = (
- getattr(torch.cuda.get_device_properties(ordinal), "gcnArchName", "") or ""
+ _arch, is_unified = _rocm_classify_unified_memory(
+ torch.cuda.get_device_properties(ordinal)
)
except Exception:
continue
- pid = (
+ if not is_unified:
+ continue
+ unified.add(
physical_ids[ordinal]
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal
)
- arch_by_id[pid] = _arch.split(":")[0].strip().lower()
- for _i in list(gpu_indices) if gpu_indices is not None else list(arch_by_id):
- # gfx1152 is Krackan Point (Radeon 860M/840M), the third RDNA 3.5
- # APU: same shared GPU/system-RAM pool as Strix Point/Halo.
- if arch_by_id.get(_i) in {"gfx1150", "gfx1151", "gfx1152"}:
- return True
+ return unified
+ except Exception:
+ return set()
+
+ @staticmethod
+ def _amd_apu_wants_unified_memory(gpu_indices = None) -> bool:
+ """True only for AMD unified-memory APUs, where GGML_CUDA_ENABLE_UNIFIED_MEMORY
+ lets llama.cpp use shared system RAM (it hurts discrete GPUs). gpu_indices
+ (PHYSICAL ids) scopes the check, so a dGPU on a mixed host is not treated as
+ unified-memory; None means every visible GPU."""
+ # Guarded like the rest of this family: a bad gpu_indices (not iterable,
+ # unhashable members) answers False rather than failing the load.
+ try:
+ unified = LlamaCppBackend._rocm_unified_memory_gpu_ids()
+ if gpu_indices is None:
+ return bool(unified)
+ return any(_i in unified for _i in gpu_indices)
except Exception:
return False
- return False
# Datacenter / professional NVIDIA parts that benefit from the llama.cpp
# FP32-accum / P2P tunings. Whole-word (\b) so short markers don't match
@@ -5003,7 +5026,9 @@ class LlamaCppBackend:
are ggml's compact Vulkan ordinals (the space the pin selects via
``--device Vulkan<i>``). It reports ``total`` for discrete cards and 0
for an iGPU (shared RAM) so the fit falls back to free*frac there.
- Otherwise nvidia-smi / torch cover NVIDIA + AMD ROCm.
+ Otherwise nvidia-smi / torch cover NVIDIA + AMD ROCm. The torch branch
+ gives an AMD unified-memory APU the same treatment by arch name, since
+ ROCm reports no iGPU flag of its own.
Returns (gpu_index, free_mib, total_mib) sorted by index; empty if no
supported GPU is reachable.
@@ -5078,6 +5103,9 @@ class LlamaCppBackend:
# Empty mask (CVD="") yields an empty list -> no GPUs, consistent
# with the nvidia-smi path.
physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
+ # Shared-pool APU: same as the Vulkan iGPU path. Hold back the host
+ # margin, and report total 0 since that "total" is system RAM.
+ unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids()
gpus = []
for ordinal in range(torch.cuda.device_count()):
free_bytes, total_bytes = torch.cuda.mem_get_info(ordinal)
@@ -5086,7 +5114,23 @@ class LlamaCppBackend:
if physical_ids is not None and ordinal < len(physical_ids)
else ordinal
)
- gpus.append((idx, free_bytes // (1024 * 1024), total_bytes // (1024 * 1024)))
+ shared = idx in unified_ids
+ raw_mib = free_bytes // (1024 * 1024)
+ if shared:
+ # ROCm's free is unreliable on a shared pool (Windows HIP
+ # reports free==total, #7072), and system RAM is the real
+ # ceiling there, so cap before taking the reserve.
+ avail = LlamaCppBackend._available_system_memory_mib()
+ if avail is not None:
+ raw_mib = min(raw_mib, avail)
+ free_mib = _apply_igpu_host_reserve_mib(raw_mib, shared)
+ if free_mib < raw_mib:
+ logger.info(
+ f"ROCm device {idx} is a unified-memory APU sharing system "
+ f"RAM; reserving {raw_mib - free_mib}MiB host headroom "
+ f"({raw_mib}->{free_mib}MiB usable)"
+ )
+ gpus.append((idx, free_mib, 0 if shared else total_bytes // (1024 * 1024)))
# Match the nvidia-smi path's docstring guarantee of sorted-by-id.
return sorted(gpus, key = lambda g: g[0])
except Exception as e:
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 1cca54f3d79..b0057c28316 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -1489,7 +1489,8 @@ def _rocm_classify_unified_memory(props: Any) -> tuple[str, bool]:
if gcn_arch:
# gfx1152 is Krackan Point: same shared GPU/system-RAM pool as gfx1150/gfx1151.
- return gcn_arch, gcn_arch in {"gfx1150", "gfx1151", "gfx1152"}
+ # Case-folded: the attribute is lowercase in practice but is not guaranteed.
+ return gcn_arch, gcn_arch.lower() in {"gfx1150", "gfx1151", "gfx1152"}
# Arch attrs absent -- fall back to device-name matching. Only reached under _hw.IS_ROCM,
# so the NVIDIA GeForce 840M cannot collide with the Krackan markers.
diff --git a/studio/backend/tests/test_amd_apu_unified_memory.py b/studio/backend/tests/test_amd_apu_unified_memory.py
index be85fd56d13..b1664a0d120 100644
--- a/studio/backend/tests/test_amd_apu_unified_memory.py
+++ b/studio/backend/tests/test_amd_apu_unified_memory.py
@@ -117,3 +117,225 @@ class TestApuRamShortfall:
def test_available_system_memory_is_int_or_none(self):
v = LlamaCppBackend._available_system_memory_mib()
assert v is None or (isinstance(v, int) and v > 0)
+
+
+# The local B200's real profile, so the spoofed APU is sized like a machine we
+# actually have rather than an invented one. A large shared pool is exactly where
+# the missing host reserve mattered: 3% of 179 GiB is 5.4 GiB, but the reserve is
+# an absolute 1 GiB off free, and the "total" must not become a VRAM budget.
+_B200_TOTAL_MIB = 183359
+_B200_FREE_MIB = 181928
+_MIB = 1024 * 1024
+
+
+def _fake_torch_with_memory(
+ hip,
+ archs,
+ free_mib,
+ total_mib,
+ *,
+ cuda_ok = True,
+):
+ """_fake_torch plus mem_get_info, which the memory probe needs."""
+ t = _fake_torch(hip, archs, cuda_ok = cuda_ok)
+ t.cuda.mem_get_info = lambda i: (free_mib * _MIB, total_mib * _MIB)
+ return t
+
+
+def _probe(
+ monkeypatch,
+ hip,
+ archs,
+ free_mib = _B200_FREE_MIB,
+ total_mib = _B200_TOTAL_MIB,
+):
+ for _m in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_m, raising = False)
+ monkeypatch.setitem(
+ sys.modules, "torch", _fake_torch_with_memory(hip, archs, free_mib, total_mib)
+ )
+ # Force the torch branch: no Vulkan build, and nvidia-smi must not answer.
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b: False))
+ monkeypatch.setattr(LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "x"))
+ # Pin host availability: the shared path caps by it, so a runner with less RAM
+ # than the spoofed profile would otherwise change every expectation below.
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 1 << 30)
+ )
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError("no nvidia-smi")),
+ )
+ return LlamaCppBackend._get_gpu_memory()
+
+
+class TestTheRocmProbeReservesHostRamOnAnApu:
+ """ROCm reports no iGPU flag, so before this an APU was sized as a discrete
+ card: no host margin, and an absolute reserve taken off what is really
+ system RAM. The Vulkan probe already did both; this matches it."""
+
+ def test_an_apu_loses_the_host_reserve_and_reports_no_total(self, monkeypatch):
+ assert _probe(monkeypatch, "6.2.0", ["gfx1151:xnack-"]) == [(0, _B200_FREE_MIB - 1024, 0)]
+
+ def test_a_discrete_amd_card_is_untouched(self, monkeypatch):
+ assert _probe(monkeypatch, "6.2.0", ["gfx1100"]) == [(0, _B200_FREE_MIB, _B200_TOTAL_MIB)]
+
+ def test_nvidia_through_the_torch_fallback_is_untouched(self, monkeypatch):
+ """The real local GPU: no HIP, so nothing here may apply."""
+ assert _probe(monkeypatch, None, ["sm_100"]) == [(0, _B200_FREE_MIB, _B200_TOTAL_MIB)]
+
+ def test_a_mixed_host_only_reserves_on_the_apu(self, monkeypatch):
+ assert _probe(monkeypatch, "6.2.0", ["gfx1100", "gfx1151"]) == [
+ (0, _B200_FREE_MIB, _B200_TOTAL_MIB),
+ (1, _B200_FREE_MIB - 1024, 0),
+ ]
+
+ def test_the_reserve_cannot_go_negative(self, monkeypatch):
+ assert _probe(monkeypatch, "6.2.0", ["gfx1151"], free_mib = 512, total_mib = 512) == [(0, 0, 0)]
+
+ @pytest.mark.parametrize("arch", ["gfx1150", "gfx1151", "gfx1152"])
+ def test_every_unified_arch_is_covered(self, monkeypatch, arch):
+ assert _probe(monkeypatch, "6.2.0", [arch])[0][1] == _B200_FREE_MIB - 1024
+
+ def test_the_probe_and_the_mlock_gate_agree(self, monkeypatch):
+ """Both read one arch map, so they cannot disagree about a device."""
+ for arch, shared in (("gfx1151", True), ("gfx1100", False)):
+ rows = _probe(monkeypatch, "6.2.0", [arch])
+ assert (rows[0][2] == 0) is shared
+ assert LlamaCppBackend._amd_apu_wants_unified_memory([0]) is shared
+
+
+class TestTheGateStillFailsOpen:
+ """Every helper in this family answers False rather than raising: they are
+ consulted on the load path, so a bad argument must skip the optimisation,
+ not fail the load."""
+
+ @pytest.mark.parametrize("gpu_indices", [5, [[0]], "0", [None], object()])
+ def test_a_bad_gpu_indices_answers_false(self, monkeypatch, gpu_indices):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch("6.2.0", ["gfx1151"]))
+ assert LlamaCppBackend._amd_apu_wants_unified_memory(gpu_indices) is False
+
+ def test_a_good_one_still_works(self, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch("6.2.0", ["gfx1151"]))
+ assert LlamaCppBackend._amd_apu_wants_unified_memory([0]) is True
+
+
+class TestAmdSdkWheelsCountAsRocm:
+ """AMD SDK / Radeon wheels leave torch.version.hip unset and only encode
+ "rocm" in __version__, which _resolve_visible_physical_ids already handles.
+ The arch map must use the same predicate or an APU goes unrecognised there."""
+
+ @staticmethod
+ def _torch(
+ hip,
+ version,
+ archs = ("gfx1151",),
+ ):
+ t = _fake_torch(hip, list(archs))
+ t.__version__ = version
+ return t
+
+ @pytest.mark.parametrize(
+ ("hip", "version", "expected"),
+ [
+ ("6.2.0", "2.5.0+rocm6.2", True),
+ (None, "2.11.0+rocm7.13", True), # AMD SDK wheel
+ (None, "2.5.0+ROCm7.0", True), # case-insensitive
+ (None, "2.5.0+cu124", False),
+ (None, "2.5.0", False),
+ ],
+ )
+ def test_the_arch_map_matches_the_id_resolver(self, monkeypatch, hip, version, expected):
+ monkeypatch.setitem(sys.modules, "torch", self._torch(hip, version))
+ assert bool(LlamaCppBackend._rocm_unified_memory_gpu_ids()) is expected
+ assert LlamaCppBackend._amd_apu_wants_unified_memory([0]) is expected
+
+
+class TestTheApuBudgetIsCappedByHostRam:
+ """Windows HIP without the SDK reports free==total (#7072), so the ROCm free
+ figure cannot be trusted on a shared pool. System RAM is the real ceiling."""
+
+ @staticmethod
+ def _probe(monkeypatch, arch, free_mib, avail_mib):
+ t = _fake_torch("6.2.0", [arch])
+ t.cuda.mem_get_info = lambda i: (free_mib * 1024 * 1024, free_mib * 1024 * 1024)
+ monkeypatch.setitem(sys.modules, "torch", t)
+ for _m in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(_m, raising = False)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: avail_mib)
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b: False))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "llama-server")
+ )
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError("no nvidia-smi")),
+ )
+ return LlamaCppBackend._get_gpu_memory()
+
+ def test_the_sentinel_is_capped(self, monkeypatch):
+ assert self._probe(monkeypatch, "gfx1151", 100_000, 12_000) == [(0, 12_000 - 1024, 0)]
+
+ def test_an_honest_smaller_free_wins(self, monkeypatch):
+ """The cap is a ceiling, never a floor."""
+ assert self._probe(monkeypatch, "gfx1151", 8_000, 64_000) == [(0, 8_000 - 1024, 0)]
+
+ def test_unreadable_system_ram_keeps_the_old_answer(self, monkeypatch):
+ assert self._probe(monkeypatch, "gfx1151", 100_000, None) == [(0, 100_000 - 1024, 0)]
+
+ def test_a_discrete_card_is_never_capped(self, monkeypatch):
+ assert self._probe(monkeypatch, "gfx1100", 100_000, 12_000) == [(0, 100_000, 100_000)]
+
+
+class TestRadeonWheelsWithoutAnArchName:
+ """AMD SDK / Radeon wheels may populate none of the arch attributes. The
+ training worker's classifier already handles that (is_integrated, then the
+ arch spellings, then the Radeon name table); this path shares it so the two
+ cannot disagree about a device."""
+
+ @staticmethod
+ def _torch(**props):
+ t = _fake_torch("6.2.0", ["unused"])
+ t.cuda.get_device_properties = lambda i: types.SimpleNamespace(**props)
+ return t
+
+ @pytest.mark.parametrize(
+ ("props", "expected"),
+ [
+ ({"gcnArchName": "gfx1151"}, True),
+ ({"gcn_arch_name": "gfx1150"}, True), # variant spelling
+ ({"name": "AMD Radeon 8060S Graphics"}, True), # Strix Halo by name
+ ({"name": "AMD Radeon 860M"}, True), # Krackan by name
+ ({"is_integrated": True, "name": "AMD Radeon Graphics"}, True),
+ ({"gcnArchName": "gfx1100"}, False),
+ ({"name": "AMD Radeon RX 7900 XTX"}, False),
+ ],
+ )
+ def test_the_probe_uses_every_fallback(self, monkeypatch, props, expected):
+ monkeypatch.setitem(sys.modules, "torch", self._torch(**props))
+ assert LlamaCppBackend._amd_apu_wants_unified_memory([0]) is expected
+ assert bool(LlamaCppBackend._rocm_unified_memory_gpu_ids()) is expected
+
+
+class TestTheProbeTestsDoNotDependOnHostRam:
+ """The shared path caps by available system RAM, so the spoofed profile must
+ pin it or every expectation moves with the runner's memory."""
+
+ def test_the_helper_pins_availability(self, monkeypatch):
+ """_probe must survive a runner smaller than the spoofed free figure."""
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 14_000)
+ )
+ assert _probe(monkeypatch, "6.2.0", ["gfx1151"]) == [(0, _B200_FREE_MIB - 1024, 0)]
+
+ def test_without_the_pin_the_cap_really_would_bite(self, monkeypatch):
+ """Proves the pin is load-bearing rather than decorative."""
+ rows = _probe(monkeypatch, "6.2.0", ["gfx1151"])
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 14_000)
+ )
+ capped = LlamaCppBackend._get_gpu_memory()
+ assert rows == [(0, _B200_FREE_MIB - 1024, 0)]
+ assert capped == [(0, 14_000 - 1024, 0)]