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(local-rl): render --min-pairs and -o into the nightly-train job (#1448) (#1517)

Mohammad Hijjawi1bc20670c3c0
diff --git a/changelog.d/0.75.1/1517.fixed.md b/changelog.d/0.75.1/1517.fixed.md
new file mode 100644
index 00000000..11cd8353
--- /dev/null
+++ b/changelog.d/0.75.1/1517.fixed.md
@@ -0,0 +1 @@
+- `soup local-rl train` without `--once` renders `--min-pairs` and `-o` into the systemd `.service` and launchd `.plist` it writes, so the nightly job trains with the threshold and output directory the user asked for instead of the defaults (10 pairs, `local_rl_adapter/`). A `--min-pairs` the nightly run would refuse now exits 2 before any unit file is written (part of #1448 by @MohammadHijjawi97 in #1517).
diff --git a/docs/commands.md b/docs/commands.md
index c1ee912c..b4cf0ac0 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -347,7 +347,7 @@ soup local-rl status --db <path> Print interactions / thumbs-up / t
soup local-rl record --db <path> --prompt <q> --response <r> --thumb up|down Append thumbs record
soup local-rl harvest --db <path> -o <pairs.jsonl> Harvest DPO pairs from thumbs into JSONL
soup local-rl train --db <path> --model <id> --once [--train-method dpo|kto|orpo] [--min-pairs N] [-o <dir>] Ad-hoc DPO/KTO/ORPO train from harvested thumbs — live (v0.71.13)
-soup local-rl train --db <path> --model <id> [--scheduler-dir <dir>] [--hour H] [--minute M] Render a systemd/launchd nightly-train scaffold (no --once) (v0.71.13)
+soup local-rl train --db <path> --model <id> [--scheduler-dir <dir>] [--hour H] [--minute M] [--train-method dpo|kto|orpo] [--min-pairs N] [-o <dir>] Render a systemd/launchd nightly-train scaffold (no --once) that runs `--once` with the same flags (v0.71.13)
soup build <manifest.yaml> [--dry-run] [--output-dir <dir>] dbt-for-SFT DAG: validate + plan + live materialise (v0.69.0; live v0.71.6)
soup expect <data.jsonl> <suite.yaml> Expectations suite: PII / token-length / refusal / judge (v0.69.0)
soup data gen-magpie --base <m> --provider ollama|vllm --target N --output <jsonl> [--base-url <url>] [--quality-filter] Magpie synthetic generator — live (v0.69.0; live v0.71.6)
diff --git a/src/soup_cli/commands/local_rl.py b/src/soup_cli/commands/local_rl.py
index 13971eb1..439e2a16 100644
--- a/src/soup_cli/commands/local_rl.py
+++ b/src/soup_cli/commands/local_rl.py
@@ -222,6 +222,8 @@ def train_cmd(
train_method=train_method,
hour=hour,
minute=minute,
+ min_pairs=min_pairs,
+ output_dir=output,
)
except (TypeError, ValueError) as exc:
console.print(f"[red]{escape(str(exc))}[/]")
diff --git a/src/soup_cli/utils/local_rl.py b/src/soup_cli/utils/local_rl.py
index 8af8fad2..71a64e8e 100644
--- a/src/soup_cli/utils/local_rl.py
+++ b/src/soup_cli/utils/local_rl.py
@@ -494,6 +494,23 @@ def _default_train_fn(
pass
+def validate_min_pairs(value: object) -> int:
+ """``--min-pairs`` of the nightly train, checked the same way whether the
+ run is ad-hoc (``--once``) or rendered into a scheduler unit (#1448)."""
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise TypeError("min_pairs must be int")
+ if value < 1 or value > _MAX_MIN_PAIRS:
+ raise ValueError(f"min_pairs must be in [1, {_MAX_MIN_PAIRS}]")
+ return value
+
+
+def validate_output_dir(value: object) -> str:
+ """``--output`` of the nightly train (see :func:`validate_min_pairs`)."""
+ if not isinstance(value, str) or not value or "\x00" in value:
+ raise ValueError("output_dir must be a non-empty NUL-free string")
+ return value
+
+
def run_nightly_train(
config: LocalRLConfig,
*,
@@ -522,12 +539,8 @@ def run_nightly_train(
raise TypeError("config must be LocalRLConfig")
if not isinstance(once, bool):
raise TypeError("once must be bool")
- if isinstance(min_pairs, bool) or not isinstance(min_pairs, int):
- raise TypeError("min_pairs must be int")
- if min_pairs < 1 or min_pairs > _MAX_MIN_PAIRS:
- raise ValueError(f"min_pairs must be in [1, {_MAX_MIN_PAIRS}]")
- if not isinstance(output_dir, str) or not output_dir or "\x00" in output_dir:
- raise ValueError("output_dir must be a non-empty NUL-free string")
+ validate_min_pairs(min_pairs)
+ validate_output_dir(output_dir)
runner = train_fn if train_fn is not None else _default_train_fn
if not callable(runner):
@@ -607,6 +620,8 @@ __all__ = [
"validate_local_rl_backend",
"validate_local_rl_train_method",
"validate_db_path",
+ "validate_min_pairs",
+ "validate_output_dir",
"LocalRLConfig",
"DpoPair",
"NightlyTrainResult",
diff --git a/src/soup_cli/utils/local_rl_scheduler.py b/src/soup_cli/utils/local_rl_scheduler.py
index 8f84a48d..77ade9f5 100644
--- a/src/soup_cli/utils/local_rl_scheduler.py
+++ b/src/soup_cli/utils/local_rl_scheduler.py
@@ -24,8 +24,11 @@ import os
from typing import Dict, List
from soup_cli.utils.local_rl import (
+ MIN_PAIRS_DEFAULT,
validate_db_path,
validate_local_rl_train_method,
+ validate_min_pairs,
+ validate_output_dir,
)
from soup_cli.utils.paths import atomic_write_text
@@ -89,12 +92,24 @@ def build_train_argv(
db_path: str,
model: str,
train_method: str,
+ min_pairs: int = MIN_PAIRS_DEFAULT,
+ output_dir: str = "local_rl_adapter",
) -> List[str]:
- """Return the argv list the scheduler invokes (no shell)."""
+ """Return the argv list the scheduler invokes (no shell).
+
+ ``min_pairs`` and ``output_dir`` are always rendered, so the scheduled run
+ does what ``soup local-rl train --once`` with the same flags does (#1448).
+ They are validated here with the runner's own checks, so a value the
+ nightly run would refuse is refused before the unit is written.
+ """
soup_python = _validate_soup_python(soup_python)
validate_db_path(db_path)
model = _validate_model(model)
method = validate_local_rl_train_method(train_method)
+ min_pairs = validate_min_pairs(min_pairs)
+ output_dir = validate_output_dir(output_dir)
+ if "\n" in output_dir or "\r" in output_dir:
+ raise ValueError("output_dir must not contain newline / carriage return")
return [
soup_python,
"-m",
@@ -108,6 +123,10 @@ def build_train_argv(
model,
"--train-method",
method,
+ "--min-pairs",
+ str(min_pairs),
+ "--output",
+ output_dir,
]
@@ -131,6 +150,8 @@ def render_systemd_service(
db_path: str,
model: str,
train_method: str,
+ min_pairs: int = MIN_PAIRS_DEFAULT,
+ output_dir: str = "local_rl_adapter",
) -> str:
"""Render the systemd-user ``.service`` unit."""
argv = build_train_argv(
@@ -138,6 +159,8 @@ def render_systemd_service(
db_path=db_path,
model=model,
train_method=train_method,
+ min_pairs=min_pairs,
+ output_dir=output_dir,
)
exec_start = " ".join(_systemd_quote(a) for a in argv)
return (
@@ -175,6 +198,8 @@ def render_launchd_plist(
train_method: str,
hour: int = 3,
minute: int = 0,
+ min_pairs: int = MIN_PAIRS_DEFAULT,
+ output_dir: str = "local_rl_adapter",
) -> str:
"""Render a macOS launchd ``.plist`` (daily ``StartCalendarInterval``)."""
from xml.sax.saxutils import escape as _xml_escape
@@ -185,6 +210,8 @@ def render_launchd_plist(
db_path=db_path,
model=model,
train_method=train_method,
+ min_pairs=min_pairs,
+ output_dir=output_dir,
)
args_xml = "\n".join(
f" <string>{_xml_escape(a)}</string>" for a in argv
@@ -225,6 +252,8 @@ def write_scheduler_files(
train_method: str,
hour: int = 3,
minute: int = 0,
+ min_pairs: int = MIN_PAIRS_DEFAULT,
+ output_dir: str = "local_rl_adapter",
) -> Dict[str, str]:
"""Render both the systemd units and the launchd plist into ``target_dir``.
@@ -234,13 +263,14 @@ def write_scheduler_files(
"""
if not isinstance(target_dir, str) or not target_dir or "\x00" in target_dir:
raise ValueError("target_dir must be a non-empty NUL-free string")
- os.makedirs(target_dir, exist_ok=True)
service = render_systemd_service(
soup_python=soup_python,
db_path=db_path,
model=model,
train_method=train_method,
+ min_pairs=min_pairs,
+ output_dir=output_dir,
)
timer = render_systemd_timer(hour=hour, minute=minute)
plist = render_launchd_plist(
@@ -250,8 +280,12 @@ def write_scheduler_files(
train_method=train_method,
hour=hour,
minute=minute,
+ min_pairs=min_pairs,
+ output_dir=output_dir,
)
+ # Render (and so validate) everything before creating the directory.
+ os.makedirs(target_dir, exist_ok=True)
written: Dict[str, str] = {}
for name, body in (
(SYSTEMD_SERVICE_NAME, service),
diff --git a/tests/test_issue1448_local_rl_schedule_args.py b/tests/test_issue1448_local_rl_schedule_args.py
new file mode 100644
index 00000000..5fd67ab5
--- /dev/null
+++ b/tests/test_issue1448_local_rl_schedule_args.py
@@ -0,0 +1,176 @@
+"""#1448 — ``soup local-rl train`` (scheduled mode) drops ``--min-pairs`` and ``-o``.
+
+Without ``--once``, ``soup local-rl train`` renders a systemd ``.service`` /
+``.timer`` and a launchd ``.plist`` that run ``soup local-rl train --once``
+every night. The rendered command carried ``--db``, ``--model`` and
+``--train-method`` only, so the nightly job trained on as few as 10 pairs into
+``local_rl_adapter/`` whatever ``--min-pairs`` and ``--output`` the user had
+asked for, and printed nothing about it. ``--once`` already passed both.
+
+This file pins:
+
+* the rendered ``.service`` and ``.plist`` carry both values;
+* the rendered command, parsed by the real CLI, reaches ``run_nightly_train``
+ with the same ``min_pairs`` and ``output_dir`` that ``--once`` would pass;
+* a ``--min-pairs`` the nightly run would refuse is refused when the scaffold
+ is rendered, before any unit file is written;
+* the defaults are rendered explicitly, so the nightly job matches ``--once``.
+"""
+
+from __future__ import annotations
+
+import os
+import plistlib
+import shlex
+import sys
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils.local_rl import init_local_rl_db
+from soup_cli.utils.local_rl_scheduler import (
+ LAUNCHD_PLIST_NAME,
+ SYSTEMD_SERVICE_NAME,
+ build_train_argv,
+)
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+
+def _schedule(*extra: str) -> "object":
+ return runner.invoke(
+ app,
+ [
+ "local-rl", "train",
+ "--db", "local_rl.db",
+ "--model", "org/base",
+ "--scheduler-dir", "sched",
+ *extra,
+ ],
+ )
+
+
+def _service_argv(tmp_path) -> list:
+ text = (tmp_path / "sched" / SYSTEMD_SERVICE_NAME).read_text(encoding="utf-8")
+ line = next(ln for ln in text.splitlines() if ln.startswith("ExecStart="))
+ return shlex.split(line[len("ExecStart="):], posix=True)
+
+
+def _plist_argv(tmp_path) -> list:
+ with open(tmp_path / "sched" / LAUNCHD_PLIST_NAME, "rb") as fh:
+ return list(plistlib.load(fh)["ProgramArguments"])
+
+
+def _value_after(argv: list, flag: str) -> str:
+ assert flag in argv, (flag, argv)
+ return argv[argv.index(flag) + 1]
+
+
+def workdir(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ init_local_rl_db("local_rl.db")
+ return tmp_path
+
+
+class TestTheRenderedJobCarriesTheOptions:
+ def test_systemd_service(self, workdir):
+ result = _schedule("--min-pairs", "200", "-o", "adapters/nightly")
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ argv = _service_argv(workdir)
+ assert _value_after(argv, "--min-pairs") == "200"
+ assert _value_after(argv, "--output") == "adapters/nightly"
+
+ def test_launchd_plist(self, workdir):
+ result = _schedule("--min-pairs", "200", "-o", "adapters/nightly")
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ argv = _plist_argv(workdir)
+ assert _value_after(argv, "--min-pairs") == "200"
+ assert _value_after(argv, "--output") == "adapters/nightly"
+
+ def test_an_output_path_with_a_space_survives_systemd_quoting(self, workdir):
+ result = _schedule("-o", "my adapters/nightly")
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ assert _value_after(_service_argv(workdir), "--output") == "my adapters/nightly"
+ assert _value_after(_plist_argv(workdir), "--output") == "my adapters/nightly"
+
+ def test_the_defaults_are_rendered_too(self, workdir):
+ """The nightly job must do what ``--once`` with the same flags does,
+ including when the user left both at their defaults."""
+ result = _schedule()
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ for argv in (_service_argv(workdir), _plist_argv(workdir)):
+ assert _value_after(argv, "--min-pairs") == "10"
+ assert _value_after(argv, "--output") == "local_rl_adapter"
+
+
+def test_the_rendered_command_reaches_the_runner_with_the_same_values(
+ workdir, monkeypatch
+):
+ """Run the scheduled command through the real CLI and record what the
+ runner receives: a flag rendered under the wrong name would fail here."""
+ import soup_cli.commands.local_rl as local_rl_cmd
+ from soup_cli.utils.local_rl import NightlyTrainResult
+
+ seen = {}
+
+ def fake_run(cfg, *, once, min_pairs, output_dir):
+ seen.update(once=once, min_pairs=min_pairs, output_dir=output_dir)
+ return NightlyTrainResult(
+ status="skipped_insufficient_pairs", num_pairs=0, output_dir=None,
+ reason="test",
+ )
+
+ argv = build_train_argv(
+ soup_python=sys.executable,
+ db_path="local_rl.db",
+ model="org/base",
+ train_method="kto",
+ min_pairs=200,
+ output_dir="adapters/nightly",
+ )
+ assert argv[1:3] == ["-m", "soup_cli.cli"]
+ monkeypatch.setattr(local_rl_cmd, "run_nightly_train", fake_run)
+
+ result = runner.invoke(app, argv[3:])
+
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert seen == {"once": True, "min_pairs": 200, "output_dir": "adapters/nightly"}
+
+
[email protected]("min_pairs", ["0", "-5", "1000001"])
+def test_a_min_pairs_the_nightly_run_would_refuse_is_refused_now(workdir, min_pairs):
+ """Rendering it would install a job that fails every night."""
+ result = _schedule("--min-pairs", min_pairs)
+
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "min_pairs must be in [1, 1000000]" in " ".join(strip_ansi(result.output).split())
+ assert not os.path.exists(workdir / "sched")
+
+
+ "kwargs, error",
+ [
+ ({"min_pairs": True}, TypeError),
+ ({"min_pairs": 2.5}, TypeError),
+ ({"min_pairs": 0}, ValueError),
+ ({"output_dir": ""}, ValueError),
+ ({"output_dir": "a\x00b"}, ValueError),
+ ({"output_dir": "a\nExecStartPre=/bin/sh"}, ValueError),
+ ],
+)
+def test_build_train_argv_validates_the_new_arguments(workdir, kwargs, error):
+ with pytest.raises(error):
+ build_train_argv(
+ soup_python=sys.executable,
+ db_path="local_rl.db",
+ model="org/base",
+ train_method="dpo",
+ **kwargs,
+ )