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(streaming): report per-drive direct I/O state (#1962)
Samarth Mukhija56f4a9ccd68c
diff --git a/changelog.d/0.76.0/1962.fixed.md b/changelog.d/0.76.0/1962.fixed.mdnew file mode 100644index 00000000..d2cfbec9--- /dev/null+++ b/changelog.d/0.76.0/1962.fixed.md@@ -0,0 +1 @@+- **Layer streaming now reports mixed direct-I/O stripes accurately.** The ready line shows direct-I/O drives as `k/N`, runtime stats expose each root's mode, page-cache fallbacks name the affected root and operating-system reason, and RAM-tier runs no longer print disk read-ahead guidance (#1615 by @Samearth17 in #1962)diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 1a3d0328..7066d915 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -63,8 +63,13 @@ def _stream_source_line(stats: dict) -> str:)# Since #974 the staging lives in the same power-of-two arenas as the RAM# store, so the disk tier can say what was page-locked too.+ drive_count = stats.get("drive_count", 1)+ direct_io = stats.get("direct_io_drives", drive_count)+ media = "an NVMe volume"+ if drive_count > 1:+ media = f"{drive_count} NVMe volumes, direct I/O {direct_io}/{drive_count}"return (- f"streamed from DISK ({stats['disk_bytes'] / 1e9:.2f} GB on an NVMe volume) "+ f"streamed from DISK ({stats['disk_bytes'] / 1e9:.2f} GB on {media}) "f"by an async reader, read_ahead={stats['read_ahead']}, "f"{stats['store_bytes'] / 1e6:.0f} MB {pinned} host staging") + _page_locked_note(stats)@@ -306,7 +311,31 @@ def _disk_volume(path: str) -> tuple[int, int]:return int(os.stat(anchor).st_dev), int(shutil.disk_usage(anchor).free)-def _effective_read_ahead(tcfg: Any, n_roots: int, console: Any) -> ReadAheadDecision:+def _say_read_ahead_decision(decision: ReadAheadDecision, console: Any) -> None:+ """Explain a striped disk reader's effective depth."""+ n_roots = decision.n_roots+ if n_roots <= 1:+ return+ configured = decision.configured+ wanted = min(n_roots + 1, MAX_STREAM_READ_AHEAD)+ if decision.raised:+ console.print(+ f"[dim]training.stream_read_ahead {configured} -> {decision.depth}: the layer "+ f"cache spans {n_roots} drives, and each needs a read in flight "+ f"({DEFAULT_STREAM_READ_AHEAD} counts as the default; any other value is kept as "+ f"set).[/]"+ )+ elif configured < wanted:+ console.print(+ f"[yellow]training.stream_read_ahead={configured} with {n_roots} stripe drives "+ f"keeps {wanted - configured} of them idle between layers; {wanted} lets every "+ f"drive read at once (one more layer of host staging each).[/]"+ )+++def _effective_read_ahead(+ tcfg: Any, n_roots: int, console: Any, *, announce: bool = True+) -> ReadAheadDecision:"""The async reader's depth with ``n_roots`` drives (R4), and how it came about.Every drive needs a read in flight beside the slot the consumer holds, so the DEFAULT depth@@ -326,22 +355,8 @@ def _effective_read_ahead(tcfg: Any, n_roots: int, console: Any) -> ReadAheadDecdecision = ReadAheadDecision(depth=effective_read_ahead(configured, n_roots), configured=configured, n_roots=n_roots)- if n_roots <= 1:- return decision- wanted = min(n_roots + 1, MAX_STREAM_READ_AHEAD)- if decision.raised:- console.print(- f"[dim]training.stream_read_ahead {configured} -> {decision.depth}: the layer "- f"cache spans {n_roots} drives, and each needs a read in flight "- f"({DEFAULT_STREAM_READ_AHEAD} counts as the default; any other value is kept as "- f"set).[/]"- )- elif configured < wanted:- console.print(- f"[yellow]training.stream_read_ahead={configured} with {n_roots} stripe drives "- f"keeps {wanted - configured} of them idle between layers; {wanted} lets every "- f"drive read at once (one more layer of host staging each).[/]"- )+ if announce:+ _say_read_ahead_decision(decision, console)return decision@@ -961,7 +976,10 @@ class StreamingSetupMixin:# with getattr like `external_tensors` below: an index without the field is one root.# The whole decision travels to every message that advises lowering the depth.read_ahead_decision = _effective_read_ahead(- tcfg, 1 + len(getattr(index, "stripe_roots", None) or ()), console+ tcfg,+ 1 + len(getattr(index, "stripe_roots", None) or ()),+ console,+ announce=False,)read_ahead = read_ahead_decision.depth@@ -1081,6 +1099,8 @@ class StreamingSetupMixin:# back to disk when it does not. build_stream_plan already refused a# non-NVMe disk, so reaching here with tier='disk' means NVMe.tier = TIER_DISK if tcfg.stream_source == "disk" else plan.tier+ if tier == TIER_DISK:+ _say_read_ahead_decision(read_ahead_decision, console)if tier != plan.tier:# The panel is rendered from `plan`, so a forced tier has to be# reflected there or the pre-flight reports "tier ram" immediatelydiff --git a/src/soup_cli/utils/async_disk_source.py b/src/soup_cli/utils/async_disk_source.pyindex 8ca80585..90b50bac 100644--- a/src/soup_cli/utils/async_disk_source.py+++ b/src/soup_cli/utils/async_disk_source.py@@ -37,6 +37,7 @@ NO top-level torch: this module is imported by the trainer path only.import loggingimport math+import osimport queueimport threadingimport time@@ -590,14 +591,21 @@ class AsyncDiskSource:if not aligned: # _allocate_staging aligns every arena; kept as the safe fallbacklogger.warning(UNALIGNED_STAGING_MESSAGE)self._open_of: Dict[int, Any] = {}+ self.direct_io_roots: Dict[str, bool] = {}+ self.page_cache_reasons: Dict[str, str] = {}for root in self._roots:self._open_of[root] = self._open_buffered- if not aligned or root not in first_of_root:+ if root not in first_of_root:continueprobe_path = self._paths[first_of_root[root]]+ root_path = os.path.dirname(probe_path)+ self.direct_io_roots[root_path] = False+ if not aligned:+ continuetry:open_direct(probe_path).close()except OSError as exc:+ self.page_cache_reasons[root_path] = str(exc)logger.info("layer streaming's disk tier reads %s through the page cache: direct ""I/O is unavailable there (%s)",@@ -606,6 +614,7 @@ class AsyncDiskSource:)else:self._open_of[root] = open_direct+ self.direct_io_roots[root_path] = Trueself.direct_io = all(opener is not self._open_buffered for opener in self._open_of.values())# One drive keeps the historical worker names (`soup-layer-range-<n>`), which the# #974 and #1056 tests match on; a striped source names each drive's pool apart, so adiff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.pyindex 11651675..c8fbb82e 100644--- a/src/soup_cli/utils/layer_stream_runtime.py+++ b/src/soup_cli/utils/layer_stream_runtime.py@@ -2922,6 +2922,11 @@ class StreamRuntime:# number there would be an invented one."read_ahead": getattr(self.source, "read_ahead", None),"disk_bytes": getattr(self.source, "disk_bytes", 0),+ "drive_count": len(getattr(self.source, "direct_io_roots", {})),+ "direct_io_drives": sum(+ getattr(self.source, "direct_io_roots", {}).values()+ ),+ "direct_io_roots": dict(getattr(self.source, "direct_io_roots", {})),"layer_loads": self.pool.loads,"large_loads": getattr(self.large_pool, "loads", 0),"device": self.device,@@ -3513,6 +3518,25 @@ def _say_unaligned_staging(source: Any, console: Any) -> None:console.print(f"[yellow]{UNALIGNED_STAGING_MESSAGE}[/]")+def _say_page_cache_roots(source: Any, console: Any) -> None:+ """Name each drive whose operating system refused direct I/O (#1615)."""+ if console is None:+ return+ from soup_cli.utils.terminal import for_terminal++ for root, reason in getattr(source, "page_cache_reasons", {}).items():+ console.print(+ "[yellow]Layer streaming reads "+ f"{for_terminal(root)} through the page cache: direct I/O is unavailable there "+ f"({for_terminal(reason)}).[/]"+ )+++def _say_disk_source_fallbacks(source: Any, console: Any) -> None:+ _say_unaligned_staging(source, console)+ _say_page_cache_roots(source, console)++def _build_source(shard_dir,n_layers,@@ -3614,10 +3638,10 @@ def _build_source(# otherwise report as an out-of-memory it never had.recover_from_failed_page_lock(console=console)else:- _say_unaligned_staging(source, console)+ _say_disk_source_fallbacks(source, console)return source, source.pinnedsource = AsyncDiskSource(shard_dir, n_layers, spec, pin=False, **open_kwargs)- _say_unaligned_staging(source, console)+ _say_disk_source_fallbacks(source, console)return source, source.pinned# `source.pinned` on both branches rather than the literal, so the tuple's# second element has ONE meaning to read off: what the source says aboutdiff --git a/tests/test_disk_tier_stripe_reader.py b/tests/test_disk_tier_stripe_reader.pyindex 74c0e849..dfb73b1b 100644--- a/tests/test_disk_tier_stripe_reader.py+++ b/tests/test_disk_tier_stripe_reader.py@@ -1,10 +1,12 @@"""R4 — every drive keeps a read in flight; one drive still reads one layer at a time."""+import ioimport threadingimport timefrom pathlib import Pathimport pytest+from rich.console import Consoletorch = pytest.importorskip("torch")pytest.importorskip("safetensors")@@ -14,7 +16,14 @@ from safetensors.torch import save_file # noqa: E402import soup_cli.utils.async_disk_source as mod # noqa: E402from soup_cli.utils.async_disk_source import AsyncDiskSource, _RangeReaders # noqa: E402from soup_cli.utils.layer_shard import layer_shard_path # noqa: E402-from soup_cli.utils.layer_stream_runtime import DiskSource, RamSource # noqa: E402+from soup_cli.utils.layer_stream_runtime import ( # noqa: E402+ DiskSource,+ RamSource,+ StreamRuntime,+ _build_source,+ _say_page_cache_roots,+)+from tests.conftest import strip_ansi # noqa: E402N = 8@@ -302,6 +311,72 @@ def test_direct_io_is_decided_per_drive(tmp_path, monkeypatch):source.close()+def test_build_source_reports_each_drive_mode_and_page_cache_reason(tmp_path, monkeypatch):+ """The console and runtime stats expose the same per-drive decision."""+ def refuse_root1(path):+ if Path(path).parent.name == "root1":+ raise OSError("no direct I/O on this volume")+ return open(path, "rb", buffering=0)++ monkeypatch.setattr(mod, "open_direct", refuse_root1)+ shard_dir, paths, roots = _striped_shards(tmp_path)+ spec = RamSource.layer_specs_from_paths(paths)+ output = io.StringIO()+ source, pinned = _build_source(+ shard_dir,+ N,+ spec,+ pin=False,+ console=Console(file=output, width=200, color_system=None),+ tier="disk",+ shard_paths=paths,+ layer_roots=roots,+ read_ahead=3,+ )+ try:+ assert source._open_of[0] is refuse_root1+ assert source._open_of[1] == source._open_buffered+ pool = type("Pool", (), {"n": 2, "nbytes": 0, "loads": 0})()+ stats = StreamRuntime(+ pool=pool,+ source=source,+ prefetcher=None,+ n_layers=N,+ pinned=pinned,+ device="cpu",+ tier="disk",+ ).stats()+ assert stats["drive_count"] == 2+ assert stats["direct_io_drives"] == 1+ assert sorted(stats["direct_io_roots"].values()) == [False, True]+ said = " ".join(strip_ansi(output.getvalue()).split())+ assert "root1" in said+ assert "page cache" in said+ assert "no direct I/O on this volume" in said+ finally:+ source.close()+++def test_page_cache_warning_sanitizes_external_root_and_reason():+ output = io.StringIO()+ source = type(+ "Source",+ (),+ {"page_cache_reasons": {"[/]root\x1b": "[bold]refused[/]\x07"}},+ )()++ _say_page_cache_roots(+ source,+ Console(file=output, width=200, color_system=None),+ )++ said = strip_ansi(output.getvalue())+ assert "[/]root" in said+ assert "[bold]refused[/]" in said+ assert "\x1b" not in said+ assert "\x07" not in said++def test_submit_calls_on_done_once_per_job_after_its_outcome_is_set():pool = _RangeReaders(2)finished, calls = [], []diff --git a/tests/test_disk_tier_stripe_setup.py b/tests/test_disk_tier_stripe_setup.pyindex 4debb29a..ed361b86 100644--- a/tests/test_disk_tier_stripe_setup.py+++ b/tests/test_disk_tier_stripe_setup.py@@ -59,6 +59,34 @@ class TestTheDepth:assert _depth(DEFAULT_STREAM_READ_AHEAD, 9)[0] == MAX_STREAM_READ_AHEAD+class TestTheReadyLineNamesDriveModes:+ @staticmethod+ def _stats(drive_count, direct_io_drives):+ return {+ "tier": "disk",+ "pinned": False,+ "pinned_bytes": 0,+ "disk_bytes": 1_000_000_000,+ "read_ahead": 3,+ "store_bytes": 20_000_000,+ "drive_count": drive_count,+ "direct_io_drives": direct_io_drives,+ }++ def test_two_direct_drives_are_counted(self):+ line = stream_setup._stream_source_line(self._stats(2, 2))+ assert "2 NVMe volumes, direct I/O 2/2" in line++ def test_a_mixed_pair_is_counted(self):+ line = stream_setup._stream_source_line(self._stats(2, 1))+ assert "2 NVMe volumes, direct I/O 1/2" in line++ def test_one_drive_keeps_the_existing_wording(self):+ line = stream_setup._stream_source_line(self._stats(1, 1))+ assert "on an NVMe volume" in line+ assert "direct I/O" not in line++def test_every_depth_consumer_in_the_setup_reads_the_effective_value():"""The default N+1 is worth nothing if one consumer still reads the raw setting."""source = inspect.getsource(stream_setup)@@ -421,7 +449,7 @@ def _make_synthetic_untied_checkpoint(tmp_path, n_layers: int = 5) -> str:return str(weights)-def _drive_setup(tmp_path, monkeypatch, *, striped):+def _drive_setup(tmp_path, monkeypatch, *, striped, stream_source="ram"):"""The real `_setup_streaming_transformers` on a tiny checkpoint, runtime boundary spied.Same harness as test_issue623 (simulated CUDA, ``build_streamed_model`` spied). Two temp@@ -478,7 +506,7 @@ def _drive_setup(tmp_path, monkeypatch, *, striped):captured.update(kwargs)runtime = MagicMock()runtime.stats.return_value = {- "tier": "ram", "store_bytes": 1_000_000, "disk_bytes": 1_000_000,+ "tier": stream_source, "store_bytes": 1_000_000, "disk_bytes": 1_000_000,"pinned": False, "read_ahead": kwargs.get("read_ahead"), "buffers": 2,"buffer_bytes": 4_000, "n_layers": 3,}@@ -490,7 +518,7 @@ def _drive_setup(tmp_path, monkeypatch, *, striped):stream_setup, "console", Console(file=buffer, width=400, color_system=None))- cfg = load_config_from_string(_cfg_yaml(weights, ""))+ cfg = load_config_from_string(_cfg_yaml(weights, "", stream_source=stream_source))wrapper = SFTTrainerWrapper(cfg)wrapper.device = "cuda"wrapper._setup_streaming_transformers(cfg, cfg.training)@@ -512,7 +540,7 @@ class TestTheSetupPathUsesTheRoots:assert captured["read_ahead_decision"].raisedassert "Layer cache striped over" in saidassert "layer-shard stripe 1" in said # the second drive is charged on its own- assert f"training.stream_read_ahead {DEFAULT_STREAM_READ_AHEAD} -> 3" in said+ assert f"training.stream_read_ahead {DEFAULT_STREAM_READ_AHEAD} -> 3" not in saidstripe_folder = second_drive / os.listdir(second_drive)[0]assert any(name.startswith("layer_") for name in os.listdir(stripe_folder)), ("no layer file landed on the second drive"@@ -521,6 +549,12 @@ class TestTheSetupPathUsesTheRoots:assert len(preflight_calls) >= 1assert preflight_calls[0]["shard_write_bytes"] > preflight_calls[0]["stripe_writes"][0][1]+ def test_disk_tier_announces_the_effective_stripe_depth(self, tmp_path, monkeypatch):+ _captured, said, _second_drive, _preflight = _drive_setup(+ tmp_path, monkeypatch, striped=True, stream_source="disk"+ )+ assert f"training.stream_read_ahead {DEFAULT_STREAM_READ_AHEAD} -> 3" in said+def test_one_drive_is_left_exactly_as_it_was(self, tmp_path, monkeypatch):captured, said, _second_drive, _preflight = _drive_setup(tmp_path, monkeypatch, striped=False