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
Keep download scopes out of the GGUF quantization list (#8153)
Michael Han5c4623f55638
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex 2aaac31a187..a30b34f48cb 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -302,6 +302,39 @@ def gguf_variant_blob_hashes(return frozenset()+def _is_scope_key(variant: str) -> bool:+ """Whether a stored variant key is a download SCOPE ("@diffusion"), not a quant.++ A scoped job rides the variant slot with an "@" prefix to keep its state out+ of the quant namespace. Its manifest names the file it fetched, so rebuilding+ quants from download state would list the same .gguf twice, the scope row+ permanently partial, and cost the picker its single-quant collapse.+ """+ return variant.startswith("@")+++def _quants_from_state(+ repo_id: str, hub_cache: Optional[Path]+) -> Optional[tuple[list[GgufVariantInfo], bool]]:+ """``list_partial_gguf_variants_from_state`` with download scopes dropped.++ A scope whose payload is gone is dropped by the lister, the only place that+ can tell a recovered digest from a variant truly named like one (see+ _is_state_filename_fallback); left here is the readable "@diffusion" case.+ Scopes alone return None like nothing at all, since a scope naming no .gguf+ reconstructs as ``f"{variant}.gguf"``, a file that never existed, so the+ caller must fall through rather than serve one.+ """+ partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)+ if partial is None:+ return None+ variants, has_vision = partial+ variants = [v for v in variants if not (v.quant and _is_scope_key(v.quant))]+ if not variants:+ return None+ return variants, has_vision++def _partial_transport_for_variant(repo_id: str,variant: str,@@ -939,7 +972,7 @@ async def get_gguf_variants_answer(before any file landed has no snapshot entry, so a listing builtfrom the cache alone reads as if it were never asked for, and therow loses its resume."""- state = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)+ state = _quants_from_state(repo_id, hub_cache)if state is None:return responselisted = {v.quant.lower() for v in response.variants if v.quant}@@ -1067,7 +1100,7 @@ async def get_gguf_variants_answer(return _local_response(repo_id, variants, has_vision, _complete_quants_under(local_path))- partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)+ partial = _quants_from_state(repo_id, hub_cache)if partial is not None:variants, has_vision = partialreturn _partial_local_response(repo_id, variants, has_vision)@@ -1102,7 +1135,7 @@ async def get_gguf_variants_answer(return _with_state_partials(_local_response(repo_id, variants, has_vision, complete))- partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)+ partial = _quants_from_state(repo_id, hub_cache)if partial is not None:variants, has_vision = partialreturn _partial_local_response(repo_id, variants, has_vision)diff --git a/studio/backend/hub/tests/test_download_manifest_scoping.py b/studio/backend/hub/tests/test_download_manifest_scoping.pyindex 966eeaf0c29..a7cc5a0bed8 100644--- a/studio/backend/hub/tests/test_download_manifest_scoping.py+++ b/studio/backend/hub/tests/test_download_manifest_scoping.py@@ -60,3 +60,45 @@ def test_purge_state_removes_legacy_owned_by_the_deleted_cache(monkeypatch, tmp_assert removed is Trueassert not legacy.is_file() # owned by the deleted cache -> purged+++def test_a_scope_whose_payload_is_lost_reads_back_as_a_digest(monkeypatch, tmp_path):+ """A scope is unspellable in a filename, so it is stored hashed. Lose the payload+ and the reader falls back to that filename, handing back the digest instead of+ "@diffusion" -- and the older tag spells it without the "@". Both have to be+ recognisable as digests."""+ hub_cache = tmp_path / "hub"+ hub_cache.mkdir(parents = True)+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(+ "utils.hf_cache_settings.get_hf_cache_paths",+ lambda: SimpleNamespace(hub_cache = str(hub_cache)),+ )++ download_manifest.write_cancel_marker(+ "model", "Org/Model", "@diffusion", transport = "xet", hub_cache = str(hub_cache)+ )+ ((variant, path),) = download_manifest.iter_variant_markers(+ "model", "Org/Model", hub_cache = str(hub_cache)+ )+ assert variant == "@diffusion" # intact while the payload is readable+ assert "--variant--@sha256-" in path.name++ payload = json.loads(path.read_text(encoding = "utf-8"))+ payload.pop("variant")+ for name, expected_tag in (+ (path.name, "@sha256-"),+ (path.name.replace("@sha256-", "sha256-"), "sha256-"),+ ):+ target = path.with_name(name)+ _write_manifest(target, payload)+ ((recovered, _),) = download_manifest.iter_variant_markers(+ "model", "Org/Model", hub_cache = str(hub_cache)+ )+ assert recovered.startswith(expected_tag)+ assert state_dir.variant_is_hashed_fragment(recovered)+ target.unlink()++ # A real quant label is never mistaken for one.+ for quant in ("Q4_K_M", "UD-Q4_K_XL", "sha256-short"):+ assert not state_dir.variant_is_hashed_fragment(quant)diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 1785f17b691..0050333f37a 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -3982,6 +3982,32 @@ def test_partial_gguf_reconstruction_dedupes_variant_casing(monkeypatch):assert [variant.quant for variant in variants] == ["Q4_K_M"]+def test_partial_gguf_reconstruction_drops_a_variant_read_off_the_filename(monkeypatch):+ # An unreadable payload leaves the reader the filename, whose digest fragment+ # names nothing and would re-key to a further hash on resume. A variant genuinely+ # called sha256-<32 hex> reads the same but is stored under the hash of itself, so+ # the file it came from tells them apart where the spelling cannot.+ digest = "sha256-" + "0" * 32+ entries = [+ # variant, the file it was recovered from+ (f"@{digest}", Path(f"repo--variant--@{digest}.json")), # scope, payload lost+ (digest, Path(f"repo--variant--{digest}.json")), # ditto, older tag+ (digest, Path("repo--variant--@sha256-" + "c" * 32 + ".json")), # real, payload intact+ ("Q4_K_M", Path("repo--variant--q4_k_m.json")),+ ]+ monkeypatch.setattr(+ download_manifest, "iter_variant_manifests", lambda *_a, **_k: iter(entries)+ )+ monkeypatch.setattr(download_manifest, "iter_variant_markers", lambda *_a, **_k: iter(()))+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)++ result = gguf.list_partial_gguf_variants_from_state("Org/Repo")++ assert result is not None+ variants, _has_vision = result+ assert sorted(variant.quant for variant in variants) == ["Q4_K_M", digest]++def test_download_registry_serializes_cross_transport_variant_downloads():# An HTTP append-resume and an XET rewrite of the same shared blob would# corrupt each other, so different-transport variants are serialized.diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 7a2e3d1ab99..5d8fe2585ed 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -389,6 +389,21 @@ def list_gguf_variants_from_hf_cache(return selected[:3] if selected is not None else None+def _is_state_filename_fallback(variant: str, path: Path) -> bool:+ """Whether *variant* was read off *path*'s own name rather than out of it.++ An unreadable payload leaves the reader the filename, whose fragment for an+ unspellable variant is a digest. Spelling cannot tell that from a variant+ genuinely called ``sha256-<32 hex>``, but the file can: a real one is stored+ under the hash of itself, never under its own name. A recovered digest names+ nothing -- it cannot be spelled back, and a resume would re-key it again.+ """+ from hub.utils.state_dir import variant_is_hashed_fragment+ return variant_is_hashed_fragment(variant) and path.stem.lower().endswith(+ f"--variant--{variant.strip().lower()}"+ )++def list_partial_gguf_variants_from_state(repo_id: str, hub_cache: Optional[Path] = None) -> Optional[tuple[list[GgufVariantInfo], bool]]:@@ -426,7 +441,9 @@ def list_partial_gguf_variants_from_state())for source in sources:- for variant, _path in source:+ for variant, path in source:+ if _is_state_filename_fallback(variant, path):+ continuekey = variant.lower()if key not in seen:seen.add(key)diff --git a/studio/backend/hub/utils/state_dir.py b/studio/backend/hub/utils/state_dir.pyindex 31f05374c47..abb8626b156 100644--- a/studio/backend/hub/utils/state_dir.py+++ b/studio/backend/hub/utils/state_dir.py@@ -57,6 +57,9 @@ _MAX_VARIANT_FRAGMENT_LENGTH = 64_CACHE_SCOPE_DIGEST_LENGTH = 32_HASH_PREFIXES = ("sha256-", "@sha256-")_LEGACY_HASH_FRAGMENT = re.compile(r"sha256-[0-9a-f]{32}")+# Either tag _variant_fragment stamps, so a reader can spot a digest handed to it+# in place of a variant name.+_HASHED_FRAGMENT = re.compile(r"@?sha256-[0-9a-f]{32}")def state_root(*, create: bool = False) -> Optional[Path]:@@ -105,6 +108,17 @@ def _state_filename_fits(entry_key: str) -> bool:return _filename_bytes(filename) + _ATOMIC_WRITE_TMP_OVERHEAD <= _MAX_STATE_BASENAME_BYTES+def variant_is_hashed_fragment(variant: str) -> bool:+ """Whether *variant* is a digest fragment rather than a variant name.++ An unreadable state file falls back to its own filename, which for a variant+ :func:`_variant_fragment` had to hash is this digest. It names nothing: it+ cannot be spelled back, and re-keying it would hash the digest again. Both+ tags count, the older one carrying no "@".+ """+ return bool(_HASHED_FRAGMENT.fullmatch(variant.strip().lower()))++def state_filename_is_ambiguous(name: str) -> bool:"""Whether an unreadable state filename has multiple possible owners."""stem, separator = name.removesuffix(_STATE_EXTENSION).lower(), "--variant--"diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 743ee8a4817..940f7c06317 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -4151,3 +4151,159 @@ def test_a_case_variant_repo_dir_still_names_its_snapshot(monkeypatch, tmp_path))assert [v.quant for v in response.variants] == ["Q8_0"]assert context_calls == [(str(repo_dir / "snapshots" / "rev"), True)]+++def test_a_download_scope_is_not_listed_as_a_quant(monkeypatch, tmp_path):+ """A scoped job ("@diffusion") rides the variant slot, so its manifest names the+ same .gguf the real quant does: rebuilding from download state listed one file+ twice, the second permanently partial, costing the picker its single-quant+ collapse. A real cancelled quant must still survive, or it loses its resume."""+ repo_dir = tmp_path / "models--org--repo"+ (repo_dir / "snapshots" / "rev").mkdir(parents = True)++ monkeypatch.setattr(+ GV,+ "select_gguf_cache_snapshot",+ lambda repo_id, root = None: (+ [+ SimpleNamespace(+ filename = "m-Q4_K_S.gguf",+ quant = "Q4_K_S",+ display_label = None,+ size_bytes = 10,+ )+ ],+ False,+ {"q4_k_s"},+ repo_dir / "snapshots" / "rev",+ ),+ )+ # State holds both: the scope the diffusion load ran under, and a cancelled quant.+ monkeypatch.setattr(+ GV,+ "list_partial_gguf_variants_from_state",+ lambda *a, **k: (+ [+ SimpleNamespace(+ filename = "m-Q4_K_S.gguf",+ quant = "@diffusion",+ display_label = None,+ size_bytes = 10,+ download_size_bytes = 10,+ ),+ SimpleNamespace(+ filename = "m-Q6_K.gguf",+ quant = "Q6_K",+ display_label = None,+ size_bytes = 20,+ download_size_bytes = 20,+ ),+ ],+ False,+ ),+ )+ monkeypatch.setattr(+ models_route, "_read_native_context_length", lambda model, *, is_local: None+ )++ response = asyncio.run(+ models_route.get_gguf_variants(+ repo_id = "org/repo",+ offline = True,+ local_path = str(repo_dir),+ hf_token = None,+ current_subject = "test-user",+ )+ )+ quants = [v.quant for v in response.variants]+ assert "@diffusion" not in quants+ assert quants == ["Q4_K_S", "Q6_K"]+ # The scope named the quant's own file, so keeping it would list that file twice.+ filenames = [v.filename for v in response.variants]+ assert len(filenames) == len(set(filenames))+++def test_a_scope_alone_in_state_is_not_an_answer(monkeypatch, tmp_path):+ """A scope reaching the state-only fallbacks is worse than a duplicate row: naming+ no .gguf, it reconstructs as "@diffusion.gguf", a file never on disk. So scopes+ alone must make the fallback decline and let the next answer through."""+ repo_dir = tmp_path / "models--org--repo"+ (repo_dir / "snapshots" / "rev").mkdir(parents = True)++ monkeypatch.setattr(GV, "select_gguf_cache_snapshot", lambda repo_id, root = None: None)+ monkeypatch.setattr(+ GV,+ "list_partial_gguf_variants_from_state",+ lambda *a, **k: (+ [+ SimpleNamespace(+ filename = "@diffusion.gguf",+ quant = "@diffusion",+ display_label = None,+ size_bytes = 0,+ download_size_bytes = 0,+ )+ ],+ False,+ ),+ )+ monkeypatch.setattr(+ models_route, "_read_native_context_length", lambda model, *, is_local: None+ )++ response = asyncio.run(+ models_route.get_gguf_variants(+ repo_id = "org/repo",+ offline = True,+ local_path = str(repo_dir),+ hf_token = None,+ current_subject = "test-user",+ )+ )+ assert response.variants == []+++def test_a_cancelled_quant_beside_a_scope_still_answers_from_state(monkeypatch, tmp_path):+ """Dropping scopes must not cost the fallback its reason to exist: a cancelled quant+ with no snapshot keeps its row, and its resume."""+ repo_dir = tmp_path / "models--org--repo"+ (repo_dir / "snapshots" / "rev").mkdir(parents = True)++ monkeypatch.setattr(GV, "select_gguf_cache_snapshot", lambda repo_id, root = None: None)+ monkeypatch.setattr(+ GV,+ "list_partial_gguf_variants_from_state",+ lambda *a, **k: (+ [+ SimpleNamespace(+ filename = "m-Q6_K.gguf",+ quant = "Q6_K",+ display_label = None,+ size_bytes = 20,+ download_size_bytes = 20,+ ),+ SimpleNamespace(+ filename = "@diffusion.gguf",+ quant = "@diffusion",+ display_label = None,+ size_bytes = 0,+ download_size_bytes = 0,+ ),+ ],+ False,+ ),+ )+ monkeypatch.setattr(+ models_route, "_read_native_context_length", lambda model, *, is_local: None+ )++ response = asyncio.run(+ models_route.get_gguf_variants(+ repo_id = "org/repo",+ offline = True,+ local_path = str(repo_dir),+ hf_token = None,+ current_subject = "test-user",+ )+ )+ assert [(v.quant, v.partial) for v in response.variants] == [("Q6_K", True)]