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: stop the memory guards trusting an over-reported free VRAM on Windows ROCm (#8482)
Daniel Hanb53de1e4c243
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex ff0b1fb712c..85cae4cbb52 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -254,7 +254,14 @@ def _cuda_memory(backend: str) -> tuple[Optional[int], Optional[int], str]:try:import torch- free, total = torch.cuda.mem_get_info()+ # Not torch.cuda.mem_get_info directly: on Windows ROCm its free half is an+ # over-report that does not track residency, and this feeds the activation+ # refusal that exists BECAUSE Windows WDDM spills to host RAM instead of+ # raising (#8403). Imported lazily to keep this module free of backend+ # imports at module scope.+ from utils.hardware import trusted_mem_get_info++ free, total = trusted_mem_get_info()kind = "discrete_vram"try:# Query the CURRENT device (mem_get_info reports it); hardcoding 0 would inspect the wrong GPU and misclassify it.diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 1e84ec988f8..1cbd03f9719 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -5481,8 +5481,14 @@ class LlamaCppBackend:# margin, and report total 0 since that "total" is system RAM.unified_ids = LlamaCppBackend._rocm_unified_memory_gpu_ids()gpus = []+ # Windows ROCm's free reading is an over-report on discrete cards too,+ # not only on the shared pool handled below (#8403). It is capped+ # against this process's own allocator, so VRAM a resident torch model+ # holds in the backend process stops being offered to llama.cpp slots.+ from utils.hardware import trusted_mem_get_info+for ordinal in range(torch.cuda.device_count()):- free_bytes, total_bytes = torch.cuda.mem_get_info(ordinal)+ free_bytes, total_bytes = trusted_mem_get_info(ordinal)idx = (physical_ids[ordinal]if physical_ids is not None and ordinal < len(physical_ids)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 2f886c15ec5..30ac1ae37ff 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -666,8 +666,11 @@ def _h3_free_device_bytes(device: str) -> Optional[int]:if device != "cuda":return Nonetry:- import torch- return int(torch.cuda.mem_get_info()[0])+ from utils.hardware import trusted_mem_get_info++ # Windows ROCm over-reports free (#8403); pinning the denoiser on that+ # reading is how a card that is already full still looks roomy.+ return int(trusted_mem_get_info()[0])except Exception: # noqa: BLE001 -- an unreadable card decides nothingreturn None@@ -4197,7 +4200,7 @@ class VideoBackend:free_bytes = Noneif sizes is not None:try:- free_bytes = torch.cuda.mem_get_info()[0] if device == "cuda" else None+ free_bytes = _h3_free_device_bytes(device)except Exception: # noqa: BLE001 -- unreadable free memory keeps the rotationfree_bytes = Noneif sizes is not None and free_bytes is not None:@@ -4764,7 +4767,11 @@ class VideoBackend:device_obj = torch.device(state.device)device_module = getattr(torch, device_obj.type, None)if device_module is not None and hasattr(device_module, "mem_get_info"):- free_bytes, _ = device_module.mem_get_info(device_obj)+ # Windows ROCm's free half is an over-report and this is a+ # hard refusal, so cap it against the allocator (#8403).+ from utils.hardware import trusted_mem_get_info++ free_bytes, _ = trusted_mem_get_info(device_obj, module = device_module)reserved_bytes = (device_module.memory_reserved(device_obj)if hasattr(device_module, "memory_reserved")diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex 5ff448dc0ae..004a2ff1f91 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -584,7 +584,11 @@ def _resolve_base_precision(cfg, spec, device) -> str:try:import torch- free_gb = torch.cuda.mem_get_info()[0] / 1e9+ # Windows ROCm over-reports free VRAM (#8403), which would pick a+ # dense precision the card cannot actually hold.+ from utils.hardware import trusted_mem_get_info++ free_gb = trusted_mem_get_info()[0] / 1e9capability = torch.cuda.get_device_capability()has_fp8 = hasattr(torch, "float8_e4m3fn")except Exception: # noqa: BLE001 -- probe failure -> the safe modediff --git a/studio/backend/tests/test_rocm_windows_mem_guards_8403.py b/studio/backend/tests/test_rocm_windows_mem_guards_8403.pynew file mode 100644index 00000000000..f0a4a9427d8--- /dev/null+++ b/studio/backend/tests/test_rocm_windows_mem_guards_8403.py@@ -0,0 +1,257 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for issue #8403 -- the ``mem_get_info`` free over-report is+uncorrected in the memory guards, so the host-RAM spill refusal never fires.++On Windows ROCm the driver's FREE figure does not track residency: it is returned+at or near ``total`` on a card that is nearly full (ROCm/librocdxg#57, where the+reporter observes it does not move as VRAM is consumed on Windows native;+ROCm/TheRock#3724, where torch OOMs on Windows while reporting 52.71 GiB of a+53.92 GiB card free; ggml-org/llama.cpp#24836 on the reading being OS-dependent).+``utils/hardware/hardware.py`` has always known this for the System tab. The+guards did not, and they only ever over-report, so they go blind rather than+noisy.++The sharpest case is ``image_activation_shortfall_message``, shipped in #8224.+Its own docstring says it exists because on Windows WDDM the overrun does not+raise -- the driver satisfies it from host RAM and the process grows past the+card -- so on that platform it is the only protection there is. It budgets from+``_cuda_memory``, which had no platform branch, so on Windows ROCm it was told+the whole card was free.++Reporter hardware for the family: AMD RDNA3/RDNA4 on Windows (the #7072/#7452+reporter runs a Radeon PRO W7900 + W7500 on Windows 10 with ROCm 7.13). The+16-24 GiB single-card shapes below are the class #8188 was reported from. torch,+the platform and ROCm detection are all mocked: this repository has no AMD GPU+and no Windows or ROCm CI, so none of this is a hardware validation.+"""++from __future__ import annotations++import sys+import types++import pytest++from core.inference import diffusion_memory as dm+from utils.hardware import hardware as hw++MiB = 1024**2+GiB = 1024**3+++def _fake_torch(+ total_bytes,+ *,+ free_bytes,+ reserved_bytes = 0,+ allocated_bytes = None,+):+ """A torch whose driver free reading and allocator accounting can disagree.++ ``mem_get_info`` takes no argument here because ``_cuda_memory`` calls it that+ way; the optional ordinal matches the real signature.+ """++ class _Props:+ def __init__(self):+ self.name = "AMD Radeon RX 7900 XTX"+ self.total_memory = total_bytes+ self.integrated = False++ allocated = reserved_bytes if allocated_bytes is None else allocated_bytes++ t = types.ModuleType("torch")+ t.__version__ = "2.11.0+rocm7.13"+ t.version = types.SimpleNamespace(hip = "7.13", cuda = None)+ t.cuda = types.SimpleNamespace(+ is_available = lambda: True,+ device_count = lambda: 1,+ current_device = lambda: 0,+ get_device_properties = lambda i = 0: _Props(),+ mem_get_info = lambda i = None: (free_bytes, total_bytes),+ memory_reserved = lambda i = None: reserved_bytes,+ memory_allocated = lambda i = None: allocated,+ )+ return t+++def win_rocm(monkeypatch):+ """Windows ROCm, as the hardware module's own sentinel predicate reads it."""+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.sys, "platform", "win32")+ return monkeypatch+++class _Target:+ """The minimal shape snapshot_device_memory() reads off a diffusion state."""++ device = "cuda"+ backend = "diffusers"+++# ----------------------------------------------------------------------------- #+# The #8224 guard, which is the one #8403 is about+# ----------------------------------------------------------------------------- #+def test_activation_guard_fires_on_a_full_card_that_reports_itself_empty(win_rocm, monkeypatch):+ """A 24 GiB card with 20 GiB of pipeline resident, driver reporting the whole+ card free. 1536x1536 does not fit the 4 GiB that is actually left, and on+ Windows nothing else will refuse it: WDDM spills to host RAM instead of+ raising. Before the fix the guard saw 24 GiB free and said nothing."""+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(24 * GiB, free_bytes = 24 * GiB, reserved_bytes = 20 * GiB),+ )++ memory = dm.snapshot_device_memory(_Target())+ assert memory.free_mib == 4 * 1024 # not the driver's 24576++ message = dm.image_activation_shortfall_message(+ device_memory = memory, width = 1536, height = 1536, family = "sdxl"+ )+ assert message is not None+ with pytest.raises(dm.ImageActivationShortfallError):+ dm.raise_on_image_activation_shortfall(+ device_memory = memory, width = 1536, height = 1536, family = "sdxl"+ )+++def test_activation_guard_still_silent_at_the_default_resolution(win_rocm, monkeypatch):+ """The correction must not turn the guard into a nuisance: a request at or+ below what the load itself budgeted is exempt by the `needed <= planned` arm,+ which the tighter free reading does not touch."""+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(24 * GiB, free_bytes = 24 * GiB, reserved_bytes = 20 * GiB),+ )+ memory = dm.snapshot_device_memory(_Target())+ assert (+ dm.image_activation_shortfall_message(+ device_memory = memory, width = 1024, height = 1024, family = "sdxl"+ )+ is None+ )+++def test_linux_rocm_reading_is_untouched(monkeypatch):+ """Control: the same numbers off Windows keep the driver's free reading, so+ Linux ROCm and NVIDIA behaviour is byte-identical to before."""+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.sys, "platform", "linux")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(24 * GiB, free_bytes = 9 * GiB, reserved_bytes = 20 * GiB),+ )+ assert dm.snapshot_device_memory(_Target()).free_mib == 9 * 1024+++def test_windows_nvidia_reading_is_untouched(monkeypatch):+ """The cap is ROCm-gated: CUDA's free reading is trustworthy on Windows."""+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw.sys, "platform", "win32")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(24 * GiB, free_bytes = 9 * GiB, reserved_bytes = 20 * GiB),+ )+ assert dm.snapshot_device_memory(_Target()).free_mib == 9 * 1024+++# ----------------------------------------------------------------------------- #+# The #8224 memory PLAN reads the same feeder+# ----------------------------------------------------------------------------- #+def test_memory_plan_budget_sees_the_corrected_free(win_rocm, monkeypatch):+ """_plan_memory budgets from settled_snapshot_device_memory, so the offload+ tier was picked against a card that claimed to be empty. The settling loop's+ early exit (free >= total - headroom) also trips instantly on the sentinel,+ which is why the plan never even retried."""+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(24 * GiB, free_bytes = 24 * GiB, reserved_bytes = 20 * GiB),+ )+ memory = dm.settled_snapshot_device_memory(_Target(), attempts = 1)+ assert memory.free_mib == 4 * 1024+ assert dm._safe_device_budget_mib(memory) < 4 * 1024+++def test_reclaimable_snapshot_credits_the_cache_back(win_rocm, monkeypatch):+ """The cap is against RESERVED, and the per-generation snapshot adds torch's+ reclaimable cache back, so a process holding 20 GiB reserved of which 6 GiB is+ cached lands on total - allocated rather than on a pessimistic floor."""+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(+ 24 * GiB,+ free_bytes = 24 * GiB,+ reserved_bytes = 20 * GiB,+ allocated_bytes = 14 * GiB,+ ),+ )+ assert dm.reclaimable_snapshot_device_memory(_Target()).free_mib == 10 * 1024+++# ----------------------------------------------------------------------------- #+# The shared helper (pure unit)+# ----------------------------------------------------------------------------- #+def test_trusted_mem_get_info_caps_free_at_unreserved_bytes(win_rocm, monkeypatch):+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(16 * GiB, free_bytes = 16 * GiB, reserved_bytes = 11 * GiB),+ )+ assert hw.trusted_mem_get_info() == (5 * GiB, 16 * GiB)+ # A near-sentinel reading (TheRock#3724: 52.71 GiB "free" of 53.92 GiB while+ # OOMing) is capped too: the cap does not depend on exact equality.+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(16 * GiB, free_bytes = 15 * GiB, reserved_bytes = 11 * GiB),+ )+ assert hw.trusted_mem_get_info() == (5 * GiB, 16 * GiB)+ # Never optimistic: a driver figure already below the cap is kept.+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(16 * GiB, free_bytes = 2 * GiB, reserved_bytes = 11 * GiB),+ )+ assert hw.trusted_mem_get_info() == (2 * GiB, 16 * GiB)+++def test_trusted_mem_get_info_is_a_no_op_without_the_sentinel(monkeypatch):+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw.sys, "platform", "linux")+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _fake_torch(16 * GiB, free_bytes = 15 * GiB, reserved_bytes = 11 * GiB),+ )+ assert hw.trusted_mem_get_info() == (15 * GiB, 16 * GiB)+++def test_trusted_mem_get_info_falls_back_when_the_allocator_cannot_answer(win_rocm, monkeypatch):+ """No allocator accounting to cap against leaves the driver figure as the only+ reading there is, rather than a fabricated zero."""+ torch_mod = _fake_torch(16 * GiB, free_bytes = 16 * GiB)++ def _boom(i = None):+ raise RuntimeError("no allocator")++ torch_mod.cuda.memory_reserved = _boom+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ assert hw.trusted_mem_get_info() == (16 * GiB, 16 * GiB)+++def test_trusted_mem_get_info_accepts_an_explicit_device_and_module(win_rocm, monkeypatch):+ """llama.cpp slot fitting probes per ordinal and the video preflight passes the+ resolved device module, so both call shapes have to work."""+ torch_mod = _fake_torch(16 * GiB, free_bytes = 16 * GiB, reserved_bytes = 4 * GiB)+ monkeypatch.setitem(sys.modules, "torch", torch_mod)+ assert hw.trusted_mem_get_info(0) == (12 * GiB, 16 * GiB)+ assert hw.trusted_mem_get_info(0, module = torch_mod.cuda) == (12 * GiB, 16 * GiB)diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.pyindex 4d06fb20737..50417af3dd6 100644--- a/studio/backend/utils/hardware/__init__.py+++ b/studio/backend/utils/hardware/__init__.py@@ -20,6 +20,8 @@ from .hardware import (get_package_versions,get_gpu_utilization,get_visible_gpu_utilization,+ rocm_windows_free_is_untrusted,+ trusted_mem_get_info,get_backend_visible_gpu_info,get_vulkan_inference_gpu_info,get_physical_gpu_count,@@ -97,6 +99,8 @@ __all__ = ["get_package_versions","get_gpu_utilization","get_visible_gpu_utilization",+ "rocm_windows_free_is_untrusted",+ "trusted_mem_get_info","get_backend_visible_gpu_info","get_vulkan_inference_gpu_info","get_physical_gpu_count",diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 61497819961..0972358b859 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -1079,6 +1079,43 @@ def rocm_windows_free_is_untrusted() -> bool:return sys.platform == "win32" and IS_ROCM+def trusted_mem_get_info(device: Any = None, *, module: Any = None) -> tuple[int, int]:+ """``mem_get_info`` with the Windows ROCm free over-report capped (#8403).++ Guards that budget against free VRAM (the image activation refusal, llama.cpp+ slot fitting, the video preflight) cannot be handed a figure that says the+ whole card is free while a model is resident: on Windows WDDM the overflow+ does not raise, the driver satisfies it from host RAM, and the process grows+ past the card instead of failing, so an optimistic reading removes the only+ protection there is.++ Free is capped at what this process's own torch allocator has NOT reserved,+ which is a true upper bound on free VRAM. It still cannot see another+ process's allocations, so it is a ceiling, not a measurement; a caller that+ adds torch's reclaimable cache back (as the diffusion snapshot does) recovers+ exactly ``total - allocated``. Off Windows ROCm this returns the driver's own+ numbers untouched.++ ``module`` defaults to ``torch.cuda``; pass ``torch.xpu`` or the resolved+ device module to probe another backend. Exceptions propagate, so callers keep+ their existing "unreadable card decides nothing" handling.+ """+ import torch++ mod = module if module is not None else torch.cuda+ free_bytes, total_bytes = mod.mem_get_info() if device is None else mod.mem_get_info(device)+ free_bytes, total_bytes = int(free_bytes), int(total_bytes)+ if not rocm_windows_free_is_untrusted():+ return free_bytes, total_bytes+ try:+ reserved = int(mod.memory_reserved() if device is None else mod.memory_reserved(device))+ except Exception as e:+ # No allocator accounting to cap against: the driver figure is all there is.+ logger.debug("memory_reserved probe failed while capping free VRAM: %s", e)+ return free_bytes, total_bytes+ return min(free_bytes, max(0, total_bytes - reserved)), total_bytes++def _torch_get_per_device_info(device_indices: list[int]) -> list[Dict[str, Any]]:"""Query torch for per-GPU name, total VRAM, and used VRAM.