Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: video component sizes from safetensors headers, measured peaks for every video family (#13537)

Daniel Hanbc3114d5c7c7
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index ecab9d63233..0aa189c7145 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -5545,12 +5545,11 @@ class DiffusionBackend:
pinned: tuple[str, ...] = (),
) -> Optional[int]:
"""A half load narrows only a file stored wider throughout (a mixed file pins its fp32 norms)."""
+ from .diffusion_component_sizes import read_safetensors_header
try:
- with open(path, "rb") as fh:
- length = int.from_bytes(fh.read(8), "little")
- if length > 100_000_000:
- return None
- header = json.loads(fh.read(length))
+ header = read_safetensors_header(path, max_bytes = 100_000_000)
+ if header is None:
+ return None
tensors = []
for name, meta in header.items():
if name == "__metadata__" or not isinstance(meta, dict):
@@ -5893,10 +5892,11 @@ class DiffusionBackend:
def _safetensors_param_count(path: Path) -> int:
"""Total tensor elements in a safetensors file, read from its JSON header without touching
the tensor data. 0 on any read/parse failure."""
+ from .diffusion_component_sizes import read_safetensors_header
try:
- with open(path, "rb") as fh:
- header_len = int.from_bytes(fh.read(8), "little")
- header = json.loads(fh.read(header_len))
+ header = read_safetensors_header(path)
+ if header is None:
+ return 0
total = 0
for name, meta in header.items():
if name == "__metadata__" or not isinstance(meta, dict):
@@ -11943,14 +11943,11 @@ def _pipeline_components_from_index(
if not isinstance(payload, dict):
raise ValueError(f"{repo_id}/model_index.json is not an object")
if explicit_components is None:
+ from .diffusion_component_sizes import manifest_entry_loaded
+
+ # the same predicate the size planner reads the manifest with
selected = {
- str(name)
- for name, spec in payload.items()
- if not str(name).startswith("_")
- and isinstance(spec, (list, tuple))
- and len(spec) >= 2
- and spec[0] is not None
- and spec[1] is not None
+ str(name) for name, spec in payload.items() if manifest_entry_loaded(name, spec)
}
else:
selected = {str(name) for name in explicit_components}
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.py
index fc993b2ac3e..66b3b118a7f 100644
--- a/studio/backend/core/inference/diffusion_cache.py
+++ b/studio/backend/core/inference/diffusion_cache.py
@@ -741,6 +741,12 @@ def effective_request_strength(
return pipe_default_strength if isinstance(pipe_default_strength, (int, float)) else None
+def auto_step_cache_mode(steps: int) -> Optional[str]:
+ """The cache mode an AUTO decision runs for ``steps`` (before the runner check): FBCache at
+ ``FBCACHE_MIN_STEPS``+, else uncached. The single rule ``maybe_toggle_step_cache`` applies."""
+ return TC_FBCACHE if int(steps) >= FBCACHE_MIN_STEPS else None
+
+
def maybe_toggle_step_cache(
pipe: Any,
*,
@@ -756,7 +762,7 @@ def maybe_toggle_step_cache(
if transformer is None:
return None
engaged = getattr(transformer, "_unsloth_step_cache", None)
- want = int(steps) >= FBCACHE_MIN_STEPS
+ want = auto_step_cache_mode(steps) is not None
if want and not engaged:
return apply_step_cache(
pipe,
diff --git a/studio/backend/core/inference/diffusion_component_sizes.py b/studio/backend/core/inference/diffusion_component_sizes.py
new file mode 100644
index 00000000000..29633526194
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_component_sizes.py
@@ -0,0 +1,1223 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Component sizes of a diffusers pipeline from safetensors headers; the family tables stay the offline fallback."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import struct
+import threading
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Iterable, Optional
+
+logger = logging.getLogger(__name__)
+
+MAX_HEADER_BYTES = 256 * 1024 * 1024
+# Bits per element of every floating dtype safetensors names. Float8 / float6 / float4 / MX scales count as float:
+# loaded at bf16 they occupy 2 bytes per parameter. Sub-byte types are packed: the header ``shape`` is the logical
+# element count and the byte span is numel * bits / 8 (an F4 [4, 16] tensor spans 32 bytes), so parameters are
+# counted as bytes * 8 / bits.
+FLOAT_BITS = {
+ "F64": 64,
+ "F32": 32,
+ "F16": 16,
+ "BF16": 16,
+ "F8_E4M3": 8,
+ "F8_E5M2": 8,
+ "F8_E4M3FNUZ": 8,
+ "F8_E5M2FNUZ": 8,
+ "F8_E8M0": 8,
+ "F6_E2M3": 6,
+ "F6_E3M2": 6,
+ "F4": 4,
+}
+FLOAT_WIDTH = {k: v / 8 for k, v in FLOAT_BITS.items()}
+_GB = 1000.0**3
+
+ReadRange = Callable[[int, int], bytes]
+
+
+def parse_safetensors_header(
+ read: Callable[[int], bytes], *, max_bytes: int = MAX_HEADER_BYTES
+) -> dict:
+ """Raises ValueError on a non-safetensors file or implausible header length."""
+ raw = read(8)
+ if len(raw) != 8:
+ raise ValueError("not a safetensors file")
+ (length,) = struct.unpack("<Q", raw)
+ if not 0 < length <= max_bytes:
+ raise ValueError("implausible safetensors header length")
+ body = read(length)
+ if len(body) != length:
+ raise ValueError("truncated safetensors header")
+ header = json.loads(body)
+ if not isinstance(header, dict):
+ raise ValueError("safetensors header is not an object")
+ return header
+
+
+def read_safetensors_header(path: Any, *, max_bytes: int = MAX_HEADER_BYTES) -> Optional[dict]:
+ """None when unreadable. Never raises."""
+ try:
+ with open(path, "rb") as fh:
+ return parse_safetensors_header(fh.read, max_bytes = max_bytes)
+ except Exception: # noqa: BLE001 - unreadable / crafted header: no claim about this file
+ return None
+
+
+def tensor_entries(header: Optional[dict]) -> Iterable[tuple[str, dict]]:
+ for name, meta in (header or {}).items():
+ if name != "__metadata__" and isinstance(meta, dict):
+ yield name, meta
+
+
+def entry_numel(meta: dict) -> int:
+ numel = 1
+ for dim in meta.get("shape", []) or []:
+ numel *= int(dim)
+ return numel
+
+
+def entry_nbytes(meta: dict) -> int:
+ begin, end = meta["data_offsets"]
+ return int(end) - int(begin)
+
+
+@dataclass(frozen = True)
+class ComponentSize:
+ name: str
+ stored_bytes: int
+ float_params: int
+ nonfloat_bytes: int
+ bytes_by_dtype: tuple[tuple[str, int], ...] = field(default_factory = tuple)
+ files: tuple[str, ...] = field(default_factory = tuple)
+ # Of the totals above: tensors under the LTX loader's connector key prefixes bundled into a denoiser folder. The
+ # loader splits them off (video_ltx2._checkpoint_group) and the pack prices them as its own connectors/ folder.
+ bundled_connector_float_params: int = 0
+ bundled_connector_nonfloat_bytes: int = 0
+
+ @property
+ def params(self) -> int:
+ return self.float_params
+
+ def resident_bytes(self, itemsize: int = 2) -> int:
+ """Bytes on device after every float tensor is cast to ``itemsize`` bytes (non-float tensors as stored)."""
+ return self.float_params * int(itemsize) + self.nonfloat_bytes
+
+ def resident_bytes_without_bundled_connectors(self, itemsize: int = 2) -> int:
+ return self.resident_bytes(itemsize) - (
+ self.bundled_connector_float_params * int(itemsize)
+ + self.bundled_connector_nonfloat_bytes
+ )
+
+ def resident_gb(self, itemsize: int = 2) -> float:
+ return self.resident_bytes(itemsize) / _GB
+
+
+@dataclass(frozen = True)
+class ComponentSizes:
+ components: dict
+ source: str = "local"
+ revision: Optional[str] = None
+ # Component names model_index.json declares (None when it was not read).
+ manifest: Optional[frozenset] = None
+ # Folders holding weights whose size could not be read (a .bin checkpoint, an unreadable header or index).
+ unknown: frozenset = frozenset()
+ # Stored bytes of the weight files in each ``unknown`` folder (an upper bound of its bf16-resident size for any
+ # checkpoint stored at >= 2 bytes per parameter), when known.
+ unknown_bytes: tuple = ()
+
+ def get(self, name: str) -> Optional[ComponentSize]:
+ return self.components.get(name)
+
+ def names(self) -> tuple[str, ...]:
+ return tuple(sorted(self.components))
+
+ def resident_gb(
+ self,
+ names: Iterable[str],
+ itemsize: int = 2,
+ ) -> float:
+ return (
+ sum(self.components[n].resident_bytes(itemsize) for n in names if n in self.components)
+ / _GB
+ )
+
+
+def _accumulate(
+ name: str, headers: Iterable[tuple[str, Optional[dict]]]
+) -> Optional[ComponentSize]:
+ stored = float_params = nonfloat = 0
+ conn_params = conn_nonfloat = 0
+ connector_group = _connector_key_matcher() if str(name).startswith("transformer") else None
+ by_dtype: dict[str, int] = {}
+ files: list[str] = []
+ seen: set = set()
+ for fname, header in headers:
+ if header is None:
+ return None # a missing shard makes the component unknown, never smaller
+ files.append(fname)
+ for tname, meta in tensor_entries(header):
+ if tname in seen:
+ continue
+ seen.add(tname)
+ try:
+ nbytes = entry_nbytes(meta)
+ dtype = str(meta.get("dtype", ""))
+ numel = entry_numel(meta)
+ except Exception: # noqa: BLE001
+ return None
+ stored += nbytes
+ bundled = connector_group is not None and connector_group(tname)
+ if dtype in FLOAT_BITS:
+ bits = FLOAT_BITS[dtype]
+ params = numel if bits >= 8 else (nbytes * 8) // bits
+ float_params += params
+ by_dtype[dtype] = by_dtype.get(dtype, 0) + nbytes
+ if bundled:
+ conn_params += params
+ else:
+ nonfloat += nbytes
+ if bundled:
+ conn_nonfloat += nbytes
+ if not files or stored <= 0:
+ return None
+ return ComponentSize(
+ name = name,
+ stored_bytes = stored,
+ float_params = float_params,
+ nonfloat_bytes = nonfloat,
+ bytes_by_dtype = tuple(sorted(by_dtype.items())),
+ files = tuple(files),
+ bundled_connector_float_params = conn_params,
+ bundled_connector_nonfloat_bytes = conn_nonfloat,
+ )
+
+
+def _connector_key_matcher() -> Optional[Callable[[str], bool]]:
+ """Whether a tensor key is a connector tensor, by the LTX loader's own grouping; None if it cannot load."""
+ try:
+ from .video_ltx2 import _checkpoint_group
+ return lambda key: _checkpoint_group(key)[0] == "connectors"
+ except Exception: # noqa: BLE001
+ return None
+
+
+# The loader's default weight stems (diffusion.py _DEFAULT_PIPELINE_WEIGHT_RE), safetensors only.
+_DEFAULT_WEIGHT_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)(?:-\d{5}-of-\d{5})?\.safetensors$"
+)
+_SHARD_RE = re.compile(r"^.+-\d{5}-of-\d{5}\.safetensors$")
+_INDEX_RE = re.compile(
+ r"^(?:diffusion_pytorch_model|pytorch_model|model)\.safetensors\.index\.json$"
+)
+
+
+_TRANSFORMERS_FOLDER_RE = re.compile(r"^(?:text_encoder|image_encoder|prompt_enhancer)(?:_\d+)?$")
+
+
+def _stem_order(folder: str) -> tuple[str, ...]:
+ """LTX-2's text_encoder/ ships both stems; only the preferred one loads. ``pytorch_model`` is the legacy stem."""
+ if _TRANSFORMERS_FOLDER_RE.match(folder or ""):
+ # transformers' PreTrainedModel.from_pretrained reads model.safetensors / its index, else pytorch_model.bin
+ # (not sized here, so the folder is unknown); never diffusion_pytorch_model.* or pytorch_model.safetensors
+ return ("model",)
+ return ("diffusion_pytorch_model", "model", "pytorch_model")
+
+
+def select_weight_files(
+ names: Iterable[str],
+ index_files: Optional[Iterable[str]] = None,
+ folder: str = "",
+) -> list[str]:
+ """Listed ``index_files`` win over stray shards of an older layout."""
+ names = [n for n in names if n.endswith(".safetensors")]
+ if index_files:
+ listed = sorted(set(index_files))
+ if all(n in names for n in listed):
+ return listed
+ return [] # an index naming a file not present: incomplete, unknown
+ # Shards without an index are unknown, never the sum of whatever is present.
+ for stem in _stem_order(folder):
+ if f"{stem}.safetensors" in names:
+ return [f"{stem}.safetensors"]
+ if any(_SHARD_RE.match(n) and n.startswith(stem + "-") for n in names):
+ return []
+ # Nothing else is selected: from_pretrained reads only these stems (Studio passes no variant, so a
+ # diffusion_pytorch_model.fp16.safetensors twin is not read either), never e.g. adapter_model.safetensors.
+ return []
+
+
+_WEIGHT_SUFFIXES = (
+ ".safetensors",
+ ".bin",
+ ".pt",
+ ".pth",
+ ".ckpt",
+ ".gguf",
+ ".safetensors.index.json",
+ ".bin.index.json",
+)
+
+
+def _is_weight_file(name: str) -> bool:
+ return str(name).endswith(_WEIGHT_SUFFIXES) and not str(name).endswith(".index.json")
+
+
+def _holds_weights(names: Iterable[str]) -> bool:
+ return any(str(n).endswith(_WEIGHT_SUFFIXES) for n in names)
+
+
+def _read_capped_file(path: Path, cap: int) -> str:
+ if path.stat().st_size > cap:
+ raise ValueError(f"{path.name} is larger than {cap} bytes")
+ return path.read_text(encoding = "utf-8")
+
+
+def _index_shards(text: str) -> Optional[list[str]]:
+ try:
+ weight_map = json.loads(text).get("weight_map") or {}
+ return sorted(set(str(v) for v in weight_map.values()))
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _pick_files(
+ names: Iterable[str],
+ read_text: Callable[[str], str],
+ folder: str = "",
+) -> list[str]:
+ """Only the loader's PREFERRED index counts (it never falls back to a stale second one); unreadable or
+ naming a missing shard makes the component unknown, never a smaller subset."""
+ names = list(names)
+ # Same-stem order follows the loader: transformers (5.5 modeling_utils._get_resolved_checkpoint_files) takes an
+ # unsharded model.safetensors before the index; diffusers (ModelMixin.from_pretrained, _fetch_index_file) takes
+ # the index first.
+ unsharded_first = bool(_TRANSFORMERS_FOLDER_RE.match(folder or ""))
+ for stem in _stem_order(folder):
+ index = f"{stem}.safetensors.index.json"
+ if unsharded_first and f"{stem}.safetensors" in names:
+ return [f"{stem}.safetensors"]
+ if index in names:
+ try:
+ shards = _index_shards(read_text(index))
+ except Exception: # noqa: BLE001
+ shards = None
+ if shards and all(s in names for s in shards):
+ return select_weight_files(names, shards, folder)
+ return []
+ if any(
+ _DEFAULT_WEIGHT_RE.match(n) and n.startswith((stem + ".", stem + "-")) for n in names
+ ):
+ return select_weight_files(
+ [n for n in names if n.startswith((stem + ".", stem + "-"))], folder = folder
+ )
+ return select_weight_files(names, folder = folder)
+
+
+def local_component_sizes(
+ root: Any, components: Optional[Iterable[str]] = None
+) -> Optional[ComponentSizes]:
+ """None when unreadable or weightless. Never raises."""
+ try:
+ base = Path(root)
+ if not base.is_dir():
+ return None
+ wanted = set(components) if components is not None else None
+ out: dict[str, ComponentSize] = {}
+ unknown: set = set()
+ unknown_bytes: dict = {}
+ for sub in sorted(p for p in base.iterdir() if p.is_dir()):
+ if wanted is not None and sub.name not in wanted:
+ continue
+ names = [p.name for p in sub.iterdir() if p.is_file()]
+ files = _pick_files(
+ names, lambda n, sub = sub: _read_capped_file(sub / n, MAX_INDEX_BYTES), sub.name
+ )
+ size = (
+ _accumulate(sub.name, ((f, read_safetensors_header(sub / f)) for f in files))
+ if files
+ else None
+ )
+ if size is not None:
+ out[sub.name] = size
+ elif _holds_weights(names):
+ unknown.add(sub.name)
+ unknown_bytes[sub.name] = sum(
+ (sub / n).stat().st_size for n in names if _is_weight_file(n)
+ )
+ if not out:
+ return None
+ return ComponentSizes(
+ out,
+ source = "local",
+ manifest = _manifest_names(base),
+ unknown = frozenset(unknown),
+ unknown_bytes = tuple(sorted(unknown_bytes.items())),
+ )
+ except Exception: # noqa: BLE001
+ return None
+
+
+def manifest_entry_loaded(name: Any, spec: Any) -> bool:
+ """Whether a ``model_index.json`` entry is a component the pipeline loads: a public name whose spec is a
+ ``[library, class]`` list with both set. The ONE predicate, shared with the loader's staging selection
+ (DiffusionBackend download plan), so sizing and loading cannot disagree about what is loaded."""
+ return (
+ not str(name).startswith("_")
+ and isinstance(spec, (list, tuple))
+ and len(spec) >= 2
+ and spec[0] is not None
+ and spec[1] is not None
+ )
+
+
+def _manifest_from_text(text: str) -> Optional[frozenset]:
+ try:
+ data = json.loads(text)
+ if not isinstance(data, dict):
+ return None
+ return frozenset(k for k, v in data.items() if manifest_entry_loaded(k, v))
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _manifest_names(root: Path) -> Optional[frozenset]:
+ """Components ``model_index.json`` loads (an entry set to null is not loaded)."""
+ try:
+ path = root / "model_index.json"
+ if not path.is_file() or path.stat().st_size > MAX_MANIFEST_BYTES:
+ return None
+ return _manifest_from_text(path.read_text(encoding = "utf-8"))
+ except Exception: # noqa: BLE001
+ return None
+
+
+def active_cache_dir() -> Optional[str]:
+ """Studio's LIVE hub cache root, not huggingface_hub's import-time default."""
+ try:
+ from utils.hf_cache_settings import active_hf_hub_cache
+ return active_hf_hub_cache()
+ except Exception: # noqa: BLE001
+ return None
+
+
+def local_snapshot_dir(repo_id: str, cache_dir: Any = None) -> Optional[Path]:
+ try:
+ from .diffusion_small_host import resolve_snapshot_dir
+ return resolve_snapshot_dir(
+ repo_id, cache_dir if cache_dir is not None else active_cache_dir()
+ )
+ except Exception: # noqa: BLE001
+ return None
+
+
+HUB_TIMEOUT_SECONDS = 20.0
+HUB_RETRY_SECONDS = 600.0
+# Mutable-ref answers revalidate after this; headers are re-read only if the commit changed.
+HUB_REFRESH_SECONDS = 600.0
+_HUB_CACHE: dict = {}
+_HUB_SHA_CACHE: dict = {}
+_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+
+
+def _token_id(token: Any) -> Optional[str]:
+ """Token digest: a gated repo read with one token is never served to a load without it."""
+ if not token or not isinstance(token, str):
+ return None if not token else "implicit"
+ import hashlib
+
+ return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
+
+
+_HUB_LOCK = threading.Lock()
+
+
+def hub_disabled() -> bool:
+ try:
+ from .diffusion_prequant import _LOCAL_FILES_ONLY
+ if _LOCAL_FILES_ONLY.get():
+ return True
+ except Exception: # noqa: BLE001
+ pass
+ if (os.environ.get("UNSLOTH_DIFFUSION_HEADER_FETCH") or "").strip().lower() in (
+ "0",
+ "off",
+ "false",
+ "no",
+ ):
+ return True
+ return (os.environ.get("HF_HUB_OFFLINE") or "").strip().lower() in ("1", "on", "true", "yes")
+
+
+def _hub_header(
+ repo_id: str, filename: str, revision: str, token: Any, size: int, deadline: float
+) -> Optional[dict]:
+ try:
+ from huggingface_hub import hf_hub_url
+ from huggingface_hub.utils import build_hf_headers
+
+ from .prequant_header_probe import (
+ MAX_SAFETENSORS_HEADER_BYTES,
+ _hub_range_reader,
+ _json_within,
+ )
+
+ reader = _hub_range_reader(
+ hf_hub_url(repo_id, filename, revision = revision),
+ dict(build_hf_headers(token = token)),
+ deadline,
+ )
+ (length,) = struct.unpack("<Q", reader(0, 7))
+ if not 0 < length <= MAX_SAFETENSORS_HEADER_BYTES or 8 + length > size:
+ return None
+ raw = reader(8, 8 + length - 1)
+ if not _json_within(raw):
+ return None
+ header = json.loads(raw.decode("utf-8"))
+ return header if isinstance(header, dict) else None
+ except Exception: # noqa: BLE001
+ return None
+
+
+MAX_INDEX_BYTES = 64 * 1024 * 1024
+MAX_MANIFEST_BYTES = 1 << 20
+
+
+def _fetch_capped_text(
+ session: Any,
+ url: str,
+ headers: dict,
+ timeout: float,
+ deadline: float,
+ cap: int = MAX_INDEX_BYTES,
+) -> str:
+ """Refuses past ``cap`` while streaming, so an oversized (or lying) index is never buffered whole. Works on
+ both clients huggingface_hub ships: httpx (1.x, ``Client.stream``, redirects followed to the CDN) and requests
+ (0.x, ``stream=True``); see ``diffusion_compat._ranged_stream``.
+
+ The whole fetch (connect, headers, body) runs on a worker behind the same watchdog as the ranged-header reader
+ (``prequant_header_probe._hub_range_reader``): past ``deadline`` the read is interrupted with
+ ``diffusion_compat._interrupt_read`` and abandoned, so a peer trickling bytes cannot outlive the deadline."""
+ import time
+
+ from .diffusion_compat import _interrupt_read, _iter_body
+
+ holder: list = [None]
+ result: list = []
+ failure: list = []
+
+ def _fetch() -> None:
+ try:
+ if callable(getattr(session, "stream", None)):
+ opened = session.stream(
+ "GET", url, headers = headers, timeout = timeout, follow_redirects = True
+ )
+ else:
+ opened = session.get(url, headers = headers, timeout = timeout, stream = True)
+ with opened as response:
+ holder[0] = response
+ response.raise_for_status()
+ declared = (
+ response.headers.get("Content-Length")
+ if getattr(response, "headers", None)
+ else None
+ )
+ if declared is not None and int(declared) > cap:
+ raise ValueError("index too large")
+ body = bytearray()
+ for chunk in _iter_body(response, 65536):
+ body.extend(chunk)
+ if len(body) > cap:
+ raise ValueError("index too large")
+ if time.monotonic() > deadline:
+ raise TimeoutError("index read deadline")
+ result.append(body.decode("utf-8"))
+ except BaseException as exc: # noqa: BLE001 - re-raised on the caller's thread
+ failure.append(exc)
+
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError("index read deadline")
+ worker = threading.Thread(target = _fetch, name = "component-sizes-index-read", daemon = True)
+ worker.start()
+ worker.join(min(remaining, threading.TIMEOUT_MAX))
+ if worker.is_alive():
+ _interrupt_read(holder[0])
+ raise TimeoutError("index read deadline")
+ if failure:
+ raise failure[0]
+ return result[0]
+
+
+_REF_CACHE: dict = {}
+
+
+def resolve_ref(
+ repo_id: str,
+ revision: Optional[str] = None,
+ *,
+ token: Any = None,
+ timeout_seconds: float = HUB_TIMEOUT_SECONDS,
+) -> Optional[str]:
+ """The commit sha ``revision`` (default ``main``) points at now, from one metadata call cached for
+ ``HUB_REFRESH_SECONDS`` (a failure for ``HUB_RETRY_SECONDS``). A pinned sha is returned as is. None when the Hub
+ is off or does not answer. Never raises."""
+ if revision and _SHA_RE.match(str(revision)):
+ return str(revision)
+ if hub_disabled():
+ return None
+ import time
+
+ key = (repo_id, revision, _token_id(token))
+ with _HUB_LOCK:
+ if key in _REF_CACHE:
+ sha, stamp = _REF_CACHE[key]
+ age = time.monotonic() - stamp
+ if (sha is not None and age < HUB_REFRESH_SECONDS) or (
+ sha is None and age < HUB_RETRY_SECONDS
+ ):
+ return sha
+ sha = None
+ try:
+ from huggingface_hub import HfApi
+ info = HfApi(token = token).model_info(repo_id, revision = revision, timeout = timeout_seconds)
+ sha = getattr(info, "sha", None)
+ except Exception: # noqa: BLE001
+ sha = None
+ _note_ref(repo_id, revision, token, sha)
+ return sha
+
+
+def _note_ref(repo_id: str, revision: Optional[str], token: Any, sha: Optional[str]) -> None:
+ import time
+ with _HUB_LOCK:
+ _REF_CACHE[(repo_id, revision, _token_id(token))] = (sha, time.monotonic())
+
+
+def hub_component_sizes(
+ repo_id: str,
+ *,
+ components: Optional[Iterable[str]] = None,
+ revision: Optional[str] = None,
+ token: Any = None,
+ timeout_seconds: float = HUB_TIMEOUT_SECONDS,
+) -> Optional[ComponentSizes]:
+ """Ranged header reads with the load's ``token``, cached per resolved commit. Never raises."""
+ if hub_disabled():
+ return None
+ import time
+
+ wanted = set(components) if components is not None else None
+ key = (
+ repo_id,
+ revision,
+ tuple(sorted(wanted)) if wanted is not None else None,
+ _token_id(token),
+ )
+ immutable = bool(revision and _SHA_RE.match(str(revision)))
+ with _HUB_LOCK:
+ if key in _HUB_CACHE:
+ hit, stamp = _HUB_CACHE[key]
+ age = time.monotonic() - stamp
+ if hit is not None and (immutable or age < HUB_REFRESH_SECONDS):
+ return hit
+ if hit is None and age < HUB_RETRY_SECONDS:
+ return None # never a stall per load
+ result = _hub_component_sizes(repo_id, wanted, revision, token, float(timeout_seconds))
+ with _HUB_LOCK:
+ _HUB_CACHE[key] = (result, time.monotonic())
+ return result
+
+
+def _hub_component_sizes(
+ repo_id: str, wanted: Optional[set], revision: Optional[str], token: Any, timeout_seconds: float
+) -> Optional[ComponentSizes]:
+ import time
+
+ deadline = time.monotonic() + timeout_seconds
+ try:
+ from huggingface_hub import HfApi
+ info = HfApi(token = token).model_info(
+ repo_id, revision = revision, files_metadata = True, timeout = timeout_seconds
+ )
+ except Exception: # noqa: BLE001 - offline, gated, missing: the table answers
+ return None
+ commit = getattr(info, "sha", None) or revision
+ if getattr(info, "sha", None):
+ _note_ref(repo_id, revision, token, info.sha) # the same resolve resolve_ref would make
+ sha_key = (
+ repo_id,
+ commit,
+ tuple(sorted(wanted)) if wanted is not None else None,
+ _token_id(token),
+ )
+ with _HUB_LOCK:
+ if commit and sha_key in _HUB_SHA_CACHE:
+ return _HUB_SHA_CACHE[sha_key] # the ref still points at a commit already read
+ result = _read_hub_sizes(repo_id, info, commit, wanted, token, deadline, timeout_seconds)
+ if result is not None and commit:
+ with _HUB_LOCK:
+ _HUB_SHA_CACHE[sha_key] = result
+ return result
+
+
+def _read_hub_sizes(
+ repo_id: str,
+ info: Any,
+ commit: Optional[str],
+ wanted: Optional[set],
+ token: Any,
+ deadline: float,
+ timeout_seconds: float,
+) -> Optional[ComponentSizes]:
+ import time
+
+ from huggingface_hub import hf_hub_url
+ from huggingface_hub.utils import build_hf_headers, get_session
+
+ by_folder: dict[str, dict[str, int]] = {}
+ for sib in getattr(info, "siblings", None) or ():
+ parts = str(getattr(sib, "rfilename", "")).split("/")
+ if len(parts) != 2:
+ continue
+ if wanted is not None and parts[0] not in wanted:
+ continue
+ by_folder.setdefault(parts[0], {})[parts[1]] = int(getattr(sib, "size", 0) or 0)
+ # The manifest first: a folder model_index.json omits or sets to null is not loaded, so its failure is not ours.
+ manifest = None
+ if any(str(getattr(s, "rfilename", "")) == "model_index.json" for s in info.siblings or ()):
+ try:
+ manifest = _manifest_from_text(
+ _fetch_capped_text(
+ get_session(),
+ hf_hub_url(repo_id, "model_index.json", revision = commit),
+ dict(build_hf_headers(token = token)),
+ max(1.0, deadline - time.monotonic()),
+ deadline,
+ cap = MAX_MANIFEST_BYTES,
+ )
+ )
+ except Exception: # noqa: BLE001 - no manifest: every folder counts as loaded
+ manifest = None
+ out: dict[str, ComponentSize] = {}
+ unknown: set = set()
+ unknown_bytes: dict = {}
+ try:
+ for folder, files in sorted(by_folder.items()):
+ # Studio-attached extras are never in the manifest; the caller only asks for them when attached
+ if (
+ manifest is not None
+ and folder not in manifest
+ and folder not in _LOADED_OUTSIDE_MANIFEST
+ ):
+ continue
+
+ def _read_index(n: str, folder: str = folder) -> str:
+ # never from the HF cache: a stray index there would read as a started download
+ return _fetch_capped_text(
+ get_session(),
+ hf_hub_url(repo_id, f"{folder}/{n}", revision = commit),
+ dict(build_hf_headers(token = token)),
+ max(1.0, deadline - time.monotonic()),
+ deadline,
+ )
+
+ if time.monotonic() > deadline:
+ return None
+ picked = _pick_files(list(files), _read_index, folder)
+ if not picked:
+ if any(n.endswith(".safetensors") or _INDEX_RE.match(n) for n in files):
+ return None # safetensors weights this read cannot select (index unreadable / incomplete)
+ if _holds_weights(files):
+ unknown.add(
+ folder
+ ) # a loaded .bin component: its term is unknown, never smaller
+ unknown_bytes[folder] = sum(b for n, b in files.items() if _is_weight_file(n))
+ continue
+ size = _accumulate(
+ folder,
+ (
+ (
+ f,
+ _hub_header(
+ repo_id, f"{folder}/{f}", commit, token, files.get(f, 0), deadline
+ ),
+ )
+ for f in picked
+ ),
+ )
+ if size is None:
+ # any failed header of a loaded folder voids the answer: a partial one would be cached smaller
+ return None
+ out[folder] = size
+ except Exception: # noqa: BLE001
+ return None
+ if not out:
+ return None
+ return ComponentSizes(
+ out,
+ source = "hub",
+ revision = commit,
+ manifest = manifest,
+ unknown = frozenset(unknown),
+ unknown_bytes = tuple(sorted(unknown_bytes.items())),
+ )
+
+
+def component_sizes(
+ repo_or_dir: Any,
+ *,
+ components: Optional[Iterable[str]] = None,
+ allow_hub: bool = False,
+ cache_dir: Any = None,
+ required: Any = None,
+ token: Any = None,
+) -> Optional[ComponentSizes]:
+ """Local headers, then Hub. ``required``: the folders a complete local answer must hold, or a callable of the
+ local sizes returning them (so the snapshot's own manifest can add loaded roles); others never send a cached
+ model to the Hub."""
+ if repo_or_dir is None:
+ return None
+ path = Path(str(repo_or_dir)).expanduser()
+ if path.is_dir():
+ return local_component_sizes(path, components)
+ snap = local_snapshot_dir(str(repo_or_dir), cache_dir)
+ local = local_component_sizes(snap, components) if snap is not None else None
+ if callable(required):
+ required = required(local) if local is not None else ()
+ need = (
+ tuple(required)
+ if required is not None
+ else (tuple(components) if components is not None else ())
+ )
+ if local is not None and all(c in local.components for c in need):
+ if not allow_hub or snap is None or hub_disabled():
+ return local
+ # online: the cached snapshot answers only while the ref still points at it (TTL-cached resolve)
+ # an unresolved ref (head None) is not a match: probe the Hub, and keep the local sizes only if that fails too
+ head = resolve_ref(str(repo_or_dir), token = token)
+ if head is not None and head == snap.name:
+ return local
+ if allow_hub:
+ hub = hub_component_sizes(str(repo_or_dir), components = components, token = token)
+ if hub is not None:
+ return hub
+ return local
+
+
+# Folders not named here are outside the table (unloaded, or priced separately like LTX-2.5's upsampler).
+VIDEO_ROLE_DENOISER = ("transformer", "transformer_2")
+VIDEO_ROLE_TEXT = ("text_encoder", "text_encoder_2", "text_encoder_3")
+VIDEO_ROLE_VAE = ("vae", "audio_vae", "vocoder", "connectors")
+VIDEO_EXTRA_VAE_ROLE: dict[str, tuple[str, ...]] = {"ltx-2.5": ("latent_upsampler",)}
+# Studio attaches these itself, so model_index.json never names them (LTX-2.5's latent_upsampler/).
+_LOADED_OUTSIDE_MANIFEST = frozenset(f for roles in VIDEO_EXTRA_VAE_ROLE.values() for f in roles)
+# Companion folders and when a family loads them; one that is present is counted only when its family rule says so
+# or model_index.json names it (a leftover folder in a repo is not a loaded component).
+VIDEO_COMPANION_RULES: dict[str, Callable[[Any], bool]] = {
+ "audio_vae": lambda fam: bool(getattr(fam, "has_audio", False)),
+ "vocoder": lambda fam: bool(getattr(fam, "has_audio", False)),
+ "connectors": lambda fam: str(getattr(fam, "name", "") or "").startswith("ltx"),
+ # HunyuanVideo-1.5 loads its ByT5 glyph encoder as text_encoder_2; any other extra encoder needs the manifest.
+ "text_encoder_2": lambda fam: str(getattr(fam, "name", "") or "").startswith("hunyuanvideo"),
+ "text_encoder_3": lambda fam: False,
+}
+
+
+TABLE_ROUNDING_GB = 0.06
+
+_MISMATCHES: dict = {}
+
+
+def table_mismatches() -> dict:
+ return dict(_MISMATCHES)
+
+
+def _role_loaded(fam: Any, manifest: Optional[frozenset], name: str) -> bool:
+ """Whether a load of ``fam`` uses folder ``name``: a family rule, or model_index.json naming it (Studio-attached
+ extras are decided by ``attached_extras``)."""
+ rule = VIDEO_COMPANION_RULES.get(name)
+ if rule is not None and rule(fam):
+ return True
+ return manifest is not None and name in manifest
+
+
+# When Studio attaches each extra: LTX-2.5's latent upsampler only on the two-stage distilled recipe.
+def _upsampler_attached(dev: bool) -> bool:
+ try:
+ from .video_ltx25 import ltx25_uses_upsampler
+ return bool(ltx25_uses_upsampler(bool(dev)))
+ except Exception: # noqa: BLE001
+ return True
+
+
+VIDEO_EXTRA_ATTACHED: dict[str, Callable[[bool], bool]] = {"latent_upsampler": _upsampler_attached}
+
+
+def attached_extras(fam: Any, dev: bool = False) -> tuple[str, ...]:
+ """The Studio-attached extras this load actually holds (``dev``: an LTX-2.5 dev / single-stage load)."""
+ return tuple(
+ n
+ for n in VIDEO_EXTRA_VAE_ROLE.get(str(getattr(fam, "name", "") or ""), ())
+ if VIDEO_EXTRA_ATTACHED.get(n, lambda _dev: True)(dev)
+ )
+
+
+def _second_expert_loaded(fam: Any, sizes: Optional[ComponentSizes]) -> bool:
+ """video._transformer_names: an MoE's second expert loads only when the checkpoint ships it (present, or named
+ by model_index.json); a first-expert-only checkpoint is a complete single denoiser."""
+ if not bool(getattr(fam, "is_moe", False)) or sizes is None:
+ return False
+ if sizes.manifest is not None:
+ return (
+ "transformer_2" in sizes.manifest
+ ) # authoritative: an omitted / null entry is a stale folder
+ return sizes.get("transformer_2") is not None or "transformer_2" in sizes.unknown
+
+
+def video_loaded_roles(
+ fam: Any,
+ sizes: Optional[ComponentSizes] = None,
+ dev: bool = False,
+) -> tuple[str, ...]:
+ """Every folder this load reads: the required roles plus each optional one the family, Studio (when attached) or
+ the snapshot's manifest loads. A cached snapshot missing any of them is incomplete."""
+ manifest = sizes.manifest if sizes is not None else None
+ roles = list(video_required_roles(fam))
+ if _second_expert_loaded(fam, sizes):
+ roles.append("transformer_2")
+ roles += [n for n in (*VIDEO_ROLE_TEXT[1:], *VIDEO_ROLE_VAE) if _role_loaded(fam, manifest, n)]
+ roles += list(attached_extras(fam, dev))
+ return tuple(dict.fromkeys(roles))
+
+
+def video_required_roles(fam: Any) -> tuple[str, ...]:
+ """Connectors, vocoder, upsampler, a second text encoder are optional: never a reason to go to the Hub."""
+ denoiser = getattr(fam, "denoiser_attr", None) or "transformer"
+ # an MoE's second expert is not required: see _second_expert_loaded
+ roles = [denoiser]
+ roles += ["text_encoder", "vae"]
+ if bool(getattr(fam, "has_audio", False)):
+ roles.append("audio_vae")
+ return tuple(dict.fromkeys(roles))
+
+
+def video_header_parts(
+ fam: Any,
+ sizes: Optional[ComponentSizes],
+ dev: bool = False,
+) -> tuple[tuple[Optional[float], bool], ...]:
+ """Per term ``(known_sum, complete)``: the bf16-resident GB of every loaded folder whose size is known, and
+ whether every folder the load reads is among them. An incomplete term's sum is a LOWER bound (a .bin vocoder,
+ an absent loaded role): never a reason to discard what did read. ``known_sum`` is None when nothing read."""
+ if sizes is None:
+ return ((None, False),) * 3
+ name = str(getattr(fam, "name", "") or "")
+ loaded = set(video_loaded_roles(fam, sizes, dev))
+ primary = getattr(fam, "denoiser_attr", None) or "transformer"
+ ltx = name.startswith("ltx")
+
+ def _part(
+ names: Iterable[str], itemsize_of: Callable[[str], int]
+ ) -> tuple[Optional[float], bool]:
+ names = [n for n in dict.fromkeys(names) if n in loaded]
+ known = [n for n in names if sizes.get(n) is not None]
+ complete = len(known) == len(names) and bool(names)
+ if not known:
+ return (None, False)
+ total = 0
+ for n in known:
+ size = sizes.components[n]
+ if ltx and n in VIDEO_ROLE_DENOISER:
+ # LTX: connector tensors bundled into transformer/ are split off by the loader, priced as connectors/
+ total += size.resident_bytes_without_bundled_connectors(itemsize_of(n))
+ else:
+ total += size.resident_bytes(itemsize_of(n))
+ return (total / _GB, complete)
+
+ vae_itemsize = 4 if bool(getattr(fam, "vae_force_fp32", False)) else 2
+ return (
+ _part((primary, "transformer_2"), lambda n: 2),
+ _part(VIDEO_ROLE_TEXT, lambda n: 2),
+ _part(
+ VIDEO_ROLE_VAE + attached_extras(fam, dev), lambda n: vae_itemsize if n == "vae" else 2
+ ),
+ )
+
+
+def video_header_missing(
+ fam: Any,
+ sizes: Optional[ComponentSizes],
+ dev: bool = False,
+) -> tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...]]:
+ """Per term, the folders the load reads whose size is not known (unreadable or absent)."""
+ loaded = set(video_loaded_roles(fam, sizes, dev))
+ primary = getattr(fam, "denoiser_attr", None) or "transformer"
+
+ def _missing(names: Iterable[str]) -> tuple[str, ...]:
+ return tuple(
+ n
+ for n in dict.fromkeys(names)
+ if n in loaded and (sizes is None or sizes.get(n) is None)
+ )
+
+ return (
+ _missing((primary, "transformer_2")),
+ _missing(VIDEO_ROLE_TEXT),
+ _missing(VIDEO_ROLE_VAE + attached_extras(fam, dev)),
+ )
+
+
+def _term_lower_bound(
+ known: Optional[float],
+ missing: tuple[str, ...],
+ sizes: Optional[ComponentSizes],
+ table_term: Optional[float],
+) -> Optional[float]:
+ """An incomplete term: the known part plus an allowance per unknown loaded folder, its stored file bytes when
+ readable (an upper bound at bf16), else its own table constant (a Studio-attached extra); folders with neither
+ share ONE whole table term between them. Never a smaller total than what is loaded; None without a table."""
+ if table_term is None or sizes is None:
+ return None
+ on_disk = dict(sizes.unknown_bytes)
+ allowance = 0.0
+ unestimated = False
+ for n in missing:
+ if on_disk.get(n):
+ allowance += on_disk[n] / _GB
+ elif _extra_table_gb(n):
+ allowance += _extra_table_gb(n)
+ else:
+ unestimated = True
+ if unestimated:
+ allowance += float(table_term)
+ return (known or 0.0) + allowance
+
+
+def video_header_terms(
+ fam: Any,
+ sizes: Optional[ComponentSizes],
+ dev: bool = False,
+) -> tuple[Optional[float], Optional[float], Optional[float]]:
+ """Each term when every folder it loads is known, else None (see ``video_header_parts`` for the lower bound)."""
+ return tuple(v if complete else None for v, complete in video_header_parts(fam, sizes, dev)) # type: ignore[return-value]
+
+
+def video_header_components_gb(
+ fam: Any, sizes: Optional[ComponentSizes]
+) -> Optional[tuple[float, float, float]]:
+ terms = video_header_terms(fam, sizes)
+ return None if any(t is None for t in terms) else terms # type: ignore[return-value]
+
+
+IMAGE_ROLE_DENOISER = ("transformer", "transformer_2", "unconditional_transformer", "unet", "prior")
+
+
+def image_header_components_gb(
+ sizes: Optional[ComponentSizes],
+) -> Optional[tuple[float, float, float]]:
+ """``_FAMILY_BF16_GB`` layout; None unless denoiser, text encoder and VAE are all present."""
+ if sizes is None:
+ return None
+ denoisers = [n for n in IMAGE_ROLE_DENOISER if sizes.get(n) is not None]
+ text = [
+ n
+ for n in sizes.names()
+ if re.match(r"^text_encoder(?:_\d+)?$", n)
+ and (n == "text_encoder" or sizes.manifest is None or n in sizes.manifest)
+ ]
+ if not denoisers or not text or sizes.get("vae") is None:
+ return None
+ return (sizes.resident_gb(denoisers), sizes.resident_gb(text), sizes.resident_gb(("vae",)))
+
+
+def reconcile_with_table(
+ header: Optional[tuple[float, float, float]],
+ table: Optional[tuple[float, float, float]],
+ *,
+ is_base: bool,
+ key: Any = None,
+ lower: Optional[tuple] = None,
+) -> Optional[tuple[float, float, float]]:
+ """Base repo: the table wins (disagreements recorded, never applied). Other repo: per-term max of the two.
+ An unknown header term takes the table; without a table every term must be known. ``lower``: per-term lower
+ bounds (the known part of an incomplete term); no term is ever returned below its bound."""
+ out = _reconcile(header, table, is_base = is_base, key = key)
+ if out is None or not lower:
+ return out
+ return tuple( # type: ignore[return-value]
+ max(float(v), round(float(lb), 1)) if lb is not None and h is None else v
+ for v, lb, h in zip(out, lower, header or (None,) * 3)
+ )
+
+
+def _reconcile(
+ header: Optional[tuple],
+ table: Optional[tuple],
+ *,
+ is_base: bool,
+ key: Any = None,
+) -> Optional[tuple[float, float, float]]:
+ if header is None or all(h is None for h in header):
+ return table
+ if table is None:
+ if any(h is None for h in header):
+ return None
+ return tuple(round(float(v), 1) for v in header) # type: ignore[return-value]
+ header = tuple(t if h is None else h for h, t in zip(header, table))
+ rounded = tuple(round(float(v), 1) for v in header)
+ agree = all(abs(float(h) - float(t)) <= TABLE_ROUNDING_GB for h, t in zip(header, table))
+ if agree:
+ return table
+ if key is not None and key not in _MISMATCHES:
+ _MISMATCHES[key] = (rounded, tuple(table))
+ logger.info(
+ "diffusion.sizes: %s headers %s disagree with the table %s; using the %s",
+ key,
+ rounded,
+ tuple(table),
+ "table" if is_base else "larger per term",
+ )
+ if is_base:
+ return tuple(table) # type: ignore[return-value]
+ return tuple(max(float(h), float(t)) for h, t in zip(rounded, table)) # type: ignore[return-value]
+
+
+def video_components_gb(
+ fam: Any,
+ repo: Any = None,
+ *,
+ allow_hub: bool = False,
+ token: Any = None,
+ details: Optional[dict] = None,
+ dev: bool = False,
+) -> Optional[tuple[float, float, float]]:
+ """Header sizes reconciled with ``fam.bf16_components_gb``. Never raises; None when neither answers.
+ ``details`` (filled when given): ``sizes`` (the snapshot the answer came from) and ``sources``, per term
+ "header" or "table", so a caller pricing a part of a term reads it from the same answer. ``dev``: an LTX-2.5 dev
+ (single-stage) load, which attaches no latent upsampler."""
+ table = getattr(fam, "bf16_components_gb", None)
+ if details is not None:
+ details.update(sizes = None, sources = ("table",) * 3)
+ try:
+ if getattr(fam, "modular_workflow", None):
+ return table # modular (H3) layouts are not a diffusers component tree
+ base = getattr(fam, "base_repo", None)
+ target = repo or base
+ if not target:
+ return _table_for_load(fam, table, dev)
+ is_base = str(target).lower() == str(base or "").lower()
+ wanted = (
+ *(VIDEO_ROLE_DENOISER if getattr(fam, "is_moe", False) else VIDEO_ROLE_DENOISER[:1]),
+ *(
+ ()
+ if getattr(fam, "denoiser_attr", "transformer") in VIDEO_ROLE_DENOISER
+ else (fam.denoiser_attr,)
+ ),
+ *VIDEO_ROLE_TEXT,
+ *VIDEO_ROLE_VAE,
+ # only the extras this load attaches: a dev / single-stage load never probes the latent upsampler
+ *attached_extras(fam, dev),
+ )
+ sizes = component_sizes(
+ target,
+ components = wanted,
+ required = lambda local: video_loaded_roles(fam, local, dev),
+ allow_hub = allow_hub and (table is None or not is_base),
+ token = token,
+ )
+ table = _table_for_load(fam, table, dev)
+ parts = video_header_parts(fam, sizes, dev)
+ missing = video_header_missing(fam, sizes, dev)
+ header = tuple(v if complete else None for v, complete in parts)
+ result = reconcile_with_table(
+ header,
+ table,
+ is_base = is_base,
+ key = (getattr(fam, "name", None), str(target)),
+ lower = tuple(
+ _term_lower_bound(v, missing[i], sizes, table[i] if table else None)
+ if not complete
+ else None
+ for i, (v, complete) in enumerate(parts)
+ ),
+ )
+ if details is not None and result is not None:
+ sources = tuple(
+ "table" if table is not None and float(r) == float(t) else "header"
+ for r, t in zip(result, table or (None,) * 3)
+ )
+ details.update(sizes = sizes, sources = sources)
+ return result
+ except Exception: # noqa: BLE001 - sizing aid: the table stands
+ return _table_for_load(fam, getattr(fam, "bf16_components_gb", None), dev)
+
+
+# Table GB of each Studio-attached extra inside the family table's companion term.
+def _extra_table_gb(name: str) -> float:
+ if name == "latent_upsampler":
+ from .video_ltx25 import LTX25_LATENT_UPSAMPLER_GB
+ return float(LTX25_LATENT_UPSAMPLER_GB)
+ return 0.0
+
+
+def _table_for_load(fam: Any, table: Optional[tuple], dev: bool) -> Optional[tuple]:
+ """The family table for THIS load: an extra the table's companion term includes but the load does not attach
+ (LTX-2.5's latent upsampler on a dev / single-stage load) comes out, so header and table terms compare like for
+ like and no caller subtracts it again."""
+ if table is None:
+ return None
+ detached = [
+ n
+ for n in VIDEO_EXTRA_VAE_ROLE.get(str(getattr(fam, "name", "") or ""), ())
+ if n not in attached_extras(fam, dev)
+ ]
+ if not detached:
+ return table
+ vae = round(float(table[2]) - sum(_extra_table_gb(n) for n in detached), 3)
+ return (table[0], table[1], vae)
+
+
+_SNAPSHOT_RE = re.compile(r"(?:^|/)snapshots/([0-9a-f]{40})(?:/|$)")
+
+
+def checkpoint_fingerprint(repo_or_path: Any, filename: Optional[str] = None) -> Optional[str]:
+ """What identifies the exact weights a load read, for keys that must not outlive an update: the HF cache
+ snapshot commit for a repo id (of ``filename`` when given, e.g. the picked GGUF, else ``model_index.json``), a
+ digest of ``model_index.json`` + ``transformer/config.json`` for a local folder, size + mtime for a local file.
+ None when it cannot tell. Local reads only; never raises."""
+ try:
+ import hashlib
+
+ path = Path(str(repo_or_path)).expanduser()
+ if path.is_dir():
+ digest = hashlib.sha256()
+ for rel in ("model_index.json", "transformer/config.json", "config.json"):
+ f = path / rel
+ if f.is_file() and f.stat().st_size <= MAX_MANIFEST_BYTES:
+ digest.update(rel.encode() + b"\0" + f.read_bytes() + b"\0")
+ if filename and (path / filename).is_file():
+ st = (path / filename).stat()
+ digest.update(f"{filename}:{st.st_size}:{st.st_mtime_ns}".encode())
+ return "local:" + digest.hexdigest()[:16]
+ if path.is_file():
+ st = path.stat()
+ return f"file:{st.st_size}:{st.st_mtime_ns}"
+ from huggingface_hub import try_to_load_from_cache
+
+ hit = try_to_load_from_cache(
+ str(repo_or_path), filename or "model_index.json", cache_dir = active_cache_dir()
+ )
+ if isinstance(hit, str):
+ match = _SNAPSHOT_RE.search(Path(hit).as_posix())
+ if match:
+ return match.group(1)
+ except Exception: # noqa: BLE001
+ return None
+ return None
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 31609f815e0..d7a9aab6831 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -965,20 +965,16 @@ def file_size_mib(path: Any) -> Optional[int]:
def safetensors_prefix_mib(path: Any, prefix: str) -> Optional[int]:
"""MiB of the ``prefix*`` tensors, from the safetensors header alone; None if unreadable or unmatched."""
- import json
- import struct
+ from .diffusion_component_sizes import entry_nbytes, read_safetensors_header, tensor_entries
+ header = read_safetensors_header(path)
+ if header is None:
+ return None
try:
- with open(path, "rb") as fh:
- (header_len,) = struct.unpack("<Q", fh.read(8))
- if not 0 < header_len <= 256 * 1024 * 1024:
- return None
- header = json.loads(fh.read(header_len))
total = 0
- for name, meta in header.items():
- if name != "__metadata__" and name.startswith(prefix):
- start, end = meta["data_offsets"]
- total += int(end) - int(start)
+ for name, meta in tensor_entries(header):
+ if name.startswith(prefix):
+ total += entry_nbytes(meta)
except Exception: # noqa: BLE001 - not a readable safetensors header
return None
return -(-total // (1024 * 1024)) if total > 0 else None
diff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.py
index 209b01d6e91..0349d748f8c 100644
--- a/studio/backend/core/inference/diffusion_small_host.py
+++ b/studio/backend/core/inference/diffusion_small_host.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import json
import os
-import struct
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional
@@ -52,14 +51,11 @@ _ST_DTYPES = {"BF16": "bfloat16", "F16": "float16", "F32": "float32"}
def _safetensors_bytes_by_dtype(path: Path, keep: tuple[str, ...] = ()) -> dict[str, int]:
+ from .diffusion_component_sizes import read_safetensors_header
+
out: dict[str, int] = {}
- try:
- with open(path, "rb") as fh:
- (n,) = struct.unpack("<Q", fh.read(8))
- if not 0 < n <= 256 * _MIB:
- return out
- header = json.loads(fh.read(n))
- except Exception: # noqa: BLE001 - unreadable header: no claim about this file
+ header = read_safetensors_header(path, max_bytes = 256 * _MIB)
+ if header is None: # unreadable header: no claim about this file
return out
for name, meta in header.items():
if name == "__metadata__":
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index c9514955cc6..bf853372331 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1997,12 +1997,16 @@ def _video_seed_stays_resident(
text_encoder_quant: Optional[str],
base_repo: Optional[str],
reclaimable_mib: int = 0,
+ hf_token: Optional[str] = None,
+ ltx25_dev: bool = False,
) -> bool:
"""True when an artifact-sized plan keeps the denoiser resident (text encoders may stream).
``scheme=None`` sizes the released bf16 DiT instead, and then also requires a measured budget (see
``_auto_keeps_resident_bf16``)."""
- components = getattr(fam, "bf16_components_gb", None)
+ from .diffusion_component_sizes import video_components_gb
+
+ components = video_components_gb(fam, base_repo, allow_hub = True, token = hf_token, dev = ltx25_dev)
if not components:
return scheme is not None
import torch
@@ -2465,11 +2469,16 @@ def video_offload_shortfall_message(
height: Optional[int] = None,
frames: Optional[int] = None,
decode_floor_mib: Optional[int] = None,
+ measured_extra_mib: Optional[int] = None,
) -> Optional[str]:
"""Refusal when co-resident weights plus the activation headroom exceed the device, else None.
+ ``measured_extra_mib``: a recorded peak (above the request's start) of a completed request at least this large
+ under the same load; it replaces the estimated headroom when it asks for less (margin and slack as the Wan
+ residency fit uses).
Denoise and VAE decode are separate phases: the decoded-clip share is held only beside the weights still on the
device during the decode (``decode_floor_mib``, the full floor when unknown), never beside the streamed DiT."""
headroom = DEFAULT_BASE_OVERHEAD_MIB
+ full_floor_mib = int(floor_mib)
required = int(floor_mib) + headroom
if width and height and frames:
# decoded-clip share of the runtime estimate; its fixed 4 GiB denoise base over-refuses measured cells
@@ -2484,6 +2493,14 @@ def video_offload_shortfall_message(
if decode_floor + headroom + clip_mib > required:
floor_mib, headroom = decode_floor, headroom + clip_mib
required = decode_floor + headroom
+ if measured_extra_mib is not None and measured_extra_mib > 0:
+ from .video_stream_residency import MEASURED_PEAK_MARGIN, MEASURED_SLACK_MIB
+
+ measured_headroom = int(measured_extra_mib * MEASURED_PEAK_MARGIN) + MEASURED_SLACK_MIB
+ measured_floor = full_floor_mib
+ if measured_floor + measured_headroom < required:
+ floor_mib, headroom = measured_floor, measured_headroom
+ required = measured_floor + measured_headroom
if int(available_mib) >= required:
return None
shape = f" for {width}x{height} at {frames} frames" if width and height and frames else ""
@@ -2507,6 +2524,33 @@ def _progress(phase: Optional[str], **extra: Any) -> dict[str, Any]:
# quantiser all act on ``pipe.transformer``. Wan2.2-A14B is a dual-expert MoE (transformer = high-noise, transformer_2 =
# low-noise), so present the second DiT AS ``pipe.transformer`` via a thin proxy.
# ── dual-DiT (Wan2.2-A14B MoE) helpers ────────────────────────────────────────
+def _calibration_revision(state: Any) -> Optional[str]:
+ """The exact weights this pipeline holds (cache snapshot commit / local fingerprint, plus the companion base for a
+ GGUF / single-file load), read once per pipeline."""
+ pipe = getattr(state, "pipe", None)
+ cached = getattr(pipe, "_unsloth_calibration_revision", None)
+ if cached is not None:
+ return cached or None
+ from .diffusion_component_sizes import checkpoint_fingerprint
+
+ revision = checkpoint_fingerprint(
+ getattr(state, "repo_id", None), getattr(state, "gguf_filename", None)
+ )
+ if getattr(state, "kind", "pipeline") != "pipeline":
+ # a GGUF / single-file load takes its companions from a base repo: its id and exact weights are part of it
+ base = getattr(state, "base_repo", None)
+ revision = (
+ f"{revision or ''}|base={base or ''}@{checkpoint_fingerprint(base) or ''}"
+ if base
+ else revision
+ )
+ try:
+ pipe._unsloth_calibration_revision = revision or ""
+ except Exception: # noqa: BLE001
+ pass
+ return revision
+
+
def _transformer_names(pipe: Any, fam: VideoFamily) -> tuple[str, ...]:
"""Attribute names of the denoiser(s) on ``pipe`` to optimise. Just
("transformer",) for a single-DiT family; also "transformer_2" for an MoE family
@@ -3374,6 +3418,7 @@ class VideoBackend:
text_encoder_quant = kwargs.get("text_encoder_quant"),
gpu_ordinal = kwargs.get("gpu_ordinal"),
hf_token = kwargs.get("hf_token"),
+ ltx25_dev = ltx25_dev,
)
video_seed_declined = video_auto_denoiser == DENOISER_SEED_DECLINED
if video_seed_declined:
@@ -4554,6 +4599,7 @@ class VideoBackend:
text_encoder_quant: Optional[str] = None,
gpu_ordinal: Optional[int] = None,
hf_token: Optional[str] = None,
+ ltx25_dev: bool = False,
) -> Optional[str]:
"""The pre-download auto denoiser scheme, None, or ``DENOISER_SEED_DECLINED`` if the plan would offload."""
try:
@@ -4596,6 +4642,8 @@ class VideoBackend:
text_encoder_quant = text_encoder_quant,
base_repo = base,
reclaimable_mib = reclaimable,
+ hf_token = hf_token,
+ ltx25_dev = ltx25_dev,
):
# auto keeps a resident bf16 DiT, so the dense shards are what this load runs.
return None
@@ -4610,6 +4658,8 @@ class VideoBackend:
getattr(resident, "pipe", None),
ordinal = _target_ordinal(target),
),
+ hf_token = hf_token,
+ ltx25_dev = ltx25_dev,
):
logger.info(
"video.denoiser_prequant: an artifact-sized plan for %s still offloads on "
@@ -5378,6 +5428,7 @@ class VideoBackend:
text_encoder_quant = text_encoder_quant,
gpu_ordinal = load_kwargs.get("gpu_ordinal"),
hf_token = hf_token,
+ ltx25_dev = ltx25_dev,
)
if video_planned == DENOISER_SEED_DECLINED:
video_planned = None
@@ -6309,7 +6360,18 @@ class VideoBackend:
# read as occupied.
# ── memory plan: family-table resident estimate + frames-aware headroom.
device_memory = settled_snapshot_device_memory(target)
- components = fam.bf16_components_gb
+ from .diffusion_component_sizes import video_components_gb
+
+ components = video_components_gb(
+ fam,
+ # a GGUF / single-file load takes its companions from the resolved base (a caller-supplied base_repo
+ # included), not the family default
+ repo_id if kind == "pipeline" else base,
+ allow_hub = not local_files_only,
+ token = hf_token,
+ # a dev (single-stage) LTX-2.5 load attaches no latent upsampler, so it is not a loaded role
+ dev = _ltx25_dev_load(fam, kind, gguf_filename, repo_id, display_repo_id),
+ )
mib_per_gb = 1000.0**3 / (1024.0 * 1024.0)
# bf16_components_gb is (transformer, text_encoder, vae) at bf16. When this pick takes its encoder PRE-CAST from
# a hosted fp8 checkpoint, the bf16 entry over-states what is loaded by ~11 GB for ltx-2's Gemma3-12B, which
@@ -6457,20 +6519,12 @@ class VideoBackend:
# hard refusal.
vae_gb = components[2] if components is not None else 0.0
if components is not None and fam.name == "ltx-2.5":
- from .video_ltx25 import (
- LTX25_LATENT_UPSAMPLER_GB,
- LTX25_WORKER_RESIDENT_GB,
- ltx25_uses_upsampler,
- )
+ from .video_ltx25 import LTX25_WORKER_RESIDENT_GB
# The encoder worker is a second process on the card: its CUDA context and allocator slack stay
- # resident on every tier, even when its weights are off the card.
+ # resident on every tier, even when its weights are off the card. The latent upsampler a dev (single
+ # stage) load never attaches is already out of components[2] (video_components_gb(dev=...)).
vae_gb += LTX25_WORKER_RESIDENT_GB
- # The table's companions include the latent upsampler, which a dev (single stage) load never attaches.
- if not ltx25_uses_upsampler(
- _ltx25_dev_load(fam, kind, gguf_filename, repo_id, display_repo_id)
- ):
- vae_gb -= LTX25_LATENT_UPSAMPLER_GB
vae_scale = 1.0 if getattr(fam, "vae_force_fp32", False) else dtype_scale
scaled_te_gb = text_encoder_gb * dtype_scale
scaled_vae_gb = vae_gb * vae_scale
@@ -9848,12 +9902,60 @@ class VideoBackend:
)
from . import video_stream_residency
- if video_stream_residency.applies(
+ residency_fit = video_stream_residency.applies(
fam.name,
is_moe = bool(getattr(fam, "is_moe", False)),
offload_policy = state.offload_policy,
device = state.device,
- ):
+ )
+ # The step-cache mode THIS request runs: an AUTO decision is re-taken per request below
+ # (maybe_toggle_step_cache), so the key uses the same rule now and is corrected after the
+ # runner-aware toggle if that disagrees.
+ if state.cache_auto:
+ from .diffusion_cache import auto_step_cache_mode
+ request_cache_mode = auto_step_cache_mode(steps)
+ else:
+ request_cache_mode = getattr(state, "transformer_cache", None)
+ # This request's peak sizes the next request of its size (refusal below, Wan residency fit).
+ calibration = video_stream_residency.calibration_key(
+ fam.name,
+ getattr(state, "repo_id", None),
+ state.offload_policy,
+ device_obj,
+ # the exact weights: a mutable repo updated and reloaded must not reuse old peaks
+ revision = _calibration_revision(state),
+ kind = getattr(state, "kind", None),
+ gguf_filename = getattr(state, "gguf_filename", None),
+ variant_id = getattr(state, "variant_id", None),
+ h3_task = getattr(state, "h3_task", None),
+ dtype = getattr(state, "dtype", None),
+ attention_backend = getattr(state, "attention_backend", None),
+ speed_mode = getattr(state, "speed_mode", None),
+ speed_optims = tuple(getattr(state, "speed_optims", ()) or ()),
+ transformer_cache = request_cache_mode,
+ vae_tiling = getattr(state, "vae_tiling", None),
+ memory_mode = getattr(state, "memory_mode", None),
+ transformer_quant = getattr(state, "transformer_quant", None),
+ text_encoder_quant = getattr(state, "text_encoder_quant", None),
+ # fps (audio length), keyframes / references (extra latents) and CFG all move the peak
+ fps = out_fps if getattr(fam, "has_audio", False) else None,
+ conditioning = conditioning,
+ first_frame = first_pil is not None,
+ last_frame = last_pil is not None,
+ references = len(references or ()),
+ cfg = bool(getattr(fam, "supports_cfg", True)) and float(guidance) > 1.0,
+ )
+ # Tag BEFORE the residency fit: after a reload the fit reads process-wide peaks through this key.
+ video_stream_residency.arm_request(
+ state.pipe,
+ key = calibration,
+ width = width,
+ height = height,
+ frames = frames,
+ device = device_obj,
+ rearm = False,
+ )
+ if residency_fit:
# Resident groups are allocated, so the reserved term below still counts them as available.
video_stream_residency.fit_for_request(
state.pipe,
@@ -9864,6 +9966,16 @@ class VideoBackend:
frames = frames,
logger = logger,
)
+ else:
+ # the fit arms its own measurement; every other family is armed here
+ video_stream_residency.arm_request(
+ state.pipe,
+ key = calibration,
+ width = width,
+ height = height,
+ frames = frames,
+ device = device_obj,
+ )
free_bytes, _ = trusted_mem_get_info(device_obj, module = torch.cuda)
reserved_bytes = (
torch.cuda.memory_reserved(device_obj)
@@ -9879,6 +9991,9 @@ class VideoBackend:
height = height,
frames = frames,
decode_floor_mib = getattr(state, "vram_decode_floor_mib", None),
+ measured_extra_mib = video_stream_residency.measured_extra_mib(
+ calibration, int(width) * int(height) * int(frames)
+ ),
)
if shortfall is not None:
raise RuntimeError(shortfall)
@@ -10223,6 +10338,10 @@ class VideoBackend:
threshold = state.cache_threshold,
logger = logger,
)
+ from . import video_stream_residency
+
+ # the peak this request records belongs to the cache mode that actually runs
+ video_stream_residency.retag(state.pipe, "transformer_cache", toggled)
if toggled != state.transformer_cache:
# _VideoLoadState is frozen; record the pipe-level toggle so status() is truthful.
object.__setattr__(state, "transformer_cache", toggled)
diff --git a/studio/backend/core/inference/video_stream_residency.py b/studio/backend/core/inference/video_stream_residency.py
index d79f68476b4..f754b8989cb 100644
--- a/studio/backend/core/inference/video_stream_residency.py
+++ b/studio/backend/core/inference/video_stream_residency.py
@@ -8,6 +8,10 @@ or, for a request no larger (pixels x frames) than a completed one, that request
estimate stays the lower bound. Resident groups keep their host copy, so streaming them again is a pointer swap.
Kill switches: UNSLOTH_VIDEO_DIT_RESIDENT=0, UNSLOTH_VIDEO_DIT_RESIDENT_BLOCKS=0 (top-level group only),
UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0 (estimate only).
+
+Calibration is not Wan-only: ``arm_request`` arms the same peak measurement for any video family, and every recorded
+peak also lands in a process-wide table keyed by the loaded model (``calibration_key``), so a reload of the same model
+and the offload refusal (``measured_extra_mib``) reuse it. ``UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0`` turns reuse off.
"""
from __future__ import annotations
@@ -133,13 +137,104 @@ def measured_room_mib(
return max(0, available - need)
-def _measured_extra_mib(module: Any, work: int) -> Optional[int]:
- """The largest recorded peak among completed requests at least as large as ``work``; None when none covers it."""
- peaks = getattr(module, "_unsloth_video_peaks", None) or {}
- covering = [extra for w, extra in peaks.items() if w >= work]
+# calibration key -> {work (pixels x frames): peak MiB above the request's start}; survives a reload of the same model
+_PEAKS: dict = {}
+
+
+def calibration_key(
+ family: Any,
+ repo: Any = None,
+ offload_policy: Any = None,
+ device: Any = None,
+ **extra: Any,
+) -> tuple:
+ return (
+ str(family or ""),
+ str(repo or ""),
+ str(offload_policy or ""),
+ str(
+ device or ""
+ ), # the card too: a different GPU model can pick different kernels and workspaces
+ tuple(sorted((k, str(v)) for k, v in extra.items())),
+ )
+
+
+def with_extra(key: Any, name: str, value: Any) -> Any:
+ """``key`` with one keyword entry replaced (e.g. the step-cache mode a request actually ran with)."""
+ if not isinstance(key, tuple) or len(key) != 5:
+ return key
+ extras = dict(key[4])
+ extras[name] = str(value)
+ return (*key[:4], tuple(sorted(extras.items())))
+
+
+def retag(pipe: Any, name: str, value: Any) -> Any:
+ """Rewrite one entry of the denoiser's calibration key in place (the peak recorded later lands there)."""
+ module = getattr(pipe, "transformer", None)
+ key = getattr(module, "_unsloth_video_calibration_key", None)
+ if key is None:
+ return None
+ new = with_extra(key, name, value)
+ try:
+ module._unsloth_video_calibration_key = new
+ except Exception: # noqa: BLE001
+ return key
+ return new
+
+
+def _covering(peaks: dict, work: int) -> Optional[int]:
+ covering = [extra for w, extra in (peaks or {}).items() if w >= work]
return max(covering) if covering else None
+def measured_extra_mib(key: Any, work: int) -> Optional[int]:
+ if key is None or not measured_enabled():
+ return None
+ return _covering(_PEAKS.get(key) or {}, int(work))
+
+
+def _measured_extra_mib(module: Any, work: int) -> Optional[int]:
+ """The largest recorded peak among completed requests at least as large as ``work``; None when none covers it.
+ A tagged module reads only the peaks of its calibration key (same load AND request mode), which also carries the
+ peaks it recorded itself; the module's own mode-blind table is the fallback for an untagged one."""
+ key = getattr(module, "_unsloth_video_calibration_key", None)
+ if key is not None:
+ return _covering(_PEAKS.get(key) or {}, work)
+ return _covering(getattr(module, "_unsloth_video_peaks", None) or {}, work)
+
+
+def arm_request(
+ pipe: Any,
+ *,
+ key: Any,
+ width: int,
+ height: int,
+ frames: int,
+ device: Any,
+ rearm: bool = True,
+) -> bool:
+ """Tag the denoiser with ``key`` and arm the peak measurement ``record_request_peak`` closes. ``rearm=False``
+ after ``fit_for_request`` only tags. CUDA only; never raises."""
+ module = getattr(pipe, "transformer", None)
+ if module is None:
+ return False
+ try:
+ import torch
+
+ dev = torch.device(device)
+ if dev.type != "cuda":
+ return False
+ module._unsloth_video_calibration_key = key
+ if not rearm:
+ return True
+ torch.cuda.reset_peak_memory_stats(dev)
+ work = int(width) * int(height) * int(frames)
+ module._unsloth_video_pending = (work, int(torch.cuda.memory_allocated(dev)), dev)
+ return True
+ except Exception: # noqa: BLE001 -- an unarmed request keeps the estimate
+ return False
+
+
def record_request_peak(pipe: Any, *, logger: Any = None) -> Optional[int]:
"""Record the request's peak allocation above its start; call only after decode and export."""
module = getattr(pipe, "transformer", None)
@@ -159,6 +254,10 @@ def record_request_peak(pipe: Any, *, logger: Any = None) -> Optional[int]:
peaks = {}
module._unsloth_video_peaks = peaks
peaks[work] = max(extra, peaks.get(work, 0))
+ key = getattr(module, "_unsloth_video_calibration_key", None)
+ if key is not None:
+ shared = _PEAKS.setdefault(key, {})
+ shared[work] = max(extra, shared.get(work, 0))
_COUNTS["recorded"] += 1
if logger is not None:
logger.info("video.dit_resident: request peak %d MiB above its start recorded", extra)
diff --git a/studio/backend/tests/test_diffusion_component_sizes.py b/studio/backend/tests/test_diffusion_component_sizes.py
new file mode 100644
index 00000000000..d974ef99295
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_component_sizes.py
@@ -0,0 +1,1777 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Component sizes from safetensors headers (diffusion_component_sizes) against the hand tables they back up."""
+
+from __future__ import annotations
+
+import json
+import os
+import struct
+from pathlib import Path
+
+import pytest
+
+from core.inference import diffusion_component_sizes as dcs
+from core.inference import video_stream_residency as vsr
+from core.inference.video_families import _FAMILIES as VIDEO_FAMILIES
+
+_GB = 1000.0**3
+
+
+def _real_hub_cache():
+ """The host's HF hub cache, read at collection (before conftest points every cache root at an empty dir)."""
+ try:
+ from huggingface_hub import constants
+ return os.environ.get("HF_HUB_CACHE") or constants.HF_HUB_CACHE
+ except Exception: # noqa: BLE001
+ return None
+
+
+_REAL_HUB_CACHE = _real_hub_cache()
+
+
+def _write_header(path: Path, tensors: dict) -> None:
+ """A header-only safetensors file: the size readers never touch the data section."""
+ header: dict = {"__metadata__": {"format": "pt"}}
+ offset = 0
+ for name, (dtype, numel) in tensors.items():
+ width = {"BF16": 2, "F16": 2, "F32": 4, "I64": 8, "F8_E4M3": 1, "F8_E5M2": 1}[dtype]
+ header[name] = {
+ "dtype": dtype,
+ "shape": [numel],
+ "data_offsets": [offset, offset + numel * width],
+ }
+ offset += numel * width
+ raw = json.dumps(header).encode()
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw)
+
+
+def _component(
+ root: Path,
+ folder: str,
+ gb: float,
+ dtype: str = "BF16",
+ *,
+ stem: str = "diffusion_pytorch_model",
+):
+ width = 4 if dtype == "F32" else 2
+ _write_header(
+ root / folder / f"{stem}.safetensors", {"w": (dtype, int(round(gb * _GB / width)))}
+ )
+
+
+def test_parser_rejects_implausible_and_non_object_headers(tmp_path):
+ bad = tmp_path / "bad.safetensors"
+ bad.write_bytes(struct.pack("<Q", 1 << 40) + b"{}")
+ assert dcs.read_safetensors_header(bad) is None
+ arr = tmp_path / "arr.safetensors"
+ arr.write_bytes(struct.pack("<Q", 2) + b"[]")
+ assert dcs.read_safetensors_header(arr) is None
+ short = tmp_path / "short.safetensors"
+ short.write_bytes(b"\x01\x02")
+ assert dcs.read_safetensors_header(short) is None
+ capped = tmp_path / "capped.safetensors"
+ _write_header(capped, {"a": ("BF16", 4)})
+ assert dcs.read_safetensors_header(capped) is not None
+ assert dcs.read_safetensors_header(capped, max_bytes = 8) is None
+
+
+def test_merged_callers_read_through_the_shared_parser(tmp_path):
+ from core.inference.diffusion import DiffusionBackend
+ from core.inference.diffusion_memory import safetensors_prefix_mib
+ from core.inference.diffusion_small_host import _safetensors_bytes_by_dtype
+
+ f = tmp_path / "m.safetensors"
+ _write_header(f, {"blk.a": ("F32", 1 << 20), "blk.b": ("BF16", 1 << 20), "other": ("I64", 16)})
+ assert safetensors_prefix_mib(f, "blk.") == 6
+ assert _safetensors_bytes_by_dtype(f) == {"float32": 4 << 20, "bfloat16": 2 << 20, "i64": 128}
+ assert DiffusionBackend._safetensors_param_count(f) == (2 << 20) + 16
+ # mixed widths: the half load does not narrow (the fp32 tensors are pinned), sizes as stored
+ assert DiffusionBackend._safetensors_cast_bytes(f, 2) == (4 << 20) + (2 << 20) + 128
+ bad = tmp_path / "bad.safetensors"
+ bad.write_bytes(b"\x00" * 4)
+ assert safetensors_prefix_mib(bad, "blk.") is None
+ assert _safetensors_bytes_by_dtype(bad) == {}
+ assert DiffusionBackend._safetensors_param_count(bad) == 0
+ assert DiffusionBackend._safetensors_cast_bytes(bad, 2) is None
+
+
+def test_local_sizes_pick_default_variant_and_complete_index(tmp_path):
+ root = tmp_path / "pipe"
+ # sharded transformer + a stray fp16 variant the loader never reads
+ for i in (1, 2):
+ _write_header(
+ root / "transformer" / f"diffusion_pytorch_model-0000{i}-of-00002.safetensors",
+ {f"t{i}": ("F32", 1000)},
+ )
+ (root / "transformer" / "diffusion_pytorch_model.safetensors.index.json").write_text(
+ json.dumps(
+ {
+ "weight_map": {
+ "t1": "diffusion_pytorch_model-00001-of-00002.safetensors",
+ "t2": "diffusion_pytorch_model-00002-of-00002.safetensors",
+ }
+ }
+ )
+ )
+ _write_header(
+ root / "transformer" / "diffusion_pytorch_model.fp16.safetensors", {"x": ("F16", 999_999)}
+ )
+ # text_encoder with a complete transformers index and a stale diffusers index naming absent shards (LTX-2 layout)
+ _write_header(root / "text_encoder" / "model-00001-of-00001.safetensors", {"e": ("F32", 500)})
+ (root / "text_encoder" / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"e": "model-00001-of-00001.safetensors"}})
+ )
+ (root / "text_encoder" / "diffusion_pytorch_model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"e": "diffusion_pytorch_model-00001-of-00009.safetensors"}})
+ )
+ # a partially downloaded component: its index lists a shard that is not there -> unknown, never smaller
+ _write_header(
+ root / "vae" / "diffusion_pytorch_model-00001-of-00002.safetensors", {"v": ("BF16", 10)}
+ )
+ (root / "vae" / "diffusion_pytorch_model.safetensors.index.json").write_text(
+ json.dumps(
+ {
+ "weight_map": {
+ "v": "diffusion_pytorch_model-00001-of-00002.safetensors",
+ "w": "diffusion_pytorch_model-00002-of-00002.safetensors",
+ }
+ }
+ )
+ )
+ sizes = dcs.local_component_sizes(root)
+ assert sizes is not None and sizes.names() == ("text_encoder", "transformer")
+ t = sizes.get("transformer")
+ assert t.float_params == 2000 and t.stored_bytes == 8000 and t.resident_bytes(2) == 4000
+ assert len(t.files) == 2 and all(".fp16." not in f for f in t.files)
+ assert sizes.get("text_encoder").files == ("model-00001-of-00001.safetensors",)
+
+
+def test_resident_cast_keeps_non_float_tensors(tmp_path):
+ _write_header(tmp_path / "c" / "model.safetensors", {"f": ("F32", 100), "ids": ("I64", 10)})
+ size = dcs.local_component_sizes(tmp_path).get("c")
+ assert size.resident_bytes(2) == 200 + 80
+ assert size.resident_bytes(4) == 400 + 80
+ assert dict(size.bytes_by_dtype) == {"F32": 400}
+
+
+def _fam(name):
+ return next(f for f in VIDEO_FAMILIES if f.name == name)
+
+
+def test_video_roles(tmp_path):
+ ltx25 = tmp_path / "ltx25"
+ for folder, gb in (
+ ("transformer", 37.98),
+ ("text_encoder", 23.92),
+ ("connectors", 6.34),
+ ("vae", 1.45),
+ ("audio_vae", 0.11),
+ ("vocoder", 0.26),
+ ("latent_upsampler", 1.0),
+ ("prompt_enhancer", 10.2), # not loaded by the pipeline: outside the table
+ ):
+ _component(
+ ltx25,
+ folder,
+ gb,
+ stem = "model"
+ if folder in ("text_encoder", "prompt_enhancer")
+ else "diffusion_pytorch_model",
+ )
+ triple = dcs.video_header_components_gb(_fam("ltx-2.5"), dcs.local_component_sizes(ltx25))
+ assert triple == pytest.approx((37.98, 23.92, 6.34 + 1.45 + 0.11 + 0.26 + 1.0), abs = 1e-6)
+ # an audio family without its audio VAE is incomplete
+ (ltx25 / "audio_vae" / "diffusion_pytorch_model.safetensors").unlink()
+ assert dcs.video_header_components_gb(_fam("ltx-2.5"), dcs.local_component_sizes(ltx25)) is None
+
+ wan = tmp_path / "wan"
+ _component(wan, "transformer", 5.68, "F32")
+ _component(wan, "text_encoder", 22.72, "F32", stem = "model")
+ _component(wan, "vae", 0.508, "F32")
+ fam = _fam("wan2.1-t2v-1.3b")
+ assert fam.vae_force_fp32
+ # DiT and encoder cast to bf16, the fp32-pinned VAE stays at fp32
+ assert dcs.video_header_components_gb(fam, dcs.local_component_sizes(wan)) == pytest.approx(
+ (2.84, 11.36, 0.508), abs = 1e-6
+ )
+
+ moe = _fam("wan2.2-t2v-a14b")
+ # a first-expert-only checkpoint is a complete single denoiser (video._transformer_names)
+ assert dcs.video_header_components_gb(moe, dcs.local_component_sizes(wan))[0] == pytest.approx(
+ 2.84
+ )
+ _component(wan, "transformer_2", 5.68, "F32")
+ assert dcs.video_header_components_gb(moe, dcs.local_component_sizes(wan))[0] == pytest.approx(
+ 5.68
+ )
+
+
+def test_reconcile_rules(monkeypatch):
+ monkeypatch.setattr(dcs, "_MISMATCHES", {})
+ table = (10.0, 11.4, 2.8)
+ assert dcs.reconcile_with_table(None, table, is_base = True) == table
+ assert dcs.reconcile_with_table((9.9996, 11.3618, 2.8188), table, is_base = True) == table
+ assert dcs.reconcile_with_table((9.9996, 11.3618, 2.8188), None, is_base = True) == (
+ 10.0,
+ 11.4,
+ 2.8,
+ )
+ # base repo: a real disagreement keeps the table and is recorded for review
+ assert dcs.reconcile_with_table((12.0, 11.4, 2.8), table, is_base = True, key = ("f", "b")) == table
+ assert dcs.table_mismatches()[("f", "b")] == ((12.0, 11.4, 2.8), table)
+ # a variant the table does not describe: the larger of its headers and the table, per term
+ assert dcs.reconcile_with_table((12.04, 11.4, 2.8), table, is_base = False) == (12.0, 11.4, 2.8)
+ assert dcs.reconcile_with_table((8.0, 12.0, 1.0), table, is_base = False) == (10.0, 12.0, 2.8)
+
+
+def _stub_for_table(root: Path, fam) -> None:
+ """A snapshot whose headers reproduce ``fam.bf16_components_gb`` exactly (stub for un-cached families)."""
+ denoiser, text, vae = fam.bf16_components_gb
+ experts = ("transformer", "transformer_2") if fam.is_moe else ("transformer",)
+ for name in experts:
+ _component(root, name, denoiser / len(experts))
+ # every optional folder the family loads (connectors / vocoder / upsampler / a second text encoder) is present,
+ # so the stub is a COMPLETE snapshot; their small sizes come out of the same table term
+ extra_text = [n for n in dcs.video_loaded_roles(fam) if n.startswith("text_encoder_")]
+ for n in extra_text:
+ _component(root, n, 0.1, stem = "model")
+ _component(root, "text_encoder", text - 0.1 * len(extra_text), stem = "model")
+ companions = [
+ n
+ for n in dcs.video_loaded_roles(fam)
+ if n not in ("vae", "text_encoder")
+ and n not in extra_text
+ and not n.startswith("transformer")
+ ]
+ for n in companions:
+ _component(root, n, 0.1)
+ _component(root, "vae", vae - 0.1 * len(companions), "F32" if fam.vae_force_fp32 else "BF16")
+
+
+_TABLE_FAMILIES = [f for f in VIDEO_FAMILIES if f.bf16_components_gb and not f.modular_workflow]
+
+
[email protected]("fam", _TABLE_FAMILIES, ids = lambda f: f.name)
+def test_stub_headers_reproduce_every_video_table(tmp_path, monkeypatch, fam):
+ monkeypatch.setattr(dcs, "_MISMATCHES", {})
+ _stub_for_table(tmp_path, fam)
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert dcs.video_header_components_gb(fam, sizes) == pytest.approx(
+ fam.bf16_components_gb, abs = 1e-6
+ )
+ # the base repo resolving to these headers keeps the table exactly
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ assert dcs.video_components_gb(fam) == fam.bf16_components_gb
+ # a larger denoiser on the base repo is reported and the table still answers
+ _component(tmp_path, "transformer", fam.bf16_components_gb[0] + 2.0)
+ if fam.is_moe:
+ (tmp_path / "transformer_2").rename(tmp_path / "unused")
+ _component(tmp_path, "transformer_2", 0.0001)
+ assert dcs.video_components_gb(fam) == fam.bf16_components_gb
+ assert (fam.name, fam.base_repo) in dcs.table_mismatches()
+ # the same headers on a variant repo price the variant
+ variant = dcs.video_components_gb(fam, str(tmp_path))
+ assert variant[0] == pytest.approx(
+ round(fam.bf16_components_gb[0] + 2.0 + (0.0001 if fam.is_moe else 0), 1)
+ )
+
+
+def test_no_headers_falls_back_to_the_table(monkeypatch):
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: None)
+ monkeypatch.setattr(
+ dcs, "hub_component_sizes", lambda *a, **k: pytest.fail("hub read for a tabled base")
+ )
+ for fam in VIDEO_FAMILIES:
+ assert dcs.video_components_gb(fam, allow_hub = True) == fam.bf16_components_gb
+
+
+def test_untabled_or_variant_repo_reads_the_hub_before_download(monkeypatch, tmp_path):
+ fam = _fam("wan2.2-ti2v-5b")
+ _stub_for_table(tmp_path, fam)
+ stub = dcs.local_component_sizes(tmp_path)
+ calls = []
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: None)
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda repo, **k: calls.append(repo) or stub)
+ assert (
+ dcs.video_components_gb(fam, "someone/finetune", allow_hub = True) == fam.bf16_components_gb
+ )
+ assert (
+ dcs.video_components_gb(fam, "someone/finetune", allow_hub = False) == fam.bf16_components_gb
+ )
+ assert calls == ["someone/finetune"]
+
+
+def test_hub_reads_are_disabled_offline(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ assert dcs.hub_component_sizes("Wan-AI/Wan2.2-TI2V-5B-Diffusers") is None
+ monkeypatch.delenv("HF_HUB_OFFLINE")
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_HEADER_FETCH", "0")
+ assert dcs.hub_component_sizes("Wan-AI/Wan2.2-TI2V-5B-Diffusers") is None
+
+
+# Header-vs-table disagreements (Hub, 2026-10-13); each needs a human decision before a table changes.
+KNOWN_TABLE_DELTAS = {
+ # 42.0 is the single-file DiT incl. ~4 GB connectors, already in the companion term: over-states the pack.
+ ("ltx-2.5", 0): 4.03,
+ # Qwen2.5-VL 7B (14.14) + ByT5 (0.44 at bf16) = 14.58, table 14.8; VAE 2.52 at bf16 (5.04 stored fp32), table 2.4.
+ ("hunyuanvideo-1.5", 1): -0.22,
+ ("hunyuanvideo-1.5", 2): 0.12,
+ ("hunyuanvideo-1.5-720p", 1): -0.22,
+ ("hunyuanvideo-1.5-720p", 2): 0.12,
+ # image: Qwen-Image-2.1's VAE is stored fp32 (1.35 GB) and loads at bf16 (0.68 GB); the table holds the stored size.
+ ("qwen-image-2.1", 2): -0.72,
+}
+
+
+def _check_against_table(name: str, header, table) -> list:
+ problems = []
+ for i, (h, t) in enumerate(zip(header, table)):
+ known = KNOWN_TABLE_DELTAS.get((name, i))
+ if known is not None:
+ if abs((t - h) - known) > 0.06 and abs((h - t) - known) > 0.06:
+ problems.append((name, i, h, t, "known delta moved"))
+ elif abs(h - t) > dcs.TABLE_ROUNDING_GB:
+ problems.append((name, i, h, t))
+ return problems
+
+
+def test_cached_video_families_headers_match_tables():
+ checked, problems = [], []
+ for fam in _TABLE_FAMILIES:
+ snap = dcs.local_snapshot_dir(fam.base_repo, _REAL_HUB_CACHE)
+ header = (
+ dcs.video_header_components_gb(fam, dcs.local_component_sizes(snap)) if snap else None
+ )
+ if header is None:
+ continue
+ checked.append(fam.name)
+ problems += _check_against_table(fam.name, header, fam.bf16_components_gb)
+ if not checked:
+ pytest.skip("no video family is fully cached on this host")
+ assert not problems, problems
+
+
+def test_cached_image_families_headers_match_tables():
+ from core.inference.diffusion_auto_policy import family_bf16_components_gb
+ from core.inference.diffusion_families import _FAMILIES as IMAGE_FAMILIES
+
+ checked, problems = [], []
+ for fam in IMAGE_FAMILIES:
+ table = family_bf16_components_gb(fam, fam.base_repo)
+ snap = dcs.local_snapshot_dir(fam.base_repo, _REAL_HUB_CACHE)
+ header = (
+ dcs.image_header_components_gb(dcs.local_component_sizes(snap))
+ if snap and table
+ else None
+ )
+ if header is None:
+ continue
+ checked.append(fam.name)
+ problems += _check_against_table(fam.name, header, table)
+ if not checked:
+ pytest.skip("no image family is fully cached on this host")
+ assert not problems, problems
+
+
+ os.environ.get("UNSLOTH_TEST_HUB_HEADERS") != "1",
+ reason = "Hub ranged header reads (set UNSLOTH_TEST_HUB_HEADERS=1)",
+)
[email protected]("fam", _TABLE_FAMILIES, ids = lambda f: f.name)
+def test_hub_headers_match_tables(fam):
+ sizes = dcs.hub_component_sizes(fam.base_repo, timeout_seconds = 120)
+ header = dcs.video_header_components_gb(fam, sizes)
+ assert header is not None
+ assert not _check_against_table(fam.name, header, fam.bf16_components_gb)
+
+
+class _Module:
+ pass
+
+
+class _Pipe:
+ def __init__(self):
+ self.transformer = _Module()
+
+
+def test_calibration_records_and_reuses_for_any_family(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(vsr, "_PEAKS", {})
+ allocated = {"now": 1000 << 20, "peak": 0}
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda dev = None: None)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda dev = None: allocated["now"])
+ monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda dev = None: allocated["peak"])
+
+ key = vsr.calibration_key("ltx-2.5", "Lightricks/LTX-2.5-Diffusers", "group", "cuda")
+ pipe = _Pipe()
+ assert vsr.arm_request(pipe, key = key, width = 64, height = 32, frames = 9, device = "cuda:0")
+ allocated["peak"] = (1000 + 3000) << 20
+ assert vsr.record_request_peak(pipe) == 3000
+ work = 64 * 32 * 9
+ assert vsr.measured_extra_mib(key, work) == 3000
+ assert vsr.measured_extra_mib(key, work - 1) == 3000 # a smaller request is covered
+ assert vsr.measured_extra_mib(key, work + 1) is None # a larger one is not
+ # a reload of the same model (fresh module) reuses the process-wide record
+ reloaded = _Pipe()
+ reloaded.transformer._unsloth_video_calibration_key = key
+ assert vsr._measured_extra_mib(reloaded.transformer, work) == 3000
+ # rearm=False (fit_for_request armed it) only tags the module
+ other = _Pipe()
+ assert vsr.arm_request(
+ other, key = key, width = 1, height = 1, frames = 1, device = "cuda:0", rearm = False
+ )
+ assert getattr(other.transformer, "_unsloth_video_pending", None) is None
+ assert not vsr.arm_request(_Pipe(), key = key, width = 1, height = 1, frames = 1, device = "cpu")
+ monkeypatch.setenv(vsr.VIDEO_DIT_RESIDENT_MEASURED_ENV, "0")
+ assert vsr.measured_extra_mib(key, work) is None
+
+
+def test_shortfall_uses_a_measured_peak_only_when_smaller():
+ from core.inference.video import video_offload_shortfall_message
+
+ kwargs = dict(
+ family = "ltx-2.5", floor_mib = 20_000, placement = "x", width = 1280, height = 704, frames = 121
+ )
+ base = video_offload_shortfall_message(available_mib = 1, **kwargs)
+ needed = float(base.split("needs about ")[1].split(" GiB")[0])
+ # unchanged without a measurement
+ assert (
+ video_offload_shortfall_message(available_mib = 1, measured_extra_mib = None, **kwargs) == base
+ )
+ # a large measured peak never raises the bar
+ assert (
+ video_offload_shortfall_message(available_mib = 1, measured_extra_mib = 10**6, **kwargs) == base
+ )
+ small = video_offload_shortfall_message(available_mib = 1, measured_extra_mib = 2000, **kwargs)
+ assert float(small.split("needs about ")[1].split(" GiB")[0]) < needed
+ fits = 20_000 + int(2000 * vsr.MEASURED_PEAK_MARGIN) + vsr.MEASURED_SLACK_MIB
+ assert (
+ video_offload_shortfall_message(available_mib = fits, measured_extra_mib = 2000, **kwargs)
+ is None
+ )
+
+
+def test_float8_tensors_are_floating_parameters(tmp_path):
+ _write_header(
+ tmp_path / "transformer" / "diffusion_pytorch_model.safetensors",
+ {"a": ("F8_E4M3", 1000), "b": ("F8_E5M2", 500), "ids": ("I64", 2)},
+ )
+ size = dcs.local_component_sizes(tmp_path).get("transformer")
+ assert size.float_params == 1500 and size.nonfloat_bytes == 16
+ assert size.resident_bytes(2) == 1500 * 2 + 16 # a float8 store loaded at bf16 / fp16
+ for dtype in ("F8_E4M3", "F8_E5M2", "F8_E4M3FNUZ", "F8_E5M2FNUZ", "F8_E8M0"):
+ assert dcs.FLOAT_WIDTH[dtype] == 1
+
+
+def test_optional_folders_do_not_send_a_cached_model_to_the_hub(tmp_path, monkeypatch):
+ fam = _fam(
+ "wan2.2-ti2v-5b"
+ ) # non-MoE, no audio: no transformer_2 / audio_vae / connectors / vocoder
+ _stub_for_table(tmp_path, fam)
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ # the ref still points at the cached snapshot, so only the folder rule is under test
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: tmp_path.name)
+ monkeypatch.setattr(
+ dcs, "hub_component_sizes", lambda *a, **k: pytest.fail("hub read for a fully cached model")
+ )
+ assert (
+ dcs.video_components_gb(fam, "someone/finetune", allow_hub = True) == fam.bf16_components_gb
+ )
+ assert dcs.video_required_roles(fam) == ("transformer", "text_encoder", "vae")
+ # the second expert is loaded only when shipped (present or in the manifest), so never required
+ assert dcs.video_required_roles(_fam("wan2.2-t2v-a14b")) == (
+ "transformer",
+ "text_encoder",
+ "vae",
+ )
+ assert dcs.video_required_roles(_fam("ltx-2.5"))[-1] == "audio_vae"
+ # optional folders are still counted when present
+ ltx = _fam("ltx-2.5")
+ root = tmp_path / "ltx"
+ _stub_for_table(root, ltx)
+ _component(root, "connectors", 1.0)
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: root)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: root.name)
+ got = dcs.video_components_gb(ltx, "someone/ltx-finetune", allow_hub = True)
+ assert got[2] == pytest.approx(
+ round(ltx.bf16_components_gb[2] - 0.1 + 1.0, 1)
+ ) # stub connectors 0.1 -> 1.0
+ # a missing required folder still asks the Hub (with the load's token)
+ (root / "vae" / "diffusion_pytorch_model.safetensors").unlink()
+ calls = []
+ monkeypatch.setattr(
+ dcs, "hub_component_sizes", lambda repo, **k: calls.append((repo, k.get("token")))
+ )
+ dcs.video_components_gb(ltx, "someone/ltx-finetune", allow_hub = True, token = "hf_secret")
+ assert calls == [("someone/ltx-finetune", "hf_secret")]
+
+
+class _Info:
+ def __init__(self, sha):
+ self.sha = sha
+ self.siblings = ()
+
+
+def _fake_hub(monkeypatch, shas, reads, tokens):
+ import huggingface_hub
+
+ class _Api:
+ def __init__(self, token = None):
+ tokens.append(token)
+
+ def model_info(
+ self,
+ repo_id,
+ revision = None,
+ files_metadata = False,
+ timeout = None,
+ ):
+ return _Info(shas[0])
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)
+ monkeypatch.setattr(
+ dcs,
+ "_read_hub_sizes",
+ lambda repo, info, commit, *a, **k: reads.append(commit)
+ or dcs.ComponentSizes({}, "hub", commit),
+ )
+
+
+def test_hub_cache_revalidates_mutable_refs_by_commit(monkeypatch):
+ monkeypatch.setattr(dcs, "_HUB_CACHE", {})
+ monkeypatch.setattr(dcs, "_HUB_SHA_CACHE", {})
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+ shas, reads, tokens = ["a" * 40], [], []
+ _fake_hub(monkeypatch, shas, reads, tokens)
+ clock = [1000.0]
+ import time as _time
+
+ monkeypatch.setattr(_time, "monotonic", lambda: clock[0])
+ assert dcs.hub_component_sizes("o/r", token = "t1").revision == "a" * 40
+ assert dcs.hub_component_sizes("o/r", token = "t1").revision == "a" * 40 # fresh: no call
+ assert reads == ["a" * 40] and tokens == ["t1"]
+ clock[0] += dcs.HUB_REFRESH_SECONDS + 1
+ # stale ref, same commit: one metadata call, no header re-read
+ assert dcs.hub_component_sizes("o/r", token = "t1").revision == "a" * 40
+ assert reads == ["a" * 40] and tokens == ["t1", "t1"]
+ clock[0] += dcs.HUB_REFRESH_SECONDS + 1
+ shas[0] = "b" * 40 # the branch moved
+ assert dcs.hub_component_sizes("o/r", token = "t1").revision == "b" * 40
+ assert reads == ["a" * 40, "b" * 40]
+ # a pinned commit never revalidates
+ pinned = "c" * 40
+ shas[0] = pinned
+ dcs.hub_component_sizes("o/r", revision = pinned)
+ clock[0] += 10 * dcs.HUB_REFRESH_SECONDS
+ n = len(tokens)
+ dcs.hub_component_sizes("o/r", revision = pinned)
+ assert len(tokens) == n
+ # another token is a separate cache partition (and is the one sent)
+ dcs.hub_component_sizes("o/r", token = "t2")
+ assert tokens[-1] == "t2"
+
+
+def test_calibration_key_separates_load_configurations():
+ base = dict(
+ transformer_quant = "int8",
+ text_encoder_quant = None,
+ dtype = "bfloat16",
+ attention_backend = "sdpa",
+ )
+ k = vsr.calibration_key("ltx-2", "r", "group", "cuda:0", gguf_filename = "a-Q4_K_M.gguf", **base)
+ assert k == vsr.calibration_key(
+ "ltx-2", "r", "group", "cuda:0", gguf_filename = "a-Q4_K_M.gguf", **base
+ )
+ assert k != vsr.calibration_key(
+ "ltx-2", "r", "group", "cuda:0", gguf_filename = "a-Q8_0.gguf", **base
+ )
+ assert k != vsr.calibration_key(
+ "ltx-2",
+ "r",
+ "group",
+ "cuda:0",
+ gguf_filename = "a-Q4_K_M.gguf",
+ **{**base, "dtype": "float32"},
+ )
+ assert k != vsr.calibration_key(
+ "ltx-2",
+ "r",
+ "group",
+ "cuda:0",
+ gguf_filename = "a-Q4_K_M.gguf",
+ **{**base, "attention_backend": "flash"},
+ )
+ assert k != vsr.calibration_key(
+ "ltx-2", "r", "group", "cuda:1", gguf_filename = "a-Q4_K_M.gguf", **base
+ )
+
+
+def test_generate_keys_calibration_on_the_load_configuration():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video)
+ call = src[src.index("video_stream_residency.calibration_key(") :]
+ call = call[: call.index("\n )")]
+ for field in (
+ "gguf_filename",
+ "dtype",
+ "attention_backend",
+ "speed_mode",
+ "transformer_quant",
+ "text_encoder_quant",
+ "kind",
+ "variant_id",
+ ):
+ assert f'"{field}"' in call, field
+ # the cache mode is the one this request runs (see test_auto_cache_decision_is_shared_and_retags_the_calibration)
+ assert "transformer_cache = request_cache_mode" in call
+
+
+def _index(path: Path, shards: list) -> None:
+ path.write_text(json.dumps({"weight_map": {f"t{i}": s for i, s in enumerate(shards)}}))
+
+
+def test_incomplete_preferred_index_is_unknown_even_beside_a_complete_one(tmp_path):
+ # diffusers folder: the preferred diffusion_pytorch_model index is incomplete, a stale model index is complete
+ t = tmp_path / "transformer"
+ _write_header(t / "model-00001-of-00001.safetensors", {"a": ("BF16", 10)})
+ _index(t / "model.safetensors.index.json", ["model-00001-of-00001.safetensors"])
+ _write_header(t / "diffusion_pytorch_model-00001-of-00002.safetensors", {"b": ("BF16", 10)})
+ _index(
+ t / "diffusion_pytorch_model.safetensors.index.json",
+ [
+ "diffusion_pytorch_model-00001-of-00002.safetensors",
+ "diffusion_pytorch_model-00002-of-00002.safetensors",
+ ],
+ )
+ # transformers folder: the preferred model index is incomplete, a diffusers index beside it is complete
+ e = tmp_path / "text_encoder"
+ _write_header(e / "diffusion_pytorch_model-00001-of-00001.safetensors", {"c": ("BF16", 10)})
+ _index(
+ e / "diffusion_pytorch_model.safetensors.index.json",
+ ["diffusion_pytorch_model-00001-of-00001.safetensors"],
+ )
+ _write_header(e / "model-00001-of-00002.safetensors", {"d": ("BF16", 10)})
+ _index(
+ e / "model.safetensors.index.json",
+ ["model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"],
+ )
+ assert dcs.local_component_sizes(tmp_path) is None
+ # the preferred stem's unindexed file wins over a lower-priority index
+ v = tmp_path / "vae"
+ _write_header(v / "diffusion_pytorch_model.safetensors", {"v": ("BF16", 7)})
+ _write_header(v / "model-00001-of-00001.safetensors", {"w": ("BF16", 999)})
+ _index(v / "model.safetensors.index.json", ["model-00001-of-00001.safetensors"])
+ assert dcs.local_component_sizes(tmp_path).get("vae").files == (
+ "diffusion_pytorch_model.safetensors",
+ )
+
+
+class _Sib:
+ def __init__(
+ self,
+ name,
+ size = 100,
+ ):
+ self.rfilename, self.size = name, size
+
+
+def _hub_with(monkeypatch, siblings, header_for):
+ import huggingface_hub
+
+ class _Api:
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo_id,
+ revision = None,
+ files_metadata = False,
+ timeout = None,
+ ):
+ info = _Info("d" * 40)
+ info.siblings = [_Sib(n) for n in siblings]
+ return info
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)
+ monkeypatch.setattr(dcs, "_hub_header", lambda repo, filename, *a, **k: header_for(filename))
+ monkeypatch.setattr(dcs, "_HUB_CACHE", {})
+ monkeypatch.setattr(dcs, "_HUB_SHA_CACHE", {})
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+
+
+def test_hub_result_with_a_failed_header_is_rejected(monkeypatch):
+ files = [
+ "transformer/diffusion_pytorch_model.safetensors",
+ "text_encoder/model.safetensors",
+ "vae/diffusion_pytorch_model.safetensors",
+ "connectors/diffusion_pytorch_model.safetensors",
+ ]
+ ok = {"__metadata__": {}, "w": {"dtype": "BF16", "shape": [10], "data_offsets": [0, 20]}}
+ _hub_with(monkeypatch, files, lambda f: ok)
+ assert dcs.hub_component_sizes("o/r").names() == (
+ "connectors",
+ "text_encoder",
+ "transformer",
+ "vae",
+ )
+ # an optional-but-loaded folder whose header does not read invalidates the whole answer (and is not cached)
+ _hub_with(monkeypatch, files, lambda f: None if f.startswith("connectors/") else ok)
+ assert dcs.hub_component_sizes("o/r") is None
+ assert not dcs._HUB_SHA_CACHE
+ # an index that cannot be read is unknown too, not a skipped folder
+ _hub_with(
+ monkeypatch,
+ files[:3] + ["vocoder/diffusion_pytorch_model.safetensors.index.json"],
+ lambda f: ok,
+ )
+ monkeypatch.setattr(
+ dcs, "_fetch_capped_text", lambda *a, **k: (_ for _ in ()).throw(OSError("refused"))
+ )
+ assert dcs.hub_component_sizes("o/r") is None
+
+
+class _Resp:
+ def __init__(
+ self,
+ chunks,
+ length = None,
+ ):
+ self.chunks, self.headers, self.pulled, self.closed = chunks, {}, 0, False
+ if length is not None:
+ self.headers["Content-Length"] = str(length)
+
+ def raise_for_status(self):
+ pass
+
+ def iter_content(self, chunk_size = 1):
+ for c in self.chunks:
+ self.pulled += 1
+ yield c
+
+ def close(self):
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+ return False
+
+
+class _Session:
+ def __init__(self, resp):
+ self.resp, self.kwargs = resp, None
+
+ def get(self, url, **kwargs):
+ self.kwargs = kwargs
+ return self.resp
+
+
+class _HttpxClient:
+ """huggingface_hub 1.x: an httpx Client streams via ``Client.stream`` and has no ``stream=`` keyword."""
+
+ def __init__(self, resp):
+ self.resp, self.args = resp, None
+
+ def stream(self, method, url, **kwargs):
+ self.args = (method, kwargs)
+ return self.resp
+
+ def get(self, url, **kwargs):
+ if "stream" in kwargs:
+ raise TypeError("Client.get() got an unexpected keyword argument 'stream'")
+ return self.resp
+
+
+def test_index_fetch_works_on_the_httpx_client():
+ resp = _Resp([b'{"a"', b": 1}"])
+ resp.iter_bytes = resp.iter_content
+ client = _HttpxClient(resp)
+ assert dcs._fetch_capped_text(client, "u", {}, 1.0, float("inf")) == '{"a": 1}'
+ assert client.args[0] == "GET" and client.args[1]["follow_redirects"] is True and resp.closed
+
+
+def test_index_fetch_is_streamed_under_the_cap():
+ good = _Session(_Resp([b'{"weight_map"', b": {}}"]))
+ assert dcs._fetch_capped_text(good, "u", {}, 1.0, float("inf")) == '{"weight_map": {}}'
+ assert good.kwargs["stream"] is True and good.resp.closed
+ declared = _Session(_Resp([b"x"], length = 100))
+ with pytest.raises(ValueError):
+ dcs._fetch_capped_text(declared, "u", {}, 1.0, float("inf"), cap = 10)
+ assert declared.resp.pulled == 0 # refused on Content-Length, nothing read
+ lying = _Session(_Resp([b"x" * 6] * 1000))
+ with pytest.raises(ValueError):
+ dcs._fetch_capped_text(lying, "u", {}, 1.0, float("inf"), cap = 10)
+ assert (
+ lying.resp.pulled == 2 and lying.resp.closed
+ ) # stopped as soon as the body passed the cap
+
+
+def test_tagged_module_reads_only_its_own_mode(monkeypatch):
+ monkeypatch.setattr(vsr, "_PEAKS", {})
+ t2v = vsr.calibration_key("ltx-2", "r", "group", "cuda:0", fps = 24, conditioning = "t2v", cfg = True)
+ i2v = vsr.calibration_key("ltx-2", "r", "group", "cuda:0", fps = 24, conditioning = "i2v", cfg = True)
+ fps50 = vsr.calibration_key(
+ "ltx-2", "r", "group", "cuda:0", fps = 50, conditioning = "t2v", cfg = True
+ )
+ assert len({t2v, i2v, fps50}) == 3
+ vsr._PEAKS[t2v] = {1000: 3000}
+ module = _Module()
+ module._unsloth_video_peaks = {1000: 9999} # mode-blind own table: ignored once tagged
+ module._unsloth_video_calibration_key = i2v
+ assert vsr._measured_extra_mib(module, 1000) is None
+ module._unsloth_video_calibration_key = t2v
+ assert vsr._measured_extra_mib(module, 1000) == 3000
+ # a fresh module after a reload, tagged before the fit, finds the process-wide peak (arm_request reads the
+ # device through torch)
+ pytest.importorskip("torch")
+ reloaded = _Pipe()
+ assert vsr.arm_request(
+ reloaded, key = t2v, width = 1, height = 1, frames = 1, device = "cuda:0", rearm = False
+ )
+ assert vsr._measured_extra_mib(reloaded.transformer, 1000) == 3000
+
+
+def test_generate_tags_before_the_fit_and_keys_the_request_mode():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video)
+ key_at = src.index("video_stream_residency.calibration_key(")
+ tag_at = src.index("rearm = False", key_at)
+ fit_at = src.index("video_stream_residency.fit_for_request(", key_at)
+ assert key_at < tag_at < fit_at
+ call = src[key_at : src.index("\n )", key_at)]
+ for field in ("fps", "conditioning", "first_frame", "last_frame", "references", "cfg"):
+ assert f"{field} = " in call, field
+
+
+def test_local_files_only_scope_disables_hub_reads(monkeypatch):
+ from core.inference.diffusion_prequant import _LOCAL_FILES_ONLY
+
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+ assert not dcs.hub_disabled()
+ token = _LOCAL_FILES_ONLY.set(True)
+ try:
+ assert dcs.hub_disabled()
+ assert dcs.hub_component_sizes("o/r") is None
+ finally:
+ _LOCAL_FILES_ONLY.reset(token)
+
+
+def test_load_pipeline_passes_local_only_to_the_sizing_path():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video.VideoBackend.load_pipeline)
+ call = src[src.index("components = video_components_gb(") :]
+ call = call[: call.index("\n )")]
+ assert "allow_hub = not local_files_only" in call
+
+
+def test_snapshot_lookup_uses_the_active_cache_root(monkeypatch, tmp_path):
+ from huggingface_hub import constants
+
+ from utils import hf_cache_settings
+
+ custom = tmp_path / "custom_hub"
+ snap = custom / "models--o--r" / "snapshots" / ("e" * 40)
+ _component(snap, "transformer", 0.001)
+ (snap / "model_index.json").write_text("{}")
+ (custom / "models--o--r" / "refs").mkdir(parents = True)
+ (custom / "models--o--r" / "refs" / "main").write_text("e" * 40)
+ assert constants.HF_HUB_CACHE != str(custom) # huggingface_hub's own default does not see it
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(custom))
+ assert dcs.local_snapshot_dir("o/r") == snap
+ assert dcs.component_sizes("o/r").names() == ("transformer",)
+
+
+def test_shards_without_an_index_are_unknown(tmp_path):
+ t = tmp_path / "transformer"
+ _write_header(t / "diffusion_pytorch_model-00001-of-00002.safetensors", {"a": ("BF16", 10)})
+ _write_header(t / "diffusion_pytorch_model-00002-of-00002.safetensors", {"b": ("BF16", 10)})
+ assert dcs.local_component_sizes(tmp_path) is None
+ assert (
+ dcs.select_weight_files(["model-00001-of-00001.safetensors"], folder = "text_encoder") == []
+ )
+ # the unsharded file alone is a complete answer, a stray shard beside it is ignored
+ _write_header(t / "diffusion_pytorch_model.safetensors", {"c": ("BF16", 30)})
+ assert dcs.local_component_sizes(tmp_path).get("transformer").files == (
+ "diffusion_pytorch_model.safetensors",
+ )
+
+
+def test_mixed_format_variant_keeps_its_known_larger_terms(tmp_path, monkeypatch):
+ monkeypatch.setattr(dcs, "_MISMATCHES", {})
+ fam = _fam("wan2.2-ti2v-5b")
+ table = fam.bf16_components_gb
+ _component(tmp_path, "transformer", table[0] + 3.0)
+ (tmp_path / "text_encoder").mkdir()
+ (tmp_path / "text_encoder" / "pytorch_model.bin").write_bytes(
+ b"\0" * 16
+ ) # header-less: unknown term
+ _component(tmp_path, "vae", 0.1, "F32")
+ terms = dcs.video_header_terms(fam, dcs.local_component_sizes(tmp_path))
+ assert terms[1] is None and terms[0] == pytest.approx(table[0] + 3.0)
+ got = dcs.video_components_gb(fam, str(tmp_path))
+ # known larger denoiser wins, unknown text encoder and smaller VAE take the table
+ assert got == (round(table[0] + 3.0, 1), table[1], table[2])
+ # the base repo keeps the table on every term
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ assert dcs.video_components_gb(fam) == table
+ # without a table an unknown term means no answer
+ assert dcs.reconcile_with_table((1.0, None, 1.0), None, is_base = False) is None
+
+
+def test_transformer_2_counts_only_for_moe(tmp_path):
+ _component(tmp_path, "transformer", 2.0)
+ _component(tmp_path, "transformer_2", 2.0)
+ _component(tmp_path, "text_encoder", 1.0, stem = "model")
+ _component(tmp_path, "vae", 0.5)
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert dcs.video_header_terms(_fam("wan2.2-ti2v-5b"), sizes)[0] == pytest.approx(2.0)
+ assert dcs.video_header_terms(_fam("wan2.2-t2v-a14b"), sizes)[0] == pytest.approx(4.0)
+
+
+# ---- review round 4 ----
+
+
+def test_pytorch_model_stem_and_its_index_are_recognised(tmp_path):
+ t = tmp_path / "transformer"
+ for i in (1, 2):
+ _write_header(t / f"pytorch_model-0000{i}-of-00002.safetensors", {f"p{i}": ("BF16", 100)})
+ _index(
+ t / "pytorch_model.safetensors.index.json",
+ ["pytorch_model-00001-of-00002.safetensors", "pytorch_model-00002-of-00002.safetensors"],
+ )
+ size = dcs.local_component_sizes(tmp_path).get("transformer")
+ assert size.float_params == 200 and len(size.files) == 2
+ # the stems match the loader's default weight names
+ from core.inference.diffusion import (
+ _DEFAULT_PIPELINE_WEIGHT_INDEX_RE,
+ _DEFAULT_PIPELINE_WEIGHT_RE,
+ )
+
+ for name in ("pytorch_model-00001-of-00002.safetensors", "pytorch_model.safetensors"):
+ assert dcs._DEFAULT_WEIGHT_RE.match(name) and _DEFAULT_PIPELINE_WEIGHT_RE.match(name)
+ assert dcs._INDEX_RE.match("pytorch_model.safetensors.index.json")
+ assert _DEFAULT_PIPELINE_WEIGHT_INDEX_RE.match("pytorch_model.safetensors.index.json")
+ # an incomplete pytorch_model index is unknown, like the others
+ (t / "pytorch_model-00002-of-00002.safetensors").unlink()
+ assert dcs.local_component_sizes(tmp_path) is None
+
+
+def test_complete_local_snapshot_is_revalidated_online(tmp_path, monkeypatch):
+ fam = _fam("wan2.2-ti2v-5b")
+ snap = tmp_path / ("a" * 40)
+ _stub_for_table(snap, fam)
+ _component(
+ snap, "transformer", fam.bf16_components_gb[0] + 5.0
+ ) # the cached (old) commit is larger
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: snap)
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+ fresh_root = tmp_path / "fresh"
+ _stub_for_table(fresh_root, fam)
+ fresh = dcs.local_component_sizes(fresh_root)
+ hub_calls, ref_calls = [], []
+ monkeypatch.setattr(
+ dcs, "hub_component_sizes", lambda repo, **k: hub_calls.append(repo) or fresh
+ )
+ head = ["a" * 40]
+ monkeypatch.setattr(
+ dcs, "resolve_ref", lambda repo, revision = None, **k: ref_calls.append(repo) or head[0]
+ )
+ expected_old = round(fam.bf16_components_gb[0] + 5.0, 1)
+ # the ref still points at the cached snapshot: local answer, no header reads
+ assert dcs.video_components_gb(fam, "o/variant", allow_hub = True)[0] == expected_old
+ assert hub_calls == [] and ref_calls == ["o/variant"]
+ # the ref moved: hub sizing
+ head[0] = "b" * 40
+ assert dcs.video_components_gb(fam, "o/variant", allow_hub = True) == fam.bf16_components_gb
+ assert hub_calls == ["o/variant"]
+ # offline / local-only / allow_hub=False stay local without resolving
+ ref_calls.clear()
+ assert dcs.video_components_gb(fam, "o/variant", allow_hub = False)[0] == expected_old
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ assert dcs.video_components_gb(fam, "o/variant", allow_hub = True)[0] == expected_old
+ assert ref_calls == []
+
+
+def test_resolve_ref_is_ttl_cached(monkeypatch):
+ import huggingface_hub
+
+ monkeypatch.setattr(dcs, "_REF_CACHE", {})
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+ calls, sha = [], ["c" * 40]
+
+ class _Api:
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo_id,
+ revision = None,
+ timeout = None,
+ files_metadata = False,
+ ):
+ calls.append(files_metadata)
+ return _Info(sha[0])
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)
+ clock = [0.0]
+ import time as _time
+
+ monkeypatch.setattr(_time, "monotonic", lambda: clock[0])
+ assert dcs.resolve_ref("o/r") == "c" * 40
+ assert dcs.resolve_ref("o/r") == "c" * 40
+ assert calls == [False] # one cheap call (no files metadata) inside the TTL
+ clock[0] += dcs.HUB_REFRESH_SECONDS + 1
+ sha[0] = "d" * 40
+ assert dcs.resolve_ref("o/r") == "d" * 40 and len(calls) == 2
+ assert dcs.resolve_ref("o/r", "e" * 40) == "e" * 40 and len(calls) == 2 # pinned: no call
+
+
+def test_companion_folders_follow_the_family_or_manifest(tmp_path):
+ wan = _fam("wan2.2-ti2v-5b") # no audio, not LTX
+ _stub_for_table(tmp_path, wan)
+ base = dcs.video_header_terms(wan, dcs.local_component_sizes(tmp_path))[2]
+ for folder in ("connectors", "vocoder", "audio_vae"):
+ _component(tmp_path, folder, 1.0)
+ # leftover companion folders are not counted for a family that does not load them
+ assert dcs.video_header_terms(wan, dcs.local_component_sizes(tmp_path))[2] == pytest.approx(
+ base
+ )
+ # ... unless model_index.json names them
+ (tmp_path / "model_index.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "X",
+ "vae": ["diffusers", "A"],
+ "vocoder": ["transformers", "B"],
+ "connectors": [None, None],
+ }
+ )
+ )
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert sizes.manifest == frozenset({"vae", "vocoder"})
+ assert dcs.video_header_terms(wan, sizes)[2] == pytest.approx(base + 1.0)
+ # the LTX family loads connectors, an audio family audio_vae and vocoder
+ ltx = _fam("ltx-2")
+ ltx_root = tmp_path / "ltx"
+ _stub_for_table(ltx_root, ltx)
+ before = dcs.video_header_terms(ltx, dcs.local_component_sizes(ltx_root))[2]
+ _component(ltx_root, "connectors", 1.0)
+ _component(ltx_root, "vocoder", 0.5)
+ # the stub already holds 0.1 GB of each; they grew to 1.0 and 0.5
+ assert dcs.video_header_terms(ltx, dcs.local_component_sizes(ltx_root))[2] == pytest.approx(
+ before + 0.9 + 0.4
+ )
+
+
+def test_sub_byte_floats_count_parameters_by_bit_width(tmp_path):
+ # safetensors packs sub-byte dtypes: shape is the logical element count, bytes = numel * bits / 8
+ header = {
+ "__metadata__": {},
+ "f4": {"dtype": "F4", "shape": [4, 16], "data_offsets": [0, 32]},
+ "f6a": {"dtype": "F6_E2M3", "shape": [8], "data_offsets": [32, 38]},
+ "f6b": {"dtype": "F6_E3M2", "shape": [16], "data_offsets": [38, 50]},
+ "scale": {"dtype": "F8_E8M0", "shape": [4], "data_offsets": [50, 54]},
+ }
+ raw = json.dumps(header).encode()
+ path = tmp_path / "transformer" / "diffusion_pytorch_model.safetensors"
+ path.parent.mkdir(parents = True)
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw)
+ size = dcs.local_component_sizes(tmp_path).get("transformer")
+ assert size.float_params == 64 + 8 + 16 + 4
+ assert size.nonfloat_bytes == 0
+ assert size.resident_bytes(2) == (64 + 8 + 16 + 4) * 2 # a bf16 load budgets 2 bytes per param
+ assert dcs.FLOAT_BITS["F4"] == 4 and dcs.FLOAT_BITS["F6_E2M3"] == dcs.FLOAT_BITS["F6_E3M2"] == 6
+
+
+# ---- review round 5 ----
+
+
+def test_unresolved_ref_probes_the_hub_and_falls_back_to_local(tmp_path, monkeypatch):
+ fam = _fam("wan2.2-ti2v-5b")
+ snap = tmp_path / ("a" * 40)
+ _stub_for_table(snap, fam)
+ _component(snap, "transformer", fam.bf16_components_gb[0] + 5.0)
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: snap)
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_HEADER_FETCH", raising = False)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: None)
+ fresh_root = tmp_path / "fresh"
+ _stub_for_table(fresh_root, fam)
+ hub = [dcs.local_component_sizes(fresh_root)]
+ calls = []
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda repo, **k: calls.append(repo) or hub[0])
+ # head unknown: the Hub answers
+ assert dcs.video_components_gb(fam, "o/variant", allow_hub = True) == fam.bf16_components_gb
+ assert calls == ["o/variant"]
+ # head unknown and the Hub probe fails too: the cached local sizes stand (no refusal on a network blip)
+ hub[0] = None
+ got = dcs.video_components_gb(fam, "o/variant", allow_hub = True)
+ assert got[0] == round(fam.bf16_components_gb[0] + 5.0, 1) and len(calls) == 2
+
+
+def test_extra_text_encoders_need_the_family_or_manifest(tmp_path):
+ wan = _fam("wan2.2-ti2v-5b")
+ _stub_for_table(tmp_path, wan)
+ base = dcs.video_header_terms(wan, dcs.local_component_sizes(tmp_path))[1]
+ _component(tmp_path, "text_encoder_2", 1.0, stem = "model")
+ _component(tmp_path, "text_encoder_3", 2.0, stem = "model")
+ assert dcs.video_header_terms(wan, dcs.local_component_sizes(tmp_path))[1] == pytest.approx(
+ base
+ )
+ (tmp_path / "model_index.json").write_text(
+ json.dumps(
+ {
+ "text_encoder": ["t", "A"],
+ "text_encoder_2": ["t", "B"],
+ "text_encoder_3": [None, None],
+ }
+ )
+ )
+ assert dcs.video_header_terms(wan, dcs.local_component_sizes(tmp_path))[1] == pytest.approx(
+ base + 1.0
+ )
+ # HunyuanVideo-1.5 loads its ByT5 text_encoder_2 without a manifest
+ hv = _fam("hunyuanvideo-1.5")
+ root = tmp_path / "hv"
+ _stub_for_table(root, hv)
+ before = dcs.video_header_terms(hv, dcs.local_component_sizes(root))[1]
+ _component(root, "text_encoder_2", 0.44, stem = "model")
+ assert dcs.video_header_terms(hv, dcs.local_component_sizes(root))[1] == pytest.approx(
+ before - 0.1 + 0.44
+ )
+
+
+def test_same_stem_order_follows_the_loader(tmp_path):
+ for folder in ("text_encoder", "transformer"):
+ d = tmp_path / folder
+ stem = "model" if folder == "text_encoder" else "diffusion_pytorch_model"
+ _write_header(d / f"{stem}.safetensors", {"u": ("BF16", 10)})
+ _write_header(d / f"{stem}-00001-of-00001.safetensors", {"s": ("BF16", 999)})
+ _index(d / f"{stem}.safetensors.index.json", [f"{stem}-00001-of-00001.safetensors"])
+ sizes = dcs.local_component_sizes(tmp_path)
+ # transformers folder: the unsharded file first; diffusers folder: the index first
+ assert sizes.get("text_encoder").files == ("model.safetensors",)
+ assert sizes.get("transformer").files == ("diffusion_pytorch_model-00001-of-00001.safetensors",)
+
+
+# ---- review round 6 ----
+
+
+def test_hub_skips_folders_the_manifest_does_not_load(monkeypatch):
+ files = [
+ "model_index.json",
+ "transformer/diffusion_pytorch_model.safetensors",
+ "text_encoder/model.safetensors",
+ "vae/diffusion_pytorch_model.safetensors",
+ "connectors/diffusion_pytorch_model.safetensors",
+ "vocoder/diffusion_pytorch_model.safetensors",
+ "latent_upsampler/diffusion_pytorch_model.safetensors",
+ ]
+ ok = {"__metadata__": {}, "w": {"dtype": "BF16", "shape": [10], "data_offsets": [0, 20]}}
+ # vocoder is null in the manifest and its header fails: not loaded, so not fatal
+ _hub_with(monkeypatch, files, lambda f: None if f.startswith("vocoder/") else ok)
+ manifest = json.dumps(
+ {
+ "transformer": ["d", "T"],
+ "text_encoder": ["t", "E"],
+ "vae": ["d", "V"],
+ "connectors": ["l", "C"],
+ "vocoder": [None, None],
+ }
+ )
+ monkeypatch.setattr(dcs, "_fetch_capped_text", lambda *a, **k: manifest)
+ sizes = dcs.hub_component_sizes("o/r")
+ # latent_upsampler is attached by Studio outside the manifest, so it is still read
+ assert sizes is not None and sizes.names() == (
+ "connectors",
+ "latent_upsampler",
+ "text_encoder",
+ "transformer",
+ "vae",
+ )
+ # a LOADED folder that fails stays fatal
+ _hub_with(monkeypatch, files, lambda f: None if f.startswith("connectors/") else ok)
+ monkeypatch.setattr(dcs, "_fetch_capped_text", lambda *a, **k: manifest)
+ assert dcs.hub_component_sizes("o/r") is None
+
+
+def test_loaded_role_with_unreadable_size_makes_its_term_unknown(tmp_path, monkeypatch):
+ ltx = _fam("ltx-2") # loads connectors and vocoder
+ _stub_for_table(tmp_path, ltx)
+ _component(tmp_path, "connectors", 1.0)
+ import shutil
+
+ shutil.rmtree(tmp_path / "vocoder") # the stub's safetensors vocoder becomes a .bin one
+ (tmp_path / "vocoder").mkdir()
+ (tmp_path / "vocoder" / "diffusion_pytorch_model.bin").write_bytes(b"\0" * 8)
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert "vocoder" in sizes.unknown
+ assert dcs.video_header_terms(ltx, sizes)[2] is None # not the remaining folders summed
+ # a loaded extra text encoder stored as .bin: the text term is unknown
+ hv = _fam("hunyuanvideo-1.5")
+ root = tmp_path / "hv"
+ _stub_for_table(root, hv)
+ shutil.rmtree(root / "text_encoder_2")
+ (root / "text_encoder_2").mkdir()
+ (root / "text_encoder_2" / "pytorch_model.bin").write_bytes(b"\0" * 8)
+ assert dcs.video_header_terms(hv, dcs.local_component_sizes(root))[1] is None
+ # an unloaded leftover .bin folder changes nothing
+ wan = _fam("wan2.2-ti2v-5b")
+ w = tmp_path / "wan"
+ _stub_for_table(w, wan)
+ (w / "vocoder").mkdir()
+ (w / "vocoder" / "diffusion_pytorch_model.bin").write_bytes(b"\0" * 8)
+ assert None not in dcs.video_header_terms(wan, dcs.local_component_sizes(w))
+ # end to end: a variant whose loaded companion is unknown takes the table for that term
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: tmp_path.name)
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda *a, **k: None)
+ # ... and the readable siblings stay a lower bound: never below their known sum
+ known = dcs.video_header_parts(ltx, dcs.local_component_sizes(tmp_path))[2]
+ assert known[1] is False
+ got = dcs.video_components_gb(ltx, "o/ltx2-variant", allow_hub = True)[2]
+ assert got == max(ltx.bf16_components_gb[2], round(known[0], 1))
+
+
+def test_no_index_fallback_takes_only_loader_names(tmp_path):
+ for name in (
+ "adapter_model.safetensors",
+ "weights.safetensors",
+ "diffusion_pytorch_model.fp16.safetensors",
+ ):
+ assert dcs.select_weight_files([name], folder = "transformer") == []
+ _write_header(tmp_path / "transformer" / "adapter_model.safetensors", {"a": ("BF16", 10)})
+ assert dcs.local_component_sizes(tmp_path) is None
+ for stem in ("diffusion_pytorch_model", "model", "pytorch_model"):
+ assert dcs.select_weight_files([f"{stem}.safetensors", "adapter_model.safetensors"]) == [
+ f"{stem}.safetensors"
+ ]
+
+
+def test_local_index_read_is_capped(tmp_path, monkeypatch):
+ t = tmp_path / "transformer"
+ _write_header(t / "diffusion_pytorch_model-00001-of-00001.safetensors", {"a": ("BF16", 10)})
+ _index(
+ t / "diffusion_pytorch_model.safetensors.index.json",
+ ["diffusion_pytorch_model-00001-of-00001.safetensors"],
+ )
+ assert dcs.local_component_sizes(tmp_path) is not None
+ monkeypatch.setattr(
+ dcs, "MAX_INDEX_BYTES", 8
+ ) # the index is now over the cap: never read, unknown
+ reads = []
+ real = Path.read_text
+ monkeypatch.setattr(
+ Path, "read_text", lambda self, *a, **k: reads.append(self.name) or real(self, *a, **k)
+ )
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert sizes is None and "diffusion_pytorch_model.safetensors.index.json" not in reads
+
+
+# ---- review round 7 ----
+
+
+def test_snapshot_missing_a_loaded_role_is_incomplete(tmp_path, monkeypatch):
+ import shutil
+
+ for name, folder, term in (
+ ("ltx-2.5", "latent_upsampler", 2), # Studio-attached, never in model_index.json
+ ("ltx-2", "vocoder", 2), # family rule
+ ("hunyuanvideo-1.5", "text_encoder_2", 1), # family rule
+ ):
+ fam = _fam(name)
+ root = tmp_path / name
+ _stub_for_table(root, fam)
+ assert folder in dcs.video_loaded_roles(fam)
+ shutil.rmtree(root / folder)
+ # the absent loaded role makes its term unknown (table), never the rest summed
+ assert dcs.video_header_terms(fam, dcs.local_component_sizes(root))[term] is None
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None, root = root: root)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, root = root, **k: root.name)
+ calls = []
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda repo, **k: calls.append(repo))
+ got = dcs.video_components_gb(fam, "o/variant", allow_hub = True)
+ assert calls == ["o/variant"], name # incomplete local snapshot: the Hub is probed
+ # the Hub failed too: the known part plus an allowance for the absent folder, never below the table
+ known = dcs.video_header_parts(fam, dcs.local_component_sizes(root))[term][0]
+ allowance = 1.0 if folder == "latent_upsampler" else fam.bf16_components_gb[term]
+ assert got[term] == max(fam.bf16_components_gb[term], round(known + allowance, 1)), name
+ assert got[term] >= fam.bf16_components_gb[term]
+ # a manifest-loaded extra counts too
+ wan = _fam("wan2.2-ti2v-5b")
+ w = tmp_path / "wan"
+ _stub_for_table(w, wan)
+ (w / "model_index.json").write_text(json.dumps({"vae": ["d", "V"], "connectors": ["l", "C"]}))
+ assert "connectors" in dcs.video_loaded_roles(wan, dcs.local_component_sizes(w))
+ assert dcs.video_header_terms(wan, dcs.local_component_sizes(w))[2] is None
+
+
+def test_index_fetch_is_bounded_by_the_deadline_while_a_peer_trickles():
+ import threading as _threading
+ import time as _time
+
+ release = _threading.Event()
+
+ class _Trickle(_Resp):
+ def iter_content(self, chunk_size = 1):
+ yield b"{"
+ release.wait(30) # a peer that never completes the chunk
+ yield b"}"
+
+ resp = _Trickle([])
+ start = _time.monotonic()
+ with pytest.raises(TimeoutError):
+ dcs._fetch_capped_text(_Session(resp), "u", {}, 30.0, _time.monotonic() + 0.5)
+ assert _time.monotonic() - start < 5 # the whole fetch, not one 30 s read
+ assert resp.closed # interrupted (no urllib3 raw here, so closed)
+ release.set()
+
+
+# ---- review round 8 ----
+
+
+def test_ltx_bundled_connector_tensors_leave_the_denoiser_term(tmp_path):
+ fam = _fam("ltx-2.5")
+ _stub_for_table(tmp_path, fam)
+ clean = dcs.video_header_terms(fam, dcs.local_component_sizes(tmp_path))[0]
+ # a variant whose transformer/ also carries the connector tensors (single-file style keys, both prefixes)
+ _write_header(
+ tmp_path / "transformer" / "diffusion_pytorch_model.safetensors",
+ {
+ "w": ("BF16", int(round(fam.bf16_components_gb[0] * _GB / 2))),
+ "video_embeddings_connector.x": ("BF16", 1_000_000_000),
+ "model.diffusion_model.text_embedding_projection.y": ("BF16", 500_000_000),
+ "connectors.z": ("F32", 250_000_000),
+ },
+ )
+ size = dcs.local_component_sizes(tmp_path).get("transformer")
+ assert size.bundled_connector_float_params == 1_750_000_000
+ assert dcs.video_header_terms(fam, dcs.local_component_sizes(tmp_path))[0] == pytest.approx(
+ clean
+ )
+ # the same split for LTX-2; a non-LTX family keeps every tensor
+ assert dcs.video_header_terms(_fam("ltx-2"), dcs.local_component_sizes(tmp_path))[
+ 0
+ ] == pytest.approx(clean)
+ wan = dcs.video_header_terms(_fam("wan2.2-ti2v-5b"), dcs.local_component_sizes(tmp_path))[0]
+ assert wan == pytest.approx(clean + 3.5)
+ # base plans are unchanged: the table still answers for the base repo
+ from unittest import mock
+
+ with mock.patch.object(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path):
+ assert dcs.video_components_gb(fam) == fam.bf16_components_gb
+
+
+def test_latent_upsampler_is_loaded_only_when_attached(tmp_path, monkeypatch):
+ import shutil
+
+ from core.inference import video_ltx25
+
+ fam = _fam("ltx-2.5")
+ _stub_for_table(tmp_path, fam)
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: True)
+ assert "latent_upsampler" in dcs.video_loaded_roles(fam)
+ assert "latent_upsampler" not in dcs.video_loaded_roles(fam, dev = True)
+ shutil.rmtree(tmp_path / "latent_upsampler")
+ sizes = dcs.local_component_sizes(tmp_path)
+ # two-stage distilled: the absent upsampler makes the term unknown; dev: it is not loaded, the term is known
+ assert dcs.video_header_terms(fam, sizes)[2] is None
+ assert dcs.video_header_terms(fam, sizes, dev = True)[2] is not None
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: False)
+ assert "latent_upsampler" not in dcs.video_loaded_roles(fam)
+ assert dcs.video_header_terms(fam, sizes)[2] is not None
+
+
+def test_load_pipeline_passes_the_dev_flag():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video.VideoBackend.load_pipeline)
+ call = src[src.index("components = video_components_gb(") :]
+ call = call[: call.index("\n )")]
+ assert "dev = _ltx25_dev_load(" in call
+
+
+def test_moe_second_expert_is_optional_unless_shipped(tmp_path):
+ moe = _fam("wan2.2-t2v-a14b")
+ _component(tmp_path, "transformer", 28.6)
+ _component(tmp_path, "text_encoder", 11.4, stem = "model")
+ _component(tmp_path, "vae", 0.254, "F32")
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert "transformer_2" not in dcs.video_loaded_roles(moe, sizes)
+ assert dcs.video_header_terms(moe, sizes)[0] == pytest.approx(
+ 28.6
+ ) # the known first expert is kept
+ # named by the manifest but absent: loaded, so the snapshot is incomplete and the term unknown
+ (tmp_path / "model_index.json").write_text(
+ json.dumps({"transformer": ["d", "W"], "transformer_2": ["d", "W"]})
+ )
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert "transformer_2" in dcs.video_loaded_roles(moe, sizes)
+ assert dcs.video_header_terms(moe, sizes)[0] is None
+ # present: both experts count
+ _component(tmp_path, "transformer_2", 28.6)
+ assert dcs.video_header_terms(moe, dcs.local_component_sizes(tmp_path))[0] == pytest.approx(
+ 57.2
+ )
+ # a non-MoE family never counts a stray transformer_2
+ assert dcs.video_header_terms(_fam("wan2.2-ti2v-5b"), dcs.local_component_sizes(tmp_path))[
+ 0
+ ] == pytest.approx(28.6)
+
+
+# ---- review round 9 ----
+
+
+def test_partial_term_keeps_its_known_sum_as_a_lower_bound(tmp_path, monkeypatch):
+ import shutil
+
+ ltx = _fam("ltx-2")
+ _stub_for_table(tmp_path, ltx)
+ _component(
+ tmp_path, "vae", ltx.bf16_components_gb[2] + 4.0
+ ) # readable siblings far above the table term
+ shutil.rmtree(tmp_path / "vocoder")
+ (tmp_path / "vocoder").mkdir()
+ (tmp_path / "vocoder" / "diffusion_pytorch_model.bin").write_bytes(b"\0" * 8)
+ known, complete = dcs.video_header_parts(ltx, dcs.local_component_sizes(tmp_path))[2]
+ assert not complete and known > ltx.bf16_components_gb[2]
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: tmp_path.name)
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda *a, **k: None)
+ got = dcs.video_components_gb(ltx, "o/variant", allow_hub = True)
+ assert got[2] == round(known, 1) # never below what did read
+ assert dcs.reconcile_with_table(
+ (None, None, None), (1.0, 1.0, 1.0), is_base = False, lower = (None, 2.04, None)
+ ) == (1.0, 2.0, 1.0)
+
+
+def test_dev_table_term_drops_the_upsampler_before_reconciling(monkeypatch, tmp_path):
+ from core.inference import video_ltx25
+
+ fam = _fam("ltx-2.5")
+ table = fam.bf16_components_gb
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: None)
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: True)
+ assert dcs.video_components_gb(fam) == table
+ # dev: the table's companion term loses the upsampler constant, so it compares with a header term without it
+ dev = dcs.video_components_gb(fam, dev = True)
+ assert dev == (table[0], table[1], round(table[2] - video_ltx25.LTX25_LATENT_UPSAMPLER_GB, 3))
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: False)
+ assert dcs.video_components_gb(fam) == dev
+ # a dev variant whose headers equal the table minus the upsampler agrees, no mismatch recorded
+ monkeypatch.setattr(dcs, "_MISMATCHES", {})
+ _stub_for_table(tmp_path, fam) # two-stage off: no upsampler folder in the stub
+ _component(
+ tmp_path, "vae", 0.1 + 0.0
+ ) # shrink the stub's companion term by the upsampler the table includes
+ vae_known = dcs.video_header_parts(fam, dcs.local_component_sizes(tmp_path))[2][0]
+ _component(tmp_path, "vae", 0.1 + dev[2] - vae_known)
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: tmp_path.name)
+ got = dcs.video_components_gb(fam, "o/ltx25-variant", allow_hub = True, dev = True)
+ assert got[2] == pytest.approx(dev[2], abs = 0.06) and not dcs.table_mismatches()
+
+
+def test_load_pipeline_no_longer_subtracts_the_upsampler_itself():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video.VideoBackend.load_pipeline)
+ assert "LTX25_LATENT_UPSAMPLER_GB" not in src and "term_part_gb" not in src
+ assert "dev = _ltx25_dev_load(" in src
+
+
+def test_dev_load_never_probes_the_upsampler_on_the_hub(monkeypatch):
+ from core.inference import video_ltx25
+
+ fam = _fam("ltx-2.5")
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: None)
+ seen = []
+ monkeypatch.setattr(
+ dcs,
+ "hub_component_sizes",
+ lambda repo, components = None, **k: seen.append(tuple(components)),
+ )
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: True)
+ dcs.video_components_gb(fam, "o/v", allow_hub = True, dev = True)
+ dcs.video_components_gb(fam, "o/v", allow_hub = True, dev = False)
+ assert "latent_upsampler" not in seen[0] and "latent_upsampler" in seen[1]
+ monkeypatch.setattr(video_ltx25, "two_stage_enabled", lambda: False)
+ dcs.video_components_gb(fam, "o/v", allow_hub = True)
+ assert "latent_upsampler" not in seen[2]
+
+
+def test_manifest_is_authoritative_for_the_second_expert(tmp_path):
+ moe = _fam("wan2.2-t2v-a14b")
+ _component(tmp_path, "transformer", 28.6)
+ _component(tmp_path, "transformer_2", 28.6) # a stale folder
+ _component(tmp_path, "text_encoder", 11.4, stem = "model")
+ _component(tmp_path, "vae", 0.254, "F32")
+ assert dcs.video_header_terms(moe, dcs.local_component_sizes(tmp_path))[0] == pytest.approx(
+ 57.2
+ ) # no manifest
+ (tmp_path / "model_index.json").write_text(
+ json.dumps({"transformer": ["d", "W"], "transformer_2": [None, None]})
+ )
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert "transformer_2" not in dcs.video_loaded_roles(moe, sizes)
+ assert dcs.video_header_terms(moe, sizes)[0] == pytest.approx(28.6)
+
+
+def test_checkpoint_fingerprint_tracks_the_exact_weights(tmp_path, monkeypatch):
+ root = tmp_path / "pipe"
+ _component(root, "transformer", 0.001)
+ (root / "transformer" / "config.json").write_text('{"a": 1}')
+ (root / "model_index.json").write_text("{}")
+ first = dcs.checkpoint_fingerprint(str(root))
+ assert first and first == dcs.checkpoint_fingerprint(str(root))
+ (root / "transformer" / "config.json").write_text('{"a": 2}')
+ assert dcs.checkpoint_fingerprint(str(root)) != first
+ # a repo id resolves to its cache snapshot commit
+ from utils import hf_cache_settings
+
+ cache = tmp_path / "hub"
+ snap = cache / "models--o--r" / "snapshots" / ("f" * 40)
+ snap.mkdir(parents = True)
+ (snap / "model_index.json").write_text("{}")
+ (cache / "models--o--r" / "refs").mkdir()
+ (cache / "models--o--r" / "refs" / "main").write_text("f" * 40)
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))
+ assert dcs.checkpoint_fingerprint("o/r") == "f" * 40
+ assert dcs.checkpoint_fingerprint("o/missing") is None
+
+
+def test_calibration_key_carries_the_revision():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video)
+ key_at = src.index("video_stream_residency.calibration_key(")
+ call = src[key_at : src.index("\n )", key_at)]
+ assert "revision = _calibration_revision(state)" in call
+ a = vsr.calibration_key("ltx-2", "r", "group", "cuda:0", revision = "a" * 40)
+ assert a != vsr.calibration_key("ltx-2", "r", "group", "cuda:0", revision = "b" * 40)
+
+
+# ---- review round 10 ----
+
+
+def test_manifest_predicate_matches_the_loader(tmp_path):
+ import inspect
+
+ from core.inference import diffusion
+
+ assert dcs.manifest_entry_loaded("vae", ["diffusers", "AutoencoderKL"])
+ for spec in (
+ ["diffusers"],
+ ["diffusers", None],
+ [None, "X"],
+ [None, None],
+ "diffusers",
+ None,
+ [],
+ ):
+ assert not dcs.manifest_entry_loaded("vae", spec), spec
+ assert not dcs.manifest_entry_loaded("_class_name", ["a", "b"])
+ (tmp_path / "model_index.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "P",
+ "vae": ["d", "V"],
+ "vocoder": ["d", None],
+ "connectors": ["l"],
+ "text_encoder": [None, "T"],
+ }
+ )
+ )
+ assert dcs._manifest_names(tmp_path) == frozenset({"vae"})
+ # the loader's staging selection uses the same predicate (no second copy to drift)
+ src = inspect.getsource(diffusion)
+ assert "manifest_entry_loaded(name, spec)" in src
+ assert "len(spec) >= 2" not in src
+
+
+def test_auto_cache_decision_is_shared_and_retags_the_calibration():
+ import inspect
+
+ from core.inference import diffusion_cache, video
+
+ assert (
+ diffusion_cache.auto_step_cache_mode(diffusion_cache.FBCACHE_MIN_STEPS)
+ == diffusion_cache.TC_FBCACHE
+ )
+ assert diffusion_cache.auto_step_cache_mode(diffusion_cache.FBCACHE_MIN_STEPS - 1) is None
+ assert "auto_step_cache_mode(steps)" in inspect.getsource(
+ diffusion_cache.maybe_toggle_step_cache
+ )
+ src = inspect.getsource(video)
+ key_at = src.index("video_stream_residency.calibration_key(")
+ call = src[key_at : src.index("\n )", key_at)]
+ assert "transformer_cache = request_cache_mode" in call
+ assert src.index("request_cache_mode = auto_step_cache_mode(steps)") < key_at
+ toggle_at = src.index("toggled = maybe_toggle_step_cache(")
+ assert (
+ src.index('video_stream_residency.retag(state.pipe, "transformer_cache", toggled)')
+ > toggle_at
+ )
+ # the retag rewrites only that entry, so the recorded peak lands under the mode that ran
+ pipe = _Pipe()
+ key = vsr.calibration_key(
+ "wan", "r", "group", "cuda:0", transformer_cache = "fbcache", dtype = "bf16"
+ )
+ pipe.transformer._unsloth_video_calibration_key = key
+ new = vsr.retag(pipe, "transformer_cache", None)
+ assert new == vsr.calibration_key(
+ "wan", "r", "group", "cuda:0", transformer_cache = None, dtype = "bf16"
+ )
+ assert pipe.transformer._unsloth_video_calibration_key == new
+ assert vsr.retag(_Pipe(), "transformer_cache", None) is None
+
+
+def test_retagged_peak_is_recorded_under_the_mode_that_ran(monkeypatch):
+ import torch
+
+ monkeypatch.setattr(vsr, "_PEAKS", {})
+ alloc = {"now": 0, "peak": 0}
+ monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda dev = None: None)
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda dev = None: alloc["now"])
+ monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda dev = None: alloc["peak"])
+ predicted = vsr.calibration_key("wan", "r", "group", "cuda:0", transformer_cache = "fbcache")
+ pipe = _Pipe()
+ vsr.arm_request(pipe, key = predicted, width = 8, height = 8, frames = 1, device = "cuda:0")
+ vsr.retag(pipe, "transformer_cache", None) # the runner-aware toggle ran uncached
+ alloc["peak"] = 500 << 20
+ vsr.record_request_peak(pipe)
+ ran = vsr.with_extra(predicted, "transformer_cache", None)
+ assert vsr.measured_extra_mib(ran, 64) == 500
+ assert vsr.measured_extra_mib(predicted, 64) is None
+
+
+# ---- review round 11 ----
+
+
+def test_pre_download_plan_threads_the_dev_flag():
+ import inspect
+
+ from core.inference import video
+
+ seed = inspect.getsource(video._video_seed_stays_resident)
+ assert "dev = ltx25_dev" in seed
+ planned = inspect.getsource(video.VideoBackend._video_planned_auto_denoiser_scheme)
+ assert planned.count("ltx25_dev = ltx25_dev,") == 2 # both seed checks
+ for caller in (video.VideoBackend._run_load, video.VideoBackend.download_plan):
+ src = inspect.getsource(caller)
+ call = src[src.index("_video_planned_auto_denoiser_scheme(") :]
+ assert (
+ "ltx25_dev = ltx25_dev" in call[: call.index("DENOISER_SEED_DECLINED")]
+ ), caller.__name__
+
+
+def test_unknown_loaded_folder_gets_an_allowance(tmp_path, monkeypatch):
+ import shutil
+
+ ltx = _fam("ltx-2")
+ _stub_for_table(tmp_path, ltx)
+ _component(
+ tmp_path, "vae", ltx.bf16_components_gb[2] + 4.0
+ ) # known siblings above the table term
+ shutil.rmtree(tmp_path / "vocoder")
+ (tmp_path / "vocoder").mkdir()
+ (tmp_path / "vocoder" / "diffusion_pytorch_model.bin").write_bytes(
+ b"\0" * 300_000_000
+ ) # 0.3 GB on disk
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert dict(sizes.unknown_bytes)["vocoder"] == 300_000_000
+ known = dcs.video_header_parts(ltx, sizes)[2][0]
+ monkeypatch.setattr(dcs, "local_snapshot_dir", lambda repo, cache_dir = None: tmp_path)
+ monkeypatch.setattr(dcs, "resolve_ref", lambda *a, **k: tmp_path.name)
+ monkeypatch.setattr(dcs, "hub_component_sizes", lambda *a, **k: None)
+ got = dcs.video_components_gb(ltx, "o/variant", allow_hub = True)
+ assert got[2] == round(known + 0.3, 1) # the .bin's stored bytes are its allowance, not dropped
+ # no file and no own constant: one whole table term for the unestimated folders
+ assert dcs._term_lower_bound(2.0, ("a", "b"), sizes, 5.0) == 7.0
+ assert dcs._term_lower_bound(2.0, ("vocoder",), sizes, 5.0) == pytest.approx(2.3)
+ assert dcs._term_lower_bound(2.0, ("latent_upsampler",), sizes, 5.0) == pytest.approx(3.0)
+ assert dcs._term_lower_bound(2.0, ("a",), sizes, None) is None
+
+
+def test_single_file_loads_size_companions_from_the_resolved_base():
+ import inspect
+
+ from core.inference import video
+
+ src = inspect.getsource(video.VideoBackend.load_pipeline)
+ call = src[src.index("components = video_components_gb(") :]
+ call = call[: call.index("\n )")]
+ assert 'repo_id if kind == "pipeline" else base,' in call
+
+
+def test_calibration_revision_includes_the_companion_base(monkeypatch):
+ from types import SimpleNamespace
+
+ from core.inference import video
+
+ fps = {"u/ltx-gguf": "g" * 40, "Lightricks/LTX-2": "b" * 40, "someone/ltx2-base": "c" * 40}
+ monkeypatch.setattr(dcs, "checkpoint_fingerprint", lambda repo, filename = None: fps.get(repo))
+
+ def rev(kind, base):
+ state = SimpleNamespace(
+ pipe = SimpleNamespace(),
+ repo_id = "u/ltx-gguf",
+ gguf_filename = "x.gguf",
+ kind = kind,
+ base_repo = base,
+ )
+ return video._calibration_revision(state)
+
+ assert rev("pipeline", "Lightricks/LTX-2") == "g" * 40
+ gguf_default = rev("gguf", "Lightricks/LTX-2")
+ assert gguf_default == f"{'g' * 40}|base=Lightricks/LTX-2@{'b' * 40}"
+ assert rev("gguf", "someone/ltx2-base") != gguf_default
+
+
+def test_transformers_folders_recognise_only_transformers_stems(tmp_path):
+ for name in (
+ "diffusion_pytorch_model.safetensors",
+ "pytorch_model.safetensors",
+ ):
+ assert dcs._pick_files([name], lambda n: "", "text_encoder") == [], name
+ assert dcs._pick_files([name], lambda n: "", "transformer") == [name], name
+ assert dcs._pick_files(["model.safetensors"], lambda n: "", "image_encoder") == [
+ "model.safetensors"
+ ]
+ # pytorch_model.bin: what transformers reads next, not sized here -> unknown, with its bytes as the allowance
+ te = tmp_path / "text_encoder"
+ te.mkdir()
+ (te / "pytorch_model.bin").write_bytes(b"\0" * 1000)
+ _write_header(te / "diffusion_pytorch_model.safetensors", {"x": ("BF16", 10)})
+ _component(tmp_path, "vae", 0.1)
+ sizes = dcs.local_component_sizes(tmp_path)
+ assert sizes.get("text_encoder") is None and "text_encoder" in sizes.unknown