Skip to content

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

Studio: cut repeated work in the local model listing (#16146)

Daniel Hand8ae3f9376dd
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index cf1b3e39407..2103d79f9ba 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -1457,6 +1457,36 @@ def detect_family(repo_id: str, override: Optional[str] = None) -> Optional[Diff
if any(normalize_family_name(t) == norm for t in (fam.name, *fam.aliases)):
return fam
return None
+ memo = _detect_family_memo()
+ try:
+ return memo[repo_id]
+ except (KeyError, TypeError):
+ pass
+ match = _detect_family_by_name(repo_id)
+ try:
+ if len(memo) >= _DETECT_FAMILY_MEMO_MAX:
+ memo.clear()
+ memo[repo_id] = match
+ except TypeError:
+ pass
+ return match
+
+
+_DETECT_FAMILY_MEMO_MAX = 8192
+# Paired with the table it was filled from: a replaced _FAMILIES starts an empty memo.
+_detect_family_memo_state: tuple[object, dict] = ((), {})
+
+
+def _detect_family_memo() -> dict:
+ global _detect_family_memo_state
+ families, memo = _detect_family_memo_state
+ if families is not _FAMILIES:
+ memo = {}
+ _detect_family_memo_state = (_FAMILIES, memo)
+ return memo
+
+
+def _detect_family_by_name(repo_id: str) -> Optional[DiffusionFamily]:
needle = model_identity(repo_id).lower()
match = _best_family_match(needle)
if match is not None:
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 52f4a956918..623655a93e3 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -1160,6 +1160,36 @@ def detect_video_family(repo_id: str, override: Optional[str] = None) -> Optiona
if any(normalize_family_name(t) == norm for t in (fam.name, *fam.aliases)):
return fam
return None
+ memo = _detect_video_family_memo()
+ try:
+ return memo[repo_id]
+ except (KeyError, TypeError):
+ pass
+ family = _detect_video_family_by_name(repo_id)
+ try:
+ if len(memo) >= _DETECT_VIDEO_FAMILY_MEMO_MAX:
+ memo.clear()
+ memo[repo_id] = family
+ except TypeError:
+ pass
+ return family
+
+
+_DETECT_VIDEO_FAMILY_MEMO_MAX = 8192
+# Paired with the tables it was filled from: replacing either starts an empty memo.
+_detect_video_family_memo_state: tuple[object, object, dict] = ((), (), {})
+
+
+def _detect_video_family_memo() -> dict:
+ global _detect_video_family_memo_state
+ families, unsupported, memo = _detect_video_family_memo_state
+ if families is not _FAMILIES or unsupported is not _UNSUPPORTED_VIDEO_CHECKPOINTS:
+ memo = {}
+ _detect_video_family_memo_state = (_FAMILIES, _UNSUPPORTED_VIDEO_CHECKPOINTS, memo)
+ return memo
+
+
+def _detect_video_family_by_name(repo_id: str) -> Optional[VideoFamily]:
# I2V / VACE / FastWan names can carry a T2V token (Wan2.1_T2V_14B_FusionX_VACE): no T2V pipeline over those weights.
if unsupported_video_checkpoint_reason(repo_id):
return None
diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.py
index c4bceea4a64..e06c88e0f4e 100644
--- a/studio/backend/hub/services/models/catalog_classification.py
+++ b/studio/backend/hub/services/models/catalog_classification.py
@@ -660,15 +660,20 @@ def _local_is_diffusers(model) -> bool:
return True
except Exception:
pass
+ needles: Optional[tuple[str, ...]] = None
try:
from core.inference.diffusion_families import detect_family
- if any(detect_family(needle) is not None for needle in _local_family_needles(model)):
+ needles = _local_family_needles(model)
+ if any(detect_family(needle) is not None for needle in needles):
return True
except Exception:
pass
try:
from core.inference.video_families import detect_video_family
- families = (detect_video_family(needle) for needle in _local_family_needles(model))
+
+ if needles is None:
+ needles = _local_family_needles(model)
+ families = (detect_video_family(needle) for needle in needles)
return any(
family is not None and not _pipeline_only_video_family(family) for family in families
)
diff --git a/studio/backend/hub/utils/download_manifest.py b/studio/backend/hub/utils/download_manifest.py
index 9fd3d8dea0f..41f0ccc094d 100644
--- a/studio/backend/hub/utils/download_manifest.py
+++ b/studio/backend/hub/utils/download_manifest.py
@@ -9,6 +9,7 @@ import hashlib
import json
import os
import re
+import unicodedata
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -31,6 +32,7 @@ from hub.utils.state_dir import (
variant_key_fragments,
)
from utils.paths.path_utils import drop_appledouble_metadata
+from utils.scan_memo import memoized, scan_memo_active
logger = get_logger(__name__)
@@ -292,7 +294,7 @@ def _state_read_path(
)
for path in scoped:
try:
- if path.is_file() and applies(path):
+ if _state_file_may_exist(path) and path.is_file() and applies(path):
return path
except OSError:
continue
@@ -300,7 +302,7 @@ def _state_read_path(
if path in scoped:
continue
try:
- if not path.is_file():
+ if not (_state_file_may_exist(path) and path.is_file()):
continue
except OSError:
continue
@@ -309,6 +311,32 @@ def _state_read_path(
return None
+def _state_name_key(name: str) -> str:
+ # Folded wide enough for case-insensitive (Windows, macOS) and normalization-insensitive (APFS) volumes.
+ return os.path.normcase(unicodedata.normalize("NFC", name)).casefold()
+
+
+def _state_dir_name_keys(directory: Path) -> Optional[frozenset[str]]:
+ try:
+ with os.scandir(directory) as entries:
+ return frozenset(_state_name_key(entry.name) for entry in entries)
+ except (FileNotFoundError, NotADirectoryError):
+ return frozenset()
+ except OSError:
+ return None
+
+
+def _state_file_may_exist(path: Path) -> bool:
+ """False only when this scan's one listing of the state dir lacks the name; else probe as before."""
+ if not scan_memo_active():
+ return True
+ names = memoized(
+ ("hub_state_dir_names", os.fspath(path.parent)),
+ lambda: _state_dir_name_keys(path.parent),
+ )
+ return names is None or _state_name_key(path.name) in names
+
+
def _state_paths(
path_factory,
repo_type: RepoType,
diff --git a/studio/backend/hub/utils/state_dir.py b/studio/backend/hub/utils/state_dir.py
index 86def2cd462..d2b7cfb6054 100644
--- a/studio/backend/hub/utils/state_dir.py
+++ b/studio/backend/hub/utils/state_dir.py
@@ -56,6 +56,12 @@ def state_root(*, create: bool = False) -> Optional[Path]:
def _subdir(name: str, *, create: bool = False) -> Optional[Path]:
+ if not create:
+ return memoized(("hub_state_subdir", name), lambda: _subdir_uncached(name))
+ return _subdir_uncached(name, create = True)
+
+
+def _subdir_uncached(name: str, *, create: bool = False) -> Optional[Path]:
root = state_root(create = create)
if root is None:
return None
diff --git a/studio/backend/tests/test_local_models_list_scan_cache.py b/studio/backend/tests/test_local_models_list_scan_cache.py
new file mode 100644
index 00000000000..fa26cf0fd45
--- /dev/null
+++ b/studio/backend/tests/test_local_models_list_scan_cache.py
@@ -0,0 +1,273 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""/api/models/local keeps per-file and per-name verdicts across requests: the listing must stay
+identical to an uncached scan, notice every add / remove / rewrite, and skip repeated work."""
+
+from __future__ import annotations
+
+import asyncio
+import errno
+import json
+import os
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+import routes.models as models_route
+from core.inference import diffusion_families, video_families
+from hub.utils import download_manifest
+from utils import audio_tokens
+from utils.scan_memo import scan_memo, scan_memo_active
+
+_CSM_TOKENS = {"1": {"content": "<|AUDIO|>"}, "2": {"content": "<|audio_eos|>"}}
+_PLAIN_TOKENS = {"1": {"content": "<|PLAIN|>"}, "2": {"content": "<|plain_eos|>"}}
+
+
+def _clear_cross_request_caches():
+ audio_tokens._TOKENIZER_AUDIO_TYPE_CACHE.clear()
+ diffusion_families._detect_family_memo_state = ((), {})
+ video_families._detect_video_family_memo_state = ((), (), {})
+
+
[email protected](autouse = True)
+def _fresh_caches():
+ _clear_cross_request_caches()
+ yield
+ _clear_cross_request_caches()
+
+
+def _write_tokenizer(path: Path, tokens: dict) -> None:
+ path.write_text(json.dumps({"added_tokens_decoder": tokens}), encoding = "utf-8")
+
+
+def _make_repo(hub: Path, repo_id: str, files: dict[str, str]) -> Path:
+ snapshot = hub / f"models--{repo_id.replace('/', '--')}" / "snapshots" / "rev"
+ snapshot.mkdir(parents = True)
+ (snapshot.parent.parent / "refs").mkdir()
+ (snapshot.parent.parent / "refs" / "main").write_text("rev", encoding = "utf-8")
+ for name, body in files.items():
+ target = snapshot / name
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_text(body, encoding = "utf-8")
+ return snapshot
+
+
+def hub(monkeypatch, tmp_path):
+ active = tmp_path / "hub"
+ active.mkdir()
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+ monkeypatch.setattr("utils.paths.legacy_hf_cache_dir", lambda: tmp_path / "legacy")
+ monkeypatch.setattr("utils.paths.hf_default_cache_dir", lambda: tmp_path / "default")
+ monkeypatch.setattr("utils.paths.lmstudio_model_dirs", lambda: [])
+ monkeypatch.setattr("utils.paths.hermes_model_dirs", lambda: [])
+ monkeypatch.setattr("utils.paths.ollama_model_dirs", lambda: [])
+ monkeypatch.setattr("utils.paths.omlx_model_dirs", lambda: [])
+ monkeypatch.setattr("utils.hf_cache_settings.known_hf_hub_caches", lambda: [active])
+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])
+ config = json.dumps({"architectures": ["LlamaForCausalLM"], "model_type": "llama"})
+ _make_repo(active, "org/plain-chat", {"config.json": config, "model.safetensors": "x"})
+ speech = _make_repo(active, "org/speech-csm", {"config.json": config, "model.safetensors": "x"})
+ _write_tokenizer(speech / "tokenizer_config.json", _CSM_TOKENS)
+ _make_repo(
+ active,
+ "org/flux.1-dev-copy",
+ {"model_index.json": json.dumps({"_class_name": "FluxPipeline"}), "vae/config.json": "{}"},
+ )
+ _make_repo(active, "org/wan2.1-t2v-1.3b-diffusers", {"model_index.json": "{}"})
+ _make_repo(active, "org/tiny-GGUF", {"tiny-Q4_K_M.gguf": "GGUF"})
+ return active
+
+
+def _scan(models_root: Path) -> list[dict]:
+ rows = asyncio.run(models_route._shared_compat_local_inventory_scan(models_root))
+ return [row.model_dump(mode = "json") for row in rows]
+
+
+def _cold_scan(models_root: Path) -> list[dict]:
+ _clear_cross_request_caches()
+ return _scan(models_root)
+
+
+def _row(rows: list[dict], model_id: str) -> dict:
+ return next(row for row in rows if row["model_id"] == model_id)
+
+
+def _speech_tokenizer(hub: Path) -> Path:
+ return hub / "models--org--speech-csm" / "snapshots" / "rev" / "tokenizer_config.json"
+
+
+def test_repeat_scan_is_identical_to_a_cold_scan(hub, tmp_path):
+ first = _scan(tmp_path / "models")
+ second = _scan(tmp_path / "models")
+ assert first == second == _cold_scan(tmp_path / "models")
+ assert _row(first, "org/speech-csm")["audio_type"] == "csm"
+ assert _row(first, "org/speech-csm")["task"] == "text-to-speech"
+ assert _row(first, "org/plain-chat")["audio_type"] is None
+
+
+def test_second_scan_reads_no_tokenizer_config(hub, tmp_path, monkeypatch):
+ reads: list[str] = []
+ real_read_text = Path.read_text
+
+ def counting_read_text(self, *args, **kwargs):
+ reads.append(self.name)
+ return real_read_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", counting_read_text)
+ _scan(tmp_path / "models")
+ assert reads.count("tokenizer_config.json") >= 1
+ reads.clear()
+ _scan(tmp_path / "models")
+ assert reads.count("tokenizer_config.json") == 0
+
+
+def test_rewrite_with_same_size_and_new_mtime_is_reread(hub, tmp_path):
+ tokenizer = _speech_tokenizer(hub)
+ before = _scan(tmp_path / "models")
+ assert _row(before, "org/speech-csm")["audio_type"] == "csm"
+
+ old = tokenizer.stat()
+ _write_tokenizer(tokenizer, _PLAIN_TOKENS)
+ assert tokenizer.stat().st_size == old.st_size
+ os.utime(tokenizer, ns = (old.st_atime_ns, old.st_mtime_ns + 1_000_000_000))
+
+ after = _scan(tmp_path / "models")
+ assert _row(after, "org/speech-csm")["audio_type"] is None
+ assert after == _cold_scan(tmp_path / "models")
+
+
[email protected](sys.platform == "win32", reason = "ctime is creation time on Windows")
+def test_rewrite_that_restores_size_and_mtime_is_still_reread(hub, tmp_path):
+ tokenizer = _speech_tokenizer(hub)
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] == "csm"
+
+ old = tokenizer.stat()
+ _write_tokenizer(tokenizer, _PLAIN_TOKENS)
+ os.utime(tokenizer, ns = (old.st_atime_ns, old.st_mtime_ns))
+ new = tokenizer.stat()
+ assert (new.st_size, new.st_mtime_ns) == (old.st_size, old.st_mtime_ns)
+
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] is None
+
+
+def test_failed_tokenizer_read_is_retried_on_the_next_scan(hub, tmp_path, monkeypatch):
+ real_read_text = Path.read_text
+ failures = [OSError(errno.EMFILE, "Too many open files")]
+
+ def flaky_read_text(self, *args, **kwargs):
+ if self.name == "tokenizer_config.json" and failures:
+ raise failures.pop()
+ return real_read_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", flaky_read_text)
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] is None
+ # The file never changed, so its stat key is the same: the failed read must not be what it answers.
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] == "csm"
+
+
+def test_added_and_removed_models_show_up_on_the_next_scan(hub, tmp_path):
+ before = _scan(tmp_path / "models")
+ assert "org/speech-csm" in {row["model_id"] for row in before}
+
+ shutil.rmtree(hub / "models--org--speech-csm")
+ added = _make_repo(
+ hub,
+ "org/second-speech",
+ {"config.json": json.dumps({"model_type": "llama"}), "model.safetensors": "x"},
+ )
+ _write_tokenizer(added / "tokenizer_config.json", _CSM_TOKENS)
+
+ after = _scan(tmp_path / "models")
+ ids = {row["model_id"] for row in after}
+ assert "org/speech-csm" not in ids
+ assert _row(after, "org/second-speech")["audio_type"] == "csm"
+ assert after == _cold_scan(tmp_path / "models")
+
+
+def test_removed_tokenizer_config_drops_the_audio_type(hub, tmp_path):
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] == "csm"
+ _speech_tokenizer(hub).unlink()
+ assert _row(_scan(tmp_path / "models"), "org/speech-csm")["audio_type"] is None
+
+
+def test_cancel_marker_written_between_scans_marks_the_row_partial(hub, tmp_path):
+ assert _row(_scan(tmp_path / "models"), "org/plain-chat")["partial"] is False
+ assert download_manifest.write_cancel_marker("model", "org/plain-chat", None, hub_cache = hub)
+ after = _scan(tmp_path / "models")
+ assert _row(after, "org/plain-chat")["partial"] is True
+ assert after == _cold_scan(tmp_path / "models")
+ download_manifest.clear_cancel_marker("model", "org/plain-chat", None, hub_cache = hub)
+ assert _row(_scan(tmp_path / "models"), "org/plain-chat")["partial"] is False
+
+
+def test_state_probes_inside_a_scan_skip_absent_files(hub, tmp_path, monkeypatch):
+ assert download_manifest.write_cancel_marker("model", "org/plain-chat", None, hub_cache = hub)
+ probed: list[Path] = []
+ real_is_file = Path.is_file
+
+ def counting_is_file(self, *args, **kwargs):
+ probed.append(self)
+ return real_is_file(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "is_file", counting_is_file)
+ with scan_memo():
+ assert scan_memo_active()
+ assert download_manifest.has_cancel_marker("model", "org/plain-chat", hub_cache = hub)
+ assert not download_manifest.has_cancel_marker("model", "org/speech-csm", hub_cache = hub)
+ # Only the marker that exists is stat'ed; every absent candidate was answered by the listing.
+ assert [path.name for path in probed] == [
+ download_manifest.marker_path("model", "org/plain-chat", None, hub_cache = hub).name
+ ]
+ assert not scan_memo_active()
+
+ probed.clear()
+ assert not download_manifest.has_cancel_marker("model", "org/speech-csm", hub_cache = hub)
+ assert len(probed) > 1 # outside a scan every candidate is probed as before
+
+
+def test_state_listing_falls_back_to_a_probe_on_a_case_variant(tmp_path):
+ directory = tmp_path / "scope"
+ directory.mkdir()
+ (directory / "Models--Org--Repo.json").write_text("{}", encoding = "utf-8")
+ with scan_memo():
+ assert download_manifest._state_file_may_exist(directory / "models--org--repo.json")
+ assert not download_manifest._state_file_may_exist(directory / "models--org--other.json")
+ assert not download_manifest._state_file_may_exist(tmp_path / "missing" / "x.json")
+
+
+ "name",
+ [
+ "black-forest-labs/FLUX.1-dev",
+ "Qwen/Qwen-Image-Edit-2511",
+ "org/flux.3-klein-pup",
+ "/models/models--org--sdxl-base/snapshots/abc/unet",
+ "unsloth/Llama-3.2-1B-Instruct",
+ "",
+ ],
+)
+def test_family_memo_matches_the_uncached_detector(name):
+ assert diffusion_families.detect_family(name) is diffusion_families._detect_family_by_name(name)
+ assert diffusion_families.detect_family(name) is diffusion_families._detect_family_by_name(name)
+ assert video_families.detect_video_family(name) is video_families._detect_video_family_by_name(
+ name
+ )
+ assert video_families.detect_video_family(name) is video_families._detect_video_family_by_name(
+ name
+ )
+
+
+def test_family_memo_follows_a_replaced_table(monkeypatch):
+ name = "black-forest-labs/FLUX.1-dev"
+ assert diffusion_families.detect_family(name) is not None
+ monkeypatch.setattr(diffusion_families, "_FAMILIES", ())
+ assert diffusion_families.detect_family(name) is None
+
+ video = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
+ assert video_families.detect_video_family(video) is not None
+ monkeypatch.setattr(video_families, "_FAMILIES", ())
+ assert video_families.detect_video_family(video) is None
diff --git a/studio/backend/utils/audio_tokens.py b/studio/backend/utils/audio_tokens.py
index 96f0625292f..e9ee0077571 100644
--- a/studio/backend/utils/audio_tokens.py
+++ b/studio/backend/utils/audio_tokens.py
@@ -6,6 +6,10 @@
from __future__ import annotations
import json
+import os
+import stat
+import threading
+from collections import OrderedDict
from pathlib import Path
from typing import Optional
@@ -164,14 +168,47 @@ def detect_local_tts_audio_type(directory) -> Optional[str]:
for tok_path in AUDIO_TOKENIZER_CONFIG_PATHS:
tok_file = root / tok_path
try:
- if not tok_file.is_file() or tok_file.stat().st_size > _MAX_TOKENIZER_CONFIG_BYTES:
+ st = tok_file.stat()
+ if not stat.S_ISREG(st.st_mode) or st.st_size > _MAX_TOKENIZER_CONFIG_BYTES:
continue
- raw = tok_file.read_text(encoding = "utf-8-sig")
- if not may_hold_audio_tokens(raw):
- continue
- audio_type = classify_audio_tokens(json.loads(raw))
except Exception:
continue
+ audio_type = _tokenizer_config_audio_type(tok_file, st)
if is_tts_audio_type(audio_type):
return audio_type
return None
+
+
+# Kept per file version: a rewrite moves mtime/ctime/size/inode and misses.
+_TOKENIZER_AUDIO_TYPE_CACHE: "OrderedDict[tuple, Optional[str]]" = OrderedDict()
+_TOKENIZER_AUDIO_TYPE_CACHE_MAX = 4096
+_TOKENIZER_AUDIO_TYPE_LOCK = threading.Lock()
+
+
+def _tokenizer_config_audio_type(tok_file: Path, st: os.stat_result) -> Optional[str]:
+ key = (
+ os.fspath(tok_file),
+ st.st_dev,
+ st.st_ino,
+ st.st_size,
+ st.st_mtime_ns,
+ st.st_ctime_ns,
+ )
+ with _TOKENIZER_AUDIO_TYPE_LOCK:
+ if key in _TOKENIZER_AUDIO_TYPE_CACHE:
+ _TOKENIZER_AUDIO_TYPE_CACHE.move_to_end(key)
+ return _TOKENIZER_AUDIO_TYPE_CACHE[key]
+ try:
+ raw = tok_file.read_text(encoding = "utf-8-sig")
+ audio_type = classify_audio_tokens(json.loads(raw)) if may_hold_audio_tokens(raw) else None
+ except OSError:
+ # Not cached: a failed read (EMFILE, EIO, a Windows sharing lock) can clear with no change to the file's stat.
+ return None
+ except Exception:
+ # Cached too: a writer that finishes the file moves its mtime or size, so this key misses.
+ audio_type = None
+ with _TOKENIZER_AUDIO_TYPE_LOCK:
+ _TOKENIZER_AUDIO_TYPE_CACHE[key] = audio_type
+ while len(_TOKENIZER_AUDIO_TYPE_CACHE) > _TOKENIZER_AUDIO_TYPE_CACHE_MAX:
+ _TOKENIZER_AUDIO_TYPE_CACHE.popitem(last = False)
+ return audio_type
diff --git a/studio/backend/utils/scan_memo.py b/studio/backend/utils/scan_memo.py
index edf8664c107..962cbbbbab2 100644
--- a/studio/backend/utils/scan_memo.py
+++ b/studio/backend/utils/scan_memo.py
@@ -44,6 +44,12 @@ def scan_memo() -> Iterator[None]:
_scope.reset(token)
+def scan_memo_active() -> bool:
+ """Whether the caller runs inside an open scan_memo() scope."""
+ memo = _scope.get()
+ return memo is not None and _CLOSED not in memo
+
+
def memoized(key: Hashable, compute: Callable[[], _T]) -> _T:
"""compute() once per scope for key; a raise is not cached."""
memo = _scope.get()