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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: speed up the local model inventory and keep it off the API loop (#8770)
oobaboogaf885e9460aaf
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex cc1a8848cb8..e0ea90a01df 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport jsonimport osimport re+import sysimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPath@@ -1002,10 +1003,13 @@ _DIFFUSERS_DROPPED_PY39 = "0.37.0"# First diffusers release exporting each pipeline class, read off ``src/diffusers/__init__.py`` at# the upstream tags and cross-checked against each release's requires-python on PyPI. An unlisted# class gets a version-free "a newer diffusers" instead of a number, since the ones left out are-# older than any release in play. This exists so the remedy is true: telling a+# older than any release in play -- and ``family_pipeline_available`` reads one as available, so+# every class the listing probes belongs here. This exists so the remedy is true: telling a# 3.9 host that Z-Image needs Python >= 3.10 sends it to upgrade the interpreter when# ``pip install -U diffusers`` (0.36.0 there) would have been enough._PIPELINE_MIN_DIFFUSERS: dict[str, str] = {+ # MiniMax-H3 is judged by its transformer, first available in diffusers 0.40.0.+ "MiniMaxH3Transformer3DModel": "0.40.0","Flux2Pipeline": "0.36.0","ZImagePipeline": "0.36.0","ZImageImg2ImgPipeline": "0.36.0",@@ -1025,6 +1029,12 @@ _PIPELINE_MIN_DIFFUSERS: dict[str, str] = {"QwenImagePipeline": "0.35.0","QwenImageImg2ImgPipeline": "0.35.0","QwenImageInpaintPipeline": "0.35.0",+ "FluxKontextPipeline": "0.35.0",+ "HiDreamImagePipeline": "0.34.0",+ # WanPipeline arrived with Wan2.1 in 0.33.0. The shipped Wan2.2 family wants weights only+ # 0.35 carries, but this table answers class presence, like the attribute probe before it.+ "WanPipeline": "0.33.0",+ "Lumina2Pipeline": "0.33.0","FluxPipeline": "0.30.0","FluxImg2ImgPipeline": "0.30.0","FluxInpaintPipeline": "0.30.0",@@ -1173,6 +1183,47 @@ def assert_pipeline_class_available()+def _module_namespace_is_unreadable(module: Any) -> bool:+ """Return whether probing attributes could import code or read a partial module."""+ if hasattr(type(module), "__getattr__"):+ return True+ if callable(getattr(module, "__getattr__", None)):+ return True+ return bool(getattr(getattr(module, "__spec__", None), "_initializing", False))+++def _installed_diffusers_version() -> Optional[str]:+ """Read the installed diffusers version without importing it."""+ module = sys.modules.get("diffusers")+ if module is not None:+ try:+ installed = getattr(module, "__version__", None)+ except Exception: # noqa: BLE001 -- a module that raises on __version__ just falls through+ installed = None+ if isinstance(installed, str) and installed.strip():+ return installed.strip()+ try:+ from importlib.metadata import version+ installed = version("diffusers")+ except Exception: # noqa: BLE001 -- not installed / unreadable metadata: caller fails open+ return None+ return installed.strip() if isinstance(installed, str) and installed.strip() else None+++def _installed_at_least(installed: str, minimum: str) -> bool:+ """Whether an INSTALLED version satisfies ``minimum``, judged on its release numbers.++ Not ``_version_tuple``, which is for the clean constants in the table above: a vendor build+ carries a PEP 440 local suffix (``0.40.0+dfsg``) that stops the numeric parse mid-version, and+ a git install carries ``.dev0``, which strict PEP 440 sorts below its own release. Both HAVE+ the class, so compare the release they were cut from. An unreadable version answers OPEN."""+ try:+ from packaging.version import Version+ return Version(Version(installed).base_version) >= Version(minimum)+ except Exception: # noqa: BLE001 -- an unparseable version must not hide a model+ return True++def family_probe_class(fam: Any) -> str:"""The class whose presence in the installed diffusers actually proves ``fam`` is loadable.@@ -1197,10 +1248,10 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:conditional or the extra becomes unresolvable). Advertising Z-Image or Krea 2 in the pickeron such an environment offers a pick that can only fail, and no `pip install -U diffusers`can fix it without also upgrading Python. Fails OPEN (True) when diffusers cannot be- imported at all, so a listing never hides a model over an unrelated import problem. The- attribute lookup is inside the guard for the same reason: diffusers resolves its pipelines- lazily, so the class name is only a hasattr for a name it does not know -- for one it does, the- lookup imports that pipeline module and can raise something other than AttributeError."""+ imported at all, so a listing never hides a model over an unrelated import problem.++ Uses installed-version metadata because probing diffusers' lazy attributes imports pipeline+ dependencies. The load path remains the final availability check."""if fam is None:return False# A modular family is judged on its own transformer class, not on the generic@@ -1212,11 +1263,24 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:# the guard below, and ``hasattr(diffusers, "")`` is False -- which would hide the model.if not name:return True- try:- import diffusers- return hasattr(diffusers, name)- except Exception: # noqa: BLE001 -- no diffusers here: the load path reports it properly+ if "diffusers" in sys.modules:+ module = sys.modules["diffusers"]+ # A None entry blocks imports, so preserve the existing fail-open behavior.+ if module is None:+ return True+ if not _module_namespace_is_unreadable(module):+ try:+ return hasattr(module, name)+ except Exception: # noqa: BLE001 -- a probe failure must not hide a model+ return True+ minimum, _needs_py310 = pipeline_class_requirement(name)+ # Unlisted classes predate the version gates in this table.+ if minimum is None:+ return True+ installed = _installed_diffusers_version()+ if installed is None:return True+ return _installed_at_least(installed, minimum)def family_gguf_loadable(fam: DiffusionFamily) -> bool:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 5bc86449586..4b57a2ac63e 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -393,10 +393,9 @@ def _picked_gguf_arch(repo_id: str, gguf_filename: str) -> Optional[str]:if not isinstance(cached, str):return Nonepath = Path(cached)- from utils.models.gguf_metadata import read_gguf_general_metadata+ from utils.models.gguf_metadata import read_gguf_architecture- arch = (read_gguf_general_metadata(str(path)) or {}).get("general.architecture")- return arch.strip() if isinstance(arch, str) and arch.strip() else None+ return read_gguf_architecture(str(path))except Exception: # noqa: BLE001 -- a header read glitch just falls through to name detectionreturn Nonediff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 6a123ec8a34..b3d1c67fed1 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -929,6 +929,7 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel# These rows feed the same pickers as /api/models/local. Classified inside the# shared worker so retrying waiters do not repeat GGUF metadata reads, and only# for a response that is actually about to be served.+ # Classification reads GGUF headers, so keep it off the event loop too.try:from routes.models import _local_model_taskmodels = [@@ -946,7 +947,11 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModelresponse = await _scan_local_models_response(models_dir, custom_folders, sources)if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:raise _LocalCacheChanged(response)- return classify(response)+ classified = await asyncio.to_thread(classify, response)+ # That hop is an await point of its own, so a mutation can land after the check above.+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:+ raise _LocalCacheChanged(response)+ return classified# Discard obsolete results and retry their waiters against the current cache epoch.superseded: Optional[LocalModelListResponse] = None@@ -979,7 +984,7 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel# current. Answer with the freshest one (the loop only reaches here through# the retry path, so there is always one) instead of rescanning forever.logger.warning("Local inventory kept racing cache invalidations; serving the last scan")- return classify(superseded)+ return await asyncio.to_thread(classify, superseded)def get_models_folder_response() -> dict:diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 65d53e830cf..2f2666a0b1b 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -7120,3 +7120,135 @@ def test_a_stale_revisions_filenames_do_not_settle_the_resolved_one(monkeypatch,)assert result["complete_on_disk"] is False, result+++def test_local_inventory_classifies_off_the_event_loop(monkeypatch):+ """Classification must not block unrelated event-loop work."""+ from hub.services.models import local_inventory++ idents: list[int] = []+ loop_is_free = threading.Event()+ model = SimpleNamespace(id = "model")+ model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])+ response = SimpleNamespace(models = [model])+ response.model_copy = lambda update: SimpleNamespace(models = update["models"])++ def classify_row(row):+ idents.append(threading.get_ident())+ # Only a responsive event loop can set this event.+ assert loop_is_free.wait(10), "the event loop was blocked while classification ran"+ return "task"++ async def scan(*_args):+ return response++ async def no_folders():+ return []++ monkeypatch.setitem(+ sys.modules, "routes.models", SimpleNamespace(_local_model_task = classify_row)+ )+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)+ monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: 0)++ async def run():+ async def keep_the_loop_moving():+ while not idents:+ await asyncio.sleep(0.005)+ loop_is_free.set()++ listing = asyncio.create_task(local_inventory.list_local_models_response("./models"))+ await asyncio.wait_for(asyncio.gather(listing, keep_the_loop_moving()), timeout = 15)+ return threading.get_ident(), listing.result()++ loop_ident, listed = asyncio.run(run())+ assert [row.task for row in listed.models] == ["task"]+ assert idents and loop_ident not in idents, "classification ran on the event loop thread"+++def test_local_inventory_classifies_a_superseded_result_off_the_event_loop(monkeypatch):+ """The give-up path serves the freshest scan it has, and classifies it the same way."""+ from hub.services.models import local_inventory++ idents: list[int] = []+ epoch = [0]+ model = SimpleNamespace(id = "model")+ model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])+ response = SimpleNamespace(models = [model])+ response.model_copy = lambda update: SimpleNamespace(models = update["models"])++ async def always_superseded(*_args):+ epoch[0] += 1 # every walk is invalidated before it returns+ return response++ async def no_folders():+ return []++ monkeypatch.setitem(+ sys.modules,+ "routes.models",+ SimpleNamespace(+ _local_model_task = lambda row: idents.append(threading.get_ident()) or "task"+ ),+ )+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", always_superseded)+ monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])++ async def run():+ listed = await asyncio.wait_for(+ local_inventory.list_local_models_response("./models"), timeout = 15+ )+ return threading.get_ident(), listed++ loop_ident, listed = asyncio.run(run())+ assert [row.task for row in listed.models] == ["task"]+ assert idents and loop_ident not in idents, "classification ran on the event loop thread"+++def test_local_inventory_retries_when_the_cache_changes_during_classification(monkeypatch):+ """A deletion landing while classification runs must not be answered with the old rows."""+ from hub.services.models import local_inventory++ epoch = [0]+ scans: list[int] = []++ def _scan_response(tag: str):+ row = SimpleNamespace(id = tag)+ row.model_copy = lambda update, tag = tag: SimpleNamespace(id = tag, task = update["task"])+ response = SimpleNamespace(models = [row])+ response.model_copy = lambda update: SimpleNamespace(models = update["models"])+ return response++ async def scan(*_args):+ scans.append(epoch[0])+ return _scan_response(f"scan{len(scans)}")++ def classify_row(row):+ # The cache is invalidated while the first scan's rows are being classified.+ if len(scans) == 1:+ epoch[0] += 1+ return "task"++ async def no_folders():+ return []++ monkeypatch.setitem(+ sys.modules, "routes.models", SimpleNamespace(_local_model_task = classify_row)+ )+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)+ monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])++ async def run():+ return await asyncio.wait_for(+ local_inventory.list_local_models_response("./models"), timeout = 15+ )++ listed = asyncio.run(run())+ assert scans == [0, 1], scans+ assert [row.id for row in listed.models] == ["scan2"]diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 549f170a41e..77c7660bbcc 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1080,6 +1080,12 @@ async def _shared_compat_local_inventory_scan(requested_sources = sources+ def classify(models: List[LocalModelInfo]) -> List[LocalModelInfo]:+ # Tag each model with its task so the Images picker can filter to diffusion.+ # Inside the shared flight so overlapping callers reuse one classified result+ # instead of each repeating the GGUF header reads.+ return [m.model_copy(update = {"task": _local_model_task(m)}) for m in models]+async def collect(expected_epoch: int, custom_folders: List[dict], scan_sources: _CompatLocalInventorySources) -> List[LocalModelInfo]:@@ -1091,7 +1097,11 @@ async def _shared_compat_local_inventory_scan()if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:raise _CompatLocalCacheChanged(models)- return models+ classified = await asyncio.to_thread(classify, models)+ # That hop is an await point of its own, so a mutation can land after the check above.+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:+ raise _CompatLocalCacheChanged(models)+ return classified# Discard obsolete results and retry their waiters against the current cache epoch.superseded: Optional[List[LocalModelInfo]] = None@@ -1130,7 +1140,7 @@ async def _shared_compat_local_inventory_scan(# current. Answer with the freshest one (the loop only reaches here through# the retry path, so there is always one) instead of rescanning forever.logger.warning("Compat local inventory kept racing cache invalidations; serving the last scan")- return superseded+ return await asyncio.to_thread(classify, superseded)@router.get("/local", response_model = LocalModelListResponse)@@ -1176,9 +1186,6 @@ async def list_local_models(try:models = await _shared_compat_local_inventory_scan(models_root, sources)- # Tag each model with its task so the Images picker can filter to diffusion.- models = [m.model_copy(update = {"task": _local_model_task(m)}) for m in models]-return LocalModelListResponse(models_dir = str(models_root),hf_cache_dir = str(hf_cache_dir),@@ -4018,10 +4025,8 @@ def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:def _gguf_architecture(path: str) -> Optional[str]:"""The GGUF ``general.architecture``, or None. Delegates to the shared,bounds-checked header reader (cached by path/mtime/size)."""- from utils.models.gguf_metadata import read_gguf_general_metadata-- arch = (read_gguf_general_metadata(path) or {}).get("general.architecture")- return arch.strip() if isinstance(arch, str) and arch.strip() else None+ from utils.models.gguf_metadata import read_gguf_architecture+ return read_gguf_architecture(path)def _gguf_family_buildable(name_hints: tuple[Optional[str], ...]) -> bool:diff --git a/studio/backend/tests/data/refactor_guard/patch_targets.json b/studio/backend/tests/data/refactor_guard/patch_targets.jsonindex d1bb41d6c7c..a868726fb5a 100644--- a/studio/backend/tests/data/refactor_guard/patch_targets.json+++ b/studio/backend/tests/data/refactor_guard/patch_targets.json@@ -1153,15 +1153,15 @@"utils.llama_cpp_freshness.read_install_marker": ["tests/test_llama_cpp_mtp_detection.py"],- "utils.models.gguf_metadata.read_gguf_context_length": [- "tests/test_cached_gguf_routes.py",- "tests/test_cached_gguf_routes.py"- ],- "utils.models.gguf_metadata.read_gguf_general_metadata": [+ "utils.models.gguf_metadata.read_gguf_architecture": ["tests/test_video_backend.py","tests/test_video_backend.py","tests/test_video_backend.py"],+ "utils.models.gguf_metadata.read_gguf_context_length": [+ "tests/test_cached_gguf_routes.py",+ "tests/test_cached_gguf_routes.py"+ ],"utils.models.model_config._env_offline": ["tests/test_vision_cache.py"],diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 881d1814c65..7717abea59a 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -223,6 +223,129 @@ def test_compat_local_inventory_requests_share_scan(monkeypatch, tmp_path):)+def _compat_inventory_row(tmp_path, name = "model"):+ return models_route.LocalModelInfo(+ id = name,+ display_name = "Model",+ path = str(tmp_path / f"{name}.gguf"),+ source = "models_dir",+ model_format = "gguf",+ )+++def _compat_inventory_sources(tmp_path):+ return models_route._CompatLocalInventorySources(+ tmp_path,+ tmp_path / "legacy",+ tmp_path / "default",+ (),+ (),+ )+++def test_compat_local_inventory_classifies_inside_the_shared_scan(monkeypatch, tmp_path):+ """Classification belongs to the coalesced flight, and runs off the event loop.++ Producing classified rows inside the flight is what lets overlapping callers reuse one+ result instead of each repeating the GGUF header reads on the shared executor."""+ from hub.utils import inventory_scan as hf_cache_scan++ classifier_threads: list[int] = []+ shared: list[list] = []+ real_shared_scan = hf_cache_scan.shared_scan++ async def recording_shared_scan(flights, key, factory):+ models = await real_shared_scan(flights, key, factory)+ shared.append(models)+ return models++ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])+ monkeypatch.setattr(+ models_route, "_compat_local_inventory_sources", lambda: _compat_inventory_sources(tmp_path)+ )+ monkeypatch.setattr(+ models_route, "collect_local_models", lambda *_a, **_kw: [_compat_inventory_row(tmp_path)]+ )+ monkeypatch.setattr(+ models_route,+ "_local_model_task",+ lambda _model: classifier_threads.append(threading.get_ident()) or "text-generation",+ )+ monkeypatch.setattr(hf_cache_scan, "shared_scan", recording_shared_scan)++ async def run():+ return threading.get_ident(), await models_route.list_local_models(str(tmp_path), "subject")++ loop_thread, listed = asyncio.run(run())+ assert [row.task for row in listed.models] == ["text-generation"]+ # The flight resolves to classified rows, so waiters on it never reclassify.+ assert [[row.task for row in models] for models in shared] == [["text-generation"]]+ assert classifier_threads and loop_thread not in classifier_threads+++def test_compat_local_inventory_rescans_when_the_cache_changes_during_classification(+ monkeypatch, tmp_path+):+ """A deletion landing during the classification hop must not be answered with old rows."""+ from hub.utils import inventory_scan as hf_cache_scan++ epoch = [0]+ scans: list[int] = []++ def collect(*_args, **_kwargs):+ scans.append(epoch[0])+ return [_compat_inventory_row(tmp_path, f"scan{len(scans)}")]++ def classify(_model):+ # The cache is invalidated while the first scan's rows are being classified.+ if len(scans) == 1:+ epoch[0] += 1+ return "text-generation"++ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])+ monkeypatch.setattr(+ models_route, "_compat_local_inventory_sources", lambda: _compat_inventory_sources(tmp_path)+ )+ monkeypatch.setattr(models_route, "collect_local_models", collect)+ monkeypatch.setattr(models_route, "_local_model_task", classify)+ monkeypatch.setattr(hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])++ listed = asyncio.run(models_route.list_local_models(str(tmp_path), "subject"))+ assert scans == [0, 1], scans+ assert [row.id for row in listed.models] == ["scan2"]+++def test_compat_local_inventory_classifies_a_superseded_result(monkeypatch, tmp_path):+ """The give-up path serves the freshest scan it has, classified like any other."""+ from hub.utils import inventory_scan as hf_cache_scan++ epoch = [0]+ classifier_threads: list[int] = []++ def collect(*_args, **_kwargs):+ epoch[0] += 1 # every walk is invalidated before it returns+ return [_compat_inventory_row(tmp_path)]++ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])+ monkeypatch.setattr(+ models_route, "_compat_local_inventory_sources", lambda: _compat_inventory_sources(tmp_path)+ )+ monkeypatch.setattr(models_route, "collect_local_models", collect)+ monkeypatch.setattr(+ models_route,+ "_local_model_task",+ lambda _model: classifier_threads.append(threading.get_ident()) or "text-generation",+ )+ monkeypatch.setattr(hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])++ async def run():+ return threading.get_ident(), await models_route.list_local_models(str(tmp_path), "subject")++ loop_thread, listed = asyncio.run(run())+ assert [row.task for row in listed.models] == ["text-generation"]+ assert classifier_threads and loop_thread not in classifier_threads++def test_legacy_custom_inventory_filters_registered_mtp_root(tmp_path, monkeypatch):root = tmp_path / "MTP"root.mkdir()@@ -5012,3 +5135,248 @@ def test_a_saved_inpaint_pipeline_is_not_tagged_as_its_base_family():"FluxImg2ImgPipeline",):assert families.detect_family_by_pipeline_class(variant) is None, variant+++# Diffusers listing probes+++def _listing_families():+ from core.inference.diffusion_families import detect_family, family_probe_class+ from core.inference.video_families import detect_video_family++ z_image = detect_family("unsloth/Z-Image-Turbo") # ZImagePipeline, from 0.36.0+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3") # ModularPipeline, probed on its transformer+ assert z_image is not None and h3 is not None+ assert family_probe_class(h3) == "MiniMaxH3Transformer3DModel"+ return z_image, h3+++def test_the_listing_probe_reads_the_installed_version_instead_of_importing_diffusers(monkeypatch):+ """Listing models must not import diffusers' lazy pipeline modules."""+ import importlib.metadata++ from core.inference.diffusion_families import family_pipeline_available++ z_image, h3 = _listing_families()+ installed = ["0.39.0"]+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.setattr(importlib.metadata, "version", lambda name: installed[0])++ assert family_pipeline_available(z_image) is True+ assert (+ family_pipeline_available(h3) is False+ ) # 0.40.0 is the first release with its transformer+ assert "diffusers" not in sys.modules, "the listing probe imported diffusers"++ installed[0] = "0.40.0.dev0" # a dev build of the release that has it+ assert family_pipeline_available(h3) is True++ installed[0] = "0.35.2" # the last release before ZImagePipeline+ assert family_pipeline_available(z_image) is False+ assert "diffusers" not in sys.modules+++def test_the_listing_probe_fails_open_when_the_version_is_unknowable(monkeypatch):+ """An unknown version must not hide models from listings."""+ import importlib.metadata++ from core.inference.diffusion_families import family_pipeline_available++ z_image, h3 = _listing_families()+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)++ def _not_installed(name):+ raise importlib.metadata.PackageNotFoundError(name)++ monkeypatch.setattr(importlib.metadata, "version", _not_installed)+ assert family_pipeline_available(z_image) is True+ assert family_pipeline_available(h3) is True++ # A None entry blocks importing diffusers.+ monkeypatch.setattr(importlib.metadata, "version", lambda name: "0.30.0")+ monkeypatch.setitem(sys.modules, "diffusers", None)+ assert family_pipeline_available(z_image) is True+ assert family_pipeline_available(h3) is True+++def test_the_listing_probe_still_judges_a_conventional_module_by_its_attributes(monkeypatch):+ """A conventional module can still be checked by its exported attributes."""+ import importlib.metadata++ from core.inference.diffusion_families import family_pipeline_available++ z_image, h3 = _listing_families()+ monkeypatch.setattr(importlib.metadata, "version", lambda name: "0.40.0")+ stub = types.ModuleType("diffusers")+ stub.__version__ = "0.40.0" # new enough for every class, and it exports none of them+ monkeypatch.setitem(sys.modules, "diffusers", stub)++ assert family_pipeline_available(z_image) is False+ assert family_pipeline_available(h3) is False++ stub.ZImagePipeline = object+ assert family_pipeline_available(z_image) is True+ assert family_pipeline_available(h3) is False++ # Classes without a version gate are still checked directly.+ from core.inference.diffusion_families import detect_family++ sdxl = detect_family("stabilityai/stable-diffusion-xl-base-1.0")+ assert sdxl is not None+ assert family_pipeline_available(sdxl) is False+ stub.StableDiffusionXLPipeline = object+ assert family_pipeline_available(sdxl) is True+++def test_the_listing_probe_never_touches_a_lazy_modules_attributes(monkeypatch):+ """Attribute reads on a lazy module would trigger imports."""+ from core.inference.diffusion_families import family_pipeline_available++ z_image, _h3 = _listing_families()++ class _Lazy(types.ModuleType):+ def __init__(self, version: str) -> None:+ super().__init__("diffusers")+ self.__version__ = version+ self.resolved: list[str] = []++ def __getattr__(self, item): # only reached for names not already in the namespace+ self.resolved.append(item)+ raise AttributeError(item)++ lazy = _Lazy("0.40.0")+ monkeypatch.setitem(sys.modules, "diffusers", lazy)+ assert family_pipeline_available(z_image) is True+ assert lazy.resolved == [], lazy.resolved++ lazy = _Lazy("0.35.2")+ monkeypatch.setitem(sys.modules, "diffusers", lazy)+ assert family_pipeline_available(z_image) is False+ assert lazy.resolved == [], lazy.resolved+++def test_the_load_path_stays_the_authority_on_a_nonstandard_build(monkeypatch):+ """The load path must reject a class omitted by a nonstandard build."""+ import pytest++ from core.inference.diffusion_families import (+ assert_pipeline_class_available,+ family_pipeline_available,+ )++ z_image, _h3 = _listing_families()++ class _LazyMissingTheClass(types.ModuleType):+ def __getattr__(self, item):+ raise AttributeError(item)++ nonstandard = _LazyMissingTheClass("diffusers")+ nonstandard.__version__ = "0.40.0"+ monkeypatch.setitem(sys.modules, "diffusers", nonstandard)++ assert family_pipeline_available(z_image) is True+ with pytest.raises(ValueError, match = "ZImagePipeline"):+ assert_pipeline_class_available("ZImagePipeline", "z-image")+++def test_the_listing_probe_does_not_read_a_module_that_is_still_importing(monkeypatch):+ """A partial module from a concurrent import must not hide model rows."""+ import importlib.metadata+ import importlib.util++ from core.inference.diffusion_families import family_pipeline_available++ z_image, h3 = _listing_families()++ partial = types.ModuleType("diffusers")+ spec = importlib.util.spec_from_loader("diffusers", loader = None)+ spec._initializing = True+ partial.__spec__ = spec+ monkeypatch.setitem(sys.modules, "diffusers", partial)++ installed = ["0.40.0"]+ monkeypatch.setattr(importlib.metadata, "version", lambda name: installed[0])++ # Use package metadata while the module namespace is incomplete.+ assert family_pipeline_available(z_image) is True+ assert family_pipeline_available(h3) is True++ # An old installed version still fails the gate.+ installed[0] = "0.35.2"+ assert family_pipeline_available(z_image) is False++ # A fully imported conventional module is checked directly.+ spec._initializing = False+ installed[0] = "0.40.0"+ assert family_pipeline_available(z_image) is False+ partial.ZImagePipeline = object+ assert family_pipeline_available(z_image) is True+++def test_the_listing_probe_reads_a_vendor_or_prerelease_version(monkeypatch):+ """A local or pre-release suffix names the release the build was cut from."""+ import importlib.metadata++ from core.inference.diffusion_families import detect_family, family_pipeline_available++ z_image, h3 = _listing_families()+ sdxl = detect_family("stabilityai/stable-diffusion-xl-base-1.0")+ assert sdxl is not None+ installed = ["0.40.0+dfsg"]+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.setattr(importlib.metadata, "version", lambda name: installed[0])++ assert family_pipeline_available(sdxl) is True+ # A vendor rebuild of the release that first shipped the class.+ assert family_pipeline_available(h3) is True+ assert family_pipeline_available(z_image) is True++ for version in ("0.40.0rc1", "0.40.0.dev0", "0.40.1+local"):+ installed[0] = version+ assert family_pipeline_available(h3) is True, version++ # An older rebuild is still too old.+ installed[0] = "0.39.0+dfsg"+ assert family_pipeline_available(h3) is False+ assert family_pipeline_available(z_image) is True++ # An unreadable version fails open, like a missing one.+ installed[0] = "unknown"+ assert family_pipeline_available(h3) is True+ assert "diffusers" not in sys.modules, "the listing probe imported diffusers"+++def test_every_listing_probe_class_has_a_version_gate():+ """An unlisted class reads as available, so every probed class needs an entry."""+ from core.inference.diffusion_families import (+ _FAMILIES,+ _PIPELINE_MIN_DIFFUSERS,+ family_probe_class,+ )+ from core.inference.video_families import _FAMILIES as _VIDEO_FAMILIES++ # Exported before any diffusers still in play, so no entry can make the answer more true.+ predates_every_release = {"StableDiffusionXLPipeline"}+ probed = {family_probe_class(fam) for fam in (*_FAMILIES, *_VIDEO_FAMILIES)}+ ungated = sorted(name for name in probed if name and name not in _PIPELINE_MIN_DIFFUSERS)+ assert set(ungated) <= predates_every_release, ungated+++def test_the_listing_probe_hides_a_class_the_installed_diffusers_predates(monkeypatch):+ """A family whose class the install predates must not reach the picker."""+ import importlib.metadata++ from core.inference.diffusion_families import family_pipeline_available, family_probe_class+ from core.inference.video_families import detect_video_family++ wan = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")+ assert wan is not None and family_probe_class(wan) == "WanPipeline"++ installed = ["0.32.0"]+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)+ monkeypatch.setattr(importlib.metadata, "version", lambda name: installed[0])++ assert family_pipeline_available(wan) is False # WanPipeline arrived in 0.33.0+ installed[0] = "0.33.0"+ assert family_pipeline_available(wan) is True+ assert "diffusers" not in sys.modules, "the listing probe imported diffusers"diff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.pyindex 872103f20eb..3092a80e9a7 100644--- a/studio/backend/tests/test_gguf_metadata.py+++ b/studio/backend/tests/test_gguf_metadata.py@@ -14,6 +14,7 @@ from utils.models.gguf_metadata import (is_mmproj_by_metadata,mmproj_accepts_image,pairing_score,+ read_gguf_architecture,read_gguf_context_length,read_gguf_general_metadata,read_gguf_staged_dims,@@ -417,6 +418,114 @@ def test_mmproj_audio_capability_missing_or_non_gguf(tmp_path: Path):assert read_mmproj_audio_capability(str(junk)) is None+# read_gguf_architecture+++class _CountingFile:+ """A file handle that records how many reads and seeks a parser performs on it."""++ def __init__(self, handle) -> None:+ self._handle = handle+ self.operations = 0++ def read(self, size = -1):+ self.operations += 1+ return self._handle.read(size)++ def seek(+ self,+ offset,+ whence = 0,+ ):+ self.operations += 1+ return self._handle.seek(offset, whence)++ def __enter__(self):+ return self++ def __exit__(self, *exc_info):+ return self._handle.__exit__(*exc_info)+++def _count_header_operations(monkeypatch, path: Path, read) -> int:+ """File operations ``read`` performs against ``path``. Other files are untouched."""+ import builtins++ real_open = builtins.open+ counters: list[_CountingFile] = []++ def counting_open(file, *args, **kwargs):+ handle = real_open(file, *args, **kwargs)+ if str(file) != str(path):+ return handle+ counter = _CountingFile(handle)+ counters.append(counter)+ return counter++ monkeypatch.setattr(builtins, "open", counting_open)+ try:+ read(str(path))+ finally:+ monkeypatch.undo()+ return sum(counter.operations for counter in counters)+++def test_architecture_read_stops_before_a_large_tokenizer_array(tmp_path: Path, monkeypatch):+ """Reading one key must not scan a large tokenizer array."""+ p = _write_synthetic_gguf(+ tmp_path / "model.gguf",+ {"general.architecture": "llama", "general.name": "Test"},+ extra_string_arrays = {"tokenizer.ggml.tokens": [f"tok{i}" for i in range(20000)]},+ )++ assert read_gguf_architecture(str(p)) == "llama"+ assert read_gguf_general_metadata(str(p)) == {+ "general.architecture": "llama",+ "general.name": "Test",+ }++ # Use separate paths to avoid the readers' file-stat caches.+ targeted = tmp_path / "targeted.gguf"+ targeted.write_bytes(p.read_bytes())+ whole = tmp_path / "whole.gguf"+ whole.write_bytes(p.read_bytes())++ targeted_ops = _count_header_operations(monkeypatch, targeted, read_gguf_architecture)+ whole_ops = _count_header_operations(monkeypatch, whole, read_gguf_general_metadata)+ assert targeted_ops < 10, targeted_ops+ assert whole_ops > 20000, whole_ops+++def test_architecture_is_stripped_and_absent_values_are_none(tmp_path: Path):+ stripped = _write_synthetic_gguf(+ tmp_path / "padded.gguf", {"general.architecture": " ltxv \n"}+ )+ assert read_gguf_architecture(str(stripped)) == "ltxv"++ blank = _write_synthetic_gguf(tmp_path / "blank.gguf", {"general.architecture": " "})+ assert read_gguf_architecture(str(blank)) is None++ empty = _write_synthetic_gguf(tmp_path / "empty.gguf", {})+ assert read_gguf_architecture(str(empty)) is None++ assert read_gguf_architecture(str(tmp_path / "nope.gguf")) is None+ junk = tmp_path / "garbage.gguf"+ junk.write_bytes(b"not a gguf file at all, just bytes")+ assert read_gguf_architecture(str(junk)) is None+++def test_architecture_matches_the_general_metadata_reader(tmp_path: Path):+ """The targeted and general readers must return the same architecture."""+ for index, arch in enumerate(("llama", "flux2", "ltxv", "dflash", "qwen3vl")):+ p = _write_synthetic_gguf(+ tmp_path / f"model{index}.gguf",+ {"general.architecture": arch, "general.name": "n", "general.type": "model"},+ extra_uint32 = {f"{arch}.block_count": 32},+ )+ expected = (read_gguf_general_metadata(str(p)) or {}).get("general.architecture")+ assert read_gguf_architecture(str(p)) == expected == arch++# --- mmproj_accepts_image ----------------------------------------------diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex c32f1059d18..909ca8d89ac 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -794,9 +794,7 @@ def test_detect_load_family_cached_hub_arch_fallback(monkeypatch):"try_to_load_from_cache",lambda repo_id, filename, **kw: "/fake/cache/blobs/model.gguf",)- monkeypatch.setattr(- gguf_meta, "read_gguf_general_metadata", lambda path: {"general.architecture": "ltxv"}- )+ monkeypatch.setattr(gguf_meta, "read_gguf_architecture", lambda path: "ltxv")fam = _detect_load_family("someorg/opaque-quants", "model.gguf", None)assert fam is not None and fam.name == "ltx-2"@@ -808,9 +806,7 @@ def test_detect_load_family_cached_hub_arch_fallback(monkeypatch):monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", lambda *a, **k: "/fake/cache/blobs/model.gguf")- monkeypatch.setattr(- gguf_meta, "read_gguf_general_metadata", lambda path: {"general.architecture": "wan"}- )+ monkeypatch.setattr(gguf_meta, "read_gguf_architecture", lambda path: "wan")assert _detect_load_family("someorg/opaque-quants", "model.gguf", None) is None# The blob lives in a NON-active cache root: the active probe misses, but the per-root probe finds it.@@ -818,9 +814,7 @@ def test_detect_load_family_cached_hub_arch_fallback(monkeypatch):monkeypatch.setattr(hub_paths, "legacy_hf_cache_dir", lambda: "/fake/legacy")monkeypatch.setattr(hub_paths, "hf_default_cache_dir", lambda: "/fake/default")- monkeypatch.setattr(- gguf_meta, "read_gguf_general_metadata", lambda path: {"general.architecture": "ltxv"}- )+ monkeypatch.setattr(gguf_meta, "read_gguf_architecture", lambda path: "ltxv")monkeypatch.setattr(huggingface_hub,"try_to_load_from_cache",@@ -2371,23 +2365,23 @@ def test_detect_load_family_arch_fallback_for_local_gguf(tmp_path, monkeypatch):# ltxv arch resolves to the ltx-2 family via the arch fallback.monkeypatch.setattr(- "utils.models.gguf_metadata.read_gguf_general_metadata",- lambda p: {"general.architecture": "ltxv"},+ "utils.models.gguf_metadata.read_gguf_architecture",+ lambda p: "ltxv",)fam = vid._detect_load_family(str(d), "model.gguf", None)assert fam is not None and fam.name == "ltx-2"# A video arch with no backend family (wan) stays None, so the loader 400s as before.monkeypatch.setattr(- "utils.models.gguf_metadata.read_gguf_general_metadata",- lambda p: {"general.architecture": "wan"},+ "utils.models.gguf_metadata.read_gguf_architecture",+ lambda p: "wan",)assert vid._detect_load_family(str(d), "model.gguf", None) is None# An explicit family_override skips the arch read entirely (worker parity).monkeypatch.setattr(- "utils.models.gguf_metadata.read_gguf_general_metadata",- lambda p: {"general.architecture": "ltxv"},+ "utils.models.gguf_metadata.read_gguf_architecture",+ lambda p: "ltxv",)assert vid._detect_load_family(str(d), "model.gguf", "ltx-2").name == "ltx-2"diff --git a/studio/backend/utils/models/drafters/dflash.py b/studio/backend/utils/models/drafters/dflash.pyindex c9dd1fdcb88..d09d7aeca69 100644--- a/studio/backend/utils/models/drafters/dflash.py+++ b/studio/backend/utils/models/drafters/dflash.py@@ -17,7 +17,7 @@ import osfrom pathlib import Pathfrom typing import Callable, Optional-from utils.models.gguf_metadata import read_gguf_general_metadata+from utils.models.gguf_metadata import read_gguf_architecturefrom utils.models.drafters.common import (_drafter_launch_path,_drafter_matches_weight,@@ -50,8 +50,7 @@ def is_dflash_architecture(path: str) -> bool:apply it -- a remote path that trusted the prefix alone would downloadgigabytes the launch then cannot use."""- meta = read_gguf_general_metadata(str(path)) or {}- return (meta.get("general.architecture") or "").strip().lower() == "dflash"+ return (read_gguf_architecture(str(path)) or "").lower() == "dflash"def detect_dflash_file(@@ -205,7 +204,7 @@ def detect_dflash_file(# Re-read only on the reject path, and header reads are cached by# (path, mtime, size), so naming the offending architecture in the# log costs nothing.- (read_gguf_general_metadata(launch) or {}).get("general.architecture"),+ read_gguf_architecture(launch),)continuelogger.info("Detected DFlash drafter: %s", launch)diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex d4d7b4bcd95..72c50c07b9f 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -489,6 +489,16 @@ def read_gguf_chat_template(path: str) -> Optional[str]:return None+def read_gguf_architecture(path: str) -> Optional[str]:+ """``general.architecture``, or ``None`` when absent / unreadable / not a GGUF.++ Reads only the requested key instead of walking the rest of the header."""+ architecture = _read_gguf_string(path, "general.architecture")+ if isinstance(architecture, str) and architecture.strip():+ return architecture.strip()+ return None++def read_mmproj_audio_capability(path: str) -> Optional[bool]:"""``clip.has_audio_encoder`` from an mmproj GGUF (e.g. Gemma 4'sgemma4ua): ``True``/``False`` if present, ``None`` if absent/unreadable.