Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(layer-stream): materialize snapshots whose blobs live in huggingface_hub's shared store (#1509) (#1510)
Alberto Cucca1d52d3a38e9c
diff --git a/changelog.d/0.75.1/1510.fixed.md b/changelog.d/0.75.1/1510.fixed.mdnew file mode 100644index 00000000..f2535b39--- /dev/null+++ b/changelog.d/0.75.1/1510.fixed.md@@ -0,0 +1,3 @@+- Layer streaming now materializes models cached by huggingface_hub 1.32 or later,+ whose Xet blobs live in the cache-wide shared blob store; links that leave both the+ repo's blob store and the marked shared store are still refused (#1509 by @bobbonauta in #1510).diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 2ea43732..b971c6a8 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -861,7 +861,8 @@ snapshot is complete. Soup pins the commit resolved by the initial cache lookuponly verified snapshot files from that commit's blob store; it does not perform a second Hubmetadata request for the regular-file directory. A missing blob or an escaping symlink abortsbefore the destination is published, rather than leaving a partial checkpoint that the sharder-could consume.+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.## Correctness First (v0.36.0)diff --git a/src/soup_cli/utils/spectrum_scan.py b/src/soup_cli/utils/spectrum_scan.pyindex 9f6bd7da..f86ed831 100644--- a/src/soup_cli/utils/spectrum_scan.py+++ b/src/soup_cli/utils/spectrum_scan.py@@ -612,7 +612,7 @@ def _materialized_matches_hf_snapshot(source_path = os.path.join(source_dir, name)if not os.path.islink(source_path):return None- blob_id = os.path.basename(os.path.realpath(source_path))+ blob_id = _hf_blob_id(source_path)metadata_path = os.path.join(materialized_dir,".cache",@@ -635,6 +635,38 @@ def _materialized_matches_hf_snapshot(return existing+def _hf_blob_id(snapshot_path: str) -> str:+ """The per-repo ``blobs/<etag>`` name a snapshot link points at.++ Not the final target: huggingface_hub >= 1.32 may chain that entry to its+ cache-wide Xet store, whose file is named by the Xet hash instead.+ """+ return os.path.basename(os.readlink(snapshot_path))+++def _hf_shared_blob_root(repo_root: str) -> Optional[str]:+ """The cache-wide ``<cache>/blobs`` store of huggingface_hub >= 1.32, if marked.++ Per-repo ``blobs/<etag>`` entries of Xet downloads are relative symlinks into+ it; huggingface_hub writes the ``.huggingface-shared-blobs`` marker file.+ Like huggingface_hub's ``is_shared_blobs_dir``, neither the directory nor the+ marker may be a link: a linked store points somewhere else.+ """+ store = os.path.join(os.path.dirname(repo_root), "blobs")+ marker = os.path.join(store, ".huggingface-shared-blobs")+ try:+ store_stat = os.lstat(store)+ marker_stat = os.lstat(marker)+ except OSError:+ return None+ if not stat.S_ISDIR(store_stat.st_mode) or not stat.S_ISREG(marker_stat.st_mode):+ return None+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if getattr(store_stat, "st_file_attributes", 0) & reparse:+ return None+ 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))@@ -652,8 +684,10 @@ def _snapshot_materialization_entries("""Validate and list cached files before any destination is created.Canonical Hugging Face snapshots contain symlinks into their sibling- ``blobs`` directory. Only those links are followed: a crafted snapshot- cannot turn Soup's regular-file copy into an arbitrary-file disclosure.+ ``blobs`` directory, whose Xet entries may in turn link into the+ cache-wide shared blob store. Only links resolving into one of those two+ stores are followed: a crafted snapshot cannot turn Soup's regular-file+ copy into an arbitrary-file disclosure."""from soup_cli.utils.paths import is_under@@ -661,7 +695,7 @@ def _snapshot_materialization_entries(if not os.path.isdir(source):raise FileNotFoundError(f"cached snapshot directory not found: {source_dir}")- blob_root = None+ blob_roots: list[str] = []if source_revision is not None:repo_root = os.path.dirname(os.path.dirname(source))expected = os.path.realpath(@@ -672,6 +706,10 @@ def _snapshot_materialization_entries(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)+ shared_root = _hf_shared_blob_root(repo_root)+ if shared_root is not None:+ blob_roots.append(shared_root)entries: list[Tuple[str, str, Optional[str]]] = []for root, dirnames, filenames in os.walk(source, followlinks=False):@@ -689,12 +727,12 @@ def _snapshot_materialization_entries(blob_id = Noneif os.path.islink(snapshot_path):resolved = os.path.realpath(snapshot_path)- if blob_root is not None and not is_under(resolved, blob_root):+ if blob_roots and not any(is_under(resolved, r) for r in blob_roots):raise ValueError(f"cached snapshot file {relative!r} points outside the ""Hugging Face blob store")- blob_id = os.path.basename(resolved)+ blob_id = _hf_blob_id(snapshot_path)else:resolved = snapshot_pathif not os.path.isfile(resolved):diff --git a/tests/test_hf_shared_blob_store.py b/tests/test_hf_shared_blob_store.pynew file mode 100644index 00000000..a300fad0--- /dev/null+++ b/tests/test_hf_shared_blob_store.py@@ -0,0 +1,177 @@+"""Layer streaming over huggingface_hub's cache-wide shared blob store.++Since huggingface_hub 1.32, a Xet download stores its bytes once per cache in+``<cache>/blobs/<2-hex>/<xet-hash>`` (a directory marked with+``.huggingface-shared-blobs``); the per-repo ``blobs/<etag>`` entry becomes a+relative symlink to it. Soup must copy such a snapshot, and still refuse links+that leave both stores.+"""++from __future__ import annotations++import os+from pathlib import Path++import pytest++COMMIT = "a" * 40+ETAG = "b" * 64+XET_HASH = "c" * 64+CONFIG_BLOB = "d" * 40+++def _shared_store_snapshot(tmp_path: Path, *, marker: bool = True) -> tuple[Path, Path]:+ import torch+ from safetensors.torch import save_file++ repo = tmp_path / "models--org--model"+ blobs = repo / "blobs"+ snapshot = repo / "snapshots" / COMMIT+ store = tmp_path / "blobs"+ for directory in (blobs, snapshot, store / XET_HASH[:2]):+ directory.mkdir(parents=True)+ if marker:+ (store / ".huggingface-shared-blobs").write_text("1\n", encoding="utf-8")++ shared = store / XET_HASH[:2] / XET_HASH+ save_file({"model.layers.0.self_attn.q_proj.weight": torch.eye(2)}, str(shared))+ (blobs / ETAG).symlink_to(Path("../../blobs") / XET_HASH[:2] / XET_HASH)+ (blobs / CONFIG_BLOB).write_text('{"model_type":"llama"}\n', encoding="utf-8")+ (snapshot / "model.safetensors").symlink_to(Path("../../blobs") / ETAG)+ (snapshot / "config.json").symlink_to(Path("../../blobs") / CONFIG_BLOB)+ return snapshot, shared+++def _use_snapshot(monkeypatch, tmp_path: Path, snapshot: Path) -> Path:+ from soup_cli.utils import hubs++ cache_root = tmp_path / "soup-cache"+ monkeypatch.setenv("SOUP_SPECTRUM_CACHE_DIR", str(cache_root))+ monkeypatch.setattr(hubs, "snapshot_download", lambda *_a, **_k: str(snapshot))+ return cache_root++[email protected]_symlink+def test_shared_store_snapshot_is_materialized(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.layer_shard import shard_checkpoint+ from soup_cli.utils.spectrum_scan import resolve_model_weights++ snapshot, shared = _shared_store_snapshot(tmp_path)+ cache_root = _use_snapshot(monkeypatch, tmp_path, snapshot)++ resolved = Path(resolve_model_weights("org/model"))++ assert resolved == cache_root / "weights" / "org__model"+ assert not (resolved / "model.safetensors").is_symlink()+ assert (resolved / "model.safetensors").read_bytes() == shared.read_bytes()+ metadata = (+ resolved / ".cache" / "huggingface" / "download" / "model.safetensors.metadata"+ ).read_text(encoding="utf-8").splitlines()+ # the recorded blob id is the repo's etag, not the shared store's Xet hash+ assert metadata[:2] == [COMMIT, ETAG]+ index = shard_checkpoint(+ str(resolved), str(tmp_path / "shards"), dtype="float32", arch="llama"+ )+ assert index.n_layers == 1++[email protected]_symlink+def test_shared_store_copy_is_reused(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.spectrum_scan import plan_model_weights, resolve_model_weights++ snapshot, _shared = _shared_store_snapshot(tmp_path)+ _use_snapshot(monkeypatch, tmp_path, snapshot)+ resolve_model_weights("org/model")++ plan = plan_model_weights("org/model")++ assert plan.materialize_bytes == 0+ assert plan.materialized_copy_bytes > 0++[email protected]_symlink+def test_unmarked_sibling_blobs_dir_is_not_trusted(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.spectrum_scan import materialize_model_weights, plan_model_weights++ snapshot, _shared = _shared_store_snapshot(tmp_path, marker=False)+ _use_snapshot(monkeypatch, tmp_path, snapshot)+ plan = plan_model_weights("org/model")++ with pytest.raises(ValueError, match="outside the Hugging Face blob store"):+ materialize_model_weights(plan)++ assert not os.path.lexists(plan.weights_dir)++[email protected]_symlink+def test_link_leaving_both_stores_is_still_refused(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.spectrum_scan import materialize_model_weights, plan_model_weights++ snapshot, _shared = _shared_store_snapshot(tmp_path)+ outside = tmp_path / "outside.json"+ outside.write_text('{"unsafe":true}\n', encoding="utf-8")+ (snapshot / "config.json").unlink()+ (snapshot / "config.json").symlink_to(outside)+ _use_snapshot(monkeypatch, tmp_path, snapshot)+ plan = plan_model_weights("org/model")++ with pytest.raises(ValueError, match="outside the Hugging Face blob store"):+ materialize_model_weights(plan)++ assert not os.path.lexists(plan.weights_dir)+++def _snapshot_with_store(tmp_path: Path, store: Path) -> Path:+ import torch+ from safetensors.torch import save_file++ repo = tmp_path / "hub" / "models--org--model"+ blobs = repo / "blobs"+ snapshot = repo / "snapshots" / COMMIT+ for directory in (blobs, snapshot, store / XET_HASH[:2]):+ directory.mkdir(parents=True, exist_ok=True)+ save_file(+ {"model.layers.0.self_attn.q_proj.weight": torch.eye(2)},+ str(store / XET_HASH[:2] / XET_HASH),+ )+ (blobs / ETAG).symlink_to(Path("../../blobs") / XET_HASH[:2] / XET_HASH)+ (snapshot / "model.safetensors").symlink_to(Path("../../blobs") / ETAG)+ return snapshot+++def _plan(monkeypatch, tmp_path: Path, snapshot: Path):+ from soup_cli.utils.spectrum_scan import plan_model_weights++ _use_snapshot(monkeypatch, tmp_path, snapshot)+ return plan_model_weights("org/model")++[email protected]_symlink+def test_symlinked_marker_is_not_trusted(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.spectrum_scan import materialize_model_weights++ store = tmp_path / "hub" / "blobs"+ snapshot = _snapshot_with_store(tmp_path, store)+ real_marker = tmp_path / "elsewhere-marker"+ real_marker.write_text("1\n", encoding="utf-8")+ (store / ".huggingface-shared-blobs").symlink_to(real_marker)+ plan = _plan(monkeypatch, tmp_path, snapshot)++ with pytest.raises(ValueError, match="outside the Hugging Face blob store"):+ materialize_model_weights(plan)+ assert not os.path.lexists(plan.weights_dir)++[email protected]_symlink+def test_symlinked_store_directory_is_not_trusted(tmp_path, monkeypatch) -> None:+ from soup_cli.utils.spectrum_scan import materialize_model_weights++ outside = tmp_path / "outside-store"+ snapshot = _snapshot_with_store(tmp_path, outside)+ (outside / ".huggingface-shared-blobs").write_text("1\n", encoding="utf-8")+ (tmp_path / "hub" / "blobs").symlink_to(outside, target_is_directory=True)+ plan = _plan(monkeypatch, tmp_path, snapshot)++ with pytest.raises(ValueError, match="outside the Hugging Face blob store"):+ materialize_model_weights(plan)+ assert not os.path.lexists(plan.weights_dir)