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.

Studio: set `GGML_CUDA_ENABLE_UNIFIED_MEMORY` only where it gains memory (#9884)

oobabooga16d596d53cb0
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 5434b4eddc9..d13dd696ebb 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -7999,6 +7999,77 @@ class LlamaCppBackend:
except Exception:
return set()
+ @staticmethod
+ def _rocm_selected_pool_mib(gpu_indices = None) -> Optional[int]:
+ """Return selected ROCm APUs' combined carve-out in MiB.
+
+ Return ``None`` unless every requested device is present, readable, and a
+ unified-memory APU. The ggml setting is process-wide, so mixed selections
+ fail closed.
+ """
+ try:
+ import torch
+
+ if not LlamaCppBackend._torch_is_rocm(torch):
+ return None
+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
+ return None
+ from core.training.worker import _rocm_classify_unified_memory
+
+ wanted = None if gpu_indices is None else set(gpu_indices)
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
+ total_mib = 0
+ seen: set[int] = set()
+ for ordinal in range(torch.cuda.device_count()):
+ pid = (
+ physical_ids[ordinal]
+ if physical_ids is not None and ordinal < len(physical_ids)
+ else ordinal
+ )
+ if wanted is not None and pid not in wanted:
+ continue
+ try:
+ props = torch.cuda.get_device_properties(ordinal)
+ _arch, is_unified = _rocm_classify_unified_memory(props)
+ except Exception:
+ return None
+ if not is_unified:
+ return None
+ total = int(getattr(props, "total_memory", 0) or 0)
+ if total <= 0:
+ return None
+ total_mib += total // (1024 * 1024)
+ seen.add(pid)
+ if not seen or (wanted is not None and seen != wanted):
+ return None
+ return total_mib
+ except Exception:
+ return None
+
+ @staticmethod
+ def _unified_memory_would_help(gpu_indices = None) -> bool:
+ """Whether managed allocation is the larger pool for the selected APUs.
+
+ On HIP it draws host RAM instead of the selected APUs' carve-outs, so the
+ decision is a direct comparison of the two pools. Available host RAM against
+ the carve-out's TOTAL is deliberate: a carve-out another process is holding
+ is not credited back to the host side, because the two pools fail
+ differently. Over-asking the carve-out returns hipErrorOutOfMemory and the
+ load fails cleanly, while over-asking host RAM is the OOM kill this gate
+ exists to stop, so both halves of the asymmetry lean toward the pool a miss
+ is recoverable in. Missing data and mixed-device selections fail closed.
+ """
+ try:
+ pool_mib = LlamaCppBackend._rocm_selected_pool_mib(gpu_indices)
+ if not pool_mib:
+ return False
+ host_mib = LlamaCppBackend._available_system_memory_mib()
+ if not host_mib:
+ return False
+ return int(host_mib) > int(pool_mib)
+ except Exception:
+ return False
+
@staticmethod
def _rocm_arch_by_physical_id() -> dict[int, str]:
"""Base gfx arch (lowercased, ``:xnack`` stripped) per PHYSICAL device id,
@@ -21834,10 +21905,9 @@ class LlamaCppBackend:
if not threads_overridden:
env.setdefault("OMP_NUM_THREADS", "2")
- # AMD unified-memory APUs (gfx1150/gfx1151): let llama.cpp use shared
- # system RAM. Not on Vulkan (nor DC below): gpu_indices are ggml
- # ordinals, not CUDA/ROCm ids. Ownership-tracked, so the arch-crash
- # retry withdraws it only when THIS launch set it.
+ # Managed allocations trade ROCm APU carve-out capacity for host RAM.
+ # Vulkan indices are not ROCm ids. Track ownership so later retries
+ # preserve inherited values.
_unified_env_applied = False
_unified_opt_out = self._unified_memory_opted_out(env)
if _unified_opt_out:
@@ -21847,10 +21917,13 @@ class LlamaCppBackend:
logger.info(
"Unified memory opted out: unset GGML_CUDA_ENABLE_UNIFIED_MEMORY"
)
- elif not is_vulkan_backend and self._amd_apu_wants_unified_memory(gpu_indices):
+ elif not is_vulkan_backend and self._unified_memory_would_help(gpu_indices):
_unified_env_applied = "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
env.setdefault("GGML_CUDA_ENABLE_UNIFIED_MEMORY", "1")
- logger.info("AMD unified-memory APU: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1")
+ logger.info(
+ "AMD unified-memory APU whose carve-out is smaller than host "
+ "RAM: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1"
+ )
# DC NVIDIA GPUs: FP32 accum (+ P2P / launch queues for multi-GPU).
# See _apply_datacenter_env; opt out with UNSLOTH_DISABLE_DC_TUNING=1.
@@ -21999,20 +22072,28 @@ class LlamaCppBackend:
# mode or ratio, and the mask re-indexes the survivors
# under both.
self._clear_split_placement_env(env)
- # GGML_CUDA_ENABLE_UNIFIED_MEMORY was decided against
- # gpu_indices, None here, so an uncovered APU anywhere on the
- # host turned it on -- and this narrowing hands the child only
- # discrete cards, where _amd_apu_wants_unified_memory's docstring
- # calls it harmful. Same withdrawal and ownership check as the
- # arch-crash retry: only the value THIS launch set.
- if _unified_env_applied and not self._amd_apu_wants_unified_memory(
- _survivors
- ):
+ # The setting is process-wide, so recompute it after changing
+ # the selected devices. Ownership protects inherited values.
+ _survivors_gain_unified = self._unified_memory_would_help(_survivors)
+ if _unified_env_applied and not _survivors_gain_unified:
env.pop("GGML_CUDA_ENABLE_UNIFIED_MEMORY", None)
_unified_env_applied = False
logger.info(
- "Arch gate narrowed the launch to discrete GPU(s); "
- "dropped GGML_CUDA_ENABLE_UNIFIED_MEMORY."
+ "Arch gate narrowed the launch onto GPU(s) the "
+ "unified-memory swap cannot help; dropped "
+ "GGML_CUDA_ENABLE_UNIFIED_MEMORY."
+ )
+ elif (
+ _survivors_gain_unified
+ and not _unified_opt_out
+ and "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+ ):
+ env["GGML_CUDA_ENABLE_UNIFIED_MEMORY"] = "1"
+ _unified_env_applied = True
+ logger.info(
+ "Arch gate narrowed the launch onto a unified-memory "
+ "APU whose carve-out is smaller than host RAM; set "
+ "GGML_CUDA_ENABLE_UNIFIED_MEMORY=1."
)
self._emit_child_gpu_visibility(
env, ",".join(str(i) for i in _survivors), prefer_rocr = True
@@ -22827,7 +22908,10 @@ class LlamaCppBackend:
gpu_indices, [i for i, _free in _detected_gpus]
)
if _remaining:
+ # APU presence controls the RAM guard; relative pool sizes
+ # determine whether managed allocations help.
_retry_wants_unified = self._amd_apu_wants_unified_memory(_remaining)
+ _retry_unified_helps = self._unified_memory_would_help(_remaining)
# Everything recorded so far priced the CRASHED selection, and
# that placement is gone: the canonical #7624 shape pins the APU
# whose shared-pool "free memory" outranked the dGPU, warns that
@@ -22888,22 +22972,24 @@ class LlamaCppBackend:
# the value this launch set. Both directions: a markerless
# mixed host can as easily crash on the dGPU and land on the
# APU, which needs it.
- if _unified_env_applied and not _retry_wants_unified:
+ if _unified_env_applied and not _retry_unified_helps:
env.pop("GGML_CUDA_ENABLE_UNIFIED_MEMORY", None)
_unified_env_applied = False
logger.info(
- "Arch-crash retry targets discrete GPU(s); dropped "
+ "Arch-crash retry targets GPU(s) the unified-memory "
+ "swap cannot help; dropped "
"GGML_CUDA_ENABLE_UNIFIED_MEMORY for the respawn."
)
elif (
- _retry_wants_unified
+ _retry_unified_helps
and not _unified_opt_out # the opt-out outlives the respawn
and "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
):
env["GGML_CUDA_ENABLE_UNIFIED_MEMORY"] = "1"
_unified_env_applied = True
logger.info(
- "Arch-crash retry targets a unified-memory APU; set "
+ "Arch-crash retry targets a unified-memory APU whose "
+ "carve-out is smaller than host RAM; set "
"GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 for the respawn."
)
self._emit_child_gpu_visibility(
diff --git a/studio/backend/tests/test_amd_apu_unified_memory.py b/studio/backend/tests/test_amd_apu_unified_memory.py
index 87275cea72f..65f52233ea1 100644
--- a/studio/backend/tests/test_amd_apu_unified_memory.py
+++ b/studio/backend/tests/test_amd_apu_unified_memory.py
@@ -400,3 +400,95 @@ class TestTheOptOutHelper:
raise RuntimeError("no")
assert LlamaCppBackend._unified_memory_opted_out(_Exploding()) is False
+
+
+def _fake_torch_sized(specs, *, hip = "6.2.0"):
+ """Build fake ROCm devices from ``(arch, total_bytes)`` specs."""
+ t = types.ModuleType("torch")
+ t.version = types.SimpleNamespace(hip = hip)
+ t.cuda = types.SimpleNamespace(
+ is_available = lambda: True,
+ device_count = lambda: len(specs),
+ get_device_properties = lambda i: types.SimpleNamespace(
+ gcnArchName = specs[i][0], total_memory = specs[i][1]
+ ),
+ )
+ return t
+
+
+_GIB = 1024**3
+
+
+class TestTheUnifiedMemorySwapIsOnlyTakenWhenItPays:
+ """Managed allocation is enabled only when host RAM is the larger pool."""
+
+ def _host(self, monkeypatch, specs, ram_mib):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch_sized(specs))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: ram_mib)
+ )
+
+ def test_a_small_carve_out_still_gets_it(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 16 * _GIB)], 117_000)
+ assert LlamaCppBackend._unified_memory_would_help() is True
+
+ def test_a_carve_out_larger_than_host_ram_does_not(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 64 * _GIB)], 58_880)
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_an_exact_tie_does_not(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 32 * _GIB)], 32 * 1024)
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_a_discrete_card_is_never_offered_it(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1100", 16 * _GIB)], 117_000)
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_unreadable_host_ram_fails_closed(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 16 * _GIB)], None)
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_an_unreported_pool_size_fails_closed(self, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch("6.2.0", ["gfx1151"]))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 117_000)
+ )
+ assert LlamaCppBackend._rocm_selected_pool_mib() is None
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_a_missing_torch_fails_closed(self, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert LlamaCppBackend._rocm_selected_pool_mib() is None
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_two_apus_are_weighed_together(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB), ("gfx1150", 24 * _GIB)], 40_000)
+ assert LlamaCppBackend._rocm_selected_pool_mib() == 32 * 1024
+ assert LlamaCppBackend._unified_memory_would_help() is True
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB), ("gfx1150", 24 * _GIB)], 30_000)
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_the_answer_is_scoped_to_the_selected_gpu(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB), ("gfx1150", 64 * _GIB)], 40_000)
+ assert LlamaCppBackend._unified_memory_would_help([0]) is True
+ assert LlamaCppBackend._unified_memory_would_help([1]) is False
+
+ def test_a_discrete_card_in_the_selection_fails_closed(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB), ("gfx1100", 64 * _GIB)], 40_000)
+ assert LlamaCppBackend._rocm_selected_pool_mib() is None
+ assert LlamaCppBackend._unified_memory_would_help() is False
+
+ def test_the_same_mixed_host_pinned_to_the_apu_still_gains(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB), ("gfx1100", 64 * _GIB)], 40_000)
+ assert LlamaCppBackend._rocm_selected_pool_mib([0]) == 8 * 1024
+ assert LlamaCppBackend._unified_memory_would_help([0]) is True
+
+ def test_an_id_this_host_does_not_enumerate_fails_closed(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB)], 117_000)
+ assert LlamaCppBackend._rocm_selected_pool_mib([0, 3]) is None
+ assert LlamaCppBackend._unified_memory_would_help([0, 3]) is False
+
+ def test_an_empty_selection_fails_closed(self, monkeypatch):
+ self._host(monkeypatch, [("gfx1151", 8 * _GIB)], 117_000)
+ assert LlamaCppBackend._rocm_selected_pool_mib([]) is None
+ assert LlamaCppBackend._unified_memory_would_help([]) is False
diff --git a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py
index 5c1f6ed21f0..ef3d6ad3703 100644
--- a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py
+++ b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py
@@ -46,7 +46,8 @@ from core.inference.llama_cpp import (
from utils.hardware import hardware as hw
MiB = 1024 * 1024
-_TOTAL_BYTES = 32 * 1024**3
+GIB = 1024**3
+_TOTAL_BYTES = 32 * GIB
# Concrete tokens the published ROCm manifest records for these bundles. gfx103X
# omits the gfx1033/1035/1036 iGPUs, which is the whole of #7624: they enumerate,
@@ -2192,7 +2193,8 @@ class TestArchCrashRetryRechecksTheApuRamGuard:
assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"
_retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]
assert _retry, "the arch-crash retry did not fire"
- assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)
+ # Its 32 GiB carve-out exceeds the 8 GiB host pool.
+ assert all("GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env for env in _retry)
@staticmethod
def _override_log(monkeypatch):
@@ -2921,3 +2923,126 @@ class TestTheApuRetryRecomputesThePageLock:
# comparator fights a child it already agrees with.
assert capture["backend"]._memory_mlock_applicable is True
assert capture["backend"]._memory_state[0] is True # (mlock, reserves_ram)
+
+
+class TestTheCarveOutDecidesTheUnifiedMemoryEnv:
+ """Launch behavior for the ROCm APU carve-out gate."""
+
+ def _apu(self, monkeypatch, carve_out_bytes, ram_mib):
+ _apply_os(monkeypatch, "linux", is_rocm = True)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: ram_mib)
+ )
+ return _fake_torch(
+ [
+ _device(
+ "gfx1151",
+ free_mib = 47000,
+ total_bytes = carve_out_bytes,
+ is_integrated = 1,
+ )
+ ],
+ vendor = "amd",
+ )
+
+ def _load(
+ self,
+ tmp_path,
+ monkeypatch,
+ torch,
+ env_extra = None,
+ ):
+ return _run_auto_load(
+ monkeypatch, tmp_path, torch, None, returncode = None, env_extra = env_extra
+ )
+
+ def test_a_small_carve_out_gets_it(self, tmp_path, monkeypatch, probe_env):
+ torch = self._apu(monkeypatch, 16 * GIB, 117_000)
+ _cmd, env = self._load(tmp_path, monkeypatch, torch)[0]
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"
+
+ def test_a_carve_out_bigger_than_host_ram_does_not(self, tmp_path, monkeypatch, probe_env):
+ torch = self._apu(monkeypatch, 64 * GIB, 58_880)
+ _cmd, env = self._load(tmp_path, monkeypatch, torch)[0]
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ def test_the_user_can_still_ask_for_it_on_that_host(self, tmp_path, monkeypatch, probe_env):
+ torch = self._apu(monkeypatch, 64 * GIB, 58_880)
+ _cmd, env = self._load(
+ tmp_path, monkeypatch, torch, {"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1"}
+ )[0]
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"
+
+ def test_the_opt_out_still_wins_on_a_host_that_would_get_it(
+ self, tmp_path, monkeypatch, probe_env
+ ):
+ torch = self._apu(monkeypatch, 16 * GIB, 117_000)
+ _cmd, env = self._load(
+ tmp_path, monkeypatch, torch, {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1"}
+ )[0]
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ def _apu_and_dgpu(self, monkeypatch, ram_mib):
+ _apply_os(monkeypatch, "linux", is_rocm = True)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: ram_mib)
+ )
+ return _fake_torch(
+ [
+ _device("gfx1151", free_mib = 7000, total_bytes = 8 * GIB, is_integrated = 1),
+ _device("gfx1100", free_mib = 60000, total_bytes = 64 * GIB),
+ ],
+ vendor = "amd",
+ )
+
+ def test_a_discrete_card_in_the_launch_keeps_it_off(self, tmp_path, monkeypatch, probe_env):
+ torch = self._apu_and_dgpu(monkeypatch, 40_000)
+ _cmd, env = _run_auto_load(
+ monkeypatch,
+ tmp_path,
+ torch,
+ None,
+ returncode = None,
+ intent_kwargs = {
+ "gpu_ids": (0, 1),
+ "gpu_memory_mode": "manual",
+ "gpu_layers": 1,
+ },
+ )[0]
+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0,1", "CUDA_VISIBLE_DEVICES": "0,1"}
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ def test_the_arch_gate_narrowing_onto_the_apu_adds_it_back(
+ self, tmp_path, monkeypatch, probe_env
+ ):
+ torch = self._apu_and_dgpu(monkeypatch, 40_000)
+ launches = _run_auto_load(
+ monkeypatch,
+ tmp_path,
+ torch,
+ ["gfx1151"], # covers the APU, not the discrete gfx1100
+ returncode = None,
+ model_bytes = 400 * GIB,
+ )
+ _cmd, env = launches[0]
+ assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"
+
+ def test_the_opt_out_survives_that_narrowing(self, tmp_path, monkeypatch, probe_env):
+ torch = self._apu_and_dgpu(monkeypatch, 40_000)
+ launches = _run_auto_load(
+ monkeypatch,
+ tmp_path,
+ torch,
+ ["gfx1151"],
+ returncode = None,
+ model_bytes = 400 * GIB,
+ env_extra = {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1"},
+ )
+ assert all("GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env for _c, env in launches)