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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: do not reserve the OS share twice on Linux ROCm APUs (#12675)
Daniel Han24af86a2ae90
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex ea5bc5e4862..8185dc78c83 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -2595,17 +2595,14 @@ class DiffusionBackend:# Capacity gate: mirror plan_fits_total_capacity against TOTAL capacity, else load_pipeline declines the dense# path anywayfrom .diffusion_memory import (- _reserve_mib,snapshot_device_memory,+ total_capacity_budget_mib,)- memory = snapshot_device_memory(target)- total = memory.total_mib+ budget = total_capacity_budget_mib(snapshot_device_memory(target))steady = getattr(candidate, "steady_total_mib", None)- if total is not None and steady is not None:- budget = int((int(total) - _reserve_mib(memory.memory_kind, int(total))) * 0.85)- if int(steady) > budget:- return False+ if budget is not None and steady is not None and int(steady) > budget:+ return Falsereturn Truedef _hosted_prequant_reachable(self, fam: Any, scheme: Optional[str], kwargs: dict) -> bool:diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex 174a2a48843..c95dc49c421 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -1072,13 +1072,37 @@ def _reserve_mib(memory_kind: str, base: int) -> int:return max(2048, int(base * 0.10))+def _rocm_linux_apu_os_room_outside_pool(memory: DeviceMemory) -> bool:+ """Linux ROCm APU whose host RAM outside the pool's free part already covers the unified OS reserve: the pool is+ the amdgpu GTT cap, below physical RAM, so reserving 20% of it too reserves twice. Not Windows (HIP over-reports+ free, #7072); unknown readings answer False."""+ if (+ memory.memory_kind != "unified_memory"+ or not sys.platform.startswith("linux")+ or memory.free_mib is None+ ):+ return False+ torch = sys.modules.get("torch")+ if torch is None or not _torch_is_rocm(torch):+ return False+ available = _available_system_memory_mib()+ if available is None:+ return False+ os_reserve = _reserve_mib("unified_memory", memory.total_mib or memory.free_mib)+ return int(available) - int(memory.free_mib) >= os_reserve+++def _budget_reserve_kind(memory: DeviceMemory) -> str:+ return "discrete_vram" if _rocm_linux_apu_os_room_outside_pool(memory) else memory.memory_kind++def _safe_device_budget_mib(memory: DeviceMemory) -> Optional[int]:"""Free memory minus a headroom reserve (room for fragmentation + other tenants). None whenfree memory is unknown."""if memory.free_mib is None:return Nonebase = memory.total_mib or memory.free_mib- return max(0, int(memory.free_mib) - _reserve_mib(memory.memory_kind, base))+ return max(0, int(memory.free_mib) - _reserve_mib(_budget_reserve_kind(memory), base))def _fast_device_budget_mib(memory: DeviceMemory) -> Optional[int]:@@ -1087,7 +1111,7 @@ def _fast_device_budget_mib(memory: DeviceMemory) -> Optional[int]:if memory.free_mib is None:return Nonebase = memory.total_mib or memory.free_mib- reserve = max(2048, _reserve_mib(memory.memory_kind, base) // 2)+ reserve = max(2048, _reserve_mib(_budget_reserve_kind(memory), base) // 2)return max(0, int(memory.free_mib) - reserve)@@ -1542,14 +1566,21 @@ def plan_fits_total_capacity(plan: Any) -> bool:input (unknown sizes keep today's behaviour)."""try:required = plan.estimates.get("resident_required_mib")- memory = plan.device_memory- total = memory.total_mib- kind = memory.memory_kind+ budget = total_capacity_budget_mib(plan.device_memory)except Exception: # noqa: BLE001 - malformed plan: no retryreturn False- if required is None or total is None:+ if required is None or budget is None:return False- return int(required) <= int((int(total) - _reserve_mib(kind, int(total))) * 0.85)+ return int(required) <= budget+++def total_capacity_budget_mib(memory: DeviceMemory) -> Optional[int]:+ """TOTAL capacity minus the same reserve the free budget takes, times the 0.85 resident margin. None when the+ total is unknown. Shared with the dense prefetch gate so the two cannot disagree."""+ total = memory.total_mib+ if total is None:+ return None+ return int((int(total) - _reserve_mib(_budget_reserve_kind(memory), int(total))) * 0.85)# Opt-in escape hatch for the unified-memory refusal below: the shortfall check is an estimate, so an operator whodiff --git a/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.py b/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.pynew file mode 100644index 00000000000..fc96c17b5ac--- /dev/null+++ b/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.py@@ -0,0 +1,145 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Linux ROCm APU (Strix Halo): the unified OS reserve is not taken twice. Numbers are the gfx1151 runner's at the+refusal."""++from __future__ import annotations++import types++import pytest++import core.inference.diffusion_memory as dm+from core.inference.diffusion_memory import (+ DeviceMemory,+ plan_diffusion_memory,+ unified_memory_shortfall_message,+)++POOL_TOTAL = 64 * 1024+POOL_FREE = 31 * 1024+HOST_AVAILABLE = 86 * 1024+ZIMAGE_WEIGHTS = 20 * 1024 # + the 1 GiB default base overhead = the "about 21 GB" of the refusal+++def _rocm_torch():+ return types.SimpleNamespace(+ __version__ = "2.11.0+rocm7.13.0", version = types.SimpleNamespace(hip = "7.13")+ )+++def _cuda_torch():+ return types.SimpleNamespace(+ __version__ = "2.11.0+cu130", version = types.SimpleNamespace(hip = None)+ )+++def host(monkeypatch):+ state = {"torch": _rocm_torch(), "platform": "linux", "available": HOST_AVAILABLE}+ monkeypatch.setattr(dm.sys, "platform", "linux")++ def apply():+ monkeypatch.setitem(dm.sys.modules, "torch", state["torch"])+ monkeypatch.setattr(dm.sys, "platform", state["platform"])+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: state["available"])++ state["apply"] = apply+ apply()+ return state+++def _plan(+ free = POOL_FREE,+ total = POOL_TOTAL,+ kind = "unified_memory",+):+ return plan_diffusion_memory(+ target = types.SimpleNamespace(+ device = "cuda", backend = "cuda", supports_model_cpu_offload = True+ ),+ device_memory = DeviceMemory("cuda", "cuda:0", kind, free, total),+ model_dense_mib = ZIMAGE_WEIGHTS,+ runtime_headroom_mib = 3072,+ )+++def test_linux_rocm_apu_with_host_room_loads_what_comfyui_loads(host):+ plan = _plan()+ assert plan.estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.10)+ assert unified_memory_shortfall_message(plan, family = "z-image") is None+++def test_still_refuses_what_cannot_fit_the_pool(host):+ plan = _plan(free = 18 * 1024)+ assert unified_memory_shortfall_message(plan, family = "z-image") is not None+++def test_host_ram_too_tight_keeps_the_unified_reserve(host):+ host["available"] = (+ POOL_FREE + 4 * 1024+ ) # 4 GiB outside the pool: the OS reserve is not covered+ host["apply"]()+ plan = _plan()+ assert plan.estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.20)+ assert unified_memory_shortfall_message(plan, family = "z-image") is not None+++def test_unknown_host_reading_keeps_the_unified_reserve(host):+ host["available"] = None+ host["apply"]()+ assert _plan().estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.20)++[email protected]("platform", ["win32", "darwin"])+def test_other_platforms_unchanged(host, platform):+ host["platform"] = platform+ host["apply"]()+ assert _plan().estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.20)+++def test_nvidia_unified_memory_unchanged(host):+ host["torch"] = _cuda_torch()+ host["apply"]()+ assert _plan().estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.20)+++def test_discrete_vram_unchanged(host):+ assert _plan(kind = "discrete_vram").estimates["safe_device_budget_mib"] == POOL_FREE - int(+ POOL_TOTAL * 0.10+ )+++def test_fast_budget_follows_the_same_reserve(host):+ memory = DeviceMemory("cuda", "cuda:0", "unified_memory", POOL_FREE, POOL_TOTAL)+ assert dm._fast_device_budget_mib(memory) == POOL_FREE - max(2048, int(POOL_TOTAL * 0.10) // 2)+ host["torch"] = _cuda_torch()+ host["apply"]()+ assert dm._fast_device_budget_mib(memory) == POOL_FREE - max(2048, int(POOL_TOTAL * 0.20) // 2)+++def test_total_capacity_gates_follow_the_same_reserve(host):+ # 47 GiB fits 0.85 * (64 - 6.4), not 0.85 * (64 - 12.8): a disagreeing prefetch gate drops the load to GGUF.+ memory = DeviceMemory("cuda", "cuda:0", "unified_memory", POOL_FREE, POOL_TOTAL)+ plan = types.SimpleNamespace(+ estimates = {"resident_required_mib": 47 * 1024}, device_memory = memory+ )+ assert dm.total_capacity_budget_mib(memory) == int((POOL_TOTAL - int(POOL_TOTAL * 0.10)) * 0.85)+ assert dm.plan_fits_total_capacity(plan)+ host["torch"] = _cuda_torch()+ host["apply"]()+ assert dm.total_capacity_budget_mib(memory) == int((POOL_TOTAL - int(POOL_TOTAL * 0.20)) * 0.85)+ assert not dm.plan_fits_total_capacity(plan)+++def test_dense_prefetch_gate_uses_the_shared_capacity_budget():+ import ast+ import inspect++ import core.inference.diffusion as diffusion++ src = inspect.getsource(diffusion)+ assert "total_capacity_budget_mib(snapshot_device_memory(target))" in src+ names = {n.id for n in ast.walk(ast.parse(src)) if isinstance(n, ast.Name)}+ assert "_reserve_mib" not in names