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(grpo): record the held-out reward as the validation metric, not TRL's policy objective (#1389) (#1592)

Srinivasan R1f390dd0fa52
diff --git a/changelog.d/0.75.1/1592.fixed.md b/changelog.d/0.75.1/1592.fixed.md
new file mode 100644
index 00000000..649da9ab
--- /dev/null
+++ b/changelog.d/0.75.1/1592.fixed.md
@@ -0,0 +1 @@
+- A `task: grpo` run with `training.eval_steps` now records the held-out reward (`eval_reward`, higher is better) as its validation metric: the live panel shows a `Val reward` row, the tracker's metrics table gains a `val_reward` column (added to existing databases in place), and the training event stream carries `val_reward`. TRL's `eval_loss` on grpo, the policy objective, is no longer stored or shown as `val_loss`; every other task keeps `eval_loss` / `val_loss` unchanged. The per-task choice lives in `VALIDATION_METRICS` in `utils/eval_schedule.py` (#1389 by @Srinivasan8888 in #1592).
diff --git a/docs/training.md b/docs/training.md
index b777d041..61a30e9d 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -92,12 +92,18 @@ they do not evaluate by default, and they do not withhold rows either:
`data.val_split` is ignored, every row trains, and the run prints a one-line note
saying so. On `grpo`, set `training.eval_steps` to hold the split out and
evaluate it; TRL generates completions for the held-out prompts and logs
-`eval_loss` with the evaluation rewards. On `grpo` that `eval_loss` (the Val
-loss row and the tracker's `val_loss`) is TRL's policy objective on the
-held-out completions, not a likelihood: advantages are normalised within each
-group, so it stays near zero, can be negative, and does not measure held-out
-quality. The held-out reward is `eval_reward`, in the `log_history` of each
-checkpoint's `trainer_state.json`. TRL needs whole groups of
+`eval_loss` with the evaluation rewards. On `grpo` the run's validation number
+is the held-out reward, `eval_reward` (the mean reward over the held-out
+completions, higher is better): the live panel shows it as `Val reward`, the
+tracker stores it in the `val_reward` column of the metrics table, and the
+training event stream carries it as `val_reward` (#1389). TRL's `eval_loss` on
+`grpo` is its policy objective at importance ratio 1, not a likelihood:
+advantages are normalised within each group, so it stays near zero, can be
+negative, and does not measure held-out quality. It is not recorded or shown as
+a loss: a `grpo` run's `val_loss` series is empty, and `Val loss` does not
+appear. The per-task choice lives in `VALIDATION_METRICS` in
+`utils/eval_schedule.py`; every other task records `eval_loss` as `val_loss`.
+TRL needs whole groups of
`num_generations` completions in an evaluation batch, so `grpo` evaluates at the
largest multiple of `num_generations` that fits in the train batch, and says so
when that differs from the train batch. The evaluation's rewards never reach the
diff --git a/src/soup_cli/experiment/tracker.py b/src/soup_cli/experiment/tracker.py
index d7cc964f..359c20f4 100644
--- a/src/soup_cli/experiment/tracker.py
+++ b/src/soup_cli/experiment/tracker.py
@@ -79,6 +79,7 @@ CREATE TABLE IF NOT EXISTS metrics (
epoch REAL,
loss REAL,
val_loss REAL,
+ val_reward REAL,
lr REAL,
grad_norm REAL,
speed REAL,
@@ -190,6 +191,9 @@ class ExperimentTracker:
# column existed has no evaluation loss, and NULL says so. A 0.0
# would read as a measurement nobody took.
("metrics", "val_loss", "ALTER TABLE metrics ADD COLUMN val_loss REAL"),
+ # grpo's held-out reward (#1389): its own column, because a reward
+ # is higher-is-better and must not be read as a loss.
+ ("metrics", "val_reward", "ALTER TABLE metrics ADD COLUMN val_reward REAL"),
):
existing = {
row[1]
@@ -349,21 +353,25 @@ class ExperimentTracker:
speed: float = 0.0,
gpu_mem: str = "",
val_loss: Optional[float] = None,
+ val_reward: Optional[float] = None,
) -> None:
"""Log a single metrics row for the given run.
- ``val_loss`` and ``grad_norm`` default to ``None`` rather than ``0.0``:
- an omitted measurement must not look like a genuinely measured zero.
- ``loss`` is None for a training log that carried no loss (#1225).
+ ``val_loss``, ``val_reward`` and ``grad_norm`` default to ``None`` rather
+ than ``0.0``: an omitted measurement must not look like a genuinely
+ measured zero. ``loss`` is None for a training log that carried no loss
+ (#1225). ``val_reward`` is grpo's held-out reward (#1389); every other
+ task leaves it NULL.
"""
now = datetime.now().isoformat()
conn = self._get_conn()
conn.execute(
"""INSERT INTO metrics
- (run_id, step, epoch, loss, val_loss, lr, grad_norm, speed,
+ (run_id, step, epoch, loss, val_loss, val_reward, lr, grad_norm, speed,
gpu_mem, timestamp)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
- (run_id, step, epoch, loss, val_loss, lr, grad_norm, speed, gpu_mem, now),
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (run_id, step, epoch, loss, val_loss, val_reward, lr, grad_norm, speed,
+ gpu_mem, now),
)
conn.commit()
diff --git a/src/soup_cli/monitoring/callback.py b/src/soup_cli/monitoring/callback.py
index 579088cd..5629e6e6 100644
--- a/src/soup_cli/monitoring/callback.py
+++ b/src/soup_cli/monitoring/callback.py
@@ -22,12 +22,20 @@ def soup_callback_kwargs(
batch_size: Optional[int] = None,
output_dir: Optional[str] = None,
include_eval_gate: bool = True,
+ task: Optional[str] = None,
) -> dict[str, Any]:
"""Shared kwargs for :class:`SoupTrainerCallback` across all trainers (#802).
Unifies watchdog, spike recovery, and grad-accum parameters so they cannot
drift across trainer implementations.
+
+ ``task`` picks the run's validation metric from
+ :data:`soup_cli.utils.eval_schedule.VALIDATION_METRICS` (#1389): every task
+ records ``eval_loss`` as ``val_loss`` unless the table says otherwise, so only
+ a trainer whose evaluation is scored differently (``grpo``: the held-out
+ reward) needs to pass it.
"""
+ from soup_cli.utils.eval_schedule import validation_metric
resolved_batch = 1
if batch_size is not None and not isinstance(batch_size, bool):
try:
@@ -60,6 +68,7 @@ def soup_callback_kwargs(
tcfg, "gradient_accumulation_steps", 1
),
"grad_accum_current_batch": resolved_batch,
+ "val_metric": validation_metric(task),
}
if include_eval_gate:
kwargs["eval_gate_config"] = getattr(tcfg, "eval_gate", None)
@@ -76,8 +85,12 @@ def build_soup_trainer_callback(
run_id: str = "",
batch_size: Optional[int] = None,
output_dir: Optional[str] = None,
+ task: Optional[str] = None,
) -> Any:
- """Build a trainer callback with shared training and evaluation config."""
+ """Build a trainer callback with shared training and evaluation config.
+
+ ``task`` picks the run's validation metric (#1389); only a trainer whose
+ evaluation is scored differently (``grpo``) needs to pass it."""
training_config = config.training
callback_cls = globals().get("SoupTrainerCallback")
if callback_cls is None:
@@ -92,6 +105,7 @@ def build_soup_trainer_callback(
training_config,
batch_size=batch_size,
output_dir=output_dir,
+ task=task,
),
)
@@ -149,12 +163,21 @@ class _SoupTrainerCallback_body: # noqa: N801
grad_accum_total_vram_gb: Optional[float] = None,
grad_accum_current_steps: int = 1,
grad_accum_current_batch: int = 1,
+ val_metric: Optional[object] = None,
):
+ from soup_cli.utils.eval_schedule import DEFAULT_VALIDATION_METRIC
+
self.display = display
self.tracker = tracker
self.run_id = run_id
self.eval_config = eval_config
self.output_dir = output_dir
+ #: Which evaluation entry is this run's validation number, and under
+ #: what name it is recorded (#1389). ``eval_loss`` -> ``val_loss`` for
+ #: every task but the generation-scored ones; grpo records
+ #: ``eval_reward`` as ``val_reward`` and its ``eval_loss``, the policy
+ #: objective, reaches no sink.
+ self._val_metric = val_metric or DEFAULT_VALIDATION_METRIC
# HF emits a summary-only ``on_log`` event after the final optimizer
# step. It has runtime/throughput fields but no loss/LR/grad norm. Keep
# the last real values so that event cannot reset the dashboards and
@@ -308,8 +331,12 @@ class _SoupTrainerCallback_body: # noqa: N801
# `_last_loss` untouched and re-reported the stale training number to
# every sink at the same step, so the evaluated value existed nowhere.
# It is kept as a separate series and never folded into `loss`.
- if logs.get("eval_loss") is not None:
- self._last_val_loss = logs["eval_loss"]
+ # Which entry that is depends on the task (#1389): `eval_loss` for a
+ # likelihood-scored task, `eval_reward` for grpo, where `eval_loss` is
+ # the policy objective and is deliberately not read.
+ val_key, val_field = self._val_metric.log_key, self._val_metric.field
+ if logs.get(val_key) is not None:
+ self._last_val_loss = logs[val_key]
loss = self._last_loss
lr = self._last_lr
display_grad_norm = self._last_grad_norm
@@ -328,18 +355,18 @@ class _SoupTrainerCallback_body: # noqa: N801
# would be inconsistent to reject 0.0 there and accept a carried value
# here.
display_val_loss = self._last_val_loss
- measured_val_loss = logs.get("eval_loss")
+ measured_val_loss = logs.get(val_key)
speed = logs.get("train_steps_per_second", 0.0)
self.display.update(
step=step,
epoch=epoch,
loss=loss,
- val_loss=display_val_loss,
lr=lr,
grad_norm=display_grad_norm,
speed=speed,
gpu_mem=gpu_mem,
+ **{val_field: display_val_loss},
)
# v0.53.9 #94 — push to the global SSE buffer so the live Web UI
@@ -357,17 +384,19 @@ class _SoupTrainerCallback_body: # noqa: N801
# `is not None`, not truthiness — a real 0.0 loss / lr (e.g.
# end of an LR schedule) must not be reported as None.
loss=float(loss) if loss is not None else None,
- val_loss=(
- float(measured_val_loss)
- if measured_val_loss is not None
- else None
- ),
lr=float(lr) if lr is not None else None,
grad_norm=(
float(measured_grad_norm)
if measured_grad_norm is not None
else None
),
+ **{
+ val_field: (
+ float(measured_val_loss)
+ if measured_val_loss is not None
+ else None
+ )
+ },
)
)
except Exception:
@@ -447,11 +476,11 @@ class _SoupTrainerCallback_body: # noqa: N801
step=step,
epoch=epoch,
loss=loss,
- val_loss=measured_val_loss,
lr=lr,
grad_norm=measured_grad_norm,
speed=speed,
gpu_mem=gpu_mem,
+ **{val_field: measured_val_loss},
)
def on_epoch_end(
diff --git a/src/soup_cli/monitoring/display.py b/src/soup_cli/monitoring/display.py
index e0080415..03a06747 100644
--- a/src/soup_cli/monitoring/display.py
+++ b/src/soup_cli/monitoring/display.py
@@ -72,6 +72,9 @@ class TrainingDisplay:
#: None until an evaluation actually runs. Its own series --
#: never folded into `self.loss`, which is the training curve.
self.val_loss = None
+ #: grpo's validation number: the mean reward on the held-out
+ #: completions, higher is better (#1389). Its own row, never a "loss".
+ self.val_reward = None
self._live: Optional[Live] = None
def start(self, total_steps: int):
@@ -94,6 +97,8 @@ class TrainingDisplay:
# than blinking out on every training step.
if kwargs.get("val_loss") is not None:
self.val_loss = kwargs["val_loss"]
+ if kwargs.get("val_reward") is not None:
+ self.val_reward = kwargs["val_reward"]
if self._live:
self._live.update(self._render())
@@ -125,6 +130,8 @@ class TrainingDisplay:
if self.val_loss is not None:
lines.append(f"Val loss: {self.val_loss:.4f}")
+ if self.val_reward is not None:
+ lines.append(f"Val reward: {self.val_reward:.4f}")
if self.speed > 0:
lines.append(f"Speed: {self.speed:.2f} it/s")
if self.gpu_mem:
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index 198899c4..6f349595 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -773,6 +773,9 @@ class GRPOTrainerWrapper:
batch_size=self._batch_size,
run_id=run_id,
output_dir=self._output_dir,
+ # #1389: grpo's validation number is the held-out
+ # reward, not TRL's policy objective in `eval_loss`.
+ task=self.config.task,
)
)
diff --git a/src/soup_cli/utils/eval_gate_hook.py b/src/soup_cli/utils/eval_gate_hook.py
index 106150f9..02693931 100644
--- a/src/soup_cli/utils/eval_gate_hook.py
+++ b/src/soup_cli/utils/eval_gate_hook.py
@@ -256,7 +256,10 @@ _ALLOWED_METRIC_HELP = (
"task_accuracy, judge:<model>, benchmark:<name>"
)
_RESERVED_TRAINING_METRICS = frozenset(
- {"loss", "val_loss", "lr", "grad_norm", "speed", "gpu_mem", "epoch"}
+ # every column of the metrics table a run writes, so `benchmark:<name>` can
+ # never gate on a training-time series; `val_reward` is grpo's held-out
+ # reward (#1389), a training-time measurement like `val_loss`
+ {"loss", "val_loss", "val_reward", "lr", "grad_norm", "speed", "gpu_mem", "epoch"}
)
diff --git a/src/soup_cli/utils/eval_schedule.py b/src/soup_cli/utils/eval_schedule.py
index 1a58a934..62b5183e 100644
--- a/src/soup_cli/utils/eval_schedule.py
+++ b/src/soup_cli/utils/eval_schedule.py
@@ -30,7 +30,7 @@ here may pull torch, transformers or the data stack.
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, NamedTuple, Optional
if TYPE_CHECKING: # pragma: no cover - typing only
from soup_cli.config.schema import DataConfig, SoupConfig
@@ -39,6 +39,45 @@ if TYPE_CHECKING: # pragma: no cover - typing only
#: much per row as training does. They evaluate only when asked to.
GENERATION_EVAL_TASKS: frozenset[str] = frozenset({"grpo", "ppo", "online_dpo"})
+
+class ValidationMetric(NamedTuple):
+ """Which number an evaluation produces for a task, and what it means (#1389).
+
+ ``log_key`` is the entry in the trainer's ``on_log`` dict; ``field`` is the
+ name Soup records it under -- the tracker column, the ``TrainEvent`` field and
+ the display's attribute, which all spell it the same way; ``label`` is the
+ live panel's row; ``direction`` says how to read the series.
+ """
+
+ log_key: str
+ field: str
+ label: str
+ direction: str
+
+
+#: Every task's evaluation logs a held-out loss, lower is better ...
+DEFAULT_VALIDATION_METRIC = ValidationMetric(
+ "eval_loss", "val_loss", "Val loss", "lower is better"
+)
+
+#: ... except the generation-scored ones. On ``grpo`` TRL's ``eval_loss`` is the
+#: policy objective at importance ratio 1 with group-normalised advantages: it
+#: sits near zero, is often negative and does not measure held-out quality. The
+#: held-out reward, ``eval_reward``, is the run's validation number, and it is
+#: recorded under its own name so nothing reads it as a loss (#1389). A task
+#: that later gains a generation-based evaluation (``ppo``, ``online_dpo``, which
+#: refuse ``eval_steps`` today) adds a row here, not a special case downstream.
+VALIDATION_METRICS: dict[str, ValidationMetric] = {
+ "grpo": ValidationMetric("eval_reward", "val_reward", "Val reward", "higher is better"),
+}
+
+
+def validation_metric(task: Optional[str]) -> ValidationMetric:
+ """The validation metric a task records; the loss for any task not in the table."""
+ if isinstance(task, str):
+ return VALIDATION_METRICS.get(task, DEFAULT_VALIDATION_METRIC)
+ return DEFAULT_VALIDATION_METRIC
+
#: Tasks that refuse ``training.eval_steps`` at config load, each with the
#: reason. The setting would be read by nothing on them (ppo, unlearn) or would
#: crash the run (online_dpo). A generation-based evaluation for ppo and
diff --git a/src/soup_cli/utils/sse_train_stream.py b/src/soup_cli/utils/sse_train_stream.py
index 05cf7a02..17d2f355 100644
--- a/src/soup_cli/utils/sse_train_stream.py
+++ b/src/soup_cli/utils/sse_train_stream.py
@@ -21,6 +21,7 @@ _ALLOWED_KEYS = frozenset(
"epoch",
"loss",
"val_loss",
+ "val_reward",
"lr",
"grad_norm",
"tokens_per_s",
@@ -51,6 +52,10 @@ class TrainEvent:
#: training series would replace one curve with another at the same
#: step, which looks correct and is not.
val_loss: Optional[float] = None
+ #: grpo's held-out reward at an evaluation step, higher is better (#1389).
+ #: Its own field for the same reason ``val_loss`` is: a reward written into
+ #: the loss curve would read as a loss.
+ val_reward: Optional[float] = None
lr: Optional[float] = None
grad_norm: Optional[float] = None
tokens_per_s: Optional[float] = None
@@ -91,6 +96,7 @@ def to_payload(event: TrainEvent) -> Dict[str, Any]:
"epoch",
"loss",
"val_loss",
+ "val_reward",
"lr",
"grad_norm",
"tokens_per_s",
diff --git a/tests/test_issue1389_grpo_val_reward.py b/tests/test_issue1389_grpo_val_reward.py
new file mode 100644
index 00000000..8964d686
--- /dev/null
+++ b/tests/test_issue1389_grpo_val_reward.py
@@ -0,0 +1,453 @@
+"""#1389: a grpo run's validation number is the held-out reward, recorded as a reward.
+
+Since #1313 ``task: grpo`` + ``training.eval_steps`` evaluates the held-out prompts, and
+the callback turned that evaluation's ``eval_loss`` into the run's ``val_loss``: the
+``Val loss`` panel row, the tracker column, the ``TrainEvent`` field. On grpo that
+number is TRL's policy objective at importance ratio 1 with group-normalised
+advantages: near zero, often negative, unrelated to held-out quality. The number that
+measures it, ``eval_reward``, reached only ``trainer_state.json``.
+
+Now a per-task table (``VALIDATION_METRICS`` in ``utils/eval_schedule.py``) says which
+evaluation entry is a task's validation number and what it is called. grpo records
+``eval_reward`` as ``val_reward`` (panel row ``Val reward``, tracker column, event field),
+and its ``eval_loss`` reaches no sink; every other task records ``eval_loss`` as
+``val_loss`` exactly as before.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.experiment.tracker import ExperimentTracker
+from soup_cli.monitoring.display import TrainingDisplay
+from soup_cli.utils.eval_schedule import (
+ DEFAULT_VALIDATION_METRIC,
+ EVAL_STEPS_UNSUPPORTED_TASKS,
+ GENERATION_EVAL_TASKS,
+ VALIDATION_METRICS,
+ validation_metric,
+)
+from soup_cli.utils.sse_train_stream import TrainEvent, format_sse_frame, to_payload
+
+_GRPO_EVAL_LOG = {"eval_loss": -0.1301, "eval_reward": 15.25, "eval_reward_std": 2.5}
+
+
+class TestTheTable:
+ def test_grpo_records_the_held_out_reward(self):
+ spec = validation_metric("grpo")
+ assert spec.log_key == "eval_reward"
+ assert spec.field == "val_reward"
+ assert spec.label == "Val reward"
+ assert spec.direction == "higher is better"
+
+ @pytest.mark.parametrize("task", ["sft", "dpo", "pretrain", "classifier", None, ""])
+ def test_everything_else_records_the_loss(self, task):
+ assert validation_metric(task) is DEFAULT_VALIDATION_METRIC
+ assert DEFAULT_VALIDATION_METRIC.log_key == "eval_loss"
+ assert DEFAULT_VALIDATION_METRIC.field == "val_loss"
+ assert DEFAULT_VALIDATION_METRIC.direction == "lower is better"
+
+ def test_every_generation_task_that_can_evaluate_has_a_row(self):
+ """ppo and online_dpo refuse eval_steps today; the day one of them
+ evaluates, it needs a row here or its policy objective becomes a loss."""
+ evaluating = GENERATION_EVAL_TASKS - set(EVAL_STEPS_UNSUPPORTED_TASKS)
+ assert evaluating == {"grpo"}
+ assert evaluating <= set(VALIDATION_METRICS)
+
+ def test_every_recorded_validation_field_is_a_reserved_training_metric(self):
+ """#812 keeps `soup eval against --metric benchmark:<name>` off the metrics
+ table's training columns; a new validation field is one of those columns, or
+ `benchmark:val_reward` would compare two runs' training-time rewards as
+ benchmark scores (review of #1592)."""
+ from soup_cli.utils.eval_gate_hook import _RESERVED_TRAINING_METRICS
+
+ for spec in (DEFAULT_VALIDATION_METRIC, *VALIDATION_METRICS.values()):
+ assert spec.field in _RESERVED_TRAINING_METRICS, spec
+
+ def test_every_field_in_the_table_has_a_sink_everywhere(self, tmp_path):
+ """The field name is spelled in four places; the table must name a field
+ that every sink knows, or the value is written to nothing."""
+ db = tmp_path / "t.db"
+ ExperimentTracker(db_path=str(db)).init_db()
+ columns = {row[1] for row in sqlite3.connect(db).execute("PRAGMA table_info(metrics)")}
+ display = TrainingDisplay(_display_config())
+ for spec in (DEFAULT_VALIDATION_METRIC, *VALIDATION_METRICS.values()):
+ assert spec.field in columns, spec
+ assert spec.field in TrainEvent.__dataclass_fields__, spec
+ assert hasattr(display, spec.field), spec
+
+
+def _display_config():
+ return SimpleNamespace(
+ training=SimpleNamespace(epochs=1), experiment_name="x", base="org/m"
+ )
+
+
+class _Tracker:
+ def __init__(self):
+ self.rows = []
+
+ def log_metrics(self, **row):
+ self.rows.append(row)
+
+
+def _callback(task, tracker, events, monkeypatch):
+ from soup_cli.monitoring.callback import SoupTrainerCallback, soup_callback_kwargs
+ from soup_cli.utils import train_event_buffer
+
+ monkeypatch.setattr(train_event_buffer, "push_train_event", events.append)
+ display = TrainingDisplay(_display_config())
+ callback = SoupTrainerCallback(
+ display, tracker=tracker, run_id="run-1",
+ **soup_callback_kwargs(SimpleNamespace(), task=task),
+ )
+ return callback, display
+
+
+def _log(callback, step, logs):
+ callback.on_log(
+ args=None, state=SimpleNamespace(global_step=step, epoch=1.0), control=None, logs=logs
+ )
+
+
+class TestTheCallbackRoutesTheTasksMetric:
+ def test_a_grpo_evaluation_reaches_every_sink_as_a_reward(self, monkeypatch):
+ tracker, events = _Tracker(), []
+ callback, display = _callback("grpo", tracker, events, monkeypatch)
+ _log(callback, 1, dict(_GRPO_EVAL_LOG))
+
+ assert display.val_reward == 15.25 and display.val_loss is None
+ assert tracker.rows[-1]["val_reward"] == 15.25
+ assert tracker.rows[-1].get("val_loss") is None
+ assert events[-1].val_reward == 15.25 and events[-1].val_loss is None
+
+ def test_the_policy_objective_is_stored_nowhere(self, monkeypatch):
+ """``eval_loss`` is in the same log dict and must not leak into any sink
+ under any name."""
+ tracker, events = _Tracker(), []
+ callback, display = _callback("grpo", tracker, events, monkeypatch)
+ _log(callback, 1, dict(_GRPO_EVAL_LOG))
+ recorded = {k: v for k, v in tracker.rows[-1].items() if v == -0.1301}
+ assert recorded == {}
+ assert -0.1301 not in to_payload(events[-1]).values()
+ assert "Val loss" not in display._render().renderable
+
+ def test_a_training_log_carries_the_reward_forward_on_the_panel_only(self, monkeypatch):
+ tracker, events = _Tracker(), []
+ callback, display = _callback("grpo", tracker, events, monkeypatch)
+ _log(callback, 1, dict(_GRPO_EVAL_LOG))
+ _log(callback, 2, {"loss": 0.5, "learning_rate": 1e-5, "grad_norm": 0.1})
+
+ assert display.val_reward == 15.25, "sticky between evaluations"
+ assert tracker.rows[-1]["val_reward"] is None, "not a measurement at step 2"
+ assert events[-1].val_reward is None
+
+ def test_the_default_task_still_records_the_loss(self, monkeypatch):
+ """The control: an sft evaluation lands in ``val_loss`` as before, and the
+ reward column stays empty."""
+ tracker, events = _Tracker(), []
+ callback, display = _callback("sft", tracker, events, monkeypatch)
+ _log(callback, 1, {"eval_loss": 1.25})
+
+ assert display.val_loss == 1.25 and display.val_reward is None
+ assert tracker.rows[-1]["val_loss"] == 1.25
+ assert tracker.rows[-1].get("val_reward") is None
+ assert events[-1].val_loss == 1.25 and events[-1].val_reward is None
+
+ def test_the_table_is_what_routes_it(self, monkeypatch):
+ """The same grpo-shaped log through the default spec records the loss and
+ ignores the reward: the routing is the task's row, not the log's keys."""
+ tracker, events = _Tracker(), []
+ callback, display = _callback(None, tracker, events, monkeypatch)
+ _log(callback, 1, dict(_GRPO_EVAL_LOG))
+
+ assert tracker.rows[-1]["val_loss"] == -0.1301
+ assert tracker.rows[-1].get("val_reward") is None
+ assert display.val_reward is None
+
+ def test_grpo_passes_its_task_to_the_shared_kwargs(self):
+ """The one trainer whose row differs must say so; the others take the
+ default. Read from the source the way #802's ratchet reads the kwargs."""
+ import inspect
+
+ from soup_cli.trainer import grpo
+
+ source = inspect.getsource(grpo)
+ assert "task=self.config.task" in source
+
+ def test_the_builder_forwards_the_task(self):
+ """``build_soup_trainer_callback`` (#1546) is the only path a trainer has to
+ the shared kwargs now, so the task must survive it."""
+ from soup_cli.monitoring.callback import build_soup_trainer_callback
+
+ def built(task):
+ config = SimpleNamespace(training=SimpleNamespace(), eval=None)
+ return build_soup_trainer_callback(
+ TrainingDisplay(_display_config()), config=config, task=task
+ )
+
+ assert built("grpo")._val_metric == VALIDATION_METRICS["grpo"]
+ assert built(None)._val_metric is DEFAULT_VALIDATION_METRIC
+
+ def test_the_kwargs_carry_the_spec(self):
+ from soup_cli.monitoring.callback import soup_callback_kwargs
+
+ assert soup_callback_kwargs(SimpleNamespace())["val_metric"] is DEFAULT_VALIDATION_METRIC
+ assert soup_callback_kwargs(SimpleNamespace(), task="grpo")["val_metric"] == (
+ VALIDATION_METRICS["grpo"]
+ )
+
+
+class TestThePanel:
+ def test_a_reward_row_is_labelled_as_a_reward(self):
+ display = TrainingDisplay(_display_config())
+ display.update(step=1, epoch=0.5, loss=0.4, lr=1e-5, val_reward=15.25)
+ text = display._render().renderable
+ assert "Val reward: 15.2500" in text
+ assert "Val loss" not in text
+
+ def test_a_loss_row_is_unchanged(self):
+ display = TrainingDisplay(_display_config())
+ display.update(step=1, epoch=0.5, loss=0.4, lr=1e-5, val_loss=1.25)
+ text = display._render().renderable
+ assert "Val loss: 1.2500" in text
+ assert "Val reward" not in text
+
+ def test_the_reward_row_stays_between_evaluations(self):
+ """The panel's own stickiness, not the callback's carry-forward (the one
+ mutation that survived the first round)."""
+ display = TrainingDisplay(_display_config())
+ display.update(step=1, epoch=0.5, loss=0.4, lr=1e-5, val_reward=15.25)
+ display.update(step=2, epoch=0.6, loss=0.3, lr=1e-5)
+ assert "Val reward: 15.2500" in display._render().renderable
+
+ def test_nothing_is_shown_before_an_evaluation(self):
+ display = TrainingDisplay(_display_config())
+ display.update(step=1, epoch=0.5, loss=0.4, lr=1e-5)
+ text = display._render().renderable
+ assert "Val" not in text
+
+
+def _legacy_db(path: Path) -> None:
+ """A metrics table from before the ``val_loss`` column existed."""
+ conn = sqlite3.connect(path)
+ conn.executescript(
+ """
+ CREATE TABLE runs (run_id TEXT PRIMARY KEY, status TEXT);
+ CREATE TABLE metrics (
+ id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL, step INTEGER NOT NULL,
+ epoch REAL, loss REAL, lr REAL, grad_norm REAL, speed REAL, gpu_mem TEXT,
+ timestamp TEXT NOT NULL
+ );
+ INSERT INTO runs VALUES ('old', 'completed');
+ INSERT INTO metrics (run_id, step, loss, timestamp) VALUES ('old', 1, 2.0, 't');
+ """
+ )
+ conn.commit()
+ conn.close()
+
+
+def _columns(db: Path) -> set[str]:
+ conn = sqlite3.connect(db)
+ try:
+ return {row[1] for row in conn.execute("PRAGMA table_info(metrics)")}
+ finally:
+ conn.close()
+
+
+class TestTheTracker:
+ def test_a_fresh_db_has_the_column(self, tmp_path):
+ db = tmp_path / "fresh.db"
+ ExperimentTracker(db_path=str(db)).init_db()
+ assert "val_reward" in _columns(db)
+
+ def test_a_legacy_db_gains_it_and_the_old_row_reads_null(self, tmp_path):
+ db = tmp_path / "experiments.db"
+ _legacy_db(db)
+ assert "val_reward" not in _columns(db)
+ tracker = ExperimentTracker(db_path=str(db))
+ tracker.init_db()
+ assert "val_reward" in _columns(db)
+ (row,) = tracker.get_metrics("old")
+ assert row["loss"] == 2.0 and row["val_reward"] is None
+
+ def test_the_second_migration_issues_no_alter(self, tmp_path):
+ db = tmp_path / "experiments.db"
+ _legacy_db(db)
+ ExperimentTracker(db_path=str(db)).init_db()
+ tracker = ExperimentTracker(db_path=str(db))
+ conn = tracker._get_conn()
+ statements: list[str] = []
+ conn.set_trace_callback(statements.append)
+ tracker.init_db()
+ conn.set_trace_callback(None)
+ assert not [q for q in statements if "ALTER TABLE" in q.upper()]
+
+ def test_the_reward_round_trips_and_the_loss_stays_null(self, tmp_path):
+ tracker = ExperimentTracker(db_path=str(tmp_path / "t.db"))
+ tracker.init_db()
+ tracker.log_metrics("r", step=1, loss=0.5, val_reward=15.25)
+ tracker.log_metrics("r", step=2, loss=0.4)
+ rows = tracker.get_metrics("r")
+ assert [r["val_reward"] for r in rows] == [15.25, None]
+ assert [r["val_loss"] for r in rows] == [None, None]
+ assert tracker.get_metric_series("r", "val_reward") == [15.25]
+
+
+class TestTheEventStream:
+ def test_the_reward_reaches_the_wire(self):
+ event = TrainEvent(type="metric", step=3, val_reward=15.25)
+ payload = to_payload(event)
+ assert payload["val_reward"] == 15.25 and "val_loss" not in payload
+ assert '"val_reward":15.25' in format_sse_frame(event)
+
+ def test_absent_means_omitted(self):
+ assert "val_reward" not in to_payload(TrainEvent(type="metric", step=3, loss=0.1))
+
+
+# ==========================================================================
+# the issue's reproduction: a real tiny grpo run on CPU, and the sft control
+# ==========================================================================
+def _requires_train_extra():
+ for mod in ("torch", "transformers", "peft", "trl", "datasets"):
+ pytest.importorskip(mod, reason=f"{mod} is only in the [train] extra")
+
+
+def _tiny_llama_dir(root: Path) -> str:
+ """The fixture from tests/test_issue1223_evaluate_val_split.py, verbatim."""
+ 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 _cfg(task: str, base: str, out: Path, **training_over):
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+
+ training = {
+ "batch_size": 2, "gradient_accumulation_steps": 1, "quantization": "none",
+ "epochs": 1, "logging_steps": 1, "save_steps": 1000,
+ "lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]},
+ }
+ if task == "grpo":
+ # The issue's reward: completion length, so the held-out reward is a
+ # number that varies and is visibly not the policy objective.
+ training.update({"num_generations": 2, "reward_fn": "./reward.py", "eval_steps": 1})
+ training.update(training_over)
+ return load_config_from_string(yaml.safe_dump({
+ "base": base, "task": task, "backend": "transformers", "modality": "text",
+ "data": {"train": "train.jsonl", "max_length": 64, "chat_template": "chatml"},
+ "training": training, "output": str(out),
+ }))
+
+
+def _run(tmp_path, monkeypatch, task, rows):
+ import importlib
+
+ from soup_cli.utils import train_event_buffer
+
+ monkeypatch.chdir(tmp_path)
+ events = []
+ monkeypatch.setattr(train_event_buffer, "push_train_event", events.append)
+ base = _tiny_llama_dir(tmp_path)
+ (tmp_path / "reward.py").write_text(
+ "def reward_fn(completions, **kwargs):\n"
+ " return [float(len(c)) for c in completions]\n",
+ encoding="utf-8",
+ )
+ cfg = _cfg(task, base, tmp_path / "out")
+ module, cls_name = {
+ "grpo": ("soup_cli.trainer.grpo", "GRPOTrainerWrapper"),
+ "sft": ("soup_cli.trainer.sft", "SFTTrainerWrapper"),
+ }[task]
+ wrapper = getattr(importlib.import_module(module), cls_name)(cfg, device="cpu")
+ wrapper.setup({"train": rows(8), "val": rows(2)})
+ tracker = ExperimentTracker(db_path=str(tmp_path / "experiments.db"))
+ tracker.init_db()
+ display = TrainingDisplay(cfg)
+ wrapper.train(display=display, tracker=tracker, run_id="run-1")
+ return wrapper, tracker.get_metrics("run-1"), display, events
+
+
+def _prompt_rows(n):
+ return [{"prompt": "hi"} for _ in range(n)]
+
+
+def _chat_rows(n):
+ return [{"messages": [{"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "good answer"}]} for _ in range(n)]
+
+
+class TestARealGrpoRun:
+ def test_the_tracker_holds_the_held_out_reward_and_no_val_loss(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ wrapper, metrics, display, events = _run(tmp_path, monkeypatch, "grpo", _prompt_rows)
+
+ evals = [e for e in wrapper.trainer.state.log_history if "eval_reward" in e]
+ assert evals, "the run never evaluated"
+ # A length reward on a random model is a real, positive number, and it is
+ # not the policy objective: the two series must be distinguishable, or
+ # the equality below would hold for the wrong reason.
+ assert all(e["eval_reward"] > 0 for e in evals), evals
+ assert [e["eval_reward"] for e in evals] != [e["eval_loss"] for e in evals]
+ recorded = [row["val_reward"] for row in metrics if row["val_reward"] is not None]
+ assert recorded == pytest.approx([e["eval_reward"] for e in evals])
+ assert all(row["val_loss"] is None for row in metrics), (
+ "the policy objective was stored as a loss"
+ )
+ assert display.val_reward == pytest.approx(evals[-1]["eval_reward"])
+ assert display.val_loss is None
+ streamed = [e.val_reward for e in events if e.val_reward is not None]
+ assert streamed == pytest.approx([e["eval_reward"] for e in evals])
+ assert all(e.val_loss is None for e in events)
+
+ def test_the_sft_control_is_unchanged(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ wrapper, metrics, display, events = _run(tmp_path, monkeypatch, "sft", _chat_rows)
+
+ evals = [e for e in wrapper.trainer.state.log_history if "eval_loss" in e]
+ assert evals
+ recorded = [row["val_loss"] for row in metrics if row["val_loss"] is not None]
+ assert recorded == pytest.approx([e["eval_loss"] for e in evals])
+ assert all(row["val_reward"] is None for row in metrics)
+ assert display.val_loss is not None and display.val_reward is None
+ assert all(e.val_reward is None for e in events)
+
+
+class TestTheDocs:
+ def test_training_md_points_at_the_new_metric(self):
+ docs = (Path(__file__).resolve().parents[1] / "docs" / "training.md").read_text(
+ encoding="utf-8"
+ )
+ assert "`val_reward`" in docs and "Val reward" in docs
+ assert "VALIDATION_METRICS" in docs
diff --git a/tests/test_issue812_eval_against_results.py b/tests/test_issue812_eval_against_results.py
index 37b06513..775b2a07 100644
--- a/tests/test_issue812_eval_against_results.py
+++ b/tests/test_issue812_eval_against_results.py
@@ -157,7 +157,7 @@ def test_empty_series_has_honest_unavailable_message():
@pytest.mark.parametrize(
"metric",
- ["loss", "val_loss", "lr", "grad_norm", "speed", "gpu_mem", "epoch"],
+ ["loss", "val_loss", "val_reward", "lr", "grad_norm", "speed", "gpu_mem", "epoch"],
)
def test_benchmark_namespace_rejects_reserved_training_metrics(metric, monkeypatch):
import soup_cli.experiment.tracker as tracker_module