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: fetch every video component from unsloth repos (#14003)

Daniel Han3111a2c76b06
diff --git a/studio/backend/core/inference/diffusion_comfy_components.py b/studio/backend/core/inference/diffusion_comfy_components.py
index 59e6015c403..42950587b33 100644
--- a/studio/backend/core/inference/diffusion_comfy_components.py
+++ b/studio/backend/core/inference/diffusion_comfy_components.py
@@ -1048,24 +1048,30 @@ def _component_class_and_config(
vae_cls = getattr(diffusers, class_name, None)
if vae_cls is None:
raise ComponentFileError(f"diffusers has no {class_name}; update diffusers")
+ from .diffusion_families import pinned_revision_kwargs
+
return vae_cls, vae_cls.load_config(
base,
subfolder = COMPONENT_VAE,
token = hf_token,
cache_dir = cache_dir,
local_files_only = local_files_only,
+ **pinned_revision_kwargs(base),
)
import transformers
encoder_cls = getattr(transformers, class_name, None)
if encoder_cls is None:
raise ComponentFileError(f"transformers has no {class_name}; update transformers")
+ from .diffusion_families import pinned_revision_kwargs
+
config = transformers.AutoConfig.from_pretrained(
base,
subfolder = component,
token = hf_token,
cache_dir = cache_dir,
local_files_only = local_files_only,
+ **pinned_revision_kwargs(base),
)
from .diffusion_krea2 import remap_rope_parameters
@@ -1198,12 +1204,15 @@ def read_model_index(
continue
from huggingface_hub import hf_hub_download
+ from .diffusion_families import pinned_revision_kwargs
+
local = hf_hub_download(
base,
"model_index.json",
token = hf_token,
cache_dir = cache_dir,
local_files_only = local_files_only,
+ **pinned_revision_kwargs(base),
)
return json.loads(Path(local).read_text(encoding = "utf-8"))
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index ca9322ceda6..2a0de683c23 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -1093,12 +1093,16 @@ def load_comfy_quant_transformer(
local_files_only = bool(kwargs.pop("local_files_only", False))
if not isinstance(config_repo, str):
raise ValueError("a ComfyUI-quantized single file needs the base repo's transformer config")
+ from .diffusion_families import pinned_revision_kwargs
+
+ kwargs.pop("revision", None) # the pin below is keyed on config_repo itself
config = transformer_cls.load_config(
config_repo,
subfolder = subfolder,
token = token,
cache_dir = cache_dir,
local_files_only = local_files_only,
+ **pinned_revision_kwargs(config_repo),
)
expected, optional = transformer_cls._get_signature_keys(transformer_cls)
config.update({k: v for k, v in kwargs.items() if k in expected or k in optional})
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 4308b5f4adf..7c807828a13 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import importlib.util
import json
+import contextvars
import os
import re
import sys
@@ -1509,6 +1510,37 @@ _UNGATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
("stabilityai/sdxl-turbo", "unsloth/sdxl-turbo"),
)
_MIRROR_PAIRS: tuple[tuple[str, str], ...] = _GATED_MIRROR_PAIRS + _UNGATED_MIRROR_PAIRS
+
+# The VIDEO bases (video_families). No separate mirror repo: the official files Studio loads (the diffusers folders,
+# bf16 transformer included, or the single files of a split release) are copied byte-identical, at their upstream
+# paths, into the EXISTING unsloth repo of that model -- its -FP8 repo, or -GGUF when there is no -FP8 -- beside the
+# upstream LICENSE and the NOTICE the licence asks for. The listing selectors skip that repo's own root checkpoints
+# (.pt, root .safetensors, .gguf, samples/), so it serves as the base. MiniMax-H3 already has a complete copy.
+# Kept OUT of ``_MIRROR_PAIRS``: that tuple is the IMAGE companion table (hub/utils/companion_assets reads it to decide
+# which cached repos an image checkpoint can strand), while these feed only the id lookups below, so mirror_repo /
+# canonical_base / prefer_ungated_mirror answer for video ids and nothing image-side changes.
+# Absent on purpose: HunyuanVideo-1.5, whose Tencent Hunyuan Community licence is limited to a Territory that excludes
+# the EU, UK and South Korea, which a public Hub repo cannot honour (the reason HunyuanImage-2.1 has no mirror either);
+# and Wan2.1-T2V-1.3B / -14B, for which no unsloth repo exists to carry the files.
+_VIDEO_GATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
+ ("Lightricks/LTX-2.5-Diffusers", "unsloth/LTX-2.5-FP8"),
+ # The split single-file release (text_encoders/, vae/, latent_upscale_models/, diffusion_models/ bf16 DiTs). In the
+ # GGUF repo because the FP8 repo already carries the Diffusers pack, and one repo cannot stand for two upstreams.
+ ("Lightricks/LTX-2.5", "unsloth/LTX-2.5-GGUF"),
+)
+_VIDEO_UNGATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
+ ("Wan-AI/Wan2.2-TI2V-5B-Diffusers", "unsloth/Wan2.2-TI2V-5B-FP8"),
+ ("Wan-AI/Wan2.2-T2V-A14B-Diffusers", "unsloth/Wan2.2-T2V-A14B-FP8"),
+ # LTX-2 is the base of the ltx-2 family AND the source of LTX-2.3's scheduler, Gemma3 text encoder and tokenizer.
+ ("Lightricks/LTX-2", "unsloth/LTX-2-FP8"),
+ # LTX-2.3 ships single files only (the bf16 dev / distilled / distilled-1.1 DiTs a pick names).
+ ("Lightricks/LTX-2.3", "unsloth/LTX-2.3-FP8"),
+ ("MiniMaxAI/MiniMax-H3", "unsloth/MiniMax-H3"),
+)
+_VIDEO_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (
+ _VIDEO_GATED_MIRROR_PAIRS + _VIDEO_UNGATED_MIRROR_PAIRS
+)
+
# Mirror targets that are ALSO a model's own artifact repo (its GGUF / prequant checkpoints sit at the root beside the
# official diffusers folders). A user picks these ids directly, so they are never "just a copy of the upstream": no
# opt-out may rewrite them to the upstream (which has no such checkpoint), a cached one is its own checkpoint rather
@@ -1524,9 +1556,56 @@ _ARTIFACT_MIRRORS: frozenset[str] = frozenset(
"unsloth/qwen-image-layered-gguf",
}
)
-_GATED_MIRRORS: dict[str, str] = {u.lower(): m for u, m in _MIRROR_PAIRS}
-_MIRROR_UPSTREAM: dict[str, str] = {m.lower(): u for u, m in _MIRROR_PAIRS}
-_GATED_UPSTREAMS: frozenset[str] = frozenset(u.lower() for u, _m in _GATED_MIRROR_PAIRS)
+_ALL_MIRROR_PAIRS: tuple[tuple[str, str], ...] = _MIRROR_PAIRS + _VIDEO_MIRROR_PAIRS
+_GATED_MIRRORS: dict[str, str] = {u.lower(): m for u, m in _ALL_MIRROR_PAIRS}
+_MIRROR_UPSTREAM: dict[str, str] = {m.lower(): u for u, m in _ALL_MIRROR_PAIRS}
+_GATED_UPSTREAMS: frozenset[str] = frozenset(
+ u.lower() for u, _m in _GATED_MIRROR_PAIRS + _VIDEO_GATED_MIRROR_PAIRS
+)
+
+
+# Repo id (lowercased) -> the commit a load's plan pinned it to, for the duration of that load's assembly. Set only by
+# ``pinned_repo_revision`` around a video load; every hub-id CONFIG read of a base repo (encoder / VAE / transformer
+# configs, model_index, the LTX-2.5 companions) asks ``pinned_revision_kwargs`` so it reads the planned commit. Empty
+# outside such a block, so unpinned callers (image loads, direct calls) pass no revision and behave as before.
+_PINNED_REVISIONS: "contextvars.ContextVar[Optional[dict[str, str]]]" = contextvars.ContextVar(
+ "unsloth_pinned_repo_revisions", default = None
+)
+
+
+def _pins() -> "contextvars.ContextVar[Optional[dict[str, str]]]":
+ return _PINNED_REVISIONS
+
+
+class pinned_repo_revision:
+ """``with pinned_repo_revision(repo, revision):`` pins hub-id reads of ``repo`` to ``revision`` in this context.
+ A no-op when either is missing or ``repo`` is a local path."""
+
+ def __init__(self, repo: Optional[str], revision: Optional[str]):
+ self._key = (
+ (repo or "").strip().lower() if repo and revision and not _is_local_path(repo) else ""
+ )
+ self._revision = revision
+ self._token = None
+
+ def __enter__(self) -> "pinned_repo_revision":
+ if self._key:
+ var = _pins()
+ self._token = var.set({**(var.get() or {}), self._key: str(self._revision)})
+ return self
+
+ def __exit__(self, *_exc: Any) -> None:
+ if self._token is not None:
+ _pins().reset(self._token)
+ self._token = None
+
+
+def pinned_revision_kwargs(repo: Any) -> dict[str, str]:
+ """``{"revision": <commit>}`` when ``repo`` is pinned in this context, else ``{}``."""
+ if not isinstance(repo, str) or not repo:
+ return {}
+ revision = (_pins().get() or {}).get(repo.strip().lower())
+ return {"revision": revision} if revision else {}
def mirror_repo(repo_id: Optional[str]) -> Optional[str]:
@@ -1704,17 +1783,10 @@ def cache_holds_files(repo_id: str, files: Sequence[str]) -> bool:
# Lowercased unsloth mirror -> the community repack the tables named before it. The mirrors are byte identical, so an
# existing install that already pulled the repack holds the very same bytes under the OLD repo key: the HF cache is
# keyed by repo id, so re-pointing the table alone would re-download up to tens of GB on upgrade and fail outright
-# offline.
-_SD_CPP_LEGACY_SOURCES: dict[str, str] = {
- # No image entry: every image sd-cli asset is now an official upstream file or an unsloth GGUF, so no image load
- # reads a Comfy-made repack, not even one already in the cache.
- "unsloth/wan2.2-ti2v-5b-gguf": "QuantStack/Wan2.2-TI2V-5B-GGUF",
- # MiniMax-H3, where only PART of the mirror came from the repack: the two VAEs now sit beside the denoisers in the
- # GGUF repo, and the int8 ConvRot conditioner beside the other prequantized checkpoints. That is why every caller
- # passes the exact file list -- a denoiser the repack never carried simply misses the probe and keeps the mirror.
- "unsloth/minimax-h3-gguf": "Comfy-Org/MiniMax-H3",
- "unsloth/minimax-h3-fp8": "Comfy-Org/MiniMax-H3",
-}
+# offline. Empty now: every image sd-cli asset is an official upstream file or an unsloth GGUF, and a video load never
+# reads from a Comfy or third-party repack (the MiniMax-H3 and Wan2.2-TI2V-5B-GGUF rows are gone), so no load reads a
+# repack, not even bytes already cached under one. Kept as the hook ``prefer_cached_legacy_source`` reads.
+_SD_CPP_LEGACY_SOURCES: dict[str, str] = {}
def legacy_source_repo(repo_id: Optional[str]) -> Optional[str]:
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index c1ad36aa59b..94ea78ff164 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -2693,12 +2693,14 @@ def _load_transformer_config(
last: Optional[BaseException] = None
for root in _config_cache_roots(checkpoint_path, cache_dir):
try:
+ from .diffusion_families import pinned_revision_kwargs
return transformer_cls.load_config(
base,
subfolder = subfolder,
token = hf_token,
cache_dir = root,
local_files_only = local_files_only,
+ **pinned_revision_kwargs(base),
)
except Exception as exc: # noqa: BLE001 - try the other root before giving up
last = exc
diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.py
index 566c065379b..d4f88297dfb 100644
--- a/studio/backend/core/inference/diffusion_te_prequant.py
+++ b/studio/backend/core/inference/diffusion_te_prequant.py
@@ -1156,7 +1156,12 @@ def load_prequant_text_encoder(
}
if subfolder:
config_kwargs["subfolder"] = subfolder
- config = transformers.AutoConfig.from_pretrained(config_source or base, **config_kwargs)
+ from .diffusion_families import pinned_revision_kwargs
+
+ config_from = config_source or base
+ config = transformers.AutoConfig.from_pretrained(
+ config_from, **config_kwargs, **pinned_revision_kwargs(config_from)
+ )
# Krea-2 ships transformers-5.x configs whose rope lives under rope_parameters; the runtime component loader
# remaps it for a 4.x runtime, and the meta-init here must match or the rebuilt encoder forwards with a broken
# rope.
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e27f424cc0a..711308d8b38 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -35,14 +35,15 @@ import dataclasses
import functools
import inspect
import os
+import re
import tempfile
import threading
from utils.account_context import account_thread, current_account_id
import time
import types
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any, Callable, NamedTuple, Optional, Sequence
from hub.utils.hf_errors import modelscope_missing
from loggers import get_logger
@@ -253,7 +254,6 @@ from .video_minimax_h3 import (
h3_transformer_task,
)
from .video_minimax_h3_te import (
- H3_LEGACY_TE_QUANT_REPO,
H3_TE_QUANT_DEFAULT,
H3_TE_QUANT_REPO,
h3_te_quant_scheme,
@@ -802,6 +802,16 @@ def _cached_checkpoint_file(repo_id: str, filename: str) -> Optional[Path]:
path = Path(repo_id).expanduser() / filename
if path.is_file():
return path
+ # A mirrored repo is fetched into the MIRROR's cache key, an older install's copy sits under the upstream's.
+ for alias in _video_repo_aliases(repo_id) or (repo_id,):
+ hit = _cached_hub_checkpoint_file(alias, filename)
+ if hit is not None:
+ return hit
+ return None
+
+
+def _cached_hub_checkpoint_file(repo_id: str, filename: str) -> Optional[Path]:
+ """``filename``'s cached hub blob for exactly ``repo_id`` (active, legacy and default cache roots), else None."""
from huggingface_hub import try_to_load_from_cache
cached = try_to_load_from_cache(repo_id, filename)
@@ -1175,6 +1185,9 @@ def _detect_load_family(
)
if fam is not None and fam.name == "ltx-2.5" and not ltx_file:
from .video_ltx25 import LTX25_SINGLE_FILE_REPO, is_ltx25_single_file_base
+
+ # Mirror-folded: the carrier (unsloth/LTX-2.5-GGUF) has no model_index.json either. Only a FILE pick keeps
+ # the unfolded check (ltx25_default_base), so a GGUF from the carrier keeps the Diffusers base.
if is_ltx25_single_file_base(repo_id):
# No model_index.json there: a pipeline load would stage ~29 GB of companions and then fail.
raise ValueError(
@@ -1448,6 +1461,152 @@ class _VideoLoadingState:
# Companion repos this load is ALSO pulling from, beyond repo_id / base_repo (the native H3 GGUF and component
# repos). Mirrors the image backend's _SdLoading.asset_repos.
asset_repos: tuple[str, ...] = ()
+ # Fetch ROLE ("checkpoint" / "base") -> the one plan this load settled at estimate time: the repo that role
+ # fetches from, the revision it is pinned to and every file with its blob key and size. Written only by the worker
+ # that owns this state (under the load-token check), replaced whole by a re-estimate, never patched by a fetch site.
+ # The fetch sites read their repo + revision from it, and load_progress reads nothing else.
+ fetch_plan: dict[str, "_PlannedFetch"] = field(default_factory = dict)
+
+
+class _PlannedFetch(NamedTuple):
+ """One fetch role's plan: the repo it reads, the revision it is pinned to (the listing commit when that repo IS the
+ listing; None for an upstream kept for its cache, which resolves its own ref) and ``(name, blob key, size)`` per
+ file. The blob key (LFS sha256, else git blob id) is what huggingface_hub names the cache blob, so progress reads a
+ file's bytes by content: revision-proof, root-proof, and blind to any other blob in the repo."""
+
+ repo: str
+ revision: Optional[str]
+ files: tuple
+ # The encoder components the plan left out (hosted pre-cast checkpoints it expected to find); _run_load re-plans
+ # the base when the actual fetches skip a different set.
+ skip_te: tuple = ()
+
+
+def _sibling_etag(sibling: Any) -> Optional[str]:
+ """The key huggingface_hub names a sibling's cache blob by: the LFS sha256, else the git blob id."""
+ lfs = getattr(sibling, "lfs", None)
+ sha = getattr(lfs, "sha256", None) or (lfs.get("sha256") if isinstance(lfs, dict) else None)
+ return sha or getattr(sibling, "blob_id", None) or None
+
+
+def _fetched_pins(plan: dict[str, "_PlannedFetch"]) -> dict[str, str]:
+ """The commit the checkpoint was already fetched under, keyed by its repo, for a re-plan to list that repo at."""
+ entry = plan.get(_FETCH_CHECKPOINT)
+ return {entry.repo: entry.revision} if entry is not None and entry.revision else {}
+
+
+def _keep_fetched_checkpoint(
+ replanned: dict[str, "_PlannedFetch"], previous: dict[str, "_PlannedFetch"]
+) -> dict[str, "_PlannedFetch"]:
+ """A re-plan made after the checkpoint was fetched keeps the checkpoint entry it was fetched under."""
+ out = dict(replanned)
+ if _FETCH_CHECKPOINT in previous:
+ out[_FETCH_CHECKPOINT] = previous[_FETCH_CHECKPOINT]
+ return out
+
+
+class _OneCommitListings:
+ """``model_info`` per physical repo, ONCE per plan: two roles reading one repo (a carrier's own checkpoint and the
+ base it mirrors) are sized and pinned from the same listing, so they can never land on two commits. ``pins`` maps
+ a lowercased repo to the commit a role was already fetched under (a re-plan after the checkpoint fetch), and that
+ repo is then listed at exactly that commit."""
+
+ def __init__(
+ self,
+ api: Any,
+ pins: Optional[dict[str, str]] = None,
+ ):
+ self._api = api
+ self._pins = {k.lower(): v for k, v in (pins or {}).items() if k and v}
+ self._infos: dict[str, Any] = {}
+
+ def info(self, repo: str) -> Any:
+ key = repo.strip().lower()
+ if key not in self._infos:
+ pinned = self._pins.get(key)
+ self._infos[key] = self._api.model_info(
+ repo, files_metadata = True, **({"revision": pinned} if pinned else {})
+ )
+ return self._infos[key]
+
+
+def _plan_total(plan: dict[str, "_PlannedFetch"]) -> Optional[int]:
+ """The bytes a plan sums to (what ``expected_bytes`` reports), None for an empty one."""
+ # Counted once per blob in a repo, exactly as load_progress counts them: two names with identical bytes share one
+ # cache blob, so summing both would leave the bar short of 100% forever.
+ seen: set[tuple[str, str]] = set()
+ total = 0
+ for entry in plan.values():
+ for name, key, size in entry.files:
+ ident = ((entry.repo or "").strip().lower(), key or name)
+ if ident not in seen:
+ seen.add(ident)
+ total += int(size or 0)
+ return total or None
+
+
+def _cached_snapshot_plan(repo: str, names: list) -> Optional[tuple[str, tuple]]:
+ """``(commit, ((name, blob key, size), ...))`` of the one cached revision of ``repo`` that holds every name, in the
+ live root or the import-time root (the roots the fetches resolve through), else None. The blob key is the cache
+ blob the snapshot entry points at (None where the cache keeps plain copies, e.g. no symlinks)."""
+ try:
+ from huggingface_hub import constants
+
+ from .diffusion_families import _cached_revisions
+
+ roots = [Path(hub_cache_dir())]
+ if Path(constants.HF_HUB_CACHE) != roots[0]:
+ roots.append(Path(constants.HF_HUB_CACHE))
+ for root in roots:
+ for rev in _cached_revisions(root, repo):
+ if not all((rev / name).is_file() for name in names):
+ continue
+ files = []
+ for name in names:
+ entry = rev / name
+ blob = Path(os.path.realpath(entry))
+ key = blob.name if blob.parent.name == "blobs" else None
+ files.append((name, key, int(blob.stat().st_size)))
+ return rev.name, tuple(files)
+ except Exception: # noqa: BLE001 -- unreadable cache: fall back to the listing's metadata
+ return None
+ return None
+
+
+def _plan_fetch(
+ logical: str,
+ listing: str,
+ info: Any,
+ names: Any,
+ hf_token: Optional[str],
+ *,
+ checkpoint: bool = False,
+) -> "_PlannedFetch":
+ """The plan for one role: its fetch repo settled on the exact names, pinned to the listing commit when the fetch
+ reads the listing repo, and each file's blob key + size from the same listing."""
+ wanted = list(dict.fromkeys(names))
+ repo = _video_fetch_repo(logical, hf_token, files = wanted, checkpoint = checkpoint) or logical
+ if repo.lower() != (listing or "").lower():
+ # An upstream kept for its complete cache: the plan describes THAT snapshot (its commit, its blobs), not the
+ # mirror listing, which may already be a newer revision of a file.
+ cached = _cached_snapshot_plan(repo, wanted)
+ if cached is not None:
+ return _PlannedFetch(repo, cached[0], cached[1])
+ meta = {s.rfilename: s for s in (getattr(info, "siblings", None) or [])}
+ files = tuple(
+ (
+ name,
+ _sibling_etag(meta[name]) if name in meta else None,
+ int(getattr(meta.get(name), "size", 0) or 0),
+ )
+ for name in wanted
+ )
+ revision = getattr(info, "sha", None) if repo.lower() == (listing or "").lower() else None
+ return _PlannedFetch(repo, revision, files)
+
+
+_FETCH_CHECKPOINT = "checkpoint"
+_FETCH_BASE = "base"
def _physical_card_name(ordinal: Optional[int]) -> "tuple[Optional[str], Optional[int]]":
@@ -1630,6 +1789,321 @@ def _h3_te_canonical(repo_id: Optional[str]) -> str:
return canonical_base(repo_id).strip().lower()
+def _video_fetch_repo(
+ repo_id: Optional[str],
+ hf_token: Optional[str] = None,
+ *,
+ files: Optional[Sequence[str]] = None,
+ checkpoint: bool = False,
+) -> Optional[str]:
+ """The repo a video download should hit for ``repo_id``: its byte-identical unsloth mirror when one exists
+ (``diffusion_families._VIDEO_MIRROR_PAIRS``), else ``repo_id`` unchanged.
+
+ FETCH sites only, exactly like the image side's ``prefer_ungated_mirror`` calls: the upstream id stays the
+ logical identity (picker, status(), prequant / te-prequant base checks, size tables), and every table keyed on
+ it normalises a mirror back through ``canonical_base``. Same opt-outs too: a local path, an upstream already
+ satisfying the load from cache (``files`` sharpens that to the names about to be fetched), and
+ ``UNSLOTH_DIFFUSION_NO_MIRROR``. Pure: table lookup, env read, local stat."""
+ if not repo_id:
+ return repo_id
+ # ``checkpoint``: the user-selected file itself. The opt-out folds a mirror back onto its upstream only for BASE
+ # components; an unsloth carrier repo's own root FP8 / GGUF checkpoints do not exist upstream, so a pick stays in
+ # the repo it was selected from.
+ no_mirror = bool(os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip())
+ if checkpoint and no_mirror:
+ return repo_id
+ from .diffusion_families import (
+ _is_local_path,
+ _upstream_is_cached,
+ mirror_repo,
+ prefer_ungated_mirror,
+ )
+
+ mirror = None if no_mirror or _is_local_path(repo_id) else mirror_repo(repo_id)
+ if mirror:
+ if files:
+ # Every video fetch passes ``reuse_other_cache_root``, so an upstream complete under EITHER root is reused
+ # rather than re-staged under the mirror (a cache-folder change leaves it in the import-time root).
+ if _upstream_whole_in_one_root(repo_id, tuple(files)):
+ return repo_id
+ else:
+ # No names to check (assembly, an offline load, progress): the any-weight default would keep a partial
+ # upstream over a complete mirror. Pick the side whose cached snapshot is more complete; upstream on a tie.
+ # A GATED upstream wins only when its snapshot is whole: anything missing would be fetched from the vendor
+ # repo, a 401 for a user without its licence, while the mirror serves the same bytes to everyone. A load
+ # that cannot download keeps the cached upstream unless the mirror is cached too (it may read only the
+ # upstream's cached part, e.g. a GGUF pick that skips the transformer).
+ (up, up_whole), mir = (
+ _video_cached_completeness_detail(repo_id),
+ _video_cached_completeness(mirror),
+ )
+ if up >= 0 or mir >= 0:
+ if (
+ not up_whole
+ and _is_gated_video_upstream(repo_id)
+ and (mir >= 0 or _can_download())
+ ):
+ return mirror
+ return repo_id if up >= mir else mirror
+ return prefer_ungated_mirror(repo_id, hf_token, files = files)
+
+
+def _is_gated_video_upstream(repo_id: str) -> bool:
+ from .diffusion_families import _GATED_UPSTREAMS
+ return (repo_id or "").strip().lower() in _GATED_UPSTREAMS
+
+
+def _can_download() -> bool:
+ from .diffusion_prequant import _LOCAL_FILES_ONLY, hub_offline
+ return not hub_offline() and not _LOCAL_FILES_ONLY.get()
+
+
+def _video_index_repo(base: str, *, local_files_only: bool = False) -> str:
+ """The repo to read ``base``'s index from: the one its base pull will stage. The plan keeps a cached upstream only
+ when it already holds the files the pull needs, so the upstream answers only when its snapshot holds every
+ component (its ``text_encoder`` aside: an H3 load may skip those shards); else the mirror, unless the load cannot
+ download and only the upstream is cached."""
+ from .diffusion_families import _is_local_path, mirror_repo
+
+ if os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip() or _is_local_path(base):
+ return base
+ mirror = mirror_repo(base)
+ if not mirror:
+ return base
+ up, up_whole = _video_cached_completeness_detail(base, skip = ("text_encoder",))
+ if up_whole:
+ return base
+ if (
+ up >= 0
+ and (local_files_only or not _can_download())
+ and _video_cached_completeness(mirror) < 0
+ ):
+ return base
+ return mirror
+
+
+def _video_offline_base_choice(
+ base: str,
+ folders: Optional[Sequence[str]] = None,
+ skip: Sequence[str] = (),
+) -> Optional[str]:
+ """Offline (no plan to read the choice from): the side of ``base``'s mirror pair whose cached snapshot holds more of
+ the ``folders`` this load reads (every index component but ``skip`` when None), upstream on a tie; None when
+ neither is cached or there is no mirror."""
+ from .diffusion_families import _is_local_path, mirror_repo
+
+ if os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip() or _is_local_path(base):
+ return None
+ mirror = mirror_repo(base)
+ if not mirror:
+ return None
+ up = _video_cached_completeness(base, folders, skip)
+ mir = _video_cached_completeness(mirror, folders, skip)
+ if up < 0 and mir < 0:
+ return None
+ return base if up >= mir else mirror
+
+
+def _upstream_whole_in_one_root(repo_id: str, files: tuple) -> bool:
+ """Whether ONE cache root (the live one, or the import-time root the fetches fall back to) holds every name in one
+ revision: the only upstream cache assembly can open as a single snapshot. Names split across the two roots are not
+ a hit, so the load takes the mirror instead of a set that assembly sees half of (a 401 on a gated upstream)."""
+ from .diffusion_families import _root_holds_upstream
+
+ roots = [Path(hub_cache_dir())]
+ try:
+ from huggingface_hub import constants
+ if Path(constants.HF_HUB_CACHE) != roots[0]:
+ roots.append(Path(constants.HF_HUB_CACHE))
+ except Exception: # noqa: BLE001 -- the live root alone
+ pass
+ return any(_root_holds_upstream(root, repo_id, files) for root in roots)
+
+
+def _h3_mirrored_component_sources(
+ pipe: Any,
+ base: Optional[str],
+ fetch_repo: Optional[str],
+ *,
+ local_files_only: bool,
+ cache_dir: Optional[str] = None,
+ staged_dir: Optional[str] = None,
+) -> dict[str, str]:
+ """``{component: source}`` sending every modular spec that names ``base`` (either side of its mirror pair) to
+ ``fetch_repo``, the repo the base was staged from, as ``load_components(pretrained_model_name_or_path = ...)``.
+ ``staged_dir``, a snapshot the plan reused from another cache root, takes those specs instead: load_components
+ searches only the live root and would fetch the ~145 GB of components again.
+ Offline, tokenizer / processor specs resolve to that repo's cached snapshot folder (as
+ ``offline_component_sources`` does). Empty when nothing is redirected: a local base, no mirror in play, or a
+ spec naming a different repo (a derivative's own encoder keeps its source)."""
+ from .diffusion_families import _is_local_path
+
+ if not base or not fetch_repo or _is_local_path(fetch_repo):
+ return {}
+ specs = getattr(pipe, "_component_specs", None)
+ if not isinstance(specs, dict):
+ return {}
+ from .diffusion_offline_source import _is_tokenizer_or_processor, offline_snapshot_source
+
+ want = _h3_te_canonical(base)
+ out: dict[str, str] = {}
+ for name, spec in specs.items():
+ source = getattr(spec, "pretrained_model_name_or_path", None)
+ if not isinstance(source, str) or not source or (source == fetch_repo and not staged_dir):
+ continue
+ if _h3_te_canonical(source) != want:
+ continue
+ if staged_dir:
+ out[name] = staged_dir
+ continue
+ target = fetch_repo
+ if _is_tokenizer_or_processor(getattr(spec, "type_hint", None)):
+ target = offline_snapshot_source(
+ fetch_repo,
+ getattr(spec, "subfolder", None),
+ local_files_only = local_files_only,
+ cache_dir = cache_dir,
+ )
+ out[name] = target
+ return out
+
+
+def _is_under_dir(path: str, root: Optional[str]) -> bool:
+ try:
+ return bool(root) and Path(path).resolve().is_relative_to(Path(str(root)).resolve())
+ except (OSError, ValueError):
+ return False
+
+
+def _video_cached_completeness(
+ repo_id: str,
+ folders: Optional[Sequence[str]] = None,
+ skip: Sequence[str] = (),
+) -> int:
+ """How complete ``repo_id``'s cached diffusers snapshot is in the live root (the one ``from_pretrained`` reads):
+ the number of ``model_index.json`` (or H3's ``modular_model_index.json``) components whose folder holds a file and
+ whose shard sets are fully present, best revision. -1 without a cached index. Local stat only, never raises."""
+ return _video_cached_completeness_detail(repo_id, folders, skip)[0]
+
+
+_SHARD_NAME = re.compile(r"^(?P<stem>.+)-(?P<part>\d+)-of-(?P<total>\d+)(?P<ext>\.[^.]+)$")
+
+
+def _shards_complete(folder: Path, names: Sequence[str]) -> bool:
+ """Whether every ``<stem>-NNNNN-of-MMMMM<ext>`` set among ``names`` has all M parts in ``folder``: an interrupted
+ pull can leave one shard and no index, which the index check alone cannot see."""
+ for name in names:
+ m = _SHARD_NAME.match(name)
+ if not m:
+ continue
+ width, total = len(m["part"]), int(m["total"])
+ for part in range(1, total + 1):
+ if not (folder / f"{m['stem']}-{part:0{width}d}-of-{m['total']}{m['ext']}").is_file():
+ return False
+ return True
+
+
+def _video_cached_completeness_detail(
+ repo_id: str,
+ folders: Optional[Sequence[str]] = None,
+ skip: Sequence[str] = (),
+) -> tuple[int, bool]:
+ """``(best score, whether some cached revision holds EVERY component it lists)``; ``(-1, False)`` when nothing is
+ cached. The score is ``_video_cached_completeness``."""
+ try:
+ import json
+
+ from .diffusion_families import _WEIGHT_SUFFIXES, _cached_revisions
+
+ best, whole = -1, False
+ for rev in _cached_revisions(Path(hub_cache_dir()), repo_id):
+ index = next(
+ (
+ rev / n
+ for n in ("model_index.json", "modular_model_index.json")
+ if (rev / n).is_file()
+ ),
+ None,
+ )
+ if index is None:
+ continue
+ components = []
+ for key, value in json.loads(index.read_text(encoding = "utf-8")).items():
+ if key.startswith("_") or not isinstance(value, (list, tuple)) or not value:
+ continue
+ if value[0] in (None, "null"):
+ continue
+ spec = value[2] if len(value) == 3 and isinstance(value[2], dict) else {}
+ components.append(spec.get("subfolder") or key)
+ if folders is not None:
+ # Only what this load reads from the base (LTX-2.3: its scheduler, tokenizer and encoder).
+ components = [c for c in components if c in folders]
+ # A single-file / GGUF pick brings its own denoiser: the base's transformer folders are not read.
+ components = [c for c in components if not any(c.startswith(p) for p in skip)]
+ score = 0
+ for key in components:
+ folder = rev / key
+ if not folder.is_dir() or not any(p.is_file() for p in folder.iterdir()):
+ continue
+ complete = True
+ # A model component (it has a config.json) needs real weights, not just the configs an interrupted
+ # pull leaves; scheduler / tokenizer folders carry no weights and count on any file.
+ weights = [
+ p.name
+ for p in folder.iterdir()
+ if p.is_file() and p.suffix.lower() in _WEIGHT_SUFFIXES
+ ]
+ if (folder / "config.json").is_file() and not weights:
+ complete = False
+ elif not _shards_complete(folder, weights):
+ complete = False
+ for shard_index in folder.glob("*.index.json"):
+ weight_map = (
+ json.loads(shard_index.read_text(encoding = "utf-8")).get("weight_map") or {}
+ )
+ if not all((folder / name).is_file() for name in set(weight_map.values())):
+ complete = False
+ break
+ score += complete
+ best = max(best, score)
+ whole = whole or score == len(components)
+ return best, whole
+ except Exception: # noqa: BLE001 -- an unreadable cache scores as absent
+ return -1, False
+
+
+def _video_listing_repo(repo_id: str) -> str:
+ """The repo to read ``repo_id``'s file LISTING / sizes from: its mirror whenever one exists, cached upstream or
+ not, since the two listings are identical and only the mirror keeps the metadata call inside unsloth/*. Honours
+ ``UNSLOTH_DIFFUSION_NO_MIRROR`` and never rewrites a local path."""
+ from .diffusion_families import _is_local_path, mirror_repo
+
+ if (
+ not repo_id
+ or os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip()
+ or _is_local_path(repo_id)
+ ):
+ return repo_id
+ return mirror_repo(repo_id) or repo_id
+
+
+def _video_repo_aliases(repo_id: Optional[str]) -> tuple[str, ...]:
+ """``repo_id`` plus the other side of its mirror pair, for the guards that must protect whichever id a load is
+ actually reading from (the delete-cached guard, the progress cache scan)."""
+ if not repo_id:
+ return ()
+ from .diffusion_families import canonical_base, mirror_repo
+
+ upstream = canonical_base(repo_id)
+ return tuple(dict.fromkeys(r for r in (repo_id, upstream, mirror_repo(upstream)) if r))
+
+
+def _video_fetch_key(repo_id: Optional[str]) -> str:
+ """A mirror pair's key: the upstream id, lowercased (load_progress dedupes its no-plan fallback on it)."""
+ from .diffusion_families import canonical_base
+ return canonical_base(repo_id).strip().lower()
+
+
# MiniMax-H3 modular precision tri-state. unset/"auto" -> whatever the backend decided;
@@ -3491,16 +3965,13 @@ class VideoBackend:
from .video_minimax_h3 import (
H3_COMPONENT_REPO,
H3_GGUF_REPO,
- H3_LEGACY_COMPONENT_REPO,
is_h3_native,
)
h3_native = is_h3_native(fam, resolve_video_model_kind(gguf_filename, model_kind))
# Both ids: an install may hold the components under either the mirror or the repack it was mirrored from, and
# whichever one this load reads must be protected.
- claimed_assets = (
- (H3_GGUF_REPO, H3_COMPONENT_REPO, H3_LEGACY_COMPONENT_REPO) if h3_native else ()
- )
+ claimed_assets = (H3_GGUF_REPO, H3_COMPONENT_REPO) if h3_native else ()
# Claim the hosted LTX-2.3 FP8 DiT repo with _loading.
if _ltx23_prequant_serves_on_card(
fam,
@@ -3728,22 +4199,19 @@ class VideoBackend:
h3_te_scheme = h3_te_scheme,
local_files_only = local_files_only,
ltx25_dev = ltx25_dev,
+ planned_files = (planned_files := {}),
)
with self._lock:
if self._load_token == token and self._loading is not None:
self._loading.base_repo = base
+ if hasattr(self._loading, "fetch_plan"):
+ self._loading.fetch_plan = planned_files
# The conditioner artifact comes from a THIRD repo, neither repo_id nor base_repo, so without this
# the delete-cached guard would let it be deleted out from under the in-flight fetch (or out from
# under the assembly, while the base snapshot that no longer carries a dense encoder is still coming
- # down). Same registration the native H3 path makes for its companions. Both ids, for the same
- # reason the native path claims both: an install whose cache predates the move reads the artifact
- # from the repack, and a claim over only the mirror would leave the entry this load is reading
- # deletable mid-fetch.
+ # down). Same registration the native H3 path makes for its companions.
if h3_te_scheme:
- self._loading.asset_repos = self._loading.asset_repos + (
- H3_TE_QUANT_REPO,
- H3_LEGACY_TE_QUANT_REPO,
- )
+ self._loading.asset_repos = self._loading.asset_repos + (H3_TE_QUANT_REPO,)
# The same for a hosted pre-cast encoder (unsloth/Wan2.2-TI2V-5B-FP8 for every Wan base).
te_repos = tuple(
src.location
@@ -3772,11 +4240,33 @@ class VideoBackend:
if kwargs.get("gguf_filename") and not Path(kwargs["repo_id"]).expanduser().exists():
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
+ partner = moe_partner_filename(kwargs["gguf_filename"])
+ fetch_partner = bool(
+ getattr(fam, "is_moe", False) and kind != "pipeline" and partner
+ )
+ # One choice for the pick and its partner expert, settled on both names, so they come from one repo and
+ # progress reads that repo for both.
+ # The estimate's plan when it made one (the repo + revision progress reads); else settled here.
+ checkpoint_plan = planned_files.get(_FETCH_CHECKPOINT)
+ checkpoint_repo = (
+ checkpoint_plan.repo
+ if checkpoint_plan is not None
+ else _video_fetch_repo(
+ kwargs["repo_id"],
+ kwargs.get("hf_token"),
+ files = (kwargs["gguf_filename"],) + ((partner,) if fetch_partner else ()),
+ checkpoint = True,
+ )
+ )
+ checkpoint_revision = (
+ checkpoint_plan.revision if checkpoint_plan is not None else None
+ )
checkpoint_local = Path(
hf_hub_download_with_xet_fallback(
- kwargs["repo_id"],
+ checkpoint_repo,
kwargs["gguf_filename"],
kwargs.get("hf_token"),
+ revision = checkpoint_revision,
cancel_event = cancel_event,
# The plan counts a file cached under EITHER root, so the load has to resolve through both or it
# re-pulls what the planner skipped.
@@ -3787,12 +4277,12 @@ class VideoBackend:
gguf_header_delta = True,
)
)
- partner = moe_partner_filename(kwargs["gguf_filename"])
- if getattr(fam, "is_moe", False) and kind != "pipeline" and partner:
+ if fetch_partner:
hf_hub_download_with_xet_fallback(
- kwargs["repo_id"],
+ checkpoint_repo,
partner,
kwargs.get("hf_token"),
+ revision = checkpoint_revision,
cancel_event = cancel_event,
reuse_other_cache_root = True,
local_files_only = local_files_only,
@@ -3836,10 +4326,17 @@ class VideoBackend:
h3_te_scheme = h3_te_scheme,
local_files_only = local_files_only,
ltx25_dev = ltx25_dev,
+ planned_files = (replanned := {}),
+ pin_revisions = _fetched_pins(planned_files),
)
+ planned_files = _keep_fetched_checkpoint(replanned, planned_files)
+ # The total follows the plan actually kept: the retained checkpoint entry, not a re-listed one.
+ expected = _plan_total(planned_files) if expected else expected
with self._lock:
if self._load_token == token and self._loading is not None:
self._loading.expected_bytes = expected
+ if hasattr(self._loading, "fetch_plan"):
+ self._loading.fetch_plan = planned_files
# Only a pre-cast checkpoint actually on disk earns the dense skip below.
te_skipped = self._fetch_te_prequant(
te_sources,
@@ -3901,10 +4398,50 @@ class VideoBackend:
local_files_only = local_files_only,
scheme = h3_auto_denoiser or video_auto_denoiser or requested_denoiser,
)
+ base_plan = planned_files.get(_FETCH_BASE)
+ actual_te_skip = tuple(te_skipped) + tuple(h3_te_skipped)
+ if base_plan is not None and set(base_plan.skip_te) != set(actual_te_skip):
+ # An encoder fetch fell back (or found more than planned): the base file set changed, so its repo /
+ # revision choice is settled again on the new names, and progress follows.
+ expected = self._estimate_download_bytes(
+ kwargs["repo_id"],
+ kwargs.get("gguf_filename"),
+ base,
+ kwargs.get("hf_token"),
+ kind,
+ ltx23 = ltx23,
+ te_sources = te_sources,
+ skip_transformer_weights = skip_transformer_weights,
+ skip_transformer_components = skip_transformer_components,
+ h3_task = kwargs.get("h3_task"),
+ h3_te_scheme = h3_te_scheme,
+ local_files_only = local_files_only,
+ ltx25_dev = ltx25_dev,
+ planned_files = (replanned := {}),
+ skip_te_override = actual_te_skip,
+ pin_revisions = _fetched_pins(planned_files),
+ )
+ planned_files = _keep_fetched_checkpoint(replanned, planned_files)
+ # The total follows the plan actually kept: the retained checkpoint entry, not a re-listed newer one.
+ expected = _plan_total(planned_files) if expected else expected
+ with self._lock:
+ if self._load_token == token and self._loading is not None:
+ self._loading.expected_bytes = expected
+ if hasattr(self._loading, "fetch_plan"):
+ self._loading.fetch_plan = planned_files
+ base_plan = planned_files.get(_FETCH_BASE)
+ checkpoint_plan = planned_files.get(_FETCH_CHECKPOINT)
+ if checkpoint_plan is not None:
+ # Assembly opens the very file the prefetch pinned, never a re-resolved newer one.
+ kwargs["_checkpoint_fetch"] = (checkpoint_plan.repo, checkpoint_plan.revision)
+ base_fetch_choice: dict[str, str] = {}
base_local = self._predownload_base(
base,
kwargs.get("hf_token"),
kind,
+ fetch_choice = base_fetch_choice,
+ fetch_repo = base_plan.repo if base_plan is not None else None,
+ revision = base_plan.revision if base_plan is not None else None,
ltx23 = ltx23,
skip_te_components = te_skipped + h3_te_skipped,
skip_transformer_weights = skip_transformer_weights,
@@ -3919,10 +4456,39 @@ class VideoBackend:
# The 2.3 assembly pulls per component from the hub id (its snapshot lacks the base VAEs), so it only gets
# the warmed cache.
kwargs["_base_local_dir"] = None if ltx23 else base_local
+ # The repo the exact-name check staged the base into: re-deciding at assembly without the names would flip a
+ # partially cached upstream back in (LTX-2.3 resolves every component through it).
+ # The predownload's choice; when it left early (no scoped pull), the plan it was handed still stands.
+ kwargs["_base_fetch_repo"] = base_fetch_choice.get("repo") or (
+ base_plan.repo if base_plan is not None else None
+ )
+ if kwargs["_base_fetch_repo"] is None and kind != "pipeline":
+ # No plan (a cache-only load): assembly's nameless choice counts every index component, and an upstream
+ # holding the transformer folders this pick replaces (or 2.3's unused VAEs) would outscore a mirror
+ # holding what the load reads.
+ kwargs["_base_fetch_repo"] = _video_offline_base_choice(
+ base,
+ tuple(p.rstrip("/") for p in VideoBackend._LTX23_BASE_PREFIXES)
+ if ltx23
+ else None,
+ skip = ("transformer",),
+ )
+ kwargs["_base_fetch_revision"] = (
+ base_fetch_choice.get("revision")
+ if base_fetch_choice
+ else (base_plan.revision if base_plan is not None else None)
+ )
from .safetensors_pread import pread_safetensors
+ from .diffusion_families import pinned_repo_revision
+
+ # Every hub-id config read of the base during assembly (encoder / VAE / transformer configs, the LTX-2.5
+ # companions and encoder worker) reads the commit the plan pinned; a no-op for an unpinned load.
with pread_safetensors():
- self.load_pipeline(**kwargs)
+ with pinned_repo_revision(
+ kwargs.get("_base_fetch_repo"), kwargs.get("_base_fetch_revision")
+ ):
+ self.load_pipeline(**kwargs)
with self._lock:
if self._load_token == token:
self._loading = None
@@ -4021,7 +4587,6 @@ class VideoBackend:
from .video_minimax_h3 import (
H3_COMPONENT_REPO,
H3_GGUF_REPO,
- H3_LEGACY_COMPONENT_REPO,
h3_component_metadata_repo,
h3_download_error,
h3_text_encoder_filename,
@@ -4046,7 +4611,6 @@ class VideoBackend:
self._loading.asset_repos = (
H3_GGUF_REPO,
H3_COMPONENT_REPO,
- H3_LEGACY_COMPONENT_REPO,
)
if cancel_event.is_set():
@@ -4803,7 +5367,9 @@ class VideoBackend:
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
path = Path(
hf_hub_download_with_xet_fallback(
- base,
+ # The repo the base pull reads: a fresh install fetches the index from the mirror, never the
+ # vendor id, and an upstream cache holding only an older index does not win it.
+ _video_index_repo(base, local_files_only = local_files_only),
"modular_model_index.json",
hf_token,
cache_dir = hub_cache_dir(),
@@ -5686,8 +6252,14 @@ class VideoBackend:
and name.endswith(".safetensors.index.json")
and not name.startswith(_PACK_SKIP_PREFIXES)
):
+ # The listing's commit: the shard choice must describe the revision the plan pins.
+ sha = getattr(info, "sha", None)
local = hf_hub_download_with_xet_fallback(
- base, name, hf_token, reuse_other_cache_root = True
+ base,
+ name,
+ hf_token,
+ **({"revision": sha} if sha else {}),
+ reuse_other_cache_root = True,
)
indexes[name] = json.loads(Path(local).read_text(encoding = "utf-8"))
except Exception as exc: # noqa: BLE001 -- the plan falls back to ltx25_pack_files' listing-only choice
@@ -5710,6 +6282,9 @@ class VideoBackend:
h3_te_scheme: Optional[str] = None,
local_files_only: bool = False,
ltx25_dev: bool = False,
+ planned_files: Optional[dict[str, "_PlannedFetch"]] = None,
+ skip_te_override: Optional[tuple[str, ...]] = None,
+ pin_revisions: Optional[dict[str, str]] = None,
) -> Optional[int]:
"""Total bytes this load will pull (checkpoint + companions), or None.
@@ -5734,32 +6309,49 @@ class VideoBackend:
total = 0
api = HfApi(token = hf_token or None)
- skip_te_components = tuple(self._te_prequant_hub_files(te_sources or {}, api))
- if self._h3_te_quant_hub_files(h3_te_scheme, api)[1]:
- skip_te_components = skip_te_components + ("text_encoder",)
+ if skip_te_override is not None:
+ # The encoder fetches already ran: plan around what they actually staged.
+ skip_te_components = tuple(skip_te_override)
+ else:
+ skip_te_components = tuple(self._te_prequant_hub_files(te_sources or {}, api))
+ if self._h3_te_quant_hub_files(h3_te_scheme, api)[1]:
+ skip_te_components = skip_te_components + ("text_encoder",)
+ planned: dict[str, _PlannedFetch] = {}
+ listings = _OneCommitListings(api, pin_revisions)
if gguf_filename and not Path(repo_id).expanduser().exists():
- info = api.model_info(repo_id, files_metadata = True)
+ listing = _video_listing_repo(repo_id)
+ info = listings.info(listing)
wanted = _checkpoint_files(gguf_filename, kind)
+ names = set()
for sibling in info.siblings or []:
if sibling.rfilename in wanted and sibling.size:
total += int(sibling.size)
+ names.add(sibling.rfilename)
+ planned[_FETCH_CHECKPOINT] = _plan_fetch(
+ repo_id, listing, info, names, hf_token, checkpoint = True
+ )
if base and not Path(base).expanduser().exists():
- info = api.model_info(base, files_metadata = True)
- total += sum(
- size
- for _, size in self._base_download_files(
- info,
- kind,
- ltx23 = ltx23,
- skip_te_components = skip_te_components,
- skip_transformer_weights = skip_transformer_weights,
- skip_transformer_components = skip_transformer_components,
- h3_task = h3_task,
- ltx25_dev = ltx25_dev,
- ltx25_shards = self._ltx25_plan_shards(info, base, hf_token),
- )
+ listing = _video_listing_repo(base)
+ info = listings.info(listing)
+ base_files = self._base_download_files(
+ info,
+ kind,
+ ltx23 = ltx23,
+ skip_te_components = skip_te_components,
+ skip_transformer_weights = skip_transformer_weights,
+ skip_transformer_components = skip_transformer_components,
+ h3_task = h3_task,
+ ltx25_dev = ltx25_dev,
+ ltx25_shards = self._ltx25_plan_shards(info, _video_listing_repo(base), hf_token),
)
- return total or None
+ total += sum(size for _, size in base_files)
+ planned[_FETCH_BASE] = _plan_fetch(
+ base, listing, info, [name for name, _ in base_files], hf_token
+ )._replace(skip_te = tuple(skip_te_components))
+ if planned_files is not None:
+ planned_files.update(planned)
+ # The plan's own total (one count per blob, as progress reads it); the raw sum only without a plan.
+ return _plan_total(planned) if planned else (total or None)
except Exception: # noqa: BLE001 -- progress totals are best-effort only
return None
@@ -5919,8 +6511,10 @@ class VideoBackend:
try:
api = HfApi(token = hf_token or None)
+ listings = _OneCommitListings(api)
if gguf_filename and not Path(repo_id).expanduser().exists():
- info = api.model_info(repo_id, files_metadata = True)
+ listing = _video_listing_repo(repo_id)
+ info = listings.info(listing)
wanted_checkpoints = (
_checkpoint_files(gguf_filename, kind) if fam.is_moe else (gguf_filename,)
)
@@ -5930,11 +6524,19 @@ class VideoBackend:
if s.rfilename in wanted_checkpoints
]
checkpoint_bytes = sum(size for _name, size in sizes)
+ # Staged under the repo the load will FETCH from (the download manager pulls the entry's repo); the
+ # mirror's commit only describes the mirror, so an upstream kept for its complete cache gets no pin.
+ fetch_repo = (
+ _video_fetch_repo(
+ repo_id, hf_token, files = [n for n, _ in sizes], checkpoint = True
+ )
+ or repo_id
+ )
total += add(
- repo_id,
+ fetch_repo,
sizes,
gguf = gguf_filename,
- revision = getattr(info, "sha", None),
+ revision = getattr(info, "sha", None) if fetch_repo == listing else None,
checkpoint = True,
)
if ltx23:
@@ -6012,35 +6614,50 @@ class VideoBackend:
if h3_te_repo:
total += add(h3_te_repo, h3_te_files)
if base and not Path(base).expanduser().exists():
- info = api.model_info(base, files_metadata = True)
- total += add(
- base,
- self._base_download_files(
- info,
- kind,
- ltx23 = ltx23,
- skip_te_components = (
- tuple(te_files) + (("text_encoder",) if h3_te_repo else ())
- ),
- # Gated on the artifact RESOLVING, exactly like the two encoder skips above, not on the registry
- # alone: the registry says a checkpoint should exist, dq_repo says one does. When the
- # task-specific file is absent or its repo cannot be read, dropping the dense shards leaves a
- # plan with NEITHER denoiser, and the bf16 fallback the loader documents has nothing to fall
- # back to offline. The registry probe still runs, because it is the one that refuses a
- # non-modular family and an auto request.
- skip_transformer_weights = (
- dq_repo is not None
- and self._denoiser_prequant_covered(
- fam, transformer_quant, base, h3_task, kind = kind, hf_token = hf_token
- )
- ),
- skip_transformer_components = _planned_denoiser_components(fam, kind),
- h3_task = h3_task,
- ltx25_dev = ltx25_dev,
- # The pack's indexes pick the transformer / connectors copy, as _predownload_base does.
- ltx25_shards = self._ltx25_plan_shards(info, base, hf_token),
+ listing = _video_listing_repo(base)
+ info = listings.info(listing)
+ base_files = self._base_download_files(
+ info,
+ kind,
+ ltx23 = ltx23,
+ skip_te_components = (
+ tuple(te_files) + (("text_encoder",) if h3_te_repo else ())
+ ),
+ # Gated on the artifact RESOLVING, exactly like the two encoder skips above, not on the registry
+ # alone: the registry says a checkpoint should exist, dq_repo says one does. When the
+ # task-specific file is absent or its repo cannot be read, dropping the dense shards leaves a
+ # plan with NEITHER denoiser, and the bf16 fallback the loader documents has nothing to fall
+ # back to offline. The registry probe still runs, because it is the one that refuses a
+ # non-modular family and an auto request.
+ skip_transformer_weights = (
+ dq_repo is not None
+ and self._denoiser_prequant_covered(
+ fam, transformer_quant, base, h3_task, kind = kind, hf_token = hf_token
+ )
),
- revision = getattr(info, "sha", None),
+ skip_transformer_components = _planned_denoiser_components(fam, kind),
+ h3_task = h3_task,
+ ltx25_dev = ltx25_dev,
+ # The pack's indexes pick the transformer / connectors copy, as _predownload_base does.
+ ltx25_shards = self._ltx25_plan_shards(info, listing, hf_token),
+ )
+ # The same fetch-repo decision _predownload_base makes from the same names, so the staged entry is the
+ # repo the load then reads (its mirror, unless the upstream cache already holds every file).
+ fetch_base = (
+ _video_fetch_repo(base, hf_token, files = [n for n, _ in base_files]) or base
+ )
+ base_revision = getattr(info, "sha", None) if fetch_base == listing else None
+ if fetch_base.lower() != (listing or "").lower():
+ # An upstream kept for its complete cache: probe THAT snapshot (its commit, its sizes), as
+ # _plan_fetch does for the load, not the mirror head, whose sizes may be a newer revision.
+ cached = _cached_snapshot_plan(fetch_base, [n for n, _ in base_files])
+ if cached is not None:
+ base_revision = cached[0]
+ base_files = [(name, size) for name, _key, size in cached[1]]
+ total += add(
+ fetch_base,
+ base_files,
+ revision = base_revision,
# A pipeline pick has no single file: the base IS the selected model (base = repo_id above). Under a
# GGUF pick the base is a companion, so it stays unflagged.
checkpoint = kind == "pipeline",
@@ -6343,6 +6960,36 @@ class VideoBackend:
fetched.append(component)
return tuple(fetched)
+ def _top_up_dense_base(
+ self,
+ base: str,
+ hf_token: Optional[str],
+ kind: str,
+ *,
+ base_local_dir: Optional[str],
+ fetch_repo: Optional[str],
+ revision: Optional[str],
+ local_files_only: bool,
+ ltx25_dev: bool = False,
+ ) -> Optional[str]:
+ """Restore the dense weights a failed injection left out: the same scoped pull with nothing skipped, from the
+ plan's repo at the plan's commit, so the topped-up snapshot is the one the rest of the base was staged into.
+ An offline load never had a scoped snapshot to top up (the prefetch returns None), so this is a no-op there --
+ but the flag is carried so the top-up can never become the one call that reaches the Hub."""
+ return (
+ self._predownload_base(
+ base,
+ hf_token,
+ kind,
+ ltx23 = False,
+ local_files_only = local_files_only,
+ ltx25_dev = ltx25_dev,
+ fetch_repo = fetch_repo,
+ revision = revision,
+ )
+ or base_local_dir
+ )
+
def _predownload_base(
self,
base: str,
@@ -6357,9 +7004,19 @@ class VideoBackend:
cancel_event: Optional[threading.Event] = None,
local_files_only: bool = False,
ltx25_dev: bool = False,
+ fetch_choice: Optional[dict[str, str]] = None,
+ fetch_repo: Optional[str] = None,
+ revision: Optional[str] = None,
) -> Optional[str]:
"""Pull exactly the base-repo files the load needs; return the local snapshot dir.
+ ``fetch_repo`` / ``revision``: the load's settled plan (``_PlannedFetch``) for the base. Given, every file comes
+ from that repo at that commit, so the bytes land exactly where load_progress reads them; absent (a top-up, a
+ direct call), the repo is settled here on the exact names, unpinned, as before.
+
+ ``fetch_choice`` (when given) receives ``{"repo": <id>}``, the side of the mirror pair the exact-name check
+ settled on, so the assembly that follows reads the same repo instead of re-deciding without the names.
+
A bare ``from_pretrained(repo_id)`` snapshot of Lightricks/LTX-2 downloads the
whole 314 GB repo (root packaged checkpoints plus a second 50 GB text-encoder
shard set) when ~93 GB is used. Downloading the scoped file list ourselves is
@@ -6383,7 +7040,20 @@ class VideoBackend:
return None
from huggingface_hub import HfApi
- info = HfApi(token = hf_token or None).model_info(base, files_metadata = True)
+ # Listed from the mirror (byte identical, so the same names and sizes), then the fetch repo is settled
+ # against the EXACT names: an upstream snapshot that already holds every one of them keeps being used.
+ listing = _video_listing_repo(base)
+ info = HfApi(token = hf_token or None).model_info(
+ listing,
+ files_metadata = True,
+ # The plan's commit describes the listing only when the plan reads the listing repo; an upstream kept for
+ # its cache is pinned to its own snapshot's commit, which the mirror does not have.
+ **(
+ {"revision": revision}
+ if revision and (fetch_repo or "").lower() == listing.lower()
+ else {}
+ ),
+ )
files = self._base_download_files(
info,
kind,
@@ -6419,7 +7089,12 @@ class VideoBackend:
if cancel.is_set():
raise RuntimeError(VIDEO_CANCELLED_MSG)
local_index = hf_hub_download_with_xet_fallback(
- base, name, hf_token, cancel_event = cancel, reuse_other_cache_root = True
+ fetch_repo or _video_fetch_repo(base, hf_token, files = (name,)) or base,
+ name,
+ hf_token,
+ revision = revision,
+ cancel_event = cancel,
+ reuse_other_cache_root = True,
)
indexes[name] = json.loads(Path(local_index).read_text(encoding = "utf-8"))
files = self._base_download_files(
@@ -6436,6 +7111,15 @@ class VideoBackend:
snapshot_root: Optional[str] = None
roots: set[str] = set()
+ base = (
+ fetch_repo
+ or _video_fetch_repo(base, hf_token, files = [name for name, _ in files])
+ or base
+ )
+ if fetch_choice is not None:
+ fetch_choice["repo"] = base
+ if revision:
+ fetch_choice["revision"] = revision
for name, _ in files:
# Explicit check: a cached file returns without consulting the event, so a warm-cache sweep would run to
# completion after a cancel.
@@ -6446,6 +7130,7 @@ class VideoBackend:
base,
name,
hf_token,
+ revision = revision,
cancel_event = cancel,
reuse_other_cache_root = True,
)
@@ -6472,7 +7157,7 @@ class VideoBackend:
return None
def _cache_bytes(self, repo_id: Optional[str]) -> int:
- """Bytes of ``repo_id`` currently in the HF blob cache (progress polling).
+ """Bytes of ``repo_id`` currently in the HF blob cache (progress polling without a plan).
Walks the repo's cache directory directly instead of ``scan_cache_dir``:
the scanner skips in-flight ``*.incomplete`` blobs, so during a multi-GB
@@ -6487,8 +7172,8 @@ class VideoBackend:
if not folder.is_dir():
return 0
total = 0
- for root, _dirs, files in os.walk(folder):
- for name in files:
+ for root, _dirs, names in os.walk(folder):
+ for name in names:
try:
path = os.path.join(root, name)
# Snapshot entries are symlinks into blobs/; skip them so a blob is not counted twice.
@@ -6500,6 +7185,58 @@ class VideoBackend:
except Exception: # noqa: BLE001 -- cache scan is best-effort
return 0
+ @staticmethod
+ def _planned_bytes(plan: dict[str, "_PlannedFetch"]) -> int:
+ """Bytes of the load's planned files present in the cache, read by blob key from the plan's repo.
+
+ A blob is named by its content key, so this counts exactly the planned file whichever revision it lands under
+ (a superseded snapshot's same-named file has another key), never a carrier's other checkpoints or an unrelated
+ partial, and the in-flight ``<key>.incomplete`` while it downloads. Both cache roots are read, as every fetch
+ passes ``reuse_other_cache_root``. A file with no key falls back to its entry in the pinned revision (else
+ ``refs/main``). Each file is capped at its listed size and counted once."""
+ import os
+
+ roots = [Path(hub_cache_dir())]
+ try:
+ from huggingface_hub import constants
+ if Path(constants.HF_HUB_CACHE) != roots[0]:
+ roots.append(Path(constants.HF_HUB_CACHE))
+ except Exception: # noqa: BLE001 -- the live root alone
+ pass
+ total = 0
+ seen: set[tuple[str, str]] = set()
+ for entry in plan.values():
+ repo = (entry.repo or "").strip()
+ if not repo:
+ continue
+ for name, etag, size in entry.files:
+ key = (repo.lower(), etag or name)
+ if key in seen:
+ continue
+ seen.add(key)
+ best = 0
+ for root in roots:
+ folder = root / ("models--" + repo.replace("/", "--"))
+ try:
+ if etag:
+ candidates = [
+ folder / "blobs" / etag,
+ folder / "blobs" / f"{etag}.incomplete",
+ ]
+ else:
+ ref = folder / "refs" / "main"
+ rev = entry.revision or (
+ ref.read_text(encoding = "utf-8").strip() if ref.is_file() else None
+ )
+ candidates = [folder / "snapshots" / rev / name] if rev else []
+ for path in candidates:
+ if path.is_file():
+ best = max(best, os.path.getsize(path))
+ except OSError:
+ continue
+ total += min(best, size) if size else best
+ return int(total)
+
def load_progress(self) -> dict[str, Any]:
"""Phase + downloaded/total bytes for the in-flight load (cache-scan based)."""
loading = self._loading
@@ -6507,9 +7244,22 @@ class VideoBackend:
return _progress("error", error = loading.error)
if loading is None:
return _progress("ready" if self._state is not None else None)
- downloaded = self._cache_bytes(loading.repo_id)
- if loading.base_repo and loading.base_repo != loading.repo_id:
- downloaded += self._cache_bytes(loading.base_repo)
+ # The load's own plan, settled once at estimate time by the worker that owns this state: the repo + revision
+ # every fetch site reads, and each file's blob key and size. Nothing else is consulted.
+ plan = dict(getattr(loading, "fetch_plan", None) or {})
+ if plan:
+ downloaded = self._planned_bytes(plan)
+ else:
+ # No plan (offline, a failed estimate, or a state built outside _run_load): the whole cache of each id's
+ # default fetch side.
+ reading: dict[str, str] = {}
+ for rid, is_checkpoint in ((loading.repo_id, True), (loading.base_repo, False)):
+ if rid:
+ reading.setdefault(
+ _video_fetch_key(rid),
+ _video_fetch_repo(rid, checkpoint = is_checkpoint) or rid,
+ )
+ downloaded = sum(self._cache_bytes(rid) for rid in dict.fromkeys(reading.values()))
expected = loading.expected_bytes
phase = "downloading"
if not expected:
@@ -6542,7 +7292,8 @@ class VideoBackend:
if loading is None or loading.error is not None:
return ()
ids = (loading.repo_id, loading.base_repo, *loading.asset_repos)
- return tuple(r for r in ids if r)
+ # Both sides of a mirror pair: the fetch reads the mirror while status() names the upstream.
+ return tuple(dict.fromkeys(alias for r in ids if r for alias in _video_repo_aliases(r)))
def loaded_repo_ids(self) -> tuple[str, ...]:
"""Repo ids the COMMITTED model reads from disk (empty unless a native model is loaded).
@@ -6559,10 +7310,9 @@ class VideoBackend:
from .video_minimax_h3 import (
H3_COMPONENT_REPO,
H3_GGUF_REPO,
- H3_LEGACY_COMPONENT_REPO,
)
- return (repo_id, H3_GGUF_REPO, H3_COMPONENT_REPO, H3_LEGACY_COMPONENT_REPO)
+ return (repo_id, H3_GGUF_REPO, H3_COMPONENT_REPO)
# ── the load itself ──────────────────────────────────────────────────────
@@ -6591,6 +7341,9 @@ class VideoBackend:
gpu_ordinal: Optional[int] = None,
_load_token: Optional[int] = None,
_base_local_dir: Optional[str] = None,
+ _base_fetch_repo: Optional[str] = None,
+ _base_fetch_revision: Optional[str] = None,
+ _checkpoint_fetch: Optional[tuple[str, Optional[str]]] = None,
_te_prequant_skipped: tuple[str, ...] = (),
_h3_auto_denoiser_planned: Optional[str] = None,
_video_auto_denoiser_planned: Optional[str] = None,
@@ -6650,6 +7403,10 @@ class VideoBackend:
pass
base = repo_id if kind == "pipeline" else resolve_video_base_repo(fam, base_repo, repo_id)
+ # Where the base's components are FETCHED from when no staged snapshot dir covers them: its unsloth mirror.
+ # ``base`` stays the upstream id every table below is keyed on.
+ # The predownload's exact-name choice when it made one, so assembly reads the repo it just staged.
+ fetch_base = _base_fetch_repo or _video_fetch_repo(base, hf_token) or base
with self._lock:
if _load_token is not None and _load_token != self._load_token:
@@ -6746,7 +7503,11 @@ class VideoBackend:
if kind == "single_file":
comfy_checkpoint = str(
self._resolve_checkpoint_path(
- repo_id, gguf_filename, hf_token, local_files_only = local_files_only
+ repo_id,
+ gguf_filename,
+ hf_token,
+ local_files_only = local_files_only,
+ fetch = _checkpoint_fetch,
)
)
if not _is_trusted_video_repo(repo_id):
@@ -6777,6 +7538,8 @@ class VideoBackend:
h3_task = h3_task,
_load_token = _load_token,
_base_local_dir = _base_local_dir,
+ _base_fetch_repo = _base_fetch_repo,
+ _base_fetch_revision = _base_fetch_revision,
# Settled before the pull when the pull acted on it; None when it did not.
_h3_auto_denoiser_planned = _h3_auto_denoiser_planned,
_nvfp4_install_outcome = _nvfp4_install_outcome,
@@ -6836,7 +7599,11 @@ class VideoBackend:
ltx_keys = None
if kind != "pipeline":
checkpoint_path = self._resolve_checkpoint_path(
- repo_id, gguf_filename, hf_token, local_files_only = local_files_only
+ repo_id,
+ gguf_filename,
+ hf_token,
+ local_files_only = local_files_only,
+ fetch = _checkpoint_fetch,
)
# Admitted per file from an untrusted repo: prove each file is a safetensors container before any probe.
untrusted_single_file = kind == "single_file" and not _is_trusted_video_repo(repo_id)
@@ -6903,7 +7670,11 @@ class VideoBackend:
if getattr(fam, "is_moe", False):
# Both experts stay loaded, so price the pair; the planner splits the total per expert.
partner_path = self._resolve_moe_partner_path(
- repo_id, gguf_filename, hf_token, local_files_only = local_files_only
+ repo_id,
+ gguf_filename,
+ hf_token,
+ local_files_only = local_files_only,
+ fetch = _checkpoint_fetch,
)
partner_mib, partner_scan = _price_checkpoint(partner_path)
if (comfy_scan is None) != (partner_scan is None):
@@ -7206,7 +7977,9 @@ class VideoBackend:
if stale_encoder is not None:
_stop_ltx25_encoder(stale_encoder[1])
ltx25_client = start_text_encoder(
- repo = _base_local_dir or (repo_id if kind == "pipeline" else base),
+ repo = _base_local_dir or fetch_base,
+ # The plan's commit when the worker reads the hub id (a staged dir already is that commit).
+ revision = None if _base_local_dir else _base_fetch_revision,
hf_token = hf_token,
cache_dir = hub_cache_dir(),
local_files_only = local_files_only,
@@ -7233,8 +8006,17 @@ class VideoBackend:
if is_ltx2_pipeline_class(fam.pipeline_class):
ensure_ltx2_pipelines_importable(logger)
pipeline_cls = getattr(diffusers, fam.pipeline_class)
+
# cache_dir pins every loader call to the live cache root, so a mid-session change cannot split one model across
# roots.
+ def _pinned_base_kwargs() -> dict[str, Any]:
+ """A hub-id base read takes the plan's commit; the staged dir already is that commit."""
+ return (
+ {"revision": _base_fetch_revision}
+ if _base_fetch_revision and not _base_local_dir
+ else {}
+ )
+
pipe_kwargs: dict[str, Any] = {
"torch_dtype": dtype,
"cache_dir": hub_cache_dir(),
@@ -7253,7 +8035,8 @@ class VideoBackend:
te_injected = te_prequant_pipe_kwargs(
fam,
- repo_id if kind == "pipeline" else base,
+ # the encoder config is read from here; the base checks fold a mirror back onto its upstream
+ fetch_base,
te_quant_mode = text_encoder_quant,
target = target,
dtype = dtype,
@@ -7293,7 +8076,7 @@ class VideoBackend:
denoiser_injected = denoiser_prequant_pipe_kwargs(
fam,
- base,
+ fetch_base,
scheme = denoiser_seed_scheme,
dtype = dtype,
device = device,
@@ -7331,19 +8114,15 @@ class VideoBackend:
"pre-download skipped",
", ".join(missing_dense),
)
- _base_local_dir = (
- self._predownload_base(
- base,
- hf_token,
- kind,
- ltx23 = False,
- # An offline load never had a scoped snapshot to top up (the prefetch returns None), so this is a
- # no-op there -- but the flag is carried rather than defaulted so the top-up can never become the
- # one call that reaches the Hub.
- local_files_only = local_files_only,
- ltx25_dev = ltx25_dev,
- )
- or _base_local_dir
+ _base_local_dir = self._top_up_dense_base(
+ base,
+ hf_token,
+ kind,
+ base_local_dir = _base_local_dir,
+ fetch_repo = _base_fetch_repo,
+ revision = _base_fetch_revision,
+ local_files_only = local_files_only,
+ ltx25_dev = ltx25_dev,
)
if ltx25_client is not None:
from .video_ltx25 import LTX25_NONE_COMPONENTS
@@ -7352,13 +8131,19 @@ class VideoBackend:
pipe_kwargs.update({name: None for name in LTX25_NONE_COMPONENTS})
if kind == "pipeline":
# The pre-downloaded snapshot dir keeps from_pretrained off the hub; hub id when pre-download was skipped.
- pipe = pipeline_cls.from_pretrained(_base_local_dir or repo_id, **pipe_kwargs)
+ pipe = pipeline_cls.from_pretrained(
+ _base_local_dir or fetch_base,
+ **_pinned_base_kwargs(),
+ **pipe_kwargs,
+ )
else:
transformer_cls = getattr(diffusers, fam.transformer_class)
# checkpoint_path was resolved (and downloaded) by the memory-planning branch above.
sf_kwargs: dict[str, Any] = {
"torch_dtype": dtype,
- "config": base,
+ "config": fetch_base,
+ # The plan's commit for that config (absent for an unpinned load).
+ **({"revision": _base_fetch_revision} if _base_fetch_revision else {}),
"subfolder": "transformer",
"token": hf_token,
"cache_dir": hub_cache_dir(),
@@ -7391,7 +8176,7 @@ class VideoBackend:
ltx23_override = load_ltx23_comfy_transformer(
checkpoint_path,
comfy_scan,
- base_repo = base,
+ base_repo = fetch_base,
torch_dtype = dtype,
hf_token = hf_token,
cache_dir = hub_cache_dir(),
@@ -7409,7 +8194,7 @@ class VideoBackend:
fam,
ltx23_scheme,
checkpoint_path,
- config_repo = base,
+ config_repo = fetch_base,
device = device,
dtype = dtype,
hf_token = hf_token,
@@ -7468,7 +8253,8 @@ class VideoBackend:
# the 2.3 connectors/VAEs/vocoder.
pipe = load_ltx23_pipeline(
checkpoint_path,
- base_repo = base,
+ base_repo = fetch_base,
+ revision = _base_fetch_revision,
torch_dtype = dtype,
is_gguf = kind == "gguf",
hf_token = hf_token,
@@ -7492,7 +8278,9 @@ class VideoBackend:
load_ltx25_transformer,
)
- if comfy_scan is not None and is_ltx25_single_file_base(_base_local_dir or base):
+ if comfy_scan is not None and is_ltx25_single_file_base(
+ _base_local_dir or fetch_base
+ ):
# The int8-convrot files quantize the text connectors too, and the pack-free assembly reads them from
# the DiT file: refuse before the DiT is read.
raise ValueError(
@@ -7504,7 +8292,7 @@ class VideoBackend:
ltx25_transformer = load_ltx25_comfy_transformer(
checkpoint_path,
comfy_scan,
- base_repo = _base_local_dir or base,
+ base_repo = _base_local_dir or fetch_base,
torch_dtype = dtype,
hf_token = hf_token,
cache_dir = hub_cache_dir(),
@@ -7519,7 +8307,7 @@ class VideoBackend:
else:
ltx25_transformer = load_ltx25_transformer(
checkpoint_path,
- base_repo = _base_local_dir or base,
+ base_repo = _base_local_dir or fetch_base,
torch_dtype = dtype,
is_gguf = kind == "gguf",
hf_token = hf_token,
@@ -7531,19 +8319,21 @@ class VideoBackend:
is_ltx25_single_file_base,
)
- if is_ltx25_single_file_base(_base_local_dir or base):
+ if is_ltx25_single_file_base(_base_local_dir or fetch_base):
# The split single-file release: every component from the files beside the DiT, no pack.
pipe = assemble_ltx25_single_file_pipeline(
ltx25_transformer,
checkpoint_path,
- base = _base_local_dir or base,
+ base = _base_local_dir or fetch_base,
torch_dtype = dtype,
hf_token = hf_token,
local_files_only = local_files_only,
)
else:
pipe = pipeline_cls.from_pretrained(
- _base_local_dir or base, **{**pipe_kwargs, "transformer": ltx25_transformer}
+ _base_local_dir or fetch_base,
+ **_pinned_base_kwargs(),
+ **{**pipe_kwargs, "transformer": ltx25_transformer},
)
else:
@@ -7579,7 +8369,9 @@ class VideoBackend:
Path(str(partner_path)).name,
)
pipe = pipeline_cls.from_pretrained(
- _base_local_dir or base, **{**pipe_kwargs, **experts}
+ _base_local_dir or fetch_base,
+ **_pinned_base_kwargs(),
+ **{**pipe_kwargs, **experts},
)
# The dtype dict already loads the Wan VAE at float32; belt-and-suspenders for any path that bypassed it (e.g. a
@@ -7595,7 +8387,7 @@ class VideoBackend:
pipe,
ltx25_client,
dev = ltx25_dev,
- base_repo = _base_local_dir or (repo_id if kind == "pipeline" else base),
+ base_repo = _base_local_dir or fetch_base,
torch_dtype = dtype,
hf_token = hf_token,
cache_dir = hub_cache_dir(),
@@ -8494,6 +9286,8 @@ class VideoBackend:
target: Any = None,
_load_token: Optional[int] = None,
_base_local_dir: Optional[str] = None,
+ _base_fetch_repo: Optional[str] = None,
+ _base_fetch_revision: Optional[str] = None,
_h3_auto_denoiser_planned: Optional[str] = None,
_nvfp4_install_outcome: Optional[tuple[bool, str]] = None,
local_files_only: bool = False,
@@ -8511,6 +9305,9 @@ class VideoBackend:
quantized CONDITIONER and the released bfloat16 DENOISER; ``"none"`` pins the released
component either way; an explicit scheme is honored or falls back with the reason
recorded."""
+ # Component configs and the dense weights are FETCHED from the base's unsloth mirror; ``base`` stays the
+ # upstream id the prequant / te-prequant tables are keyed on.
+ fetch_base = _base_fetch_repo or _video_fetch_repo(base, hf_token) or base
# Defence in depth: validate_load_request now refuses a single_file modular pick outright, so this is
# unreachable from the routes. It stays because this method is also reachable directly, and by the time it runs
# the resident pipeline has already been torn down.
@@ -8553,7 +9350,13 @@ class VideoBackend:
if hf_token:
load_kwargs["token"] = hf_token
pipe = diffusers.ModularPipeline.from_pretrained(
- _base_local_dir or (base if comfy_checkpoint else repo_id), **load_kwargs
+ _base_local_dir or fetch_base,
+ **(
+ {"revision": _base_fetch_revision}
+ if _base_fetch_revision and not _base_local_dir
+ else {}
+ ),
+ **load_kwargs,
)
transformer_quant_engaged: Optional[str] = None
transformer_quant_reason = "released bfloat16 components"
@@ -8670,7 +9473,7 @@ class VideoBackend:
getattr(diffusers, fam.transformer_class),
comfy_checkpoint,
comfy_scan,
- config = _base_local_dir or base,
+ config = _base_local_dir or fetch_base,
subfolder = denoiser_component,
dtype = dtype,
hf_token = hf_token,
@@ -8717,7 +9520,7 @@ class VideoBackend:
else:
transformer = load_prequantized_transformer(
getattr(diffusers, fam.transformer_class),
- base,
+ fetch_base,
source,
# CPU: enable_auto_cpu_offload below owns placement for every component, so a pre-placed denoiser
# would just be moved again (and a 66 GB pin on a device the manager wanted to offload from is how
@@ -8861,7 +9664,7 @@ class VideoBackend:
if te_scheme is not None:
from .video_minimax_h3_te import load_h3_quantized_text_encoder
text_encoder = load_h3_quantized_text_encoder(
- base,
+ fetch_base,
te_scheme,
dtype = dtype,
hf_token = hf_token,
@@ -8945,6 +9748,25 @@ class VideoBackend:
offline_sources = offline_component_sources(
pipe, local_files_only = local_files_only, cache_dir = hub_cache_dir()
)
+ # The index is byte identical, so every spec still names the upstream id; load_components would read those
+ # from the vendor repo under a different cache key than the mirror the base was staged into.
+ mirrored_sources = _h3_mirrored_component_sources(
+ pipe,
+ base,
+ fetch_base,
+ local_files_only = local_files_only,
+ cache_dir = hub_cache_dir(),
+ staged_dir = _base_local_dir
+ if _base_local_dir and not _is_under_dir(_base_local_dir, hub_cache_dir())
+ else None,
+ )
+ offline_sources = {**offline_sources, **mirrored_sources}
+ # The redirected components read the plan's commit of the staged repo (a snapshot folder needs none).
+ component_revisions = {
+ name: _base_fetch_revision
+ for name, source in mirrored_sources.items()
+ if _base_fetch_revision and source == fetch_base
+ }
pipe.load_components(
workflow = workflow,
dtype = dtype,
@@ -8952,6 +9774,7 @@ class VideoBackend:
local_files_only = local_files_only,
**({"token": hf_token} if hf_token else {}),
**({"pretrained_model_name_or_path": offline_sources} if offline_sources else {}),
+ **({"revision": component_revisions} if component_revisions else {}),
)
# The video VAE loads at float32 and the decode runs under float16 autocast, so both copies are resident for the
# whole decode. Pre-casting the decoder removes the pair without changing a single output value. The encoder
@@ -9613,9 +10436,13 @@ class VideoBackend:
gguf_filename: Optional[str],
hf_token: Optional[str],
local_files_only: bool = False,
+ fetch: Optional[tuple[str, Optional[str]]] = None,
) -> Path:
"""The local checkpoint file for a gguf/single_file load (downloads if hub).
+ ``fetch``: the load plan's ``(repo, revision)`` for the checkpoint, so assembly opens the exact file the
+ prefetch pinned; absent, the repo is settled here and ``main`` is followed.
+
``local_files_only`` resolves it from the cache instead: an API-initiated load has already
been told the checkpoint is staged, and this call runs a second time inside load_pipeline
(after _run_load's own fetch), where a cache miss must fail rather than pull the file."""
@@ -9628,11 +10455,16 @@ class VideoBackend:
return root
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
+ fetch_repo, revision = fetch or (
+ _video_fetch_repo(repo_id, hf_token, files = (gguf_filename or "",), checkpoint = True),
+ None,
+ )
return Path(
hf_hub_download_with_xet_fallback(
- repo_id,
+ fetch_repo,
gguf_filename or "",
hf_token,
+ revision = revision,
reuse_other_cache_root = True,
local_files_only = local_files_only,
gguf_header_delta = True,
@@ -9645,6 +10477,7 @@ class VideoBackend:
gguf_filename: Optional[str],
hf_token: Optional[str],
local_files_only: bool = False,
+ fetch: Optional[tuple[str, Optional[str]]] = None,
) -> Path:
"""The OTHER expert's file of a dual-expert pick (same folder / repo, paired by name; downloads if hub)."""
root = Path(repo_id).expanduser()
@@ -9660,7 +10493,7 @@ class VideoBackend:
if partner is None:
raise ValueError(f"'{gguf_filename}' does not name a high_noise / low_noise expert.")
return VideoBackend._resolve_checkpoint_path(
- repo_id, partner, hf_token, local_files_only = local_files_only
+ repo_id, partner, hf_token, local_files_only = local_files_only, fetch = fetch
)
# ── generation ───────────────────────────────────────────────────────────
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index d89dfab82ee..5c4be408ac5 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -1110,13 +1110,19 @@ def resolve_video_base_repo(
def _prequant_base_key(repo_id: Optional[str]) -> str:
- """The lookup key ``prequant_variant_repos`` is written against: trimmed and lowercased.
+ """The lookup key ``prequant_variant_repos`` is written against: the UPSTREAM id, trimmed and lowercased.
- Deliberately local rather than reusing ``diffusion_families.canonical_base``: this module
- header keeps the two registries apart so neither picker can reach the other's tables, and the
- image mirror map holds image repos only, so importing it would buy nothing but the coupling.
+ A video base's byte-identical unsloth mirror (``diffusion_families._VIDEO_MIRROR_PAIRS``) folds onto the upstream
+ it copies, since the fetch sites hand the mirror id to the loaders and an unfolded mirror would miss every row.
+ Only the id map is read (a lazy import of a pure function), never the image family table, so the two pickers
+ stay apart.
"""
- return (repo_id or "").strip().lower()
+ text = (repo_id or "").strip()
+ try:
+ from .diffusion_families import canonical_base
+ except Exception: # noqa: BLE001 -- the fold is an addition; the plain key is the old behaviour
+ return text.lower()
+ return canonical_base(text).strip().lower()
def video_family_prequant_repo(
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index b0224cb8f74..389decda521 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -802,7 +802,9 @@ LTX23_PREQUANT_RESIDENT_GB = 19.06
# The hosted DiT REPLACES the file's own, so the file must be the official one (a same-named fine-tune would be swapped silently).
-LTX23_PREQUANT_SOURCE_REPOS = frozenset({"lightricks/ltx-2.3"})
+# The official repo and the unsloth repo carrying its byte-identical files (diffusion_families._VIDEO_MIRROR_PAIRS): a
+# pick of Lightricks/LTX-2.3 is FETCHED from there, so the file it lands on sits under that repo's cache dir.
+LTX23_PREQUANT_SOURCE_REPOS = frozenset({"lightricks/ltx-2.3", "unsloth/ltx-2.3-fp8"})
_LTX23_HUB_REPO_DIRS = frozenset(
"models--" + r.replace("/", "--") for r in LTX23_PREQUANT_SOURCE_REPOS
)
@@ -985,7 +987,16 @@ def ltx23_prequant_eligible(
return False
if str(repo_id).strip().lower() not in LTX23_PREQUANT_SOURCE_REPOS:
return False
- cached = _ltx23_hub_cached_file(str(repo_id).strip(), str(checkpoint_filename))
+ cached = None
+ from .diffusion_families import canonical_base, mirror_repo
+
+ upstream = canonical_base(str(repo_id).strip())
+ for candidate in dict.fromkeys(
+ (str(repo_id).strip(), upstream, mirror_repo(upstream) or upstream)
+ ):
+ cached = _ltx23_hub_cached_file(candidate, str(checkpoint_filename))
+ if cached is not None:
+ break
return True if cached is None else ltx23_source_file_verified(cached)
@@ -999,7 +1010,15 @@ class _LTX23PrequantConfig:
def load_config(self, _base: str, **kwargs: Any) -> dict[str, Any]:
from diffusers import LTX2VideoTransformer3DModel
- config = dict(LTX2VideoTransformer3DModel.load_config(self.config_repo, **kwargs))
+ from .diffusion_families import pinned_revision_kwargs
+
+ # Pinned on the repo actually read, which need not be the caller's ``_base``.
+ kwargs.pop("revision", None)
+ config = dict(
+ LTX2VideoTransformer3DModel.load_config(
+ self.config_repo, **kwargs, **pinned_revision_kwargs(self.config_repo)
+ )
+ )
config.update(LTX_2_3_TRANSFORMER_CONFIG_OVERRIDES)
return config
@@ -1291,6 +1310,10 @@ def load_ltx23_transformer(
"local_files_only": local_files_only,
**LTX_2_3_TRANSFORMER_CONFIG_OVERRIDES,
}
+ from .diffusion_families import pinned_revision_kwargs
+
+ # The load plan's commit for that hub-id config (absent for an unpinned load).
+ kwargs.update(pinned_revision_kwargs(base_repo))
if is_gguf:
kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(compute_dtype = torch_dtype)
elif device is not None:
@@ -1557,6 +1580,7 @@ def _assemble_ltx23_pipeline(
transformer_override: Optional[Any] = None,
device: Optional[Any] = None,
text_encoder_device: Optional[Any] = None,
+ revision: Optional[str] = None,
) -> Any:
"""Full LTX-2.3 pipeline from a single-file/GGUF checkpoint. Assembled per-component
(constructor, not from_pretrained) because the base model_index pins LTX2Vocoder while 2.3
@@ -1667,8 +1691,15 @@ def _assemble_ltx23_pipeline(
# mid-session change searches the OTHER root, so under local_files_only it raises for a base that is fully
# downloaded, after eviction.
cache_dir = _live_cache_dir()
+ # ``revision``: the load plan's commit for the base, so the components come from the snapshot it staged (passed only
+ # when set, so an unpinned load calls exactly as before).
+ pinned: dict[str, Any] = {"revision": revision} if revision else {}
index = LTX2Pipeline.load_config(
- base_repo, token = hf_token, local_files_only = local_files_only, cache_dir = cache_dir
+ base_repo,
+ token = hf_token,
+ local_files_only = local_files_only,
+ cache_dir = cache_dir,
+ **pinned,
)
def _sub(name: str, **extra: Any) -> Any:
@@ -1680,6 +1711,7 @@ def _assemble_ltx23_pipeline(
token = hf_token,
local_files_only = local_files_only,
cache_dir = cache_dir,
+ **pinned,
**extra,
)
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.py
index a8d6dae718e..ec7ea2facba 100644
--- a/studio/backend/core/inference/video_ltx25.py
+++ b/studio/backend/core/inference/video_ltx25.py
@@ -391,6 +391,10 @@ def load_ltx25_transformer(
"cache_dir": cache_dir,
"local_files_only": local_files_only,
}
+ from .diffusion_families import pinned_revision_kwargs
+
+ # The load plan's commit for a hub-id config (none for the bundled config dir or an unpinned load).
+ kwargs.update(pinned_revision_kwargs(kwargs["config"]))
if is_gguf:
kwargs["quantization_config"] = diffusers.GGUFQuantizationConfig(compute_dtype = torch_dtype)
elif device is not None:
@@ -451,6 +455,7 @@ def load_latent_upsampler(
local_files_only: bool = False,
) -> Any:
from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
+
if is_ltx25_single_file_base(base_repo):
from safetensors.torch import load_file
@@ -460,8 +465,11 @@ def load_latent_upsampler(
return _build_from_config(
LTX2LatentUpsamplerModel, LTX25_UPSAMPLER_CONFIG, load_file(path), {}, torch_dtype
)
+ from .diffusion_families import pinned_revision_kwargs
+
return LTX2LatentUpsamplerModel.from_pretrained(
base_repo,
+ **pinned_revision_kwargs(base_repo),
subfolder = LATENT_UPSAMPLER_SUBFOLDER,
torch_dtype = torch_dtype,
token = hf_token,
@@ -473,7 +481,7 @@ def load_latent_upsampler(
# ── the split single-file layout as its own base ────────────────────────────
-def is_ltx25_single_file_base(base: Optional[str]) -> bool:
+def is_ltx25_single_file_base(base: Optional[str], *, fold_mirror: bool = True) -> bool:
"""Whether ``base`` is the split single-file release (hub id) or a local folder with its layout (the encoder file
and the conv VAE beside the DiTs), rather than a Diffusers pack."""
text = (base or "").strip()
@@ -484,7 +492,13 @@ def is_ltx25_single_file_base(base: Optional[str]) -> bool:
return (path / LTX25_SINGLE_TEXT_ENCODER).is_file() and (
path / LTX25_SINGLE_VIDEO_VAE
).is_file()
- return text.lower() == LTX25_SINGLE_FILE_REPO.lower()
+ if not fold_mirror:
+ return text.lower() == LTX25_SINGLE_FILE_REPO.lower()
+ # The fetch sites hand the assembly the repo carrying the release's byte-identical files (unsloth/LTX-2.5-GGUF).
+ # ``fold_mirror=False`` is for a PICK's own repo: a GGUF picked from that repo keeps the Diffusers base.
+ from .diffusion_families import canonical_base
+
+ return canonical_base(text).lower() == LTX25_SINGLE_FILE_REPO.lower()
def is_ltx25_single_file_listing(names: Any) -> bool:
@@ -510,7 +524,7 @@ def ltx25_single_file_companions(
def ltx25_default_base(repo_id: Optional[str]) -> Optional[str]:
"""A DiT picked from the single-file release (or a local copy of it) uses that release as its base."""
- return repo_id if is_ltx25_single_file_base(repo_id) else None
+ return repo_id if is_ltx25_single_file_base(repo_id, fold_mirror = False) else None
def ltx25_companion_path(
@@ -530,10 +544,13 @@ def ltx25_companion_path(
return str(target)
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
+ from .diffusion_families import pinned_revision_kwargs
+
return hf_hub_download_with_xet_fallback(
base,
filename,
hf_token,
+ **pinned_revision_kwargs(base),
reuse_other_cache_root = True,
local_files_only = local_files_only,
)
@@ -1119,6 +1136,7 @@ def close_encoder(pipe: Any) -> None:
def start_text_encoder(
*,
repo: str,
+ revision: Optional[str] = None,
hf_token: Optional[str],
cache_dir: Optional[str],
local_files_only: bool,
@@ -1160,6 +1178,10 @@ def start_text_encoder(
te_prequant = te_prequant,
hub_repo = hub_repo if hub_repo != repo else None,
)
+ from .diffusion_families import pinned_revision_kwargs
+
+ # The worker is another process: the plan's commit travels in its config (absent when unpinned).
+ client.config.update({"revision": revision} if revision else pinned_revision_kwargs(repo))
client.start()
return client
diff --git a/studio/backend/core/inference/video_ltx25_te_worker.py b/studio/backend/core/inference/video_ltx25_te_worker.py
index a5b127e89ae..b41824d502f 100644
--- a/studio/backend/core/inference/video_ltx25_te_worker.py
+++ b/studio/backend/core/inference/video_ltx25_te_worker.py
@@ -62,6 +62,7 @@ def _single_file_folder(config: dict) -> str:
path = hf_hub_download(
repo,
name,
+ **({"revision": config["revision"]} if config.get("revision") else {}),
token = config.get("hf_token") or None,
cache_dir = config.get("cache_dir") or None,
local_files_only = bool(config.get("local_files_only")),
@@ -133,6 +134,8 @@ def _load(config: dict) -> tuple[Any, Any]:
"token": config.get("hf_token") or None,
"cache_dir": config.get("cache_dir") or None,
"local_files_only": bool(config.get("local_files_only")),
+ # The load plan's commit for the base, when it pinned one.
+ **({"revision": config["revision"]} if config.get("revision") else {}),
}
if config.get("single_file"):
import shutil
@@ -239,7 +242,8 @@ def _hosted_path(spec: dict, common: dict) -> str:
return mirror
from huggingface_hub import hf_hub_download, try_to_load_from_cache
- kwargs = dict(common)
+ # ``common`` may pin the BASE repo's commit; the hosted file lives in its own repo, so that revision never applies.
+ kwargs = {k: v for k, v in common.items() if k != "revision"}
# The server stages this file with reuse_other_cache_root (hf_hub_download_with_xet_fallback), so a copy cached
# only under huggingface_hub's own root counts as staged and the dense shards are dropped. Resolve it the same way,
# else a local_files_only load misses it here and has no dense encoder to fall back to.
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index 2177af9f46b..2ecf441d093 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -20,17 +20,14 @@ from typing import Any, Callable, Optional
# the Qwen3-VL encoder quants as well as the denoisers, so this repo alone satisfies h3_native_hub_files' first two
# entries.
H3_GGUF_REPO = "unsloth/MiniMax-H3-GGUF"
-# The VAEs live beside the denoisers, so the native pick is one repo we control end to end. It was Comfy-Org/MiniMax-H3,
-# which put a community repack in the download path of BOTH H3 paths; an install that already holds those bytes keeps
-# using them through h3_component_source below, because the HF cache is keyed by repo id and repointing alone
-# re-downloads ~6 GB.
+# The VAEs live beside the denoisers, so the native pick is one repo we control end to end. It was the Comfy-Org repack
+# once; a video load never reads from that repack any more, cached or not.
H3_COMPONENT_REPO = "unsloth/MiniMax-H3-GGUF"
-# Where the component files came from originally. Only for reusing an existing cache entry: a fresh install never
-# reads it. The pairing itself lives in diffusion_families' _SD_CPP_LEGACY_SOURCES, which owns this decision for every
-# mirrored asset; this name is what the delete-cached claims read, and a test pins the two together.
-H3_LEGACY_COMPONENT_REPO = "Comfy-Org/MiniMax-H3"
-H3_VIDEO_VAE = "vae/minimax_h3_video_vae_fp16.safetensors"
-H3_AUDIO_VAE = "vae/minimax_h3_audio_vae_fp32.safetensors"
+# Built from the official MiniMaxAI vae/ and audio_vae/ weights (diffusers layout -> sd.cpp layout; video cast to fp16)
+# and uploaded beside the originals under vae/official/. They are byte-identical to the vae/ copies that came from the
+# Comfy-Org repack, which stay in place for released builds; this build reads only the official-provenance paths.
+H3_VIDEO_VAE = "vae/official/minimax_h3_video_vae_fp16.safetensors"
+H3_AUDIO_VAE = "vae/official/minimax_h3_audio_vae_fp32.safetensors"
H3_QWEN_Q2 = "qwen3vl_32b_minimax_h3-Q2_K_M.gguf"
H3_QWEN_Q4 = "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"
@@ -1263,44 +1260,18 @@ def h3_download_error(repo_id: str, filename: str, exc: Exception) -> Exception:
def h3_component_source(*files: str) -> str:
- """The repo to fetch the shared VAEs from: our mirror, or the repack it was mirrored from when an
- existing install already holds those exact bytes under the old id.
-
- The HF cache is keyed by repo id, so moving the id alone would re-download ~5.8 GB on upgrade
- and fail outright offline. The mirror is byte identical (same sha256), so reusing the old entry
- loads the same weights. Fresh installs never take this branch.
-
- ``prefer_cached_legacy_source`` rather than a probe of our own: it already owns this exact
- mirror-to-repack decision for every other sd.cpp asset, and it counts BOTH cache roots. That
- second part is why it has to be this one -- the native fetch below passes
- ``reuse_other_cache_root``, so a repack left behind by a cache-folder change is still usable,
- but only the OLD repo id can reach it and a live-root-only probe would call it absent and
- re-pull ~5.8 GB.
-
- Answered for the files GIVEN, and the native loop asks one at a time because that is how it
- downloads them: a pre-move pull interrupted between the two VAEs leaves only one under the old
- id, and asking per file reuses it. With no argument it answers for the pair.
-
- PURE: table lookup plus a local stat, no network, so a download plan and the fetch that follows
- it agree on the source.
- """
- wanted = files or (H3_VIDEO_VAE, H3_AUDIO_VAE)
- try:
- from .diffusion_families import prefer_cached_legacy_source
- return prefer_cached_legacy_source(H3_COMPONENT_REPO, wanted)
- except Exception: # noqa: BLE001 -- an unreadable cache just means "not cached"
- return H3_COMPONENT_REPO
+ """The repo to fetch the shared VAEs from: always ``H3_COMPONENT_REPO``.
+ An install that pulled them from the Comfy-Org repack before the move re-downloads them from here once: a video
+ load never reads from a Comfy repack, not even bytes already cached under one. ``files`` is kept so the callers
+ that ask per file need not change."""
+ del files
+ return H3_COMPONENT_REPO
-def h3_component_metadata_repo(repo_id: str) -> str:
- """Which repo to read a shared VAE's SIZE from, given the repo its bytes will come from.
- The repack is a source of bytes ALREADY ON DISK, never of network metadata. It may since have
- been renamed or taken down -- the exact failure this move exists to survive -- and a
- ``model_info`` against it would fail the download plan for a load its own cache can still
- satisfy. The mirror's copy is byte identical, so the number is the same.
- """
- return H3_COMPONENT_REPO if repo_id == H3_LEGACY_COMPONENT_REPO else repo_id
+def h3_component_metadata_repo(repo_id: str) -> str:
+ """Which repo to read a shared VAE's SIZE from: the repo its bytes come from (kept for the callers)."""
+ return repo_id
# Resident peak is the four files plus ~1 GiB (sd.cpp frees the text encoder before the denoiser's compute buffer);
diff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.py
index 8be23e5a58a..9a02cedeb65 100644
--- a/studio/backend/core/inference/video_minimax_h3_te.py
+++ b/studio/backend/core/inference/video_minimax_h3_te.py
@@ -61,17 +61,15 @@ from .diffusion_convrot import ( # noqa: F401 (re-export: callers and tests na
# H3_COMPONENT_REPO: the VAEs moved to the GGUF mirror and the conditioner did not, so the two are now separate repos
# and aliasing them would send this file to the wrong one.
H3_TE_QUANT_REPO = "unsloth/MiniMax-H3-FP8"
-# The community repack these quants were mirrored from, for an install whose cache predates the move. Same reasoning as
-# H3_LEGACY_COMPONENT_REPO, and the same owner: the pairing itself lives in diffusion_families' _SD_CPP_LEGACY_SOURCES
-# and is read through h3_te_quant_source below.
-H3_LEGACY_TE_QUANT_REPO = "Comfy-Org/MiniMax-H3"
-
# Hosted quantized conditioners, by ``text_encoder_quant`` scheme. nvfp4
# (``qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors``, 14.61 GiB) is deliberately absent: it is an AWQ NVFP4 layout with
# two levels of scale and a per-tensor global scale, a different loader and a different kernel, and shipping it needs
# its own numerical verification. The table is the one place to add it.
H3_TE_QUANT_FILES: dict[str, str] = {
- "int8": "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors",
+ # Built from the official MiniMaxAI text_encoder/ with Studio's quantize_convrot_int8_weight and uploaded under
+ # text_encoders/official/. Byte-identical to the text_encoders/ copy that came from the Comfy-Org repack, which
+ # stays in place for released builds; this build reads only the official-provenance path.
+ "int8": "text_encoders/official/qwen3vl_32b_minimax_h3_int8_convrot.safetensors",
}
# The scheme an UNSET ``text_encoder_quant`` resolves to on a device that supports it. The released conditioner is a
@@ -125,27 +123,10 @@ def h3_te_quant_filename(scheme: Optional[str]) -> Optional[str]:
def h3_te_quant_source(scheme: Optional[str]) -> str:
- """The repo to fetch the hosted quantized conditioner for ``scheme`` from: our mirror, or the
- repack it was mirrored from when this install already holds that exact artifact under the old
- id.
-
- The conditioner's half of ``h3_component_source``, and it matters more than the VAEs do: the
- artifact is ~27 GB, and the load that wants it has already dropped the dense encoder shards
- from its pull. So on an upgraded install a live re-download is not merely slow -- offline it
- leaves the pipeline with no encoder at all, because the base snapshot it would fall back to
- was never staged either.
-
- PURE, and the same shared owner (``prefer_cached_legacy_source``, both cache roots) the VAEs
- use, so planning, prefetching and loading cannot name different repos.
- """
- filename = h3_te_quant_filename(scheme)
- if filename is None:
- return H3_TE_QUANT_REPO
- try:
- from .diffusion_families import prefer_cached_legacy_source
- return prefer_cached_legacy_source(H3_TE_QUANT_REPO, (filename,))
- except Exception: # noqa: BLE001 -- an unreadable cache just means "not cached"
- return H3_TE_QUANT_REPO
+ """The repo to fetch the hosted quantized conditioner for ``scheme`` from: always ``H3_TE_QUANT_REPO``. A video
+ load never reads from the Comfy-Org repack, not even bytes an older install cached under it."""
+ del scheme
+ return H3_TE_QUANT_REPO
def h3_te_resident_gb(scheme: Optional[str], *, bf16_gb: float) -> float:
@@ -348,8 +329,11 @@ def load_h3_quantized_text_encoder(
gguf_header_delta = True,
)
+ from .diffusion_families import pinned_revision_kwargs
+
config = transformers.AutoConfig.from_pretrained(
local_base or base,
+ **pinned_revision_kwargs(local_base or base),
subfolder = "text_encoder",
token = hf_token,
cache_dir = cache_dir,
diff --git a/studio/backend/tests/test_nvfp4_diffusion_flag.py b/studio/backend/tests/test_nvfp4_diffusion_flag.py
index e47e82d0740..c5c7625bfcb 100644
--- a/studio/backend/tests/test_nvfp4_diffusion_flag.py
+++ b/studio/backend/tests/test_nvfp4_diffusion_flag.py
@@ -350,6 +350,10 @@ _WAN_SIBLINGS = {
_sib("text_encoder/model-00001-of-00001.safetensors", 11_000_000_000),
_sib("vae/diffusion_pytorch_model.safetensors", 500_000_000),
],
+}
+# The base's unsloth mirror holds the same files at the same paths, and is the repo a default load fetches from.
+_WAN_SIBLINGS["unsloth/Wan2.2-T2V-A14B-FP8"] = _WAN_SIBLINGS[_WAN_T2V]
+_WAN_SIBLINGS |= {
"unsloth/Wan2.2-T2V-A14B-NVFP4": [
_sib("Wan2.2-T2V-A14B-NVFP4.pt", 8_000_000_000),
_sib("Wan2.2-T2V-A14B-transformer_2-NVFP4.pt", 8_100_000_000),
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index cdc03ad1086..ab1e01936e8 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -2354,9 +2354,8 @@ def test_the_delete_guard_names_the_repack_as_well_as_the_mirror(monkeypatch):
protected = _with_mirrors([mirror])
assert mirror in protected
assert repack in protected
- # The remaining real (video) row is covered the same way.
- protected = _with_mirrors(["unsloth/Wan2.2-TI2V-5B-GGUF"])
- assert "QuantStack/Wan2.2-TI2V-5B-GGUF" in protected
+ # No real row is left: the Wan GGUF no longer drags its old QuantStack repack along.
+ assert "QuantStack/Wan2.2-TI2V-5B-GGUF" not in _with_mirrors(["unsloth/Wan2.2-TI2V-5B-GGUF"])
def test_begin_load_answers_without_waiting_on_the_header_probe(monkeypatch):
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index c2a0b44fe25..58c3267dbed 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -50,12 +50,10 @@ def _shared_setup_2():
def _shared_setup_3():
- from core.inference.video_minimax_h3 import (
- H3_COMPONENT_REPO,
- H3_GGUF_REPO,
- H3_LEGACY_COMPONENT_REPO,
- )
- return H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO
+ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO
+
+ # The third slot was the Comfy-Org repack the components came from; a video load never reads it any more.
+ return H3_COMPONENT_REPO, H3_GGUF_REPO, None
def _shared_setup_4(monkeypatch, tmp_path):
@@ -139,6 +137,14 @@ def _shared_setup_12(_download, monkeypatch):
return backend, fam
[email protected](autouse = True)
+def _pin_video_fetch_to_the_named_repo(monkeypatch):
+ """These tests are about plan / load decisions, written against the UPSTREAM ids their fake Hub serves. The fetch
+ swap onto the unsloth mirrors depends on the developer's own HF cache, so it is pinned off here, as the image
+ offline-load tests do; tests/test_video_unsloth_mirrors.py covers the swap itself."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+
+
@pytest.fixture(autouse = True)
def _roomy_host_ram(monkeypatch):
"""Native H3 loads fit against the host's available RAM, which a CI runner may not have (macos-15: about 3 GiB).
@@ -1072,7 +1078,8 @@ def test_loading_repo_ids_guards_in_flight_delete():
backend = VideoBackend()
assert backend.loading_repo_ids() == () # idle: nothing to guard
backend._loading = _VideoLoadingState(repo_id = "org/ckpt", base_repo = "Lightricks/LTX-2")
- assert set(backend.loading_repo_ids()) == {"org/ckpt", "Lightricks/LTX-2"}
+ # The base's unsloth mirror too: that is the id the fetch actually pulls into.
+ assert set(backend.loading_repo_ids()) == {"org/ckpt", "Lightricks/LTX-2", "unsloth/LTX-2-FP8"}
# An errored load is no longer in flight, so the files are safe to delete.
backend._loading = _VideoLoadingState(
repo_id = "org/ckpt", base_repo = "Lightricks/LTX-2", error = "boom"
@@ -3333,8 +3340,8 @@ def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):
"unsloth/MiniMax-H3-GGUF": [
_PlanSibling("minimax_h3_fl2va-Q4_K_M.gguf", 19),
_PlanSibling("qwen3vl_32b_minimax_h3-Q4_K_M.gguf", 18),
- _PlanSibling("vae/minimax_h3_video_vae_fp16.safetensors", 5),
- _PlanSibling("vae/minimax_h3_audio_vae_fp32.safetensors", 1),
+ _PlanSibling("vae/official/minimax_h3_video_vae_fp16.safetensors", 5),
+ _PlanSibling("vae/official/minimax_h3_audio_vae_fp32.safetensors", 1),
],
},
)
@@ -3353,8 +3360,8 @@ def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):
assert by_repo["unsloth/MiniMax-H3-GGUF"]["files"] == [
"minimax_h3_fl2va-Q4_K_M.gguf",
"qwen3vl_32b_minimax_h3-Q4_K_M.gguf",
- "vae/minimax_h3_video_vae_fp16.safetensors",
- "vae/minimax_h3_audio_vae_fp32.safetensors",
+ "vae/official/minimax_h3_video_vae_fp16.safetensors",
+ "vae/official/minimax_h3_audio_vae_fp32.safetensors",
]
assert plan["total_bytes"] == 43
@@ -3420,8 +3427,8 @@ def test_h3_native_uses_the_local_bundles_own_text_encoder(monkeypatch, tmp_path
"unsloth/MiniMax-H3-GGUF": [
_PlanSibling("minimax_h3_fl2va-Q4_K_M.gguf", 19),
_PlanSibling("qwen3vl_32b_minimax_h3-Q4_K_M.gguf", 18),
- _PlanSibling("vae/minimax_h3_video_vae_fp16.safetensors", 5),
- _PlanSibling("vae/minimax_h3_audio_vae_fp32.safetensors", 1),
+ _PlanSibling("vae/official/minimax_h3_video_vae_fp16.safetensors", 5),
+ _PlanSibling("vae/official/minimax_h3_audio_vae_fp32.safetensors", 1),
],
},
)
@@ -3804,7 +3811,7 @@ def test_h3_native_load_claims_the_companion_repos_before_the_preflight(monkeypa
from core.inference import video as video_mod
from core.inference import sd_cpp_backend, sd_cpp_engine
- H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO = _shared_setup_3()
+ H3_COMPONENT_REPO, H3_GGUF_REPO, _ = _shared_setup_3()
class _Api:
def __init__(self, **_kwargs):
@@ -3859,11 +3866,8 @@ def test_h3_native_load_claims_the_companion_repos_before_the_preflight(monkeypa
gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
)
- # Every id a component source can resolve to, not one resolved answer: the two VAEs are
- # resolved independently, so an interrupted pre-move pull can leave one on the repack and the
- # other on the mirror, and a claim naming either alone leaves the other deletable mid-load.
- # Same triple begin_load publishes.
- assert seen == [(H3_GGUF_REPO, H3_COMPONENT_REPO, H3_LEGACY_COMPONENT_REPO)]
+ # Every repo a component is read from (never the Comfy-Org repack). Same pair begin_load publishes.
+ assert seen == [(H3_GGUF_REPO, H3_COMPONENT_REPO)]
def test_begin_load_publishes_the_h3_companion_claim_with_the_loading_state(
@@ -3876,7 +3880,7 @@ def test_begin_load_publishes_the_h3_companion_claim_with_the_loading_state(
import threading
from types import SimpleNamespace
- H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO = _shared_setup_3()
+ H3_COMPONENT_REPO, H3_GGUF_REPO, _ = _shared_setup_3()
backend = VideoBackend()
# Never started: the window under test is before the load thread is scheduled.
@@ -3925,9 +3929,23 @@ def test_begin_load_publishes_the_hosted_ltx23_fp8_claim_with_the_loading_state(
)
return backend.loading_repo_ids()
+ # Read off the asset claim, not loading_repo_ids(): the pick's own bf16 file is now fetched from that same repo
+ # (it carries Lightricks/LTX-2.3's files), so the delete guard names it either way.
+ def _asset(**kwargs):
+ backend = VideoBackend()
+ backend.begin_load(
+ "Lightricks/LTX-2.3",
+ gguf_filename = "ltx-2.3-22b-distilled.safetensors",
+ family_override = "ltx-2",
+ model_kind = "single_file",
+ **kwargs,
+ )
+ return backend._loading.asset_repos
+
assert "unsloth/LTX-2.3-FP8" in _claimed(transformer_quant = "fp8")
- assert "unsloth/LTX-2.3-FP8" not in _claimed()
- assert "unsloth/LTX-2.3-FP8" not in _claimed(transformer_quant = "fp8", memory_mode = "balanced")
+ assert "unsloth/LTX-2.3-FP8" in _asset(transformer_quant = "fp8")
+ assert "unsloth/LTX-2.3-FP8" not in _asset()
+ assert "unsloth/LTX-2.3-FP8" not in _asset(transformer_quant = "fp8", memory_mode = "balanced")
def test_begin_load_claims_no_companion_repos_for_a_non_h3_family(fake_runtime, monkeypatch):
@@ -3936,7 +3954,7 @@ def test_begin_load_claims_no_companion_repos_for_a_non_h3_family(fake_runtime,
import threading
from types import SimpleNamespace
- H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO = _shared_setup_3()
+ H3_COMPONENT_REPO, H3_GGUF_REPO, _ = _shared_setup_3()
backend = VideoBackend()
monkeypatch.setattr(
@@ -5464,7 +5482,7 @@ def test_h3_native_load_publishes_the_companion_repos_while_downloading(monkeypa
from core.inference import video as video_mod
from core.inference import sd_cpp_backend, sd_cpp_engine
- H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO = _shared_setup_3()
+ H3_COMPONENT_REPO, H3_GGUF_REPO, _ = _shared_setup_3()
class _Api:
def __init__(self, **_kwargs):
@@ -5749,7 +5767,7 @@ def test_h3_native_loaded_repo_ids_cover_the_companion_repos():
# so deleting either On Device while H3 is loaded must be refused.
from core.inference.video import _VideoLoadState
- H3_COMPONENT_REPO, H3_GGUF_REPO, H3_LEGACY_COMPONENT_REPO = _shared_setup_3()
+ H3_COMPONENT_REPO, H3_GGUF_REPO, _ = _shared_setup_3()
backend = VideoBackend()
assert backend.loaded_repo_ids() == ()
@@ -5766,14 +5784,10 @@ def test_h3_native_loaded_repo_ids_cover_the_companion_repos():
engine = "sd_cpp",
gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
)
- # Both component ids: the components moved to our own mirror, but an install whose cache
- # predates that move still reads them from the repack under the old id, and the delete guard
- # has to cover whichever one this load is actually holding.
assert backend.loaded_repo_ids() == (
"leejet/MiniMax-H3-GGUF",
H3_GGUF_REPO,
H3_COMPONENT_REPO,
- H3_LEGACY_COMPONENT_REPO,
)
# A diffusers load holds its weights in memory, and base_repo already names its repo.
object.__setattr__(backend._state, "engine", "diffusers")
@@ -6550,104 +6564,6 @@ def test_every_h3_asset_comes_from_an_unsloth_repo(monkeypatch):
assert not offenders, f"H3 would download from a repo we do not control: {offenders}"
-def test_the_h3_legacy_ids_are_the_ones_the_shared_table_names():
- """The constants the delete-cached claims read must be the table's own answer.
-
- The claims name `H3_LEGACY_*` directly, while the source resolvers go through
- `_SD_CPP_LEGACY_SOURCES`. If those two ever disagree the claim protects one repo while the
- load reads another, which is the exact mid-load deletion the claim exists to stop.
- """
- from core.inference.diffusion_families import legacy_source_repo
- from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_LEGACY_COMPONENT_REPO
- from core.inference.video_minimax_h3_te import H3_LEGACY_TE_QUANT_REPO, H3_TE_QUANT_REPO
-
- assert legacy_source_repo(H3_COMPONENT_REPO) == H3_LEGACY_COMPONENT_REPO
- assert legacy_source_repo(H3_TE_QUANT_REPO) == H3_LEGACY_TE_QUANT_REPO
-
-
-def test_the_h3_components_fall_back_to_a_cache_that_predates_the_move(monkeypatch):
- """An install holding the old repack's bytes must not re-download them.
-
- The HF cache is keyed by repo id, so repointing the constant alone re-fetches ~5.8 GB on
- upgrade and fails outright offline. The bytes are identical either way.
- """
- from core.inference import diffusion_families
- from core.inference import video_minimax_h3 as h3
-
- monkeypatch.setattr(diffusion_families, "_upstream_is_cached", lambda *a, **k: True)
- assert h3.h3_component_source() == h3.H3_LEGACY_COMPONENT_REPO
- files = dict(h3_files := h3.h3_native_hub_files("minimax_h3_fl2va_pruned-Q2_K.gguf"))
- assert files[h3.H3_LEGACY_COMPONENT_REPO] in (h3.H3_VIDEO_VAE, h3.H3_AUDIO_VAE)
- assert len(h3_files) == 4
-
- monkeypatch.setattr(diffusion_families, "_upstream_is_cached", lambda *a, **k: False)
- assert h3.h3_component_source() == h3.H3_COMPONENT_REPO
-
-
-def test_the_h3_component_probe_counts_the_other_cache_root(monkeypatch):
- """A repack left behind by a cache-folder change still counts.
-
- The native fetch passes `reuse_other_cache_root`, so bytes under huggingface_hub's
- import-time root really are reusable -- but only the OLD repo id can reach them. A live-root
- only probe (`cache_holds_files`) calls them absent, picks the mirror and re-pulls ~5.8 GB;
- offline it fails outright, which is the whole failure this fallback exists to prevent.
- """
- from core.inference import diffusion_families
- from core.inference import video_minimax_h3 as h3
-
- seen: list[dict] = []
-
- def _probe(
- repo_id,
- files = None,
- *,
- other_root = False,
- ):
- seen.append({"repo": repo_id, "files": tuple(files or ()), "other_root": other_root})
- return other_root # cached ONLY in the root the live-root probe cannot see
-
- monkeypatch.setattr(diffusion_families, "_upstream_is_cached", _probe)
- assert h3.h3_component_source() == h3.H3_LEGACY_COMPONENT_REPO
- assert seen and seen[0]["other_root"] is True
- assert seen[0]["repo"] == h3.H3_LEGACY_COMPONENT_REPO
- assert set(seen[0]["files"]) == {h3.H3_VIDEO_VAE, h3.H3_AUDIO_VAE}
-
-
-def test_the_h3_conditioner_falls_back_to_a_cache_that_predates_the_move(monkeypatch):
- """The 27 GB int8 conditioner needs the same fallback the VAEs got, for a worse failure.
-
- `H3_TE_QUANT_REPO` used to alias the repack, so an install that pulled the artifact before the
- move holds it under the old id. Re-pointing the constant alone re-downloads 27 GB online, and
- offline leaves the pipeline with no encoder at all: the load that asks for this artifact has
- already dropped the dense encoder shards from its pull, so there is nothing to fall back to.
- """
- from core.inference import diffusion_families
- from core.inference import video_minimax_h3_te as te
-
- asked: list[tuple] = []
-
- def _probe(
- repo_id,
- files = None,
- *,
- other_root = False,
- ):
- asked.append((repo_id, tuple(files or ()), other_root))
- return True
-
- monkeypatch.setattr(diffusion_families, "_upstream_is_cached", _probe)
- assert te.h3_te_quant_source("int8") == te.H3_LEGACY_TE_QUANT_REPO
- assert asked == [
- (te.H3_LEGACY_TE_QUANT_REPO, (te.H3_TE_QUANT_FILES["int8"],), True)
- ], "the conditioner must be probed by its own filename, in both cache roots"
-
- monkeypatch.setattr(diffusion_families, "_upstream_is_cached", lambda *a, **k: False)
- assert te.h3_te_quant_source("int8") == te.H3_TE_QUANT_REPO
- # A scheme with no hosted artifact has nothing to probe and never leaves the mirror.
- assert te.h3_te_quant_source(None) == te.H3_TE_QUANT_REPO
- assert te.h3_te_quant_source("nvfp4") == te.H3_TE_QUANT_REPO
-
-
def test_the_native_h3_vaes_come_from_a_local_bundle_when_it_has_them(tmp_path):
"""A local clone of the mirror is self-contained, so nothing may go to the Hub.
@@ -6671,6 +6587,7 @@ def test_the_native_h3_vaes_come_from_a_local_bundle_when_it_has_them(tmp_path):
for name in (gguf, qwen):
(bundle / name).write_bytes(b"x")
for name in (H3_VIDEO_VAE, H3_AUDIO_VAE):
+ (bundle / name).parent.mkdir(parents = True, exist_ok = True)
(bundle / name).write_bytes(b"x")
requests = VideoBackend._h3_native_requests(str(bundle), gguf, qwen)
@@ -6710,94 +6627,6 @@ def _legacy_cache_holding(monkeypatch, names):
monkeypatch.setattr(diffusion_families, "_upstream_is_cached", _probe)
-def test_a_pre_move_cache_holding_one_vae_still_gets_reused_for_that_one(monkeypatch, tmp_path):
- """The two VAEs are fetched one at a time, so the source is decided one at a time.
-
- A pre-move pull interrupted between them leaves the 5.2 GB video VAE under the old id and
- nothing else. Deciding the pair together calls the old id useless and re-downloads the file
- already on disk, or fails offline.
- """
- from core.inference.video import VideoBackend
- from core.inference.video_minimax_h3 import (
- H3_AUDIO_VAE,
- H3_COMPONENT_REPO,
- H3_GGUF_REPO,
- H3_LEGACY_COMPONENT_REPO,
- H3_VIDEO_VAE,
- h3_component_source,
- h3_native_hub_files,
- )
-
- gguf = "minimax_h3_fl2va_pruned-Q2_K.gguf"
- qwen = "qwen3vl_32b_minimax_h3-Q2_K_M.gguf"
- _legacy_cache_holding(monkeypatch, {H3_VIDEO_VAE})
-
- assert h3_component_source(H3_VIDEO_VAE) == H3_LEGACY_COMPONENT_REPO
- assert h3_component_source(H3_AUDIO_VAE) == H3_COMPONENT_REPO
- assert VideoBackend._h3_native_requests(H3_GGUF_REPO, gguf, qwen) == (
- (H3_GGUF_REPO, gguf),
- (H3_GGUF_REPO, qwen),
- (H3_LEGACY_COMPONENT_REPO, H3_VIDEO_VAE),
- (H3_COMPONENT_REPO, H3_AUDIO_VAE),
- )
- assert dict(h3_native_hub_files(gguf))[H3_LEGACY_COMPONENT_REPO] == H3_VIDEO_VAE
-
- # And with a local bundle carrying the other one, nothing is left for the network at all.
- bundle = tmp_path / "MiniMax-H3-GGUF"
- (bundle / "vae").mkdir(parents = True)
- for name in (gguf, qwen, H3_AUDIO_VAE):
- (bundle / name).write_bytes(b"x")
- assert VideoBackend._h3_native_requests(str(bundle), gguf, qwen) == (
- (str(bundle), gguf),
- (str(bundle), qwen),
- (H3_LEGACY_COMPONENT_REPO, H3_VIDEO_VAE),
- (str(bundle), H3_AUDIO_VAE),
- )
-
-
-def test_the_plan_sizes_a_cached_repack_from_the_repo_we_control(monkeypatch):
- """A repack that is gone must not fail a plan for a load its own cache still satisfies.
-
- `model_info` on the repack raises once it is renamed or taken down, which is the failure the
- move exists to survive, and one raising call fails the WHOLE native plan: `plan_failed` makes
- every locality-dependent caller (media auto-switch) refuse a load that would have worked. The
- two copies are byte identical, so the size comes from the mirror while the entry keeps the id
- the bytes are read from.
- """
- from core.inference.video_minimax_h3 import (
- H3_AUDIO_VAE,
- H3_LEGACY_COMPONENT_REPO,
- H3_VIDEO_VAE,
- )
-
- _legacy_cache_holding(monkeypatch, {H3_VIDEO_VAE, H3_AUDIO_VAE})
- # Only the mirror answers: asking the repack raises KeyError, exactly as a taken-down repo
- # would raise from the Hub.
- _plan_api(
- monkeypatch,
- {
- "unsloth/MiniMax-H3-GGUF": [
- _PlanSibling("minimax_h3_fl2va-Q4_K_M.gguf", 19),
- _PlanSibling("qwen3vl_32b_minimax_h3-Q4_K_M.gguf", 18),
- _PlanSibling(H3_VIDEO_VAE, 5),
- _PlanSibling(H3_AUDIO_VAE, 1),
- ],
- },
- )
-
- plan = VideoBackend._h3_native_download_plan(
- "unsloth/MiniMax-H3-GGUF", "minimax_h3_fl2va-Q4_K_M.gguf", hf_token = None
- )
- assert not plan.get("plan_failed")
- by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
- # The VAEs are staged under the id they will be read from, at the mirror's sizes.
- assert sorted(by_repo[H3_LEGACY_COMPONENT_REPO]["files"]) == sorted(
- [H3_VIDEO_VAE, H3_AUDIO_VAE]
- )
- assert by_repo[H3_LEGACY_COMPONENT_REPO]["bytes"] == 6
- assert plan["required_bytes"] == 43
-
-
def test_the_h3_native_repo_matches_the_family_gguf_repo():
"""The declared pick and the actual download must be the same repo.
@@ -9718,16 +9547,24 @@ def test_plan_keeps_the_bf16_budget_without_a_hosted_pre_cast_encoder(fake_runti
def test_default_load_budgets_the_hosted_encoder_its_family_defaults_to(fake_runtime, monkeypatch):
# An UNSET request on a family with te_quant_auto takes the hosted fp8 encoder, so the plan is
# built from the pre-cast size, exactly as for an explicit fp8; "none" keeps the bf16 budget.
+ # The hosted file has to be CONFIRMED (on disk or listed by the Hub): unconfirmed, the automatic pick falls back to
+ # the dense encoder, so that is what it budgets.
+ import core.inference.diffusion_te_prequant as tpq
from core.inference.video_families import detect_video_family
scale = _allow_te_prequant(monkeypatch)
for repo in ("Wan-AI/Wan2.2-TI2V-5B-Diffusers", "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"):
fam = detect_video_family(repo)
transformer_gb, text_encoder_gb, vae_gb = fam.bf16_components_gb
+ monkeypatch.setattr(tpq, "te_prequant_sources_confirmed", lambda *a, **k: True)
calls = _capture_plan(monkeypatch)
VideoBackend().load_pipeline(repo, model_kind = "pipeline")
assert calls[0]["text_encoder_dense_mib"] == int(
text_encoder_gb * scale * _MIB_PER_GB
), repo
+ monkeypatch.setattr(tpq, "te_prequant_sources_confirmed", lambda *a, **k: False)
+ calls = _capture_plan(monkeypatch)
+ VideoBackend().load_pipeline(repo, model_kind = "pipeline")
+ assert calls[0]["text_encoder_dense_mib"] == int(text_encoder_gb * _MIB_PER_GB), repo
calls = _capture_plan(monkeypatch)
VideoBackend().load_pipeline(repo, model_kind = "pipeline", text_encoder_quant = "none")
assert calls[0]["text_encoder_dense_mib"] == int(text_encoder_gb * _MIB_PER_GB), repo
diff --git a/studio/backend/tests/test_video_h3_te_quant.py b/studio/backend/tests/test_video_h3_te_quant.py
index 493cffac6c9..918ed85c958 100644
--- a/studio/backend/tests/test_video_h3_te_quant.py
+++ b/studio/backend/tests/test_video_h3_te_quant.py
@@ -94,7 +94,7 @@ def test_the_hosted_filename_comes_from_an_unsloth_repo():
assert H3_TE_QUANT_REPO in {repo for _, repo in (h3.prequant_repos or ())}
assert (
h3_te_quant_filename("int8")
- == "text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors"
+ == "text_encoders/official/qwen3vl_32b_minimax_h3_int8_convrot.safetensors"
)
assert h3_te_quant_filename("fp8") is None
assert h3_te_quant_filename(None) is None
@@ -390,17 +390,10 @@ def test_a_resolvable_artifact_is_staged_in_place_of_the_dense_shards():
assert files == [(wanted, 27_141_342_152)]
-def test_the_conditioner_entry_survives_a_repack_that_is_gone(monkeypatch):
- """A cached artifact must keep its entry even when the repo it is cached under is unreachable.
-
- Once the repack is renamed or taken down, a `model_info` against it raises and this reports no
- hosted artifact. The plan then stages the 62 GB dense `text_encoder/` shards, while the load,
- reading the artifact straight out of that same cache, never opens them: a whole download
- wasted, or a disk preflight refusing a load that fits. So the SIZE comes from the mirror and
- only the entry id follows the cache.
- """
+def test_the_conditioner_never_comes_from_the_comfy_repack(monkeypatch):
+ """Even with the Comfy-Org repack holding the artifact in cache, the entry, its size and its bytes all come from
+ unsloth/MiniMax-H3-FP8: a video load never reads from a Comfy repo."""
from core.inference import diffusion_families
- from core.inference.video_minimax_h3_te import H3_LEGACY_TE_QUANT_REPO
wanted = h3_te_quant_filename("int8")
monkeypatch.setattr(diffusion_families, "_upstream_is_cached", lambda *a, **k: True)
@@ -410,17 +403,13 @@ def test_the_conditioner_entry_survives_a_repack_that_is_gone(monkeypatch):
class _Api:
def model_info(self, repo_id, **_kwargs):
asked.append(repo_id)
- if repo_id != H3_TE_QUANT_REPO:
- raise RuntimeError(f"{repo_id} is gone")
return types.SimpleNamespace(
siblings = [types.SimpleNamespace(rfilename = wanted, size = 27_141_342_152)]
)
repo, files = VideoBackend._h3_te_quant_hub_files("int8", _Api())
- assert asked == [H3_TE_QUANT_REPO], "the repack must never be asked for metadata"
- # The id the bytes are read from, so the entry's cache check asks about the right repo...
- assert repo == H3_LEGACY_TE_QUANT_REPO
- # ...at the mirror's size, which is the same file.
+ assert asked == [H3_TE_QUANT_REPO]
+ assert repo == H3_TE_QUANT_REPO
assert files == [(wanted, 27_141_342_152)]
diff --git a/studio/backend/tests/test_video_ltx25_te_hosted.py b/studio/backend/tests/test_video_ltx25_te_hosted.py
index b11b982596d..9ee14d8da26 100644
--- a/studio/backend/tests/test_video_ltx25_te_hosted.py
+++ b/studio/backend/tests/test_video_ltx25_te_hosted.py
@@ -337,6 +337,27 @@ def test_hosted_path_resolves_a_copy_under_the_other_cache_root(tmp_path, monkey
assert Path(worker._hosted_path(spec, common)) == mine
+def test_hosted_path_ignores_the_base_revision(tmp_path, monkeypatch):
+ # ``common`` carries the BASE repo's planned commit; the hosted file lives in unsloth/LTX-2.5-FP8, where that
+ # commit does not exist, so it must be read at the hosted repo's own ref.
+ import huggingface_hub.constants as hub_constants
+
+ repo, filename = "unsloth/LTX-2.5-FP8", "LTX-2.5-text_encoder-INT8-ConvRot.safetensors"
+ root = tmp_path / "cache"
+ staged = _hf_cache_entry(root, repo, filename, b"hosted")
+ monkeypatch.setattr(hub_constants, "HF_HUB_CACHE", str(root))
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ spec = {"repo": repo, "filename": filename, "mirror_path": None}
+ common = {
+ "token": None,
+ "cache_dir": str(root),
+ "local_files_only": True,
+ "revision": "f" * 40,
+ }
+ assert Path(worker._hosted_path(spec, common)).read_bytes() == staged.read_bytes()
+ assert common["revision"] == "f" * 40
+
+
def test_builder_drops_a_tied_lm_head(tmp_path, monkeypatch):
import build_ltx25_te_int8_convrot as builder
diff --git a/studio/backend/tests/test_video_offline_load.py b/studio/backend/tests/test_video_offline_load.py
index 0312e40ab11..8931994a25c 100644
--- a/studio/backend/tests/test_video_offline_load.py
+++ b/studio/backend/tests/test_video_offline_load.py
@@ -138,8 +138,12 @@ def test_a_user_initiated_load_still_calls_every_one_of_them(monkeypatch, tmp_pa
assert backend._loading is None, getattr(backend._loading, "error", None)
assert seen.get("local_files_only") in (False, None)
- # The byte estimate probes the checkpoint repo and the base; the base prefetch probes it again.
- assert WAN_GGUF in calls.model_info and WAN_BASE in calls.model_info
+ # The byte estimate probes the checkpoint repo and the base; the base prefetch probes it again. The base's sizes
+ # are read from its byte-identical unsloth mirror, so the listing never leaves unsloth/*.
+ from core.inference.diffusion_families import mirror_repo
+
+ assert WAN_GGUF in calls.model_info and mirror_repo(WAN_BASE) in calls.model_info
+ assert WAN_BASE not in calls.model_info
# And the checkpoint is FETCHED, not looked up.
assert calls.downloads == [(WAN_GGUF, WAN_FILE, False)]
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 1162612a875..f4e8b36ca7c 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -256,6 +256,14 @@ class _FakeBackend(video_module.VideoBackend):
}
[email protected](autouse = True)
+def _pin_video_fetch_to_the_named_repo(monkeypatch):
+ """These tests are about plan / load decisions, written against the UPSTREAM ids their fake Hub serves. The fetch
+ swap onto the unsloth mirrors depends on the developer's own HF cache, so it is pinned off here, as the image
+ offline-load tests do; tests/test_video_unsloth_mirrors.py covers the swap itself."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+
+
@pytest.fixture(autouse = True)
def _healthy_diffusers(healthy_diffusers):
"""These tests are about the route, not about the runner's diffusers.
diff --git a/studio/backend/tests/test_video_unsloth_mirrors.py b/studio/backend/tests/test_video_unsloth_mirrors.py
new file mode 100644
index 00000000000..61c34a66838
--- /dev/null
+++ b/studio/backend/tests/test_video_unsloth_mirrors.py
@@ -0,0 +1,1361 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every component a VIDEO load fetches comes from an unsloth/* repo.
+
+The video families name vendor bases (Wan-AI, Lightricks, MiniMaxAI) as their logical identity; the fetch sites swap
+each for the existing unsloth repo that carries its official files byte-identical at upstream paths (the model's -FP8
+repo, or -GGUF; diffusion_families._VIDEO_MIRROR_PAIRS) exactly as the image side does. Only a licence-blocked repo,
+or a model with no unsloth repo at all, may stay outside unsloth/*.
+"""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+from core.inference import video as video_mod
+from core.inference import video_families as vf
+from core.inference.diffusion_families import (
+ _GATED_MIRROR_PAIRS,
+ _MIRROR_PAIRS,
+ _UNGATED_MIRROR_PAIRS,
+ _VIDEO_GATED_MIRROR_PAIRS,
+ _VIDEO_MIRROR_PAIRS,
+ _VIDEO_UNGATED_MIRROR_PAIRS,
+ canonical_base,
+ mirror_repo,
+ prefer_cached_legacy_source,
+ prefer_ungated_mirror,
+ upstream_is_gated,
+)
+
+# The ONLY ids a video load may fetch from outside unsloth/*, each with the licence clause that blocks a mirror.
+# HunyuanVideo-1.5 (Tencent Hunyuan Community License): "THIS LICENSE AGREEMENT DOES NOT APPLY IN THE EUROPEAN UNION,
+# UNITED KINGDOM AND SOUTH KOREA AND IS EXPRESSLY LIMITED TO THE TERRITORY" and "You must not use, reproduce, modify,
+# distribute, or display the Tencent Hunyuan Works ... outside the Territory". A public Hub repo cannot honour that.
+LICENCE_BLOCKED = frozenset(
+ {
+ "hunyuanvideo-community/hunyuanvideo-1.5-diffusers-480p_t2v",
+ "hunyuanvideo-community/hunyuanvideo-1.5-diffusers-720p_t2v",
+ }
+)
+
+# No unsloth repo exists for these (no -FP8, no -GGUF), so nothing can carry their files yet.
+NO_UNSLOTH_REPO = frozenset(
+ {
+ "wan-ai/wan2.1-t2v-1.3b-diffusers",
+ "wan-ai/wan2.1-t2v-14b-diffusers",
+ }
+)
+
+EXPECTED_VIDEO_PAIRS = {
+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers": "unsloth/Wan2.2-TI2V-5B-FP8",
+ "Wan-AI/Wan2.2-T2V-A14B-Diffusers": "unsloth/Wan2.2-T2V-A14B-FP8",
+ "Lightricks/LTX-2": "unsloth/LTX-2-FP8",
+ "Lightricks/LTX-2.3": "unsloth/LTX-2.3-FP8",
+ "Lightricks/LTX-2.5-Diffusers": "unsloth/LTX-2.5-FP8",
+ "Lightricks/LTX-2.5": "unsloth/LTX-2.5-GGUF",
+ "MiniMaxAI/MiniMax-H3": "unsloth/MiniMax-H3",
+}
+
+
+def empty_cache(monkeypatch, tmp_path):
+ """A fresh install: nothing cached under any id, mirrors enabled."""
+ monkeypatch.setattr("utils.hf_cache_settings.active_hf_hub_cache", lambda: str(tmp_path))
+ import huggingface_hub.constants as hub_constants
+
+ monkeypatch.setattr(hub_constants, "HF_HUB_CACHE", str(tmp_path / "other"))
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)
+ return tmp_path
+
+
+def test_video_mirror_pairs_round_trip(empty_cache):
+ assert dict(_VIDEO_MIRROR_PAIRS) == EXPECTED_VIDEO_PAIRS
+ for upstream, mirror in _VIDEO_MIRROR_PAIRS:
+ assert mirror.startswith("unsloth/")
+ assert mirror_repo(upstream) == mirror
+ assert mirror_repo(upstream.lower()) == mirror
+ assert canonical_base(mirror) == upstream
+ assert canonical_base(mirror.upper()) == upstream
+ assert prefer_ungated_mirror(upstream) == mirror
+ assert video_mod._video_fetch_repo(upstream) == mirror
+ for upstream, _mirror in _VIDEO_GATED_MIRROR_PAIRS:
+ assert upstream_is_gated(upstream)
+ for upstream, _mirror in _VIDEO_UNGATED_MIRROR_PAIRS:
+ assert not upstream_is_gated(upstream)
+
+
+def test_video_mirror_opt_out_keeps_upstream(empty_cache, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ for upstream, mirror in _VIDEO_MIRROR_PAIRS:
+ assert video_mod._video_fetch_repo(upstream) == upstream
+ assert video_mod._video_fetch_repo(mirror) == upstream
+ assert video_mod._video_listing_repo(upstream) == upstream
+
+
+def test_video_pairs_stay_out_of_the_image_companion_table():
+ """The image companion table (companion_assets reads it) is unchanged; video ids only feed the id lookups."""
+ image_ids = {rid.lower() for pair in _MIRROR_PAIRS for rid in pair}
+ assert not image_ids & {rid.lower() for pair in _VIDEO_MIRROR_PAIRS for rid in pair}
+ assert len(_MIRROR_PAIRS) == len(_GATED_MIRROR_PAIRS) + len(_UNGATED_MIRROR_PAIRS) == 32
+
+
+def _video_fetch_ids() -> dict[str, str]:
+ """Every Hub id a video load can fetch from, mapped to where it came from."""
+ from core.inference import video_ltx2, video_ltx25, video_minimax_h3, video_minimax_h3_te
+
+ ids: dict[str, str] = {}
+ for fam in vf._FAMILIES:
+ ids[fam.base_repo] = f"{fam.name}.base_repo"
+ if fam.gguf_repo:
+ ids[fam.gguf_repo] = f"{fam.name}.gguf_repo"
+ for _scheme, repo in fam.prequant_repos:
+ ids[repo] = f"{fam.name}.prequant_repos"
+ for base, _scheme, repo in fam.prequant_variant_repos:
+ ids[base] = f"{fam.name}.prequant_variant_repos(base)"
+ ids[repo] = f"{fam.name}.prequant_variant_repos"
+ for _scheme, _component, repo in fam.te_prequant_repos:
+ ids[repo] = f"{fam.name}.te_prequant_repos"
+ ids[video_ltx2.LTX23_PREQUANT_BASE] = "video_ltx2.LTX23_PREQUANT_BASE"
+ ids[video_ltx2.LTX23_EXTRAS_REPO] = "video_ltx2.LTX23_EXTRAS_REPO"
+ ids[video_ltx25.LTX25_SINGLE_FILE_REPO] = "video_ltx25.LTX25_SINGLE_FILE_REPO"
+ ids[video_minimax_h3.H3_GGUF_REPO] = "video_minimax_h3.H3_GGUF_REPO"
+ ids[video_minimax_h3.H3_COMPONENT_REPO] = "video_minimax_h3.H3_COMPONENT_REPO"
+ ids[video_minimax_h3_te.H3_TE_QUANT_REPO] = "video_minimax_h3_te.H3_TE_QUANT_REPO"
+ return ids
+
+
+def test_every_video_fetch_id_resolves_to_unsloth(empty_cache):
+ """Walks the video family table: any fetch id that does not land on unsloth/* fails, bar the licence-blocked."""
+ offenders = {}
+ for rid, where in _video_fetch_ids().items():
+ fetched = prefer_cached_legacy_source(video_mod._video_fetch_repo(rid) or rid)
+ if fetched.lower().startswith("unsloth/"):
+ continue
+ if rid.lower() in LICENCE_BLOCKED | NO_UNSLOTH_REPO:
+ continue
+ offenders[rid] = (where, fetched)
+ assert offenders == {}
+
+
+def test_licence_blocked_allowlist_is_exact(empty_cache):
+ """The allowlist names only what the table still fetches from outside unsloth/*: a stale entry fails here."""
+ outside = {
+ rid.lower()
+ for rid in _video_fetch_ids()
+ if not (video_mod._video_fetch_repo(rid) or rid).lower().startswith("unsloth/")
+ }
+ assert outside == LICENCE_BLOCKED | NO_UNSLOTH_REPO
+
+
+def test_prequant_tables_fold_a_mirror_onto_its_upstream():
+ """The loaders now receive the mirror id; the variant tables are keyed on the upstream."""
+ for upstream, mirror in _VIDEO_MIRROR_PAIRS:
+ assert vf._prequant_base_key(mirror) == vf._prequant_base_key(upstream) == upstream.lower()
+ for fam in vf._FAMILIES:
+ for base, scheme, repo in fam.prequant_variant_repos:
+ mirror = mirror_repo(base)
+ if mirror:
+ assert vf.video_family_prequant_repo(
+ fam, scheme, mirror
+ ) == vf.video_family_prequant_repo(fam, scheme, base)
+
+
+def test_ltx25_single_file_release_recognised_under_its_mirror():
+ from core.inference.video_ltx25 import is_ltx25_single_file_base
+
+ assert is_ltx25_single_file_base("Lightricks/LTX-2.5")
+ assert is_ltx25_single_file_base("unsloth/LTX-2.5-GGUF")
+ assert not is_ltx25_single_file_base("unsloth/LTX-2.5-FP8")
+
+
+def test_a_gguf_pick_from_the_ltx25_gguf_repo_keeps_the_diffusers_base():
+ """That repo now also carries the split release's files, but a GGUF picked from it is still a pack load."""
+ from core.inference.video_families import detect_video_family, resolve_video_base_repo
+ from core.inference.video_ltx25 import is_ltx25_single_file_base, ltx25_default_base
+
+ assert ltx25_default_base("unsloth/LTX-2.5-GGUF") is None
+ assert not is_ltx25_single_file_base("unsloth/LTX-2.5-GGUF", fold_mirror = False)
+ fam = detect_video_family("unsloth/LTX-2.5-GGUF")
+ assert (
+ resolve_video_base_repo(fam, None, "unsloth/LTX-2.5-GGUF") == "Lightricks/LTX-2.5-Diffusers"
+ )
+ # A DiT picked from the official single-file release still assembles from that release.
+ assert ltx25_default_base("Lightricks/LTX-2.5") == "Lightricks/LTX-2.5"
+
+
+def test_the_fp8_repos_still_resolve_their_own_prequant_rows():
+ """The -FP8 repos are both a hosted-checkpoint repo and now a base's file carrier: folding their id onto the
+ upstream base must not change which checkpoint repo a scheme resolves to."""
+ for fam in vf._FAMILIES:
+ for scheme, repo in fam.prequant_repos:
+ assert vf.video_family_prequant_repo(
+ fam, scheme, fam.base_repo
+ ) == vf.video_family_prequant_repo(
+ fam, scheme, mirror_repo(fam.base_repo) or fam.base_repo
+ )
+
+
+def test_no_video_fetch_reads_a_comfy_or_third_party_repack(tmp_path, monkeypatch):
+ """Even with the old Comfy-Org / QuantStack repack fully cached, the H3 VAEs, the H3 conditioner and the Wan GGUFs
+ come from unsloth/*."""
+ from core.inference.diffusion_families import legacy_source_repo
+ from core.inference.video_minimax_h3 import H3_AUDIO_VAE, H3_VIDEO_VAE, h3_component_source
+ from core.inference.video_minimax_h3_te import h3_te_quant_source
+
+ monkeypatch.setattr(
+ "core.inference.diffusion_families._upstream_is_cached", lambda *_a, **_k: True
+ )
+ for repo in (
+ "unsloth/MiniMax-H3-GGUF",
+ "unsloth/MiniMax-H3-FP8",
+ "unsloth/Wan2.2-TI2V-5B-GGUF",
+ ):
+ assert legacy_source_repo(repo) is None
+ assert prefer_cached_legacy_source(repo, ("x.safetensors",)) == repo
+ assert (
+ h3_component_source(H3_VIDEO_VAE)
+ == h3_component_source(H3_AUDIO_VAE)
+ == "unsloth/MiniMax-H3-GGUF"
+ )
+ assert h3_te_quant_source("int8") == "unsloth/MiniMax-H3-FP8"
+ from core.inference import video_minimax_h3, video_minimax_h3_te
+
+ assert not hasattr(video_minimax_h3, "H3_LEGACY_COMPONENT_REPO")
+ assert not hasattr(video_minimax_h3_te, "H3_LEGACY_TE_QUANT_REPO")
+
+
+def test_ltx23_official_file_is_eligible_from_its_mirror():
+ from core.inference.video_ltx2 import LTX23_PREQUANT_SOURCE_REPOS
+ assert "unsloth/ltx-2.3-fp8" in LTX23_PREQUANT_SOURCE_REPOS
+
+
+def _sib(name, size):
+ return types.SimpleNamespace(rfilename = name, size = size, lfs = None, blob_id = None)
+
+
+class _RecordingApi:
+ calls: list = []
+
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo,
+ files_metadata = True,
+ **_kw,
+ ):
+ type(self).calls.append(repo)
+ return types.SimpleNamespace(
+ sha = "0" * 40,
+ siblings = [
+ _sib("model_index.json", 1),
+ _sib("scheduler/scheduler_config.json", 1),
+ _sib("vae/config.json", 1),
+ _sib("vae/diffusion_pytorch_model.safetensors", 2),
+ _sib("transformer/config.json", 1),
+ _sib("transformer/diffusion_pytorch_model.safetensors", 3),
+ # The carrier repo's OWN files, which a base load must never stage.
+ _sib("Model-FP8.safetensors", 9),
+ _sib("Model-FP8.pt", 9),
+ _sib("samples/fp8_1.png", 9),
+ ],
+ )
+
+
[email protected]("upstream", ["Wan-AI/Wan2.2-TI2V-5B-Diffusers", "Lightricks/LTX-2"])
+def test_predownload_base_pulls_every_file_from_the_mirror(empty_cache, monkeypatch, upstream):
+ import huggingface_hub
+
+ _RecordingApi.calls = []
+ fetched: list = []
+ names: list = []
+
+ def _download(repo, name, token, **_kw):
+ fetched.append(repo)
+ names.append(name)
+ path = empty_cache / "snap" / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _RecordingApi)
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ backend = video_mod.VideoBackend()
+ root = backend._predownload_base(upstream, None, "pipeline")
+ assert root is not None
+ assert fetched and set(fetched) == {EXPECTED_VIDEO_PAIRS[upstream]}
+ assert set(_RecordingApi.calls) == {EXPECTED_VIDEO_PAIRS[upstream]}
+ assert not {"Model-FP8.safetensors", "Model-FP8.pt", "samples/fp8_1.png"} & set(names)
+
+
+def test_checkpoint_pick_from_a_mirrored_repo_downloads_from_the_mirror(empty_cache, monkeypatch):
+ seen: list = []
+ monkeypatch.setattr(
+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",
+ lambda repo, name, token, **kw: (seen.append(repo), str(empty_cache / name))[1],
+ )
+ video_mod.VideoBackend._resolve_checkpoint_path(
+ "Lightricks/LTX-2.3", "ltx-2.3-22b-dev.safetensors", None
+ )
+ assert seen == ["unsloth/LTX-2.3-FP8"]
+
+
+def test_in_flight_load_claims_both_sides_of_a_mirror_pair():
+ backend = video_mod.VideoBackend()
+ backend._loading = video_mod._VideoLoadingState(
+ repo_id = "unsloth/Wan2.2-TI2V-5B-GGUF", base_repo = "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
+ )
+ ids = backend.loading_repo_ids()
+ assert "Wan-AI/Wan2.2-TI2V-5B-Diffusers" in ids
+ assert "unsloth/Wan2.2-TI2V-5B-FP8" in ids
+
+
+def test_h3_vaes_are_read_from_the_official_provenance_paths():
+ """The vae/ copies came from the Comfy-Org repack; the build reads the vae/official/ files made from MiniMaxAI's
+ weights (byte-identical, so released builds reading vae/ keep working)."""
+ from core.inference.video_minimax_h3 import H3_AUDIO_VAE, H3_VIDEO_VAE
+
+ assert H3_VIDEO_VAE == "vae/official/minimax_h3_video_vae_fp16.safetensors"
+ assert H3_AUDIO_VAE == "vae/official/minimax_h3_audio_vae_fp32.safetensors"
+
+
+def _partial_upstream_cache(root, repo, files):
+ """An upstream snapshot holding ``files`` (some weight, not the whole component set)."""
+ folder = root / ("models--" + repo.replace("/", "--"))
+ (folder / "refs").mkdir(parents = True, exist_ok = True)
+ (folder / "refs" / "main").write_text("a" * 40)
+ for name in files:
+ path = folder / "snapshots" / ("a" * 40) / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"x" * 10)
+ return folder
+
+
+def test_assembly_reads_the_repo_the_predownload_staged(empty_cache, monkeypatch):
+ """A partial upstream cache: the exact-name check stages into the mirror, and that choice reaches assembly
+ (the name-less default would flip back to the partial upstream)."""
+ import huggingface_hub
+
+ upstream = "Lightricks/LTX-2"
+ _partial_upstream_cache(empty_cache, upstream, ["vae/diffusion_pytorch_model.safetensors"])
+ assert (
+ video_mod._video_fetch_repo(upstream) == upstream
+ ) # the default assembly would re-decide to
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _RecordingApi)
+
+ def _download(repo, name, token, **_kw):
+ path = empty_cache / "snap" / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ backend = video_mod.VideoBackend()
+ choice: dict = {}
+ assert backend._predownload_base(upstream, None, "pipeline", fetch_choice = choice)
+ assert choice == {"repo": "unsloth/LTX-2-FP8"}
+
+ # _run_load forwards it, and load_pipeline / the H3 modular loader take it ahead of the name-less default.
+ import inspect
+
+ for fn in (
+ video_mod.VideoBackend.load_pipeline,
+ video_mod.VideoBackend._load_h3_modular_pipeline,
+ ):
+ assert "_base_fetch_repo" in inspect.signature(fn).parameters
+ src = inspect.getsource(video_mod.VideoBackend._run_load)
+ assert 'kwargs["_base_fetch_repo"] = base_fetch_choice.get("repo")' in src
+ assert "fetch_choice = base_fetch_choice" in src
+
+
+def test_no_mirror_keeps_an_explicit_checkpoint_in_its_repo(empty_cache, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")
+ seen: list = []
+ monkeypatch.setattr(
+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",
+ lambda repo, name, token, **kw: (seen.append(repo), str(empty_cache / name))[1],
+ )
+ video_mod.VideoBackend._resolve_checkpoint_path(
+ "unsloth/LTX-2.5-GGUF", "ltx-2.5-Q4_K_M.gguf", None
+ )
+ assert seen == ["unsloth/LTX-2.5-GGUF"]
+ # Base components still fold back onto the upstream under the opt-out.
+ assert video_mod._video_fetch_repo("unsloth/LTX-2.5-FP8") == "Lightricks/LTX-2.5-Diffusers"
+
+
+def test_ltx25_estimate_reads_shard_indexes_from_the_listing_mirror(empty_cache, monkeypatch):
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _RecordingApi)
+ seen: list = []
+
+ def _plan_shards(info, base, hf_token):
+ seen.append(base)
+ return None
+
+ backend = video_mod.VideoBackend()
+ monkeypatch.setattr(backend, "_ltx25_plan_shards", _plan_shards)
+ monkeypatch.setattr(backend, "_te_prequant_hub_files", lambda *a, **k: ())
+ monkeypatch.setattr(backend, "_h3_te_quant_hub_files", lambda *a, **k: ((), ()))
+ backend._estimate_download_bytes(
+ "Lightricks/LTX-2.5-Diffusers", None, "Lightricks/LTX-2.5-Diffusers", None, "pipeline"
+ )
+ assert seen == ["unsloth/LTX-2.5-FP8"]
+
+
+def _snapshot(root, repo, files):
+ """A cached revision of ``repo`` under ``root`` holding ``files`` (name -> bytes)."""
+ folder = root / ("models--" + repo.replace("/", "--"))
+ (folder / "refs").mkdir(parents = True, exist_ok = True)
+ (folder / "refs" / "main").write_text("b" * 40)
+ for name, data in files.items():
+ path = folder / "snapshots" / ("b" * 40) / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(data)
+ return folder
+
+
+_INDEX = (
+ b'{"_class_name": "LTX2Pipeline", "vae": ["diffusers", "AutoencoderKL"],'
+ b' "transformer": ["diffusers", "LTX2Transformer"], "scheduler": ["diffusers", "S"]}'
+)
+_COMPLETE = {
+ "model_index.json": _INDEX,
+ "vae/diffusion_pytorch_model.safetensors": b"v",
+ "transformer/diffusion_pytorch_model.safetensors": b"t",
+ "scheduler/scheduler_config.json": b"{}",
+}
+
+
+def test_nameless_choice_prefers_the_complete_mirror_over_a_partial_upstream(
+ empty_cache, monkeypatch
+):
+ upstream, mirror = "Lightricks/LTX-2", "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _snapshot(
+ empty_cache,
+ upstream,
+ {"model_index.json": _INDEX, "vae/diffusion_pytorch_model.safetensors": b"v"},
+ )
+ _snapshot(empty_cache, mirror, _COMPLETE)
+ # Offline assembly has no names: the complete mirror wins over the partial upstream.
+ assert video_mod._video_fetch_repo(upstream) == mirror
+ # An equally complete upstream keeps being used.
+ _snapshot(empty_cache, upstream, _COMPLETE)
+ assert video_mod._video_fetch_repo(upstream) == upstream
+
+
+def test_a_lone_shard_without_its_index_is_not_a_complete_component(empty_cache, monkeypatch):
+ repo = "Lightricks/LTX-2"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ files = dict(_COMPLETE)
+ del files["transformer/diffusion_pytorch_model.safetensors"]
+ # An interrupted pull: the config and the first of two shards, and never the shard index.
+ files["transformer/config.json"] = b"{}"
+ files["transformer/diffusion_pytorch_model-00001-of-00002.safetensors"] = b"t"
+ _snapshot(empty_cache, repo, files)
+ assert video_mod._video_cached_completeness_detail(repo) == (2, False)
+ files["transformer/diffusion_pytorch_model-00002-of-00002.safetensors"] = b"t"
+ _snapshot(empty_cache, repo, files)
+ assert video_mod._video_cached_completeness_detail(repo) == (3, True)
+
+
+def test_nameless_choice_keeps_a_partial_gated_upstream_off_the_vendor_repo(
+ empty_cache, monkeypatch
+):
+ upstream, mirror = "Lightricks/LTX-2.5-Diffusers", "unsloth/LTX-2.5-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ monkeypatch.setattr(video_mod, "_can_download", lambda: True)
+ partial = {k: v for k, v in _COMPLETE.items() if not k.startswith("transformer/")}
+ _snapshot(empty_cache, upstream, partial)
+ # Online, the missing transformer would come from the gated vendor repo: the mirror serves it instead.
+ assert video_mod._video_fetch_repo(upstream) == mirror
+ # A load that cannot download keeps what is cached (it may read only that part).
+ monkeypatch.setattr(video_mod, "_can_download", lambda: False)
+ assert video_mod._video_fetch_repo(upstream) == upstream
+ # A whole gated upstream is used as before.
+ monkeypatch.setattr(video_mod, "_can_download", lambda: True)
+ _snapshot(empty_cache, upstream, _COMPLETE)
+ assert video_mod._video_fetch_repo(upstream) == upstream
+
+
+def test_h3_index_is_read_from_the_repo_the_base_pull_stages(empty_cache, monkeypatch):
+ upstream, mirror = "MiniMaxAI/MiniMax-H3", "unsloth/MiniMax-H3"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ monkeypatch.setattr(video_mod, "_can_download", lambda: True)
+ index = (
+ b'{"_class_name": "H3", "transformer": ["diffusers", "T"], "vae": ["diffusers", "V"],'
+ b' "text_encoder": ["transformers", "E"]}'
+ )
+ # An older upstream cache holding only its index: the plan stages the mirror, so the mirror's index answers.
+ _snapshot(empty_cache, upstream, {"modular_model_index.json": index})
+ assert video_mod._video_index_repo(upstream) == mirror
+ # Offline with nothing else cached, the upstream's index is all there is.
+ assert video_mod._video_index_repo(upstream, local_files_only = True) == upstream
+ # An upstream holding the whole base (its dense text_encoder skipped by an earlier H3 load) is the base itself.
+ _snapshot(
+ empty_cache,
+ upstream,
+ {
+ "modular_model_index.json": index,
+ "transformer/diffusion_pytorch_model.safetensors": b"t",
+ "vae/diffusion_pytorch_model.safetensors": b"v",
+ },
+ )
+ assert video_mod._video_index_repo(upstream) == upstream
+
+
+def test_offline_ltx23_base_choice_counts_only_the_folders_it_reads(empty_cache, monkeypatch):
+ upstream, mirror = "Lightricks/LTX-2", "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ index = (
+ b'{"_class_name": "LTX2Pipeline", "vae": ["diffusers", "AutoencoderKL"],'
+ b' "transformer": ["diffusers", "LTX2Transformer"], "scheduler": ["diffusers", "S"],'
+ b' "text_encoder": ["transformers", "T"], "tokenizer": ["transformers", "Tok"]}'
+ )
+ # The upstream holds folders 2.3 never reads from the base; the mirror holds the ones it does.
+ _snapshot(
+ empty_cache,
+ upstream,
+ {
+ "model_index.json": index,
+ "vae/diffusion_pytorch_model.safetensors": b"v",
+ "transformer/diffusion_pytorch_model.safetensors": b"t",
+ "scheduler/scheduler_config.json": b"{}",
+ },
+ )
+ _snapshot(
+ empty_cache,
+ mirror,
+ {
+ "model_index.json": index,
+ "scheduler/scheduler_config.json": b"{}",
+ "tokenizer/tokenizer.json": b"{}",
+ "text_encoder/model.safetensors": b"e",
+ },
+ )
+ folders = ("scheduler", "text_encoder", "tokenizer")
+ assert video_mod._video_fetch_repo(upstream) == upstream # the aggregate count
+ assert video_mod._video_offline_base_choice(upstream, folders) == mirror
+ assert video_mod._video_offline_base_choice("someone/no-mirror", folders) is None
+
+
+def test_offline_single_file_base_choice_ignores_the_transformer_it_replaces(
+ empty_cache, monkeypatch
+):
+ upstream, mirror = "Lightricks/LTX-2", "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ # The upstream holds the transformer a GGUF pick replaces and nothing else; the mirror holds the rest.
+ _snapshot(
+ empty_cache,
+ upstream,
+ {
+ "model_index.json": _INDEX,
+ "transformer/diffusion_pytorch_model.safetensors": b"t",
+ "scheduler/scheduler_config.json": b"{}",
+ },
+ )
+ _snapshot(
+ empty_cache,
+ mirror,
+ {
+ "model_index.json": _INDEX,
+ "vae/diffusion_pytorch_model.safetensors": b"v",
+ "scheduler/scheduler_config.json": b"{}",
+ },
+ )
+ assert video_mod._video_fetch_repo(upstream) == upstream # the aggregate count ties
+ assert video_mod._video_offline_base_choice(upstream, skip = ("transformer",)) == mirror
+
+
+def test_the_download_plan_probes_a_cached_upstream_base_at_its_own_snapshot():
+ import inspect
+
+ # The base entry reads the kept upstream snapshot's commit and sizes, as _plan_fetch does for the load.
+ assert "_cached_snapshot_plan(fetch_base, [n for n, _ in base_files])" in inspect.getsource(
+ video_mod
+ )
+
+
+def test_named_choice_reuses_an_upstream_complete_in_the_fallback_root(empty_cache):
+ upstream = "Lightricks/LTX-2"
+ _snapshot(empty_cache / "other", upstream, _COMPLETE)
+ names = list(_COMPLETE)
+ assert video_mod._video_fetch_repo(upstream, files = names) == upstream
+ assert (
+ video_mod._video_fetch_repo(upstream, files = names + ["missing.safetensors"])
+ == "unsloth/LTX-2-FP8"
+ )
+
+
+def test_h3_staging_index_is_read_from_the_mirror(empty_cache, monkeypatch):
+ seen: list = []
+
+ def _download(repo, name, token, **_kw):
+ seen.append(repo)
+ path = empty_cache / name
+ path.write_text(
+ '{"text_encoder": ["x", "Y", {"pretrained_model_name_or_path": "MiniMaxAI/MiniMax-H3"}]}'
+ )
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ assert (
+ video_mod.VideoBackend._h3_te_base_index_source("MiniMaxAI/MiniMax-H3", None)
+ == "MiniMaxAI/MiniMax-H3"
+ )
+ assert seen == ["unsloth/MiniMax-H3"]
+
+
+def test_h3_component_specs_follow_the_selected_mirror(empty_cache):
+ spec = lambda src, sub = None: types.SimpleNamespace( # noqa: E731
+ pretrained_model_name_or_path = src, subfolder = sub, type_hint = object
+ )
+ pipe = types.SimpleNamespace(
+ _component_specs = {
+ "transformer": spec("MiniMaxAI/MiniMax-H3", "transformer"),
+ "vae": spec("MiniMaxAI/MiniMax-H3", "vae"),
+ "text_encoder": spec("someone/other-encoder", "text_encoder"),
+ "scheduler": spec("unsloth/MiniMax-H3", "scheduler"),
+ }
+ )
+ got = video_mod._h3_mirrored_component_sources(
+ pipe, "MiniMaxAI/MiniMax-H3", "unsloth/MiniMax-H3", local_files_only = False
+ )
+ assert got == {"transformer": "unsloth/MiniMax-H3", "vae": "unsloth/MiniMax-H3"}
+ # An upstream kept for its complete cache, or a local base, redirects nothing.
+ assert not video_mod._h3_mirrored_component_sources(
+ pipe, "MiniMaxAI/MiniMax-H3", str(empty_cache), local_files_only = False
+ )
+
+
+def test_h3_components_open_from_a_snapshot_staged_under_another_cache_root(tmp_path):
+ spec = lambda src, sub = None: types.SimpleNamespace( # noqa: E731
+ pretrained_model_name_or_path = src, subfolder = sub, type_hint = object
+ )
+ pipe = types.SimpleNamespace(
+ _component_specs = {
+ "transformer": spec("MiniMaxAI/MiniMax-H3", "transformer"),
+ "scheduler": spec("unsloth/MiniMax-H3", "scheduler"),
+ "text_encoder": spec("someone/other-encoder", "text_encoder"),
+ }
+ )
+ staged = str(tmp_path / "other_root" / "snapshots" / "abc")
+ got = video_mod._h3_mirrored_component_sources(
+ pipe,
+ "MiniMaxAI/MiniMax-H3",
+ "unsloth/MiniMax-H3",
+ local_files_only = False,
+ staged_dir = staged,
+ )
+ # Either side of the mirror pair reads the reused snapshot; a derivative's own encoder keeps its source.
+ assert got == {"transformer": staged, "scheduler": staged}
+ assert video_mod._is_under_dir(str(tmp_path / "a" / "b"), str(tmp_path / "a"))
+ assert not video_mod._is_under_dir(staged, str(tmp_path / "live"))
+
+
+def test_h3_modular_load_passes_the_mirrored_sources_to_load_components():
+ import inspect
+
+ src = inspect.getsource(video_mod.VideoBackend._load_h3_modular_pipeline)
+ assert "_h3_mirrored_component_sources(" in src
+ assert src.index("_h3_mirrored_component_sources(") < src.index("pipe.load_components(")
+
+
+def test_a_pipeline_load_of_the_ltx25_carrier_is_refused():
+ with pytest.raises(ValueError, match = "single files"):
+ video_mod._detect_load_family("unsloth/LTX-2.5-GGUF", None, None, None, "pipeline")
+ with pytest.raises(ValueError, match = "single files"):
+ video_mod._detect_load_family("Lightricks/LTX-2.5", None, None, None, "pipeline")
+
+
+# ── the load's fetch plan: one immutable record per role, read by every fetch site and by progress ────────────────
+
+
+def _blob(
+ root,
+ repo,
+ key,
+ data,
+ incomplete = False,
+):
+ folder = root / ("models--" + repo.replace("/", "--")) / "blobs"
+ folder.mkdir(parents = True, exist_ok = True)
+ (folder / (key + (".incomplete" if incomplete else ""))).write_bytes(data)
+
+
+def _plan(
+ repo,
+ files,
+ revision = None,
+):
+ return video_mod._PlannedFetch(repo, revision, tuple(files))
+
+
+def _progress_of(backend, plan, expected):
+ backend._loading = video_mod._VideoLoadingState(
+ repo_id = "x/ckpt", base_repo = "x/base", expected_bytes = expected
+ )
+ backend._loading.fetch_plan = plan
+ return backend.load_progress()
+
+
+def test_progress_reads_planned_files_by_blob_key_in_the_plan_repo(empty_cache, monkeypatch):
+ upstream, mirror = "Lightricks/LTX-2", "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _blob(
+ empty_cache, upstream, "k-vae", b"u" * 30
+ ) # a partial upstream cache the load does not read
+ _blob(empty_cache, mirror, "k-carrier-fp8", b"c" * 900) # the carrier's own root checkpoint
+ _blob(
+ empty_cache, mirror, "k-old-transformer", b"o" * 50
+ ) # a superseded revision's same-named file
+ _blob(
+ empty_cache, mirror, "k-unrelated", b"z" * 500, incomplete = True
+ ) # an abandoned unrelated partial
+ _blob(empty_cache, mirror, "k-index", b"i" * 2)
+ _blob(
+ empty_cache, mirror, "k-transformer", b"t" * 7, incomplete = True
+ ) # the planned shard, in flight
+ plan = {
+ "base": _plan(
+ mirror,
+ [
+ ("model_index.json", "k-index", 2),
+ ("vae/diffusion_pytorch_model.safetensors", "k-vae", 30),
+ ("transformer/diffusion_pytorch_model.safetensors", "k-transformer", 100),
+ ],
+ )
+ }
+ progress = _progress_of(video_mod.VideoBackend(), plan, 132)
+ assert progress["phase"] == "downloading"
+ assert progress["downloaded_bytes"] == 2 + 7
+
+
+def test_progress_reads_the_fallback_cache_root(empty_cache, monkeypatch):
+ """Fetches pass reuse_other_cache_root; an upstream complete only in the import-time root counts."""
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _blob(empty_cache / "other", "Lightricks/LTX-2", "k-a", b"a" * 40)
+ plan = {"base": _plan("Lightricks/LTX-2", [("a.safetensors", "k-a", 40)])}
+ assert _progress_of(video_mod.VideoBackend(), plan, 40)["phase"] == "finalizing"
+
+
+def test_progress_counts_a_carrier_checkpoint_and_its_mirrored_base_per_role(
+ empty_cache, monkeypatch
+):
+ upstream, carrier = "Wan-AI/Wan2.2-TI2V-5B-Diffusers", "unsloth/Wan2.2-TI2V-5B-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _blob(empty_cache, carrier, "k-fp8", b"c" * 40)
+ _blob(empty_cache, upstream, "k-vae", b"v" * 3)
+ plan = {
+ "checkpoint": _plan(carrier, [("Wan-FP8.safetensors", "k-fp8", 40)]),
+ "base": _plan(upstream, [("vae/diffusion_pytorch_model.safetensors", "k-vae", 3)]),
+ }
+ assert _progress_of(video_mod.VideoBackend(), plan, 1000)["downloaded_bytes"] == 43
+
+
+def test_progress_without_a_blob_key_reads_the_pinned_revision(empty_cache, monkeypatch):
+ mirror = "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _snapshot(empty_cache, mirror, {"model_index.json": b"{}"}) # revision "b" * 40
+ plan_old = {"base": _plan(mirror, [("model_index.json", None, 2)], revision = "a" * 40)}
+ plan_new = {"base": _plan(mirror, [("model_index.json", None, 2)], revision = "b" * 40)}
+ backend = video_mod.VideoBackend()
+ assert _progress_of(backend, plan_old, 100)["downloaded_bytes"] == 0
+ assert _progress_of(backend, plan_new, 100)["downloaded_bytes"] == 2
+
+
+class _KeyedApi(_RecordingApi):
+ revisions: list = []
+
+ def model_info(
+ self,
+ repo,
+ files_metadata = True,
+ revision = None,
+ **_kw,
+ ):
+ type(self).revisions.append(revision)
+ info = super().model_info(repo, files_metadata)
+ for sib in info.siblings:
+ sib.blob_id = "git-" + sib.rfilename
+ if sib.rfilename.endswith(".safetensors"):
+ sib.lfs = types.SimpleNamespace(sha256 = "lfs-" + sib.rfilename)
+ return info
+
+
+def test_estimate_settles_one_plan_per_role(empty_cache, monkeypatch):
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _KeyedApi)
+ backend = video_mod.VideoBackend()
+ monkeypatch.setattr(backend, "_te_prequant_hub_files", lambda *a, **k: ())
+ monkeypatch.setattr(backend, "_h3_te_quant_hub_files", lambda *a, **k: ((), ()))
+ planned: dict = {}
+ backend._estimate_download_bytes(
+ "Lightricks/LTX-2", None, "Lightricks/LTX-2", None, "pipeline", planned_files = planned
+ )
+ base = planned["base"]
+ assert base.repo == "unsloth/LTX-2-FP8" and base.revision == "0" * 40
+ files = {name: (key, size) for name, key, size in base.files}
+ assert files["transformer/diffusion_pytorch_model.safetensors"] == (
+ "lfs-transformer/diffusion_pytorch_model.safetensors",
+ 3,
+ )
+ assert files["model_index.json"] == ("git-model_index.json", 1)
+ assert "Model-FP8.safetensors" not in files
+ # An upstream complete in the cache keeps being read, pinned to its own snapshot (not the mirror listing).
+ _snapshot(empty_cache, "Lightricks/LTX-2", {name: b"x" for name in files})
+ planned.clear()
+ backend._estimate_download_bytes(
+ "Lightricks/LTX-2", None, "Lightricks/LTX-2", None, "pipeline", planned_files = planned
+ )
+ # ...pinned to ITS snapshot's commit, with that snapshot's own sizes (the mirror listing says 3 for the DiT).
+ assert planned["base"].repo == "Lightricks/LTX-2" and planned["base"].revision == "b" * 40
+ sizes = {name: size for name, _key, size in planned["base"].files}
+ assert sizes["transformer/diffusion_pytorch_model.safetensors"] == 1
+
+
+def test_predownload_follows_the_plan_repo_and_revision(empty_cache, monkeypatch):
+ import huggingface_hub
+
+ _KeyedApi.revisions = []
+ monkeypatch.setattr(huggingface_hub, "HfApi", _KeyedApi)
+ calls: list = []
+
+ def _download(
+ repo,
+ name,
+ token,
+ revision = None,
+ **_kw,
+ ):
+ calls.append((repo, revision))
+ path = empty_cache / "snap" / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ backend = video_mod.VideoBackend()
+ choice: dict = {}
+ backend._predownload_base(
+ "Lightricks/LTX-2",
+ None,
+ "pipeline",
+ fetch_choice = choice,
+ fetch_repo = "unsloth/LTX-2-FP8",
+ revision = "c" * 40,
+ )
+ assert calls and set(calls) == {("unsloth/LTX-2-FP8", "c" * 40)}
+ assert _KeyedApi.revisions == ["c" * 40]
+ assert choice == {"repo": "unsloth/LTX-2-FP8", "revision": "c" * 40}
+
+
+def test_a_superseded_worker_cannot_rewrite_the_active_plan(empty_cache, monkeypatch):
+ """Only _run_load writes fetch_plan, under its token check; a fetch site has no way to patch it."""
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _KeyedApi)
+ monkeypatch.setattr(
+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",
+ lambda repo, name, token, **kw: (
+ (empty_cache / "snap" / name).parent.mkdir(parents = True, exist_ok = True),
+ (empty_cache / "snap" / name).write_bytes(b"x"),
+ str(empty_cache / "snap" / name),
+ )[2],
+ )
+ backend = video_mod.VideoBackend()
+ active = {"base": _plan("unsloth/Wan2.2-TI2V-5B-FP8", [("a", "k", 1)])}
+ backend._loading = video_mod._VideoLoadingState(repo_id = "n/new", base_repo = "n/new")
+ backend._loading.fetch_plan = dict(active)
+ backend._predownload_base("Lightricks/LTX-2", None, "pipeline") # the stale worker's base pull
+ assert backend._loading.fetch_plan == active
+ assert not hasattr(video_mod.VideoBackend, "_note_load_fetch_repo")
+
+
+def test_completeness_needs_weights_beside_a_model_config(empty_cache, monkeypatch):
+ """An interrupted upstream pull that left every component's config but no weights does not tie a full mirror."""
+ upstream, mirror = "Lightricks/LTX-2", "unsloth/LTX-2-FP8"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _snapshot(
+ empty_cache,
+ upstream,
+ {
+ "model_index.json": _INDEX,
+ "vae/config.json": b"{}",
+ "transformer/config.json": b"{}",
+ "scheduler/scheduler_config.json": b"{}",
+ },
+ )
+ _snapshot(
+ empty_cache,
+ mirror,
+ {**_COMPLETE, "vae/config.json": b"{}", "transformer/config.json": b"{}"},
+ )
+ assert video_mod._video_cached_completeness(upstream) == 1 # the scheduler alone
+ assert video_mod._video_fetch_repo(upstream) == mirror
+
+
+def test_assembly_opens_the_pinned_checkpoint_and_partner(empty_cache, monkeypatch):
+ seen: list = []
+ monkeypatch.setattr(
+ "utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",
+ lambda repo, name, token, revision = None, **kw: (
+ seen.append((repo, name, revision)),
+ str(empty_cache / name),
+ )[1],
+ )
+ pin = ("unsloth/Wan2.2-T2V-A14B-GGUF", "c" * 40)
+ video_mod.VideoBackend._resolve_checkpoint_path(
+ "unsloth/Wan2.2-T2V-A14B-GGUF", "HighNoise/x-HighNoise-Q4_K_M.gguf", None, fetch = pin
+ )
+ video_mod.VideoBackend._resolve_moe_partner_path(
+ "unsloth/Wan2.2-T2V-A14B-GGUF", "HighNoise/x-HighNoise-Q4_K_M.gguf", None, fetch = pin
+ )
+ assert {(repo, rev) for repo, _name, rev in seen} == {pin}
+ assert len(seen) == 2 and seen[0][1] != seen[1][1]
+
+
+# ── invariant: a load touches the Hub only at the (repo, revision) pairs its own plan names ─────────────────────────
+
+_GGUF_REPO = "unsloth/Wan2.2-TI2V-5B-GGUF"
+_GGUF_FILE = "Wan2.2-TI2V-5B-Q4_K_M.gguf"
+_WAN_UP, _WAN_MIRROR = "Wan-AI/Wan2.2-TI2V-5B-Diffusers", "unsloth/Wan2.2-TI2V-5B-FP8"
+_WAN_FILES = {
+ "model_index.json": 1,
+ "scheduler/scheduler_config.json": 1,
+ "tokenizer/tokenizer.json": 1,
+ "vae/config.json": 1,
+ "vae/diffusion_pytorch_model.safetensors": 2,
+ "text_encoder/config.json": 1,
+ "text_encoder/model.safetensors": 5,
+ "transformer/config.json": 1,
+ "transformer/diffusion_pytorch_model.safetensors": 9,
+}
+
+
+class _HubRecorder:
+ listings: list = []
+ downloads: list = []
+ config_reads: list = []
+ # Repos whose main advances after their first listing (a later unpinned listing sees a new commit).
+ moving: tuple = (_GGUF_REPO,)
+
+ def __init__(self, token = None):
+ pass
+
+ def model_info(
+ self,
+ repo,
+ files_metadata = True,
+ revision = None,
+ **_kw,
+ ):
+ type(self).listings.append((repo, revision))
+ # The checkpoint repo's main advances after the first listing: a re-plan must keep the fetched commit and size.
+ moved = (
+ revision is None
+ and repo in type(self).moving
+ and any(r == repo for r, _ in type(self).listings[:-1])
+ )
+ files = (
+ {_GGUF_FILE: 70 if moved else 7}
+ if repo == _GGUF_REPO
+ else dict(_WAN_FILES, **{"Wan-FP8.safetensors": 99})
+ )
+ return types.SimpleNamespace(
+ sha = revision
+ or (
+ ("h" if moved else "g") * 40 if repo == _GGUF_REPO else ("n" if moved else "m") * 40
+ ),
+ siblings = [
+ types.SimpleNamespace(
+ rfilename = n,
+ size = sz,
+ blob_id = "git-" + n,
+ lfs = types.SimpleNamespace(sha256 = "lfs-" + n),
+ )
+ for n, sz in files.items()
+ ],
+ )
+
+
+def _assembly_config_reads(base, empty_cache, monkeypatch):
+ """The base config reads assembly makes by hub id, through the real readers, recorded as (repo, revision)."""
+ import diffusers
+ import transformers
+
+ from core.inference import (
+ diffusion_comfy_components,
+ diffusion_prequant,
+ video_ltx2,
+ video_ltx25,
+ )
+
+ def _record(
+ repo,
+ *_a,
+ revision = None,
+ **_kw,
+ ):
+ _HubRecorder.config_reads.append((repo, revision))
+ return {}
+
+ monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", staticmethod(_record))
+ monkeypatch.setattr(diffusers.LTX2VideoTransformer3DModel, "load_config", staticmethod(_record))
+ monkeypatch.setattr(diffusers.AutoencoderKL, "load_config", staticmethod(_record))
+ monkeypatch.setattr(
+ "core.inference.diffusion_krea2.remap_rope_parameters", lambda *_a, **_k: None
+ )
+ # encoder + VAE configs (supplied components), a prequant DiT's config, the LTX-2.3 config, an LTX-2.5 companion
+ diffusion_comfy_components._component_class_and_config(
+ "text_encoder",
+ "T5EncoderModel",
+ base = base,
+ hf_token = None,
+ local_files_only = False,
+ cache_dir = None,
+ )
+ diffusion_comfy_components._component_class_and_config(
+ "vae", "AutoencoderKL", base = base, hf_token = None, local_files_only = False, cache_dir = None
+ )
+ diffusion_prequant._load_transformer_config(
+ types.SimpleNamespace(load_config = _record), base, None, None, str(empty_cache / "ckpt")
+ )
+ video_ltx2._LTX23PrequantConfig(base).load_config(base)
+ before = len(_HubRecorder.downloads)
+ video_ltx25.ltx25_companion_path(base, "companion.safetensors", None)
+ _HubRecorder.config_reads.extend((r, rev) for r, rev, _ in _HubRecorder.downloads[before:])
+ # The LTX-2.5 encoder worker is another process: the pin rides in its config.
+ monkeypatch.setattr(video_ltx25, "ensure_text_encoder_sidecar", lambda: str(empty_cache))
+ monkeypatch.setattr(video_ltx25.Ltx25TextEncoderClient, "start", lambda self: None)
+ client = video_ltx25.start_text_encoder(
+ repo = base,
+ hf_token = None,
+ cache_dir = None,
+ local_files_only = False,
+ device = "cpu",
+ dtype = "bfloat16",
+ resident = False,
+ )
+ _HubRecorder.config_reads.append((client.config["repo"], client.config.get("revision")))
+ # The LTX-2.5 DiT's single-file config.
+ import diffusers.loaders.single_file_utils as sfu
+
+ monkeypatch.setattr(sfu, "load_single_file_checkpoint", lambda *_a, **_k: {})
+ monkeypatch.setattr(
+ diffusers.LTX2VideoTransformer3DModel,
+ "from_single_file",
+ staticmethod(
+ lambda _state, config = None, revision = None, **_k: _record(config, revision = revision)
+ ),
+ )
+ video_ltx25.load_ltx25_transformer(
+ str(empty_cache / "dit.safetensors"),
+ base_repo = base,
+ torch_dtype = None,
+ is_gguf = False,
+ hf_token = None,
+ )
+ # The LTX-2.3 DiT's single-file config.
+ video_ltx2.load_ltx23_transformer(
+ {}, base_repo = base, torch_dtype = None, is_gguf = False, hf_token = None
+ )
+
+
+def _walk_a_load(
+ empty_cache,
+ monkeypatch,
+ *,
+ te_fetch_falls_back,
+ predownload_leaves_early = False,
+ carrier_checkpoint = False,
+ top_up = False,
+):
+ import huggingface_hub
+
+ # The assembly stand-in drives the real diffusers config readers; without diffusers the load would record the
+ # ImportError as its error rather than skip.
+ pytest.importorskip("diffusers")
+
+ _HubRecorder.listings, _HubRecorder.downloads, _HubRecorder.config_reads = [], [], []
+ _HubRecorder.moving = (_WAN_MIRROR,) if carrier_checkpoint else (_GGUF_REPO,)
+ monkeypatch.setattr(huggingface_hub, "HfApi", _HubRecorder)
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+
+ def _download(
+ repo,
+ name,
+ token,
+ revision = None,
+ **_kw,
+ ):
+ _HubRecorder.downloads.append((repo, revision, name))
+ path = empty_cache / "dl" / repo.replace("/", "--") / (revision or "main") / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ # The upstream already holds every base file EXCEPT the dense encoder weights: enough for the reduced plan only.
+ _snapshot(
+ empty_cache, _WAN_UP, {n: b"x" for n in _WAN_FILES if n != "text_encoder/model.safetensors"}
+ )
+ backend = video_mod.VideoBackend()
+ # The estimate expects a hosted pre-cast encoder; the real fetch then finds it (or falls back).
+ monkeypatch.setattr(backend, "_te_prequant_sources", lambda *a, **k: {"text_encoder": object()})
+ monkeypatch.setattr(backend, "_te_prequant_hub_files", lambda *a, **k: {"text_encoder": []})
+ monkeypatch.setattr(
+ backend,
+ "_fetch_te_prequant",
+ lambda *a, **k: () if te_fetch_falls_back else ("text_encoder",),
+ )
+ monkeypatch.setattr(video_mod, "_assert_pick_is_not_speech", lambda *a, **k: None)
+ captured: dict = {}
+
+ def _assemble(**kwargs):
+ captured.update(kwargs)
+ # What assembly does with the plan: re-open the checkpoint where the prefetch pinned it.
+ import inspect
+
+ pin = (
+ {"fetch": kwargs.get("_checkpoint_fetch")}
+ if "fetch" in inspect.signature(backend._resolve_checkpoint_path).parameters
+ else {}
+ )
+ backend._resolve_checkpoint_path(kwargs["repo_id"], kwargs["gguf_filename"], None, **pin)
+ _assembly_config_reads(kwargs["_base_fetch_repo"], empty_cache, monkeypatch)
+ if top_up:
+ # An injection failed: load_pipeline restores the skipped dense weights through this, with its plan.
+ backend._top_up_dense_base(
+ kwargs["base_repo"],
+ None,
+ "single_file",
+ base_local_dir = kwargs.get("_base_local_dir"),
+ fetch_repo = kwargs["_base_fetch_repo"],
+ revision = kwargs["_base_fetch_revision"],
+ local_files_only = False,
+ )
+
+ monkeypatch.setattr(backend, "load_pipeline", _assemble)
+ if predownload_leaves_early:
+ # No scoped pull (a non-diffusers layout, a metadata failure): fetch_choice is never filled.
+ monkeypatch.setattr(backend, "_predownload_base", lambda *a, **k: None)
+ backend._load_token = 1
+ repo_id, filename = (
+ (_WAN_MIRROR, "Wan-FP8.safetensors") if carrier_checkpoint else (_GGUF_REPO, _GGUF_FILE)
+ )
+ backend._loading = video_mod._VideoLoadingState(repo_id = repo_id, base_repo = _WAN_UP)
+ loading = backend._loading
+ backend._run_load(repo_id = repo_id, gguf_filename = filename, _load_token = 1)
+ assert loading.error is None, loading.error
+ captured["_expected_bytes"] = loading.expected_bytes
+ return loading.fetch_plan, captured
+
+
+ "te_fetch_falls_back, predownload_leaves_early", [(False, False), (True, False), (True, True)]
+)
+def test_every_hub_call_of_a_load_matches_its_plan(
+ empty_cache, monkeypatch, te_fetch_falls_back, predownload_leaves_early
+):
+ plan, captured = _walk_a_load(
+ empty_cache,
+ monkeypatch,
+ te_fetch_falls_back = te_fetch_falls_back,
+ predownload_leaves_early = predownload_leaves_early,
+ )
+ pinned = {(p.repo, p.revision) for p in plan.values()}
+ assert {(repo, rev) for repo, rev, _ in _HubRecorder.downloads} <= pinned
+ # Listings are read from the listing repos only (the mirror, never the vendor id), at the plan's commit or before
+ # the plan existed.
+ assert {repo for repo, _ in _HubRecorder.listings} <= {_GGUF_REPO, _WAN_MIRROR}
+ revisions = {p.revision for p in plan.values()} | {None}
+ assert {rev for _, rev in _HubRecorder.listings} <= revisions
+ assert captured["_checkpoint_fetch"] == (plan["checkpoint"].repo, plan["checkpoint"].revision)
+ # The total is exactly what the kept plan sums to, after every re-plan.
+ assert captured["_expected_bytes"] == sum(
+ size for p in plan.values() for _n, _k, size in p.files
+ )
+ # Every base config read during assembly hits the plan's base (repo, revision).
+ assert len(_HubRecorder.config_reads) == 8
+ assert set(_HubRecorder.config_reads) == {(plan["base"].repo, plan["base"].revision)}
+ assert captured["_base_fetch_repo"] == plan["base"].repo
+ assert captured["_base_fetch_revision"] == plan["base"].revision
+ if te_fetch_falls_back:
+ # The dense encoder is back in the pull, which the partial upstream cannot serve: re-planned onto the mirror.
+ assert plan["base"].repo == _WAN_MIRROR and plan["base"].revision == "m" * 40
+ if not predownload_leaves_early:
+ assert any(
+ name == "text_encoder/model.safetensors" for _, _, name in _HubRecorder.downloads
+ )
+ else:
+ assert plan["base"].repo == _WAN_UP and plan["base"].revision == "b" * 40
+ assert plan["checkpoint"] == video_mod._PlannedFetch(
+ _GGUF_REPO, "g" * 40, ((_GGUF_FILE, "lfs-" + _GGUF_FILE, 7),)
+ )
+
+
+def test_the_ltx25_encoder_worker_takes_the_plan_revision(empty_cache, monkeypatch):
+ from core.inference import video_ltx25
+
+ monkeypatch.setattr(video_ltx25, "ensure_text_encoder_sidecar", lambda: str(empty_cache))
+ monkeypatch.setattr(video_ltx25.Ltx25TextEncoderClient, "start", lambda self: None)
+ common = dict(
+ hf_token = None, cache_dir = None, local_files_only = False, device = "cpu", dtype = "bfloat16"
+ )
+ pinned = video_ltx25.start_text_encoder(
+ repo = "unsloth/LTX-2.5-FP8", revision = "r" * 40, resident = False, **common
+ )
+ assert pinned.config["revision"] == "r" * 40
+ unpinned = video_ltx25.start_text_encoder(repo = "unsloth/LTX-2.5-FP8", resident = False, **common)
+ assert "revision" not in unpinned.config
+ import inspect
+
+ src = inspect.getsource(video_mod.VideoBackend.load_pipeline)
+ assert "revision = None if _base_local_dir else _base_fetch_revision" in src
+
+
+def test_an_upstream_split_across_cache_roots_is_not_reused(empty_cache):
+ upstream = "Lightricks/LTX-2"
+ names = list(_COMPLETE)
+ half = len(names) // 2
+ _snapshot(empty_cache, upstream, {n: _COMPLETE[n] for n in names[:half]})
+ _snapshot(empty_cache / "other", upstream, {n: _COMPLETE[n] for n in names[half:]})
+ # Every name is cached, but no ONE root holds the set: assembly could not open it as one snapshot.
+ assert video_mod._video_fetch_repo(upstream, files = names) == "unsloth/LTX-2-FP8"
+
+
+def test_ltx25_shard_indexes_are_read_at_the_listing_commit(empty_cache, monkeypatch):
+ from core.inference import video_ltx25
+
+ seen: list = []
+
+ def _download(
+ repo,
+ name,
+ token,
+ revision = None,
+ **_kw,
+ ):
+ seen.append((repo, name, revision))
+ path = empty_cache / name
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text('{"weight_map": {}}')
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+ monkeypatch.setattr(video_ltx25, "is_ltx25_pack", lambda names: True)
+ info = types.SimpleNamespace(
+ sha = "s" * 40,
+ siblings = [_sib("transformer/diffusion_pytorch_model.safetensors.index.json", 1)],
+ )
+ video_mod.VideoBackend._ltx25_plan_shards(info, "unsloth/LTX-2.5-FP8", None)
+ assert seen == [
+ (
+ "unsloth/LTX-2.5-FP8",
+ "transformer/diffusion_pytorch_model.safetensors.index.json",
+ "s" * 40,
+ )
+ ]
+
+
+def test_expected_total_counts_identical_blobs_once(empty_cache, monkeypatch):
+ plan = {
+ "base": _plan(
+ "unsloth/LTX-2-FP8",
+ [
+ ("a/model.safetensors", "same", 10),
+ ("b/model.safetensors", "same", 10),
+ ("c.json", "other", 1),
+ ],
+ )
+ }
+ assert video_mod._plan_total(plan) == 11
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ _blob(empty_cache, "unsloth/LTX-2-FP8", "same", b"x" * 10)
+ _blob(empty_cache, "unsloth/LTX-2-FP8", "other", b"y")
+ progress = _progress_of(video_mod.VideoBackend(), plan, video_mod._plan_total(plan))
+ assert progress["phase"] == "finalizing"
+
+
[email protected]("te_fetch_falls_back", [False, True])
+def test_roles_sharing_a_repo_share_one_commit(empty_cache, monkeypatch, te_fetch_falls_back):
+ """An FP8 pick from the carrier that also mirrors the base: both roles list that repo once and pin one commit,
+ even though its main moves mid-load."""
+ plan, captured = _walk_a_load(
+ empty_cache,
+ monkeypatch,
+ te_fetch_falls_back = te_fetch_falls_back,
+ carrier_checkpoint = True,
+ )
+ by_repo: dict = {}
+ for entry in plan.values():
+ by_repo.setdefault(entry.repo, set()).add(entry.revision)
+ assert all(len(revs) == 1 for revs in by_repo.values()), by_repo
+ assert plan["checkpoint"].repo == _WAN_MIRROR and plan["checkpoint"].revision == "m" * 40
+ pinned = {(p.repo, p.revision) for p in plan.values()}
+ assert {(repo, rev) for repo, rev, _ in _HubRecorder.downloads} <= pinned
+ assert captured["_expected_bytes"] == video_mod._plan_total(plan)
+
+
+def test_load_pipeline_tops_up_through_the_plan():
+ import inspect
+
+ src = inspect.getsource(video_mod.VideoBackend.load_pipeline)
+ call = src[src.index("self._top_up_dense_base(") :][:600]
+ assert "fetch_repo = _base_fetch_repo" in call and "revision = _base_fetch_revision" in call
+
+
[email protected]("te_fetch_falls_back", [False, True])
+def test_the_dense_top_up_after_a_failed_injection_stays_on_the_plan(
+ empty_cache, monkeypatch, te_fetch_falls_back
+):
+ plan, _captured = _walk_a_load(
+ empty_cache, monkeypatch, te_fetch_falls_back = te_fetch_falls_back, top_up = True
+ )
+ pinned = {(p.repo, p.revision) for p in plan.values()}
+ assert {(repo, rev) for repo, rev, _ in _HubRecorder.downloads} <= pinned
+ # The top-up pulled the whole unskipped set again, from the plan's base repo at its commit.
+ base = (plan["base"].repo, plan["base"].revision)
+ assert (
+ sum(1 for repo, rev, _ in _HubRecorder.downloads if (repo, rev) == base)
+ >= len(_WAN_FILES) - 3
+ )
+
+
+def test_a_cached_upstream_plan_describes_its_own_snapshot(empty_cache, monkeypatch):
+ """The mirror's file changed after the upstream was cached: the plan (and so progress) reads the upstream blob."""
+ upstream = "Lightricks/LTX-2"
+ monkeypatch.setattr(video_mod, "hub_cache_dir", lambda: str(empty_cache))
+ folder = empty_cache / ("models--" + upstream.replace("/", "--"))
+ (folder / "blobs").mkdir(parents = True)
+ (folder / "blobs" / "old-key").write_bytes(b"o" * 12)
+ snap = folder / "snapshots" / ("c" * 40)
+ snap.mkdir(parents = True)
+ (snap / "model.safetensors").symlink_to(folder / "blobs" / "old-key")
+ (folder / "refs").mkdir()
+ (folder / "refs" / "main").write_text("c" * 40)
+ info = types.SimpleNamespace(
+ sha = "m" * 40,
+ siblings = [
+ types.SimpleNamespace(
+ rfilename = "model.safetensors",
+ size = 99,
+ blob_id = None,
+ lfs = types.SimpleNamespace(sha256 = "new-key"),
+ )
+ ],
+ )
+ entry = video_mod._plan_fetch(upstream, "unsloth/LTX-2-FP8", info, ["model.safetensors"], None)
+ assert entry == video_mod._PlannedFetch(
+ upstream, "c" * 40, (("model.safetensors", "old-key", 12),)
+ )
+ assert _progress_of(video_mod.VideoBackend(), {"base": entry}, 12)["phase"] == "finalizing"