Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(weights): the checkpoint is the files the index names, not every *.safetensors (#1906)

ndablizov64c12ca36df3
diff --git a/changelog.d/0.76.0/1906.fixed.md b/changelog.d/0.76.0/1906.fixed.md
new file mode 100644
index 00000000..8b77c613
--- /dev/null
+++ b/changelog.d/0.76.0/1906.fixed.md
@@ -0,0 +1 @@
+- A Hugging Face checkpoint is the files `model.safetensors.index.json` names, not every `*.safetensors` in the directory: a `consolidated.safetensors` beside the shards (the mistral-inference copy Mistral's repositories ship, which transformers never loads) is no longer counted by the hardware-fit pre-flight, `soup profile`, `soup cost` and batch estimation, no longer downloaded for layer streaming and `soup spectrum scan` (29.0 GB for a 14.5 GB model), no longer copied out of the HF cache, no longer scored by the spectrum scan (which emitted `unfrozen_parameters` matching no parameter) and no longer kept resident by the layer-stream sharder. Without an index the checkpoint is `model.safetensors`, else the `model-*-of-*.safetensors` shards, else every `*.safetensors` except `consolidated*`, and the Hub download fetches by the same rule; a directory holding only a consolidated file is refused with its name (#1806 by @ndablizov in #1906)
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 2d571f11..f0be800a 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -1231,7 +1231,7 @@ soup env check
Given (params, seq_len, batch_size, optimizer, quant, peft, gradient_checkpointing), the analytical predictor returns a 5-bucket peak-VRAM breakdown (weights / optimizer / gradients / activations / overhead) and an OK/OOM verdict with a 10% safety margin.
For `soup train`, `params_b` is derived by `model_size_from_name`:
-- A local checkpoint path is measured directly from safetensors metadata headers.
+- A local checkpoint path is measured directly from safetensors metadata headers. The files measured are the checkpoint's own: the ones `model.safetensors.index.json` names; without an index `model.safetensors`, else the `model-*-of-*.safetensors` shards, else every `*.safetensors` except `consolidated*`. The Hub download for layer streaming and `soup spectrum scan` fetches by the same rule, so what is downloaded is what is counted. A `consolidated.safetensors` beside the checkpoint (the mistral-inference copy Mistral's repositories ship, which transformers never loads) is not counted, not downloaded for layer streaming or `soup spectrum scan`, not copied out of the HF cache, and not sharded; a directory holding only such a file is refused with its name (#1806).
- A Hub id is parsed: e.g. `72B`, `8x7B` → `46.7` total, `17B-16E` → `109` total, with active-parameter markers (`-A22B`) ignored.
- An id with no size token (e.g. `DeepSeek-V3`, `Kimi-K2`, `GLM-5`, `MiniMax-M2`) still falls back to `7B`, which under-predicts these models (they have 229B to 1T parameters). Point `base:` at a local download to have the checkpoint measured instead.
diff --git a/src/soup_cli/utils/checkpoint_files.py b/src/soup_cli/utils/checkpoint_files.py
new file mode 100644
index 00000000..d71f6d34
--- /dev/null
+++ b/src/soup_cli/utils/checkpoint_files.py
@@ -0,0 +1,193 @@
+"""Which ``*.safetensors`` files make up a Hugging Face checkpoint directory (#1806).
+
+Mistral's Hub repositories ship the same weights twice: the Hugging Face shards
+with ``model.safetensors.index.json``, and one ``consolidated.safetensors`` with
+mistral-inference parameter names. transformers follows the index and never
+opens the consolidated file. Soup's file filters took every top-level
+``*.safetensors`` as part of the checkpoint, so on such a repo the parameter
+count doubled (hardware-fit pre-flight, ``soup profile``, ``soup cost``, batch
+estimation), the weight download fetched both copies, the cache-snapshot copy
+held both, ``soup spectrum scan`` scored both name sets, and the layer-stream
+sharder kept every consolidated tensor resident.
+
+This module is the one answer to "which files are the checkpoint", read by
+every one of those sites:
+
+- with an index, exactly the files its ``weight_map`` names, as transformers loads;
+- without one, ``model.safetensors`` if present, else the ``model-*-of-*.safetensors``
+ shards;
+- otherwise every ``*.safetensors`` except ``consolidated*.safetensors``, so an
+ unconventionally named single file still counts and the mistral-inference copy
+ never does.
+
+No torch here: the helper lists names and reads one small JSON file.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+from dataclasses import dataclass
+from typing import Iterable, Mapping, Optional, Tuple
+
+INDEX_FILE = "model.safetensors.index.json"
+SINGLE_FILE = "model.safetensors"
+_SHARD_RE = re.compile(r"^model-\d+-of-\d+\.safetensors$")
+_CONSOLIDATED_PREFIX = "consolidated"
+_MAX_INDEX_BYTES = 64 * 1024 * 1024 # a 70B index is ~70 KB; bound a crafted file
+
+#: ``allow_patterns`` for a Hub download's first call: the Hugging Face spellings,
+#: which are the ``single`` and ``shards`` rules below, plus the JSON files (the index
+#: among them). Never ``*.safetensors``: that is what fetched Mistral's consolidated
+#: copy beside the shards (29.0 GB for a 14.5 GB model).
+HUB_WEIGHT_PATTERNS_WITHOUT_INDEX: Tuple[str, ...] = (
+ SINGLE_FILE,
+ "model-*-of-*.safetensors",
+)
+#: The ``fallback`` rule as Hub patterns: every ``*.safetensors`` except
+#: ``consolidated*``, so a repository whose only weight file has another name is
+#: fetched just as the local rule would count it (#1806 review).
+HUB_FALLBACK_ALLOW_PATTERNS: Tuple[str, ...] = ("*.safetensors",)
+HUB_FALLBACK_IGNORE_PATTERNS: Tuple[str, ...] = (
+ f"{_CONSOLIDATED_PREFIX}*.safetensors",
+ f"*/{_CONSOLIDATED_PREFIX}*.safetensors",
+)
+
+
+@dataclass(frozen=True)
+class CheckpointFiles:
+ """The checkpoint's safetensors files, by basename, sorted."""
+
+ weights: Tuple[str, ...]
+ #: ``*.safetensors`` present beside the checkpoint that are not part of it.
+ ignored: Tuple[str, ...]
+ #: Files the index names that the directory lacks.
+ missing: Tuple[str, ...]
+ #: How the set was chosen: ``index`` / ``single`` / ``shards`` / ``fallback`` / ``none``.
+ rule: str
+
+ def why_empty(self, directory: str) -> str:
+ """A refusal message for a directory with no checkpoint file, naming what is there."""
+ if self.ignored:
+ names = ", ".join(self.ignored)
+ return (
+ f"no Hugging Face checkpoint in {directory}: the only safetensors file(s) "
+ f"there, {names}, are not part of one (a consolidated.safetensors holds the "
+ f"mistral-inference copy of the weights, which transformers does not load). "
+ f"A checkpoint is model.safetensors, or model-*-of-*.safetensors shards with "
+ f"model.safetensors.index.json."
+ )
+ return f"no .safetensors weight files found in {directory}"
+
+
+def _is_safetensors(name: str) -> bool:
+ return name.endswith(".safetensors")
+
+
+def select_checkpoint_files(
+ names: Iterable[str],
+ index_weight_map: Optional[Mapping[str, str]] = None,
+) -> CheckpointFiles:
+ """Choose the checkpoint's files from a directory's top-level file names.
+
+ ``index_weight_map`` is the parsed ``weight_map`` of ``model.safetensors.index.json``
+ when the directory has one (``None`` otherwise).
+ """
+ present = sorted({name for name in names if _is_safetensors(name)})
+ if index_weight_map is not None:
+ named = sorted({str(value) for value in index_weight_map.values()})
+ present_set = set(present)
+ weights = tuple(name for name in named if name in present_set)
+ missing = tuple(name for name in named if name not in present_set)
+ ignored = tuple(name for name in present if name not in set(named))
+ return CheckpointFiles(weights, ignored, missing, "index")
+ if SINGLE_FILE in present:
+ rest = tuple(name for name in present if name != SINGLE_FILE)
+ return CheckpointFiles((SINGLE_FILE,), rest, (), "single")
+ shards = tuple(name for name in present if _SHARD_RE.match(name))
+ if shards:
+ rest = tuple(name for name in present if not _SHARD_RE.match(name))
+ return CheckpointFiles(shards, rest, (), "shards")
+ consolidated = tuple(name for name in present if name.startswith(_CONSOLIDATED_PREFIX))
+ others = tuple(name for name in present if not name.startswith(_CONSOLIDATED_PREFIX))
+ return CheckpointFiles(others, consolidated, (), "fallback" if others else "none")
+
+
+def read_index_weight_map(directory: str) -> Optional[Mapping[str, str]]:
+ """The index's ``weight_map`` (basename values), or ``None`` without an index.
+
+ Raises ``ValueError`` for an index that is present but unreadable, so a
+ corrupt index is a named failure rather than a silent fall-through to a
+ filter that would count the consolidated copy again.
+ """
+ path = os.path.join(directory, INDEX_FILE)
+ if not os.path.isfile(path):
+ return None
+ if os.path.getsize(path) > _MAX_INDEX_BYTES:
+ raise ValueError(f"{INDEX_FILE} in {directory} exceeds {_MAX_INDEX_BYTES} bytes")
+ try:
+ with open(path, encoding="utf-8") as handle:
+ data = json.load(handle)
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ValueError(f"{INDEX_FILE} in {directory} is not valid JSON: {exc}") from exc
+ weight_map = data.get("weight_map") if isinstance(data, dict) else None
+ if not isinstance(weight_map, dict) or not weight_map:
+ raise ValueError(f"{INDEX_FILE} in {directory} has no weight_map")
+ # transformers stores basenames; tolerate a relative path by keeping its basename.
+ return {str(key): os.path.basename(str(value)) for key, value in weight_map.items()}
+
+
+def checkpoint_files(directory: str) -> CheckpointFiles:
+ """The checkpoint's files in ``directory`` (top level only, names not resolved)."""
+ names = []
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ if _is_safetensors(entry.name):
+ names.append(entry.name)
+ return select_checkpoint_files(names, read_index_weight_map(directory))
+
+
+def hub_allow_patterns(index_weight_map: Optional[Mapping[str, str]]) -> list[str]:
+ """``allow_patterns`` for the weight download: the indexed files, or the HF spellings.
+
+ Never ``*.safetensors``: that pattern is what fetched Mistral's consolidated
+ copy beside the shards (29.0 GB for a 14.5 GB model).
+ """
+ if index_weight_map is not None:
+ return sorted({os.path.basename(str(value)) for value in index_weight_map.values()})
+ return list(HUB_WEIGHT_PATTERNS_WITHOUT_INDEX)
+
+
+def hub_second_call(selected: CheckpointFiles) -> Optional[Tuple[list[str], list[str]]]:
+ """What a second download call must ask for, after the first fetched the HF spellings.
+
+ ``(allow_patterns, ignore_patterns)``, or ``None`` when the first call already
+ holds the checkpoint. The local rule and the download agree by construction:
+ with an index, the files it names that are not there yet (an index naming
+ ``weights-part1.safetensors``); without one, when neither ``model.safetensors``
+ nor shards came, the ``fallback`` rule's own patterns, every ``*.safetensors``
+ except ``consolidated*`` (#1806 review).
+ """
+ if selected.rule == "index":
+ if selected.missing:
+ return list(selected.missing), []
+ return None
+ if selected.rule == "none":
+ return list(HUB_FALLBACK_ALLOW_PATTERNS), list(HUB_FALLBACK_IGNORE_PATTERNS)
+ return None
+
+
+__all__ = [
+ "HUB_FALLBACK_ALLOW_PATTERNS",
+ "HUB_FALLBACK_IGNORE_PATTERNS",
+ "HUB_WEIGHT_PATTERNS_WITHOUT_INDEX",
+ "INDEX_FILE",
+ "SINGLE_FILE",
+ "CheckpointFiles",
+ "checkpoint_files",
+ "hub_allow_patterns",
+ "hub_second_call",
+ "read_index_weight_map",
+ "select_checkpoint_files",
+]
diff --git a/src/soup_cli/utils/gpu.py b/src/soup_cli/utils/gpu.py
index 2e87de93..d78a6ad9 100644
--- a/src/soup_cli/utils/gpu.py
+++ b/src/soup_cli/utils/gpu.py
@@ -27,13 +27,20 @@ def _params_from_local_safetensors(path: str) -> float | None:
refuse to train a 135M model. The checkpoint knows its own size, so ask
it instead of guessing.
"""
+ from soup_cli.utils.checkpoint_files import checkpoint_files
+
try:
if not os.path.isdir(path):
return None
+ # #1806: the checkpoint is what the index names (or model.safetensors /
+ # the model-*-of-* shards), never every *.safetensors: Mistral's repos
+ # keep a consolidated.safetensors copy beside the shards, which doubled
+ # the count here and everything sized from it.
+ selected = checkpoint_files(path)
shards = [
- entry.path
- for entry in os.scandir(path)
- if entry.is_file() and entry.name.endswith(".safetensors")
+ os.path.join(path, name)
+ for name in selected.weights
+ if os.path.isfile(os.path.join(path, name))
]
if not shards:
return None
diff --git a/src/soup_cli/utils/hubs.py b/src/soup_cli/utils/hubs.py
index 6abcf170..a08648bc 100644
--- a/src/soup_cli/utils/hubs.py
+++ b/src/soup_cli/utils/hubs.py
@@ -437,6 +437,7 @@ def snapshot_download(
cache_dir: str | None,
revision: str | None = None,
allow_patterns: list[str] | None = None,
+ ignore_patterns: list[str] | None = None,
namespace_check: bool = True,
allow_namespace_shift: str | None = None,
_metadata_fn: Optional[Callable[[str], Optional[Tuple[str, str]]]] = None,
@@ -449,7 +450,9 @@ def snapshot_download(
``None`` asks Hugging Face for its canonical cached snapshot instead; this
is used by layer streaming to inspect and reuse an existing non-symlinked
cache entry before deciding whether a second materialised copy is needed.
- The namespace-pin gate (#186) runs in both cases.
+ The namespace-pin gate (#186) runs in both cases. ``ignore_patterns`` is
+ forwarded only when given, as huggingface_hub applies it after
+ ``allow_patterns`` (#1806).
Returns the absolute path to the downloaded snapshot directory. Raises
``ImportError`` (with a pip-install hint) when ``huggingface_hub`` is
@@ -462,11 +465,11 @@ def snapshot_download(
raise TypeError("revision must be str or None")
if "\x00" in revision or any(ord(c) < 0x20 for c in revision):
raise ValueError("revision must not contain control characters")
- if allow_patterns is not None:
- if not isinstance(allow_patterns, list) or not all(
- isinstance(p, str) for p in allow_patterns
- ):
- raise TypeError("allow_patterns must be a list of str or None")
+ for field_name, patterns in (("allow_patterns", allow_patterns),
+ ("ignore_patterns", ignore_patterns)):
+ if patterns is not None:
+ if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns):
+ raise TypeError(f"{field_name} must be a list of str or None")
if namespace_check:
_run_namespace_check(
@@ -487,6 +490,8 @@ def snapshot_download(
"revision": revision,
"allow_patterns": allow_patterns,
}
+ if ignore_patterns is not None:
+ kwargs["ignore_patterns"] = ignore_patterns
if canonical_cache is None:
return hf_snapshot_download(**kwargs)
os.makedirs(canonical_cache, exist_ok=True)
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index 6529b3b2..51eb0510 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -809,14 +809,21 @@ def resolve_shard_dir(model: str, cache_dir: Optional[str] = None) -> str:
# sharding
# ==========================================================================
def _discover_safetensors(weights_dir: str) -> List[str]:
- """Sorted, non-symlinked ``*.safetensors`` under ``weights_dir``."""
+ """Sorted, non-symlinked checkpoint files under ``weights_dir``.
+
+ The checkpoint's files are what the index names, or ``model.safetensors`` /
+ the ``model-*-of-*`` shards (#1806); Mistral's ``consolidated.safetensors``
+ beside them used to put every one of its tensors into the resident extras
+ shard and double ``source_weight_bytes``.
+ """
+ from soup_cli.utils.checkpoint_files import checkpoint_files
+
root = os.path.realpath(os.path.expanduser(weights_dir))
if not os.path.isdir(root):
raise FileNotFoundError(f"weights directory not found: {weights_dir}")
+ selected = checkpoint_files(root)
found = []
- for name in sorted(os.listdir(root)):
- if not name.endswith(".safetensors"):
- continue
+ for name in selected.weights:
path = os.path.join(root, name)
if os.path.islink(path):
logger.warning("layer-stream sharder: skipping symlinked shard %s", name)
@@ -826,8 +833,8 @@ def _discover_safetensors(weights_dir: str) -> List[str]:
found.append(path)
if not found:
raise FileNotFoundError(
- f"no .safetensors weight files found in {weights_dir} — layer "
- f"streaming needs a safetensors checkpoint"
+ f"{selected.why_empty(weights_dir)} — layer streaming needs a safetensors "
+ f"checkpoint"
)
if len(found) > _MAX_SHARD_FILES:
raise ValueError(f"too many shard files ({len(found)} > {_MAX_SHARD_FILES})")
diff --git a/src/soup_cli/utils/spectrum_scan.py b/src/soup_cli/utils/spectrum_scan.py
index 948eb192..c8b4de16 100644
--- a/src/soup_cli/utils/spectrum_scan.py
+++ b/src/soup_cli/utils/spectrum_scan.py
@@ -296,22 +296,29 @@ def _framework() -> Tuple[str, Callable[[Any], "NDArray[Any]"]]:
def _discover_safetensors(weights_dir: str) -> list[str]:
+ from soup_cli.utils.checkpoint_files import checkpoint_files
+
real = os.path.realpath(weights_dir)
if not os.path.isdir(real):
raise FileNotFoundError(f"weights dir not found: {weights_dir}")
+ # #1806: the checkpoint's own files, not every *.safetensors. Mistral's
+ # consolidated.safetensors carries the same weights under mistral-inference
+ # names; scanning it too emitted unfrozen_parameters that match no
+ # parameter of the HF model.
+ selected = checkpoint_files(real)
files = []
- for entry in sorted(os.listdir(real)):
- if not entry.endswith(".safetensors"):
- continue
+ for entry in selected.weights:
full = os.path.join(real, entry)
# Skip symlinked shards — defence-in-depth against a link redirecting
# the read (mirrors the project's no-symlink TOCTOU policy).
if os.path.islink(full):
logger.warning("spectrum scan: skipping symlinked shard %s", entry)
continue
+ if not os.path.isfile(full):
+ continue
files.append(full)
if not files:
- raise FileNotFoundError(f"no .safetensors files in {weights_dir}")
+ raise FileNotFoundError(selected.why_empty(weights_dir))
return files
@@ -572,14 +579,19 @@ def _weight_file_manifest(
*,
permit_symlinks: bool,
) -> Tuple[Tuple[str, int, int], ...]:
- """Return ``(basename, size, mtime_ns)`` for top-level safetensors files."""
+ """Return ``(basename, size, mtime_ns)`` for the checkpoint's top-level safetensors.
+
+ The checkpoint's files are what the index names (#1806), so a Mistral-style
+ ``consolidated.safetensors`` beside the shards is neither sized nor copied.
+ """
+ from soup_cli.utils.checkpoint_files import checkpoint_files
+
root = os.path.realpath(os.path.expanduser(directory))
if not os.path.isdir(root):
raise FileNotFoundError(f"weights directory not found: {directory}")
+ selected = checkpoint_files(root)
files = []
- for name in sorted(os.listdir(root)):
- if not name.endswith(".safetensors"):
- continue
+ for name in selected.weights:
path = os.path.join(root, name)
if os.path.islink(path) and not permit_symlinks:
raise FileNotFoundError(
@@ -590,9 +602,7 @@ def _weight_file_manifest(
stat = os.stat(path)
files.append((name, int(stat.st_size), int(stat.st_mtime_ns)))
if not files:
- raise FileNotFoundError(
- f"no .safetensors weight files found in {directory}"
- )
+ raise FileNotFoundError(selected.why_empty(directory))
return tuple(files)
@@ -763,6 +773,13 @@ def _snapshot_materialization_entries(
if shared_root is not None:
blob_roots.append(shared_root)
+ from soup_cli.utils.checkpoint_files import checkpoint_files
+
+ # #1806: only the checkpoint's own top-level weights are copied (and sized in
+ # materialize_bytes), the same set _weight_file_manifest reports, since the
+ # copy is checked against that manifest afterwards.
+ top_level_weights = set(checkpoint_files(source).weights)
+
entries: list[Tuple[str, str, Optional[str]]] = []
for root, dirnames, filenames in os.walk(source, followlinks=False):
for dirname in dirnames:
@@ -778,6 +795,12 @@ def _snapshot_materialization_entries(
for filename in filenames:
if not filename.endswith((".safetensors", ".json")):
continue
+ if (
+ filename.endswith(".safetensors")
+ and root == source
+ and filename not in top_level_weights
+ ):
+ continue
snapshot_path = os.path.join(root, filename)
relative = os.path.relpath(snapshot_path, source)
blob_id = None
@@ -938,14 +961,7 @@ def plan_model_weights(model: str) -> ModelWeightsPlan:
materialize_bytes=0,
source_files=manifest,
)
- from soup_cli.utils.hubs import snapshot_download
-
- source = snapshot_download(
- model,
- cache_dir=None,
- allow_patterns=["*.safetensors", "*.json"],
- )
- source = os.path.realpath(source)
+ source = os.path.realpath(_download_hub_checkpoint(model))
source_revision = _hf_snapshot_revision(source)
manifest = _weight_file_manifest(source, permit_symlinks=True)
source_paths = [os.path.join(source, name) for name, _size, _mtime in manifest]
@@ -963,6 +979,44 @@ def plan_model_weights(model: str) -> ModelWeightsPlan:
return _hf_snapshot_plan(model, source, manifest, source_revision)
+def _download_hub_checkpoint(model: str) -> str:
+ """Fetch a Hub repo's checkpoint files, and nothing beside them (#1806).
+
+ ``*.safetensors`` fetched Mistral's ``consolidated.safetensors`` next to the
+ shards: 29.0 GB for a 14.5 GB model. One call asks for the Hugging Face
+ spellings (``model.safetensors``, ``model-*-of-*.safetensors``) and the JSON
+ files; one call, so an already complete cache entry resolves offline as
+ before (#533). The local rule then reads what came, and a second call is
+ made only when it says the checkpoint is not all there: the files an index
+ names outside those spellings, or, with no index and neither spelling
+ present, every ``*.safetensors`` except ``consolidated*``, which is the
+ local fallback rule itself. So what is downloaded is what is counted.
+ """
+ from soup_cli.utils.checkpoint_files import (
+ hub_allow_patterns,
+ hub_second_call,
+ read_index_weight_map,
+ select_checkpoint_files,
+ )
+ from soup_cli.utils.hubs import snapshot_download
+
+ source = snapshot_download(
+ model, cache_dir=None, allow_patterns=[*hub_allow_patterns(None), "*.json"]
+ )
+ real = os.path.realpath(source)
+ selected = select_checkpoint_files(os.listdir(real), read_index_weight_map(real))
+ second = hub_second_call(selected)
+ if second is not None:
+ allow, ignore = second
+ source = snapshot_download(
+ model,
+ cache_dir=None,
+ allow_patterns=[*allow, "*.json"],
+ ignore_patterns=ignore or None,
+ )
+ return source
+
+
def _hf_cache_repo_id(source_dir: str) -> Optional[str]:
"""``org/name`` for a ``models--org--name/snapshots/<sha>`` directory."""
repo_dir = os.path.basename(os.path.dirname(os.path.dirname(source_dir)))
diff --git a/tests/test_checkpoint_files.py b/tests/test_checkpoint_files.py
new file mode 100644
index 00000000..e8cc53ff
--- /dev/null
+++ b/tests/test_checkpoint_files.py
@@ -0,0 +1,593 @@
+"""#1806 — the checkpoint is the files the index names, not every ``*.safetensors``.
+
+Mistral's Hub repositories ship the same weights twice: the Hugging Face shards
+with ``model.safetensors.index.json`` and one ``consolidated.safetensors`` with
+mistral-inference names, which transformers never opens. Four of Soup's file
+filters, the Hub download pattern and the cache-snapshot copy took every
+top-level ``*.safetensors``, so the parameter count, the download, the copy, the
+spectrum scan and the layer-stream sharder all saw the model twice.
+
+``utils/checkpoint_files.py`` is now the one answer, and every site reads it.
+The fixture is the issue's reproduction: a tiny random Llama saved sharded, plus
+the same weights under mistral-inference names in ``consolidated.safetensors``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from soup_cli.utils.checkpoint_files import (
+ CheckpointFiles,
+ checkpoint_files,
+ hub_allow_patterns,
+ hub_second_call,
+ read_index_weight_map,
+ select_checkpoint_files,
+)
+
+pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")
+
+_RENAME = {
+ "model.embed_tokens.weight": "tok_embeddings.weight",
+ "lm_head.weight": "output.weight",
+ "model.norm.weight": "norm.weight",
+}
+_LAYER_RENAME = (
+ ("self_attn.q_proj", "attention.wq"), ("self_attn.k_proj", "attention.wk"),
+ ("self_attn.v_proj", "attention.wv"), ("self_attn.o_proj", "attention.wo"),
+ ("mlp.gate_proj", "feed_forward.w1"), ("mlp.down_proj", "feed_forward.w2"),
+ ("mlp.up_proj", "feed_forward.w3"), ("input_layernorm", "attention_norm"),
+ ("post_attention_layernorm", "ffn_norm"),
+)
+
+
+def _tiny_llama():
+ import torch
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ torch.manual_seed(0)
+ cfg = LlamaConfig(
+ vocab_size=128, hidden_size=64, intermediate_size=128, num_hidden_layers=2,
+ num_attention_heads=4, num_key_value_heads=4, max_position_embeddings=64,
+ )
+ return cfg, LlamaForCausalLM(cfg)
+
+
+def _write_consolidated(model, cfg, directory: Path) -> None:
+ from safetensors.torch import save_file
+
+ state = model.state_dict()
+ rename = dict(_RENAME)
+ for i in range(cfg.num_hidden_layers):
+ for hf_name, mi_name in _LAYER_RENAME:
+ rename[f"model.layers.{i}.{hf_name}.weight"] = f"layers.{i}.{mi_name}.weight"
+ save_file(
+ {rename[k]: v.clone().contiguous() for k, v in state.items()},
+ str(directory / "consolidated.safetensors"),
+ )
+
+
[email protected](scope="module")
+def mistral_like(tmp_path_factory) -> dict:
+ """Index + shards (the HF checkpoint) beside ``consolidated.safetensors``."""
+ directory = tmp_path_factory.mktemp("mistral_like")
+ cfg, model = _tiny_llama()
+ model.save_pretrained(str(directory), max_shard_size="100KB")
+ _write_consolidated(model, cfg, directory)
+ names = sorted(p.name for p in directory.iterdir())
+ assert "model.safetensors.index.json" in names, names
+ shards = sorted(n for n in names if n.startswith("model-") and n.endswith(".safetensors"))
+ assert len(shards) >= 2, names
+ return {
+ "dir": directory,
+ "shards": shards,
+ "true_params": sum(v.numel() for v in model.state_dict().values()),
+ "hf_names": [n for n, _ in model.named_parameters()],
+ "shard_bytes": sum(os.path.getsize(directory / s) for s in shards),
+ "all_bytes": sum(os.path.getsize(directory / n) for n in names
+ if n.endswith(".safetensors")),
+ }
+
+
+# ---------------------------------------------------------------------------
+# The helper's rules
+# ---------------------------------------------------------------------------
+
+
+class TestSelection:
+ def test_an_index_decides_exactly(self):
+ got = select_checkpoint_files(
+ ["consolidated.safetensors", "model-00001-of-00002.safetensors",
+ "model-00002-of-00002.safetensors", "model.safetensors", "config.json"],
+ {"a": "model-00001-of-00002.safetensors", "b": "model-00002-of-00002.safetensors"},
+ )
+ assert got.weights == ("model-00001-of-00002.safetensors",
+ "model-00002-of-00002.safetensors")
+ assert got.ignored == ("consolidated.safetensors", "model.safetensors")
+ assert got.missing == ()
+ assert got.rule == "index"
+
+ def test_an_index_naming_a_missing_shard_reports_it(self):
+ got = select_checkpoint_files(
+ ["model-00001-of-00002.safetensors"],
+ {"a": "model-00001-of-00002.safetensors", "b": "model-00002-of-00002.safetensors"},
+ )
+ assert got.weights == ("model-00001-of-00002.safetensors",)
+ assert got.missing == ("model-00002-of-00002.safetensors",)
+
+ def test_without_an_index_the_single_file_wins(self):
+ got = select_checkpoint_files(["consolidated.safetensors", "model.safetensors"], None)
+ assert got.weights == ("model.safetensors",)
+ assert got.ignored == ("consolidated.safetensors",)
+ assert got.rule == "single"
+
+ def test_without_an_index_the_shards_win(self):
+ got = select_checkpoint_files(
+ ["consolidated.safetensors", "model-00002-of-00002.safetensors",
+ "model-00001-of-00002.safetensors"], None,
+ )
+ assert got.weights == ("model-00001-of-00002.safetensors",
+ "model-00002-of-00002.safetensors")
+ assert got.rule == "shards"
+
+ def test_an_unconventional_name_still_counts_but_consolidated_never(self):
+ got = select_checkpoint_files(["weights.safetensors", "consolidated.00.safetensors"],
+ None)
+ assert got.weights == ("weights.safetensors",)
+ assert got.ignored == ("consolidated.00.safetensors",)
+ assert got.rule == "fallback"
+
+ def test_consolidated_only_is_empty_and_the_message_names_it(self):
+ got = select_checkpoint_files(["consolidated.safetensors"], None)
+ assert got.weights == ()
+ assert got.rule == "none"
+ msg = got.why_empty("/m")
+ assert "consolidated.safetensors" in msg
+ assert "model.safetensors.index.json" in msg
+
+ def test_nothing_at_all_keeps_the_old_message(self):
+ got = select_checkpoint_files(["config.json"], None)
+ assert got == CheckpointFiles((), (), (), "none")
+ assert got.why_empty("/m") == "no .safetensors weight files found in /m"
+
+ def test_hub_patterns_never_say_star_safetensors(self):
+ assert hub_allow_patterns(None) == ["model.safetensors", "model-*-of-*.safetensors"]
+ assert hub_allow_patterns({"a": "model-00001-of-00001.safetensors"}) == [
+ "model-00001-of-00001.safetensors"
+ ]
+ assert "*.safetensors" not in hub_allow_patterns(None)
+
+ def test_second_call_is_the_indexed_files_still_missing(self):
+ got = select_checkpoint_files(["model-00002-of-00002.safetensors"],
+ {"a": "weights-part1.safetensors",
+ "b": "model-00002-of-00002.safetensors"})
+ assert hub_second_call(got) == (["weights-part1.safetensors"], [])
+
+ @pytest.mark.parametrize(
+ "names,weight_map",
+ [
+ (["model-00001-of-00001.safetensors"], {"a": "model-00001-of-00001.safetensors"}),
+ (["model.safetensors"], None),
+ (["model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"], None),
+ ],
+ )
+ def test_no_second_call_when_the_first_holds_the_checkpoint(self, names, weight_map):
+ assert hub_second_call(select_checkpoint_files(names, weight_map)) is None
+
+ def test_second_call_without_index_is_the_fallback_rule_as_patterns(self):
+ # Neither spelling came, so ask for what the local fallback would count:
+ # every *.safetensors except consolidated*, top level or nested.
+ import fnmatch
+
+ allow, ignore = hub_second_call(select_checkpoint_files(["config.json"], None))
+ assert allow == ["*.safetensors"]
+
+ def fetched(name: str) -> bool:
+ return (any(fnmatch.fnmatch(name, p) for p in allow)
+ and not any(fnmatch.fnmatch(name, p) for p in ignore))
+
+ assert fetched("pytorch_model.safetensors")
+ assert fetched("weights.safetensors")
+ assert not fetched("consolidated.safetensors")
+ assert not fetched("consolidated.00.safetensors")
+ assert not fetched("sub/consolidated.safetensors")
+ assert not fetched("consolidated.00.pth")
+
+
+class TestIndexReading:
+ def test_reads_the_weight_map_basenames(self, mistral_like):
+ wm = read_index_weight_map(str(mistral_like["dir"]))
+ assert wm is not None
+ assert sorted(set(wm.values())) == mistral_like["shards"]
+
+ def test_no_index_is_none(self, tmp_path: Path):
+ assert read_index_weight_map(str(tmp_path)) is None
+
+ def test_a_corrupt_index_is_a_named_failure(self, tmp_path: Path):
+ (tmp_path / "model.safetensors.index.json").write_text("{not json", encoding="utf-8")
+ with pytest.raises(ValueError, match="not valid JSON"):
+ read_index_weight_map(str(tmp_path))
+
+ def test_checkpoint_files_on_the_fixture(self, mistral_like):
+ got = checkpoint_files(str(mistral_like["dir"]))
+ assert list(got.weights) == mistral_like["shards"]
+ assert got.ignored == ("consolidated.safetensors",)
+
+
+# ---------------------------------------------------------------------------
+# Every consumer, on the issue's layout
+# ---------------------------------------------------------------------------
+
+
+def test_model_size_from_name_counts_the_model_once(mistral_like):
+ from soup_cli.utils.gpu import model_size_from_name
+
+ got = round(model_size_from_name(str(mistral_like["dir"])) * 1e9)
+ assert got == mistral_like["true_params"]
+
+
+def test_a_leftover_single_file_beside_index_and_shards_is_not_counted(mistral_like, tmp_path):
+ import shutil
+
+ from soup_cli.utils.gpu import model_size_from_name
+
+ target = tmp_path / "leftover"
+ shutil.copytree(mistral_like["dir"], target)
+ shutil.copy(target / mistral_like["shards"][0], target / "model.safetensors")
+ got = round(model_size_from_name(str(target)) * 1e9)
+ assert got == mistral_like["true_params"]
+
+
+def test_plan_model_weights_lists_only_the_indexed_shards(mistral_like):
+ from soup_cli.utils.spectrum_scan import plan_model_weights
+
+ plan = plan_model_weights(str(mistral_like["dir"]))
+ assert [name for name, _s, _m in plan.source_files] == mistral_like["shards"]
+ assert plan.source_bytes == mistral_like["shard_bytes"]
+ assert plan.source_bytes < mistral_like["all_bytes"]
+
+
+def test_scan_reads_the_hf_names_only_and_selects_no_phantom(mistral_like):
+ from soup_cli.utils.spectrum_scan import scan_weights_dir, select_unfrozen_parameters
+
+ layers = scan_weights_dir(str(mistral_like["dir"]))
+ names = {layer.name for layer in layers}
+ assert not any(n.startswith(("layers.", "tok_embeddings", "output")) for n in names), names
+ chosen = select_unfrozen_parameters(layers, top_percent=50)
+ hf_names = mistral_like["hf_names"]
+ phantom = [p for p in chosen if not any(n.startswith(p) for n in hf_names)]
+ assert phantom == []
+
+
+def test_source_weight_bytes_sums_the_shards_only(mistral_like):
+ from soup_cli.utils.layer_shard import source_weight_bytes
+
+ assert source_weight_bytes(str(mistral_like["dir"])) == mistral_like["shard_bytes"]
+
+
+def test_shard_checkpoint_keeps_no_consolidated_tensor(mistral_like, tmp_path):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ index = shard_checkpoint(str(mistral_like["dir"]), str(tmp_path / "shards"), dtype="float32")
+ assert index.total_params == mistral_like["true_params"]
+ assert not any(k.startswith(("layers.", "tok_embeddings", "output", "norm."))
+ for k in index.extra_keys), index.extra_keys
+ assert [name for name, _s, _m in index.source_files] == mistral_like["shards"]
+
+
+# ---------------------------------------------------------------------------
+# The Hub download and the snapshot copy
+# ---------------------------------------------------------------------------
+
+
+def test_hub_download_asks_for_the_indexed_files_not_star_safetensors(mistral_like, monkeypatch):
+ from soup_cli.utils import hubs, spectrum_scan
+
+ calls = []
+
+ def fake(repo_id, *, cache_dir, allow_patterns=None, **kwargs):
+ calls.append(list(allow_patterns or []))
+ return str(mistral_like["dir"])
+
+ monkeypatch.setattr(hubs, "snapshot_download", fake)
+ plan = spectrum_scan.plan_model_weights("mistralai/Mistral-7B-Instruct-v0.3")
+ # One call (a complete cache entry must keep resolving offline, #533), with
+ # the Hugging Face spellings: the shards match, the consolidated copy does not.
+ assert calls == [["model.safetensors", "model-*-of-*.safetensors", "*.json"]], calls
+ import fnmatch
+
+ for shard in mistral_like["shards"]:
+ assert any(fnmatch.fnmatch(shard, p) for p in calls[0])
+ assert not any(fnmatch.fnmatch("consolidated.safetensors", p) for p in calls[0])
+ assert [name for name, _s, _m in plan.source_files] == mistral_like["shards"]
+
+
+def test_an_index_naming_a_file_outside_the_hf_spellings_fetches_it_by_name(
+ mistral_like, tmp_path, monkeypatch
+):
+ import fnmatch
+ import shutil
+
+ from soup_cli.utils import hubs, spectrum_scan
+
+ # A repo whose index names `weights-part1.safetensors`: the first call's
+ # patterns do not cover it, so a second call asks for exactly that file.
+ repo = tmp_path / "repo"
+ shutil.copytree(mistral_like["dir"], repo)
+ first = mistral_like["shards"][0]
+ os.rename(repo / first, repo / "weights-part1.safetensors")
+ index_path = repo / "model.safetensors.index.json"
+ index = json.loads(index_path.read_text(encoding="utf-8"))
+ index["weight_map"] = {k: ("weights-part1.safetensors" if v == first else v)
+ for k, v in index["weight_map"].items()}
+ index_path.write_text(json.dumps(index), encoding="utf-8")
+
+ download = tmp_path / "download" # what the fake Hub has delivered so far
+ download.mkdir()
+ calls = []
+
+ def fake(repo_id, *, cache_dir, allow_patterns=None, **kwargs):
+ calls.append(list(allow_patterns or []))
+ for name in os.listdir(repo):
+ if any(fnmatch.fnmatch(name, p) for p in allow_patterns or []):
+ if not (download / name).exists():
+ shutil.copy(repo / name, download / name)
+ return str(download)
+
+ monkeypatch.setattr(hubs, "snapshot_download", fake)
+ plan = spectrum_scan.plan_model_weights("org/odd-names")
+ assert len(calls) == 2, calls
+ assert calls[1] == ["weights-part1.safetensors", "*.json"]
+ assert not (download / "consolidated.safetensors").exists()
+ assert [name for name, _s, _m in plan.source_files] == sorted(
+ ["weights-part1.safetensors", *mistral_like["shards"][1:]]
+ )
+
+
+def test_the_hub_wrapper_forwards_ignore_patterns_only_when_given(tmp_path, monkeypatch):
+ import huggingface_hub
+
+ from soup_cli.utils import hubs
+
+ captured = []
+ monkeypatch.setattr(huggingface_hub, "snapshot_download",
+ lambda **kw: captured.append(kw) or str(tmp_path))
+ hubs.snapshot_download("org/m", cache_dir=None, allow_patterns=["*.safetensors"],
+ ignore_patterns=["consolidated*.safetensors"], namespace_check=False)
+ hubs.snapshot_download("org/m", cache_dir=None, allow_patterns=["*.json"],
+ namespace_check=False)
+ assert captured[0]["ignore_patterns"] == ["consolidated*.safetensors"]
+ assert "ignore_patterns" not in captured[1] # the pre-#1806 call shape, unchanged
+ with pytest.raises(TypeError, match="ignore_patterns"):
+ hubs.snapshot_download("org/m", cache_dir=None, ignore_patterns="consolidated*",
+ namespace_check=False)
+
+
+def _fake_hub(repo: Path, download: Path, calls: list):
+ """A Hub that delivers the files of ``repo`` matching allow minus ignore patterns."""
+ import fnmatch
+ import shutil
+
+ def fake(repo_id, *, cache_dir, allow_patterns=None, ignore_patterns=None, **kwargs):
+ calls.append((list(allow_patterns or []), list(ignore_patterns or [])))
+ for name in os.listdir(repo):
+ if not any(fnmatch.fnmatch(name, p) for p in allow_patterns or []):
+ continue
+ if any(fnmatch.fnmatch(name, p) for p in ignore_patterns or []):
+ continue
+ if not (download / name).exists():
+ shutil.copy(repo / name, download / name)
+ return str(download)
+
+ return fake
+
+
+def _layout(mistral_like: dict, tmp_path: Path, name: str) -> Path:
+ """Repository layouts without an index, built from the fixture's files."""
+ import shutil
+
+ repo = tmp_path / name
+ repo.mkdir()
+ src = mistral_like["dir"]
+ first, second = mistral_like["shards"][:2]
+ shutil.copy(src / "config.json", repo / "config.json")
+ if name == "indexed":
+ shutil.rmtree(repo)
+ shutil.copytree(src, repo)
+ elif name == "single":
+ shutil.copy(src / first, repo / "model.safetensors")
+ shutil.copy(src / "consolidated.safetensors", repo / "consolidated.safetensors")
+ elif name == "shards-no-index":
+ shutil.copy(src / first, repo / first)
+ shutil.copy(src / second, repo / second)
+ shutil.copy(src / second, repo / "extra.safetensors")
+ elif name == "odd-single":
+ shutil.copy(src / first, repo / "pytorch_model.safetensors")
+ shutil.copy(src / "consolidated.safetensors", repo / "consolidated.safetensors")
+ elif name == "consolidated-only":
+ shutil.copy(src / "consolidated.safetensors", repo / "consolidated.safetensors")
+ return repo
+
+
+def test_a_repo_whose_only_weight_file_has_another_name_is_fetched_by_the_fallback_rule(
+ mistral_like, tmp_path, monkeypatch
+):
+ # No index, no model.safetensors, no shards: the first call brings only the JSON,
+ # and the second asks for every *.safetensors except consolidated* (#1806 review).
+ from soup_cli.utils import hubs, spectrum_scan
+
+ repo = _layout(mistral_like, tmp_path, "odd-single")
+ download = tmp_path / "download"
+ download.mkdir()
+ calls = []
+ monkeypatch.setattr(hubs, "snapshot_download", _fake_hub(repo, download, calls))
+ plan = spectrum_scan.plan_model_weights("org/odd-single")
+ assert len(calls) == 2, calls
+ assert calls[1] == (["*.safetensors", "*.json"],
+ ["consolidated*.safetensors", "*/consolidated*.safetensors"])
+ assert (download / "pytorch_model.safetensors").exists()
+ assert not (download / "consolidated.safetensors").exists()
+ assert [name for name, _s, _m in plan.source_files] == ["pytorch_model.safetensors"]
+
+
+ "layout", ["indexed", "single", "shards-no-index", "odd-single", "consolidated-only"]
+)
+def test_what_the_download_fetches_is_what_the_local_rule_counts(
+ mistral_like, tmp_path, monkeypatch, layout
+):
+ # The two rules agree: on every layout the safetensors the Hub delivered are
+ # exactly the files the local helper selects on the full repository.
+ from soup_cli.utils import hubs, spectrum_scan
+
+ repo = _layout(mistral_like, tmp_path, layout)
+ download = tmp_path / "download"
+ download.mkdir()
+ calls = []
+ monkeypatch.setattr(hubs, "snapshot_download", _fake_hub(repo, download, calls))
+ local = checkpoint_files(str(repo))
+ if layout == "consolidated-only":
+ with pytest.raises(FileNotFoundError, match="no .safetensors weight files"):
+ spectrum_scan.plan_model_weights("org/x")
+ fetched = sorted(n for n in os.listdir(download) if n.endswith(".safetensors"))
+ assert fetched == [] == list(local.weights)
+ return
+ plan = spectrum_scan.plan_model_weights("org/x")
+ fetched = sorted(n for n in os.listdir(download) if n.endswith(".safetensors"))
+ assert fetched == list(local.weights)
+ assert [name for name, _s, _m in plan.source_files] == list(local.weights)
+ assert len(calls) == (2 if layout == "odd-single" else 1), calls
+
+
+def _hf_cache_snapshot(root: Path, source: Path) -> Path:
+ """Lay ``source`` out as ``models--org--name/snapshots/<sha>/`` with blob links."""
+ repo = root / "models--org--name"
+ blobs = repo / "blobs"
+ snapshot = repo / "snapshots" / ("a" * 40)
+ blobs.mkdir(parents=True)
+ snapshot.mkdir(parents=True)
+ for i, name in enumerate(sorted(p.name for p in source.iterdir())):
+ blob = blobs / f"blob{i:02d}"
+ blob.write_bytes((source / name).read_bytes())
+ os.symlink(str(blob), str(snapshot / name))
+ return snapshot
+
+
+def test_the_snapshot_copy_covers_the_indexed_shards_only(mistral_like, tmp_path, monkeypatch):
+ from soup_cli.utils import spectrum_scan
+
+ snapshot = _hf_cache_snapshot(tmp_path / "hub", mistral_like["dir"])
+ monkeypatch.setattr(spectrum_scan, "resolve_cache_dir", lambda: str(tmp_path / "soup-cache"))
+ entries = spectrum_scan._snapshot_materialization_entries(
+ str(snapshot), source_revision="a" * 40
+ )
+ copied = sorted(rel for rel, _src, _blob in entries if rel.endswith(".safetensors"))
+ assert copied == mistral_like["shards"]
+ plan = spectrum_scan.plan_model_weights(str(snapshot))
+ assert plan.materialize_bytes == mistral_like["shard_bytes"]
+ assert [name for name, _s, _m in plan.source_files] == mistral_like["shards"]
+
+
+# ---------------------------------------------------------------------------
+# The two documented edges
+# ---------------------------------------------------------------------------
+
+
+def test_no_index_and_a_single_model_safetensors_is_counted(tmp_path):
+ from soup_cli.utils.gpu import model_size_from_name
+ from soup_cli.utils.layer_shard import source_weight_bytes
+ from soup_cli.utils.spectrum_scan import plan_model_weights
+
+ cfg, model = _tiny_llama()
+ model.save_pretrained(str(tmp_path))
+ _write_consolidated(model, cfg, tmp_path)
+ true_params = sum(v.numel() for v in model.state_dict().values())
+ assert round(model_size_from_name(str(tmp_path)) * 1e9) == true_params
+ assert [n for n, _s, _m in plan_model_weights(str(tmp_path)).source_files] == [
+ "model.safetensors"
+ ]
+ assert source_weight_bytes(str(tmp_path)) == os.path.getsize(tmp_path / "model.safetensors")
+
+
+def test_consolidated_only_is_refused_naming_the_file(tmp_path):
+ from soup_cli.utils.gpu import _params_from_local_safetensors
+ from soup_cli.utils.layer_shard import source_weight_bytes
+ from soup_cli.utils.spectrum_scan import plan_model_weights, scan_weights_dir
+
+ cfg, model = _tiny_llama()
+ _write_consolidated(model, cfg, tmp_path)
+ (tmp_path / "config.json").write_text(json.dumps(cfg.to_dict()), encoding="utf-8")
+ assert _params_from_local_safetensors(str(tmp_path)) is None
+ for call in (lambda: plan_model_weights(str(tmp_path)),
+ lambda: scan_weights_dir(str(tmp_path)),
+ lambda: source_weight_bytes(str(tmp_path))):
+ with pytest.raises(FileNotFoundError, match="consolidated.safetensors"):
+ call()
+
+
+# ---------------------------------------------------------------------------
+# Small guards, each pinned (#1906 review)
+# ---------------------------------------------------------------------------
+
+
+def test_an_index_with_an_empty_weight_map_is_a_named_failure(tmp_path: Path):
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"metadata": {}, "weight_map": {}}), encoding="utf-8"
+ )
+ with pytest.raises(ValueError, match="no weight_map"):
+ read_index_weight_map(str(tmp_path))
+
+
+def test_an_index_over_the_size_bound_is_a_named_failure(tmp_path: Path, monkeypatch):
+ from soup_cli.utils import checkpoint_files as cf
+
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"a": "model-00001-of-00001.safetensors"}}), encoding="utf-8"
+ )
+ monkeypatch.setattr(cf, "_MAX_INDEX_BYTES", 16) # the real bound is 64 MiB
+ with pytest.raises(ValueError, match="exceeds"):
+ read_index_weight_map(str(tmp_path))
+
+
+def test_an_index_value_with_a_directory_part_resolves_to_its_basename(tmp_path: Path):
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"a": "sub/model-1.safetensors"}}), encoding="utf-8"
+ )
+ assert read_index_weight_map(str(tmp_path)) == {"a": "model-1.safetensors"}
+
+
+def _indexed_dir_with_a_directory_shard(tmp_path: Path) -> tuple[Path, int]:
+ """An index naming two shards, the second of which is a directory, not a file."""
+ import torch
+ from safetensors.torch import save_file
+
+ directory = tmp_path / "ckpt"
+ directory.mkdir()
+ save_file({"w": torch.zeros(3, 5)}, str(directory / "model-00001-of-00002.safetensors"))
+ (directory / "model-00002-of-00002.safetensors").mkdir()
+ (directory / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"w": "model-00001-of-00002.safetensors",
+ "v": "model-00002-of-00002.safetensors"}}),
+ encoding="utf-8",
+ )
+ return directory, 15
+
+
+def test_spectrum_discovery_skips_an_entry_that_is_not_a_file(tmp_path: Path):
+ from soup_cli.utils.spectrum_scan import _discover_safetensors
+
+ directory, _ = _indexed_dir_with_a_directory_shard(tmp_path)
+ found = _discover_safetensors(str(directory))
+ assert [os.path.basename(p) for p in found] == ["model-00001-of-00002.safetensors"]
+
+
+def test_the_size_probe_skips_an_entry_that_is_not_a_file(tmp_path: Path):
+ from soup_cli.utils.gpu import _params_from_local_safetensors
+
+ directory, params = _indexed_dir_with_a_directory_shard(tmp_path)
+ assert _params_from_local_safetensors(str(directory)) == pytest.approx(params / 1e9)