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): charge stripe drives exact layer bytes in disk pre-flight (#1612) (#1726)
Nariman Abdikarim19287819bf73
diff --git a/changelog.d/0.75.1/1726.fixed.md b/changelog.d/0.75.1/1726.fixed.mdnew file mode 100644index 00000000..3987086b--- /dev/null+++ b/changelog.d/0.75.1/1726.fixed.md@@ -0,0 +1 @@+- Layer streaming now reads source safetensors headers during the disk pre-flight to charge each stripe drive the exact bytes of the decoder layers it receives, allocating non-decoder weights to the primary root at streaming dtype rather than splitting the shard estimate evenly (#1612 by @Nari-Ab in #1726).diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex cd9b773d..67a90aaa 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -839,8 +839,12 @@ above); it does not make the reference free.**Disk pre-flight and shard cache.** Before Soup materialises or shards a checkpoint, itreports the complete projected footprint: the HF/local source, any regular-file copy Soupstill needs, and the per-layer shard cache. Required writes are grouped by target volume and-the run refuses before either write when that volume lacks free space. Override the two cache-roots with `SOUP_SPECTRUM_CACHE_DIR` and `SOUP_LAYER_STREAM_CACHE_DIR`; both retain Soup's+the run refuses before either write when that volume lacks free space. With+`SOUP_LAYER_STREAM_STRIPE_DIRS` set, each root is charged the bytes it will receive,+read from the source safetensors headers (the primary root also holds the embedding,+head and extras); when a header cannot be read or the model is qwen4_exp the split is+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'shome/cwd/tmp containment policy.**Two or more NVMe drives.** On a cold store larger than RAM the disk-tier step can wait on thediff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 25f907ed..66d96df5 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -346,18 +346,126 @@ def _effective_read_ahead(tcfg: Any, n_roots: int, console: Any) -> ReadAheadDecdef _stripe_write_shares(total: int, n_roots: int) -> list[int]:- """The shard estimate split evenly across roots, summing to it (layers alternate).+ """Fallback even split across roots when source safetensors headers cannot be read.- APPROXIMATE, and biased against root 0: root 0 also holds ``extras.safetensors``, the- ``large_*`` embedding/head files and, when the layer count does not divide by the roots,- the odd layer, so it is under-charged and the stripe drives over-charged by about that- much (~1-3% of the store on a 70B). An exact split needs the per-root placement and the- large tensors' stored sizes, which the estimate does not have here.+ Used when source headers are unreadable or for architectures like qwen4_exp.+ Evenly divides total across roots with divmod remainder distribution."""base, extra = divmod(int(total), n_roots)return [base + (1 if position < extra else 0) for position in range(n_roots)]+def estimate_stripe_write_shares(+ weights_dir: Optional[str],+ *,+ total_bytes: int,+ n_roots: int,+ dtype: str = "bfloat16",+ quant: str = "none",+ double_quant: bool = True,+ arch: str = "",+) -> tuple[list[int], bool]:+ """Calculate per-root shard write shares, charging root 0 non-decoder bytes (#1612).++ Returns ``(shares, approximate)``:+ - When source safetensors headers can be parsed without tensor loads:+ calculates the parameter count per decoder layer and for non-decoder weights.+ Root k is charged decoder bytes for layers placed on root k according to+ ``layer_roots_for(n_layers, n_roots)``.+ Root 0 is charged its decoder layers plus all non-decoder weights at the+ streaming dtype rate.+ ``approximate`` is False.+ - When headers cannot be read, or n_roots == 1, or total_bytes <= 0, or arch == "qwen4_exp":+ falls back to ``_stripe_write_shares(total_bytes, n_roots)``, with+ ``approximate`` True (when n_roots > 1 and total_bytes > 0).+ """+ if arch == "qwen4_exp":+ return _stripe_write_shares(total_bytes, n_roots), n_roots > 1+ if n_roots <= 1 or total_bytes <= 0:+ return _stripe_write_shares(total_bytes, n_roots), False+ if not weights_dir:+ return _stripe_write_shares(total_bytes, n_roots), True++ try:+ resolved_dir = os.path.realpath(os.path.expanduser(str(weights_dir)))+ if not os.path.isdir(resolved_dir):+ return _stripe_write_shares(total_bytes, n_roots), True++ from soup_cli.utils.layer_shard import (+ _LAYER_RE,+ QUANT_NF4,+ _canonical_stream_key,+ _discover_safetensors,+ )+ from soup_cli.utils.layer_stream import (+ NF4_BYTES_PER_PARAM,+ NF4_BYTES_PER_PARAM_SINGLE,+ )+ from soup_cli.utils.safetensors_reader import _ITEMSIZE, read_header+ from soup_cli.utils.stripe_roots import layer_roots_for++ shards = _discover_safetensors(resolved_dir)+ itemsize = _ITEMSIZE.get(dtype, 2)++ decoder_layer_bytes: dict[int, float] = {}+ non_decoder_bytes: float = 0.0++ for shard_path in shards:+ header = read_header(shard_path)+ for source_key, tensor_range in header.items():+ canonical = _canonical_stream_key(source_key)+ if canonical.endswith((".scales", ".biases")):+ continue+ match = _LAYER_RE.match(canonical)+ numel = math.prod(tensor_range.shape)+ if match:+ layer_idx = int(match.group(1))+ if quant == QUANT_NF4:+ if len(tensor_range.shape) >= 2:+ rate = (+ NF4_BYTES_PER_PARAM+ if double_quant+ else NF4_BYTES_PER_PARAM_SINGLE+ )+ else:+ rate = itemsize+ else:+ rate = itemsize+ decoder_layer_bytes[layer_idx] = (+ decoder_layer_bytes.get(layer_idx, 0.0) + numel * rate+ )+ else:+ non_decoder_bytes += numel * itemsize++ if not decoder_layer_bytes:+ return _stripe_write_shares(total_bytes, n_roots), True++ n_layers = max(decoder_layer_bytes.keys()) + 1+ layer_roots = layer_roots_for(n_layers, n_roots)+ raw_root_shares = [0.0] * n_roots+ for layer_idx in range(n_layers):+ raw_root_shares[layer_roots[layer_idx]] += decoder_layer_bytes.get(layer_idx, 0.0)+ raw_root_shares[0] += non_decoder_bytes++ raw_total = sum(raw_root_shares)+ if raw_total <= 0:+ return _stripe_write_shares(total_bytes, n_roots), True++ effective_total = max(int(total_bytes), int(math.ceil(raw_total)))+ raw_scaled = [effective_total * (s / raw_total) for s in raw_root_shares]+ shares = [int(v) for v in raw_scaled]+ remainder = effective_total - sum(shares)+ fractions = sorted(+ range(n_roots), key=lambda i: raw_scaled[i] - shares[i], reverse=True+ )+ for i in range(remainder):+ shares[fractions[i]] += 1++ return shares, False+ except Exception:+ return _stripe_write_shares(total_bytes, n_roots), True++def _render_stream_disk_preflight(*,source_bytes: int,@@ -368,6 +476,7 @@ def _render_stream_disk_preflight(shard_write_bytes: int,shard_path: str,stripe_writes: Sequence[tuple[str, int]] = (),+ approximate: bool = False,) -> None:"""Print and enforce the complete on-disk cost before either cache writes.@@ -403,7 +512,8 @@ def _render_stream_disk_preflight(f"({'write required' if materialize_bytes else 'no write required'})"),(- f"Layer-shard cache: {shard_bytes / 1e9:.2f} GB "+ f"Layer-shard cache: {'approximately ' if approximate else ''}"+ f"{shard_bytes / 1e9:.2f} GB "f"({'write required' if shard_write_bytes else 'reusable'})"),f"Projected total on disk: {projected_total / 1e9:.2f} GB",@@ -720,17 +830,27 @@ class StreamingSetupMixin:stripe_roots=stripe_roots,)write_total = 0 if cached is not None else shard_estimate- shares = _stripe_write_shares(write_total, 1 + len(stripe_roots))+ shares, approximate = estimate_stripe_write_shares(+ weights_plan.weights_dir,+ total_bytes=write_total,+ n_roots=1 + len(stripe_roots),+ dtype=dtype,+ quant=quant,+ double_quant=double_quant,+ arch=arch,+ )dirs = stripe_dirs(shard_dir, stripe_roots)+ effective_shard_bytes = max(shard_estimate, sum(shares))_render_stream_disk_preflight(source_bytes=weights_plan.source_bytes,materialized_copy_bytes=weights_plan.materialized_copy_bytes,materialize_bytes=weights_plan.materialize_bytes,materialized_path=weights_plan.weights_dir,- shard_bytes=shard_estimate,+ shard_bytes=effective_shard_bytes,shard_write_bytes=shares[0],shard_path=shard_dir,stripe_writes=tuple(zip(dirs[1:], shares[1:])),+ approximate=approximate,)weights_dir = resolve_model_weights(diff --git a/tests/test_disk_tier_stripe_setup.py b/tests/test_disk_tier_stripe_setup.pyindex 76bfdc19..c5809ab5 100644--- a/tests/test_disk_tier_stripe_setup.py+++ b/tests/test_disk_tier_stripe_setup.py@@ -3,7 +3,9 @@import astimport inspectimport io+import jsonimport os+import structfrom types import SimpleNamespaceimport pytest@@ -126,6 +128,296 @@ class TestTheDiskPreflight:)assert "Additional writes before training: 3.00 GB" in recorder.getvalue()+ def test_exact_shares_charge_primary_drive_more_than_even_split_two_roots(self, tmp_path):+ """#1612: 5 layers over 2 roots puts 3 layers + non-decoder weights on root 0."""+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ file_size = os.path.getsize(os.path.join(weights, "model.safetensors"))+ shares, approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=2, dtype="bfloat16"+ )+ assert not approx+ assert sum(shares) == file_size+ even_shares = stream_setup._stripe_write_shares(file_size, 2)+ # Primary drive receives 3 of 5 layers plus embedding/head; must exceed even split+ assert shares[0] > even_shares[0]+ assert shares[1] < even_shares[1]++ def test_exact_shares_three_roots_odd_layer_count(self, tmp_path):+ """#1612: 5 layers over 3 roots gives (2, 2, 1) layer placement."""+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ file_size = os.path.getsize(os.path.join(weights, "model.safetensors"))+ shares, approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=3, dtype="bfloat16"+ )+ assert not approx+ assert sum(shares) == file_size+ even_shares = stream_setup._stripe_write_shares(file_size, 3)+ assert shares[0] > even_shares[0]+ # Root 0 and 1 each have 2 layers; root 0 also has non-decoder weights+ assert shares[0] > shares[1]+ # Root 2 has only 1 layer+ assert shares[1] > shares[2]++ def test_preflight_refusal_when_primary_volume_short_two_roots(self, tmp_path, monkeypatch):+ """#1612: pre-flight refuses when primary drive fits even split but not real bytes."""+ monkeypatch.setattr(stream_setup, "console", _console()[0])+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ file_size = os.path.getsize(os.path.join(weights, "model.safetensors"))+ shares, approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=2, dtype="bfloat16"+ )+ assert not approx+ even_shares = stream_setup._stripe_write_shares(file_size, 2)+ assert shares[0] > even_shares[0]++ primary_dir = str(tmp_path / "cache")+ stripe_dir = str(tmp_path / "stripe")+ # Primary volume has room for even share, but NOT for real share+ primary_free = even_shares[0] + 1+ monkeypatch.setattr(+ stream_setup,+ "_disk_volume",+ lambda path: (1, primary_free) if path == primary_dir else (2, 10**15),+ )++ # Real shares: refusal fires and names layer-shard cache+ with pytest.raises(ValueError, match="layer-shard cache"):+ stream_setup._render_stream_disk_preflight(+ source_bytes=file_size, materialized_copy_bytes=0, materialize_bytes=0,+ materialized_path=weights, shard_bytes=file_size, shard_write_bytes=shares[0],+ shard_path=primary_dir, stripe_writes=((stripe_dir, shares[1]),),+ )++ # Mutation check: with even split, pre-flight would have falsely passed+ recorder = io.StringIO()+ monkeypatch.setattr(+ stream_setup, "console", Console(file=recorder, width=200, color_system=None)+ )+ stream_setup._render_stream_disk_preflight(+ source_bytes=file_size, materialized_copy_bytes=0, materialize_bytes=0,+ materialized_path=weights, shard_bytes=file_size, shard_write_bytes=even_shares[0],+ shard_path=primary_dir, stripe_writes=((stripe_dir, even_shares[1]),),+ )+ assert "Layer-shard cache" in recorder.getvalue()++ def test_preflight_refusal_when_primary_volume_short_three_roots(self, tmp_path, monkeypatch):+ """#1612: 3-root case refuses when primary volume is short."""+ monkeypatch.setattr(stream_setup, "console", _console()[0])+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ file_size = os.path.getsize(os.path.join(weights, "model.safetensors"))+ shares, _approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=3, dtype="bfloat16"+ )+ even_shares = stream_setup._stripe_write_shares(file_size, 3)+ assert shares[0] > even_shares[0]++ primary_dir = str(tmp_path / "cache")+ stripe_a = str(tmp_path / "stripe_a")+ stripe_b = str(tmp_path / "stripe_b")+ primary_free = even_shares[0] + 1+ monkeypatch.setattr(+ stream_setup,+ "_disk_volume",+ lambda path: (1, primary_free) if path == primary_dir else (hash(path), 10**15),+ )++ with pytest.raises(ValueError, match="layer-shard cache"):+ stream_setup._render_stream_disk_preflight(+ source_bytes=file_size, materialized_copy_bytes=0, materialize_bytes=0,+ materialized_path=weights, shard_bytes=file_size, shard_write_bytes=shares[0],+ shard_path=primary_dir,+ stripe_writes=((stripe_a, shares[1]), (stripe_b, shares[2])),+ )++ def test_preflight_panel_line_approximate_when_unreadable(self, tmp_path, monkeypatch):+ """#1612: when headers cannot be read, even split is kept and panel says approximately."""+ recorder = io.StringIO()+ monkeypatch.setattr(+ stream_setup, "console", Console(file=recorder, width=200, color_system=None)+ )+ monkeypatch.setattr(stream_setup, "_disk_volume", lambda path: (hash(path), 10**15))++ shares, approx = stream_setup.estimate_stripe_write_shares(+ str(tmp_path / "nonexistent"), total_bytes=1000, n_roots=2+ )+ assert approx is True+ assert shares == stream_setup._stripe_write_shares(1000, 2)++ stream_setup._render_stream_disk_preflight(+ source_bytes=0, materialized_copy_bytes=0, materialize_bytes=0,+ materialized_path=str(tmp_path), shard_bytes=1000, shard_write_bytes=shares[0],+ shard_path=str(tmp_path / "cache"), stripe_writes=((str(tmp_path / "a"), shares[1]),),+ approximate=approx,+ )+ assert "Layer-shard cache: approximately 0.00 GB (write required)" in recorder.getvalue()++ def test_exact_shares_match_actual_sharded_files_on_disk(self, tmp_path):+ """#1612: compare charged shares with actual sharded bytes on disk."""+ pytest.importorskip("torch")+ pytest.importorskip("safetensors")+ pytest.importorskip("transformers")+ import torch+ from safetensors.torch import save_file+ from transformers import AutoModelForCausalLM, LlamaConfig++ from soup_cli.utils.layer_shard import shard_checkpoint++ weights = tmp_path / "model"+ weights.mkdir(parents=True, exist_ok=True)+ config = LlamaConfig(+ vocab_size=64, hidden_size=64, intermediate_size=64,+ num_hidden_layers=5, num_attention_heads=4,+ num_key_value_heads=2, tie_word_embeddings=False,+ max_position_embeddings=128,+ )+ torch.manual_seed(42)+ model = AutoModelForCausalLM.from_config(config).to(torch.bfloat16).eval()+ save_file(+ {k: v.contiguous() for k, v in model.state_dict().items()},+ str(weights / "model.safetensors"),+ )+ config.save_pretrained(str(weights))++ file_size = os.path.getsize(str(weights / "model.safetensors"))+ shares, approx = stream_setup.estimate_stripe_write_shares(+ str(weights), total_bytes=file_size, n_roots=2, dtype="bfloat16"+ )+ assert not approx++ cache_dir = tmp_path / "cache" / "model"+ stripe_dir = tmp_path / "stripe"+ stripe_dir.mkdir(parents=True, exist_ok=True)+ shard_checkpoint(+ str(weights), str(cache_dir), dtype="bfloat16", stripe_roots=(str(stripe_dir),)+ )++ actual_root0 = sum(f.stat().st_size for f in cache_dir.glob("*.safetensors"))+ subdirs = [d for d in stripe_dir.iterdir() if d.is_dir()]+ stripe_sub = subdirs[0] if subdirs else stripe_dir+ actual_root1 = sum(f.stat().st_size for f in stripe_sub.glob("*.safetensors"))++ assert shares[0] >= actual_root0+ assert shares[1] >= actual_root1+ # Within 10% tolerance+ assert abs(shares[0] - actual_root0) / actual_root0 < 0.10+ assert abs(shares[1] - actual_root1) / actual_root1 < 0.10++ # Mutation check: with even split, root 0's share is below its actual bytes+ even_shares = stream_setup._stripe_write_shares(file_size, 2)+ assert even_shares[0] < actual_root0++ def test_exact_shares_nf4_charges_non_decoder_at_streaming_dtype(self, tmp_path):+ """#1612: NF4 applies to linears, non-decoder charged at streaming dtype."""+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ file_size = os.path.getsize(os.path.join(weights, "model.safetensors"))+ shares_bf16, _ = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=2, dtype="bfloat16", quant="none"+ )+ shares_nf4, approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=file_size, n_roots=2, dtype="bfloat16", quant="nf4"+ )+ assert not approx+ assert sum(shares_nf4) == file_size+ # Root 0 holds non-decoder weights charged at full itemsize, so its share ratio+ # under NF4 is higher than under unquantised bf16+ assert shares_nf4[0] / sum(shares_nf4) > shares_bf16[0] / sum(shares_bf16)++ def test_preflight_unparseable_header_falls_back_to_even_split(self, tmp_path):+ """#1612 mutation check: garbage safetensors header falls back to even split."""+ corrupt = tmp_path / "corrupt"+ corrupt.mkdir(parents=True, exist_ok=True)+ with open(corrupt / "model.safetensors", "wb") as f:+ f.write(struct.pack("<Q", 100))+ f.write(b"NOT_VALID_JSON_GARBAGE_HEADER_DATA")+ shares, approx = stream_setup.estimate_stripe_write_shares(+ str(corrupt), total_bytes=1000, n_roots=2+ )+ assert approx is True+ assert shares == stream_setup._stripe_write_shares(1000, 2)++ def test_exact_shares_qwen4_exp_ple_skipped_and_even_split_used(self, tmp_path):+ """#1612: qwen4_exp arch falls back to even split so external PLE tables are not charged."""+ qwen_dir = tmp_path / "qwen4_model"+ qwen_dir.mkdir(parents=True, exist_ok=True)+ cur = 0+ tensors = {+ "model.embed_tokens.weight": {+ "dtype": "BF16", "shape": [128, 64], "data_offsets": [cur, cur + 16384]+ },+ "model.layers.0.ple.ple_embedding.ngram_embedding.weight": {+ "dtype": "BF16", "shape": [64, 64], "data_offsets": [cur + 16384, cur + 24576]+ },+ "model.layers.0.self_attn.q_proj.weight": {+ "dtype": "BF16", "shape": [64, 64], "data_offsets": [cur + 24576, cur + 32768]+ },+ }+ cur += 32768+ data = json.dumps(tensors).encode("utf-8")+ with open(qwen_dir / "model.safetensors", "wb") as f:+ f.write(struct.pack("<Q", len(data)))+ f.write(data)+ f.write(b"\x00" * cur)++ shares, approx = stream_setup.estimate_stripe_write_shares(+ str(qwen_dir), total_bytes=10000, n_roots=2, arch="qwen4_exp"+ )+ assert approx is True+ assert shares == stream_setup._stripe_write_shares(10000, 2)++ def test_exact_shares_never_charge_less_than_the_header_bytes(self, tmp_path):+ """#1612: an estimate below the real header bytes is raised to them, not trusted."""+ weights = _make_synthetic_untied_checkpoint(tmp_path, n_layers=5)+ shares, approx = stream_setup.estimate_stripe_write_shares(+ weights, total_bytes=1000, n_roots=2, dtype="float32"+ )+ assert not approx+ assert sum(shares) > 1000+++def _make_synthetic_untied_checkpoint(tmp_path, n_layers: int = 5) -> str:+ """A synthetic safetensors checkpoint with n_layers and untied lm_head (no torch needed)."""+ weights = tmp_path / "model"+ weights.mkdir(parents=True, exist_ok=True)+ tensors = {}+ cur = 0+ tensors["model.embed_tokens.weight"] = {+ "dtype": "BF16", "shape": [128, 64], "data_offsets": [cur, cur + 16384]+ }+ cur += 16384+ tensors["lm_head.weight"] = {+ "dtype": "BF16", "shape": [128, 64], "data_offsets": [cur, cur + 16384]+ }+ cur += 16384+ tensors["model.norm.weight"] = {+ "dtype": "BF16", "shape": [64], "data_offsets": [cur, cur + 128]+ }+ cur += 128+ for i in range(n_layers):+ for proj in ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]:+ name = (+ f"model.layers.{i}.self_attn.{proj}.weight"+ if "proj" in proj and "gate" not in proj and "up" not in proj and "down" not in proj+ else f"model.layers.{i}.mlp.{proj}.weight"+ )+ tensors[name] = {"dtype": "BF16", "shape": [64, 64], "data_offsets": [cur, cur + 8192]}+ cur += 8192+ tensors[f"model.layers.{i}.input_layernorm.weight"] = {+ "dtype": "BF16", "shape": [64], "data_offsets": [cur, cur + 128]+ }+ cur += 128+ tensors[f"model.layers.{i}.post_attention_layernorm.weight"] = {+ "dtype": "BF16", "shape": [64], "data_offsets": [cur, cur + 128]+ }+ cur += 128++ data = json.dumps(tensors).encode("utf-8")+ file_path = weights / "model.safetensors"+ with open(file_path, "wb") as f:+ f.write(struct.pack("<Q", len(data)))+ f.write(data)+ f.write(b"\x00" * cur)+ return str(weights)+def _drive_setup(tmp_path, monkeypatch, *, striped):"""The real `_setup_streaming_transformers` on a tiny checkpoint, runtime boundary spied.@@ -167,6 +459,15 @@ def _drive_setup(tmp_path, monkeypatch, *, striped):monkeypatch.setattr(torch.cuda, "mem_get_info", lambda *_a, **_k: (free, free))monkeypatch.setattr(runtime_module, "expandable_segments_status", lambda *_a, **_k: (True, ""))+ preflight_calls = []+ orig_preflight = stream_setup._render_stream_disk_preflight++ def spy_preflight(**kwargs):+ preflight_calls.append(kwargs)+ return orig_preflight(**kwargs)++ monkeypatch.setattr(stream_setup, "_render_stream_disk_preflight", spy_preflight)+captured = {}def spy_build(**kwargs):@@ -191,14 +492,16 @@ def _drive_setup(tmp_path, monkeypatch, *, striped):wrapper = SFTTrainerWrapper(cfg)wrapper.device = "cuda"wrapper._setup_streaming_transformers(cfg, cfg.training)- return captured, " ".join(buffer.getvalue().split()), second_drive+ return captured, " ".join(buffer.getvalue().split()), second_drive, preflight_callsclass TestTheSetupPathUsesTheRoots:"""R4 end to end: the variable reaches the sharder, the pre-flight and the reader."""def test_two_drives_stripe_the_cache_and_deepen_the_reader(self, tmp_path, monkeypatch):- captured, said, second_drive = _drive_setup(tmp_path, monkeypatch, striped=True)+ captured, said, second_drive, preflight_calls = _drive_setup(+ tmp_path, monkeypatch, striped=True+ )index = captured["index"]assert index.stripe_roots == (os.path.realpath(second_drive),)assert index.layer_roots == (0, 1, 0)@@ -212,9 +515,14 @@ class TestTheSetupPathUsesTheRoots:assert any(name.startswith("layer_") for name in os.listdir(stripe_folder)), ("no layer file landed on the second drive")+ # #1612: exact shares charge root 0 more than root 1 (2 of 3 layers plus extras on root 0)+ assert len(preflight_calls) >= 1+ assert preflight_calls[0]["shard_write_bytes"] > preflight_calls[0]["stripe_writes"][0][1]def test_one_drive_is_left_exactly_as_it_was(self, tmp_path, monkeypatch):- captured, said, _second_drive = _drive_setup(tmp_path, monkeypatch, striped=False)+ captured, said, _second_drive, _preflight = _drive_setup(+ tmp_path, monkeypatch, striped=False+ )index = captured["index"]assert index.stripe_roots == () and index.layer_roots == ()assert captured["read_ahead"] == DEFAULT_STREAM_READ_AHEAD@@ -223,6 +531,22 @@ class TestTheSetupPathUsesTheRoots:def test_a_striped_cache_is_reused_not_rewritten_on_the_next_run(self, tmp_path, monkeypatch):"""The pre-flight asks the cache check about the SAME roots the sharder will use."""_drive_setup(tmp_path, monkeypatch, striped=True)- _captured, said, _second_drive = _drive_setup(tmp_path, monkeypatch, striped=True)+ _captured, said, _second_drive, _preflight = _drive_setup(+ tmp_path, monkeypatch, striped=True+ )assert "(reusable)" in saidassert "layer-shard stripe 1" not in said # no write is planned for a cache we keep++ def test_the_setup_hands_the_estimate_its_dtype_quant_and_arch(self, tmp_path, monkeypatch):+ calls = []+ real = stream_setup.estimate_stripe_write_shares++ def spy(*args, **kwargs):+ calls.append(kwargs)+ return real(*args, **kwargs)++ monkeypatch.setattr(stream_setup, "estimate_stripe_write_shares", spy)+ _drive_setup(tmp_path, monkeypatch, striped=True)+ 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"