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: stop a multi-checkpoint GGUF repo collapsing into one row per quant (#8222)
Daniel Han995921268ad6
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 66ec4540090..3f92187a55c 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -1723,6 +1723,18 @@ def _gguf_extra_shards(files: Iterable[str], first_shard: str) -> list[str]:return sorted(f for f in files if f != first_shard and sibling_pat.match(f))+def _quant_label_for_endian(path: str) -> Optional[str]:+ """The file's own quant label, for ``_is_big_endian_gguf_path``, or None when unreadable.++ Best-effort: with no label the caller keeps its previous argument rather than dropping the+ endian test, which would admit a genuinely big-endian build."""+ try:+ from hub.utils.gguf import extract_quant_token+ return extract_quant_token(path)+ except Exception: # noqa: BLE001 -- an unreadable label must not sink the resolution+ return None++def _gguf_files_for_variant(files: Iterable[str], variant: str) -> list[str]:"""Return main GGUF files matching a requested variant.@@ -1735,15 +1747,33 @@ def _gguf_files_for_variant(files: Iterable[str], variant: str) -> list[str]:for f in filesif f.lower().endswith(".gguf")and not _is_companion_gguf_path(f)- and not _is_big_endian_gguf_path(f, variant_key)+ # The endian predicate reads a quant TOKEN -- it decides whether the quant came from the+ # parent directory only -- so it gets the file's own label, never the requested key. Handed+ # a path-qualified key it cannot find that string in either the basename or the parent and+ # reads distilled/Q4_K_M/foo-be.gguf as big-endian, dropping the one file the key owns:+ # the row is advertised and downloadable but never resolves for loading. Same reason+ # gguf_plan and the auto-download map pass the label here.+ and not _is_big_endian_gguf_path(f, _quant_label_for_endian(f) or variant_key)]if not variant_key:return sorted(main_files)try:- from utils.models.model_config import _extract_quant_label+ from utils.models.model_config import _extract_quant_label, _gguf_variant_keyexcept Exception:_extract_quant_label = None+ _gguf_variant_key = None++ if _gguf_variant_key is not None:+ try:+ # The variant's own files first. In a repo holding several checkpoints at+ # one quant the label alone names all of them, and handing llama-server a+ # mixed set makes it read another checkpoint's weights as a shard.+ owned = sorted(f for f in main_files if _gguf_variant_key(f).lower() == variant_key)+ if owned:+ return owned+ except Exception as e:+ logger.warning("Failed to derive GGUF variant keys: %s", e)if _extract_quant_label is not None:try:diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex ef11f8b77ae..4b680098d07 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -127,7 +127,14 @@ def _local_gguf_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:# load would take: answering with the largest can evict a model and then OOM.from core.inference.openai_auto_download import preferred_quant- best = preferred_quant(quants)+ # Rank the ROOT checkpoints alone when there are any. A plain local load resolves+ # through non-recursive detect_gguf_model and so always takes the repo root, while+ # preferred_quant ranks on the key text and would hand a bare id an equally-good+ # ``distilled/...`` row that sorts earlier -- the same id serving different weights+ # depending on which resolver answered it. The qualified rows stay advertised; they+ # simply are not what a bare id means.+ unqualified = tuple(q for q in quants if "/" not in q)+ best = preferred_quant(unqualified or quants)if best and quants[0] != best:quants = (best, *(q for q in quants if q != best))return _LocalGgufEntry(loader_id, str(load_dir), quants)diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.pyindex fa1a3b26c95..711996c028b 100644--- a/studio/backend/core/inference/openai_auto_download.py+++ b/studio/backend/core/inference/openai_auto_download.py@@ -148,6 +148,13 @@ def looks_like_quant(variant: Optional[str]) -> bool:return False# _extract_quant_label can append a bpw modifier (IQ4_XS-3.53bpw); still a quant.label = re.sub(r"-[0-9]+(?:\.[0-9]+)?bpw$", "", variant.strip(), flags = re.IGNORECASE)+ # A path-qualified variant key (``distilled/model-Q6_K``) is one of OUR advertised rows: a+ # repo with several checkpoints at one quant keys each on its path. No foreign tag has that+ # shape -- Ollama's is ``:latest``, LiteLLM's namespace sits before the colon -- so it must+ # be read as an explicit checkpoint request and MISS when absent. Falling through instead+ # served the caller a different checkpoint under the model id they asked for.+ if "/" in label.replace("\\", "/"):+ return Truereturn _GGUF_KNOWN_QUANT_RE.fullmatch(label) is not None@@ -235,6 +242,7 @@ def _gguf_variants(siblings) -> dict[str, int]:quant, so the disk reserve is measured against what the worker fetches."""from hub.utils.gguf import extract_quant_label as canonical_quant_label+ from hub.utils.gguf import gguf_variant_keyfrom hub.utils.gguf_plan import build_gguf_variant_plansfrom utils.models.model_config import (_extract_quant_label,@@ -250,13 +258,18 @@ def _gguf_variants(siblings) -> dict[str, int]:name = getattr(sibling, "rfilename", "") or ""if not name.lower().endswith(".gguf"):continue- quant = _extract_quant_label(name)+ label = _extract_quant_label(name)+ # The identity the PLAN is keyed on. A repo holding several checkpoints at one quant+ # advertises a qualified key per checkpoint, and keying this map on the bare label left+ # every one of those rows a hard miss here: a 404 instead of the download.+ quant = gguf_variant_key(name)if not looks_like_quant(quant):# With no recognized quant token the extractors part ways: this one takes# the last hyphenated segment ("7b" of llama-7b) while the plan and worker# key the whole stem, so advertising ours dispatches an unresolvable variant.quant = canonical_quant_label(name) or quant- if _is_mmproj(name) or _is_mtp_drafter(name) or _is_big_endian_gguf_path(name, quant):+ # The endian test reads a quant TOKEN, so it gets the label, not the path-qualified key.+ if _is_mmproj(name) or _is_mtp_drafter(name) or _is_big_endian_gguf_path(name, label):continueplan = plans.get(quant.lower())if plan is not None:@@ -676,10 +689,10 @@ async def _admit_and_start()expected_bytes = variants[variant]- from hub.utils.gguf_plan import build_gguf_variant_plans+ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant- plan = build_gguf_variant_plans(list(getattr(info, "siblings", None) or [])).get(- variant.lower()+ plan = plan_for_variant(+ build_gguf_variant_plans(list(getattr(info, "siblings", None) or [])), variant)if require_vision and not (plan and plan.mmproj_filenames):_release(active)@@ -735,6 +748,26 @@ def preferred_quant(labels) -> Optional[str]:return synthetic.get(best) if best else None+def _bare_quant_alias(wanted: str, lowered: dict[str, str]) -> Optional[str]:+ """The one qualified variant whose quant token is *wanted*, or None when it names 0 or 2+.++ A key is a pure function of the path, so a repo that files every quant under one shared+ container qualifies all of them even though the directory disambiguates nothing, and the bare+ spelling every stored id uses then matches no key at all.+ """+ from hub.utils.gguf import bare_quant_alias++ target = (wanted or "").strip().lower()+ if not target:+ return None+ matches = [+ name+ for key, name in lowered.items()+ if "/" in key and bare_quant_alias(key).lower() == target+ ]+ return matches[0] if len(matches) == 1 else None++def _match_variant(wanted: Optional[str], variants: dict[str, int]) -> Optional[str]:"""Resolve the requested quant against what the repo actually has.@@ -749,10 +782,23 @@ def _match_variant(wanted: Optional[str], variants: dict[str, int]) -> Optional[# and defaulting past one would fetch a model nobody asked for.lowered = {name.lower(): name for name in variants}exact = lowered.get(wanted.strip().lower())+ if exact is None:+ # Same bare-quant fallback the plan lookup makes, and it has to be made HERE too:+ # admission rejects against this map first, so a repo that files every quant under+ # one shared container answered a legacy org/repo:Q4_K_M with a 404 and the worker's+ # fallback was never reached. Unambiguous only, for the same reason.+ exact = _bare_quant_alias(wanted, lowered)if exact is not None or looks_like_quant(wanted):# A quant-shaped suffix that matches nothing is a miss, never a swap.return exact- return preferred_quant(variants)+ # A BARE org/repo means the ROOT checkpoint, so a qualified sibling must not be ranked+ # against it: preferred_quant is order-sensitive, and once the map carried a key per+ # checkpoint a repo with distilled/model-Q6_K beside model-Q6_K could serve the sibling for+ # a bare id -- the same id that resolves to the root locally. Same filter+ # local_model_resolver._local_gguf_entry applies, so both resolvers answer one id one way.+ # A repo with nothing at the root falls back to the whole set rather than refusing.+ unqualified = {name: size for name, size in variants.items() if "/" not in name}+ return preferred_quant(unqualified or variants)async def _dispatch(diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.pyindex c3b8a5b79e1..b4b32e8b292 100644--- a/studio/backend/hub/services/models/common.py+++ b/studio/backend/hub/services/models/common.py@@ -18,7 +18,7 @@ from hub.schemas.inventory import (ModelRuntime,)from hub.utils.gguf import (- extract_quant_label,+ gguf_variant_key,is_gguf_filename as _is_gguf_filename,is_mmproj_filename as _is_mmproj_filename,is_mtp_drafter_path as _is_mtp_drafter_path,@@ -769,7 +769,7 @@ def _classify_local_path(if gguf_files:gguf_size_bytes = _sum_file_sizes(gguf_files)variant = (- extract_quant_label(gguf_files[0].name)+ gguf_variant_key(gguf_files[0].name)if scan_path.is_file() and len(gguf_files) == 1else None)diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex db31d25cd32..82c0e0b4233 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -17,8 +17,9 @@ from hub.utils import download_manifestfrom hub.utils import download_registryfrom hub.utils import inventory_scan as hf_cache_scanfrom hub.utils.gguf import (- extract_quant_label,+ bare_quant_alias,extract_quant_token,+ gguf_variant_key,is_reclaimable_drafter_path as _is_reclaimable_drafter_path,)from hub.utils.hf_cache_state import (@@ -131,7 +132,11 @@ def _remove_empty_variant_dirs(target_repos: list, variant: str) -> tuple[int, l"""Remove now-empty ``snapshots/<rev>/<quant>/`` folders for *variant* (thequant label names the folder); only empty dirs go, so siblings are safe.Returns (count removed, removal failures other than a concurrent refill)."""- variant_key = (extract_quant_token(variant) or variant).lower()+ # A path-qualified variant key names its own folder; its quant token belongs to+ # sibling checkpoints too, so it must not reach for a <quant>/ dir it does not own.+ variant_key = (+ variant.lower() if "/" in variant else (extract_quant_token(variant) or variant).lower()+ )removed = 0failures: list[str] = []for target_repo in target_repos:@@ -197,6 +202,33 @@ def _remove_empty_snapshot_dirs(target_repos: list) -> tuple[int, list[str]]:return removed, failures+def _variant_keys_to_delete(target_repo, variant: str) -> set[str]:+ """The variant keys in *target_repo* that *variant* names, lowercased.++ Its own key, always. Plus the unambiguous bare-quant alias the download side already admits+ (``gguf_plan.plan_for_variant``): a repo filing its sole Q4_K_M under a shared container+ (``weights/model-Q4_K_M.gguf``) qualifies that key, because the key is a pure function of the+ path and cannot know the directory disambiguates nothing, so every stored pin and every+ explicit ``repo:Q4_K_M`` names it by quant alone. Admitting the alias for the download and not+ for the delete answered "not found" and left the weights on disk.++ Only when it is unambiguous, exactly as the download side decides it: a repo that really does+ hold several checkpoints at one quant gets no fallback, because there the bare name genuinely+ does not name one of them and deleting the wrong one is unrecoverable.+ """+ wanted = (variant or "").strip().lower()+ if not wanted or "/" in wanted:+ return {wanted}+ keys = {+ gguf_variant_key(name).lower()+ for _snap, _blob, name in _repo_file_matches(target_repo, _is_main_gguf_filename)+ }+ if wanted in keys:+ return {wanted}+ aliased = {key for key in keys if "/" in key and bare_quant_alias(key).lower() == wanted}+ return aliased if len(aliased) == 1 else {wanted}++def _delete_gguf_variant_from_repos(repo_id: str,variant: str,@@ -214,10 +246,11 @@ def _delete_gguf_variant_from_repos(for target_repo in target_repos:repo_dir = Path(target_repo.repo_path) if getattr(target_repo, "repo_path", None) else None+ wanted_keys = _variant_keys_to_delete(target_repo, variant)matched = _repo_file_matches(target_repo,- lambda name: _is_main_gguf_filename(name)- and extract_quant_label(name).lower() == variant.lower(),+ lambda name, keys = wanted_keys: _is_main_gguf_filename(name)+ and gguf_variant_key(name).lower() in keys,)for snap, _blob, name in matched:@@ -440,7 +473,7 @@ def reclaim_replaced_gguf_variant(matches = _repo_file_matches(target_repo,lambda name: _is_main_gguf_filename(name)- and extract_quant_label(name).lower() == variant_key,+ and gguf_variant_key(name).lower() == variant_key,)for snap, blob, name in matches:# Prune only a file we can identify as a real, stale cache blob. Adiff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex a30b34f48cb..d82929e36bd 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -30,6 +30,7 @@ from hub.utils.hf_cache_state import (from hub.utils.gguf import (GgufVariantInfo,extract_quant_label,+ gguf_variant_key,iter_hf_cache_snapshots,is_big_endian_gguf_path,list_empty_gguf_variant_dirs,@@ -392,8 +393,11 @@ def _local_main_gguf_blobs_by_quant(str(blob) for blob in hashes if blob)continue- quant = extract_quant_label(normalized).lower()- if is_big_endian_gguf_path(normalized, quant):+ quant = gguf_variant_key(normalized).lower()+ # The endian predicate reads a quant TOKEN so it can tell a parent-only quant+ # from a big-endian build; the qualified key makes it misread the path and drop+ # the blob, which leaves update detection with no local main files to compare.+ if is_big_endian_gguf_path(normalized, extract_quant_label(normalized)):continuebucket = result.setdefault(quant, {}).setdefault(normalized, set())bucket.update(str(blob) for blob in hashes if blob)@@ -870,6 +874,20 @@ class VariantsAnswer(NamedTuple):context_source: Optional[str]+def _default_variant_candidates(variants) -> list[str]:+ """The filenames the automatic default may be picked from: ROOT rows when there are any.++ ``pick_best_gguf`` keeps whichever filename it met first among equals, so a repo with+ ``model-Q6_K.gguf`` beside ``distilled/model-Q6_K.gguf`` could make the qualified sibling the+ default -- and then a bare repo id would mean one checkpoint here and another to+ ``_match_variant(None, ...)`` and ``local_model_resolver``, which both define it as the root.+ Every branch of this service (remote, cached, partial-local) has to apply it, or the answer+ depends on which one served the request. Nothing at the root falls back to the whole set.+ """+ root_rows = [v.filename for v in variants if "/" not in v.quant]+ return root_rows or [v.filename for v in variants]++async def get_gguf_variants_answer(repo_id: str,prefer_local_cache: bool = False,@@ -917,8 +935,8 @@ async def get_gguf_variants_answer(# The default comes from the ready rows; with none ready every row is the fallback.ready = [v for v in variants if _downloaded(v)]- best = pick_best_gguf([v.filename for v in (ready or variants)])- default_variant = extract_quant_label(best) if best else None+ best = pick_best_gguf(_default_variant_candidates(ready or variants))+ default_variant = gguf_variant_key(best) if best else Nonereturn GgufVariantsResponse(repo_id = response_repo_id,@@ -941,9 +959,8 @@ async def get_gguf_variants_answer(def _partial_local_response(response_repo_id: str, variants, has_vision: bool) -> GgufVariantsResponse:- filenames = [v.filename for v in variants]- best = pick_best_gguf(filenames)- default_variant = extract_quant_label(best) if best else None+ best = pick_best_gguf(_default_variant_candidates(variants))+ default_variant = gguf_variant_key(best) if best else Nonereturn GgufVariantsResponse(repo_id = response_repo_id,variants = [@@ -1156,9 +1173,8 @@ async def get_gguf_variants_answer(if fallback is not None:return fallback- filenames = [v.filename for v in variants]- best = pick_best_gguf(filenames)- default_variant = extract_quant_label(best) if best else None+ best = pick_best_gguf(_default_variant_candidates(variants))+ default_variant = gguf_variant_key(best) if best else None# Per-snapshot accounting: a variant counts as present only when one# snapshot holds all its files (split GGUFs need every shard together),@@ -1192,8 +1208,8 @@ async def get_gguf_variants_answer(by_filename[key] = max(by_filename.get(key, 0), size)if _is_mmproj_filename(f.name) or _is_mtp_drafter_path(rel):continue- q = extract_quant_label(rel)- if is_big_endian_gguf_path(rel, q):+ q = gguf_variant_key(rel)+ if is_big_endian_gguf_path(rel, extract_quant_label(rel)):continueq = q.lower()by_quant[q] = by_quant.get(q, 0) + sizediff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex f8daed55a7e..56b568ca735 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -279,6 +279,35 @@ def extract_quant_token(filename: str) -> Optional[str]:return None+# A bits-per-weight modifier trailing the quant token. Two builds of one base quant at different+# bpw are two checkpoints (byteshape ships IQ4_XS at 3.53, 3.97 and 4.19), and the loader's own+# label keeps the modifier for exactly that reason. The variant KEY has to keep it too: without it+# the lister advertises IQ4_XS-3.53bpw while the plan, the download map and the delete predicate+# all say IQ4_XS, so the advertised name 404s and the collapsed one unlinks every build.+_GGUF_BPW_SUFFIX_RE = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw$", re.IGNORECASE)+++def _gguf_bpw_suffix(filename: str) -> str:+ """``-3.53bpw`` from whichever path segment names the quant, else ``""``.++ Not the basename alone: the quant-directory layout carries it upstairs+ (``IQ4_XS-3.53bpw/model.gguf``), which is exactly where ``extract_quant_token`` looks next, so+ reading only ``model`` gave both bpw builds the bare ``IQ4_XS`` key. The walk stops at the+ segment that named the quant -- a modifier further up the tree belongs to something else.+ """+ path = filename.replace("\\", "/")+ parents = path.rpartition("/")[0]+ for segment in (_gguf_stem(path), *reversed(parents.split("/"))):+ if not segment:+ continue+ match = _GGUF_BPW_SUFFIX_RE.search(segment)+ if match:+ return match.group(0)+ if _select_quant_match(segment) is not None:+ return ""+ return ""++def _unknown_gguf_variant_key(filename: str) -> str:stem = _gguf_stem(filename)if "/" not in filename:@@ -287,19 +316,144 @@ def _unknown_gguf_variant_key(filename: str) -> str:return f"{parents}/{stem}" if parents and stem else stem or "gguf"+def gguf_variant_family(filename: str) -> str:+ """The shard family *filename* belongs to: its directory plus its shard-stripped name.++ The unit a row and a download plan describe. Every shard of one split GGUF shares+ a family, which is why summing sizes within a family is right; two files that do+ NOT share one are two different checkpoints, so summing across them is not.+ """+ return _unknown_gguf_variant_key(filename)++def extract_quant_label(filename: str) -> str:return extract_quant_token(filename) or _unknown_gguf_variant_key(filename)+def bare_quant_alias(key: str) -> str:+ """The bare quant spelling a path-qualified *key* also answers to.++ ``weights/model-IQ4_XS-3.53bpw`` -> ``IQ4_XS-3.53bpw``. The bpw modifier is part of the+ identity now, so the three compatibility fallbacks that accept a bare name for a qualified+ key (the plan lookup, auto-download admission, deletion) have to keep it -- comparing on the+ token alone means a persisted ``IQ4_XS-3.53bpw`` resolves nothing.+ """+ # A key is already shard- and extension-stripped, so re-stemming it would cut at the dot in+ # "3.53bpw" (and at the one in "ltx-2.3"). Hand the extractors a name they expect instead.+ probe = f'{(key or "").replace(chr(92), "/").rsplit("/", 1)[-1]}.gguf'+ return f"{extract_quant_label(probe)}{_gguf_bpw_suffix(probe)}"+++def _is_quant_directory(segment: str) -> bool:+ """Whether a path segment names a quant (``Q6_K/``, ``Llama-3.3-70B-Instruct-Q6_K/``).++ Such a directory says only how the file was quantized, which its name already says,+ so it adds nothing to the file's identity. A directory naming something else+ (``distilled/``) is a different checkpoint and does. The basename still wins on+ which quant it is: ``Q8_0/model-Q4_K_M.gguf`` IS the Q4_K_M file.+ """+ return _select_quant_match(segment) is not None+++def gguf_variant_key(filename: str) -> str:+ """The persisted identity of a selectable GGUF variant.++ The bare quant token when that token names the file within its path -- the shape+ almost every repo uses, so this is byte-identical to the historical key there and+ every stored pin, manifest and marker keeps resolving. When the token does NOT+ single the file out, because a sibling directory holds another checkpoint at the+ same quant (``distilled/`` and ``distilled-1.1/`` beside the repo root), the key+ is the file's :func:`gguf_variant_family` instead, which is unique within the+ repo and which the loader already accepts as a spelling+ (``model_config._find_local_gguf_by_variant`` matches its shard-stripped relative+ path, as does ``llama_cpp._gguf_files_for_variant``).++ A pure function of the path, deliberately: the remote listing sees a whole repo+ while a cache scan sees whatever was downloaded, and a key that depended on the+ set would disagree between them and strand a finished download as incomplete.+ """+ path = filename.replace("\\", "/")+ quant = extract_quant_token(path)+ if quant is None:+ return _unknown_gguf_variant_key(path)+ parents = path.rpartition("/")[0]+ if any(segment and not _is_quant_directory(segment) for segment in parents.split("/")):+ return _unknown_gguf_variant_key(path)+ return f"{quant}{_gguf_bpw_suffix(path)}"+++def _variant_scope_label(filename: str, *, with_stem: bool = False) -> str:+ """The part of a qualified variant's path that tells it apart from its namesakes.++ The directory alone reads best and is enough for the usual shape, where each checkpoint+ has its own. ``with_stem`` adds the filename back for the case where it is not: two+ checkpoints in ONE directory at one quant are two rows, and a label naming only the+ directory would print the same text on both.+ """+ parents = filename.replace("\\", "/").rpartition("/")[0].strip("/")+ stem = _gguf_stem(filename)+ if not parents:+ return stem+ return f"{parents}/{stem}" if with_stem else parents++def _apply_gguf_display_labels(variants: list[GgufVariantInfo]) -> None:unknown_variants = [variant for variant in variants if extract_quant_token(variant.filename) is None]- if not unknown_variants:- returnambiguous = len(unknown_variants) > 1- for variant in unknown_variants:- variant.display_label = f"GGUF · {variant.filename}" if ambiguous else "GGUF"++ # The bpw modifier is part of the key but reads perfectly well on its own+ # ("IQ4_XS-3.53bpw"), so a key that is only the token plus its bpw suffix is NOT a+ # path-qualified one and needs no scope label.+ def _plain_key(variant) -> Optional[str]:+ token = extract_quant_token(variant.filename)+ return None if token is None else f"{token}{_gguf_bpw_suffix(variant.filename)}"++ qualified = [+ variant+ for variant in variants+ if (plain := _plain_key(variant)) is not None and variant.quant.lower() != plain.lower()+ ]+ # A scope shared by two rows does not tell them apart, so those rows show the file too.+ scopes: dict[str, int] = {}+ for variant in qualified:+ scope = _variant_scope_label(variant.filename).lower()+ scopes[scope] = scopes.get(scope, 0) + 1+ for variant in variants:+ token = extract_quant_token(variant.filename)+ if token is None:+ variant.display_label = f"GGUF · {variant.filename}" if ambiguous else "GGUF"+ elif variant.quant.lower() != (_plain_key(variant) or "").lower():+ # A key qualified by path: show the quant, plus what distinguishes it.+ collides = scopes.get(_variant_scope_label(variant.filename).lower(), 0) > 1+ variant.display_label = (+ f"{token} · {_variant_scope_label(variant.filename, with_stem = collides)}"+ )+++def group_gguf_variant_files(entries) -> dict[str, tuple[str, int]]:+ """``variant key -> (first filename, size of that variant's shard family)``.++ *entries* is an iterable of ``(path, size)`` for main GGUFs only, already filtered+ of mmproj, drafters and big-endian builds.++ Sizes are summed across the shards of ONE family, never across families. A repo+ that ships the same quant twice (``BF16/QwQ-32B-BF16-*`` beside+ ``BF16/QwQ-32B.BF16-*``) therefore advertises what a load would actually read+ rather than the total of both copies. The family kept is the one holding the+ lexicographically first file, which is the shard the lister and the loader open.+ """+ families: dict[str, dict[str, list[tuple[str, int]]]] = {}+ for path, size in entries:+ families.setdefault(gguf_variant_key(path), {}).setdefault(+ gguf_variant_family(path), []+ ).append((path, int(size or 0)))+ grouped: dict[str, tuple[str, int]] = {}+ for key, by_family in families.items():+ chosen = min(by_family.values(), key = lambda members: min(path for path, _ in members))+ grouped[key] = (min(path for path, _ in chosen), sum(size for _, size in chosen))+ return groupeddef _env_offline() -> bool:@@ -606,10 +760,8 @@ def list_gguf_variants(return _ready_cached_variants(cached)raise- variants: list[GgufVariantInfo] = []has_vision = False- quant_totals: dict[str, int] = {}- quant_first_file: dict[str, str] = {}+ main_files: list[tuple[str, int]] = []for sibling in info.siblings:filename = getattr(sibling, "rfilename", None)@@ -622,24 +774,18 @@ def list_gguf_variants(if is_mmproj_filename(filename):has_vision = Truecontinue- quant = extract_quant_label(filename)# The two extractors disagree on F16-be-checkpoint-Q4_K_M shapes; judge with the# loader's label so no row is advertised for a file the remote detector refuses.from utils.models.model_config import _extract_quant_label as _loader_quantif is_big_endian_gguf_path(filename, _loader_quant(filename)):continue- quant_totals[quant] = quant_totals.get(quant, 0) + int(getattr(sibling, "size", 0) or 0)- quant_first_file.setdefault(quant, filename)+ main_files.append((filename, int(getattr(sibling, "size", 0) or 0)))- for quant, total_size in quant_totals.items():- variants.append(- GgufVariantInfo(- filename = quant_first_file[quant],- quant = quant,- size_bytes = total_size,- )- )+ variants = [+ GgufVariantInfo(filename = filename, quant = quant, size_bytes = size)+ for quant, (filename, size) in group_gguf_variant_files(main_files).items()+ ]variants.sort(key = lambda variant: -variant.size_bytes)_apply_gguf_display_labels(variants)@@ -677,8 +823,7 @@ def list_local_gguf_variants(else _registered_custom_model_root(directory))- quant_totals: dict[str, int] = {}- quant_first_file: dict[str, str] = {}+ main_files: list[tuple[str, int]] = []has_vision = False# Match the cache dir of ANY H3 bundle repo, not just one of them: the same aggregation runs# over whichever mirror the user actually downloaded.@@ -704,23 +849,17 @@ def list_local_gguf_variants(rel = file.relative_to(root).as_posix()if _is_local_mtp_drafter(file, custom_root, rel):continue- quant = extract_quant_label(rel)# The two extractors disagree on F16-be-checkpoint-Q4_K_M shapes; judge with the# loader's label so no row is listed for a file the local detector refuses.from utils.models.model_config import _extract_quant_label as _loader_quantif is_big_endian_gguf_path(rel, _loader_quant(rel)):continue- quant_totals[quant] = quant_totals.get(quant, 0) + size- quant_first_file.setdefault(quant, rel)+ main_files.append((rel, size))variants = [- GgufVariantInfo(- filename = quant_first_file[quant],- quant = quant,- size_bytes = size,- )- for quant, size in quant_totals.items()+ GgufVariantInfo(filename = filename, quant = quant, size_bytes = size)+ for quant, (filename, size) in group_gguf_variant_files(main_files).items()]variants.sort(key = lambda variant: -variant.size_bytes)_apply_gguf_display_labels(variants)diff --git a/studio/backend/hub/utils/gguf_plan.py b/studio/backend/hub/utils/gguf_plan.pyindex 18daa4f84e7..b05ed430d13 100644--- a/studio/backend/hub/utils/gguf_plan.py+++ b/studio/backend/hub/utils/gguf_plan.py@@ -8,7 +8,10 @@ from typing import Optional, Sequencefrom hub.utils.download_manifest import ExpectedFilefrom hub.utils.gguf import (+ bare_quant_alias,extract_quant_label,+ gguf_variant_family,+ gguf_variant_key,is_big_endian_gguf_path,is_gguf_filename,is_mmproj_filename,@@ -68,12 +71,21 @@ def is_companion_gguf_path(path: str) -> bool:def is_main_gguf_variant_path(path: str, variant: str) -> bool:+ """Whether *path* is one of *variant*'s own weight files.++ Keyed on :func:`gguf_variant_key`, in lockstep with the listers: a row built under+ one identity and matched under another produces a variant that can be shown but+ not downloaded.+ """return (is_gguf_filename(path)and not is_mmproj_filename(path)and not is_mtp_drafter_path(path)- and not is_big_endian_gguf_path(path, variant)- and extract_quant_label(path).lower() == variant.lower()+ # The endian predicate reads a quant TOKEN, so it gets the label: handed the qualified key+ # it cannot see a parent-only quant and drops the file, leaving the plan with no main+ # files at all and an interrupted download with no hashes to resume against.+ and not is_big_endian_gguf_path(path, extract_quant_label(path))+ and gguf_variant_key(path).lower() == variant.lower())@@ -145,8 +157,11 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:# (the root mtp-*.gguf carries a quant label, e.g. Q8_0).if is_mmproj_filename(name) or is_mtp_drafter_path(name):continue- quant = extract_quant_label(name).lower()- if is_big_endian_gguf_path(name, quant):+ quant = gguf_variant_key(name).lower()+ # The endian predicate reads a quant TOKEN -- it decides whether the quant came from the+ # parent directory only -- so a qualified key would make it misread the path and drop the+ # file from every plan.+ if is_big_endian_gguf_path(name, extract_quant_label(name)):continuemain.setdefault(quant, []).append(sibling)@@ -167,6 +182,52 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:return plans+def plan_for_variant(plans: dict[str, GgufVariantPlan], variant: str) -> Optional[GgufVariantPlan]:+ """The plan for *variant*, accepting a bare quant when exactly one plan carries it.++ A repo that files every variant under one shared container (``weights/model-Q4_K_M.gguf``)+ qualifies every key, because the key is a pure function of the path and cannot know that the+ directory disambiguates nothing. Every stored pin and every explicit ``repo:Q4_K_M`` then+ missed the plan map and the worker exited with "No GGUF shards matching variant".++ Resolved at LOOKUP rather than by aliasing the map, so the key stays a pure function of the+ path -- the remote listing and a partial cache scan have to agree on it -- and the advertised+ rows stay one per checkpoint. Only when the bare name is UNAMBIGUOUS: a repo that really does+ hold several checkpoints at one quant gets no fallback, because there the bare name genuinely+ does not name one of them.+ """+ wanted = (variant or "").strip().lower()+ if not wanted:+ return None+ exact = plans.get(wanted)+ if exact is not None:+ return exact+ matches = [key for key in plans if "/" in key and bare_quant_alias(key).lower() == wanted]+ return plans[matches[0]] if len(matches) == 1 else None+++def _one_shard_family(main_files: Sequence[ExpectedFile]) -> tuple[ExpectedFile, ...]:+ """Narrow a variant's weight files to the single shard family a load would read.++ A repo can ship one quant twice under names that share a variant key -- the same+ BF16 as ``QwQ-32B-BF16-*`` and ``QwQ-32B.BF16-*``, or one Q6_K under both ``Q6_K/``+ and ``<model>-Q6_K/``. Fetching both doubles the download and leaves the variant+ permanently short of its expected bytes, because the loader only ever opens one.+ Keep the family holding the lexicographically first file, the shard the lister+ advertises and the loader opens. A genuinely split GGUF is one family, so all of+ its shards survive this untouched.+ """+ if len(main_files) < 2:+ return tuple(main_files)+ families: dict[str, list[ExpectedFile]] = {}+ for file in main_files:+ families.setdefault(gguf_variant_family(file.path), []).append(file)+ if len(families) < 2:+ return tuple(main_files)+ chosen = min(families.values(), key = lambda group: min(file.path for file in group))+ return tuple(chosen)++def plan_from_expected_files(variant: str,expected_files: Sequence[ExpectedFile],@@ -175,7 +236,14 @@ def plan_from_expected_files(all_mmproj_hashes: frozenset[str] | None = None,) -> GgufVariantPlan:expected = tuple(expected_files)- main_files = tuple(file for file in expected if is_main_gguf_variant_path(file.path, variant))+ all_main = tuple(file for file in expected if is_main_gguf_variant_path(file.path, variant))+ main_files = _one_shard_family(all_main)+ # A discarded family has to leave the plan ENTIRELY, not just its main files. It is+ # target_filenames, required_hashes and download_size_bytes that the worker fetches and the+ # manifest checks against; leaving the copy there downloaded it, then reclaim deleted it as+ # not-ours (it is absent from main_hashes) and the job reported partial and fetched it again.+ kept = {file.path for file in main_files}+ expected = tuple(file for file in expected if file not in all_main or file.path in kept)companion_files = tuple(file for file in expected if is_companion_gguf_path(file.path))# Manifest-resume fallback for the mmproj fields below: companion_files# also holds the MTP drafter, so keep an mmproj-only view.diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex 1122eb0cfaf..f811124366d 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -29,7 +29,7 @@ from loggers import get_loggerlogger = get_logger(__name__)from hub.utils.gguf import (- extract_quant_label,+ gguf_variant_key,is_big_endian_gguf_path,is_gguf_filename,is_mmproj_filename,@@ -776,7 +776,7 @@ def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:rel = path.relative_to(snapshot_dir).as_posix()if not is_gguf_filename(rel) or is_mmproj_filename(rel) or is_mtp_drafter_path(rel):continue- quant = extract_quant_label(rel)+ quant = gguf_variant_key(rel)# Mirror the lister: a big-endian build is never offered, so it cannot vouch for the# quant. Judged with the loader's label, since the two extractors disagree on# F16-be-checkpoint-Q4_K_M and this file must not mark Q4_K_M complete.diff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.pyindex 29f456280df..7557d8085fd 100644--- a/studio/backend/hub/workers/hf_download.py+++ b/studio/backend/hub/workers/hf_download.py@@ -50,6 +50,7 @@ from hub.utils.snapshot_filters import (from hub.utils.gguf_plan import (GgufVariantPlan,build_gguf_variant_plans,+ plan_for_variant,plan_from_expected_files,sibling_sha256,)@@ -615,7 +616,10 @@ def _gguf_variant_target_plan(raise RuntimeError(f"Metadata unavailable while resolving GGUF variant '{variant}' " f"for {repo_id}") from e- return build_gguf_variant_plans(list(info.siblings)).get(variant.lower())+ # plan_for_variant, not .get: a repo that files every variant under one shared container+ # qualifies every key, and a stored pin or an explicit repo:Q4_K_M then missed the map and+ # the worker exited with "No GGUF shards matching variant".+ return plan_for_variant(build_gguf_variant_plans(list(info.siblings)), variant)def _download_gguf_variant(repo_id: str, variant: str, hf_token: str | None, mode: str) -> None:diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex 63bb543a205..be2da4f0498 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -134,7 +134,13 @@ class GgufVariantDetail(BaseModel):"""A single GGUF quantization variant in a HuggingFace repo."""filename: str = Field(..., description = "GGUF filename (e.g., 'gemma-3-4b-it-Q4_K_M.gguf')")- quant: str = Field(..., description = "Quantization label (e.g., 'Q4_K_M')")+ quant: str = Field(..., description = "Quantization label or internal GGUF variant key")+ # Mirrors hub.schemas.inventory.GgufVariantDetail. The route builds THIS model, so a field+ # that exists only on the hub twin is dropped by pydantic without a word, and a qualified+ # row falls back to rendering its whole relative path.+ display_label: Optional[str] = Field(+ None, description = "Optional user-facing label when quant is an internal key"+ )size_bytes: int = Field(0, description = "File size in bytes")download_size_bytes: int = Field(0, description = "Total bytes needed to download this variant")downloaded: bool = Field(diff --git a/studio/backend/picker/service.py b/studio/backend/picker/service.pyindex 7b08bc6e48a..123d332f655 100644--- a/studio/backend/picker/service.py+++ b/studio/backend/picker/service.py@@ -244,6 +244,12 @@ def _iter_ggufs(dir_path: Path) -> list[Path]:def _variant_matches(relative_path: str, needle: str) -> bool:+ from hub.utils.gguf import gguf_variant_key++ # The variant's own key first: in a repo holding several checkpoints at one quant+ # the bare label names every one of them, so it cannot pick between them.+ if gguf_variant_key(relative_path).lower() == needle:+ return Truequant = _extract_quant_label(relative_path).lower()if quant == needle:return True@@ -276,13 +282,22 @@ def _find_gguf_in_dir(dir_path: Path, gguf_variant: Optional[str]) -> Optional[Preturn Noneneedle = (gguf_variant or "").strip().lower()if needle:- for path in ggufs:+ from hub.utils.gguf import gguf_variant_key++ def _relative(path: Path) -> str:try:- relative = path.relative_to(dir_path).as_posix()+ return path.relative_to(dir_path).as_posix()except ValueError:- relative = path.name- if _variant_matches(relative, needle):- return path+ return path.name++ # Files this variant owns outright before ones its label merely also names.+ for owned in (True, False):+ for path in ggufs:+ relative = _relative(path)+ if owned != (gguf_variant_key(relative).lower() == needle):+ continue+ if _variant_matches(relative, needle):+ return pathreturn Nonecandidates = [path for path in ggufs if not _is_nonfirst_gguf_split(path)] or ggufstry:diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex c253f98d05a..7d3a539b595 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -2752,13 +2752,44 @@ def _prune_empty_parents(start: Path, stop_at: Path) -> None:parent = parent.parent+def _variant_names_same_checkpoint(a: Optional[str], b: Optional[str]) -> bool:+ """Whether two variant spellings can name the SAME checkpoint, for the load-state guard.++ Deletion accepts an unambiguous bare quant for a path-qualified key (the shared-container+ layout, ``weights/model-Q4_K_M.gguf``), so a guard comparing the two spellings literally lets+ a model loaded through a legacy bare pin be deleted through its advertised qualified row --+ unlinking the resident model's snapshot and blob. Deliberately loose: a false match only+ refuses a delete, a false miss loses weights.+ """+ from hub.utils.gguf import bare_quant_alias++ left = (a or "").strip().lower()+ right = (b or "").strip().lower()+ if not left or not right:+ return False+ if left == right:+ return True+ for key, bare in ((left, right), (right, left)):+ if "/" in key and "/" not in bare and bare_quant_alias(key).lower() == bare:+ return True+ return False++def _delete_gguf_variant_files(root: Path, variant: str) -> tuple[int, int]:deleted_count = 0deleted_bytes = 0for path in root.rglob("*"):if not path.is_file() or not _is_main_gguf_filename(path.name):continue- if _extract_quant_label(path.name).lower() != variant.lower():+ # Keyed on the path, not the basename: a repo holding several checkpoints at+ # one quant would otherwise delete every one of them for a single row.+ from utils.models.model_config import _gguf_variant_key++ try:+ relative = path.relative_to(root).as_posix()+ except ValueError:+ relative = path.name+ if _gguf_variant_key(relative).lower() != variant.lower():continuetry:deleted_bytes += path.stat().st_size@@ -2892,7 +2923,9 @@ async def delete_finetuned_model(and (not gguf_variantor not llama_backend.hf_variant- or llama_backend.hf_variant.lower() == gguf_variant.lower()+ # Alias-aware: the delete below accepts a bare quant for a qualified key, so a+ # literal comparison here would wave through the very spelling it then deletes.+ or _variant_names_same_checkpoint(llama_backend.hf_variant, gguf_variant))):raise HTTPException(@@ -2909,7 +2942,7 @@ async def delete_finetuned_model(and (not gguf_variantor not llama_backend.hf_variant- or llama_backend.hf_variant.lower() == gguf_variant.lower()+ or _variant_names_same_checkpoint(llama_backend.hf_variant, gguf_variant))):raise HTTPException(@@ -3319,25 +3352,34 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optioif snaps.is_dir():roots.extend(s for s in snaps.iterdir() if s.is_dir())- want = _normalized_quant_label(quant)+ want = (quant or "").strip()best_total = 0best_first: Optional[str] = Nonefor root in roots:- matches: list[tuple[str, Path]] = []- total = 0+ ranked: dict[int, list[tuple[str, Path, int]]] = {0: [], 1: []}for f in _iter_gguf_paths(root):try:rel = f.relative_to(root).as_posix()except ValueError:rel = f.name- q = _main_variant_gguf_label(rel)- if q is None or _normalized_quant_label(q) != want:+ rank = _main_variant_rank(rel, want)+ if rank is None:continuetry:- total += f.stat().st_size+ size = f.stat().st_sizeexcept OSError:continue- matches.append((rel, f))+ ranked[rank].append((rel, f, size))+ # Exact keys alone when any exist: summing them with the label matches counts other+ # checkpoints' bytes into this row's estimate and can reveal one of their files.+ # ... and within those, ONE shard family, the same rule group_gguf_variant_files+ # applies: a snapshot holding the same quant twice (QwQ-32B's two BF16 shard sets)+ # would otherwise report double the weights the loader opens, which /kv-cache-estimate+ # turns into a false exceeds-memory warning and which can make a snapshot look+ # "more complete" purely for holding a redundant copy.+ chosen = _one_shard_family_of(ranked[0] or ranked[1])+ matches = [(rel, f) for rel, f, _size in chosen]+ total = sum(size for _rel, _f, size in chosen)# Prefer the most complete snapshot so a partial older revision can't underestimate bytes.if matches and total > best_total:matches.sort(key = lambda m: m[0])@@ -3453,6 +3495,9 @@ async def get_gguf_variants(GgufVariantDetail(filename = v.filename,quant = v.quant,+ # A path-qualified key is not a label a picker can show; without this+ # the row reads as its whole relative path.+ display_label = getattr(v, "display_label", None),size_bytes = v.size_bytes,download_size_bytes = int(getattr(v, "download_size_bytes", v.size_bytes) or v.size_bytes@@ -3640,6 +3685,62 @@ def _main_variant_gguf_label(rel_path: str) -> Optional[str]:return label+def _one_shard_family_of(entries: list) -> list:+ """*entries* narrowed to the single shard family the loader would open.++ ``(rel, path, size)`` triples. Same rule as ``hub.utils.gguf.group_gguf_variant_files``:+ every shard of one split GGUF shares a family, two files that do not are two checkpoints, and+ the family kept is the one holding the lexicographically first file. A genuinely split GGUF is+ one family and survives whole.+ """+ if len(entries) < 2:+ return list(entries)+ from hub.utils.gguf import gguf_variant_family++ families: dict[str, list] = {}+ for entry in entries:+ families.setdefault(gguf_variant_family(entry[0]), []).append(entry)+ if len(families) < 2:+ return list(entries)+ return min(families.values(), key = lambda group: min(e[0] for e in group))+++def _main_variant_rank(rel_path: str, want: str) -> Optional[int]:+ """How well *want* names this file's variant: 0 for its own key, 1 for the legacy+ quant-label spelling, None for neither.++ *want* is the request VERBATIM: the bare-quant folding is applied per comparison, because+ doing it once up front strips a qualified key's own path punctuation and folds ``exp-a/`` into+ ``expa/``. Both spellings have to resolve -- a stored pin predates the qualified keys -- but+ they cannot rank equally. In a repo holding several checkpoints at one quant the bare label+ names every one of them, so a request for the repo-root ``Q6_K`` matched the qualified+ files too and then took whichever sorted first. Exact keys are used alone whenever any+ exist, and the label is the fallback for the rows that have no qualified spelling.+ """+ from utils.models.model_config import _gguf_variant_key++ label = _main_variant_gguf_label(rel_path)+ if label is None:+ return None+ if _variant_keys_match(_gguf_variant_key(rel_path), want):+ return 0+ return 1 if _normalized_quant_label(label) == _normalized_quant_label(want) else None+++def _variant_keys_match(key: str, want: str) -> bool:+ """Whether *want* is *key*, for the exact-key test.++ ``_normalized_quant_label`` strips hyphens and underscores, which is right for a bare quant+ (``UD-Q4_K_XL`` and ``udq4kxl`` are the same ask) and wrong for a path: it folds ``exp-a/`` and+ ``expa/`` into one, so two advertised checkpoints both answered to the other's key. A qualified+ key keeps its punctuation and compares case-insensitively; the legacy folding applies to the+ bare aliases it was written for.+ """+ if "/" in key or "/" in want:+ return key.strip().lower() == want.strip().lower()+ return _normalized_quant_label(key) == _normalized_quant_label(want)++def _normalized_quant_label(label: str) -> str:return label.lower().replace("-", "").replace("_", "")@@ -4421,7 +4522,7 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:raise HTTPException(status_code = 404, detail = "Model not found in cache")if variant:- want = _normalized_quant_label(variant)+ want = (variant or "").strip()candidate_revisions = sorted((rev for repo_info in matching_repos for rev in repo_info.revisions),key = lambda rev: getattr(rev, "last_modified", 0) or 0,@@ -4429,7 +4530,7 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:)for rev in candidate_revisions:snapshot = getattr(rev, "snapshot_path", None)- matches = []+ ranked: dict[int, list[tuple[str, Path]]] = {0: [], 1: []}for f in rev.files:p = Path(f.file_path)rel = f.file_name@@ -4438,11 +4539,13 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:rel = p.relative_to(snapshot).as_posix()except ValueError:pass- label = _main_variant_gguf_label(rel)- if label is None or _normalized_quant_label(label) != want:+ rank = _main_variant_rank(rel, want)+ if rank is None:continueif p.exists() or p.is_symlink():- matches.append((rel, p))+ ranked[rank].append((rel, p))+ # Exact keys alone when any exist, else the legacy label spelling.+ matches = ranked[0] or ranked[1]if matches:# Path-sorted so a sharded quant deterministically yields its first split.return sorted(matches, key = lambda m: m[0].lower())[0][1]diff --git a/studio/backend/tests/test_gguf_variant_rows.py b/studio/backend/tests/test_gguf_variant_rows.pynew file mode 100644index 00000000000..8c7bda6537b--- /dev/null+++ b/studio/backend/tests/test_gguf_variant_rows.py@@ -0,0 +1,1024 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""GGUF picker rows describe one checkpoint each.++A repo can publish several checkpoints under one set of quant labels+(``unsloth/LTX-2.3-GGUF`` ships 63 GGUFs as ``ltx-2.3-22b-dev-*`` at the root,+``distilled/ltx-2.3-22b-distilled-*`` and ``distilled-1.1/...``). Keying a row on+the quant token alone folded those into one row per quant, hid two of the three+checkpoints and advertised the sum of all three as the row's size.++Splitting a genuinely split GGUF is the opposite mistake, so both are pinned here.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from core.inference.llama_cpp import _gguf_files_for_variant+from hub.utils.gguf import (+ GgufVariantInfo,+ _apply_gguf_display_labels,+ extract_quant_label,+ gguf_variant_family,+ gguf_variant_key,+ group_gguf_variant_files,+ list_local_gguf_variants,+)+from hub.utils.gguf_plan import build_gguf_variant_plans, is_main_gguf_variant_path+from hub.utils.inventory_scan import complete_snapshot_variants+from utils.models.model_config import (+ _extract_quant_label,+ _find_local_gguf_by_variant,+ _gguf_variant_key,+)++LTX_FILES = [+ ("ltx-2.3-22b-dev-Q6_K.gguf", 17_770_000_000),+ ("distilled/ltx-2.3-22b-distilled-Q6_K.gguf", 17_770_000_000),+ ("distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K.gguf", 17_770_000_000),+]++# A real split GGUF: one variant, several shards, which must stay one row.+SHARDED_FILES = [+ ("BF16/DeepSeek-R1-BF16-00001-of-00003.gguf", 40),+ ("BF16/DeepSeek-R1-BF16-00002-of-00003.gguf", 40),+ ("BF16/DeepSeek-R1-BF16-00003-of-00003.gguf", 20),+]+++class _Sibling:+ def __init__(self, rfilename: str, size: int) -> None:+ self.rfilename = rfilename+ self.size = size+ self.lfs = {"sha256": f"hash-of-{rfilename}"}+++# --------------------------------------------------------------------------------------+# The key itself+# --------------------------------------------------------------------------------------+++ "path,expected",+ [+ # The shape almost every repo uses keeps the historical key, so every stored+ # pin, manifest and marker keeps resolving.+ ("Wan2.2-TI2V-5B-Q8_0.gguf", "Q8_0"),+ ("gemma-3-4b-it-UD-Q4_K_XL.gguf", "UD-Q4_K_XL"),+ ("BF16/DeepSeek-R1-BF16-00001-of-00003.gguf", "BF16"),+ ("MXFP4_MOE/model-MXFP4_MOE-00001-of-00003.gguf", "MXFP4_MOE"),+ # A <model>-<QUANT>/ directory names the same quant, so it adds nothing.+ ("DeepSeek-R1-Q4_K_M/DeepSeek-R1-Q4_K_M-00001-of-00009.gguf", "Q4_K_M"),+ ("Llama-3.3-70B-Instruct-F16/Llama-3.3-70B-Instruct-F16-00001-of-00004.gguf", "F16"),+ # A directory naming something else is another checkpoint, and qualifies.+ ("ltx-2.3-22b-dev-Q6_K.gguf", "Q6_K"),+ (+ "distilled/ltx-2.3-22b-distilled-Q6_K.gguf",+ "distilled/ltx-2.3-22b-distilled-Q6_K",+ ),+ (+ "distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K.gguf",+ "distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K",+ ),+ # A quant-named directory never overrides the basename, and a suffix after the+ # quant does not qualify it: both are established spellings.+ ("Q8_0/model-Q4_K_M.gguf", "Q4_K_M"),+ ("BF16/gemma-4-12b-it-Q8_0-MTP-001-of-002.gguf", "Q8_0"),+ # No quant anywhere: unchanged fallback.+ ("weights/model.gguf", "weights/model"),+ ],+)+def test_gguf_variant_key(path, expected):+ assert gguf_variant_key(path) == expected+++def test_key_is_unchanged_for_conventional_layouts():+ """The persisted variant identity must not churn where there is no collision."""+ for path in (+ "Wan2.2-TI2V-5B-Q4_K_M.gguf",+ "Qwen3-8B-UD-Q8_K_XL.gguf",+ "BF16/DeepSeek-R1-BF16-00002-of-00003.gguf",+ "DeepSeek-R1-Q4_K_M/DeepSeek-R1-Q4_K_M-00001-of-00009.gguf",+ ):+ assert gguf_variant_key(path) == extract_quant_label(path)+++def test_shards_of_one_gguf_share_a_key_and_a_family():+ keys = {gguf_variant_key(path) for path, _ in SHARDED_FILES}+ families = {gguf_variant_family(path) for path, _ in SHARDED_FILES}+ assert keys == {"BF16"}+ assert len(families) == 1+++def test_sibling_checkpoints_do_not_share_a_family():+ assert len({gguf_variant_family(path) for path, _ in LTX_FILES}) == 3+++def test_loader_mirror_agrees_with_the_hub_key():+ """``model_config._gguf_variant_key`` is a copy; drift means a row that misloads."""+ corpus = [path for path, _ in (*LTX_FILES, *SHARDED_FILES)] + [+ "Wan2.2-TI2V-5B-Q8_0.gguf",+ "gemma-3-4b-it-UD-Q4_K_XL.gguf",+ "MXFP4_MOE/model-MXFP4_MOE-00001-of-00003.gguf",+ "DeepSeek-R1-Q4_K_M/DeepSeek-R1-Q4_K_M-00001-of-00009.gguf",+ "Llama-3.3-70B-Instruct-Q6_K/Llama-3.3-70B-Instruct-Q6_K-00001-of-00002.gguf",+ "Q6_K/Llama-3.3-70B-Instruct-Q6_K-00001-of-00002.gguf",+ "Q8_0/model-Q4_K_M.gguf",+ "BF16/gemma-4-12b-it-Q8_0-MTP-001-of-002.gguf",+ "weights/model.gguf",+ "BF16/foo.gguf",+ ]+ assert [_gguf_variant_key(p) for p in corpus] == [gguf_variant_key(p) for p in corpus]+++# --------------------------------------------------------------------------------------+# Rows+# --------------------------------------------------------------------------------------+++def test_each_checkpoint_gets_its_own_row_at_its_own_size():+ rows = group_gguf_variant_files(LTX_FILES)+ assert len(rows) == 3+ assert {size for _, size in rows.values()} == {17_770_000_000}+ assert sorted(filename for filename, _ in rows.values()) == sorted(p for p, _ in LTX_FILES)+++def test_shards_stay_one_row_summing_to_the_whole_file():+ rows = group_gguf_variant_files(SHARDED_FILES)+ assert list(rows) == ["BF16"]+ assert rows["BF16"] == ("BF16/DeepSeek-R1-BF16-00001-of-00003.gguf", 100)+++def test_one_quant_shipped_twice_is_not_advertised_twice():+ """``unsloth/QwQ-32B-GGUF`` carries the same BF16 as ``-BF16`` and ``.BF16``."""+ duplicated = [+ ("BF16/QwQ-32B-BF16-00001-of-00002.gguf", 50),+ ("BF16/QwQ-32B-BF16-00002-of-00002.gguf", 15),+ ("BF16/QwQ-32B.BF16-00001-of-00002.gguf", 50),+ ("BF16/QwQ-32B.BF16-00002-of-00002.gguf", 15),+ ]+ rows = group_gguf_variant_files(duplicated)+ assert list(rows) == ["BF16"]+ assert rows["BF16"] == ("BF16/QwQ-32B-BF16-00001-of-00002.gguf", 65)+++def test_local_lister_matches_the_remote_shape(tmp_path):+ snapshot = tmp_path / "snap"+ for path, _ in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ (snapshot / "config.json").write_text("{}")++ variants, _ = list_local_gguf_variants(str(snapshot))+ assert sorted(v.quant for v in variants) == sorted(+ gguf_variant_key(path) for path, _ in LTX_FILES+ )+ assert all(v.size_bytes == 512 for v in variants)+++def test_qualified_rows_carry_a_readable_label():+ variants = [+ GgufVariantInfo(filename = path, quant = gguf_variant_key(path), size_bytes = 1)+ for path, _ in LTX_FILES+ ]+ _apply_gguf_display_labels(variants)+ labels = {v.quant: v.display_label for v in variants}+ assert labels["Q6_K"] is None+ assert labels["distilled/ltx-2.3-22b-distilled-Q6_K"] == "Q6_K · distilled"+ assert labels["distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K"] == "Q6_K · distilled-1.1"+++# --------------------------------------------------------------------------------------+# The row must be downloadable, loadable and complete-able under its own key+# --------------------------------------------------------------------------------------+++def test_every_row_key_matches_exactly_its_own_file():+ for path, _ in LTX_FILES:+ key = gguf_variant_key(path)+ owned = [other for other, _ in LTX_FILES if is_main_gguf_variant_path(other, key)]+ assert owned == [path], key+++def test_download_plan_fetches_one_checkpoint_not_three():+ plans = build_gguf_variant_plans([_Sibling(path, size) for path, size in LTX_FILES])+ assert len(plans) == 3+ for path, size in LTX_FILES:+ plan = plans[gguf_variant_key(path).lower()]+ assert plan.main_filenames == frozenset({path})+ assert plan.main_size_bytes == size+++def test_download_plan_keeps_every_shard_of_a_split_gguf():+ plans = build_gguf_variant_plans([_Sibling(path, size) for path, size in SHARDED_FILES])+ assert list(plans) == ["bf16"]+ assert plans["bf16"].main_filenames == frozenset(path for path, _ in SHARDED_FILES)+ assert plans["bf16"].main_size_bytes == 100+++def test_download_plan_drops_a_duplicate_copy_of_one_quant():+ """Fetching both copies doubles the download and never reads as complete."""+ siblings = [+ _Sibling("Q6_K/model-Q6_K-00001-of-00002.gguf", 50),+ _Sibling("Q6_K/model-Q6_K-00002-of-00002.gguf", 8),+ _Sibling("model-Q6_K/model-Q6_K-00001-of-00002.gguf", 50),+ _Sibling("model-Q6_K/model-Q6_K-00002-of-00002.gguf", 8),+ ]+ plan = build_gguf_variant_plans(siblings)["q6_k"]+ assert plan.main_size_bytes == 58+ assert {path.split("/")[0] for path in plan.main_filenames} == {"Q6_K"}+++def test_readiness_agrees_with_the_rows(tmp_path):+ """A finished download must read as complete under the same key it was listed by."""+ snapshot = tmp_path / "snap"+ for path, _ in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ variants, _ = list_local_gguf_variants(str(snapshot))+ assert {v.quant for v in variants} <= complete_snapshot_variants(str(snapshot))+++def test_a_chosen_row_loads_its_own_checkpoint(tmp_path):+ snapshot = tmp_path / "snap"+ for path, _ in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ (snapshot / "config.json").write_text("{}")++ for path, _ in LTX_FILES:+ key = gguf_variant_key(path)+ assert _find_local_gguf_by_variant(str(snapshot), key) == str(snapshot / path)+ assert _gguf_files_for_variant([p for p, _ in LTX_FILES], key) == [path]+++def test_llama_cpp_still_hands_over_every_shard():+ paths = [path for path, _ in SHARDED_FILES]+ assert _gguf_files_for_variant(paths, "bf16") == paths+++def test_the_bare_label_still_resolves_for_an_ordinary_repo(tmp_path):+ """A pin stored before this change keeps working where nothing collided."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "Wan2.2-TI2V-5B-Q6_K.gguf").write_bytes(b"x" * 64)+ (snapshot / "config.json").write_text("{}")+ assert _extract_quant_label("Wan2.2-TI2V-5B-Q6_K.gguf") == "Q6_K"+ assert _find_local_gguf_by_variant(str(snapshot), "Q6_K") == str(+ snapshot / "Wan2.2-TI2V-5B-Q6_K.gguf"+ )+++def test_delete_removes_only_the_chosen_checkpoint(tmp_path):+ from routes.models import _delete_gguf_variant_files++ snapshot = tmp_path / "snap"+ for path, _ in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)++ count, _ = _delete_gguf_variant_files(snapshot, "distilled/ltx-2.3-22b-distilled-Q6_K")+ assert count == 1+ assert not (snapshot / "distilled/ltx-2.3-22b-distilled-Q6_K.gguf").exists()+ assert (snapshot / "ltx-2.3-22b-dev-Q6_K.gguf").exists()+ assert (snapshot / "distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K.gguf").exists()+++def test_delete_removes_every_shard_of_one_variant(tmp_path):+ from routes.models import _delete_gguf_variant_files++ snapshot = tmp_path / "snap"+ for path, _ in SHARDED_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 8)++ count, _ = _delete_gguf_variant_files(snapshot, "BF16")+ assert count == 3+ assert not list((snapshot / "BF16").glob("*.gguf"))+++def test_a_local_subset_keys_the_same_as_the_whole_repo(tmp_path):+ """The key is a pure function of the path, so a half-downloaded snapshot and the+ remote listing cannot disagree and strand a finished download as incomplete."""+ whole = group_gguf_variant_files(LTX_FILES)+ for path, size in LTX_FILES:+ subset = group_gguf_variant_files([(path, size)])+ assert list(subset) == [gguf_variant_key(path)]+ assert subset[gguf_variant_key(path)] == whole[gguf_variant_key(path)]+++def test_paths_are_keyed_the_same_on_windows_separators():+ assert gguf_variant_key("distilled\\ltx-2.3-22b-distilled-Q6_K.gguf") == gguf_variant_key(+ "distilled/ltx-2.3-22b-distilled-Q6_K.gguf"+ )+++def test_row_filenames_are_real_paths_under_the_snapshot(tmp_path):+ """Every advertised row must point at a file that exists, for all three checkpoints."""+ snapshot = tmp_path / "snap"+ for path, _ in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ variants, _ = list_local_gguf_variants(str(snapshot))+ assert len(variants) == 3+ for variant in variants:+ assert (snapshot / variant.filename).is_file()+ assert Path(sorted(v.filename for v in variants)[-1]).name.startswith("ltx-2.3-22b-dev")+++def test_the_route_model_carries_display_label_to_the_picker():+ """The route builds ``models.models.GgufVariantDetail``, not the hub twin. When only the+ twin declared ``display_label`` pydantic dropped the kwarg without a word, so every+ qualified row reached the picker labelled with its whole relative path. Both models+ have to declare it or the qualified label silently never ships."""+ from hub.schemas.inventory import GgufVariantDetail as HubDetail+ from models.models import GgufVariantDetail as RouteDetail++ assert "display_label" in HubDetail.model_fields+ assert "display_label" in RouteDetail.model_fields, (+ "the route's own response model dropped display_label; a qualified row will render "+ "as its relative path"+ )++ row = RouteDetail(+ filename = "distilled/ltx-2.3-22b-distilled-Q6_K.gguf",+ quant = "distilled/ltx-2.3-22b-distilled-Q6_K",+ display_label = "Q6_K · distilled",+ size_bytes = 17_774_906_400,+ )+ assert row.model_dump()["display_label"] == "Q6_K · distilled"+++def test_an_unqualified_row_still_reports_no_display_label():+ """The label is only for keys a picker cannot show. A plain quant token must not grow+ one, or every ordinary row gains a redundant second name."""+ from models.models import GgufVariantDetail as RouteDetail++ row = RouteDetail(filename = "model-Q4_K_M.gguf", quant = "Q4_K_M", size_bytes = 1)+ assert row.model_dump()["display_label"] is None+++# --------------------------------------------------------------------------------------+# A row must not reach outside its own checkpoint+# --------------------------------------------------------------------------------------+++def test_a_discarded_shard_family_leaves_the_download_targets_too():+ """Narrowing only ``main_files`` left the copy in ``target_filenames`` /+ ``required_hashes`` / ``download_size_bytes``. The worker fetched both copies, reclaim+ then deleted the unchosen one (it is absent from the narrowed ``main_hashes``), and the+ manifest still required it -- so the finished job reported partial and re-downloaded a+ multi-gigabyte checkpoint on every retry."""+ from hub.utils.download_manifest import ExpectedFile+ from hub.utils.gguf_plan import plan_from_expected_files++ expected = [+ ExpectedFile(path = "BF16/QwQ-32B-BF16-00001-of-00002.gguf", size = 50, sha256 = "a1"),+ ExpectedFile(path = "BF16/QwQ-32B-BF16-00002-of-00002.gguf", size = 15, sha256 = "a2"),+ ExpectedFile(path = "BF16/QwQ-32B.BF16-00001-of-00002.gguf", size = 50, sha256 = "b1"),+ ExpectedFile(path = "BF16/QwQ-32B.BF16-00002-of-00002.gguf", size = 15, sha256 = "b2"),+ ExpectedFile(path = "mmproj-F16.gguf", size = 5, sha256 = "c1"),+ ]+ plan = plan_from_expected_files("bf16", expected)++ assert plan.main_filenames == {+ "BF16/QwQ-32B-BF16-00001-of-00002.gguf",+ "BF16/QwQ-32B-BF16-00002-of-00002.gguf",+ }+ # Everything the worker fetches and the manifest checks agrees with that choice.+ assert set(plan.target_filenames) == plan.main_filenames | {"mmproj-F16.gguf"}+ assert plan.required_hashes == frozenset({"a1", "a2", "c1"})+ assert plan.download_size_bytes == 70+ assert plan.main_size_bytes == 65+++def test_a_genuine_split_keeps_every_shard_in_the_plan():+ """The narrowing must stay blind to shard count: one family is one checkpoint."""+ from hub.utils.download_manifest import ExpectedFile+ from hub.utils.gguf_plan import plan_from_expected_files++ expected = [+ ExpectedFile(path = f"BF16/DeepSeek-R1-BF16-0000{n}-of-00003.gguf", size = 10, sha256 = f"h{n}")+ for n in (1, 2, 3)+ ]+ plan = plan_from_expected_files("bf16", expected)+ assert len(plan.main_filenames) == 3+ assert set(plan.target_filenames) == plan.main_filenames+ assert plan.download_size_bytes == 30+++def test_a_qualified_key_is_an_explicit_checkpoint_request():+ """``resolve_local_gguf`` falls back to the first local variant for a ``:tag`` that+ names no quant, which is right for ``:latest`` and wrong for one of our own rows. The+ full-match rejected every slash-qualified key, so asking for an absent checkpoint was+ answered by whichever one happened to be downloaded, under the requested model id."""+ from core.inference.openai_auto_download import looks_like_quant++ assert looks_like_quant("distilled/ltx-2.3-22b-distilled-Q6_K") is True+ assert looks_like_quant("distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K") is True+ # Unchanged for the spellings it already judged.+ assert looks_like_quant("Q6_K") is True+ assert looks_like_quant("IQ4_XS-3.53bpw") is True+ assert looks_like_quant("latest") is False+ assert looks_like_quant("8b") is False+ assert looks_like_quant(None) is False+++def test_the_exact_key_wins_over_the_bare_quant_label():+ """A bare label names every checkpoint carrying that quant, so the repo-root ``Q6_K``+ row matched the qualified files too and then took whichever sorted first -- reporting+ the sum of every checkpoint as its size and revealing another one's file."""+ from routes.models import _main_variant_rank++ # The request VERBATIM: folding it up front would strip a qualified key's path punctuation.+ assert _main_variant_rank("ltx-2.3-22b-dev-Q6_K.gguf", "Q6_K") == 0+ assert _main_variant_rank("distilled/ltx-2.3-22b-distilled-Q6_K.gguf", "Q6_K") == 1+ assert _main_variant_rank("ltx-2.3-22b-dev-Q4_K_M.gguf", "Q6_K") is None+ # And the qualified row is exact under its own key, while the root file is not a match.+ qualified = "distilled/ltx-2.3-22b-distilled-Q6_K"+ assert _main_variant_rank("distilled/ltx-2.3-22b-distilled-Q6_K.gguf", qualified) == 0+ assert _main_variant_rank("ltx-2.3-22b-dev-Q6_K.gguf", qualified) is None+ # The bare spelling keeps its hyphen/underscore folding; a qualified one keeps its path.+ assert _main_variant_rank("model-UD-Q4_K_XL.gguf", "udq4kxl") == 0+ assert _main_variant_rank("exp-a/model-Q6_K.gguf", "expa/model-Q6_K") is None+ assert _main_variant_rank("exp-a/model-Q6_K.gguf", "exp-a/model-q6_k") == 0+++def test_two_checkpoints_in_one_directory_get_distinguishable_labels():+ """Two rows labelled ``Q6_K · experiments`` are two rows a user cannot tell apart."""+ paths = ("experiments/model-a-Q6_K.gguf", "experiments/model-b-Q6_K.gguf")+ variants = [+ GgufVariantInfo(filename = path, quant = gguf_variant_key(path), size_bytes = 1) for path in paths+ ]+ _apply_gguf_display_labels(variants)+ labels = [v.display_label for v in variants]+ assert labels == ["Q6_K · experiments/model-a-Q6_K", "Q6_K · experiments/model-b-Q6_K"]+ assert len(set(labels)) == 2+++def test_the_model_config_listers_advertise_the_qualified_keys(tmp_path):+ """Three consumers read their variant identities from these two listers rather than from the+ hub copy: the /v1 local index (``local_model_resolver`` builds ``entry.variants`` here), the+ remote VRAM preflight (which looks for a matching ``v.quant`` to get ``main_bytes``), and the+ picker's own remote sizing. While they grouped on the bare label the qualified rows were+ invisible to all three, and a slash-qualified suffix is now an explicit variant, so the miss+ is a 404 rather than a fallback onto some other checkpoint."""+ from utils.models.model_config import list_local_gguf_variants++ snapshot = tmp_path / "snap"+ for path, _size in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ (snapshot / "config.json").write_text("{}")++ variants, _has_vision = list_local_gguf_variants(str(snapshot))+ assert sorted(v.quant for v in variants) == sorted(+ gguf_variant_key(path) for path, _ in LTX_FILES+ )+ # Every advertised key resolves back to its OWN file, which is what the row promises.+ for variant in variants:+ resolved = _find_local_gguf_by_variant(str(snapshot), variant.quant)+ assert resolved is not None, variant.quant+ assert _gguf_variant_key(Path(resolved).relative_to(snapshot).as_posix()) == variant.quant+++def test_the_ordinary_repo_keeps_its_bare_labels(tmp_path):+ """The qualified key is only for repos that need it. Every ordinary repo must list exactly+ the labels it listed before, or every stored pin and every /v1 model id breaks at once."""+ from utils.models.model_config import list_local_gguf_variants++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ for name in ("model-Q4_K_M.gguf", "model-Q6_K.gguf", "BF16/model-BF16-00001-of-00002.gguf"):+ target = snapshot / name+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 64)+ (snapshot / "config.json").write_text("{}")+ variants, _ = list_local_gguf_variants(str(snapshot))+ assert sorted(v.quant for v in variants) == ["BF16", "Q4_K_M", "Q6_K"]+++def test_the_auto_download_map_is_keyed_like_the_plan():+ """``_match_variant`` looks the request up in this map and the worker then looks the plan up+ by the same string, so a map keyed on the bare label turned every qualified row into a 404+ instead of dispatching its download."""+ from types import SimpleNamespace++ from core.inference.openai_auto_download import _gguf_variants++ siblings = [SimpleNamespace(rfilename = path, size = size) for path, size in LTX_FILES]+ sizes = _gguf_variants(siblings)+ assert set(sizes) == {gguf_variant_key(path) for path, _ in LTX_FILES}+ assert "distilled/ltx-2.3-22b-distilled-Q6_K" in sizes+ # Each row is sized for its own checkpoint, not the sum of every checkpoint at that quant.+ assert all(size > 0 for size in sizes.values())+++def test_an_unknown_layout_row_keeps_the_label_it_always_had(tmp_path):+ """The qualified key is for several checkpoints sharing one quant, nothing else. A file with+ no recognised quant token has always been listed here under this module's label (the last+ hyphenated segment) rather than the whole stem, and renaming those rows would break every pin+ that holds one -- for no benefit, since there is no ambiguity to resolve."""+ from utils.models.model_config import list_local_gguf_variants++ snapshot = tmp_path / "snap"+ (snapshot / "BF16").mkdir(parents = True)+ (snapshot / "Qwen3.6-27B-MTP-001-of-002.gguf").write_bytes(b"x" * 100)+ (snapshot / "BF16" / "gemma-4-12b-it-Q8_0-001-of-002.gguf").write_bytes(b"x" * 40)+ (snapshot / "config.json").write_text("{}")++ variants, _ = list_local_gguf_variants(str(snapshot))+ assert sorted(v.quant for v in variants) == ["MTP", "Q8_0"]+++def test_a_shared_container_directory_still_answers_its_bare_quant():+ """A repo that files every variant under one container (``weights/model-Q4_K_M.gguf``)+ qualifies every key, because the key is a pure function of the path and cannot know the+ directory disambiguates nothing. Every stored pin and every explicit repo:Q4_K_M then missed+ the plan map, and the worker exited with 'No GGUF shards matching variant'."""+ from types import SimpleNamespace++ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant++ siblings = [+ SimpleNamespace(rfilename = f"weights/model-{q}.gguf", size = 10, lfs = None)+ for q in ("Q4_K_M", "Q6_K")+ ]+ plans = build_gguf_variant_plans(siblings)+ # The rows are still one per checkpoint, keyed on the path.+ assert set(plans) == {"weights/model-q4_k_m", "weights/model-q6_k"}+ # ... and the bare pin still resolves, because it names exactly one of them.+ assert plan_for_variant(plans, "Q4_K_M") is plans["weights/model-q4_k_m"]+ assert plan_for_variant(plans, "q6_k") is plans["weights/model-q6_k"]+ assert plan_for_variant(plans, "weights/model-q6_k") is plans["weights/model-q6_k"]+ assert plan_for_variant(plans, "Q8_0") is None+ assert plan_for_variant(plans, "") is None+++def test_an_ambiguous_bare_quant_gets_no_fallback():+ """Where a repo genuinely holds several checkpoints at one quant, the bare name does not name+ one of them, and guessing is the collapse this PR exists to undo."""+ from types import SimpleNamespace++ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant++ siblings = [+ SimpleNamespace(rfilename = path, size = 10, lfs = None)+ for path in (+ "distilled/ltx-2.3-22b-distilled-Q6_K.gguf",+ "distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K.gguf",+ )+ ]+ plans = build_gguf_variant_plans(siblings)+ assert len(plans) == 2+ assert plan_for_variant(plans, "Q6_K") is None+ # The exact key still resolves, which is what the advertised row asks for.+ assert plan_for_variant(plans, "distilled/ltx-2.3-22b-distilled-q6_k") is not None+++def test_a_bare_local_id_keeps_the_checkpoint_a_plain_load_takes():+ """A plain local load resolves through non-recursive detect_gguf_model and always takes the+ repo root; the /v1 index ranks on the key text and would hand a bare id an equally good+ ``distilled/...`` row that sorts earlier. One id, two answers, different weights."""+ from core.inference.openai_auto_download import preferred_quant++ quants = (+ "Q6_K",+ "distilled/ltx-2.3-22b-distilled-Q6_K",+ "distilled-1.1/ltx-2.3-22b-distilled-1.1-Q6_K",+ )+ unqualified = tuple(q for q in quants if "/" not in q)+ assert preferred_quant(unqualified) == "Q6_K"+++def test_bpw_precisions_stay_separately_selectable(tmp_path):+ """_extract_quant_label deliberately keeps the bpw modifier so byteshape's IQ4_XS at 3.53,+ 3.97 and 4.19 stay three rows. The token extractor drops it, so routing these listers through+ the key merged all three under IQ4_XS and an explicit request for the formerly advertised+ spelling missed."""+ from utils.models.model_config import list_local_gguf_variants++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ for bpw in ("3.53", "3.97", "4.19"):+ (snapshot / f"Qwen3.6-IQ4_XS-{bpw}bpw.gguf").write_bytes(b"x" * 64)+ (snapshot / "config.json").write_text("{}")+ variants, _ = list_local_gguf_variants(str(snapshot))+ assert sorted(v.quant for v in variants) == [+ "IQ4_XS-3.53bpw",+ "IQ4_XS-3.97bpw",+ "IQ4_XS-4.19bpw",+ ]+++def test_a_parent_only_quant_survives_the_endian_filter():+ """_is_big_endian_gguf_path reads a quant TOKEN so it can tell a parent-only quant from a+ big-endian build. Handing it the qualified key made it misread the path and drop the file+ from every plan, so the advertised row could never be downloaded."""+ from types import SimpleNamespace++ from hub.utils.gguf_plan import build_gguf_variant_plans++ siblings = [+ SimpleNamespace(rfilename = "distilled/Q4_K_M/foo.gguf", size = 10, lfs = None),+ ]+ plans = build_gguf_variant_plans(siblings)+ assert plans, "the only file in the repo was filtered out of every plan"+ key = next(iter(plans))+ assert plans[key].main_filenames == {"distilled/Q4_K_M/foo.gguf"}+++def test_admission_resolves_a_bare_alias_instead_of_404ing():+ """Admission rejects against its own size map before the worker plan is ever consulted, so+ the container-directory fallback has to exist on both. Without it a legacy org/repo:Q4_K_M+ got a 404 and the worker fix was unreachable."""+ from core.inference.openai_auto_download import _match_variant++ variants = {"weights/model-Q4_K_M": 10, "weights/model-Q6_K": 20}+ assert _match_variant("Q4_K_M", variants) == "weights/model-Q4_K_M"+ assert _match_variant("weights/model-q6_k", variants) == "weights/model-Q6_K"+ assert _match_variant("Q8_0", variants) is None+ # Ambiguous stays a miss: with two checkpoints at one quant the bare name names neither.+ ambiguous = {"distilled/m-Q6_K": 10, "distilled-1.1/m-Q6_K": 20}+ assert _match_variant("Q6_K", ambiguous) is None+++def test_a_parent_only_quant_survives_the_main_file_predicate():+ """is_main_gguf_variant_path runs the endian test too. Handed the qualified key it could not+ see the parent-only quant, so the plan came back with no main files and an interrupted+ download had no hashes to resume against."""+ from hub.utils.gguf_plan import is_main_gguf_variant_path++ path = "distilled/Q4_K_M/foo.gguf"+ assert is_main_gguf_variant_path(path, gguf_variant_key(path))+++def test_a_local_load_keeps_the_qualified_identity_it_was_asked_for(tmp_path):+ """_find_local_gguf_by_variant picks the right file, but the returned config dropped the+ variant, so the load intent carried none and llama.cpp recorded the bare label off the+ filename. /status then named the root row for a qualified checkpoint, and the deletion guard+ compared that bare label against the selected key and let the delete through."""+ from utils.models.model_config import ModelConfig++ snapshot = tmp_path / "snap"+ for path, _size in LTX_FILES:+ target = snapshot / path+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 512)+ (snapshot / "config.json").write_text("{}")++ wanted = "distilled/ltx-2.3-22b-distilled-Q6_K"+ cfg = ModelConfig.from_identifier(str(snapshot), gguf_variant = wanted)+ assert cfg is not None and cfg.is_gguf and cfg.is_local+ assert cfg.gguf_variant == wanted+ assert "distilled/" in Path(cfg.gguf_file).as_posix()+ # A bare request still records the bare identity it asked for.+ bare = ModelConfig.from_identifier(str(snapshot), gguf_variant = "Q6_K")+ assert bare is not None and bare.gguf_variant == "Q6_K"+++def _cache_repo(tmp_path: Path, repo_id: str, names: list[str]):+ """An HF cache repo: snapshot symlinks pointing at blobs, as the deletion scan reads it."""+ from types import SimpleNamespace++ repo_dir = tmp_path / f"models--{repo_id.replace('/', '--')}"+ snap = repo_dir / "snapshots" / "rev1"+ blobs = repo_dir / "blobs"+ snap.mkdir(parents = True)+ blobs.mkdir(parents = True)+ files = []+ for index, name in enumerate(names):+ blob = blobs / f"sha{index}"+ blob.write_bytes(b"x" * 64)+ link = snap / name+ link.parent.mkdir(parents = True, exist_ok = True)+ link.symlink_to(blob)+ files.append(+ SimpleNamespace(+ file_name = Path(name).name,+ file_path = str(link),+ blob_path = str(blob),+ size_on_disk = 64,+ )+ )+ return SimpleNamespace(+ repo_id = repo_id,+ repo_type = "model",+ repo_path = repo_dir,+ revisions = [SimpleNamespace(files = files, snapshot_path = str(snap))],+ ), snap+++def test_deleting_a_container_variant_accepts_the_bare_quant_the_download_admits(tmp_path):+ """A repo filing its sole Q4_K_M under a shared container qualifies that key, so every stored+ pin and every explicit ``repo:Q4_K_M`` names it by quant alone -- which ``plan_for_variant``+ admits for the download. Matching only the qualified key on delete answered "not found" and+ left the weights on disk."""+ from hub.services.models.deletion import _delete_gguf_variant_from_repos+ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant++ repo, snap = _cache_repo(tmp_path, "org/Model-GGUF", ["weights/model-Q4_K_M.gguf"])+ # The download side already resolves the bare name here; keep the two in step.+ plans = build_gguf_variant_plans([_Sibling("weights/model-Q4_K_M.gguf", 64)])+ assert set(plans) == {"weights/model-q4_k_m"}+ assert plan_for_variant(plans, "Q4_K_M") is not None++ _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)+ assert not (snap / "weights" / "model-Q4_K_M.gguf").is_symlink()+++def test_an_ambiguous_bare_quant_deletes_nothing(tmp_path):+ """Two checkpoints at one quant: the bare name genuinely does not name one of them, and+ deleting the wrong one is unrecoverable. Same rule ``plan_for_variant`` applies."""+ from fastapi import HTTPException++ from hub.services.models.deletion import _delete_gguf_variant_from_repos++ repo, snap = _cache_repo(+ tmp_path,+ "org/Model-GGUF",+ ["distilled/model-Q4_K_M.gguf", "distilled-1.1/model-Q4_K_M.gguf"],+ )+ with pytest.raises(HTTPException) as excinfo:+ _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)+ assert excinfo.value.status_code == 404+ assert (snap / "distilled" / "model-Q4_K_M.gguf").is_symlink()+ assert (snap / "distilled-1.1" / "model-Q4_K_M.gguf").is_symlink()++ # The qualified key still deletes exactly its own checkpoint.+ _delete_gguf_variant_from_repos(+ "org/Model-GGUF", "distilled/model-Q4_K_M", [repo], None, root = tmp_path+ )+ assert not (snap / "distilled" / "model-Q4_K_M.gguf").is_symlink()+ assert (snap / "distilled-1.1" / "model-Q4_K_M.gguf").is_symlink()+++def test_a_bare_quant_that_is_its_own_key_still_deletes_only_itself(tmp_path):+ """The overwhelmingly common shape: the root file's key IS the bare quant, so the alias+ fallback must not fire and must not reach a qualified sibling."""+ from hub.services.models.deletion import _delete_gguf_variant_from_repos++ repo, snap = _cache_repo(+ tmp_path, "org/Model-GGUF", ["model-Q4_K_M.gguf", "distilled/model-Q4_K_M.gguf"]+ )+ _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)+ assert not (snap / "model-Q4_K_M.gguf").is_symlink()+ assert (snap / "distilled" / "model-Q4_K_M.gguf").is_symlink()+++def test_a_qualified_key_whose_basename_ends_in_be_still_resolves_for_loading():+ """The endian predicate reads a quant TOKEN -- whether the quant came from the parent+ directory only. Handed the path-qualified key instead, it cannot find that string in the+ basename or the parent and reads distilled/Q4_K_M/foo-be.gguf as a big-endian build, dropping+ the one file the key owns: the row is advertised and downloadable but never loadable."""+ files = [+ "distilled/Q4_K_M/foo-be.gguf",+ "other/Q4_K_M/bar.gguf",+ "stories260K.gguf",+ "stories260K-be.gguf",+ ]+ assert _gguf_files_for_variant(files, "distilled/Q4_K_M/foo-be") == [+ "distilled/Q4_K_M/foo-be.gguf"+ ]+ assert _gguf_files_for_variant(files, "other/Q4_K_M/bar") == ["other/Q4_K_M/bar.gguf"]+ # A genuinely big-endian build is still dropped: the -be file never joins the row.+ assert _gguf_files_for_variant(files, "stories260K") == ["stories260K.gguf"]+ # ... and the plan and the lister agree the qualified file is a normal parent-quant one.+ assert is_main_gguf_variant_path(+ "distilled/Q4_K_M/foo-be.gguf", gguf_variant_key("distilled/Q4_K_M/foo-be.gguf")+ )+++def test_a_bpw_build_keeps_its_own_identity_everywhere():+ """Two builds of one base quant at different bits-per-weight are two checkpoints. The loader's+ label always kept the modifier; the variant key dropped it, so the local export lister+ advertised IQ4_XS-3.53bpw while the plan, the auto-download map and the delete predicate all+ said IQ4_XS -- the advertised name 404s and the collapsed one unlinks BOTH builds."""+ from utils.models.model_config import _extract_quant_label as loader_label++ a = "model-IQ4_XS-3.53bpw.gguf"+ b = "model-IQ4_XS-3.97bpw.gguf"+ for path in (a, b):+ assert gguf_variant_key(path) == loader_label(path)+ assert _gguf_variant_key(path) == gguf_variant_key(path)+ assert gguf_variant_key(a) != gguf_variant_key(b)+ # Shards of ONE bpw build still share a key.+ assert gguf_variant_key("model-IQ4_XS-3.53bpw-00001-of-00002.gguf") == gguf_variant_key(a)+ # Two rows, each sized on its own family rather than the sum of both.+ grouped = group_gguf_variant_files([(a, 10), (b, 20)])+ assert grouped == {"IQ4_XS-3.53bpw": (a, 10), "IQ4_XS-3.97bpw": (b, 20)}+ # A plain quant is untouched, so every stored pin still resolves.+ assert gguf_variant_key("model-Q4_K_M.gguf") == "Q4_K_M"+ assert gguf_variant_key("distilled/model-Q6_K.gguf") == "distilled/model-Q6_K"+++def test_a_bpw_key_needs_no_scope_label():+ """It reads as a label already, so the display pass must not append the whole filename to it+ the way it does for a path-qualified key."""+ variants = [+ GgufVariantInfo(filename = "model-IQ4_XS-3.53bpw.gguf", quant = "IQ4_XS-3.53bpw", size_bytes = 1),+ GgufVariantInfo(filename = "model-IQ4_XS-3.97bpw.gguf", quant = "IQ4_XS-3.97bpw", size_bytes = 2),+ GgufVariantInfo(+ filename = "distilled/model-Q6_K.gguf", quant = "distilled/model-Q6_K", size_bytes = 3+ ),+ ]+ _apply_gguf_display_labels(variants)+ assert variants[0].display_label is None+ assert variants[1].display_label is None+ assert variants[2].display_label == "Q6_K · distilled"+++def test_a_bare_auto_download_stays_on_the_root_checkpoint():+ """preferred_quant is order-sensitive, so once the map carried a key per checkpoint a bare+ org/repo could pick distilled/model-Q6_K over the root model-Q6_K -- while the same id+ resolves to the root locally, i.e. one model id serving two different sets of weights."""+ from core.inference.openai_auto_download import _match_variant++ both = {"distilled/model-Q6_K": 1, "Q6_K": 2}+ assert _match_variant(None, both) == "Q6_K"+ assert _match_variant(None, {"Q6_K": 2, "distilled/model-Q6_K": 1}) == "Q6_K"+ # An explicit qualified ask still resolves to the sibling.+ assert _match_variant("distilled/model-Q6_K", both) == "distilled/model-Q6_K"+ # A repo with nothing at the root falls back to the whole set rather than refusing.+ assert _match_variant(None, {"distilled/model-Q6_K": 1}) == "distilled/model-Q6_K"+++def test_the_bare_alias_keeps_the_bpw_and_survives_a_dotted_stem():+ """The three compatibility fallbacks that accept a bare name for a path-qualified key -- the+ plan lookup, auto-download admission and deletion -- share this. Two traps: the bpw modifier+ is part of the identity now, and a key is already extension-stripped, so re-stemming it cuts+ at the dot in "3.53bpw" (and at the one in "ltx-2.3")."""+ from hub.utils.gguf import bare_quant_alias++ assert bare_quant_alias("weights/model-IQ4_XS-3.53bpw") == "IQ4_XS-3.53bpw"+ assert bare_quant_alias("weights/model-Q4_K_M") == "Q4_K_M"+ assert bare_quant_alias("distilled/ltx-2.3-22b-distilled-Q6_K") == "Q6_K"+++def test_a_bpw_container_build_resolves_by_its_bare_spelling(tmp_path):+ """A shared container qualifies the key, so the persisted bare spelling has to keep resolving+ -- and that spelling carries the bpw suffix."""+ from hub.services.models.deletion import _delete_gguf_variant_from_repos+ from hub.utils.gguf_plan import build_gguf_variant_plans, plan_for_variant++ plans = build_gguf_variant_plans([_Sibling("weights/model-IQ4_XS-3.53bpw.gguf", 64)])+ assert set(plans) == {"weights/model-iq4_xs-3.53bpw"}+ assert plan_for_variant(plans, "IQ4_XS-3.53bpw") is not None+ # The token alone is NOT that build's name; it must not resolve one bpw build for another.+ assert plan_for_variant(plans, "IQ4_XS") is None++ repo, snap = _cache_repo(tmp_path, "org/Model-GGUF", ["weights/model-IQ4_XS-3.53bpw.gguf"])+ _delete_gguf_variant_from_repos("org/Model-GGUF", "IQ4_XS-3.53bpw", [repo], None, root = tmp_path)+ assert not (snap / "weights" / "model-IQ4_XS-3.53bpw.gguf").is_symlink()+++def test_the_inference_lister_sizes_one_shard_family_not_both_copies():+ """A repo shipping the same quant twice (QwQ-32B's BF16 as QwQ-32B-BF16-* beside+ QwQ-32B.BF16-*) has one row; charging both copies to it doubles the weight figure that+ routes/inference.py bills to the VRAM guard, which then refuses a load that fits. The hub+ lister already keeps one family; this is the mirror that feeds the guard."""+ from utils.models.model_config import _group_gguf_variant_files++ entries = [+ ("QwQ-32B-BF16-00001-of-00002.gguf", "BF16", 10),+ ("QwQ-32B-BF16-00002-of-00002.gguf", "BF16", 10),+ ("QwQ-32B.BF16-00001-of-00002.gguf", "BF16", 10),+ ("QwQ-32B.BF16-00002-of-00002.gguf", "BF16", 10),+ ]+ grouped = _group_gguf_variant_files(entries)+ assert grouped == {"BF16": ("QwQ-32B-BF16-00001-of-00002.gguf", 20)}+ # Byte-for-byte what the hub lister answers, so the two cannot drift.+ assert grouped == group_gguf_variant_files([(n, s) for n, _q, s in entries])+ # A genuinely split GGUF is ONE family, so every shard still counts.+ split = [("m-00001-of-00003.gguf", "Q4_K_M", 5)] * 1 + [+ ("m-00002-of-00003.gguf", "Q4_K_M", 5),+ ("m-00003-of-00003.gguf", "Q4_K_M", 5),+ ]+ assert _group_gguf_variant_files(split)["Q4_K_M"][1] == 15+++def test_a_bpw_modifier_in_the_quant_directory_still_makes_two_keys():+ """The quant-directory layout carries the modifier upstairs (IQ4_XS-3.53bpw/model.gguf),+ which is exactly where extract_quant_token looks next. Reading only the basename gave both+ builds the bare IQ4_XS key, so grouping and the plan kept one family and deleting that+ advertised key unlinked BOTH -- the same data loss as the root-filename case."""+ a = "IQ4_XS-3.53bpw/model.gguf"+ b = "IQ4_XS-3.97bpw/model.gguf"+ assert gguf_variant_key(a) == "IQ4_XS-3.53bpw"+ assert gguf_variant_key(b) == "IQ4_XS-3.97bpw"+ assert _gguf_variant_key(a) == gguf_variant_key(a)+ assert _gguf_variant_key(b) == gguf_variant_key(b)+ assert group_gguf_variant_files([(a, 10), (b, 20)]) == {+ "IQ4_XS-3.53bpw": (a, 10),+ "IQ4_XS-3.97bpw": (b, 20),+ }+ # A plain quant directory is untouched, so every stored pin still resolves.+ assert gguf_variant_key("Q4_K_M/model.gguf") == "Q4_K_M"+ # The walk stops at the segment that named the quant: a modifier on the FILE under a plain+ # quant directory is still this build's own.+ assert gguf_variant_key("Q6_K/model-3.5bpw.gguf") == "Q6_K-3.5bpw"+++def test_the_remote_default_variant_prefers_the_root_checkpoint():+ """pick_best_gguf keeps whichever filename it met first among equals, so a repo with+ model-Q6_K.gguf beside distilled/model-Q6_K.gguf could hand the picker the distilled+ checkpoint as its automatic default -- while a bare repo id means the ROOT checkpoint to+ _match_variant(None, ...) and to local_model_resolver."""+ import inspect++ from hub.services.models import gguf_variants as service++ source = inspect.getsource(service)+ assert 'root_rows = [v.filename for v in variants if "/" not in v.quant]' in source+ assert "pick_best_gguf(_default_variant_candidates(variants))" in source+++def test_the_load_guard_sees_the_alias_the_delete_accepts():+ """Deletion accepts an unambiguous bare quant for a path-qualified key (the shared-container+ layout), so a guard comparing spellings literally lets a model loaded through a legacy bare+ pin be deleted through its advertised qualified row -- unlinking the resident model's own+ snapshot and blob. Loose on purpose: a false match only refuses a delete."""+ from routes.models import _variant_names_same_checkpoint as same++ assert same("Q4_K_M", "weights/model-Q4_K_M")+ assert same("weights/model-Q4_K_M", "Q4_K_M")+ assert same("Q4_K_M", "Q4_K_M")+ # Two different checkpoints are never the same, in either direction.+ assert not same("Q4_K_M", "Q6_K")+ assert not same("distilled/model-Q6_K", "other/model-Q6_K")+ # An unknown side never matches: the caller falls back to its own not-loaded branch.+ assert not same(None, "Q4_K_M")+ assert not same("Q4_K_M", "")+++def test_every_branch_derives_the_default_from_the_root_rows():+ """Remote, cached and partial-local all answer /gguf-variants, so all three have to define a+ bare repo id the way _match_variant(None, ...) and local_model_resolver do -- the ROOT+ checkpoint -- or the automatic default depends on which branch served the request."""+ import inspect+ import types++ from hub.services.models import gguf_variants as service++ rows = [+ types.SimpleNamespace(filename = "distilled/model-Q6_K.gguf", quant = "distilled/model-Q6_K"),+ types.SimpleNamespace(filename = "model-Q6_K.gguf", quant = "Q6_K"),+ ]+ assert service._default_variant_candidates(rows) == ["model-Q6_K.gguf"]+ # Nothing at the root falls back to the whole set rather than answering nothing.+ assert service._default_variant_candidates(rows[:1]) == ["distilled/model-Q6_K.gguf"]+ # No branch may call pick_best_gguf on the raw filenames any more.+ source = inspect.getsource(service)+ assert source.count("pick_best_gguf(_default_variant_candidates(") == 3+ assert "pick_best_gguf(filenames)" not in source+++def test_the_kv_cache_estimate_sizes_one_shard_family():+ """A snapshot holding the same quant twice (QwQ-32B's two BF16 shard sets) would report double+ the weights the loader opens, which /kv-cache-estimate turns into a false exceeds-memory+ warning -- and which can make a snapshot look "more complete" purely for holding a redundant+ copy. Same rule group_gguf_variant_files applies."""+ from routes.models import _one_shard_family_of++ duplicated = [+ ("QwQ-32B-BF16-00001-of-00002.gguf", None, 10),+ ("QwQ-32B-BF16-00002-of-00002.gguf", None, 10),+ ("QwQ-32B.BF16-00001-of-00002.gguf", None, 10),+ ("QwQ-32B.BF16-00002-of-00002.gguf", None, 10),+ ]+ kept = _one_shard_family_of(duplicated)+ assert [e[0] for e in kept] == [+ "QwQ-32B-BF16-00001-of-00002.gguf",+ "QwQ-32B-BF16-00002-of-00002.gguf",+ ]+ assert sum(e[2] for e in kept) == 20+ # A genuinely split GGUF is ONE family and survives whole.+ split = [(f"m-0000{i}-of-00003.gguf", None, 5) for i in (1, 2, 3)]+ assert _one_shard_family_of(split) == split+++def test_the_remote_load_path_auto_selects_the_root_checkpoint():+ """ModelConfig.from_identifier is the LOAD path, so it has to define a bare repo id the way+ local_model_resolver, the auto-download map and /gguf-variants do -- the ROOT checkpoint.+ _pick_best_gguf keeps whichever filename it met first among equals, and an LTX-style listing+ puts distilled/... before the root file."""+ import inspect++ from utils.models import model_config as mc++ source = inspect.getsource(mc.ModelConfig.from_identifier)+ assert "root_rows = [" in source+ assert "variant_filenames = root_rows or [v.filename for v in variants]" in source+ # The filter reads the ADVERTISED identity, the same one the lister assigns each row.+ assert '"/" not in _qualified_variant_name(v.filename, v.quant)' in sourcediff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex ee4207fcc8e..2969c9d4ffe 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -2299,6 +2299,111 @@ _GGUF_KNOWN_QUANT_RE = re.compile()+_FLOAT_PRECISION_QUANTS = frozenset({"BF16", "F16", "F32"})+_GGUF_SPLIT_SUFFIX_RE = re.compile(r"-\d{3,}-of-\d{3,}", re.IGNORECASE)+++def _select_known_quant_match(text: str):+ fallback = None+ for match in _GGUF_KNOWN_QUANT_RE.finditer(text):+ if match.group(2).upper() in _FLOAT_PRECISION_QUANTS:+ if fallback is None:+ fallback = match+ continue+ return match+ return fallback+++def _gguf_variant_stem(filename: str) -> str:+ basename = filename.rsplit("/", 1)[-1]+ return _GGUF_SPLIT_SUFFIX_RE.sub("", basename.rsplit(".", 1)[0]).strip()+++def _gguf_variant_token(filename: str) -> Optional[str]:+ match = _select_known_quant_match(_gguf_variant_stem(filename))+ if not match and "/" in filename:+ for segment in reversed(filename.rsplit("/", 1)[0].split("/")):+ parent_match = _select_known_quant_match(segment)+ if parent_match:+ match = parent_match+ break+ return f"{match.group(1) or ''}{match.group(2)}" if match else None+++def _gguf_variant_family(filename: str) -> str:+ stem = _gguf_variant_stem(filename)+ if "/" not in filename:+ return stem or "gguf"+ parents = filename.rsplit("/", 1)[0].strip("/")+ return f"{parents}/{stem}" if parents and stem else stem or "gguf"+++def _gguf_bpw_suffix(filename: str) -> str:+ """``-3.53bpw`` from whichever path segment names the quant, else ``""``.++ MIRROR of ``hub.utils.gguf._gguf_bpw_suffix``; see ``_gguf_variant_key``. The quant-directory+ layout carries the modifier upstairs (``IQ4_XS-3.53bpw/model.gguf``), so the basename alone+ gave both bpw builds one key. The walk stops at the segment that named the quant.+ """+ path = filename.replace("\\", "/")+ parents = path.rpartition("/")[0]+ for segment in (_gguf_variant_family(path).rsplit("/", 1)[-1], *reversed(parents.split("/"))):+ if not segment:+ continue+ match = re.search(r"-[0-9]+(?:\.[0-9]+)?bpw$", segment, re.IGNORECASE)+ if match:+ return match.group(0)+ if _select_known_quant_match(segment) is not None:+ return ""+ return ""+++def _gguf_variant_key(filename: str) -> str:+ """MIRROR of ``hub.utils.gguf.gguf_variant_key``; utils cannot import hub.++ The two must change in lockstep: the hub builds the picker rows with its copy+ and this one decides which file a chosen row loads, so a disagreement is a row+ that resolves to another checkpoint's weights.+ ``tests/test_gguf_variant_rows.py`` asserts they agree.+ """+ path = filename.replace("\\", "/")+ quant = _gguf_variant_token(path)+ if quant is None:+ return _gguf_variant_family(path)+ for segment in path.rpartition("/")[0].split("/"):+ # A quant-named directory adds nothing the basename does not already say; a+ # directory naming something else is a different checkpoint and qualifies.+ if segment and _select_known_quant_match(segment) is None:+ return _gguf_variant_family(path)+ # ... and the bpw modifier stays on, so two builds of one base quant keep two identities.+ return f"{quant}{_gguf_bpw_suffix(path)}"+++def _qualified_variant_name(filename: str, label: str) -> str:+ """The name these listers advertise for *filename*, given its quant *label*.++ The path-qualified key when a recognised quant token is qualified by a non-quant directory,+ because there the label alone names several checkpoints at once and the consumers reading+ these listers -- the /v1 local index, the remote VRAM preflight -- would never see the row+ they are asked for.++ The label everywhere else, including a bare quant at the repo root and a file with no+ recognised quant token at all. This+ module's label for those is the last hyphenated segment while the variant key is the whole+ stem, and that difference is old, deliberate elsewhere, and nothing to do with several+ checkpoints sharing a quant. Changing it here would rename every such row and break the pins+ that hold them (``Qwen3.6-27B-MTP-001-of-002.gguf`` is listed as ``MTP``).+ """+ if _gguf_variant_token(filename) is None:+ return label+ key = _gguf_variant_key(filename)+ # Only a PATH-qualified key. Without the slash the key is the bare quant token, and this+ # module's label is the richer of the two: it carries the bpw modifier that keeps+ # ``model-IQ4_XS-3.53bpw.gguf`` and ``model-IQ4_XS-3.97bpw.gguf`` separately selectable, which+ # the token extractor drops. Swapping in the token would merge them.+ return key if "/" in key else label++def _is_big_endian_gguf_path(path: str, quant: str = "") -> bool:normalized = path.replace("\\", "/")name = normalized.rsplit("/", 1)[-1]@@ -2471,8 +2576,8 @@ def list_gguf_variants(variants: list[GgufVariantInfo] = []has_vision = False- quant_totals: dict[str, int] = {} # quant -> total bytes- quant_first_file: dict[str, str] = {} # quant -> first filename (display)+ # (name, quant, size); grouped per shard FAMILY below, not summed across copies.+ main_files: list[tuple[str, str, int]] = []for sibling in info.siblings:fname = sibling.rfilename@@ -2488,17 +2593,15 @@ def list_gguf_variants(if _is_mtp_drafter(fname):continue- quant = _extract_quant_label(fname)- if _is_big_endian_gguf_path(fname, quant):+ label = _extract_quant_label(fname)+ if _is_big_endian_gguf_path(fname, label):continue- quant_totals[quant] = quant_totals.get(quant, 0) + size- if quant not in quant_first_file:- quant_first_file[quant] = fname+ main_files.append((fname, _qualified_variant_name(fname, label), size))- for quant, total_size in quant_totals.items():+ for quant, (first_file, total_size) in _group_gguf_variant_files(main_files).items():variants.append(GgufVariantInfo(- filename = quant_first_file[quant],+ filename = first_file,quant = quant,size_bytes = total_size,)@@ -2510,6 +2613,29 @@ def list_gguf_variants(return variants, has_vision+def _group_gguf_variant_files(entries: list[tuple[str, str, int]]) -> dict[str, tuple[str, int]]:+ """``quant -> (first filename, size of that quant's shard family)``.++ MIRROR of ``hub.utils.gguf.group_gguf_variant_files`` over ``(name, quant, size)`` triples.+ Sizes are summed across the shards of ONE family, never across families: a repo shipping the+ same quant twice (QwQ-32B's BF16 as ``QwQ-32B-BF16-*`` beside ``QwQ-32B.BF16-*``) would+ otherwise charge both copies to a row the loader only ever opens one of, and+ ``routes/inference.py`` bills this ``size_bytes`` to the VRAM guard, which then refuses a load+ that fits. The family kept is the one holding the lexicographically first file, which is the+ shard this lister advertises and the loader opens.+ """+ families: dict[str, dict[str, list[tuple[str, int]]]] = {}+ for name, quant, size in entries:+ families.setdefault(quant, {}).setdefault(_gguf_variant_family(name), []).append(+ (name, int(size or 0))+ )+ grouped: dict[str, tuple[str, int]] = {}+ for quant, by_family in families.items():+ chosen = min(by_family.values(), key = lambda members: min(n for n, _ in members))+ grouped[quant] = (min(n for n, _ in chosen), sum(s for _, s in chosen))+ return grouped++def _resolve_gguf_dir(p: Path) -> Optional[Path]:"""Resolve a path to the directory containing GGUF variants.@@ -2551,8 +2677,7 @@ def list_local_gguf_variants(else _registered_custom_model_root(directory))- quant_totals: dict[str, int] = {}- quant_first_file: dict[str, str] = {}+ main_files: list[tuple[str, str, int]] = []has_vision = False# Recurse so variant-specific subdirs (``BF16/...gguf``) are picked up. Result filenames@@ -2569,20 +2694,18 @@ def list_local_gguf_variants(rel = f.relative_to(p).as_posix()if _is_local_mtp_drafter(f, root, rel):continue- quant = _extract_quant_label(rel)- if _is_big_endian_gguf_path(rel, quant):+ label = _extract_quant_label(rel)+ if _is_big_endian_gguf_path(rel, label):continue- quant_totals[quant] = quant_totals.get(quant, 0) + size- if quant not in quant_first_file:- quant_first_file[quant] = rel+ main_files.append((rel, _qualified_variant_name(rel, label), size))variants = [GgufVariantInfo(- filename = quant_first_file[q],- quant = q,- size_bytes = s,+ filename = first_file,+ quant = quant,+ size_bytes = total_size,)- for q, s in quant_totals.items()+ for quant, (first_file, total_size) in _group_gguf_variant_files(main_files).items()]variants.sort(key = lambda v: -v.size_bytes)return variants, has_vision@@ -2656,6 +2779,7 @@ def _find_local_gguf_by_variant(# Recurse so variants under a quant-named subdir (``BF16/foo-BF16-00001-of-00002.gguf``)# are found. Match the relative path so the quant label can come from the dir name.matches = []+ owned = []for f in _iter_gguf_files(p, recursive = True):rel = f.relative_to(p).as_posix()if _is_mmproj(f.name) or _is_local_mtp_drafter(f, root, rel):@@ -2675,7 +2799,15 @@ def _find_local_gguf_by_variant() or _is_big_endian_gguf_path(rel, quant):continuematches.append(f)+ # A repo holding several checkpoints at one quant offers a row per checkpoint,+ # and only one of them is this variant's. Name order alone would hand a request+ # for the repo-root ``Q6_K`` the alphabetically earlier ``distilled/`` copy.+ if _variant_matches(variant, _gguf_variant_key(rel)):+ owned.append(f)matches.sort()+ owned.sort()+ if owned:+ return str(_local_gguf_load_path(owned[0]))if matches:return str(_local_gguf_load_path(matches[0]))return None@@ -3482,6 +3614,12 @@ class ModelConfig:is_lora = False,is_gguf = True,gguf_file = gguf_file,+ # The identity the CALLER asked for, carried through. Dropping it left the+ # load intent with no variant, so llama.cpp recorded the bare label off the+ # filename: /status named the root row for a qualified checkpoint, and the+ # deletion guard compared that bare label against the selected key and let+ # the delete through.+ gguf_variant = gguf_variant,gguf_mmproj_file = mmproj_file,gguf_mtp_file = mtp_file,gguf_dspark_file = dspark_file,@@ -3532,10 +3670,23 @@ class ModelConfig:f"Available variants: {available}")if not variant: # auto-select best quant- variant_filenames = [v.filename for v in variants]+ # ROOT rows when there are any. _pick_best_gguf keeps whichever filename it+ # met first among equals, so an LTX-style listing that puts distilled/...-Q6_K+ # before the root ...-Q6_K made a bare repo id load the distilled checkpoint --+ # while local_model_resolver, the auto-download map and /gguf-variants all+ # define a bare id as the root. This is the LOAD path, so it has to agree.+ root_rows = [+ v.filename+ for v in variants+ if "/" not in _qualified_variant_name(v.filename, v.quant)+ ]+ variant_filenames = root_rows or [v.filename for v in variants]best = _pick_best_gguf(variant_filenames)if best:- variant = _extract_quant_label(best)+ # The SAME identity the lister advertised for that file. Converting the+ # winner back to a bare label handed the load a name several checkpoints+ # answer to, and it then resolved whichever sorted first.+ variant = _qualified_variant_name(best, _extract_quant_label(best))else:variant = "Q4_K_M" # Fallback — llama-server's own defaultdiff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex ac5e94113bf..ba5f6a3dec9 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -134,7 +134,10 @@ export interface ValidateModelResponse {export interface GgufVariantDetail {filename: string;+ /** Selection identity. Path-qualified when a repo holds several checkpoints at one quant. */quant: string;+ /** What to SHOW for `quant` ("Q6_K · distilled"); absent when the key already reads as a label. */+ display_label?: string | null;size_bytes: number;download_size_bytes?: number;downloaded?: boolean;diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex b2ad1ac3123..97ef8e91429 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -40,6 +40,7 @@ import {TrainIcon,TransportConflictDialog,deleteCachedModel,+ ggufVariantDisplayLabel,invalidateGgufVariantsCache,listGgufVariants as listGgufVariantsCached,useGgufVariantsCacheVersions,@@ -1435,7 +1436,10 @@ function GgufVariantExpander({<spanclassName={cn(oom && "!text-gray-500 dark:!text-gray-400")}>- {v.quant}+ {/* The key is the selection identity and can be path-qualified+ ("distilled/ltx-2.3-22b-distilled-Q6_K"); the label is what that reads+ as ("Q6_K · distilled"). Everything below still keys on v.quant. */}+ {ggufVariantDisplayLabel(v)}</span>{unusableLocal ? (<span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">diff --git a/studio/frontend/src/features/recipe-studio/dialogs/models/local-recipe-model-selector.tsx b/studio/frontend/src/features/recipe-studio/dialogs/models/local-recipe-model-selector.tsxindex 48229ecdccc..92f6da47951 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/models/local-recipe-model-selector.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/models/local-recipe-model-selector.tsx@@ -19,6 +19,7 @@ import {import { cn } from "@/lib/utils";import { Link } from "@tanstack/react-router";import { ChevronDownIcon, ChevronRightIcon, RefreshCwIcon } from "lucide-react";+import { ggufVariantDisplayLabel } from "@/features/hub";import {type ComponentPropsWithoutRef,type ReactElement,@@ -207,7 +208,10 @@ function LocalGgufVariantList({)}><span className="min-w-0 flex-1 truncate font-mono">- {variant.quant}+ {/* The key is the selection identity and can be path-qualified+ ("distilled/ltx-2.3-22b-distilled-Q6_K"); the label is what it reads as.+ onSelect and the recommended check still key on variant.quant. */}+ {ggufVariantDisplayLabel(variant)}</span>{variant.quant === defaultVariant ? (<Badge variant="secondary" className="h-4 px-1.5 text-ui-10">diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsxindex 00eb87146f2..9c36b11f5da 100644--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx@@ -54,6 +54,7 @@ import {import { SettingsSection } from "../components/settings-section";import { psSingle, shSingle } from "../components/usage-examples";import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";+import { ggufVariantDisplayLabel } from "@/features/hub";const DOCS_URL = "https://unsloth.ai/docs/integrations/unsloth-start";const EXAMPLE_MODEL_REPO = "unsloth/gemma-4-E4B-it-GGUF";@@ -1473,7 +1474,14 @@ export function AgentsTab() {: t("settings.agents.noQuantizations")}>- {selectedVariant}+ {/* The closed trigger is where the choice is READ, so it shows the label+ too; SelectValue renders this instead of the raw item text. The value+ bound to the Select is still the key. */}+ {ggufVariantDisplayLabel(+ variants.find((v) => v.quant === selectedVariant) ?? {+ quant: selectedVariant ?? "",+ },+ )}</SelectValue></SelectTrigger><SelectContent align="start" className="min-w-[16rem]">@@ -1492,7 +1500,9 @@ export function AgentsTab() {className="[&>span:last-child]:w-full [&>span:last-child]:justify-between"><span className="font-mono text-xs whitespace-nowrap">- {variant.quant}+ {/* The key is the selection identity and can be path-qualified; the+ label is what it reads as. The SelectItem value stays the key. */}+ {ggufVariantDisplayLabel(variant)}</span>{size ? (<span className="text-ui-10 whitespace-nowrap text-muted-foreground">diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex a66ea392b4f..9975a0ee227 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -2257,7 +2257,11 @@ def test_a_standalone_gguf_has_one_settings_key():common = _read_backend("hub/services/models/common.py")# The rule this mirrors: a variant is derived only for a single scanned file.- assert "extract_quant_label(gguf_files[0].name)" in common+ # gguf_variant_key, not the hub's extract_quant_label: for a standalone file there is no+ # directory to qualify, so the key IS the quant token -- and it keeps the bpw modifier, which+ # is what makes it agree with the loader's own _extract_quant_label (the equality the sibling+ # test below depends on). The hub label drops that modifier.+ assert "gguf_variant_key(gguf_files[0].name)" in commonassert "if scan_path.is_file() and len(gguf_files) == 1" in common