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.

Fix image model dependency downloads and show full footprint (#8036)

Lee Jackson5a2d9e185fd4
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index f24af98529c..a0dbdfa9a73 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -266,6 +266,36 @@ jobs:
mkdir -p logs/playwright_fontscale
python tests/studio/playwright_ui_font_scale.py
+ - name: Image model full-footprint selector regression (Playwright)
+ env:
+ BASE_URL: http://127.0.0.1:18894
+ STUDIO_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
+ PW_ART_DIR: logs/playwright_image_footprint
+ run: |
+ mkdir -p logs/playwright_image_footprint
+ python tests/studio/playwright_image_model_footprint.py
+
+ - name: Image staged-download cancel/retry regression (Playwright)
+ env:
+ BASE_URL: http://127.0.0.1:18894
+ STUDIO_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
+ PW_ART_DIR: logs/playwright_image_cancel_retry
+ run: |
+ mkdir -p logs/playwright_image_cancel_retry
+ python tests/studio/playwright_image_download_cancel_retry.py
+
+ # Same drive with the checkpoint absent, so the plan stages two entries instead of one and
+ # the queue's ordering and cancellation are covered as well as the single-entry path.
+ - name: Image staged-download cancel/retry regression, cold checkpoint (Playwright)
+ env:
+ BASE_URL: http://127.0.0.1:18894
+ STUDIO_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}
+ PW_ART_DIR: logs/playwright_image_cancel_retry_cold
+ PW_CHECKPOINT_CACHED: "0"
+ run: |
+ mkdir -p logs/playwright_image_cancel_retry_cold
+ python tests/studio/playwright_image_download_cancel_retry.py
+
- name: Stop second Unsloth
if: always()
run: |
@@ -372,6 +402,9 @@ jobs:
logs/playwright-permissions-*
logs/playwright_extra
logs/playwright_fontscale
+ logs/playwright_image_footprint
+ logs/playwright_image_cancel_retry
+ logs/playwright_image_cancel_retry_cold
logs/playwright_modelcfg
logs/playwright_ime
logs/studio-permissions-*.log
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 99724f6df04..036e8b73c7b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -170,15 +170,11 @@ install_torchao_windows_rocm_stub()
_MODEL_KINDS = frozenset({"gguf", "single_file", "pipeline"})
-def _record_sha(shas_out: Optional[dict[str, str]], repo_id: str, info: Any) -> None:
- """Note the commit ``info`` describes so a cache probe can pin to it.
-
- No ``sha`` just means the plan cannot pin, and stages as before."""
- if shas_out is None:
- return
+def _record_revision(out: Optional[dict[str, str]], repo_id: str, info: Any) -> None:
+ """Remember the commit a ``model_info`` answer described, when the Hub reports one."""
sha = getattr(info, "sha", None)
- if isinstance(sha, str) and sha:
- shas_out[repo_id] = sha
+ if out is not None and isinstance(sha, str) and sha:
+ out[repo_id] = sha
def hub_cache_dir() -> str:
@@ -1522,8 +1518,7 @@ class DiffusionBackend:
# The companion base repo also loads via from_pretrained, so it must clear the same trust bar.
if base_repo and base_repo.strip() and not _is_trusted_diffusion_repo(base_repo):
raise ValueError(
- f"base_repo is restricted to unsloth/* repos (or a local path); got "
- f"'{base_repo}'."
+ f"base_repo is restricted to unsloth/* repos (or a local path); got '{base_repo}'."
)
# A local base_repo loads as a full pipeline; reject a non-pipeline one before eviction.
_assert_local_base_is_pipeline(base_repo)
@@ -1887,6 +1882,104 @@ class DiffusionBackend:
logger.warning("diffusion.te_prequant_plan_failed: %s", exc)
return {}
+ def _dit_prequant_plan_source(
+ self, fam: Any, kind: str, hf_token: Optional[str], kwargs: dict[str, Any]
+ ) -> Optional[tuple[str, str, int]]:
+ """The hosted PRE-QUANTIZED transformer this pick loads INSTEAD of the base repo's dense
+ shards, as ``(repo, filename, declared_size)``, or None when no such artifact is used.
+
+ Those shards are already excluded for a GGUF pick, so without this the plan neither counts
+ nor stages the multi-GB denoiser the load really keeps on disk: the footprint reads short
+ and the file is pulled INLINE during the load, outside the manager's progress, cancel and
+ disk preflight. Mirrors the prequant gates in ``_load_dense_quant_pipeline`` so the plan
+ and the load agree."""
+ if kind != "gguf" or fam is None:
+ return None
+ try:
+ raw = kwargs.get("transformer_quant")
+ # Same tri-state as load_pipeline: unset or "auto" means the hardware ladder decides.
+ auto = raw is None or str(raw).strip().lower() in ("", "auto")
+ # An AUTO quant under an explicit Speed="off" is forced to "off" by load_pipeline, which
+ # normalizes to None and skips the fast path entirely, so no prequant is ever fetched.
+ # An EXPLICIT quant still takes it: that force applies only to the auto tri-state.
+ speed = kwargs.get("speed_mode")
+ if auto and speed is not None and str(speed).strip().lower() == SPEED_OFF:
+ return None
+ mode = TQ_AUTO if auto else normalize_transformer_quant(raw)
+ if mode is None:
+ return None
+ # A LoRA bake forces the DENSE path, so no prequant is fetched.
+ if _has_active_lora(kwargs.get("loras")):
+ return None
+ # A definite-offload policy keeps the GGUF: the fast path needs either a plan with no
+ # offload or a quant-sized replan that came back with none, and balanced/low_vram
+ # offload BY MODE, so no replan can clear it. Same gate _dense_quant_prefetch_needed
+ # applies, for the same reason.
+ mm = normalize_memory_mode(kwargs.get("memory_mode"))
+ if mm in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM):
+ return None
+ if mm is None and kwargs.get("cpu_offload"):
+ return None
+ target = self._resolve_device_target(fam)
+ # An auto quant DECLINES an uncached hosted checkpoint and runs the GGUF as-is, so
+ # those bytes never land. Only a cached one, or an explicit request, counts.
+ if (
+ auto
+ and _uncached_prequant_repo(
+ fam,
+ target,
+ mode,
+ base_repo = kwargs.get("base_repo"),
+ prequant_path = kwargs.get("transformer_prequant_path"),
+ )
+ is not None
+ ):
+ return None
+ scheme = select_transformer_quant_scheme(
+ target, mode, family = getattr(fam, "name", None)
+ )
+ if scheme is None:
+ return None
+ source = usable_prequant_source(
+ fam,
+ scheme,
+ path_override = kwargs.get("transformer_prequant_path"),
+ base_repo = kwargs.get("base_repo"),
+ )
+
+ if source is None and auto:
+ retry = self._auto_prequant_retry_scheme(
+ target,
+ fam,
+ mode,
+ scheme,
+ base_repo = kwargs.get("base_repo"),
+ path_override = kwargs.get("transformer_prequant_path"),
+ loras = kwargs.get("loras"),
+ )
+ if retry is not None:
+ source = usable_prequant_source(
+ fam,
+ retry,
+ path_override = kwargs.get("transformer_prequant_path"),
+ base_repo = kwargs.get("base_repo"),
+ )
+ # A local override is the operator's own file: already on disk, never downloaded.
+ if source is None or source.kind != "repo":
+ return None
+ from huggingface_hub import HfApi
+
+ info = HfApi(token = hf_token or None).model_info(source.location, files_metadata = True)
+ sizes = {s.rfilename: int(getattr(s, "size", 0) or 0) for s in (info.siblings or [])}
+ # Primary name first, then the legacy one, in the order the loader tries them.
+ for name in (source.filename, source.fallback_filename):
+ if name and name in sizes:
+ return (source.location, name, int(sizes[name]))
+ return None
+ except Exception as exc: # noqa: BLE001 -- an unsizable prequant must not fail the plan
+ logger.warning("diffusion.dit_prequant_plan_failed: %s", exc)
+ return None
+
@staticmethod
def _estimate_download_bytes(
repo_id: str,
@@ -1898,8 +1991,8 @@ class DiffusionBackend:
single_file_is_pipeline: bool = False,
include_transformer: "bool | Callable[[Sequence[str], Sequence[str]], bool]" = False,
sizes_out: Optional[dict[str, int]] = None,
- file_sizes_out: Optional[dict[tuple[str, str], int]] = None,
- shas_out: Optional[dict[str, str]] = None,
+ file_sizes_out: Optional[dict[str, dict[str, int]]] = None,
+ revisions_out: Optional[dict[str, str]] = None,
skip_te_components: tuple[str, ...] = (),
) -> tuple[int, list[str]]:
"""Total download size for the progress bar, plus the base-repo files to
@@ -1907,9 +2000,8 @@ class DiffusionBackend:
``sizes_out``, when given, is filled with per-repo byte totals so the download
plan can size one job per repo off this same single pair of Hub lookups.
- ``file_sizes_out`` is the per (repo, filename) breakdown, so the plan can drop cached
- files and size the rest. ``shas_out`` is each repo's CURRENT commit, so a cache hit
- counts only in that revision.
+ ``revisions_out`` records the commit each lookup described, so a cache probe can ask
+ about the SAME revision the sizes came from instead of whatever ``main`` is locally.
For a ``pipeline`` load the whole repo IS the pipeline (``base_repo`` is the
repo itself), so the transformer/ subfolder is INCLUDED -- unlike the GGUF /
@@ -1948,7 +2040,6 @@ class DiffusionBackend:
try:
if kind == "pipeline":
info = api.model_info(repo_id, files_metadata = True, token = hf_token)
- _record_sha(shas_out, repo_id, info)
picked = [
s
for s in info.siblings
@@ -1965,21 +2056,33 @@ class DiffusionBackend:
continue
base_files.append(s.rfilename)
total += s.size or 0
- if file_sizes_out is not None:
- file_sizes_out[(repo_id, s.rfilename)] = s.size or 0
if sizes_out is not None:
sizes_out[repo_id] = total
+ if file_sizes_out is not None:
+ file_sizes_out[repo_id] = {
+ s.rfilename: int(s.size or 0)
+ for s in picked
+ if not (
+ s.rfilename.endswith(".bin")
+ and s.rfilename.rsplit("/", 1)[0] in st_dirs
+ )
+ }
+ _record_revision(revisions_out, repo_id, info)
return total, base_files
# Skip the Hub size lookup for a LOCAL gguf path: model_info raises on a filesystem path.
if gguf_filename and not Path(repo_id).expanduser().exists():
info = api.model_info(repo_id, files_metadata = True, token = hf_token)
- _record_sha(shas_out, repo_id, info)
gguf_bytes = sum(s.size or 0 for s in info.siblings if s.rfilename == gguf_filename)
total += gguf_bytes
if sizes_out is not None:
sizes_out[repo_id] = gguf_bytes
if file_sizes_out is not None:
- file_sizes_out[(repo_id, gguf_filename)] = gguf_bytes
+ file_sizes_out[repo_id] = {
+ s.rfilename: int(s.size or 0)
+ for s in info.siblings
+ if s.rfilename == gguf_filename
+ }
+ _record_revision(revisions_out, repo_id, info)
# A whole-pipeline single file (SDXL) needs only the base's config/tokenizer, not its weights.
if kind == "single_file" and single_file_is_pipeline:
base_filter = _base_config_file_downloaded
@@ -1989,7 +2092,7 @@ class DiffusionBackend:
return _base_file_downloaded(rfilename, include_transformer = include_transformer)
base_info = api.model_info(base_repo, files_metadata = True, token = hf_token)
- _record_sha(shas_out, base_repo, base_info)
+ _record_revision(revisions_out, base_repo, base_info)
if callable(include_transformer):
kept = [s.rfilename for s in base_info.siblings if not _dense_te_shard(s.rfilename)]
companions = tuple(
@@ -2003,86 +2106,30 @@ class DiffusionBackend:
)
# Rebinding before base_filter is ever CALLED, so the loop below reads the answer.
include_transformer = bool(include_transformer(companions, transformer_files))
+ # Do not stage a combined repo's checkpoint again as a companion.
+ counted = {gguf_filename} if base_repo == repo_id and gguf_filename else set()
base_bytes = 0
+ base_sizes: dict[str, int] = {}
for s in base_info.siblings:
- if base_filter(s.rfilename) and not _dense_te_shard(s.rfilename):
- base_files.append(s.rfilename)
- base_bytes += s.size or 0
- if file_sizes_out is not None:
- file_sizes_out[(base_repo, s.rfilename)] = s.size or 0
+ if not base_filter(s.rfilename) or _dense_te_shard(s.rfilename):
+ continue
+ if s.rfilename in counted:
+ continue
+ base_files.append(s.rfilename)
+ base_bytes += s.size or 0
+ base_sizes[s.rfilename] = int(s.size or 0)
total += base_bytes
+ # ACCUMULATE, never assign: on a combined repo both branches key the same repo id, and
+ # a plain assignment drops the checkpoint's size and file map.
if sizes_out is not None:
- sizes_out[base_repo] = base_bytes
+ sizes_out[base_repo] = sizes_out.get(base_repo, 0) + base_bytes
+ if file_sizes_out is not None:
+ file_sizes_out.setdefault(base_repo, {}).update(base_sizes)
+ _record_revision(revisions_out, base_repo, base_info)
except Exception as exc: # noqa: BLE001 — estimate is best-effort
logger.warning("diffusion.size_estimate_failed: %s", exc)
return total, base_files
- @staticmethod
- def _files_already_cached(
- repo_id: str,
- files: list[str],
- revision: Optional[str] = None,
- ) -> set[str]:
- """Of ``files``, the names ONE root serves whole at ``revision``: all of them, or none.
-
- Both roots are searched -- Studio's live setting, and ``cache_dir = None`` for
- huggingface_hub's constant -- but hits are never UNIONED. A set split between the roots is
- complete in neither: ``_prefetch_files`` hands back a snapshot only when every file came
- from the SAME root, else None, and ``from_pretrained`` is then pinned to ``hub_cache_dir()``
- and cannot see the other root, so dropping the repo moves its refetch inline, outside the
- panel's progress and disk preflight. One root holding all of it still drops.
-
- ``revision`` is REQUIRED to drop anything: defaulted, ``try_to_load_from_cache`` reads the
- cache's OWN ``refs/main``, which a republished repo leaves on the superseded commit, so the
- stale blob would leave the plan and the loader would pull the new one inline.
-
- Only a str is a cached path. Never raises: an unreadable cache means "stage it"."""
- if not revision or not files:
- return set()
- try:
- from huggingface_hub import try_to_load_from_cache
-
- # Once, inside the try: hub_cache_dir is a SQLite read plus Path.home(), which raises
- # with no home -- per file and outside, it was the one way this could 500.
- roots = (hub_cache_dir(), None)
- except Exception: # noqa: BLE001 — no hub package / unreadable settings: stage everything
- return set()
- wanted = set(files)
- live_root, fallback_root = roots
-
- def _hits(root: Optional[str]) -> set[str]:
- found: set[str] = set()
- for name in wanted:
- try:
- hit = try_to_load_from_cache(repo_id, name, cache_dir = root, revision = revision)
- except Exception: # noqa: BLE001 — a cache we cannot read is not a verdict
- continue
- # is_file() is belt and braces: hub already ends on os.path.isfile today.
- if isinstance(hit, str) and Path(hit).is_file():
- found.add(name)
- return found
-
- live = _hits(live_root)
- if live == wanted:
- return wanted
- # A partial live hit IS the split: no single-root snapshot, so the pinned load refetches
- # the fallback's share.
- if live:
- return set()
- return wanted if _hits(fallback_root) == wanted else set()
-
- @staticmethod
- def _current_sha(repo_id: str, hf_token: Optional[str]) -> Optional[str]:
- """``repo_id``'s current commit, or None when the Hub does not say.
-
- Only for the MIRROR: it is a separate repo with its own history, so the vendor sha
- ``_estimate_download_bytes`` recorded would never hit."""
- try:
- from huggingface_hub import HfApi
- return getattr(HfApi().model_info(repo_id, token = hf_token), "sha", None) or None
- except Exception: # noqa: BLE001 — no sha means no skip, never a failed plan
- return None
-
def download_plan(
self,
repo_id: str,
@@ -2112,6 +2159,12 @@ class DiffusionBackend:
kind = resolve_model_kind(gguf_filename, model_kind)
if kind == "pipeline":
base = repo_id # the full pipeline IS the repo
+ elif fam is None and not (base_repo or "").strip():
+ # An unrecognised GGUF (a neutral repo whose id and filename match no family) has no
+ # companion set to resolve, and the family fallback would raise. The pick still loads:
+ # an empty plan just means nothing to pre-stage. The picker asks for a plan on EVERY
+ # hub pick, so raising here would 500 the route rather than plan no work.
+ return {"entries": [], "total_bytes": 0, "required_bytes": 0, "checkpoint_bytes": 0}
else:
base = _resolve_base_repo(repo_id, base_repo, fam, hf_token)
# Reported, not raised. The images page falls back to /images/load on ANY plan failure, so
@@ -2122,10 +2175,9 @@ class DiffusionBackend:
# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.
te_files = self._te_prequant_plan_files(fam, text_encoder_quant, hf_token)
sizes: dict[str, int] = {}
- file_sizes: dict[tuple[str, str], int] = {}
- shas: dict[str, str] = {}
- # Total discarded: it counts every file the pick needs, not what is left to fetch.
- _estimate_total, base_files = self._estimate_download_bytes(
+ file_sizes: dict[str, dict[str, int]] = {}
+ revisions: dict[str, str] = {}
+ required_total, base_files = self._estimate_download_bytes(
repo_id,
gguf_filename,
base,
@@ -2151,7 +2203,7 @@ class DiffusionBackend:
),
sizes_out = sizes,
file_sizes_out = file_sizes,
- shas_out = shas,
+ revisions_out = revisions,
skip_te_components = tuple(te_files),
)
# Decided once, from the staged file list, and both probed and reported: a gated base
@@ -2161,76 +2213,332 @@ class DiffusionBackend:
fetch_base = prefer_ungated_mirror(base, hf_token, files = base_files)
_assert_base_repo_accessible(fetch_base, hf_token)
entries: list[dict[str, Any]] = []
+ checkpoint_bytes = 0
+ if gguf_filename:
+ checkpoint_bytes = int(
+ file_sizes.get(repo_id, {}).get(gguf_filename, sizes.get(repo_id, 0))
+ )
+ required_total += sum(int(size) for files in te_files.values() for _name, size in files[1])
+ # The dense transformer/ shards are excluded for a GGUF pick, so a hosted prequant that
+ # replaces them is real footprint the plan would otherwise never report. Sized against the
+ # RESOLVED base, as the load passes it: a variant base picks its own prequant repo.
+ dit_prequant = self._dit_prequant_plan_source(
+ fam, kind, hf_token, {**load_kwargs, "base_repo": base}
+ )
+ if dit_prequant is not None:
+ required_total += dit_prequant[2]
+
+ scoped_files: dict[str, list[str]] = {}
+ scoped_gguf: dict[str, Optional[str]] = {}
+ missing_checkpoints: set[str] = set()
- def _stage(
+ def add_missing_entry(
repo: str,
files: list[str],
- sized: dict[str, int],
- gguf: Optional[str],
- revision: Optional[str] = None,
+ declared_sizes: dict[str, int],
+ *,
+ gguf: Optional[str] = None,
+ checkpoint: bool = False,
) -> None:
- """Queue the files the cache is missing at ``revision``.
-
- Entries are what the Downloads panel lists, so an all-cached pick yields none rather
- than reading as a re-download of a model the user already has. No revision drops
- nothing, so an unpinnable repo stages in full as it always did.
+ """Add only files the loader cannot already resolve from either cache root.
+
+ The picker knows whether its checkpoint is cached, but not whether companion repos
+ are. Keeping this decision in the plan makes a cached GGUF + missing text encoder one
+ explicit dependency download, and prevents a cached GGUF from being staged again.
+
+ The probe asks about the revision this plan's sizes came from, so a companion that
+ republished a file is a MISS here rather than a silent inline fetch during the load.
+ One entry per repo: same-repo groups share a scope variant, so a second job for the
+ same repo would fight the first over progress, manifest and cancellation.
+
+ ``checkpoint`` marks the entry that holds the SELECTED model, so the panel can label
+ it without re-deriving the answer from the repo id: only this planner knows a gated
+ base was swapped for an ungated mirror, which leaves the entry's repo id different
+ from the id the caller picked.
+ """
+
+ scope = scoped_files.setdefault(repo, [])
+ scope.extend(name for name in files if name not in scope)
+ scoped_gguf[repo] = scoped_gguf.get(repo) or gguf
+ revision = revisions.get(repo)
+ live = hub_cache_dir()
+
+ # Preserve main's stable-scope invariant: a running @diffusion job is adopted only
+ # when a second claim names the same complete file set. This strict, pinned fast path
+ # drops a repo only when one cache root already serves the whole snapshot. The
+ # per-file probes below remain necessary for size-corroborated unrelated commits and
+ # for accurate remaining-byte accounting.
+ if self._files_already_cached(repo, files, revision, declared_sizes).issuperset(files):
+ for entry in entries:
+ if entry["repo_id"] == repo:
+ entry["files"].extend(name for name in scope if name not in entry["files"])
+ entry["gguf_filename"] = scoped_gguf[repo]
+ break
+ return
- All or nothing per repo, never a subset: every diffusion entry for a repo rides the one
- "@diffusion" scope slot, and download_registry refuses a claim whose scoped_files differ
- from the live job's, so a shrinking list would 409 a second pick sharing this base where
- it used to adopt the running job. Staging a cached file costs nothing anyway, since
- hf_hub_download returns the pointer without a transfer.
+ def _where(name: str) -> Optional[str]:
+ size = declared_sizes.get(name)
+ if self._hub_file_is_cached(repo, name, revision, size, roots = (live,)):
+ return "live"
+ if not self._hub_file_is_cached(repo, name, revision, size, roots = (None,)):
+ return None
+ # The other root holds a good copy, but reuse_other_cache_root only switches roots
+ # when the live lookup finds NOTHING. A stale live copy (right name, wrong bytes)
+ # therefore shadows the good one and gets served, or re-fetched inline. Passing no
+ # size asks presence alone, which is exactly what that switch tests.
+ if self._hub_file_is_cached(repo, name, revision, None, roots = (live,)):
+ return None
+ return "other"
+
+ where = {name: _where(name) for name in files}
+ # A repo whose files STRADDLE the two roots cannot be handed to from_pretrained as one
+ # snapshot: _prefetch_files returns no _base_local_dir in that state and the assembly is
+ # pinned to hub_cache_dir(), so the old-root subset is invisible to it. Stage that subset
+ # instead, or the load re-pulls it inline past the plan's own progress, cancel and disk
+ # preflight, and fails offline after a plan that reported nothing left to do. A repo
+ # living entirely in the other root is fine, which is what reuse_other_cache_root is for.
+ # A file that is missing everywhere will be downloaded INTO the live root, so it counts
+ # as live here: dropping it would read a genuinely-mixed repo as unsplit and stage only
+ # the missing part, manufacturing the very split this branch exists to avoid.
+ split = {w or "live" for w in where.values()} == {"live", "other"}
+ missing = [n for n, w in where.items() if w is None or (split and w != "live")]
+ if not missing:
+ return
- "Cached" is per ROOT, never a union across the two; see ``_files_already_cached``."""
- cached = self._files_already_cached(repo, files, revision)
- if files and cached.issuperset(files):
+ if checkpoint:
+ missing_checkpoints.add(repo)
+ for entry in entries:
+ if entry["repo_id"] != repo:
+ continue
+ newly_missing = [n for n in missing if n not in entry["files"]]
+ added = [n for n in scope if n not in entry["files"]]
+ entry["files"].extend(added)
+ entry["bytes"] += int(sum(declared_sizes.get(n, 0) for n in newly_missing))
+ entry["gguf_filename"] = scoped_gguf[repo]
+ entry["checkpoint"] = repo in missing_checkpoints
return
entries.append(
{
"repo_id": repo,
- "files": files,
- "bytes": int(sum(sized.get(name, 0) for name in files)),
- "gguf_filename": gguf,
+ # Stable across a warming cache so a second pick can adopt the same live
+ # scoped job. Cached names are cheap no-op hf_hub_download calls; only the
+ # genuinely missing subset contributes to bytes/preflight below.
+ "files": list(scope),
+ "bytes": int(sum(declared_sizes.get(name, 0) for name in missing)),
+ "gguf_filename": scoped_gguf[repo],
+ "checkpoint": repo in missing_checkpoints,
}
)
for repo, files in te_files.values():
- # No revision: te_prequant_hub_files reports names and sizes only, so a pre-cast
- # checkpoint stages whole, not off a stale refs/main. Worth surfacing its info.sha:
- # these replace tens of GB.
- _stage(repo, [n for n, _s in files], dict(files), None)
+ add_missing_entry(
+ repo,
+ [name for name, _size in files],
+ {name: int(size) for name, size in files},
+ )
if gguf_filename and not Path(repo_id).expanduser().exists():
- _stage(
+ add_missing_entry(
repo_id,
[gguf_filename],
- # file_sizes, not sizes: a base repo equal to this one overwrote sizes[repo_id]
- # with the base total, mis-sizing this row.
- {gguf_filename: int(file_sizes.get((repo_id, gguf_filename), 0))},
- gguf_filename,
- shas.get(repo_id),
+ file_sizes.get(repo_id, {gguf_filename: int(sizes.get(repo_id, 0))}),
+ gguf = gguf_filename,
+ checkpoint = True,
)
if base_files and not Path(base).expanduser().exists():
# STAGED before the loader runs, so it must name the MIRROR: a gated upstream here 401s
# an anonymous user at staging and the swap downstream is never reached. status(), the
# API base repo, saved configs and LoRA tags keep the vendor id; sizes key on it too.
- # The commit follows the id: the sizes came from the vendor, the probe must not.
- base_rev = (
- shas.get(base) if fetch_base == base else self._current_sha(fetch_base, hf_token)
- )
- _stage(
+ if fetch_base != base and fetch_base not in revisions:
+ mirror_revision = self._current_sha(fetch_base, hf_token)
+ if mirror_revision:
+ revisions[fetch_base] = mirror_revision
+ add_missing_entry(
fetch_base,
base_files,
- {name: file_sizes.get((base, name), 0) for name in base_files},
- None,
- base_rev,
+ file_sizes.get(base, {}),
+ # A pipeline pick has no single file: the base IS the selected model (base = repo_id
+ # above). Flagged here rather than by comparing repo ids downstream, because the swap
+ # just above leaves this entry named after the MIRROR. Under a GGUF or single-file
+ # pick the base is a companion, so it stays unflagged.
+ checkpoint = kind == "pipeline",
)
- # Derived, never decremented: a carried total can only drift from the rows the panel shows.
+ if dit_prequant is not None:
+ # Staged, not just counted: _load_dense_quant_pipeline fetches this checkpoint during the
+ # load, under the load lock and after the previous pipeline was evicted, so leaving it
+ # out means a multi-GB inline pull with no progress, no cancel and no disk preflight.
+ # A companion of the checkpoint, never the selected model itself.
+ prequant_repo, prequant_file, prequant_size = dit_prequant
+ add_missing_entry(prequant_repo, [prequant_file], {prequant_file: prequant_size})
return {
"entries": entries,
- "total_bytes": int(sum(e["bytes"] for e in entries)),
+ "total_bytes": sum(entry["bytes"] for entry in entries),
+ "required_bytes": int(required_total),
+ "checkpoint_bytes": checkpoint_bytes,
"incompatible_reason": incompatible,
}
+ @staticmethod
+ def _files_already_cached(
+ repo_id: str,
+ files: list[str],
+ revision: Optional[str] = None,
+ declared_sizes: Optional[dict[str, int]] = None,
+ ) -> set[str]:
+ """Return all ``files`` only when one cache root serves the whole pinned snapshot.
+
+ A union across roots is not loadable as one snapshot. No revision is no verdict: the
+ size-aware per-file probe may still accept an unchanged file after an unrelated repo
+ commit, but this strict fast path never trusts a potentially stale local ``main`` ref.
+ """
+ if not revision or not files:
+ return set()
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ roots = (hub_cache_dir(), None)
+ except Exception: # noqa: BLE001 -- unreadable cache means stage, never fail the plan
+ return set()
+ wanted = set(files)
+
+ def _hits(root: Optional[str]) -> set[str]:
+ found: set[str] = set()
+ for name in wanted:
+ try:
+ value = try_to_load_from_cache(repo_id, name, cache_dir = root, revision = revision)
+ except Exception: # noqa: BLE001 -- keep checking the other files/root
+ continue
+ if not isinstance(value, str):
+ continue
+ path = Path(value)
+ if not path.is_file():
+ continue
+ expected = (declared_sizes or {}).get(name)
+ if expected and expected > 0:
+ try:
+ if path.stat().st_size != expected:
+ continue
+ except OSError:
+ continue
+ found.add(name)
+ return found
+
+ live = _hits(roots[0])
+ if live == wanted:
+ return wanted
+ if live:
+ return set()
+ return wanted if _hits(roots[1]) == wanted else set()
+
+ @staticmethod
+ def _current_sha(repo_id: str, hf_token: Optional[str]) -> Optional[str]:
+ """The current Hub commit for a mirror repo, or None when metadata is unavailable."""
+ try:
+ from huggingface_hub import HfApi
+ return getattr(HfApi().model_info(repo_id, token = hf_token), "sha", None) or None
+ except Exception: # noqa: BLE001 -- no SHA means conservative staging
+ return None
+
+ @staticmethod
+ def _hub_file_is_loadable(
+ repo_id: str,
+ filename: str,
+ revision: Optional[str] = None,
+ expected_size: Optional[int] = None,
+ ) -> bool:
+ """Whether the LOAD will actually resolve a good copy, which is stricter than being cached
+ somewhere. ``reuse_other_cache_root`` only switches roots when the live lookup finds
+ nothing, so a stale live copy under the right name shadows a good one in the other root:
+ the load reads the stale file, or refetches it inline, after a plan that saw the good copy
+ and staged nothing. Presence in the live root is asked separately from validity, because
+ presence alone is what that switch tests."""
+ live = hub_cache_dir()
+ if DiffusionBackend._hub_file_is_cached(
+ repo_id, filename, revision, expected_size, roots = (live,)
+ ):
+ return True
+ if not DiffusionBackend._hub_file_is_cached(
+ repo_id, filename, revision, expected_size, roots = (None,)
+ ):
+ return False
+ return not DiffusionBackend._hub_file_is_cached(
+ repo_id, filename, revision, None, roots = (live,)
+ )
+
+ @staticmethod
+ def _hub_file_is_cached(
+ repo_id: str,
+ filename: str,
+ revision: Optional[str] = None,
+ expected_size: Optional[int] = None,
+ roots: Optional[tuple[Optional[str], ...]] = None,
+ ) -> bool:
+ """Whether ``filename`` is complete in either cache root the loader reuses.
+
+ ``roots`` narrows the search; the default asks both, as the loader's own fetches do.
+
+ ``try_to_load_from_cache`` is network-free. A pinned miss proves nothing: ``revision`` is
+ the REPO head, so an unrelated README commit can name a snapshot that a healthy weight was
+ never downloaded into. In that case a size-corroborated local ``main`` hit is still valid.
+
+ A pinned HIT is different: it proves the current file exists locally. The loader omits
+ ``revision``, so it will open the snapshot selected by the local ``main`` ref. We may omit
+ the file from the staged plan only when that unpinned lookup resolves to the SAME snapshot
+ path. Otherwise a stale main ref would make the plan bless the current explicit-SHA copy
+ while the loader opens an older one (or revalidates inline outside the manager).
+
+ Every hit is also corroborated with the size declared by the same Hub lookup. A different
+ size means the file was republished or damaged and must be fetched through the manager.
+
+ A string alone is not enough on Windows, where a broken snapshot link can survive a
+ cancelled download, so the target must still be a real file.
+ """
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ search = (hub_cache_dir(), None) if roots is None else roots
+
+ def hit(root: Optional[str], rev: Optional[str]) -> Optional[str]:
+ value = try_to_load_from_cache(repo_id, filename, cache_dir = root, revision = rev)
+ return value if isinstance(value, str) and Path(value).is_file() else None
+
+ def sound(hit: str) -> bool:
+ """A hit is only proof if it also has the declared bytes. Naming the right commit
+ is not enough: a truncated or half-copied file can sit at that path (Windows has
+ no symlink to keep the blob out of it), and trusting the ref alone hands the load
+ a damaged cache entry it fails on, instead of restaging it through the manager."""
+ if not expected_size or expected_size <= 0:
+ return True # nothing declared to check against; trust the ref
+ try:
+ return Path(hit).stat().st_size == expected_size
+ except OSError:
+ return False
+
+ unpinned = [(root, value) for root in search if (value := hit(root, None))]
+ if revision is None:
+ return any(sound(value) for _root, value in unpinned)
+
+ # Presence, not soundness, is the branch condition: a damaged current snapshot must
+ # not fall back to and bless an older same-size main snapshot.
+ pinned = [(root, value) for root in search if (value := hit(root, revision))]
+ if not pinned:
+ return any(sound(value) for _root, value in unpinned)
+
+ def snapshot_path(value: str) -> Path:
+ # Do not resolve symlinks: their blob targets can be shared across snapshots, while
+ # the loader's unpinned choice is encoded by the snapshots/<sha>/... path itself.
+ return Path(value).absolute()
+
+ return any(
+ pinned_root == main_root
+ and sound(pinned_value)
+ and sound(main_value)
+ and snapshot_path(pinned_value) == snapshot_path(main_value)
+ for pinned_root, pinned_value in pinned
+ for main_root, main_value in unpinned
+ )
+ except Exception: # noqa: BLE001 -- an unreadable cache is a miss, never a plan failure
+ pass
+ return False
+
@staticmethod
def _hub_cache_repo_dir(repo_id: str) -> Path:
"""Local HF hub cache dir for ``repo_id``.
@@ -2688,8 +2996,7 @@ class DiffusionBackend:
target
):
transformer_quant_decline = (
- "this device cannot run a dense torchao quant (it needs a CUDA GPU in "
- "bf16)"
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
)
transformer_quant_decline_status = RESOLVED_UNSUPPORTED
elif transformer_quant_pinned is not None and (
@@ -4682,8 +4989,7 @@ class DiffusionBackend:
"cuDNN fused attention upgrade" if attention_engaged else "diffusers default"
)
logger.info(
- "diffusion.speed: deferred profile engaged on generation 3 "
- "(optims=%s, attention=%s)",
+ "diffusion.speed: deferred profile engaged on generation 3 (optims=%s, attention=%s)",
",".join(state.speed_optims) or "none",
attention_engaged or "native",
)
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 4c8c9fb47cf..28cc34e57a4 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1088,7 +1088,15 @@ class SdCppDiffusionBackend:
# and an anonymous user would 401 at staging, never reaching the swap. Same per-repo file
# list on both sides, so both take the same decision.
fetch_repo = _fetch_repo_map(specs, hf_token)
- by_repo = {fetch_repo[repo]: names for repo, names in by_repo.items()}
+ # MERGED, not reassigned: two upstream repos can share one fetch repo (the FLUX.2 VAE and
+ # the dev encoders both come from Comfy-Org/flux2-dev once that repack is cached), and a
+ # plain comprehension would drop whichever landed first, leaving its files out of both the
+ # staged entry and the footprint.
+ merged: dict[str, list[str]] = {}
+ for repo, names in by_repo.items():
+ into = merged.setdefault(fetch_repo[repo], [])
+ into.extend(n for n in names if n not in into)
+ by_repo = merged
fetch_repo_id = fetch_repo.get(repo_id, repo_id)
# AFTER the swap: preflighting the upstream id would refuse the very picks the ungated
# mirror exists to rescue.
@@ -1096,19 +1104,47 @@ class SdCppDiffusionBackend:
sizes = self._plan_file_sizes(by_repo, hf_token)
entries: list[dict[str, Any]] = []
total = 0
+ # Imported here, not at module scope: diffusion.py is the heavier module and the routes
+ # already load this one on its own.
+ from core.inference.diffusion import DiffusionBackend
+
for repo, names in by_repo.items():
- repo_bytes = int(sum(sizes.get((repo, n), 0) for n in names))
- total += repo_bytes
+ total += int(sum(sizes.get((repo, n), 0) for n in names))
+ # Same missing-file filter the diffusers planner applies: _fetch_assets already reads
+ # both cache roots, so staging an asset it can resolve re-downloads it for nothing and
+ # fails offline. required_bytes keeps the UNFILTERED sum -- it is the disk footprint.
+ # Sized, so a republished asset under the same name is a miss rather than a silent
+ # inline fetch during the load. Without it the probe trusts the local ref alone.
+ # Loadable, not merely cached: a stale live-root copy shadows a good one in the other
+ # root, because the fetch only switches roots when the live lookup finds nothing.
+ missing = [
+ n
+ for n in names
+ if not DiffusionBackend._hub_file_is_loadable(repo, n, None, sizes.get((repo, n)))
+ ]
+ if not missing:
+ continue
entries.append(
{
"repo_id": repo,
- "files": names,
- "bytes": repo_bytes,
+ # A stable scope lets repeated picks adopt an in-flight download.
+ "files": list(names),
+ "bytes": int(sum(sizes.get((repo, n), 0) for n in missing)),
# Only the transformer entry carries the GGUF filename; the VAE / encoder entries are plain single files.
"gguf_filename": gguf_filename if repo == fetch_repo_id else None,
+ # Same entry, said plainly for the panel's label: the transformer IS the pick, the
+ # VAE / encoders are required assets. Compared against the POST-swap id, because a
+ # gated pick staged from its ungated mirror no longer matches the id the caller
+ # asked for. Native picks are always single-file, so there is no pipeline case.
+ "checkpoint": repo == fetch_repo_id and gguf_filename in missing,
}
)
- return {"entries": entries, "total_bytes": total}
+ return {
+ "entries": entries,
+ "total_bytes": sum(entry["bytes"] for entry in entries),
+ "required_bytes": total,
+ "checkpoint_bytes": int(sizes.get((fetch_repo_id, gguf_filename), 0)),
+ }
@staticmethod
def _assets_by_repo(specs: list[tuple[str, str, str]]) -> dict[str, list[str]]:
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 7b9a5ab7a7f..589019d8d4c 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1006,6 +1006,9 @@ class VideoBackend:
kwargs["gguf_filename"],
kwargs.get("hf_token"),
cancel_event = cancel_event,
+ # The plan counts a file cached under EITHER root and stages neither, so the
+ # load has to resolve through both or it re-pulls what the planner skipped.
+ reuse_other_cache_root = True,
)
)
# An LTX-2.3 checkpoint supplies the VAEs/vocoder/connectors, so the base pull shrinks to scheduler + TE + tokenizer; recompute the estimate.
@@ -1162,7 +1165,11 @@ class VideoBackend:
try:
local = Path(
hf_hub_download_with_xet_fallback(
- repo, wanted, hf_token, cancel_event = cancel_event
+ repo,
+ wanted,
+ hf_token,
+ cancel_event = cancel_event,
+ reuse_other_cache_root = True,
)
)
except Exception as exc: # noqa: BLE001 -- re-raised below, narrowed by name
@@ -1384,6 +1391,7 @@ class VideoBackend:
"modular_model_index.json",
hf_token,
cache_dir = hub_cache_dir(),
+ reuse_other_cache_root = True,
)
)
with open(path, "r", encoding = "utf-8") as handle:
@@ -1504,6 +1512,7 @@ class VideoBackend:
hf_token,
cancel_event = cancel,
cache_dir = hub_cache_dir(),
+ reuse_other_cache_root = True,
)
except Exception as exc: # noqa: BLE001 -- no artifact just means the dense encoder
if cancel.is_set():
@@ -1779,29 +1788,62 @@ class VideoBackend:
# Keyed by repo so a 2.3 pick's checkpoint and extras stay ONE scoped job; two entries would collide on the job key.
entries: dict[str, dict[str, Any]] = {}
total = 0
+ checkpoint_bytes = 0
+ planned: dict[str, set[str]] = {}
+ # Where the loader would resolve each file (live root / other root / nowhere), and the
+ # entry labels, both keyed by repo so the staging decision can be made once per repo.
+ located: dict[str, dict[str, tuple[Optional[str], int]]] = {}
+ labels: dict[str, dict[str, Any]] = {}
def add(
repo: str,
files: list[tuple[str, int]],
gguf: Optional[str] = None,
+ revision: Optional[str] = None,
+ checkpoint: bool = False,
) -> int:
- if not files:
- return 0
- entry = entries.setdefault(
- repo, {"repo_id": repo, "files": [], "bytes": 0, "gguf_filename": None}
- )
- seen = set(entry["files"])
- added = 0
+ """Count every required file and record, per root, where the loader would find it.
+ Which of them to stage is decided per REPO once every add is in (see below), not here:
+ the 2.3 path adds one repo across several calls, and a call that happens to hold only
+ other-root files cannot see that the repo straddles both. Returns the full size.
+
+ ``checkpoint`` marks the entry holding the SELECTED model so the panel can label it
+ without re-deriving the answer from the repo id, which the plan itself may have
+ rewritten. Same envelope key the image planners emit, so one page-side map serves both."""
+ from core.inference.diffusion import DiffusionBackend
+
+ def _where(name: str, size: int) -> Optional[str]:
+ live = hub_cache_dir()
+ if DiffusionBackend._hub_file_is_cached(repo, name, revision, size, roots = (live,)):
+ return "live"
+ if not DiffusionBackend._hub_file_is_cached(
+ repo, name, revision, size, roots = (None,)
+ ):
+ return None
+ # A stale live copy under the right name shadows the good one, because
+ # reuse_other_cache_root switches roots only when the live lookup finds NOTHING.
+ # Presence alone is what that switch tests, so ask without the size.
+ if DiffusionBackend._hub_file_is_cached(repo, name, revision, None, roots = (live,)):
+ return None
+ return "other"
+
+ seen = planned.setdefault(repo, set())
+ where = located.setdefault(repo, {})
+ label = labels.setdefault(repo, {"gguf": None, "checkpoint": False})
+ if gguf:
+ label["gguf"] = gguf
+ # Only ever raised, never cleared: a repo holding both the checkpoint and companion
+ # files (a 2.3 pick whose extras live in the checkpoint repo) is keyed once, so a later
+ # companion add would otherwise unflag what the checkpoint add marked.
+ label["checkpoint"] = label["checkpoint"] or checkpoint
+ required = 0
for name, size in files:
if name in seen:
continue
seen.add(name)
- entry["files"].append(name)
- entry["bytes"] += int(size)
- added += int(size)
- if gguf:
- entry["gguf_filename"] = gguf
- return added
+ required += int(size)
+ where[name] = (_where(name, int(size)), int(size))
+ return required
try:
api = HfApi(token = hf_token or None)
@@ -1812,7 +1854,14 @@ class VideoBackend:
for s in (info.siblings or [])
if s.rfilename == gguf_filename
]
- total += add(repo_id, sizes, gguf = gguf_filename)
+ checkpoint_bytes = sum(size for _name, size in sizes)
+ total += add(
+ repo_id,
+ sizes,
+ gguf = gguf_filename,
+ revision = getattr(info, "sha", None),
+ checkpoint = True,
+ )
if ltx23:
# The 2.3 assembly reads these companion files at load; without them here they would be pulled inline, outside the panel's disk preflight.
from .video_ltx2 import ltx23_extras_files, LTX23_EXTRAS_REPO
@@ -1830,6 +1879,7 @@ class VideoBackend:
for s in (extras_info.siblings or [])
if s.rfilename in wanted
],
+ revision = getattr(extras_info, "sha", None),
)
# Pre-cast encoders first: only a checkpoint that really resolves earns the right to drop the dense shards.
te_sources = self._te_prequant_sources(fam, text_encoder_quant)
@@ -1868,11 +1918,57 @@ class VideoBackend:
fam, transformer_quant, base
),
),
+ revision = getattr(info, "sha", None),
+ # 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",
)
except Exception as exc: # noqa: BLE001 -- an unavailable plan falls back to the inline pull
logger.warning("video.download_plan_failed: %s", exc)
- return {"entries": [], "total_bytes": 0}
- return {"entries": list(entries.values()), "total_bytes": total}
+ return {"entries": [], "total_bytes": 0, "required_bytes": 0, "checkpoint_bytes": 0}
+ for repo, where in located.items():
+ # Files STRADDLING the two roots cannot be handed to from_pretrained as one snapshot:
+ # _predownload_base returns no directory in that state and the assembly is pinned to
+ # hub_cache_dir(), so the other-root subset is invisible to it and gets re-pulled
+ # inline, past this plan's progress, cancel and disk preflight, failing offline after a
+ # plan that reported nothing left to do. A repo living wholly in the other root is fine,
+ # which is what reuse_other_cache_root is for. A file missing everywhere downloads INTO
+ # the live root, so it counts as live: dropping it would read a mixed repo as unsplit
+ # and stage only the missing part, manufacturing the very split this avoids.
+ split = {w or "live" for w, _size in where.values()} == {"live", "other"}
+ staged = [
+ (name, size)
+ for name, (w, size) in where.items()
+ if w is None or (split and w != "live")
+ ]
+ if not staged:
+ continue
+ missing_names = [name for name, _size in staged]
+ # Keep the scoped claim stable while this repo warms so a second pick adopts the
+ # running @diffusion job instead of 409ing on a smaller file list. Cached names are
+ # no-op Hub calls; only ``staged`` contributes to bytes/preflight.
+ names = list(where)
+ gguf = labels[repo]["gguf"]
+ entries[repo] = {
+ "repo_id": repo,
+ "files": names,
+ "bytes": sum(size for _name, size in staged),
+ "gguf_filename": gguf,
+ # The flag describes the ENTRY, not the pick: a 2.3 repo holding both the cached
+ # checkpoint and its missing extras stages companion files only, and labelling that
+ # "Model file" misdescribes what is downloading. A pipeline pick has no single file,
+ # so the repo itself is the model and anything staged from it is part of it.
+ "checkpoint": labels[repo]["checkpoint"]
+ and (gguf is None or gguf in missing_names),
+ }
+ return {
+ "entries": list(entries.values()),
+ # Remaining vs the full footprint: cache state changes what is left to fetch, never
+ # what the load needs on disk.
+ "total_bytes": sum(entry["bytes"] for entry in entries.values()),
+ "required_bytes": total,
+ "checkpoint_bytes": int(checkpoint_bytes),
+ }
@staticmethod
def _h3_native_download_plan(
@@ -1888,6 +1984,7 @@ class VideoBackend:
h3_text_encoder_filename,
validate_h3_transformer_filename,
)
+ from core.inference.diffusion import DiffusionBackend
validate_h3_transformer_filename(gguf_filename)
wanted = (
@@ -1897,7 +1994,10 @@ class VideoBackend:
(H3_COMPONENT_REPO, H3_AUDIO_VAE),
)
grouped: dict[str, dict[str, Any]] = {}
+ missing_files: dict[str, set[str]] = {}
total = 0
+ required_total = 0
+ checkpoint_bytes = 0
try:
api = HfApi(token = hf_token or None)
for repo, filename in wanted:
@@ -1908,20 +2008,49 @@ class VideoBackend:
if match is None:
raise ValueError(f"Required MiniMax-H3 component is missing: {repo}/{filename}")
size = int(match.size or 0)
+ required_total += size
+ if repo == repo_id and filename == gguf_filename:
+ checkpoint_bytes = size
entry = grouped.setdefault(
repo,
- {"repo_id": repo, "files": [], "bytes": 0, "gguf_filename": None},
+ {
+ "repo_id": repo,
+ "files": [],
+ "bytes": 0,
+ "gguf_filename": None,
+ "checkpoint": False,
+ },
)
if filename not in entry["files"]:
entry["files"].append(filename)
- entry["bytes"] += size
- total += size
+ revision = getattr(info, "sha", None)
+ if not DiffusionBackend._hub_file_is_loadable(repo, filename, revision, size):
+ missing_files.setdefault(repo, set()).add(filename)
+ entry["bytes"] += size
+ total += size
if filename == gguf_filename:
entry["gguf_filename"] = filename
except Exception as exc: # noqa: BLE001 -- inline loading remains the fallback
logger.warning("video.h3_native_download_plan_failed: %s", exc)
- return {"entries": [], "total_bytes": 0}
- return {"entries": list(grouped.values()), "total_bytes": total}
+ return {
+ "entries": [],
+ "total_bytes": 0,
+ "required_bytes": 0,
+ "checkpoint_bytes": 0,
+ }
+ entries = []
+ for repo, entry in grouped.items():
+ missing = missing_files.get(repo, set())
+ if not missing:
+ continue
+ entry["checkpoint"] = entry["gguf_filename"] in missing
+ entries.append(entry)
+ return {
+ "entries": entries,
+ "total_bytes": total,
+ "required_bytes": required_total,
+ "checkpoint_bytes": checkpoint_bytes,
+ }
@staticmethod
def _pick_looks_like_ltx23(
@@ -1970,6 +2099,8 @@ class VideoBackend:
source.filename,
hf_token,
cancel_event = cancel,
+ # Pre-quant encoders are planned with the same both-roots probe.
+ reuse_other_cache_root = True,
)
except Exception as exc: # noqa: BLE001 -- no pre-cast file just means the dense encoder
if cancel.is_set():
@@ -2022,17 +2153,38 @@ class VideoBackend:
return None
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
- snapshot_root: Optional[Path] = None
+ snapshot_root: Optional[str] = None
+ roots: set[str] = set()
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.
if cancel.is_set():
raise RuntimeError(VIDEO_CANCELLED_MSG)
local = Path(
- hf_hub_download_with_xet_fallback(base, name, hf_token, cancel_event = cancel)
+ hf_hub_download_with_xet_fallback(
+ base,
+ name,
+ hf_token,
+ cancel_event = cancel,
+ # Same reason as the checkpoint: the plan already treats either root as cached.
+ reuse_other_cache_root = True,
+ )
)
+ # The resolved path minus the file's own relative parts, so a subfolder entry yields
+ # the same root as a top-level one. Not resolve()d: that follows the link into blobs/.
+ try:
+ root = str(local.parents[len(Path(name).parts) - 1])
+ except (IndexError, ValueError, OSError):
+ root = ""
+ roots.add(root)
if name == "model_index.json":
- snapshot_root = local.parent
- return str(snapshot_root) if snapshot_root is not None else None
+ snapshot_root = root or None
+ # Only hand back a snapshot the WHOLE set lives in. reuse_other_cache_root resolves each
+ # file through whichever root holds it, so a moved cache can serve the manifest from the
+ # old root while the rest land in the live one, and from_pretrained would then be pointed
+ # at a tree missing the others. Mirrors the image prefetch path.
+ if snapshot_root is not None and roots != {snapshot_root}:
+ return None
+ return snapshot_root
except Exception as exc: # noqa: BLE001 -- fall back to from_pretrained's own pull
if cancel.is_set():
raise
@@ -3281,7 +3433,15 @@ class VideoBackend:
return root
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
- return Path(hf_hub_download_with_xet_fallback(repo_id, gguf_filename or "", hf_token))
+ return Path(
+ hf_hub_download_with_xet_fallback(
+ repo_id,
+ gguf_filename or "",
+ hf_token,
+ # Matches the planner's both-roots cache probe, as the diffusion fetches already do.
+ reuse_other_cache_root = True,
+ )
+ )
# ── generation ───────────────────────────────────────────────────────────
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index e88564333f0..9431f03fe91 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -338,7 +338,14 @@ def _load_extras_file(filename: str, hf_token: Optional[str]) -> dict[str, Any]:
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
- path = hf_hub_download_with_xet_fallback(LTX23_EXTRAS_REPO, filename, hf_token)
+ path = hf_hub_download_with_xet_fallback(
+ LTX23_EXTRAS_REPO,
+ filename,
+ hf_token,
+ # The plan counts an extras file cached under EITHER root and stages neither, so this has to
+ # resolve both or it re-pulls what the planner skipped, inline and outside the manager.
+ reuse_other_cache_root = True,
+ )
return load_file(path)
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index 2e99dca4e81..8a44654421b 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -49,6 +49,19 @@ class GgufVariantDetail(BaseModel):
"this to pick Resume (http) vs Redownload (xet) labels."
),
)
+ dependency_key: Optional[str] = Field(
+ None,
+ description = (
+ "Opaque grouping key: variants sharing a key share one companion "
+ "download footprint (text encoders, VAE, tokenizer, configs), so a "
+ "footprint resolved for one of them is correct for all of them. The "
+ "companion set is NOT repository-wide -- one repo can hold GGUFs of "
+ "different diffusion families, and FLUX.2-klein picks its text "
+ "encoder per checkpoint size -- so a client must group by this key "
+ "rather than per repo. Null means unknown (no family resolved); "
+ "clients should then treat the repo as a single group."
+ ),
+ )
class GgufVariantsResponse(BaseModel):
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index d82929e36bd..ccf014fe25a 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import re
import threading
import time
@@ -336,6 +337,56 @@ def _quants_from_state(
return variants, has_vision
+def _variant_dependency_key(repo_id: str, filename: str) -> Optional[str]:
+ """Group key for variants that share one companion download footprint.
+
+ The companion set (text encoders, VAE, tokenizer, configs) is not a property of
+ the repo: ``detect_family_for_pick`` falls back to ``repo_id/filename``, so a
+ neutral repo can hold GGUFs of different families with different base repos,
+ and ``sd_cpp_text_encoders_for`` picks Qwen3-8B vs Qwen3-4B per klein checkpoint
+ size within one family. Both sources of variation therefore go into the key, so
+ a client that resolves the footprint once per key never advertises one row's
+ total on another row.
+
+ Local resolution only, and never raises: the key is an optimization for the
+ client's grouping, so an unknown key (None) must not fail the listing.
+ """
+ try:
+ from core.inference.diffusion_families import (
+ detect_family_for_pick,
+ sd_cpp_text_encoders_for,
+ )
+
+ fam = detect_family_for_pick(repo_id, filename)
+ if fam is None:
+ return None
+ inner_dim = None
+ if fam.name == "flux.2-klein":
+ from core.inference.diffusion_compat import flux2_inner_dim_for_pick
+
+ inner_dim = flux2_inner_dim_for_pick(repo_id, filename, allow_network = False)
+ identity = f"{repo_id}/{filename}".lower()
+ sized = re.search(r"(?<![a-z0-9])(?:4b|9b)(?![a-z0-9])", identity)
+ if (
+ inner_dim is None
+ and sized is None
+ and "klein4b" not in identity
+ and "klein9b" not in identity
+ ):
+ unknown = hashlib.sha256(filename.lower().encode("utf-8")).hexdigest()[:16]
+ return f"{fam.name}:unknown:{unknown}"
+ encoders = sd_cpp_text_encoders_for(fam, repo_id, filename, inner_dim = inner_dim)
+ # Hashed, not joined raw: the encoder table is long, and the key is opaque
+ # to the client, which only ever compares it for equality.
+ digest = hashlib.sha256(
+ "\n".join("/".join(str(part) for part in entry) for entry in encoders).encode("utf-8")
+ ).hexdigest()[:16]
+ return f"{fam.name}:{digest}"
+ except Exception as e:
+ logger.debug("Dependency key unavailable for %s/%s: %s", repo_id, filename, e)
+ return None
+
+
def _partial_transport_for_variant(
repo_id: str,
variant: str,
@@ -949,6 +1000,7 @@ async def get_gguf_variants_answer(
download_size_bytes = v.size_bytes,
downloaded = _downloaded(v),
partial = not _downloaded(v),
+ dependency_key = _variant_dependency_key(response_repo_id, v.filename),
)
for v in variants
],
@@ -977,6 +1029,7 @@ async def get_gguf_variants_answer(
v.quant,
repo_cache_dir,
),
+ dependency_key = _variant_dependency_key(response_repo_id, v.filename),
)
for v in variants
],
@@ -1005,6 +1058,7 @@ async def get_gguf_variants_answer(
partial_transport = _partial_transport_for_variant(
repo_id, v.quant, repo_cache_dir
),
+ dependency_key = _variant_dependency_key(repo_id, v.filename),
)
for v in state[0]
if v.quant and v.quant.lower() not in listed
@@ -1413,6 +1467,7 @@ async def get_gguf_variants_answer(
),
partial = is_partial,
partial_transport = (partial_quant_transports.get(v.quant) if is_partial else None),
+ dependency_key = _variant_dependency_key(repo_id, v.filename),
)
return GgufVariantsResponse(
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index cc575181473..0e60dacc717 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2943,10 +2943,18 @@ class DiffusionDownloadPlanEntry(BaseModel):
"also pull the packaged root single, transformer/ shards and fp16 twins the loader "
"never opens (tens of GB on a FLUX repo).",
)
- bytes: int = Field(0, description = "Declared size of those files, 0 when unknown")
+ bytes: int = Field(
+ 0, description = "Declared size of the files still missing from cache, 0 when unknown"
+ )
gguf_filename: Optional[str] = Field(
None, description = "Set when this entry is the single-file GGUF checkpoint"
)
+ checkpoint: bool = Field(
+ False,
+ description = "This entry holds the SELECTED model rather than a companion repo. The "
+ "planner has to say so: a gated base is staged from its ungated mirror, so the entry's "
+ "repo id is not the id the caller picked and the role cannot be recovered downstream.",
+ )
class DiffusionDownloadPlanResponse(BaseModel):
@@ -2954,7 +2962,16 @@ class DiffusionDownloadPlanResponse(BaseModel):
same file scope the loader would. Empty entries mean nothing to download (local path)."""
entries: List[DiffusionDownloadPlanEntry] = Field(default_factory = list)
- total_bytes: int = Field(0, description = "Sum across entries, 0 when the estimate failed")
+ total_bytes: int = Field(
+ 0, description = "Sum of the remaining download entries, 0 when ready or unknown"
+ )
+ required_bytes: int = Field(
+ 0,
+ description = "Full declared footprint of every file the load requires, including cached files",
+ )
+ checkpoint_bytes: int = Field(
+ 0, description = "Declared size of the selected checkpoint within required_bytes"
+ )
incompatible_reason: Optional[str] = Field(
None,
description = "Why this pick cannot load as selected (today: a FLUX.2 GGUF paired with a "
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 6e0074c2929..560f5c1ecad 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -6080,8 +6080,13 @@ class _FakeSibling:
class _FakeInfo:
- def __init__(self, siblings):
+ def __init__(
+ self,
+ siblings,
+ sha = None,
+ ):
self.siblings = siblings
+ self.sha = sha
GB = 1024**3
@@ -6099,7 +6104,11 @@ _FLUX_BASE_SIBLINGS = [
_FLUX_BASE_SIBLINGS_BY_NAME = {s.rfilename: s.size for s in _FLUX_BASE_SIBLINGS}
-def _fake_hf_api(monkeypatch, repos):
+def _fake_hf_api(
+ monkeypatch,
+ repos,
+ shas = None,
+):
"""Point HfApi.model_info at a canned sibling list per repo id."""
class _Api:
@@ -6109,9 +6118,16 @@ def _fake_hf_api(monkeypatch, repos):
files_metadata = False,
token = None,
):
- return _FakeInfo(repos[repo_id])
+ return _FakeInfo(repos[repo_id], (shas or {}).get(repo_id))
monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ # Download-plan tests describe their cache state explicitly. Never let a developer's real
+ # Studio cache make an entry disappear from these otherwise hermetic tests.
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kwargs: False),
+ )
def test_download_plan_scopes_the_base_repo_files(monkeypatch):
@@ -6145,6 +6161,10 @@ def test_download_plan_scopes_the_base_repo_files(monkeypatch):
checkpoint, base = plan["entries"]
assert checkpoint["files"] == ["flux1-dev-Q4_K_M.gguf"]
assert checkpoint["bytes"] == 7 * GB
+ # The panel labels "Model file" vs "Required assets" from this flag. Only the planner can name
+ # the selected entry, so it says so outright: the companion base is assets, not the pick.
+ assert checkpoint["checkpoint"] is True
+ assert base["checkpoint"] is False
assert "flux1-dev.safetensors" not in base["files"]
assert not any(f.startswith("transformer/") for f in base["files"])
assert not any(f.startswith("assets/") for f in base["files"])
@@ -6153,6 +6173,268 @@ def test_download_plan_scopes_the_base_repo_files(monkeypatch):
# Sized per repo, so each download job gets its own expected bytes.
assert base["bytes"] < 24 * GB
assert plan["total_bytes"] == checkpoint["bytes"] + base["bytes"]
+ assert plan["required_bytes"] == plan["total_bytes"]
+ assert plan["checkpoint_bytes"] == 7 * GB
+
+
+def test_download_plan_omits_a_cached_gguf_but_keeps_missing_companions(monkeypatch):
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],
+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo",
+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",
+ )
+ monkeypatch.setattr(
+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs, **_kw: False
+ )
+ _no_cache(monkeypatch)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(
+ lambda repo_id, filename, revision = None, expected_size = None, **kwargs: repo_id
+ == "unsloth/FLUX.1-dev-GGUF"
+ and filename == "flux1-dev-Q4_K_M.gguf"
+ ),
+ )
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ assert [entry["repo_id"] for entry in plan["entries"]] == ["unsloth/FLUX.1-dev"]
+ assert "text_encoder/model.safetensors" in plan["entries"][0]["files"]
+ assert plan["total_bytes"] == plan["entries"][0]["bytes"]
+ # Cache state changes the pending download, never the selector's declared footprint.
+ assert plan["required_bytes"] == 7 * GB + plan["total_bytes"]
+ assert plan["checkpoint_bytes"] == 7 * GB
+
+
+def test_download_plan_is_empty_when_every_required_file_is_cached(monkeypatch):
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],
+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo",
+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",
+ )
+ monkeypatch.setattr(
+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs, **_kw: False
+ )
+ _all_cached(monkeypatch)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kwargs: True),
+ )
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ assert plan["entries"] == []
+ assert plan["total_bytes"] == 0
+ assert plan["required_bytes"] > 7 * GB
+ assert plan["checkpoint_bytes"] == 7 * GB
+
+
+def test_download_plan_sizes_the_checkpoint_when_the_base_is_the_same_repo(monkeypatch):
+ # A combined repo (explicit base_repo, or a self-referential base_model tag) keys both Hub
+ # lookups on one id. Overwriting instead of merging left the checkpoint at 0 bytes and put the
+ # companion total in checkpoint_bytes, and listing it twice double counted the footprint.
+ combined = "unsloth/Combined-Image-GGUF"
+ _fake_hf_api(
+ monkeypatch,
+ {
+ combined: [
+ _FakeSibling("model-Q4_K_M.gguf", 7 * GB),
+ _FakeSibling("model_index.json", 1000),
+ _FakeSibling("text_encoder/model.safetensors", 2 * GB),
+ _FakeSibling("vae/diffusion_pytorch_model.safetensors", 300),
+ ],
+ },
+ )
+ monkeypatch.setattr("core.inference.diffusion._resolve_base_repo", lambda *a, **k: combined)
+ monkeypatch.setattr(
+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs, **_kw: False
+ )
+ _no_cache(monkeypatch)
+
+ plan = DiffusionBackend().download_plan(
+ combined, gguf_filename = "model-Q4_K_M.gguf", base_repo = combined
+ )
+
+ assert len(plan["entries"]) == 1, "one repo, one scoped job"
+ entry = plan["entries"][0]
+ assert entry["gguf_filename"] == "model-Q4_K_M.gguf"
+ assert entry["files"].count("model-Q4_K_M.gguf") == 1
+ assert plan["checkpoint_bytes"] == 7 * GB
+ assert entry["bytes"] == plan["required_bytes"] == 7 * GB + 2 * GB + 1300
+
+ assert entry["checkpoint"] is True
+
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_files_already_cached",
+ staticmethod(
+ lambda _repo, files, _revision = None, _declared_sizes = None: (
+ set(files) if files == ["model-Q4_K_M.gguf"] else set()
+ )
+ ),
+ )
+ warming = DiffusionBackend().download_plan(
+ combined, gguf_filename = "model-Q4_K_M.gguf", base_repo = combined
+ )
+ assert warming["entries"][0]["files"] == entry["files"]
+
+ assert warming["entries"][0]["checkpoint"] is False
+
+
+def _write_hub_cache(
+ root,
+ repo_id,
+ filename,
+ sha,
+ size,
+ *,
+ symlink = True,
+ set_main = True,
+):
+ """The tree hf_hub_download leaves behind: blobs/ + snapshots/<sha>/ + refs/main."""
+ import os
+
+ repo_dir = (root / f"models--{repo_id.replace('/', '--')}").resolve()
+ blobs, snaps, refs = repo_dir / "blobs", repo_dir / "snapshots" / sha, repo_dir / "refs"
+ for d in (blobs, (snaps / filename).parent, refs):
+ d.mkdir(parents = True, exist_ok = True)
+ blob = blobs / f"etag-{sha}"
+ blob.write_bytes(b"\0" * size)
+ target = snaps / filename
+ if symlink:
+ os.symlink(os.path.relpath(blob, target.parent), target)
+ else:
+ import shutil
+ shutil.copyfile(blob, target)
+ if set_main:
+ (refs / "main").write_text(sha)
+
+
[email protected]("symlink", [True, False], ids = ["posix_links", "windows_copies"])
+def test_a_cached_file_survives_an_unrelated_commit_to_its_repo(tmp_path, monkeypatch, symlink):
+ # model_info().sha is the REPO head, so a README commit moves it while every weight stays
+ # byte identical. Calling those files missing would re-stage the whole footprint and can fail
+ # a disk preflight for space nobody needs, so the size the plan declared has the last word.
+ repo, name = "black-forest-labs/FLUX.1-dev", "text_encoder/model.safetensors"
+ _write_hub_cache(tmp_path, repo, name, "a" * 40, 4096, symlink = symlink)
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path))
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "unused"))
+
+ assert DiffusionBackend._hub_file_is_cached(repo, name, "a" * 40, 4096)
+ assert DiffusionBackend._hub_file_is_cached(
+ repo, name, "b" * 40, 4096
+ ), "an unrelated repo commit must not invalidate a file the plan sized identically"
+ assert not DiffusionBackend._hub_file_is_cached(
+ repo, name, "b" * 40, 9999
+ ), "a republished file has a different declared size and must be fetched through the manager"
+ # Nothing declared to compare against: trust the ref rather than call a present file missing.
+ assert DiffusionBackend._hub_file_is_cached(repo, name, "b" * 40, 0)
+
+
[email protected]("symlink", [True, False], ids = ["posix_links", "windows_copies"])
+def test_an_explicit_current_snapshot_does_not_hide_a_stale_main_ref(
+ tmp_path, monkeypatch, symlink
+):
+ # The planner sizes revision B, but the loader omits revision and follows refs/main to A. A
+ # same-size B hit must not make the planner omit the file: the two calls would use different
+ # snapshots, moving revalidation into the load (or reading A offline).
+ repo, name = "black-forest-labs/FLUX.1-dev", "text_encoder/model.safetensors"
+ stale, current = "a" * 40, "b" * 40
+ _write_hub_cache(tmp_path, repo, name, stale, 4096, symlink = symlink)
+ _write_hub_cache(
+ tmp_path,
+ repo,
+ name,
+ current,
+ 4096,
+ symlink = symlink,
+ set_main = False,
+ )
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path))
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "unused"))
+
+ assert not DiffusionBackend._hub_file_is_cached(repo, name, current, 4096)
+
+ # Once the loader's unpinned ref names B too, the staged manager can safely omit it.
+ repo_dir = tmp_path / f"models--{repo.replace('/', '--')}"
+ (repo_dir / "refs" / "main").write_text(current)
+ assert DiffusionBackend._hub_file_is_cached(repo, name, current, 4096)
+
+
[email protected]("symlink", [True, False], ids = ["posix_links", "windows_copies"])
+def test_a_damaged_file_is_restaged_even_under_the_pinned_revision(tmp_path, monkeypatch, symlink):
+ # Naming the right commit is not proof the bytes are right. A truncated or half-copied file
+ # can sit at that path, and the copy layout has no symlink keeping the blob out of it, so the
+ # pinned probe has to corroborate with the declared size exactly as the main-ref probe does.
+ # Otherwise the plan omits the file and the load consumes the damaged entry.
+ repo, name = "black-forest-labs/FLUX.1-dev", "text_encoder/model.safetensors"
+ _write_hub_cache(tmp_path, repo, name, "a" * 40, 1024, symlink = symlink)
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: str(tmp_path))
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "unused"))
+
+ assert not DiffusionBackend._hub_file_is_cached(
+ repo, name, "a" * 40, 4096
+ ), "the pinned commit is right but the bytes are not, so it must be restaged"
+ assert DiffusionBackend._hub_file_is_cached(repo, name, "a" * 40, 1024)
+ # Still no size to compare against: an intact-looking hit is trusted, as before.
+ assert DiffusionBackend._hub_file_is_cached(repo, name, "a" * 40, 0)
+
+
+def test_download_plan_probes_the_cache_at_the_revision_it_sized(monkeypatch):
+ # An unpinned probe answers from the LOCAL main ref, so a republished companion reads as
+ # present and the loader fetches it inline, outside the download manager.
+ seen = []
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/FLUX.1-dev-GGUF": [_FakeSibling("flux1-dev-Q4_K_M.gguf", 7 * GB)],
+ "black-forest-labs/FLUX.1-dev": _FLUX_BASE_SIBLINGS,
+ },
+ shas = {"unsloth/FLUX.1-dev-GGUF": "abc123", "black-forest-labs/FLUX.1-dev": "def456"},
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo",
+ lambda *a, **k: "black-forest-labs/FLUX.1-dev",
+ )
+ monkeypatch.setattr(
+ DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs, **_kw: False
+ )
+ # Upstream serves this pick, so both entries keep the id the sizes were read from. A mirror
+ # swap deliberately drops the pin instead: the vendor's commit means nothing in that repo.
+ _all_cached(monkeypatch)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(
+ lambda repo_id, filename, revision = None, expected_size = None, **kwargs: bool(
+ seen.append(revision)
+ )
+ ),
+ )
+
+ DiffusionBackend().download_plan(
+ "unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
+ )
+
+ assert set(seen) == {"abc123", "def456"}
def test_download_plan_decides_the_widening_from_the_base_listing(monkeypatch):
@@ -6218,6 +6500,23 @@ def test_download_plan_pipeline_kind_is_one_entry(monkeypatch):
assert "text_encoder/model.fp16.safetensors" not in files
+def test_download_plan_flags_a_mirrored_pipeline_as_the_checkpoint(monkeypatch):
+ # The regression this flag exists for. A gated pipeline is STAGED from its ungated mirror, so
+ # the entry's repo id is unsloth/FLUX.1-dev while the pick is black-forest-labs/FLUX.1-dev.
+ # The page used to derive the label by comparing those two ids, which made every file of the
+ # selected model read as "Required assets". Only the planner knows about the swap.
+ gated = "black-forest-labs/FLUX.1-dev"
+ _fake_hf_api(monkeypatch, {gated: _FLUX_BASE_SIBLINGS})
+ _no_cache(monkeypatch)
+
+ plan = DiffusionBackend().download_plan(gated, model_kind = "pipeline")
+
+ assert len(plan["entries"]) == 1
+ entry = plan["entries"][0]
+ assert entry["repo_id"] == "unsloth/FLUX.1-dev" != gated
+ assert entry["checkpoint"] is True
+
+
def test_download_plan_is_empty_for_a_local_path(tmp_path, monkeypatch):
# Nothing to stage: the files are already on disk.
local = tmp_path / "my-model"
@@ -6230,6 +6529,8 @@ def test_download_plan_is_empty_for_a_local_path(tmp_path, monkeypatch):
plan = DiffusionBackend().download_plan(str(local), gguf_filename = "weights.gguf")
assert plan["entries"] == []
+ assert plan["required_bytes"] == 0
+ assert plan["checkpoint_bytes"] == 0
def test_download_plan_stages_the_precast_encoder_instead_of_the_dense_one(monkeypatch):
@@ -6356,6 +6657,7 @@ _ZIMAGE_BASE_SIBLINGS = [
_FakeSibling("text_encoder/model.safetensors", 8 * GB),
_FakeSibling("vae/diffusion_pytorch_model.safetensors", 300),
]
+_ZIMAGE_BASE_SIBLINGS_BY_NAME = {s.rfilename: s.size for s in _ZIMAGE_BASE_SIBLINGS}
def test_download_plan_stages_no_second_denoiser_for_an_uncached_prequant(monkeypatch):
@@ -6392,6 +6694,190 @@ def test_download_plan_stages_no_second_denoiser_for_an_uncached_prequant(monkey
assert plan["total_bytes"] == 4 * GB + base["bytes"] < 17 * GB
+def test_download_plan_counts_the_hosted_prequant_in_the_required_footprint(monkeypatch):
+ # An explicit fp8 request loads the hosted prequant INSTEAD of the base transformer/ shards,
+ # which the plan already excludes. required_bytes is the on-disk footprint the picker renders
+ # as "Full required size", so leaving the prequant out under-reports it by the whole denoiser.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Z-Image-GGUF": [_FakeSibling("Z-Image-Turbo-Q4_K_M.gguf", 4 * GB)],
+ "Tongyi-MAI/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ "unsloth/Z-Image-Turbo-FP8": [_FakeSibling("Z-Image-Turbo-FP8.pt", 6 * GB)],
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: "Tongyi-MAI/Z-Image-Turbo"
+ )
+ _stub_hosted_prequant(monkeypatch, cached = False)
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF",
+ gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf",
+ transformer_quant = "fp8",
+ )
+
+ # Counted AND staged: the load fetches this checkpoint inline otherwise, under the load lock
+ # and past the manager's progress, cancel and disk preflight.
+ staged = {(e["repo_id"], f) for e in plan["entries"] for f in e["files"]}
+ assert ("unsloth/Z-Image-Turbo-FP8", "Z-Image-Turbo-FP8.pt") in staged
+ assert plan["required_bytes"] == plan["total_bytes"]
+ # Measured against the same pick without the quant, so the base's small configs do not have
+ # to be enumerated here: the delta is exactly the prequant checkpoint.
+ baseline = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF", gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf"
+ )
+ assert plan["required_bytes"] - baseline["required_bytes"] == 6 * GB
+ # A companion, never the selected model.
+ prequant = next(e for e in plan["entries"] if e["repo_id"] == "unsloth/Z-Image-Turbo-FP8")
+ assert prequant["checkpoint"] is False
+
+
+def test_download_plan_counts_a_cached_lower_auto_prequant(monkeypatch):
+ from core.inference import diffusion as dmod
+
+ source = types.SimpleNamespace(
+ kind = "repo",
+ location = "unsloth/Qwen-Image-FP8",
+ filename = "Qwen-Image-INT8.pt",
+ fallback_filename = "transformer_int8.pt",
+ )
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Qwen-Image-GGUF": [_FakeSibling("Qwen-Image-Q4_K_M.gguf", 4 * GB)],
+ "Qwen/Qwen-Image": _ZIMAGE_BASE_SIBLINGS,
+ source.location: [_FakeSibling(source.filename, 6 * GB)],
+ },
+ )
+ monkeypatch.setattr(dmod, "_resolve_base_repo", lambda *a, **k: "Qwen/Qwen-Image")
+ monkeypatch.setattr(dmod, "select_transformer_quant_scheme", lambda *a, **k: "fp8")
+ monkeypatch.setattr(
+ "core.inference.diffusion_transformer_quant.auto_scheme_candidates",
+ lambda *a, **k: ("fp8", "int8"),
+ )
+ monkeypatch.setattr(
+ dmod,
+ "usable_prequant_source",
+ lambda fam, scheme, **kw: source if scheme == "int8" else None,
+ )
+ monkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda *a, **k: True)
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/Qwen-Image-GGUF",
+ gguf_filename = "Qwen-Image-Q4_K_M.gguf",
+ text_encoder_quant = "off",
+ )
+ baseline = DiffusionBackend().download_plan(
+ "unsloth/Qwen-Image-GGUF",
+ gguf_filename = "Qwen-Image-Q4_K_M.gguf",
+ text_encoder_quant = "off",
+ speed_mode = "off",
+ )
+
+ assert plan["required_bytes"] - baseline["required_bytes"] == 6 * GB
+ assert any(source.filename in entry["files"] for entry in plan["entries"])
+
+
+def test_download_plan_omits_the_prequant_under_a_definite_offload_policy(monkeypatch):
+ # The fast path needs a plan with no offload, or a quant-sized replan that came back with
+ # none. Balanced and low_vram offload BY MODE, which no replan can clear, so the load keeps
+ # the GGUF and never fetches the hosted checkpoint. Counting it overstates the footprint by
+ # the whole denoiser even though an explicit quant was requested.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Z-Image-GGUF": [_FakeSibling("Z-Image-Turbo-Q4_K_M.gguf", 4 * GB)],
+ "Tongyi-MAI/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ "unsloth/Z-Image-Turbo-FP8": [_FakeSibling("Z-Image-Turbo-FP8.pt", 6 * GB)],
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: "Tongyi-MAI/Z-Image-Turbo"
+ )
+ _stub_hosted_prequant(monkeypatch, cached = True)
+
+ for kwargs in (
+ {"memory_mode": "balanced"},
+ {"memory_mode": "low_vram"},
+ {"cpu_offload": True},
+ ):
+ plan = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF",
+ gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf",
+ transformer_quant = "fp8",
+ **kwargs,
+ )
+ assert plan["required_bytes"] == plan["total_bytes"], kwargs
+ assert not any(f.endswith("-FP8.pt") for e in plan["entries"] for f in e["files"]), kwargs
+
+ # A resident-capable pick still pays for it, so the gate cannot just zero everything.
+ resident = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF",
+ gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf",
+ transformer_quant = "fp8",
+ )
+ assert any(f.endswith("-FP8.pt") for e in resident["entries"] for f in e["files"])
+
+
+def test_download_plan_omits_the_prequant_for_an_auto_pick_at_speed_off(monkeypatch):
+ # load_pipeline forces an AUTO quant to "off" under Speed="off", which normalizes to None and
+ # skips the fast path, so nothing is fetched and the footprint must not claim it.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Z-Image-GGUF": [_FakeSibling("Z-Image-Turbo-Q4_K_M.gguf", 4 * GB)],
+ "Tongyi-MAI/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ "unsloth/Z-Image-Turbo-FP8": [_FakeSibling("Z-Image-Turbo-FP8.pt", 6 * GB)],
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: "Tongyi-MAI/Z-Image-Turbo"
+ )
+ _stub_hosted_prequant(monkeypatch, cached = True)
+
+ auto = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF", gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf", speed_mode = "off"
+ )
+ assert not any(f.endswith("-FP8.pt") for e in auto["entries"] for f in e["files"])
+
+ # An EXPLICIT quant is not forced off, so it still loads the prequant and still pays for it.
+ explicit = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF",
+ gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf",
+ speed_mode = "off",
+ transformer_quant = "fp8",
+ )
+ assert any(f.endswith("-FP8.pt") for e in explicit["entries"] for f in e["files"])
+
+
+def test_download_plan_omits_a_prequant_an_auto_pick_would_decline(monkeypatch):
+ # Auto runs the GGUF as-is rather than download an uncached hosted checkpoint, so those bytes
+ # never land and must not inflate the figure either. Only an explicit request pays for it.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "unsloth/Z-Image-GGUF": [_FakeSibling("Z-Image-Turbo-Q4_K_M.gguf", 4 * GB)],
+ "Tongyi-MAI/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ "unsloth/Z-Image-Turbo-FP8": [_FakeSibling("Z-Image-Turbo-FP8.pt", 6 * GB)],
+ },
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: "Tongyi-MAI/Z-Image-Turbo"
+ )
+ _stub_hosted_prequant(monkeypatch, cached = False)
+ monkeypatch.setattr(
+ "core.inference.diffusion._uncached_prequant_repo",
+ lambda *a, **k: "unsloth/Z-Image-Turbo-FP8",
+ )
+
+ plan = DiffusionBackend().download_plan(
+ "unsloth/Z-Image-GGUF", gguf_filename = "Z-Image-Turbo-Q4_K_M.gguf"
+ )
+
+ assert plan["required_bytes"] == plan["total_bytes"]
+
+
def test_download_plan_for_a_pipeline_kind_ignores_the_prequant_cache(monkeypatch):
# Only a GGUF pick is restricted: a full pipeline's transformer IS the repo's.
_fake_hf_api(monkeypatch, {"unsloth/some-pipeline": _ZIMAGE_BASE_SIBLINGS})
@@ -6402,6 +6888,156 @@ def test_download_plan_for_a_pipeline_kind_ignores_the_prequant_cache(monkeypatc
assert any(f.startswith("transformer/") for f in plan["entries"][0]["files"])
+def test_download_plan_restages_a_base_split_across_both_cache_roots(monkeypatch):
+ # Studio's cache folder is a setting, so a base can end up half in the old root and half in the
+ # new one. _prefetch_files refuses to name a snapshot in that state and the assembly is pinned
+ # to hub_cache_dir(), so the old-root half is invisible to from_pretrained. Staging nothing
+ # there means the load re-pulls it inline, past the plan's progress, cancel and disk preflight.
+ _fake_hf_api(monkeypatch, {"unsloth/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS})
+ old_root_only = {"model_index.json"}
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ **kwargs,
+ ):
+ # roots=(live,) asks the active root; roots=(None,) asks huggingface_hub's import-time one.
+ asks_live = roots is not None and roots != (None,)
+ return (filename not in old_root_only) if asks_live else (filename in old_root_only)
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ plan = DiffusionBackend().download_plan("unsloth/Z-Image-Turbo", model_kind = "pipeline")
+
+ entry = plan["entries"][0]
+ assert set(entry["files"]) == set(_ZIMAGE_BASE_SIBLINGS_BY_NAME)
+ assert entry["bytes"] == sum(_ZIMAGE_BASE_SIBLINGS_BY_NAME[n] for n in old_root_only)
+
+
+def test_download_plan_restages_the_old_root_half_when_other_files_are_missing_too(monkeypatch):
+ # The mixed case that matters most: some files sit in the old root, others are absent entirely.
+ # Those absent ones land in the LIVE root when staged, so the repo ends up straddling both even
+ # though nothing looked split at plan time. The old-root half has to come along.
+ _fake_hf_api(monkeypatch, {"unsloth/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS})
+ old_root_only = {"model_index.json"}
+ absent = {"vae/diffusion_pytorch_model.safetensors"}
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ **kwargs,
+ ):
+ if filename in absent:
+ return False
+ asks_live = roots is not None and roots != (None,)
+ return (filename not in old_root_only) if asks_live else (filename in old_root_only)
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ plan = DiffusionBackend().download_plan("unsloth/Z-Image-Turbo", model_kind = "pipeline")
+
+ entry = plan["entries"][0]
+ assert set(entry["files"]) == set(_ZIMAGE_BASE_SIBLINGS_BY_NAME)
+ assert entry["bytes"] == sum(_ZIMAGE_BASE_SIBLINGS_BY_NAME[n] for n in old_root_only | absent)
+
+
+def test_download_plan_stages_a_file_a_stale_live_copy_shadows(monkeypatch):
+ # The nastiest split: the live root holds an OLD copy under the right name and the other root
+ # holds the revision the plan sized. reuse_other_cache_root only switches roots when the live
+ # lookup finds nothing, so the stale copy wins and the load reads it, or refetches inline.
+ # Treating that as cached would report an empty plan for a base that is not actually usable.
+ _fake_hf_api(monkeypatch, {"unsloth/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS})
+ shadowed = {"model_index.json"}
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ **kwargs,
+ ):
+ asks_live = roots is not None and roots != (None,)
+ if filename in shadowed:
+ # Present in the live root but the wrong bytes; correct in the other root.
+ return expected_size is None if asks_live else True
+ return asks_live
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ plan = DiffusionBackend().download_plan("unsloth/Z-Image-Turbo", model_kind = "pipeline")
+
+ entry = plan["entries"][0]
+ assert set(entry["files"]) == set(_ZIMAGE_BASE_SIBLINGS_BY_NAME)
+ assert entry["bytes"] == sum(_ZIMAGE_BASE_SIBLINGS_BY_NAME[n] for n in shadowed)
+
+
+def test_download_plan_stages_nothing_for_a_base_wholly_in_the_other_root(monkeypatch):
+ # The case reuse_other_cache_root exists for: one root holds the WHOLE base, so _prefetch_files
+ # hands back that snapshot and the load reads it off disk. Nothing to restage.
+ _fake_hf_api(monkeypatch, {"unsloth/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS})
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ **kwargs,
+ ):
+ return roots is None or roots == (None,)
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ plan = DiffusionBackend().download_plan("unsloth/Z-Image-Turbo", model_kind = "pipeline")
+
+ assert plan["entries"] == [], "a base living entirely in one root is already loadable"
+
+
+def test_download_plan_declines_an_unrecognised_gguf_instead_of_raising(monkeypatch):
+ # A neutral repo whose id AND filename match no family resolves no companions, and the family
+ # fallback used to raise on None. The picker asks for a plan on every hub pick, so that 500s
+ # the route; planning no work is the honest answer and the load still handles its own fetch.
+ _fake_hf_api(monkeypatch, {})
+
+ plan = DiffusionBackend().download_plan(
+ "someone/mixed-gguf-collection",
+ gguf_filename = "totally-unknown-thing-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+
+ assert plan == {"entries": [], "total_bytes": 0, "required_bytes": 0, "checkpoint_bytes": 0}
+
+
+def test_download_plan_still_plans_an_unrecognised_gguf_given_an_explicit_base(monkeypatch):
+ # An explicit base_repo supplies what family detection could not, so the pick must still plan.
+ _fake_hf_api(
+ monkeypatch,
+ {
+ "someone/mixed-gguf-collection": [
+ _FakeSibling("totally-unknown-thing-Q4_K_M.gguf", 4_000)
+ ],
+ "unsloth/Z-Image-Turbo": _ZIMAGE_BASE_SIBLINGS,
+ },
+ )
+ _no_cache(monkeypatch)
+
+ plan = DiffusionBackend().download_plan(
+ "someone/mixed-gguf-collection",
+ gguf_filename = "totally-unknown-thing-Q4_K_M.gguf",
+ model_kind = "gguf",
+ base_repo = "unsloth/Z-Image-Turbo",
+ )
+
+ assert plan["entries"], "an explicit base still has a companion set to stage"
+
+
# ── teardown fence ────────────────────────────────────────────────────────────
@@ -6904,7 +7540,7 @@ def test_download_plan_skips_files_already_in_the_cache(monkeypatch):
monkeypatch.setattr(
DiffusionBackend,
"_files_already_cached",
- staticmethod(lambda repo_id, files, revision = None: set(files)),
+ staticmethod(lambda repo_id, files, revision = None, declared_sizes = None: set(files)),
)
plan = DiffusionBackend().download_plan(
@@ -6937,7 +7573,7 @@ def test_download_plan_stages_only_what_the_cache_is_missing(monkeypatch):
DiffusionBackend,
"_files_already_cached",
staticmethod(
- lambda repo_id, files, revision = None: (
+ lambda repo_id, files, revision = None, declared_sizes = None: (
set() if repo_id.endswith("-GGUF") else set(files)
)
),
@@ -6959,6 +7595,7 @@ def _seed_cache_file(
filename,
sha,
*,
+ size = None,
dangling = False,
):
"""Write ``filename`` into a real HF cache layout at ``sha``, refs/main pointing there."""
@@ -6977,6 +7614,9 @@ def _seed_cache_file(
pytest.skip("symlinks unavailable on this host")
else:
target.write_bytes(b"x")
+ if size is not None:
+ with target.open("r+b") as handle:
+ handle.truncate(size)
return target
@@ -7034,7 +7674,8 @@ def test_files_already_cached_skips_unusable_hits(monkeypatch, tmp_path):
probe = DiffusionBackend._files_already_cached
files = ["model_index.json", "vae/diffusion_pytorch_model.safetensors"]
- assert probe(repo, files, sha) == set(files)
+ assert probe(repo, files, sha, {name: 1 for name in files}) == set(files)
+ assert probe(repo, files, sha, {files[0]: 1, files[1]: 2}) == set()
# The dangling link and the file that was never fetched both leave the set incomplete.
assert probe(repo, [*files, "text_encoder/model.safetensors"], sha) == set()
assert probe(repo, [*files, "scheduler/scheduler_config.json"], sha) == set()
@@ -7130,10 +7771,16 @@ def test_download_plan_drops_a_repo_the_fallback_root_holds_whole(monkeypatch, t
DiffusionBackend, "_dense_quant_prefetch_needed", lambda self, fam, kwargs, **_kw: False
)
_all_cached(monkeypatch)
- for name in _FLUX_BASE_SIBLINGS_BY_NAME:
+ for name, size in _FLUX_BASE_SIBLINGS_BY_NAME.items():
if _base_file_downloaded(name, include_transformer = False):
- _seed_cache_file(other, base, name, base_sha)
- _seed_cache_file(other, "unsloth/FLUX.1-dev-GGUF", "flux1-dev-Q4_K_M.gguf", gguf_sha)
+ _seed_cache_file(other, base, name, base_sha, size = size)
+ _seed_cache_file(
+ other,
+ "unsloth/FLUX.1-dev-GGUF",
+ "flux1-dev-Q4_K_M.gguf",
+ gguf_sha,
+ size = 7 * GB,
+ )
plan = DiffusionBackend().download_plan(
"unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf"
@@ -7141,7 +7788,11 @@ def test_download_plan_drops_a_repo_the_fallback_root_holds_whole(monkeypatch, t
# incompatible_reason rides in the same envelope: the plan is where a FLUX.2 GGUF/base
# mismatch is reported, and None is "nothing known to be wrong".
- assert plan == {"entries": [], "total_bytes": 0, "incompatible_reason": None}
+ assert plan["entries"] == []
+ assert plan["total_bytes"] == 0
+ assert plan["incompatible_reason"] is None
+ assert plan["required_bytes"] > 0
+ assert plan["checkpoint_bytes"] == 7 * GB
def test_files_already_cached_survives_an_unreadable_root(monkeypatch, tmp_path):
@@ -7195,7 +7846,7 @@ def test_download_plan_stages_a_half_cached_repo_whole(monkeypatch):
DiffusionBackend,
"_files_already_cached",
staticmethod(
- lambda repo_id, files, revision = None: (
+ lambda repo_id, files, revision = None, declared_sizes = None: (
set()
if repo_id.endswith("-GGUF")
else {n for n in files if n != "vae/diffusion_pytorch_model.safetensors"}
@@ -7250,7 +7901,7 @@ def test_download_plan_files_do_not_shrink_as_a_repo_warms(monkeypatch):
DiffusionBackend,
"_files_already_cached",
staticmethod(
- lambda repo_id, files, revision = None: (
+ lambda repo_id, files, revision = None, declared_sizes = None: (
set() if repo_id.endswith("-GGUF") else set(cached_for_base(files))
)
),
@@ -7324,7 +7975,10 @@ def test_download_plan_pins_each_probe_to_the_commit_it_just_read(monkeypatch):
DiffusionBackend,
"_files_already_cached",
staticmethod(
- lambda repo_id, files, revision = None: seen.append((repo_id, revision)) or set()
+ lambda repo_id, files, revision = None, declared_sizes = None: seen.append(
+ (repo_id, revision)
+ )
+ or set()
),
)
@@ -7363,9 +8017,10 @@ def test_download_plan_skips_nothing_when_the_hub_reports_no_commit(monkeypatch)
repo_id,
files,
revision = None,
+ declared_sizes = None,
):
revisions.append(revision)
- return real(repo_id, files, revision)
+ return real(repo_id, files, revision, declared_sizes)
monkeypatch.setattr(DiffusionBackend, "_files_already_cached", staticmethod(_spy))
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index e25c6137017..243fb2ca711 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -1576,6 +1576,85 @@ def test_download_plan_forwards_the_load_time_controls(client, monkeypatch):
assert len(seen["loras"] or []) == 1
+def test_download_plan_response_keeps_the_planners_checkpoint_marker(client, monkeypatch):
+ # Through the ROUTE, not the planner: the response model is what the picker actually reads, and
+ # a field the planner sets but the model does not declare is dropped silently on serialization.
+ # That is exactly how the checkpoint marker was lost, leaving a mirrored pipeline mislabelled.
+ from core.inference import diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS
+
+ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)
+ backend = diffusion_module.get_diffusion_backend()
+
+ def _plan(model_path, **kwargs):
+ return {
+ "entries": [
+ {
+ "repo_id": "unsloth/FLUX.1-dev", # the ungated MIRROR, not the picked id
+ "files": ["model_index.json"],
+ "bytes": 10,
+ "gguf_filename": None,
+ "checkpoint": True,
+ },
+ {
+ "repo_id": "some/text-encoder",
+ "files": ["model.safetensors"],
+ "bytes": 20,
+ "gguf_filename": None,
+ "checkpoint": False,
+ },
+ ],
+ "total_bytes": 30,
+ "required_bytes": 30,
+ "checkpoint_bytes": 10,
+ }
+
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/FLUX.1-dev-GGUF",
+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",
+ "model_kind": "gguf",
+ },
+ )
+
+ assert resp.status_code == 200
+ assert [e["checkpoint"] for e in resp.json()["entries"]] == [True, False]
+
+
+def test_download_plan_defaults_the_checkpoint_marker_for_an_older_planner(client, monkeypatch):
+ # A plan built before the marker existed must still serialize, defaulting to not-the-checkpoint
+ # so the picker falls back to its own derivation rather than seeing a missing key.
+ from core.inference import diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS
+
+ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)
+ backend = diffusion_module.get_diffusion_backend()
+ monkeypatch.setattr(
+ backend,
+ "download_plan",
+ lambda model_path, **kwargs: {
+ "entries": [{"repo_id": "a/b", "files": ["f"], "bytes": 1}],
+ "total_bytes": 1,
+ },
+ raising = False,
+ )
+
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/FLUX.1-dev-GGUF",
+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",
+ "model_kind": "gguf",
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["entries"][0]["checkpoint"] is False
+
+
def test_download_plan_surfaces_a_gated_base_as_a_400(client, monkeypatch):
# The planner's ValueError has to reach the UI intact: the repo id and licence URL are the fix.
from core.inference import diffusion_engine_router as router
diff --git a/studio/backend/tests/test_gguf_variant_dependency_key.py b/studio/backend/tests/test_gguf_variant_dependency_key.py
new file mode 100644
index 00000000000..292f710992d
--- /dev/null
+++ b/studio/backend/tests/test_gguf_variant_dependency_key.py
@@ -0,0 +1,99 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The per-variant dependency key a GGUF listing carries.
+
+The companion download footprint (text encoders, VAE, tokenizer, configs) is not a
+property of the repo, so a client that resolves it once per repo advertises a
+GB-wrong "Full required size" on every row that is not the one it sampled. The key
+exists so the client can group rows correctly, which means it has to move whenever
+the companion set moves and stay put when it does not.
+"""
+
+from hub.services.models.gguf_variants import _variant_dependency_key
+
+
+KLEIN_REPO = "unsloth/FLUX.2-klein-GGUF"
+
+
+def test_klein_4b_and_9b_in_one_repo_get_different_keys():
+ """sd_cpp_text_encoders_for hands klein-9B Qwen3-8B and klein-4B the family
+ default, keyed on repo id + filename. Same repo, same family, different
+ companions, so a repo-wide footprint is wrong for one of the two rows."""
+ key_4b = _variant_dependency_key(KLEIN_REPO, "flux.2-klein-4b-Q4_K_M.gguf")
+ key_9b = _variant_dependency_key(KLEIN_REPO, "flux.2-klein-9b-Q4_K_M.gguf")
+ assert key_4b is not None and key_9b is not None
+ assert key_4b != key_9b
+
+
+def test_renamed_klein_uses_its_cached_header_size(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.diffusion_compat.flux2_inner_dim_for_pick",
+ lambda *args, **kwargs: 4096,
+ )
+ renamed = _variant_dependency_key(KLEIN_REPO, "renamed-Q4_K_M.gguf")
+ known_9b = _variant_dependency_key(KLEIN_REPO, "flux.2-klein-9b-Q4_K_M.gguf")
+ assert renamed == known_9b
+
+
+def test_unidentified_klein_filenames_do_not_share_a_footprint(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.diffusion_compat.flux2_inner_dim_for_pick",
+ lambda *args, **kwargs: None,
+ )
+ first = _variant_dependency_key(KLEIN_REPO, "renamed-a-Q4_K_M.gguf")
+ second = _variant_dependency_key(KLEIN_REPO, "renamed-b-Q4_K_M.gguf")
+ assert first is not None and second is not None
+ assert first != second
+
+
+def test_two_quants_of_the_same_model_share_one_key():
+ """The common case must stay a single group: the client resolves one footprint
+ per key, and splitting quants of one model would multiply the requests."""
+ assert _variant_dependency_key(
+ KLEIN_REPO, "flux.2-klein-4b-Q4_K_M.gguf"
+ ) == _variant_dependency_key(KLEIN_REPO, "flux.2-klein-4b-Q8_0.gguf")
+
+
+def test_different_families_in_one_neutral_repo_get_different_keys():
+ """detect_family_for_pick falls back to `repo_id/filename`, so a repo whose id
+ matches no family can still hold GGUFs of two families with entirely different
+ base repos."""
+ key_flux = _variant_dependency_key("someone/mixed-gguf", "flux.1-dev-Q4_K_M.gguf")
+ key_qwen = _variant_dependency_key("someone/mixed-gguf", "qwen-image-Q4_K_M.gguf")
+ assert key_flux is not None and key_qwen is not None
+ assert key_flux != key_qwen
+
+
+def test_a_text_model_has_no_key():
+ """No family resolves, so there is nothing to group by. Null, not a made-up key:
+ the client treats an unkeyed listing as one group, which is the old behavior."""
+ assert (
+ _variant_dependency_key(
+ "unsloth/Llama-3.2-1B-Instruct-GGUF", "Llama-3.2-1B-Instruct-Q4_K_M.gguf"
+ )
+ is None
+ )
+
+
+def test_the_key_never_raises_and_makes_no_network_call(monkeypatch):
+ """It runs inside the variant listing, once per row. A family-detection failure
+ must cost the listing nothing, and a socket here would stall the picker."""
+ import hub.services.models.gguf_variants as gv
+
+ def _boom(*args, **kwargs):
+ raise RuntimeError("family registry unavailable")
+
+ monkeypatch.setattr("core.inference.diffusion_families.detect_family_for_pick", _boom)
+ assert gv._variant_dependency_key(KLEIN_REPO, "flux.2-klein-4b-Q4_K_M.gguf") is None
+
+
+def test_the_listing_carries_the_key_per_variant():
+ """The field is on the variant row, not the response, because the response is
+ the repo and the repo is exactly the wrong granularity."""
+ from hub.schemas.inventory import GgufVariantDetail
+
+ field = GgufVariantDetail.model_fields["dependency_key"]
+ assert field.default is None
+ detail = GgufVariantDetail(filename = "a.gguf", quant = "Q4_K_M")
+ assert detail.dependency_key is None
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 37e86b375c4..c11bc6a34fa 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -214,6 +214,200 @@ def test_asset_specs_cover_required_files(fam_name, expect_kinds):
assert tr[0] == "unsloth/x-GGUF" and tr[1] == "x-Q4_K_M.gguf"
[email protected](autouse = True)
+def _plan_sees_an_empty_cache(monkeypatch):
+ """Plan tests describe their cache state, so a developer's real one cannot drop an entry."""
+ from core.inference.diffusion import DiffusionBackend
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kwargs: False),
+ )
+
+
+def test_download_plan_skips_assets_already_in_the_cache(monkeypatch):
+ # _fetch_assets resolves either cache root, so staging a file it can already open re-downloads
+ # it for nothing and fails offline. required_bytes stays the full footprint regardless.
+ from core.inference.diffusion import DiffusionBackend
+
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ monkeypatch.setattr(
+ SdCppDiffusionBackend,
+ "_plan_file_sizes",
+ staticmethod(
+ lambda by_repo, token: {
+ ("unsloth/Z-Image-Turbo-GGUF", "z-image-turbo-Q4_K_M.gguf"): 4_000,
+ ("unsloth/Z-Image-Turbo-ComfyUI", "split_files/vae/ae.safetensors"): 300,
+ (
+ "unsloth/Z-Image-Turbo-ComfyUI",
+ "split_files/text_encoders/qwen_3_4b.safetensors",
+ ): 8_000,
+ }
+ ),
+ )
+ cached = {"z-image-turbo-Q4_K_M.gguf"}
+
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(
+ lambda repo_id, filename, revision = None, expected_size = None, **kwargs: filename
+ in cached
+ ),
+ )
+
+ plan = b.download_plan(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+ cached.add("split_files/vae/ae.safetensors")
+ warming = b.download_plan(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+
+ assert [e["repo_id"] for e in plan["entries"]] == ["unsloth/Z-Image-Turbo-ComfyUI"]
+ assert plan["entries"][0]["files"] == warming["entries"][0]["files"]
+ assert plan["total_bytes"] == 8_300
+ assert warming["total_bytes"] == 8_000
+ assert plan["required_bytes"] == 12_300
+ assert plan["checkpoint_bytes"] == 4_000
+
+
+def test_download_plan_does_not_label_same_repo_companions_as_checkpoint(monkeypatch):
+ import core.inference.sd_cpp_backend as module
+ from core.inference.diffusion import DiffusionBackend
+
+ repo = "unsloth/Z-Image-Turbo-GGUF"
+ checkpoint = "model-Q4_K_M.gguf"
+ companion = "vae/ae.safetensors"
+ backend = SdCppDiffusionBackend(engine = _FakeEngine())
+ monkeypatch.setattr(
+ backend,
+ "_asset_specs",
+ lambda *args, **kwargs: [
+ (repo, checkpoint, "diffusion_model"),
+ (repo, companion, "vae"),
+ ],
+ )
+ monkeypatch.setattr(module, "_fetch_repo_map", lambda specs, token: {repo: repo})
+ monkeypatch.setattr(backend, "_preflight_companion_repos", lambda *args, **kwargs: None)
+ monkeypatch.setattr(
+ backend,
+ "_plan_file_sizes",
+ lambda by_repo, token: {(repo, checkpoint): 4_000, (repo, companion): 300},
+ )
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_loadable",
+ staticmethod(lambda _repo, filename, *_args, **_kwargs: filename == checkpoint),
+ )
+
+ plan = backend.download_plan(repo, gguf_filename = checkpoint, model_kind = "gguf")
+
+ assert plan["entries"][0]["bytes"] == 300
+ assert plan["entries"][0]["checkpoint"] is False
+
+
+def test_download_plan_restages_a_native_asset_a_stale_live_copy_shadows(monkeypatch):
+ # _fetch_assets passes reuse_other_cache_root, but that only switches roots when the LIVE
+ # lookup finds nothing. A stale same-named copy in the live root therefore shadows the good
+ # copy in the other root, so crediting the other root would stage nothing for an asset the
+ # load cannot actually read.
+ from core.inference.diffusion import DiffusionBackend
+
+ shadowed = "split_files/vae/ae.safetensors"
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ **kwargs,
+ ):
+ asks_live = roots is not None and roots != (None,)
+ if filename == shadowed:
+ # Live root: present (no size asked) but wrong bytes. Other root: correct.
+ return expected_size is None if asks_live else True
+ return True
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ assert not DiffusionBackend._hub_file_is_loadable("r", shadowed, None, 300)
+ assert DiffusionBackend._hub_file_is_loadable("r", "other.safetensors", None, 300)
+
+
+def test_download_plan_restages_a_native_asset_that_changed_size(monkeypatch):
+ # A same-named republish is what the cache probe cannot see from the ref alone. The plan
+ # already knows the declared size, so pass it: otherwise the stale copy reads as complete and
+ # the load fetches it inline, outside the manager's progress, cancel and disk preflight.
+ from core.inference.diffusion import DiffusionBackend
+
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ seen = {}
+ monkeypatch.setattr(
+ SdCppDiffusionBackend,
+ "_plan_file_sizes",
+ staticmethod(
+ lambda by_repo, token: {
+ ("unsloth/Z-Image-Turbo-GGUF", "z-image-turbo-Q4_K_M.gguf"): 4_000,
+ ("unsloth/Z-Image-Turbo-ComfyUI", "split_files/vae/ae.safetensors"): 300,
+ (
+ "unsloth/Z-Image-Turbo-ComfyUI",
+ "split_files/text_encoders/qwen_3_4b.safetensors",
+ ): 8_000,
+ }
+ ),
+ )
+
+ def probe(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ **kwargs,
+ ):
+ seen[filename] = expected_size
+ return True
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(probe))
+
+ b.download_plan(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+
+ assert seen["z-image-turbo-Q4_K_M.gguf"] == 4_000
+ assert seen["split_files/vae/ae.safetensors"] == 300
+ assert all(size for size in seen.values()), "an unsized probe trusts the local ref alone"
+
+
+def test_download_plan_is_empty_when_every_native_asset_is_cached(monkeypatch):
+ from core.inference.diffusion import DiffusionBackend
+
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: {})
+ )
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kwargs: True),
+ )
+
+ plan = b.download_plan(
+ "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ model_kind = "gguf",
+ )
+
+ assert plan["entries"] == [] and plan["total_bytes"] == 0
+
+
def test_download_plan_stages_exactly_what_sd_cli_opens(monkeypatch):
# The plan feeds the Hub download manager. Native reads single-file assets, so a native-routed pick must be staged from the asset specs.
b = SdCppDiffusionBackend(engine = _FakeEngine())
@@ -247,12 +441,66 @@ def test_download_plan_stages_exactly_what_sd_cli_opens(monkeypatch):
listed = {(e["repo_id"], f) for e in plan["entries"] for f in e["files"]}
assert listed == expected
assert plan["total_bytes"] == 12_300
+ assert plan["required_bytes"] == 12_300
+ assert plan["checkpoint_bytes"] == 4_000
# The transformer entry is the only one carrying the GGUF filename; the VAE + encoder share one repo entry.
tr = [e for e in plan["entries"] if e["gguf_filename"]]
assert len(tr) == 1 and tr[0]["repo_id"] == "unsloth/Z-Image-Turbo-GGUF"
assert len([e for e in plan["entries"] if e["repo_id"] == "unsloth/Z-Image-Turbo-ComfyUI"]) == 1
+def test_download_plan_merges_asset_repos_that_share_one_fetch_repo(monkeypatch):
+ # Two upstream repos can resolve to ONE fetch repo: on an install that already holds the
+ # Comfy-Org/flux2-dev repack, both unsloth/FLUX.2-VAE and unsloth/FLUX.2-dev-ComfyUI are
+ # served from it. Keying the swapped map by fetch repo therefore drops whichever landed
+ # first, taking its files out of the staged entry AND out of the footprint.
+ import core.inference.sd_cpp_backend as S
+
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ specs = [
+ ("unsloth/FLUX.2-dev-GGUF", "flux2-dev-Q4_K_M.gguf", "transformer"),
+ ("unsloth/FLUX.2-VAE", "vae/ae.safetensors", "vae"),
+ ("unsloth/FLUX.2-dev-ComfyUI", "text_encoders/mistral.safetensors", "text_encoder"),
+ ]
+ monkeypatch.setattr(SdCppDiffusionBackend, "_asset_specs", lambda *a, **k: specs)
+ monkeypatch.setattr(
+ S,
+ "_fetch_repo_map",
+ lambda assets, token: {
+ "unsloth/FLUX.2-dev-GGUF": "unsloth/FLUX.2-dev-GGUF",
+ "unsloth/FLUX.2-VAE": "Comfy-Org/flux2-dev",
+ "unsloth/FLUX.2-dev-ComfyUI": "Comfy-Org/flux2-dev",
+ },
+ )
+ monkeypatch.setattr(SdCppDiffusionBackend, "_preflight_companion_repos", lambda *a, **k: None)
+ sizes = {
+ ("unsloth/FLUX.2-dev-GGUF", "flux2-dev-Q4_K_M.gguf"): 4_000,
+ ("Comfy-Org/flux2-dev", "vae/ae.safetensors"): 300,
+ ("Comfy-Org/flux2-dev", "text_encoders/mistral.safetensors"): 8_000,
+ }
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_plan_file_sizes", staticmethod(lambda by_repo, token: sizes)
+ )
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_loadable",
+ staticmethod(lambda *a, **k: False),
+ )
+
+ plan = b.download_plan(
+ "unsloth/FLUX.2-dev-GGUF", gguf_filename = "flux2-dev-Q4_K_M.gguf", model_kind = "gguf"
+ )
+
+ shared = next(e for e in plan["entries"] if e["repo_id"] == "Comfy-Org/flux2-dev")
+ assert sorted(shared["files"]) == [
+ "text_encoders/mistral.safetensors",
+ "vae/ae.safetensors",
+ ], "neither collapsed repo's files may be dropped"
+ assert plan["required_bytes"] == 12_300
+
+
def test_download_plan_skips_a_local_transformer_but_still_stages_the_assets(monkeypatch, tmp_path):
# A local GGUF folder is already on disk; its VAE + encoder still have to come from the Hub.
b = SdCppDiffusionBackend(engine = _FakeEngine())
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index ea3ce215890..477e548c6fa 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -8,6 +8,7 @@ stack loads."""
import builtins
import contextlib
+from pathlib import Path
import sys
import threading
import time
@@ -2103,6 +2104,255 @@ def _plan_api(monkeypatch, repos):
return _PlanInfo(repos[repo_id])
monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())
+ # These tests describe their cache state explicitly; never let a developer's real Studio
+ # cache make an entry disappear from an otherwise hermetic plan.
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kwargs: False),
+ )
+
+
+def _plan_cache(monkeypatch, cached):
+ """Force the plan's cache verdict for every file."""
+ from core.inference.diffusion import DiffusionBackend
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(
+ lambda repo_id, filename, revision = None, expected_size = None, **kwargs: cached(filename)
+ ),
+ )
+
+
+def test_download_plan_omits_cached_video_files_but_keeps_the_footprint(monkeypatch):
+ # The Video page plans every hub pick, so an unfiltered plan would re-stage a model that is
+ # already on disk. required_bytes stays the full footprint either way.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ _plan_cache(monkeypatch, lambda name: name.endswith(".gguf"))
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ staged = {f for e in plan["entries"] for f in e["files"]}
+ assert "ltx-2.3-22b-distilled.gguf" in staged, "the scoped claim stays stable as the repo warms"
+ assert not any(
+ e["checkpoint"] for e in plan["entries"] if e["repo_id"] == "unsloth/LTX-2.3-GGUF"
+ )
+ assert staged, "its uncached companions still have to be fetched"
+ assert plan["checkpoint_bytes"] > 0
+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])
+ assert plan["required_bytes"] == plan["total_bytes"] + plan["checkpoint_bytes"]
+
+
+def test_download_plan_is_empty_when_the_whole_video_pick_is_cached(monkeypatch):
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ _plan_cache(monkeypatch, lambda name: True)
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ assert plan["entries"] == [] and plan["total_bytes"] == 0
+ # Nothing to fetch, but the load still needs every one of those bytes on disk.
+ assert plan["required_bytes"] > 0
+
+
+def test_download_plan_restages_a_video_file_shadowed_in_the_live_cache(monkeypatch):
+ # The live cache holds a stale copy under the right name and the import-time cache the good
+ # one. reuse_other_cache_root switches roots only when the live lookup resolves nothing, so
+ # the stale entry shadows the good copy: accepting "cached in either root" drops the file from
+ # the plan and the load then reads the stale file or refetches it inline.
+ #
+ # Every OTHER file here lives wholly in the import-time root, so the split branch cannot stage
+ # anything on its own: only recognising the shadow makes this repo straddle the two roots.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ from core.inference.diffusion import DiffusionBackend
+
+ shadowed = "vae/ltx-2.3-22b-distilled_video_vae.safetensors"
+
+ def _cached(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ ):
+ if roots != ("live",):
+ return True # every file has a good copy in the import-time root
+ # The live root holds exactly one file, under the right name and with the wrong bytes.
+ return filename == shadowed and expected_size is None
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(_cached))
+ monkeypatch.setattr("core.inference.video.hub_cache_dir", lambda: "live")
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ staged = {f for e in plan["entries"] for f in e["files"]}
+ assert shadowed in staged, "a shadowed file must be restaged, not trusted"
+ # The shadowed file has to land in the live root, so the rest of that repo now straddles both
+ # and comes with it. The base repo is wholly in the other root and stays untouched.
+ assert staged == {s.rfilename for s in _LTX23_REPO_SIBLINGS} - {
+ "vae/ltx-2.3-22b-dev_video_vae.safetensors"
+ }
+
+
+def test_download_plan_restages_a_video_base_split_across_cache_roots(monkeypatch):
+ # Every file resolves in ONE of the two roots, so a per-file check finds nothing to do. But a
+ # base straddling both roots cannot be handed to from_pretrained as a snapshot:
+ # _predownload_base returns nothing and the assembly is pinned to hub_cache_dir(), so the
+ # other-root subset is refetched inline, or the load fails offline.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ from core.inference.diffusion import DiffusionBackend
+
+ live_root = "live"
+ elsewhere = {
+ "vae/ltx-2.3-22b-distilled_video_vae.safetensors",
+ "vae/ltx-2.3-22b-distilled_audio_vae.safetensors",
+ }
+
+ def _cached(
+ repo_id,
+ filename,
+ revision = None,
+ expected_size = None,
+ roots = None,
+ ):
+ """Half the repo in the live root, half in the other one, nothing missing."""
+ if roots == (live_root,):
+ return filename not in elsewhere
+ return True
+
+ monkeypatch.setattr(DiffusionBackend, "_hub_file_is_cached", staticmethod(_cached))
+ monkeypatch.setattr("core.inference.video.hub_cache_dir", lambda: live_root)
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ entry = next(e for e in plan["entries"] if e["repo_id"] == "unsloth/LTX-2.3-GGUF")
+ expected_scope = {s.rfilename for s in _LTX23_REPO_SIBLINGS} - {
+ "vae/ltx-2.3-22b-dev_video_vae.safetensors"
+ }
+ assert set(entry["files"]) == expected_scope
+ sizes = {s.rfilename: s.size for s in _LTX23_REPO_SIBLINGS}
+ assert entry["bytes"] == sum(sizes[name] for name in elsewhere)
+
+
+def test_download_plan_keeps_a_video_base_that_lives_wholly_in_the_other_root(monkeypatch):
+ # Not a split: reuse_other_cache_root resolves the whole repo from the other root, so staging
+ # any of it would re-download a model that is entirely on disk.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_hub_file_is_cached",
+ staticmethod(
+ lambda repo_id, filename, revision = None, expected_size = None, roots = None: roots
+ != ("live",)
+ ),
+ )
+ monkeypatch.setattr("core.inference.video.hub_cache_dir", lambda: "live")
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ assert plan["entries"] == [] and plan["required_bytes"] > 0
+
+
+def test_a_companion_only_entry_is_not_labelled_the_checkpoint(monkeypatch):
+ # The 2.3 checkpoint and its extras share one repo. With the GGUF already cached and the
+ # extras missing, the stable download scope still names the checkpoint for job adoption,
+ # but only the companion files contribute bytes. Labelling that work as the model file
+ # would misdescribe what the panel is downloading.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ _plan_cache(monkeypatch, lambda name: name.endswith(".gguf"))
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ entry = next(e for e in plan["entries"] if e["repo_id"] == "unsloth/LTX-2.3-GGUF")
+ assert "ltx-2.3-22b-distilled.gguf" in entry["files"]
+ assert entry["bytes"] == 2_400_000_000 + 200_000_000 + 900_000_000
+ assert entry["checkpoint"] is False, "companion files only, so not the model file"
+
+
+def test_the_checkpoint_entry_is_labelled_when_its_file_is_staged(monkeypatch):
+ # The other half of the same rule: nothing cached, so the GGUF itself is in the entry.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/LTX-2.3-GGUF": _LTX23_REPO_SIBLINGS,
+ "Lightricks/LTX-2": _LTX_BASE_SIBLINGS,
+ },
+ )
+ _plan_cache(monkeypatch, lambda name: False)
+
+ plan = VideoBackend().download_plan(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-22b-distilled.gguf",
+ family_override = "ltx-2",
+ )
+
+ entry = next(e for e in plan["entries"] if e["repo_id"] == "unsloth/LTX-2.3-GGUF")
+ assert "ltx-2.3-22b-distilled.gguf" in entry["files"]
+ assert entry["checkpoint"] is True
def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):
@@ -2140,6 +2390,36 @@ def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):
]
assert plan["total_bytes"] == 43
+ assert plan["required_bytes"] == 43
+ assert plan["checkpoint_bytes"] == 19
+ assert by_repo["unsloth/MiniMax-H3-GGUF"]["checkpoint"] is True
+ assert by_repo["Comfy-Org/MiniMax-H3"]["checkpoint"] is False
+
+ _plan_cache(monkeypatch, lambda name: name == "minimax_h3_fl2va-Q4_K_M.gguf")
+ warming = VideoBackend().download_plan(
+ "unsloth/MiniMax-H3-GGUF",
+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
+ family_override = "minimax-h3",
+ model_kind = "gguf",
+ )
+ warming_entry = next(e for e in warming["entries"] if e["repo_id"] == "unsloth/MiniMax-H3-GGUF")
+ assert warming_entry["files"] == by_repo["unsloth/MiniMax-H3-GGUF"]["files"]
+ assert warming_entry["checkpoint"] is False
+
+ _plan_cache(monkeypatch, lambda _name: True)
+ cached = VideoBackend().download_plan(
+ "unsloth/MiniMax-H3-GGUF",
+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
+ family_override = "minimax-h3",
+ model_kind = "gguf",
+ )
+ assert cached == {
+ "entries": [],
+ "total_bytes": 0,
+ "required_bytes": 43,
+ "checkpoint_bytes": 19,
+ }
+
_H3_BASE_SIBLINGS = [
_PlanSibling("transformer/config.json", 1),
@@ -2997,6 +3277,7 @@ def test_fetch_te_prequant_only_reports_what_it_downloaded(monkeypatch):
filename,
token,
cancel_event = None,
+ **kwargs,
):
raise OSError("404")
@@ -3005,7 +3286,7 @@ def test_fetch_te_prequant_only_reports_what_it_downloaded(monkeypatch):
monkeypatch.setattr(
"utils.hf_xet_fallback.hf_hub_download_with_xet_fallback",
- lambda repo, filename, token, cancel_event = None: "/tmp/precast.pt",
+ lambda repo, filename, token, cancel_event = None, **kwargs: "/tmp/precast.pt",
)
assert backend._fetch_te_prequant({"text_encoder": source}, None) == ("text_encoder",)
# A local path override is the injection's business (allowlist), and nothing is fetched for it.
@@ -3495,6 +3776,28 @@ def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, mon
assert "hunyuan_attn_trim" not in status["speed_optims"], mode
+def test_every_video_fetch_resolves_both_cache_roots():
+ """The plan probe accepts a file cached under EITHER root (Studio's cache folder is a
+ setting, so a pre-move download sits under huggingface_hub's import-time root) and stages
+ neither. So every fetch on the load path has to resolve both roots as well, or the file the
+ planner skipped is re-pulled inside the load, outside the manager's progress, cancel and disk
+ preflight -- and fails outright offline. The diffusion and sd.cpp fetches already opt in."""
+ # Every module on the video load path, not just video.py: the LTX-2.3 extras loader lives in
+ # video_ltx2.py and shipped without the opt-in while the plan already skipped its files.
+ root = Path(__file__).resolve().parents[1] / "core/inference"
+ for name in ("video.py", "video_ltx2.py"):
+ src = (root / name).read_text(encoding = "utf-8")
+ # The bare `from ... import name` has no trailing paren, so this counts call sites only.
+ calls = src.count("hf_hub_download_with_xet_fallback(")
+ if calls == 0:
+ continue
+ optins = src.count("reuse_other_cache_root = True")
+ assert optins == calls, (
+ f"{name}: {calls - optins} of {calls} video fetches resolve only the active cache "
+ "root, so the planner's both-roots probe can drop a file the load cannot then find"
+ )
+
+
# ── unified-memory oversize refusal, at the video load seam ───────────────────
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index ba5f6a3dec9..cd84d8678b9 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -144,6 +144,11 @@ export interface GgufVariantDetail {
update_available?: boolean;
/** An interrupted download: some shards are missing, so it cannot load yet. */
partial?: boolean;
+ /** Variants sharing this key share one companion download footprint (text
+ * encoder, VAE, tokenizer, configs). The set is not repo-wide: one repo can
+ * hold GGUFs of different families, and FLUX.2-klein picks its text encoder
+ * per checkpoint size. Null/absent means unknown, so the repo is one group. */
+ dependency_key?: string | null;
}
export interface GgufVariantsResponse {
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
index c22afa84d72..c6dad53bc65 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
@@ -73,6 +73,16 @@ function canUseDownloadManager(pathname: string): boolean {
}
function variantSuffix(job: ManagedDownload): string {
+ if (job.variant?.startsWith("@")) {
+ // The staging page tagged the entry it picked, which is the only reliable answer: a checkpoint
+ // can be a curated single .safetensors and companion repos carry .safetensors too, so the
+ // extension decides nothing. The old guess stays for jobs persisted before the flag existed,
+ // which would otherwise change label mid-download after a restart.
+ const isModelFile =
+ job.checkpoint ??
+ job.scopedFiles?.some((file) => file.toLowerCase().endsWith(".gguf"));
+ return ` · ${isModelFile ? "Model file" : "Required assets"}`;
+ }
return job.variant ? ` · ${job.variant}` : "";
}
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
index 66c4ab2db0a..37d335bc7be 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
@@ -77,6 +77,9 @@ function sanitizePersistedJob(value: unknown): ManagedDownload | null {
value.scopedFiles.every((f) => typeof f === "string")
? { scopedFiles: value.scopedFiles as string[] }
: {}),
+ ...(typeof value.checkpoint === "boolean"
+ ? { checkpoint: value.checkpoint }
+ : {}),
...(isResolvedTransport(value.transport)
? { transport: value.transport }
: {}),
@@ -122,6 +125,7 @@ function toPersistedJob(
? { serverGeneration: job.serverGeneration }
: {}),
...(job.scopedFiles !== undefined ? { scopedFiles: job.scopedFiles } : {}),
+ ...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),
...(job.transport !== undefined ? { transport: job.transport } : {}),
// Alongside the transport, never instead of it: a fallback run reads as
// plain HTTP without this and the reloaded card offers Pause for a stop
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index 88d15f696ce..37cc940c2f7 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -28,6 +28,8 @@ export interface ManagedDownload {
serverGeneration?: number;
/** Files a scoped job is fetching, when known. Every file set of one repo rides the same scope slot (see `scopedVariant`), so this separates "my transfer is already running" from "a different quant of this repo is running": adopting the latter would report ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */
scopedFiles?: string[];
+ /** Set by the page that staged a multi-repo plan: true for the entry that IS the model the user picked, false for the companion repos it needs. Only the stager can tell them apart, since a checkpoint may be a single `.safetensors` and companions carry `.safetensors` too. Undefined on a job persisted before this field existed. */
+ checkpoint?: boolean;
// The transport this run resolved to, so a surface can say whether stopping
// keeps a resumable partial. Absent only when neither the backend nor
// persisted state identifies an adopted job's transport.
@@ -50,6 +52,8 @@ export interface DownloadRequest {
/** Marks a partial-by-design download of `files` only, for a consumer that reads a deliberate subset of a repo (the diffusion loader skips the packaged root single, transformer/ shards and fp16 twins). Set `variant` to `scopedVariant(scopeId)` so this surface keys the job the way the backend does. */
scopeId?: string | null;
files?: string[];
+ /** See `ManagedDownload.checkpoint`. Carried on the request so the job records the role its stager already knew, rather than a surface re-deriving it from filenames. */
+ checkpoint?: boolean;
}
/** The variant slot a scoped job occupies. Mirrors the backend's `_scope_variant`: no GGUF quant label starts with "@", so a scope collides with neither a real variant nor the repo's full snapshot. */
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
index f32d5b3b02b..9ae111c7a06 100644
--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -646,6 +646,12 @@ export async function startJob(
: opts.adopt && existing?.scopedFiles
? { scopedFiles: existing.scopedFiles }
: {}),
+ // The staged plan's own verdict on which entry is the picked model, so the panel labels it without guessing from file extensions. An adopted job keeps the existing record, since only the stager can supply it.
+ ...(req.checkpoint !== undefined
+ ? { checkpoint: req.checkpoint }
+ : opts.adopt && existing?.checkpoint !== undefined
+ ? { checkpoint: existing.checkpoint }
+ : {}),
});
if (!opts.adopt) {
diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
index 316abf8e4bb..69201a6c3a7 100644
--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts
@@ -17,16 +17,27 @@ export interface StagedDownloadEntry {
bytes: number;
/** Set when this entry is a single-file GGUF checkpoint. Informational: it is fetched as a scoped job like every other entry. */
ggufFilename?: string | null;
+ /** True for the entry whose repo is the one the user picked; the rest of the plan is companion repos it needs. The stager is the only place that knows this, so it travels with the job for surfaces that label the two differently. */
+ checkpoint?: boolean;
+}
+
+function entryKey(entry: StagedDownloadEntry): string {
+ return `${entry.repoId}|${[...entry.files].sort().join(",")}`;
}
/** Runs a multi-repo download plan through the shared download manager, then calls `onReady` once every entry is on disk. Chat stages a single repo inline; the diffusion pages need two (a GGUF checkpoint plus its companion base) and read only part of each, so the entries go out as scoped jobs. Staging here rather than inside the load is what puts image and video downloads in the same panel, with the same progress, cancel, resume, disk preflight and manifest verification. */
export function useStagedDownload({
scopeId,
onReady,
+ onCancelled,
}: {
/** Scope label for entries that fetch a file subset (e.g. "diffusion"). */
scopeId: string;
onReady: () => void;
+ /** Clears the consumer's pending auto-load whenever the plan ends without every entry on disk:
+ * cancelled, failed, or never started. A pick is only an intent until then, and leaving it
+ * behind lets a later completion or a deferred page activation load a model nobody asked for. */
+ onCancelled?: () => void;
}) {
const [queue, setQueue] = useState<StagedDownloadEntry[] | null>(null);
const current = queue?.[0] ?? null;
@@ -47,8 +58,6 @@ export function useStagedDownload({
// shares the "@diffusion" variant, so restaging while the first job finishes would let its completion pass for the new pick.
const inFlight = useRef<{ key: string; generation: number } | null>(null);
const generation = useRef(0);
- const entryKey = (entry: StagedDownloadEntry) =>
- `${entry.repoId}|${[...entry.files].sort().join(",")}`;
const isOurs = (variant: string | null | undefined) =>
(variant ?? null) === activeVariant &&
current !== null &&
@@ -74,18 +83,28 @@ export function useStagedDownload({
if (!isOurs(variant)) return;
inFlight.current = null;
setQueue(null);
+ onCancelled?.();
},
onCancelled: (variant) => {
if (!isOurs(variant)) return;
inFlight.current = null;
setQueue(null);
+ onCancelled?.();
},
});
+ // Read through a ref so a consumer's inline callback cannot re-run the start effect and
+ // restart a live download.
+ const onCancelledRef = useRef(onCancelled);
+ onCancelledRef.current = onCancelled;
useEffect(() => {
if (!current) return;
let active = true;
const started = { key: entryKey(current), generation: generation.current };
+ // Register ownership before the start request. The global panel can expose the job as soon as
+ // the controller updates its store, before this await resumes; a very fast cancel/completion in
+ // that window must still belong to this plan.
+ inFlight.current = started;
void (async () => {
const outcome = await downloadManager.requestStart({
kind: DOWNLOAD_KIND.MODEL,
@@ -94,39 +113,31 @@ export function useStagedDownload({
expectedBytes: current.bytes,
scopeId,
files: current.files,
+ checkpoint: current.checkpoint,
});
if (!active) return;
- if (outcome === "started") {
- inFlight.current = started;
- toast.info("Downloading model", {
- description: "It'll load automatically once the download finishes.",
- });
- return;
- }
+ if (outcome === "started") return;
+ if (inFlight.current === started) inFlight.current = null;
// A start that never got off the ground (network failure, rejected scoped request, worker refused) will never complete, so
// clear the queue instead of leaving the head in place, where the effect never re-runs and onReady never fires.
+ // The pick dies with it, so the consumer's pending auto-load has to go too.
if (outcome === "error") {
toast.error("Could not start the download", {
description: "Check the connection, then select the model again.",
});
- setQueue(null);
- return;
- }
- if (outcome === "conflict") {
+ } else if (outcome === "conflict") {
toast.info("Resume this download from Models", {
description:
"An earlier partial download used a different transport. Open the Model hub tab to resume or restart it.",
});
- setQueue(null);
- return;
- }
- if (outcome === "busy") {
+ } else if (outcome === "busy") {
toast.info("Download already in progress", {
description:
"Reselect this model once the running download finishes to load it.",
});
- setQueue(null);
}
+ setQueue(null);
+ onCancelledRef.current?.();
})();
return () => {
active = false;
@@ -138,6 +149,9 @@ export function useStagedDownload({
// A fresh plan supersedes whatever was staged, so bump the generation: a callback for the previous plan's job is no longer ours.
generation.current += 1;
inFlight.current = null;
+ // The Downloads panel is the sole download surface. A second toast duplicated its
+ // progress and exposed another X that looked like cancellation but only dismissed copy.
+ // `onReady` owns the later GPU-load toast, after every queued entry is complete.
setQueue(entries.length > 0 ? entries : null);
}, []);
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index ef1d37a58e0..bc9e713540a 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -173,6 +173,9 @@ export interface GgufVariantDetail {
update_available?: boolean;
partial?: boolean;
partial_transport?: string | null;
+ /** Variants sharing this key share one companion download footprint, so a
+ * footprint resolved for one of them is correct for all of them. */
+ dependency_key?: string | null;
}
export interface GgufVariantsResponse {
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 1450cd08af9..aa3ff152e03 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -277,8 +277,14 @@ export interface DiffusionDownloadPlan {
files: string[];
bytes: number;
gguf_filename: string | null;
+ /** Whether this entry holds the selected model. Only the planner knows, because a gated pick is staged from an ungated mirror under a different repo id. Optional: an older backend omits it. */
+ checkpoint?: boolean;
}[];
total_bytes: number;
+ /** Full declared footprint, including files already present in cache. */
+ required_bytes?: number;
+ /** Selected checkpoint's contribution to required_bytes. */
+ checkpoint_bytes?: number;
/**
* Why this pick cannot load as selected (a FLUX.2 GGUF paired with a different-size base), or
* null/undefined when nothing is known to be wrong. The backend reads metadata only, so it stays
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 79e95c6da60..d4c7d27a485 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -479,7 +479,7 @@ function loadToastDescription(p: DiffusionLoadProgress) {
// "Downloading" only when bytes actually remain: a cached model (or the pre-estimate window) must not claim a download.
const downloading = p.bytes_total > 0 && p.bytes_downloaded < p.bytes_total * 0.999;
const title = downloading
- ? "Downloading model…"
+ ? "Downloading model requirements…"
: p.phase === "finalizing"
? "Loading to GPU…"
: "Starting model…";
@@ -487,7 +487,11 @@ function loadToastDescription(p: DiffusionLoadProgress) {
return (
<ModelLoadDescription
title={title}
- message="Loading the model. This may include downloading its base model."
+ message={
+ downloading
+ ? "Downloading the files required to load this model."
+ : "Loading the model."
+ }
progressPercent={hasTotal ? p.fraction * 100 : null}
progressLabel={
hasTotal
@@ -1099,6 +1103,10 @@ function reportLoadFailure(message: string | null | undefined, fallback: string)
type Busy = "loading" | "unloading" | "generating" | null;
+// What a pick optimistically replaced, so a load that never takes can put all of it back. The quant
+// label and the generation recipe move together at pick time, so they have to roll back together too.
+type PickRevert = { prev: string | null; steps: number; guidance: number };
+
// The Advanced controls a load sends, with "auto" sentinels resolved to omitted. A staged download pins one at pick time.
type LoadAdvanced = Pick<
DiffusionLoadRequest,
@@ -1134,6 +1142,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Z-Image-Turbo official defaults: 9 steps (= 8 DiT forwards), guidance 0 (distilled, CFG-free).
const [steps, setSteps] = useState(DEFAULT_GEN.steps);
const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);
+ // Put back everything a pick optimistically applied. Setters are stable, so this never re-renders on its own.
+ const revertPick = useCallback((r: PickRevert) => {
+ setQuant(r.prev);
+ setSteps(r.steps);
+ setGuidance(r.guidance);
+ }, []);
const [seed, setSeed] = useState("");
// Batch size = images per forward pass (VRAM-heavy); count = sequential loops.
const [batchSize, setBatchSize] = useState(1);
@@ -1264,7 +1278,14 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const lastLoadSig = useRef<string | null>(null);
// The quant to restore if the optimistic swap fails: a same-repo change sets `quant` immediately for picker feedback, but a
// load failing AFTER starting leaves the old pipeline. `{ prev }` distinguishes "revert to null" from "nothing pending".
- const quantRevert = useRef<{ prev: string | null } | null>(null);
+ // A pick also applies its own step/guidance recipe, so the rollback carries those too: a cancelled Turbo pick
+ // otherwise leaves a 4-step, guidance-0 recipe applied to the non-distilled model that is still resident.
+ const quantRevert = useRef<PickRevert | null>(null);
+ // Which quantRevert entry the live staged download belongs to. Staging does not set `busy`, so a second pick can overwrite
+ // quantRevert while the first plan is still resolving; without this the dying first job reverts the newer pick's label.
+ const stagedQuantRevert = useRef<PickRevert | null>(null);
+ // Bumped per Hub pick, so a plan that resolves after a newer pick can tell it has been superseded.
+ const pickSeq = useRef(0);
// The Reapply target to restore if the optimistic swap fails: handleLoad overwrites lastLoad.current at load start, and a
// load failing after that leaves the previous pipeline resident. Mirrors quantRevert.
const lastLoadRevert = useRef<{ prev: typeof lastLoad.current } | null>(null);
@@ -1765,7 +1786,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
setBusy(null);
// A load that failed AFTER starting leaves the previous pipeline loaded, so roll the optimistic quant label back.
if (quantRevert.current) {
- setQuant(quantRevert.current.prev);
+ revertPick(quantRevert.current);
quantRevert.current = null;
}
// Same rollback for the Reapply target: the previous pipeline is still resident.
@@ -1784,7 +1805,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
setBusy(null);
// Same optimistic-quant rollback as the error path: the swap did not take.
if (quantRevert.current) {
- setQuant(quantRevert.current.prev);
+ revertPick(quantRevert.current);
quantRevert.current = null;
}
// Restore the Reapply target too, so it never lingers on the failed pick after a cancel or eviction.
@@ -2125,14 +2146,28 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Set when a staged download finished while this page was hidden: both diffusion pages stay mounted and a load evicts
// whatever holds the GPU. The pick is not dropped; it fires when this page comes back.
const stagedLoadDeferred = useRef(false);
- // A pick made while the download ran already owns the page; only the newest may load. `isLatest`, not `holds`: leaving the
- // page is not a new pick, and the deferred load below is exactly that case.
- const runStagedLoad = useCallback(() => {
- const pending = pendingStagedLoad.current;
- pendingStagedLoad.current = null;
- if (!pending || !pickGuard.isLatest(pending.token)) return;
- void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced);
- }, [pickGuard]);
+ // Both deferred paths run the load minutes after the pick was reported started, so both need
+ // the same rollback: onReady when the page is active, and the effect below when the download
+ // finished off-tab. The deferred load can still be REFUSED, by a training run or another load
+ // claiming the slot while the download ran. Staging started no load, so nothing polls and the
+ // poll's own rollback never runs; without this the selector keeps advertising a quant that was
+ // never loaded. `owned` is read BEFORE the call, so a newer pick's label is left alone.
+ const runStagedLoad = useCallback(
+ (pending: NonNullable<typeof pendingStagedLoad.current>) => {
+ if (pendingStagedLoad.current === pending) pendingStagedLoad.current = null;
+ if (!pickGuard.isLatest(pending.token)) return;
+ const owned = stagedQuantRevert.current;
+ void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced).then((started) => {
+ if (started) return;
+ if (quantRevert.current && quantRevert.current === owned) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ if (stagedQuantRevert.current === owned) stagedQuantRevert.current = null;
+ });
+ },
+ [pickGuard, revertPick],
+ );
const { stage } = useStagedDownload({
scopeId: "diffusion",
onReady: () => {
@@ -2140,65 +2175,122 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
stagedLoadDeferred.current = true;
return;
}
- runStagedLoad();
+ const pending = pendingStagedLoad.current;
+ if (pending) runStagedLoad(pending);
+ },
+ onCancelled: () => {
+ // The selected model is only an intent until every dependency is ready. A cancelled
+ // companion must not leave that intent behind for a late completion/deferred effect to load.
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ // Staging starts no load, so nothing polls and the poll's own rollback never runs: the
+ // optimistic label has to come back here or the selector keeps describing the resident
+ // model with a quant that was never loaded (and the gallery cache persists it). Only for
+ // the pick that staged THIS job: a newer pick owns the label from the moment it is made.
+ if (quantRevert.current && quantRevert.current === stagedQuantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ stagedQuantRevert.current = null;
},
});
useEffect(() => {
if (!active || !stagedLoadDeferred.current) return;
stagedLoadDeferred.current = false;
- runStagedLoad();
+ const pending = pendingStagedLoad.current;
+ if (pending) runStagedLoad(pending);
}, [active, runStagedLoad]);
- // Stage a not-yet-downloaded hub pick, else load it directly. Returns true when the pick was accepted either way.
- // `token` lets an awaiting caller drop out: the plan below is a second window for a newer pick to take the page.
+ // Ask for a cache-aware plan for every Hub pick. The picker only knows whether the selected
+ // checkpoint is cached; image models can still need a separate text encoder/VAE repository.
+ // Returns true when the pick was accepted either way.
+ const requestDownloadPlan = useCallback(
+ (
+ repoId: string,
+ opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
+ advanced: LoadAdvanced,
+ ) =>
+ getDiffusionDownloadPlan({
+ model_path: repoId,
+ gguf_filename: opts.filename,
+ model_kind: opts.kind,
+ // The same token and Advanced values handleLoad sends, so the plan describes the load that will actually run. Without the
+ // token a gated base plans no companion entry; without the memory/quant controls it stages shards the load never opens.
+ hf_token: hfApiToken(getHfToken()),
+ cpu_offload: advanced.cpu_offload,
+ speed_mode: advanced.speed_mode,
+ // Non-GGUF loads ignore this control; the plan must describe the same request as handleLoad.
+ transformer_quant: opts.kind === "gguf" ? advanced.transformer_quant : undefined,
+ memory_mode: advanced.memory_mode,
+ // The backend prefetch decision reads the adapter selection too: a baked LoRA always runs the dense build path. Omitting it
+ // planned a quantized file set and staged too little. Same list handleLoad bakes.
+ loras: advanced.loras,
+ }),
+ [],
+ );
+
const loadOrStage = useCallback(
async (
repoId: string,
opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
- isDownloaded?: boolean,
+ source: ModelSelectorChangeMeta["source"] = "hub",
token?: number,
): Promise<boolean> => {
+ // Staging never sets `busy`, so a second pick passes handleModelSelect's guard while this
+ // plan is still in flight. Plans then resolve in response order, not pick order: without
+ // this the older one restages over the newer queue, or loads the model the user left.
+ // Bumped before the non-hub return too: a local pick must invalidate an in-flight hub plan.
+ const pick = ++pickSeq.current;
+ // The previous pick's staged intent dies with it. A pick that stages nothing (fully cached,
+ // local, no plan) never calls stage(), so the hook's queue keeps running the older job and
+ // its onReady would load the model the user moved away from, evicting this one.
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ stagedQuantRevert.current = null;
const owns = () => token === undefined || pickGuard.holds(token);
- if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);
+ if (!owns()) return true;
+ if (source !== "hub") return handleLoadRef.current(repoId, opts);
// ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.
const advanced = currentLoadAdvanced(repoId);
+ // Read before the await: a pick made while the plan resolves replaces quantRevert, and this job must not revert it.
+ const ownRevert = quantRevert.current;
// Read inside the try, acted on outside it: refusing from in there would fall through to the
- // load on any throw from the refusal itself, which is the one outcome that must not happen.
+ // load if the refusal itself threw, which is the one outcome that must not happen.
let incompatible: string | null = null;
try {
- const plan = await getDiffusionDownloadPlan({
- model_path: repoId,
- gguf_filename: opts.filename,
- model_kind: opts.kind,
- // The same token and Advanced values handleLoad sends, so the plan describes the load that will actually run. Without the
- // token a gated base plans no companion entry; without the memory/quant controls it stages shards the load never opens.
- hf_token: hfApiToken(getHfToken()),
- cpu_offload: advanced.cpu_offload,
- speed_mode: advanced.speed_mode,
- // Dropped for the non-GGUF kinds exactly as handleLoad drops it, so the plan describes
- // the load that will actually run.
- transformer_quant: opts.kind === "gguf" ? advanced.transformer_quant : undefined,
- memory_mode: advanced.memory_mode,
- // The backend prefetch decision reads the adapter selection too: a baked LoRA always runs the dense build path. Omitting it
- // planned a quantized file set and staged too little. Same list handleLoad bakes.
- loras: advanced.loras,
- });
- // Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.
- if (!owns()) return false;
- // Refuse an incompatible pairing HERE, at selection time. The backend also raises it from
- // the load, but only after staging the base repo: the whole point of checking it in the
- // plan is that no byte has moved yet. Returning false reverts the picker's optimistic
- // quant selection, exactly as a load that fails to start does.
+ const plan = await requestDownloadPlan(repoId, opts, advanced);
+ // Superseded. Report started so this pick's `.then` leaves the newer label alone.
+ if (pick !== pickSeq.current || !owns()) return true;
incompatible = plan.incompatible_reason ?? null;
if (!incompatible && plan.entries.length > 0) {
- pendingStagedLoad.current = { repoId, opts, advanced, token: token ?? pickGuard.claim() };
+ pendingStagedLoad.current = {
+ repoId,
+ opts,
+ advanced,
+ token: token ?? pickGuard.claim(),
+ };
+ stagedQuantRevert.current = ownRevert;
stage(
plan.entries.map((e) => ({
repoId: e.repo_id,
files: e.files,
bytes: e.bytes,
ggufFilename: e.gguf_filename,
+ // The entry carrying the picked checkpoint file, so the panel can label it without
+ // guessing: filenames cannot tell the two apart once a checkpoint ships as
+ // .safetensors like its companions do. Repo identity alone is not enough, because a
+ // checkpoint that shares its repo with the companions and is already cached leaves an
+ // entry of companion files only. A pipeline pick has no one file: the repo IS it.
+ // The backend's own answer wins: a gated pipeline is staged from an ungated MIRROR,
+ // so its entry no longer carries the id we picked and the id test below reads the
+ // whole selected model as companion assets. `??`, not `||`: a planner that says false
+ // is answering, and the fallback exists only for a backend too old to send the key.
+ checkpoint:
+ e.checkpoint ??
+ (opts.filename
+ ? e.files.includes(opts.filename)
+ : e.repo_id === repoId),
})),
);
return true;
@@ -2206,14 +2298,34 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
} catch {
// No plan (older backend, metadata hiccup): fall back to the load's own download.
}
- if (!owns()) return false;
+ // Re-checked: a plan that REJECTED after a newer pick would otherwise reach the fallback load.
+ if (pick !== pickSeq.current || !owns()) return true;
if (incompatible) {
toast.error(incompatible);
return false;
}
- return handleLoadRef.current(repoId, opts);
+ return handleLoadRef.current(repoId, opts, advanced);
},
- [stage, currentLoadAdvanced, pickGuard],
+ [stage, currentLoadAdvanced, requestDownloadPlan],
+ );
+
+ const resolveDownloadFootprint = useCallback(
+ async (repoId: string, meta: ModelSelectorChangeMeta) => {
+ if (!meta.ggufFilename) return null;
+ const plan = await requestDownloadPlan(
+ repoId,
+ { kind: "gguf", filename: meta.ggufFilename },
+ currentLoadAdvanced(repoId),
+ );
+ const requiredBytes = plan.required_bytes ?? 0;
+ if (requiredBytes <= 0) return null;
+ return {
+ requiredBytes,
+ checkpointBytes:
+ plan.checkpoint_bytes ?? meta.expectedBytes ?? 0,
+ };
+ },
+ [currentLoadAdvanced, requestDownloadPlan, pickGuard, stage],
);
// A GGUF pick can arrive with only a repo id (a pinned row, a curated artifact, a local GGUF directory). The backend
@@ -2222,13 +2334,13 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
async (
repoId: string,
quantHint: string | null,
- isDownloaded?: boolean,
+ source: ModelSelectorChangeMeta["source"] = "hub",
localPath?: string | null,
): Promise<boolean> => {
// Claimed here so every entry point is covered; the next pick's claim makes this one inert.
const token = pickGuard.claim();
const isCurrent = () => isMounted.current && pickGuard.holds(token);
- const prevQuant = quant;
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
return runGgufRepoPick({
isCurrent,
resolve: () =>
@@ -2242,21 +2354,23 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
toast.error("Pick a quantization for this model to load it"),
// Optimistic label, reverted if the load never starts, like the curated GGUF branch below.
onResolved: (filename) => {
- quantRevert.current = { prev: prevQuant };
+ quantRevert.current = revert;
setQuant(quantHint ?? filename);
const d = defaultsFor(repoId);
setSteps(d.steps);
setGuidance(d.guidance);
},
onNotStarted: () => {
- setQuant(prevQuant);
- quantRevert.current = null;
+ if (quantRevert.current === revert) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
},
load: (filename) =>
- loadOrStage(repoId, { kind: "gguf", filename }, isDownloaded, token),
+ loadOrStage(repoId, { kind: "gguf", filename }, source, token),
});
},
- [loadOrStage, pickGuard, quant],
+ [guidance, loadOrStage, pickGuard, quant, revertPick, steps],
);
// A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.
@@ -2299,7 +2413,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
if (routedLabel) {
// Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.
void Promise.resolve().then(() =>
- loadGgufRepoPick(wanted, routedLabel, false),
+ loadGgufRepoPick(wanted, routedLabel, "hub"),
);
return;
}
@@ -2311,10 +2425,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
);
// A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.
if (pick.opts.kind === "gguf" && !pick.opts.filename) {
- void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, false));
+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
return;
}
- void loadOrStage(pick.repoId, pick.opts, false, token);
+ void loadOrStage(pick.repoId, pick.opts, "hub", token);
}, [
active,
routeSearch.model,
@@ -2332,17 +2446,47 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
if (l) void handleLoad(l.repoId, { kind: l.kind, filename: l.filename });
}, [handleLoad]);
+ // Every pick supersedes the one before it, whichever route it takes. A staged download outlives
+ // its pick, and the direct-local branches call handleLoad rather than loadOrStage, so clearing
+ // only inside loadOrStage left the old job's onReady free to load the abandoned model over the
+ // one just chosen. Bumping the sequence here also invalidates any plan still in flight.
+ // A pick that is rejected after beginPick() has already retired the staged pick it replaced, so
+ // nothing will load and nothing else will restore the label. Hand the resident state back here or
+ // the selector keeps showing the abandoned pick's quant and recipe for good.
+ const abandonPick = useCallback(() => {
+ if (quantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ }, [revertPick]);
+
+ const beginPick = useCallback(() => {
+ pickSeq.current += 1;
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ stagedQuantRevert.current = null;
+ }, []);
+
// The chat picker emits (modelId, quant + filename) for a GGUF, or just (modelId) for a curated safetensors pick.
const handleModelSelect = useCallback(
(id: string, meta: ModelSelectorChangeMeta) => {
// Ignore picks while a load/generation/unload is in flight: the backend rejects a second load with a 409.
if (busy !== null) return;
+ beginPick();
// This pick owns the page now, so one still awaiting a listing or a plan drops out. Before any branch: staging never
// sets `busy`, so any pick can land on an awaiting one.
const token = pickGuard.claim();
// Curated non-GGUF model: load as a full pipeline or single-file safetensors.
const spec = loadSpecFor(id, IMAGE_CATALOG);
if (spec && spec.kind !== "gguf") {
+ // Carried forward when one is already pending: a superseded staged pick left its
+ // optimistic quant and recipe in state, so snapshotting now would record THAT and
+ // restore a model which never loaded. The live entry already holds the resident one.
+ // Registers its own rollback like every other branch. Leaving the previous pick's entry in
+ // place would let that older staged download, on cancelling, revert to state from before it
+ // -- over a selection this pick already replaced -- and leave this one with no rollback.
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(null);
const d = defaultsFor(id);
setSteps(d.steps);
@@ -2350,16 +2494,21 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void loadOrStage(
id,
{ kind: spec.kind, filename: spec.filename },
- meta.isDownloaded,
+ meta.source,
token,
- );
+ ).then((started) => {
+ if (!started && pickGuard.holds(token)) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
return;
}
// GGUF quant pick from the variant expander. Optimistic for instant picker feedback, but revert if the load fails to START
// or LATER in the poll: the old pipeline stays loaded either way. The poll owns the after-start revert via quantRevert.
if (meta.ggufVariant && meta.ggufFilename) {
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(meta.ggufVariant);
const dq = defaultsFor(id);
setSteps(dq.steps);
@@ -2367,12 +2516,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void loadOrStage(
id,
{ kind: "gguf", filename: meta.ggufFilename },
- meta.isDownloaded,
+ meta.source,
token,
).then((started) => {
// `quantRevert` is one slot, so only the pick that set the label may take it back.
if (!started && pickGuard.holds(token)) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -2390,22 +2539,22 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void loadGgufRepoPick(
id,
meta.ggufVariant ?? null,
- meta.isDownloaded,
+ meta.source,
meta.source === "local" ? id : null,
);
return;
}
// A direct pick carries no curated variant label; surface the filename so the selector stops advertising the old quant.
// Optimistic, reverted if the load fails to start OR later in the poll (mirrors the curated branch above).
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(filename);
const dq2 = defaultsFor(id);
setSteps(dq2.steps);
setGuidance(dq2.guidance);
void handleLoad(dir, { kind: "gguf", filename }).then((started) => {
if (!started) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -2418,15 +2567,15 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const slash = norm.lastIndexOf("/");
const filename = slash >= 0 ? norm.slice(slash + 1) : norm;
const dir = slash >= 0 ? norm.slice(0, slash) : ".";
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(filename);
const dsf = defaultsFor(id);
setSteps(dsf.steps);
setGuidance(dsf.guidance);
void handleLoad(dir, { kind: "single_file", filename }).then((started) => {
if (!started) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -2439,7 +2588,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void loadGgufRepoPick(
id,
spec?.filename ?? meta.ggufVariant ?? null,
- meta.isDownloaded,
+ meta.source,
meta.source === "local" ? id : null,
);
return;
@@ -2447,25 +2596,36 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos or on-device paths.
if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {
toast.error("Only unsloth or on-device image models can be loaded here");
+ abandonPick();
return;
}
// Optimistically clear the quant label, revert it if the load never starts.
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(null);
const d = defaultsFor(id);
setSteps(d.steps);
setGuidance(d.guidance);
- void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded, token).then(
- (started) => {
- if (!started && pickGuard.holds(token)) {
- setQuant(prevQuant);
- quantRevert.current = null;
- }
- },
- );
+ void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
+ if (!started && pickGuard.holds(token)) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
},
- [busy, handleLoad, loadGgufRepoPick, loadOrStage, pickGuard, quant],
+ [
+ abandonPick,
+ beginPick,
+ busy,
+ guidance,
+ handleLoad,
+ loadGgufRepoPick,
+ loadOrStage,
+ pickGuard,
+ quant,
+ revertPick,
+ steps,
+ ],
);
// Deploy a freshly-trained adapter from the Train tab: switch to Create, load the base, and queue the adapter for the LoRA discovery effect.
@@ -3022,6 +3182,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
value={status?.loaded ? status.repo_id ?? undefined : undefined}
activeGgufVariant={quant}
onValueChange={handleModelSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onEject={status?.loaded ? handleUnload : undefined}
variant="ghost"
className="!h-[34px] max-w-full overflow-hidden"
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 90cd48897cb..05d0ec95e35 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -56,6 +56,7 @@ import type {
DeletedModelRef,
ExternalModelOption,
LoraModelOption,
+ ModelDownloadFootprintResolver,
ModelOption,
ModelPickTarget,
ModelSelectorChangeMeta,
@@ -146,6 +147,8 @@ interface ModelSelectorProps {
selectedConfig?: PerModelConfig | null;
selectedGgufVariant?: string | null;
onValueChange?: (value: string, meta: ModelSelectorChangeMeta) => void;
+ /** Optional task-specific resolver for companion assets a GGUF row alone cannot describe. */
+ resolveDownloadFootprint?: ModelDownloadFootprintResolver;
onEject?: () => void;
onFoldersChange?: () => void;
onPickLocalModel?: () => void | Promise<void>;
@@ -337,6 +340,7 @@ function ModelSelectorContent({
selectedConfig,
selectedGgufVariant,
onSelect,
+ resolveDownloadFootprint,
onEject,
onFoldersChange,
onPickLocalModel,
@@ -359,6 +363,7 @@ function ModelSelectorContent({
selectedConfig?: PerModelConfig | null;
selectedGgufVariant?: string | null;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
+ resolveDownloadFootprint?: ModelDownloadFootprintResolver;
onEject?: () => void;
onFoldersChange?: () => void;
onPickLocalModel?: () => void;
@@ -606,6 +611,7 @@ function ModelSelectorContent({
externalModels={externalModels}
value={value}
onSelect={handlePick}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onFoldersChange={onFoldersChange}
onBrowseHub={onBrowseHub}
onModelsChange={onModelsChange}
@@ -684,6 +690,7 @@ export function ModelSelector({
selectedConfig,
selectedGgufVariant,
onValueChange,
+ resolveDownloadFootprint,
onEject,
onFoldersChange,
onPickLocalModel,
@@ -828,6 +835,7 @@ export function ModelSelector({
selectedConfig={selectedConfig}
selectedGgufVariant={selectedGgufVariant}
onSelect={handleSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onEject={onEject ? handleEject : undefined}
onFoldersChange={onFoldersChange}
onPickLocalModel={onPickLocalModel ? handlePickLocalModel : undefined}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 97ef8e91429..465cf964481 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -78,6 +78,7 @@ import {
Download01Icon,
Flag01Icon,
Folder02Icon,
+ HelpCircleIcon,
PinIcon,
RemoveCircleIcon,
Search01Icon,
@@ -158,6 +159,7 @@ import type {
ExternalModelOption,
LoraModelOption,
ModelOption,
+ ModelDownloadFootprintResolver,
ModelSelectorChangeMeta,
} from "./types";
import {
@@ -558,6 +560,61 @@ function SizeText({ value }: { value: string }) {
);
}
+/** Keep the row's size treatment consistent with every other model. Diffusion
+ * GGUFs get one small explanation affordance because their checkpoint is only
+ * part of what the loader must keep on disk. The icon is decorative: the
+ * explanation hangs off the row button, the one focusable element here. */
+export function GgufDownloadFootprint({
+ checkpointBytes,
+ companionBytes,
+}: {
+ checkpointBytes: number;
+ companionBytes: number;
+}) {
+ const totalBytes = checkpointBytes + companionBytes;
+ // Whole-GB rounding is too lossy for a sum: "2.6 GB + 8.2 GB = 11 GB"
+ // looks contradictory. Keep one decimal for the aggregate through GB/TB.
+ const totalLabel =
+ totalBytes >= 1_000_000_000 && totalBytes < 1_000_000_000_000
+ ? `${(totalBytes / 1_000_000_000).toFixed(1)} GB`
+ : totalBytes >= 1_000_000_000_000
+ ? `${(totalBytes / 1_000_000_000_000).toFixed(1)} TB`
+ : formatBytes(totalBytes);
+ return (
+ <span
+ data-model-download-footprint={true}
+ className="flex items-center gap-1 whitespace-nowrap text-foreground/80"
+ >
+ <SizeText value={totalLabel} />
+ <span
+ data-model-download-footprint-help={true}
+ aria-hidden={true}
+ className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground/70"
+ >
+ <HugeiconsIcon icon={HelpCircleIcon} className="size-3" strokeWidth={1.8} />
+ </span>
+ </span>
+ );
+}
+
+/** The checkpoint-versus-assets breakdown behind that aggregate. */
+export function GgufDownloadFootprintExplanation({
+ checkpointBytes,
+ companionBytes,
+}: {
+ checkpointBytes: number;
+ companionBytes: number;
+}) {
+ return (
+ <>
+ <span className="font-medium">Full required size</span>
+ <span className="ml-1 text-muted-foreground">
+ {formatBytes(checkpointBytes)} model + {formatBytes(companionBytes)} required assets
+ </span>
+ </>
+ );
+}
+
/** The one quant a row loads, as a compact mono chip. */
function QuantChip({ label }: { label: string }) {
return (
@@ -919,7 +976,13 @@ function isValidGgufVariant(variant: unknown): variant is GgufVariantDetail {
Number.isFinite(candidate.size_bytes) &&
candidate.size_bytes >= 0 &&
(candidate.downloaded === undefined ||
- typeof candidate.downloaded === "boolean")
+ typeof candidate.downloaded === "boolean") &&
+ // Carried through so each row can look up its own dependency group's
+ // footprint. Absent or null on an older backend, which groups the repo as
+ // one, so it must never reject the row.
+ (candidate.dependency_key === undefined ||
+ candidate.dependency_key === null ||
+ typeof candidate.dependency_key === "string")
);
}
@@ -930,6 +993,7 @@ function normalizeGgufVariantsResponse(
default_variant?: unknown;
has_vision?: unknown;
context_length?: unknown;
+ resolved_locally?: unknown;
}
| null
| undefined,
@@ -938,6 +1002,7 @@ function normalizeGgufVariantsResponse(
defaultVariant: string | null;
hasVision: boolean;
contextLength: number | null;
+ resolvedLocally: boolean;
} {
const contextLength = res?.context_length;
return {
@@ -955,6 +1020,10 @@ function normalizeGgufVariantsResponse(
contextLength >= 0
? contextLength
: null,
+ // The backend's own verdict, which resolves existence-first: a marker-less relative name
+ // that exists on disk is a local model even though no path prefix says so. A server that
+ // predates the field omits it, leaving the prefix test to answer alone as before.
+ resolvedLocally: res?.resolved_locally === true,
};
}
@@ -1095,6 +1164,7 @@ function GgufVariantExpander({
loadId,
cachePath,
onSelect,
+ resolveDownloadFootprint,
gpuGb,
systemRamGb,
budgetKnown = false,
@@ -1115,6 +1185,7 @@ function GgufVariantExpander({
/** Cache directory this downloaded row represents, if any. */
cachePath?: string | null;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
+ resolveDownloadFootprint?: ModelDownloadFootprintResolver;
gpuGb?: number;
systemRamGb?: number;
budgetKnown?: boolean;
@@ -1173,6 +1244,9 @@ function GgufVariantExpander({
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [refreshKey, setRefreshKey] = useState(0);
+ // Whether the LISTING resolved this identifier off disk. Not derivable from loadId/cachePath,
+ // which a downloaded hub model also carries.
+ const [resolvedLocally, setResolvedLocally] = useState(false);
const localSource = loadId || cachePath || null;
useEffect(() => {
@@ -1184,6 +1258,9 @@ function GgufVariantExpander({
if (canceled) return;
setLoading(true);
setError(null);
+ // Belongs to the identifier being listed: carrying it over would apply the previous
+ // row's locality to this one's footprint arithmetic.
+ setResolvedLocally(false);
});
// The row's own directory, so disk contents count against that cache, not the active one. No
@@ -1200,6 +1277,7 @@ function GgufVariantExpander({
setHasVision(normalized.hasVision);
onHasVision?.(normalized.hasVision);
setNativeContext(normalized.contextLength);
+ setResolvedLocally(normalized.resolvedLocally);
})
.catch((err) => {
if (canceled) return;
@@ -1219,6 +1297,10 @@ function GgufVariantExpander({
const isLocalPath = /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(
repoId,
);
+ // The prefix test cannot see a marker-less relative directory like "models/my-image-model",
+ // which the backend loads off disk. Whether the checkpoint is on disk decides the footprint
+ // arithmetic, so that question is asked of the listing, not of the spelling.
+ const checkpointIsLocal = isLocalPath || resolvedLocally;
const handleVariantClick = useCallback(
// ``filename`` is required, not decorative: the diffusion pages load a quant with {kind: "gguf", filename} and gate that branch on meta.ggufFilename, so a quant label alone made every Images/Video GGUF pick a dead click.
@@ -1328,6 +1410,106 @@ function GgufVariantExpander({
});
}, [sortedVariants, showAllQuantizations, onDevice]);
+ // A diffusion GGUF is not self-contained: the loader also needs a text
+ // encoder, VAE, tokenizer and configs. That companion set is NOT
+ // repository-wide, so one representative's footprint cannot speak for the
+ // whole listing: a neutral repo can hold GGUFs of different families with
+ // different base repos, and FLUX.2-klein picks a different text encoder for
+ // its 9B checkpoints than for its 4B ones. Both are folded into the
+ // backend's dependency_key, so grouping by it is what keeps a non
+ // representative row from advertising a GB-wrong total. One request per
+ // distinct key: the ordinary repo has exactly one, which is the cost this
+ // representative scheme exists to protect.
+ const footprintVariants = useMemo(() => {
+ const byKey = new Map<string, GgufVariantDetail>();
+ for (const variant of displayVariants ?? []) {
+ // An unkeyed repo (older backend, or no family resolved) collapses to one
+ // group, which is exactly the previous repo-wide behavior.
+ const key = variant.dependency_key ?? "";
+ const current = byKey.get(key);
+ if (current === undefined) {
+ byKey.set(key, variant);
+ continue;
+ }
+ // The recommended quant is the representative of its own group when it
+ // has one; otherwise the group's first row stands.
+ if (
+ current.quant !== effectiveRecommended &&
+ variant.quant === effectiveRecommended
+ ) {
+ byKey.set(key, variant);
+ }
+ }
+ return Array.from(byKey.values());
+ }, [displayVariants, effectiveRecommended]);
+ const [companionBytesByKey, setCompanionBytesByKey] = useState<
+ Map<string, number>
+ >(() => new Map());
+ useEffect(() => {
+ let cancelled = false;
+ setCompanionBytesByKey(new Map());
+ // A local path is resolved too: only the CHECKPOINT is on disk. Its text encoder, VAE,
+ // tokenizer and configs still come from the remote base, which is the larger half of the
+ // footprint, so suppressing the request understated a local row by many gigabytes.
+ if (!resolveDownloadFootprint) {
+ return () => {
+ cancelled = true;
+ };
+ }
+ for (const footprintVariant of footprintVariants) {
+ const dependencyKey = footprintVariant.dependency_key ?? "";
+ const expectedBytes = ggufVariantExpectedBytes(footprintVariant);
+ void resolveDownloadFootprint(repoId, {
+ // Same source the row itself reports, so the plan describes the pick that would run.
+ source: sourceOverride ?? (isLocalPath ? "local" : "hub"),
+ isLora: false,
+ ggufVariant: footprintVariant.quant,
+ ggufFilename: footprintVariant.filename,
+ isDownloaded: footprintVariant.downloaded,
+ expectedBytes,
+ isGguf: true,
+ })
+ .then((footprint) => {
+ if (cancelled || !footprint) return;
+ // A checkpoint already on disk is not part of required_bytes at all, so nothing may
+ // be subtracted for it: the whole figure IS the remote companion set. Subtracting
+ // anyway drove the total to zero and hid a multi-GB companion set behind the
+ // checkpoint size. Only a hub pick carries its checkpoint inside the total, and
+ // expectedBytes stands in when the planner could not size it.
+ const checkpoint = checkpointIsLocal
+ ? 0
+ : footprint.checkpointBytes > 0
+ ? footprint.checkpointBytes
+ : expectedBytes;
+ const companion = footprint.requiredBytes - checkpoint;
+ if (Number.isFinite(companion) && companion > 0) {
+ // A fresh Map per resolution: React compares state by identity, and
+ // the groups resolve independently, so a mutation would drop the
+ // rows whose request landed first.
+ setCompanionBytesByKey((previous) => {
+ const next = new Map(previous);
+ next.set(dependencyKey, companion);
+ return next;
+ });
+ }
+ })
+ .catch(() => {
+ // The checkpoint size remains useful when an older backend or a Hub
+ // metadata failure cannot provide the companion footprint.
+ });
+ }
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ checkpointIsLocal,
+ footprintVariants,
+ isLocalPath,
+ repoId,
+ resolveDownloadFootprint,
+ sourceOverride,
+ ]);
+
const variantOptionKeys = useMemo(
() =>
(displayVariants ?? []).map((variant) =>
@@ -1408,76 +1590,100 @@ function GgufVariantExpander({
const oom = fit === "oom";
const tight = fit === "tight";
const expectedBytes = ggufVariantExpectedBytes(v);
+ // This row's own dependency group, never the listing's: see the
+ // footprintVariants comment above.
+ const companionBytes =
+ companionBytesByKey.get(v.dependency_key ?? "") ?? null;
// A folder has no download to resume; a quant short a shard has no files to load.
const unusableLocal = isLocalPath && v.partial === true;
const keyBase = `${repoId}:${v.filename}`;
const variantOptionKey = makeModelOptionKey("gguf-variant", keyBase);
- return (
- <div key={v.filename} className="flex items-center">
- <button
- type="button"
- {...variantList.getOptionProps(variantOptionKey, false)}
- disabled={unusableLocal}
- onClick={() =>
- handleVariantClick(
- v.quant,
- v.filename,
- v.downloaded,
- expectedBytes,
- )
- }
- className={cn(
- "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-full py-1 pl-2 pr-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
- unusableLocal &&
- "cursor-default opacity-50 hover:bg-transparent dark:hover:bg-transparent",
- )}
- >
- <span className="min-w-0 flex-1 truncate font-mono text-xs">
- <span
- className={cn(oom && "!text-gray-500 dark:!text-gray-400")}
- >
- {/* The key is the selection identity and can be path-qualified
- ("distilled/ltx-2.3-22b-distilled-Q6_K"); the label is what that reads
- as ("Q6_K · distilled"). Everything below still keys on v.quant. */}
- {ggufVariantDisplayLabel(v)}
+ const rowButton = (
+ <button
+ type="button"
+ {...variantList.getOptionProps(variantOptionKey, false)}
+ disabled={unusableLocal}
+ onClick={() =>
+ handleVariantClick(
+ v.quant,
+ v.filename,
+ v.downloaded,
+ expectedBytes,
+ )
+ }
+ className={cn(
+ "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-full py-1 pl-2 pr-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
+ unusableLocal &&
+ "cursor-default opacity-50 hover:bg-transparent dark:hover:bg-transparent",
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">
+ <span
+ className={cn(oom && "!text-gray-500 dark:!text-gray-400")}
+ >
+ {ggufVariantDisplayLabel(v)}
+ </span>
+ {unusableLocal ? (
+ <span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">
+ incomplete
</span>
- {unusableLocal ? (
- <span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">
- incomplete
+ ) : v.downloaded ? (
+ <>
+ <span className="ml-1.5 text-ui-9 font-sans font-medium text-green-600/90 dark:text-green-400/80">
+ downloaded
</span>
- ) : v.downloaded ? (
- <>
- <span className="ml-1.5 text-ui-9 font-sans font-medium text-green-600/90 dark:text-green-400/80">
- downloaded
+ {v.update_available ? (
+ <span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">
+ update available
</span>
- {v.update_available ? (
- <span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">
- update available
- </span>
- ) : null}
- </>
- ) : v.quant === effectiveRecommended ? (
- <span className="ml-1.5 text-ui-9 font-sans font-medium text-primary/70">
- recommended
- </span>
- ) : null}
- </span>
- <span className="flex items-center gap-1.5 shrink-0">
- {oom && (
- <span className="text-ui-9 font-medium !text-red-700 !bg-red-50 dark:!text-red-300 dark:!bg-red-500/15 px-1.5 py-0.5 rounded">
- OOM
- </span>
- )}
- {tight && (
- <span className="text-ui-9 font-medium !text-amber-400">
- TIGHT
- </span>
- )}
- <span className="font-mono text-ui-10 text-muted-foreground tabular-nums">
- <SizeText value={formatBytes(v.size_bytes)} />
+ ) : null}
+ </>
+ ) : v.quant === effectiveRecommended ? (
+ <span className="ml-1.5 text-ui-9 font-sans font-medium text-primary/70">
+ recommended
</span>
+ ) : null}
+ </span>
+ <span className="flex items-center gap-1.5 shrink-0">
+ {oom && (
+ <span className="text-ui-9 font-medium !text-red-700 !bg-red-50 dark:!text-red-300 dark:!bg-red-500/15 px-1.5 py-0.5 rounded">
+ OOM
+ </span>
+ )}
+ {tight && (
+ <span className="text-ui-9 font-medium !text-amber-400">
+ TIGHT
+ </span>
+ )}
+ <span className="font-mono text-ui-10 text-muted-foreground tabular-nums">
+ {companionBytes === null ? (
+ <SizeText value={formatBytes(v.size_bytes)} />
+ ) : (
+ <GgufDownloadFootprint
+ checkpointBytes={v.size_bytes}
+ companionBytes={companionBytes}
+ />
+ )}
</span>
- </button>
+ </span>
+ </button>
+ );
+ return (
+ <div key={v.filename} className="flex items-center">
+ {/* The explanation rides the row button; nested button triggers are not accessible. */}
+ {companionBytes === null ? (
+ rowButton
+ ) : (
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>{rowButton}</TooltipTrigger>
+ <TooltipContent side="top" className="tooltip-compact">
+ <GgufDownloadFootprintExplanation
+ checkpointBytes={v.size_bytes}
+ companionBytes={companionBytes}
+ />
+ </TooltipContent>
+ </Tooltip>
+ )}
{v.downloaded && onConfigure && (
<ModelLoadSettingsAction
ariaLabel={`Inference settings for ${repoId} ${v.quant}`}
@@ -1864,6 +2070,7 @@ export function HubModelPicker({
externalModels = [],
value,
onSelect: onSelectProp,
+ resolveDownloadFootprint,
onFoldersChange,
onBrowseHub,
onModelsChange,
@@ -1882,6 +2089,7 @@ export function HubModelPicker({
externalModels?: ExternalModelOption[];
value?: string;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
+ resolveDownloadFootprint?: ModelDownloadFootprintResolver;
onFoldersChange?: () => void;
/** Open the full Hub page to browse more models. */
onBrowseHub?: () => void;
@@ -3735,6 +3943,7 @@ export function HubModelPicker({
allowPin={true}
onHasVision={(v) => reportVision(c.repo_id, v)}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
hfToken={hfToken || undefined}
parentOptionKey={optionKey}
@@ -4530,6 +4739,7 @@ export function HubModelPicker({
repoId={m.id}
onDevice={true}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
parentOptionKey={optionKey}
onNavigatePastStart={() =>
@@ -4659,6 +4869,7 @@ export function HubModelPicker({
repoId={m.id}
onDevice={true}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
parentOptionKey={optionKey}
onNavigatePastStart={() =>
@@ -4774,6 +4985,7 @@ export function HubModelPicker({
repoId={m.id}
onDevice={true}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
parentOptionKey={optionKey}
onNavigatePastStart={() =>
@@ -4864,6 +5076,7 @@ export function HubModelPicker({
<GgufVariantExpander
repoId={id}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
hfToken={hfToken || undefined}
parentOptionKey={optionKey}
@@ -4981,6 +5194,7 @@ export function HubModelPicker({
<GgufVariantExpander
repoId={id}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
hfToken={hfToken || undefined}
parentOptionKey={optionKey}
@@ -5087,6 +5301,7 @@ export function HubModelPicker({
<GgufVariantExpander
repoId={id}
onSelect={onSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
hfToken={hfToken || undefined}
parentOptionKey={optionKey}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index 63cc51c175f..15a827bdf00 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -50,6 +50,18 @@ export interface ModelSelectorChangeMeta {
nativePathExpiresAtMs?: number | null;
}
+/** Full on-disk requirement for a model pick, including its checkpoint and
+ * companion assets (text encoders, VAE, tokenizer/config files, etc.). */
+export interface ModelDownloadFootprint {
+ requiredBytes: number;
+ checkpointBytes: number;
+}
+
+export type ModelDownloadFootprintResolver = (
+ id: string,
+ meta: ModelSelectorChangeMeta,
+) => Promise<ModelDownloadFootprint | null>;
+
export interface ModelPickTarget {
id: string;
displayName: string;
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 15fe4f1021a..8829a9547bf 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -96,6 +96,7 @@ import {
type VideoReferenceVideo,
type VideoLoadProgress,
type VideoStatus,
+ type VideoLoadRequest,
cancelVideoGeneration,
clearVideoGallery,
deleteGalleryVideo,
@@ -661,6 +662,19 @@ function RecipeRow({
type Busy = "loading" | "unloading" | "generating" | null;
+// What a pick optimistically replaced, so a load that never takes can put all of it back. The quant
+// label and the generation recipe move together at pick time, so they have to roll back together too.
+type PickRevert = { prev: string | null; steps: number; guidance: number };
+// Resolved Advanced controls pinned across preflight, staging, and load.
+type VideoLoadAdvanced = Pick<
+ VideoLoadRequest,
+ | "memory_mode"
+ | "speed_mode"
+ | "attention_backend"
+ | "transformer_cache"
+ | "transformer_quant"
+>;
+
// Centered panel used for both halves of the capability gate below: the wait, and the answer.
function VideoGate({ children }: { children: ReactNode }) {
return (
@@ -724,6 +738,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const [negativeOpen, setNegativeOpen] = useState(false);
const [steps, setSteps] = useState(DEFAULT_GEN.steps);
const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);
+ // Put back everything a pick optimistically applied. Setters are stable, so this never re-renders on its own.
+ const revertPick = useCallback((r: PickRevert) => {
+ setQuant(r.prev);
+ setSteps(r.steps);
+ setGuidance(r.guidance);
+ }, []);
const [seed, setSeed] = useState("");
// Preset index, or MATCH_SOURCE_RESOLUTION for a keyframe-derived canvas.
const [resolutionIdx, setResolutionIdx] = useState(0);
@@ -812,7 +832,14 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Last load-progress signature shown, so a tick that moved nothing skips the toast.
const lastLoadSig = useRef<string | null>(null);
// The quant to restore if the current optimistic swap fails.
- const quantRevert = useRef<{ prev: string | null } | null>(null);
+ // A pick also applies its own step/guidance recipe, so the rollback carries those too: a cancelled distilled
+ // pick otherwise leaves its low-step, guidance-0 recipe applied to the model that is still resident.
+ const quantRevert = useRef<PickRevert | null>(null);
+ // Which quantRevert entry the live staged download belongs to. Staging does not set `busy`, so a second pick can overwrite
+ // quantRevert while the first plan is still resolving; without this the dying first job reverts the newer pick's label.
+ const stagedQuantRevert = useRef<PickRevert | null>(null);
+ // Bumped per Hub pick, so a plan that resolves after a newer pick can tell it has been superseded.
+ const pickSeq = useRef(0);
// The Reapply target (and its canReapply flag) to restore if the optimistic swap fails: handleLoad overwrites lastLoad at
// load start, and a load failing AFTER that leaves the previous model resident, so the poll rolls it back.
const lastLoadRevert = useRef<{ prev: typeof lastLoad.current; canReapply: boolean } | null>(null);
@@ -1383,7 +1410,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
reportLoadFailure(p.error, "Failed to load model");
setBusy(null);
if (quantRevert.current) {
- setQuant(quantRevert.current.prev);
+ revertPick(quantRevert.current);
quantRevert.current = null;
}
// Same rollback for the Reapply target: the previous model is still resident, so point Reapply back at it.
@@ -1400,7 +1427,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
dismissLoadToast();
setBusy(null);
if (quantRevert.current) {
- setQuant(quantRevert.current.prev);
+ revertPick(quantRevert.current);
quantRevert.current = null;
}
// Restore the Reapply target too, so it never lingers on the failed pick after a cancel or eviction.
@@ -1545,6 +1572,61 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
};
}, [refreshStatus, dismissLoadToast, pollLoadProgress, startGenPoll, stopGenPoll, ensureSrc, cancelLoadFromToast]);
+ // Keep the snapshot helper stable: route effects depend on loadOrStage.
+ const loadControlsRef = useRef({
+ memoryMode,
+ speedMode,
+ attentionBackend,
+ transformerCache,
+ transformerQuant,
+ });
+ loadControlsRef.current = {
+ memoryMode,
+ speedMode,
+ attentionBackend,
+ transformerCache,
+ transformerQuant,
+ };
+ const currentLoadAdvanced = useCallback(
+ (kind: "gguf" | "single_file" | "pipeline"): VideoLoadAdvanced => {
+ const controls = loadControlsRef.current;
+ return {
+ memory_mode: controls.memoryMode === "auto" ? undefined : controls.memoryMode,
+ speed_mode: controls.speedMode === "auto" ? undefined : controls.speedMode,
+ attention_backend:
+ controls.attentionBackend === "auto" ? undefined : controls.attentionBackend,
+ transformer_cache:
+ controls.transformerCache === "auto" ? undefined : controls.transformerCache,
+ transformer_quant:
+ kind === "pipeline" && controls.transformerQuant !== "auto"
+ ? controls.transformerQuant
+ : undefined,
+ };
+ },
+ [],
+ );
+ const resolveDownloadFootprint = useCallback(
+ async (repoId: string, meta: ModelSelectorChangeMeta) => {
+ if (!meta.ggufFilename) return null;
+ const advanced = currentLoadAdvanced("gguf");
+ const plan = await getVideoDownloadPlan({
+ model_path: repoId,
+ gguf_filename: meta.ggufFilename,
+ model_kind: "gguf",
+ hf_token: hfApiToken(getHfToken()),
+ transformer_quant: advanced.transformer_quant,
+ memory_mode: advanced.memory_mode,
+ });
+ const requiredBytes = plan.required_bytes ?? 0;
+ if (requiredBytes <= 0) return null;
+ return {
+ requiredBytes,
+ checkpointBytes: plan.checkpoint_bytes ?? meta.expectedBytes ?? 0,
+ };
+ },
+ [currentLoadAdvanced],
+ );
+
const handleLoad = useCallback(
// Resolves true when the background load STARTED (callers may revert optimistic picker state on false).
async (
@@ -1553,6 +1635,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
kind: "gguf" | "single_file" | "pipeline";
filename?: string;
},
+ // Staged loads use the controls their preflight validated.
+ pinned?: VideoLoadAdvanced,
): Promise<boolean> => {
if (pollTimer.current) clearTimeout(pollTimer.current);
// Read BEFORE the start request goes out: a Cancel pressed while it is in flight sends an
@@ -1580,26 +1664,23 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Snapshot the prior Reapply target first: a load that fails to START leaves the previous model resident, so Reapply must keep pointing at it.
const prevLastLoad = lastLoad.current;
const prevCanReapply = canReapply;
+ const advanced = pinned ?? currentLoadAdvanced(opts.kind);
lastLoad.current = { repoId, kind: opts.kind, filename: opts.filename };
setCanReapply(true);
// Carry the prior target so the async poll can restore it if the background load fails after starting.
lastLoadRevert.current = { prev: prevLastLoad, canReapply: prevCanReapply };
try {
- // Returns immediately -- the load runs in the background and we poll. The backend infers the family + base repo from the id; the "auto"/"off" sentinels map to omitted.
+ // Returns immediately; the load runs in the background and we poll.
const startRequest = loadVideoModel({
model_path: repoId,
model_kind: opts.kind,
gguf_filename: opts.filename,
hf_token: hfApiToken(getHfToken()),
- memory_mode: memoryMode === "auto" ? undefined : memoryMode,
- speed_mode: speedMode === "auto" ? undefined : speedMode,
- attention_backend: attentionBackend === "auto" ? undefined : attentionBackend,
- transformer_cache: transformerCache === "auto" ? undefined : transformerCache,
- // Full-pipeline loads only: a GGUF / single-file DiT runs the precision its checkpoint
- // carries. The Precision control is hidden for those kinds but the state persists across
- // picks, so a stale scheme would reach a load that can only refuse it.
- transformer_quant:
- opts.kind === "pipeline" && transformerQuant !== "auto" ? transformerQuant : undefined,
+ memory_mode: advanced.memory_mode,
+ speed_mode: advanced.speed_mode,
+ attention_backend: advanced.attention_backend,
+ transformer_cache: advanced.transformer_cache,
+ transformer_quant: advanced.transformer_quant,
});
await startRequest;
} catch (err) {
@@ -1642,11 +1723,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
dismissLoadToast,
cancelLoadFromToast,
canReapply,
- memoryMode,
- speedMode,
- attentionBackend,
- transformerCache,
- transformerQuant,
+ currentLoadAdvanced,
],
);
@@ -1654,33 +1731,36 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const pendingStagedLoad = useRef<{
repoId: string;
opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string };
+ advanced: VideoLoadAdvanced;
// The pick that staged it: a download outlives its pick, so it must not evict a newer one when it lands.
token: number;
} | null>(null);
const handleLoadRef = useRef(handleLoad);
handleLoadRef.current = handleLoad;
- // Read through a ref for the same reason handleLoad is: loadOrStage is memoized so its
- // consumers keep a stable identity, and a plain capture froze the precision at whatever was
- // selected when the callback was built. The ordinary auto -> FP8 change then sent the plan no
- // precision at all, skipping the pre-download refusal, and the user staged tens of GB before
- // /video/load rejected the same pick.
- const transformerQuantRef = useRef(transformerQuant);
- transformerQuantRef.current = transformerQuant;
- // And the memory request, for the same reason and through the same ref: the route refuses an
- // explicit precision under balanced or low_vram only when it is told the memory mode, so a
- // plan asked without it staged tens of GB and left the 409 to the load.
- const memoryModeRef = useRef(memoryMode);
- memoryModeRef.current = memoryMode;
// A download finishing while this page is hidden must not evict the model the visible page loaded. The pick is held, not dropped.
const stagedLoadDeferred = useRef(false);
- // A pick made while the download ran already owns the page; only the newest may load. `isLatest`, not `holds`: leaving the
- // page is not a new pick, and the deferred load below is exactly that case.
- const runStagedLoad = useCallback(() => {
- const pending = pendingStagedLoad.current;
- pendingStagedLoad.current = null;
- if (!pending || !pickGuard.isLatest(pending.token)) return;
- void handleLoadRef.current(pending.repoId, pending.opts);
- }, [pickGuard]);
+ // Both deferred paths run the load minutes after the pick was reported started, so both need
+ // the same rollback: onReady when the page is active, and the effect below when the download
+ // finished off-tab. The deferred load can still be REFUSED, by a training run or another load
+ // claiming the slot while the download ran. Staging started no load, so nothing polls and the
+ // poll's own rollback never runs; without this the selector keeps advertising a quant that was
+ // never loaded. `owned` is read BEFORE the call, so a newer pick's label is left alone.
+ const runStagedLoad = useCallback(
+ (pending: NonNullable<typeof pendingStagedLoad.current>) => {
+ if (pendingStagedLoad.current === pending) pendingStagedLoad.current = null;
+ if (!pickGuard.isLatest(pending.token)) return;
+ const owned = stagedQuantRevert.current;
+ void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced).then((started) => {
+ if (started) return;
+ if (quantRevert.current && quantRevert.current === owned) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ if (stagedQuantRevert.current === owned) stagedQuantRevert.current = null;
+ });
+ },
+ [pickGuard, revertPick],
+ );
const { stage } = useStagedDownload({
scopeId: "diffusion",
onReady: () => {
@@ -1688,14 +1768,31 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
stagedLoadDeferred.current = true;
return;
}
- runStagedLoad();
+ const pending = pendingStagedLoad.current;
+ if (pending) runStagedLoad(pending);
+ },
+ onCancelled: () => {
+ // Same rule as the images page: a plan that ends without every dependency on disk must not
+ // leave an intent for a late completion or a deferred activation to act on.
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ // No load started, so the poll that owns the after-start rollback never runs: put the
+ // optimistic quant label back, or the selector describes the resident model with a
+ // quant nothing ever loaded. Only for the pick that staged THIS job: a newer pick owns
+ // the label from the moment it is made.
+ if (quantRevert.current && quantRevert.current === stagedQuantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ stagedQuantRevert.current = null;
},
});
useEffect(() => {
if (!active || !stagedLoadDeferred.current) return;
stagedLoadDeferred.current = false;
- runStagedLoad();
+ const pending = pendingStagedLoad.current;
+ if (pending) runStagedLoad(pending);
}, [active, runStagedLoad]);
// Stage a not-yet-downloaded hub pick, else load it directly.
@@ -1704,11 +1801,30 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
async (
repoId: string,
opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
- isDownloaded?: boolean,
+ source: ModelSelectorChangeMeta["source"] = "hub",
token?: number,
): Promise<boolean> => {
+ // Every Hub pick needs the plan, not just an undownloaded one: a cached checkpoint can
+ // still be missing its base repo's text encoder or VAE, and only the plan can see that.
+ // The plan is cache-aware, so a fully cached pick comes back with no entries.
+ // Staging never sets `busy`, so a second pick passes handleModelSelect's guard while this
+ // plan is still in flight. Plans then resolve in response order, not pick order: without
+ // this the older one restages over the newer queue, or loads the model the user left.
+ // Bumped before the non-hub return too: a local pick must invalidate an in-flight hub plan.
+ const pick = ++pickSeq.current;
+ // The previous pick's staged intent dies with it. A pick that stages nothing (fully cached,
+ // local, no plan) never calls stage(), so the hook's queue keeps running the older job and
+ // its onReady would load the model the user moved away from, evicting this one.
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ stagedQuantRevert.current = null;
const owns = () => token === undefined || pickGuard.holds(token);
- if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);
+ if (!owns()) return true;
+ if (source !== "hub") return handleLoadRef.current(repoId, opts);
+
+ const advanced = currentLoadAdvanced(opts.kind);
+ // Read before the await: a pick made while the plan resolves replaces quantRevert, and this job must not revert it.
+ const ownRevert = quantRevert.current;
// Read inside the try, acted on outside it, as on the images page.
let incompatible: string | null = null;
try {
@@ -1718,20 +1834,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
model_kind: opts.kind,
// Same token handleLoad sends: without it the metadata lookup fails on a gated base and the plan drops the companion entry, so the load pulls those files inline.
hf_token: hfApiToken(getHfToken()),
- // And the same precision, for the same reason: the plan refuses a scheme this host
- // cannot honour, so omitting it staged tens of GB of weights and left the refusal to
- // the load afterwards. Sent under the identical pipeline-only rule handleLoad applies.
- transformer_quant:
- opts.kind === "pipeline" && transformerQuantRef.current !== "auto"
- ? transformerQuantRef.current
- : undefined,
- // The same memory request handleLoad sends: the precision gate refuses the
- // offload-forcing modes only when it can see them.
- memory_mode:
- memoryModeRef.current === "auto" ? undefined : memoryModeRef.current,
+ // The route preflights the same values used by the eventual load.
+ transformer_quant: advanced.transformer_quant,
+ memory_mode: advanced.memory_mode,
});
- // Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.
- if (!owns()) return false;
+ // Superseded. Report started so this pick's `.then` leaves the newer label alone.
+ if (pick !== pickSeq.current || !owns()) return true;
// Same selection-time refusal the images page makes: the plan is the last point at which
// an incompatible pairing can be caught before the download it would waste. No video
// family declares one today (the check is the FLUX.2 GGUF/base size pairing, and the video
@@ -1739,13 +1847,33 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// the contract rather than a live path -- keep it, or a future one lands unguarded.
incompatible = plan.incompatible_reason ?? null;
if (!incompatible && plan.entries.length > 0) {
- pendingStagedLoad.current = { repoId, opts, token: token ?? pickGuard.claim() };
+ pendingStagedLoad.current = {
+ repoId,
+ opts,
+ advanced,
+ token: token ?? pickGuard.claim(),
+ };
+ stagedQuantRevert.current = ownRevert;
stage(
plan.entries.map((e) => ({
repoId: e.repo_id,
files: e.files,
bytes: e.bytes,
ggufFilename: e.gguf_filename,
+ // The entry carrying the picked checkpoint file, so the panel can label it without
+ // guessing: filenames cannot tell the two apart once a checkpoint ships as
+ // .safetensors like its companions do. Repo identity alone is not enough, because a
+ // checkpoint that shares its repo with the companions and is already cached leaves an
+ // entry of companion files only. A pipeline pick has no one file: the repo IS it.
+ // The backend's own answer wins: a gated pipeline is staged from an ungated MIRROR,
+ // so its entry no longer carries the id we picked and the id test below reads the
+ // whole selected model as companion assets. `??`, not `||`: a planner that says false
+ // is answering, and the fallback exists only for a backend too old to send the key.
+ checkpoint:
+ e.checkpoint ??
+ (opts.filename
+ ? e.files.includes(opts.filename)
+ : e.repo_id === repoId),
})),
);
return true;
@@ -1753,14 +1881,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
} catch {
// No plan (older backend, metadata hiccup): fall back to the load's own download.
}
- if (!owns()) return false;
+ // Re-checked: a plan that REJECTED after a newer pick would otherwise reach the fallback load.
+ if (pick !== pickSeq.current || !owns()) return true;
if (incompatible) {
toast.error(incompatible);
return false;
}
- return handleLoadRef.current(repoId, opts);
+ return handleLoadRef.current(repoId, opts, advanced);
},
- [stage, pickGuard],
+ [stage, pickGuard, currentLoadAdvanced],
);
// A GGUF pick can arrive with only a repo id (a pinned row, a curated artifact, a local GGUF directory). The backend
@@ -1769,13 +1898,13 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
async (
repoId: string,
quantHint: string | null,
- isDownloaded?: boolean,
+ source: ModelSelectorChangeMeta["source"] = "hub",
localPath?: string | null,
): Promise<boolean> => {
// Claimed here so every entry point is covered; the next pick's claim makes this one inert.
const token = pickGuard.claim();
const isCurrent = () => isMounted.current && pickGuard.holds(token);
- const prevQuant = quant;
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
return runGgufRepoPick({
isCurrent,
resolve: () =>
@@ -1789,7 +1918,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
toast.error("Pick a quantization for this model to load it"),
// Optimistic label, reverted if the load never starts, like the curated GGUF branch below.
onResolved: (filename) => {
- quantRevert.current = { prev: prevQuant };
+ quantRevert.current = revert;
setQuant(quantHint ?? filename);
// Filename-qualified like the expander branch: the LTX variant lives in the checkpoint name, not the repo id.
const d = defaultsFor(`${repoId}/${filename}`);
@@ -1797,14 +1926,16 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
setGuidance(d.guidance);
},
onNotStarted: () => {
- setQuant(prevQuant);
- quantRevert.current = null;
+ if (quantRevert.current === revert) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
},
load: (filename) =>
- loadOrStage(repoId, { kind: "gguf", filename }, isDownloaded, token),
+ loadOrStage(repoId, { kind: "gguf", filename }, source, token),
});
},
- [loadOrStage, pickGuard, quant],
+ [guidance, loadOrStage, pickGuard, quant, revertPick, steps],
);
// A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.
@@ -1846,7 +1977,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
if (routedLabel) {
// Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.
void Promise.resolve().then(() =>
- loadGgufRepoPick(wanted, routedLabel, false),
+ loadGgufRepoPick(wanted, routedLabel, "hub"),
);
return;
}
@@ -1858,10 +1989,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
);
// A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.
if (pick.opts.kind === "gguf" && !pick.opts.filename) {
- void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, false));
+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
return;
}
- void loadOrStage(pick.repoId, pick.opts, false, token);
+ void loadOrStage(pick.repoId, pick.opts, "hub", token);
}, [
active,
routeSearch.model,
@@ -1880,16 +2011,46 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
}, [handleLoad]);
// The chat picker emits (modelId, quant + filename) for a GGUF, or just (modelId) for a curated pipeline pick.
+ // Every pick supersedes the one before it, whichever route it takes. A staged download outlives
+ // its pick, and the direct-local branches call handleLoad rather than loadOrStage, so clearing
+ // only inside loadOrStage left the old job's onReady free to load the abandoned model over the
+ // one just chosen. Bumping the sequence here also invalidates any plan still in flight.
+ // A pick that is rejected after beginPick() has already retired the staged pick it replaced, so
+ // nothing will load and nothing else will restore the label. Hand the resident state back here or
+ // the selector keeps showing the abandoned pick's quant and recipe for good.
+ const abandonPick = useCallback(() => {
+ if (quantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ }, [revertPick]);
+
+ const beginPick = useCallback(() => {
+ pickSeq.current += 1;
+ pendingStagedLoad.current = null;
+ stagedLoadDeferred.current = false;
+ stagedQuantRevert.current = null;
+ }, []);
+
const handleModelSelect = useCallback(
(id: string, meta: ModelSelectorChangeMeta) => {
// Ignore picks while a load/generation/unload is in flight.
if (busy !== null) return;
+ beginPick();
// This pick owns the page now, so one still awaiting a listing or a plan drops out. Before any branch: staging never
// sets `busy`, so any pick can land on an awaiting one.
const token = pickGuard.claim();
// Curated non-GGUF model: load as a full pipeline.
const spec = loadSpecFor(id, VIDEO_CATALOG);
if (spec && spec.kind !== "gguf") {
+ // Carried forward when one is already pending: a superseded staged pick left its
+ // optimistic quant and recipe in state, so snapshotting now would record THAT and
+ // restore a model which never loaded. The live entry already holds the resident one.
+ // Registers its own rollback like every other branch. Leaving the previous pick's entry in
+ // place would let that older staged download, on cancelling, revert to state from before it
+ // -- over a selection this pick already replaced -- and leave this one with no rollback.
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(null);
// The distilled variant lives in the checkpoint name, not the repo id, so include the filename when seeding defaults.
// Without it these distilled entries fall through to the generic LTX 40-step/CFG-4 defaults instead of the 8-step schedule.
@@ -1899,15 +2060,20 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void loadOrStage(
id,
{ kind: spec.kind, filename: spec.filename },
- meta.isDownloaded,
+ meta.source,
token,
- );
+ ).then((started) => {
+ if (!started && pickGuard.holds(token)) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
return;
}
// GGUF quant pick from the variant expander. Optimistic for picker feedback, reverted if the load fails to START; the poll owns the after-start revert.
if (meta.ggufVariant && meta.ggufFilename) {
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(meta.ggufVariant);
// Include the picked filename: the variant (distilled vs dev) lives there, not in the repo id.
const dq = defaultsFor(`${id}/${meta.ggufFilename}`);
@@ -1916,12 +2082,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void loadOrStage(
id,
{ kind: "gguf", filename: meta.ggufFilename },
- meta.isDownloaded,
+ meta.source,
token,
).then((started) => {
// `quantRevert` is one slot, so only the pick that set the label may take it back.
if (!started && pickGuard.holds(token)) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -1939,20 +2105,20 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void loadGgufRepoPick(
id,
meta.ggufVariant ?? null,
- meta.isDownloaded,
+ meta.source,
meta.source === "local" ? id : null,
);
return;
}
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(filename);
const dq2 = defaultsFor(id);
setSteps(dq2.steps);
setGuidance(dq2.guidance);
void handleLoad(dir, { kind: "gguf", filename }).then((started) => {
if (!started) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -1964,15 +2130,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const slash = norm.lastIndexOf("/");
const filename = slash >= 0 ? norm.slice(slash + 1) : norm;
const dir = slash >= 0 ? norm.slice(0, slash) : ".";
- const prevQuant = quant;
- quantRevert.current = { prev: prevQuant };
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(filename);
const dsf = defaultsFor(id);
setSteps(dsf.steps);
setGuidance(dsf.guidance);
void handleLoad(dir, { kind: "single_file", filename }).then((started) => {
if (!started) {
- setQuant(prevQuant);
+ revertPick(revert);
quantRevert.current = null;
}
});
@@ -1985,7 +2151,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void loadGgufRepoPick(
id,
spec?.filename ?? meta.ggufVariant ?? null,
- meta.isDownloaded,
+ meta.source,
meta.source === "local" ? id : null,
);
return;
@@ -1993,15 +2159,37 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos, the family bases, or on-device paths.
if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {
toast.error("Only unsloth or on-device video models can be loaded here");
+ abandonPick();
return;
}
+ // Its own rollback, like every other branch: leaving the previous pick's entry live lets an
+ // older staged download revert over a selection this pick already replaced.
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(null);
const d = defaultsFor(id);
setSteps(d.steps);
setGuidance(d.guidance);
- void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded, token);
+ void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
+ if (!started && pickGuard.holds(token)) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
},
- [busy, handleLoad, loadGgufRepoPick, loadOrStage, pickGuard, quant],
+ [
+ abandonPick,
+ beginPick,
+ busy,
+ guidance,
+ handleLoad,
+ loadGgufRepoPick,
+ loadOrStage,
+ pickGuard,
+ quant,
+ revertPick,
+ steps,
+ ],
);
// Resolves true when the backend accepted the unload; handleCancelLoad reports the cancel only then.
@@ -2298,6 +2486,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
value={status?.loaded ? status.repo_id ?? undefined : undefined}
activeGgufVariant={quant}
onValueChange={handleModelSelect}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onEject={status?.loaded ? handleUnload : undefined}
variant="ghost"
className="!h-[34px]"
diff --git a/studio/frontend/src/lib/diffusion-gguf-pick.ts b/studio/frontend/src/lib/diffusion-gguf-pick.ts
index a729b3a8780..b77f46ffba8 100644
--- a/studio/frontend/src/lib/diffusion-gguf-pick.ts
+++ b/studio/frontend/src/lib/diffusion-gguf-pick.ts
@@ -62,6 +62,7 @@ export async function runGgufRepoPick(
if (!handlers.isCurrent()) return false;
if (!filename) {
handlers.onAmbiguous();
+ handlers.onNotStarted();
return false;
}
handlers.onResolved(filename);
diff --git a/studio/frontend/tests/diffusion-gguf-pick.test.ts b/studio/frontend/tests/diffusion-gguf-pick.test.ts
index 155261b1dd7..189da0505ec 100644
--- a/studio/frontend/tests/diffusion-gguf-pick.test.ts
+++ b/studio/frontend/tests/diffusion-gguf-pick.test.ts
@@ -57,7 +57,7 @@ test("a resolved pick applies its label and loads", async () => {
test("an unresolvable pick prompts and loads nothing", async () => {
const { handlers, log } = recorder({ resolve: () => Promise.resolve(null) });
assert.equal(await runGgufRepoPick(handlers), false);
- assert.deepEqual(log, ["ambiguous"]);
+ assert.deepEqual(log, ["ambiguous", "reverted"]);
});
test("a load that never starts takes its own label back", async () => {
diff --git a/studio/frontend/tests/video-download-plan-payload.test.ts b/studio/frontend/tests/video-download-plan-payload.test.ts
index 5cfab9a0f56..4c2ac86f13c 100644
--- a/studio/frontend/tests/video-download-plan-payload.test.ts
+++ b/studio/frontend/tests/video-download-plan-payload.test.ts
@@ -26,49 +26,39 @@ test("the video download plan is asked with the selected precision", () => {
);
assert.ok(call.length > 0, "the plan call must exist");
assert.ok(
- call.includes("transformer_quant:"),
- "the plan must be asked with the precision the load will use",
+ call.includes("transformer_quant: advanced.transformer_quant"),
+ "the plan must use the precision snapshot",
);
- // Under the same pipeline-only rule the load applies: a GGUF / single-file DiT runs the
- // precision its checkpoint carries, and the stale control value must not reach either call.
- assert.ok(call.includes('opts.kind === "pipeline"'));
+ const snapshot = source.slice(
+ source.indexOf("const currentLoadAdvanced = useCallback("),
+ source.indexOf("const handleLoad = useCallback("),
+ );
+ assert.ok(snapshot.includes("loadControlsRef.current"));
+
+ assert.ok(snapshot.includes('kind === "pipeline"'));
});
-test("the staged plan reads the precision live, not the value it closed over", () => {
- // loadOrStage is memoized on [stage, pickGuard] so its consumers keep a stable identity. A
- // plain capture of transformerQuant therefore froze at the value selected when the callback
- // was built, and the ordinary auto -> FP8 change sent the plan no precision at all: the
- // pre-download refusal was skipped and tens of GB were staged before the load refused it.
- const call = source.slice(
- source.indexOf("await getVideoDownloadPlan({"),
- source.indexOf("await getVideoDownloadPlan({") + 900,
- );
- assert.ok(
- call.includes("transformerQuantRef.current"),
- "the plan must read the precision through the ref",
- );
- assert.ok(
- !/transformerQuant\s*[!=]==/.test(call),
- "a direct read of the memoized capture is the stale value",
- );
- assert.ok(
- source.includes("transformerQuantRef.current = transformerQuant"),
- "the ref must be kept current on every render",
+test("the staged plan pins its controls through the eventual load", () => {
+ const flow = source.slice(
+ source.indexOf("const loadOrStage = useCallback("),
+ source.indexOf("// A GGUF pick can arrive"),
);
+ const advancedAt = flow.indexOf("const advanced = currentLoadAdvanced(opts.kind);");
+ const planAt = flow.indexOf("await getVideoDownloadPlan({");
+ assert.ok(advancedAt >= 0, "the staged flow must compute the advanced snapshot");
+ assert.ok(planAt >= 0, "the staged flow must request the download plan");
+ assert.ok(advancedAt < planAt, "the snapshot must precede the plan request");
+ assert.match(flow, /pendingStagedLoad\.current = \{\s*repoId,\s*opts,\s*advanced,/);
+ assert.ok(source.includes("pending.opts, pending.advanced"));
+
+ assert.ok(flow.includes("handleLoadRef.current(repoId, opts, advanced)"));
});
+test("the video picker resolves the full GGUF footprint", () => {
+ assert.ok(source.includes("const resolveDownloadFootprint = useCallback("));
+ assert.ok(source.includes("const requiredBytes = plan.required_bytes"));
+ assert.ok(source.includes("resolveDownloadFootprint={resolveDownloadFootprint}"));
+});
test("the staged plan carries the memory request too", () => {
- // The route refuses an explicit precision under balanced or low_vram only when it can see the
- // memory mode. Omitting it here meant the plan succeeded, tens of GB were staged, and the
- // identical pick was then rejected by /video/load -- the regression the plan gate exists for.
- const call = source.slice(
- source.indexOf("await getVideoDownloadPlan({"),
- source.indexOf("await getVideoDownloadPlan({") + 1200,
- );
- assert.ok(call.includes("memory_mode:"), "the plan must be asked with the memory request");
- assert.ok(
- call.includes("memoryModeRef.current"),
- "and read it live, like the precision",
- );
- assert.ok(source.includes("memoryModeRef.current = memoryMode"));
+ assert.equal(source.match(/memory_mode: advanced\.memory_mode/g)?.length, 3);
});
diff --git a/tests/studio/playwright_image_download_cancel_retry.py b/tests/studio/playwright_image_download_cancel_retry.py
new file mode 100644
index 00000000000..6958855dcac
--- /dev/null
+++ b/tests/studio/playwright_image_download_cancel_retry.py
@@ -0,0 +1,420 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Rendered cancel/retry regression for staged diffusion downloads.
+
+The browser runs the real Studio UI against a deterministic API simulation of
+the reported sequence:
+
+1. Start with the 2.6 GB Klein GGUF already cached.
+2. Stage its missing 8.2 GB companion assets through the Downloads panel.
+3. Cancel, pick the same quant again, and resume only those companion assets.
+4. Load exactly once and observe a short 100% GPU-finalization state that reaches ready.
+
+No model bytes are downloaded and no GPU is required.
+"""
+
+import json
+import os
+import time
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import Route, sync_playwright
+
+from playwright_image_model_footprint import (
+ BASE_URL,
+ CHECKPOINT_BYTES,
+ COMPANION_BYTES,
+ FILENAME,
+ REPO_ID,
+ REQUIRED_BYTES,
+ _api_payload,
+ _json,
+)
+
+
+ART_DIR = Path(os.environ.get("PW_ART_DIR", "logs/playwright_image_cancel_retry"))
+ART_DIR.mkdir(parents = True, exist_ok = True)
+EXPECT = os.environ.get("PW_EXPECT", "after").strip().lower()
+if EXPECT not in {"before", "after"}:
+ raise ValueError("PW_EXPECT must be 'before' or 'after'")
+CHECKPOINT_CACHED = os.environ.get("PW_CHECKPOINT_CACHED", "1").strip() != "0"
+if EXPECT == "before" and not CHECKPOINT_CACHED:
+ raise ValueError("The before-state requires PW_CHECKPOINT_CACHED=1")
+
+COMPANION_REPO = "black-forest-labs/FLUX.2-klein-4B"
+COMPANION_FILES = [
+ "text_encoder/model-00001-of-00002.safetensors",
+ "text_encoder/model-00002-of-00002.safetensors",
+ "vae/diffusion_pytorch_model.safetensors",
+]
+
+
+def _status(*, loaded: bool) -> dict[str, object]:
+ return {
+ "loaded": loaded,
+ "repo_id": REPO_ID if loaded else None,
+ "family": "flux2-klein" if loaded else None,
+ "base_repo": COMPANION_REPO if loaded else None,
+ "device": "cuda:0" if loaded else None,
+ "dtype": "bfloat16" if loaded else None,
+ "model_kind": "gguf" if loaded else None,
+ "cpu_offload": False,
+ "workflows": ["text2img"] if loaded else [],
+ "supports_lora": False,
+ "supports_controlnet": False,
+ }
+
+
+def _entry(repo_id: str) -> dict[str, object]:
+ if repo_id == REPO_ID:
+ return {
+ "repo_id": REPO_ID,
+ "files": [FILENAME],
+ "bytes": CHECKPOINT_BYTES,
+ "gguf_filename": FILENAME,
+ }
+ return {
+ "repo_id": COMPANION_REPO,
+ "files": COMPANION_FILES,
+ "bytes": COMPANION_BYTES,
+ "gguf_filename": None,
+ }
+
+
+def _open_quant(page, *, navigate: bool) -> None:
+ if navigate:
+ page.goto(f"{BASE_URL}/images", wait_until = "domcontentloaded")
+ trigger = page.get_by_role("button", name = "Select image model")
+ trigger.wait_for(state = "visible", timeout = 30_000)
+ trigger.click()
+ page.get_by_text("FLUX.2-klein-4B-GGUF", exact = True).click()
+ gguf = page.get_by_text("GGUF", exact = True)
+ if gguf.count() == 1:
+ gguf.click()
+ quant = page.locator("button").filter(has_text = "Q4_K_M")
+ quant.wait_for(state = "visible")
+ assert quant.count() == 1
+ quant.click()
+
+
+def main() -> None:
+ state: dict[str, object] = {
+ "checkpoint_cached": CHECKPOINT_CACHED,
+ "companion_attempt": 0,
+ "jobs": {},
+ "starts": [],
+ "cancelled": False,
+ "load_calls": 0,
+ "load_payloads": [],
+ "load_progress_polls": 0,
+ "loaded": False,
+ "plan_snapshots": [],
+ }
+ page_errors: list[str] = []
+
+ def download_plan() -> dict[str, object]:
+ entries = [_entry(COMPANION_REPO)]
+ if not state["checkpoint_cached"]:
+ entries.insert(0, _entry(REPO_ID))
+ snapshot = [entry["repo_id"] for entry in entries]
+ state["plan_snapshots"].append(snapshot)
+ return {
+ "entries": entries,
+ "total_bytes": sum(int(entry["bytes"]) for entry in entries),
+ "required_bytes": REQUIRED_BYTES,
+ "checkpoint_bytes": CHECKPOINT_BYTES,
+ }
+
+ def start_download(payload: dict[str, object]) -> dict[str, object]:
+ repo_id = str(payload["repo_id"])
+ assert payload.get("scope_id") == "diffusion", payload
+ assert payload.get("gguf_variant") is None, payload
+ generation = len(state["starts"]) + 1
+ state["starts"].append(repo_id)
+ if repo_id == COMPANION_REPO:
+ state["companion_attempt"] = int(state["companion_attempt"]) + 1
+ state["jobs"][repo_id] = {
+ "state": "running",
+ "generation": generation,
+ "polls": 0,
+ "attempt": int(state["companion_attempt"]) if repo_id == COMPANION_REPO else 1,
+ }
+ return {
+ "job_key": f"model:{repo_id}:@diffusion",
+ "accepted": True,
+ "state": "running",
+ "generation": generation,
+ "transport": "http",
+ "cancel_transport": None,
+ }
+
+ def job_status(repo_id: str) -> dict[str, object]:
+ job = state["jobs"].get(repo_id)
+ if job is None:
+ return {"state": "idle", "error": None}
+ if job["state"] == "running":
+ job["polls"] = int(job["polls"]) + 1
+ should_complete = repo_id == REPO_ID or int(job["attempt"]) >= 2
+ if should_complete and int(job["polls"]) >= 3:
+ job["state"] = "complete"
+ if repo_id == REPO_ID:
+ state["checkpoint_cached"] = True
+ return {
+ "state": job["state"],
+ "error": None,
+ "generation": job["generation"],
+ }
+
+ def job_progress(repo_id: str) -> dict[str, object]:
+ job = state["jobs"].get(repo_id)
+ expected = CHECKPOINT_BYTES if repo_id == REPO_ID else COMPANION_BYTES
+ complete = bool(job and job["state"] == "complete")
+ if complete:
+ downloaded = expected
+ elif repo_id == COMPANION_REPO:
+ downloaded = 1_100_000_000
+ else:
+ downloaded = 1_900_000_000
+ return {
+ "downloaded_bytes": downloaded,
+ "completed_bytes": downloaded,
+ "complete_on_disk": complete,
+ "expected_bytes": expected,
+ "progress": downloaded / expected,
+ "cache_path": f"C:\\mock-cache\\{repo_id.replace('/', '--')}",
+ }
+
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless = True)
+ context = browser.new_context(
+ viewport = {"width": 1440, "height": 900},
+ reduced_motion = "reduce",
+ color_scheme = "dark",
+ )
+ context.add_init_script(
+ "localStorage.setItem('unsloth_auth_token', 'rendered-ui-test');"
+ "localStorage.setItem('unsloth_onboarding_done', 'true');"
+ "localStorage.setItem('unsloth_download_transport', 'http');"
+ )
+
+ def route_request(route: Route) -> None:
+ request = route.request
+ parsed = urlparse(request.url)
+ path = parsed.path
+ query = parse_qs(parsed.query)
+ if parsed.netloc == "huggingface.co":
+ _json(route, [])
+ return
+ if not path.startswith("/api/"):
+ route.continue_()
+ return
+
+ payload = json.loads(request.post_data or "{}")
+ if path in {"/api/hub/gguf-variants", "/api/models/gguf-variants"}:
+ variants = _api_payload(path, query, full_footprint = True)
+ # This is the critical reported precondition: the picker knows the 2.6 GB
+ # checkpoint is cached, but its separate 8.2 GB requirements are absent.
+ variants["variants"][0]["downloaded"] = CHECKPOINT_CACHED
+ _json(route, variants)
+ return
+ if path == "/api/inference/images/download-plan":
+ _json(route, download_plan())
+ return
+ if path == "/api/studio/download-transport-capabilities":
+ _json(
+ route,
+ {
+ "http": {"available": True, "reason": None},
+ "xet": {"available": False, "reason": "Rendered test uses HTTP"},
+ "auto_resolves_to": "http",
+ "auto_reason": "Deterministic rendered test",
+ },
+ )
+ return
+ if path == "/api/hub/transport-status":
+ _json(
+ route,
+ {"has_partial": False, "last_transport": None, "resumable": False},
+ )
+ return
+ if path == "/api/hub/download" and request.method == "POST":
+ _json(route, start_download(payload))
+ return
+ if path == "/api/hub/download/cancel" and request.method == "POST":
+ repo_id = str(payload["repo_id"])
+ job = state["jobs"][repo_id]
+ job["state"] = "cancelled"
+ state["cancelled"] = True
+ _json(
+ route,
+ {
+ "job_key": f"model:{repo_id}:@diffusion",
+ "state": "cancelled",
+ },
+ )
+ return
+ if path == "/api/hub/download-status":
+ _json(route, job_status(query["repo_id"][0]))
+ return
+ if path in {"/api/hub/gguf-download-progress", "/api/hub/download-progress"}:
+ _json(route, job_progress(query["repo_id"][0]))
+ return
+ if path == "/api/inference/images/load" and request.method == "POST":
+ state["load_calls"] = int(state["load_calls"]) + 1
+ state["load_payloads"].append(payload)
+ state["load_progress_polls"] = 0
+ _json(route, _status(loaded = False))
+ return
+ if path == "/api/inference/images/load-progress":
+ if int(state["load_calls"]) == 0:
+ progress = {
+ "phase": None,
+ "bytes_downloaded": 0,
+ "bytes_total": 0,
+ "fraction": 0,
+ "error": None,
+ }
+ else:
+ state["load_progress_polls"] = int(state["load_progress_polls"]) + 1
+ direct_legacy_load = len(state["starts"]) == 0
+ downloading_inline = (
+ direct_legacy_load and int(state["load_progress_polls"]) < 5
+ )
+ ready = not downloading_inline and int(state["load_progress_polls"]) >= 5
+ if ready:
+ state["loaded"] = True
+ progress = {
+ "phase": (
+ "ready"
+ if ready
+ else "downloading"
+ if downloading_inline
+ else "finalizing"
+ ),
+ "bytes_downloaded": (
+ CHECKPOINT_BYTES if downloading_inline else REQUIRED_BYTES
+ ),
+ "bytes_total": REQUIRED_BYTES,
+ "fraction": (
+ CHECKPOINT_BYTES / REQUIRED_BYTES if downloading_inline else 1
+ ),
+ "error": None,
+ }
+ _json(route, progress)
+ return
+ if path == "/api/inference/images/status":
+ _json(route, _status(loaded = bool(state["loaded"])))
+ return
+ _json(route, _api_payload(path, query, full_footprint = True))
+
+ context.route("**/*", route_request)
+ page = context.new_page()
+ page.on("pageerror", lambda exc: page_errors.append(str(exc)))
+
+ _open_quant(page, navigate = True)
+ if EXPECT == "before":
+ deadline = time.monotonic() + 20
+ while int(state["load_calls"]) < 1 and time.monotonic() < deadline:
+ page.wait_for_timeout(250)
+ legacy_toast = page.locator("[data-sonner-toast]").filter(has_text = "Downloading model")
+ legacy_toast.wait_for(state = "visible", timeout = 10_000)
+ assert "2.6 GB of 11 GB" in legacy_toast.inner_text()
+ assert state["starts"] == [], state["starts"]
+ assert state["plan_snapshots"] == [], state["plan_snapshots"]
+ assert state["load_calls"] == 1
+ assert page.get_by_role("button", name = "Cancel download").count() == 0
+ assert not page_errors, page_errors
+ page.screenshot(
+ path = str(ART_DIR / "before-legacy-model-download-toast.png"),
+ full_page = True,
+ )
+ result = {
+ "expectation": EXPECT,
+ "legacy_toast": True,
+ "download_manager_starts": state["starts"],
+ "load_calls_while_companion_missing": state["load_calls"],
+ "real_cancel_available": False,
+ }
+ (ART_DIR / "result.json").write_text(json.dumps(result, indent = 2), encoding = "utf-8")
+ browser.close()
+ print(f"PASS expected before-state; evidence: {ART_DIR.resolve()}")
+ return
+
+ expected_initial_starts = (
+ [COMPANION_REPO] if CHECKPOINT_CACHED else [REPO_ID, COMPANION_REPO]
+ )
+ deadline = time.monotonic() + 20
+ while len(state["starts"]) < len(expected_initial_starts) and time.monotonic() < deadline:
+ page.wait_for_timeout(250)
+ if len(state["starts"]) < len(expected_initial_starts):
+ page.screenshot(
+ path = str(ART_DIR / "image-download-companion-timeout.png"), full_page = True
+ )
+ print("companion timeout state:", json.dumps(state, default = str, indent = 2))
+ print(page.locator("body").inner_text()[:8_000])
+ assert state["starts"] == expected_initial_starts, state["starts"]
+ companion_row = page.locator(".hub-download-panel").filter(has_text = COMPANION_REPO)
+ companion_row.wait_for(state = "visible", timeout = 10_000)
+ panel_text = companion_row.inner_text()
+ assert "Required assets" in panel_text
+ assert "@diffusion" not in panel_text
+ if not CHECKPOINT_CACHED:
+ assert "Model file" in panel_text
+ assert page.get_by_text("Downloading model requirements", exact = False).count() == 0
+ assert page.get_by_text("Downloading model…", exact = True).count() == 0
+ assert page.get_by_text("Loading to GPU…", exact = True).count() == 0
+ assert state["load_calls"] == 0, "missing companion bypassed staging"
+ page.screenshot(path = str(ART_DIR / "image-companion-download.png"), full_page = True)
+
+ cancel = page.get_by_role("button", name = "Cancel download")
+ assert cancel.count() == 1
+ cancel.click()
+ page.get_by_text("Cancelled. Partial files kept.", exact = True).wait_for(
+ state = "visible", timeout = 10_000
+ )
+ page.screenshot(path = str(ART_DIR / "image-download-cancelled.png"), full_page = True)
+ assert state["cancelled"] is True
+ assert state["load_calls"] == 0, "cancelled staging unexpectedly loaded the model"
+
+ _open_quant(page, navigate = False)
+ page.locator("[data-sonner-toast]").filter(has_text = "Loading to GPU").wait_for(
+ state = "visible", timeout = 20_000
+ )
+ finalizing_toast = page.locator("[data-sonner-toast]").filter(has_text = "Loading to GPU")
+ assert "100%" in finalizing_toast.inner_text()
+ page.screenshot(path = str(ART_DIR / "image-download-retry-finalizing.png"), full_page = True)
+
+ page.get_by_text("Model loaded", exact = True).wait_for(state = "visible", timeout = 15_000)
+ page.screenshot(path = str(ART_DIR / "image-download-retry-loaded.png"), full_page = True)
+
+ assert state["starts"] == [*expected_initial_starts, COMPANION_REPO], state["starts"]
+ assert state["load_calls"] == 1
+ assert state["load_payloads"][0]["model_path"] == REPO_ID
+ assert state["load_payloads"][0]["model_kind"] == "gguf"
+ assert state["load_payloads"][0]["gguf_filename"] == FILENAME
+ assert state["loaded"] is True
+ assert [COMPANION_REPO] in state["plan_snapshots"]
+ if not CHECKPOINT_CACHED:
+ assert [REPO_ID, COMPANION_REPO] in state["plan_snapshots"]
+ assert not page_errors, page_errors
+
+ result = {
+ "expectation": EXPECT,
+ "legacy_toast": False,
+ "starts": state["starts"],
+ "cancelled_before_load": True,
+ "checkpoint_redownloaded": state["starts"].count(REPO_ID) > 1,
+ "load_calls": state["load_calls"],
+ "finalization_progress_polls": state["load_progress_polls"],
+ "loaded": state["loaded"],
+ }
+ (ART_DIR / "result.json").write_text(json.dumps(result, indent = 2), encoding = "utf-8")
+ browser.close()
+
+ print(f"PASS rendered image cancel/retry; evidence: {ART_DIR.resolve()}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/playwright_image_model_footprint.py b/tests/studio/playwright_image_model_footprint.py
new file mode 100644
index 00000000000..696cbaf6b2b
--- /dev/null
+++ b/tests/studio/playwright_image_model_footprint.py
@@ -0,0 +1,276 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Rendered regression for the image-model selector's full disk footprint.
+
+The browser runs the real Vite application. Network data is deterministic so
+the test proves the UI contract without downloading a model or depending on
+live Hugging Face metadata.
+"""
+
+import os
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+from playwright.sync_api import Route, sync_playwright
+
+
+BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:4173")
+ART_DIR = Path(os.environ.get("PW_ART_DIR", "logs/playwright_image_footprint"))
+ART_DIR.mkdir(parents = True, exist_ok = True)
+
+CHECKPOINT_BYTES = 2_600_000_000
+COMPANION_BYTES = 8_200_000_000
+REQUIRED_BYTES = CHECKPOINT_BYTES + COMPANION_BYTES
+REPO_ID = "unsloth/FLUX.2-klein-4B-GGUF"
+FILENAME = "FLUX.2-klein-4B-Q4_K_M.gguf"
+
+
+def _json(route: Route, payload: object) -> None:
+ route.fulfill(status = 200, content_type = "application/json", json = payload)
+
+
+def _api_payload(path: str, query: dict[str, list[str]], *, full_footprint: bool) -> object:
+ if path == "/api/auth/status":
+ return {"initialized": True, "requires_password_change": False}
+ if path == "/api/health":
+ return {
+ "version": "ui-test",
+ "device_type": "windows",
+ "chat_only": False,
+ "hardware_detecting": False,
+ }
+ if path == "/api/system":
+ device = {
+ "index": 0,
+ "index_kind": "physical",
+ "name": "Rendered test GPU",
+ "memory_total_gb": 24,
+ "vram_free_gb": 22,
+ }
+ return {
+ "platform": "Windows",
+ "python_version": "3.13",
+ "device_backend": "cuda",
+ "uptime_seconds": 1,
+ "cpu": {
+ "logical_count": 16,
+ "physical_count": 8,
+ "usage_percent": 1,
+ "frequency_mhz": 4000,
+ },
+ "memory": {
+ "total_gb": 64,
+ "available_gb": 48,
+ "percent_used": 25,
+ "process_used_mb": 512,
+ },
+ "disk": {"total_gb": 1000, "free_gb": 800, "percent_used": 20},
+ "gpu": {"available": True, "backend": "cuda", "devices": [device]},
+ "inference_gpu": {
+ "available": True,
+ "backend": "cuda",
+ "devices": [device],
+ },
+ "ml_packages": {},
+ }
+ if path == "/api/inference/images/status":
+ return {
+ "loaded": False,
+ "repo_id": None,
+ "family": None,
+ "base_repo": None,
+ "device": None,
+ "dtype": None,
+ "model_kind": None,
+ "workflows": [],
+ }
+ if path == "/api/inference/images/load-progress":
+ return {"phase": None, "bytes_downloaded": 0, "bytes_total": 0, "error": None}
+ if path == "/api/inference/images/generate-progress":
+ return {"active": False, "step": 0, "total_steps": 0, "eta_seconds": None}
+ if path == "/api/inference/images/info":
+ return {"families": []}
+ if path == "/api/inference/monitor":
+ return {
+ "status": "idle",
+ "active_model": None,
+ "active_requests": 0,
+ "entries": [],
+ }
+ if path == "/api/inference/images/gallery":
+ return {"images": [], "has_more": False}
+ if path == "/api/models/diffusion-loras":
+ return {"loras": []}
+ if path == "/api/models/diffusion-controlnets":
+ return {"controlnets": []}
+ if path == "/api/hub/local":
+ return {"models_dir": "C:\\models", "lmstudio_dirs": [], "models": []}
+ if path in {"/api/hub/cached-gguf", "/api/hub/cached-models"}:
+ return {"cached": []}
+ if path == "/api/hub/hidden-models":
+ return {"patterns": []}
+ if path == "/api/hub/active-downloads":
+ return {"downloads": []}
+ if path == "/api/hub/datasets/active-downloads":
+ return {"downloads": []}
+ if path == "/api/chat/threads":
+ return {"threads": []}
+ if path == "/api/chat/projects":
+ return {"projects": []}
+ if path == "/api/settings/personalization":
+ return {
+ "version": 1,
+ "profile": {
+ "displayName": "",
+ "nickname": "",
+ "avatarDataUrl": None,
+ "avatarShape": "circle",
+ "showGreetingSloth": True,
+ },
+ "appearance": {
+ "theme": "dark",
+ "palette": "standard",
+ "language": None,
+ "customization": {},
+ },
+ "saved": False,
+ "customizationSaved": False,
+ "paletteSaved": False,
+ "greetingSlothSaved": False,
+ }
+ if path == "/api/export/status":
+ return {
+ "current_checkpoint": None,
+ "is_vision": False,
+ "is_peft": False,
+ "is_export_active": False,
+ }
+ if path in {"/api/hub/gguf-variants", "/api/models/gguf-variants"}:
+ assert query.get("repo_id") == [REPO_ID], query
+ return {
+ "repo_id": REPO_ID,
+ "variants": [
+ {
+ "filename": FILENAME,
+ "quant": "Q4_K_M",
+ "size_bytes": CHECKPOINT_BYTES,
+ "download_size_bytes": CHECKPOINT_BYTES,
+ "downloaded": False,
+ }
+ ],
+ "has_vision": False,
+ "default_variant": "Q4_K_M",
+ "context_length": None,
+ }
+ if path == "/api/inference/images/download-plan":
+ base = {"entries": [], "total_bytes": REQUIRED_BYTES}
+ if full_footprint:
+ base.update(
+ required_bytes = REQUIRED_BYTES,
+ checkpoint_bytes = CHECKPOINT_BYTES,
+ )
+ return base
+ # Nonessential background probes are allowed to settle to an empty object;
+ # the test fails on browser exceptions or a missing selector row below.
+ return {}
+
+
+def _open_klein_quant(page) -> None:
+ page.goto(f"{BASE_URL}/images", wait_until = "domcontentloaded")
+ trigger = page.get_by_role("button", name = "Select image model")
+ try:
+ trigger.wait_for(state = "visible", timeout = 30_000)
+ except Exception:
+ print(f"selector startup URL: {page.url}")
+ print(page.locator("body").inner_text()[:4_000])
+ raise
+ trigger.click()
+ klein = page.get_by_text("FLUX.2-klein-4B-GGUF", exact = True)
+ try:
+ klein.wait_for(state = "visible", timeout = 30_000)
+ except Exception:
+ print(page.locator("body").inner_text()[:8_000])
+ raise
+ klein.click()
+ gguf = page.get_by_text("GGUF", exact = True)
+ if gguf.count() == 1:
+ gguf.click()
+ page.get_by_text("Q4_K_M", exact = True).wait_for(state = "visible")
+
+
+def main() -> None:
+ full_footprint = {"enabled": False}
+ page_errors: list[str] = []
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(headless = True)
+ context = browser.new_context(
+ viewport = {"width": 1440, "height": 900},
+ reduced_motion = "reduce",
+ color_scheme = "dark",
+ )
+ context.add_init_script(
+ "localStorage.setItem('unsloth_auth_token', 'rendered-ui-test');"
+ "localStorage.setItem('unsloth_onboarding_done', 'true');"
+ )
+
+ def route_request(route: Route) -> None:
+ parsed = urlparse(route.request.url)
+ if parsed.netloc == "huggingface.co":
+ _json(route, [])
+ return
+ if parsed.path.startswith("/api/"):
+ _json(
+ route,
+ _api_payload(
+ parsed.path,
+ parse_qs(parsed.query),
+ full_footprint = full_footprint["enabled"],
+ ),
+ )
+ return
+ route.continue_()
+
+ context.route("**/*", route_request)
+ page = context.new_page()
+ page.on("pageerror", lambda exc: page_errors.append(str(exc)))
+
+ _open_klein_quant(page)
+ quant_row = page.locator("button").filter(has_text = "Q4_K_M")
+ assert quant_row.count() == 1
+ assert "2.6GB" in "".join(quant_row.inner_text().split())
+ assert page.locator("[data-model-download-footprint]").count() == 0
+ picker = page.locator(".unsloth-model-selector-menu")
+ assert picker.count() == 1
+ picker.screenshot(path = str(ART_DIR / "image-model-footprint-before.png"))
+ page.screenshot(path = str(ART_DIR / "image-model-footprint-before-full.png"), full_page = True)
+
+ full_footprint["enabled"] = True
+ _open_klein_quant(page)
+ footprint = page.locator("[data-model-download-footprint]")
+ footprint.wait_for(state = "visible")
+ assert footprint.count() == 1
+ footprint_text = "".join(footprint.inner_text().split())
+ assert footprint_text == "10.8GB"
+ picker = page.locator(".unsloth-model-selector-menu")
+ assert picker.count() == 1
+ picker.screenshot(path = str(ART_DIR / "image-model-footprint-after.png"))
+ page.screenshot(path = str(ART_DIR / "image-model-footprint-after-full.png"), full_page = True)
+ help_icon = page.locator("[data-model-download-footprint-help]")
+ assert help_icon.count() == 1
+ help_icon.hover()
+ explanation = page.get_by_role("tooltip")
+ explanation.wait_for(state = "visible")
+ explanation_text = " ".join(explanation.inner_text().split())
+ assert "Full required size" in explanation_text
+ assert "2.6GBmodel+8.2GBrequiredassets" in "".join(explanation_text.split())
+ page.screenshot(path = str(ART_DIR / "image-model-footprint-hover.png"), full_page = True)
+
+ assert not page_errors, page_errors
+ browser.close()
+
+ print(f"PASS rendered image footprint; screenshots: {ART_DIR.resolve()}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 9975a0ee227..8a4fd5ca7a2 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1110,7 +1110,7 @@ def test_a_quantized_load_drops_a_lora_selection_it_cannot_bake():
src = _read("features/images/images-page.tsx")
assert "bakedLorasOnLoad.current = bakeLoras.length > 0;" in src
guard = re.search(
- r"if \(!loraCapable \|\| checkedBuildForBake\.current === residentBuildKey\) return;.*?\n \}, \[",
+ r"if \(\s*!loraCapable \|\| checkedBuildForBake\.current === residentBuildKey\s*\)\s*return;.*?\n \}, \[",
src,
re.S,
)
@@ -1138,9 +1138,9 @@ def test_diffusion_pages_never_drop_a_gguf_pick_silently():
def test_diffusion_pages_stage_downloads_through_the_manager():
- """Images/Video must not download inside the load: an undownloaded hub pick goes to
- the Hub download manager first, so it shares the panel, progress, cancel/resume,
- disk preflight and manifest verification with every other model."""
+ """Images/Video must not download inside the load: a Hub pick with missing files goes
+ to the download manager first, so it shares progress, cancel/resume, disk preflight,
+ and manifest verification with every other model."""
for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
src = _read(rel)
assert "useStagedDownload" in src, f"{rel}: not wired to the download manager"
@@ -1149,11 +1149,45 @@ def test_diffusion_pages_stage_downloads_through_the_manager():
stage_fn = re.search(r"const loadOrStage = useCallback\(.*?\n \);", src, re.S)
assert stage_fn, f"{rel}: loadOrStage not found"
body = stage_fn.group(0)
- # Already-downloaded (and local) picks must skip staging and load straight away.
- assert "isDownloaded !== false" in body, f"{rel}: cached picks would re-stage"
+ # A cached GGUF can still be missing a separate text encoder or VAE, and only the plan
+ # sees that, so every Hub pick is planned and only local picks bypass it. Safe on both
+ # pages because both planners filter against the cache: a fully cached pick returns no
+ # entries. Flipping this on a planner that does not filter would re-stage a whole model.
+ assert 'source !== "hub"' in body, f"{rel}: local picks would be planned"
+ assert (
+ "isDownloaded !== false" not in body
+ ), f"{rel}: cached checkpoint would hide missing companion assets"
# A missing plan must still load rather than dead-end.
assert "catch" in body, f"{rel}: no fallback when the plan is unavailable"
+ assert "handleLoadRef.current(repoId, opts, advanced)" in body, rel
+
+
+def test_every_diffusion_planner_filters_the_cache_before_staging():
+ """Planning every Hub pick is only safe on a planner that skips files already on disk;
+ without that an unchanged, fully cached model stages its whole footprint again. The two
+ move together, so pin them together rather than leaving it to a comment."""
+ root = WORKDIR / "studio" / "backend" / "core" / "inference"
+ for name in ("diffusion.py", "sd_cpp_backend.py", "video.py"):
+ src = (root / name).read_text(encoding = "utf-8")
+ plan = re.search(r"def download_plan\(.*?\n (?=@|def )", src, re.S)
+ assert plan, f"{name}: download_plan not found"
+ # Either probe: `_hub_file_is_loadable` is the stricter one, adding the stale-live-copy
+ # check on top, and a planner may reasonably use it instead.
+ assert "_hub_file_is_cached" in plan.group(0) or "_hub_file_is_loadable" in plan.group(
+ 0
+ ), f"{name}: download_plan stages files without checking the cache"
+
+
+def test_image_load_fallback_names_requirements_instead_of_only_the_model():
+ """If planning fails and the backend has to fetch files inside the load, its toast must
+ not call companion text encoders and VAEs the selected model. The normal path stages
+ them through Downloads; this wording keeps the defensive fallback honest too."""
+ src = _read("features/images/images-page.tsx")
+ assert '"Downloading model requirements…"' in src
+ assert '"Downloading model…"' not in src
+ assert '"Downloading the files required to load this model."' in src
+
def test_a_hidden_diffusion_page_does_not_load_when_its_download_lands():
"""Images and Video stay mounted behind the router, and a load evicts whoever holds the
@@ -1179,18 +1213,269 @@ def test_a_hidden_diffusion_page_does_not_load_when_its_download_lands():
assert flush, f"{rel}: nothing flushes the deferred load when the page is shown"
deps = [dep.strip() for dep in flush.group(2).split(",")]
assert "active" in deps, f"{rel}: the flush does not re-run when the page is shown"
- body = flush.group(1)
- # Loading directly or through the visible path's helper is fine; clearing the
- # flag and stopping is not.
+ assert "runStagedLoad(pending);" in flush.group(0), f"{rel}: deferred load never runs"
+
+
+def test_a_staged_download_that_ends_rolls_back_the_optimistic_quant():
+ """A quant pick sets its label optimistically and hands the rollback to whoever learns the
+ load did not take: the `.then` when the load never STARTS, the progress poll when it fails
+ after starting. A staged pick has neither -- staging starts no load, so nothing polls, and
+ `loadOrStage` returns true when it stages, so the `.then` treats it as started.
+
+ So the label has to come back where the plan dies (cancelled, failed, or never started), or
+ the selector goes on describing the still-resident model with a quant nothing ever loaded --
+ and images-page writes that label into the gallery cache, so it survives a remount too."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ cancelled = re.search(r"onCancelled: \(\) => \{.*?\n \},", src, re.S)
+ assert cancelled, f"{rel}: staged-download onCancelled not found"
+ region = cancelled.group(0)
+ # The pick itself still has to go, or a late completion loads a model nobody asked for.
+ assert "pendingStagedLoad.current = null" in region, f"{rel}: the dead pick is kept"
+ assert "quantRevert.current" in region, f"{rel}: the pending quant rollback is ignored"
+ assert re.search(
+ r"revertPick\(quantRevert\.current\)", region
+ ), f"{rel}: the optimistic quant outlives the download that was supposed to justify it"
+ assert "quantRevert.current = null" in region, f"{rel}: the rollback is never consumed"
+
+
+def test_a_dying_staged_download_only_rolls_back_its_own_pick():
+ """Staging leaves `busy` null on purpose, so a second Hub pick can be made while the first
+ job is still alive. `quantRevert` is a single ref, so by the time the first job dies it can
+ already hold the SECOND pick's entry: rolling back then reverts a label the newer, still-live
+ pick owns, and nothing restores it when that pick goes on to stage and load.
+
+ So the rollback has to be bound to the pick that staged the job. `loadOrStage` reads the
+ entry BEFORE awaiting its plan (the await is the window in which a newer pick lands) and
+ records it when it stages; the cancel path reverts only on an identity match."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ # Captured before the plan await, otherwise it is the newer pick's entry that gets stored.
+ own = re.search(r"const ownRevert = quantRevert\.current;\n(.*?)await ", src, re.S)
+ assert own, f"{rel}: loadOrStage does not capture its own rollback entry"
+ assert "await" not in own.group(
+ 1
+ ), f"{rel}: ownRevert is read after an await, so it can be the newer pick's"
+ assert (
+ "stagedQuantRevert.current = ownRevert" in src
+ ), f"{rel}: the staged job records no owner"
+
+ cancelled = re.search(r"onCancelled: \(\) => \{.*?\n \},", src, re.S)
+ assert cancelled, f"{rel}: staged-download onCancelled not found"
+ region = cancelled.group(0)
+ assert re.search(
+ r"if \(\s*quantRevert\.current &&\s*quantRevert\.current === stagedQuantRevert\.current\s*\)",
+ region,
+ ), f"{rel}: a dead job can roll back a newer pick's quant label"
+ # Cleared either way, or a later job inherits this one's owner and reverts on its behalf.
+ assert (
+ "stagedQuantRevert.current = null" in region
+ ), f"{rel}: the staged owner is never released"
+
+
+def test_a_plan_that_lands_after_a_newer_pick_is_dropped():
+ """Staging never sets `busy`, so a second Hub pick passes handleModelSelect's guard while the
+ first plan is still in flight. Plans then resolve in RESPONSE order, not pick order: the older
+ one would restage over the newer queue, or fall through and load the model the user left.
+
+ So each pick takes a sequence number and gives up if a newer one has been made since. It must
+ report started, not failed: returning false would send this pick's `.then` rollback at a label
+ the newer pick now owns. Every exit that acts on the pick is covered, not just the one after a
+ successful plan -- a rejected plan falls through to the load, and a pick that never asks for a
+ plan at all (local, exported) must still invalidate one already in flight."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ body = re.search(r"const loadOrStage = useCallback\(\n(.*?)\n \);", src, re.S)
+ assert body, f"{rel}: loadOrStage not found"
+ text = body.group(1)
+ assert "const pick = ++pickSeq.current;" in text, f"{rel}: no pick sequence is taken"
+ # Before any real await, or two picks can share a number.
+ seq = text.index("const pick = ++pickSeq.current;")
+ first_await = min(
+ (
+ text.index(tok)
+ for tok in ("await requestDownloadPlan", "await getVideoDownloadPlan")
+ if tok in text
+ ),
+ default = len(text),
+ )
+ assert seq < first_await, f"{rel}: the sequence is taken after the plan await"
+ # Before the non-hub return, so a local pick invalidates an in-flight hub plan.
+ assert seq < text.index(
+ 'if (source !== "hub")'
+ ), f"{rel}: a non-hub pick returns without invalidating an in-flight hub plan"
+ guards = re.findall(
+ r"if \(pick !== pickSeq\.current(?: \|\| !owns\(\))?\) return (\w+);", text
+ )
+ assert guards, f"{rel}: a superseded plan is not dropped"
+ assert (
+ set(guards) == {"true"}
+ ), f"{rel}: a superseded pick reports failure, so its rollback fires at the newer pick's label"
+ # The fallback load after a rejected plan is guarded too.
+ tail = text[text.rindex("} catch {") :]
+ assert re.search(
+ r"if \(pick !== pickSeq\.current(?: \|\| !owns\(\))?\) return true;.*?return handleLoadRef",
+ tail,
+ re.S,
+ ), f"{rel}: a plan that rejected after a newer pick still reaches the fallback load"
+
+
+def test_a_pick_that_never_loads_restores_its_generation_recipe():
+ """A pick applies its model's step/guidance recipe at the same moment it sets the quant label,
+ optimistically. If the load never takes, the previous pipeline stays resident: restoring only
+ the label leaves a distilled model's low-step, guidance-0 recipe pointed at a non-distilled
+ model, and the next generation silently runs with the wrong settings.
+
+ So the rollback token carries the recipe and every rollback path puts all of it back."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ assert (
+ "type PickRevert = { prev: string | null; steps: number; guidance: number };" in src
+ ), f"{rel}: the rollback token does not carry the generation recipe"
+ revert = re.search(
+ r"const revertPick = useCallback\(\(r: PickRevert\) => \{(.*?)\}, \[\]\);", src, re.S
+ )
+ assert revert, f"{rel}: no shared rollback helper"
+ body = revert.group(1)
+ for setter in ("setQuant(r.prev)", "setSteps(r.steps)", "setGuidance(r.guidance)"):
+ assert setter in body, f"{rel}: rollback does not restore {setter}"
+ # No rollback path may still put back the label alone.
+ assert (
+ "setQuant(quantRevert.current.prev)" not in src
+ ), f"{rel}: a rollback path restores the label without its recipe"
+
+
+def test_every_pick_replaces_the_rollback_it_leaves_behind():
+ """`quantRevert` is one ref and the staged cancel path reverts on identity. A branch that
+ changes the quant or the recipe WITHOUT writing a new entry leaves the previous pick's entry
+ in place, so an older staged download cancelling later still matches, and reverts to state
+ from before a selection this pick already replaced -- while this pick keeps no rollback of
+ its own. Every branch that moves the selection registers its own entry."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ select = re.search(r"const handleModelSelect = useCallback\(\n(.*?)\n \);", src, re.S)
+ assert select, f"{rel}: handleModelSelect not found"
+ body = select.group(1)
+ # One installed entry per branch that moves the label. Counting is what catches the
+ # branches nobody thinks about: the curated non-GGUF one and the generic pipeline
+ # fall-through both shipped without an entry at different points.
+ moves = body.count("setQuant(")
+ installs = body.count("quantRevert.current = revert;")
+ assert moves == installs, (
+ f"{rel}: {moves} branches move the selection but only {installs} install a rollback, "
+ "so an older staged download can revert over a pick that already replaced it"
+ )
+
+
+def test_every_pick_route_invalidates_the_staged_intent():
+ """Clearing inside `loadOrStage` is not enough: the direct-local GGUF and safetensors branches
+ call `handleLoad` themselves and never go through it, so a staged Hub download kept its intent
+ and its `onReady` could load the abandoned Hub model over the local one just picked.
+
+ So the invalidation sits in one helper fired at the top of every pick, before any branch."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ helper = re.search(r"const beginPick = useCallback\(\(\) => \{(.*?)\}, \[\]\);", src, re.S)
+ assert helper, f"{rel}: no shared pick-invalidation helper"
+ body = helper.group(1)
+ for cleared in (
+ "pickSeq.current += 1;",
+ "pendingStagedLoad.current = null;",
+ "stagedLoadDeferred.current = false;",
+ "stagedQuantRevert.current = null;",
+ ):
+ assert cleared in body, f"{rel}: beginPick does not release {cleared}"
+ select = re.search(r"const handleModelSelect = useCallback\(\n(.*?)\n \);", src, re.S)
+ assert select, f"{rel}: handleModelSelect not found"
+ pick = select.group(1)
+ assert "beginPick();" in pick, f"{rel}: a pick can run without invalidating the last one"
+ # Before every branch, or the branch that returns first keeps the old intent armed.
+ first_branch = min(
+ pick.index(tok)
+ for tok in ("const spec = loadSpecFor(", "if (meta.ggufVariant")
+ if tok in pick
+ )
+ assert (
+ pick.index("beginPick();") < first_branch
+ ), f"{rel}: the invalidation runs after a branch that can already have returned"
+
+
+def test_a_rejected_pick_hands_the_resident_state_back():
+ """`beginPick` retires the staged pick before the new row is validated, so a pick that is then
+ REJECTED (a bare repo with no quant, a non-unsloth pipeline) loads nothing and has nothing left
+ to restore it: the selector would show the abandoned pick's quant and recipe indefinitely.
+
+ Every rejecting early return therefore hands the carried rollback back."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ helper = re.search(r"const abandonPick = useCallback\(\(\) => \{(.*?)\}, \[", src, re.S)
+ assert helper, f"{rel}: no rejected-pick restore helper"
+ body = helper.group(1)
+ assert "revertPick(quantRevert.current)" in body, f"{rel}: the label is not handed back"
+ assert "quantRevert.current = null" in body, f"{rel}: the entry is never consumed"
+
+ select = re.search(r"const handleModelSelect = useCallback\(\n(.*?)\n \);", src, re.S)
+ assert select, f"{rel}: handleModelSelect not found"
+ pick = select.group(1)
+ # Each toast.error that ends the pick must restore before returning.
+ rejects = re.findall(r"toast\.error\([^;]*\);\n(\s*)([^\n]*)\n", pick)
+ assert rejects, f"{rel}: no rejecting early return found; this guard has gone stale"
+ for _indent, following in rejects:
+ assert (
+ "abandonPick();" in following
+ ), f"{rel}: a rejected pick returns without restoring the state it superseded"
+
+
+def test_a_new_pick_drops_the_previous_staged_intent():
+ """A staged download outlives the pick that made it. If the next pick stages nothing of its
+ own -- fully cached, local, or no plan at all -- it never calls `stage()`, so the hook's queue
+ keeps running the OLDER job and its `onReady` loads the model the user moved away from,
+ evicting the one they actually chose. The pick sequence alone does not cover this: the older
+ job already staged, so there is no pending response left to invalidate.
+
+ So the intent is dropped at the start of every pick, before any early return, and a pick that
+ does stage simply writes a fresh one."""
+ for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(rel)
+ body = re.search(r"const loadOrStage = useCallback\(\n(.*?)\n \);", src, re.S)
+ assert body, f"{rel}: loadOrStage not found"
+ text = body.group(1)
+ cleared = text.index("pendingStagedLoad.current = null;")
+ assert cleared < text.index(
+ 'if (source !== "hub")'
+ ), f"{rel}: a non-hub pick returns while the previous staged intent is still armed"
+ assert cleared < text.index("await "), f"{rel}: the intent survives until the plan resolves"
+ # The deferred re-fire and the rollback owner belong to that dead intent too.
+ head = text[: text.index('if (source !== "hub")')]
+ assert (
+ "stagedLoadDeferred.current = false;" in head
+ ), f"{rel}: a deferred staged load can still fire for the abandoned pick"
assert (
- "runStagedLoad()" in body or "handleLoadRef.current(" in body
- ), f"{rel}: deferred load never runs"
- if "runStagedLoad()" in body:
- runner = re.search(r"const runStagedLoad = useCallback\(.*?\n \}, \[", src, re.S)
- assert runner, f"{rel}: runStagedLoad not found"
- assert "handleLoadRef.current(" in runner.group(
- 0
- ), f"{rel}: runStagedLoad loads nothing"
+ "stagedQuantRevert.current = null;" in head
+ ), f"{rel}: the dead intent keeps ownership of the rollback"
+
+
+def test_a_local_gguf_still_shows_its_remote_companion_footprint():
+ """Only the CHECKPOINT is on disk for a local GGUF directory. Its text encoder, VAE, tokenizer
+ and configs still come from the remote base, and both diffusion planners size them, so
+ suppressing the footprint request understated a local row by the larger half of the download.
+
+ The arithmetic differs though: a local checkpoint is not part of `required_bytes` at all, so
+ nothing may be subtracted for it, where a hub pick carries its checkpoint inside that total.
+ "On disk" is the listing's verdict, not the spelling of the id, so the gate is
+ `checkpointIsLocal` rather than the path prefix test alone."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ effect = re.search(r"setCompanionBytesByKey\(new Map\(\)\);(.*?)\n \}, \[", src, re.S)
+ assert effect, "footprint resolution effect not found"
+ body = effect.group(1)
+ guard = re.search(r"if \(!resolveDownloadFootprint([^)]*)\) \{", body)
+ assert guard, "the footprint effect has no bail-out guard"
+ assert "isLocalPath" not in guard.group(
+ 1
+ ), "a local pick skips the footprint request, hiding its remote companion set"
+ assert re.search(
+ r"const checkpoint = checkpointIsLocal\n?\s*\? 0", body
+ ), "a local checkpoint is subtracted from a total it was never part of"
def test_staged_downloads_always_scope_their_files():
@@ -1208,6 +1493,68 @@ def test_staged_downloads_always_scope_their_files():
assert "const activeVariant = current ? scopedVariant(scopeId) : null;" in src
+def test_staged_downloads_use_one_actionable_download_surface():
+ """The Downloads panel owns progress and cancellation. A second informational toast
+ duplicates the same state and gives users another X that only dismisses copy."""
+ staged = _read("features/hub/download-manager/use-staged-download.ts")
+ stage_fn = re.search(
+ r"const stage = useCallback\(\(entries: StagedDownloadEntry\[\]\) => \{.*?\n \}, \[\]\);",
+ staged,
+ re.S,
+ )
+ assert stage_fn, "staged-download stage callback not found"
+ assert "toast.info" not in stage_fn.group(0)
+
+ panel = _read("features/hub/download-manager/download-manager-panel.tsx")
+ assert 'job.variant?.startsWith("@")' in panel
+ assert '"Model file" : "Required assets"' in panel
+
+
+def test_staged_plans_label_the_checkpoint_without_guessing_from_the_extension():
+ """The panel's "Model file" vs "Required assets" suffix must come from the plan, not
+ from a filename. A checkpoint is not always a GGUF (the curated LTX single-file
+ artifact is one ~90GB .safetensors) and companion repos carry .safetensors too, so an
+ extension test mislabelled the model itself as "Required assets". The staging page is
+ the only place that knows: the entry carrying the picked checkpoint file. Repo identity
+ alone is not enough -- a checkpoint sharing its repo with the companions, and already
+ cached, leaves an entry of companion files that would still claim to be the model."""
+ for page in ("images/images-page.tsx", "video/video-page.tsx"):
+ src = _read(f"features/{page}")
+ entries = re.search(r"plan\.entries\.map\(\(e\) => \(\{.*?\}\)\)", src, re.S)
+ assert entries, f"{page} does not map the plan entries into staged downloads"
+ assert "e.files.includes(opts.filename)" in entries.group(
+ 0
+ ), f"{page} does not mark the picked repo's entry as the checkpoint"
+ # The plan's own answer wins over both local guesses. A gated pipeline is staged from an
+ # ungated MIRROR, so its entry no longer carries the id we picked and the repo-id test
+ # reads the whole selected model as "Required assets". Only the planner knows about the
+ # swap. `??`, not `||`: a planner that answers false must not fall through to a guess.
+ assert "e.checkpoint ??" in entries.group(
+ 0
+ ), f"{page} ignores the checkpoint flag the plan carried"
+
+ staged = _read("features/hub/download-manager/use-staged-download.ts")
+ assert "checkpoint?: boolean;" in staged
+ start = re.search(r"downloadManager\.requestStart\(\{.*?\}\);", staged, re.S)
+ assert start, "requestStart call not found"
+ assert "checkpoint: current.checkpoint," in start.group(0)
+
+ # Carried onto the job and back out of persisted state, or a restart loses the label.
+ poll = _read("features/hub/download-manager/poll-loop.ts")
+ assert "checkpoint: req.checkpoint" in poll
+ state = _read("features/hub/download-manager/download-manager-state.ts")
+ assert 'typeof value.checkpoint === "boolean"' in state
+ assert "{ checkpoint: job.checkpoint }" in state
+
+ panel = _read("features/hub/download-manager/download-manager-panel.tsx")
+ suffix = re.search(r"function variantSuffix\(.*?\n\}", panel, re.S)
+ assert suffix, "variantSuffix not found"
+ body = suffix.group(0)
+ assert "job.checkpoint ??" in body, "the label ignores the flag the plan carried"
+ # The .gguf guess may only survive as the fallback for jobs persisted before the flag.
+ assert body.index("job.checkpoint ??") < body.index(".gguf")
+
+
def test_local_model_sections_respect_the_task_filter():
"""LM Studio / ./models / custom-folder rows must honour the picker's task filter.
The backend tags every local model with a task for exactly this; without the gate the
@@ -1305,13 +1652,20 @@ def test_local_diffusion_routing_is_keyed_by_the_id_the_row_selects():
def test_a_staged_download_that_never_starts_clears_the_queue():
- """requestStart can answer "error" (network failure, rejected scoped request, worker refused).
- Nothing completes after that, so leaving the head in place stranded the pick: the effect never
- re-ran and onReady never fired."""
+ """requestStart can answer "error" (network failure, rejected scoped request, worker refused),
+ "conflict" or "busy". Nothing completes after any of them, so leaving the head in place strands
+ the pick: the effect never re-runs and onReady never fires. The consumer's pending auto-load
+ has to go with it, or a later completion loads a model nobody asked for.
+
+ Asserted over the whole non-started region rather than a fixed window after the first branch,
+ so one shared clean-up for all three outcomes passes and three copies would too."""
src = _read("features/hub/download-manager/use-staged-download.ts")
- assert 'if (outcome === "error") {' in src
- branch = src[src.index('if (outcome === "error") {') :][:400]
- assert "setQueue(null)" in branch
+ assert 'if (outcome === "started") return;' in src
+ region = src[src.index('if (outcome === "started") return;') : src.index("return () => {")]
+ for outcome in ("error", "conflict", "busy"):
+ assert f'outcome === "{outcome}"' in region
+ assert "setQueue(null)" in region
+ assert "onCancelledRef.current?.()" in region
def test_staged_download_callbacks_are_bound_to_the_started_file_set():
@@ -2984,3 +3338,143 @@ def test_bare_vision_and_audio_backbones_are_classified_non_chat():
encoders = encoders.split(")", 1)[0]
for model_type in ('"vit"', '"dinov2"', '"swin"', '"wav2vec2"', '"resnet"'):
assert model_type in encoders, model_type
+
+
+def test_the_gguf_footprint_is_resolved_per_dependency_group_not_per_repo():
+ """The companion set a diffusion GGUF needs (text encoder, VAE, tokenizer,
+ configs) is not repository-wide: `detect_family_for_pick` falls back to
+ `repo_id/filename`, so one neutral repo can hold GGUFs of two families with
+ different base repos, and `sd_cpp_text_encoders_for` hands FLUX.2-klein-9B a
+ different text encoder than klein-4B in the same repo. Sampling ONE
+ representative and pasting its companionBytes onto every row therefore
+ advertised a GB-wrong "Full required size" on the rows it did not sample."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ # The old shape: one scalar for the whole listing.
+ assert "const [companionBytes, setCompanionBytes] = useState" not in src
+ assert (
+ "const [companionBytesByKey, setCompanionBytesByKey] = useState<\n Map<string, number>\n >"
+ in src
+ )
+ # Representatives are derived per key, not once for the listing.
+ group = src.split("const footprintVariants = useMemo(", 1)[1]
+ group = group.split("}, [displayVariants, effectiveRecommended]);", 1)[0]
+ assert "new Map<string, GgufVariantDetail>()" in group
+ assert 'const key = variant.dependency_key ?? "";' in group
+ # The recommended quant still wins, but only inside its own group.
+ assert "variant.quant === effectiveRecommended" in group
+ assert "current.quant !== effectiveRecommended" in group
+
+
+def test_every_footprint_group_gets_its_own_resolve_call():
+ """One request per distinct key. The ordinary repo has exactly one key, so the
+ common case stays exactly one request, which is what the representative scheme
+ exists to protect."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ effect = src.split("const [companionBytesByKey, setCompanionBytesByKey]", 1)[1]
+ effect = effect.split("const variantOptionKeys = useMemo(", 1)[0]
+ assert "for (const footprintVariant of footprintVariants) {" in effect
+ assert "resolveDownloadFootprint(repoId, {" in effect
+ # Each resolution writes only its own key, into a fresh Map: mutating the state
+ # Map in place would leave React on the old identity and drop earlier groups.
+ assert "next.set(dependencyKey, companion);" in effect
+ assert "const next = new Map(previous);" in effect
+ # Cleared per listing, so a reopened repo never shows the previous repo's totals.
+ assert "setCompanionBytesByKey(new Map());" in effect
+
+
+def test_the_footprint_asks_the_listing_whether_the_checkpoint_is_on_disk():
+ """Whether the checkpoint sits inside `required_bytes` is a question about the
+ disk, and the prefix regex cannot answer it: the backend resolves identifiers
+ existence-first, so a marker-less relative directory like "models/my-image-model"
+ is a local model with no path marker to match. Gating the subtraction on the
+ regex alone subtracted a checkpoint the plan had never counted, driving the
+ figure to zero and hiding a multi-GB companion set behind the checkpoint size.
+ The listing already reports the backend's own verdict as `resolved_locally`."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ # Surfaced by the normalizer, so no caller re-implements the field name.
+ assert "resolved_locally?: unknown;" in src
+ assert "resolvedLocally: res?.resolved_locally === true," in src
+ assert "setResolvedLocally(normalized.resolvedLocally);" in src
+ # Reset per listing: the previous row's locality must not decide this row's total.
+ assert "setResolvedLocally(false);" in src
+ assert "const checkpointIsLocal = isLocalPath || resolvedLocally;" in src
+ # The subtraction reads the combined verdict, never the regex on its own.
+ effect = src.split("const [companionBytesByKey, setCompanionBytesByKey]", 1)[1]
+ effect = effect.split("const variantOptionKeys = useMemo(", 1)[0]
+ assert "const checkpoint = checkpointIsLocal" in effect
+ assert "const checkpoint = isLocalPath" not in effect
+
+
+def test_a_refused_load_after_staging_rolls_the_pick_back():
+ """Staging reports the pick STARTED as soon as the download is queued, so the caller's own
+ `if (!started) revert` has already been skipped. The load only runs minutes later and can
+ still be refused: a training run or another load can claim the backend while the download
+ is going. Nothing polls for a staged pick, so the poll's rollback never runs either, and the
+ selector would keep advertising a quant that was never loaded.
+
+ BOTH deferred paths have to roll back. onReady hands off to the `active` effect when the
+ page is off-tab, so leaving the tab during the download otherwise walks straight back into
+ the same bug."""
+ for page in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
+ src = _read(page)
+ helper = src.split("const runStagedLoad = useCallback(", 1)[1].split("[revertPick],", 1)[0]
+ # Fire-and-forget is precisely the defect: the boolean has to be observed.
+ assert ".then((started) => {" in helper, page
+ assert "if (started) return;" in helper, page
+ # Same identity guard onCancelled uses: a newer pick owns the label from the moment it
+ # is made, so a stale completion must not revert it.
+ assert "const owned = stagedQuantRevert.current;" in helper, page
+ assert "quantRevert.current === owned" in helper, page
+ assert "revertPick(quantRevert.current);" in helper, page
+ # One implementation, reached from both deferred paths, so neither can drift.
+ assert src.count("if (pending) runStagedLoad(pending);") == 2, page
+ # Exactly one direct call left, the one inside the helper itself.
+ assert len(re.findall(r"void handleLoadRef\s*\.current\(\s*pending\.", src)) == 1, page
+
+
+def test_each_quant_row_reads_its_own_dependency_key():
+ """A row must look up its own group, and keep the plain formatBytes fallback
+ when that group has no answer yet (or the backend sends no key at all)."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ row = src.split("{displayVariants.map((v) => {", 1)[1]
+ row = row.split("</TooltipContent>", 1)[0]
+ assert 'companionBytesByKey.get(v.dependency_key ?? "") ?? null' in row
+ # The fallback and the tooltip gate still hang off this row's own value.
+ assert (
+ "companionBytes === null ? (\n <SizeText value={formatBytes(v.size_bytes)} />"
+ in row
+ )
+ assert "companionBytes={companionBytes}" in row
+
+
+def test_the_dependency_key_survives_the_variant_validator():
+ """isValidGgufVariant filters the listing, so a field it rejects never reaches a
+ row. An older backend sends none, which must stay valid."""
+ src = _read("features/model-picker/components/model-selector/pickers.tsx")
+ guard = src.split("function isValidGgufVariant(", 1)[1].split("\n}", 1)[0]
+ assert "candidate.dependency_key === undefined" in guard
+ assert "candidate.dependency_key === null" in guard
+ assert 'typeof candidate.dependency_key === "string"' in guard
+ types = _read("features/chat/types/api.ts")
+ assert "dependency_key?: string | null;" in types
+
+
+def test_the_backend_keys_the_footprint_on_family_and_text_encoders():
+ """Both sources of variation have to be in the key. Folding in only the family
+ would give klein-4B and klein-9B the same key inside one repo, which is the
+ exact case the per-row lookup exists for."""
+ src = _read_backend("hub/services/models/gguf_variants.py")
+ helper = src.split("def _variant_dependency_key(", 1)[1].split("\ndef ", 1)[0]
+ assert "detect_family_for_pick(repo_id, filename)" in helper
+ assert "sd_cpp_text_encoders_for(" in helper
+ assert "inner_dim = inner_dim" in helper
+ # No family means no grouping information, not a fabricated key.
+ assert "if fam is None:\n return None" in helper
+ # It runs once per row inside the listing, so it must never fail it.
+ assert "except Exception as e:" in helper
+ assert helper.rstrip().endswith("return None")
+ # Every row of the listing carries one, local and remote branches alike.
+ answer = src.split("async def get_gguf_variants_answer(", 1)[1]
+ assert answer.count("dependency_key = _variant_dependency_key(") >= 4
+ schema = _read_backend("hub/schemas/inventory.py")
+ assert "dependency_key: Optional[str] = Field(" in schema