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 diffusion: cache runtime-quantized denoisers as local pre-quant checkpoints (#13715)
Daniel Hana6c1e068353f
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1befc53a69f..960b8d46c97 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -1935,6 +1935,17 @@ def _planned_quant_scheme()+def _is_local_cache_entry(source: Any) -> bool:+ """A source resolved from Studio's local pre-quant cache, not a hosted repo or an operator's file."""+ if getattr(source, "kind", None) != "path":+ return False+ try:+ from .diffusion_prequant_cache import path_in_cache+ return bool(path_in_cache(getattr(source, "location", None)))+ except Exception: # noqa: BLE001+ return False++def _prequant_probe(fam: Optional[DiffusionFamily], *, base_repo: Optional[str], prequant_path: Optional[str]) -> Callable[[str], bool]:@@ -2867,6 +2878,20 @@ def _bg_compile_module()+def _prequant_bakes_auto_accumulate(source: Any) -> bool:+ """Hosted repos and local cache entries bake the auto fp8 accumulate (forced-mode builds are never cached)."""+ kind = getattr(source, "kind", None)+ if kind == "repo":+ return True+ if kind != "path":+ return False+ try:+ from .diffusion_prequant_cache import path_in_cache+ return path_in_cache(getattr(source, "location", None) or "")+ except Exception: # noqa: BLE001+ return False++class DiffusionBackend:"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""@@ -3657,7 +3682,8 @@ class DiffusionBackend:source = usable_prequant_source(fam, candidate, path_override = path_override, base_repo = base_repo)- if source is None:+ if source is None or _is_local_cache_entry(source):+ # Lower rungs never come from the local cache: one earlier explicit load must not change auto's pick.continue# Same cached-only rule _uncached_prequant_repo applies to the winner. That guard runs# select_transformer_quant_scheme, which only ever sees the winner, so a retry that returned an UNCACHED@@ -5115,9 +5141,13 @@ class DiffusionBackend:)if source is None:continue+ if rung != scheme and _is_local_cache_entry(source):+ # Cache seeds only auto's pick: one explicit int8 load must not turn later auto loads into int8.+ continue# The loader's checkpoint validation refuses a FORCED fp8 accumulate the artifact does not bake,- # but only after the plan dropped the released shards. An operator's own file is left to it.- if getattr(source, "kind", None) == "repo" and hosted_fast_accum_conflict(+ # but only after the plan dropped the released shards. Hosted artifacts and Studio's own local+ # pre-quant cache entries both bake the auto value; an operator's own file is left to it.+ if _prequant_bakes_auto_accumulate(source) and hosted_fast_accum_conflict(rung, fast_accum):continue@@ -8840,6 +8870,18 @@ class DiffusionBackend:engaged.append(scheme)if engaged and len(engaged) == len(denoisers):transformer_quant_engaged = engaged[0]+ self._save_pipeline_quant_to_cache(+ pipe,+ fam,+ denoisers,+ loras = loras,+ base = base,+ source_base = _base_local_dir or fetch_base,+ cancel_check = lambda: self._raise_if_load_cancelled(+ _load_token+ ),+ )+ self._raise_if_load_cancelled(_load_token)else:# A clean decline can remain bf16; a partial in-place conversion is unusable.dirty = [@@ -9974,6 +10016,12 @@ class DiffusionBackend:self._prequant_fallback_note,)if transformer is not None:+ from .diffusion_prequant_cache import note_hit, path_in_cache++ if getattr(source, "kind", None) == "path" and path_in_cache(+ getattr(source, "location", "")+ ):+ note_hit(source.location, logger)if scheme == TQ_NVFP4:from .diffusion_nvfp4_linear import nvfp4_prewarmnvfp4_prewarm(transformer, (1,), logger = logger)@@ -10075,8 +10123,51 @@ class DiffusionBackend:check_cancelled()if scheme is None:raise RuntimeError("transformer quant unsupported for this device/scheme")+ if fam is not None and not _has_active_lora(lora_specs):+ # Best-effort: cache this build so the next load of the same weights skips the dense transformer.+ from .diffusion_prequant_cache import save_runtime_quant+ save_runtime_quant(+ getattr(pipe, "transformer", None),+ fam,+ base_repo = base,+ source_base = base_local_dir or fetch_base,+ logger = logger,+ cancel_check = check_cancelled,+ )+ check_cancelled()return pipe, scheme+ @staticmethod+ def _save_pipeline_quant_to_cache(+ pipe: Any,+ fam: Any,+ denoisers: Any,+ *,+ loras: Any,+ base: Optional[str],+ source_base: Optional[str],+ cancel_check: Optional[Callable[[], None]] = None,+ ) -> Optional[str]:+ """Cache a load-time quantized ``transformer`` (single denoiser only, the cache keys that component; no LoRA).+ Never raises."""+ try:+ names = [attr for attr, _module in (denoisers or ())]+ if fam is None or names != ["transformer"] or _has_active_lora(loras):+ return None+ from .diffusion_prequant_cache import save_runtime_quant++ return save_runtime_quant(+ getattr(pipe, "transformer", None),+ fam,+ base_repo = base,+ source_base = source_base,+ logger = logger,+ cancel_check = cancel_check,+ )+ except Exception as exc: # noqa: BLE001 - a cache write never fails a load+ logger.warning("diffusion.prequant_cache: skipped (%s)", exc)+ return None+@staticmethoddef _assemble_pipe(pipeline_cls: Any,diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex 94ea78ff164..dd5a284a819 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -413,6 +413,13 @@ def _local_prequant_path_allowed(path: str) -> bool:symlink cannot point an allowlisted name at a file outside the allowed roots."""import os+ # Studio's own pre-quant cache root only.+ try:+ from .diffusion_prequant_cache import path_in_cache+ if path_in_cache(path):+ return True+ except Exception: # noqa: BLE001 - an unanswerable check falls back to the operator allowlist+ passroots = _allowed_prequant_roots()if not roots:return False@@ -765,6 +772,10 @@ def prefer_cached_pickle_twins(_LOCAL_FILES_ONLY = contextvars.ContextVar("unsloth_prequant_local_files_only", default = False)+# The load's Hub token for probes lacking one in their signature (cache freshness of a gated base); outer token wins.+_LOAD_HF_TOKEN: contextvars.ContextVar = contextvars.ContextVar(+ "unsloth_prequant_hf_token", default = None+)def scoped_local_files_only(fn: Any) -> Any:@@ -776,9 +787,11 @@ def scoped_local_files_only(fn: Any) -> Any:token = _LOCAL_FILES_ONLY.set(bool(kwargs.get("local_files_only")) or _LOCAL_FILES_ONLY.get())+ hf_token = _LOAD_HF_TOKEN.set(kwargs.get("hf_token") or _LOAD_HF_TOKEN.get())try:return fn(*args, **kwargs)finally:+ _LOAD_HF_TOKEN.reset(hf_token)_LOCAL_FILES_ONLY.reset(token)return _wrapper@@ -960,7 +973,8 @@ def resolve_prequant_source(Priority: an explicit local ``path_override``; then the family's hosted repo for ``scheme``(variant-specific when ``base_repo`` names a base with its own baked checkpoint); then None,- meaning no pre-quant and the caller quantises dense. Pure: no IO, no torch.+ meaning no pre-quant and the caller quantises dense. No torch; the only IO is the memoised local cache lookup+ (safetensors headers), reached only when nothing is hosted.``task`` names the workflow / denoiser PARTITION the load is bringing up, for the families thathost more than one under a single repo and scheme (MiniMax-H3's keyframe and reference@@ -1054,6 +1068,19 @@ def resolve_prequant_source(fallback_filenames = tuple(names[1:]),declared_filenames = declared,)+ # Nothing hosted: try this machine's cache of an earlier build; task names the component (MoE transformer_2).+ try:+ from .diffusion_prequant_cache import lookup+ cached = lookup(+ fam,+ scheme,+ base_repo = base_repo,+ component = task if task in ("transformer_2",) else "transformer",+ )+ except Exception: # noqa: BLE001 - a cache problem is a miss, never a failed load+ cached = None+ if cached:+ return PrequantSource(kind = "path", location = cached, filename = None)return None@@ -2215,6 +2242,28 @@ def _pin_kernel_preference(state_dict: Any, logger: Any = None) -> int:return pinned+def _reports_rejected_cache_entry(fn: Any) -> Any:+ """Report an unusable cache entry so the dense fallback build replaces it; a forced fp8 accumulate mismatch is+ the request's choice, not a fault, and leaves the entry alone."""++ @functools.wraps(fn)+ def wrapper(transformer_cls: Any, base: str, source: Any, *args: Any, **kwargs: Any) -> Any:+ out = fn(transformer_cls, base, source, *args, **kwargs)+ if out is None and getattr(source, "kind", None) == "path":+ try:+ if not hosted_fast_accum_conflict(+ str(kwargs.get("scheme") or ""), kwargs.get("fast_accum")+ ):+ from .diffusion_prequant_cache import note_rejected+ note_rejected(source.location, kwargs.get("logger"))+ except Exception: # noqa: BLE001 - bookkeeping never changes the load's outcome+ pass+ return out++ return wrapper+++@_reports_rejected_cache_entrydef load_prequantized_transformer(transformer_cls: Any,base: str,@@ -2297,6 +2346,14 @@ def load_prequantized_transformer()if path is None:return None+ if source.kind == "path":+ # Verify the payload digest: the manifest size check misses same-size corruption.+ from .diffusion_prequant_cache import path_in_cache, verify_entry+ if path_in_cache(path) and not verify_entry(path, logger):+ _LAST_FAILURE.text = (+ "ValueError: local pre-quant cache entry failed its payload digest"+ )+ return None# A ComfyUI-format file rebuilds into the same torchao weights as Studio's own checkpoint of this scheme.from .diffusion_comfy_quant import load_comfy_prequant, scan_comfy_quantdiff --git a/studio/backend/core/inference/diffusion_prequant_cache.py b/studio/backend/core/inference/diffusion_prequant_cache.pynew file mode 100644index 00000000000..a0b98da8b09--- /dev/null+++ b/studio/backend/core/inference/diffusion_prequant_cache.py@@ -0,0 +1,1317 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Local cache of runtime-quantized denoisers for families with no hosted pre-quant, written in the hosted+artifacts' exact container + metadata so the next load takes the hosted path from a local file.++KEY: sha256 of every source shard's safetensors header plus content identity (Hub blob name, else stat; two uploads+of one architecture share a header), component, scheme, POLICY_VERSION, class, Linear filter, ConvRot, fp8+fast-accum and torch / torchao minors. The multi-GB payload is never read for the key.++TRUST: only Studio writes the root (safetensors, no pickle), so files under its exact realpath count as allowlisted.++COMMIT: artifact then manifest, each via temp + os.replace; the manifest is the commit point.++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)+"""++from __future__ import annotations++import contextlib+import hashlib+import json+import os+import shutil+import sys+import struct+import tempfile+import threading+import time+import uuid+from contextlib import contextmanager+from pathlib import Path+from typing import Any, Iterable, Optional++ENV_MODE = "UNSLOTH_DIFFUSION_PREQUANT_CACHE"+ENV_DIR = "UNSLOTH_DIFFUSION_PREQUANT_CACHE_DIR"+ENV_MAX_GB = "UNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GB"+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.+POLICY_VERSION = 1++FILE_NAME = "model.safetensors"+MANIFEST_NAME = "manifest.json"+LAST_USED_NAME = "last_used"+# sha256 of the artifact, recorded with the stat it was last checked against (save, or the first load after a change).+VERIFIED_NAME = "verified"+_HASH_CHUNK = 16 << 20+_TEMP_SUFFIX = ".tmp"+_TOMBSTONE_SUFFIX = ".evicting"+# Keys used within the grace window are spared (another process may be loading them) unless still over budget,+# then only the last _EVICT_ACTIVE_SECONDS (lookup to open), so fresh saves cannot grow past the budget.+_EVICT_GRACE_SECONDS = 600.0+_EVICT_ACTIVE_SECONDS = 60.0+# Free space kept after a save: max(this, 5% of the artifact).+_DISK_MARGIN_BYTES = 2 << 30+_MAX_HEADER_BYTES = 100 << 20++_LEGACY_ROOT = Path.home() / ".cache" / "unsloth" / "diffusion_prequant_cache"++# torch dtype name -> safetensors dtype tag (the reverse of prequant_safetensors._ST_DTYPES).+_DTYPE_TAGS = {+ "bfloat16": "BF16",+ "float16": "F16",+ "float32": "F32",+ "float64": "F64",+ "complex64": "C64",+ "float8_e4m3fn": "F8_E4M3",+ "float8_e5m2": "F8_E5M2",+ "float8_e8m0fnu": "F8_E8M0",+ "int8": "I8",+ "uint8": "U8",+ "int16": "I16",+ "uint16": "U16",+ "int32": "I32",+ "uint32": "U32",+ "int64": "I64",+ "uint64": "U64",+ "bool": "BOOL",+}++_lock = threading.Lock()+_HEADER_MEMO: dict[tuple, str] = {}+# Realpaths of entries a load in this process resolved but could not use: the next save of that key replaces them.+_REJECTED: set[str] = set()+++# ------------------------------------------------------------------------------------------------- settings+def enabled() -> bool:+ raw = (os.environ.get(ENV_MODE) 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:+ return Path(os.path.expanduser(raw))+ try:+ from utils.paths.storage_roots import cache_root as studio_cache_root+ except ImportError:+ return _LEGACY_ROOT+ return studio_cache_root() / "diffusion_prequant_cache"+++def max_cache_bytes() -> Optional[int]:+ raw = (os.environ.get(ENV_MAX_GB) or "").strip()+ try:+ gb = float(raw) if raw else DEFAULT_MAX_GB+ except ValueError:+ gb = DEFAULT_MAX_GB+ if gb != gb or gb in (float("inf"), float("-inf")):+ gb = DEFAULT_MAX_GB+ if not gb > 0:+ return None+ return int(gb * (1 << 30))+++def path_in_cache(path: Any) -> bool:+ """True when ``path`` really resolves to an artifact inside the cache root (symlinks resolved on both sides)."""+ try:+ real = os.path.realpath(os.path.expanduser(str(path)))+ root = os.path.realpath(str(cache_root()))+ except Exception: # noqa: BLE001+ return False+ if not real.startswith(root + os.sep):+ return False+ rel = os.path.relpath(real, root).split(os.sep)+ return len(rel) == 2 and rel[1] == FILE_NAME+++# ------------------------------------------------------------------------------------------------- key+def _minor(version: Any) -> str:+ parts = str(version or "").split("+")[0].split(".")+ return ".".join(parts[:2])+++def _toolchain() -> dict:+ out: dict[str, Any] = {}+ try:+ import torch+ out["torch"] = _minor(torch.__version__)+ except Exception: # noqa: BLE001+ out["torch"] = None+ try:+ import importlib.metadata as md+ out["torchao"] = _minor(md.version("torchao"))+ except Exception: # noqa: BLE001+ out["torchao"] = None+ return out+++def read_header_bytes(path: Any) -> Optional[bytes]:+ """The 8-byte length plus the JSON header of a safetensors file, or None."""+ try:+ with open(path, "rb") as fh:+ head = fh.read(8)+ if len(head) != 8:+ return None+ (length,) = struct.unpack("<Q", head)+ if length <= 0 or length > _MAX_HEADER_BYTES:+ return None+ body = fh.read(length)+ if len(body) != length:+ return None+ return head + body+ except OSError:+ return None+++def _content_identity(real: str, st: Any) -> str:+ """Payload identity: the Hub blob name (its sha256), else stat incl. inode + ctime, which a size/mtime-preserving+ replacement still changes."""+ name = os.path.basename(real)+ if len(name) == 64 and all(c in "0123456789abcdef" for c in name):+ return "blob:" + name+ return f"stat:{st.st_size}:{st.st_mtime_ns}:{st.st_ino}:{st.st_ctime_ns}"+++def source_fingerprint(shards: Iterable[Any]) -> Optional[str]:+ """Order-independent sha256 over (basename, header, content identity) of every shard; None if any is unreadable.+ Memoised: planners resolve sources several times per load."""+ digest = hashlib.sha256()+ entries = []+ for shard in shards:+ try:+ real = os.path.realpath(str(shard))+ st = os.stat(real)+ except OSError:+ return None+ memo = (real, st.st_mtime_ns, st.st_size, st.st_ino, st.st_ctime_ns)+ with _lock:+ cached = _HEADER_MEMO.get(memo)+ if cached is None:+ header = read_header_bytes(real)+ if header is None:+ return None+ cached = hashlib.sha256(+ header + b"\0" + _content_identity(real, st).encode("utf-8")+ ).hexdigest()+ with _lock:+ _HEADER_MEMO[memo] = cached+ entries.append((os.path.basename(str(shard)), cached))+ if not entries:+ return None+ for name, sha in sorted(entries):+ digest.update(name.encode("utf-8") + b"\0" + sha.encode("ascii") + b"\n")+ return digest.hexdigest()+++def _hub_cache_dir() -> Optional[str]:+ try:+ from utils.hf_cache_settings import active_hf_hub_cache+ return active_hf_hub_cache()+ except Exception: # noqa: BLE001+ return None+++def _hub_cache_roots() -> list:+ """The live Hub cache root, plus huggingface_hub's import-time root when it differs (``cache_dir = None``)."""+ roots = [_hub_cache_dir()]+ try:+ from huggingface_hub import constants+ other = constants.HF_HUB_CACHE+ if other and (roots[0] is None or os.path.realpath(other) != os.path.realpath(roots[0])):+ roots.append(other)+ except Exception: # noqa: BLE001+ pass+ return roots+++def _local_file(+ repo_or_dir: str,+ filename: str,+ cache_dir: Optional[str],+ revision: Optional[str] = None,+) -> Optional[str]:+ """``filename`` of a local directory or a Hub repo already in the cache; never a network call."""+ if os.path.isdir(os.path.expanduser(repo_or_dir)):+ path = os.path.join(os.path.expanduser(repo_or_dir), filename)+ return path if os.path.isfile(path) else None+ try:+ from huggingface_hub import try_to_load_from_cache+ hit = try_to_load_from_cache(repo_or_dir, filename, cache_dir = cache_dir, revision = revision)+ except Exception: # noqa: BLE001 - not a repo id, or no cache+ return None+ return hit if isinstance(hit, str) and os.path.isfile(hit) else None+++def _unreferenced_revisions(repo: str, cache_dir: Optional[str]) -> list:+ """Cached snapshot commits of ``repo``, newest first, only when there is no ``refs/main`` (a commit-pinned+ download writes no ref, so ``try_to_load_from_cache`` cannot see it). Never raises."""+ if os.path.isdir(os.path.expanduser(repo)):+ return []+ try:+ if cache_dir is None:+ from huggingface_hub import constants+ cache_dir = constants.HF_HUB_CACHE+ repo_dir = Path(cache_dir) / ("models--" + str(repo).replace("/", "--"))+ if (repo_dir / "refs" / "main").is_file():+ return []+ snaps = [p for p in (repo_dir / "snapshots").iterdir() if p.is_dir()]+ snaps.sort(key = lambda p: p.stat().st_mtime, reverse = True)+ return [p.name for p in snaps]+ except Exception: # noqa: BLE001 - no cache for this repo+ return []+++def _shard_sets(+ base: Optional[str],+ component: str,+ cache_dir: Optional[str] = None,+):+ """Every complete local shard set of ``base``'s ``component``, in preference order (see ``source_shards``)."""+ if not base:+ return+ if cache_dir is not None:+ yield from _shard_sets_in(base, component, cache_dir)+ return+ # Loaders fetch with reuse_other_cache_root, so the shards may sit in the live or the import-time root.+ roots = [r for r in _hub_cache_roots() if r] or [None]+ for root in roots:+ yield from _shard_sets_in(base, component, root)+++def source_shards(+ base: Optional[str],+ component: str = "transformer",+ *,+ cache_dir: Optional[str] = None,+) -> Optional[list[str]]:+ """Local paths of the dense safetensors shards of ``base``'s ``component``, or None when not all are local."""+ for found in _shard_sets(base, component, cache_dir):+ return found+ return None+++def _source_shards_in(base: str, component: str, cache_dir: Optional[str]) -> Optional[list[str]]:+ for found in _shard_sets_in(base, component, cache_dir):+ return found+ return None+++def _shard_sets_in(base: str, component: str, cache_dir: Optional[str]):+ candidates = [str(base)]+ try:+ from .diffusion_families import canonical_base, mirror_repo+ for alt in (mirror_repo(base), canonical_base(base)):+ if alt and alt not in candidates:+ candidates.append(alt)+ except Exception: # noqa: BLE001+ pass+ stem = f"{component}/diffusion_pytorch_model"+ for repo in candidates:+ # One revision at a time, so a set never mixes snapshots.+ for revision in [None, *_unreferenced_revisions(repo, cache_dir)]:+ index = _local_file(repo, f"{stem}.safetensors.index.json", cache_dir, revision)+ if index is not None:+ try:+ with open(index, "r", encoding = "utf-8") as fh:+ weight_map = (json.load(fh) or {}).get("weight_map") or {}+ names = sorted(set(str(v) for v in weight_map.values()))+ except Exception: # noqa: BLE001+ continue+ paths = [_local_file(repo, f"{component}/{n}", cache_dir, revision) for n in names]+ if names and all(paths):+ yield [str(p) for p in paths]+ continue+ single = _local_file(repo, f"{stem}.safetensors", cache_dir, revision)+ if single is not None:+ yield [single]+++def base_identity(base: Optional[str]) -> str:+ """The base as ``_same_base_model`` compares it; keyed so byte-identical bases that fail that check never share."""+ raw = str(base or "").strip()+ if not raw:+ return ""+ try:+ from .diffusion_families import canonical_base+ raw = str(canonical_base(raw) or raw)+ except Exception: # noqa: BLE001+ pass+ return raw.replace("\\", "/").rstrip("/").split("/")[-1].lower()+++def key_parts(+ *,+ family: Optional[str],+ transformer_class: Optional[str],+ scheme: str,+ component: str,+ source_fp: str,+ base: Optional[str] = None,+) -> dict:+ """Everything besides the source weights that changes the quantized bytes this cache would hold."""+ from .diffusion_transformer_quant import (+ DEFAULT_MIN_LINEAR_FEATURES,+ TQ_FP8,+ _REQUIRE_BF16_SCHEMES,+ _resolve_fast_accum,+ convrot_spec_for_scheme,+ divisible_for_scheme,+ exclude_tokens_for_scheme,+ int8_convrot_enabled,+ )++ group, suffixes = convrot_spec_for_scheme(scheme, family)+ return {+ "policy": POLICY_VERSION,+ "family": str(family or ""),+ "transformer_class": str(transformer_class or ""),+ "scheme": scheme,+ "component": component,+ "source": source_fp,+ "base": base_identity(base),+ "min_features": DEFAULT_MIN_LINEAR_FEATURES,+ "exclude_name_tokens": sorted(exclude_tokens_for_scheme(scheme, family)),+ "require_bf16": scheme in _REQUIRE_BF16_SCHEMES,+ "require_divisible": divisible_for_scheme(scheme),+ "convrot": [int(group or 0), sorted(suffixes or ())]+ if group and int8_convrot_enabled(family)+ else None,+ "fast_accum": _resolve_fast_accum(None) if scheme == TQ_FP8 else None,+ **_toolchain(),+ }+++def cache_key(parts: dict) -> str:+ return hashlib.sha256(+ json.dumps(parts, sort_keys = True, default = str).encode("utf-8")+ ).hexdigest()[:32]+++# Only schemes whose runtime and hosted builds are identical (nvfp4 converts per family at load; mxfp8 has no twin).+CACHEABLE_SCHEMES = ("int8", "fp8")+++def _key_for(+ fam: Any,+ scheme: str,+ base: Optional[str],+ component: str,+ base_id: Optional[str] = None,+ shards: Optional[list] = None,+) -> Optional[tuple[str, dict]]:+ """``base`` is where the dense shards are found (or ``shards`` themselves); ``base_id`` the base model the artifact+ is recorded and validated against (default ``base``)."""+ if scheme not in CACHEABLE_SCHEMES:+ return None+ if shards is None:+ shards = source_shards(base, component)+ if not shards:+ return None+ fp = source_fingerprint(shards)+ if fp is None:+ return None+ parts = key_parts(+ family = getattr(fam, "name", fam if isinstance(fam, str) else None),+ transformer_class = getattr(fam, "transformer_class", None),+ scheme = scheme,+ component = component,+ source_fp = fp,+ base = base_id if base_id is not None else base,+ )+ return cache_key(parts), parts+++# ------------------------------------------------------------------------------------------------- lookup+def _entry(key: str) -> Optional[Path]:+ """The artifact of ``key`` when its manifest commits to it, else None."""+ kdir = cache_root() / key+ manifest = kdir / MANIFEST_NAME+ artifact = kdir / FILE_NAME+ try:+ data = json.loads(manifest.read_text(encoding = "utf-8"))+ if not isinstance(data, dict) or data.get("key") != key:+ return None+ if artifact.stat().st_size != int(data.get("bytes", -1)):+ return None+ except Exception: # noqa: BLE001 - absent / torn / unreadable: a miss+ return None+ return artifact+++def lookup(+ fam: Any,+ scheme: str,+ *,+ base_repo: Optional[str],+ component: str = "transformer",+ logger: Any = None,+) -> Optional[str]:+ """Path of a cached artifact for this exact source + scheme, or None. Local reads only, never raises."""+ if not enabled() or scheme not in CACHEABLE_SCHEMES:+ return None+ try:+ source = base_repo or getattr(fam, "base_repo", None)+ key = shards = None+ # Every shard set: a repo without refs/main may hold several commit-pinned snapshots.+ seen: set = set()+ for candidate in (source_shards(source, component), *_shard_sets(source, component)):+ if not candidate or tuple(candidate) in seen:+ continue+ seen.add(tuple(candidate))+ keyed = _key_for(fam, scheme, source, component, shards = candidate)+ # Ask the Hub only when there is an entry to serve (a manifest), never on a plain miss.+ if keyed is not None and (cache_root() / keyed[0] / MANIFEST_NAME).is_file():+ key, shards = keyed[0], candidate+ break+ if key is None:+ return None+ if _hub_source_stale(shards, logger):+ return None+ # Check + touch under eviction's lock, so no process removes the entry before the loader opens it.+ with _cache_lock():+ artifact = _entry(key)+ if artifact is None:+ return None+ with _lock:+ rejected = os.path.realpath(str(artifact)) in _REJECTED+ if rejected:+ # Refused earlier in this process: a miss until replaced, so retries don't pick it again.+ return None+ _touch(artifact.parent)+ # The planner's header probe drops such an entry before the loader's rejection hook runs: record it+ # here, or the dense build would see it as already cached and never replace it.+ from .diffusion_prequant import local_prequant_scheme++ if local_prequant_scheme(str(artifact)) != scheme:+ note_rejected(artifact, logger)+ return None+ return str(artifact)+ except Exception as exc: # noqa: BLE001+ _log(logger, "warning", f"skipped (lookup failed: {type(exc).__name__}: {exc})")+ return None+++def _stat_stamp(path: Path) -> Optional[list]:+ try:+ st = os.stat(path)+ except OSError:+ return None+ return [st.st_size, st.st_mtime_ns, st.st_ino, st.st_ctime_ns]+++def _record_verified(kdir: Path, sha: str) -> None:+ stamp = _stat_stamp(kdir / FILE_NAME)+ if stamp is None:+ return+ try:+ _atomic_bytes(+ kdir / VERIFIED_NAME, json.dumps({"sha256": sha, "stat": stamp}).encode("utf-8")+ )+ except OSError:+ pass+++def verify_entry(+ path: Any,+ logger: Any = None,+ cancel_check: Optional[Any] = None,+) -> bool:+ """Whether the artifact still hashes to its manifest sha256 (skipped when the stat matches the last check); no+ digest fails. Never raises."""+ try:+ artifact = Path(os.path.realpath(str(path)))+ kdir = artifact.parent+ manifest = json.loads((kdir / MANIFEST_NAME).read_text(encoding = "utf-8"))+ expected = manifest.get("sha256") if isinstance(manifest, dict) else None+ if not isinstance(expected, str) or len(expected) != 64:+ _log(logger, "warning", f"entry {kdir.name} records no payload digest")+ return False+ stamp = _stat_stamp(artifact)+ try:+ seen = json.loads((kdir / VERIFIED_NAME).read_text(encoding = "utf-8"))+ if seen.get("sha256") == expected and seen.get("stat") == stamp and stamp is not None:+ return True+ except Exception: # noqa: BLE001 - no / torn marker: hash it+ pass+ digest = hashlib.sha256()+ with open(artifact, "rb") as fh:+ while True:+ if cancel_check is not None:+ cancel_check()+ chunk = fh.read(_HASH_CHUNK)+ if not chunk:+ break+ digest.update(chunk)+ if digest.hexdigest() != expected:+ _log(+ logger,+ "warning",+ f"entry {kdir.name} failed its payload digest (corrupt or modified)",+ )+ return False+ _record_verified(kdir, expected)+ return True+ except Exception as exc: # noqa: BLE001+ _log(logger, "warning", f"entry check failed: {type(exc).__name__}: {exc}")+ return False+++def note_rejected(path: Any, logger: Any = None) -> None:+ """Mark an unusable entry so the dense fallback's save replaces it. Never raises."""+ try:+ if not path_in_cache(path):+ return+ with _lock:+ _REJECTED.add(os.path.realpath(str(path)))+ _log(+ logger,+ "warning",+ f"entry {Path(str(path)).parent.name} failed to load; the next save replaces it",+ )+ except Exception: # noqa: BLE001+ pass+++# ------------------------------------------------------------------------------------------------- hub revision+# A remote answer is reused this long: planners resolve the source several times per load.+_REMOTE_TTL_SECONDS = 300.0+_REMOTE_TIMEOUT_SECONDS = 5.0+_REMOTE_MEMO: dict[tuple, tuple] = {}+_GONE = "gone"+++def _hub_coords(path: Any) -> Optional[tuple[str, str, str, str]]:+ """``(repo_id, filename, blob, commit)`` of a Hub snapshot path, else None. ``blob`` is the plain filename in a+ symlink-less cache (Windows without Developer Mode)."""+ parts = Path(str(path)).parts+ try:+ i = len(parts) - 1 - parts[::-1].index("snapshots")+ except ValueError:+ return None+ if i < 1 or i + 2 >= len(parts) or not parts[i - 1].startswith("models--"):+ return None+ repo = parts[i - 1][len("models--") :].replace("--", "/")+ return (+ repo,+ "/".join(parts[i + 2 :]),+ os.path.basename(os.path.realpath(str(path))),+ parts[i + 1],+ )+++def _is_content_hash(name: str) -> bool:+ return len(name) in (40, 64) and all(c in "0123456789abcdef" for c in name)+++def _remote_etag(+ repo: str,+ filename: str,+ revision: str = "main",+) -> Optional[str]:+ """The Hub etag of ``filename`` at ``revision``, ``_GONE`` if absent, None if unanswerable (treated as offline)."""+ memo = (repo, filename, revision)+ with _lock:+ hit = _REMOTE_MEMO.get(memo)+ if hit is not None and time.monotonic() - hit[0] < _REMOTE_TTL_SECONDS:+ return hit[1]+ try:+ from huggingface_hub import get_hf_file_metadata, hf_hub_url+ from huggingface_hub.utils import EntryNotFoundError+ except Exception: # noqa: BLE001+ return None+ try:+ from .diffusion_prequant import _LOAD_HF_TOKEN+ token = _LOAD_HF_TOKEN.get() # a gated / private base answers only to the load's own token+ except Exception: # noqa: BLE001+ token = None+ try:+ etag = get_hf_file_metadata(+ hf_hub_url(repo, filename, revision = revision),+ token = token or None,+ timeout = _REMOTE_TIMEOUT_SECONDS,+ ).etag+ value = str(etag) if etag else None # already normalized (no quotes, no W/ prefix)+ except EntryNotFoundError:+ value = _GONE+ except Exception: # noqa: BLE001 - offline, gated without a token, rate limited: unanswerable+ return None+ with _lock:+ _REMOTE_MEMO[memo] = (time.monotonic(), value)+ return value+++def _hub_source_stale(shards: Optional[list], logger: Any = None) -> bool:+ """Whether Hub ``main`` moved past these shards' snapshot: a cache hit skips the ``from_pretrained`` request that+ would advance the ref. Offline loads keep the local snapshot."""+ if not shards:+ return False+ try:+ from .diffusion_prequant import _LOCAL_FILES_ONLY, hub_offline+ if _LOCAL_FILES_ONLY.get() or hub_offline():+ return False+ except Exception: # noqa: BLE001+ return False+ for shard in shards:+ coords = _hub_coords(shard)+ if coords is None:+ continue+ repo, filename, blob, commit = coords+ etag = _remote_etag(repo, filename)+ if etag is not None and not _is_content_hash(blob):+ # No symlink content hash: ask what the snapshot's own commit serves.+ blob = _remote_etag(repo, filename, revision = commit)+ if blob is None or blob == _GONE:+ continue # unanswerable: the local snapshot stands, as offline+ if etag is not None and etag != blob:+ _log(logger, "info", f"miss ({repo}:{filename} changed on the Hub since it was cached)")+ return True+ return False+++def note_hit(path: Any, logger: Any = None) -> None:+ """Called once the loader really used ``path``."""+ _log(logger, "info", f"hit ({Path(str(path)).parent.name})")+++_LOCK_NAME = ".lock"+++# Nesting depth of _cache_lock (tests only).+_LOCK_DEPTH = [0]+++# msvcrt.LK_LOCK retries for about 10 s, then raises; the sections it guards take milliseconds.+_WINDOWS_LOCK_ATTEMPTS = 6+++def _lock_file(fh: Any) -> Optional[str]:+ """Exclusive flock, else msvcrt lock; returns the kind taken or None."""+ try:+ import fcntl+ except ImportError:+ fcntl = None+ if fcntl is not None:+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)+ return "flock"+ try:+ import msvcrt+ except ImportError:+ return None+ for attempt in range(_WINDOWS_LOCK_ATTEMPTS):+ try:+ fh.seek(0)+ msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1)+ return "msvcrt"+ except OSError:+ if attempt == _WINDOWS_LOCK_ATTEMPTS - 1:+ raise+ return None+++def _unlock_file(fh: Any, kind: Optional[str]) -> None:+ if kind == "msvcrt":+ import msvcrt+ fh.seek(0)+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)+ # flock is dropped by closing the descriptor+++@contextmanager+def _cache_lock(root: Optional[Path] = None):+ """Cross-process lock over the root for short check-and-act sections; runs unlocked if no lock exists."""+ fh = None+ kind = None+ try:+ root = root if root is not None else cache_root()+ root.mkdir(parents = True, exist_ok = True)+ fh = open(root / _LOCK_NAME, "a+b")+ try:+ kind = _lock_file(fh)+ except OSError:+ kind = None+ except OSError:+ fh = None+ _LOCK_DEPTH[0] += 1+ try:+ yield+ finally:+ _LOCK_DEPTH[0] -= 1+ if fh is not None:+ try:+ _unlock_file(fh, kind)+ except OSError:+ pass+ try:+ fh.close()+ except OSError:+ pass+++def _writer_lock_path(root: Path, key: str) -> Path:+ # Beside the key dir, not in it: eviction renames the dir, and the lock must outlive that rename.+ return root / f".{key}.writing"+++def _try_lock_file(fh: Any) -> Optional[bool]:+ """Non-blocking lock: True taken, False held elsewhere, None unsupported."""+ try:+ import fcntl+ except ImportError:+ fcntl = None+ if fcntl is not None:+ try:+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ return True+ except OSError:+ return False+ try:+ import msvcrt+ except ImportError:+ return None+ try:+ fh.seek(0)+ msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)+ return True+ except OSError:+ return False+++@contextmanager+def _writer_lock(root: Path, key: str):+ """Per-key cross-process build lease from the "already cached?" check through publication; yields False when no+ lock can be taken (caller skips rather than publishing unlocked)."""+ fh = None+ kind = None+ try:+ root.mkdir(parents = True, exist_ok = True)+ fh = open(_writer_lock_path(root, key), "a+b")+ kind = _lock_file(fh)+ except OSError:+ kind = None+ try:+ yield kind is not None+ finally:+ if fh is not None:+ try:+ _unlock_file(fh, kind)+ except OSError:+ pass+ try:+ fh.close()+ except OSError:+ pass+++def _writer_active(root: Path, key: str) -> bool:+ """Whether a build of ``key`` is in progress in some process (its lease is held). Never raises."""+ path = _writer_lock_path(root, key)+ if not path.exists():+ return False+ try:+ with open(path, "a+b") as fh:+ taken = _try_lock_file(fh)+ if taken:+ _unlock_file(fh, "msvcrt" if sys.platform == "win32" else "flock")+ return taken is False+ except OSError:+ return False+++def _reclaim(kdir: Path) -> None:+ """Remove a key dir: renamed to a tombstone under the cache lock, then deleted. Never raises."""+ tomb = kdir.with_name(f"{kdir.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}{_TOMBSTONE_SUFFIX}")+ try:+ with _cache_lock(kdir.parent):+ os.rename(kdir, tomb)+ except OSError:+ return+ shutil.rmtree(tomb, ignore_errors = True)+++def _touch(kdir: Path) -> None:+ try:+ p = kdir / LAST_USED_NAME+ p.touch(exist_ok = True)+ os.utime(p, None)+ except OSError:+ pass+++# ------------------------------------------------------------------------------------------------- writer+def _tensor_bytes(tensor: Any) -> int:+ return int(tensor.numel()) * int(tensor.element_size())+++def write_streaming_safetensors(+ path: Any,+ tensors: dict,+ metadata: Optional[dict] = None,+ cancel_check: Optional[Any] = None,+ hasher: Optional[Any] = None,+) -> 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."""+ import torch++ order = sorted(tensors.items(), key = lambda kv: (-kv[1].element_size(), kv[0]))+ header: dict[str, Any] = {}+ if metadata:+ header["__metadata__"] = {str(k): str(v) for k, v in metadata.items()}+ offset = 0+ for name, tensor in order:+ tag = _DTYPE_TAGS.get(str(tensor.dtype).replace("torch.", ""))+ if tag is None:+ raise ValueError(f"{name}: dtype {tensor.dtype} has no safetensors tag")+ size = _tensor_bytes(tensor)+ header[name] = {+ "dtype": tag,+ "shape": list(tensor.shape),+ "data_offsets": [offset, offset + size],+ }+ offset += size+ blob = json.dumps(header, separators = (",", ":")).encode("utf-8")+ blob += b" " * ((8 - len(blob) % 8) % 8)++ def put(data: Any) -> None:+ fh.write(data)+ if hasher is not None:+ hasher.update(data)++ with open(path, "wb") as fh:+ put(struct.pack("<Q", len(blob)))+ put(blob)+ for _name, tensor in order:+ if cancel_check is not None:+ cancel_check()+ if tensor.numel() == 0:+ 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+ fh.flush()+ os.fsync(fh.fileno())+ return 8 + len(blob) + offset+++def _atomic_bytes(path: Path, data: bytes) -> None:+ fd, tmp = tempfile.mkstemp(dir = str(path.parent), prefix = f".{path.name}.", suffix = _TEMP_SUFFIX)+ try:+ with os.fdopen(fd, "wb") as fh:+ fh.write(data)+ fh.flush()+ os.fsync(fh.fileno())+ os.replace(tmp, path)+ tmp = None+ finally:+ if tmp is not None:+ try:+ os.unlink(tmp)+ except OSError:+ pass+++class _FlatRef:+ """A flat entry read from the live module at write time: torchao's flatten clones every quantized tensor on+ device, a second full VRAM copy when the card is fullest."""++ __slots__ = ("_get", "dtype", "shape", "_numel", "_esize")++ def __init__(self, get: Any, tensor: Any) -> None:+ self._get = get+ self.dtype = tensor.dtype+ self.shape = tuple(tensor.shape)+ self._numel = int(tensor.numel())+ self._esize = int(tensor.element_size())++ def numel(self) -> int:+ return self._numel++ def element_size(self) -> int:+ return self._esize++ def tensor(self) -> Any:+ return self._get()+++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 (+ UNSLOTH_ROOT_KEYS_KEY,+ UNSLOTH_ROOT_PREFIX,+ _root_level_keys,+ _torchao_helpers,+ unsupported_state_dict_keys,+ )++ helpers = _torchao_helpers()+ if helpers is None:+ raise RuntimeError("torchao safetensors helpers unavailable")+ if unsupported_state_dict_keys(state_dict):+ raise ValueError("root-level quantized tensors cannot be written as safetensors")+ roots = set(_root_level_keys(state_dict))+ flatten, _ = helpers+ header: dict = {}+ flat: dict = {}+ names: list = []+ for key, value in state_dict.items():+ if key in roots:+ continue+ part, meta = flatten({key: value})+ names.append(key)+ header[key] = meta[key]+ if "." in key:+ prefix, _, last = key.rpartition(".")+ stem = f"{prefix}._{last}_"+ else:+ stem = None+ for name, clone in part.items():+ if name == key: # a plain tensor is passed through, not cloned+ flat[name] = value+ continue+ field = name[len(stem) :] if stem is not None and name.startswith(stem) else None+ inner = getattr(value, field, None) if field else None+ if (+ inner is not None+ and tuple(inner.shape) == tuple(clone.shape)+ and inner.dtype == clone.dtype+ ):+ flat[name] = _FlatRef(lambda v = value, f = field: getattr(v, f), clone)+ else:+ flat[name] = (+ clone # unrecognised naming: keep torchao's copy (correct, not bounded)+ )+ del part+ header["tensor_names"] = json.dumps(names)+ if roots:+ for key in _root_level_keys(state_dict):+ flat[f"{UNSLOTH_ROOT_PREFIX}{key}"] = state_dict[key]+ header[UNSLOTH_ROOT_KEYS_KEY] = json.dumps([str(k) for k in _root_level_keys(state_dict)])+ return flat, header+++def _rotation(transformer: Any, info: dict) -> dict:+ fqns = tuple(info.get("convrot_fqns") or ())+ group = info.get("convrot_group")+ if not fqns or not group:+ return {}+ from .diffusion_convrot import rotation_metadata++ return rotation_metadata(int(group), fqns)+++def save_runtime_quant(+ transformer: Any,+ fam: Any,+ *,+ base_repo: Optional[str],+ source_base: Optional[str] = None,+ component: str = "transformer",+ logger: Any = None,+ cancel_check: Optional[Any] = None,+) -> Optional[str]:+ """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)."""+ if not enabled():+ return None+ t0 = time.perf_counter()+ cancelled = [False]+ user_cancel_check = cancel_check++ def cancel_check() -> None:+ if user_cancel_check is None:+ return+ try:+ user_cancel_check()+ except BaseException:+ cancelled[0] = True+ raise++ stack = contextlib.ExitStack()+ try:+ info = dict(getattr(transformer, "_unsloth_runtime_quant_info", None) or {})+ scheme = info.get("scheme")+ if not info or scheme not in CACHEABLE_SCHEMES:+ _log(logger, "info", f"skipped (scheme {scheme or 'unknown'} is not cached)")+ return None+ if info.get("native"):+ _log(logger, "info", "skipped (native weight-only layers have no safetensors layout)")+ return None+ if info.get("lora"):+ _log(logger, "info", "skipped (baked LoRA adapters)")+ return None+ import torch++ if info.get("dtype") not in (None, "None", str(torch.bfloat16), "bfloat16"):+ _log(logger, "info", f"skipped (model dtype {info.get('dtype')} is not bfloat16)")+ return None+ recorded_base = str(base_repo or getattr(fam, "base_repo", "") or "")+ keyed = _key_for(fam, scheme, source_base or base_repo, component, base_id = recorded_base)+ if keyed is None:+ _log(logger, "info", "skipped (dense source shards not found locally)")+ return None+ key, parts = keyed+ # The runtime filter must be the one the key describes, or the artifact would not match a fresh quantize.+ for name in ("min_features", "require_bf16", "require_divisible"):+ if name in info and info[name] != parts[name]:+ _log(logger, "info", f"skipped (runtime {name} {info[name]!r} != {parts[name]!r})")+ return None+ if (+ "exclude_name_tokens" in info+ and sorted(t for t in info["exclude_name_tokens"] if t != "lora_")+ != parts["exclude_name_tokens"]+ ):+ _log(logger, "info", "skipped (runtime exclusion list differs)")+ return None+ if parts["fast_accum"] is not None:+ # Entries bake the auto accumulate like hosted fp8; a forced-mode build would be mislabelled as auto.+ from .diffusion_transformer_quant import _resolve_fast_accum+ if _resolve_fast_accum(info.get("fast_accum")) != parts["fast_accum"]:+ _log(+ logger,+ "info",+ "skipped (fp8 quantized with a forced non-default accumulate mode)",+ )+ return None+ if bool(info.get("convrot_fqns")) != bool(parts["convrot"]):+ _log(logger, "info", "skipped (ConvRot state differs from the key)")+ return None+ if not stack.enter_context(_writer_lock(cache_root(), key)):+ _log(logger, "info", "skipped (no cross-process lock available for the build)")+ return None+ existing = _entry(key)+ replacing = None+ if existing is not None:+ real = os.path.realpath(str(existing))+ with _lock:+ replacing = real if real in _REJECTED else None+ if replacing is None:+ _log(logger, "info", f"skipped (already cached as {key})")+ return None+ _log(logger, "info", f"replacing {key} (it failed to load)")++ state_dict = transformer.state_dict()+ if any(".lora_" in k or k.startswith("lora_") for k in state_dict):+ _log(logger, "info", "skipped (baked LoRA adapters)")+ return None+ try:+ flat, header = _flatten(state_dict)+ except Exception as exc: # noqa: BLE001 - legacy int8 subclass on torchao < 0.18, root subclass, ...+ _log(+ logger, "info", f"skipped (not flattenable: {type(exc).__name__}: {str(exc)[:160]})"+ )+ return None+ nbytes = sum(_tensor_bytes(t) for t in flat.values())+ # Before eviction: an over-budget artifact must not cost existing entries.+ budget = max_cache_bytes()+ if budget is not None and nbytes > budget:+ _log(logger, "info", "skipped (artifact larger than the cache budget)")+ return None+ root = cache_root()+ root.mkdir(parents = True, exist_ok = True)+ if replacing is not None:+ # Reclaim the rejected artifact first: eviction keeps ``key``, so it would hold a second copy's disk.+ _reclaim(root / key)+ with _lock:+ _REJECTED.discard(replacing)+ free = shutil.disk_usage(str(root)).free+ need = nbytes + max(_DISK_MARGIN_BYTES, nbytes // 20)+ if free < need:+ evict(root = root, extra_free_bytes = need - free, keep = key, logger = logger)+ free = shutil.disk_usage(str(root)).free+ if free < need:+ _log(+ logger,+ "info",+ f"skipped (disk short: {free / 2**30:.1f} GiB free, need {need / 2**30:.1f} GiB)",+ )+ return None++ from .diffusion_prequant import prequant_format_for+ from .prequant_safetensors import UNSLOTH_FORMAT_KEY, UNSLOTH_METADATA_KEY++ metadata = {+ "base_model_id": recorded_base,+ "family": parts["family"],+ "scheme": scheme,+ "min_features": parts["min_features"],+ "exclude_name_tokens": list(parts["exclude_name_tokens"]),+ "require_bf16": parts["require_bf16"],+ "require_divisible": parts["require_divisible"],+ "fast_accum": parts["fast_accum"],+ "torch_dtype": "bfloat16",+ "quant_backend": "torchao",+ "transformer_class": parts["transformer_class"] or type(transformer).__name__,+ "component": component,+ "torch_version": str(torch.__version__),+ "torchao_version": parts.get("torchao"),+ "local_prequant_cache": {"key": key, "policy": POLICY_VERSION},+ }+ if scheme == "fp8":+ from .diffusion_transformer_quant import FP8_GRANULARITY+ metadata["fp8_granularity"] = FP8_GRANULARITY+ metadata.update(_rotation(transformer, info))+ header[UNSLOTH_FORMAT_KEY] = prequant_format_for(metadata)+ header[UNSLOTH_METADATA_KEY] = json.dumps(metadata, default = str)++ kdir = root / key+ 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()+ size = write_streaming_safetensors(+ tmp, flat, header, cancel_check = cancel_check, hasher = hasher+ )+ del flat, state_dict+ os.replace(tmp, kdir / FILE_NAME)+ tmp = None+ finally:+ if tmp is not None:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ sha = hasher.hexdigest()+ _record_verified(kdir, sha)+ manifest = {+ "key": key,+ "bytes": size,+ "sha256": sha,+ "created": time.time(),+ "parts": parts,+ }+ _atomic_bytes(+ kdir / MANIFEST_NAME, json.dumps(manifest, indent = 1, default = str).encode("utf-8")+ )+ _touch(kdir)+ if replacing is not None:+ with _lock:+ _REJECTED.discard(replacing)+ _log(+ logger,+ "info",+ f"saved ({key}, {size / 2**30:.2f} GiB in {time.perf_counter() - t0:.1f} s)",+ )+ 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()+++def _release_device_cache() -> None:+ try:+ import torch+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ except Exception: # noqa: BLE001+ pass+++# ------------------------------------------------------------------------------------------------- eviction+def _dir_bytes(path: Path) -> int:+ total = 0+ for dirpath, _dirs, files in os.walk(path, followlinks = False):+ for name in files:+ try:+ total += os.lstat(os.path.join(dirpath, name)).st_size+ except OSError:+ pass+ return total+++def _last_used(path: Path) -> float:+ for name in (LAST_USED_NAME, MANIFEST_NAME):+ try:+ return (path / name).stat().st_mtime+ except OSError:+ continue+ try:+ return path.stat().st_mtime+ except OSError:+ return 0.0+++def _is_key_dir(path: Path) -> bool:+ return len(path.name) == 32 and all(c in "0123456789abcdef" for c in path.name)+++def evict(+ *,+ root: Optional[Path] = None,+ max_bytes: Optional[int] = None,+ keep: Optional[str] = None,+ extra_free_bytes: int = 0,+ logger: Any = None,+) -> list[str]:+ """LRU-evict until under budget and ``extra_free_bytes`` freed; a disabled budget never evicts. Never raises."""+ removed: list[str] = []+ try:+ root = root if root is not None else cache_root()+ budget = max_bytes if max_bytes is not None else max_cache_bytes()+ if budget is None or not root.is_dir():+ return removed+ entries = []+ for child in root.iterdir():+ if child.is_symlink() or not child.is_dir():+ continue+ if child.name.endswith(_TOMBSTONE_SUFFIX):+ shutil.rmtree(child, ignore_errors = True)+ elif _is_key_dir(child):+ entries.append((_last_used(child), child, _dir_bytes(child)))+ total = sum(e[2] for e in entries)+ if extra_free_bytes > 0:+ budget = min(budget, max(0, total - int(extra_free_bytes)))+ now = time.time()+ passes = [now - _EVICT_GRACE_SECONDS, now - _EVICT_ACTIVE_SECONDS]+ for cutoff, (used, path, size) in (+ (c, e) for c in passes for e in sorted(entries, key = lambda e: e[0])+ ):+ if total <= budget:+ break+ if path.name == keep or path.name in removed or used > cutoff:+ continue+ if _writer_active(root, path.name):+ continue # a build is streaming into it: not idle, whatever its timestamps say+ tomb = path.with_name(+ f"{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}{_TOMBSTONE_SUFFIX}"+ )+ # Re-check under lookup's lock: another process may have resolved this entry since the scan.+ with _cache_lock(root):+ if _last_used(path) > cutoff:+ continue+ try:+ os.rename(path, tomb)+ except OSError:+ continue+ shutil.rmtree(tomb, ignore_errors = True)+ total -= size+ removed.append(path.name)+ if removed:+ _log(logger, "info", f"evicted {len(removed)} key(s); {total / 2**30:.2f} GiB in use")+ except Exception as exc: # noqa: BLE001+ _log(logger, "warning", f"eviction failed: {exc}")+ return removed+++def _log(logger: Any, level: str, msg: str) -> None:+ if logger is not None:+ getattr(logger, level)("diffusion.prequant_cache: %s", msg)diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 05e9025bc4b..a4c131f99a5 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -1935,7 +1935,9 @@ def quantize_transformer(require_bf16 = scheme in _REQUIRE_BF16_SCHEMES,require_divisible = divisible,)- apply_runtime_convrot(transformer, scheme, family, filter_fn, target = target, logger = logger)+ rotated = apply_runtime_convrot(+ transformer, scheme, family, filter_fn, target = target, logger = logger+ )quantize_(transformer,_make_quant_config(scheme, fast_accum = fast_accum),@@ -1948,6 +1950,19 @@ def quantize_transformer(apply_zero_row_guard(transformer, scheme, family, logger = logger)try:transformer._unsloth_runtime_quant = scheme+ # What diffusion_prequant_cache needs to persist this exact build.+ transformer._unsloth_runtime_quant_info = {+ "scheme": scheme,+ "family": family,+ "min_features": int(min_features),+ "exclude_name_tokens": list(exclude),+ "require_bf16": scheme in _REQUIRE_BF16_SCHEMES,+ "require_divisible": divisible,+ "fast_accum": fast_accum,+ "convrot_group": convrot_spec_for_scheme(scheme, family)[0] if rotated else None,+ "convrot_fqns": list(rotated or ()),+ "dtype": str(getattr(target, "dtype", None) or _first_weight_dtype(transformer)),+ }except Exception: # noqa: BLE001 - marker is best-effortpassreturn scheme@@ -1994,6 +2009,7 @@ def _quantize_native(probe_mps_int8pack(transformer, scale_dtype, logger = logger)try:transformer._unsloth_runtime_quant = scheme+ transformer._unsloth_runtime_quant_info = {"scheme": scheme, "native": True}except Exception: # noqa: BLE001 - marker is best-effortpassreturn scheme@@ -2002,6 +2018,21 @@ def _quantize_native(return None+def _first_weight_dtype(module: Any) -> Any:+ """The dtype the dense model was loaded in: a parameter left high precision by the quant filter (norms, embeds)."""+ try:+ import torch+ for param in module.parameters():+ if (+ type(param.data) in (torch.Tensor, torch.nn.Parameter)+ and param.dtype.is_floating_point+ ):+ return param.dtype+ except Exception: # noqa: BLE001+ pass+ return None++def _warn(logger: Any, what: str, exc: Exception) -> None:if logger is not None:logger.warning("diffusion.transformer_quant: %s failed: %s", what, exc)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex d387dc251ef..bdf056ab64a 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -2575,6 +2575,16 @@ def _video_auto_denoiser_scheme(for s in video_family_prequant_schemes(fam)if denoiser_prequant_sources(fam, s, base_repo, hf_token = hf_token) is not None)+ if not auto and normalize_transformer_quant(requested) not in hosted:+ # An EXPLICIT unhosted scheme may seed from the local cache; never under auto, so the cache can't change+ # auto's pick.+ from .diffusion_prequant_cache import CACHEABLE_SCHEMES+ wanted = normalize_transformer_quant(requested)+ if (+ wanted in CACHEABLE_SCHEMES+ and denoiser_prequant_sources(fam, wanted, base_repo, hf_token = hf_token) is not None+ ):+ hosted = hosted + (wanted,)if not hosted or (not auto and normalize_transformer_quant(requested) not in hosted):return None@@ -2601,6 +2611,37 @@ def _video_auto_denoiser_scheme(return None+def _save_runtime_quant_to_cache(+ fam: Any,+ views: Any,+ *,+ base: Optional[str],+ source: Optional[str],+ cancel_check: Any = None,+) -> None:+ """Cache a runtime-quantized single denoiser; MoE is skipped (no lookup slot for the second expert)."""+ try:+ from .video_denoiser_prequant import denoiser_components++ views = list(views or ())+ if len(denoiser_components(fam)) != 1 or len(views) != 1:+ logger.info("diffusion.prequant_cache: skipped (multi-denoiser video family)")+ return+ from .diffusion_prequant_cache import save_runtime_quant++ save_runtime_quant(+ getattr(views[0], "transformer", None),+ fam,+ base_repo = base,+ source_base = source,+ component = "transformer",+ logger = logger,+ cancel_check = cancel_check,+ )+ except Exception as exc: # noqa: BLE001 - a cache write never fails a load+ logger.warning("diffusion.prequant_cache: skipped (%s)", exc)++# The planner DECIDED against the seed (not "never ran"); a load must not re-take it after teardown.DENOISER_SEED_DECLINED = "__declined__"@@ -7480,6 +7521,10 @@ class VideoBackend:# ── the load itself ──────────────────────────────────────────────────────+ def _raise_if_video_load_superseded(self, token: Optional[int]) -> None:+ if token is not None and token != self._load_token:+ raise RuntimeError("Video load was cancelled or superseded.")+@_invalidates_gpu_memory("video load")@rocm_probe_load_scoped@scoped_local_files_only@@ -8775,6 +8820,16 @@ class VideoBackend:)if engaged:transformer_quant_engaged = engaged[0]+ # Only explicit schemes read the cache back, so an auto save would be a write nothing opens.+ if transformer_quant_pinned is not None:+ _save_runtime_quant_to_cache(+ fam,+ views,+ base = base,+ source = _base_local_dir or fetch_base,+ cancel_check = lambda: self._raise_if_video_load_superseded(_load_token),+ )+ self._raise_if_video_load_superseded(_load_token)elif transformer_quant_pinned is not None:transformer_quant_decline = (f"'{transformer_quant_pinned}' did not engage on family '{fam.name}' with this "diff --git a/studio/backend/core/inference/video_denoiser_prequant.py b/studio/backend/core/inference/video_denoiser_prequant.pyindex 4acf4314d30..99616e8cc5d 100644--- a/studio/backend/core/inference/video_denoiser_prequant.py+++ b/studio/backend/core/inference/video_denoiser_prequant.py@@ -169,6 +169,10 @@ def denoiser_prequant_pipe_kwargs()return {}seeded[component] = module+ from .diffusion_prequant_cache import note_hit, path_in_cache++ if getattr(source, "kind", None) == "path" and path_in_cache(source.location):+ note_hit(source.location, logger)gc.collect()if logger is not None:logger.info(diff --git a/studio/backend/tests/test_diffusion_pipeline_prequant.py b/studio/backend/tests/test_diffusion_pipeline_prequant.pyindex 813d58f8efd..0c17ad59d79 100644--- a/studio/backend/tests/test_diffusion_pipeline_prequant.py+++ b/studio/backend/tests/test_diffusion_pipeline_prequant.py@@ -575,6 +575,28 @@ def test_a_forced_fp8_accumulate_the_artifact_cannot_bake_keeps_the_released_weiassert _settle(backend, transformer_quant = "fp8") == "fp8"+def test_a_forced_fp8_accumulate_also_rules_out_a_local_prequant_cache_entry(monkeypatch, tmp_path):+ """A cache entry bakes the auto accumulate, so a forced different value must not seed it; an operator file is+ left to the loader's validation."""+ from core.inference import diffusion_prequant_cache as cache++ root = tmp_path / "prequant_cache"+ monkeypatch.setenv(cache.ENV_DIR, str(root))+ entry = str(root / ("e" * 32) / cache.FILE_NAME)+ operator_file = str(tmp_path / "mine" / "fp8.safetensors")+ backend = _settle_backend(monkeypatch)+ for location, forced_off in ((entry, None), (operator_file, "fp8")):+ monkeypatch.setattr(+ dmod,+ "denoiser_prequant_source",+ lambda fam, scheme, _loc = location, **_k: pqmod.PrequantSource(+ kind = "path", location = _loc, filename = None+ ),+ )+ assert _settle(backend, transformer_quant = "fp8", fast_accum = False) == forced_off+ assert _settle(backend, transformer_quant = "fp8", fast_accum = True) == "fp8"++def test_a_forced_accumulate_never_blocks_a_scheme_that_bakes_none(monkeypatch):"""Only fp8 records ``fast_accum``, so the int8 artifact is seeded whatever the caller forces."""backend = _settle_backend(monkeypatch, scheme = "int8")diff --git a/studio/backend/tests/test_diffusion_prequant_cache.py b/studio/backend/tests/test_diffusion_prequant_cache.pynew file mode 100644index 00000000000..a5ae598f09d--- /dev/null+++ b/studio/backend/tests/test_diffusion_prequant_cache.py@@ -0,0 +1,1249 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Local pre-quant cache (diffusion_prequant_cache): key, round trip, trust, atomicity, budget, host RAM.++Hermetic: a hand-built bf16 module quantized on the CPU (fp8 on torchao <= 0.17, int8 where the install can flatten+it), a base "repo" that is a local directory with one safetensors shard, and a private cache root per test.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import textwrap+import time+import types+from pathlib import Path+from typing import Optional++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))++from core.inference import diffusion_prequant_cache as C # noqa: E402+from core.inference import prequant_safetensors as PS # noqa: E402+from core.inference.diffusion_transformer_quant import ( # noqa: E402+ _REQUIRE_BF16_SCHEMES,+ _make_quant_config,+ divisible_for_scheme,+ exclude_tokens_for_scheme,+ make_filter_fn,+)++FAMILY = "tinyfam-cache-test"+++class _Block(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.to_q = torch.nn.Linear(512, 512)+ self.ff = torch.nn.Linear(512, 1024)+ self.norm = torch.nn.LayerNorm(512)+++class Tiny(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ # Root-level plain tensor (z-image's pad tokens): written beside torchao's flat set.+ self.pad_token = torch.nn.Parameter(torch.randn(1, 512))+ self.blocks = torch.nn.ModuleList([_Block() for _ in range(2)])+++def _usable_scheme() -> tuple[str, bool]:+ """``(scheme, really_quantized)``: a CPU-quantizable + flattenable scheme, else fp8 over plain bf16 (CPU-only CI);+ the cache never looks inside tensors, so the plain case still covers everything but subclass bit-identity."""+ for scheme in ("fp8", "int8"):+ try:+ m = torch.nn.Sequential(torch.nn.Linear(512, 512)).to(torch.bfloat16)+ from torchao.quantization import quantize_++ quantize_(m, _make_quant_config(scheme))+ helpers = PS._torchao_helpers()+ if helpers is None:+ continue+ helpers[0](m.state_dict())+ return scheme, True+ except Exception: # noqa: BLE001+ continue+ if PS._torchao_helpers() is None:+ pytest.skip("torchao safetensors helpers unavailable")+ return "fp8", False+++_SCHEME: Optional[tuple[str, bool]] = None++[email protected](scope = "module")+def scheme() -> str:+ global _SCHEME+ if _SCHEME is None:+ _SCHEME = _usable_scheme()+ return _SCHEME[0]+++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("UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH", raising = False)+ C._HEADER_MEMO.clear()+ return root+++def _fam(base: Path) -> types.SimpleNamespace:+ return types.SimpleNamespace(name = FAMILY, transformer_class = "Tiny", base_repo = str(base))+++def _write_base(+ tmp_path: Path,+ seed: int = 0,+ name: str = "base",+) -> tuple[Path, Tiny]:+ from safetensors.torch import save_file++ torch.manual_seed(seed)+ model = Tiny().to(torch.bfloat16)+ base = tmp_path / name+ (base / "transformer").mkdir(parents = True)+ save_file(+ {k: v.contiguous() for k, v in model.state_dict().items()},+ str(base / "transformer" / "diffusion_pytorch_model.safetensors"),+ )+ return base, model+++def _quantize(model: Tiny, scheme: str) -> Tiny:+ exclude = exclude_tokens_for_scheme(scheme, FAMILY) + ("lora_",)+ divisible = divisible_for_scheme(scheme)+ if _SCHEME is not None and _SCHEME[1] and _SCHEME[0] == scheme:+ from torchao.quantization import quantize_+ quantize_(+ model,+ _make_quant_config(scheme),+ filter_fn = make_filter_fn(+ 512,+ exclude_name_tokens = exclude,+ require_bf16 = scheme in _REQUIRE_BF16_SCHEMES,+ require_divisible = divisible,+ ),+ )+ model._unsloth_runtime_quant_info = {+ "scheme": scheme,+ "family": FAMILY,+ "min_features": 512,+ "exclude_name_tokens": list(exclude),+ "require_bf16": scheme in _REQUIRE_BF16_SCHEMES,+ "require_divisible": divisible,+ "fast_accum": None,+ "convrot_group": None,+ "convrot_fqns": [],+ "dtype": str(torch.bfloat16),+ }+ return model+++def _flat_equal(a: dict, b: dict) -> list:+ fa, _ = C._flatten(a)+ fb, _ = C._flatten(b)+ assert set(fa) == set(fb)+ bad = []+ for k in fa:+ x, y = fa[k], fb[k]+ x = x.tensor() if isinstance(x, C._FlatRef) else x+ y = y.tensor() if isinstance(y, C._FlatRef) else y+ if x.dtype != y.dtype or x.shape != y.shape:+ bad.append(k)+ continue+ if not torch.equal(x.reshape(-1).view(torch.uint8), y.reshape(-1).view(torch.uint8)):+ bad.append(k)+ return bad+++# ------------------------------------------------------------------------------------------------ round trip+def test_round_trip_is_bit_identical_and_validates(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ assert path is not None and Path(path).is_file()+ assert C.lookup(fam, scheme, base_repo = str(base)) == path++ ckpt = PS.load_prequant_safetensors(path, mmap = True)+ assert _flat_equal(model.state_dict(), ckpt["state_dict"]) == []+ meta = ckpt["metadata"]+ assert meta["scheme"] == scheme and meta["component"] == "transformer"+ assert meta["base_model_id"] == str(base) and meta["min_features"] == 512++ from core.inference.diffusion_prequant import _validate_checkpoint++ assert _validate_checkpoint(+ ckpt, scheme, str(base), None, min_features = 512, component = "transformer"+ )+ # A second save of an existing entry is a no-op.+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+++def test_streaming_writer_matches_safetensors_reader(tmp_path):+ tensors = {+ "a": torch.randn(3, 5).to(torch.bfloat16),+ "b": torch.arange(7, dtype = torch.int8),+ "c": torch.randn(2, 2, dtype = torch.float32),+ "empty": torch.empty(0, 4, dtype = torch.float16),+ "flag": torch.tensor([True, False]),+ }+ path = tmp_path / "x.safetensors"+ size = C.write_streaming_safetensors(path, tensors, {"k": "v"})+ assert size == path.stat().st_size+ from safetensors import safe_open++ with safe_open(str(path), framework = "pt") as fh:+ assert fh.metadata() == {"k": "v"}+ for name, value in tensors.items():+ assert torch.equal(fh.get_tensor(name), value), name+ # And through the mmap reader the hosted loader uses (it checks the byte ranges tile the file exactly).+ _meta, mapped = PS._mapped_tensors(str(path))+ for name, value in tensors.items():+ assert torch.equal(mapped[name], value), name+++# ------------------------------------------------------------------------------------------------ key+def test_key_changes_with_source_scheme_and_policy(env, tmp_path, scheme, monkeypatch):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ assert C.save_runtime_quant(model, fam, base_repo = str(base))+ assert C.lookup(fam, scheme, base_repo = str(base))++ other = "int8" if scheme == "fp8" else "fp8"+ assert C.lookup(fam, other, base_repo = str(base)) is None+ assert C.lookup(fam, scheme, base_repo = str(base), component = "transformer_2") is None++ monkeypatch.setattr(C, "POLICY_VERSION", C.POLICY_VERSION + 1)+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+ monkeypatch.setattr(C, "POLICY_VERSION", C.POLICY_VERSION - 1)+ assert C.lookup(fam, scheme, base_repo = str(base))++ # Same architecture (identical header), different weights: the content identity changes the key.+ shard = base / "transformer" / "diffusion_pytorch_model.safetensors"+ header_before = C.read_header_bytes(shard)+ from safetensors.torch import save_file++ torch.manual_seed(123)+ save_file(+ {k: v.contiguous() for k, v in Tiny().to(torch.bfloat16).state_dict().items()}, str(shard)+ )+ os.utime(shard, ns = (time.time_ns() + 10_000_000, time.time_ns() + 10_000_000))+ assert C.read_header_bytes(shard) == header_before+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+++def test_hub_blob_name_is_the_content_identity(tmp_path):+ blob = tmp_path / ("a" * 64)+ blob.write_bytes(b"x")+ assert C._content_identity(str(blob), blob.stat()) == "blob:" + "a" * 64+ plain = tmp_path / "model.safetensors"+ plain.write_bytes(b"x")+ assert C._content_identity(str(plain), plain.stat()).startswith("stat:")+++def test_missing_source_shards_is_a_miss(env, tmp_path, scheme):+ fam = _fam(tmp_path / "nowhere")+ assert C.lookup(fam, scheme, base_repo = str(tmp_path / "nowhere")) is None+++def test_uncached_schemes_never_key(env, tmp_path):+ base, _ = _write_base(tmp_path)+ assert C.lookup(_fam(base), "nvfp4", base_repo = str(base)) is None+++# ------------------------------------------------------------------------------------------------ atomicity+def test_interrupted_write_leaves_no_entry(env, tmp_path, scheme, monkeypatch):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)++ wrote = []++ def boom(+ path,+ tensors,+ metadata = None,+ cancel_check = None,+ hasher = None,+ ):+ with open(path, "wb") as fh:+ fh.write(b"partial")+ wrote.append(path)+ raise OSError("killed mid-write")++ monkeypatch.setattr(C, "write_streaming_safetensors", boom)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ assert wrote, "the stub must really write partial bytes, or this passes on a signature error"+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+ # The root's lock file and the per-key build lease are the cache's own, not a partial entry.+ leftovers = [+ p+ for p in env.rglob("*")+ if p.is_file()+ and p.name not in (C.LAST_USED_NAME, C._LOCK_NAME)+ and not p.name.endswith(".writing")+ ]+ assert leftovers == []+++def test_artifact_without_manifest_or_wrong_size_is_a_miss(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = Path(C.save_runtime_quant(model, fam, base_repo = str(base)))+ manifest = path.parent / C.MANIFEST_NAME+ data = json.loads(manifest.read_text())+ data["bytes"] += 1+ manifest.write_text(json.dumps(data))+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+ manifest.unlink()+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+++# ------------------------------------------------------------------------------------------------ switches, disk+def test_kill_switch(env, tmp_path, scheme, monkeypatch):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ monkeypatch.setenv(C.ENV_MODE, "0")+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ assert not env.exists() or not any(env.iterdir())+ monkeypatch.delenv(C.ENV_MODE)+ assert C.save_runtime_quant(model, fam, base_repo = str(base))+ monkeypatch.setenv(C.ENV_MODE, "0")+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+++def test_disk_short_skips_the_save(env, tmp_path, scheme, monkeypatch):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ usage = types.SimpleNamespace(total = 1 << 40, used = 1 << 40, free = 1 << 20)+ monkeypatch.setattr(C.shutil, "disk_usage", lambda _p: usage)+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is None+ assert not any(p.name == C.FILE_NAME for p in env.rglob("*"))+++def test_baked_lora_and_native_and_other_dtypes_skip(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ model._unsloth_runtime_quant_info["lora"] = True+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ model._unsloth_runtime_quant_info.pop("lora")+ model._unsloth_runtime_quant_info["dtype"] = str(torch.float16)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ model._unsloth_runtime_quant_info = {"scheme": "int8", "native": True}+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ del model._unsloth_runtime_quant_info+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+++def test_lora_keys_in_the_state_dict_skip(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ model.blocks[0].lora_A = torch.nn.Linear(4, 4)+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is None+++def test_runtime_filter_mismatch_skips(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ model._unsloth_runtime_quant_info["min_features"] = 256+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is None+++def test_fp8_forced_non_default_accumulate_is_not_cached_under_the_auto_label(env, tmp_path):+ """A precise-accumulate fp8 build must not be stored as the auto (fast) artifact a default load would restore."""+ from core.inference.diffusion_transformer_quant import _resolve_fast_accum++ base, model = _write_base(tmp_path)+ _quantize(model, "fp8")+ model._unsloth_runtime_quant_info["fast_accum"] = not _resolve_fast_accum(None)+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is None+ assert C.lookup(_fam(base), "fp8", base_repo = str(base)) is None+ # The auto mode (and a forced value equal to it) is what the key and the metadata describe.+ model._unsloth_runtime_quant_info["fast_accum"] = _resolve_fast_accum(None)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert path is not None and C.lookup(_fam(base), "fp8", base_repo = str(base)) == path++[email protected](not torch.cuda.is_available(), reason = "needs a CUDA device")+def test_a_save_hands_the_flatten_copies_back_to_the_device(env, tmp_path, scheme):+ from safetensors.torch import save_file++ torch.manual_seed(0)+ model = torch.nn.Sequential(*[torch.nn.Linear(4096, 4096) for _ in range(4)]).to(torch.bfloat16)+ base = tmp_path / "big"+ (base / "transformer").mkdir(parents = True)+ save_file(+ {k: v.contiguous() for k, v in model.state_dict().items()},+ str(base / "transformer" / "diffusion_pytorch_model.safetensors"),+ )+ model = _quantize(model.cuda(), scheme)+ torch.cuda.synchronize()+ torch.cuda.empty_cache()+ before = torch.cuda.memory_reserved()+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is not None+ assert torch.cuda.memory_reserved() <= before+++# ------------------------------------------------------------------------------------------------ eviction+def test_lru_eviction_spares_recent_and_kept_keys(env):+ env.mkdir(parents = True)+ now = time.time()+ dirs = []+ for i, age in enumerate((7200, 3600, 30)):+ d = env / (f"{i:x}" * 32)[:32]+ d.mkdir()+ (d / C.FILE_NAME).write_bytes(b"\0" * 1000)+ os.utime(d / C.FILE_NAME, (now - age, now - age))+ (d / C.LAST_USED_NAME).touch()+ os.utime(d / C.LAST_USED_NAME, (now - age, now - age))+ dirs.append(d)+ removed = C.evict(root = env, max_bytes = 1500)+ # Oldest goes first; the 30 s old key is inside the grace window and stays even over budget.+ assert removed == [dirs[0].name, dirs[1].name]+ assert dirs[2].exists()+ assert (+ C.evict(root = env, max_bytes = 0) == []+ ) # max_bytes=0 -> nothing over budget except grace-held+++def test_budget_env(monkeypatch):+ monkeypatch.setenv(C.ENV_MAX_GB, "0")+ assert C.max_cache_bytes() is None+ monkeypatch.setenv(C.ENV_MAX_GB, "2")+ assert C.max_cache_bytes() == 2 << 30+ monkeypatch.setenv(C.ENV_MAX_GB, "junk")+ assert C.max_cache_bytes() == int(C.DEFAULT_MAX_GB * (1 << 30))+++# ------------------------------------------------------------------------------------------------ trust+def test_cache_root_is_trusted_without_the_allowlist_and_symlinks_cannot_escape(+ env, tmp_path, scheme+):+ from core.inference.diffusion_prequant import (+ _local_prequant_path_allowed,+ local_prequant_path_ready,+ )++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert C.path_in_cache(path)+ assert _local_prequant_path_allowed(path) and local_prequant_path_ready(path)++ outside = tmp_path / "outside" / C.FILE_NAME+ outside.parent.mkdir()+ outside.write_bytes(b"x")+ assert not _local_prequant_path_allowed(str(outside))+ link_dir = env / ("f" * 32)+ link_dir.mkdir()+ (link_dir / C.FILE_NAME).symlink_to(outside)+ assert not C.path_in_cache(link_dir / C.FILE_NAME)+ assert not _local_prequant_path_allowed(str(link_dir / C.FILE_NAME))+ # Only the artifact name at key depth counts, not any file under the root.+ stray = env / "stray.safetensors"+ stray.write_bytes(b"x")+ assert not C.path_in_cache(stray)+++def test_resolver_falls_back_to_the_cache_only_without_a_hosted_repo(env, tmp_path, scheme):+ from core.inference.diffusion_prequant import resolve_prequant_source, usable_prequant_source++ base, model = _write_base(tmp_path)+ fam = _fam(base)+ assert resolve_prequant_source(fam, scheme, base_repo = str(base)) is None+ _quantize(model, scheme)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ src = resolve_prequant_source(fam, scheme, base_repo = str(base))+ assert src is not None and src.kind == "path" and src.location == path+ usable = usable_prequant_source(fam, scheme, base_repo = str(base))+ assert usable is not None and usable.location == path+ # An explicit override still wins.+ override = resolve_prequant_source(+ fam, scheme, path_override = "/x/y.safetensors", base_repo = str(base)+ )+ assert override.location == "/x/y.safetensors"+++# ------------------------------------------------------------------------------------------------ quantize stamp+def test_quantize_transformer_stamps_what_the_cache_needs(env, tmp_path, scheme, monkeypatch):+ import core.inference.diffusion_transformer_quant as Q++ if not _SCHEME[1]:+ pytest.skip("torchao cannot quantize on this host's CPU")+ base, model = _write_base(tmp_path)+ monkeypatch.setattr(Q, "select_transformer_quant_scheme", lambda *a, **k: scheme)+ monkeypatch.setattr(Q, "native_quant_scheme", lambda *a, **k: None)+ pipe = types.SimpleNamespace(transformer = model)+ target = types.SimpleNamespace(dtype = torch.bfloat16, device = "cpu")+ assert Q.quantize_transformer(pipe, target, mode = scheme, family = FAMILY) == scheme+ info = model._unsloth_runtime_quant_info+ assert (+ info["scheme"] == scheme+ and info["min_features"] == 512+ and "lora_" in info["exclude_name_tokens"]+ )+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert path and C.lookup(_fam(base), scheme, base_repo = str(base)) == path+++# ------------------------------------------------------------------------------------------------ host RAM+def test_streaming_save_does_not_hold_the_state_dict_on_the_host(tmp_path):+ """ru_maxrss of a child writing 384 MB: the streaming writer adds far less than the payload, save_file about it."""+ script = textwrap.dedent(+ f"""+ import resource, sys+ sys.path.insert(0, {str(BACKEND)!r})+ import torch+ from core.inference.diffusion_prequant_cache import write_streaming_safetensors+ tensors = {{f"t{{i}}": torch.ones(1024, 1024, 24, dtype = torch.uint8) for i in range(16)}}+ before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss+ if sys.argv[1] == "stream":+ write_streaming_safetensors(sys.argv[2], tensors, {{}})+ else:+ from safetensors.torch import save_file+ save_file(tensors, sys.argv[2])+ after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss+ print((after - before) // 1024)+ """+ )+ env = {**os.environ, "CUDA_VISIBLE_DEVICES": ""}++ def grow(mode: str) -> int:+ out = subprocess.run(+ [sys.executable, "-c", script, mode, str(tmp_path / f"{mode}.st")],+ capture_output = True,+ text = True,+ env = env,+ timeout = 300,+ )+ assert out.returncode == 0, out.stderr[-2000:]+ return int(out.stdout.strip().splitlines()[-1])++ stream_mb = grow("stream")+ assert stream_mb < 64, stream_mb+ assert (tmp_path / "stream.st").stat().st_size > 384 * 2**20+++def test_full_pipeline_image_quantize_is_saved_to_the_cache(monkeypatch):+ """A model_kind=pipeline load quantizes in its own loop (not _load_dense_quant_pipeline); it must save too."""+ import inspect++ from core.inference import diffusion as D++ calls = []+ monkeypatch.setattr(+ C, "save_runtime_quant", lambda t, fam, **kw: calls.append((t, fam, kw)) or "/x"+ )+ pipe = types.SimpleNamespace(transformer = object())+ fam = types.SimpleNamespace(name = FAMILY)+ save = D.DiffusionBackend._save_pipeline_quant_to_cache+ assert (+ save(pipe, fam, [("transformer", pipe.transformer)], loras = [], base = "b", source_base = "/src")+ == "/x"+ )+ assert calls and calls[0][0] is pipe.transformer and calls[0][2]["source_base"] == "/src"+ calls.clear()+ # Two denoisers (no lookup slot for the second), an active LoRA, or no family: nothing saved.+ two = [("transformer", object()), ("transformer_2", object())]+ assert save(pipe, fam, two, loras = [], base = "b", source_base = None) is None+ assert (+ save(+ pipe,+ fam,+ [("transformer", pipe.transformer)],+ loras = [("a", 1.0)],+ base = "b",+ source_base = None,+ )+ is None+ )+ assert (+ save(pipe, None, [("transformer", pipe.transformer)], loras = [], base = "b", source_base = None)+ is None+ )+ assert calls == []+ # And the pipeline-kind quantize loop calls it once every denoiser engaged.+ src = inspect.getsource(D.DiffusionBackend.load_pipeline)+ engaged = src.index("if engaged and len(engaged) == len(denoisers):")+ assert "_save_pipeline_quant_to_cache(" in src[engaged : engaged + 600]+++def test_source_shards_are_found_in_the_pre_change_hub_root(tmp_path, monkeypatch):+ """After a cache-folder change the key must still come from shards in the import-time Hub root."""+ from huggingface_hub import constants+ from safetensors.torch import save_file++ old_root, live_root = tmp_path / "old_hub", tmp_path / "live_hub"+ live_root.mkdir()+ repo = "org/tiny"+ snap = old_root / "models--org--tiny" / "snapshots" / ("c" * 40) / "transformer"+ snap.mkdir(parents = True)+ (old_root / "models--org--tiny" / "refs").mkdir(parents = True)+ (old_root / "models--org--tiny" / "refs" / "main").write_text("c" * 40)+ save_file({"w": torch.zeros(4)}, str(snap / "diffusion_pytorch_model.safetensors"))+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(old_root))+ monkeypatch.setattr(C, "_hub_cache_dir", lambda: str(live_root))+ found = C.source_shards(repo)+ assert found and found[0].endswith("diffusion_pytorch_model.safetensors")+ # An explicit cache_dir is still that root only.+ assert C.source_shards(repo, cache_dir = str(live_root)) is None+++def _old_entry(root: Path, name: str, nbytes: int, age: float) -> Path:+ d = root / name+ d.mkdir(parents = True)+ (d / C.FILE_NAME).write_bytes(b"\0" * nbytes)+ stamp = time.time() - age+ for f in (C.FILE_NAME, C.LAST_USED_NAME):+ (d / f).touch()+ os.utime(d / f, (stamp, stamp))+ return d+++def test_a_full_volume_rotates_stale_entries_out_before_skipping_the_save(+ env, tmp_path, scheme, monkeypatch+):+ """Old entries filling the volume must be evicted to make room, not make every new save fail for good."""+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ stale = _old_entry(env, "a" * 32, 4096, age = 7200)+ disk = {"free": 1 << 20}++ def usage(_p):+ # Free space comes back once the stale entry is gone.+ free = disk["free"] if stale.exists() else 1 << 40+ return types.SimpleNamespace(total = 1 << 41, used = 0, free = free)++ monkeypatch.setattr(C.shutil, "disk_usage", usage)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert path is not None and not stale.exists()+++def test_eviction_rechecks_an_entry_another_process_just_resolved(env, monkeypatch):+ """The scan's last-used time is stale once another process resolves the entry: it must survive."""+ env.mkdir(parents = True)+ entry = _old_entry(env, "b" * 32, 1000, age = 7200)+ real_dir_bytes = C._dir_bytes++ def dir_bytes(path):+ # Another process resolves (and so touches) the entry right after this process scanned it.+ if path == entry:+ C._touch(entry)+ return real_dir_bytes(path)++ monkeypatch.setattr(C, "_dir_bytes", dir_bytes)+ assert C.evict(root = env, max_bytes = 0) == []+ assert entry.exists()+++def test_lookup_takes_the_eviction_lock_for_its_check_and_touch(env, tmp_path, scheme, monkeypatch):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ held = []+ real_entry = C._entry+ monkeypatch.setattr(C, "_entry", lambda key: held.append(C._LOCK_DEPTH[0]) or real_entry(key))+ assert C.lookup(_fam(base), scheme, base_repo = str(base)) == path+ assert held == [1]+++def test_the_cache_lock_is_a_real_lock_on_windows(env, monkeypatch):+ """No fcntl (Windows): the lookup / eviction sections must still hold a cross-process lock, via msvcrt."""+ calls = []+ fake = types.SimpleNamespace(+ LK_LOCK = 1,+ LK_UNLCK = 0,+ locking = lambda fd, mode, nbytes: calls.append((mode, nbytes)),+ )+ monkeypatch.setitem(sys.modules, "fcntl", None) # import fcntl -> ImportError+ monkeypatch.setitem(sys.modules, "msvcrt", fake)+ with C._cache_lock(env):+ assert calls == [(fake.LK_LOCK, 1)]+ assert calls == [(fake.LK_LOCK, 1), (fake.LK_UNLCK, 1)]+++def test_a_windows_lock_that_stays_contended_still_runs_the_section(env, monkeypatch):+ def locking(fd, mode, nbytes):+ raise OSError("deadlock avoided")++ monkeypatch.setitem(sys.modules, "fcntl", None)+ monkeypatch.setitem(+ sys.modules, "msvcrt", types.SimpleNamespace(LK_LOCK = 1, LK_UNLCK = 0, locking = locking)+ )+ ran = []+ with C._cache_lock(env):+ ran.append(True)+ assert ran == [True]+++def test_an_artifact_over_the_budget_never_evicts_the_existing_cache(+ env, tmp_path, scheme, monkeypatch+):+ """A save the budget will refuse anyway must not first evict valid entries to make disk room for it."""+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ stale = _old_entry(env, "c" * 32, 4096, age = 7200)+ monkeypatch.setenv(+ C.ENV_MAX_GB, str(1 / (1 << 30))+ ) # a 1-byte budget: every artifact is over it+ usage = types.SimpleNamespace(total = 1 << 41, used = 0, free = 1 << 20)+ monkeypatch.setattr(C.shutil, "disk_usage", lambda _p: usage)+ assert C.save_runtime_quant(model, _fam(base), base_repo = str(base)) is None+ assert stale.exists()+++def test_bases_sharing_their_weights_but_not_their_identity_never_share_an_entry(+ env, tmp_path, scheme+):+ """Two bases whose shards are one Hub blob (a mirror and its upstream under different names) fingerprint alike,+ but the loader validates the artifact's recorded base_model_id against the requested base: each needs its own+ entry."""+ base_a, model = _write_base(tmp_path, name = "model-a")+ shard = "transformer/diffusion_pytorch_model.safetensors"+ blob = tmp_path / "blobs" / ("ab" * 32)+ blob.parent.mkdir()+ os.replace(base_a / shard, blob)+ base_b = tmp_path / "model-b"+ (base_b / "transformer").mkdir(parents = True)+ for b in (base_a, base_b):+ os.symlink(blob, b / shard)+ assert C.source_fingerprint([base_a / shard]) == C.source_fingerprint([base_b / shard])+ _quantize(model, scheme)+ assert C.save_runtime_quant(model, _fam(base_a), base_repo = str(base_a))+ assert C.lookup(_fam(base_b), scheme, base_repo = str(base_b)) is None+ path_b = C.save_runtime_quant(model, _fam(base_b), base_repo = str(base_b))+ assert path_b is not None+ header = json.loads(C.read_header_bytes(path_b)[8:])+ assert json.loads(header["__metadata__"][PS.UNSLOTH_METADATA_KEY])["base_model_id"] == str(+ base_b+ )+ assert C.lookup(_fam(base_a), scheme, base_repo = str(base_a)) != path_b+++def _corrupt_in_place(path: str) -> None:+ """Same-size corruption: manifest key and byte count still match, so ``_entry`` accepts it."""+ size = os.path.getsize(path)+ with open(path, "r+b") as fh:+ fh.write(b"\xff" * min(size, 64))+++def test_an_entry_the_loader_rejects_is_replaced_by_the_dense_build(env, tmp_path, scheme):+ from core.inference.diffusion_prequant import PrequantSource, load_prequantized_transformer++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ good = Path(path).read_bytes()+ _corrupt_in_place(path)+ assert C._entry(Path(path).parent.name) is not None # size-valid: still looks cached++ source = PrequantSource(kind = "path", location = path, filename = None)+ out = load_prequantized_transformer(+ Tiny, str(base), source, device = "cpu", dtype = torch.bfloat16, scheme = scheme+ )+ assert out is None+ # The load's dense fallback then saves: the corrupt entry is replaced, not kept as "already cached".+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) == path+ assert Path(path).read_bytes() == good+ # Replaced once: a further save of the now good entry is skipped again.+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+++def test_a_forced_accumulate_mismatch_is_not_a_bad_entry(env, tmp_path, scheme, monkeypatch):+ """A forced fp8 accumulate the entry does not bake is the request's choice: the entry stays for default loads."""+ from core.inference import diffusion_prequant as P++ monkeypatch.setattr(P, "hosted_fast_accum_conflict", lambda s, f: f is not None)+ rejected = []+ monkeypatch.setattr(C, "note_rejected", lambda path, logger = None: rejected.append(path))+ source = P.PrequantSource(+ kind = "path", location = str(env / ("d" * 32) / C.FILE_NAME), filename = None+ )+ kwargs = dict(device = "cpu", dtype = torch.bfloat16, scheme = "fp8")+ assert P.load_prequantized_transformer(Tiny, "x", source, fast_accum = False, **kwargs) is None+ assert rejected == []+ assert P.load_prequantized_transformer(Tiny, "x", source, **kwargs) is None+ assert len(rejected) == 1+++def _flip_payload_byte(path: str, tensor_suffix: str) -> None:+ """Same-size corruption inside one tensor's payload (the header, key and byte count all still match)."""+ raw = C.read_header_bytes(path)+ header = json.loads(raw[8:])+ name = next(k for k in header if k != "__metadata__" and k.endswith(tensor_suffix))+ start = len(raw) + header[name]["data_offsets"][0]+ with open(path, "r+b") as fh:+ fh.seek(start)+ byte = fh.read(1)+ fh.seek(start)+ fh.write(bytes([byte[0] ^ 0x5A]))+++ "victim", ["to_q._weight_qdata|to_q.weight", "norm.bias", "unsloth_root::pad_token"]+)+def test_same_size_corruption_of_any_tensor_fails_the_payload_digest(+ env, tmp_path, scheme, monkeypatch, victim+):+ """Quantized weights, plain tensors the filter left alone and root-level parameters alike: a flipped byte anywhere+ in the artifact refuses it before its tensors are read."""+ from core.inference import diffusion_prequant as P++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert C.verify_entry(path)+ names = json.loads(C.read_header_bytes(path)[8:])+ suffix = next(v for v in victim.split("|") if any(k.endswith(v) for k in names))+ _flip_payload_byte(path, suffix)+ assert not C.verify_entry(path)++ reads = []+ monkeypatch.setattr(P, "_read_prequant_for", lambda *a, **k: reads.append(a) or {})+ source = P.PrequantSource(kind = "path", location = path, filename = None)+ assert (+ P.load_prequantized_transformer(+ Tiny, str(base), source, device = "cpu", dtype = torch.bfloat16, scheme = scheme+ )+ is None+ )+ assert reads == []+++def test_the_save_takes_no_uncancellable_pass_over_the_weights(env, tmp_path, scheme, monkeypatch):+ """The payload digest is taken inside the cancellable writer: no whole-model fingerprint pass before it."""+ from core.inference import diffusion_prequant as P++ def boom(*_a, **_k):+ raise AssertionError("whole-model fingerprint pass outside the writer")++ monkeypatch.setattr(P, "canonical_weight_fingerprint", boom)+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ path = C.save_runtime_quant(model, _fam(base), base_repo = str(base))+ assert path is not None+ manifest = json.loads((Path(path).parent / C.MANIFEST_NAME).read_text())+ import hashlib++ assert manifest["sha256"] == hashlib.sha256(Path(path).read_bytes()).hexdigest()+++def test_the_rejected_artifact_is_reclaimed_before_measuring_room_for_its_replacement(+ env, tmp_path, scheme, monkeypatch+):+ """A corrupt entry filling a nearly full volume: deleting it is what makes room for its own replacement."""+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ good = Path(path).read_bytes()+ _corrupt_in_place(path)+ C.note_rejected(path)+ kdir = Path(path).parent+ marker = kdir / "old-artifact-still-here"+ marker.touch()++ def usage(_p):+ # Room for the replacement only once the rejected entry's bytes are gone.+ return types.SimpleNamespace(+ total = 1 << 41, used = 0, free = (1 << 20) if marker.exists() else (1 << 40)+ )++ monkeypatch.setattr(C.shutil, "disk_usage", usage)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) == path+ assert Path(path).read_bytes() == good+++def test_a_cancelled_load_stops_the_cache_write_between_tensors(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ calls = []++ def cancel_check():+ calls.append(1)+ if len(calls) > 2:+ raise RuntimeError("Diffusion load was cancelled.")++ assert (+ C.save_runtime_quant(model, _fam(base), base_repo = str(base), cancel_check = cancel_check)+ is None+ )+ assert len(calls) == 3+ # the root lock and the per-key build lease are the cache's own files, not a partial entry+ leftovers = [+ p+ for p in env.rglob("*")+ if p.is_file() and p.name != C._LOCK_NAME and not p.name.endswith(".writing")+ ]+ assert leftovers == []+++def test_every_load_path_hands_its_cancellation_check_to_the_cache_save():+ import inspect++ from core.inference import diffusion as D+ from core.inference import video as V++ dense = inspect.getsource(D.DiffusionBackend._load_dense_quant_pipeline)+ assert "cancel_check = check_cancelled" in dense+ pipeline = inspect.getsource(D.DiffusionBackend.load_pipeline)+ assert "_save_pipeline_quant_to_cache(" in pipeline and "cancel_check = lambda" in pipeline+ assert "cancel_check = cancel_check" in inspect.getsource(+ D.DiffusionBackend._save_pipeline_quant_to_cache+ )+ video = inspect.getsource(V.VideoBackend.load_pipeline)+ assert (+ "_raise_if_video_load_superseded(_load_token)"+ in video.split("_save_runtime_quant_to_cache(", 1)[1][:400]+ )+ assert "cancel_check = cancel_check" in inspect.getsource(V._save_runtime_quant_to_cache)+++def test_a_local_shard_replaced_with_its_size_and_mtime_kept_is_a_new_source(env, tmp_path):+ """A metadata-preserving replacement (same header, size and mtime, different weights) must change the key."""+ from safetensors.torch import save_file++ base, _model = _write_base(tmp_path)+ shard = base / "transformer" / "diffusion_pytorch_model.safetensors"+ before = C.source_fingerprint([shard])+ st = shard.stat()+ torch.manual_seed(321)+ fresh = tmp_path / "fresh.safetensors"+ save_file(+ {k: v.contiguous() for k, v in Tiny().to(torch.bfloat16).state_dict().items()}, str(fresh)+ )+ assert fresh.stat().st_size == st.st_size+ os.replace(fresh, shard)+ os.utime(shard, ns = (st.st_atime_ns, st.st_mtime_ns))+ assert shard.stat().st_mtime_ns == st.st_mtime_ns and shard.stat().st_size == st.st_size+ assert C.source_fingerprint([shard]) != before+++def _hub_snapshot(+ tmp_path: Path,+ base_dir: Path,+ commit: str = "c" * 40,+) -> tuple[str, str]:+ """Lay ``base_dir``'s shard out like the Hub cache: snapshots/<commit>/<file> -> blobs/<sha256>."""+ import hashlib++ shard = base_dir / "transformer" / "diffusion_pytorch_model.safetensors"+ data = shard.read_bytes()+ blob_name = hashlib.sha256(data).hexdigest()+ repo_dir = tmp_path / "hub" / "models--org--tiny"+ (repo_dir / "blobs").mkdir(parents = True)+ (repo_dir / "blobs" / blob_name).write_bytes(data)+ snap = repo_dir / "snapshots" / commit / "transformer"+ snap.mkdir(parents = True)+ link = snap / "diffusion_pytorch_model.safetensors"+ os.symlink(repo_dir / "blobs" / blob_name, link)+ return str(link), blob_name+++def test_an_online_hit_on_a_hub_snapshot_is_revalidated_against_the_moved_main(+ env, tmp_path, scheme, monkeypatch+):+ import huggingface_hub++ from core.inference import diffusion_prequant as P++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ link, blob = _hub_snapshot(tmp_path, base)+ monkeypatch.setattr(C, "source_shards", lambda *_a, **_k: [link])+ monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", False)+ C._REMOTE_MEMO.clear()+ remote = {"etag": blob, "calls": 0}++ def metadata(url, **_k):+ remote["calls"] += 1+ assert "org/tiny" in url and "transformer/diffusion_pytorch_model.safetensors" in url+ return types.SimpleNamespace(etag = remote["etag"])++ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", metadata)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = "org/tiny")+ assert path and C.lookup(fam, scheme, base_repo = "org/tiny") == path # main unchanged: a hit++ C._REMOTE_MEMO.clear()+ remote["etag"] = "f" * 64 # main moved to new weights+ assert C.lookup(fam, scheme, base_repo = "org/tiny") is None++ # Offline or local-files-only: the local snapshot stands, and the Hub is not asked.+ C._REMOTE_MEMO.clear()+ calls = remote["calls"]+ token = P._LOCAL_FILES_ONLY.set(True)+ try:+ assert C.lookup(fam, scheme, base_repo = "org/tiny") == path+ finally:+ P._LOCAL_FILES_ONLY.reset(token)+ monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True)+ assert C.lookup(fam, scheme, base_repo = "org/tiny") == path+ assert remote["calls"] == calls++ # Unanswerable (network down, gated without a token): the local snapshot stands.+ monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", False)++ def down(url, **_k):+ raise OSError("network unreachable")++ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", down)+ assert C.lookup(fam, scheme, base_repo = "org/tiny") == path+++def test_the_freshness_check_of_a_gated_base_carries_the_loads_token(env, monkeypatch):+ import huggingface_hub++ from core.inference.diffusion_prequant import scoped_local_files_only++ seen = []++ def metadata(+ url,+ token = None,+ **_k,+ ):+ seen.append(token)+ return types.SimpleNamespace(etag = "e" * 64)++ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", metadata)+ C._REMOTE_MEMO.clear()++ @scoped_local_files_only+ def load(**_kwargs):+ return C._remote_etag("org/gated", "transformer/diffusion_pytorch_model.safetensors")++ assert load(hf_token = "hf_request_token") == "e" * 64+ assert seen == ["hf_request_token"]+++def test_an_entry_the_loader_rejected_is_a_miss_until_replaced(env, tmp_path, scheme):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ try:+ C.note_rejected(path)+ assert C.lookup(fam, scheme, base_repo = str(base)) is None+ _corrupt_in_place(path)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) == path # the replacement+ assert C.lookup(fam, scheme, base_repo = str(base)) == path+ finally:+ C._REJECTED.clear()+++def test_entries_written_minutes_ago_do_not_hold_the_cache_over_budget(env):+ """Several saves inside the grace window: the oldest goes once over budget; one resolved seconds ago stays."""+ env.mkdir(parents = True)+ older = _old_entry(env, "1" * 32, 1000, age = 300)+ newer = _old_entry(env, "2" * 32, 1000, age = 200)+ active = _old_entry(env, "3" * 32, 1000, age = 5)+ assert C.evict(root = env, max_bytes = 1500) == [older.name, newer.name]+ assert active.exists()+++# ------------------------------------------------------------------------------------------------ review fixes+def test_the_flatten_writes_torchaos_bytes_without_cloning_the_quantized_payload(+ env, tmp_path, scheme+):+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ state = model.state_dict()+ flatten, _ = PS._torchao_helpers()+ # the previous whole-dict flatten: torchao over every non-root key at once, root keys appended under the prefix+ roots = PS._root_level_keys(state)+ whole, whole_meta = flatten({k: v for k, v in state.items() if k not in set(roots)})+ whole, whole_meta = dict(whole), dict(whole_meta)+ for key in roots:+ whole[f"{PS.UNSLOTH_ROOT_PREFIX}{key}"] = state[key]+ if roots:+ whole_meta[PS.UNSLOTH_ROOT_KEYS_KEY] = json.dumps([str(k) for k in roots])+ flat, header = C._flatten(state)+ if any(type(v) is not torch.Tensor for v in state.values()):+ # quantized fields point at the live module's storage instead of a torchao clone+ assert any(isinstance(v, C._FlatRef) for v in flat.values())+ assert sorted(flat) == sorted(whole) and header == {**whole_meta}+ a, b = tmp_path / "ref.safetensors", tmp_path / "new.safetensors"+ C.write_streaming_safetensors(a, dict(whole), dict(whole_meta))+ C.write_streaming_safetensors(b, flat, header)+ assert a.read_bytes() == b.read_bytes()+++def _copy_snapshot(+ tmp_path: Path,+ base_dir: Path,+ commit: str = "d" * 40,+) -> str:+ """A Hub cache laid out without symlinks (Windows without Developer Mode): the file copied into the snapshot."""+ shard = base_dir / "transformer" / "diffusion_pytorch_model.safetensors"+ snap = tmp_path / "hub_copy" / "models--org--tiny" / "snapshots" / commit / "transformer"+ snap.mkdir(parents = True)+ target = snap / "diffusion_pytorch_model.safetensors"+ target.write_bytes(shard.read_bytes())+ return str(target)+++def test_a_hub_cache_without_symlinks_is_judged_by_its_commit_not_its_filename(+ env, tmp_path, scheme, monkeypatch+):+ import huggingface_hub++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ commit = "d" * 40+ copy = _copy_snapshot(tmp_path, base, commit)+ monkeypatch.setattr(C, "source_shards", lambda *_a, **_k: [copy])+ monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", False)+ C._REMOTE_MEMO.clear()+ etags = {"main": "a" * 64, commit: "a" * 64}++ def metadata(url, **_k):+ rev = "main" if "/resolve/main/" in url else commit+ return types.SimpleNamespace(etag = etags[rev])++ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", metadata)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = "org/tiny")+ assert path and C.lookup(fam, scheme, base_repo = "org/tiny") == path # unchanged weights: a hit+ C._REMOTE_MEMO.clear()+ etags["main"] = "b" * 64 # main moved past the snapshot's commit+ assert C.lookup(fam, scheme, base_repo = "org/tiny") is None+++def test_a_builder_rechecks_after_taking_the_key_lease(env, tmp_path, scheme, monkeypatch):+ """Two processes building one key: the second waits on the lease, then skips the first's published entry."""+ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ first = C.save_runtime_quant(model, fam, base_repo = str(base))+ assert first+ entry = Path(first)+ before = entry.stat().st_mtime_ns+ real = C._writer_lock+ took = []++ @C.contextmanager+ def lease(root, key):+ took.append(key)+ with real(root, key) as ok:+ yield ok++ monkeypatch.setattr(C, "_writer_lock", lease)+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) is None+ assert took and entry.stat().st_mtime_ns == before+++def test_eviction_skips_an_entry_whose_build_is_in_progress(env):+ old = _old_entry(env, "a" * 32, 4 << 20, age = 10_000)+ with C._writer_lock(env, old.name) as ok:+ assert ok and C._writer_active(env, old.name)+ assert C.evict(root = env, max_bytes = 0) == []+ assert old.is_dir()+ assert not C._writer_active(env, old.name)+ assert C.evict(root = env, max_bytes = 0) == [old.name]+++def test_auto_never_promotes_a_lower_rung_through_the_local_cache():+ import inspect++ from core.inference import diffusion as D+ from core.inference import video as V++ planned = inspect.getsource(D.DiffusionBackend._pipeline_planned_denoiser_scheme)+ assert "rung != scheme and _is_local_cache_entry(source)" in planned+ retry = inspect.getsource(D.DiffusionBackend._auto_prequant_retry_scheme)+ assert "_is_local_cache_entry(source)" in retry+ video = inspect.getsource(V.VideoBackend.load_pipeline)+ save_at = video.index("_save_runtime_quant_to_cache(")+ assert "if transformer_quant_pinned is not None:" in video[save_at - 400 : save_at]+++def test_is_local_cache_entry(env, tmp_path):+ from core.inference import diffusion as D++ inside = env / ("e" * 32) / C.FILE_NAME+ inside.parent.mkdir(parents = True)+ inside.write_bytes(b"x")+ assert D._is_local_cache_entry(types.SimpleNamespace(kind = "path", location = str(inside)))+ outside = tmp_path / "own.safetensors"+ outside.write_bytes(b"x")+ assert not D._is_local_cache_entry(types.SimpleNamespace(kind = "path", location = str(outside)))+ assert not D._is_local_cache_entry(types.SimpleNamespace(kind = "repo", location = "unsloth/x"))+++def test_a_commit_pinned_hub_snapshot_without_refs_main_is_found_by_repo_id(+ env, tmp_path, scheme, monkeypatch+):+ """A commit-pinned base (no refs/main) must still be found by the next lookup by repo id."""+ import huggingface_hub++ from core.inference import diffusion_prequant as P++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ commit = "d" * 40+ _hub_snapshot(tmp_path, base, commit = commit)+ hub = tmp_path / "hub"+ repo_dir = hub / "models--org--tiny"+ assert not (repo_dir / "refs" / "main").exists()+ monkeypatch.setattr(C, "_hub_cache_dir", lambda: str(hub))+ monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_CACHE", str(hub))+ fam = _fam(base)+ path = C.save_runtime_quant(+ model, fam, base_repo = "org/tiny", source_base = str(repo_dir / "snapshots" / commit)+ )+ assert path is not None+ token = P._LOCAL_FILES_ONLY.set(True)+ try:+ assert C.lookup(fam, scheme, base_repo = "org/tiny") == path+ finally:+ P._LOCAL_FILES_ONLY.reset(token)+++def test_an_entry_the_planner_header_probe_drops_is_replaced_by_the_dense_build(+ env, tmp_path, scheme+):+ """Header corruption dropped by the planner probe (loader hook never fires) must still be replaced."""+ from core.inference.diffusion_prequant import usable_prequant_source++ base, model = _write_base(tmp_path)+ _quantize(model, scheme)+ fam = _fam(base)+ path = C.save_runtime_quant(model, fam, base_repo = str(base))+ good = Path(path).read_bytes()+ _corrupt_in_place(path)+ assert usable_prequant_source(fam, scheme, base_repo = str(base)) is None+ assert C.save_runtime_quant(model, fam, base_repo = str(base)) == path+ assert Path(path).read_bytes() == good+ assert usable_prequant_source(fam, scheme, base_repo = str(base)).location == path+++def test_the_video_save_fingerprints_the_repo_that_supplied_the_dense_weights():+ """Without a staged local dir the video key must come from fetch_base's shards (maybe the mirror)."""+ import inspect++ from core.inference import video as V++ video = inspect.getsource(V.VideoBackend.load_pipeline)+ call = video.split("_save_runtime_quant_to_cache(", 1)[1][:400]+ assert "source = _base_local_dir or fetch_base," in calldiff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.pyindex 7674672ec74..aeb64658b1b 100644--- a/studio/backend/tests/test_video_prequant.py+++ b/studio/backend/tests/test_video_prequant.py@@ -1916,3 +1916,18 @@ def test_unreadability_is_reported_only_when_it_is_what_kept_bfloat16(monkeypatcmonkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda *a, **k: True)monkeypatch.setattr(vid, "_h3_free_device_bytes", lambda device: 80 * 1000**3)assert ask() == vid.H3_AUTO_FALLBACK_SCHEME and fired == []+++def test_an_explicit_cached_scheme_seeds_even_when_another_scheme_is_hosted(monkeypatch):+ """HunyuanVideo-1.5 hosts nvfp4; an explicit locally cached int8 must still seed."""+ from core.inference import video as vid+ from core.inference import video_denoiser_prequant as vdp++ monkeypatch.setattr(vid, "video_family_prequant_schemes", lambda fam: ("nvfp4",))+ sources = {"nvfp4": object(), "int8": object()} # int8 resolves only through the local cache+ monkeypatch.setattr(+ vdp, "denoiser_prequant_sources", lambda fam, s, base, hf_token = None: sources.get(s)+ )+ assert _video_auto(monkeypatch, scheme = "int8", requested = "int8") == "int8"+ sources.pop("int8")+ assert _video_auto(monkeypatch, scheme = "int8", requested = "int8") is None