Skip to content

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.

Read the bpw modifier where the quant token was found, not anywhere in the name (#8255)

Daniel Hande5ba0614e8a
diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.py
index 82c0e0b4233..f2cb0936577 100644
--- a/studio/backend/hub/services/models/deletion.py
+++ b/studio/backend/hub/services/models/deletion.py
@@ -20,6 +20,7 @@ from hub.utils.gguf import (
bare_quant_alias,
extract_quant_token,
gguf_variant_key,
+ quant_token_with_bpw,
is_reclaimable_drafter_path as _is_reclaimable_drafter_path,
)
from hub.utils.hf_cache_state import (
@@ -132,10 +133,13 @@ def _remove_empty_variant_dirs(target_repos: list, variant: str) -> tuple[int, l
"""Remove now-empty ``snapshots/<rev>/<quant>/`` folders for *variant* (the
quant label names the folder); only empty dirs go, so siblings are safe.
Returns (count removed, removal failures other than a concurrent refill)."""
- # 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.
+ # A 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. Qualification
+ # has two shapes: a path (``distilled/...-Q6_K``) and a bpw modifier (``IQ4_XS-3.53bpw``,
+ # whose token-only ``IQ4_XS/`` folder, if it exists, is a different build's).
+ qualified = "/" in variant or (quant_token_with_bpw(variant) or "").lower() == variant.lower()
variant_key = (
- variant.lower() if "/" in variant else (extract_quant_token(variant) or variant).lower()
+ variant.lower() if qualified else (extract_quant_token(variant) or variant).lower()
)
removed = 0
failures: list[str] = []
@@ -159,7 +163,7 @@ def _remove_empty_variant_dirs(target_repos: list, variant: str) -> tuple[int, l
try:
if sub.is_symlink() or not sub.is_dir():
continue
- folder_quant = extract_quant_token(sub.name)
+ folder_quant = quant_token_with_bpw(sub.name)
matches = (
folder_quant is not None and folder_quant.lower() == variant_key
) or sub.name.lower() == variant.lower()
diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.py
index 56b568ca735..fc4886df4b7 100644
--- a/studio/backend/hub/utils/gguf.py
+++ b/studio/backend/hub/utils/gguf.py
@@ -263,16 +263,38 @@ def _select_quant_match(text: str) -> Optional[re.Match]:
return fallback
-def extract_quant_token(filename: str) -> Optional[str]:
- stem = _gguf_stem(filename)
+def _quant_search_stem(filename: str) -> str:
+ """The text a quant token is looked for in: the basename, less any shard suffix.
+
+ Unlike :func:`_gguf_stem` this keeps everything after the last dot. The extension is not in
+ the way, since the token is matched rather than the whole string, while cutting at the dot
+ truncates a bare ``IQ4_XS-3.53bpw`` to ``IQ4_XS-3``. Bare names do arrive here: a ``<quant>/``
+ folder and a stored variant string both come without ``.gguf``.
+ """
+ return _GGUF_SPLIT_SUFFIX_RE.sub("", filename.rsplit("/", 1)[-1]).strip()
+
+
+def _locate_quant_match(filename: str) -> tuple[Optional[re.Match], str]:
+ """The quant match naming *filename*, with the text it was found in.
+
+ The basename decides; only when it names no quant do parent directories, nearest first.
+ Callers that need what trails the token (the bpw modifier) need that text too, so this is
+ the one place the search order lives.
+ """
+ stem = _quant_search_stem(filename)
match = _select_quant_match(stem)
- if not match and "/" in filename:
- parents = filename.rsplit("/", 1)[0]
- for segment in reversed(parents.split("/")):
+ if match:
+ return match, stem
+ if "/" in filename:
+ for segment in reversed(filename.rsplit("/", 1)[0].split("/")):
parent_match = _select_quant_match(segment)
if parent_match:
- match = parent_match
- break
+ return parent_match, segment
+ return None, ""
+
+
+def extract_quant_token(filename: str) -> Optional[str]:
+ match, _ = _locate_quant_match(filename)
if match:
prefix = match.group(1) or ""
return f"{prefix}{match.group(2)}"
@@ -284,28 +306,48 @@ def extract_quant_token(filename: str) -> Optional[str]:
# 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)
+#
+# Applied with ``match`` against the text that follows the token, never ``search``: only a
+# modifier IMMEDIATELY after the quant qualifies it, so ``flux1-dev-Q8_0-fp32-08.577bpw`` keeps
+# the bare ``Q8_0`` rather than borrowing a number that describes something else in the name.
+_GGUF_BPW_SUFFIX_RE = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw", re.IGNORECASE)
+
+# The same modifier ending a name of its own, with or without the extension still on it. Used
+# only for the basename under a quant DIRECTORY (``Q6_K/model-3.5bpw.gguf``), where the token is
+# in the parent and the number is all the file has to say which build it is.
+_GGUF_BPW_TRAILING_RE = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw(?=\.[A-Za-z0-9]+$|$)", re.IGNORECASE)
+
+
+def quant_token_with_bpw(filename: str) -> Optional[str]:
+ """:func:`extract_quant_token` with the bpw modifier that trails it, when there is one.
+ The spelling that identifies a checkpoint. The bare token does not: a repo publishing one
+ base quant at several bit widths gives every one of them the same token, and the modifier is
+ the only thing telling them apart.
-def _gguf_bpw_suffix(filename: str) -> str:
- """``-3.53bpw`` from whichever path segment names the quant, else ``""``.
+ Where the modifier is found follows where the token was. Named by the basename, only a
+ modifier IMMEDIATELY after it counts, so ``flux1-dev-Q8_0-fp32-08.577bpw`` keeps the bare
+ ``Q8_0`` rather than borrowing a number describing something else. Named by a parent
+ directory, the modifier may sit against the token there (``IQ4_XS-3.53bpw/model.gguf``) or
+ end the basename instead (``Q6_K/model-3.5bpw.gguf``), and both are this build's own.
- 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.
+ Returns the bare token unchanged for every repo without one, which is nearly all of them,
+ and ``None`` when nothing in the path names a quant.
"""
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 ""
+ match, text = _locate_quant_match(path)
+ if match is None:
+ return None
+ token = f"{match.group(1) or ''}{match.group(2)}"
+ adjacent = _GGUF_BPW_SUFFIX_RE.match(text[match.end() :])
+ if adjacent:
+ return f"{token}{adjacent.group(0)}"
+ stem = _quant_search_stem(path)
+ if text != stem:
+ trailing = _GGUF_BPW_TRAILING_RE.search(stem)
+ if trailing:
+ return f"{token}{trailing.group(0)}"
+ return token
def _unknown_gguf_variant_key(filename: str) -> str:
@@ -338,10 +380,14 @@ def bare_quant_alias(key: str) -> str:
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)}"
+ basename = (key or "").replace("\\", "/").rsplit("/", 1)[-1]
+ token = quant_token_with_bpw(basename)
+ if token is not None:
+ return token
+ # Nothing in the name is a quant, so the alias is the unknown-variant spelling. That one
+ # still re-stems, and a key arrives already extension-stripped, so hand it an extension to
+ # strip rather than let it cut at the dot in "ltx-2.3".
+ return extract_quant_label(f"{basename}.gguf")
def _is_quant_directory(segment: str) -> bool:
@@ -373,13 +419,13 @@ def gguf_variant_key(filename: str) -> str:
set would disagree between them and strand a finished download as incomplete.
"""
path = filename.replace("\\", "/")
- quant = extract_quant_token(path)
+ quant = quant_token_with_bpw(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)}"
+ return quant
def _variant_scope_label(filename: str, *, with_stem: bool = False) -> str:
@@ -407,8 +453,7 @@ def _apply_gguf_display_labels(variants: list[GgufVariantInfo]) -> None:
# ("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)}"
+ return quant_token_with_bpw(variant.filename)
qualified = [
variant
@@ -496,7 +541,11 @@ def iter_hf_cache_snapshots(repo_id: str, root: Optional[Path] = None):
def list_empty_gguf_variant_dirs(repo_id: str, root: Optional[Path] = None) -> set[str]:
"""Quant labels present only as an EMPTY snapshot ``<quant>/`` folder (an
- interrupted split download); a quant with shards in any snapshot is excluded."""
+ interrupted split download); a quant with shards in any snapshot is excluded.
+
+ Labelled the way a row is keyed, bpw modifier included, or an empty ``IQ4_XS-3.53bpw/``
+ folder would be reported against a bare ``IQ4_XS`` row that does not exist while the row
+ it belongs to reads as absent."""
empty: dict[str, str] = {}
nonempty: set[str] = set()
snapshots = (
@@ -513,7 +562,7 @@ def list_empty_gguf_variant_dirs(repo_id: str, root: Optional[Path] = None) -> s
try:
if sub.is_symlink() or not sub.is_dir():
continue
- quant = extract_quant_token(sub.name)
+ quant = quant_token_with_bpw(sub.name)
if not quant:
continue
has_child = any(sub.iterdir())
diff --git a/studio/backend/tests/test_gguf_bpw_variant_rows.py b/studio/backend/tests/test_gguf_bpw_variant_rows.py
new file mode 100644
index 00000000000..bf6b3e368bd
--- /dev/null
+++ b/studio/backend/tests/test_gguf_bpw_variant_rows.py
@@ -0,0 +1,319 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A base quant published at several bit widths is several variants.
+
+``byteshape/Llama-3.1-8B-Instruct-GGUF`` ships 18 GGUFs at four base quants, telling
+them apart with a bits-per-weight modifier the loader's label has always kept and the
+hub's dropped (``Llama-3.1-8B-Instruct-IQ3_S-2.54bpw.gguf`` through ``-3.31bpw``).
+Every file sits in the repo root, so there is no directory to qualify the key by, and
+keying on the bare token folded 18 checkpoints into 4 rows: 14 of them unselectable,
+each row advertising one file's size while the download plan fetched a different one.
+
+The modifier therefore belongs to the key. Repos without one must key exactly as
+before, and a genuinely split GGUF must still collapse its shards into one row, so
+both are pinned here alongside.
+"""
+
+from __future__ import annotations
+
+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,
+ extract_quant_token,
+ gguf_variant_family,
+ gguf_variant_key,
+ group_gguf_variant_files,
+ list_local_gguf_variants,
+ quant_token_with_bpw,
+)
+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,
+)
+
+# Live listing of byteshape/Llama-3.1-8B-Instruct-GGUF, one base quant's worth.
+BPW_FILES = [
+ ("Llama-3.1-8B-Instruct-IQ4_XS-3.57bpw.gguf", 3_587_540_000),
+ ("Llama-3.1-8B-Instruct-IQ4_XS-3.94bpw.gguf", 3_958_211_616),
+ ("Llama-3.1-8B-Instruct-IQ4_XS-4.05bpw.gguf", 4_069_393_440),
+]
+
+# One bpw variant, split across shards, which must stay one row.
+BPW_SHARDED_FILES = [
+ ("IQ4_XS-3.57bpw/model-IQ4_XS-3.57bpw-00001-of-00002.gguf", 40),
+ ("IQ4_XS-3.57bpw/model-IQ4_XS-3.57bpw-00002-of-00002.gguf", 25),
+]
+
+
+class _Sibling:
+ def __init__(self, rfilename: str, size: int) -> None:
+ self.rfilename = rfilename
+ self.size = size
+ self.lfs = {"sha256": f"hash-of-{rfilename}"}
+
+
+def _materialize(root, files):
+ for path, _ in files:
+ target = root / path
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_bytes(b"x" * 512)
+ (root / "config.json").write_text("{}")
+ return root
+
+
+# --------------------------------------------------------------------------------------
+# The key itself
+# --------------------------------------------------------------------------------------
+
+
+ "path,expected",
+ [
+ # The modifier trailing the quant token is part of the token.
+ ("Llama-3.1-8B-Instruct-IQ3_S-2.54bpw.gguf", "IQ3_S-2.54bpw"),
+ ("Llama-3.1-8B-Instruct-IQ3_S-3.31bpw.gguf", "IQ3_S-3.31bpw"),
+ ("Qwen-Image-2512-Q6_K-6.61bpw.gguf", "Q6_K-6.61bpw"),
+ # Integer widths and an uppercase spelling both occur on the Hub.
+ ("Step-3.5-Flash-IQ3_S-3BPW.gguf", "IQ3_S-3BPW"),
+ # Shard suffix is stripped first, so every shard keys alike.
+ ("model-IQ4_XS-3.57bpw-00001-of-00002.gguf", "IQ4_XS-3.57bpw"),
+ # The modifier can live on the directory instead, when the basename has no quant.
+ ("IQ4_XS-3.53bpw/model.gguf", "IQ4_XS-3.53bpw"),
+ # A modifier that does not trail the token is not part of it: it belongs to
+ # something else in the name and cannot be relied on to identify the file.
+ ("flux1-dev-Q8_0-fp32-08.577bpw.gguf", "Q8_0"),
+ # No modifier at all: the historical key, unchanged.
+ ("Wan2.2-TI2V-5B-Q8_0.gguf", "Q8_0"),
+ ("BF16/DeepSeek-R1-BF16-00001-of-00003.gguf", "BF16"),
+ ],
+)
+def test_bpw_variant_key(path, expected):
+ assert gguf_variant_key(path) == expected
+
+
+def test_key_is_unchanged_where_there_is_no_modifier():
+ """The persisted variant identity must not churn for the repos that have no bpw
+ modifier, which is all but a handful on the whole Hub."""
+ 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",
+ "MXFP4_MOE/model-MXFP4_MOE-00001-of-00003.gguf",
+ ):
+ assert gguf_variant_key(path) == extract_quant_label(path)
+ assert quant_token_with_bpw(path) == extract_quant_token(path)
+
+
+def test_a_bare_bpw_name_is_not_truncated_at_its_decimal_point():
+ """Folder names and stored variant strings arrive without a ``.gguf`` extension, and
+ cutting at the last dot would leave ``IQ4_XS-3``, silently dropping the modifier and
+ keying the folder as the bare quant again."""
+ assert quant_token_with_bpw("IQ4_XS-3.53bpw") == "IQ4_XS-3.53bpw"
+ assert quant_token_with_bpw("Llama-3.1-8B-Instruct-IQ4_XS-3.57bpw") == "IQ4_XS-3.57bpw"
+ assert quant_token_with_bpw("Q6_K") == "Q6_K"
+
+
+def test_an_interrupted_bpw_folder_is_labelled_like_its_row(tmp_path):
+ """An empty ``<quant>/`` folder marks a variant partial. Labelled by the bare token it
+ would mark a row that no longer exists, and the real one would read as absent."""
+ from hub.utils.gguf import list_empty_gguf_variant_dirs
+
+ snapshot = tmp_path / "models--acme--m" / "snapshots" / "rev"
+ (snapshot / "IQ4_XS-3.57bpw").mkdir(parents = True)
+ assert list_empty_gguf_variant_dirs("acme/m", root = tmp_path) == {"IQ4_XS-3.57bpw"}
+
+
+def test_files_at_one_base_quant_do_not_share_a_key():
+ assert len({gguf_variant_key(path) for path, _ in BPW_FILES}) == len(BPW_FILES)
+ assert {extract_quant_token(path) for path, _ in BPW_FILES} == {"IQ4_XS"}
+
+
+def test_shards_of_one_bpw_variant_share_a_key_and_a_family():
+ assert {gguf_variant_key(path) for path, _ in BPW_SHARDED_FILES} == {"IQ4_XS-3.57bpw"}
+ assert len({gguf_variant_family(path) for path, _ in BPW_SHARDED_FILES}) == 1
+
+
+def test_loader_mirror_agrees_on_bpw_labels():
+ """``model_config._gguf_variant_token`` is a copy of ``quant_token_with_bpw``; drift
+ means a row keyed one way and loaded another. The loader's own label already carried
+ the modifier, which is the divergence this closes."""
+ corpus = [path for path, _ in (*BPW_FILES, *BPW_SHARDED_FILES)] + [
+ "Llama-3.1-8B-Instruct-IQ3_S-2.54bpw.gguf",
+ "Step-3.5-Flash-IQ3_S-3BPW.gguf",
+ "IQ4_XS-3.53bpw/model.gguf",
+ "flux1-dev-Q8_0-fp32-08.577bpw.gguf",
+ "Reflection-70b-PreciseQuant-6bpw.gguf",
+ "Wan2.2-TI2V-5B-Q8_0.gguf",
+ "distilled/ltx-2.3-22b-distilled-Q6_K.gguf",
+ # Bare names, as a <quant>/ folder and a stored variant string arrive.
+ "IQ4_XS-3.53bpw",
+ "Llama-3.1-8B-Instruct-IQ4_XS-3.57bpw",
+ "Q6_K",
+ ]
+ assert [_gguf_variant_key(p) for p in corpus] == [gguf_variant_key(p) for p in corpus]
+ for path, _ in BPW_FILES:
+ assert _extract_quant_label(path) == gguf_variant_key(path)
+
+
+# --------------------------------------------------------------------------------------
+# Rows
+# --------------------------------------------------------------------------------------
+
+
+def test_each_bit_width_gets_its_own_row_at_its_own_size():
+ rows = group_gguf_variant_files(BPW_FILES)
+ assert len(rows) == 3
+ assert {key: size for key, (_, size) in rows.items()} == {
+ "IQ4_XS-3.57bpw": 3_587_540_000,
+ "IQ4_XS-3.94bpw": 3_958_211_616,
+ "IQ4_XS-4.05bpw": 4_069_393_440,
+ }
+
+
+def test_bpw_shards_stay_one_row_summing_to_the_whole_file():
+ rows = group_gguf_variant_files(BPW_SHARDED_FILES)
+ assert list(rows) == ["IQ4_XS-3.57bpw"]
+ assert rows["IQ4_XS-3.57bpw"] == (BPW_SHARDED_FILES[0][0], 65)
+
+
+def test_local_lister_matches_the_remote_shape(tmp_path):
+ snapshot = _materialize(tmp_path / "snap", BPW_FILES)
+ variants, _ = list_local_gguf_variants(str(snapshot))
+ assert sorted(v.quant for v in variants) == sorted(
+ gguf_variant_key(path) for path, _ in BPW_FILES
+ )
+ assert all(v.size_bytes == 512 for v in variants)
+
+
+def test_a_bpw_row_reads_as_its_own_quant_and_needs_no_scope_suffix():
+ """``IQ4_XS-3.57bpw`` is the label byteshape publishes and the loader reports, so it
+ is showable as it stands. Only a key qualified by a path needs a second name."""
+ variants = [
+ GgufVariantInfo(filename = path, quant = gguf_variant_key(path), size_bytes = 1)
+ for path, _ in BPW_FILES
+ ]
+ _apply_gguf_display_labels(variants)
+ assert {v.display_label for v in variants} == {None}
+
+
+# --------------------------------------------------------------------------------------
+# 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 BPW_FILES:
+ key = gguf_variant_key(path)
+ owned = [other for other, _ in BPW_FILES if is_main_gguf_variant_path(other, key)]
+ assert owned == [path], key
+
+
+def test_download_plan_fetches_one_bit_width_not_three():
+ plans = build_gguf_variant_plans([_Sibling(path, size) for path, size in BPW_FILES])
+ assert len(plans) == 3
+ for path, size in BPW_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_bpw_variant():
+ plans = build_gguf_variant_plans([_Sibling(p, s) for p, s in BPW_SHARDED_FILES])
+ assert list(plans) == ["iq4_xs-3.57bpw"]
+ assert plans["iq4_xs-3.57bpw"].main_filenames == frozenset(p for p, _ in BPW_SHARDED_FILES)
+ assert plans["iq4_xs-3.57bpw"].main_size_bytes == 65
+
+
+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 = _materialize(tmp_path / "snap", BPW_FILES)
+ 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_bit_width(tmp_path):
+ snapshot = _materialize(tmp_path / "snap", BPW_FILES)
+ for path, _ in BPW_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 BPW_FILES], key) == [path]
+
+
+def test_llama_cpp_hands_over_every_shard_of_one_bit_width():
+ paths = [path for path, _ in BPW_SHARDED_FILES]
+ assert _gguf_files_for_variant(paths, "iq4_xs-3.57bpw") == paths
+
+
+def test_delete_removes_only_the_chosen_bit_width(tmp_path):
+ from routes.models import _delete_gguf_variant_files
+
+ snapshot = _materialize(tmp_path / "snap", BPW_FILES)
+ count, _ = _delete_gguf_variant_files(snapshot, "IQ4_XS-3.94bpw")
+ assert count == 1
+ assert not (snapshot / "Llama-3.1-8B-Instruct-IQ4_XS-3.94bpw.gguf").exists()
+ assert (snapshot / "Llama-3.1-8B-Instruct-IQ4_XS-3.57bpw.gguf").exists()
+ assert (snapshot / "Llama-3.1-8B-Instruct-IQ4_XS-4.05bpw.gguf").exists()
+
+
+def test_empty_folder_cleanup_takes_only_the_variants_own_folder(tmp_path):
+ """Cleanup after a delete removes the emptied ``<quant>/`` folder. A bpw key owns
+ ``IQ4_XS-3.57bpw/`` and nothing else; reducing it to its bare token would take a
+ sibling row's ``IQ4_XS/`` with it."""
+ from hub.services.models.deletion import _remove_empty_variant_dirs
+
+ snapshot = tmp_path / "repo" / "snapshots" / "rev"
+ for folder in ("IQ4_XS", "IQ4_XS-3.57bpw", "model-IQ4_XS-3.57bpw", "IQ4_XS-3.94bpw"):
+ (snapshot / folder).mkdir(parents = True)
+
+ class _Repo:
+ repo_path = str(tmp_path / "repo")
+
+ # Both spellings of this variant's own folder go, as they do for a bare quant.
+ removed, failures = _remove_empty_variant_dirs([_Repo()], "IQ4_XS-3.57bpw")
+ assert (removed, failures) == (2, [])
+ assert not (snapshot / "IQ4_XS-3.57bpw").exists()
+ assert not (snapshot / "model-IQ4_XS-3.57bpw").exists()
+ assert (snapshot / "IQ4_XS").is_dir()
+ assert (snapshot / "IQ4_XS-3.94bpw").is_dir()
+
+
+def test_empty_folder_cleanup_still_takes_a_bare_quant_folder(tmp_path):
+ """The unqualified path is unchanged: a plain ``Q6_K`` variant still clears
+ ``Q6_K/`` and the ``<model>-Q6_K/`` spelling of the same quant."""
+ from hub.services.models.deletion import _remove_empty_variant_dirs
+
+ snapshot = tmp_path / "repo" / "snapshots" / "rev"
+ for folder in ("Q6_K", "model-Q6_K", "Q4_K_M"):
+ (snapshot / folder).mkdir(parents = True)
+
+ class _Repo:
+ repo_path = str(tmp_path / "repo")
+
+ removed, failures = _remove_empty_variant_dirs([_Repo()], "Q6_K")
+ assert (removed, failures) == (2, [])
+ assert (snapshot / "Q4_K_M").is_dir()
+
+
+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(BPW_FILES)
+ for path, size in BPW_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("IQ4_XS-3.53bpw\\model.gguf") == gguf_variant_key(
+ "IQ4_XS-3.53bpw/model.gguf"
+ )
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 2969c9d4ffe..9851817e0ed 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -2319,14 +2319,37 @@ def _gguf_variant_stem(filename: str) -> str:
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:
+def _quant_search_stem(filename: str) -> str:
+ """The text a quant token is looked for in: the basename, less any shard suffix.
+
+ MIRROR of ``hub.utils.gguf._quant_search_stem``. Unlike ``_gguf_variant_stem`` it keeps
+ everything after the last dot, because cutting there truncates a bare ``IQ4_XS-3.53bpw`` to
+ ``IQ4_XS-3``, and bare names arrive here from ``<quant>/`` folders and stored variant keys.
+ """
+ return _GGUF_SPLIT_SUFFIX_RE.sub("", filename.rsplit("/", 1)[-1]).strip()
+
+
+def _locate_quant_match(filename: str):
+ """The quant match naming *filename*, with the text it was found in.
+
+ MIRROR of ``hub.utils.gguf._locate_quant_match``. The basename decides; only when it names
+ no quant do parent directories, nearest first. Callers that need what trails the token (the
+ bpw modifier) need that text too, so the search order lives in one place.
+ """
+ stem = _quant_search_stem(filename)
+ match = _select_known_quant_match(stem)
+ if match:
+ return match, stem
+ if "/" 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 parent_match, segment
+ return None, ""
+
+
+def _gguf_variant_token(filename: str) -> Optional[str]:
+ match, _ = _locate_quant_match(filename)
return f"{match.group(1) or ''}{match.group(2)}" if match else None
@@ -2338,24 +2361,37 @@ def _gguf_variant_family(filename: str) -> str:
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_RE``. Applied with ``match`` against the text that
+# follows the token, never ``search``: only a modifier IMMEDIATELY after the quant qualifies it,
+# so ``flux1-dev-Q8_0-fp32-08.577bpw`` keeps the bare ``Q8_0``.
+_GGUF_BPW_SUFFIX_RE = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw", re.IGNORECASE)
+
+# MIRROR of ``hub.utils.gguf._GGUF_BPW_TRAILING_RE``: the modifier ending a name of its own,
+# for the basename under a quant DIRECTORY (``Q6_K/model-3.5bpw.gguf``).
+_GGUF_BPW_TRAILING_RE = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw(?=\.[A-Za-z0-9]+$|$)", re.IGNORECASE)
+
- 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.
+def _quant_token_with_bpw(filename: str) -> Optional[str]:
+ """``_gguf_variant_token`` with the bpw modifier that trails it, when there is one.
+
+ MIRROR of ``hub.utils.gguf.quant_token_with_bpw``; see ``_gguf_variant_key``. Where the
+ modifier is found follows where the token was: adjacent to it in the basename, or, when a
+ parent directory named the quant, adjacent to it there or ending the basename instead.
"""
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 ""
+ match, text = _locate_quant_match(path)
+ if match is None:
+ return None
+ token = f"{match.group(1) or ''}{match.group(2)}"
+ adjacent = _GGUF_BPW_SUFFIX_RE.match(text[match.end() :])
+ if adjacent:
+ return f"{token}{adjacent.group(0)}"
+ stem = _quant_search_stem(path)
+ if text != stem:
+ trailing = _GGUF_BPW_TRAILING_RE.search(stem)
+ if trailing:
+ return f"{token}{trailing.group(0)}"
+ return token
def _gguf_variant_key(filename: str) -> str:
@@ -2367,7 +2403,8 @@ def _gguf_variant_key(filename: str) -> str:
``tests/test_gguf_variant_rows.py`` asserts they agree.
"""
path = filename.replace("\\", "/")
- quant = _gguf_variant_token(path)
+ # The bpw modifier stays on, so two builds of one base quant keep two identities.
+ quant = _quant_token_with_bpw(path)
if quant is None:
return _gguf_variant_family(path)
for segment in path.rpartition("/")[0].split("/"):
@@ -2375,8 +2412,7 @@ def _gguf_variant_key(filename: str) -> str:
# 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)}"
+ return quant
def _qualified_variant_name(filename: str, label: str) -> str: