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 diffusion: write the runtime int8 / fp8 prequant cache after the load, off the first image (#15202)

Daniel Handa0542b94a15
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 8bdb03899a0..7d21dfeb8d4 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -9291,6 +9291,7 @@ class DiffusionBackend:
state_committed = False
load_bg_compile = None
state = None
+ pending_cache_write = None
try:
self._raise_if_load_cancelled(_load_token)
if (
@@ -10162,7 +10163,7 @@ class DiffusionBackend:
transformer_quant_engaged = cached_scheme
elif engaged and len(engaged) == len(denoisers):
transformer_quant_engaged = engaged[0]
- self._save_pipeline_quant_to_cache(
+ pending_cache_write = self._save_pipeline_quant_to_cache(
pipe,
fam,
denoisers,
@@ -10172,7 +10173,10 @@ class DiffusionBackend:
cancel_check = lambda: self._raise_if_load_cancelled(
_load_token
),
+ defer = True,
)
+ if not hasattr(pending_cache_write, "start"):
+ pending_cache_write = None
self._raise_if_load_cancelled(_load_token)
else:
# A clean decline can remain bf16; a partial in-place conversion is unusable.
@@ -11097,6 +11101,15 @@ class DiffusionBackend:
raise
finally:
self._stop_load_prefetch()
+ if pending_cache_write is not None:
+ try:
+ if state_committed:
+ pending_cache_write.start()
+ else:
+ pending_cache_write.discard()
+ except Exception: # noqa: BLE001 - a cache write never fails a load
+ pass
+ pending_cache_write = None
# Pre-commit failure: roll back the process-wide mutations (symmetric with _unload_locked).
if not state_committed:
# Never published, so _unload_locked cannot reach them: the pinners would keep the encoders.
@@ -11638,9 +11651,10 @@ class DiffusionBackend:
base: Optional[str],
source_base: Optional[str],
cancel_check: Optional[Callable[[], None]] = None,
- ) -> Optional[str]:
+ defer: bool = False,
+ ) -> Any:
"""Cache a load-time quantized ``transformer`` (single denoiser only, the cache keys that component; no LoRA).
- Never raises."""
+ ``defer`` may return a ``PendingWrite`` for the caller to start once the load is published. Never raises."""
try:
names = [attr for attr, _module in (denoisers or ())]
if fam is None or names != ["transformer"] or _has_active_lora(loras):
@@ -11654,6 +11668,7 @@ class DiffusionBackend:
source_base = source_base,
logger = logger,
cancel_check = cancel_check,
+ defer = defer,
)
except Exception as exc: # noqa: BLE001 - a cache write never fails a load
logger.warning("diffusion.prequant_cache: skipped (%s)", exc)
@@ -14984,6 +14999,13 @@ class DiffusionBackend:
def _unload_locked(self) -> None:
release_load_budget_fraction("image")
+ # Let a background prequant write finish so the next load never shares host RAM with it.
+ prequant_cache = sys.modules.get(f"{__package__}.diffusion_prequant_cache")
+ if prequant_cache is not None:
+ try:
+ prequant_cache.finish_background_writes(logger = logger)
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
state = self._state
if state is None:
return
diff --git a/studio/backend/core/inference/diffusion_prequant_cache.py b/studio/backend/core/inference/diffusion_prequant_cache.py
index 3327233e5db..1fa443a4b4d 100644
--- a/studio/backend/core/inference/diffusion_prequant_cache.py
+++ b/studio/backend/core/inference/diffusion_prequant_cache.py
@@ -16,10 +16,13 @@ ENV:
UNSLOTH_DIFFUSION_PREQUANT_CACHE 0 disables lookups and saves (default on)
UNSLOTH_DIFFUSION_PREQUANT_CACHE_DIR cache root (default <studio cache>/diffusion_prequant_cache)
UNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GB LRU budget in GB (default 40; 0 disables eviction)
+ UNSLOTH_DIFFUSION_PREQUANT_CACHE_ASYNC 0 writes a pipeline load's build before the load returns (default: on a
+ background thread once the load is published)
"""
from __future__ import annotations
+import atexit
import contextlib
import hashlib
import json
@@ -40,6 +43,7 @@ from . import hub_reachability as _reach
ENV_MODE = "UNSLOTH_DIFFUSION_PREQUANT_CACHE"
ENV_DIR = "UNSLOTH_DIFFUSION_PREQUANT_CACHE_DIR"
ENV_MAX_GB = "UNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GB"
+ENV_ASYNC = "UNSLOTH_DIFFUSION_PREQUANT_CACHE_ASYNC"
DEFAULT_MAX_GB = 40.0
# Bump when anything about how Studio quantizes at load changes in a way the key below does not already see.
@@ -96,6 +100,11 @@ def enabled() -> bool:
return raw not in ("0", "off", "false", "no", "none")
+def async_enabled() -> bool:
+ raw = (os.environ.get(ENV_ASYNC) or "").strip().lower()
+ return raw not in ("0", "off", "false", "no", "none")
+
+
def cache_root() -> Path:
raw = (os.environ.get(ENV_DIR) or "").strip()
if raw:
@@ -890,9 +899,11 @@ def write_streaming_safetensors(
metadata: Optional[dict] = None,
cancel_check: Optional[Any] = None,
hasher: Optional[Any] = None,
+ release: bool = False,
) -> int:
"""Write ``tensors`` as safetensors one tensor at a time on the host; returns the file size.
- Ordered like ``save_file`` (dtype size desc, then name) so every tensor stays aligned for mmap."""
+ Ordered like ``save_file`` (dtype size desc, then name) so every tensor stays aligned for mmap. ``release`` pops
+ each tensor from ``tensors`` once written, so a caller's last reference frees it during the write."""
import torch
order = sorted(tensors.items(), key = lambda kv: (-kv[1].element_size(), kv[0]))
@@ -911,6 +922,8 @@ def write_streaming_safetensors(
"data_offsets": [offset, offset + size],
}
offset += size
+ names = [name for name, _tensor in order]
+ order = tensor = None
blob = json.dumps(header, separators = (",", ":")).encode("utf-8")
blob += b" " * ((8 - len(blob) % 8) % 8)
@@ -922,17 +935,22 @@ def write_streaming_safetensors(
with open(path, "wb") as fh:
put(struct.pack("<Q", len(blob)))
put(blob)
- for _name, tensor in order:
+ for name in names:
if cancel_check is not None:
cancel_check()
+ tensor = tensors.pop(name) if release else tensors[name]
if tensor.numel() == 0:
continue
+ if isinstance(tensor, _FileSlice):
+ tensor.stream(put, cancel_check)
+ del tensor
+ continue
if isinstance(tensor, _FlatRef):
tensor = tensor.tensor()
flat = tensor.detach().contiguous().reshape(-1).view(torch.uint8)
host = flat.cpu() if flat.device.type != "cpu" else flat
put(memoryview(host.numpy()))
- del host, flat
+ del host, flat, tensor
fh.flush()
os.fsync(fh.fileno())
return 8 + len(blob) + offset
@@ -978,6 +996,78 @@ class _FlatRef:
return self._get()
+class _FileSlice:
+ """A view of an mmapped shard held as (fd, offset, size), not a reference that would pin the whole mapping.
+ Read back with ``pread`` from the same inode; a changed size / mtime fails the write."""
+
+ __slots__ = ("fd", "offset", "nbytes", "dtype", "shape", "_numel", "_esize", "stamp")
+
+ def __init__(self, fd: int, offset: int, tensor: Any, stamp: tuple) -> None:
+ self.fd = fd
+ self.offset = int(offset)
+ self.dtype = tensor.dtype
+ self.shape = tuple(tensor.shape)
+ self._numel = int(tensor.numel())
+ self._esize = int(tensor.element_size())
+ self.nbytes = self._numel * self._esize
+ self.stamp = stamp
+
+ def numel(self) -> int:
+ return self._numel
+
+ def element_size(self) -> int:
+ return self._esize
+
+ def stream(
+ self,
+ put: Any,
+ cancel_check: Optional[Any] = None,
+ ) -> None:
+ st = os.fstat(self.fd)
+ if (st.st_size, st.st_mtime_ns) != self.stamp:
+ raise OSError("a mapped source shard changed during the cache write")
+ pos, end = self.offset, self.offset + self.nbytes
+ while pos < end:
+ if cancel_check is not None:
+ cancel_check()
+ data = os.pread(self.fd, min(_HASH_CHUNK, end - pos), pos)
+ if not data:
+ raise OSError("short read from a mapped source shard")
+ put(data)
+ pos += len(data)
+
+
+def _file_regions() -> list:
+ """``[(start, end, file_offset, dev, inode, path)]`` sorted by start; empty without /proc/self/maps."""
+ out = []
+ try:
+ with open("/proc/self/maps", "r", encoding = "utf-8", errors = "replace") as fh:
+ for line in fh:
+ parts = line.split(None, 5)
+ if len(parts) < 6:
+ continue
+ path = parts[5].strip()
+ if not path.startswith("/") or path.endswith("(deleted)") or parts[4] == "0":
+ continue
+ lo, hi = (int(x, 16) for x in parts[0].split("-"))
+ major, minor = (int(x, 16) for x in parts[3].split(":"))
+ out.append((lo, hi, int(parts[2], 16), (major, minor), int(parts[4]), path))
+ except (OSError, ValueError):
+ return []
+ out.sort()
+ return out
+
+
+def _region_of(regions: list, ptr: int, nbytes: int) -> Optional[tuple]:
+ import bisect
+
+ i = bisect.bisect_right(regions, (ptr, float("inf"))) - 1
+ if i < 0:
+ return None
+ region = regions[i]
+ return region if region[0] <= ptr and ptr + nbytes <= region[1] else None
+
+
def _flatten(state_dict: dict) -> tuple[dict, dict]:
"""``(flat tensors, header)`` in ``save_prequant_safetensors``'s layout; peak extra VRAM is one param's clone."""
from .prequant_safetensors import (
@@ -1053,9 +1143,12 @@ def save_runtime_quant(
component: str = "transformer",
logger: Any = None,
cancel_check: Optional[Any] = None,
-) -> Optional[str]:
+ defer: bool = False,
+) -> Any:
"""Persist a just-quantized transformer; returns the artifact path or None (logged). Never raises.
- ``base_repo`` is recorded as ``base_model_id``; ``source_base`` is where the dense weights were read (a mirror)."""
+ ``base_repo`` is recorded as ``base_model_id``; ``source_base`` is where the dense weights were read (a mirror).
+ ``defer`` runs every check now and returns a ``PendingWrite`` owning host tensors only; falls back to the
+ synchronous write when the build is off-host, RAM is short, another write runs, or ASYNC=0."""
if not enabled():
return None
t0 = time.perf_counter()
@@ -1072,6 +1165,8 @@ def save_runtime_quant(
raise
stack = contextlib.ExitStack()
+ handed_off = False
+ flat = header = state_dict = job = None
try:
info = dict(getattr(transformer, "_unsloth_runtime_quant_info", None) or {})
scheme = info.get("scheme")
@@ -1198,20 +1293,139 @@ def save_runtime_quant(
header[UNSLOTH_FORMAT_KEY] = prequant_format_for(metadata)
header[UNSLOTH_METADATA_KEY] = json.dumps(metadata, default = str)
- kdir = root / key
+ job = _WriteJob(key, root / key, flat, header, parts, nbytes, t0, logger)
+ flat = header = None
+ if defer:
+ why = _defer_blocker(job)
+ if why is None:
+ state_dict = None
+ pending = PendingWrite(job, stack.pop_all())
+ handed_off = True
+ _log(
+ logger,
+ "info",
+ f"writing {key} ({nbytes / 2**30:.2f} GiB) on a background thread once the load is published "
+ f"(holds {job.held_bytes / 2**30:.2f} GiB, {job.file_bytes / 2**30:.2f} GiB re-read from the "
+ f"source shards, pins {job.pinned_map_bytes / 2**30:.2f} GiB of mappings)",
+ )
+ return pending
+ _log(logger, "info", f"writing {key} before the load returns ({why})")
+ state_dict = None
+ return job.run(cancel_check)
+ except Exception as exc: # noqa: BLE001 - a cache write must never fail a load
+ if cancelled[0]:
+ _log(logger, "info", "skipped (load cancelled during the save)")
+ return None
+ _log(logger, "warning", f"skipped (save failed: {type(exc).__name__}: {str(exc)[:200]})")
+ return None
+ finally:
+ stack.close()
+ flat = header = state_dict = job = None
+ if not handed_off:
+ _release_device_cache()
+
+
+class _WriteJob:
+ """One prepared artifact; ``run`` raises on any failure with no entry published."""
+
+ def __init__(
+ self,
+ key: str,
+ kdir: Path,
+ flat: dict,
+ header: dict,
+ parts: dict,
+ nbytes: int,
+ t0: float,
+ logger: Any,
+ ) -> None:
+ self.key = key
+ self.kdir = kdir
+ self.flat = flat
+ self.header = header
+ self.parts = parts
+ self.nbytes = nbytes
+ self.t0 = t0
+ self.logger = logger
+ self.release = False
+ self.fds: dict = {}
+ self.held_bytes = nbytes
+ self.pinned_map_bytes = 0
+ self.file_bytes = 0
+
+ def tensors(self) -> Iterable[Any]:
+ return self.flat.values() if self.flat is not None else ()
+
+ def resolve(self) -> None:
+ """Materialize ``_FlatRef``s and turn mmap views into ``_FileSlice``s so the snapshot pins no mapping."""
+ regions = _file_regions()
+ out: dict = {}
+ held = file_bytes = 0
+ pinned: dict = {}
+ for name, t in self.flat.items():
+ if isinstance(t, _FlatRef):
+ t = t.tensor()
+ size = _tensor_bytes(t)
+ region = None
+ if regions and size and getattr(t.device, "type", None) == "cpu":
+ region = _region_of(regions, int(t.data_ptr()), size)
+ if region is not None and t.is_contiguous():
+ piece = self._slice(t, region)
+ if piece is not None:
+ out[name] = piece
+ file_bytes += size
+ continue
+ if region is not None:
+ pinned[region[0]] = region[1] - region[0]
+ out[name] = t
+ held += size
+ self.flat = out
+ self.held_bytes = held
+ self.pinned_map_bytes = sum(pinned.values())
+ self.file_bytes = file_bytes
+ self.release = True
+
+ def _slice(self, t: Any, region: tuple) -> Optional[_FileSlice]:
+ lo, _hi, file_offset, dev, inode, path = region
+ entry = self.fds.get(path)
+ if entry is None:
+ try:
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0))
+ except OSError:
+ return None
+ st = os.fstat(fd)
+ if (os.major(st.st_dev), os.minor(st.st_dev), st.st_ino) != (*dev, inode):
+ os.close(fd)
+ return None
+ entry = self.fds[path] = (fd, (st.st_size, st.st_mtime_ns))
+ fd, stamp = entry
+ return _FileSlice(fd, file_offset + int(t.data_ptr()) - lo, t, stamp)
+
+ def close(self) -> None:
+ fds, self.fds = self.fds, {}
+ for fd, _stamp in fds.values():
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+
+ def run(self, cancel_check: Optional[Any] = None) -> str:
+ kdir = self.kdir
kdir.mkdir(parents = True, exist_ok = True)
fd, tmp = tempfile.mkstemp(dir = str(kdir), prefix = f".{FILE_NAME}.", suffix = _TEMP_SUFFIX)
os.close(fd)
try:
# Hashed during the write (no second pass); the loader verifies it.
hasher = hashlib.sha256()
+ extra = {"release": True} if self.release else {}
size = write_streaming_safetensors(
- tmp, flat, header, cancel_check = cancel_check, hasher = hasher
+ tmp, self.flat, self.header, cancel_check = cancel_check, hasher = hasher, **extra
)
- del flat, state_dict
+ self.flat = None
os.replace(tmp, kdir / FILE_NAME)
tmp = None
finally:
+ self.close()
if tmp is not None:
try:
os.unlink(tmp)
@@ -1220,36 +1434,249 @@ def save_runtime_quant(
sha = hasher.hexdigest()
_record_verified(kdir, sha)
manifest = {
- "key": key,
+ "key": self.key,
"bytes": size,
"sha256": sha,
"created": time.time(),
- "parts": parts,
+ "parts": self.parts,
}
_atomic_bytes(
kdir / MANIFEST_NAME, json.dumps(manifest, indent = 1, default = str).encode("utf-8")
)
_touch(kdir)
- if replacing is not None:
+ _log(
+ self.logger,
+ "info",
+ f"saved ({self.key}, {size / 2**30:.2f} GiB in {time.perf_counter() - self.t0:.1f} s)",
+ )
+ evict(logger = self.logger, keep = self.key)
+ return str(kdir / FILE_NAME)
+
+
+# Host RAM a deferred write must leave free beyond the build it keeps alive (the rest of the load pins encoders).
+_ASYNC_RESERVE_BYTES = 4 << 30
+_ASYNC_RESERVE_FRACTION = 0.10
+_BACKGROUND: set = set()
+
+
+def _cgroup_memory_bytes() -> tuple[Optional[int], Optional[int]]:
+ """Tightest cgroup v2 ``(limit, available)``; available adds back reclaimable file pages."""
+ try:
+ with open("/proc/self/cgroup", "r", encoding = "utf-8") as fh:
+ rel = next((ln.split("::", 1)[1].strip() for ln in fh if ln.startswith("0::")), None)
+ except OSError:
+ return None, None
+ if rel is None:
+ return None, None
+ best: tuple[Optional[int], Optional[int]] = (None, None)
+ node = Path("/sys/fs/cgroup") / rel.lstrip("/")
+ root = Path("/sys/fs/cgroup")
+ while True:
+ try:
+ raw = (node / "memory.max").read_text(encoding = "utf-8").strip()
+ if raw != "max":
+ limit = int(raw)
+ used = int((node / "memory.current").read_text(encoding = "utf-8").strip())
+ stat = dict(
+ ln.split()
+ for ln in (node / "memory.stat").read_text(encoding = "utf-8").splitlines()
+ if ln.strip()
+ )
+ avail = max(0, limit - used + int(stat.get("file", 0)))
+ if best[1] is None or avail < best[1]:
+ best = (limit, avail)
+ except (OSError, ValueError):
+ pass
+ if node == root or node.parent == node:
+ break
+ node = node.parent
+ return best
+
+
+def _host_memory_bytes() -> tuple[Optional[int], Optional[int]]:
+ try:
+ from .diffusion_memory import _system_memory_mib
+ total, avail = _system_memory_mib()
+ except Exception: # noqa: BLE001
+ return None, None
+ if total is None or avail is None:
+ return None, None
+ total, avail = int(total) << 20, int(avail) << 20
+ limit, cg_avail = _cgroup_memory_bytes()
+ if limit is not None:
+ total, avail = min(total, limit), min(avail, cg_avail)
+ return total, avail
+
+
+def _defer_blocker(job: _WriteJob) -> Optional[str]:
+ """Why ``job`` must be written now, or None: it must be wholly on the host and what it keeps alive must fit."""
+ if not async_enabled():
+ return f"{ENV_ASYNC}=0"
+ with _lock:
+ if any(not p.done() for p in _BACKGROUND):
+ return "another background cache write is running"
+ for t in job.tensors():
+ if isinstance(t, _FlatRef):
+ t = t.tensor()
+ device = getattr(t, "device", None)
+ if getattr(device, "type", None) != "cpu":
+ return f"the build is on {device}, not the host"
+ total, avail = _host_memory_bytes()
+ if total is None:
+ return "host memory unknown"
+ if not job.release:
+ job.resolve()
+ keeps = job.held_bytes + job.pinned_map_bytes
+ reserve = max(_ASYNC_RESERVE_BYTES, int(total * _ASYNC_RESERVE_FRACTION))
+ if avail < keeps + reserve:
+ return (
+ f"host RAM short for a background copy: {avail / 2**30:.1f} GiB available, the snapshot keeps "
+ f"{keeps / 2**30:.1f} GiB alive and needs {reserve / 2**30:.1f} GiB spare"
+ )
+ return None
+
+
+class _WriteCancelled(Exception):
+ pass
+
+
+class PendingWrite:
+ """Threaded prepared write holding only the lease and host tensors; the manifest is the commit point."""
+
+ def __init__(self, job: _WriteJob, stack: contextlib.ExitStack) -> None:
+ self._job: Optional[_WriteJob] = job
+ self._stack: Optional[contextlib.ExitStack] = stack
+ self.key = job.key
+ self.nbytes = job.nbytes
+ self._logger = job.logger
+ self._cancel = threading.Event()
+ self._finished = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+ self.result: Optional[str] = None
+ with _lock:
+ _BACKGROUND.add(self)
+
+ def _check(self) -> None:
+ if self._cancel.is_set():
+ raise _WriteCancelled()
+
+ def start(self) -> bool:
+ with _lock:
+ if self._thread is not None or self._job is None or self._cancel.is_set():
+ return False
+ self._thread = threading.Thread(
+ target = self._run, name = f"prequant-cache-write-{self.key[:8]}", daemon = True
+ )
+ try:
+ self._thread.start()
+ except Exception as exc: # noqa: BLE001 - no writer thread: drop the snapshot and lease, the next load re-quantises
with _lock:
- _REJECTED.discard(replacing)
+ self._thread = None
+ _log(
+ self._logger,
+ "warning",
+ f"skipped (background writer did not start: {type(exc).__name__})",
+ )
+ self._close()
+ return False
+ return True
+
+ def _run(self) -> None:
+ job = self._job
+ try:
+ if job is not None:
+ job.t0 = time.perf_counter()
+ self.result = job.run(self._check)
+ except _WriteCancelled:
+ _log(
+ self._logger,
+ "info",
+ f"skipped ({self.key} cancelled before its background write finished)",
+ )
+ except Exception as exc: # noqa: BLE001 - a background cache write never surfaces
+ _log(
+ self._logger,
+ "warning",
+ f"skipped (background save failed: {type(exc).__name__}: {str(exc)[:200]})",
+ )
+ finally:
+ self._close()
+
+ def _close(self) -> None:
+ job, self._job = self._job, None
+ if job is not None:
+ job.close()
+ job = None
+ stack, self._stack = self._stack, None
+ if stack is not None:
+ try:
+ stack.close()
+ except Exception: # noqa: BLE001
+ pass
+ with _lock:
+ _BACKGROUND.discard(self)
+ self._finished.set()
+
+ def discard(self) -> None:
+ with _lock:
+ started = self._thread is not None
+ self._cancel.set()
+ if not started:
+ self._close()
+
+ def cancel(self) -> None:
+ self.discard()
+
+ def done(self) -> bool:
+ return self._finished.is_set()
+
+ def wait(self, timeout: Optional[float] = None) -> bool:
+ return self._finished.wait(timeout)
+
+
+def cancel_background_writes(timeout: float = 30.0) -> bool:
+ with _lock:
+ pending = list(_BACKGROUND)
+ for p in pending:
+ p.cancel()
+ deadline = time.monotonic() + max(0.0, timeout)
+ return all(p.wait(max(0.0, deadline - time.monotonic())) for p in pending)
+
+
+def wait_background_writes(timeout: Optional[float] = None) -> bool:
+ with _lock:
+ pending = [p for p in _BACKGROUND if p._thread is not None]
+ deadline = None if timeout is None else time.monotonic() + timeout
+ for p in pending:
+ left = None if deadline is None else max(0.0, deadline - time.monotonic())
+ if not p.wait(left):
+ return False
+ return True
+
+
+FINISH_TIMEOUT_SECONDS = 600.0
+
+
+def finish_background_writes(timeout: float = FINISH_TIMEOUT_SECONDS, logger: Any = None) -> bool:
+ """Bounded wait, then cancel the rest, so the next load never shares host RAM with a held build."""
+ with _lock:
+ running = [p for p in _BACKGROUND if p._thread is not None and not p.done()]
+ if running:
_log(
logger,
"info",
- f"saved ({key}, {size / 2**30:.2f} GiB in {time.perf_counter() - t0:.1f} s)",
+ f"waiting for the background write of {', '.join(p.key for p in running)} before releasing the model",
)
- evict(logger = logger, keep = key)
- return str(kdir / FILE_NAME)
- except Exception as exc: # noqa: BLE001 - a cache write must never fail a load
- if cancelled[0]:
- _log(logger, "info", "skipped (load cancelled during the save)")
- return None
- _log(logger, "warning", f"skipped (save failed: {type(exc).__name__}: {str(exc)[:200]})")
- return None
- finally:
- stack.close()
- flat = header = state_dict = None
- _release_device_cache()
+ finished = wait_background_writes(timeout)
+ cancel_background_writes(timeout = 30.0)
+ return finished
+
+
+def _cancel_at_exit() -> None:
+ finish_background_writes()
+
+
+atexit.register(_cancel_at_exit)
def _release_device_cache() -> None:
diff --git a/studio/backend/tests/test_diffusion_prequant_cache_async.py b/studio/backend/tests/test_diffusion_prequant_cache_async.py
new file mode 100644
index 00000000000..2ab6d151c17
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_prequant_cache_async.py
@@ -0,0 +1,405 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Deferred prequant cache write: same bytes as the sync write, nothing published early, fallbacks, kill switch."""
+
+from __future__ import annotations
+
+import gc
+import hashlib
+import inspect
+import sys
+import threading
+import time
+import types
+import weakref
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("torchao")
+pytest.importorskip("safetensors")
+
+BACKEND = Path(__file__).resolve().parents[1]
+if str(BACKEND) not in sys.path:
+ sys.path.insert(0, str(BACKEND))
+TESTS = Path(__file__).resolve().parent
+if str(TESTS) not in sys.path:
+ sys.path.insert(0, str(TESTS))
+
+import test_diffusion_prequant_cache as T # noqa: E402
+from core.inference import diffusion_prequant_cache as C # noqa: E402
+
+scheme = T.scheme
+
+
+def env(tmp_path, monkeypatch):
+ root = tmp_path / "cache"
+ monkeypatch.setenv(C.ENV_DIR, str(root))
+ monkeypatch.delenv(C.ENV_MODE, raising = False)
+ monkeypatch.delenv(C.ENV_MAX_GB, raising = False)
+ monkeypatch.delenv(C.ENV_ASYNC, raising = False)
+ C._HEADER_MEMO.clear()
+ getattr(C, "_UNREACHABLE", {}).clear()
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (1 << 40, 1 << 39))
+ yield root
+ assert C.cancel_background_writes(timeout = 30.0)
+
+
+def _sha(path) -> str:
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def _leftovers(root: Path) -> list:
+ return [
+ p
+ for p in root.rglob("*")
+ if p.is_file() and p.name != C._LOCK_NAME and not p.name.endswith(".writing")
+ ]
+
+
+def _two_builds(tmp_path, scheme_name):
+ base, model = T._write_base(tmp_path)
+ other = T.Tiny().to(torch.bfloat16)
+ other.load_state_dict(model.state_dict())
+ return base, T._quantize(model, scheme_name), T._quantize(other, scheme_name)
+
+
+def _sync_reference(tmp_path, monkeypatch, base, model) -> str:
+ monkeypatch.setenv(C.ENV_DIR, str(tmp_path / "ref_cache"))
+ path = C.save_runtime_quant(model, T._fam(base), base_repo = str(base))
+ assert isinstance(path, str)
+ return path
+
+
+def test_deferred_write_publishes_nothing_until_it_runs_then_matches_the_sync_bytes(
+ env, tmp_path, scheme, monkeypatch
+):
+ base, model, twin = _two_builds(tmp_path, scheme)
+ ref = _sync_reference(tmp_path, monkeypatch, base, twin)
+ monkeypatch.setenv(C.ENV_DIR, str(env))
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ assert isinstance(pending, C.PendingWrite)
+ assert C.lookup(fam, scheme, base_repo = str(base)) is None
+ assert _leftovers(env) == []
+ assert C._writer_active(env, pending.key)
+ assert pending.start()
+ assert not pending.start() # once
+ assert pending.wait(60.0) and pending.done()
+ assert pending.result and Path(pending.result).is_file()
+ assert _sha(pending.result) == _sha(ref)
+ assert C.lookup(fam, scheme, base_repo = str(base)) == pending.result
+ assert not C._writer_active(env, pending.key)
+ assert pending._job is None and pending._stack is None
+
+
+def test_the_snapshot_is_independent_of_the_live_module(env, tmp_path, scheme, monkeypatch):
+ """Unload / reload / placement replace or drop the module's tensors after the hand-off: the write is unchanged."""
+ base, model, twin = _two_builds(tmp_path, scheme)
+ ref = _sync_reference(tmp_path, monkeypatch, base, twin)
+ monkeypatch.setenv(C.ENV_DIR, str(env))
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ assert isinstance(pending, C.PendingWrite)
+ with torch.no_grad():
+ for _name, p in model.named_parameters():
+ if type(p) in (torch.nn.Parameter, torch.Tensor):
+ p.data = torch.full_like(p.data, 7)
+ model.pad_token = torch.nn.Parameter(torch.zeros(1, 512, dtype = torch.bfloat16))
+ del model
+ gc.collect()
+ assert pending.start() and pending.wait(60.0)
+ assert _sha(pending.result) == _sha(ref)
+
+
+def test_the_snapshot_holds_host_tensors_only_and_frees_each_once_written(
+ env, tmp_path, scheme, monkeypatch
+):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ pending = C.save_runtime_quant(model, T._fam(base), base_repo = str(base), defer = True)
+ job = pending._job
+ assert job.release
+ assert not any(isinstance(t, C._FlatRef) for t in job.flat.values())
+ assert all(t.device.type == "cpu" for t in job.flat.values())
+ assert all(type(t) is torch.Tensor or type(t) is torch.nn.Parameter for t in job.flat.values())
+ refs = [weakref.ref(t) for t in job.flat.values()]
+ del model
+ gc.collect()
+ seen_during = []
+ real = C.write_streaming_safetensors
+
+ def spy(
+ path,
+ tensors,
+ metadata = None,
+ cancel_check = None,
+ hasher = None,
+ release = False,
+ ):
+ def check():
+ seen_during.append(len(tensors))
+ if cancel_check is not None:
+ cancel_check()
+
+ return real(path, tensors, metadata, cancel_check = check, hasher = hasher, release = release)
+
+ monkeypatch.setattr(C, "write_streaming_safetensors", spy)
+ job = None
+ assert pending.start() and pending.wait(60.0)
+ assert pending.result
+ assert seen_during == sorted(seen_during, reverse = True) and seen_during[0] > seen_during[-1]
+ gc.collect()
+ assert all(r() is None for r in refs)
+
+
+def test_release_writes_the_same_file_as_a_plain_write(tmp_path):
+ torch.manual_seed(0)
+ tensors = {
+ "a": torch.randn(4, 8, dtype = torch.bfloat16),
+ "b": torch.randint(-128, 127, (16, 3), dtype = torch.int8),
+ "c": torch.randn(5, dtype = torch.float32),
+ "e": torch.empty(0, dtype = torch.float32),
+ }
+ keep = dict(tensors)
+ C.write_streaming_safetensors(tmp_path / "x", dict(tensors), {"m": "1"})
+ drained = dict(tensors)
+ C.write_streaming_safetensors(tmp_path / "y", drained, {"m": "1"}, release = True)
+ assert drained == {}
+ assert _sha(tmp_path / "x") == _sha(tmp_path / "y")
+ assert keep.keys() == tensors.keys()
+
+
+def test_cancel_mid_write_unlinks_the_temp_and_publishes_nothing(
+ env, tmp_path, scheme, monkeypatch
+):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ entered = threading.Event()
+ gate = threading.Event()
+ real = C.write_streaming_safetensors
+
+ def slow(
+ path,
+ tensors,
+ metadata = None,
+ cancel_check = None,
+ hasher = None,
+ release = False,
+ ):
+ def check():
+ entered.set()
+ gate.wait(10.0)
+ cancel_check()
+
+ return real(path, tensors, metadata, cancel_check = check, hasher = hasher, release = release)
+
+ monkeypatch.setattr(C, "write_streaming_safetensors", slow)
+ assert pending.start()
+ assert entered.wait(10.0)
+ assert list(env.rglob(f"*{C._TEMP_SUFFIX}")) # the write really began
+ pending.cancel()
+ gate.set()
+ assert C.cancel_background_writes(timeout = 30.0)
+ assert pending.result is None
+ assert _leftovers(env) == []
+ assert C.lookup(fam, scheme, base_repo = str(base)) is None
+ monkeypatch.setattr(C, "write_streaming_safetensors", real)
+ assert isinstance(C.save_runtime_quant(model, fam, base_repo = str(base)), str)
+
+
+def test_a_failed_load_discards_the_prepared_write(env, tmp_path, scheme):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ pending.discard()
+ assert pending.done() and not pending.start()
+ assert _leftovers(env) == [] and not C._writer_active(env, pending.key)
+ assert C.lookup(fam, scheme, base_repo = str(base)) is None
+
+
+def test_a_writer_thread_that_cannot_start_releases_the_snapshot(
+ env, tmp_path, scheme, monkeypatch
+):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+
+ def refuse(self):
+ raise RuntimeError("can't start new thread")
+
+ monkeypatch.setattr(C.threading.Thread, "start", refuse)
+ assert pending.start() is False
+ assert pending.done() and pending not in C._BACKGROUND
+ assert _leftovers(env) == [] and not C._writer_active(env, pending.key)
+ assert C.lookup(fam, scheme, base_repo = str(base)) is None
+
+
+def test_fallbacks_write_synchronously(env, tmp_path, scheme, monkeypatch):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ fam = T._fam(base)
+ monkeypatch.setenv(C.ENV_ASYNC, "0")
+ out = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ assert isinstance(out, str) and Path(out).is_file()
+ monkeypatch.delenv(C.ENV_ASYNC)
+ job = C._WriteJob(
+ "k", env / "k", {"w": torch.zeros(1 << 20, dtype = torch.int8)}, {}, {}, 1 << 20, 0.0, None
+ )
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (8 << 30, 1 << 30))
+ assert "host RAM short" in C._defer_blocker(job)
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (None, None))
+ assert "unknown" in C._defer_blocker(job)
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (1 << 40, 1 << 39))
+ assert C._defer_blocker(job) is None
+ on_meta = C._WriteJob(
+ "k", env / "k", {"w": torch.empty(4, device = "meta")}, {}, {}, 4, 0.0, None
+ )
+ assert "not the host" in C._defer_blocker(on_meta)
+
+
+def test_one_background_write_at_a_time(env, tmp_path, scheme, monkeypatch):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ first = C.save_runtime_quant(model, T._fam(base), base_repo = str(base), defer = True)
+ assert isinstance(first, C.PendingWrite)
+ job = C._WriteJob("k", env / "k", {"w": torch.zeros(4)}, {}, {}, 16, 0.0, None)
+ assert "another background" in C._defer_blocker(job)
+ first.discard()
+ assert C._defer_blocker(job) is None
+
+
+def test_disk_short_still_skips_before_any_hand_off(env, tmp_path, scheme, monkeypatch):
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ monkeypatch.setattr(
+ C.shutil, "disk_usage", lambda p: types.SimpleNamespace(total = 1, used = 1, free = 0)
+ )
+ monkeypatch.setattr(C, "evict", lambda **kw: None)
+ assert C.save_runtime_quant(model, T._fam(base), base_repo = str(base), defer = True) is None
+ assert not C._BACKGROUND
+
+
+def test_an_unload_lets_a_running_write_finish(env, tmp_path, scheme, monkeypatch):
+ """An unload waits for the write (no lost entry, no host RAM shared with the next load) rather than cancelling."""
+ base, model = T._write_base(tmp_path)
+ T._quantize(model, scheme)
+ fam = T._fam(base)
+ pending = C.save_runtime_quant(model, fam, base_repo = str(base), defer = True)
+ entered = threading.Event()
+ real = C.write_streaming_safetensors
+
+ def slow(
+ path,
+ tensors,
+ metadata = None,
+ cancel_check = None,
+ hasher = None,
+ release = False,
+ ):
+ def check():
+ entered.set()
+ time.sleep(0.05)
+ cancel_check()
+
+ return real(path, tensors, metadata, cancel_check = check, hasher = hasher, release = release)
+
+ monkeypatch.setattr(C, "write_streaming_safetensors", slow)
+ del model
+ assert pending.start() and entered.wait(10.0)
+ assert C.finish_background_writes(timeout = 60.0)
+ assert pending.result and C.lookup(fam, scheme, base_repo = str(base)) == pending.result
+ assert not C._BACKGROUND
+
+
+def test_the_pipeline_load_defers_and_unload_finishes_the_write():
+ from core.inference import diffusion as D
+
+ src = inspect.getsource(D.DiffusionBackend.load_pipeline)
+ call = src.index("pending_cache_write = self._save_pipeline_quant_to_cache(")
+ assert "defer = True" in src[call : call + 700]
+ fin = src.index("pending_cache_write.start()")
+ # Started only from the finally, after publication, and discarded when the load did not commit.
+ assert src.index("state_committed = True") < fin
+ assert "pending_cache_write.discard()" in src[fin : fin + 300]
+ assert "defer = defer" in inspect.getsource(D.DiffusionBackend._save_pipeline_quant_to_cache)
+ unload = inspect.getsource(D.DiffusionBackend._unload_locked)
+ assert unload.index("finish_background_writes(") < unload.index("state = self._state")
+
+
+def _mapped(path) -> bool:
+ return any(r[5] == str(path) for r in C._file_regions())
+
+
[email protected](not Path("/proc/self/maps").exists(), reason = "needs /proc/self/maps")
+def test_a_view_of_a_mapped_shard_is_re_read_not_held(env, tmp_path):
+ """Mmapped-shard views become file slices: no mapping pinned, same bytes written."""
+ src = tmp_path / "shard.bin"
+ torch.manual_seed(0)
+ payload = torch.randn(1 << 18, dtype = torch.bfloat16)
+ src.write_bytes(b"\0" * 4096 + payload.view(torch.uint8).numpy().tobytes())
+ mapped = torch.from_file(
+ str(src), shared = False, size = 4096 + payload.numel() * 2, dtype = torch.uint8
+ )
+ view = mapped[4096:].view(torch.bfloat16).reshape(512, 512)
+ own = torch.randint(-128, 127, (256, 64), dtype = torch.int8)
+ assert _mapped(src)
+ ref = tmp_path / "ref.safetensors"
+ C.write_streaming_safetensors(ref, {"a": view, "q": own}, {"m": "1"})
+
+ job = C._WriteJob("k", env / "k", {"a": view, "q": own}, {"m": "1"}, {}, 0, 0.0, None)
+ job.resolve()
+ assert isinstance(job.flat["a"], C._FileSlice) and job.flat["q"] is own
+ assert job.held_bytes == own.numel() and job.pinned_map_bytes == 0
+ assert job.file_bytes == view.numel() * 2
+ del mapped, view
+ gc.collect()
+ assert not _mapped(src) # the snapshot does not keep the shard mapped
+ out = tmp_path / "out.safetensors"
+ C.write_streaming_safetensors(out, job.flat, job.header, release = True)
+ job.close()
+ assert _sha(out) == _sha(ref)
+
+
[email protected](not Path("/proc/self/maps").exists(), reason = "needs /proc/self/maps")
+def test_a_shard_changed_under_a_file_slice_fails_the_write(env, tmp_path):
+ src = tmp_path / "shard.bin"
+ src.write_bytes(bytes(range(256)) * 64)
+ mapped = torch.from_file(str(src), shared = False, size = 256 * 64, dtype = torch.uint8)
+ job = C._WriteJob("k", env / "k", {"a": mapped[256:]}, {}, {}, 0, 0.0, None)
+ job.resolve()
+ assert isinstance(job.flat["a"], C._FileSlice)
+ with open(src, "ab") as fh:
+ fh.write(b"x")
+ with pytest.raises(OSError):
+ C.write_streaming_safetensors(tmp_path / "o", job.flat, {})
+ job.close()
+
+
+def test_the_gate_counts_what_the_snapshot_keeps_alive(env, monkeypatch):
+ job = C._WriteJob(
+ "k", env / "k", {"w": torch.zeros(1 << 20, dtype = torch.int8)}, {}, {}, 1 << 30, 0.0, None
+ )
+ # Total artifact 1 GiB, but the snapshot holds 1 MiB: 4.5 GiB free clears max(4 GiB, 10%) + 1 MiB.
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (16 << 30, (4 << 30) + (512 << 20)))
+ assert C._defer_blocker(job) is None and job.held_bytes == 1 << 20
+ job2 = C._WriteJob(
+ "k", env / "k", {"w": torch.zeros(1 << 20, dtype = torch.int8)}, {}, {}, 1 << 20, 0.0, None
+ )
+ job2.resolve()
+ job2.pinned_map_bytes = 1 << 30 # a view that could not be sliced pins its whole mapping
+ monkeypatch.setattr(C, "_host_memory_bytes", lambda: (16 << 30, (4 << 30) + (512 << 20)))
+ assert "keeps 1.0 GiB alive" in C._defer_blocker(job2)
+
+
+def test_a_cgroup_limit_narrows_the_host_reading(monkeypatch):
+ monkeypatch.setattr(C, "_cgroup_memory_bytes", lambda: (20 << 30, 3 << 30))
+ total, avail = C._host_memory_bytes()
+ assert total <= 20 << 30 and avail <= 3 << 30