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: Fix GGUF classification for custom MTP scan roots (#7648)
Long Yixing37c64912d623
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex 07d00f03741..ef11f8b77ae 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -99,7 +99,7 @@ def _local_gguf_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:safetensors), listing only on-disk quants. ``load_path`` is a concrete localpath so /load resolves the variant locally and never fetches a remote one."""from pathlib import Path- from utils.models.model_config import _is_mmproj, list_local_gguf_variants+ from utils.models.model_config import detect_gguf_model, list_local_gguf_variantspath = getattr(info, "path", None)if not isinstance(path, str):@@ -114,7 +114,7 @@ def _local_gguf_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:# advertise a projector and a switch could load it instead of the weights,# evicting the loaded model. The directory branch below is already mmproj# free (list_local_gguf_variants drops mmproj quants).- if p.suffix.lower() != ".gguf" or _is_mmproj(p.name):+ if p.suffix.lower() != ".gguf" or detect_gguf_model(str(p)) is None:return Nonereturn _LocalGgufEntry(loader_id, str(p), ())load_dir = _resolve_load_dir(p)diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 9cf260b157c..8429d08c8f9 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -569,6 +569,8 @@ async def _collect_models_from_default_sources(def _scan_custom_folder(folder_path: Path) -> List[LocalModelInfo]:+ from utils.models.model_config import detect_gguf_model+supported_formats: set[ModelFormat] = {"gguf", "safetensors", "adapter"}generic = [m@@ -588,7 +590,22 @@ def _scan_custom_folder(folder_path: Path) -> List[LocalModelInfo]:if m.model_format in supported_formatsif not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)]- return generic[:_MAX_MODELS_PER_CUSTOM_FOLDER]+ selectable = []+ for model in generic:+ if model.model_format != "gguf" or model.partial:+ selectable.append(model)+ continue+ path = Path(model.path)+ if path.is_dir():+ if any(+ detect_gguf_model(str(file), model_root = str(folder_path)) is not None+ for file in path.glob("*")+ if not _safe_is_dir(file) and file.suffix.lower() == ".gguf"+ ):+ selectable.append(model)+ elif detect_gguf_model(model.path, model_root = str(folder_path)) is not None:+ selectable.append(model)+ return selectable[:_MAX_MODELS_PER_CUSTOM_FOLDER]def _promote_to_custom_source(model: LocalModelInfo) -> LocalModelInfo:diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex fa5862a13cf..54f167c7ad9 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -103,6 +103,49 @@ def test_big_endian_detection_ignores_model_name_be_token():)+def test_custom_inventory_filters_mtp_companions_at_registered_root(tmp_path, monkeypatch):+ root = tmp_path / "MTP"+ root.mkdir()+ main = root / "Qwen3.6-27B-MTP-Q6_K.gguf"+ model_dir = root / "model"+ model_dir.mkdir()+ (model_dir / "Qwen3.6-27B-MTP-Q8_0.GGUF").write_bytes(b"x")+ for file in (+ main,+ root / "gemma-4-12b-it-Q8_0-MTP.gguf",+ root / "mtp-gemma-4-12b-it.gguf",+ ):+ file.write_bytes(b"x")++ monkeypatch.setattr(gguf, "iter_gguf_files", lambda *_: pytest.fail("recursive scan"))+ rows = local_inventory._scan_custom_folder(root)++ paths = {Path(row.load_id) for row in rows}+ assert {main, model_dir} <= paths+ assert root / "gemma-4-12b-it-Q8_0-MTP.gguf" not in paths+ assert root / "mtp-gemma-4-12b-it.gguf" not in paths++ companion_root = tmp_path / "companion" / "MTP"+ (companion_root / "other.gguf").mkdir(parents = True)+ (companion_root / "config.json").write_bytes(b"{}")+ (companion_root / "gemma-4-12b-it-Q8_0-MTP.gguf").write_bytes(b"x")+ (companion_root / "other.gguf" / "Qwen3.6-27B-Q8_0.gguf").write_bytes(b"x")+ assert companion_root not in {+ Path(row.load_id) for row in local_inventory._scan_custom_folder(companion_root)+ }+++def test_unregistered_variant_identity_stays_scan_relative(tmp_path):+ from utils.models.model_config import list_local_gguf_variants++ snapshot = tmp_path / "deadbeef"+ snapshot.mkdir()+ (snapshot / "model.gguf").write_bytes(b"x")++ assert [v.quant for v in list_local_gguf_variants(str(snapshot))[0]] == ["model"]+ assert [v.quant for v in gguf.list_local_gguf_variants(str(snapshot))[0]] == ["model"]++def _cached_model_row(tmp_path: Path, *, partial: bool, active_cache: bool | None, size_bytes: int):path = tmp_path / f"cache-{active_cache}-{partial}-{size_bytes}"return model_common._local_model_info(diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex eb768db5d63..b58ccbd4126 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -518,10 +518,22 @@ def _resolve_gguf_dir(path: Path) -> Optional[Path]:return None-def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], bool]:+def list_local_gguf_variants(+ directory: str, model_root: Optional[str] = None+) -> tuple[list[GgufVariantInfo], bool]:root = _resolve_gguf_dir(Path(directory))if root is None:return [], False+ from utils.models.model_config import (+ _is_local_mtp_drafter,+ _registered_custom_model_root,+ )++ custom_root = (+ Path(os.path.abspath(Path(model_root).expanduser()))+ if model_root is not None+ else _registered_custom_model_root(directory)+ )quant_totals: dict[str, int] = {}quant_first_file: dict[str, str] = {}@@ -536,7 +548,7 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], booexcept OSError:size = 0rel = file.relative_to(root).as_posix()- if is_mtp_drafter_path(rel):+ if _is_local_mtp_drafter(file, custom_root, rel):continuequant = extract_quant_label(rel)if is_big_endian_gguf_path(rel, quant):diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex f9369d566d3..7e0a8a5acaa 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -812,6 +812,7 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:must already be validated/trusted by the caller."""from storage.studio_db import list_scan_folders+ from utils.models.model_config import detect_gguf_modelfrom utils.paths import (hf_default_cache_dir,legacy_hf_cache_dir,@@ -871,7 +872,29 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:)if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)]- custom_models = _generic+ custom_models = []+ for model in _generic:+ if model.model_format != "gguf" or model.partial:+ custom_models.append(model)+ continue+ path = Path(model.path)+ if path.is_dir():+ patterns = ("*", "*/*") if model.source == "hf_cache" else ("*",)+ if any(+ detect_gguf_model(str(file), model_root = str(folder_path)) is not None+ for pattern in patterns+ for file in path.glob(pattern)+ if not _safe_is_dir(file) and file.suffix.lower() == ".gguf"+ ):+ custom_models.append(model)+ elif (+ detect_gguf_model(+ model.path,+ model_root = str(folder_path),+ )+ is not None+ ):+ custom_models.append(model)if len(custom_models) < _MAX_MODELS_PER_FOLDER:custom_models += _scan_ollama_dir(folder_path,diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 68b181dbdc8..0cb84172fed 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -126,6 +126,56 @@ def test_collect_local_models_prefers_complete_previous_copy(monkeypatch, tmp_paassert row.active_cache is False+def test_legacy_custom_inventory_filters_registered_mtp_root(tmp_path, monkeypatch):+ root = tmp_path / "MTP"+ root.mkdir()+ main = root / "Qwen3.6-27B-MTP-Q6_K.gguf"+ companion = root / "gemma-4-12b-it-Q8_0-MTP.gguf"+ model_dir = root / "model"+ model_dir.mkdir()+ main.write_bytes(b"x")+ companion.write_bytes(b"x")+ model_main = model_dir / "Qwen3.6-27B-MTP-Q8_0.gguf"+ model_main.write_bytes(b"x")+ real_is_dir = Path.is_dir++ def locked_is_dir(path):+ if path == model_main:+ raise OSError("locked")+ return real_is_dir(path)++ monkeypatch.setattr(Path, "is_dir", locked_is_dir)+ companion_dir = root / "companion-only"+ (companion_dir / "other").mkdir(parents = True)+ (companion_dir / "mtp-gemma-4-12b-it-Q8_0.gguf").write_bytes(b"x")+ (companion_dir / "other" / "Qwen3.6-27B-Q8_0.gguf").write_bytes(b"x")+ snapshot = root / "models--Org--Nested" / "snapshots" / "revision"+ quant_dir = snapshot / "BF16"+ quant_dir.mkdir(parents = True)+ (quant_dir / "Qwen3.6-27B-MTP-BF16.gguf").write_bytes(b"x")++ def fail_recursive_variant_scan(*_args, **_kwargs):+ raise AssertionError("unexpected recursive variant scan")++ monkeypatch.setattr(+ "utils.models.model_config._iter_gguf_files",+ fail_recursive_variant_scan,+ )+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(root)}])+ monkeypatch.setattr("utils.paths.lmstudio_model_dirs", lambda: [])+ 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.hf_cache_settings.known_hf_hub_caches", lambda: [])+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: tmp_path / "active")++ rows = models_route.collect_local_models(tmp_path / "models")+ paths = {row.path for row in rows}++ assert {str(main), str(model_dir), str(snapshot.resolve())} <= paths+ assert str(companion_dir) not in paths+ assert str(companion) not in paths++def test_list_cached_gguf_reports_snapshot_load_id_for_inactive_cache(monkeypatch, tmp_path):"""Only a repo outside the active cache needs a snapshot load_id."""active = tmp_path / "active"diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex 95179b86bd1..7262cc380f2 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -22,7 +22,10 @@ if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)from hub.utils.download_manifest import ExpectedFile-from hub.utils.gguf import is_mtp_drafter_path+from hub.utils.gguf import (+ is_mtp_drafter_path,+ list_local_gguf_variants as list_hub_local_gguf_variants,+)from hub.utils.gguf_plan import (build_gguf_variant_plans,plan_from_expected_files,@@ -35,6 +38,7 @@ from utils.models.model_config import (detect_gguf_model,detect_mtp_file,extract_model_size_b,+ list_local_gguf_variants,)from utils.native_path_leases import native_gguf_companion_parent_allowed@@ -426,9 +430,43 @@ def test_detect_gguf_model_rejects_mtp_subdir_copy(tmp_path):sub.mkdir()copy = sub / "gemma-4-12b-it-BF16-MTP.gguf"copy.write_bytes(b"x")+ deep = sub / "BF16" / copy.name+ deep.parent.mkdir()+ deep.write_bytes(b"x")assert detect_gguf_model(str(copy)) is None# Selecting the MTP dir itself must not surface the copies as models.assert detect_gguf_model(str(sub)) is None+ assert list_local_gguf_variants(str(tmp_path))[0] == []+ assert list_hub_local_gguf_variants(str(tmp_path))[0] == []+++def test_registered_mtp_root_keeps_descendant_models_and_excludes_companions(tmp_path, monkeypatch):+ root = tmp_path / "MTP"+ nested = root / "BF16"+ nested.mkdir(parents = True)+ main = root / "Qwen3.6-27B-MTP-001-of-002.gguf"+ terminal = root / "gemma-4-12b-it-Q8_0-MTP.gguf"+ prefixed = root / "mtp-gemma-4-12b-it-Q8_0.gguf"+ nested_model = nested / "gemma-4-12b-it-Q8_0-MTP-001-of-002.gguf"+ for file, size in ((main, 100), (terminal, 20), (prefixed, 30), (nested_model, 40)):+ file.write_bytes(b"x" * size)+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(root)}])++ assert detect_gguf_model(str(main)) == detect_gguf_model(str(root)) == str(main.resolve())+ assert all(detect_gguf_model(str(file)) is None for file in (terminal, prefixed))+ assert detect_gguf_model(str(nested_model)) == str(nested_model.resolve())+ assert [(v.quant, v.filename) for v in list_local_gguf_variants(str(root))[0]] == [+ ("MTP", main.name),+ ("Q8_0", f"BF16/{nested_model.name}"),+ ]+ hub_variants = list_hub_local_gguf_variants(str(root))[0]+ assert (hub_variants[0].quant, hub_variants[0].filename) == ("Qwen3.6-27B-MTP", main.name)+ assert (hub_variants[-1].quant, hub_variants[-1].filename) == (+ "Q8_0",+ f"BF16/{nested_model.name}",+ )+ config = ModelConfig.from_identifier(str(root), gguf_variant = hub_variants[0].quant)+ assert config and config.is_gguf and config.gguf_file == str(main.resolve())# ── Root drafter wins over new-scheme MTP/ copies ────────────────────diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 0e544c6dc63..a030959c280 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -341,7 +341,7 @@ def test_local_gguf_entry_filters_non_gguf_and_recurses(tmp_path):assert e2 is not None and e2.variants-def test_local_gguf_entry_rejects_standalone_mmproj(tmp_path):+def test_local_gguf_entry_rejects_standalone_companions(tmp_path, monkeypatch):# Codex P2: _scan_models_dir's standalone-.gguf pass emits an entry for a# bare mmproj projector (it only filters mmproj inside directory scans). A# projector is not a servable model, so the resolver must reject it or@@ -352,6 +352,17 @@ def test_local_gguf_entry_rejects_standalone_mmproj(tmp_path):proj.write_text("x")assert resolver._local_gguf_entry("p", SimpleNamespace(path = str(proj))) is Noneassert resolver.info_has_local_gguf(SimpleNamespace(id = str(proj), path = str(proj))) is False+ root = tmp_path / "MTP"+ root.mkdir()+ main = root / "Qwen3.6-27B-MTP-Q6_K.gguf"+ terminal = root / "gemma-4-12b-it-Q8_0-MTP.gguf"+ prefixed = root / "mtp-gemma-4-12b-it.gguf"+ for file in (main, terminal, prefixed):+ file.write_text("x")+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(root)}])+ assert resolver._local_gguf_entry("main", SimpleNamespace(path = str(main))) is not None+ assert resolver._local_gguf_entry("terminal", SimpleNamespace(path = str(terminal))) is None+ assert resolver._local_gguf_entry("prefixed", SimpleNamespace(path = str(prefixed))) is Nonedef _entry(loader_id, *variants):diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex c6dcb3f9724..45a77b6eb34 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -1696,7 +1696,54 @@ def detect_mtp_file(return None-def detect_gguf_model(path: str) -> Optional[str]:+def _registered_custom_model_root(path: str) -> Optional[Path]:+ try:+ from storage.studio_db import list_scan_folders+ folders = list_scan_folders()+ except Exception:+ return None+ candidate = Path(os.path.abspath(Path(path).expanduser()))+ matches = []+ for folder in folders:+ raw = folder.get("path")+ if not isinstance(raw, str) or not raw:+ continue+ root = Path(os.path.abspath(Path(normalize_path(raw)).expanduser()))+ try:+ candidate.relative_to(root)+ except ValueError:+ continue+ matches.append(root)+ return max(matches, key = lambda root: len(root.parts), default = None)+++def _local_mtp_context(path: Path, model_root: Optional[Path], fallback: str) -> str:+ if model_root is not None:+ try:+ return Path(os.path.abspath(path)).relative_to(model_root).as_posix()+ except ValueError:+ pass+ return fallback+++def _is_terminal_gemma_mtp(name: str) -> bool:+ stem = re.sub(r"-\d{3,}-of-\d{3,}$", "", Path(name).stem.lower())+ return stem.endswith("-mtp") and bool(re.search(r"(?:^|[-_])gemma[-_]?4(?:[-_]|$)", stem))+++def _is_local_mtp_drafter(path: Path, model_root: Optional[Path], fallback: str) -> bool:+ context = _local_mtp_context(path, model_root, fallback)+ if _is_mtp_drafter(context):+ return True+ return (+ model_root is not None+ and model_root.name.lower() == "mtp"+ and "/" not in context+ and _is_terminal_gemma_mtp(path.name)+ )+++def detect_gguf_model(path: str, model_root: Optional[str] = None) -> Optional[str]:"""Check if a local path is or contains a GGUF model file.Handles a direct .gguf path or a directory of .gguf files. Skips mmproj@@ -1704,6 +1751,11 @@ def detect_gguf_model(path: str) -> Optional[str]:the .gguf path or None. For HF repos, use detect_gguf_model_remote()."""p = Path(path)+ root = (+ Path(os.path.abspath(Path(model_root).expanduser()))+ if model_root is not None+ else _registered_custom_model_root(path)+ )# Case 1: direct .gguf fileif p.suffix.lower() == ".gguf":@@ -1714,7 +1766,11 @@ def detect_gguf_model(path: str) -> Optional[str]:# (...-MTP.gguf) doesn't match the predicate's mtp- prefix.rel = f"{p.parent.name}/{p.name}"quant = _extract_quant_label(rel)- if _is_mmproj(p.name) or _is_mtp_drafter(rel) or _is_big_endian_gguf_path(rel, quant):+ if (+ _is_mmproj(p.name)+ or _is_local_mtp_drafter(p, root, rel)+ or _is_big_endian_gguf_path(rel, quant)+ ):return None# Extension is authoritative: don't gate on is_file()/exists(), which# can fail in the Windows lock window after llama-server is killed.@@ -1734,7 +1790,7 @@ def detect_gguf_model(path: str) -> Optional[str]:quant = _extract_quant_label(context_rel)if (_is_mmproj(f.name)- or _is_mtp_drafter(context_rel)+ or _is_local_mtp_drafter(f, root, context_rel)or _is_big_endian_gguf_path(context_rel, quant)):continue@@ -2098,7 +2154,9 @@ def _resolve_gguf_dir(p: Path) -> Optional[Path]:return None-def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], bool]:+def list_local_gguf_variants(+ directory: str, model_root: Optional[str] = None+) -> tuple[list[GgufVariantInfo], bool]:"""List GGUF quant variants in a local directory.Like :func:`list_gguf_variants` but reads the filesystem. Aggregates shard@@ -2110,6 +2168,11 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boop = _resolve_gguf_dir(Path(directory))if p is None:return [], False+ root = (+ Path(os.path.abspath(Path(model_root).expanduser()))+ if model_root is not None+ else _registered_custom_model_root(directory)+ )quant_totals: dict[str, int] = {}quant_first_file: dict[str, str] = {}@@ -2130,7 +2193,7 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo# Use the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``# get distinct quant labels instead of collapsing on basename.rel = f.relative_to(p).as_posix()- if _is_mtp_drafter(rel):+ if _is_local_mtp_drafter(f, root, rel):continuequant = _extract_quant_label(rel)if _is_big_endian_gguf_path(rel, quant):@@ -2151,7 +2214,11 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], booreturn variants, has_vision-def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:+def _find_local_gguf_by_variant(+ directory: str,+ variant: str,+ model_root: Optional[str] = None,+) -> Optional[str]:"""Find the GGUF file in *directory* matching a quantization *variant*.For sharded GGUFs (multiple files sharing a quant label), returns the@@ -2162,6 +2229,11 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:p = _resolve_gguf_dir(Path(directory))if p is None:return None+ root = (+ Path(os.path.abspath(Path(model_root).expanduser()))+ if model_root is not None+ else _registered_custom_model_root(directory)+ )# Recurse so variants under a quant-named subdir (e.g.# ``BF16/foo-BF16-00001-of-00002.gguf``) are found. Match the relative@@ -2170,10 +2242,11 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:matches = []for f in _iter_gguf_files(p, recursive = True):rel = f.relative_to(p).as_posix()- if _is_mmproj(f.name) or _is_mtp_drafter(rel):+ if _is_mmproj(f.name) or _is_local_mtp_drafter(f, root, rel):continuequant = _extract_quant_label(rel)- if quant != variant or _is_big_endian_gguf_path(rel, quant):+ fallback_variant = re.sub(r"-\d{3,}-of-\d{3,}$", "", rel.rsplit(".", 1)[0])+ if variant not in (quant, fallback_variant) or _is_big_endian_gguf_path(rel, quant):continuematches.append(f)matches.sort()