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: run auto-eval after training (#1546)

Suyog Vermaca7b35f21348
diff --git a/changelog.d/0.75.1/1546.fixed.md b/changelog.d/0.75.1/1546.fixed.md
new file mode 100644
index 00000000..c07be130
--- /dev/null
+++ b/changelog.d/0.75.1/1546.fixed.md
@@ -0,0 +1 @@
+- `eval.auto_eval: true` now runs the configured `eval.benchmarks` and `eval.custom_tasks` after `soup train` finishes; before, no trainer handed the evaluation config to the training callback, so nothing ran (#1487 by @commit-msuyog in #1546).
\ No newline at end of file
diff --git a/docs/evaluation.md b/docs/evaluation.md
index f9630ff6..43148700 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -847,6 +847,9 @@ baseline scorer stamp covers the bundled suites only and will not warn: re-measu
baselines, or compare new runs only with runs made on this version.
### Auto-Eval Config (soup.yaml)
+```bash
+pip install "soup-cli[eval]"
+```
```yaml
eval:
@@ -858,6 +861,15 @@ eval:
provider: openai
```
+When `eval.auto_eval: true`, Soup runs the configured evaluation once after `soup train` finishes and the trained model/adapter has been saved. The evaluation uses the output artifact produced by that training run.
+
+- `benchmarks` runs the configured `lm-eval-harness` benchmarks. Install the benchmark dependencies required by your environment before enabling them.
+- `custom_tasks` runs the configured custom evaluation tasks against the trained model.
+- `judge` is not part of auto-evaluation; configure and run judge evaluation separately.
+- Auto-evaluation keeps `trust_remote_code` disabled.
+- If auto-evaluation fails, Soup reports the failure but does not fail an otherwise successful training run.
+- Auto-evaluation can take a significant amount of time. For example, MMLU evaluates multiple subtasks.
+
## Tunability Probe (`soup tunability`)
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 1e2535bb..1e413a4e 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import contextlib
import json
+import logging
import os
import re
from pathlib import Path
@@ -28,6 +29,7 @@ if TYPE_CHECKING: # pragma: no cover - type hints only, no runtime import
from soup_cli.config.schema import SoupConfig
from soup_cli.utils.energy import EnergyMeasurement
+logger = logging.getLogger(__name__)
console = Console()
# Optimizers the analytical hardware-fit predictor understands (mirror of
@@ -87,6 +89,61 @@ def _format_training_complete_loss(result: dict) -> str:
return f"Loss: [bold]{result['initial_loss']:.4f} -> {result['final_loss']:.4f}[/]{label}"
+def _run_auto_eval_after_training(eval_config, output_dir: str, run_id: str) -> None:
+ """Run configured evaluation once after the trained model is saved."""
+ if not eval_config or not getattr(eval_config, "auto_eval", False):
+ return
+ if not output_dir or not _should_run_diagnose_gate_on_rank():
+ return
+
+ console.print("\n[bold blue]Running auto-eval...[/]")
+
+ benchmarks = getattr(eval_config, "benchmarks", None) or []
+ custom_tasks = getattr(eval_config, "custom_tasks", None)
+
+ if benchmarks:
+ try:
+ from soup_cli.commands.eval import benchmark
+
+ benchmark(
+ model=output_dir,
+ benchmarks=",".join(benchmarks),
+ num_fewshot=None,
+ batch_size=8,
+ run_id=run_id,
+ device=None,
+ trust_remote_code=False,
+ )
+ except typer.Exit:
+ logger.debug("Auto-eval benchmark skipped", exc_info=True)
+ console.print(
+ "[yellow]Auto-eval benchmark skipped (see the message above)[/]"
+ )
+ except Exception as exc:
+ logger.exception("Auto-eval benchmark failed")
+ console.print(
+ f"[yellow]Auto-eval benchmark failed: {markup_escape(str(exc))}[/]"
+ )
+
+ if custom_tasks:
+ try:
+ from soup_cli.commands.eval import custom
+
+ custom(
+ tasks=custom_tasks,
+ model=output_dir,
+ run_id=run_id,
+ attach_to_registry=None,
+ output=None,
+ trust_remote_code=False,
+ )
+ except Exception as exc:
+ logger.exception("Auto-eval custom failed")
+ console.print(
+ f"[yellow]Auto-eval custom failed: {markup_escape(str(exc))}[/]"
+ )
+
+
def _train_sample_count(dcfg, dataset) -> int:
"""Rows training will actually consume (#1054).
@@ -1775,6 +1832,12 @@ def train(
duration_secs=result["duration_secs"],
output_dir=result["output_dir"],
)
+
+ _run_auto_eval_after_training(
+ cfg.eval,
+ result["output_dir"],
+ run_id,
+ )
except Exception as exc:
tracker.fail_run(run_id, error=_describe_exception_for_tracker(exc))
# v0.34.0 Part D — write a .crash bundle next to the run for triage.
diff --git a/src/soup_cli/monitoring/callback.py b/src/soup_cli/monitoring/callback.py
index c4b57a3f..f4ed73c5 100644
--- a/src/soup_cli/monitoring/callback.py
+++ b/src/soup_cli/monitoring/callback.py
@@ -68,6 +68,34 @@ def soup_callback_kwargs(
return kwargs
+def build_soup_trainer_callback(
+ display: TrainingDisplay,
+ *,
+ config: Any,
+ tracker: Optional[object] = None,
+ run_id: str = "",
+ batch_size: Optional[int] = None,
+ output_dir: Optional[str] = None,
+) -> Any:
+ """Build a trainer callback with shared training and evaluation config."""
+ training_config = config.training
+ callback_cls = globals().get("SoupTrainerCallback")
+ if callback_cls is None:
+ callback_cls = __getattr__("SoupTrainerCallback")
+
+ return callback_cls(
+ display=display,
+ tracker=tracker,
+ run_id=run_id,
+ eval_config=getattr(config, "eval", None),
+ **soup_callback_kwargs(
+ training_config,
+ batch_size=batch_size,
+ output_dir=output_dir,
+ ),
+ )
+
+
def _get_trainer_callback_base():
"""Lazy-resolve ``transformers.TrainerCallback``."""
try:
@@ -569,58 +597,6 @@ class _SoupTrainerCallback_body: # noqa: N801
control: TrainerControl, **kwargs,
):
self.display.stop()
- self._run_auto_eval()
-
- def _run_auto_eval(self) -> None:
- """Run automatic evaluation if configured."""
- if self.eval_config is None:
- return
- if not getattr(self.eval_config, "auto_eval", False):
- return
- if not self.output_dir:
- return
-
- from rich.console import Console
-
- console = Console()
- console.print("\n[bold blue]Running auto-eval...[/]")
-
- benchmarks = getattr(self.eval_config, "benchmarks", None) or []
- custom_tasks = getattr(self.eval_config, "custom_tasks", None)
-
- # Run standard benchmarks
- if benchmarks:
- try:
- from soup_cli.commands.eval import benchmark
- benchmark(
- model=self.output_dir,
- benchmarks=",".join(benchmarks),
- num_fewshot=None,
- batch_size=8,
- run_id=self.run_id,
- device=None,
- trust_remote_code=False,
- )
- except Exception as exc:
- logger.exception("Auto-eval benchmark failed")
- console.print(f"[yellow]Auto-eval benchmark failed: {exc}[/]")
-
- # Run custom eval
- if custom_tasks:
- try:
- from soup_cli.commands.eval import custom
- # #752 — pass every typer parameter; see commands/eval.py.
- custom(
- tasks=custom_tasks,
- model=self.output_dir,
- run_id=self.run_id,
- attach_to_registry=None,
- output=None,
- trust_remote_code=False,
- )
- except Exception as exc:
- logger.exception("Auto-eval custom failed")
- console.print(f"[yellow]Auto-eval custom failed: {exc}[/]")
# ------------------------------------------------------------------
# v0.33.0 #57 — spike recovery hint
diff --git a/src/soup_cli/trainer/asr.py b/src/soup_cli/trainer/asr.py
index ec26254f..e64e206b 100644
--- a/src/soup_cli/trainer/asr.py
+++ b/src/soup_cli/trainer/asr.py
@@ -417,23 +417,16 @@ class AsrTrainerWrapper:
)
start = time.time()
if display is not None:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
+ batch_size=self._batch_size,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ output_dir=self._output_dir,
)
)
_asr_args = getattr(self.trainer, "args", None)
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index ed436fed..93aba9d4 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -384,23 +384,16 @@ class BCOTrainerWrapper:
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/classifier.py b/src/soup_cli/trainer/classifier.py
index ab192090..c6277070 100644
--- a/src/soup_cli/trainer/classifier.py
+++ b/src/soup_cli/trainer/classifier.py
@@ -462,23 +462,16 @@ class ClassifierTrainerWrapper:
)
start = time.time()
if display is not None:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
align_trainable_dtype_for_fp16(
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index 6194942d..a2fcd846 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -1166,23 +1166,16 @@ class DistillTrainerWrapper:
)
start = time.time()
if display is not None:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
align_trainable_dtype_for_fp16(
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index 62b0e872..31e30c28 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -399,23 +399,15 @@ class DPOTrainerWrapper(StreamingSetupMixin):
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index 845b568a..b159d3f2 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -389,23 +389,16 @@ class EmbeddingTrainerWrapper:
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index 6a62fb63..c759dcc1 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -759,23 +759,16 @@ class GRPOTrainerWrapper:
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
+ batch_size=self._batch_size,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index d955ba44..76f0e0ae 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -330,23 +330,16 @@ class IPOTrainerWrapper:
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index b4f4acbf..8fc3989f 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -370,23 +370,15 @@ class KTOTrainerWrapper(StreamingSetupMixin):
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/online_dpo.py b/src/soup_cli/trainer/online_dpo.py
index 073f76e0..37b13eb4 100644
--- a/src/soup_cli/trainer/online_dpo.py
+++ b/src/soup_cli/trainer/online_dpo.py
@@ -519,23 +519,15 @@ class OnlineDPOTrainerWrapper:
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index 891a8b5d..d72fa35c 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -387,23 +387,15 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.py
index 28b1e85d..f8e4c987 100644
--- a/src/soup_cli/trainer/ppo.py
+++ b/src/soup_cli/trainer/ppo.py
@@ -814,23 +814,15 @@ class PPOTrainerWrapper:
self.trainer.dataset = self._trl_train_ds
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index 10f7e8cd..d08be72c 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -487,23 +487,15 @@ class PretrainTrainerWrapper:
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index 0005f828..98489a89 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -316,23 +316,15 @@ class RewardModelTrainerWrapper:
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index cbb3f0dd..f0f4675f 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -2208,24 +2208,15 @@ class SFTTrainerWrapper(StreamingSetupMixin):
# Add callback for live display and experiment tracking
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
- tcfg_local = self.config.training
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=tcfg_local.eval_gate,
- **soup_callback_kwargs(
- tcfg_local,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index bec504d7..8731f599 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -411,23 +411,15 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
start = time.time()
if display:
- from soup_cli.monitoring.callback import (
- SoupTrainerCallback,
- soup_callback_kwargs,
- )
-
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
self.trainer.add_callback(
- SoupTrainerCallback(
+ build_soup_trainer_callback(
display,
+ config=self.config,
tracker=tracker,
run_id=run_id,
- eval_gate_config=self.config.training.eval_gate,
- **soup_callback_kwargs(
- self.config.training,
- batch_size=self._batch_size,
- output_dir=self._output_dir,
- include_eval_gate=False,
- ),
+ batch_size=self._batch_size,
+ output_dir=self._output_dir,
)
)
diff --git a/tests/test_code_review_critical.py b/tests/test_code_review_critical.py
index 095b243a..6849fb07 100644
--- a/tests/test_code_review_critical.py
+++ b/tests/test_code_review_critical.py
@@ -9,11 +9,9 @@ from __future__ import annotations
import ast
import inspect
-from pathlib import Path
import pytest
-import soup_cli
from soup_cli.config.loader import load_config_from_string
# ─────────────────────────── CRITICAL 1: RLVR verifiable rewards ───────────────
@@ -354,18 +352,3 @@ def test_no_eval_gate_config_never_halts(tmp_path, monkeypatch):
cb.on_train_begin(args, state, control)
cb.on_epoch_end(args, state, control)
assert control.should_training_stop is False
-
-
-_TRAINERS_WITH_CALLBACK = [
- "sft", "dpo", "grpo", "ppo", "kto", "orpo", "simpo", "ipo",
- "bco", "pretrain", "reward_model", "distill", "embedding", "classifier",
-]
-
-
[email protected]("name", _TRAINERS_WITH_CALLBACK)
-def test_trainer_wires_eval_gate_config(name):
- """Every trainer that builds SoupTrainerCallback must pass eval_gate_config."""
- src = (Path(soup_cli.__file__).parent / "trainer" / f"{name}.py").read_text(
- encoding="utf-8"
- )
- assert "eval_gate_config=" in src, f"{name}.py does not wire eval_gate_config"
diff --git a/tests/test_eval_platform.py b/tests/test_eval_platform.py
index d98571c2..17092295 100644
--- a/tests/test_eval_platform.py
+++ b/tests/test_eval_platform.py
@@ -2,6 +2,7 @@
import json
import re
+from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
@@ -927,45 +928,218 @@ class TestEvalConfig:
# ═══════════════════════════════════════════════════════════
-# Callback — Auto-eval hook
+# Auto-eval after training
# ═══════════════════════════════════════════════════════════
+def _tiny_llama_dir(root: Path) -> str:
+ import torch
+ from safetensors.torch import save_file
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+ torch.manual_seed(7)
+ config = LlamaConfig(
+ vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=2,
+ num_attention_heads=4, num_key_value_heads=2, tie_word_embeddings=True,
+ max_position_embeddings=128,
+ )
+ model = LlamaForCausalLM(config).to(torch.float32).eval()
+ weights = root / "model"
+ weights.mkdir(parents=True, exist_ok=True)
+ state = {k: v.contiguous() for k, v in model.state_dict().items()}
+ state.pop("lm_head.weight", None)
+ save_file(state, str(weights / "model.safetensors"))
+ config.save_pretrained(str(weights))
+ words = {"<unk>": 0, "<s>": 1, "</s>": 2, "<pad>": 3}
+ for word in ("hello", "world", "hi", "good", "answer", "bad"):
+ words[word] = len(words)
+ tok = Tokenizer(models.WordLevel(vocab=words, unk_token="<unk>"))
+ tok.pre_tokenizer = pre_tokenizers.Whitespace()
+ PreTrainedTokenizerFast(
+ tokenizer_object=tok, unk_token="<unk>", bos_token="<s>", eos_token="</s>",
+ pad_token="<pad>",
+ ).save_pretrained(str(weights))
+ return str(weights)
+
+
+def _write_project(tmp_path: Path, auto_eval: bool, seed: int = 1) -> None:
+ weights = str(tmp_path / "model")
+ if not (tmp_path / "model" / "model.safetensors").exists():
+ weights = _tiny_llama_dir(tmp_path)
+ row = {"messages": [{"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "good answer"}]}
+ (tmp_path / "chat.jsonl").write_text(
+ "\n".join(json.dumps(row) for _ in range(8)) + "\n", encoding="utf-8"
+ )
+ (tmp_path / "soup.yaml").write_text(
+ f"base: {json.dumps(weights)}\n"
+ "task: sft\n"
+ "data:\n train: chat.jsonl\n format: chatml\n chat_template: chatml\n"
+ " max_length: 64\n"
+ "training:\n epochs: 1\n batch_size: 2\n logging_steps: 1\n"
+ f" quantization: none\n seed: {seed}\n"
+ " lora:\n r: 4\n alpha: 8\n target_modules: [q_proj, v_proj]\n"
+ f"eval:\n auto_eval: {'true' if auto_eval else 'false'}\n benchmarks: [mmlu]\n"
+ "output: ./out\n",
+ encoding="utf-8",
+ )
+
+
+def _record_benchmark(monkeypatch) -> list[dict]:
+ import soup_cli.commands.eval as eval_cmd
+
+ seen: list[dict] = []
+
+ def fake_benchmark(**kwargs):
+ model = Path(kwargs["model"])
+ adapter = model / "adapter_model.safetensors"
+ seen.append({
+ "model": str(model),
+ "adapter_bytes": adapter.read_bytes() if adapter.exists() else None,
+ })
+
+ monkeypatch.setattr(eval_cmd, "benchmark", fake_benchmark)
+ return seen
-class TestCallbackAutoEval:
- def test_auto_eval_not_called_without_config(self):
- from soup_cli.monitoring.callback import SoupTrainerCallback
- display = MagicMock()
- callback = SoupTrainerCallback(display=display)
- callback._run_auto_eval() # Should be a no-op
+class TestAutoEvalAfterTraining:
def test_auto_eval_not_called_when_disabled(self):
+ from soup_cli.commands.train import _run_auto_eval_after_training
from soup_cli.config.schema import EvalConfig
- from soup_cli.monitoring.callback import SoupTrainerCallback
- display = MagicMock()
+
eval_config = EvalConfig(auto_eval=False)
- callback = SoupTrainerCallback(
- display=display, eval_config=eval_config,
- )
- callback._run_auto_eval() # Should be a no-op
- def test_auto_eval_called_when_enabled(self):
+ with patch("soup_cli.commands.eval.benchmark") as mock_bench:
+ _run_auto_eval_after_training(
+ eval_config,
+ "/tmp/model",
+ "test_run",
+ )
+
+ mock_bench.assert_not_called()
+
+ def test_auto_eval_uses_saved_output_dir(self):
+ from soup_cli.commands.train import _run_auto_eval_after_training
from soup_cli.config.schema import EvalConfig
- from soup_cli.monitoring.callback import SoupTrainerCallback
- display = MagicMock()
+
eval_config = EvalConfig(
- auto_eval=True, benchmarks=["mmlu"],
- )
- callback = SoupTrainerCallback(
- display=display,
- eval_config=eval_config,
- output_dir="/tmp/model",
- run_id="test_run",
+ auto_eval=True,
+ benchmarks=["mmlu", "gsm8k"],
)
+
with patch("soup_cli.commands.eval.benchmark") as mock_bench:
- callback._run_auto_eval()
- mock_bench.assert_called_once()
+ _run_auto_eval_after_training(
+ eval_config,
+ "/tmp/saved-adapter",
+ "test_run",
+ )
+ mock_bench.assert_called_once()
+ assert mock_bench.call_args.kwargs["model"] == "/tmp/saved-adapter"
+ assert mock_bench.call_args.kwargs["benchmarks"] == "mmlu,gsm8k"
+ assert mock_bench.call_args.kwargs["run_id"] == "test_run"
+ def test_auto_eval_failure_does_not_fail_training(self):
+ from soup_cli.commands.train import _run_auto_eval_after_training
+ from soup_cli.config.schema import EvalConfig
+
+ eval_config = EvalConfig(
+ auto_eval=True,
+ benchmarks=["mmlu"],
+ )
+
+ with patch(
+ "soup_cli.commands.eval.benchmark",
+ side_effect=RuntimeError("benchmark exploded"),
+ ):
+ _run_auto_eval_after_training(
+ eval_config,
+ "/tmp/saved-adapter",
+ "test_run",
+ )
+
+ def test_auto_eval_runs_only_on_the_main_process(self, monkeypatch):
+ from soup_cli.commands.train import _run_auto_eval_after_training
+ from soup_cli.config.schema import EvalConfig
+
+ monkeypatch.setenv("RANK", "1")
+ with patch("soup_cli.commands.eval.benchmark") as bench:
+ _run_auto_eval_after_training(
+ EvalConfig(auto_eval=True, benchmarks=["mmlu"]),
+ "out",
+ "run-1",
+ )
+ bench.assert_not_called()
+
+ def test_auto_eval_failure_prints_what_failed(self, capsys):
+ from soup_cli.commands.train import _run_auto_eval_after_training
+ from soup_cli.config.schema import EvalConfig
+
+ with patch(
+ "soup_cli.commands.eval.benchmark",
+ side_effect=RuntimeError("benchmark exploded"),
+ ):
+ _run_auto_eval_after_training(
+ EvalConfig(auto_eval=True, benchmarks=["mmlu"]),
+ "out",
+ "run-1",
+ )
+
+ out = " ".join(_strip_ansi(capsys.readouterr().out).split())
+ assert "Auto-eval benchmark failed" in out
+ assert "benchmark exploded" in out
+
+ def test_custom_eval_uses_the_saved_output_and_its_failure_does_not_raise(self):
+ from soup_cli.commands.train import _run_auto_eval_after_training
+ from soup_cli.config.schema import EvalConfig
+
+ with patch(
+ "soup_cli.commands.eval.custom",
+ side_effect=RuntimeError("custom exploded"),
+ ) as custom:
+ _run_auto_eval_after_training(
+ EvalConfig(auto_eval=True, custom_tasks="tasks.jsonl"),
+ "/tmp/saved-adapter",
+ "run-1",
+ )
+
+ assert custom.call_args.kwargs["model"] == "/tmp/saved-adapter"
+ assert custom.call_args.kwargs["tasks"] == "tasks.jsonl"
+
+ def test_auto_eval_runs_on_the_adapter_this_run_saved(
+ self, tmp_path, monkeypatch
+ ):
+ pytest.importorskip("trl")
+ monkeypatch.chdir(tmp_path)
+ seen = _record_benchmark(monkeypatch)
+
+ # The second run reuses ./out, where run 1's adapter sits; a different seed
+ # makes the two adapters differ byte for byte.
+ for seed in (1, 2):
+ _write_project(tmp_path, auto_eval=True, seed=seed)
+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ saved = (tmp_path / "out" / "adapter_model.safetensors").read_bytes()
+ assert seen, "auto_eval: true ran no evaluation"
+ assert seen[-1]["adapter_bytes"] is not None, (
+ "the evaluation ran before the adapter was saved"
+ )
+ assert seen[-1]["adapter_bytes"] == saved, (
+ "the evaluation scored a different adapter than the one this run saved"
+ )
+ assert len(seen) == 2
+
+
+ def test_auto_eval_false_runs_nothing(
+ self, tmp_path, monkeypatch
+ ):
+ pytest.importorskip("trl")
+ monkeypatch.chdir(tmp_path)
+ _write_project(tmp_path, auto_eval=False)
+ seen = _record_benchmark(monkeypatch)
+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert seen == []
# ═══════════════════════════════════════════════════════════
# CLI — eval subcommands
# ═══════════════════════════════════════════════════════════
diff --git a/tests/test_issue1449_trust_remote_code_dropped.py b/tests/test_issue1449_trust_remote_code_dropped.py
index babf3c04..a851cf26 100644
--- a/tests/test_issue1449_trust_remote_code_dropped.py
+++ b/tests/test_issue1449_trust_remote_code_dropped.py
@@ -494,19 +494,18 @@ class TestDefaultsStayDeny:
def test_training_auto_eval_callback_never_opts_in(self, monkeypatch):
import soup_cli.commands.eval as ce
- from soup_cli.monitoring.callback import SoupTrainerCallback
+ import soup_cli.commands.train as train_cmd
calls: dict = {}
monkeypatch.setattr(ce, "benchmark", lambda **kw: calls.__setitem__("benchmark", kw))
monkeypatch.setattr(ce, "custom", lambda **kw: calls.__setitem__("custom", kw))
- callback = SoupTrainerCallback.__new__(SoupTrainerCallback)
- callback.eval_config = type(
+ monkeypatch.setattr(train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True)
+
+ eval_config = type(
"EvalCfg", (),
{"auto_eval": True, "benchmarks": ["mmlu"], "custom_tasks": "tasks.jsonl"},
)()
- callback.output_dir = "out"
- callback.run_id = "run-1"
- callback._run_auto_eval()
+ train_cmd._run_auto_eval_after_training(eval_config, "out", "run-1")
assert calls["benchmark"]["trust_remote_code"] is False, calls
assert calls["custom"]["trust_remote_code"] is False, calls
diff --git a/tests/test_issue752_cli_commands_called_as_functions.py b/tests/test_issue752_cli_commands_called_as_functions.py
index 733ba863..ce393dc1 100644
--- a/tests/test_issue752_cli_commands_called_as_functions.py
+++ b/tests/test_issue752_cli_commands_called_as_functions.py
@@ -298,18 +298,19 @@ def test_training_callback_passes_every_typer_parameter_of_custom(monkeypatch):
recorded: dict = {}
monkeypatch.setattr(ce, "custom", _recording_custom(recorded))
- from soup_cli.monitoring.callback import SoupTrainerCallback
+ import soup_cli.commands.train as train_cmd
- callback = SoupTrainerCallback.__new__(SoupTrainerCallback)
- callback.eval_config = type(
+ monkeypatch.setattr(
+ train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True
+ )
+
+ eval_config = type(
"EvalCfg",
(),
{"auto_eval": True, "benchmarks": [], "custom_tasks": "tasks.jsonl"},
)()
- callback.output_dir = "out"
- callback.run_id = "run-1"
- callback._run_auto_eval()
+ train_cmd._run_auto_eval_after_training(eval_config, "out", "run-1")
assert set(recorded) == expected, (
f"the callback left {sorted(expected - set(recorded))} to typer's default"
diff --git a/tests/test_issue802_callback_kwargs_in_trainers.py b/tests/test_issue802_callback_kwargs_in_trainers.py
index a685afbb..06f5e1f0 100644
--- a/tests/test_issue802_callback_kwargs_in_trainers.py
+++ b/tests/test_issue802_callback_kwargs_in_trainers.py
@@ -12,8 +12,12 @@ from unittest.mock import MagicMock
import pytest
-from soup_cli.config.schema import SoupConfig, TrainingConfig
-from soup_cli.monitoring.callback import SoupTrainerCallback, soup_callback_kwargs
+from soup_cli.config.schema import EvalGateConfig, SoupConfig, TrainingConfig
+from soup_cli.monitoring.callback import (
+ SoupTrainerCallback,
+ build_soup_trainer_callback,
+ soup_callback_kwargs,
+)
TRAINER_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "trainer"
@@ -49,14 +53,14 @@ UNSUPPORTED_CALLBACK_TRAINERS = {
class TestTrainerCallbackKwargsUsage:
- """Verify that all 16 trainers instantiate SoupTrainerCallback using
- **soup_callback_kwargs(...) and track self._batch_size.
- """
+ """Verify that all 16 trainers use the shared callback builder."""
def test_all_expected_trainers_exist(self) -> None:
for filename in EXPECTED_CALLBACK_TRAINERS | UNSUPPORTED_CALLBACK_TRAINERS:
filepath = TRAINER_DIR / filename
- assert filepath.is_file(), f"Trainer file {filename} does not exist in {TRAINER_DIR}"
+ assert filepath.is_file(), (
+ f"Trainer file {filename} does not exist in {TRAINER_DIR}"
+ )
def test_ast_scan_trainer_callback_kwargs_unification(self) -> None:
discovered_callback_trainers: set[str] = set()
@@ -64,30 +68,117 @@ class TestTrainerCallbackKwargsUsage:
for py_file in sorted(TRAINER_DIR.glob("*.py")):
if py_file.name == "__init__.py":
continue
+
content = py_file.read_text(encoding="utf-8")
- if "SoupTrainerCallback(" in content:
- discovered_callback_trainers.add(py_file.name)
-
- # Must import soup_callback_kwargs
- assert "soup_callback_kwargs" in content, (
- f"{py_file.name} references SoupTrainerCallback but lacks "
- "soup_callback_kwargs import"
- )
-
- # Must pass **soup_callback_kwargs(...)
- assert "**soup_callback_kwargs(" in content, (
- f"{py_file.name} does not pass **soup_callback_kwargs(...) to "
- "SoupTrainerCallback"
- )
-
- # Must record self._batch_size in setup() or class
- assert "self._batch_size" in content, (
- f"{py_file.name} does not track self._batch_size"
- )
+ tree = ast.parse(content, filename=str(py_file))
+
+ builder_calls = []
+ direct_callback_calls = []
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+
+ func_name = ast.unparse(node.func)
+
+ if func_name == "build_soup_trainer_callback":
+ builder_calls.append(node)
+ elif (
+ func_name == "SoupTrainerCallback"
+ or (
+ isinstance(node.func, ast.Attribute)
+ and node.func.attr == "SoupTrainerCallback"
+ )
+ ):
+ direct_callback_calls.append(node)
+
+ # Direct callback construction is forbidden in every trainer.
+ assert not direct_callback_calls, (
+ f"{py_file.name} directly instantiates SoupTrainerCallback; "
+ "use build_soup_trainer_callback instead"
+ )
+
+ if not builder_calls:
+ continue
+
+ discovered_callback_trainers.add(py_file.name)
+
+ # Each supported trainer must have exactly one shared builder call.
+ assert len(builder_calls) == 1, (
+ f"{py_file.name} must have exactly one "
+ "build_soup_trainer_callback call"
+ )
+
+ builder = builder_calls[0]
+ keywords = {kw.arg: kw.value for kw in builder.keywords if kw.arg}
+
+ assert "config" in keywords, (
+ f"{py_file.name} does not pass config to "
+ "build_soup_trainer_callback"
+ )
+ assert ast.unparse(keywords["config"]) == "self.config", (
+ f"{py_file.name} must pass config=self.config"
+ )
+
+ assert "batch_size" in keywords, (
+ f"{py_file.name} does not pass batch_size to "
+ "build_soup_trainer_callback"
+ )
+ assert ast.unparse(keywords["batch_size"]) == "self._batch_size", (
+ f"{py_file.name} must pass batch_size=self._batch_size"
+ )
assert discovered_callback_trainers == EXPECTED_CALLBACK_TRAINERS, (
- f"Expected {EXPECTED_CALLBACK_TRAINERS}, but found {discovered_callback_trainers}"
+ f"Expected {EXPECTED_CALLBACK_TRAINERS}, "
+ f"but found {discovered_callback_trainers}"
+ )
+
+class TestBuildSoupTrainerCallback:
+ """Tests for the shared trainer callback builder."""
+
+ def test_passes_eval_config_to_callback(self) -> None:
+ config = SoupConfig(
+ base="sshleifer/tiny-gpt2",
+ task="grpo",
+ data={"train": "train.jsonl", "format": "chatml"},
+ eval={
+ "auto_eval": True,
+ "benchmarks": ["mmlu"],
+ "custom_tasks": "custom.jsonl",
+ },
+ )
+ display = MagicMock()
+
+ callback = build_soup_trainer_callback(
+ display,
+ config=config,
+ tracker=MagicMock(),
+ run_id="test-run",
+ batch_size=4,
+ output_dir="/tmp/output",
+ )
+
+ assert callback.eval_config is config.eval
+ assert callback.run_id == "test-run"
+ assert callback.output_dir == "/tmp/output"
+
+ def test_builder_passes_eval_gate_to_callback(self) -> None:
+ config = SoupConfig(
+ base="sshleifer/tiny-gpt2",
+ task="sft",
+ data={"train": "train.jsonl", "format": "chatml"},
+ training={
+ "eval_gate": {
+ "enabled": True,
+ "suite": "evals/gate.yaml",
+ }
+ },
)
+ assert config.training.eval_gate is not None
+
+ callback = build_soup_trainer_callback(MagicMock(), config=config)
+
+ assert callback.eval_gate_config is config.training.eval_gate
def test_unsupported_trainers_do_not_instantiate_callback(self) -> None:
for filename in UNSUPPORTED_CALLBACK_TRAINERS:
@@ -128,6 +219,14 @@ class TestSoupCallbackKwargsHelper:
assert kwargs["grad_accum_current_steps"] == 4
assert kwargs["grad_accum_current_batch"] == 1
assert kwargs["eval_gate_config"] is None
+ eval_gate = EvalGateConfig(
+ enabled=False,
+ suite="evals/gate.yaml",
+ )
+ tcfg_with_gate = TrainingConfig(eval_gate=eval_gate)
+ kwargs_with_gate = soup_callback_kwargs(tcfg_with_gate)
+
+ assert kwargs_with_gate["eval_gate_config"] is eval_gate
assert "output_dir" not in kwargs
# When tcfg has no gradient_accumulation_steps attribute
@@ -400,3 +499,35 @@ class TestTrainerWrapperBehaviouralCallbackWiring:
assert cb._spike_recovery_enabled is True
assert cb._grad_accum_enabled is True
assert cb._grad_accum_batch == 8
+
+ def test_grpo_wrapper_train_wires_eval_config(
+ self, tmp_path: Path
+ ) -> None:
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+ wrapper = object.__new__(GRPOTrainerWrapper)
+ wrapper.config = SoupConfig(
+ base="sshleifer/tiny-gpt2",
+ task="grpo",
+ data={"train": "train.jsonl", "format": "chatml"},
+ eval={
+ "auto_eval": True,
+ "benchmarks": ["mmlu"],
+ },
+ )
+ wrapper._batch_size = 4
+ wrapper._output_dir = str(tmp_path)
+ wrapper.tokenizer = MagicMock()
+ mock_trainer = MagicMock()
+ mock_trainer.state.log_history = []
+ wrapper.trainer = mock_trainer
+ captured_callbacks: list[object] = []
+ mock_trainer.add_callback.side_effect = captured_callbacks.append
+ wrapper.train(display=MagicMock())
+ soup_cbs = [
+ cb for cb in captured_callbacks if isinstance(cb, SoupTrainerCallback)
+ ]
+ assert len(soup_cbs) == 1
+ cb = soup_cbs[0]
+ assert cb.eval_config is wrapper.config.eval
+ assert cb.eval_config.auto_eval is True
+ assert cb.eval_config.benchmarks == ["mmlu"]