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(layer-stream): refuse a linked blobs directory and a junction inside a cached snapshot (#1629)

Alpamys Makazhan7abd05fc39ae
diff --git a/changelog.d/0.75.1/1629.fixed.md b/changelog.d/0.75.1/1629.fixed.md
new file mode 100644
index 00000000..e52fa89f
--- /dev/null
+++ b/changelog.d/0.75.1/1629.fixed.md
@@ -0,0 +1,6 @@
+- Layer streaming copies a Hugging Face snapshot only from the repo's own `blobs` directory
+ and the marked shared store: a `blobs` directory that is itself a link (a symlink, or a
+ junction on Windows) is now refused with a message naming it instead of being followed,
+ and a junction inside a snapshot directory is refused like a directory symlink. The links
+ huggingface_hub creates, including those into the shared store of 1.32 or later, work as
+ before, and so does a cache or repo folder that was moved as a whole and linked (#1629).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index b971c6a8..ebcabb60 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -863,6 +863,12 @@ metadata request for the regular-file directory. A missing blob or an escaping s
before the destination is published, rather than leaving a partial checkpoint that the sharder
could consume. With huggingface_hub 1.32 or later, links into its marked cache-wide store
(`<cache>/blobs`) are followed too, and any other target is still refused.
+The repo's own `blobs` directory is treated like that store: it has to be a real directory.
+When it is itself a link (a symlink, or a junction on Windows), Soup stops with a message
+naming it instead of following it, so a link in the cache that points outside the cache is
+never followed. To keep a model's files on another disk, move the whole cache or the whole
+repo folder and link that: the snapshot path is resolved first. A junction inside a snapshot
+directory is refused like a directory symlink.
## Correctness First (v0.36.0)
diff --git a/src/soup_cli/utils/spectrum_scan.py b/src/soup_cli/utils/spectrum_scan.py
index f86ed831..e7b81810 100644
--- a/src/soup_cli/utils/spectrum_scan.py
+++ b/src/soup_cli/utils/spectrum_scan.py
@@ -667,6 +667,45 @@ def _hf_shared_blob_root(repo_root: str) -> Optional[str]:
return os.path.realpath(store)
+def _is_junction(path: str) -> bool:
+ """Whether ``path`` is a Windows junction.
+
+ ``os.path.islink`` is false for a junction and ``os.walk`` descends into
+ one, so a junction needs its own check wherever a linked directory is
+ refused. This is the comparison ``os.path.isjunction`` makes (that function
+ needs Python 3.12), except that an ``OSError`` from ``lstat`` is not turned
+ into "not a junction": an entry that cannot be inspected is not waved on.
+ The tag is compared, not the reparse-point attribute, so a directory that
+ carries some other reparse point is not taken for a link.
+ """
+ mount_point = getattr(stat, "IO_REPARSE_TAG_MOUNT_POINT", 0xA0000003)
+ return getattr(os.lstat(path), "st_reparse_tag", 0) == mount_point
+
+
+def _hf_repo_blob_root(repo_root: str) -> str:
+ """The repo's own ``blobs`` store, which has to be a real directory.
+
+ huggingface_hub creates it with ``os.makedirs``. Like the shared store, a
+ linked one (a symlink, or a junction on Windows) points somewhere else, and
+ it is refused without being resolved. The link's target is not compared
+ with any directory: for a local snapshot path the folder around the
+ snapshot is wherever it was put, so there is no limit to hold a target to.
+ """
+ store = os.path.join(repo_root, "blobs")
+ if not os.path.lexists(store):
+ raise FileNotFoundError("cached Hugging Face blob store is missing")
+ if os.path.islink(store) or _is_junction(store):
+ raise ValueError(
+ f"cached Hugging Face blob store {store!r} is a link and is not followed: "
+ "Soup copies weights only from inside the Hugging Face cache; make blobs a "
+ "real directory (to keep the files elsewhere, link the whole repository "
+ "folder instead), or pass a directory of regular files"
+ )
+ if not os.path.isdir(store):
+ raise FileNotFoundError("cached Hugging Face blob store is missing")
+ return os.path.realpath(store)
+
+
def _hf_snapshot_revision(source_dir: str) -> Optional[str]:
"""Commit carried by a canonical ``snapshots/<sha>`` cache directory."""
source = os.path.realpath(os.path.expanduser(source_dir))
@@ -703,10 +742,7 @@ def _snapshot_materialization_entries(
)
if source != expected:
raise ValueError("cached snapshot path does not match its resolved revision")
- blob_root = os.path.realpath(os.path.join(repo_root, "blobs"))
- if not os.path.isdir(blob_root):
- raise FileNotFoundError("cached Hugging Face blob store is missing")
- blob_roots.append(blob_root)
+ blob_roots.append(_hf_repo_blob_root(repo_root))
shared_root = _hf_shared_blob_root(repo_root)
if shared_root is not None:
blob_roots.append(shared_root)
@@ -719,6 +755,10 @@ def _snapshot_materialization_entries(
raise ValueError(
f"cached snapshot directory symlink is not allowed: {dirname!r}"
)
+ if _is_junction(directory):
+ raise ValueError(
+ f"cached snapshot directory junction is not allowed: {dirname!r}"
+ )
for filename in filenames:
if not filename.endswith((".safetensors", ".json")):
continue
diff --git a/tests/test_hf_cache_link_containment.py b/tests/test_hf_cache_link_containment.py
new file mode 100644
index 00000000..c708e043
--- /dev/null
+++ b/tests/test_hf_cache_link_containment.py
@@ -0,0 +1,388 @@
+"""Layer streaming copies a Hugging Face snapshot only from inside its cache.
+
+A snapshot's files are links into the repo's ``blobs`` directory, and with
+huggingface_hub 1.32 or later an entry there may link on into the cache-wide shared
+store. Those links stay inside the cache and are followed. The ``blobs`` directory itself
+has to be a real directory: when it is a link (a symlink, or a junction on Windows) it is
+refused by name, wherever it points. A junction inside a snapshot is refused like a
+directory symlink, because ``os.walk`` descends into one.
+
+A test that needs no symlink builds its snapshot from regular files and a hand-made copy
+plan, so it also runs on a Windows account that cannot create symlinks. The junction check
+is also tested with a supplied answer, so that it is covered on every OS.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+COMMIT = "a" * 40
+WEIGHT_BLOB = "b" * 64
+CONFIG_BLOB = "c" * 40
+XET_HASH = "e" * 64
+WEIGHTS = b"weights kept inside the cache"
+CONFIG = '{"model_type":"llama"}\n'
+OUTSIDE = '{"kept":"outside the blob store"}\n'
+IS_A_LINK = "is a link and is not followed"
+#: Where a linked blob store may point. Every one is refused: the last two stay inside the
+#: repo folder, which for a local snapshot path is whatever folder the snapshot sits in.
+LINK_TARGETS = [
+ "outside-the-cache",
+ "beside-the-repo-folder",
+ "inside-the-repo-folder",
+ "the-repo-folder-itself",
+]
+
+needs_junction = pytest.mark.skipif(
+ os.name != "nt", reason="Windows junctions only exist on Windows"
+)
+
+
+def _repo(tmp_path: Path) -> Path:
+ """``hub/models--org--model`` with a blob store and an empty snapshot directory."""
+ repo = tmp_path / "hub" / "models--org--model"
+ (repo / "blobs").mkdir(parents=True)
+ (repo / "snapshots" / COMMIT).mkdir(parents=True)
+ (repo / "blobs" / WEIGHT_BLOB).write_bytes(WEIGHTS)
+ (repo / "blobs" / CONFIG_BLOB).write_text(CONFIG, encoding="utf-8")
+ return repo
+
+
+def _link_snapshot(repo: Path, *, config: str = CONFIG_BLOB) -> Path:
+ """Fill the snapshot the way huggingface_hub does: relative links into ``blobs``."""
+ snapshot = repo / "snapshots" / COMMIT
+ (snapshot / "model.safetensors").symlink_to(Path("../../blobs") / WEIGHT_BLOB)
+ (snapshot / "config.json").symlink_to(Path("../../blobs") / config)
+ return snapshot
+
+
+def _link_target(tmp_path: Path, repo: Path, where: str) -> Path:
+ """The directory a linked blob store points at, for one of ``LINK_TARGETS``."""
+ return {
+ "outside-the-cache": tmp_path / "outside" / "store",
+ "beside-the-repo-folder": repo.parent / "unrelated",
+ "inside-the-repo-folder": repo / "blob-store",
+ "the-repo-folder-itself": repo,
+ }[where]
+
+
+def _link_blob_store(repo: Path, target: Path, *, junction: bool = False) -> None:
+ """Move the files of ``<repo>/blobs`` into ``target`` and make ``blobs`` a link to it."""
+ target.mkdir(parents=True, exist_ok=True)
+ for blob in (repo / "blobs").iterdir():
+ blob.rename(target / blob.name)
+ (repo / "blobs").rmdir()
+ if junction:
+ import _winapi
+
+ _winapi.CreateJunction(str(target), str(repo / "blobs"))
+ else:
+ (repo / "blobs").symlink_to(target, target_is_directory=True)
+
+
+def _use_shared_store(repo: Path, store: Path) -> None:
+ """Move the weight into ``store`` laid out as huggingface_hub's marked shared store."""
+ (store / XET_HASH[:2]).mkdir(parents=True)
+ (store / ".huggingface-shared-blobs").write_text("1\n", encoding="utf-8")
+ (repo / "blobs" / WEIGHT_BLOB).rename(store / XET_HASH[:2] / XET_HASH)
+
+
+def _blob_store_link(repo: Path) -> str:
+ """The link's own path as the refusal prints it: resolved parents, the link kept."""
+ return os.path.join(os.path.realpath(repo), "blobs")
+
+
+def _weights_root(tmp_path: Path) -> Path:
+ """Soup's ``weights`` directory; a refusal must leave it uncreated."""
+ return tmp_path / "soup-cache" / "weights"
+
+
+def _plan(monkeypatch, tmp_path: Path, snapshot: Path):
+ """The copy plan a Hub id gets when huggingface_hub returns ``snapshot``."""
+ from soup_cli.utils import hubs
+ from soup_cli.utils.spectrum_scan import plan_model_weights
+
+ monkeypatch.setenv("SOUP_SPECTRUM_CACHE_DIR", str(tmp_path / "soup-cache"))
+ monkeypatch.setattr(hubs, "snapshot_download", lambda *_a, **_k: str(snapshot))
+ return plan_model_weights("org/model")
+
+
+def _plan_of_regular_files(monkeypatch, tmp_path: Path, repo: Path):
+ """Write the snapshot's two files as regular files and return a copy plan for them.
+
+ No symlink is needed. It also points Soup's cache into ``tmp_path``. Not for a snapshot
+ that already holds links: the writes would go through them.
+ """
+ from soup_cli.utils.spectrum_scan import ModelWeightsPlan
+
+ snapshot = repo / "snapshots" / COMMIT
+ (snapshot / "model.safetensors").write_bytes(WEIGHTS)
+ (snapshot / "config.json").write_text(CONFIG, encoding="utf-8")
+ monkeypatch.setenv("SOUP_SPECTRUM_CACHE_DIR", str(tmp_path / "soup-cache"))
+ return ModelWeightsPlan(
+ model="org/model",
+ source_dir=str(snapshot),
+ weights_dir=str(_weights_root(tmp_path) / "org__model"),
+ source_bytes=len(WEIGHTS),
+ materialized_copy_bytes=len(WEIGHTS),
+ materialize_bytes=len(WEIGHTS),
+ source_files=(("model.safetensors", len(WEIGHTS), 0),),
+ source_revision=COMMIT,
+ )
+
+
+def _assert_copied(resolved: Path) -> None:
+ assert not (resolved / "model.safetensors").is_symlink()
+ assert (resolved / "model.safetensors").read_bytes() == WEIGHTS
+ assert (resolved / "config.json").read_text(encoding="utf-8") == CONFIG
+
+
+def _assert_refused_as_a_link(refusal, repo: Path, tmp_path: Path) -> None:
+ message = str(refusal.value)
+ assert repr(_blob_store_link(repo)) in message
+ assert "Soup copies weights only from inside the Hugging Face cache" in message
+ assert not _weights_root(tmp_path).exists()
+
+
+# --- the links huggingface_hub creates, and regular files, keep working -------------
+
+
[email protected]("layout", ["repo-blob-store", "shared-blob-store"])
+def test_links_that_stay_inside_the_cache_are_copied(tmp_path, monkeypatch, layout) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ if layout == "shared-blob-store":
+ _use_shared_store(repo, repo.parent / "blobs")
+ (repo / "blobs" / WEIGHT_BLOB).symlink_to(
+ Path("../../blobs") / XET_HASH[:2] / XET_HASH
+ )
+ plan = _plan(monkeypatch, tmp_path, _link_snapshot(repo))
+
+ _assert_copied(Path(materialize_model_weights(plan)))
+
+
+def test_regular_file_beside_a_linked_weight_is_copied(tmp_path, monkeypatch) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ snapshot = repo / "snapshots" / COMMIT
+ (snapshot / "model.safetensors").symlink_to(Path("../../blobs") / WEIGHT_BLOB)
+ (snapshot / "config.json").write_text(CONFIG, encoding="utf-8")
+ plan = _plan(monkeypatch, tmp_path, snapshot)
+
+ _assert_copied(Path(materialize_model_weights(plan)))
+
+
+def test_snapshot_of_regular_files_is_copied(tmp_path, monkeypatch) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, _repo(tmp_path))
+
+ _assert_copied(Path(materialize_model_weights(plan)))
+
+
+def test_real_subdirectory_inside_a_snapshot_is_copied(tmp_path, monkeypatch) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ subdirectory = repo / "snapshots" / COMMIT / "onnx"
+ subdirectory.mkdir()
+ (subdirectory / "config.json").write_text(CONFIG, encoding="utf-8")
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+
+ resolved = Path(materialize_model_weights(plan))
+
+ _assert_copied(resolved)
+ assert (resolved / "onnx" / "config.json").read_text(encoding="utf-8") == CONFIG
+
+
+# --- a linked blob store is refused, wherever it points -----------------------------
+
+
[email protected]("where", LINK_TARGETS)
+def test_blob_store_symlink_is_refused(tmp_path, monkeypatch, where) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ target = _link_target(tmp_path, repo, where)
+ _link_blob_store(repo, target)
+ (target / "notes.json").write_text(OUTSIDE, encoding="utf-8")
+ plan = _plan(monkeypatch, tmp_path, _link_snapshot(repo, config="notes.json"))
+
+ with pytest.raises(ValueError, match=IS_A_LINK) as refusal:
+ materialize_model_weights(plan)
+
+ _assert_refused_as_a_link(refusal, repo, tmp_path)
+
+
+@needs_junction
[email protected]("where", LINK_TARGETS)
+def test_blob_store_junction_is_refused(tmp_path, monkeypatch, where) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ _link_blob_store(repo, _link_target(tmp_path, repo, where), junction=True)
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+
+ with pytest.raises(ValueError, match=IS_A_LINK) as refusal:
+ materialize_model_weights(plan)
+
+ _assert_refused_as_a_link(refusal, repo, tmp_path)
+
+
+def test_blob_store_reported_as_a_junction_is_refused(tmp_path, monkeypatch) -> None:
+ """The junction half of the check on every OS: a real directory, a supplied answer."""
+ from soup_cli.utils import spectrum_scan
+
+ repo = _repo(tmp_path)
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+ monkeypatch.setattr(
+ spectrum_scan, "_is_junction", lambda path: os.path.basename(path) == "blobs"
+ )
+
+ with pytest.raises(ValueError, match=IS_A_LINK) as refusal:
+ spectrum_scan.materialize_model_weights(plan)
+
+ _assert_refused_as_a_link(refusal, repo, tmp_path)
+
+
+def test_dangling_blob_store_link_is_refused_as_a_link(tmp_path, monkeypatch) -> None:
+ """A linked blob store is named as a link even when its target is gone."""
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ plan = _plan(monkeypatch, tmp_path, _link_snapshot(repo))
+ target = _link_target(tmp_path, repo, "outside-the-cache")
+ _link_blob_store(repo, target)
+ for blob in target.iterdir():
+ blob.unlink()
+ target.rmdir()
+
+ with pytest.raises(ValueError, match=IS_A_LINK) as refusal:
+ materialize_model_weights(plan)
+
+ _assert_refused_as_a_link(refusal, repo, tmp_path)
+
+
[email protected]("left_behind", ["nothing", "a-regular-file"])
+def test_missing_blob_store_is_reported(tmp_path, monkeypatch, left_behind) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ for blob in (repo / "blobs").iterdir():
+ blob.unlink()
+ (repo / "blobs").rmdir()
+ if left_behind == "a-regular-file":
+ (repo / "blobs").write_text("not a directory\n", encoding="utf-8")
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+
+ with pytest.raises(FileNotFoundError, match="cached Hugging Face blob store is missing"):
+ materialize_model_weights(plan)
+
+ assert not _weights_root(tmp_path).exists()
+
+
+@needs_junction
+def test_shared_store_that_is_a_junction_is_not_used(tmp_path, monkeypatch) -> None:
+ """The shared store has the same rule; a junction there leaves the weight outside."""
+ import _winapi
+
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ elsewhere = tmp_path / "outside" / "shared"
+ _use_shared_store(repo, elsewhere)
+ _winapi.CreateJunction(str(elsewhere), str(repo.parent / "blobs"))
+ (repo / "blobs" / WEIGHT_BLOB).symlink_to(Path("../../blobs") / XET_HASH[:2] / XET_HASH)
+ plan = _plan(monkeypatch, tmp_path, _link_snapshot(repo))
+
+ with pytest.raises(ValueError, match="points outside the Hugging Face blob store"):
+ materialize_model_weights(plan)
+
+ assert not _weights_root(tmp_path).exists()
+
+
+# --- a linked directory inside a snapshot is refused --------------------------------
+
+
+def _outside_directory(tmp_path: Path) -> Path:
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "notes.json").write_text(OUTSIDE, encoding="utf-8")
+ return outside
+
+
+def test_symlinked_directory_inside_a_snapshot_is_refused(tmp_path, monkeypatch) -> None:
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ snapshot = _link_snapshot(repo)
+ (snapshot / "extra").symlink_to(_outside_directory(tmp_path), target_is_directory=True)
+ plan = _plan(monkeypatch, tmp_path, snapshot)
+
+ with pytest.raises(ValueError, match="directory symlink is not allowed: 'extra'"):
+ materialize_model_weights(plan)
+
+ assert not _weights_root(tmp_path).exists()
+
+
+@needs_junction
+def test_junction_inside_a_snapshot_is_refused(tmp_path, monkeypatch) -> None:
+ import _winapi
+
+ from soup_cli.utils.spectrum_scan import materialize_model_weights
+
+ repo = _repo(tmp_path)
+ _winapi.CreateJunction(
+ str(_outside_directory(tmp_path)), str(repo / "snapshots" / COMMIT / "extra")
+ )
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+
+ with pytest.raises(ValueError, match="directory junction is not allowed: 'extra'"):
+ materialize_model_weights(plan)
+
+ assert not _weights_root(tmp_path).exists()
+
+
+def test_directory_reported_as_a_junction_is_refused(tmp_path, monkeypatch) -> None:
+ """The snapshot walk's refusal on every OS: a real directory, a supplied answer."""
+ from soup_cli.utils import spectrum_scan
+
+ repo = _repo(tmp_path)
+ (repo / "snapshots" / COMMIT / "extra").mkdir()
+ plan = _plan_of_regular_files(monkeypatch, tmp_path, repo)
+ monkeypatch.setattr(
+ spectrum_scan, "_is_junction", lambda path: os.path.basename(path) == "extra"
+ )
+
+ with pytest.raises(ValueError, match="directory junction is not allowed: 'extra'"):
+ spectrum_scan.materialize_model_weights(plan)
+
+ assert not _weights_root(tmp_path).exists()
+
+
+ ("reparse_tag", "expected"),
+ [(0xA0000003, True), (0xA000000C, False), (None, False)],
+ ids=["mount-point", "symlink", "no-reparse-tag"],
+)
+def test_junction_check_reads_the_mount_point_tag(monkeypatch, reparse_tag, expected) -> None:
+ """On every OS: the stat result is supplied, the comparison is the code's own."""
+ from soup_cli.utils import spectrum_scan
+
+ fields = {} if reparse_tag is None else {"st_reparse_tag": reparse_tag}
+ info = SimpleNamespace(**fields)
+ monkeypatch.setattr(spectrum_scan, "os", SimpleNamespace(lstat=lambda _path: info))
+
+ assert spectrum_scan._is_junction("snapshots/extra") is expected