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: give GGML_CUDA_ENABLE_UNIFIED_MEMORY a real off switch (#8651) (#8680)

Daniel Han7822b7c23393
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 19587f565c9..d2c4c240753 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -5473,6 +5473,29 @@ class LlamaCppBackend:
except Exception:
return False
+ # "Off" spellings ggml itself ignores (it tests presence); we honour them.
+ _UNIFIED_MEMORY_OFF = frozenset({"", "0", "false", "no", "off"})
+
+ @staticmethod
+ def _unified_memory_opted_out(env = None) -> bool:
+ """True when GGML_CUDA_ENABLE_UNIFIED_MEMORY must be ABSENT from this launch.
+
+ ggml tests presence, not value, so `=0` is not an off switch (#8651). Both
+ opt-outs (UNSLOTH_DISABLE_UNIFIED_MEMORY=1, mirroring UNSLOTH_DISABLE_DC_TUNING,
+ or a falsy GGML_CUDA_ENABLE_UNIFIED_MEMORY) must end in the name unset.
+ Fails open (False) so a bad env never blocks a load.
+ """
+ try:
+ source = os.environ if env is None else env
+ if str(source.get("UNSLOTH_DISABLE_UNIFIED_MEMORY", "")).strip() == "1":
+ return True
+ value = source.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY")
+ if value is None:
+ return False
+ return str(value).strip().lower() in LlamaCppBackend._UNIFIED_MEMORY_OFF
+ except Exception:
+ 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
# workstation parts as substrings: "a100" must not fire on "RTX A1000".
@@ -14121,12 +14144,19 @@ class LlamaCppBackend:
env.setdefault("OMP_NUM_THREADS", "2")
# AMD unified-memory APUs (gfx1150/gfx1151): let llama.cpp use shared
- # system RAM. setdefault so a user value wins. Not on Vulkan (nor DC
- # below): gpu_indices are ggml ordinals, not CUDA/ROCm ids. Tracked by
- # OWNERSHIP, so the arch-crash retry withdraws it only when THIS launch
- # set it.
+ # 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.
_unified_env_applied = False
- if not is_vulkan_backend and self._amd_apu_wants_unified_memory(gpu_indices):
+ _unified_opt_out = self._unified_memory_opted_out(env)
+ if _unified_opt_out:
+ # ggml tests presence, so passing a user's "0" through would
+ # ENABLE what they turned off (#8651). Only absence is off.
+ if env.pop("GGML_CUDA_ENABLE_UNIFIED_MEMORY", None) is not None:
+ 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):
_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")
@@ -14730,7 +14760,11 @@ class LlamaCppBackend:
"Arch-crash retry targets discrete GPU(s); dropped "
"GGML_CUDA_ENABLE_UNIFIED_MEMORY for the respawn."
)
- elif _retry_wants_unified and "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env:
+ elif (
+ _retry_wants_unified
+ 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(
diff --git a/studio/backend/tests/test_amd_apu_unified_memory.py b/studio/backend/tests/test_amd_apu_unified_memory.py
index cade6a399ca..87275cea72f 100644
--- a/studio/backend/tests/test_amd_apu_unified_memory.py
+++ b/studio/backend/tests/test_amd_apu_unified_memory.py
@@ -352,3 +352,51 @@ class TestTheProbeTestsDoNotDependOnHostRam:
capped = LlamaCppBackend._get_gpu_memory()
assert rows == [(0, _B200_FREE_MIB - 1024, 0)]
assert capped == [(0, 14_000 - 1024, 0)]
+
+
+class TestTheOptOutHelper:
+ """_unified_memory_opted_out, the #8651 escape hatch. ggml tests presence, not
+ value, so only ABSENCE is off and this decides when to make it absent."""
+
+ @pytest.mark.parametrize(
+ "env,expected",
+ [
+ ({}, False), # nothing set: the default decides
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1"}, False),
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "2"}, False), # any value is ON to ggml
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "true"}, False),
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "0"}, True), # the reported trap
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": ""}, True),
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": " Off "}, True), # trimmed, folded
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "no"}, True),
+ ({"GGML_CUDA_ENABLE_UNIFIED_MEMORY": "false"}, True),
+ ({"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1"}, True),
+ ({"UNSLOTH_DISABLE_UNIFIED_MEMORY": "0"}, False), # exact "1", like the DC switch
+ ({"UNSLOTH_DISABLE_UNIFIED_MEMORY": "yes"}, False),
+ # The switch has to beat a truthy value.
+ (
+ {
+ "UNSLOTH_DISABLE_UNIFIED_MEMORY": "1",
+ "GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1",
+ },
+ True,
+ ),
+ ],
+ )
+ def test_opt_out_decisions(self, env, expected):
+ assert LlamaCppBackend._unified_memory_opted_out(env) is expected
+
+ def test_none_reads_the_process_env(self, monkeypatch):
+ """The default arg is the process env, so a shell export is honoured."""
+ monkeypatch.delenv("GGML_CUDA_ENABLE_UNIFIED_MEMORY", raising = False)
+ monkeypatch.setenv("UNSLOTH_DISABLE_UNIFIED_MEMORY", "1")
+ assert LlamaCppBackend._unified_memory_opted_out() is True
+
+ def test_a_hostile_env_fails_open(self):
+ """Fails open: a bad env must not block a load. False is pre-#8651."""
+
+ class _Exploding(dict):
+ def get(self, *_args, **_kwargs):
+ raise RuntimeError("no")
+
+ assert LlamaCppBackend._unified_memory_opted_out(_Exploding()) 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 cacdcbf1a9a..5c28f5502e9 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
@@ -1775,6 +1775,111 @@ class TestArchCrashRetryOntoAnApu:
assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)
+class TestUnifiedMemoryOptOut:
+ """Turning GGML_CUDA_ENABLE_UNIFIED_MEMORY off has to make it ABSENT (#8651).
+
+ ggml gates on ``getenv(...) != nullptr``, so "0" is still on and the reporter's
+ only route was patching the source. The host below is the reported one: a
+ gfx1151 Strix Halo APU whose pool ROCm reports in full. Mock-based, no ROCm."""
+
+ def _strix_halo(self, monkeypatch):
+ _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: 60000)
+ )
+ return _fake_torch(
+ [_device("gfx1151", free_mib = 47000, is_integrated = 1)],
+ vendor = "amd",
+ )
+
+ def _load(
+ self,
+ tmp_path,
+ monkeypatch,
+ env_extra = None,
+ ):
+ return _run_auto_load(
+ monkeypatch,
+ tmp_path,
+ self._strix_halo(monkeypatch),
+ None,
+ returncode = None,
+ env_extra = env_extra,
+ )
+
+ def test_the_apu_still_gets_it_by_default(self, tmp_path, monkeypatch, probe_env):
+ """Baseline: #5301 added the variable for exactly this hardware."""
+ _cmd, env = self._load(tmp_path, monkeypatch)[0]
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"
+
+ @pytest.mark.parametrize("value", ["0", "", "false", "FALSE", "no", "off", " 0 "])
+ def test_a_falsy_user_value_is_not_passed_through(
+ self, tmp_path, monkeypatch, probe_env, value
+ ):
+ """setdefault kept the user's "0", which ggml then read as enabled."""
+ _cmd, env = self._load(tmp_path, monkeypatch, {"GGML_CUDA_ENABLE_UNIFIED_MEMORY": value})[0]
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ @pytest.mark.parametrize("value", ["1", "2", "true", "on"])
+ def test_a_truthy_user_value_still_wins(self, tmp_path, monkeypatch, probe_env, value):
+ """Only off spellings are intercepted; anything else passes through."""
+ _cmd, env = self._load(tmp_path, monkeypatch, {"GGML_CUDA_ENABLE_UNIFIED_MEMORY": value})[0]
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == value
+
+ def test_the_disable_switch_keeps_it_unset(self, tmp_path, monkeypatch, probe_env):
+ """The switch users can find, mirroring UNSLOTH_DISABLE_DC_TUNING."""
+ _cmd, env = self._load(tmp_path, monkeypatch, {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1"})[0]
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ def test_the_disable_switch_also_clears_an_inherited_value(
+ self, tmp_path, monkeypatch, probe_env
+ ):
+ """The switch has to beat a stale inherited "1" too."""
+ _cmd, env = self._load(
+ tmp_path,
+ monkeypatch,
+ {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1", "GGML_CUDA_ENABLE_UNIFIED_MEMORY": "1"},
+ )[0]
+ assert "GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env
+
+ def test_a_non_one_disable_value_does_nothing(self, tmp_path, monkeypatch, probe_env):
+ """Exact "1", like the DC switch: firing on any value is the same trap."""
+ _cmd, env = self._load(tmp_path, monkeypatch, {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "0"})[0]
+ assert env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1"
+
+ def test_the_opt_out_survives_a_retry_onto_an_apu(self, tmp_path, monkeypatch, probe_env):
+ """The retry re-adds the variable on an APU; it must not undo the opt-out."""
+ _apply_os(monkeypatch, "linux", is_rocm = True)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)
+ )
+ torch = _fake_torch(
+ [
+ _device("gfx1030", free_mib = 40000),
+ _device("gfx1151", free_mib = 12000, is_integrated = 1),
+ ],
+ vendor = "amd",
+ )
+ launches = _run_auto_load(
+ monkeypatch,
+ tmp_path,
+ torch,
+ None, # no marker: the proactive gate fails open, so the crash path runs
+ returncode = 1,
+ output = "ROCm error: device kernel image is invalid",
+ env_extra = {"UNSLOTH_DISABLE_UNIFIED_MEMORY": "1"},
+ )
+ _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("GGML_CUDA_ENABLE_UNIFIED_MEMORY" not in env for _c, env in launches)
+
+
class TestArchCrashRetryDropsDeadTensorMode:
"""Narrowing to one device makes --split-mode tensor a no-op still REPORTED as
active: tensor_parallel drives the UI and the MTP crash watchdog. Dropping