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.

Recognize shared encoder assets in Model Hub inventory (#16466)

Lee Jacksonc57f7ea38e94
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 4ac68e44099..d664f30ee18 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -1323,6 +1323,8 @@ def _scan_cached_models(
companion_only = (
not artifact_checkpoint
and hf_cache_scan.snapshot_pipeline_missing_denoiser(load_snapshot)
+ ) or hf_cache_scan.snapshot_is_encoder_companion(
+ cached_id, repo_path, load_snapshot
)
snapshot_partial = download_partial or companion_only
# Flags are OR-ed over revisions, so no payload snapshot means no directory serves the row and it would reach for the Hub.
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 66e7d191671..b7b2c2b9bc1 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -701,8 +701,10 @@ def _scan_hf_cache(
snapshot_partial_resumable = snapshot_partial_resumable,
)
# Denoiser-less pipeline (a GGUF's borrowed VAE / encoder): partial so no picker loads it, flagged so the Hub offers no Continue.
- if not snapshot_partial and hf_cache_scan.snapshot_pipeline_missing_denoiser(
- latest_snapshot := hf_cache_scan.latest_snapshot_dir(repo_dir)
+ latest_snapshot = hf_cache_scan.latest_snapshot_dir(repo_dir)
+ if not snapshot_partial and (
+ hf_cache_scan.snapshot_pipeline_missing_denoiser(latest_snapshot)
+ or hf_cache_scan.snapshot_is_encoder_companion(model_id, repo_dir, latest_snapshot)
):
# Some denoiser shards on disk is a torn download, not a prefetch: partial, but not flagged.
companion_prefetch = not hf_cache_scan.snapshot_denoiser_has_weights(latest_snapshot)
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 8f27e152741..62ee172db41 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -4462,6 +4462,120 @@ def test_unet_index_staged_by_the_config_prefetch_is_not_weight_evidence(tmp_pat
assert inventory_scan.snapshot_denoiser_has_weights(other) is True
+_QWEN_ENCODER_REPO = "unsloth/Qwen-Image-FP8"
+_QWEN_ENCODER_FILE = "Qwen-Image-text_encoder-FP8.safetensors"
+
+
+def _encoder_cache(
+ tmp_path,
+ names,
+ *,
+ repo_id = _QWEN_ENCODER_REPO,
+ ref = _SNAPSHOT_SHA,
+):
+ repo_dir = tmp_path / "hub" / f"models--{repo_id.replace('/', '--')}"
+ snapshot = repo_dir / "snapshots" / _SNAPSHOT_SHA
+ for name in names:
+ (snapshot / name).parent.mkdir(parents = True, exist_ok = True)
+ (snapshot / name).write_bytes(b"weights")
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text(ref)
+ return repo_dir, snapshot
+
+
+def test_hosted_encoder_cache_is_a_companion_in_both_inventories(monkeypatch, tmp_path):
+ real = cache_inventory.hf_cache_scan.is_snapshot_partial
+ _diffusion_scan(
+ monkeypatch,
+ tmp_path,
+ _QWEN_ENCODER_REPO,
+ [_file("text_encoder/model.safetensors", 4096)],
+ task = "text-to-image",
+ )
+ monkeypatch.setattr(cache_inventory.hf_cache_scan, "is_snapshot_partial", real)
+ (row,) = cache_inventory._scan_cached_models(active_hub_cache = tmp_path / "hub")
+ assert (row["partial"], row["companion_prefetch"], row["partial_transport"]) == (
+ True,
+ True,
+ None,
+ )
+ rows = local_inventory._scan_hf_cache(tmp_path / "hub")
+ assert rows and all(row.partial and row.companion_prefetch for row in rows)
+
+
+def test_interrupted_encoder_cache_keeps_partial_status(monkeypatch, tmp_path):
+ row = _diffusion_scan(
+ monkeypatch,
+ tmp_path,
+ _QWEN_ENCODER_REPO,
+ [_file("text_encoder/model.safetensors", 4096)],
+ task = "text-to-image",
+ download_partial = True,
+ )
+ assert (row["partial"], row["companion_prefetch"]) == (True, False)
+
+
+ ("repo_id", "names", "expected"),
+ [
+ (_QWEN_ENCODER_REPO, [_QWEN_ENCODER_FILE], True),
+ (
+ _QWEN_ENCODER_REPO,
+ [_QWEN_ENCODER_FILE, "Qwen-Image-text_encoder-INT8-ConvRot.safetensors"],
+ True,
+ ),
+ (_QWEN_ENCODER_REPO, ["text_encoder/model.safetensors", "vae/model.safetensors"], True),
+ ("unsloth/LTX-2-FP8", ["LTX-2-text_encoder-FP8.safetensors"], True),
+ ("someone/unrecognized", [_QWEN_ENCODER_FILE], False),
+ (_QWEN_ENCODER_REPO, [_QWEN_ENCODER_FILE, "Qwen-Image-FP8.safetensors"], False),
+ (_QWEN_ENCODER_REPO, [_QWEN_ENCODER_FILE, "Qwen-Image.ckpt"], False),
+ (_QWEN_ENCODER_REPO, [_QWEN_ENCODER_FILE, "transformer/model.safetensors"], False),
+ (_QWEN_ENCODER_REPO, [_QWEN_ENCODER_FILE, "model_index.json"], False),
+ (_QWEN_ENCODER_REPO, ["text_encoder/model-00002-of-00002.safetensors"], False),
+ ],
+)
+def test_encoder_companion_requires_only_whole_hosted_files(tmp_path, repo_id, names, expected):
+ repo_dir, snapshot = _encoder_cache(tmp_path, names, repo_id = repo_id)
+ assert inventory_scan.snapshot_is_encoder_companion(repo_id, repo_dir, snapshot) is expected
+
+
+def test_encoder_companion_refuses_a_bad_index_and_an_empty_file(tmp_path):
+ repo_dir, snapshot = _encoder_cache(tmp_path, ["text_encoder/model.safetensors"])
+ check = lambda: inventory_scan.snapshot_is_encoder_companion(
+ _QWEN_ENCODER_REPO, repo_dir, snapshot
+ )
+ assert check() is True
+ index = snapshot / "text_encoder" / "model.safetensors.index.json"
+ index.write_text(json.dumps({"weight_map": {"x": "missing.safetensors"}}))
+ assert check() is False
+ index.unlink()
+ (snapshot / "text_encoder" / "model.safetensors").write_bytes(b"")
+ assert check() is False
+
+
+def test_encoder_companion_requires_the_index_of_numbered_shards(tmp_path):
+ shards = [f"text_encoder/model-0000{n}-of-00002.safetensors" for n in (1, 2)]
+ repo_dir, snapshot = _encoder_cache(tmp_path, shards)
+ check = lambda: inventory_scan.snapshot_is_encoder_companion(
+ _QWEN_ENCODER_REPO, repo_dir, snapshot
+ )
+ assert check() is False
+ (snapshot / "text_encoder" / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {str(n): Path(s).name for n, s in enumerate(shards)}})
+ )
+ assert check() is True
+
+
+def test_encoder_cache_behind_a_dangling_ref_stays_partial(tmp_path):
+ repo_dir, snapshot = _encoder_cache(tmp_path, [_QWEN_ENCODER_FILE], ref = "b" * 40)
+ assert (
+ inventory_scan.snapshot_is_encoder_companion(_QWEN_ENCODER_REPO, repo_dir, snapshot)
+ is False
+ )
+ (row,) = local_inventory._scan_hf_cache(tmp_path / "hub")
+ assert (row.partial, row.companion_prefetch) == (True, False)
+
+
def test_hf_cache_scan_uses_gguf_partial_row_for_variant_state(monkeypatch, tmp_path):
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
cache_dir = tmp_path / "hub"
diff --git a/studio/backend/hub/utils/companion_assets.py b/studio/backend/hub/utils/companion_assets.py
index ffdd33b9948..8edd3eda5c9 100644
--- a/studio/backend/hub/utils/companion_assets.py
+++ b/studio/backend/hub/utils/companion_assets.py
@@ -9,6 +9,7 @@ import json
import os
import threading
import uuid
+from functools import lru_cache
from pathlib import Path
from typing import Iterable, Optional
@@ -270,6 +271,17 @@ def _hosted_component_table() -> dict[str, dict[str, set[tuple[str, str, str]]]]
return {repo: files for repo, files in table.items() if repo not in image_bases}
+@lru_cache(maxsize = None)
+def hosted_supporting_names(repo_id: str) -> frozenset[str]:
+ """Lowercased names of the encoder and VAE files *repo_id* hosts, leaving out its denoisers."""
+ files = _hosted_component_table().get(_normalise(repo_id)) or {}
+ return frozenset(
+ name
+ for name, owners in files.items()
+ if not any(owner[2] == _HOSTED_DENOISER for owner in owners)
+ )
+
+
def _hosted_names(table, repo_id: str) -> Optional[set[str]]:
files = table.get(_normalise(repo_id))
return None if files is None else set(files)
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index 7a83ae829a1..182a2144230 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -1401,6 +1401,56 @@ def _manifest_snapshot_dirs(
return snapshots
+_COMPONENT_WEIGHT_SUFFIXES = frozenset({".safetensors", ".bin", ".ckpt", ".pt", ".pth", ".gguf"})
+_SUPPORTING_COMPONENT_DIRS = frozenset(
+ {"text_encoder", "text_encoder_2", "text_encoder_3", "text_encoder_4", "vae"}
+)
+
+
+def snapshot_is_encoder_companion(
+ repo_id: str, repo_cache_dir: Optional[Path], snapshot: Optional[Path]
+) -> bool:
+ """Whether *snapshot* holds only whole encoder or VAE files of a repo that hosts them for other models. Its transfer signals stay with :func:`is_snapshot_partial`; a dangling ref is an interrupted attempt, so it never qualifies."""
+ if snapshot is None or repo_cache_dir is None:
+ return False
+ try:
+ from hub.utils.companion_assets import hosted_supporting_names
+
+ hosted = hosted_supporting_names(repo_id)
+ if not hosted or snapshot_has_pipeline_index(snapshot):
+ return False
+ if _repo_has_a_dangling_ref(repo_cache_dir):
+ return False
+ root = Path(snapshot)
+ weights = [p for p in root.rglob("*") if p.suffix.lower() in _COMPONENT_WEIGHT_SUFFIXES]
+ if not weights:
+ return False
+ for weight in weights:
+ rel = weight.relative_to(root)
+ if (
+ rel.as_posix().lower() not in hosted
+ and rel.parts[0] not in _SUPPORTING_COMPONENT_DIRS
+ ):
+ return False
+ if not weight.is_file() or weight.stat().st_size == 0:
+ return False
+ match = _WEIGHT_SHARD_RE.search(weight.name)
+ if match:
+ index = weight.name[: match.start()] + weight.name[match.end() :] + ".index.json"
+ if not (weight.parent / index).is_file():
+ return False
+ template = weight.name[: match.start(1)] + "{}" + weight.name[match.end(1) :]
+ for number in range(1, int(match.group(2)) + 1):
+ sibling = weight.parent / template.format(
+ str(number).zfill(len(match.group(1)))
+ )
+ if not sibling.is_file() or sibling.stat().st_size == 0:
+ return False
+ return all(_read_index_shards(index) is not False for index in root.rglob("*.index.json"))
+ except (OSError, ValueError):
+ return False
+
+
def is_snapshot_partial(
repo_type: RepoType,
repo_id: str,
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
index 9e92f4b361e..2aedf2c1652 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
@@ -43,12 +43,14 @@ import type { IconSvgElement } from "@hugeicons/react";
import { HugeiconsIcon } from "@hugeicons/react";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
+ type FocusEvent,
type ReactNode,
createContext,
memo,
useCallback,
useContext,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -259,12 +261,27 @@ function CatalogRow({
}) {
const [interactive, setInteractive] = useState(COARSE_POINTER);
const arm = useCallback(() => setInteractive(true), []);
+ const rowRef = useRef<HTMLDivElement>(null);
+ const refocusIndex = useRef<number | null>(null);
+ const armFromFocus = (event: FocusEvent<HTMLDivElement>) => {
+ if (interactive) return;
+ const buttons = Array.from(event.currentTarget.querySelectorAll("button"));
+ refocusIndex.current = buttons.indexOf(event.target as Element as HTMLButtonElement);
+ arm();
+ };
+ // Arming wraps the row in a Tooltip, which remounts it and would drop keyboard focus.
+ useLayoutEffect(() => {
+ if (refocusIndex.current === null) return;
+ rowRef.current?.querySelectorAll("button")[refocusIndex.current]?.focus();
+ refocusIndex.current = null;
+ }, [interactive]);
const card = variant === "card";
const button = (
<div
+ ref={rowRef}
data-selected={selected || undefined}
onPointerEnter={arm}
- onFocusCapture={arm}
+ onFocusCapture={armFromFocus}
className={cn(
"group/row relative w-full select-none overflow-hidden text-left",
card
@@ -312,17 +329,19 @@ function StatusDot({
tone,
label,
}: {
- tone: "warning" | "danger" | "success" | "downloading";
+ tone: "warning" | "danger" | "success" | "downloading" | "asset";
label: string;
}) {
const toneClass =
- tone === "warning"
- ? "bg-status-warning"
- : tone === "danger"
- ? "bg-status-danger"
- : tone === "downloading"
- ? DOWNLOADING_DOT_CLASS
- : "bg-status-success";
+ tone === "asset"
+ ? "bg-status-asset"
+ : tone === "warning"
+ ? "bg-status-warning"
+ : tone === "danger"
+ ? "bg-status-danger"
+ : tone === "downloading"
+ ? DOWNLOADING_DOT_CLASS
+ : "bg-status-success";
return (
<span
role="img"
@@ -365,6 +384,7 @@ export function buildRowStatusTooltip({
isGguf,
isAdapter,
isAvailableOnDevice,
+ isSharedAsset,
partialRepoId,
downloading = false,
unsupported,
@@ -374,6 +394,7 @@ export function buildRowStatusTooltip({
isGguf?: boolean;
isAdapter?: boolean;
isAvailableOnDevice?: boolean;
+ isSharedAsset?: boolean;
partialRepoId?: string;
downloading?: boolean;
unsupported?: boolean;
@@ -411,6 +432,12 @@ export function buildRowStatusTooltip({
. Open it to finish the download.
</TooltipLegendRow>,
);
+ } else if (isSharedAsset) {
+ lines.push(
+ <TooltipLegendRow key="asset" toneClass="bg-status-asset">
+ Shared assets. Supporting files used by compatible models.
+ </TooltipLegendRow>,
+ );
} else if (isAvailableOnDevice) {
lines.push(
<TooltipLegendRow key="success" toneClass="bg-status-success">
@@ -647,6 +674,7 @@ export const InventoryRow = memo(function InventoryRow({
isGguf: showFormatDot && row.isGguf,
isAdapter: showFormatDot && row.modelFormat === "adapter",
isAvailableOnDevice: !row.partial,
+ isSharedAsset: row.companionPrefetch,
partialRepoId,
downloading,
unsupported,
@@ -698,7 +726,9 @@ export const InventoryRow = memo(function InventoryRow({
)}
{partialRepoId ? (
<PartialStatusDot downloading={downloading} />
- ) : row.companionPrefetch ? null : (
+ ) : row.companionPrefetch ? (
+ <StatusDot tone="asset" label="Shared assets" />
+ ) : (
<StatusDot tone="success" label="On device" />
)}
{unsupported && (
@@ -708,9 +738,13 @@ export const InventoryRow = memo(function InventoryRow({
);
const compactMarkers =
- partialRepoId || unsupported ? (
+ partialRepoId || row.companionPrefetch || unsupported ? (
<span className="flex shrink-0 items-center gap-1">
- {partialRepoId && <PartialStatusDot downloading={downloading} />}
+ {partialRepoId ? (
+ <PartialStatusDot downloading={downloading} />
+ ) : row.companionPrefetch ? (
+ <StatusDot tone="asset" label="Shared assets" />
+ ) : null}
{unsupported && (
<StatusDot tone="danger" label="May not be supported yet" />
)}
diff --git a/studio/frontend/src/features/hub/hub.css b/studio/frontend/src/features/hub/hub.css
index 0550115e900..3b09b1d4f9f 100644
--- a/studio/frontend/src/features/hub/hub.css
+++ b/studio/frontend/src/features/hub/hub.css
@@ -12,6 +12,7 @@
--status-warning: #eab308;
--status-danger: #ef4444;
--status-success: #11b686;
+ --status-asset: #9270c4;
/* Fixed ink for --status-success: --primary-foreground follows a custom accent and would
lose contrast. */
--status-success-foreground: #0d0d0d;
@@ -26,6 +27,7 @@
--status-warning: #fbbf24;
--status-danger: #ef4444;
--status-success: #11b686;
+ --status-asset: #b69be8;
--status-success-foreground: #0d0d0d;
}
@@ -38,6 +40,7 @@
--color-status-warning: var(--status-warning);
--color-status-danger: var(--status-danger);
--color-status-success: var(--status-success);
+ --color-status-asset: var(--status-asset);
--color-status-success-foreground: var(--status-success-foreground);
}
diff --git a/studio/frontend/tests/hub-companion-prefetch.test.ts b/studio/frontend/tests/hub-companion-prefetch.test.ts
index f3d41086325..5fd35462943 100644
--- a/studio/frontend/tests/hub-companion-prefetch.test.ts
+++ b/studio/frontend/tests/hub-companion-prefetch.test.ts
@@ -169,6 +169,13 @@ test("a companion-only inventory row never gets the green On device dot", () =>
const rows = readSrc("features/hub/catalog/models-catalog-rows.tsx");
assert.match(
rows,
- /<PartialStatusDot downloading=\{downloading\} \/>\s*\) : row\.companionPrefetch \? null : \(\s*<StatusDot tone="success" label="On device" \/>/,
+ /<PartialStatusDot downloading=\{downloading\} \/>\s*\) : row\.companionPrefetch \? \(\s*<StatusDot tone="asset" label="Shared assets" \/>\s*\) : \(\s*<StatusDot tone="success" label="On device" \/>/,
);
});
+
+test("arming a row on keyboard focus puts focus back on the remounted control", () => {
+ const rows = readSrc("features/hub/catalog/models-catalog-rows.tsx");
+ assert.match(rows, /onFocusCapture=\{armFromFocus\}/);
+ assert.match(rows, /refocusIndex\.current = buttons\.indexOf\(/);
+ assert.match(rows, /querySelectorAll\("button"\)\[refocusIndex\.current\]\?\.focus\(\)/);
+});