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
Re-check the stripe folder before every write of a shard, not once (#1663)
Siddhardha Nanda72c6239e5097
diff --git a/changelog.d/0.75.1/1663.fixed.md b/changelog.d/0.75.1/1663.fixed.mdnew file mode 100644index 00000000..766dc37d--- /dev/null+++ b/changelog.d/0.75.1/1663.fixed.md@@ -0,0 +1 @@+- Re-check that a `SOUP_LAYER_STREAM_STRIPE_DIRS` folder has not been renamed and replaced by a link before every per-layer write and the marker write of a layer-stream shard, instead of only once before the shard starts; and refuse a directory junction as a stripe root while still accepting a genuine Windows volume mount point, distinguishing the two by their link target rather than their shared reparse tag (#1614 by @SID-6921 in #1663).diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex fd9407a6..364d6235 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -834,7 +834,11 @@ flight per drive. The cache is laid out this way whichever tier the run picks; oreads the drives in parallel. Every entry is checked, and any failure refuses the run and namesthe entry and the rule: it must be an absolute path (on Windows, with a drive letter or UNC share;no `\\?\` or `\\.\` spelling, no control characters), already exist as a folder (a drive that is-not mounted is never mistaken for an empty one), not be a symlink, not lie inside or contain the+not mounted is never mistaken for an empty one), not be a symlink or a directory junction (a+genuine Windows volume mount point is accepted — a junction and a mount point carry the same+reparse tag, but only a junction's target names a folder, under a drive letter, a UNC share or+even a volume GUID path, that can be repointed at any time; a mount point's target names a+whole volume rather than a folder), not lie inside or contain theprimary cache root or another entry, sit on a different volume from the primary root and fromevery other entry, and classify as NVMe (`training.stream_disk_kind` overrides a wrong probe); thelist holds at most 6 folders. The checks that need no disk probe run when `soup train` or@@ -848,8 +852,12 @@ primary cache's path, so two primary caches (two users, or two `SOUP_LAYER_STREAvalues) sharing one stripe drive never touch each other's files. That folder is made private tothe account running Soup (mode 0700 on POSIX; on Windows a protected ACL for that account andSYSTEM, replacing the inherited one, which on a data drive typically lets every signed-in-account modify files), checked again on every reuse, and never followed if it is a link or-junction; a folder Soup cannot make private refuses the run by name. Soup never deletes anything+account modify files), checked again on every reuse and again before every per-layer write and+the marker write of a shard, and never followed if it is a link or junction; a folder Soup+cannot make private refuses the run by name. A root renamed out from under a running shard and+replaced with a link is refused at the next write, not just at the start — but that only+narrows the window to a single write, it does not close it, which would need writes relative+to an open directory handle (the standard library has none on Windows). Soup never deletes anythinginside a stripe folder. Soup makes only its own folder owner-only, so also make the stripe ROOTitself writable only by your own account (on a default Windows data drive other accounts canmodify it).diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.pyindex cdd0e087..ded354c0 100644--- a/src/soup_cli/utils/layer_shard.py+++ b/src/soup_cli/utils/layer_shard.py@@ -1211,9 +1211,11 @@ def shard_checkpoint(from soup_cli.utils.stripe_roots import (STRIPE_DIRS_ENV,+ StripeRootError,layer_roots_for,primary_cache_identity,secure_stripe_folder,+ stripe_folder_problem,validate_stripe_root,)@@ -1627,6 +1629,19 @@ def shard_checkpoint()shared_specs.setdefault(name, spec)root = layer_roots[idx] if layer_roots else 0+ if root:+ # secure_stripe_folder ran once, before the loop started. Between then and+ # now the root could have been renamed and a link substituted in its place+ # (the folder itself still looks fine to a plain stat), so the same+ # real-path check is repeated right before every write that would otherwise+ # silently follow it.+ problem = stripe_folder_problem(shard_dirs[root], stripe[root - 1])+ if problem is not None:+ raise StripeRootError(+ f"{STRIPE_DIRS_ENV}: writing decoder layer {idx} to the stripe root "+ f"{stripe[root - 1]} refused: {problem}. The existing cache index is "+ f"unchanged."+ )try:_atomic_save(blob, layer_shard_path(shard_dirs[root], idx))except OSError as exc:@@ -1694,6 +1709,12 @@ def shard_checkpoint(primary = primary_cache_identity(resolved_out)for position, directory in enumerate(shard_dirs[1:], start=1):+ problem = stripe_folder_problem(directory, stripe[position - 1])+ if problem is not None:+ raise StripeRootError(+ f"{STRIPE_DIRS_ENV}: writing the stripe marker to {stripe[position - 1]} "+ f"refused: {problem}. The existing cache index is unchanged."+ )_write_stripe_marker(directory,fingerprint=fingerprint,diff --git a/src/soup_cli/utils/stripe_roots.py b/src/soup_cli/utils/stripe_roots.pyindex 194aea72..2b94c9db 100644--- a/src/soup_cli/utils/stripe_roots.py+++ b/src/soup_cli/utils/stripe_roots.py@@ -133,6 +133,37 @@ def volume_of(path: str) -> int:return int(os.stat(_nearest_existing(path)).st_dev)+def _is_link(info: os.stat_result) -> bool:+ """A symlink, or on Windows any reparse point: a junction does not report S_ISLNK (and+ ``os.path.islink`` misses it before 3.12), but it redirects exactly as a symlink does."""+ if stat.S_ISLNK(info.st_mode):+ return True+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ return os.name == "nt" and bool(getattr(info, "st_file_attributes", 0) & reparse)+++def is_volume_mount_point(path: str) -> bool:+ """Whether the reparse point at ``path`` is a genuine Windows volume mount point.++ A directory junction and a volume mount point carry the identical+ ``IO_REPARSE_TAG_MOUNT_POINT`` tag (``_is_link`` cannot tell them apart), so the two are+ distinguished by their target instead: ``mountvol`` names a volume mount point's target+ ``\\\\?\\Volume{<guid>}\\`` with nothing after it -- it names a whole volume rather than a+ folder, where a junction can target a folder BENEATH a volume GUID path just as easily as+ one beneath a drive letter or UNC share. Refusing every reparse point would also refuse a+ legitimate volume-mount-point stripe root; this is the narrower rule that does not.+ """+ try:+ target = os.readlink(path)+ except (OSError, ValueError):+ # On Windows, os.readlink raises ValueError ("not a symbolic link"), not OSError,+ # for a reparse point that is neither a symlink nor a junction/mount point.+ return False+ stripped = target.removeprefix("\\\\?\\").removeprefix("\\??\\")+ volume = stripped.rstrip("\\")+ return volume.startswith("Volume{") and volume.endswith("}") and "\\" not in volume++def check_stripe_root(entry: str,*,@@ -159,6 +190,22 @@ def check_stripe_root(return None, "must name a drive letter or a UNC share"if os.path.islink(expanded):return None, "must not be a symlink"+ if os.name == "nt":+ try:+ entry_info = os.lstat(expanded)+ except OSError:+ entry_info = None+ if (+ entry_info is not None+ and _is_link(entry_info)+ and not is_volume_mount_point(expanded)+ ):+ return None, (+ "is a directory junction, not a real folder or a genuine Windows "+ "volume mount point; Soup would stripe layer writes through it to wherever "+ "it currently points, which a junction (unlike a mounted volume) can be "+ "repointed to at any time"+ )if not os.path.isdir(expanded):return None, ("must be an existing directory. Soup creates only its per-model folder "@@ -328,15 +375,6 @@ def stripe_folder_name(shard_dir: str) -> str:return f"{slug}-{digest}"-def _is_link(info: os.stat_result) -> bool:- """A symlink, or on Windows any reparse point: a junction does not report S_ISLNK (and- ``os.path.islink`` misses it before 3.12), but it redirects exactly as a symlink does."""- if stat.S_ISLNK(info.st_mode):- return True- reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)- return os.name == "nt" and bool(getattr(info, "st_file_attributes", 0) & reparse)--def stripe_folder_problem(folder: str, root: str) -> Optional[str]:"""Why ``folder`` must not be read, written or deleted in, or ``None``.diff --git a/tests/test_disk_tier_stripe_folders.py b/tests/test_disk_tier_stripe_folders.pyindex 4baec4a9..d6dd8891 100644--- a/tests/test_disk_tier_stripe_folders.py+++ b/tests/test_disk_tier_stripe_folders.py@@ -450,3 +450,186 @@ class TestAFolderThatCannotBeMadePrivateRefusesTheRun:)shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,))assert [os.path.normcase(p) for p in calls] == [os.path.normcase(_folder(out, stripe))]+++# --------------------------------------------------------------------------------------------+# #1614 — the root is re-checked before EVERY write of a shard, not once at secure time+# --------------------------------------------------------------------------------------------+def _plant_link(kind, target, link):+ if kind == "symlink":+ os.symlink(str(target), str(link), target_is_directory=True)+ else:+ _junction(target, link)+++_LINK_KINDS = [+ pytest.param("symlink", marks=pytest.mark.requires_symlink),+ pytest.param(+ "junction",+ marks=pytest.mark.skipif(not WINDOWS, reason="junctions are a Windows reparse point"),+ ),+]+++class TestAStripeRootSwapIsRefusedAtTheNextStripeWrite:+ """``secure_stripe_folder`` runs once, before the per-layer write loop starts. Between+ then and the last write, the root could be renamed and a link substituted for it — the+ per-model folder's own lstat still looks like a real directory, so only comparing its+ realpath against the validated root catches the swap. The fix re-runs that comparison+ (``stripe_folder_problem``) before every per-layer write and before the marker write.++ 5 layers over (primary, stripe): layers 1 and 3 go to the stripe root, so a swap planted+ right after one of those two writes is picked up either by the next per-layer write (the+ other one) or, when the swap happens after the last layer, by the marker write.+ """++ @pytest.mark.parametrize("kind", _LINK_KINDS)+ @pytest.mark.parametrize(+ "swap_after, refused_at", [(1, "decoder layer 3"), (3, "stripe marker")]+ )+ def test_the_swap_is_refused(self, tmp_path, monkeypatch, kind, swap_after, refused_at):+ from soup_cli.utils import layer_shard as layer_shard_module++ src = _weights(tmp_path, n_layers=5)+ out = str(tmp_path / "cache" / "model")+ (tmp_path / "stripe").mkdir()+ stripe = os.path.realpath(str(tmp_path / "stripe"))+ folder_name = os.path.basename(_folder(out, stripe))+ # Already holds a same-named folder, so the substituted link looks legitimate to+ # anything that does not compare realpaths against the originally validated root.+ elsewhere = tmp_path / "elsewhere"+ (elsewhere / folder_name).mkdir(parents=True)+ trigger = os.path.basename(layer_shard_path(out, swap_after))+ real_atomic_save = layer_shard_module._atomic_save+ swapped = []++ def fake_atomic_save(blob, path):+ real_atomic_save(blob, path)+ if (+ not swapped+ and os.path.basename(path) == trigger+ and os.path.basename(os.path.dirname(path)) == folder_name+ ):+ os.replace(stripe, str(tmp_path / "moved-root"))+ _plant_link(kind, elsewhere, stripe)+ swapped.append(path)++ monkeypatch.setattr(layer_shard_module, "_atomic_save", fake_atomic_save)+ with pytest.raises(StripeRootError) as caught:+ shard_checkpoint(src, out, dtype="float32", stripe_roots=(stripe,))+ message = str(caught.value)+ assert swapped, "the fixture never planted the link"+ assert stripe in message and refused_at in message, message+ # Nothing landed through the substituted link, and no index was committed (first shard).+ assert os.listdir(str(elsewhere / folder_name)) == []+ assert not os.path.exists(os.path.join(out, "index.json"))+++# --------------------------------------------------------------------------------------------+# #1614 — a directory junction is refused as a stripe root, a volume mount point is not+# --------------------------------------------------------------------------------------------+class TestJunctionVersusVolumeMountPoint:+ @pytest.mark.skipif(not WINDOWS, reason="junctions are a Windows reparse point")+ def test_a_directory_junction_target_is_not_a_volume_mount_point(self, tmp_path):+ from soup_cli.utils.stripe_roots import is_volume_mount_point++ target = tmp_path / "target"+ target.mkdir()+ link = tmp_path / "link"+ _junction(target, link)+ assert is_volume_mount_point(str(link)) is False++ @pytest.mark.parametrize(+ "target, expected",+ [+ (r"\\?\Volume{1be1e677-9257-45ec-936f-712a49d3af54}\\", True),+ (r"\\?\Volume{1be1e677-9257-45ec-936f-712a49d3af54}", True),+ (r"\??\Volume{1be1e677-9257-45ec-936f-712a49d3af54}\\", True),+ (r"\??\Volume{1be1e677-9257-45ec-936f-712a49d3af54}", True),+ (r"\\?\Volume{1be1e677-9257-45ec-936f-712a49d3af54}\Users\nanda", False),+ (r"\\?\C:\Users\nanda", False),+ (r"\\?\UNC\server\share\folder", False),+ (r"\\?\Volume{1be1e677-9257-45ec-936f-712a49d3af54}\data\{cache}", False),+ (r"\\?\Volume{1be1e677-9257-45ec-936f-712a49d3af54}x", False),+ ],+ ids=[+ "volume-root-trailing-sep-devicepath",+ "volume-root-no-trailing-sep",+ "volume-root-trailing-sep-ntpath",+ "volume-root-no-trailing-sep-ntpath",+ "folder-below-volume-path",+ "drive-letter-folder",+ "unc-folder",+ "folder-below-volume-path-name-ends-with-a-brace",+ "text-after-the-volume-name",+ ],+ )+ def test_the_classifier_distinguishes_a_volume_root_from_a_folder_beneath_one(+ self, tmp_path, monkeypatch, target, expected+ ):+ r"""No elevation is available to mount a real volume, so the link-target resolution is+ patched directly -- the thing the classifier actually branches on. A junction can+ target a folder beneath a volume GUID path exactly as it can beneath a drive letter or+ a UNC share (reproduced for real with ``mklink /J`` against+ ``\\?\Volume{...}\Users\...``), so the rule has to be "names the whole volume", not+ "starts with Volume{"."""+ from soup_cli.utils import stripe_roots as stripe_roots_module++ link = tmp_path / "reparse-point"+ link.mkdir()+ monkeypatch.setattr(os, "readlink", lambda path: target)+ assert stripe_roots_module.is_volume_mount_point(str(link)) is expected++ def test_a_reparse_point_that_is_not_a_link_is_not_a_volume_mount_point(+ self, tmp_path, monkeypatch+ ):+ """On Windows ``os.readlink`` raises ``ValueError``, not ``OSError``, for a reparse+ point that is neither a symlink nor a junction/mount point, so the classifier has to+ expect both -- only catching ``OSError`` let such a folder through as "not a mount+ point, so must be a junction", when ``validate_stripe_root`` should refuse it by name+ instead of letting a bare ``ValueError`` escape."""+ from soup_cli.utils import stripe_roots as stripe_roots_module++ def not_a_link(path):+ raise ValueError("not a symbolic link")++ monkeypatch.setattr(os, "readlink", not_a_link)+ assert stripe_roots_module.is_volume_mount_point(str(tmp_path)) is False++ def test_a_non_reparse_folder_is_not_a_volume_mount_point(self, tmp_path):+ from soup_cli.utils.stripe_roots import is_volume_mount_point++ assert is_volume_mount_point(str(tmp_path)) is False++ @pytest.mark.skipif(not WINDOWS, reason="junctions are a Windows reparse point")+ def test_a_junction_stripe_root_is_refused(self, tmp_path):+ from soup_cli.utils.stripe_roots import validate_stripe_root++ target = tmp_path / "elsewhere"+ target.mkdir()+ link = tmp_path / "stripe-link"+ _junction(target, link)+ primary = tmp_path / "primary"+ primary.mkdir()+ with pytest.raises(StripeRootError, match="junction") as caught:+ validate_stripe_root(str(link), primary_root=str(primary))+ assert "stripe-link" in str(caught.value)++ @pytest.mark.skipif(not WINDOWS, reason="junctions are a Windows reparse point")+ def test_a_volume_mount_point_stripe_root_is_accepted(self, tmp_path, monkeypatch):+ """Same reparse tag as a junction; the classifier is what tells them apart, so this+ patches the classifier itself rather than the unavailable (needs elevation) real+ volume-mount-point setup."""+ from soup_cli.utils import stripe_roots as stripe_roots_module++ root = tmp_path / "mounted-volume"+ target = tmp_path / "elsewhere"+ target.mkdir()+ _junction(target, root)+ monkeypatch.setattr(stripe_roots_module, "is_volume_mount_point", lambda path: True)+ primary = tmp_path / "primary"+ primary.mkdir()+ resolved = stripe_roots_module.validate_stripe_root(+ str(root), primary_root=str(primary)+ )+ assert os.path.normcase(resolved) == os.path.normcase(os.path.realpath(str(root)))