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(train): --find-lr refuses instead of writing a curve nobody measured (#1203) (#1334)

UmranPros636d3efb4532
diff --git a/changelog.d/0.75.1/1334.fixed.md b/changelog.d/0.75.1/1334.fixed.md
new file mode 100644
index 00000000..2453d506
--- /dev/null
+++ b/changelog.d/0.75.1/1334.fixed.md
@@ -0,0 +1 @@
+- **`soup train --find-lr` refuses instead of writing a synthetic LR curve when the live sweep cannot run (#1203 reported by @mohdUwaish59, fixed by @umran666 in #1334).** When the config did not load (a YAML syntax error) or the sweep could not run (a base model id that does not exist, a model or dataset that cannot be loaded, or an install without `torch`), the command printed one yellow line, wrote a report whose `recommended_lr` came from the LR schedule alone, and exited 0, so two different nonexistent ids reported the identical number. It now names the cause, exits 1 and writes no report. The refusals added in #1189, for fewer than 4 rows or a loss that turns non-finite before 4 steps have run, are unchanged.
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 2d39be3a..307586cf 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -643,7 +643,7 @@ soup train --config soup.yaml \
The report contains the geometric `lrs[]`, raw + EMA-smoothed `losses[]`, the recommended LR (steepest negative gradient before divergence), the LR with min loss, and the divergence point if any.
-The sweep takes one training row per step. With fewer rows than `--find-lr-steps`, it runs one step per row over the same `--find-lr-start` → `--find-lr-end` range and prints a line saying so. The recommendation needs at least 4 points, so `--find-lr-steps` must be at least 4 and a training set with fewer than 4 rows is refused before the model loads. If the loss turns non-finite partway through, the report covers the steps before it; if that leaves fewer than 4, the command says where it diverged instead of writing a report.
+The sweep takes one training row per step. With fewer rows than `--find-lr-steps`, it runs one step per row over the same `--find-lr-start` → `--find-lr-end` range and prints a line saying so. The recommendation needs at least 4 points, so `--find-lr-steps` must be at least 4 and a training set with fewer than 4 rows is refused before the model loads. If the loss turns non-finite partway through, the report covers the steps before it; if that leaves fewer than 4, the command says where it diverged instead of writing a report. If the sweep cannot run at all (the config does not load, the model or dataset cannot be loaded, or `torch` is not installed), the command names the cause, exits 1 and writes no report.
### Auto Warmup Schedule
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 36043c88..a06c07fb 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -691,6 +691,7 @@ def train(
# --- LR range finder fast path ---
if find_lr:
from soup_cli.utils.lr_finder import (
+ LrSweepUnavailableError,
SweepTooShortError,
compute_lr_schedule,
save_lr_finder_report,
@@ -705,16 +706,15 @@ def train(
except ValueError as exc:
console.print(f"[red]Invalid --find-lr range:[/] {exc}")
raise typer.Exit(1) from exc
- # v0.33.0 #56: live LR-sweep training loop. Falls back to a
- # synthetic curve only when the real loop cannot run (no torch /
- # config load failure) so users still get a parseable report.
+ # v0.33.0 #56: live LR-sweep training loop. #1203: when it cannot run, the
+ # command refuses rather than writing a curve nobody measured.
# #1189: the sweep returns the LRs it actually ran, which can be fewer than
# --find-lr-steps (a short dataset, or a loss that went non-finite).
try:
- lrs, losses_for_report = _run_live_lr_sweep_or_synth(
+ lrs, losses_for_report = _run_live_lr_sweep(
config_path, schedule,
)
- except SweepTooShortError as exc:
+ except (SweepTooShortError, LrSweepUnavailableError) as exc:
console.print(f"[red]{markup_escape(str(exc))}[/]")
raise typer.Exit(1) from exc
try:
@@ -2322,55 +2322,39 @@ def _resolve_resume_or_exit(resume: str, cfg: "SoupConfig") -> str | None:
return resume_from
-def _run_live_lr_sweep_or_synth(
+def _run_live_lr_sweep(
config_path: str, schedule: list[float],
) -> tuple[list[float], list[float]]:
- """v0.33.0 #56 — try to run an in-process LR sweep; fall back to a
- synthetic curve when prerequisites are missing.
+ """v0.33.0 #56 — run the in-process LR sweep over the config's own model.
Returns ``(lrs, losses)`` of equal length.
- Falls back when:
- - torch / transformers / datasets are not importable
- - config load fails
- - dataset cannot be tokenized into a small in-memory loader
- The fallback curve descends 60% then diverges so the recommended-LR
- extraction in :func:`find_optimal_lr` still produces sensible output.
- A ``SweepTooShortError`` is a refusal and is never turned into a curve.
+ #1203: every reason the sweep cannot run is a refusal.
+ :class:`LrSweepUnavailableError` covers a config that will not load and a
+ model or dataset that cannot be swept; :class:`SweepTooShortError` covers
+ fewer than ``MIN_NUM_STEPS`` rows, and a loss that is non-finite from the
+ first step or turns non-finite before 4 steps have run.
+ This used to answer all of them with a synthetic curve shaped by the LR
+ schedule alone, so a base model that does not exist exited 0 with a
+ ``recommended_lr`` that described no model and no data.
"""
- from soup_cli.utils.lr_finder import SweepTooShortError
+ from soup_cli.utils.lr_finder import LrSweepUnavailableError, SweepTooShortError
try:
cfg = load_config(config_path)
- except Exception as exc: # noqa: BLE001 — fall back rather than abort
- console.print(
- f"[yellow]--find-lr: config load failed ({exc}); "
- f"writing synthetic curve.[/]"
- )
- return schedule, _synth_lr_curve(len(schedule))
+ except Exception as exc: # noqa: BLE001 — one refusal line, not a traceback
+ raise LrSweepUnavailableError(
+ f"--find-lr: config load failed ({exc}); no LR report was written."
+ ) from exc
try:
return _live_lr_sweep_from_config(cfg, schedule)
except SweepTooShortError:
raise
- except Exception as exc: # noqa: BLE001 — informative fallback
- console.print(
- f"[yellow]--find-lr: live sweep unavailable ({exc}); "
- f"writing synthetic curve.[/]"
- )
- return schedule, _synth_lr_curve(len(schedule))
-
-
-def _synth_lr_curve(n: int) -> list[float]:
- descend_until = max(1, int(n * 0.6))
- out: list[float] = []
- for i in range(n):
- if i < descend_until:
- out.append(3.0 - 2.0 * (i / descend_until))
- else:
- tail = (i - descend_until) / max(1, n - descend_until)
- out.append(1.0 + 8.0 * tail * tail)
- return out
+ except Exception as exc: # noqa: BLE001 — the cause is the useful half
+ raise LrSweepUnavailableError(
+ f"--find-lr: live sweep unavailable ({exc}); no LR report was written."
+ ) from exc
def _lr_finder_dataset_path(train) -> str:
@@ -2391,7 +2375,7 @@ def _live_lr_sweep_from_config(
the train dataset, then call :func:`run_lr_sweep`. Returns the
``(lrs, losses)`` the sweep actually ran."""
# v0.40.1 Part C / G12 — fix broken `load_local` import that previously
- # always fell through to the synthetic curve. The actual exported symbol
+ # made the live sweep fail every time. The actual exported symbol
# is ``load_raw_data`` (path-only loader) — we use that.
from pathlib import Path as _Path
diff --git a/src/soup_cli/utils/lr_finder.py b/src/soup_cli/utils/lr_finder.py
index 003ff3b3..a8877ba1 100644
--- a/src/soup_cli/utils/lr_finder.py
+++ b/src/soup_cli/utils/lr_finder.py
@@ -29,6 +29,17 @@ class SweepTooShortError(ValueError):
A refusal for the user, never a reason to fall back to a synthetic curve.
"""
+
+class LrSweepUnavailableError(RuntimeError):
+ """The live sweep cannot run at all (#1203).
+
+ Raised instead of answering with a synthetic curve, whose shape depends only
+ on the LR schedule: a base model that does not exist, or a config that will
+ not parse, used to write a report with a confident ``recommended_lr`` and
+ exit 0.
+ """
+
+
# Bounds prevent runaway sweeps and silly inputs.
MAX_NUM_STEPS = 10_000
# find_optimal_lr needs 4 (lr, loss) pairs; a shorter sweep can never produce a report.
diff --git a/tests/test_issue1189_find_lr_small_dataset.py b/tests/test_issue1189_find_lr_small_dataset.py
index 11598597..6c892bbf 100644
--- a/tests/test_issue1189_find_lr_small_dataset.py
+++ b/tests/test_issue1189_find_lr_small_dataset.py
@@ -120,9 +120,11 @@ def test_fewer_than_four_rows_is_refused_before_the_model_loads(find_lr, rows):
count = f"{rows} row" + ("" if rows == 1 else "s")
assert f"has {count}," in text and "--find-lr-steps 5" in text, text
assert loads == 0
- # Not swallowed by the synthetic-curve fallback.
+ # Not swallowed by either refusal: #1203's "live sweep unavailable" and the
+ # deleted synthetic curve would both replace this message (#1203 review).
assert report is None
assert "synthetic" not in text
+ assert "live sweep unavailable" not in text, text
def test_too_few_steps_is_rejected_before_the_model_loads(find_lr):
diff --git a/tests/test_issue1203_find_lr_no_synthetic_curve.py b/tests/test_issue1203_find_lr_no_synthetic_curve.py
new file mode 100644
index 00000000..997967f7
--- /dev/null
+++ b/tests/test_issue1203_find_lr_no_synthetic_curve.py
@@ -0,0 +1,144 @@
+"""#1203 — `soup train --find-lr` invented a curve when the sweep could not run.
+
+The fallback answered any failure — a base model that does not exist, a config
+that will not parse — with a curve shaped by the LR schedule alone, then wrote a
+report with a confident `recommended_lr` and exited 0. Two different nonexistent
+model ids therefore reported the identical number. Both now refuse with exit 1
+and write no report, while a sweep that can run still writes its report.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from typer.testing import CliRunner
+
+from tests.conftest import strip_ansi
+
+pytest.importorskip("torch")
+
+START, END = 1e-7, 1e-1
+# The words transformers uses for an id that resolves to nothing (#1189's repro).
+MISSING = (
+ "soup-audit-1189/this-model-does-not-exist is not a local folder and is not "
+ "a valid model identifier listed on 'https://huggingface.co/models'"
+)
+# Descends, then climbs: a curve find_optimal_lr can read.
+CURVE = [3.0, 2.6, 2.2, 1.9, 1.7, 1.8, 2.4, 3.5, 5.0, 8.0]
+
+
+def find_lr(tmp_path, monkeypatch):
+ """Run `soup train --find-lr` on an 8-row dataset.
+
+ `model_error` makes the model load raise that error, `scripted` swaps in a
+ model that walks `CURVE`, and `broken_yaml` writes an unparseable config.
+ Returns the normalised output, the exit code and the report (or None).
+ """
+ monkeypatch.chdir(tmp_path)
+
+ def run(model_error=None, scripted=False, broken_yaml=False, output="lr_finder.json"):
+ import torch
+ import transformers
+
+ class FakeTokenizer:
+ pad_token = None
+ eos_token = "</s>"
+
+ def __call__(self, text, **kwargs):
+ ids = torch.ones((1, 4), dtype=torch.long)
+ return {"input_ids": ids, "attention_mask": torch.ones_like(ids)}
+
+ class ScriptedModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(1))
+ self.step = 0
+
+ def forward(self, **batch):
+ value = CURVE[self.step % len(CURVE)]
+ self.step += 1
+ return {"loss": self.weight.sum() * 0 + value}
+
+ monkeypatch.setattr(
+ transformers.AutoTokenizer, "from_pretrained", lambda *a, **k: FakeTokenizer()
+ )
+ if model_error is not None:
+ def unreachable(*args, **kwargs):
+ raise model_error
+
+ monkeypatch.setattr(
+ transformers.AutoModelForCausalLM, "from_pretrained", unreachable
+ )
+ elif scripted:
+ monkeypatch.setattr(
+ transformers.AutoModelForCausalLM,
+ "from_pretrained",
+ lambda *a, **k: ScriptedModel(),
+ )
+
+ with open("train.jsonl", "w", encoding="utf-8") as handle:
+ for index in range(8):
+ handle.write(json.dumps({"text": f"row {index}"}) + "\n")
+ with open("soup.yaml", "w", encoding="utf-8") as handle:
+ handle.write(
+ "base: fake-org/fake-model\ndata: [unclosed\n"
+ if broken_yaml
+ else f"base: {MISSING.split(' is not ')[0]}\ntask: sft\n"
+ "data:\n train: ./train.jsonl\n format: plaintext\n max_length: 64\n"
+ "output: ./output\n"
+ )
+
+ from soup_cli.cli import app
+
+ result = CliRunner().invoke(app, [
+ "train", "--config", "soup.yaml", "--find-lr",
+ "--find-lr-start", str(START), "--find-lr-end", str(END),
+ "--find-lr-steps", "8", "--find-lr-output", output,
+ ])
+ text = " ".join(strip_ansi(result.output).split())
+ path = tmp_path / output
+ report = json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
+ return text, result.exit_code, report
+
+ return run
+
+
+def test_unreachable_base_refuses_and_writes_no_report(find_lr):
+ text, code, report = find_lr(model_error=OSError(MISSING))
+ assert code == 1, text
+ assert report is None, text
+ assert "live sweep unavailable" in text, text
+ assert "not a valid model identifier" in text, text
+ assert "LR finder report written" not in text
+
+
+def test_broken_yaml_refuses_with_the_loader_message(find_lr):
+ text, code, report = find_lr(broken_yaml=True)
+ assert code == 1, text
+ assert report is None, text
+ assert "config load failed" in text, text
+ # The loader's own words, not just our prefix: Rich used to read
+ # "[unclosed ... ']" in the message as a markup tag and drop it (#1203).
+ assert "while parsing a flow sequence" in text, text
+ assert "data: [unclosed" in text, text
+ assert "LR finder report written" not in text
+
+
+def test_two_unreachable_bases_both_refuse_instead_of_sharing_a_curve(find_lr):
+ # The reported symptom: two different missing ids returned one identical
+ # fabricated curve and the identical recommended_lr.
+ first = find_lr(model_error=OSError(MISSING))
+ second = find_lr(model_error=OSError("another-org/also-missing-model is not a local folder"))
+ assert first[1] == second[1] == 1, (first[0], second[0])
+ assert first[2] is None and second[2] is None, (first[0], second[0])
+
+
+def test_a_sweep_that_can_run_still_writes_its_report(find_lr):
+ # Control: the refusal must not swallow a sweep that actually ran.
+ text, code, report = find_lr(scripted=True)
+ assert code == 0, text
+ assert report is not None, text
+ assert len(report["lrs"]) == len(report["losses"]) == 8, text
+ assert report["recommended_lr"] > 0