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: fix host memory checks and improve logging for GGUF image loads (#14514)
Mathias Müller03639b70a20e
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 01739ba198e..04ab354c560 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -164,12 +164,14 @@ from .diffusion_small_host import (INT8_DENOISER_NAMES,decide_small_host,engaged_on as small_host_engaged_on,+ host_commit_mib,host_ram_mib,resolve_snapshot_dir,stored_components,torch_dtype_map as small_host_torch_dtype_map,)from .model_ids import hf_cache_repo_id+from .safetensors_pread import pread_availablefrom .diffusion_memory import (MEMORY_MODE_BALANCED,MEMORY_MODE_LOW_VRAM,@@ -3325,6 +3327,15 @@ def _comfy_keep_fp32_pricing(fam: Any, target: Any) -> dict:return {"keep_fp32": keep, "keep_fp32_bytes": 4 if fp16 else None}+def _converted_shards_pread(dtype: Any, small_host: Any) -> Any:+ """Windows: transformers components converted to ``dtype`` read through ``pread`` (no copy-on-write commit for the+ stored bytes, #14513); components the small-host route loads at their stored dtype stay memory-mapped."""+ from .safetensors_pread import pread_safetensors++ keep = tuple(small_host.storage_dtypes) if small_host is not None and small_host.engaged else ()+ return pread_safetensors(convert_to = dtype, keep = keep)++class DiffusionBackend:"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""@@ -8927,9 +8938,10 @@ class DiffusionBackend:# The prefetched snapshot dir keeps from_pretrained off the hub (24 GB per FLUX.1# otherwise)try:- pipe = pipeline_cls.from_pretrained(- _base_local_dir or fetch_base, **pipe_kwargs- )+ with _converted_shards_pread(dtype, small_host):+ pipe = pipeline_cls.from_pretrained(+ _base_local_dir or fetch_base, **pipe_kwargs+ )finally:self._stop_load_prefetch()if fam.single_file_is_pipeline:@@ -9198,9 +9210,10 @@ class DiffusionBackend:pipe_kwargs["torch_dtype"] = small_host_torch_dtype_map(small_host, dtype)- pipe = pipeline_cls.from_pretrained(- _base_local_dir or fetch_base, **pipe_kwargs- )+ with _converted_shards_pread(dtype, small_host):+ pipe = pipeline_cls.from_pretrained(+ _base_local_dir or fetch_base, **pipe_kwargs+ )if small_host is not None and small_host.engaged:plan = self._apply_small_host_route(pipe,@@ -10935,7 +10948,8 @@ class DiffusionBackend:family = getattr(fam, "name", None),))- pipe = pipeline_cls.from_pretrained(base_local_dir or base, **pipe_kwargs)+ with _converted_shards_pread(dtype, None):+ pipe = pipeline_cls.from_pretrained(base_local_dir or base, **pipe_kwargs)check_cancelled()pipe.to(device)return pipe@@ -11379,6 +11393,8 @@ class DiffusionBackend:host_total_mib = total,host_available_mib = available,lora_active = lora_active,+ host_commit_mib = host_commit_mib(),+ pread_libraries = ("transformers",) if pread_available() else (),)if decision.engaged or decision.refuse:logger.info(@@ -11387,6 +11403,8 @@ class DiffusionBackend:decision.reason,decision.storage_dtypes,)+ elif decision.available_mib is not None:+ logger.info("diffusion.small_host: engaged=False (%s)", decision.reason)if decision.refuse:raise RuntimeError(decision.refuse)return decisiondiff --git a/studio/backend/core/inference/diffusion_hidream.py b/studio/backend/core/inference/diffusion_hidream.pyindex a81b6d647de..7db8839922e 100644--- a/studio/backend/core/inference/diffusion_hidream.py+++ b/studio/backend/core/inference/diffusion_hidream.py@@ -143,15 +143,19 @@ def hidream_te4_kwargs()logger.info("diffusion.hidream: loading Llama TE4 from %s", HIDREAM_LLAMA_REPO)- text_encoder_4 = LlamaForCausalLM.from_pretrained(- HIDREAM_LLAMA_REPO,- output_hidden_states = True,- output_attentions = True,- torch_dtype = dtype,- token = hf_token,- local_files_only = local_files_only,- cache_dir = cache_dir,- )+ from .safetensors_pread import pread_safetensors++ # loaded before the pipeline's own scope: a 16 GB bf16 Llama converted on Windows reads through pread too+ with pread_safetensors(convert_to = dtype):+ text_encoder_4 = LlamaForCausalLM.from_pretrained(+ HIDREAM_LLAMA_REPO,+ output_hidden_states = True,+ output_attentions = True,+ torch_dtype = dtype,+ token = hf_token,+ local_files_only = local_files_only,+ cache_dir = cache_dir,+ )if fp8_engages:try:from .diffusion_precision import _cast_fp8diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex aa324e918f6..9223651cb30 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -1286,6 +1286,45 @@ def _host_ram_capacity_mib() -> Optional[int]:return host_memory.usable_mib(_system_memory_mib()[0], _cgroup_memory_limit_mib())+def _windows_commit_headroom_mib() -> Optional[int]:+ """(CommitLimit - CommitTotal) in MiB on Windows via ``K32GetPerformanceInfo``; 0 when exhausted, None when+ unreadable or not Windows. The diffusion guards' failure mode is commit exhaustion (#13432), which a+ physical `available` reading does not see."""+ if sys.platform != "win32":+ return None+ try:+ import ctypes++ class _PERFORMANCE_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("cb", ctypes.c_ulong),+ ("CommitTotal", ctypes.c_size_t),+ ("CommitLimit", ctypes.c_size_t),+ ("CommitPeak", ctypes.c_size_t),+ ("PhysicalTotal", ctypes.c_size_t),+ ("PhysicalAvailable", ctypes.c_size_t),+ ("SystemCache", ctypes.c_size_t),+ ("KernelTotal", ctypes.c_size_t),+ ("KernelPaged", ctypes.c_size_t),+ ("KernelNonpaged", ctypes.c_size_t),+ ("PageSize", ctypes.c_size_t),+ ("HandleCount", ctypes.c_ulong),+ ("ProcessCount", ctypes.c_ulong),+ ("ThreadCount", ctypes.c_ulong),+ ]++ info = _PERFORMANCE_INFORMATION()+ info.cb = ctypes.sizeof(_PERFORMANCE_INFORMATION)+ # kernel32 exports the K32-prefixed name only; the unprefixed one lives in psapi+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ if not kernel32.K32GetPerformanceInfo(ctypes.byref(info), info.cb):+ return None+ headroom = (int(info.CommitLimit) - int(info.CommitTotal)) * int(info.PageSize)+ return max(0, headroom // (1024 * 1024))+ except Exception: # noqa: BLE001+ return None++def _xpu_memory() -> tuple[Optional[int], Optional[int]]:try:import torchdiff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.pyindex fd6ef518665..df5fd58183f 100644--- a/studio/backend/core/inference/diffusion_small_host.py+++ b/studio/backend/core/inference/diffusion_small_host.py@@ -19,6 +19,8 @@ from .rocm_bf16 import is_rocm_torchSMALL_HOST_ENV = "UNSLOTH_DIFFUSION_SMALL_HOST"HOST_RAM_CHECK_ENV = "UNSLOTH_DIFFUSION_HOST_RAM_CHECK"+# test hook: caps every host reading the guards take (total, available, commit)+HOST_RAM_LIMIT_ENV = "UNSLOTH_DIFFUSION_HOST_RAM_LIMIT_MIB"SMALL_HOST_ATTR = "_unsloth_small_host"_MIB = 1024 * 1024@@ -79,6 +81,7 @@ class StoredComponent:dtype: str # dominant stored float dtype ("bfloat16", "float16", "float32", ...)# stored MiB of ``_keep_in_fp32_modules`` tensors: they convert to fp32 on the host even on the routekept_fp32_mib: int = 0+ library: str = ""def _keep_fp32_from_config(sub: Path) -> tuple[str, ...]:@@ -110,6 +113,10 @@ def stored_components(snapshot: Any) -> dict[str, StoredComponent]:root = Path(snapshot)if not root.is_dir():return out+ try:+ index = json.loads((root / "model_index.json").read_text(encoding = "utf-8"))+ except Exception: # noqa: BLE001+ index = {}for sub in sorted(p for p in root.iterdir() if p.is_dir()):totals: dict[str, int] = {}keep = _keep_fp32_from_config(sub) if sub.name.startswith("text_encoder") else ()@@ -120,8 +127,10 @@ def stored_components(snapshot: Any) -> dict[str, StoredComponent]:if not totals:continuedtype = max(totals.items(), key = lambda kv: kv[1])[0]+ entry = index.get(sub.name)+ library = str(entry[0]) if isinstance(entry, list) and entry and entry[0] else ""out[sub.name] = StoredComponent(- sub.name, -(-sum(totals.values()) // _MIB), dtype, -(-kept // _MIB)+ sub.name, -(-sum(totals.values()) // _MIB), dtype, -(-kept // _MIB), library)except Exception: # noqa: BLE001 - no claimreturn {}@@ -144,10 +153,33 @@ def resolve_snapshot_dir(repo_or_dir: Any, cache_dir: Any = None) -> Optional[Pareturn None+def _host_ram_limit_mib() -> int:+ try:+ return max(0, int((os.environ.get(HOST_RAM_LIMIT_ENV) or "").strip()))+ except ValueError:+ return 0+++def _capped(value: Optional[int], limit: int) -> Optional[int]:+ if limit <= 0:+ return value+ return limit if value is None else min(value, limit)++def host_ram_mib() -> tuple[Optional[int], Optional[int]]:- """(total, available) host MiB, both capped by an enforcing cgroup."""+ """(total, available) host MiB, both capped by an enforcing cgroup and the ``HOST_RAM_LIMIT_ENV`` test hook."""from .diffusion_memory import _available_system_memory_mib, _host_ram_capacity_mib- return _host_ram_capacity_mib(), _available_system_memory_mib()++ limit = _host_ram_limit_mib()+ return _capped(_host_ram_capacity_mib(), limit), _capped(_available_system_memory_mib(), limit)+++def host_commit_mib() -> Optional[int]:+ """Windows commit headroom MiB (None elsewhere or unreadable), capped by the ``HOST_RAM_LIMIT_ENV`` test hook."""+ from .diffusion_memory import _windows_commit_headroom_mib++ headroom = _windows_commit_headroom_mib()+ return None if headroom is None else _capped(headroom, _host_ram_limit_mib())def host_reserve_mib(total_mib: Optional[int]) -> int:@@ -172,6 +204,8 @@ class SmallHostDecision:total_mib: Optional[int] = Nonedense_host_mib: int = 0route_host_mib: int = 0+ commit_mib: Optional[int] = None+ dense_commit_mib: int = 0# component -> stored dtype it loads at (memory-mapped)storage_dtypes: dict[str, str] = field(default_factory = dict)refuse: Optional[str] = None@@ -185,9 +219,13 @@ def decide_small_host(host_total_mib: Optional[int],host_available_mib: Optional[int],lora_active: bool = False,+ host_commit_mib: Optional[int] = None,+ pread_libraries: tuple[str, ...] = (),) -> SmallHostDecision:"""Whether this pipeline load takes the small-host route. Only CUDA loads converting large bf16 components- (fp16 / fp32 compute) change; same-dtype loads already stay memory-mapped."""+ (fp16 / fp32 compute) change; same-dtype loads already stay memory-mapped. ``host_commit_mib`` (Windows)+ also routes a dense load whose commit need does not fit: on Windows commit exhaustion is an access+ violation in native code, not a Python error (#13432, #14513)."""if small_host_disabled():return SmallHostDecision(False, f"{SMALL_HOST_ENV}=0")if str(device) != "cuda":@@ -216,29 +254,50 @@ def decide_small_host(for n, c in converted.items())reserve = host_reserve_mib(host_total_mib)+ # Windows charges each copy-on-write safetensors view to commit until the load ends: stored bytes plus the+ # converted copy; a component read through ``pread`` (``pread_libraries``) holds no view. Linux / macOS do not+ # enforce commit.+ dense_commit = dense + int(+ sum(c.mib for c in converted.values() if c.library not in pread_libraries) * _CONVERT_MARGIN+ )storage = {name: comp.dtype for name, comp in converted.items()}forced = small_host_forced()if host_available_mib is None and not forced:return SmallHostDecision(False, "host RAM unreadable", dense_host_mib = dense)- fits = host_available_mib is not None and dense + reserve <= int(host_available_mib)+ commit = None if host_commit_mib is None else int(host_commit_mib)+ commit_fits = commit is None or dense_commit + reserve <= commit+ fits = (+ host_available_mib is not None+ and dense + reserve <= int(host_available_mib)+ and commit_fits+ )+ commit_note = (+ ""+ if commit is None+ else f", {commit} MiB commit headroom (dense needs ~{dense_commit} MiB)"+ )+ extra = {"commit_mib": commit, "dense_commit_mib": dense_commit}if fits and not forced:return SmallHostDecision(False,- f"dense {compute} load ({dense} MiB) fits {host_available_mib} MiB available host RAM",+ f"dense {compute} load ({dense} MiB) fits {host_available_mib} MiB available host RAM{commit_note}",host_available_mib,host_total_mib,dense,route,+ **extra,)if lora_active and not forced:# the int8 denoiser cannot carry adaptersreturn SmallHostDecision(False,- f"LoRA adapters need the dense denoiser (dense load ~{dense} MiB, {host_available_mib} MiB available)",+ f"LoRA adapters need the dense denoiser (dense load ~{dense} MiB, {host_available_mib} MiB available"+ f"{commit_note})",host_available_mib,host_total_mib,dense,route,+ **extra,)refuse = Noneif (@@ -251,10 +310,18 @@ def decide_small_host(f"{SMALL_HOST_ENV}=1"if forced and fitselse f"dense {compute} load needs ~{dense} MiB + {reserve} MiB reserve of host RAM, "- f"{host_available_mib} MiB available"+ f"{host_available_mib} MiB available{commit_note}")return SmallHostDecision(- True, why, host_available_mib, host_total_mib, dense, route, storage, refuse+ True,+ why,+ host_available_mib,+ host_total_mib,+ dense,+ route,+ storage_dtypes = storage,+ refuse = refuse,+ **extra,)diff --git a/studio/backend/core/inference/safetensors_pread.py b/studio/backend/core/inference/safetensors_pread.pyindex 1dfdfe98dce..6f3d53ed6be 100644--- a/studio/backend/core/inference/safetensors_pread.py+++ b/studio/backend/core/inference/safetensors_pread.py@@ -1,12 +1,16 @@# 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 video loads read fp32 safetensors shards with safetensors' ``pread`` backend instead of mmap (#9977).+"""Windows media loads read converted safetensors shards with safetensors' ``pread`` backend instead of mmap (#9977,+#14513).torch maps a shard copy-on-write and Windows charges the whole view to commit while transformers holds every shard-open: LTX-2's 48.7 GB fp32 Gemma3 loaded at bf16 needs ~73 GB, and torch's unchecked ``MapViewOfFile`` NULL is an-access violation on a 32 GB host. bf16 / fp16 shards keep mmap: their mapping is the loaded weight.-``UNSLOTH_SAFETENSORS_PREAD=0|1`` disables / forces it on any OS.+open, so a converting load commits the stored bytes next to the converted copy: LTX-2's 48.7 GB fp32 Gemma3 loaded at+bf16 needs ~73 GB, a 16.7 GB bf16 Qwen-Image encoder loaded at fp16 ~38 GB, and torch's unchecked ``MapViewOfFile``+NULL is an access violation. ``pread`` reads each tensor into its own buffer, freed once converted (what+transformers >= 5.17 does on Windows, huggingface/transformers#48341; ComfyUI and llama.cpp map read-only instead).+A shard loaded at its stored dtype keeps mmap: its mapping is the loaded weight, and the small-host route keeps it+paged from disk. ``UNSLOTH_SAFETENSORS_PREAD=0|1`` disables / forces it on any OS."""from __future__ import annotations@@ -16,13 +20,19 @@ import functoolsimport osimport sysimport threading-from typing import Any, Iterator+from typing import Any, Iterable, Iterator, OptionalPREAD_ENV = "UNSLOTH_SAFETENSORS_PREAD"_lock = threading.Lock()_depth = 0_original: Any = None+# per load thread, so concurrent media loads never share rules: (target dtype or None = fp32-only video rule, kept dirs)+_local = threading.local()+++def _active_rules() -> tuple[tuple[Optional[str], frozenset[str]], ...]:+ return getattr(_local, "rules", ())def pread_wanted() -> bool:@@ -35,36 +45,89 @@ def pread_wanted() -> bool:def _supports_backend(safe_open: Any) -> bool:- # safetensors < 0.8 has no backend keyword, and an unknown keyword is a TypeError on every load.- return "backend" in (getattr(safe_open, "__text_signature__", None) or "")+ # safetensors < 0.8 has no backend keyword (TypeError); wrappers drop __text_signature__, so read the innermost.+ fn = safe_open+ for _ in range(8):+ inner = getattr(fn, "__wrapped__", None)+ if inner is None:+ break+ fn = inner+ return "backend" in (getattr(fn, "__text_signature__", None) or "")+++def pread_available() -> bool:+ """Whether a scope opened now routes shards through ``pread`` (Windows, safetensors >= 0.8, not disabled)."""+ if not pread_wanted():+ return False+ try:+ from safetensors import safe_open+ return _supports_backend(safe_open)+ except Exception: # noqa: BLE001+ return False-def _stored_mostly_fp32(filename: Any) -> bool:+def _backend_for(filename: Any) -> Optional[str]:+ """ "pread", "keep" (a component the small-host route loads at its stored dtype) or None (caller's default)."""from pathlib import Pathfrom .diffusion_small_host import _safetensors_bytes_by_dtype- stored = _safetensors_bytes_by_dtype(Path(filename))- return stored.get("float32", 0) * 2 > sum(stored.values())+ path = Path(filename)+ rules = _active_rules()+ if any(path.parent.name in keep for _, keep in rules):+ return "keep"+ stored = {k: v for k, v in _safetensors_bytes_by_dtype(path).items() if k != "kept"}+ if not stored:+ return None+ dominant = max(stored.items(), key = lambda kv: kv[1])[0]+ for to, _ in rules:+ if to is None and stored.get("float32", 0) * 2 > sum(stored.values()):+ return "pread"+ if to is not None and dominant in ("bfloat16", "float16", "float32") and dominant != to:+ return "pread"+ return None+++def _core_pread_below(safe_open: Any) -> bool:+ # unsloth's Windows pread patch (transformers < 5.17) may sit underneath+ fn = safe_open+ for _ in range(8):+ if fn is None:+ return False+ if getattr(fn, "_unsloth_windows_pread", False):+ return True+ fn = getattr(fn, "__wrapped__", None)+ return Falsedef _with_pread(safe_open: Any) -> Any:@functools.wraps(safe_open)def pread_safe_open(filename: Any, *args: Any, **kwargs: Any) -> Any:# transformers 5.13 - 5.16 pass backend="mmap" explicitly; 5.17 already picks pread on Windows (#48341).- if kwargs.get("backend") in (None, "mmap") and _stored_mostly_fp32(filename):+ if not _active_rules():+ return safe_open(filename, *args, **kwargs)+ choice = _backend_for(filename)+ if choice == "pread" and kwargs.get("backend") in (None, "mmap"):kwargs["backend"] = "pread"+ elif choice == "keep" and kwargs.get("backend") == "pread":+ # transformers >= 5.17 asks for pread on Windows itself; the small-host route needs this shard paged+ kwargs["backend"] = "mmap"+ if choice != "pread" and _core_pread_below(safe_open):+ # this scope decides inside a media load, over unsloth's patch too+ kwargs["_unsloth_keep_mmap"] = Truereturn safe_open(filename, *args, **kwargs)return pread_safe_open@contextlib.contextmanager-def pread_safetensors() -> Iterator[bool]:- """Route ``transformers.modeling_utils.safe_open`` of fp32 shards through ``pread``; yields whether it did. Nests; a- concurrent load in another thread only gets the same bytes through another backend."""+def pread_safetensors(convert_to: Any = None, keep: Iterable[str] = ()) -> Iterator[bool]:+ """Route ``transformers.modeling_utils.safe_open`` of fp32 shards, and with ``convert_to`` of every shard stored in+ another dtype outside the ``keep`` component dirs, through ``pread``; yields whether it did. Nests; a concurrent+ load in another thread only gets the same bytes through another backend."""global _depth, _originalinstalled = False+ previous_rules = Noneif pread_wanted():try:import transformers.modeling_utils as modeling_utils@@ -80,10 +143,15 @@ def pread_safetensors() -> Iterator[bool]:_depth += 1except Exception: # noqa: BLE001 - the mmap backend still loads wherever commit allowsinstalled = False+ if installed:+ to = None if convert_to is None else str(convert_to).replace("torch.", "")+ previous_rules = _active_rules()+ _local.rules = previous_rules + ((to, frozenset(keep)),)try:yield installedfinally:if installed:+ _local.rules = previous_ruleswith _lock:_depth -= 1if not _depth:diff --git a/studio/backend/tests/test_diffusion_small_host.py b/studio/backend/tests/test_diffusion_small_host.pyindex 67df89aca4e..b00d075c7bc 100644--- a/studio/backend/tests/test_diffusion_small_host.py+++ b/studio/backend/tests/test_diffusion_small_host.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport jsonimport struct+import sysimport typesimport pytest@@ -104,6 +105,179 @@ def test_refuses_before_loading_when_even_the_route_cannot_fit(monkeypatch):assert _decide(QWEN, dtype = torch.float32, total = 16 * 1024, available = 14000).refuse is None+# #14513: Qwen-Image GGUF on a 48 GB Windows host with a 16 GB fixed pagefile. The GGUF DiT is already built (and+# already out of both readings), so only the 16.7 GB bf16 encoder converts; its fp16 load committed ~2x dense.+QWEN_GGUF_COMPANIONS = {+ "text_encoder": sh.StoredComponent("text_encoder", 16717, "bfloat16"),+ "vae": sh.StoredComponent("vae", 242, "bfloat16"),+}+WIN_TOTAL = 48 * 1024+++def test_windows_commit_headroom_routes_a_dense_load_that_fits_physical_ram():+ # physical RAM alone says the dense load fits, which is what crashed+ base = _decide(QWEN_GGUF_COMPANIONS, total = WIN_TOTAL, available = 30 * 1024)+ assert not base.engaged and base.dense_commit_mib == 2 * base.dense_host_mib+ d = _decide(+ QWEN_GGUF_COMPANIONS, total = WIN_TOTAL, available = 30 * 1024, host_commit_mib = 30 * 1024+ )+ assert d.engaged and d.refuse is None and d.commit_mib == 30 * 1024+ assert d.storage_dtypes == {"text_encoder": "bfloat16"}+ assert "commit headroom" in d.reason+ # enough commit for the source views plus the converted copy: dense, as before+ d = _decide(+ QWEN_GGUF_COMPANIONS, total = WIN_TOTAL, available = 30 * 1024, host_commit_mib = 50 * 1024+ )+ assert not d.engaged and "commit headroom" in d.reason+++def test_pread_read_components_need_no_source_view_commit():+ # with the encoder read through pread (Windows, safetensors >= 0.8), the #14513 load commits ~one fp16 copy and+ # stays dense on the reporter's headroom; a diffusers-loaded or mmap-read component still counts its view+ te = sh.StoredComponent("text_encoder", 16717, "bfloat16", 0, "transformers")+ comps = {"text_encoder": te, "vae": QWEN_GGUF_COMPANIONS["vae"]}+ mapped = _decide(comps, total = WIN_TOTAL, available = 30 * 1024, host_commit_mib = 30 * 1024)+ read = _decide(+ comps,+ total = WIN_TOTAL,+ available = 30 * 1024,+ host_commit_mib = 30 * 1024,+ pread_libraries = ("transformers",),+ )+ assert mapped.engaged and not read.engaged+ assert read.dense_commit_mib == read.dense_host_mib+ dit = {"transformer": sh.StoredComponent("transformer", 20000, "bfloat16", 0, "diffusers")}+ d = _decide(dit, total = 128 * 1024, available = 100 * 1024, pread_libraries = ("transformers",))+ assert d.dense_commit_mib == 2 * d.dense_host_mib+++def test_stored_components_record_the_loading_library(tmp_path):+ from safetensors.torch import save_file++ (tmp_path / "model_index.json").write_text(+ json.dumps(+ {+ "text_encoder": ["transformers", "Qwen2_5_VLForConditionalGeneration"],+ "vae": ["diffusers", "X"],+ }+ )+ )+ for name in ("text_encoder", "vae", "transformer"):+ (tmp_path / name).mkdir()+ save_file(+ {"w": torch.zeros(8, 8, dtype = torch.bfloat16)},+ str(tmp_path / name / "model.safetensors"),+ )+ comps = sh.stored_components(tmp_path)+ assert comps["text_encoder"].library == "transformers"+ assert comps["vae"].library == "diffusers"+ assert comps["transformer"].library == ""+++def test_commit_headroom_only_routes_and_never_refuses():+ # the route's refusal stays on physical RAM: commit can grow with a system-managed pagefile+ d = _decide(QWEN_GGUF_COMPANIONS, total = WIN_TOTAL, available = 30 * 1024, host_commit_mib = 0)+ assert d.engaged and d.refuse is None+ d = _decide(QWEN_GGUF_COMPANIONS, total = WIN_TOTAL, available = 4000, host_commit_mib = 60 * 1024)+ assert d.engaged and d.refuse and "Not enough system RAM" in d.refuse+++def test_unreadable_commit_keeps_every_decision():+ # Linux / macOS (and an unreadable Windows counter) pass None: byte-identical decisions to the physical check+ for comps, dtype, total, available, lora in [+ (FLUX1, torch.float16, KAGGLE_TOTAL, KAGGLE_AVAILABLE, False),+ (FLUX1, torch.float16, 64 * 1024, 58 * 1024, False),+ (FLUX1, torch.float16, KAGGLE_TOTAL, KAGGLE_AVAILABLE, True),+ (QWEN, torch.float32, 16 * 1024, 14000, False),+ (QWEN_GGUF_COMPANIONS, torch.float16, WIN_TOTAL, 30 * 1024, False),+ ]:+ a = _decide(comps, dtype, total, available, lora_active = lora)+ b = _decide(comps, dtype, total, available, lora_active = lora, host_commit_mib = None)+ assert (a.engaged, a.refuse, a.reason, a.storage_dtypes) == (+ b.engaged,+ b.refuse,+ b.reason,+ b.storage_dtypes,+ )+ # FLUX.1 fp16 with 58 GB free on a 64 GB host stays dense (no transient margin on the physical side)+ assert not _decide(FLUX1, total = 64 * 1024, available = 58 * 1024).engaged+++def test_lora_with_tight_commit_keeps_the_dense_denoiser():+ d = _decide(+ FLUX1, total = 128 * 1024, available = 100 * 1024, host_commit_mib = 20 * 1024, lora_active = True+ )+ assert (+ not d.engaged and d.refuse is None and "LoRA" in d.reason and "commit headroom" in d.reason+ )+++def test_host_ram_limit_env_caps_the_guard_view(monkeypatch):+ monkeypatch.setattr(dm, "_host_ram_capacity_mib", lambda: 32000)+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: 20000)+ monkeypatch.setattr(dm, "_windows_commit_headroom_mib", lambda: 25000)+ monkeypatch.setenv(sh.HOST_RAM_LIMIT_ENV, "6144")+ assert sh.host_ram_mib() == (6144, 6144)+ assert sh.host_commit_mib() == 6144+ monkeypatch.setenv(sh.HOST_RAM_LIMIT_ENV, "90000")+ assert sh.host_ram_mib() == (32000, 20000)+ assert sh.host_commit_mib() == 25000+ monkeypatch.setenv(sh.HOST_RAM_LIMIT_ENV, "not-a-number")+ assert sh.host_ram_mib() == (32000, 20000)+ # no commit reading (Linux / macOS) stays None under the hook+ monkeypatch.setattr(dm, "_windows_commit_headroom_mib", lambda: None)+ monkeypatch.setenv(sh.HOST_RAM_LIMIT_ENV, "6144")+ assert sh.host_commit_mib() is None+++def test_windows_commit_headroom_reader_reports_a_value_on_windows():+ # the reader once called an unexported kernel32 name and silently returned None, leaving the guard on the+ # physical reading; on Windows it must reach the real API, elsewhere None is by design+ if sys.platform != "win32":+ assert dm._windows_commit_headroom_mib() is None+ return+ value = dm._windows_commit_headroom_mib()+ assert value is not None and value >= 0+++def test_the_pipeline_decision_passes_the_commit_headroom_and_logs_a_dense_decision(+ tmp_path, monkeypatch+):+ from core.inference import diffusion as dif++ records = []++ class _LogSpy:+ def info(self, event, *args):+ records.append(event % args if args else event)++ monkeypatch.setattr(dif, "host_ram_mib", lambda: (WIN_TOTAL, 30 * 1024))+ monkeypatch.setattr(dif, "stored_components", lambda snapshot: dict(QWEN_GGUF_COMPANIONS))+ monkeypatch.setattr(dif, "logger", _LogSpy())++ monkeypatch.setattr(dif, "pread_available", lambda: False)++ def decide(commit):+ monkeypatch.setattr(dif, "host_commit_mib", lambda: commit)+ return dif.DiffusionBackend()._small_host_decision(+ str(tmp_path),+ {"transformer": object()},+ types.SimpleNamespace(device = "cuda"),+ torch.float16,+ lora_active = False,+ )++ d = decide(None)+ assert not d.engaged and d.refuse is None+ assert records[-1] == f"diffusion.small_host: engaged=False ({d.reason})"+ d = decide(30 * 1024)+ assert d.engaged and d.refuse is None and d.commit_mib == 30 * 1024+ assert (+ records[-1].startswith("diffusion.small_host: engaged=True (")+ and "commit headroom" in records[-1]+ )++def test_lora_keeps_the_dense_load():d = _decide(FLUX1, lora_active = True)assert not d.engaged and d.refuse is None and "LoRA" in d.reasondiff --git a/studio/backend/tests/test_safetensors_pread.py b/studio/backend/tests/test_safetensors_pread.pyindex 7e37c3ebc2c..6655810ab1f 100644--- a/studio/backend/tests/test_safetensors_pread.py+++ b/studio/backend/tests/test_safetensors_pread.py@@ -32,7 +32,7 @@ requires_backend = pytest.mark.skipif(def _clean(monkeypatch):monkeypatch.delenv(sp.PREAD_ENV, raising = False)yield- assert sp._depth == 0 and sp._original is None+ assert sp._depth == 0 and sp._original is None and not sp._active_rules()def _record_backends(monkeypatch):@@ -202,3 +202,293 @@ def test_video_load_runs_inside_the_scope():source = inspect.getsource(VideoBackend._run_load)scope = source.index("with pread_safetensors():")assert scope < source.index("self.load_pipeline(**kwargs)", scope)+++@requires_backend+ "stored, convert_to, keep, expected",+ [+ (torch.bfloat16, torch.float16, (), "pread"),+ (torch.bfloat16, torch.float32, (), "pread"),+ (torch.float16, torch.float16, (), None),+ (torch.bfloat16, torch.bfloat16, (), None),+ # the small-host route loads this component at its stored dtype: its mapping is the weight+ (torch.bfloat16, torch.float16, ("text_encoder",), None),+ (torch.int8, torch.float16, (), None),+ (torch.bfloat16, None, (), None),+ # fp32 loaded at fp32 (CPU fallback) is the loaded weight; fp32 converted down reads through pread+ (torch.float32, torch.float32, (), None),+ (torch.float32, torch.bfloat16, (), "pread"),+ # the video scope (no target dtype) keeps its fp32-only rule+ (torch.float32, None, (), "pread"),+ ],+)+def test_converted_shard_backend_choice(monkeypatch, tmp_path, stored, convert_to, keep, expected):+ from safetensors.torch import save_file++ comp = tmp_path / "text_encoder"+ comp.mkdir()+ path = comp / "model.safetensors"+ save_file({"w": torch.zeros(64, 64, dtype = stored)}, str(path))+ monkeypatch.setattr(sys, "platform", "win32")+ seen = _record_backends(monkeypatch)+ with sp.pread_safetensors(convert_to = convert_to, keep = keep):+ with modeling_utils.safe_open(str(path), framework = "pt", device = "cpu") as handle:+ handle.get_slice("w")[...]+ assert seen == [expected]+ assert not sp._active_rules()+++@requires_backend+def test_converting_bf16_load_reads_with_pread_and_matches_mmap(monkeypatch, tmp_path):+ """#14513: a bf16 encoder loaded at fp16 (fp16-only GPU) reads through pread, weights unchanged."""+ model_cls = _save_llama(tmp_path, torch.bfloat16)+ seen = _record_backends(monkeypatch)+ dense = model_cls.from_pretrained(tmp_path, dtype = torch.float16)+ assert seen and set(seen) <= MMAP++ monkeypatch.setenv(sp.PREAD_ENV, "1")+ seen.clear()+ with sp.pread_safetensors(convert_to = torch.float16) as engaged:+ assert engaged is True+ loaded = model_cls.from_pretrained(tmp_path, dtype = torch.float16)+ assert seen and set(seen) == {"pread"}++ expected = dense.state_dict()+ for name, tensor in loaded.state_dict().items():+ assert tensor.dtype == torch.float16+ assert torch.equal(tensor, expected[name]), name+++_COMMIT_ARM = r"""+import ctypes, sys, torch+sys.path.insert(0, sys.argv[1])+import core.inference.safetensors_pread as sp+from transformers import LlamaForCausalLM++class PMC(ctypes.Structure):+ _fields_ = [("cb", ctypes.c_ulong), ("PageFaultCount", ctypes.c_ulong)] + [+ (n, ctypes.c_size_t) for n in ("PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage",+ "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage", "QuotaNonPagedPoolUsage", "PagefileUsage",+ "PeakPagefileUsage")]++k = ctypes.WinDLL("kernel32", use_last_error = True)+k.GetCurrentProcess.restype = ctypes.c_void_p+k.K32GetProcessMemoryInfo.argtypes = [ctypes.c_void_p, ctypes.POINTER(PMC), ctypes.c_ulong]++def counters():+ c = PMC(); c.cb = ctypes.sizeof(PMC)+ assert k.K32GetProcessMemoryInfo(k.GetCurrentProcess(), ctypes.byref(c), c.cb), ctypes.get_last_error()+ return c++base = counters().PagefileUsage+if sys.argv[3] == "pread":+ with sp.pread_safetensors(convert_to = torch.float16):+ LlamaForCausalLM.from_pretrained(sys.argv[2], dtype = torch.float16)+else:+ LlamaForCausalLM.from_pretrained(sys.argv[2], dtype = torch.float16)+print("PEAK_MIB", (counters().PeakPagefileUsage - base) >> 20)+"""++[email protected](sys.platform != "win32", reason = "process commit is a Windows counter")+@requires_backend+def test_windows_converting_load_commits_about_one_copy(tmp_path):+ """Real Windows commit for a 1.5 GB bf16 checkpoint loaded at fp16: mmap charges the stored bytes on top of the+ fp16 copy, pread does not."""+ import subprocess+ import warnings+ from pathlib import Path++ from transformers import LlamaConfig, LlamaForCausalLM++ config = LlamaConfig(+ vocab_size = 32000,+ hidden_size = 2048,+ intermediate_size = 5632,+ num_hidden_layers = 12,+ num_attention_heads = 16,+ num_key_value_heads = 16,+ )+ with torch.device("meta"):+ model = LlamaForCausalLM(config)+ model = model.to_empty(device = "cpu").to(torch.bfloat16)+ with torch.no_grad():+ for p in model.parameters():+ p.zero_()+ model.save_pretrained(tmp_path, max_shard_size = "400MB")+ stored_mib = sum(f.stat().st_size for f in tmp_path.glob("*.safetensors")) >> 20+ del model++ backend = str(Path(sp.__file__).resolve().parents[2])+ peaks = {}+ for arm in ("mmap", "pread"):+ out = subprocess.run(+ [sys.executable, "-c", _COMMIT_ARM, backend, str(tmp_path), arm],+ capture_output = True,+ text = True,+ timeout = 900,+ )+ assert out.returncode == 0, out.stderr[-3000:]+ peaks[arm] = int(+ next(l for l in out.stdout.splitlines() if l.startswith("PEAK_MIB")).split()[1]+ )+ warnings.warn(f"windows commit for a {stored_mib} MiB bf16 -> fp16 load: {peaks}")+ # windows-latest, 1426 MiB: mmap 3477, pread 2077 (both carry ~0.6 GB of load-time allocations besides the+ # fp16 copy); pread drops the copy-on-write charge for the stored bytes+ assert peaks["mmap"] - peaks["pread"] >= stored_mib * 0.85, peaks+++@requires_backend+ "stored, convert_to, keep, sent",+ [+ (torch.bfloat16, torch.float16, (), None), # converted: this scope asks for pread itself+ (+ torch.bfloat16,+ torch.bfloat16,+ (),+ True,+ ), # same dtype: mmap, unsloth's pread patch told to keep it+ (+ torch.bfloat16,+ torch.float16,+ ("text_encoder",),+ True,+ ), # small-host route keeps the encoder mapped+ ],+)+def test_unsloth_windows_pread_patch_below_keeps_this_scopes_mmap_choices(+ monkeypatch, tmp_path, stored, convert_to, keep, sent+):+ """unsloth (transformers 5.0 - 5.16 on Windows) wraps safe_open to default every CPU open to pread; inside a media+ load this scope's mmap choices win via ``_unsloth_keep_mmap``."""+ import functools++ from safetensors.torch import save_file++ comp = tmp_path / "text_encoder"+ comp.mkdir()+ path = comp / "model.safetensors"+ save_file({"w": torch.zeros(64, 64, dtype = stored)}, str(path))+ received = []+ real = modeling_utils.safe_open++ @functools.wraps(real)+ def core_patch(*args, **kwargs):+ received.append(kwargs.pop("_unsloth_keep_mmap", None))+ return real(*args, **kwargs)++ core_patch._unsloth_windows_pread = True+ monkeypatch.setattr(modeling_utils, "safe_open", core_patch)+ monkeypatch.setattr(sys, "platform", "win32")+ with sp.pread_safetensors(convert_to = convert_to, keep = keep):+ with modeling_utils.safe_open(str(path), framework = "pt", device = "cpu") as handle:+ handle.get_slice("w")[...]+ assert received == [sent]+++@requires_backend[email protected]("passed, expected", [("pread", "mmap"), (None, None), ("mmap", "mmap")])+def test_kept_shard_overrides_a_callers_pread(monkeypatch, tmp_path, passed, expected):+ """transformers >= 5.17 passes backend="pread" on Windows itself; a shard the small-host route keeps stays mapped."""+ from safetensors.torch import save_file++ comp = tmp_path / "text_encoder"+ comp.mkdir()+ path = comp / "model.safetensors"+ save_file({"w": torch.zeros(64, 64, dtype = torch.bfloat16)}, str(path))+ monkeypatch.setattr(sys, "platform", "win32")+ seen = _record_backends(monkeypatch)+ kwargs = {} if passed is None else {"backend": passed}+ with sp.pread_safetensors(convert_to = torch.float16, keep = ("text_encoder",)):+ with modeling_utils.safe_open(str(path), framework = "pt", device = "cpu", **kwargs) as handle:+ handle.get_slice("w")[...]+ assert seen == [expected]+++@requires_backend+def test_concurrent_loads_keep_their_own_rules(monkeypatch, tmp_path):+ """An image load's keep / convert rules never reach a video load running in another thread (multi-model policy)."""+ from safetensors.torch import save_file++ image, video = tmp_path / "image" / "text_encoder", tmp_path / "video" / "text_encoder"+ for d, dtype in ((image, torch.bfloat16), (video, torch.float32)):+ d.mkdir(parents = True)+ save_file({"w": torch.zeros(64, 64, dtype = dtype)}, str(d / "model.safetensors"))+ monkeypatch.setattr(sys, "platform", "win32")+ seen = {}+ real = modeling_utils.safe_open++ def spy(filename, *args, **kwargs):+ seen[str(filename)] = kwargs.get("backend")+ return real(filename, *args, **kwargs)++ spy.__text_signature__ = real.__text_signature__+ monkeypatch.setattr(modeling_utils, "safe_open", spy)+ opened, release = threading.Event(), threading.Event()++ def video_load():+ with sp.pread_safetensors():+ with modeling_utils.safe_open(+ str(video / "model.safetensors"), framework = "pt", device = "cpu"+ ) as h:+ h.get_slice("w")[...]+ opened.set()+ release.wait(5)++ with sp.pread_safetensors(convert_to = torch.float16, keep = ("text_encoder",)):+ worker = threading.Thread(target = video_load)+ worker.start()+ assert opened.wait(5)+ with modeling_utils.safe_open(+ str(image / "model.safetensors"), framework = "pt", device = "cpu"+ ) as h:+ h.get_slice("w")[...]+ release.set()+ worker.join(5)+ assert (+ seen[str(video / "model.safetensors")] == "pread"+ ) # its fp32 encoder, despite the image's keep entry+ assert seen[str(image / "model.safetensors")] is None # the image's routed encoder stays mapped+++@requires_backend+def test_a_thread_outside_any_scope_keeps_unsloths_default(monkeypatch, tmp_path):+ """While a video scope holds the process-wide wrapper, an eager image-side load in another thread (HiDream's Llama)+ gets no keep flag, so unsloth's Windows pread patch still applies there."""+ import functools++ from safetensors.torch import save_file++ path = tmp_path / "text_encoder_4" / "model.safetensors"+ path.parent.mkdir()+ save_file({"w": torch.zeros(64, 64, dtype = torch.bfloat16)}, str(path))+ received = []+ real = modeling_utils.safe_open++ @functools.wraps(real)+ def core_patch(*args, **kwargs):+ received.append(kwargs.pop("_unsloth_keep_mmap", None))+ return real(*args, **kwargs)++ core_patch._unsloth_windows_pread = True+ monkeypatch.setattr(modeling_utils, "safe_open", core_patch)+ monkeypatch.setattr(sys, "platform", "win32")+ entered, release = threading.Event(), threading.Event()++ def video_load():+ with sp.pread_safetensors():+ entered.set()+ release.wait(5)++ worker = threading.Thread(target = video_load)+ worker.start()+ assert entered.wait(5)+ try:+ with modeling_utils.safe_open(str(path), framework = "pt", device = "cpu") as handle:+ handle.get_slice("w")[...]+ finally:+ release.set()+ worker.join(5)+ assert received == [None]