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: warn when a Windows GPU load leaves the system short of commit (#16046)
Debojyoti Banerjeed3b48f34527a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex eae69fc736e..42de99bcc6e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -4045,6 +4045,54 @@ _LLAMA_FIT_TARGET_DEFAULT_MIB = 1024.0_WINDOWS_SYSMEM_FALLBACK_RESERVE_MIB = _LLAMA_FIT_TARGET_DEFAULT_MIB_WINDOWS_SYSMEM_FALLBACK_MAX_FRACTION = 0.125+# WDDM backs GPU allocations with system commit the process never touches (#16015).+_WINDOWS_GPU_UNTOUCHED_COMMIT_MIN_MIB = 2048+_WINDOWS_GPU_COMMIT_HEADROOM_WARN_MIB = 4096+++def _windows_private_memory(pid: int) -> Optional[tuple[int, int]]:+ """(PrivateUsage, PrivateWorkingSetSize) in bytes; None when unreadable (needs Windows 10 1809+).+ psutil's uss and wset both count mmap'd GGUF pages, which would hide untouched commit."""+ from ctypes import wintypes++ class _COUNTERS_EX2(ctypes.Structure):+ _fields_ = (+ [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)]+ + [+ (name, ctypes.c_size_t)+ for name in (+ "PeakWorkingSetSize",+ "WorkingSetSize",+ "QuotaPeakPagedPoolUsage",+ "QuotaPagedPoolUsage",+ "QuotaPeakNonPagedPoolUsage",+ "QuotaNonPagedPoolUsage",+ "PagefileUsage",+ "PeakPagefileUsage",+ "PrivateUsage",+ "PrivateWorkingSetSize",+ )+ ]+ + [("SharedCommitUsage", ctypes.c_ulonglong)]+ )++ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ kernel32.K32GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD]+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return None+ try:+ counters = _COUNTERS_EX2()+ counters.cb = ctypes.sizeof(counters)+ if not kernel32.K32GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb):+ return None+ return int(counters.PrivateUsage), int(counters.PrivateWorkingSetSize)+ finally:+ kernel32.CloseHandle(handle)+def _vram_reserve_floor_mib(total_mib: float, *, sysmem_fallback: bool = False) -> float:"""Floor 512 MiB, capped at the default reserve to keep the budget monotonic; sysmem_fallback raises it and deliberately overrides a 100% budget."""@@ -15915,6 +15963,47 @@ class LlamaCppBackend:f"Auto.{kv_hint}")+ @staticmethod+ def _gpu_commit_headroom_message(+ untouched_mib: int, headroom_mib: Optional[int]+ ) -> Optional[str]:+ """Advisory for commit Windows reserves for GPU memory; None while there is room."""+ if headroom_mib is None or untouched_mib < _WINDOWS_GPU_UNTOUCHED_COMMIT_MIN_MIB:+ return None+ if headroom_mib >= _WINDOWS_GPU_COMMIT_HEADROOM_WARN_MIB:+ return None+ held_gib = untouched_mib / 1024+ return (+ f"On Windows the GPU driver reserves system commit for the model's GPU memory: "+ f"llama-server holds about {held_gib:.1f} GiB of commit it never uses in RAM, and "+ f"only {headroom_mib / 1024:.1f} GiB of commit is left on this system. Studio cannot "+ f"release it, and when the commit limit runs out other apps can fail to start or "+ f"crash. Let Windows manage the page file size, or raise it by at least "+ f"{math.ceil(held_gib)} GiB, under System > About > Advanced system settings > "+ f"Performance > Advanced > Virtual memory."+ )++ @staticmethod+ def _windows_gpu_commit_notice(pid: Optional[int], binary: Optional[str]) -> Optional[str]:+ """Measures a loaded GPU child on Windows; never raises, since it only adds a notice."""+ if sys.platform != "win32" or not pid:+ return None+ try:+ if not LlamaCppBackend._installed_ggml_backends(binary) & {"cuda", "hip", "vulkan"}:+ return None+ from .diffusion_memory import _windows_commit_headroom_mib++ counters = _windows_private_memory(pid)+ if counters is None:+ return None+ untouched_mib = max(0, counters[0] - counters[1]) // (1024 * 1024)+ return LlamaCppBackend._gpu_commit_headroom_message(+ untouched_mib, _windows_commit_headroom_mib()+ )+ except Exception as e: # noqa: BLE001 - a failed probe must not fail the load+ logger.debug("GPU commit headroom check failed: %s", e)+ return None+# Skip the wait when the last kill is older than this; the driver has already reclaimed it._VRAM_SETTLE_WINDOW_S: float = 15.0@@ -32391,6 +32480,15 @@ class LlamaCppBackend:else None),)+ elif not intent.cpu_fallback:+ _gpu_commit_notice = self._windows_gpu_commit_notice(+ getattr(self._process, "pid", None), binary+ )+ if _gpu_commit_notice:+ if self._last_load_warning:+ self._amend_load_warning(" " + _gpu_commit_notice)+ else:+ self._record_load_warning(_gpu_commit_notice)if not self._publish_healthy():# Teardown began after the 200; publishing would report a model that is gone._cleanup_cancelled_load("App shut down as the load was completing")diff --git a/studio/backend/tests/test_windows_gpu_commit_notice.py b/studio/backend/tests/test_windows_gpu_commit_notice.pynew file mode 100644index 00000000000..08a5392c65a--- /dev/null+++ b/studio/backend/tests/test_windows_gpu_commit_notice.py@@ -0,0 +1,102 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Windows charges commit for GPU buffers the process never touches (HIP and Vulkan); a load that+leaves the system short of commit says so instead of exhausting the page file silently (#16015)."""++from __future__ import annotations++import sys+import types as _types+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++_structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++import core.inference.diffusion_memory as diffusion_memory+from core.inference import llama_cpp as llama_cpp_module+from core.inference.llama_cpp import LlamaCppBackend++_MIB = 1024 * 1024+++def test_report_numbers_warn_with_page_file_advice():+ # The report: ~15.9 GiB untouched commit on llama-server, 1.2 GB of commit left.+ message = LlamaCppBackend._gpu_commit_headroom_message(16_265, 1_150)+ assert message is not None+ assert "15.9 GiB" in message+ assert "1.1 GiB" in message+ assert "at least 16 GiB" in message+ assert "Virtual memory" in message+++ ("untouched_mib", "headroom_mib"),+ [+ (16_265, 4_096), # enough commit left+ (16_265, None), # headroom unreadable+ (2_047, 0), # the child holds no meaningful untouched commit+ ],+)+def test_no_warning_while_there_is_room_or_nothing_to_blame(untouched_mib, headroom_mib):+ assert LlamaCppBackend._gpu_commit_headroom_message(untouched_mib, headroom_mib) is None+++# Reporter's DirectIO load: ~16 GiB private commit, almost none of it resident.+_REPORT_COUNTERS = (16_500 * _MIB, 235 * _MIB)+++def _windows_child(+ monkeypatch,+ backends,+ headroom_mib = 1_150,+):+ monkeypatch.setattr(llama_cpp_module.sys, "platform", "win32")+ monkeypatch.setattr(+ LlamaCppBackend, "_installed_ggml_backends", staticmethod(lambda binary = None: backends)+ )+ monkeypatch.setattr(diffusion_memory, "_windows_commit_headroom_mib", lambda: headroom_mib)+ monkeypatch.setattr(llama_cpp_module, "_windows_private_memory", lambda pid: _REPORT_COUNTERS)++[email protected]("gpu", ["hip", "vulkan", "cuda"])+def test_gpu_child_short_of_commit_gets_the_notice(monkeypatch, gpu):+ _windows_child(monkeypatch, frozenset({"base", "cpu", gpu}))+ message = LlamaCppBackend._windows_gpu_commit_notice(1234, "llama-server.exe")+ assert message is not None and "15.9 GiB" in message+++def test_cpu_only_builds_are_not_measured(monkeypatch):+ _windows_child(monkeypatch, frozenset({"base", "cpu"}))+ assert LlamaCppBackend._windows_gpu_commit_notice(1234, "llama-server.exe") is None+++def test_off_windows_or_without_a_child_nothing_is_measured(monkeypatch):+ _windows_child(monkeypatch, frozenset({"hip"}))+ assert LlamaCppBackend._windows_gpu_commit_notice(None, "llama-server.exe") is None+ monkeypatch.setattr(llama_cpp_module.sys, "platform", "linux")+ assert LlamaCppBackend._windows_gpu_commit_notice(1234, "llama-server.exe") is None++[email protected]("counters", [None, RuntimeError("OpenProcess denied")])+def test_a_failed_probe_never_fails_the_load(monkeypatch, counters):+ _windows_child(monkeypatch, frozenset({"hip"}))++ def _read(pid):+ if isinstance(counters, Exception):+ raise counters+ return counters++ monkeypatch.setattr(llama_cpp_module, "_windows_private_memory", _read)+ assert LlamaCppBackend._windows_gpu_commit_notice(1234, "llama-server.exe") is None