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(stream): report a reusable layer-shard cache at its real size in the disk pre-flight (#1709)

Younes Beriane1aecae0d1dc9
diff --git a/changelog.d/0.76.0/1709.fixed.md b/changelog.d/0.76.0/1709.fixed.md
new file mode 100644
index 00000000..f0bb9977
--- /dev/null
+++ b/changelog.d/0.76.0/1709.fixed.md
@@ -0,0 +1,8 @@
+- **The layer-streaming disk pre-flight reported a reusable cache at the size it
+ would have if it were rewritten, not at the size of the files it keeps (#1703).**
+ When the cache is reusable, `Layer-shard cache: ... GB (reusable)` and the
+ projected total now add up the cache's own files (`index.json`, the extras shard,
+ the large shards and every layer file, wherever it is striped), and a measured
+ size is not labelled "approximately". Other files in the folder are not counted,
+ and a cache file that cannot be measured keeps the estimate (#1703 by @drakeo338
+ in #1709).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index f62b1b45..39ebfc43 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -851,6 +851,9 @@ head and extras); when a header cannot be read or the model is qwen4_exp the spl
even and the panel says approximately. Override the two cache roots with
`SOUP_SPECTRUM_CACHE_DIR` and `SOUP_LAYER_STREAM_CACHE_DIR`; both retain Soup's
home/cwd/tmp containment policy.
+A shard cache Soup will reuse is reported at the size of its own files, on every drive it is
+striped over; one it has to write is reported at the estimate, or with two or more drives at
+the larger of the estimate and the bytes derived from the source headers.
**Two or more NVMe drives.** On a cold store larger than RAM the disk-tier step can wait on the
read (measured for a 70B-shaped store), and then one drive is the ceiling. Set
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 66d96df5..6001f508 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -709,6 +709,7 @@ class StreamingSetupMixin:
inspect_shard_cache,
layer_paths,
resolve_shard_dir,
+ shard_cache_disk_bytes,
shard_checkpoint,
source_weight_bytes,
stripe_dirs,
@@ -829,6 +830,11 @@ class StreamingSetupMixin:
"qwen4_ple" if arch == "qwen4_exp" else "",
stripe_roots=stripe_roots,
)
+ cached_bytes = None
+ if cached is not None:
+ cached_bytes = shard_cache_disk_bytes(shard_dir, cached)
+ if cached_bytes is not None:
+ shard_estimate = cached_bytes
write_total = 0 if cached is not None else shard_estimate
shares, approximate = estimate_stripe_write_shares(
weights_plan.weights_dir,
@@ -850,7 +856,7 @@ class StreamingSetupMixin:
shard_write_bytes=shares[0],
shard_path=shard_dir,
stripe_writes=tuple(zip(dirs[1:], shares[1:])),
- approximate=approximate,
+ approximate=approximate and cached_bytes is None, # a measured cache is exact
)
weights_dir = resolve_model_weights(
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index 7eb4c904..70622f66 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -1847,6 +1847,22 @@ def _folder_bytes(folder: str) -> int:
return total
+def shard_cache_disk_bytes(shard_dir: str, index: ShardIndex) -> Optional[int]:
+ """Bytes of the files a reusable cache is made of, or ``None`` if one cannot be measured.
+
+ Only what the cache check requires is counted: the index, the extras shard, each large
+ shard and each layer file wherever it is placed. A stray or stale file in the folder is
+ not part of the cache, and a file that cannot be read makes the caller keep its estimate.
+ """
+ paths = [os.path.join(shard_dir, _INDEX_NAME), extras_shard_path(shard_dir)]
+ paths.extend(large_shard_path(shard_dir, key) for key in index.large_keys)
+ paths.extend(layer_paths(shard_dir, index))
+ try:
+ return sum(os.path.getsize(path) for path in paths)
+ except (OSError, ValueError):
+ return None
+
+
def _notify_orphaned_stripes(
out_dir: str, keep: Sequence[str], notify: Callable[[str], None]
) -> None:
diff --git a/tests/test_disk_tier_stripe_setup.py b/tests/test_disk_tier_stripe_setup.py
index c5809ab5..4debb29a 100644
--- a/tests/test_disk_tier_stripe_setup.py
+++ b/tests/test_disk_tier_stripe_setup.py
@@ -5,6 +5,7 @@ import inspect
import io
import json
import os
+import re
import struct
from types import SimpleNamespace
@@ -12,6 +13,7 @@ import pytest
from rich.console import Console
from soup_cli.trainer import stream_setup
+from soup_cli.utils import layer_shard
from soup_cli.utils.async_disk_source import DEFAULT_STREAM_READ_AHEAD, MAX_STREAM_READ_AHEAD
@@ -550,3 +552,223 @@ class TestTheSetupPathUsesTheRoots:
assert calls, "the striped setup never asked for the exact shares"
assert {"dtype", "quant", "double_quant", "arch"} <= set(calls[0])
assert calls[0]["arch"] == "llama"
+
+
+# The tiny checkpoint ties its embeddings, so its cache has no large shard: a `large_*` file in
+# a cache folder is a stale one, and is left out of the oracle on purpose.
+_CACHE_FILE = re.compile(r"^(index\.json|extras\.safetensors|layer_\d+\.safetensors)$")
+
+
+def _cache_folders(tmp_path):
+ """Every folder a cache lives in: the primary one and each stripe folder."""
+ found = []
+ for top in (tmp_path / "cache", tmp_path / "second-drive"):
+ for folder, _dirs, names in os.walk(top):
+ if any(_CACHE_FILE.match(name) for name in names):
+ found.append(folder)
+ return found
+
+
+def _primary_folder(tmp_path):
+ """The one folder holding ``index.json``: the cache's primary folder."""
+ (folder,) = [f for f in _cache_folders(tmp_path) if "index.json" in os.listdir(f)]
+ return folder
+
+
+def _cache_files_bytes(tmp_path):
+ """The files the cache is made of, picked by name, so a stray file is never in the sum."""
+ return sum(
+ os.path.getsize(os.path.join(folder, name))
+ for folder in _cache_folders(tmp_path)
+ for name in os.listdir(folder)
+ if _CACHE_FILE.match(name)
+ )
+
+
+def _drop_strays(tmp_path):
+ """Junk a cache folder can hold: a half-written temp file, a note, a stale large shard."""
+ assert not any(n.startswith("large_") for f in _cache_folders(tmp_path) for n in os.listdir(f))
+ for folder in _cache_folders(tmp_path):
+ for name in (".soup.x.tmp", "notes.bin"):
+ with open(os.path.join(folder, name), "wb") as handle:
+ handle.write(b"x" * 100_000)
+ with open(os.path.join(folder, "large_embed.safetensors"), "wb") as handle:
+ handle.write(b"x" * 100_000)
+
+
+class TestAReusableCacheIsReportedAtItsRealSize:
+ @pytest.mark.parametrize("striped", [False, True])
+ def test_reusable_cache_reports_its_files_not_the_estimate(
+ self, tmp_path, monkeypatch, striped
+ ):
+ _drive_setup(tmp_path, monkeypatch, striped=striped) # builds the cache
+ _drop_strays(tmp_path)
+ _captured, said, _second_drive, seen = _drive_setup(
+ tmp_path, monkeypatch, striped=striped
+ )
+ assert "(reusable)" in said
+ assert seen[-1]["shard_write_bytes"] == 0
+ assert all(share == 0 for _dir, share in seen[-1]["stripe_writes"])
+ assert seen[-1]["shard_bytes"] == _cache_files_bytes(tmp_path)
+
+ def test_a_measured_cache_is_not_called_approximate(self, tmp_path, monkeypatch):
+ """qwen4_exp's even-split fallback says "approximately"; a measured size is exact."""
+ _drive_setup(tmp_path, monkeypatch, striped=True) # builds the cache
+ real = stream_setup.estimate_stripe_write_shares
+
+ def as_qwen4_exp(*args, **kwargs):
+ return real(*args, **{**kwargs, "arch": "qwen4_exp"})
+
+ monkeypatch.setattr(stream_setup, "estimate_stripe_write_shares", as_qwen4_exp)
+ assert real(None, total_bytes=0, n_roots=2, arch="qwen4_exp")[1] is True
+ _captured, said, _second_drive, seen = _drive_setup(tmp_path, monkeypatch, striped=True)
+ assert "(reusable)" in said
+ assert seen[-1]["shard_bytes"] == _cache_files_bytes(tmp_path)
+ assert seen[-1]["approximate"] is False
+ assert "approximately" not in said
+
+ def test_a_file_that_cannot_be_measured_keeps_the_estimate(self, tmp_path, monkeypatch):
+ captured, _said, _drive, seen = _drive_setup(tmp_path, monkeypatch, striped=False)
+ estimate = seen[-1]["shard_bytes"] # the first run writes the cache: a plain estimate
+ index = captured["index"]
+ shard_dir = _primary_folder(tmp_path)
+ assert layer_shard.shard_cache_disk_bytes(shard_dir, index) is not None
+ monkeypatch.setattr(layer_shard, "shard_cache_disk_bytes", lambda *_a: None)
+ _captured, _said, _drive, seen = _drive_setup(tmp_path, monkeypatch, striped=False)
+ assert seen[-1]["shard_write_bytes"] == 0
+ assert seen[-1]["shard_bytes"] == estimate
+
+ def test_a_deleted_layer_file_is_not_measured(self, tmp_path, monkeypatch):
+ captured, _said, _drive, _preflight = _drive_setup(tmp_path, monkeypatch, striped=False)
+ index = captured["index"]
+ shard_dir = _primary_folder(tmp_path)
+ os.remove(layer_shard.layer_paths(shard_dir, index)[0])
+ assert layer_shard.shard_cache_disk_bytes(shard_dir, index) is None
+
+ def test_a_cache_file_lost_after_the_check_does_not_fail_the_preflight(
+ self, tmp_path, monkeypatch
+ ):
+ """The file goes between `inspect_shard_cache` and the sizing; the estimate stays."""
+ captured, _said, _drive, seen = _drive_setup(tmp_path, monkeypatch, striped=True)
+ estimate = seen[-1]["shard_bytes"] # the first run writes the cache: a plain estimate
+ assert _cache_files_bytes(tmp_path) != estimate # else the last assert proves nothing
+ primary = _primary_folder(tmp_path)
+ victim = layer_shard.layer_paths(primary, captured["index"])[1] # on the second drive
+ assert os.path.exists(victim) and os.path.dirname(victim) != primary
+ real = layer_shard.inspect_shard_cache
+ lost = []
+
+ def inspect_then_lose_a_file(*args, **kwargs):
+ result = real(*args, **kwargs)
+ if not lost and result[0] is not None:
+ os.remove(victim)
+ lost.append(victim)
+ return result
+
+ monkeypatch.setattr(layer_shard, "inspect_shard_cache", inspect_then_lose_a_file)
+ _captured, _said, _drive, seen = _drive_setup( # must not raise
+ tmp_path, monkeypatch, striped=True
+ )
+ assert lost == [victim]
+ assert seen[-1]["shard_write_bytes"] == 0
+ assert seen[-1]["shard_bytes"] == estimate
+
+ def test_an_untied_striped_cache_counts_its_vocabulary_shards(self, tmp_path):
+ """The tied fixture above has no `large_*` file; an untied checkpoint writes two."""
+ from tests.test_disk_tier_stripe_runtime import _tiny_llama
+
+ weights = _tiny_llama(tmp_path, tie=False)
+ stripe = tmp_path / "stripe"
+ stripe.mkdir()
+ cache = str(tmp_path / "cache" / "tiny")
+ index = layer_shard.shard_checkpoint(
+ weights, cache, dtype="float32", arch="llama", stripe_roots=(str(stripe),)
+ )
+ assert index.large_keys and index.layer_roots == (0, 1, 0)
+ folders = layer_shard.stripe_dirs(cache, index.stripe_roots)
+ files = [
+ os.path.join(folder, name)
+ for folder in folders
+ for name in os.listdir(folder)
+ if name != layer_shard.STRIPE_MARKER_NAME
+ ]
+ assert any(os.path.basename(path).startswith("large_") for path in files)
+ assert layer_shard.shard_cache_disk_bytes(cache, index) == sum(
+ os.path.getsize(path) for path in files
+ )
+
+
+class TestRefusalIsUnchanged:
+ """Reporting the real size must not move what the pre-flight refuses."""
+
+ @staticmethod
+ def _free(monkeypatch, free):
+ monkeypatch.setattr(stream_setup, "_disk_volume", lambda _path: (1, free))
+
+ @pytest.mark.parametrize("free", [1, 10_000_000_000])
+ def test_a_reusable_cache_needs_no_space(self, tmp_path, monkeypatch, free):
+ _drive_setup(tmp_path, monkeypatch, striped=False)
+ self._free(monkeypatch, free)
+ _captured, said, _drive, _preflight = _drive_setup(tmp_path, monkeypatch, striped=False)
+ assert "(reusable)" in said
+
+ @pytest.mark.parametrize("free, refused", [(1, True), (10_000_000_000, False)])
+ def test_a_missing_cache_is_refused_only_without_room(
+ self, tmp_path, monkeypatch, free, refused
+ ):
+ self._free(monkeypatch, free)
+ if refused:
+ with pytest.raises(ValueError, match="additional disk space"):
+ _drive_setup(tmp_path, monkeypatch, striped=False)
+ else:
+ _drive_setup(tmp_path, monkeypatch, striped=False)
+
+ @pytest.mark.parametrize("free, refused", [(1, True), (10_000_000_000, False)])
+ def test_a_materialization_is_refused_only_without_room(
+ self, tmp_path, monkeypatch, free, refused
+ ):
+ monkeypatch.setattr(stream_setup, "console", Console(file=io.StringIO()))
+ monkeypatch.setattr(stream_setup, "_disk_volume", lambda _path: (1, free))
+ args = dict(
+ source_bytes=1000,
+ materialized_copy_bytes=500,
+ materialize_bytes=500,
+ materialized_path=str(tmp_path / "weights"),
+ shard_bytes=300, # the real size of a cache we keep
+ shard_write_bytes=0,
+ shard_path=str(tmp_path / "shards"),
+ )
+ if refused:
+ with pytest.raises(ValueError, match="additional disk space"):
+ stream_setup._render_stream_disk_preflight(**args)
+ else:
+ stream_setup._render_stream_disk_preflight(**args)
+
+ @pytest.mark.parametrize("copy_bytes, refused", [(2_000_000_000, True), (100_000_000, False)])
+ @pytest.mark.parametrize("cache_exists", [False, True])
+ def test_a_materialization_through_the_setup_is_refused_only_without_room(
+ self, tmp_path, monkeypatch, copy_bytes, refused, cache_exists
+ ):
+ """The copy is charged through the setup's own call, with or without a cache on disk."""
+ import dataclasses
+
+ import soup_cli.utils.spectrum_scan as spectrum_scan
+
+ if cache_exists:
+ _drive_setup(tmp_path, monkeypatch, striped=False)
+
+ def needs_a_copy(model, *, before_materialize=None):
+ plan = spectrum_scan.plan_model_weights(model)
+ plan = dataclasses.replace(
+ plan, materialize_bytes=copy_bytes, materialized_copy_bytes=copy_bytes
+ )
+ before_materialize(plan)
+ return plan.weights_dir
+
+ monkeypatch.setattr(spectrum_scan, "resolve_model_weights", needs_a_copy)
+ self._free(monkeypatch, 1_000_000_000) # the tiny cache fits; the copy decides
+ if refused:
+ with pytest.raises(ValueError, match="materialized weight copy"):
+ _drive_setup(tmp_path, monkeypatch, striped=False)
+ else:
+ _drive_setup(tmp_path, monkeypatch, striped=False)