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.

perf(config): move shared config bounds into a dependency-free leaf (#780) (#1368)

Ercan Er0d3724d48d22
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 04ed5096..6d57fd47 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -6,20 +6,24 @@ from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, Field, field_validator, model_validator
-# Buffer bounds live with the streaming planner so the schema bound and the
-# runtime validator's message can never disagree (layer_stream has no torch).
-from soup_cli.utils.layer_stream import (
+# Stream-buffer, read-ahead and noise-floor bounds come from a dependency-free
+# leaf that layer_stream, async_disk_source and ship_verdict re-export, so the
+# schema bound and the runtime validator's message are the same object, and the
+# schema does not pull those runtimes onto the `soup version` path (#780).
+from soup_cli.utils.config_bounds import (
DEFAULT_STREAM_BUFFERS,
DEFAULT_STREAM_READ_AHEAD,
+ MAX_NOISE_FLOOR_RUNS,
MAX_STREAM_BUFFERS,
MAX_STREAM_READ_AHEAD,
+ MIN_NOISE_FLOOR_RUNS,
MIN_STREAM_BUFFERS,
MIN_STREAM_READ_AHEAD,
)
-from soup_cli.utils.layer_stream import (
+from soup_cli.utils.config_bounds import (
ROLLOUT_STREAM_TASKS as _STREAM_ROLLOUT_TASKS,
)
-from soup_cli.utils.layer_stream import (
+from soup_cli.utils.config_bounds import (
SUPPORTED_STREAM_TASKS as _STREAM_SUPPORTED_TASKS,
)
@@ -30,14 +34,6 @@ from soup_cli.utils.long_context import LONGROPE_REFUSAL
# Stdlib-only structural check shared by every regex a config can carry.
from soup_cli.utils.safe_regex import check_config_regex
-# Noise-floor bounds live with the ship verdict so the schema bound and the
-# `--noise-floor` CLI validator can never disagree (ship_verdict has no torch,
-# same reasoning as stream_buffers importing its bounds from layer_stream).
-from soup_cli.utils.ship_verdict import (
- MAX_NOISE_FLOOR_RUNS,
- MIN_NOISE_FLOOR_RUNS,
-)
-
# v0.39.0 Part C — per-pattern LoRA rank/alpha bounds
_MAX_LORA_RANK_PATTERN_KEYS = 256
_MAX_LORA_RANK_PATTERN_VALUE = 1024
@@ -4390,8 +4386,9 @@ class ShipConfig(BaseModel):
)
# v0.73.2 shipped `--noise-floor` (#376) without its config surface, so it
# was the one gate-policy flag that could not be committed to soup.yaml
- # (#406). Bounds import from ship_verdict so the schema and the CLI
- # validator (_validate_noise_floor_flag) share one source of truth.
+ # (#406). Bounds import from utils/config_bounds, which ship_verdict
+ # re-exports to the CLI validator (_validate_noise_floor_flag), so the two
+ # share one object.
noise_floor: Optional[int] = Field(
default=None,
ge=MIN_NOISE_FLOOR_RUNS,
diff --git a/src/soup_cli/utils/async_disk_source.py b/src/soup_cli/utils/async_disk_source.py
index b318548f..93b83a23 100644
--- a/src/soup_cli/utils/async_disk_source.py
+++ b/src/soup_cli/utils/async_disk_source.py
@@ -43,6 +43,13 @@ import time
from dataclasses import dataclass
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
+# Declared in the dependency-free leaf so the schema can import the bound
+# without this module (#780); re-exported so there is only one object.
+from soup_cli.utils.config_bounds import (
+ DEFAULT_STREAM_READ_AHEAD,
+ MAX_STREAM_READ_AHEAD,
+ MIN_STREAM_READ_AHEAD,
+)
from soup_cli.utils.safetensors_reader import (
SECTOR_BYTES,
ShardIdentity,
@@ -57,10 +64,6 @@ from soup_cli.utils.safetensors_reader import (
logger = logging.getLogger(__name__)
-MIN_STREAM_READ_AHEAD = 1
-MAX_STREAM_READ_AHEAD = 8
-DEFAULT_STREAM_READ_AHEAD = 2
-
#: How many byte ranges a layer's data section is read as, each by its own
#: worker thread through its own direct-I/O handle. Measured cold on the
#: 70B-shaped NF4 store (#974; fresh layers per configuration, Samsung PM9B1
diff --git a/src/soup_cli/utils/config_bounds.py b/src/soup_cli/utils/config_bounds.py
new file mode 100644
index 00000000..e509b879
--- /dev/null
+++ b/src/soup_cli/utils/config_bounds.py
@@ -0,0 +1,38 @@
+"""Config bounds shared by ``config/schema.py`` and the runtimes that enforce them.
+
+A leaf: it imports nothing, so ``schema.py`` can take these values without
+pulling the streaming and ship-verdict runtimes (and their ``rich`` subtree)
+onto the ``soup version`` import path (#780). The runtime modules re-export
+these names, so the schema bound and the runtime message stay one object.
+"""
+
+# --- layer streaming: buffers (utils/layer_stream.py) ----------------------
+MIN_STREAM_BUFFERS = 2
+MAX_STREAM_BUFFERS = 8
+DEFAULT_STREAM_BUFFERS = 2
+
+# --- layer streaming: read-ahead (utils/async_disk_source.py) --------------
+MIN_STREAM_READ_AHEAD = 1
+MAX_STREAM_READ_AHEAD = 8
+DEFAULT_STREAM_READ_AHEAD = 2
+
+# --- layer streaming: tasks ------------------------------------------------
+#: Tasks whose trainers can run against a streamed base (v0.72.4).
+#:
+#: DPO and KTO take their reference model from the SAME streamed base with the
+#: adapters disabled (TRL's ``null_ref_context``), so the reference costs no
+#: extra weights at all — measured 0.914x the SFT peak, where forcing a real
+#: second instance cost 9.92x. ORPO and SimPO are reference-free.
+SUPPORTED_STREAM_TASKS = ("sft", "dpo", "orpo", "simpo", "kto")
+
+#: Tasks PERMANENTLY excluded, not merely unimplemented. Generation rollouts
+#: re-read every layer once per generated token, which destroys the whole
+#: premise: streaming amortises one weight read over a training step, not over a
+#: single decoded token (plan §3.2).
+ROLLOUT_STREAM_TASKS = ("grpo", "ppo")
+
+# --- ship verdict: noise floor (utils/ship_verdict.py) ---------------------
+#: A floor needs a spread, and a spread needs at least two samples.
+MIN_NOISE_FLOOR_RUNS = 2
+#: Each run is a full pass over the base model; ten is already expensive.
+MAX_NOISE_FLOOR_RUNS = 10
diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.py
index 6635a599..94dc9fee 100644
--- a/src/soup_cli/utils/layer_stream.py
+++ b/src/soup_cli/utils/layer_stream.py
@@ -23,6 +23,20 @@ from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union
from rich.panel import Panel
+# Buffer, read-ahead and task bounds live in a dependency-free leaf so the schema
+# can import them without this module's rich subtree (#780). Re-exported here, not
+# redeclared, so the schema bound and the runtime message are the same object.
+from soup_cli.utils.config_bounds import (
+ DEFAULT_STREAM_BUFFERS,
+ DEFAULT_STREAM_READ_AHEAD,
+ MAX_STREAM_BUFFERS,
+ MAX_STREAM_READ_AHEAD, # noqa: F401
+ MIN_STREAM_BUFFERS,
+ MIN_STREAM_READ_AHEAD, # noqa: F401
+ ROLLOUT_STREAM_TASKS, # noqa: F401
+ SUPPORTED_STREAM_TASKS, # noqa: F401
+)
+
# Quantisation names are re-exported, NOT redeclared: layer_shard owns the shard
# format and these same strings key its cache-invalidation check. Two copies
# could drift and leave this module's pre-flight RAM estimate disagreeing with
@@ -56,35 +70,6 @@ PHYSICAL_RAM_TIER_HEADROOM_PERCENT = round(PHYSICAL_RAM_TIER_HEADROOM * 100)
PIN_THROUGHPUT_GAIN_REAL = 6.56
PIN_THROUGHPUT_GAIN_SYNTHETIC = 7.41
-# --- buffers --------------------------------------------------------------
-MIN_STREAM_BUFFERS = 2
-MAX_STREAM_BUFFERS = 8
-DEFAULT_STREAM_BUFFERS = 2
-
-# Re-exported, not redeclared: the schema imports its bound from here and the
-# runtime declares it, so the message and the check cannot disagree (the same
-# reasoning as stream_buffers).
-from soup_cli.utils.async_disk_source import ( # noqa: E402
- DEFAULT_STREAM_READ_AHEAD, # noqa: F401
- MAX_STREAM_READ_AHEAD, # noqa: F401
- MIN_STREAM_READ_AHEAD, # noqa: F401
-)
-
-# --- tasks ----------------------------------------------------------------
-#: Tasks whose trainers can run against a streamed base (v0.72.4).
-#:
-#: DPO and KTO take their reference model from the SAME streamed base with the
-#: adapters disabled (TRL's ``null_ref_context``), so the reference costs no
-#: extra weights at all — measured 0.914x the SFT peak, where forcing a real
-#: second instance cost 9.92x. ORPO and SimPO are reference-free.
-SUPPORTED_STREAM_TASKS = ("sft", "dpo", "orpo", "simpo", "kto")
-
-#: Tasks PERMANENTLY excluded, not merely unimplemented. Generation rollouts
-#: re-read every layer once per generated token, which destroys the whole
-#: premise: streaming amortises one weight read over a training step, not over a
-#: single decoded token (plan §3.2).
-ROLLOUT_STREAM_TASKS = ("grpo", "ppo")
-
#: FLOPs per parameter per token. 6 == WITH gradient checkpointing
#: (2 forward + 2 recompute + 2 dL/dx; base weight-grads are skipped because
#: the base is frozen). Streaming always checkpoints, so this is never 4.
diff --git a/src/soup_cli/utils/ship_verdict.py b/src/soup_cli/utils/ship_verdict.py
index 578733a5..a6ea343b 100644
--- a/src/soup_cli/utils/ship_verdict.py
+++ b/src/soup_cli/utils/ship_verdict.py
@@ -47,6 +47,10 @@ from rich.panel import Panel
from rich.table import Table
from soup_cli import __version__
+
+# Declared in the dependency-free leaf so the schema can import the bound
+# without this module (#780); re-exported so there is only one object.
+from soup_cli.utils.config_bounds import MAX_NOISE_FLOOR_RUNS, MIN_NOISE_FLOOR_RUNS
from soup_cli.utils.terminal import strip_control as for_terminal
# ---------------------------------------------------------------------------
@@ -123,11 +127,6 @@ _MIN_MD_FENCE_LEN = 3
#: harmless only because it then fails downstream as an unscoreable benchmark.
TASK_AXIS = "__task__"
-#: A floor needs a spread, and a spread needs at least two samples.
-MIN_NOISE_FLOOR_RUNS = 2
-#: Each run is a full pass over the base model; ten is already expensive.
-MAX_NOISE_FLOOR_RUNS = 10
-
# Input hygiene on an evidence-supplied floors mapping. These mirror
# ``commands/ship._MAX_SUITE_BENCHMARKS`` / ``_MAX_BENCHMARK_NAME_CHARS`` so the
# file-read path is bounded the same way the CLI flag path is.
diff --git a/tests/test_config_bounds_leaf.py b/tests/test_config_bounds_leaf.py
new file mode 100644
index 00000000..9503c1df
--- /dev/null
+++ b/tests/test_config_bounds_leaf.py
@@ -0,0 +1,130 @@
+"""``utils/config_bounds.py`` must stay a leaf, and keep the streaming runtime off
+the ``soup version`` import path (#780).
+
+``config/schema.py`` takes its stream-buffer, read-ahead and noise-floor bounds
+from the leaf. If the leaf grows an import, or the schema goes back to importing
+a runtime module, six modules (``layer_stream``, ``layer_shard``,
+``async_disk_source``, ``safetensors_reader``, ``queue``, ``_queue``) creep back
+onto CLI startup with no other test noticing.
+"""
+
+from __future__ import annotations
+
+import ast
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import soup_cli.config.schema as schema
+import soup_cli.utils.async_disk_source as async_disk_source
+import soup_cli.utils.config_bounds as config_bounds
+import soup_cli.utils.layer_stream as layer_stream
+import soup_cli.utils.ship_verdict as ship_verdict
+
+# queue/_queue are left out: a third-party dependency may import them on some
+# Python or platform, which would make the assertion flaky for non-Soup reasons.
+_OFF_THE_CLI_PATH = (
+ "soup_cli.utils.layer_stream",
+ "soup_cli.utils.layer_shard",
+ "soup_cli.utils.async_disk_source",
+ "soup_cli.utils.safetensors_reader",
+)
+
+
+def _imported_modules(path: Path) -> list[str]:
+ names = []
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.Import):
+ names.extend(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom):
+ names.append(node.module or "")
+ return names
+
+
+def test_leaf_imports_nothing():
+ imported = [m for m in _imported_modules(Path(config_bounds.__file__)) if m != "__future__"]
+ assert not imported, (
+ f"config_bounds imports {imported}; it must stay a leaf or the schema drags "
+ "that module's subtree onto `soup version` (or `import soup_cli.config.schema`)."
+ )
+
+
+def _loaded_after(code: str, modules: tuple[str, ...]) -> list[str]:
+ probe = f"import sys\n{code}\nprint(','.join(m for m in {modules!r} if m in sys.modules))"
+ proc = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, timeout=300
+ )
+ assert proc.returncode == 0, (proc.stdout, proc.stderr)
+ return [m for m in proc.stdout.strip().split(",") if m]
+
+
+def test_cli_import_loads_none_of_the_streaming_runtime():
+ loaded = _loaded_after("import soup_cli.cli", _OFF_THE_CLI_PATH)
+ assert not loaded, (
+ f"`import soup_cli.cli` loaded {loaded}. Something on the CLI import path "
+ "imports the streaming runtime eagerly; config bounds belong in utils/config_bounds."
+ )
+
+
+def test_probe_reports_every_module_when_loaded():
+ """Control: each name is reported when it IS loaded."""
+ imports = "\n".join(f"import {m}" for m in _OFF_THE_CLI_PATH)
+ assert _loaded_after(f"import soup_cli.cli\n{imports}", _OFF_THE_CLI_PATH) == list(
+ _OFF_THE_CLI_PATH
+ )
+
+
+ ("module", "name", "leaf_name"),
+ [
+ (layer_stream, "MIN_STREAM_BUFFERS", "MIN_STREAM_BUFFERS"),
+ (layer_stream, "MAX_STREAM_BUFFERS", "MAX_STREAM_BUFFERS"),
+ (layer_stream, "DEFAULT_STREAM_BUFFERS", "DEFAULT_STREAM_BUFFERS"),
+ (layer_stream, "MIN_STREAM_READ_AHEAD", "MIN_STREAM_READ_AHEAD"),
+ (layer_stream, "MAX_STREAM_READ_AHEAD", "MAX_STREAM_READ_AHEAD"),
+ (layer_stream, "DEFAULT_STREAM_READ_AHEAD", "DEFAULT_STREAM_READ_AHEAD"),
+ (layer_stream, "SUPPORTED_STREAM_TASKS", "SUPPORTED_STREAM_TASKS"),
+ (layer_stream, "ROLLOUT_STREAM_TASKS", "ROLLOUT_STREAM_TASKS"),
+ (async_disk_source, "MIN_STREAM_READ_AHEAD", "MIN_STREAM_READ_AHEAD"),
+ (async_disk_source, "MAX_STREAM_READ_AHEAD", "MAX_STREAM_READ_AHEAD"),
+ (async_disk_source, "DEFAULT_STREAM_READ_AHEAD", "DEFAULT_STREAM_READ_AHEAD"),
+ (ship_verdict, "MIN_NOISE_FLOOR_RUNS", "MIN_NOISE_FLOOR_RUNS"),
+ (ship_verdict, "MAX_NOISE_FLOOR_RUNS", "MAX_NOISE_FLOOR_RUNS"),
+ (schema, "MIN_STREAM_BUFFERS", "MIN_STREAM_BUFFERS"),
+ (schema, "MAX_STREAM_BUFFERS", "MAX_STREAM_BUFFERS"),
+ (schema, "DEFAULT_STREAM_BUFFERS", "DEFAULT_STREAM_BUFFERS"),
+ (schema, "MIN_STREAM_READ_AHEAD", "MIN_STREAM_READ_AHEAD"),
+ (schema, "MAX_STREAM_READ_AHEAD", "MAX_STREAM_READ_AHEAD"),
+ (schema, "DEFAULT_STREAM_READ_AHEAD", "DEFAULT_STREAM_READ_AHEAD"),
+ (schema, "_STREAM_SUPPORTED_TASKS", "SUPPORTED_STREAM_TASKS"),
+ (schema, "_STREAM_ROLLOUT_TASKS", "ROLLOUT_STREAM_TASKS"),
+ (schema, "MIN_NOISE_FLOOR_RUNS", "MIN_NOISE_FLOOR_RUNS"),
+ (schema, "MAX_NOISE_FLOOR_RUNS", "MAX_NOISE_FLOOR_RUNS"),
+ ],
+ ids=lambda v: v.__name__.rsplit(".", 1)[-1] if hasattr(v, "__name__") else v,
+)
+def test_bound_comes_from_the_leaf_and_is_never_redeclared(module, name, leaf_name):
+ """Re-exported, not copied: a redeclared value could drift from the schema bound.
+
+ Checked on the source, not with ``is`` alone: CPython caches small ints, so a
+ copied ``MIN_STREAM_BUFFERS = 2`` would still be identical to the leaf's object.
+ Every ``Name`` in store context counts, so tuple unpacking, ``+=``, ``for``
+ targets and the walrus operator are caught as well as a plain assignment.
+ """
+ tree = ast.parse(Path(module.__file__).read_text(encoding="utf-8"))
+ from_leaf = {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and node.module == "soup_cli.utils.config_bounds"
+ for alias in node.names
+ }
+ assigned = {
+ node.id
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)
+ }
+ assert name in from_leaf, f"{module.__name__} must import {name} from config_bounds"
+ assert name not in assigned, f"{module.__name__} redeclares {name}; re-export it instead"
+ assert getattr(module, name) is getattr(config_bounds, leaf_name)