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(sharding): make interrupted content reshard miss safely (#1747)
Samarth Mukhijaa3739eed5401
diff --git a/changelog.d/0.75.1/1747.fixed.md b/changelog.d/0.75.1/1747.fixed.mdnew file mode 100644index 00000000..3b4192e0--- /dev/null+++ b/changelog.d/0.75.1/1747.fixed.md@@ -0,0 +1 @@+- **Interrupted content-changing layer re-shards can no longer leave an old cache index pointing at partially rewritten files.** Soup quarantines the old index before rewriting, reports unfinished re-shards and unindexed cache files, and keeps post-commit cleanup failures non-fatal. (#1616 by @Samearth17 in #1747)diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.pyindex ded354c0..7eb4c904 100644--- a/src/soup_cli/utils/layer_shard.py+++ b/src/soup_cli/utils/layer_shard.py@@ -98,6 +98,7 @@ _MAX_TOTAL_TENSORS = 200_000_MAX_LIVE_SOURCE_HANDLES = 2_INDEX_NAME = "index.json"+_RESHARDING_INDEX_NAME = "index.json.resharding"_EXTRAS_NAME = "extras.safetensors"_SHARD_FORMAT_VERSION = 5_LARGE_EMBED_ROLE = "embed_tokens"@@ -608,9 +609,9 @@ def _stripe_marker_problem(return None-def read_shard_index(out_dir: str) -> ShardIndex:- """Read ``index.json``. Raises on a missing or malformed index."""- path = os.path.join(out_dir, _INDEX_NAME)+def read_shard_index(out_dir: str, *, index_name: str = _INDEX_NAME) -> ShardIndex:+ """Read a shard index. Raises on a missing or malformed index."""+ path = os.path.join(out_dir, index_name)with open(path, encoding="utf-8") as handle:payload = json.load(handle)# `quant` defaults to "none" so a v0.72.0/.1 bf16 cache stays valid for a@@ -999,6 +1000,8 @@ def inspect_shard_cache(try:index = read_shard_index(out_dir)except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ if os.path.exists(os.path.join(out_dir, _RESHARDING_INDEX_NAME)):+ return None, "previous re-shard did not finish; cache index is unavailable"return None, "cache index is missing or unreadable"if index.dtype != dtype:return None, f"dtype changed ({index.dtype!r} -> {dtype!r})"@@ -1064,6 +1067,41 @@ def inspect_shard_cache(return index, "cache is reusable"+def _content_change_requires_index_quarantine(+ out_dir: str,+ *,+ dtype: str,+ fingerprint: str,+ quant: str,+ double_quant: bool,+ quant_device: str,+ external_mode: str,+) -> bool:+ """Return whether the next write could make the current index describe wrong bytes."""+ try:+ index = read_shard_index(out_dir)+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ return False+ return any(+ (+ index.dtype != dtype,+ index.quant != quant,+ index.quant != QUANT_NONE and index.double_quant != double_quant,+ index.quant != QUANT_NONE and index.quant_device != quant_device,+ index.source_fingerprint != fingerprint,+ index.external_mode != external_mode,+ index.format_version != _SHARD_FORMAT_VERSION,+ )+ )+++def _quarantine_shard_index(out_dir: str) -> None:+ """Take the old commit point out of play before rewriting content bytes."""+ path = os.path.join(out_dir, _INDEX_NAME)+ if os.path.exists(path):+ os.replace(path, os.path.join(out_dir, _RESHARDING_INDEX_NAME))++# ==========================================================================# NF4 quantisation (v0.72.2)# ==========================================================================@@ -1255,6 +1293,8 @@ def shard_checkpoint(stripe_roots=stripe,)if cached is not None:+ if notify is not None:+ _notify_unindexed_cache_files(resolved_out, cached, notify)return cachedif notify is not None:from soup_cli.utils.terminal import for_terminal@@ -1263,6 +1303,16 @@ def shard_checkpoint(# as text, never as markup or raw control bytes.notify(f"[yellow]Re-sharding layer cache:[/] {for_terminal(miss_reason)}.")_notify_orphaned_stripes(resolved_out, stripe, notify)+ if _content_change_requires_index_quarantine(+ resolved_out,+ dtype=dtype,+ fingerprint=fingerprint,+ quant=quant,+ double_quant=double_quant,+ quant_device=device_kind,+ external_mode=external_mode,+ ):+ _quarantine_shard_index(resolved_out)from safetensors import safe_open@@ -1745,6 +1795,20 @@ def shard_checkpoint(layer_roots=layer_roots,)_atomic_write_index(index, resolved_out)+ resharding_index = os.path.join(resolved_out, _RESHARDING_INDEX_NAME)+ try:+ os.remove(resharding_index)+ except FileNotFoundError:+ pass+ except OSError as exc:+ if notify is not None:+ from soup_cli.utils.terminal import for_terminal++ notify(+ f"[yellow]Could not delete the completed re-shard marker "+ f"{for_terminal(resharding_index)} ({for_terminal(exc)}); the new cache "+ f"index is committed — delete the marker when it is no longer in use.[/]"+ )# Only now: the new index above no longer names these paths, so removing them cannot# leave any on-disk index (old or new) describing a file that does not exist. Best-effort# from here on: the shard is already correct and fully committed, so a failed delete (a@@ -1766,6 +1830,8 @@ def shard_checkpoint(f"({for_terminal(exc)}); the cache is complete without it — delete it to "f"reclaim the space.[/]")+ if notify is not None:+ _notify_unindexed_cache_files(resolved_out, index, notify)return index@@ -1788,9 +1854,8 @@ def _notify_orphaned_stripes(Never deletes them: they sit outside the contained primary root, so the operator decides."""- try:- previous = read_shard_index(out_dir)- except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ previous = _read_previous_shard_index(out_dir)+ if previous is None:returnfrom soup_cli.utils.stripe_roots import stripe_folder_problemfrom soup_cli.utils.terminal import for_terminal@@ -1809,6 +1874,57 @@ def _notify_orphaned_stripes()+def _read_previous_shard_index(out_dir: str) -> Optional[ShardIndex]:+ """Read the current index, or the quarantined one during an interrupted re-shard."""+ for name in (_INDEX_NAME, _RESHARDING_INDEX_NAME):+ try:+ return read_shard_index(out_dir, index_name=name)+ except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):+ pass+ return None+++def _notify_unindexed_cache_files(+ out_dir: str, index: ShardIndex, notify: Callable[[str], None]+) -> None:+ """Report layer/temp files that the committed index no longer names."""+ from soup_cli.utils.stripe_roots import stripe_folder_problem+ from soup_cli.utils.terminal import for_terminal++ expected = {+ os.path.normcase(os.path.realpath(path)) for path in layer_paths(out_dir, index)+ }+ directories = stripe_dirs(out_dir, index.stripe_roots)+ for position, directory in enumerate(directories):+ if position:+ problem = stripe_folder_problem(directory, index.stripe_roots[position - 1])+ if problem is not None:+ continue+ try:+ entries = list(os.scandir(directory))+ except OSError:+ continue+ for entry in entries:+ if not (+ (entry.name.startswith("layer_") and entry.name.endswith(".safetensors"))+ or (entry.name.startswith(".soup.") and entry.name.endswith(".tmp"))+ ):+ continue+ try:+ if not entry.is_file(follow_symlinks=False):+ continue+ path = os.path.normcase(os.path.realpath(entry.path))+ if path in expected:+ continue+ size = entry.stat(follow_symlinks=False).st_size+ except OSError:+ continue+ notify(+ f"[yellow]Unindexed layer-cache file {for_terminal(entry.path)} "+ f"({size} bytes) is present; it was not named by the committed cache index.[/]"+ )++def _require_all_quantised(suffixes: Tuple[str, ...], matched: Iterable[str]) -> None:"""Every requested suffix must have matched at least one real decoder weight.diff --git a/tests/test_disk_tier_stripe_sharder.py b/tests/test_disk_tier_stripe_sharder.pyindex fb2fa583..db7d47f7 100644--- a/tests/test_disk_tier_stripe_sharder.py+++ b/tests/test_disk_tier_stripe_sharder.py@@ -147,6 +147,82 @@ def test_an_interrupted_reshard_leaves_the_old_index_consistent(layout, monkeypaassert not os.path.exists(layer_shard_path(out, 1))+def test_content_reshard_quarantines_index_before_layer_writes(layout, monkeypatch):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, _ = layout+ shard_checkpoint(src, out, dtype="float32")+ real_save = layer_shard_mod._atomic_save+ layer_writes = 0++ def _stop_after_two_layers(blob, path):+ nonlocal layer_writes+ if os.path.basename(path).startswith("layer_"):+ layer_writes += 1+ if layer_writes > 2:+ raise RuntimeError("interrupted")+ return real_save(blob, path)++ with monkeypatch.context() as patch:+ patch.setattr(layer_shard_mod, "_atomic_save", _stop_after_two_layers)+ with pytest.raises(RuntimeError, match="interrupted"):+ shard_checkpoint(src, out, dtype="bfloat16")++ assert not os.path.exists(os.path.join(out, "index.json"))+ assert os.path.exists(os.path.join(out, "index.json.resharding"))++ said = []+ repaired = shard_checkpoint(src, out, dtype="float32", notify=said.append)++ assert repaired.dtype == "float32"+ assert any("previous re-shard did not finish" in line for line in said), said+ assert not os.path.exists(os.path.join(out, "index.json.resharding"))+ for path in layer_paths(out, repaired):+ tensors = load_file(path)+ assert all(tensor.dtype == torch.float32 for tensor in tensors.values())+++def test_index_write_interrupt_leaves_a_miss_for_the_next_run(layout, monkeypatch):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, _ = layout+ shard_checkpoint(src, out, dtype="float32")++ def _stop_index(*_args, **_kwargs):+ raise RuntimeError("interrupted")++ with monkeypatch.context() as patch:+ patch.setattr(layer_shard_mod, "_atomic_write_index", _stop_index)+ with pytest.raises(RuntimeError, match="interrupted"):+ shard_checkpoint(src, out, dtype="bfloat16")++ assert not os.path.exists(os.path.join(out, "index.json"))+ assert os.path.exists(os.path.join(out, "index.json.resharding"))++ repaired = shard_checkpoint(src, out, dtype="float32")+ assert repaired.dtype == "float32"+ assert not os.path.exists(os.path.join(out, "index.json.resharding"))+++def test_cache_hit_reports_unindexed_layer_and_temp_files(layout):+ src, out, stripe = layout+ index = shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,))+ orphan_layer = layer_shard_path(out, 999)+ orphan_temp = os.path.join(_folder(out, stripe), ".soup.leftover.tmp")+ save_file({"orphan.weight": torch.zeros(1)}, orphan_layer)+ with open(orphan_temp, "w", encoding="utf-8") as handle:+ handle.write("incomplete")++ said = []+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,), notify=said.append)++ assert index.dtype == "float32"+ assert any(orphan_layer in line for line in said), said+ assert any(orphan_temp in line for line in said), said+ assert os.path.exists(orphan_layer)+ assert os.path.exists(orphan_temp)++def test_a_stale_copy_that_will_not_delete_still_returns_the_committed_index(layout, monkeypatch):"""Fix round 2, Important finding: the deferred delete runs AFTER the index is alreadycommitted, so a failure to delete (a leftover handle holding the file open, most plausibly@@ -202,3 +278,203 @@ def test_a_full_stripe_drive_names_the_root_and_the_variable(layout, monkeypatchassert STRIPE_DIRS_ENV in message and os.path.realpath(stripe) in message, messageassert "No space left" in message, messageassert read_shard_index(out).layer_roots == ()+++def test_content_quarantine_covers_quant_and_source_fingerprint(layout):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, _ = layout+ index = shard_checkpoint(src, out, dtype="float32")+ common = {+ "out_dir": out,+ "dtype": index.dtype,+ "double_quant": index.double_quant,+ "quant_device": index.quant_device,+ "external_mode": index.external_mode,+ }++ assert layer_shard_mod._content_change_requires_index_quarantine(+ **common, fingerprint=index.source_fingerprint, quant="nf4"+ )+ assert layer_shard_mod._content_change_requires_index_quarantine(+ **common, fingerprint="different-source", quant=index.quant+ )+++def test_previous_index_reader_falls_back_to_resharding_marker(layout):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, _ = layout+ original = shard_checkpoint(src, out, dtype="float32")+ layer_shard_mod._quarantine_shard_index(out)++ previous = layer_shard_mod._read_previous_shard_index(out)++ assert previous is not None+ assert previous.dtype == original.dtype+ assert previous.source_fingerprint == original.source_fingerprint+++def test_successful_reshard_scans_for_unindexed_files_after_commit(layout, monkeypatch):+ import soup_cli.utils.layer_shard as layer_shard_mod+ from soup_cli.utils.layer_shard import read_shard_index++ src, out, stripe = layout+ shard_checkpoint(src, out, dtype="float32")+ observed = []+ real_notify = layer_shard_mod._notify_unindexed_cache_files++ def _observe(directory, index, notify):+ committed = read_shard_index(directory)+ observed.append((committed.layer_roots, index.layer_roots))+ return real_notify(directory, index, notify)++ monkeypatch.setattr(layer_shard_mod, "_notify_unindexed_cache_files", _observe)+ index = shard_checkpoint(+ src, out, dtype="float32", stripe_roots=(stripe,), notify=lambda _line: None+ )++ assert observed == [(index.layer_roots, index.layer_roots)]++[email protected]("stop_at", ["layers", "index"])+def test_content_reshard_interrupt_is_a_miss_with_striping(layout, monkeypatch, stop_at):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, stripe = layout+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,))+ real_save = layer_shard_mod._atomic_save+ layer_writes = 0++ def _stop_after_two_layers(blob, path):+ nonlocal layer_writes+ if os.path.basename(path).startswith("layer_"):+ layer_writes += 1+ if layer_writes > 2:+ raise RuntimeError("interrupted")+ return real_save(blob, path)++ def _stop_index(*_args, **_kwargs):+ raise RuntimeError("interrupted")++ with monkeypatch.context() as patch:+ if stop_at == "layers":+ patch.setattr(layer_shard_mod, "_atomic_save", _stop_after_two_layers)+ else:+ patch.setattr(layer_shard_mod, "_atomic_write_index", _stop_index)+ with pytest.raises(RuntimeError, match="interrupted"):+ shard_checkpoint(src, out, dtype="bfloat16", stripe_roots=(stripe,))++ said = []+ repaired = shard_checkpoint(+ src, out, dtype="float32", stripe_roots=(stripe,), notify=said.append+ )+ assert any("previous re-shard did not finish" in line for line in said), said+ for path in layer_paths(out, repaired):+ tensors = load_file(path)+ assert all(tensor.dtype == torch.float32 for tensor in tensors.values())+++def test_three_root_layout_reports_files_left_on_a_kept_stripe(tmp_path):+ src = _weights(tmp_path, n_layers=6)+ out = str(tmp_path / "cache" / "model")+ first = tmp_path / "stripe-one"+ second = tmp_path / "stripe-two"+ first.mkdir()+ second.mkdir()+ first_root = str(first)+ second_root = str(second)++ shard_checkpoint(src, out, dtype="float32", stripe_roots=(first_root,))+ first_folder = _folder(out, first_root)+ leftovers = [layer_shard_path(first_folder, idx) for idx in (3, 5)]+ assert all(os.path.exists(path) for path in leftovers)++ said = []+ shard_checkpoint(+ src,+ out,+ dtype="float32",+ stripe_roots=(first_root, second_root),+ notify=said.append,+ )++ assert all(os.path.exists(path) for path in leftovers)+ for path in leftovers:+ assert any(path in line and "bytes" in line for line in said), (path, said)+++def test_interrupt_before_deferred_delete_is_reported_on_next_hit(layout, monkeypatch):+ import soup_cli.utils.layer_shard as layer_shard_mod++ src, out, stripe = layout+ shard_checkpoint(src, out, dtype="float32")+ stale = layer_shard_path(out, 1)+ real_remove = layer_shard_mod.os.remove++ def _interrupt(path, *args, **kwargs):+ if os.path.normcase(os.path.normpath(str(path))) == os.path.normcase(+ os.path.normpath(stale)+ ):+ raise KeyboardInterrupt+ return real_remove(path, *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(layer_shard_mod.os, "remove", _interrupt)+ with pytest.raises(KeyboardInterrupt):+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,))++ said = []+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,), notify=said.append)+ assert any(stale in line and "Unindexed" in line for line in said), said+++def test_notice_escapes_rich_markup_in_cache_paths(tmp_path):+ from io import StringIO++ from rich.console import Console++ src = _weights(tmp_path)+ out = str(tmp_path / "cache" / "model")+ stripe = tmp_path / "stripe-[bold]"+ stripe.mkdir()+ stripe_root = str(stripe)+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe_root,))+ orphan = os.path.join(_folder(out, stripe_root), ".soup.leftover.tmp")+ with open(orphan, "w", encoding="utf-8") as handle:+ handle.write("incomplete")++ stream = StringIO()+ console = Console(file=stream, force_terminal=False, color_system=None, width=1000)+ shard_checkpoint(+ src, out, dtype="float32", stripe_roots=(stripe_root,), notify=console.print+ )++ rendered = stream.getvalue()+ assert "stripe-[bold]" in rendered+ assert orphan in rendered+++def test_completed_marker_delete_failure_is_non_fatal(layout, monkeypatch):+ import soup_cli.utils.layer_shard as layer_shard_mod+ from soup_cli.utils.layer_shard import read_shard_index++ src, out, _ = layout+ shard_checkpoint(src, out, dtype="float32")+ marker = os.path.join(out, "index.json.resharding")+ real_remove = layer_shard_mod.os.remove++ def _deny_marker(path, *args, **kwargs):+ if os.path.normcase(os.path.normpath(str(path))) == os.path.normcase(+ os.path.normpath(marker)+ ):+ raise PermissionError("in use")+ return real_remove(path, *args, **kwargs)++ monkeypatch.setattr(layer_shard_mod.os, "remove", _deny_marker)+ said = []+ index = shard_checkpoint(src, out, dtype="bfloat16", notify=said.append)++ assert index.dtype == "bfloat16"+ assert read_shard_index(out).dtype == "bfloat16"+ assert any(marker in line and "Could not delete" in line for line in said), said