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.

Let a hosted pre-cast text encoder be safetensors, not only a pickle (#11454)

Daniel Han0b6bfed88907
diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.py
index c74235533a9..dfa2d022776 100644
--- a/studio/backend/core/inference/diffusion_te_prequant.py
+++ b/studio/backend/core/inference/diffusion_te_prequant.py
@@ -25,6 +25,7 @@ None and the caller falls back to the dense download + cast. Inert with nothing
from __future__ import annotations
+import sys
from dataclasses import dataclass
from typing import Any, Iterable, Optional
@@ -147,18 +148,79 @@ class TePrequantSource:
kind: str
location: str
filename: Optional[str] = None
+ # Names to try after ``filename``, in order, when the repo does not carry it. Only the "repo"
+ # kind uses this: a local path either exists or it does not.
+ fallback_filenames: tuple = ()
-def te_prequant_repo_filename(repo_id: str, component: str, scheme: str) -> str:
- """The checkpoint filename for ``(component, scheme)`` in ``repo_id``: hosted repos are
- named <Model>-FP8 (or -INT8 / -quantized) and carry <Model>-<component>-<SCHEME>.pt
- files, e.g. unsloth/LTX-2-FP8 -> LTX-2-text_encoder-FP8.pt."""
+def te_prequant_repo_stem(repo_id: str, component: str, scheme: str) -> str:
+ """The extensionless checkpoint name for ``(component, scheme)`` in ``repo_id``: hosted repos
+ are named <Model>-FP8 (or -INT8 / -quantized) and carry <Model>-<component>-<SCHEME> files,
+ e.g. unsloth/LTX-2-FP8 -> LTX-2-text_encoder-FP8."""
model = repo_id.rsplit("/", 1)[-1]
for suffix in ("-fp8", "-int8", "-quantized"):
if model.lower().endswith(suffix):
model = model[: -len(suffix)]
break
- return f"{model}-{component}-{scheme.upper()}.pt"
+ return f"{model}-{component}-{scheme.upper()}"
+
+
+def te_prequant_repo_filenames(repo_id: str, component: str, scheme: str) -> tuple:
+ """Candidate filenames for ``(component, scheme)``, safetensors first.
+
+ Both extensions are live. The reader handles either, but the NAME has to be asked for, and a
+ single hardcoded extension is why a hosted safetensors encoder was unreachable: the resolver
+ requested ``.pt``, the Hub returned 404 and the loader fell back to the dense encoder without
+ saying anything, which costs a user the whole point of the artifact (17.5 GB instead of 9.4 GB
+ on Qwen-Image-2.1). Preference order rather than a registry entry, so a repo that swaps its
+ encoder to safetensors is picked up with no code change, and every repo still hosting a
+ ``.pt`` (Qwen-Image, LTX-2 and the rest) keeps resolving exactly as before.
+ """
+ # Imported here, not at module scope: prequant_safetensors pulls torchao in, and this module is
+ # imported during pipeline assembly on hosts that may not have it.
+ from .prequant_safetensors import SAFETENSORS_SUFFIX
+
+ stem = te_prequant_repo_stem(repo_id, component, scheme)
+ return (f"{stem}{SAFETENSORS_SUFFIX}", f"{stem}.pt")
+
+
+def te_prequant_repo_filename(repo_id: str, component: str, scheme: str) -> str:
+ """The preferred checkpoint filename for ``(component, scheme)`` in ``repo_id``."""
+ return te_prequant_repo_filenames(repo_id, component, scheme)[0]
+
+
+def te_candidate_filenames(source: Any) -> tuple:
+ """``source``'s names, best first, for anything SHAPED like a source.
+
+ One accessor so the download PLAN and the resolver cannot disagree about which artifact a
+ source means. They did: the resolver learned the chain while every consumer kept matching
+ ``filename`` alone, so the moment the preferred name became a safetensors spelling no repo
+ hosting a ``.pt`` was recognised by the plan, its dense encoder went back into the pull, and
+ the loader fetched the ``.pt`` on top of it. Planners also pass lightweight stand-ins, so this
+ reads defensively rather than touching the dataclass.
+ """
+ names = (
+ getattr(source, "filename", None),
+ *(getattr(source, "fallback_filenames", None) or ()),
+ )
+ return tuple(n for n in names if n)
+
+
+def te_candidate_is_readable(name: Optional[str]) -> bool:
+ """Whether this install can open a pre-cast encoder artifact called ``name``.
+
+ NOT the transformer's ``restricted_prequant_load_supported``: this state dict is plain
+ tensors, read under a bare ``weights_only`` load with no constructor allowlist, so a ``.pt``
+ is always readable and asking the DiT's question would refuse one on every install whose
+ torchao lacks some DiT scheme's constructors. Only the safetensors container has a
+ requirement, and a plan that drops the dense encoder for an artifact this install cannot open
+ leaves the load with neither.
+ """
+ if not name:
+ return False
+ from .prequant_safetensors import is_safetensors_checkpoint, safetensors_prequant_supported
+
+ return safetensors_prequant_supported() if is_safetensors_checkpoint(name) else True
def family_te_prequant_repo(fam: Any, scheme: str, component: str) -> Optional[str]:
@@ -195,10 +257,12 @@ def resolve_te_prequant_source(
return TePrequantSource(kind = "path", location = override, filename = None)
repo_id = family_te_prequant_repo(fam, scheme, component)
if repo_id:
+ names = te_prequant_repo_filenames(repo_id, component, scheme)
return TePrequantSource(
kind = "repo",
location = repo_id,
- filename = te_prequant_repo_filename(repo_id, component, scheme),
+ filename = names[0],
+ fallback_filenames = names[1:],
)
return None
@@ -501,13 +565,46 @@ def _resolve_checkpoint_path(
return expanded if os.path.isfile(expanded) else None
if source.kind == "repo":
from huggingface_hub import hf_hub_download
- return hf_hub_download(
- repo_id = source.location,
- filename = source.filename,
- token = hf_token,
- cache_dir = cache_dir,
- local_files_only = local_files_only,
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+
+ # Which exception means "this NAME is absent" depends on the mode, and the two are not
+ # interchangeable. huggingface_hub documents LocalEntryNotFoundError as "not on the disk
+ # when network is disabled OR UNAVAILABLE (connection issue). The entry may exist on the
+ # Hub", and it SUBCLASSES EntryNotFoundError, so catching the base online would swallow an
+ # unreachable Hub, spend a second full attempt on the next name, and report that one's
+ # error instead of the connection failure that actually happened. Online, only a real 404
+ # advances; offline, a cache miss is the only verdict there is.
+ miss = (
+ (EntryNotFoundError, LocalEntryNotFoundError)
+ if local_files_only
+ else (EntryNotFoundError,)
)
+ names = [n for n in te_candidate_filenames(source) if te_candidate_is_readable(n)]
+ last: Optional[Exception] = None
+ for name in names:
+ try:
+ return hf_hub_download(
+ repo_id = source.location,
+ filename = name,
+ token = hf_token,
+ cache_dir = cache_dir,
+ local_files_only = local_files_only,
+ )
+ except LocalEntryNotFoundError:
+ # Online this is the Hub being unreachable, not a missing name: re-raise as itself
+ # rather than blaming the next candidate for it.
+ if not local_files_only:
+ raise
+ last = sys.exc_info()[1]
+ continue
+ except miss as exc:
+ # This name is not in this repo. Try the next extension rather than giving up:
+ # only "no candidate exists" is a real miss, and anything else (auth, a corrupt
+ # cache) must still surface as itself.
+ last = exc
+ continue
+ if last is not None:
+ raise last
return None
@@ -574,13 +671,15 @@ def te_prequant_hub_files(
except Exception as exc: # noqa: BLE001 -- unavailable pre-cast means the dense encoder
_warn(logger, f"hub_files:{source.location}", exc)
continue
- files = [
- (s.rfilename, int(getattr(s, "size", 0) or 0))
- for s in (info.siblings or [])
- if s.rfilename == source.filename
- ]
- if files:
- found[component] = files
+ sizes = {s.rfilename: int(getattr(s, "size", 0) or 0) for s in (info.siblings or [])}
+ # The first candidate the repo HOLDS and this install can OPEN, in the resolver's own
+ # order, so the bytes counted here are the bytes that will actually be fetched. Matching
+ # the primary name alone reported every .pt repo as having no pre-cast encoder at all the
+ # moment safetensors became the preferred spelling.
+ for name in te_candidate_filenames(source):
+ if name in sizes and te_candidate_is_readable(name):
+ found[component] = [(name, sizes[name])]
+ break
return found
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index c5401ddd53a..d2c9daafb1e 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -2953,24 +2953,33 @@ class VideoBackend:
Only a component listed here may have its dense weights dropped from a plan or an
estimate: an unpublished / gated / renamed artifact keeps its dense encoder, exactly as
the load's own fallback does. Checked per source so one missing repo cannot sink the
- whole plan."""
- found: dict[str, list[tuple[str, int]]] = {}
- for component, source in sources.items():
- if getattr(source, "kind", None) != "repo" or not getattr(source, "filename", None):
- continue
- try:
- info = api.model_info(source.location, files_metadata = True)
- except Exception as exc: # noqa: BLE001 -- unavailable pre-cast means the dense encoder
- logger.warning("video.te_prequant_unavailable: %s: %s", source.location, exc)
- continue
- files = [
- (s.rfilename, int(s.size or 0))
- for s in (info.siblings or [])
- if s.rfilename == source.filename
- ]
- if files:
- found[component] = files
- return found
+ whole plan.
+
+ Delegated rather than reimplemented. This was a second copy of the image-side logic
+ matching only the PRIMARY name, so the moment the resolver started preferring a
+ safetensors spelling every hosted encoder here read as absent, its dense shards went back
+ into the pull, and the load fetched the .pt on top of them. One implementation is what
+ keeps the plan and the resolver naming the same artifact."""
+ from .diffusion_te_prequant import te_prequant_hub_files
+ return te_prequant_hub_files(sources, api, logger)
+
+ @staticmethod
+ def _te_fetch_miss(exc: BaseException, *, local_files_only: bool) -> bool:
+ """Whether ``exc`` means this NAME is absent, so the next candidate is worth a try.
+
+ ``LocalEntryNotFoundError`` subclasses ``EntryNotFoundError`` and means two different things
+ depending on the mode: offline it is a cache miss, which is the only verdict there is, while
+ online huggingface_hub raises it when the Hub could not be REACHED and the entry may well
+ exist. Mirrors ``diffusion_te_prequant._resolve_checkpoint_path`` on purpose, so the prefetch
+ plan and the load agree about what counts as a miss.
+ """
+ try:
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+ except Exception: # noqa: BLE001 - an unknown hub layout keeps today's behaviour
+ return True
+ if isinstance(exc, LocalEntryNotFoundError):
+ return bool(local_files_only)
+ return isinstance(exc, EntryNotFoundError)
@staticmethod
def _base_download_files(
@@ -3593,24 +3602,44 @@ class VideoBackend:
# the dense download.
if getattr(source, "kind", None) != "repo" or not getattr(source, "filename", None):
continue
- try:
- hf_hub_download_with_xet_fallback(
- source.location,
- source.filename,
- hf_token,
- cancel_event = cancel,
- reuse_other_cache_root = True,
- local_files_only = local_files_only,
- )
- except Exception as exc: # noqa: BLE001 -- no pre-cast file just means the dense encoder
- if cancel.is_set():
- raise
- logger.warning(
- "video.te_prequant_fetch_failed: %s/%s: %s",
- source.location,
- source.filename,
- exc,
- )
+ # Every candidate, in the resolver's order: the preferred name is now a safetensors
+ # spelling most repos do not host, so stopping at it would fail every fetch and report
+ # no skippable component, which is the dense encoder downloaded twice over.
+ from .diffusion_te_prequant import te_candidate_filenames, te_candidate_is_readable
+
+ names = [n for n in te_candidate_filenames(source) if te_candidate_is_readable(n)]
+ got = False
+ for name in names:
+ try:
+ hf_hub_download_with_xet_fallback(
+ source.location,
+ name,
+ hf_token,
+ cancel_event = cancel,
+ reuse_other_cache_root = True,
+ local_files_only = local_files_only,
+ )
+ except Exception as exc: # noqa: BLE001 -- no pre-cast file means the dense encoder
+ if cancel.is_set():
+ raise
+ logger.warning(
+ "video.te_prequant_fetch_failed: %s/%s: %s",
+ source.location,
+ name,
+ exc,
+ )
+ # Advance only on "this NAME is absent", the same distinction the resolver
+ # makes. Anything else (an unreachable Hub, auth, a corrupt cache) is about the
+ # REPO, so trying the next spelling repeats a slow failure and, worse, can
+ # report a legacy artifact as fetched while the loader refuses to advance past
+ # the same error: the plan would then drop the dense encoder and the load would
+ # have neither.
+ if not VideoBackend._te_fetch_miss(exc, local_files_only = local_files_only):
+ break
+ continue
+ got = True
+ break
+ if not got:
continue
fetched.append(component)
return tuple(fetched)
diff --git a/studio/backend/tests/test_diffusion_te_prequant.py b/studio/backend/tests/test_diffusion_te_prequant.py
index d05c840d60d..af972406265 100644
--- a/studio/backend/tests/test_diffusion_te_prequant.py
+++ b/studio/backend/tests/test_diffusion_te_prequant.py
@@ -21,7 +21,7 @@ from core.inference.diffusion_te_prequant import (
family_te_prequant_repo,
resolve_te_prequant_source,
te_prequant_pipe_kwargs,
- te_prequant_repo_filename,
+ te_prequant_repo_filenames,
)
@@ -39,17 +39,18 @@ def _fam(
# ── resolution ───────────────────────────────────────────────────────────────
def test_repo_filename_convention():
- assert (
- te_prequant_repo_filename("unsloth/LTX-2-FP8", "text_encoder", "fp8")
- == "LTX-2-text_encoder-FP8.pt"
+ # safetensors first, the historical pickle second: both are live and the reader takes either.
+ assert te_prequant_repo_filenames("unsloth/LTX-2-FP8", "text_encoder", "fp8") == (
+ "LTX-2-text_encoder-FP8.safetensors",
+ "LTX-2-text_encoder-FP8.pt",
)
- assert (
- te_prequant_repo_filename("org/Some-Model-quantized", "text_encoder_2", "fp8")
- == "Some-Model-text_encoder_2-FP8.pt"
+ assert te_prequant_repo_filenames("org/Some-Model-quantized", "text_encoder_2", "fp8") == (
+ "Some-Model-text_encoder_2-FP8.safetensors",
+ "Some-Model-text_encoder_2-FP8.pt",
)
- assert (
- te_prequant_repo_filename("org/PlainRepo", "text_encoder", "fp8")
- == "PlainRepo-text_encoder-FP8.pt"
+ assert te_prequant_repo_filenames("org/PlainRepo", "text_encoder", "fp8") == (
+ "PlainRepo-text_encoder-FP8.safetensors",
+ "PlainRepo-text_encoder-FP8.pt",
)
@@ -80,7 +81,8 @@ def test_resolve_priority_and_scheme_gate():
# Hosted repo second.
src = resolve_te_prequant_source(fam, "text_encoder", "fp8")
assert src.kind == "repo" and src.location == "org/hosted-fp8"
- assert src.filename == "hosted-text_encoder-FP8.pt"
+ assert src.filename == "hosted-text_encoder-FP8.safetensors"
+ assert src.fallback_filenames == ("hosted-text_encoder-FP8.pt",)
# Nothing configured -> None.
assert resolve_te_prequant_source(_fam(), "text_encoder", "fp8") is None
# v1 hosts the layerwise fp8 storage scheme only.
@@ -88,6 +90,75 @@ def test_resolve_priority_and_scheme_gate():
assert resolve_te_prequant_source(fam, "text_encoder", "fp8_dynamic") is None
+def test_a_hosted_safetensors_encoder_is_asked_for_and_a_pickle_repo_still_resolves(monkeypatch):
+ """The regression this exists for: the resolver only ever asked for ``.pt``.
+
+ A repo hosting the encoder as safetensors then 404'd, and because the loader is best effort the
+ user silently got the dense encoder instead (17.5 GB against 9.4 GB on Qwen-Image-2.1) with no
+ error anywhere. Both extensions have to be reachable, and the repos that still host a pickle
+ have to keep working, so this drives the download path with each in turn.
+ """
+ from huggingface_hub.errors import EntryNotFoundError
+
+ asked = []
+
+ def fake_download(*, repo_id, filename, token, cache_dir, local_files_only):
+ asked.append(filename)
+ if filename not in hosted:
+ raise EntryNotFoundError(f"no {filename} in {repo_id}")
+ return f"/cache/{filename}"
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ src = resolve_te_prequant_source(
+ _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted-fp8"),)),
+ "text_encoder",
+ "fp8",
+ )
+
+ # A safetensors repo is found first, with no wasted request for the pickle.
+ hosted = {"hosted-text_encoder-FP8.safetensors"}
+ asked.clear()
+ assert tpq._resolve_checkpoint_path(src, None, cache_dir = "/cache") == (
+ "/cache/hosted-text_encoder-FP8.safetensors"
+ )
+ assert asked == ["hosted-text_encoder-FP8.safetensors"]
+
+ # A repo that still hosts the pickle resolves through the fallback.
+ hosted = {"hosted-text_encoder-FP8.pt"}
+ asked.clear()
+ assert tpq._resolve_checkpoint_path(src, None, cache_dir = "/cache") == (
+ "/cache/hosted-text_encoder-FP8.pt"
+ )
+ assert asked == ["hosted-text_encoder-FP8.safetensors", "hosted-text_encoder-FP8.pt"]
+
+ # Neither present: the miss surfaces rather than being swallowed into a None the caller
+ # cannot tell apart from "this family hosts nothing".
+ hosted = set()
+ with pytest.raises(EntryNotFoundError):
+ tpq._resolve_checkpoint_path(src, None, cache_dir = "/cache")
+
+
+def test_a_transport_failure_is_not_mistaken_for_a_missing_file(monkeypatch):
+ """Only "this name is not in this repo" may advance to the next candidate.
+
+ An auth failure or a dead network must not be retried as a different extension and then
+ reported as an absent artifact: that would turn a fixable error into a silent 17.5 GB
+ download on every load.
+ """
+
+ def fake_download(*, repo_id, filename, token, cache_dir, local_files_only):
+ raise PermissionError("401 unauthorized")
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", fake_download)
+ src = resolve_te_prequant_source(
+ _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted-fp8"),)),
+ "text_encoder",
+ "fp8",
+ )
+ with pytest.raises(PermissionError):
+ tpq._resolve_checkpoint_path(src, None, cache_dir = "/cache")
+
+
# ── checkpoint validation ────────────────────────────────────────────────────
def _good_ckpt(
scheme = "fp8",
@@ -418,33 +489,33 @@ def test_hosted_te_prequant_entries():
("fp8", "text_encoder", "unsloth/LTX-2-FP8"),
)
# The hosted filenames follow the repo naming convention the resolver derives.
- assert (
- te_prequant_repo_filename("unsloth/Qwen-Image-FP8", "text_encoder", "fp8")
- == "Qwen-Image-text_encoder-FP8.pt"
+ assert te_prequant_repo_filenames("unsloth/Qwen-Image-FP8", "text_encoder", "fp8") == (
+ "Qwen-Image-text_encoder-FP8.safetensors",
+ "Qwen-Image-text_encoder-FP8.pt",
)
- assert (
- te_prequant_repo_filename("unsloth/FLUX.2-dev-FP8", "text_encoder", "fp8")
- == "FLUX.2-dev-text_encoder-FP8.pt"
+ assert te_prequant_repo_filenames("unsloth/FLUX.2-dev-FP8", "text_encoder", "fp8") == (
+ "FLUX.2-dev-text_encoder-FP8.safetensors",
+ "FLUX.2-dev-text_encoder-FP8.pt",
)
- assert (
- te_prequant_repo_filename("unsloth/LTX-2-FP8", "text_encoder", "fp8")
- == "LTX-2-text_encoder-FP8.pt"
+ assert te_prequant_repo_filenames("unsloth/LTX-2-FP8", "text_encoder", "fp8") == (
+ "LTX-2-text_encoder-FP8.safetensors",
+ "LTX-2-text_encoder-FP8.pt",
)
# HiDream's heavyweight is TE4 (Llama-3.1-8B), engaged via hidream_te4_kwargs since the generic pass only covers text_encoder.._3.
assert detect_family("HiDream-ai/HiDream-I1-Full").te_prequant_repos == (
("fp8", "text_encoder_4", "unsloth/HiDream-I1-Full-FP8"),
)
- assert (
- te_prequant_repo_filename("unsloth/HiDream-I1-Full-FP8", "text_encoder_4", "fp8")
- == "HiDream-I1-Full-text_encoder_4-FP8.pt"
+ assert te_prequant_repo_filenames("unsloth/HiDream-I1-Full-FP8", "text_encoder_4", "fp8") == (
+ "HiDream-I1-Full-text_encoder_4-FP8.safetensors",
+ "HiDream-I1-Full-text_encoder_4-FP8.pt",
)
# Round 2: T5-XXL for every flux.1 base (byte-identical, one artifact), Gemma2-2B, Qwen3-4B, Qwen3-VL-4B, and hunyuanimage reusing the Qwen-Image artifact.
assert detect_family("black-forest-labs/FLUX.1-schnell").te_prequant_repos == (
("fp8", "text_encoder_2", "unsloth/FLUX.1-schnell-FP8"),
)
- assert (
- te_prequant_repo_filename("unsloth/FLUX.1-schnell-FP8", "text_encoder_2", "fp8")
- == "FLUX.1-schnell-text_encoder_2-FP8.pt"
+ assert te_prequant_repo_filenames("unsloth/FLUX.1-schnell-FP8", "text_encoder_2", "fp8") == (
+ "FLUX.1-schnell-text_encoder_2-FP8.safetensors",
+ "FLUX.1-schnell-text_encoder_2-FP8.pt",
)
assert detect_family("Alpha-VLLM/Lumina-Image-2.0").te_prequant_repos == (
("fp8", "text_encoder", "unsloth/Lumina-Image-2.0-FP8"),
@@ -809,3 +880,153 @@ def test_an_unrelated_custom_base_still_loses_it(monkeypatch):
assert (
tpq.te_prequant_sources_for_base(fam, base, te_quant_mode = "fp8", target = _target()) == {}
), base
+
+
+def test_the_plan_recognises_the_pt_repos_that_already_exist(monkeypatch):
+ """Preferring safetensors may only ADD a name, and the resolver is not the only reader.
+
+ Every pre-cast encoder repo published so far hosts a ``.pt``. The download plan matched the
+ PRIMARY name alone, so the moment the preferred spelling became safetensors it reported those
+ repos as having no pre-cast encoder: the dense shards went back into the pull AND the loader
+ still fetched the ``.pt``, so the user downloaded both. That is the opposite of what this
+ change is for, and no test covered it because the plan lives beside the resolver, not in it.
+ """
+ src = TePrequantSource(
+ kind = "repo",
+ location = "unsloth/LTX-2-FP8",
+ filename = "LTX-2-text_encoder-FP8.safetensors",
+ fallback_filenames = ("LTX-2-text_encoder-FP8.pt",),
+ )
+
+ class _Sib:
+ def __init__(self, name, size):
+ self.rfilename, self.size = name, size
+
+ class _Api:
+ def __init__(self, files):
+ self._files = files
+
+ def model_info(self, *a, **k):
+ outer = self
+
+ class _I:
+ siblings = outer._files
+
+ return _I()
+
+ def plan(hosted):
+ return tpq.te_prequant_hub_files({"text_encoder": src}, _Api(hosted), None)
+
+ pt, st = "LTX-2-text_encoder-FP8.pt", "LTX-2-text_encoder-FP8.safetensors"
+ # A .pt-only repo: recognised, and sized from the file that will really be fetched.
+ assert plan([_Sib(pt, 9_000_000_000)]) == {"text_encoder": [(pt, 9_000_000_000)]}
+ # A safetensors-only repo: the artifact this change exists for.
+ assert plan([_Sib(st, 9_400_000_000)]) == {"text_encoder": [(st, 9_400_000_000)]}
+ # Both hosted: the preferred one wins, matching the order the resolver downloads in.
+ assert plan([_Sib(pt, 9_000_000_000), _Sib(st, 9_400_000_000)]) == {
+ "text_encoder": [(st, 9_400_000_000)]
+ }
+ # Neither: no pre-cast, so the dense encoder stays in the plan.
+ assert plan([_Sib("unrelated.bin", 1)]) == {}
+
+ # An install that cannot read safetensors takes the pickle rather than planning for a file it
+ # would then refuse, which would leave the load with no encoder at all.
+ monkeypatch.setattr(tpq, "te_candidate_is_readable", lambda n: bool(n) and n.endswith(".pt"))
+ assert plan([_Sib(pt, 9_000_000_000), _Sib(st, 9_400_000_000)]) == {
+ "text_encoder": [(pt, 9_000_000_000)]
+ }
+
+
+def test_the_te_capability_question_is_not_the_transformers_one():
+ """A pre-cast encoder pickle is plain tensors read under a bare ``weights_only`` load, so it
+ needs no constructor allowlist. Asking the DiT's question would refuse a ``.pt`` encoder on
+ every install whose torchao lacks some DiT scheme's constructors."""
+ assert tpq.te_candidate_is_readable("X-text_encoder-FP8.pt") is True
+ assert tpq.te_candidate_is_readable(None) is False
+
+
+def test_the_candidate_accessor_tolerates_a_planner_stand_in():
+ """Planners pass lightweight objects carrying only ``filename``; reading the chain off one
+ must not raise, or the whole pre-cast plan is swallowed into a silent dense fallback."""
+ import types
+
+ assert tpq.te_candidate_filenames(types.SimpleNamespace(filename = "a.pt")) == ("a.pt",)
+ assert tpq.te_candidate_filenames(types.SimpleNamespace()) == ()
+
+
+def test_an_unreachable_hub_is_not_a_missing_filename(monkeypatch):
+ """``LocalEntryNotFoundError`` means two different things and only one of them is a miss.
+
+ huggingface_hub documents it as "not on the disk when network is disabled OR UNAVAILABLE
+ (connection issue). The entry may exist on the Hub", and it SUBCLASSES
+ ``EntryNotFoundError``. Treating it as a candidate miss online spends a second full attempt on
+ the next name and reports that one's error instead of the connection failure that happened.
+ """
+ import huggingface_hub
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+
+ assert issubclass(
+ LocalEntryNotFoundError, EntryNotFoundError
+ ), "if this stops holding the ordering below is no longer load-bearing"
+ src = TePrequantSource(
+ kind = "repo",
+ location = "org/hosted-fp8",
+ filename = "hosted-text_encoder-FP8.safetensors",
+ fallback_filenames = ("hosted-text_encoder-FP8.pt",),
+ )
+ asked: list = []
+
+ def unreachable(**kw):
+ asked.append(kw["filename"])
+ raise LocalEntryNotFoundError("Hub unreachable")
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", unreachable)
+ # ONLINE: surfaces as itself, and the second candidate is never attempted.
+ with pytest.raises(LocalEntryNotFoundError):
+ tpq._resolve_checkpoint_path(src, None, cache_dir = "/tmp/x", local_files_only = False)
+ assert asked == ["hosted-text_encoder-FP8.safetensors"], asked
+
+ # OFFLINE: a cache miss is the only verdict there is, so the chain is walked.
+ asked.clear()
+ with pytest.raises(LocalEntryNotFoundError):
+ tpq._resolve_checkpoint_path(src, None, cache_dir = "/tmp/x", local_files_only = True)
+ assert asked == ["hosted-text_encoder-FP8.safetensors", "hosted-text_encoder-FP8.pt"], asked
+
+ # A real 404 still advances online, which is the whole point of the chain.
+ asked.clear()
+
+ def only_pt(**kw):
+ asked.append(kw["filename"])
+ if kw["filename"].endswith(".safetensors"):
+ raise EntryNotFoundError("404")
+ return "/cache/hosted-text_encoder-FP8.pt"
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", only_pt)
+ got = tpq._resolve_checkpoint_path(src, None, cache_dir = "/tmp/x", local_files_only = False)
+ assert got == "/cache/hosted-text_encoder-FP8.pt", got
+ assert len(asked) == 2, asked
+
+
+def test_the_video_prefetch_advances_only_on_a_missing_name():
+ """The prefetch plan and the load have to agree about what a failure MEANS.
+
+ The resolver advances to the next spelling only for "this name is absent"; if the prefetch
+ advanced on an unreachable Hub too, it could report a legacy artifact as fetched, the plan would
+ drop the dense encoder, and the load would then refuse to advance past the same error and have
+ neither.
+ """
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+
+ from core.inference.video import VideoBackend
+
+ miss = VideoBackend._te_fetch_miss
+ # A real 404 is a miss in both modes: try the next name.
+ assert miss(EntryNotFoundError("404"), local_files_only = False) is True
+ assert miss(EntryNotFoundError("404"), local_files_only = True) is True
+ # Offline, a cache miss is the only verdict there is.
+ assert miss(LocalEntryNotFoundError("no local copy"), local_files_only = True) is True
+ # Online, the same exception means the Hub could not be reached: stop, do not blame the name.
+ assert miss(LocalEntryNotFoundError("connection error"), local_files_only = False) is False
+ # Anything else is about the repo, not the name.
+ assert miss(PermissionError("401"), local_files_only = False) is False
+ assert miss(OSError("corrupt cache"), local_files_only = True) is False