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: check local single-file checkpoints without importing the diffusion stack (#15587)
Daniel Hanfe66481b7a20
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 01095694bc5..1467722540e 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -963,41 +963,6 @@ def _set_pinned_lora_scales(pipe: Any, weights: dict) -> bool:return True-def resolve_local_single_file(model_path: str) -> Optional[str]:- """The sole single-file checkpoint basename in a local ``model_path`` directory that is NOT a- diffusers pipeline (no ``model_index.json`` or FLUX.3 ``modular_model_index.json``) and holds exactly one ``.safetensors`` file, else- None.-- The On-Device scanner advertises a bare single-file safetensors directory as a text-to-image- model, but the local picker starts it as a ``pipeline`` with no filename, so a pipeline load- 400s on the missing ``model_index.json``. The images load route uses this to reinterpret such a- pick as a ``single_file`` load of the sole checkpoint. A real pipeline dir, or an ambiguous one- (0 or more than 1 ``.safetensors``), returns None and loads unchanged. A PEFT LoRA adapter- folder is also skipped. Never raises.- """- try:- root = Path(model_path).expanduser()- if not root.is_dir() or any(- (root / index).is_file() for index in ("model_index.json", FLUX3_INDEX)- ):- return None- # A PEFT adapter folder is not a base checkpoint; skip it so validation 400s before eviction- if (root / "adapter_config.json").is_file():- return None-- checkpoints = [- p.name- for p in root.iterdir()- if p.is_file()- and p.suffix.lower() == ".safetensors"- and p.stem.lower() != "adapter_model"- and not is_appledouble_metadata(p)- ]- except OSError:- return None- return checkpoints[0] if len(checkpoints) == 1 else None--def split_local_checkpoint_path(model_path: str) -> Optional[tuple[str, str]]:"""``(dir, name)`` when ``model_path`` is one local ``.safetensors`` file, else None."""try:diff --git a/studio/backend/core/inference/diffusion_local_files.py b/studio/backend/core/inference/diffusion_local_files.pynew file mode 100644index 00000000000..c526a5170cc--- /dev/null+++ b/studio/backend/core/inference/diffusion_local_files.py@@ -0,0 +1,36 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Path-only diffusion checks, kept out of core.inference.diffusion so model listing stays light."""++from pathlib import Path+from typing import Optional++from utils.paths.path_utils import is_appledouble_metadata++from .diffusion_flux3 import FLUX3_INDEX+++def resolve_local_single_file(model_path: str) -> Optional[str]:+ """The sole ``.safetensors`` basename in a local non-pipeline, non-adapter dir, else None."""+ try:+ root = Path(model_path).expanduser()+ if not root.is_dir() or any(+ (root / index).is_file() for index in ("model_index.json", FLUX3_INDEX)+ ):+ return None+ # A PEFT adapter folder is not a base checkpoint; skip it so validation 400s before eviction+ if (root / "adapter_config.json").is_file():+ return None++ checkpoints = [+ p.name+ for p in root.iterdir()+ if p.is_file()+ and p.suffix.lower() == ".safetensors"+ and p.stem.lower() != "adapter_model"+ and not is_appledouble_metadata(p)+ ]+ except OSError:+ return None+ return checkpoints[0] if len(checkpoints) == 1 else Nonediff --git a/studio/backend/core/inference/media_locality.py b/studio/backend/core/inference/media_locality.pyindex 2c67abee2d4..465dae73d06 100644--- a/studio/backend/core/inference/media_locality.py+++ b/studio/backend/core/inference/media_locality.py@@ -62,7 +62,8 @@ def detected_image_family(pick: MediaModelPick) -> Any:def normalized_pick(pick: MediaModelPick) -> MediaModelPick:"""Pick as the load routes read it, so companions of a bare single-file directory are planned."""- from core.inference.diffusion import resolve_local_single_file, split_local_checkpoint_path+ from core.inference.diffusion import split_local_checkpoint_path+ from core.inference.diffusion_local_files import resolve_local_single_fileif pick.model_kind or pick.gguf_filename:return pickdiff --git a/studio/backend/core/inference/media_model_index.py b/studio/backend/core/inference/media_model_index.pyindex 5f78f391d0b..310df430a63 100644--- a/studio/backend/core/inference/media_model_index.py+++ b/studio/backend/core/inference/media_model_index.py@@ -248,7 +248,7 @@ def _add_gguf_picks(def _loadable_directory(load_dir: Path) -> bool:"""Only a full pipeline or one checkpoint is loadable: several with no index is ambiguous."""- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filetry:if any(diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.pyindex e1e7697145f..c4bceea4a64 100644--- a/studio/backend/hub/services/models/catalog_classification.py+++ b/studio/backend/hub/services/models/catalog_classification.py@@ -513,7 +513,7 @@ def _local_name_needles(model) -> list[Optional[str]]:def _local_family_needles(model) -> tuple[str, ...]:needles = _local_name_needles(model)try:- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filesingle = resolve_local_single_file(model.path)if single:needles.append(single)@@ -555,7 +555,6 @@ def _local_model_task(model) -> Optional[str]:if not _local_is_diffusers(model):return Nonetry:- from core.inference.video import _is_trusted_video_repofrom core.inference.video_families import (detect_video_family,unsupported_video_checkpoint_reason,@@ -565,7 +564,11 @@ def _local_model_task(model) -> Optional[str]:if not unsupported_video_checkpoint_reason(*_local_name_needles(model), path):for needle in _local_family_needles(model):family = detect_video_family(needle)- if family is None or not _is_trusted_video_repo(path):+ if family is None:+ continue+ from core.inference.video import _is_trusted_video_repo++ if not _is_trusted_video_repo(path):continueif _pipeline_only_video_family(family) and not _is_diffusers_pipeline_dir(Path(path)@@ -726,11 +729,11 @@ def _untrusted_repo_single_files_loadable(repo_info, selected: Optional[Path] =def _cached_repo_task(repo_info, selected: Optional[Path] = None) -> Optional[str]:repo_id = getattr(repo_info, "repo_id", "") or ""try:- from core.inference.video import _is_trusted_video_repofrom core.inference.video_families import detect_video_family-family = detect_video_family(repo_id)if family is not None:+ from core.inference.video import _is_trusted_video_repo+if _pipeline_only_video_family(family):# Generator-first: nvidia/Cosmos3-Edge also has a reasoner root config.json but lists as video.trusted = _is_trusted_video_repo(repo_id) and _repo_has_pipeline_index(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 6f1123addcf..611b6ee013e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -46992,10 +46992,10 @@ async def diffusion_download_plan(await _refuse_disabled_nvfp4_checkpoint(request)from core.inference.diffusion import (get_diffusion_backend,- resolve_local_single_file,split_local_checkpoint_path,resolve_model_kind,)+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.diffusion_engine_router import predict_enginefrom core.inference.diffusion_hub_evidence import prefetch_for_pickfrom core.inference.sd_cpp_engine import ENGINE_MLX, ENGINE_SD_CPP@@ -47232,10 +47232,10 @@ async def load_diffusion_model_gated(]from core.inference.diffusion import (get_diffusion_backend,- resolve_local_single_file,split_local_checkpoint_path,resolve_model_kind,)+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.diffusion_device import (resolve_diffusion_device_target,resolve_selected_cuda_ordinal,diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 470f4b9fe0f..c41bafdd976 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -534,7 +534,7 @@ def _scan_models_dir()# Several loose checkpoints: one row per file (the folder rescue below needs exactly one).- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filefrom hub.utils.comfy_models import loose_diffusion_checkpointssole = resolve_local_single_file(str(models_dir)) if not (found or loose_files) else Nonediff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 4e70670c26d..b9f79b72827 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -166,7 +166,8 @@ async def video_download_plan(update = {"hf_token": account_access.account_hf_token(request.hf_token)})await _refuse_disabled_nvfp4_checkpoint(request)- from core.inference.diffusion import resolve_local_single_file, split_local_checkpoint_path+ from core.inference.diffusion import split_local_checkpoint_path+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.video import (assert_video_precision_available,get_video_backend,@@ -328,7 +329,8 @@ async def load_video_model_gated(for ref in (request.model_path, request.base_repo)if ref and _repo_is_in_the_hub_cache(ref) is not True]- from core.inference.diffusion import resolve_local_single_file, split_local_checkpoint_path+ from core.inference.diffusion import split_local_checkpoint_path+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.diffusion_device import (resolve_diffusion_device_target,resolve_selected_cuda_ordinal,diff --git a/studio/backend/tests/test_account_media_load_retirement_race.py b/studio/backend/tests/test_account_media_load_retirement_race.pyindex 50baf13a31e..000cc8f7603 100644--- a/studio/backend/tests/test_account_media_load_retirement_race.py+++ b/studio/backend/tests/test_account_media_load_retirement_race.py@@ -14,7 +14,7 @@ from fastapi import HTTPExceptionfrom auth import policyfrom core.inference import diffusion, diffusion_device, diffusion_engine_router, video-from core.inference import diffusion_compat+from core.inference import diffusion_compat, diffusion_local_filesfrom core.training import account_jobs as jobsfrom hub.services.models import account_access as accessfrom models.inference import DiffusionLoadRequest@@ -64,7 +64,7 @@ def engine(monkeypatch, tmp_path):)monkeypatch.setattr(diffusion, "get_diffusion_backend", lambda: backend)monkeypatch.setattr(diffusion, "resolve_model_kind", lambda *a, **k: "pipeline")- monkeypatch.setattr(diffusion, "resolve_local_single_file", lambda path: None)+ monkeypatch.setattr(diffusion_local_files, "resolve_local_single_file", lambda path: None)monkeypatch.setattr(diffusion, "_diffusion_backend", fake)monkeypatch.setattr(diffusion_device,diff --git a/studio/backend/tests/test_comfy_scan_folders.py b/studio/backend/tests/test_comfy_scan_folders.pyindex b8717a76083..7a22e713c4f 100644--- a/studio/backend/tests/test_comfy_scan_folders.py+++ b/studio/backend/tests/test_comfy_scan_folders.py@@ -357,7 +357,7 @@ def test_split_local_checkpoint_path(tmp_path):def test_media_pick_of_one_file_in_a_multi_file_folder(tmp_path):- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.media_locality import normalized_pickfrom core.inference.media_model_index import MediaModelPickdiff --git a/studio/backend/tests/test_cpu_media_load_foreign_fence.py b/studio/backend/tests/test_cpu_media_load_foreign_fence.pyindex f46e69280b4..d8bb9e9f50e 100644--- a/studio/backend/tests/test_cpu_media_load_foreign_fence.py+++ b/studio/backend/tests/test_cpu_media_load_foreign_fence.py@@ -63,6 +63,7 @@ def test_cpu_media_load_refuses_a_generation_started_mid_load(diffusion_compat,diffusion_device,diffusion_engine_router,+ diffusion_local_files,video,)from models.inference import DiffusionLoadRequest, VideoLoadRequest@@ -84,7 +85,7 @@ def test_cpu_media_load_refuses_a_generation_started_mid_load(foreign_generation("diffusion" if modality == "image" else "video")monkeypatch.setattr(diffusion, "get_diffusion_backend", lambda: backend)- monkeypatch.setattr(diffusion, "resolve_local_single_file", lambda *_a, **_k: None)+ monkeypatch.setattr(diffusion_local_files, "resolve_local_single_file", lambda *_a, **_k: None)monkeypatch.setattr(video, "get_video_backend", lambda: backend)monkeypatch.setattr(video, "assert_video_precision_available", lambda *_a, **_k: None)monkeypatch.setattr(diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex f6086aa62fc..71ab97d2523 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -2265,7 +2265,7 @@ def test_validate_accepts_custom_local_components(fake_runtime, tmp_path):def test_resolve_local_single_file(tmp_path):- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filed = tmp_path / "solo"d.mkdir()diff --git a/studio/backend/tests/test_diffusion_flux3.py b/studio/backend/tests/test_diffusion_flux3.pyindex ea238d456b3..87cd5d49886 100644--- a/studio/backend/tests/test_diffusion_flux3.py+++ b/studio/backend/tests/test_diffusion_flux3.py@@ -2130,7 +2130,7 @@ def test_the_block_graph_drops_the_prompt_upsampler_step(monkeypatch, with_upsamdef test_a_modular_flux3_dir_with_one_root_checkpoint_stays_a_pipeline(tmp_path):# FLUX.3 ships modular_model_index.json, not model_index.json: a lone root .safetensors must not turn# the directory into a single-file load before the modular validation sees it.- from core.inference.diffusion import resolve_local_single_file+ from core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.diffusion_flux3 import FLUX3_INDEXd = tmp_path / "flux3-klein"diff --git a/studio/backend/tests/test_diffusion_local_files_light.py b/studio/backend/tests/test_diffusion_local_files_light.pynew file mode 100644index 00000000000..79ce80b7025--- /dev/null+++ b/studio/backend/tests/test_diffusion_local_files_light.py@@ -0,0 +1,83 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Model listing and catalog classification must not import core.inference.diffusion."""++from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+++def _probe(tmp_path, call: str) -> list:+ (tmp_path / "model.safetensors").write_bytes(b"")+ probe = (+ "import json, sys\n"+ # cwd alone does not select this checkout under PYTHONSAFEPATH=1.+ f"sys.path.insert(0, {str(_BACKEND)!r})\n"+ "from pathlib import Path\n"+ "from types import SimpleNamespace\n"+ f"d = Path({str(tmp_path)!r})\n"+ f"found = {call}\n"+ "print(json.dumps([found, 'core.inference.diffusion' in sys.modules]))\n"+ )+ result = subprocess.run(+ [sys.executable, "-c", probe],+ capture_output = True,+ text = True,+ cwd = str(_BACKEND),+ timeout = 300,+ )+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout.strip().splitlines()[-1])+++def test_scanning_a_models_folder_does_not_import_the_diffusion_stack(tmp_path):+ found, loaded = _probe(+ tmp_path,+ "[m.path for m in __import__('routes.models', fromlist = ['_'])._scan_models_dir(d)]",+ )+ assert found == [str(tmp_path)]+ assert loaded is False+++def test_catalog_classification_does_not_import_the_diffusion_stack(tmp_path):+ found, loaded = _probe(+ tmp_path,+ "'model.safetensors' in __import__('hub.services.models.catalog_classification',"+ " fromlist = ['_'])._local_family_needles(SimpleNamespace(model_id = None,"+ " display_name = d.name, id = str(d), path = str(d)))",+ )+ assert found is True+ assert loaded is False+++_LOCAL_MODEL = (+ "SimpleNamespace(model_id = None, display_name = 'flux1-dev', id = str(d), path = str(d),"+ " model_format = 'safetensors', base_model = None)"+)+++def test_classifying_a_local_image_checkpoint_does_not_import_the_diffusion_stack(tmp_path):+ task, loaded = _probe(+ tmp_path,+ "__import__('hub.services.models.catalog_classification', fromlist = ['_'])"+ f"._local_model_task({_LOCAL_MODEL})",+ )+ assert task == "text-to-image"+ assert loaded is False+++def test_classifying_a_cached_non_video_repo_does_not_import_the_diffusion_stack(tmp_path):+ task, loaded = _probe(+ tmp_path,+ "__import__('hub.services.models.catalog_classification', fromlist = ['_'])"+ "._cached_repo_task(SimpleNamespace(repo_id = 'unsloth/Llama-3.2-1B-Instruct',"+ " revisions = ()), None)",+ )+ assert task is None+ assert loaded is False