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): classify the Linux cache volume rather than any NVMe disk (#1800) (#1847)

Nurkhan Esenbek42718463fb32
diff --git a/changelog.d/0.76.0/1847.fixed.md b/changelog.d/0.76.0/1847.fixed.md
new file mode 100644
index 00000000..5819600d
--- /dev/null
+++ b/changelog.d/0.76.0/1847.fixed.md
@@ -0,0 +1 @@
+- Attribute Linux streaming disk detection to the cache volume, resolving partitions and stacked-device members instead of accepting an unrelated NVMe disk; retain the path-based throughput fallback. (#1800 by @kok-o in #1847)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index a8bb92e8..1b264d23 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -564,7 +564,7 @@ The 3.32 GB 8B row above predates large-layer streaming: its untied, unquantised
- **Warm — the whole store in the page cache — was reported as a 1.03–1.20x REGRESSION** against the synchronous source (gate-971 §5). Position-matched in both run orders it is **0.91–0.97x**, i.e. not one: the bracket was the run-order effect that record had already named for the cold fixture (#974). After the change, in one session against the reader it replaces, the new reader is 0.76x of it warm (1.58 vs 2.09 s) and 2.25x faster right after a page-cache eviction (1.79 vs 4.02 s). **If the store fits RAM, use the RAM tier** — 1.1 s against 1.8–2.0 s for either disk arm in the same session; the disk tier exists for a store that does not.
- **It is still bound by the read, less so since #974**: per-layer read brackets were 82.6–84.9% of the cold step in gate-971 and are 62–64% after the direct-I/O reader. There is no measured read-free floor at this sequence to compare that against — the ~14 s figure is at a shorter one — so no headroom ratio is quoted.
- **`stream_read_ahead` did not change throughput** in that record. Depths 1, 2 and 4 were indistinguishable once run order was controlled for — the same configuration measured 48.09 s run first and 30.28 s run last, as the page cache warmed across blocks, which is larger than the whole spread across depths. Treat it as a **host-memory knob**: 1.5 GB of pinned staging at depth 1, 2.0 GB at 2, 2.8 GB at 4 on a 70B. The pre-flight prints that figure on the disk tier (`host staging read_ahead N -> X MB`) and **refuses the run** when it plus the resident extras will not fit the free-RAM headroom, naming `stream_read_ahead` as the knob to lower — the embedding and an untied `lm_head` take one slot each at any depth, because they are one layer each.
- - **Disk-kind detection.** A paravirtual (virtio) disk reports `rotational=1` with no media hint, so a genuinely NVMe-backed cloud disk was misread as an HDD and refused (#365); detection now measures a bounded O_DIRECT sequential read when the rotational flag is unreliable and admits NVMe-class throughput (>= 1 GB/s), while a genuinely slow disk stays rejected. Set `training.stream_disk_kind: nvme` (or `ssd`/`hdd`) to override when detection is still wrong — the resolved value is printed beside what was detected.
+ - **Disk-kind detection.** On Linux, detection follows the requested path's device through `/sys/dev/block`, including partitions and device-mapper/RAID members; a mixed volume uses its slowest member. An unrelated NVMe disk does not qualify the cache volume. A paravirtual (virtio) disk reports `rotational=1` with no media hint, so a genuinely NVMe-backed cloud disk was misread as an HDD and refused (#365); detection measures a bounded O_DIRECT sequential read on the requested path when the rotational flag is unreliable or the device cannot be attributed, and admits NVMe-class throughput (>= 1 GB/s), while a genuinely slow disk stays rejected. Set `training.stream_disk_kind: nvme` (or `ssd`/`hdd`) to override when detection is still wrong — the resolved value is printed beside what was detected.
- **Apple APFS disk detection.** On macOS, an APFS volume may report `Apple Fabric`
even when its physical store is Apple's internal NVMe. Soup resolves the target
volume to its APFS physical store and admits it only when that exact device is
diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.py
index 94dc9fee..3bfbb0ea 100644
--- a/src/soup_cli/utils/layer_stream.py
+++ b/src/soup_cli/utils/layer_stream.py
@@ -654,38 +654,65 @@ def _measure_seq_read_bytes_per_s(path: str) -> Optional[float]:
pass
+_LINUX_SYS_DEV_BLOCK = "/sys/dev/block"
+
+
+def _linux_block_kind(device: str, ancestors: frozenset[str] = frozenset()) -> str:
+ """Classify one sysfs device, following partitions and stacked-volume members."""
+ import os
+
+ device = os.path.realpath(device)
+ if device in ancestors or len(ancestors) >= 32 or not os.path.isdir(device):
+ return "unknown"
+ ancestors = ancestors | {device}
+ if os.path.exists(os.path.join(device, "partition")):
+ return _linux_block_kind(os.path.dirname(device), ancestors)
+ slaves = os.path.join(device, "slaves")
+ if os.path.isdir(slaves):
+ members = os.listdir(slaves)
+ if members:
+ kinds = {_linux_block_kind(os.path.join(slaves, name), ancestors) for name in members}
+ return next(kind for kind in ("hdd", "unknown", "ssd", _NVME) if kind in kinds)
+ if os.path.basename(device).startswith("nvme"):
+ return _NVME
+ rotational = os.path.join(device, "queue", "rotational")
+ if os.path.isfile(rotational):
+ with open(rotational, encoding="utf-8") as handle:
+ value = handle.read().strip()
+ return {"0": "ssd", "1": "hdd"}.get(value, "unknown")
+ return "unknown"
+
+
+def _linux_path_disk_kind(path: str) -> str:
+ """Attribute the volume to sysfs before reading its media type."""
+ import os
+
+ try:
+ dev = os.stat(os.path.expanduser(path)).st_dev
+ device = f"{_LINUX_SYS_DEV_BLOCK}/{os.major(dev)}:{os.minor(dev)}"
+ return _linux_block_kind(device)
+ except (OSError, ValueError):
+ return "unknown"
+
+
def _probe_disk_kind(path: str) -> DiskClassification:
"""Classify the volume holding ``path``, carrying the measured rate only when
the verdict was DERIVED from a read (so a refusal can never cite a rate that
did not produce its own verdict — see ``DiskClassification``)."""
- import os
import platform
import subprocess
system = platform.system()
try:
if system == "Linux":
- # /sys/block/<dev>/queue/rotational: 1 spinning, 0 solid state.
- # The device name distinguishes NVMe, and rotational=0 is
- # authoritative — a device that declares itself solid state is one.
- # rotational=1 is NOT authoritative: virtio defaults it to 1 with no
- # media hint, so a fast cloud disk lies as spinning (#365). Fall back
- # to a measured read there rather than trust the flag.
- names = sorted(os.listdir("/sys/block"))
- for dev in names:
- if not dev.startswith("nvme"):
- continue
- return DiskClassification(_NVME)
- for dev in names:
- rot = os.path.join("/sys/block", dev, "queue", "rotational")
- if os.path.exists(rot):
- with open(rot, encoding="utf-8") as handle:
- value = handle.read().strip()
- if value == "0":
- return DiskClassification("ssd")
- measured = _measure_seq_read_bytes_per_s(path)
- return DiskClassification(_classify_measured_read(measured), measured)
- return DiskClassification("unknown")
+ kind = _linux_path_disk_kind(path)
+ if kind in (_NVME, "ssd"):
+ return DiskClassification(kind)
+ # rotational=1 can describe fast virtio storage (#365). Unknown
+ # volumes (network, overlay, missing sysfs) also need a path-based
+ # read, never the name of an unrelated physical disk (#1800).
+ measured = _measure_seq_read_bytes_per_s(path)
+ return DiskClassification(_classify_measured_read(measured), measured)
if system == "Windows":
shell = _resolve_tool("powershell", _POWERSHELL_FALLBACK)
if shell is None:
diff --git a/tests/test_issue1800_linux_disk_attribution.py b/tests/test_issue1800_linux_disk_attribution.py
new file mode 100644
index 00000000..60249d11
--- /dev/null
+++ b/tests/test_issue1800_linux_disk_attribution.py
@@ -0,0 +1,189 @@
+"""Linux disk classification follows the cache volume, not unrelated hardware."""
+
+import os
+import platform
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.utils import layer_stream as ls
+
+
+def sysfs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Real directories with emulated sysfs links (also usable on Windows)."""
+ devices = tmp_path / "sys" / "devices"
+ dev_block = tmp_path / "sys" / "dev" / "block"
+ dev_block.mkdir(parents=True)
+ links = {}
+ realpath = os.path.realpath
+ real_stat = os.stat
+ cache = str(tmp_path / "cache")
+ monkeypatch.setattr(platform, "system", lambda: "Linux")
+ monkeypatch.setattr(ls, "_LINUX_SYS_DEV_BLOCK", str(dev_block), raising=False)
+ monkeypatch.setattr(os, "major", lambda dev: dev >> 8, raising=False)
+ monkeypatch.setattr(os, "minor", lambda dev: dev & 255, raising=False)
+
+ def stat(path, *args, **kwargs):
+ if str(path) == cache:
+ return SimpleNamespace(st_dev=2049)
+ return real_stat(path, *args, **kwargs)
+
+ def resolve(path, *args, **kwargs):
+ key = os.path.normpath(str(path))
+ return links[key] if key in links else realpath(path, *args, **kwargs)
+
+ def device(name, rotational=None, *, parent=None, slaves=()):
+ node = (parent or devices) / name
+ node.mkdir(parents=True, exist_ok=True)
+ if parent is not None:
+ (node / "partition").write_text("1", encoding="utf-8")
+ if rotational is not None:
+ (node / "queue").mkdir(exist_ok=True)
+ (node / "queue/rotational").write_text(str(rotational), encoding="utf-8")
+ if slaves:
+ (node / "slaves").mkdir(exist_ok=True)
+ for member in slaves:
+ link = node / "slaves" / member.name
+ link.mkdir()
+ links[str(link)] = str(member)
+ return node
+
+ monkeypatch.setattr(os, "stat", stat)
+ monkeypatch.setattr(os.path, "realpath", resolve)
+ measured_paths = []
+ monkeypatch.setattr(
+ ls, "_measure_seq_read_bytes_per_s",
+ lambda path: measured_paths.append(path) or 150_000_000,
+ )
+ return SimpleNamespace(
+ device=device, links=links, volume=os.path.normpath(f"{dev_block}/8:1"),
+ cache=cache, measured_paths=measured_paths,
+ )
+
+
+def test_rotational_cache_does_not_borrow_unrelated_nvme(sysfs, monkeypatch) -> None:
+ sysfs.device("nvme0n1", 0)
+ sysfs.links[sysfs.volume] = str(sysfs.device("sda", 1))
+ real_listdir = os.listdir
+ monkeypatch.setattr(
+ os, "listdir",
+ lambda path: ["nvme0n1", "sda"] if str(path) == "/sys/block" else real_listdir(path),
+ )
+ verdict = ls._probe_disk_kind(sysfs.cache)
+ assert verdict == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
+ with pytest.raises(ValueError, match="not NVMe"):
+ ls.choose_tier(1000, 100, verdict)
+
+
[email protected]("name,rotational,expected", [("nvme0n1", 0, "nvme"), ("sda", 0, "ssd")])
+def test_attributed_solid_state_device_never_measures(sysfs, name, rotational, expected) -> None:
+ sysfs.links[sysfs.volume] = str(sysfs.device(name, rotational))
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification(expected)
+ assert sysfs.measured_paths == []
+
+
[email protected]("name,expected", [("nvme0n1", "nvme"), ("sda", "ssd")])
+def test_partition_resolves_to_its_parent_disk(sysfs, name, expected) -> None:
+ disk = sysfs.device(name, 0)
+ sysfs.links[sysfs.volume] = str(sysfs.device(name + "p1", parent=disk))
+ assert ls._probe_disk_kind(sysfs.cache).kind == expected
+ assert sysfs.measured_paths == []
+
+
[email protected]("stack", ["dm-0", "md0"])
+def test_stacked_volume_classifies_its_members(sysfs, stack) -> None:
+ disk = sysfs.device("nvme0n1", 0)
+ part = sysfs.device("nvme0n1p1", parent=disk)
+ sysfs.links[sysfs.volume] = str(sysfs.device(stack, 0, slaves=[part]))
+ assert ls._probe_disk_kind(sysfs.cache).kind == "nvme"
+
+
+def test_mixed_stack_uses_worst_member(sysfs) -> None:
+ nvme = sysfs.device("nvme0n1", 0)
+ sata = sysfs.device("sda", 0)
+ sysfs.links[sysfs.volume] = str(sysfs.device("dm-0", 0, slaves=[nvme, sata]))
+ assert ls._probe_disk_kind(sysfs.cache).kind == "ssd"
+
+
+def test_mixed_rotational_stack_uses_volume_measurement(sysfs) -> None:
+ nvme = sysfs.device("nvme0n1", 0)
+ hdd = sysfs.device("sda", 1)
+ sysfs.links[sysfs.volume] = str(sysfs.device("md0", 0, slaves=[nvme, hdd]))
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
[email protected]("measured,expected", [(1_500_000_000, "nvme"), (None, "hdd")])
+def test_unattributed_volume_falls_back_to_its_own_read(
+ sysfs, monkeypatch, measured, expected,
+) -> None:
+ calls = []
+ monkeypatch.setattr(ls, "_measure_seq_read_bytes_per_s", lambda p: calls.append(p) or measured)
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification(expected, measured)
+ assert calls == [sysfs.cache]
+
+
+def test_fast_virtio_keeps_issue365_measured_fallback(sysfs, monkeypatch) -> None:
+ sysfs.links[sysfs.volume] = str(sysfs.device("vda", 1))
+ monkeypatch.setattr(ls, "_measure_seq_read_bytes_per_s", lambda path: 1_500_000_000)
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("nvme", 1_500_000_000)
+
+
+def test_unreadable_path_still_attempts_its_own_measurement(sysfs, monkeypatch) -> None:
+ stat = os.stat
+
+ def unreadable(path, *args, **kwargs):
+ if str(path) == sysfs.cache:
+ raise OSError("volume inaccessible")
+ return stat(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "stat", unreadable)
+ assert ls._probe_disk_kind(sysfs.cache).kind == "hdd"
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
+def test_cyclic_sysfs_members_do_not_recurse_forever(sysfs) -> None:
+ device = sysfs.device("dm-0", 0)
+ link = device / "slaves" / "cycle"
+ link.mkdir(parents=True)
+ sysfs.links[str(link)] = str(device)
+ sysfs.links[sysfs.volume] = str(device)
+ assert ls._probe_disk_kind(sysfs.cache).kind == "hdd"
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
+def test_dangling_sysfs_entry_is_unknown_even_if_its_name_looks_like_nvme(sysfs) -> None:
+ gone = Path(sysfs.volume).parent.parent / "devices" / "gone" / "nvme0n1"
+ sysfs.links[sysfs.volume] = str(gone)
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
+def test_stack_with_an_unattributable_member_is_measured_not_trusted(sysfs) -> None:
+ ssd = sysfs.device("sda", 0)
+ odd = sysfs.device("odd0")
+ sysfs.links[sysfs.volume] = str(sysfs.device("dm-0", 0, slaves=[ssd, odd]))
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
[email protected]("content", [b"\xff\xfe", b"2", b""])
+def test_garbage_rotational_value_is_measured_not_guessed(sysfs, content) -> None:
+ disk = sysfs.device("sdx")
+ (disk / "queue").mkdir()
+ (disk / "queue" / "rotational").write_bytes(content)
+ sysfs.links[sysfs.volume] = str(disk)
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
+
+
+def test_a_very_deep_stack_is_bounded_and_measured(sysfs) -> None:
+ node = sysfs.device("n0", 0)
+ for index in range(1, 40):
+ node = sysfs.device(f"n{index}", 0, slaves=[node])
+ sysfs.links[sysfs.volume] = str(node)
+ assert ls._probe_disk_kind(sysfs.cache) == ls.DiskClassification("hdd", 150_000_000)
+ assert sysfs.measured_paths == [sysfs.cache]
diff --git a/tests/test_v07203.py b/tests/test_v07203.py
index 59d5a149..4866bf9c 100644
--- a/tests/test_v07203.py
+++ b/tests/test_v07203.py
@@ -1250,47 +1250,16 @@ class TestDiskKindMeasuredFallback:
assert _classify_measured_read(None) == "hdd" # can't tell -> refuse
@staticmethod
- def _fake_linux(monkeypatch, *, devices, rotational, measured_bps):
- """Simulate a Linux ``/sys/block`` layout so the real probe branch runs."""
- import builtins
- import io
- import os
+ def _fake_linux(monkeypatch, *, rotational, measured_bps):
+ """Supply attributed media; #1800 tests cover the sysfs traversal itself."""
import platform
- import sys
-
- import pytest
-
- # detect_disk_kind is a Linux /sys/block feature (it returns "unknown"
- # elsewhere by design). This helper hardcodes forward-slash /sys paths,
- # which os.path.join mangles on Windows, so the simulation is meaningful
- # only on Linux — where the real CI cells and local runs exercise it.
- if sys.platform != "linux":
- pytest.skip("simulates a Linux /sys/block layout; disk-tier detection is Linux-only")
import soup_cli.utils.layer_stream as ls
- real_listdir = os.listdir
- real_open = builtins.open
- real_exists = os.path.exists
-
monkeypatch.setattr(platform, "system", lambda: "Linux")
monkeypatch.setattr(
- os,
- "listdir",
- lambda p: list(devices) if str(p) == "/sys/block" else real_listdir(p),
- )
- monkeypatch.setattr(
- os.path,
- "exists",
- lambda p: True if "/queue/rotational" in str(p) else real_exists(p),
+ ls, "_linux_path_disk_kind", lambda _p: "ssd" if rotational == 0 else "hdd",
)
-
- def fake_open(p, *a, **k):
- if "/queue/rotational" in str(p):
- return io.StringIO(f"{rotational}\n")
- return real_open(p, *a, **k)
-
- monkeypatch.setattr(builtins, "open", fake_open)
monkeypatch.setattr(ls, "_measure_seq_read_bytes_per_s", lambda _p: measured_bps)
monkeypatch.setattr(ls, "_DISK_KIND_CACHE", {})
@@ -1298,7 +1267,7 @@ class TestDiskKindMeasuredFallback:
"""Criterion 1: no NVMe device, ``rotational=1``, fast measured read."""
import soup_cli.utils.layer_stream as ls
- self._fake_linux(monkeypatch, devices=["vda"], rotational=1, measured_bps=1.5e9)
+ self._fake_linux(monkeypatch, rotational=1, measured_bps=1.5e9)
assert ls.detect_disk_kind("/data") == "nvme"
# ...and choose_tier accepts it where the pre-fix "hdd" would have raised.
assert ls.choose_tier(1000, 10, ls.detect_disk_kind("/data")) == ls.TIER_DISK
@@ -1307,7 +1276,7 @@ class TestDiskKindMeasuredFallback:
"""Criterion 2 (the control): the fix cannot be satisfied by 'always allow'."""
import soup_cli.utils.layer_stream as ls
- self._fake_linux(monkeypatch, devices=["vda"], rotational=1, measured_bps=150e6)
+ self._fake_linux(monkeypatch, rotational=1, measured_bps=150e6)
assert ls.detect_disk_kind("/data") == "hdd"
with pytest.raises(ValueError, match="NVMe"):
ls.choose_tier(1000, 10, ls.detect_disk_kind("/data"))
@@ -1316,7 +1285,7 @@ class TestDiskKindMeasuredFallback:
"""A device that declares itself solid state is trusted — no probe cost."""
import soup_cli.utils.layer_stream as ls
- self._fake_linux(monkeypatch, devices=["sda"], rotational=0, measured_bps=None)
+ self._fake_linux(monkeypatch, rotational=0, measured_bps=None)
calls = []
monkeypatch.setattr(
ls, "_measure_seq_read_bytes_per_s", lambda _p: calls.append(1) or 9e9