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.

Studio: skip duplicate weight files when downloading a model from the Hub (#11227)

Nilay770f4a4745f2
diff --git a/studio/backend/hub/utils/snapshot_filters.py b/studio/backend/hub/utils/snapshot_filters.py
index 65ea85552f6..39cedef6bcd 100644
--- a/studio/backend/hub/utils/snapshot_filters.py
+++ b/studio/backend/hub/utils/snapshot_filters.py
@@ -3,6 +3,7 @@
from __future__ import annotations
+import re
from fnmatch import fnmatchcase
from typing import Iterable
from utils.paths.path_utils import drop_shadowed_appledouble_names
@@ -17,6 +18,40 @@ SNAPSHOT_IGNORE_PATTERNS: tuple[str, ...] = (
"*.bin.index.json.bak",
)
CONSOLIDATED_PATTERN = "consolidated*"
+DUPLICATE_WEIGHT_FORMAT_PATTERNS: tuple[str, ...] = (
+ "original/*",
+ "metal/*",
+ "coreml/*",
+ "tf_model*.h5",
+ "tf_model.h5.index.json",
+ "flax_model*.msgpack",
+ "flax_model.msgpack.index.json",
+ "rust_model.ot",
+)
+# Resolved per repo, not globbed: a dtype variant is redundant only when the SAME variant ships
+# as safetensors (test_prefetch_snapshot_scope.py::test_variant_keeps_bin_when_only_default_safetensors),
+# and a glob kept whisper-large-v3's pytorch_model.bin.index.fp32.json while dropping its shards.
+# Both shard layouts, since transformers writes the counter-first one (unsloth/models/_utils.py).
+_BIN_WEIGHT_RES = (
+ re.compile(r"pytorch_model(?:\.(?P<variant>[A-Za-z0-9_]+))?(?:[-_][0-9]+-of-[0-9]+)?\.bin"),
+ re.compile(r"pytorch_model[-_][0-9]+-of-[0-9]+\.(?P<variant>[A-Za-z0-9_]+)\.bin"),
+)
+
+
+def _variant_shard_re(variant: str) -> "re.Pattern[str]":
+ v = re.escape(variant)
+ return re.compile(
+ rf"model\.{v}[-_][0-9]+-of-[0-9]+\.safetensors|model[-_][0-9]+-of-[0-9]+\.{v}\.safetensors"
+ )
+
+
+_BIN_INDEX_RE = re.compile(
+ r"pytorch_model(?:\.(?P<pre>[A-Za-z0-9_]+))?\.bin\.index(?:\.(?P<post>[A-Za-z0-9_]+))?\.json"
+)
+# [0-9] rather than \d: Python's \d also matches non-ASCII digits while JavaScript's does not, and the
+# frontend mirror in studio/frontend/src/features/hub/lib/dataset-size.ts has to answer this identically.
+SHARDED_SAFETENSORS_RE = re.compile(r"model[-_][0-9]+-of-[0-9]+\.safetensors")
+SAFETENSORS_INDEX = "model.safetensors.index.json"
SNAPSHOT_WEIGHT_EXTENSIONS = (
".safetensors",
".bin",
@@ -57,11 +92,63 @@ def repo_ships_transformers_weights(filenames: Iterable[str]) -> bool:
return False
+def repo_ships_root_safetensors(filenames: Iterable[str]) -> bool:
+ """Whether a load would find a COMPLETE root safetensors checkpoint.
+
+ Numbered shards are resolved through the index; with none, a load looks for a single
+ file and raises. So one shard is not evidence a checkpoint is there.
+ """
+ names = list(filenames)
+ if any(name == "model.safetensors" for name in names):
+ return True
+ return SAFETENSORS_INDEX in names and any(
+ SHARDED_SAFETENSORS_RE.fullmatch(name) for name in names
+ )
+
+
+def _variant_ships_as_safetensors(names: list[str], variant: str | None) -> bool:
+ """Whether `variant` is already covered by a COMPLETE safetensors checkpoint.
+
+ ``None`` is the canonical one, established by the root-safetensors gate. A named variant
+ needs its own safetensors, and its sharded form needs an index, as the canonical one does.
+ """
+ if variant is None:
+ return True
+ if f"model.{variant}.safetensors" in names:
+ return True
+ # _add_variant puts the variant second-to-last, so this is the only index spelling a
+ # variant load can find; accepting another would drop bins over an index nothing reads.
+ if f"model.safetensors.index.{variant}.json" not in names:
+ return False
+ return any(_variant_shard_re(variant).fullmatch(name) for name in names)
+
+
+def redundant_torch_bin_files(filenames: Iterable[str]) -> list[str]:
+ """The pytorch_model .bin files, and their indexes, a safetensors copy makes redundant."""
+ names = list(filenames)
+ redundant = []
+ for name in names:
+ match = next((m for m in (rx.fullmatch(name) for rx in _BIN_WEIGHT_RES) if m), None)
+ variant = match.group("variant") if match else None
+ if not match:
+ match = _BIN_INDEX_RE.fullmatch(name)
+ if not match:
+ continue
+ variant = match.group("pre") or match.group("post")
+ if _variant_ships_as_safetensors(names, variant):
+ redundant.append(name)
+ return redundant
+
+
def resolve_snapshot_ignore_patterns_for_files(filenames: Iterable[str]) -> list[str]:
names = list(filenames)
ignore = list(SNAPSHOT_IGNORE_PATTERNS)
if repo_ships_transformers_weights(names):
ignore.append(CONSOLIDATED_PATTERN)
+ if repo_ships_root_safetensors(names):
+ ignore.extend(DUPLICATE_WEIGHT_FORMAT_PATTERNS)
+ # Exact names, not globs: fnmatch treats "." literally, so each entry matches only itself.
+ ignore.extend(redundant_torch_bin_files(names))
return ignore
diff --git a/studio/backend/tests/test_embedding_model_resolve.py b/studio/backend/tests/test_embedding_model_resolve.py
index 5bd8ba23f0a..bd45b58a95b 100644
--- a/studio/backend/tests/test_embedding_model_resolve.py
+++ b/studio/backend/tests/test_embedding_model_resolve.py
@@ -433,9 +433,9 @@ def test_sentence_transformers_size_matches_the_full_snapshot_download(monkeypat
lambda repo, files_metadata, token: _types.SimpleNamespace(siblings = siblings),
)
- # The full-snapshot worker keeps configs/tokenizers and both transformer
- # weight formats, while applying its normal GGUF/consolidated exclusions.
- assert settings._hf_snapshot_size("acme/embedder", None) == 270
+ # The full-snapshot worker keeps configs/tokenizers and the safetensors copy, while
+ # applying its normal GGUF/consolidated/duplicate-format exclusions.
+ assert settings._hf_snapshot_size("acme/embedder", None) == 160
def test_explicit_llama_policy_does_not_offer_safetensors(client, monkeypatch):
diff --git a/studio/backend/tests/test_hub_snapshot_duplicate_weight_formats.py b/studio/backend/tests/test_hub_snapshot_duplicate_weight_formats.py
new file mode 100644
index 00000000000..e1c9a33d9f0
--- /dev/null
+++ b/studio/backend/tests/test_hub_snapshot_duplicate_weight_formats.py
@@ -0,0 +1,237 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import types
+
+from hub.utils.snapshot_filters import (
+ resolve_snapshot_ignore_patterns_for_files,
+ snapshot_download_siblings,
+ snapshot_download_size,
+)
+
+
+def _siblings(sizes: dict[str, int]) -> list:
+ return [types.SimpleNamespace(rfilename = name, size = size) for name, size in sizes.items()]
+
+
+def _kept(sizes: dict[str, int]) -> set[str]:
+ return {s.rfilename for s in snapshot_download_siblings(_siblings(sizes))}
+
+
+GPT_OSS = {
+ "config.json": 2,
+ "tokenizer.json": 27,
+ "model.safetensors.index.json": 36,
+ "model-00000-of-00002.safetensors": 4_792,
+ "model-00001-of-00002.safetensors": 4_798,
+ "model-00002-of-00002.safetensors": 4_170,
+ "original/config.json": 1,
+ "original/dtypes.json": 13,
+ "original/model.safetensors": 13_761,
+ "metal/model.bin": 13_750,
+}
+
+# bigscience/bloom shards its root safetensors with an underscore, and ships the same
+# 72 shards again as pytorch_model_000NN-of-00072.bin.
+BLOOM = {
+ "config.json": 2,
+ "tokenizer.json": 14,
+ "model_00001-of-00072.safetensors": 4_900,
+ "model_00002-of-00072.safetensors": 4_900,
+ "model.safetensors.index.json": 1,
+ "pytorch_model_00001-of-00072.bin": 4_900,
+ "pytorch_model_00002-of-00072.bin": 4_900,
+ "pytorch_model.bin.index.json": 1,
+}
+
+WHISPER = {
+ "config.json": 2,
+ "tokenizer.json": 2,
+ "training_args.bin": 3,
+ "model.safetensors": 967,
+ "pytorch_model.bin": 967,
+ "tf_model.h5": 968,
+ "flax_model.msgpack": 967,
+}
+
+
+def test_gpt_oss_downloads_only_the_root_safetensors():
+ assert snapshot_download_size(_siblings(GPT_OSS)) == 2 + 27 + 36 + 4_792 + 4_798 + 4_170
+
+
+def test_whisper_downloads_only_the_safetensors_copy():
+ assert snapshot_download_size(_siblings(WHISPER)) == 2 + 2 + 3 + 967
+ assert "training_args.bin" in _kept(WHISPER)
+
+
+def test_sharded_bin_checkpoint_beside_safetensors_is_skipped():
+ kept = _kept(
+ {
+ "model.safetensors": 100,
+ "pytorch_model-00001-of-00002.bin": 60,
+ "pytorch_model-00002-of-00002.bin": 60,
+ "pytorch_model.bin.index.json": 1,
+ "rust_model.ot": 100,
+ "coreml/model.mlpackage/weights.bin": 100,
+ "tokenizer.bin": 5,
+ "adapter_model.bin": 7,
+ "2_Dense/pytorch_model.bin": 9,
+ }
+ )
+ assert kept == {
+ "model.safetensors",
+ "tokenizer.bin",
+ "adapter_model.bin",
+ "2_Dense/pytorch_model.bin",
+ }
+
+
+def test_sibling_formats_are_kept_without_root_safetensors():
+ bin_only = {
+ "config.json": 2,
+ "pytorch_model.bin": 967,
+ "tf_model.h5": 968,
+ "flax_model.msgpack": 967,
+ "original/consolidated.00.pth": 900,
+ "metal/model.bin": 900,
+ }
+ assert _kept(bin_only) == set(bin_only)
+
+ nested_only = {
+ "unet/diffusion_pytorch_model.safetensors": 100,
+ "adapter_model.safetensors": 10,
+ "pytorch_model.bin": 50,
+ "original/model.safetensors": 50,
+ }
+ assert _kept(nested_only) == set(nested_only)
+ assert "pytorch_model*.bin" not in resolve_snapshot_ignore_patterns_for_files(nested_only)
+
+
+def test_underscore_sharded_safetensors_still_skip_the_bin_copy():
+ assert snapshot_download_size(_siblings(BLOOM)) == 2 + 14 + 4_900 + 4_900 + 1
+ assert _kept(BLOOM) == {
+ "config.json",
+ "tokenizer.json",
+ "model_00001-of-00072.safetensors",
+ "model_00002-of-00072.safetensors",
+ "model.safetensors.index.json",
+ }
+
+
+def test_a_bin_only_dtype_variant_survives():
+ # model.safetensors cannot serve a variant="fp16" load, so the fp16 bin is not a duplicate.
+ bin_only_variant = {
+ "config.json": 2,
+ "model.safetensors": 500,
+ "pytorch_model.bin": 500,
+ "pytorch_model.fp16.bin": 250,
+ }
+ kept = _kept(bin_only_variant)
+ assert "pytorch_model.bin" not in kept
+ assert "pytorch_model.fp16.bin" in kept
+
+ # Once the variant ships as safetensors too, the bin copy IS redundant.
+ both = dict(bin_only_variant, **{"model.fp16.safetensors": 250})
+ assert "pytorch_model.fp16.bin" not in _kept(both)
+
+
+def test_an_indexless_variant_does_not_authorise_dropping_its_bins():
+ # Same rule as the canonical gate, applied per variant: sharded fp16 safetensors with no
+ # fp16 index are not loadable, so the fp16 bin family is still the only usable copy.
+ indexless_variant = {
+ "config.json": 2,
+ "model.safetensors": 500,
+ "model.fp16-00001-of-00002.safetensors": 250,
+ "pytorch_model.bin": 500,
+ "pytorch_model.fp16-00001-of-00002.bin": 250,
+ "pytorch_model.fp16-00002-of-00002.bin": 250,
+ }
+ kept = _kept(indexless_variant)
+ assert "pytorch_model.bin" not in kept
+ assert "pytorch_model.fp16-00001-of-00002.bin" in kept
+
+ # With the variant index the fp16 safetensors family is complete, so the bins go.
+ indexed = dict(indexless_variant, **{"model.safetensors.index.fp16.json": 1})
+ assert not any(n.startswith("pytorch_model") for n in _kept(indexed))
+
+ # transformers' _add_variant writes model.safetensors.index.fp16.json. The other
+ # spelling is not one a variant load can find, so it must not authorise the drop.
+ wrong_index = dict(indexless_variant, **{"model.fp16.safetensors.index.json": 1})
+ assert "pytorch_model.fp16-00001-of-00002.bin" in _kept(wrong_index)
+
+
+def test_both_variant_shard_layouts_are_recognised():
+ # transformers writes model-00001-of-00002.fp16.safetensors (counter first);
+ # unsloth/models/_utils.py::_is_canonical_variant_model_weight_safetensors takes both.
+ counter_first = {
+ "config.json": 2,
+ "model.safetensors": 500,
+ "model-00001-of-00002.fp16.safetensors": 250,
+ "model-00002-of-00002.fp16.safetensors": 250,
+ "model.safetensors.index.fp16.json": 1,
+ "pytorch_model.bin": 500,
+ "pytorch_model-00001-of-00002.fp16.bin": 250,
+ "pytorch_model-00002-of-00002.fp16.bin": 250,
+ }
+ kept = _kept(counter_first)
+ assert not any(n.startswith("pytorch_model") for n in kept), sorted(kept)
+ assert "model-00001-of-00002.fp16.safetensors" in kept
+
+
+def test_a_variant_index_never_outlives_its_shards():
+ # openai/whisper-large-v3's real shape. The fp32 variant ships as safetensors, so the bin
+ # shards go -- and their index must go with them rather than dangle over absent files.
+ whisper = {
+ "config.json": 2,
+ "model.safetensors": 3_090,
+ "model.fp32-00001-of-00002.safetensors": 3_000,
+ "model.fp32-00002-of-00002.safetensors": 3_000,
+ "model.safetensors.index.fp32.json": 1,
+ "pytorch_model.bin": 3_090,
+ "pytorch_model.fp32-00001-of-00002.bin": 3_000,
+ "pytorch_model.fp32-00002-of-00002.bin": 3_000,
+ "pytorch_model.bin.index.fp32.json": 1,
+ }
+ kept = _kept(whisper)
+ assert not any(name.startswith("pytorch_model") for name in kept), sorted(kept)
+ # The safetensors side, including its own variant index, is untouched.
+ assert "model.fp32-00001-of-00002.safetensors" in kept
+ assert "model.safetensors.index.fp32.json" in kept
+
+
+def test_indexless_shards_do_not_open_the_gate():
+ # Numbered shards are resolved through model.safetensors.index.json; with no index a
+ # load falls back to looking for a single file and raises, so the .bin checkpoint here
+ # is the only loadable one and must survive.
+ indexless = {
+ "config.json": 2,
+ "model-00001-of-00002.safetensors": 500,
+ "model-00002-of-00002.safetensors": 500,
+ "pytorch_model.bin": 990,
+ }
+ assert _kept(indexless) == set(indexless)
+ assert "pytorch_model*.bin" not in resolve_snapshot_ignore_patterns_for_files(indexless)
+
+ # The same repo WITH the index is a complete checkpoint, so the bin copy goes.
+ indexed = dict(indexless, **{"model.safetensors.index.json": 1})
+ assert "pytorch_model.bin" not in _kept(indexed)
+
+ # An unsharded model.safetensors needs no index to be loadable.
+ unsharded = {"config.json": 2, "model.safetensors": 500, "pytorch_model.bin": 500}
+ assert "pytorch_model.bin" not in _kept(unsharded)
+
+
+def test_a_non_ascii_shard_number_does_not_open_the_gate():
+ # Python's \d matches non-ASCII digits and JavaScript's does not, so a \d here would
+ # have this repo lose its .bin copy in the backend while the frontend still sized it
+ # in -- the download and the number shown in the Model hub would disagree. Both sides
+ # spell the shard number [0-9] so neither treats these as a root checkpoint.
+ arabic_indic = {
+ "config.json": 2,
+ "model-٠١-of-٠٢.safetensors": 500,
+ "pytorch_model.bin": 500,
+ }
+ assert _kept(arabic_indic) == set(arabic_indic)
+ assert "pytorch_model*.bin" not in resolve_snapshot_ignore_patterns_for_files(arabic_indic)
diff --git a/studio/backend/tests/test_hub_snapshot_filter_frontend_parity.py b/studio/backend/tests/test_hub_snapshot_filter_frontend_parity.py
new file mode 100644
index 00000000000..b342b1db3a5
--- /dev/null
+++ b/studio/backend/tests/test_hub_snapshot_filter_frontend_parity.py
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Guards that dataset-size.ts still mirrors snapshot_filters.py.
+
+The backend decides what snapshot_download fetches, the frontend is a hand-ported copy
+deciding the size shown and the progress denominator, and nothing is shared between them,
+so drift is silent: an advertised size that never matches disk, or a bar stuck below 100%.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from hub.utils.snapshot_filters import DUPLICATE_WEIGHT_FORMAT_PATTERNS
+
+_DATASET_SIZE_TS = (
+ Path(__file__).resolve().parents[2]
+ / "frontend"
+ / "src"
+ / "features"
+ / "hub"
+ / "lib"
+ / "dataset-size.ts"
+)
+
+# Each backend fnmatch pattern and the fragment its frontend regex counterpart must contain.
+_TS_COUNTERPARTS = {
+ "original/*": "original",
+ "metal/*": "metal",
+ "coreml/*": "coreml",
+ "tf_model*.h5": r"tf_model.*\.h5",
+ "tf_model.h5.index.json": r"tf_model\.h5",
+ "flax_model*.msgpack": r"flax_model.*\.msgpack",
+ "flax_model.msgpack.index.json": r"flax_model\.msgpack",
+ "rust_model.ot": r"rust_model\.ot",
+}
+
+
+def _ts_source() -> str:
+ return _DATASET_SIZE_TS.read_text(encoding = "utf-8")
+
+
+def test_every_backend_duplicate_pattern_has_a_frontend_counterpart():
+ # Keyed off the live tuple, so a pattern added to the backend alone fails here.
+ assert set(DUPLICATE_WEIGHT_FORMAT_PATTERNS) == set(_TS_COUNTERPARTS), (
+ "DUPLICATE_WEIGHT_FORMAT_PATTERNS changed; mirror it in dataset-size.ts's "
+ "DUPLICATE_WEIGHT_FORMAT_RE and record the counterpart here"
+ )
+ src = _ts_source()
+ for pattern in DUPLICATE_WEIGHT_FORMAT_PATTERNS:
+ assert _TS_COUNTERPARTS[pattern] in src, f"{pattern} has no counterpart in dataset-size.ts"
+ assert r"\.index\.json$" in src
+
+
+def test_both_gates_spell_the_shard_number_with_ascii_digits():
+ # Python's \d matches non-ASCII digits and JavaScript's does not, so \d here would have
+ # the two gates disagree about whether a repo ships a root checkpoint at all.
+ assert r"model[-_][0-9]+-of-[0-9]+\.safetensors" in (
+ Path(__file__).resolve().parents[1] / "hub" / "utils" / "snapshot_filters.py"
+ ).read_text(encoding = "utf-8")
+ assert r"^model[-_][0-9]+-of-[0-9]+\.safetensors$" in _ts_source()
+
+
+def test_both_gates_require_the_index_before_trusting_numbered_shards():
+ # A lone shard is not a loadable checkpoint, so neither side may open the gate on one.
+ assert "model.safetensors.index.json" in _ts_source()
+ assert "SAFETENSORS_INDEX" in _ts_source()
+
+
+def test_the_torch_bin_family_is_resolved_per_repo_on_both_sides():
+ # Globbing pytorch_model*.bin dropped dtype variants a default safetensors cannot serve,
+ # so both sides resolve the family against the repo's own file list instead.
+ src = _ts_source()
+ assert "redundantTorchBinFiles(" in src
+ assert "variantShipsAsSafetensors(" in src
+ assert not any(p.startswith("pytorch_model") for p in DUPLICATE_WEIGHT_FORMAT_PATTERNS)
+ assert r"pytorch_model.*\.bin" not in src
+
+
+def test_the_frontend_still_gates_the_duplicate_rules_on_root_safetensors():
+ # A repo without a root checkpoint must download exactly as before on both sides.
+ src = _ts_source()
+ assert "function shipsRootSafetensors(" in src
+ assert "skipDuplicateFormats &&" in src
+ assert "DUPLICATE_WEIGHT_FORMAT_RE.test(filename) || redundantBins.has(filename)" in src
diff --git a/studio/frontend/src/features/hub/lib/dataset-size.ts b/studio/frontend/src/features/hub/lib/dataset-size.ts
index ef76deb5d6e..87621559698 100644
--- a/studio/frontend/src/features/hub/lib/dataset-size.ts
+++ b/studio/frontend/src/features/hub/lib/dataset-size.ts
@@ -272,6 +272,55 @@ const SNAPSHOT_WEIGHT_FILE_RE =
const SNAPSHOT_NON_BIN_WEIGHT_FILE_RE =
/\.(safetensors|pt|pth|ckpt|h5|msgpack|npz)$/i;
const SNAPSHOT_BIN_WEIGHT_PREFIX_RE = /^(model|pytorch_model|adapter_model).*\.bin$/i;
+// [0-9] rather than \d, to stay identical to the backend's SHARDED_SAFETENSORS_RE in
+// studio/backend/hub/utils/snapshot_filters.py, where \d would also match non-ASCII digits.
+const SHARDED_SAFETENSORS_RE = /^model[-_][0-9]+-of-[0-9]+\.safetensors$/;
+const SAFETENSORS_INDEX = "model.safetensors.index.json";
+const DUPLICATE_WEIGHT_FORMAT_RE =
+ /^(?:(?:original|metal|coreml)\/|(?:tf_model.*\.h5|flax_model.*\.msgpack)$|(?:tf_model\.h5|flax_model\.msgpack)\.index\.json$|rust_model\.ot$)/s;
+// Mirrors redundant_torch_bin_files in snapshot_filters.py. A dtype variant is redundant only
+// when the SAME variant ships as safetensors: model.safetensors does not satisfy a
+// variant="fp16" load, and a glob also kept whisper-large-v3's pytorch_model.bin.index.fp32.json
+// while dropping the shards it indexes.
+// Both shard layouts, because transformers writes the counter-first one and this codebase
+// already recognises both in unsloth/models/_utils.py.
+const BIN_WEIGHT_RES = [
+ /^pytorch_model(?:\.([A-Za-z0-9_]+))?(?:[-_][0-9]+-of-[0-9]+)?\.bin$/,
+ /^pytorch_model[-_][0-9]+-of-[0-9]+\.([A-Za-z0-9_]+)\.bin$/,
+];
+const BIN_INDEX_RE =
+ /^pytorch_model(?:\.([A-Za-z0-9_]+))?\.bin\.index(?:\.([A-Za-z0-9_]+))?\.json$/;
+
+// A sharded variant needs its index for the same reason the canonical checkpoint does.
+function variantShipsAsSafetensors(names: string[], variant: string | undefined): boolean {
+ if (!variant) return true;
+ if (names.includes(`model.${variant}.safetensors`)) return true;
+ // transformers' _add_variant puts the variant second-to-last, so this is the only index
+ // spelling a variant load can find.
+ if (!names.includes(`model.safetensors.index.${variant}.json`)) return false;
+ const v = variant.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const sharded = new RegExp(
+ `^(?:model\\.${v}[-_][0-9]+-of-[0-9]+\\.safetensors|model[-_][0-9]+-of-[0-9]+\\.${v}\\.safetensors)$`,
+ );
+ return names.some((n) => sharded.test(n));
+}
+
+function redundantTorchBinFiles(names: string[]): Set<string> {
+ const out = new Set<string>();
+ for (const name of names) {
+ let variant: string | undefined;
+ const weight = BIN_WEIGHT_RES.map((re) => re.exec(name)).find((m) => m);
+ if (weight) {
+ variant = weight[1];
+ } else {
+ const index = BIN_INDEX_RE.exec(name);
+ if (!index) continue;
+ variant = index[1] ?? index[2];
+ }
+ if (variantShipsAsSafetensors(names, variant)) out.add(name);
+ }
+ return out;
+}
function basename(path: string): string {
return path.split("/").pop() ?? path;
@@ -288,9 +337,23 @@ function shipsTransformersWeights(siblings: ModelSibling[]): boolean {
});
}
+// Numbered shards are not loadable on their own: transformers resolves them through
+// model.safetensors.index.json, so one shard is not evidence a checkpoint is there.
+// Mirrors repo_ships_root_safetensors in snapshot_filters.py.
+function shipsRootSafetensors(siblings: ModelSibling[]): boolean {
+ const names = siblings.map((s) => s.rfilename ?? "");
+ if (names.some((n) => n === "model.safetensors")) return true;
+ return (
+ names.includes(SAFETENSORS_INDEX) &&
+ names.some((n) => SHARDED_SAFETENSORS_RE.test(n))
+ );
+}
+
function isSnapshotIgnored(
filename: string,
skipConsolidated: boolean,
+ skipDuplicateFormats: boolean,
+ redundantBins: Set<string>,
): boolean {
const lower = filename.toLowerCase();
return (
@@ -300,7 +363,9 @@ function isSnapshotIgnored(
lower.startsWith("openvino/") ||
lower.startsWith("mlx/") ||
lower.endsWith(".bin.index.json.bak") ||
- (skipConsolidated && lower.startsWith("consolidated"))
+ (skipConsolidated && lower.startsWith("consolidated")) ||
+ (skipDuplicateFormats &&
+ (DUPLICATE_WEIGHT_FORMAT_RE.test(filename) || redundantBins.has(filename)))
);
}
@@ -334,12 +399,26 @@ export function fetchModelSize(
const data = (await res.json()) as ModelInfoApiResponse;
const siblings = data.siblings ?? [];
const skipConsolidated = shipsTransformersWeights(siblings);
+ const skipDuplicateFormats = shipsRootSafetensors(siblings);
+ const redundantBins = redundantTorchBinFiles(
+ siblings.map((s) => s.rfilename ?? ""),
+ );
let total = 0;
let weights = 0;
for (const s of siblings) {
if (typeof s.size !== "number") continue;
const filename = s.rfilename ?? "";
- if (filename && isSnapshotIgnored(filename, skipConsolidated)) continue;
+ if (
+ filename &&
+ isSnapshotIgnored(
+ filename,
+ skipConsolidated,
+ skipDuplicateFormats,
+ redundantBins,
+ )
+ ) {
+ continue;
+ }
total += s.size;
if (filename && SNAPSHOT_WEIGHT_FILE_RE.test(filename)) {
weights += s.size;
diff --git a/studio/frontend/tests/hub-model-size-duplicate-weight-formats.test.ts b/studio/frontend/tests/hub-model-size-duplicate-weight-formats.test.ts
new file mode 100644
index 00000000000..40409001b3c
--- /dev/null
+++ b/studio/frontend/tests/hub-model-size-duplicate-weight-formats.test.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { fetchModelSize } = await import(
+ "../src/features/hub/lib/dataset-size.ts"
+);
+
+function stubSiblings(sizes: Record<string, number>): void {
+ globalThis.fetch = (async () =>
+ new Response(
+ JSON.stringify({
+ siblings: Object.entries(sizes).map(([rfilename, size]) => ({
+ rfilename,
+ size,
+ })),
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ )) as typeof fetch;
+}
+
+test("a gpt-oss shaped repo is sized by its root safetensors only", async () => {
+ stubSiblings({
+ "config.json": 2,
+ "model.safetensors.index.json": 36,
+ "model-00000-of-00002.safetensors": 4_792,
+ "model-00001-of-00002.safetensors": 4_798,
+ "model-00002-of-00002.safetensors": 4_170,
+ "original/dtypes.json": 13,
+ "original/model.safetensors": 13_761,
+ "metal/model.bin": 13_750,
+ });
+ assert.deepEqual(await fetchModelSize("acme/gpt-oss-shaped"), {
+ totalBytes: 2 + 36 + 4_792 + 4_798 + 4_170,
+ weightsBytes: 4_792 + 4_798 + 4_170,
+ });
+});
+
+test("a whisper shaped repo is sized by its safetensors copy only", async () => {
+ stubSiblings({
+ "config.json": 2,
+ "training_args.bin": 3,
+ "model.safetensors": 967,
+ "pytorch_model.bin": 967,
+ "tf_model.h5": 968,
+ "flax_model.msgpack": 967,
+ "2_Dense/pytorch_model.bin": 9,
+ });
+ assert.deepEqual(await fetchModelSize("acme/whisper-shaped"), {
+ totalBytes: 2 + 3 + 967 + 9,
+ weightsBytes: 3 + 967 + 9,
+ });
+});
+
+test("sibling formats still count when there is no root safetensors", async () => {
+ stubSiblings({
+ "config.json": 2,
+ "pytorch_model.bin": 967,
+ "flax_model.msgpack": 967,
+ "original/model.safetensors": 900,
+ "metal/model.bin": 900,
+ });
+ assert.deepEqual(await fetchModelSize("acme/bin-only"), {
+ totalBytes: 2 + 967 + 967 + 900 + 900,
+ weightsBytes: 967 + 967 + 900 + 900,
+ });
+});
+
+test("underscore-sharded root safetensors still skip the bin copy", async () => {
+ stubSiblings({
+ "config.json": 2,
+ "model_00001-of-00072.safetensors": 4_900,
+ "model_00002-of-00072.safetensors": 4_900,
+ "model.safetensors.index.json": 1,
+ "pytorch_model_00001-of-00072.bin": 4_900,
+ "pytorch_model_00002-of-00072.bin": 4_900,
+ "pytorch_model.bin.index.json": 1,
+ });
+ assert.deepEqual(await fetchModelSize("acme/bloom-shaped"), {
+ totalBytes: 2 + 4_900 + 4_900 + 1,
+ weightsBytes: 4_900 + 4_900,
+ });
+});
+
+test("a bin-only dtype variant is still counted", async () => {
+ // model.safetensors cannot serve a variant="fp16" load, so the fp16 bin is not a duplicate.
+ stubSiblings({
+ "config.json": 2,
+ "model.safetensors": 500,
+ "pytorch_model.bin": 500,
+ "pytorch_model.fp16.bin": 250,
+ });
+ assert.deepEqual(await fetchModelSize("acme/bin-only-variant"), {
+ totalBytes: 2 + 500 + 250,
+ weightsBytes: 500 + 250,
+ });
+});
+
+test("an indexless variant does not authorise dropping its bins", async () => {
+ // Sharded fp16 safetensors with no fp16 index are not loadable, so the fp16 bin family
+ // is still the only usable copy and must stay counted.
+ stubSiblings({
+ "config.json": 2,
+ "model.safetensors": 500,
+ "model.fp16-00001-of-00002.safetensors": 250,
+ "pytorch_model.bin": 500,
+ "pytorch_model.fp16-00001-of-00002.bin": 250,
+ "pytorch_model.fp16-00002-of-00002.bin": 250,
+ });
+ assert.deepEqual(await fetchModelSize("acme/indexless-variant"), {
+ totalBytes: 2 + 500 + 250 + 250 + 250,
+ weightsBytes: 500 + 250 + 250 + 250,
+ });
+});
+
+test("both variant shard layouts are recognised", async () => {
+ // transformers writes model-00001-of-00002.fp16.safetensors (counter first).
+ stubSiblings({
+ "config.json": 2,
+ "model.safetensors": 500,
+ "model-00001-of-00002.fp16.safetensors": 250,
+ "model-00002-of-00002.fp16.safetensors": 250,
+ "model.safetensors.index.fp16.json": 1,
+ "pytorch_model.bin": 500,
+ "pytorch_model-00001-of-00002.fp16.bin": 250,
+ "pytorch_model-00002-of-00002.fp16.bin": 250,
+ });
+ assert.deepEqual(await fetchModelSize("acme/counter-first-variant"), {
+ totalBytes: 2 + 500 + 250 + 250 + 1,
+ weightsBytes: 500 + 250 + 250,
+ });
+});
+
+test("a variant index never outlives its shards", async () => {
+ // whisper-large-v3's real shape: the fp32 variant ships as safetensors, so the bin shards
+ // and their index both go.
+ stubSiblings({
+ "config.json": 2,
+ "model.safetensors": 3_090,
+ "model.fp32-00001-of-00002.safetensors": 3_000,
+ "model.fp32-00002-of-00002.safetensors": 3_000,
+ "model.safetensors.index.fp32.json": 1,
+ "pytorch_model.bin": 3_090,
+ "pytorch_model.fp32-00001-of-00002.bin": 3_000,
+ "pytorch_model.fp32-00002-of-00002.bin": 3_000,
+ "pytorch_model.bin.index.fp32.json": 1,
+ });
+ // A repoId of its own: the module-level LRU is keyed on it, and reusing
+ // "acme/whisper-shaped" from the earlier test served that test's cached answer here.
+ assert.deepEqual(await fetchModelSize("acme/whisper-fp32-variant"), {
+ totalBytes: 2 + 3_090 + 3_000 + 3_000 + 1,
+ weightsBytes: 3_090 + 3_000 + 3_000,
+ });
+});
+
+test("indexless shards do not open the gate", async () => {
+ // Numbered shards are resolved through model.safetensors.index.json; with no index the
+ // bin copy is the only loadable checkpoint, so it must still be counted.
+ stubSiblings({
+ "config.json": 2,
+ "model-00001-of-00002.safetensors": 500,
+ "model-00002-of-00002.safetensors": 500,
+ "pytorch_model.bin": 990,
+ });
+ assert.deepEqual(await fetchModelSize("acme/indexless-shards"), {
+ totalBytes: 2 + 500 + 500 + 990,
+ weightsBytes: 500 + 500 + 990,
+ });
+});
+
+test("the same repo with an index does skip the bin copy", async () => {
+ stubSiblings({
+ "config.json": 2,
+ "model-00001-of-00002.safetensors": 500,
+ "model-00002-of-00002.safetensors": 500,
+ "model.safetensors.index.json": 1,
+ "pytorch_model.bin": 990,
+ });
+ assert.deepEqual(await fetchModelSize("acme/indexed-shards"), {
+ totalBytes: 2 + 500 + 500 + 1,
+ weightsBytes: 500 + 500,
+ });
+});
+
+test("a non-ascii shard number does not open the gate", async () => {
+ // The backend's ROOT_SAFETENSORS_RE is the authority on what gets downloaded. Python's
+ // \d matches these digits and JavaScript's does not, so spelling either side \d would
+ // size this repo here while the backend dropped its .bin copy. Both use [0-9]; neither
+ // treats this as a root checkpoint, so nothing is skipped.
+ stubSiblings({
+ "config.json": 2,
+ "model-٠١-of-٠٢.safetensors": 500,
+ "pytorch_model.bin": 500,
+ });
+ assert.deepEqual(await fetchModelSize("acme/non-ascii-shards"), {
+ totalBytes: 2 + 500 + 500,
+ weightsBytes: 500 + 500,
+ });
+});