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): evaluate the validation split, or stop withholding it (#1223) (#1313)

Alpamys Makazhanb6ef832e5adc
diff --git a/changelog.d/0.75.1/1313.changed.md b/changelog.d/0.75.1/1313.changed.md
new file mode 100644
index 00000000..fbd7b30b
--- /dev/null
+++ b/changelog.d/0.75.1/1313.changed.md
@@ -0,0 +1,15 @@
+- **Training now evaluates the validation split it holds out, and generation tasks stop holding one out (#1223 in #1313).**
+ `data.val_split` (default `0.1`) kept that share of the rows out of training on every run, but no trainer on the
+ transformers backend scheduled an evaluation, so those rows were never used and `val_loss` stayed empty. Every
+ task that receives a split now evaluates it at the end of each epoch, at the per-device train batch (not
+ Hugging Face's 8), and records `eval_loss` on the Val loss row, in the tracker's `val_loss` and in
+ `TrainEvent.val_loss`; `prm` and `moe_lora_routing`, which attach no live callback, keep it in the trainer's log
+ history. Runs take a few percent longer. The new `training.eval_steps: N` evaluates every N optimizer steps
+ instead. `grpo`, `ppo` and `online_dpo` evaluate by generating, so by default they neither evaluate nor withhold
+ rows: `data.val_split` is ignored with a one-line note and every row trains, which changes the rows a default
+ config trains on. `grpo` holds out and evaluates when `training.eval_steps` is set. It evaluates at the largest
+ multiple of `num_generations` that fits in the train batch, since TRL scores whole groups, and a note says so
+ when that differs from the train batch. Its evaluation rewards never reach the reward-hack detector, the
+ mitigation controller or the echo-trap detector. `ppo`, `online_dpo`, `unlearn` and `backend: mlx` refuse the
+ setting, and each refusal says why. The embedding trainer gains the evaluation step that Hugging Face's default
+ could not run on its anchor/positive batches.
diff --git a/docs/training.md b/docs/training.md
index fa0bfaf9..5e0cf740 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -48,12 +48,80 @@
- [Knowledge Distillation (BETA, v0.52.0)](#knowledge-distillation-beta-v0520)
- [EBFT + GDPO (BETA, v0.52.0)](#ebft--gdpo-beta-v0520)
- [gpt-oss `reasoning_effort` + `train_on_eot` (v0.52.0)](#gpt-oss-reasoning_effort--train_on_eot-v0520)
+- [Validation split & evaluation (`training.eval_steps`)](#validation-split--evaluation-trainingeval_steps)
- [Seeds & reproducibility (`training.seed`)](#seeds--reproducibility-trainingseed)
- [Rewind — which row spiked the loss (`soup rewind`)](#rewind--which-row-spiked-the-loss-soup-rewind)
- [Full fine-tuning (`lora.r: 0`)](#full-fine-tuning-lorar-0)
---
+## Validation split & evaluation (`training.eval_steps`)
+
+`data.val_split` (default `0.1`) holds that share of the rows out of training,
+and the run evaluates them:
+
+```yaml
+data:
+ val_split: 0.1 # the default
+training:
+ eval_steps: 50 # optional; unset = evaluate at the end of every epoch
+```
+
+- **Default: every epoch.** At the end of each epoch the trainer runs one pass
+ over the validation split and records `eval_loss`. It shows up as the **Val
+ loss** row on the live panel, is stored as `val_loss` in the run's metrics in
+ the experiment tracker, and is streamed as `TrainEvent.val_loss` to the Web UI.
+ The pass is a forward over the held-out rows, a few percent of the run at the
+ default split.
+- **`training.eval_steps: N`** evaluates every N optimizer steps instead,
+ counted after gradient accumulation like `save_steps`. The last step is
+ evaluated too when it is not a multiple of N, so a value larger than the run
+ still evaluates once.
+- **Batch size.** The evaluation runs at the resolved per-device train batch
+ (after `batch_size: auto`), not Hugging Face's default of 8, so a card sized
+ to train fits the evaluation too. Layer-streamed runs (`stream_layers: true`)
+ evaluate the same way, streaming the frozen layers as a training step does.
+- **`val_split: 0`** trains on every row and evaluates nothing, unless the data
+ brings its own validation split: an HF-hub dataset's `validation` split, or a
+ pre-tokenized cache's `val` / `validation` split.
+
+**Generation-based tasks (`grpo`, `ppo`, `online_dpo`).** Evaluating them means
+generating completions, which costs about as much per row as training on it. So
+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
+`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
+reward-hack detector, the mitigation controller or the echo-trap detector: they
+read training generations only. `ppo` and `online_dpo` refuse
+`training.eval_steps`: TRL's PPO loop never calls `evaluate()`, and online DPO's
+`evaluate()` crashes on prompt-only rows. A generation-based evaluation for
+those two is a separate feature.
+
+**Refused at config load.** `training.eval_steps` on `backend: mlx` (mlx-lm
+evaluates the split on its own cadence, #739), on `task: unlearn` (it trains on
+`forget_set` / `retain_set` and has no validation split), and with
+`val_split: 0` on local files or remote URIs, where there would be nothing to
+evaluate.
+
+**Evaluated but not tracked: `prm` and `moe_lora_routing`.** They attach no live
+training callback (#802), so their `eval_loss` reaches the trainer's log history
+and not the experiment tracker.
+
+Until #1223 no trainer on the transformers backend scheduled an evaluation: the
+default split was held out of training and never used, and `val_loss` stayed
+empty.
+
+---
+
## Seeds & reproducibility (`training.seed`)
Two knobs, both unset by default:
diff --git a/src/soup_cli/commands/cost.py b/src/soup_cli/commands/cost.py
index a9888fc9..b6b74bdd 100644
--- a/src/soup_cli/commands/cost.py
+++ b/src/soup_cli/commands/cost.py
@@ -38,6 +38,11 @@ def _get_dataset_size(cfg) -> tuple[int, bool]:
Returns (size, is_estimated). `is_estimated=True` means we fell back to
the default because the dataset could not be read; callers should warn.
"""
+ from soup_cli.utils.eval_schedule import effective_val_split
+
+ # #1223: the share `soup train` actually withholds, which is 0 for a task
+ # that does not evaluate its split.
+ split = 1.0 - effective_val_split(cfg)
train_path = cfg.data.train
# #443 — data.interleave: sum row counts across every local dataset
@@ -57,7 +62,6 @@ def _get_dataset_size(cfg) -> tuple[int, bool]:
pass
any_estimated = True
total += _DEFAULT_DATASET_SIZE
- split = 1.0 - cfg.data.val_split
return int(total * split), any_estimated
path = Path(train_path)
@@ -67,7 +71,6 @@ def _get_dataset_size(cfg) -> tuple[int, bool]:
from soup_cli.data.loader import load_raw_data
try:
data = load_raw_data(path)
- split = 1.0 - cfg.data.val_split
return int(len(data) * split), False
except (OSError, ValueError, KeyError):
pass
@@ -78,7 +81,6 @@ def _get_dataset_size(cfg) -> tuple[int, bool]:
from datasets import load_dataset_builder
builder = load_dataset_builder(train_path)
size = builder.info.splits["train"].num_examples
- split = 1.0 - cfg.data.val_split
return int(size * split), False
except (OSError, ValueError, KeyError, ImportError):
pass
diff --git a/src/soup_cli/commands/sweep.py b/src/soup_cli/commands/sweep.py
index fadd2cce..6202ae98 100644
--- a/src/soup_cli/commands/sweep.py
+++ b/src/soup_cli/commands/sweep.py
@@ -439,6 +439,7 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dic
from soup_cli.experiment.tracker import ExperimentTracker
from soup_cli.monitoring.display import TrainingDisplay
from soup_cli.trainer.sft import SFTTrainerWrapper
+ from soup_cli.utils.eval_schedule import loader_data_config, validation_notice
from soup_cli.utils.gpu import detect_device, get_gpu_info
cfg = SoupConfig(**config_dict)
@@ -447,9 +448,12 @@ def _run_single(base_cfg, params: dict, run_name: str, config_path: Path) -> dic
device, device_name = detect_device()
gpu_info = get_gpu_info()
- # Load data
+ # Load data -- the same split `soup train` would use (#1223).
+ val_notice = validation_notice(cfg)
+ if val_notice:
+ console.print(f"[yellow]Note:[/] {val_notice}")
dataset = load_dataset(
- cfg.data,
+ loader_data_config(cfg),
preserve_source_columns=cfg.task == "grpo",
)
console.print(f"[dim]Loaded {len(dataset['train'])} train samples[/]")
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index c17104ad..79f143ca 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1495,10 +1495,19 @@ def train(
console.print("[yellow]Cancelled.[/]")
raise typer.Exit()
+ # #1223: a split nothing evaluates is not withheld -- generation tasks train
+ # on every row unless training.eval_steps asks for evaluation.
+ from soup_cli.utils.eval_schedule import loader_data_config, validation_notice
+
+ run_data_config = loader_data_config(cfg)
+ val_notice = validation_notice(cfg)
+
if dry_run:
console.print("[yellow]Dry run - validating data...[/]")
+ if val_notice:
+ console.print(f"[yellow]Note:[/] {val_notice}")
dataset = load_dataset(
- cfg.data,
+ run_data_config,
preserve_source_columns=cfg.task == "grpo",
)
_refuse_empty_train(cfg.data, dataset)
@@ -1512,8 +1521,10 @@ def train(
# Load data
console.print("[dim]Loading dataset...[/]")
+ if val_notice:
+ console.print(f"[yellow]Note:[/] {val_notice}")
dataset = load_dataset(
- cfg.data,
+ run_data_config,
preserve_source_columns=cfg.task == "grpo",
)
_refuse_empty_train(cfg.data, dataset)
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 937388a3..4178fe4a 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -1315,6 +1315,30 @@ class TrainingConfig(BaseModel):
scheduler: str = Field(default="cosine", description="LR scheduler type")
save_steps: int = Field(default=100, description="Save checkpoint every N steps")
logging_steps: int = Field(default=10, description="Log metrics every N steps")
+ # #1223 — the validation split is evaluated at the end of every epoch by
+ # default; this switches to a step schedule. Unset rather than defaulted so
+ # "evaluate each epoch" and "evaluate every N steps" stay distinguishable,
+ # and so a generation-based task can tell "asked to evaluate" from not.
+ eval_steps: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description=(
+ "Evaluate the validation split every N optimizer steps (counted "
+ "after gradient accumulation, like save_steps). Unset = evaluate "
+ "at the end of every epoch. grpo evaluates only when this is set, "
+ "because an evaluation there generates completions. (#1223)"
+ ),
+ )
+
+ @field_validator("eval_steps", mode="before")
+ @classmethod
+ def _validate_eval_steps(cls, v: Any) -> Any:
+ """#1223 — `bool` subclasses `int`, so `eval_steps: true` would
+ silently become an evaluation every step."""
+ if isinstance(v, bool):
+ raise ValueError("training.eval_steps must be an int, not a bool")
+ return v
+
# DPO-specific
dpo_beta: float = Field(
default=0.1, gt=0, description="DPO beta — KL penalty coefficient"
@@ -4652,6 +4676,56 @@ UNSLOTH_SETUP_TASKS: frozenset[str] = frozenset({
#: for these tasks carries one of them literally (#795 review).
_BNB_QUANTIZATION_VALUES = frozenset({"4bit", "8bit"})
+#: A ``data.train`` entry with one of these suffixes is a local file. Duplicates
+#: ``loader.SUPPORTED_EXTENSIONS`` literally (not imported: loader.py imports
+#: DataConfig from this module, an import cycle, and carries the torch-adjacent
+#: deps this module stays light of). A suffix must be one of these to count as
+#: 'local' (#468 review fix) -- "any non-empty Path.suffix" misclassified every
+#: hub name with a version number (``teknium/OpenHermes-2.5``,
+#: ``mlfoundations/dclm-baseline-1.0``) as a local file.
+_LOCAL_FILE_EXTENSIONS = frozenset({".jsonl", ".json", ".csv", ".parquet", ".txt"})
+
+
+def _classify_data_train_entry(entry: str) -> str:
+ """``'remote'`` / ``'local'`` / ``'hub'`` for one ``data.train`` entry (#459).
+
+ loader.py keeps its own copy of this rule for the load-time dispatch
+ (``loader._classify_train_entry``); the two must agree, so the RULE
+ (suffix-in-allowlist / "://"-in-entry) is the only thing either site
+ encodes.
+
+ The "://" sniff is scheme-agnostic (#468 review fix), not an
+ is_remote_uri allowlist check -- it mirrors loader.py's
+ _looks_like_remote_uri. The scheme allowlist is enforced downstream, at
+ load time, by validate_remote_uri (refuses a non-allowlisted scheme BY
+ NAME); classifying only allowlisted schemes as 'remote' here let e.g. an
+ https://... entry with a familiar suffix fall through to 'local' and reach
+ hf_load unvalidated instead.
+ """
+ from pathlib import Path
+
+ if "://" in entry:
+ return "remote"
+ if Path(entry).suffix.lower() in _LOCAL_FILE_EXTENSIONS:
+ return "local"
+ return "hub"
+
+
+def _data_may_carry_its_own_validation_split(data: "DataConfig") -> bool:
+ """#1223 — can this data source supply a validation split without
+ ``data.val_split``?
+
+ Two can: an HF-hub dataset's own ``validation`` split, which the loader
+ passes through whatever ``val_split`` says, and a pre-tokenized cache's
+ ``val`` / ``validation`` split. Whether either exists is only known at load
+ time, so a config naming one is let through here and the trainer refuses
+ at setup if no rows arrived. Local files and remote URIs carry none.
+ """
+ if data.format == "pre_tokenized" and data.tokenized_path:
+ return True
+ entries = data.train if isinstance(data.train, list) else [data.train]
+ return any(_classify_data_train_entry(entry) == "hub" for entry in entries)
+
class SoupConfig(BaseModel):
"""Root config for soup.yaml."""
@@ -6472,8 +6546,6 @@ class SoupConfig(BaseModel):
keeps refusing — there is no decided answer for how a hub split
and a local file's row count should reconcile.
"""
- from pathlib import Path
-
from soup_cli.utils.data_pipeline import parse_interleave
data = self.data
@@ -6504,41 +6576,11 @@ class SoupConfig(BaseModel):
"per-source mixture ratio)"
)
- # #459 — classify every entry, then dispatch. Kept local to this
- # validator (rather than exported) since loader.py has its own
- # copy for the actual load-time dispatch; the two must agree,
- # so keep the classification RULE (suffix-in-allowlist /
- # "://"-in-entry) the only thing either site encodes, not the
- # classify function itself — see loader._classify_train_entry's
- # docstring.
- #
- # _local_file_extensions duplicates loader.SUPPORTED_EXTENSIONS
- # literally (not imported — that would import loader.py, which
- # imports DataConfig from this module, an import cycle; also
- # loader.py intentionally carries the torch-adjacent deps this
- # module stays light of). A suffix must be one of these to
- # count as 'local' (#468 review fix) — "any non-empty
- # Path.suffix" previously misclassified any hub name with a
- # version number (``teknium/OpenHermes-2.5``,
- # ``mlfoundations/dclm-baseline-1.0``) as a local file.
- _local_file_extensions = {".jsonl", ".json", ".csv", ".parquet", ".txt"}
-
- def _kind(entry: str) -> str:
- # Scheme-agnostic "://" sniff (#468 review fix), not an
- # is_remote_uri allowlist check — mirrors loader.py's
- # _looks_like_remote_uri. The scheme allowlist is enforced
- # downstream, at load time, by validate_remote_uri (refuses
- # a non-allowlisted scheme BY NAME); classifying only
- # allowlisted schemes as 'remote' here let e.g. an
- # https://... entry with a familiar suffix fall through to
- # 'local' and reach hf_load unvalidated instead.
- if "://" in entry:
- return "remote"
- if Path(entry).suffix.lower() in _local_file_extensions:
- return "local"
- return "hub"
-
- kinds = {_kind(entry) for entry in data.train}
+ # #459 — classify every entry, then dispatch. The rule lives in
+ # _classify_data_train_entry (module level since #1223, which
+ # reuses it); loader.py keeps its own copy for the load-time
+ # dispatch, and the two must agree.
+ kinds = {_classify_data_train_entry(entry) for entry in data.train}
if kinds == {"hub"}:
if data.streaming:
@@ -7578,6 +7620,45 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_eval_steps_compat(self) -> "SoupConfig":
+ """#1223 — refuse a ``training.eval_steps`` nothing would read.
+
+ mlx-lm runs its own validation loop over the split (#739), and three
+ tasks have no evaluation pass at all. Separately, a split of 0 on a
+ source that cannot carry its own validation split leaves no rows to
+ evaluate. A source that CAN carry one (an HF-hub dataset, a
+ pre-tokenized cache) is let through: whether it does is only known at
+ load time, and the trainer refuses at setup if no rows arrived.
+ """
+ from soup_cli.utils.eval_schedule import EVAL_STEPS_UNSUPPORTED_TASKS
+
+ if self.training.eval_steps is None:
+ return self
+ if self.backend == "mlx":
+ raise ValueError(
+ f"training.eval_steps is not supported for backend={self.backend!r} "
+ "because mlx-lm evaluates the validation split on its own cadence "
+ "(#1223)"
+ )
+ reason = EVAL_STEPS_UNSUPPORTED_TASKS.get(self.task)
+ if reason is not None:
+ raise ValueError(
+ f"training.eval_steps is not supported for task={self.task!r} "
+ f"because {reason} (#1223)"
+ )
+ if self.data.val_split == 0 and not _data_may_carry_its_own_validation_split(
+ self.data
+ ):
+ raise ValueError(
+ "training.eval_steps is set, but there is nothing to evaluate: "
+ "data.val_split is 0 and data.train names no source that carries "
+ "its own validation split (an HF-hub dataset or a pre-tokenized "
+ "cache). Set data.val_split above 0, or remove training.eval_steps "
+ "(#1223)"
+ )
+ return self
+
# --- Built-in templates ---
diff --git a/src/soup_cli/data/loader.py b/src/soup_cli/data/loader.py
index c57cb58a..a1321d77 100644
--- a/src/soup_cli/data/loader.py
+++ b/src/soup_cli/data/loader.py
@@ -376,7 +376,7 @@ def _classify_train_entry(value: str) -> str:
"""Classify one data.train list entry for interleave dispatch (#459).
Returns ``'remote'`` / ``'hub'`` / ``'local'``. Mirrors the identical
- classification inline in SoupConfig._validate_interleave_compat — kept
+ classification in schema._classify_data_train_entry — kept
as two copies of the same three-line rule (suffix-in-SUPPORTED_EXTENSIONS
check + "://"-in-entry check) rather than one shared function, since
schema.py must stay import-light (no torch-adjacent deps) and loader.py
diff --git a/src/soup_cli/trainer/asr.py b/src/soup_cli/trainer/asr.py
index 2fc2c3fb..1a3b7f21 100644
--- a/src/soup_cli/trainer/asr.py
+++ b/src/soup_cli/trainer/asr.py
@@ -31,6 +31,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig, TrainingConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -349,6 +350,7 @@ class AsrTrainerWrapper:
report_to=self.report_to,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
predict_with_generate=True,
remove_unused_columns=False,
**(self.fsdp_config or {}),
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index b8506f92..7115e680 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -20,6 +20,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -214,6 +215,7 @@ class BCOTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
beta=tcfg.bco_beta,
max_length=cfg.data.max_length,
diff --git a/src/soup_cli/trainer/classifier.py b/src/soup_cli/trainer/classifier.py
index a351322d..00a8beb6 100644
--- a/src/soup_cli/trainer/classifier.py
+++ b/src/soup_cli/trainer/classifier.py
@@ -33,6 +33,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -359,6 +360,7 @@ class ClassifierTrainerWrapper:
report_to=self.report_to,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
)
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index c1e52c74..265efc62 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -32,6 +32,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags, resolve_device_map
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -766,6 +767,7 @@ class DistillTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
)
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index 3a82331f..8742046f 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -10,6 +10,7 @@ from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.trainer.stream_setup import StreamingSetupMixin
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -205,6 +206,7 @@ class DPOTrainerWrapper(StreamingSetupMixin):
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
beta=tcfg.dpo_beta,
max_length=cfg.data.max_length,
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index ebae4a44..1e79964e 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -9,6 +9,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig, TrainingConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -197,6 +198,7 @@ class EmbeddingTrainerWrapper:
"dataloader_drop_last": (loss_type == "contrastive"),
"deepspeed": self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
}
if self.fsdp_config:
@@ -502,6 +504,20 @@ class _EmbeddingTrainer:
model, inputs, return_outputs
)
+ def prediction_step(
+ self, model, inputs, prediction_loss_only, ignore_keys=None
+ ):
+ # #1223: HF's default runs model(**inputs), and no model
+ # forward accepts the anchor_/positive_/negative_ keys this
+ # collator produces, so the first evaluation crashed. Score the
+ # same objective training optimises, under the same autocast.
+ import torch
+
+ inputs = self._prepare_inputs(inputs)
+ with torch.no_grad(), self.compute_loss_context_manager():
+ loss = embedding_trainer._compute_embedding_loss(model, inputs)
+ return loss.detach(), None, None
+
self._trainer = _CustomTrainer(
model=model,
args=args,
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index b50cc39d..4b667966 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -14,6 +14,7 @@ from soup_cli.config.schema import SoupConfig, TrainingConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils import final_answer
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -475,6 +476,25 @@ class GRPOTrainerWrapper:
"causing tensor size errors. A CUDA GPU is recommended.[/]"
)
+ # #1223: TRL evaluates num_generations completions per held-out prompt
+ # and refuses an eval batch that does not hold whole groups (a batch of
+ # 3 with 2 generations and gradient accumulation 2 trains, then raised
+ # at setup). Evaluate at the largest multiple of num_generations that
+ # fits in the train batch -- the bump above guarantees at least one.
+ eval_kwargs = training_eval_kwargs(
+ cfg, eval_ds, batch_size=batch_size - batch_size % num_gen
+ )
+ if (
+ eval_kwargs["eval_strategy"] != "no"
+ and eval_kwargs["per_device_eval_batch_size"] != batch_size
+ ):
+ console.print(
+ "[yellow]Note:[/] grpo evaluates at batch "
+ f"{eval_kwargs['per_device_eval_batch_size']}, not the train batch "
+ f"{batch_size}: TRL's evaluation needs whole groups of "
+ f"num_generations={num_gen} completions."
+ )
+
# --- GRPO config ---
grpo_kwargs = {
"output_dir": str(output_dir),
@@ -495,6 +515,7 @@ class GRPOTrainerWrapper:
"remove_unused_columns": False,
"deepspeed": self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **eval_kwargs,
**(self.fsdp_config or {}),
"beta": tcfg.grpo_beta,
"num_generations": tcfg.num_generations,
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 6664a109..4e37fe7a 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -10,6 +10,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -162,6 +163,7 @@ class IPOTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
loss_type="ipo",
beta=tcfg.ipo_tau,
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index 1cd8eaa4..f365e2da 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -11,6 +11,7 @@ from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.trainer.stream_setup import StreamingSetupMixin
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -196,6 +197,7 @@ class KTOTrainerWrapper(StreamingSetupMixin):
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
beta=tcfg.kto_beta,
max_length=cfg.data.max_length,
diff --git a/src/soup_cli/trainer/mole_routing.py b/src/soup_cli/trainer/mole_routing.py
index 881b4fb6..59e79107 100644
--- a/src/soup_cli/trainer/mole_routing.py
+++ b/src/soup_cli/trainer/mole_routing.py
@@ -25,6 +25,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -383,6 +384,7 @@ class MoleRoutingTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_rows, batch_size=bs),
)
mole_trainer_cls = make_mole_trainer_class(Trainer)
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index 2558bafb..5663e1f5 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -11,6 +11,7 @@ from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.trainer.stream_setup import StreamingSetupMixin
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -205,6 +206,7 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
beta=tcfg.orpo_beta,
max_length=cfg.data.max_length,
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index b6c69bd1..79f76eb5 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -9,6 +9,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -183,6 +184,7 @@ class PretrainTrainerWrapper:
"remove_unused_columns": False,
"deepspeed": self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
}
# FSDP2 — alternative to DeepSpeed
diff --git a/src/soup_cli/trainer/prm.py b/src/soup_cli/trainer/prm.py
index 2f2f2c05..0b743d6d 100644
--- a/src/soup_cli/trainer/prm.py
+++ b/src/soup_cli/trainer/prm.py
@@ -26,6 +26,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags, resolve_base_load_dtype
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -335,6 +336,7 @@ class PRMTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_rows, batch_size=bs),
)
prm_trainer_cls = make_prm_trainer_class(Trainer)
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index a8940685..1f23cce9 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -16,6 +16,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -163,6 +164,7 @@ class RewardModelTrainerWrapper:
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
max_length=cfg.data.max_length,
)
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index 54eb7e38..c5e8be30 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -13,6 +13,7 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.trainer.stream_setup import StreamingSetupMixin
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -972,6 +973,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
# than a new default. #353 moved the resolution into utils.seeding
# so the other 17 task wrappers resolve it identically.
**training_seed_kwargs(tcfg),
+ # #1223: evaluate the split handed to the trainer below, at the
+ # resolved train batch. Before this nothing set eval_strategy, so
+ # the default val_split was withheld and never evaluated.
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
}
# FSDP2 — alternative to DeepSpeed. The helper also enables
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index db6f3aca..451dccc8 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -11,6 +11,7 @@ from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.trainer.stream_setup import StreamingSetupMixin
+from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
@@ -203,6 +204,7 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
**training_seed_kwargs(tcfg),
+ **training_eval_kwargs(cfg, eval_ds, batch_size=batch_size),
**(self.fsdp_config or {}),
loss_type="simpo",
cpo_alpha=tcfg.cpo_alpha,
diff --git a/src/soup_cli/utils/eval_schedule.py b/src/soup_cli/utils/eval_schedule.py
new file mode 100644
index 00000000..1a58a934
--- /dev/null
+++ b/src/soup_cli/utils/eval_schedule.py
@@ -0,0 +1,155 @@
+"""Evaluate the validation split that every task wrapper receives (#1223).
+
+``data.val_split`` (default 0.1) moves that share of the rows out of training,
+and the task wrappers hand the result to their trainer as ``eval_dataset``. No
+wrapper set ``eval_strategy``, whose Hugging Face default is ``"no"``, so
+``Trainer.evaluate()`` never ran. The rows were withheld and used for nothing,
+and the validation-loss sinks #713 added (the metrics column,
+``TrainEvent.val_loss``, the display row) never received a value on the
+transformers backend.
+
+The policy this module encodes:
+
+* A trainer that receives a non-empty validation split evaluates it at the end
+ of every epoch, or every ``training.eval_steps`` optimizer steps when that is
+ set. Hugging Face also evaluates once more at the last step when that step
+ is not a multiple of ``eval_steps``, so a value larger than the run still
+ evaluates once.
+* The evaluation batch is the resolved per-device TRAIN batch. Hugging Face's
+ default of 8 would run out of memory on a card sized to train at 1.
+* Generation-based tasks (:data:`GENERATION_EVAL_TASKS`) do not evaluate by
+ default, because an evaluation there means generating completions. They do
+ not withhold rows either: ``data.val_split`` is ignored for them, with a
+ notice, unless ``training.eval_steps`` asks for evaluation.
+* ``backend: mlx`` is untouched. mlx-lm runs its own validation loop over the
+ split (#739), so the loader keeps withholding it there.
+
+Import-light on purpose: ``config/schema.py`` imports the task sets, so nothing
+here may pull torch, transformers or the data stack.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ from soup_cli.config.schema import DataConfig, SoupConfig
+
+#: Tasks where an evaluation pass means generating completions, so it costs as
+#: much per row as training does. They evaluate only when asked to.
+GENERATION_EVAL_TASKS: frozenset[str] = frozenset({"grpo", "ppo", "online_dpo"})
+
+#: 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
+#: online_dpo -- scoring completions for held-out prompts -- is a separate
+#: feature, not something this setting can switch on.
+EVAL_STEPS_UNSUPPORTED_TASKS: dict[str, str] = {
+ "ppo": (
+ "TRL's PPO loop never calls evaluate(); a generation-based evaluation "
+ "for ppo is a separate feature"
+ ),
+ "online_dpo": (
+ "online DPO's evaluate() crashes on prompt-only rows; a "
+ "generation-based evaluation for online_dpo is a separate feature"
+ ),
+ "unlearn": (
+ "unlearning trains on data.forget_set and data.retain_set and never "
+ "evaluates a validation split"
+ ),
+}
+
+
+def evaluates_by_default(task: str) -> bool:
+ """Whether a run of ``task`` evaluates its validation split unasked."""
+ return task not in GENERATION_EVAL_TASKS
+
+
+def holds_out_validation(cfg: SoupConfig) -> bool:
+ """Whether the loader should carve ``data.val_split`` out of the training rows.
+
+ A split that nothing evaluates is not carved out: those rows train instead.
+ """
+ if cfg.data.val_split <= 0:
+ return False
+ if getattr(cfg, "backend", None) == "mlx":
+ return True
+ return evaluates_by_default(cfg.task) or cfg.training.eval_steps is not None
+
+
+def loader_data_config(cfg: SoupConfig) -> DataConfig:
+ """The ``DataConfig`` to hand ``load_dataset`` for this run.
+
+ ``cfg.data`` itself, unless the run would withhold rows that nothing
+ evaluates; then a copy with ``val_split`` at 0, so every row trains. A
+ dataset's own validation split (an HF-hub ``validation`` split) is not
+ withheld from training, so it still arrives either way.
+ """
+ if cfg.data.val_split <= 0 or holds_out_validation(cfg):
+ return cfg.data
+ return cfg.data.model_copy(update={"val_split": 0.0})
+
+
+def effective_val_split(cfg: SoupConfig) -> float:
+ """The fraction of the rows this run actually withholds from training."""
+ return loader_data_config(cfg).val_split
+
+
+def validation_notice(cfg: SoupConfig) -> Optional[str]:
+ """One line explaining an ignored ``data.val_split``, or ``None``."""
+ if cfg.data.val_split <= 0 or holds_out_validation(cfg):
+ return None
+ notice = (
+ f"data.val_split is ignored for task={cfg.task} because evaluation "
+ "means generation, so every row trains."
+ )
+ if cfg.task not in EVAL_STEPS_UNSUPPORTED_TASKS:
+ notice += " Set training.eval_steps to evaluate on a held-out split."
+ return notice
+
+
+def _has_rows(dataset: Any) -> bool:
+ if dataset is None:
+ return False
+ try:
+ return len(dataset) > 0
+ except TypeError: # an iterable dataset of unknown length
+ return True
+
+
+def training_eval_kwargs(
+ cfg: SoupConfig, eval_dataset: Any, *, batch_size: int
+) -> dict[str, Any]:
+ """Evaluation kwargs for any ``TrainingArguments`` subclass.
+
+ ``eval_dataset`` is what the wrapper is about to hand its trainer, after its
+ own row preparation, and ``batch_size`` the resolved per-device train batch
+ (never ``"auto"``). Raises ``ValueError`` when ``training.eval_steps`` asks
+ for an evaluation that has no rows to run on.
+ """
+ eval_steps = getattr(cfg.training, "eval_steps", None)
+ kwargs: dict[str, Any] = {"per_device_eval_batch_size": int(batch_size)}
+ if not _has_rows(eval_dataset):
+ if eval_steps is not None:
+ if cfg.data.val_split > 0:
+ why = "every validation row was dropped while the dataset was prepared"
+ else:
+ why = (
+ "data.val_split is 0 and the dataset carries no validation "
+ "split of its own"
+ )
+ raise ValueError(
+ f"training.eval_steps={eval_steps} asks for evaluation, but this "
+ f"run has no validation rows: {why}. Set data.val_split above 0, "
+ "or remove training.eval_steps (#1223)."
+ )
+ kwargs["eval_strategy"] = "no"
+ return kwargs
+ if eval_steps is not None:
+ kwargs["eval_strategy"] = "steps"
+ kwargs["eval_steps"] = int(eval_steps)
+ elif evaluates_by_default(cfg.task):
+ kwargs["eval_strategy"] = "epoch"
+ else:
+ kwargs["eval_strategy"] = "no"
+ return kwargs
diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.py
index a73fbb8f..f5ae08e1 100644
--- a/src/soup_cli/utils/peft_wiring.py
+++ b/src/soup_cli/utils/peft_wiring.py
@@ -1236,6 +1236,14 @@ def attach_rl_callbacks(
except (TypeError, ValueError) as exc:
logger.debug("attach echo-trap callback rejected: %s", exc)
+ # #1223: the detectors above read ``buffer`` at every step end. An
+ # evaluation pass calls the same wrapped reward functions on held-out
+ # prompts, so keep it out of the buffer they read.
+ if buffer is not None:
+ from soup_cli.utils.rl_signal_buffer import exclude_evaluation
+
+ exclude_evaluation(trainer, buffer)
+
return attached
diff --git a/src/soup_cli/utils/reward_hacking.py b/src/soup_cli/utils/reward_hacking.py
index 785cb7bb..5845f452 100644
--- a/src/soup_cli/utils/reward_hacking.py
+++ b/src/soup_cli/utils/reward_hacking.py
@@ -571,6 +571,10 @@ class _RewardHackCallback_body: # type: ignore[misc, valid-type] # noqa: N801
return control
if not isinstance(logs, dict):
return control
+ # #1223: an evaluation's log record carries eval_-prefixed metrics about
+ # held-out prompts, not a training step. Skip the whole record.
+ if any(isinstance(key, str) and key.startswith("eval_") for key in logs):
+ return control
mean = logs.get("reward")
std = logs.get("reward_std", 0.0)
if not isinstance(mean, (int, float)) or isinstance(mean, bool):
diff --git a/src/soup_cli/utils/rl_signal_buffer.py b/src/soup_cli/utils/rl_signal_buffer.py
index 25b20ce8..4099fd48 100644
--- a/src/soup_cli/utils/rl_signal_buffer.py
+++ b/src/soup_cli/utils/rl_signal_buffer.py
@@ -22,6 +22,13 @@ Design notes:
correct (TRL logs ``rewards/<func_name>``).
- No torch import at module top (pure Python; the buffer stores plain
floats + strings).
+- Evaluation stays out (#1223). GRPO's evaluation pass calls the SAME
+ wrapped reward functions on held-out prompts. Those rewards describe no
+ training step, so :func:`exclude_evaluation` pauses the buffer for the
+ duration of ``trainer.evaluate`` and every record made inside is dropped.
+ The boundary is the call itself rather than ``model.training``: TRL's
+ paged-generation path flips the model back to train mode after generating,
+ even during an evaluation.
Security:
- Bounded buffers (``_MAX_COMPLETIONS`` / ``_MAX_COMPLETION_CHARS``) so a
@@ -31,9 +38,11 @@ Security:
from __future__ import annotations
+import contextlib
+import functools
import math
import threading
-from typing import Any, Optional, Sequence
+from typing import Any, Iterator, Optional, Sequence
_MAX_COMPLETIONS = 1024
_MAX_COMPLETION_CHARS = 100_000
@@ -94,6 +103,8 @@ class RLSignalBuffer:
self._lock = threading.Lock()
self._completions: list[str] = []
self._per_func: dict[str, list[Optional[float]]] = {}
+ # Depth of open ``paused()`` blocks; records are dropped while > 0.
+ self._paused = 0
def record(
self,
@@ -107,7 +118,7 @@ class RLSignalBuffer:
Completions are normalised to strings and capped at
``_MAX_COMPLETIONS``. Within a single GRPO step every reward
function sees the *same* completions, so overwriting on each call
- is correct.
+ is correct. A call made inside :meth:`paused` is dropped.
"""
texts: list[str] = []
if completions is not None:
@@ -120,10 +131,29 @@ class RLSignalBuffer:
coerced = _coerce_rewards(rewards)
name = func_name if isinstance(func_name, str) and func_name else "reward"
with self._lock:
+ # Checked where the write happens, under the same lock paused()
+ # takes, so a record cannot slip in as a pause begins.
+ if self._paused:
+ return
if texts:
self._completions = texts
self._per_func[name] = coerced
+ @contextlib.contextmanager
+ def paused(self) -> Iterator[None]:
+ """Drop every :meth:`record` made inside the block (#1223).
+
+ Re-entrant, and the pause ends even if the block raises, so a failed
+ evaluation cannot leave the detectors blind for the rest of the run.
+ """
+ with self._lock:
+ self._paused += 1
+ try:
+ yield
+ finally:
+ with self._lock:
+ self._paused -= 1
+
def snapshot(self) -> dict[str, Any]:
"""Return a consistent copy of the latest step signal.
@@ -219,3 +249,23 @@ def wrap_reward_funcs(reward_funcs: Any, buffer: RLSignalBuffer) -> Any:
if isinstance(reward_funcs, (list, tuple)):
return [_make_capturing(fn, buffer) for fn in reward_funcs]
return _make_capturing(reward_funcs, buffer)
+
+
+def exclude_evaluation(trainer: Any, buffer: RLSignalBuffer) -> None:
+ """Keep ``trainer``'s evaluation passes out of ``buffer`` (#1223).
+
+ Wraps ``trainer.evaluate`` on the instance -- HF's training loop reaches it
+ through ``self.evaluate`` -- so the buffer is paused for the whole pass,
+ ``on_evaluate`` callbacks included. The detectors then only ever read
+ rewards from training generations, whatever TRL's generation cadence.
+ """
+ evaluate = getattr(trainer, "evaluate", None)
+ if not callable(evaluate):
+ return
+
+ @functools.wraps(evaluate)
+ def _evaluate(*args: Any, **kwargs: Any) -> Any:
+ with buffer.paused():
+ return evaluate(*args, **kwargs)
+
+ trainer.evaluate = _evaluate
diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.json
index 71d1c6d6..6a617b8d 100644
--- a/tests/fixtures/recipe_config_snapshots.json
+++ b/tests/fixtures/recipe_config_snapshots.json
@@ -103,6 +103,7 @@
"training.embedding_temperature": 0.05,
"training.epochs": 3,
"training.eval_gate": null,
+ "training.eval_steps": null,
"training.expand_layers": null,
"training.forgetting_benchmark": "mini_mmlu",
"training.forgetting_detection": false,
diff --git a/tests/test_issue1223_eval_steps_config.py b/tests/test_issue1223_eval_steps_config.py
new file mode 100644
index 00000000..d3d83143
--- /dev/null
+++ b/tests/test_issue1223_eval_steps_config.py
@@ -0,0 +1,545 @@
+"""#1223 — the validation split is evaluated, or it is not withheld.
+
+``data.val_split: 0.1`` moved 10% of the rows out of training on every run, and
+no trainer set ``eval_strategy``, whose Hugging Face default is ``"no"``. The
+rows were withheld and never evaluated.
+
+This file covers the config and loader half of the fix:
+
+* ``training.eval_steps`` -- the new field, its bounds, and the footgun refusals
+ (a value that nothing would read);
+* the shared helper that decides the evaluation kwargs, the per-run loader
+ config and the notice;
+* the loader decision as ``soup train`` and ``soup sweep`` drive it: generation
+ tasks (``grpo``, ``ppo``, ``online_dpo``) do not withhold rows unless
+ ``training.eval_steps`` asks for evaluation, and everything else is unchanged.
+
+The trainer half (every wrapper schedules evaluation, a real run records
+``val_loss``) is ``test_issue1223_evaluate_val_split.py``.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+from unittest.mock import MagicMock
+from unittest.mock import patch as mock_patch
+
+import pytest
+
+from tests.conftest import strip_ansi
+
+_CHAT_ROWS = 20
+
+
+def _plain(text: str | None) -> str:
+ """ANSI-stripped and whitespace-collapsed: Rich colours and wraps CLI output."""
+ return " ".join(strip_ansi(text).split())
+
+
+def _load(yaml_text: str):
+ from soup_cli.config.loader import load_config_from_string
+
+ return load_config_from_string(yaml_text)
+
+
+def _yaml(
+ *,
+ task: str = "sft",
+ train: str = "chat.jsonl",
+ backend: str = "transformers",
+ data_extra: str = "",
+ training_extra: str = "",
+) -> str:
+ extra = {
+ "grpo": " num_generations: 2\n reward_fn: format\n",
+ "ppo": " reward_fn: format\n",
+ "online_dpo": " online_dpo_judge: 'ollama://m'\n",
+ "unlearn": " unlearn_method: npo\n",
+ }.get(task, "")
+ data_block = f"data:\n train: {train}\n max_length: 64\n{data_extra}"
+ if task == "unlearn":
+ data_block += " forget_set: forget.jsonl\n"
+ return (
+ "base: some-org/tiny-model\n"
+ f"task: {task}\n"
+ f"backend: {backend}\n"
+ f"{data_block}"
+ "training:\n"
+ " epochs: 1\n"
+ " batch_size: 2\n"
+ " quantization: none\n"
+ f"{extra}"
+ f"{training_extra}"
+ "output: ./out\n"
+ )
+
+
+# ==========================================================================
+# training.eval_steps -- the field
+# ==========================================================================
+class TestEvalStepsField:
+ def test_unset_by_default(self):
+ cfg = _load(_yaml())
+ assert cfg.training.eval_steps is None
+
+ @pytest.mark.parametrize("value", [1, 7, 500])
+ def test_a_positive_int_is_accepted(self, value):
+ cfg = _load(_yaml(training_extra=f" eval_steps: {value}\n"))
+ assert cfg.training.eval_steps == value
+
+ @pytest.mark.parametrize("value", [0, -3])
+ def test_zero_and_negatives_are_refused(self, value):
+ with pytest.raises(ValueError, match="eval_steps") as info:
+ _load(_yaml(training_extra=f" eval_steps: {value}\n"))
+ assert "greater than or equal to 1" in str(info.value)
+
+ def test_a_yaml_bool_is_refused_rather_than_read_as_one(self):
+ with pytest.raises(ValueError, match="eval_steps must be an int, not a bool"):
+ _load(_yaml(training_extra=" eval_steps: true\n"))
+
+
+class TestEvalStepsFootguns:
+ """Every refusal names the setting, the reason, and the issue."""
+
+ def test_nothing_to_evaluate_on_a_local_file_with_val_split_zero(self):
+ with pytest.raises(ValueError) as info:
+ _load(_yaml(data_extra=" val_split: 0\n", training_extra=" eval_steps: 5\n"))
+ message = str(info.value)
+ assert "training.eval_steps" in message
+ assert "data.val_split is 0" in message
+ assert "#1223" in message
+
+ def test_nothing_to_evaluate_on_an_interleaved_list_of_local_files(self):
+ with pytest.raises(ValueError, match="data.val_split is 0"):
+ _load(
+ _yaml(
+ train="[a.jsonl, b.jsonl]",
+ data_extra=" val_split: 0\n interleave: concat\n",
+ training_extra=" eval_steps: 5\n",
+ )
+ )
+
+ @pytest.mark.parametrize(
+ "train", ["https://example.com/train.jsonl", "s3://bucket/train.jsonl"]
+ )
+ def test_nothing_to_evaluate_on_a_remote_uri_with_val_split_zero(self, train):
+ """A remote URI is a file, not a hub dataset: it brings no validation
+ split of its own, so it is refused like a local file."""
+ with pytest.raises(ValueError, match="data.val_split is 0"):
+ _load(
+ _yaml(
+ train=train,
+ data_extra=" val_split: 0\n",
+ training_extra=" eval_steps: 5\n",
+ )
+ )
+
+ def test_a_hub_dataset_may_carry_its_own_validation_split(self):
+ """The control. An HF-hub dataset's own ``validation`` split reaches the
+ trainer whatever ``val_split`` says, so refusing here would refuse a
+ config that evaluates. Whether the split exists is only known at load."""
+ cfg = _load(
+ _yaml(
+ train="some-org/some-dataset",
+ data_extra=" val_split: 0\n",
+ training_extra=" eval_steps: 5\n",
+ )
+ )
+ assert cfg.training.eval_steps == 5
+
+ def test_a_pre_tokenized_cache_may_carry_its_own_validation_split(self):
+ cfg = _load(
+ _yaml(
+ data_extra=(
+ " val_split: 0\n format: pre_tokenized\n tokenized_path: ./cache\n"
+ ),
+ training_extra=" eval_steps: 5\n",
+ )
+ )
+ assert cfg.training.eval_steps == 5
+
+ def test_a_positive_val_split_is_enough(self):
+ cfg = _load(_yaml(data_extra=" val_split: 0.2\n", training_extra=" eval_steps: 5\n"))
+ assert cfg.training.eval_steps == 5
+
+ @pytest.mark.parametrize(
+ ("task", "reason"),
+ [
+ ("ppo", "TRL's PPO loop never calls evaluate()"),
+ ("online_dpo", "online DPO's evaluate() crashes on prompt-only rows"),
+ ("unlearn", "never evaluates a validation split"),
+ ],
+ )
+ def test_tasks_without_an_evaluation_pass_refuse_it(self, task, reason):
+ with pytest.raises(ValueError) as info:
+ _load(_yaml(task=task, training_extra=" eval_steps: 5\n"))
+ message = str(info.value)
+ assert f"training.eval_steps is not supported for task='{task}'" in message
+ assert reason in message
+ assert "#1223" in message
+
+ @pytest.mark.parametrize("task", ["ppo", "online_dpo"])
+ def test_generation_based_evaluation_is_named_as_a_separate_feature(self, task):
+ with pytest.raises(ValueError) as info:
+ _load(_yaml(task=task, training_extra=" eval_steps: 5\n"))
+ assert f"a generation-based evaluation for {task} is a separate feature" in str(
+ info.value
+ )
+
+ def test_grpo_accepts_it_as_the_opt_in(self):
+ cfg = _load(_yaml(task="grpo", training_extra=" eval_steps: 5\n"))
+ assert cfg.training.eval_steps == 5
+
+ def test_mlx_refuses_it_because_mlx_lm_evaluates_on_its_own_cadence(self):
+ with pytest.raises(ValueError) as info:
+ _load(_yaml(backend="mlx", training_extra=" eval_steps: 5\n"))
+ message = str(info.value)
+ assert "training.eval_steps is not supported for backend='mlx'" in message
+ assert "#1223" in message
+
+ def test_mlx_without_it_still_loads(self):
+ """The control for the refusal above: MLX itself is untouched."""
+ cfg = _load(_yaml(backend="mlx"))
+ assert cfg.training.eval_steps is None
+
+
+# ==========================================================================
+# the helper
+# ==========================================================================
+class _Rows:
+ def __init__(self, n: int):
+ self.n = n
+
+ def __len__(self) -> int:
+ return self.n
+
+
+class _Unsized:
+ """An iterable dataset whose length is not known."""
+
+ def __iter__(self):
+ return iter(())
+
+
+class TestTrainingEvalKwargs:
+ def test_a_non_empty_split_evaluates_every_epoch_at_the_train_batch(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml())
+ assert training_eval_kwargs(cfg, _Rows(2), batch_size=3) == {
+ "per_device_eval_batch_size": 3,
+ "eval_strategy": "epoch",
+ }
+
+ def test_eval_steps_switches_to_a_step_schedule(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml(training_extra=" eval_steps: 4\n"))
+ assert training_eval_kwargs(cfg, _Rows(2), batch_size=1) == {
+ "per_device_eval_batch_size": 1,
+ "eval_strategy": "steps",
+ "eval_steps": 4,
+ }
+
+ def test_a_generation_task_does_not_evaluate_unasked(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml(task="grpo"))
+ kwargs = training_eval_kwargs(cfg, _Rows(2), batch_size=2)
+ assert kwargs["eval_strategy"] == "no"
+ assert kwargs["per_device_eval_batch_size"] == 2
+
+ def test_a_generation_task_evaluates_when_asked(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml(task="grpo", training_extra=" eval_steps: 3\n"))
+ kwargs = training_eval_kwargs(cfg, _Rows(2), batch_size=2)
+ assert (kwargs["eval_strategy"], kwargs["eval_steps"]) == ("steps", 3)
+
+ @pytest.mark.parametrize("dataset", [None, _Rows(0)], ids=["none", "empty"])
+ def test_no_rows_means_no_evaluation(self, dataset):
+ """HF raises on a step schedule with no eval_dataset, and divides by the
+ row count of an empty one; neither is a reason to fail a run nobody
+ asked to evaluate."""
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml())
+ kwargs = training_eval_kwargs(cfg, dataset, batch_size=2)
+ assert kwargs["eval_strategy"] == "no"
+
+ def test_an_unsized_dataset_counts_as_rows(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml())
+ assert training_eval_kwargs(cfg, _Unsized(), batch_size=2)["eval_strategy"] == "epoch"
+
+ def test_eval_steps_with_no_rows_refuses_naming_the_empty_hub_split(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(
+ _yaml(
+ train="some-org/some-dataset",
+ data_extra=" val_split: 0\n",
+ training_extra=" eval_steps: 5\n",
+ )
+ )
+ with pytest.raises(ValueError) as info:
+ training_eval_kwargs(cfg, None, batch_size=2)
+ message = str(info.value)
+ assert "training.eval_steps=5 asks for evaluation" in message
+ assert "carries no validation split of its own" in message
+ assert "#1223" in message
+
+ def test_eval_steps_with_every_row_dropped_says_so(self):
+ from soup_cli.utils.eval_schedule import training_eval_kwargs
+
+ cfg = _load(_yaml(training_extra=" eval_steps: 5\n"))
+ with pytest.raises(ValueError, match="every validation row was dropped"):
+ training_eval_kwargs(cfg, _Rows(0), batch_size=2)
+
+
+class TestTheLoaderDecision:
+ @pytest.mark.parametrize("task", ["sft", "dpo", "pretrain", "distill", "classifier"])
+ def test_evaluating_tasks_keep_their_split(self, task):
+ from soup_cli.utils.eval_schedule import (
+ effective_val_split,
+ holds_out_validation,
+ loader_data_config,
+ )
+
+ training = " teacher_model: some-org/teacher\n" if task == "distill" else ""
+ training += " num_labels: 2\n" if task == "classifier" else ""
+ cfg = _load(_yaml(task=task, training_extra=training))
+ assert holds_out_validation(cfg) is True
+ assert loader_data_config(cfg) is cfg.data
+ assert effective_val_split(cfg) == pytest.approx(0.1)
+
+ @pytest.mark.parametrize("task", ["grpo", "ppo", "online_dpo"])
+ def test_generation_tasks_withhold_nothing_by_default(self, task):
+ from soup_cli.utils.eval_schedule import (
+ effective_val_split,
+ holds_out_validation,
+ loader_data_config,
+ )
+
+ cfg = _load(_yaml(task=task))
+ assert holds_out_validation(cfg) is False
+ data_cfg = loader_data_config(cfg)
+ assert data_cfg.val_split == 0.0
+ assert effective_val_split(cfg) == 0.0
+ # A copy, never the config itself: the recorded run config keeps the
+ # value the user wrote.
+ assert cfg.data.val_split == pytest.approx(0.1)
+ assert data_cfg.train == cfg.data.train
+
+ def test_grpo_with_eval_steps_holds_the_split_out(self):
+ from soup_cli.utils.eval_schedule import holds_out_validation, loader_data_config
+
+ cfg = _load(_yaml(task="grpo", training_extra=" eval_steps: 4\n"))
+ assert holds_out_validation(cfg) is True
+ assert loader_data_config(cfg) is cfg.data
+
+ def test_val_split_zero_holds_nothing_out(self):
+ from soup_cli.utils.eval_schedule import holds_out_validation, loader_data_config
+
+ cfg = _load(_yaml(data_extra=" val_split: 0\n"))
+ assert holds_out_validation(cfg) is False
+ assert loader_data_config(cfg) is cfg.data
+
+ def test_mlx_is_unchanged(self):
+ """mlx-lm evaluates the split itself (#739), so it stays withheld there,
+ whatever the task. MLX admits only sft today, so the generation-task
+ case is built with ``model_copy`` (no re-validation): the branch has to
+ hold the day MLX ships one."""
+ from soup_cli.utils.eval_schedule import holds_out_validation, loader_data_config
+
+ assert holds_out_validation(_load(_yaml(backend="mlx"))) is True
+ mlx_grpo = _load(_yaml(task="grpo")).model_copy(update={"backend": "mlx"})
+ assert holds_out_validation(mlx_grpo) is True
+ assert loader_data_config(mlx_grpo) is mlx_grpo.data
+
+
+class TestTheNotice:
+ def test_grpo_names_the_ignored_setting_and_the_way_out(self):
+ from soup_cli.utils.eval_schedule import validation_notice
+
+ notice = validation_notice(_load(_yaml(task="grpo")))
+ assert notice == (
+ "data.val_split is ignored for task=grpo because evaluation means "
+ "generation, so every row trains. Set training.eval_steps to evaluate "
+ "on a held-out split."
+ )
+
+ @pytest.mark.parametrize("task", ["ppo", "online_dpo"])
+ def test_tasks_that_refuse_eval_steps_are_not_told_to_set_it(self, task):
+ from soup_cli.utils.eval_schedule import validation_notice
+
+ notice = validation_notice(_load(_yaml(task=task)))
+ assert notice is not None
+ assert f"data.val_split is ignored for task={task}" in notice
+ assert "eval_steps" not in notice
+
+ def test_no_notice_when_nothing_is_ignored(self):
+ from soup_cli.utils.eval_schedule import validation_notice
+
+ assert validation_notice(_load(_yaml())) is None
+ assert validation_notice(_load(_yaml(task="grpo", data_extra=" val_split: 0\n"))) is None
+ assert (
+ validation_notice(_load(_yaml(task="grpo", training_extra=" eval_steps: 4\n")))
+ is None
+ )
+
+ def test_the_module_imports_without_torch(self):
+ """``config/schema.py`` imports it, so it must stay import-light."""
+ import subprocess
+ import sys
+
+ code = (
+ "import sys;"
+ "sys.modules['torch'] = None;"
+ "sys.modules['transformers'] = None;"
+ "import soup_cli.utils.eval_schedule as s;"
+ "print(sorted(s.GENERATION_EVAL_TASKS))"
+ )
+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
+ assert out.returncode == 0, out.stderr
+ # A plain print, but routed through the ANSI-strip helper all the same:
+ # the #1068 suite guard reads any `.stdout` assertion as CLI output.
+ assert _plain(out.stdout) == "['grpo', 'online_dpo', 'ppo']"
+
+
+# ==========================================================================
+# the loader decision, as `soup train --dry-run` drives it
+# ==========================================================================
+def _write_chat_rows(directory: Path, n: int = _CHAT_ROWS) -> None:
+ rows = [
+ {
+ "messages": [
+ {"role": "user", "content": f"question {i}"},
+ {"role": "assistant", "content": f"answer {i}"},
+ ]
+ }
+ for i in range(n)
+ ]
+ (directory / "chat.jsonl").write_text(
+ "\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8"
+ )
+
+
+def _dry_run(tmp_path, monkeypatch, yaml_text: str) -> str:
+ from typer.testing import CliRunner
+
+ import soup_cli.commands.train as train_cmd
+ from soup_cli.cli import app
+
+ # The row counts pinned here do not depend on the machine, but a visible card
+ # does: on a dev box with a GPU the hardware-fit gate refuses before the dry
+ # run prints anything. Answer the two probes the way a CPU runner does (the
+ # #1212 tests stub them the same way): unknown VRAM skips the gate.
+ monkeypatch.setattr(train_cmd, "detect_device", lambda backend=None: ("cpu", "CPU"))
+ monkeypatch.setattr(
+ train_cmd,
+ "get_gpu_info",
+ lambda backend=None: {"memory_total": "0 MB", "memory_total_bytes": 0, "gpu_count": 0},
+ )
+ monkeypatch.chdir(tmp_path)
+ _write_chat_rows(tmp_path)
+ (tmp_path / "soup.yaml").write_text(yaml_text, encoding="utf-8")
+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run", "--yes"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ return _plain(result.output)
+
+
+class TestDryRunCounts:
+ @pytest.mark.parametrize("task", ["grpo", "ppo", "online_dpo"])
+ def test_generation_tasks_train_on_every_row(self, tmp_path, monkeypatch, task):
+ out = _dry_run(tmp_path, monkeypatch, _yaml(task=task, data_extra=" format: chatml\n"))
+ assert f"Data OK: {_CHAT_ROWS} train samples" in out
+ assert "Val:" not in out
+ assert f"data.val_split is ignored for task={task}" in out
+
+ def test_the_grpo_notice_offers_eval_steps(self, tmp_path, monkeypatch):
+ out = _dry_run(tmp_path, monkeypatch, _yaml(task="grpo", data_extra=" format: chatml\n"))
+ assert "Set training.eval_steps to evaluate on a held-out split." in out
+
+ def test_grpo_with_eval_steps_holds_the_split_out(self, tmp_path, monkeypatch):
+ out = _dry_run(
+ tmp_path,
+ monkeypatch,
+ _yaml(
+ task="grpo",
+ data_extra=" format: chatml\n",
+ training_extra=" eval_steps: 2\n",
+ ),
+ )
+ assert f"Data OK: {_CHAT_ROWS - 2} train samples" in out
+ assert "Val: 2 samples" in out
+ assert "is ignored" not in out
+
+ def test_control_sft_still_holds_the_split_out(self, tmp_path, monkeypatch):
+ """Nothing changes for a task that now evaluates its split."""
+ out = _dry_run(tmp_path, monkeypatch, _yaml(data_extra=" format: chatml\n"))
+ assert f"Data OK: {_CHAT_ROWS - 2} train samples" in out
+ assert "Val: 2 samples" in out
+ assert "is ignored" not in out
+
+
+class TestSweepAndCostFollowTheSameRule:
+ """`soup sweep` and `soup cost` reason about the same split `soup train` uses."""
+
+ @pytest.mark.parametrize(("task", "expected"), [("grpo", 0.0), ("sft", 0.1)])
+ def test_sweep_hands_the_loader_the_run_split(self, task, expected):
+ from soup_cli.commands.sweep import _run_single
+
+ cfg = _load(_yaml(task=task, data_extra=" format: chatml\n"))
+ wrapper = {
+ "grpo": "soup_cli.trainer.grpo.GRPOTrainerWrapper",
+ "sft": "soup_cli.trainer.sft.SFTTrainerWrapper",
+ }[task]
+ fake_result = {
+ "initial_loss": 1.0,
+ "final_loss": 0.5,
+ "total_steps": 1,
+ "duration_secs": 1.0,
+ "output_dir": "./out",
+ "duration": "0m",
+ }
+ with mock_patch(
+ "soup_cli.data.loader.load_dataset", return_value={"train": [{"x": 1}]}
+ ) as mock_load, mock_patch(
+ "soup_cli.utils.gpu.detect_device", return_value=("cpu", "CPU")
+ ), mock_patch(
+ "soup_cli.utils.gpu.get_gpu_info",
+ return_value={"memory_total": "0 MB", "memory_total_bytes": 0},
+ ), mock_patch(
+ "soup_cli.experiment.tracker.ExperimentTracker"
+ ) as mock_tracker_cls, mock_patch(
+ "soup_cli.monitoring.display.TrainingDisplay"
+ ), mock_patch(f"{wrapper}.setup"), mock_patch(
+ f"{wrapper}.train", return_value=fake_result
+ ):
+ mock_tracker = MagicMock()
+ mock_tracker.start_run.return_value = "run-1"
+ mock_tracker_cls.return_value = mock_tracker
+ _run_single(cfg, {}, "sweep_1", None)
+
+ data_cfg = mock_load.call_args.args[0]
+ assert data_cfg.val_split == pytest.approx(expected)
+
+ @pytest.mark.parametrize(("task", "rows"), [("grpo", 20), ("sft", 18)])
+ def test_cost_counts_the_rows_that_train(self, tmp_path, monkeypatch, task, rows):
+ from soup_cli.commands.cost import _get_dataset_size
+
+ monkeypatch.chdir(tmp_path)
+ _write_chat_rows(tmp_path)
+ cfg = _load(_yaml(task=task, data_extra=" format: chatml\n"))
+ assert _get_dataset_size(cfg) == (rows, False)
+
+
+def test_the_plain_helper_collapses_what_rich_splits():
+ """Guard for `_plain`: Rich wraps and colours per character on Linux CI."""
+ raw = "\x1b[1mData\x1b[0m OK:\n 20 train\x1b[36m samples\x1b[0m"
+ assert _plain(raw) == "Data OK: 20 train samples"
+ assert re.search(r"\x1b", _plain(raw)) is None
diff --git a/tests/test_issue1223_evaluate_val_split.py b/tests/test_issue1223_evaluate_val_split.py
new file mode 100644
index 00000000..82234761
--- /dev/null
+++ b/tests/test_issue1223_evaluate_val_split.py
@@ -0,0 +1,778 @@
+"""#1223 — every trainer that receives a validation split evaluates it.
+
+``data.val_split: 0.1`` moved 10% of the rows out of training and every task
+wrapper passed them on as ``eval_dataset``, but none set ``eval_strategy``, whose
+Hugging Face default is ``"no"``. ``Trainer.evaluate()`` never ran, so the rows
+were used for nothing and #713's validation-loss sinks never got a value.
+
+Driven for real on CPU, per task, because a per-task omission is the failure
+mode: `setup()` is called on a tiny checkpoint, the schedule the trainer actually
+received is asserted, and then the run trains, which is the only way to know the
+evaluation pass works on that trainer. Two did not: the embedding trainer's
+default ``prediction_step`` called ``model(**inputs)`` with its own batch keys,
+and TRL's BCO evaluation fails before its first training step (which a schedule
+never reaches).
+
+The config and loader half is ``test_issue1223_eval_steps_config.py``.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+
+import pytest
+
+from tests import conftest
+from tests.conftest import strip_ansi
+
+
+def _requires_train_extra():
+ for mod in ("torch", "transformers", "peft", "trl", "datasets"):
+ pytest.importorskip(mod, reason=f"{mod} is only in the [train] extra")
+
+
[email protected](autouse=True)
+def _no_wandb(monkeypatch):
+ monkeypatch.setenv("WANDB_DISABLED", "true")
+
+
+def _plain(text: str | None) -> str:
+ """ANSI-stripped and whitespace-collapsed: Rich colours and wraps CLI output."""
+ return " ".join(strip_ansi(text).split())
+
+
+# --------------------------------------------------------------------------
+# fixtures -- a real, tiny checkpoint on disk. Duplicated from
+# test_issue353_seed_every_task.py deliberately, as the suites around it do, so
+# this file stays runnable on its own.
+# --------------------------------------------------------------------------
+def _tiny_llama_dir(root: Path, vocab: int = 64, hidden: int = 64) -> 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=vocab,
+ hidden_size=hidden,
+ intermediate_size=hidden * 2,
+ 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 _chat_rows(n):
+ return [
+ {
+ "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "good answer"},
+ ]
+ }
+ for _ in range(n)
+ ]
+
+
+def _pref_rows(n):
+ return [{"prompt": "hi", "chosen": " good answer", "rejected": " bad"} for _ in range(n)]
+
+
+def _kto_rows(n):
+ return [{"prompt": "hi", "completion": " good answer", "label": i % 2 == 0} for i in range(n)]
+
+
+def _text_rows(n):
+ return [{"text": "hello world good answer"} for _ in range(n)]
+
+
+def _label_rows(n):
+ return [{"text": "hello world", "label": i % 2} for i in range(n)]
+
+
+def _embedding_rows(n):
+ return [{"anchor": "hello world", "positive": "good answer"} for _ in range(n)]
+
+
+def _prm_rows(n):
+ return [
+ {"prompt": "hi", "completions": ["good", "answer"], "labels": [1.0, 0.0]}
+ for _ in range(n)
+ ]
+
+
+def _prompt_rows(n):
+ return [{"prompt": "hi"} for _ in range(n)]
+
+
+#: task -> (module, wrapper class, rows, extra `training:` keys). The issue's
+#: list minus grpo, which is generation-based and has its own tests below.
+_EVALUATING = {
+ "sft": ("soup_cli.trainer.sft", "SFTTrainerWrapper", _chat_rows, {}),
+ "pretrain": ("soup_cli.trainer.pretrain", "PretrainTrainerWrapper", _text_rows, {}),
+ "dpo": ("soup_cli.trainer.dpo", "DPOTrainerWrapper", _pref_rows, {}),
+ "ipo": ("soup_cli.trainer.ipo", "IPOTrainerWrapper", _pref_rows, {}),
+ "kto": ("soup_cli.trainer.kto", "KTOTrainerWrapper", _kto_rows, {}),
+ "orpo": ("soup_cli.trainer.orpo", "ORPOTrainerWrapper", _pref_rows, {}),
+ "simpo": ("soup_cli.trainer.simpo", "SimPOTrainerWrapper", _pref_rows, {}),
+ "bco": ("soup_cli.trainer.bco", "BCOTrainerWrapper", _pref_rows, {}),
+ "distill": ("soup_cli.trainer.distill", "DistillTrainerWrapper", _chat_rows, {}),
+ # batch 1: the tiny checkpoint has no pad id, and a sequence-classification
+ # head refuses batches > 1 without one -- in training as in evaluation.
+ "classifier": (
+ "soup_cli.trainer.classifier",
+ "ClassifierTrainerWrapper",
+ _label_rows,
+ {"num_labels": 2, "batch_size": 1},
+ ),
+ "embedding": ("soup_cli.trainer.embedding", "EmbeddingTrainerWrapper", _embedding_rows, {}),
+ "reward_model": (
+ "soup_cli.trainer.reward_model",
+ "RewardModelTrainerWrapper",
+ _pref_rows,
+ {},
+ ),
+ "prm": ("soup_cli.trainer.prm", "PRMTrainerWrapper", _prm_rows, {}),
+ "moe_lora_routing": (
+ "soup_cli.trainer.mole_routing",
+ "MoleRoutingTrainerWrapper",
+ _text_rows,
+ {"mole_task_adapters": ["./adapter_a", "./adapter_b"]},
+ ),
+ "asr": ("soup_cli.trainer.asr", "AsrTrainerWrapper", None, {}),
+}
+
+#: The wrappers the issue lists as receiving a validation split.
+_ISSUE_TASKS = frozenset({
+ "sft", "pretrain", "dpo", "ipo", "kto", "orpo", "simpo", "bco", "grpo",
+ "distill", "classifier", "embedding", "reward_model", "prm",
+ "moe_lora_routing", "asr",
+})
+
+#: These build their Trainer inside `train()`, so the schedule can only be
+#: read once the run has happened.
+_BUILDS_IN_TRAIN = frozenset({"prm", "moe_lora_routing"})
+
+_TINY_WHISPER = "hf-internal-testing/tiny-random-WhisperForConditionalGeneration"
+_TRAIN_ROWS = 8
+_VAL_ROWS = 2
+
+
+def _write_sine_wav(path: Path, seconds: float = 0.5, sr: int = 16000) -> None:
+ import numpy as np
+ import soundfile as sf
+
+ t = np.linspace(0.0, seconds, int(sr * seconds), endpoint=False)
+ sf.write(str(path), (0.1 * np.sin(2 * np.pi * 220.0 * t)).astype("float32"), sr)
+
+
+def _asr_rows(root: Path, n: int, prefix: str) -> list[dict]:
+ rows = []
+ for i in range(n):
+ clip = root / f"{prefix}{i}.wav"
+ _write_sine_wav(clip)
+ rows.append({"audio": str(clip), "text": "hello world"})
+ return rows
+
+
+def _tiny_whisper_dir(root: Path) -> str:
+ """The hub's tiny-random Whisper, resized so it can actually train.
+
+ As shipped it takes 60 mel frames, but the feature extractor pads every clip
+ to 30 s (3000 frames), and its vocabulary stops below the ids the tokenizer
+ gives Whisper's own special tokens, so a training step on it fails before
+ any loss. Same config (d_model 16, 2 layers) with room for 1500 encoder
+ positions and the tokenizer's full vocabulary, fresh random weights, the hub
+ copy's processor.
+ """
+ import torch
+ from transformers import WhisperConfig, WhisperForConditionalGeneration, WhisperProcessor
+
+ processor = WhisperProcessor.from_pretrained(_TINY_WHISPER)
+ config = WhisperConfig.from_pretrained(_TINY_WHISPER)
+ config.max_source_positions = 1500
+ config.vocab_size = len(processor.tokenizer)
+ torch.manual_seed(7)
+ target = root / "whisper"
+ WhisperForConditionalGeneration(config).save_pretrained(str(target))
+ processor.save_pretrained(str(target))
+ return str(target)
+
+
+def _write_task_adapters(root: Path, weights: str) -> None:
+ """Two tiny LoRA adapters for the MoLE gate to route between."""
+ from peft import LoraConfig, get_peft_model
+ from transformers import AutoModelForCausalLM
+
+ for name in ("adapter_a", "adapter_b"):
+ base = AutoModelForCausalLM.from_pretrained(weights)
+ peft_model = get_peft_model(
+ base,
+ LoraConfig(
+ r=4, lora_alpha=8, target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM"
+ ),
+ )
+ peft_model.save_pretrained(str(root / name))
+
+
+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 in _EVALUATING:
+ training.update(_EVALUATING[task][3])
+ if task == "distill":
+ training["teacher_model"] = base
+ if task == "grpo":
+ training.update({"num_generations": 2, "reward_fn": "format"})
+ if task in {"asr", "prm"}:
+ # prm fine-tunes every base parameter and refuses a lora block; asr's
+ # LoRA is its own opt-in (asr_lora).
+ training.pop("lora")
+ training.update(training_over)
+ data = {"train": "train.jsonl", "max_length": 64}
+ if task in {"sft", "dpo", "ipo", "kto", "orpo", "simpo", "bco", "distill", "grpo"}:
+ data["chat_template"] = "chatml"
+ if task == "asr":
+ data["format"] = "asr"
+ return load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": base,
+ "task": task,
+ "backend": "transformers",
+ "modality": "text",
+ "data": data,
+ "training": training,
+ "output": str(out),
+ }
+ )
+ )
+
+
+def _build(tmp_path, monkeypatch, task, *, n_train=_TRAIN_ROWS, n_val=_VAL_ROWS, **over):
+ """A real wrapper over a real tiny checkpoint, `setup()` called with the
+ train/val shape the loader hands over when `data.val_split` > 0."""
+ import importlib
+
+ monkeypatch.chdir(tmp_path)
+ if task == "asr":
+ pytest.importorskip("soundfile")
+ try: # the tiny Whisper config and processor come from the hub
+ base = _tiny_whisper_dir(tmp_path)
+ except OSError as exc:
+ pytest.skip(f"tiny whisper unavailable: {exc}")
+ dataset = {"train": _asr_rows(tmp_path, n_train, "t")}
+ if n_val:
+ dataset["val"] = _asr_rows(tmp_path, n_val, "v")
+ else:
+ base = _tiny_llama_dir(tmp_path)
+ rows = _EVALUATING[task][2] if task in _EVALUATING else _prompt_rows
+ dataset = {"train": rows(n_train)}
+ if n_val:
+ dataset["val"] = rows(n_val)
+ if task == "moe_lora_routing":
+ _write_task_adapters(tmp_path, base)
+ if task in _EVALUATING:
+ module, cls_name = _EVALUATING[task][:2]
+ else:
+ module, cls_name = "soup_cli.trainer.grpo", "GRPOTrainerWrapper"
+ cfg = _cfg(task, base, tmp_path / "out", **over)
+ wrapper = getattr(importlib.import_module(module), cls_name)(cfg, device="cpu")
+ wrapper.setup(dataset)
+ return wrapper
+
+
+def _trainer_default_device_is_cpu() -> bool:
+ """True when transformers' default device is the CPU these wrappers use.
+
+ Every wrapper here is built with ``device="cpu"``, but transformers moves
+ the model to its own default device: CUDA when a card is visible, MPS on
+ Apple Silicon. A resident model moves whole and does not notice. A streamed
+ model keeps its decoder weights where the wrapper streams them, so a
+ streamed forward then mixes devices ("found at least two devices, mps:0 and
+ cpu" on the macOS runners). ``test_v07200.py`` skips its CPU streaming steps
+ on MPS for the same reason.
+
+ CUDA is read through the suite's one probe, ``conftest.cuda_available``
+ (#833 forbids a private one), looked up at call time so the condition test
+ below can pin it.
+ """
+ import torch
+
+ if conftest.cuda_available():
+ return False
+ backend = getattr(torch.backends, "mps", None)
+ return not (backend is not None and backend.is_available())
+
+
+def _hf_trainer(wrapper):
+ """`embedding` composes HF's Trainer instead of subclassing it."""
+ trainer = wrapper.trainer
+ return getattr(trainer, "_trainer", trainer)
+
+
+def _strategy(args) -> str:
+ return getattr(args.eval_strategy, "value", args.eval_strategy)
+
+
+def _eval_entries(trainer) -> list[dict]:
+ return [e for e in trainer.state.log_history if "eval_loss" in e]
+
+
+def _run(wrapper, task):
+ """Train, and return the HF trainer that ran."""
+ if task in _BUILDS_IN_TRAIN:
+ wrapper.train()
+ else:
+ _hf_trainer(wrapper).train()
+ return _hf_trainer(wrapper)
+
+
+# ==========================================================================
+# the acceptance matrix
+# ==========================================================================
+class TestEveryWrapperEvaluatesItsSplit:
+ """Whenever the trainer receives a non-empty validation split, its schedule
+ is not ``"no"``, the pass runs at the train batch, and it logs a finite
+ ``eval_loss``. ``grpo`` is the generation-based exception, pinned below."""
+
+ @pytest.mark.parametrize("task", sorted(_EVALUATING))
+ def test_the_split_is_scheduled_and_evaluated(self, tmp_path, monkeypatch, task):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, task)
+ if task not in _BUILDS_IN_TRAIN:
+ trainer = _hf_trainer(wrapper)
+ assert trainer.eval_dataset is not None and len(trainer.eval_dataset) > 0
+ assert _strategy(trainer.args) == "epoch", (
+ f"{task}: a non-empty validation split with eval_strategy="
+ f"{_strategy(trainer.args)!r} is withheld and never evaluated"
+ )
+ trainer = _run(wrapper, task)
+ args = trainer.args
+ assert _strategy(args) == "epoch", task
+ assert args.per_device_eval_batch_size == args.per_device_train_batch_size, (
+ f"{task}: evaluation runs at batch {args.per_device_eval_batch_size}, "
+ f"training at {args.per_device_train_batch_size}"
+ )
+ evals = _eval_entries(trainer)
+ assert len(evals) == 1, f"{task}: one epoch should evaluate once, got {evals}"
+ assert math.isfinite(evals[0]["eval_loss"]), (task, evals)
+
+ def test_the_matrix_covers_the_issue_list(self):
+ assert set(_EVALUATING) | {"grpo"} == _ISSUE_TASKS
+
+
+class TestGrpoIsGenerationBased:
+ """Documented as not evaluating by default, and the loader withholds nothing
+ for it, so no row is spent on an evaluation that never runs."""
+
+ def test_the_loader_withholds_nothing(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ from soup_cli.data.loader import load_dataset
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+ from soup_cli.utils.eval_schedule import loader_data_config
+
+ monkeypatch.chdir(tmp_path)
+ weights = _tiny_llama_dir(tmp_path)
+ (tmp_path / "train.jsonl").write_text(
+ "\n".join(json.dumps(r) for r in _chat_rows(10)) + "\n", encoding="utf-8"
+ )
+ cfg = _cfg("grpo", weights, tmp_path / "out")
+ assert cfg.data.val_split == pytest.approx(0.1)
+ # Exactly what `soup train` hands the wrapper for this config.
+ dataset = load_dataset(loader_data_config(cfg), preserve_source_columns=True)
+ assert len(dataset["train"]) == 10
+ assert not dataset.get("val")
+
+ wrapper = GRPOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup(dataset)
+ assert len(wrapper.trainer.train_dataset) == 10
+ assert wrapper.trainer.eval_dataset is None
+ assert _strategy(wrapper.trainer.args) == "no"
+
+ def test_a_split_it_is_handed_anyway_is_not_evaluated_unasked(self, tmp_path, monkeypatch):
+ """An HF-hub dataset's own validation split still arrives; it is not
+ withheld from training, and grpo does not generate over it unasked."""
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, "grpo")
+ assert len(wrapper.trainer.eval_dataset) == _VAL_ROWS
+ assert _strategy(wrapper.trainer.args) == "no"
+
+ def test_eval_steps_opts_in_and_the_pass_runs(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, "grpo", eval_steps=2)
+ args = wrapper.trainer.args
+ assert (_strategy(args), args.eval_steps) == ("steps", 2)
+ assert args.per_device_eval_batch_size == args.per_device_train_batch_size
+ args.max_steps = 2
+ wrapper.trainer.train()
+ evals = _eval_entries(wrapper.trainer)
+ assert [e["step"] for e in evals] == [2]
+ assert math.isfinite(evals[0]["eval_loss"])
+
+
+class TestGrpoEvalBatchHoldsWholeGroups:
+ """TRL evaluates ``num_generations`` completions per held-out prompt and
+ refuses an eval batch that splits a group. Batch 3 with 2 generations
+ trains (gradient accumulation 2 makes the generation batch 6) but raised at
+ setup, on one process, as soon as ``eval_steps`` was set."""
+
+ _NOTE = (
+ "grpo evaluates at batch 2, not the train batch 3: TRL's evaluation needs "
+ "whole groups of num_generations=2 completions."
+ )
+
+ def _build3(self, tmp_path, monkeypatch, **over):
+ return _build(
+ tmp_path, monkeypatch, "grpo", batch_size=3, gradient_accumulation_steps=2, **over
+ )
+
+ def test_the_eval_batch_rounds_down_to_whole_groups(self, tmp_path, monkeypatch, capsys):
+ _requires_train_extra()
+ wrapper = self._build3(tmp_path, monkeypatch, eval_steps=1)
+ args = wrapper.trainer.args
+ assert (args.per_device_train_batch_size, args.per_device_eval_batch_size) == (3, 2)
+ assert self._NOTE in _plain(capsys.readouterr().out)
+ args.max_steps = 1
+ wrapper.trainer.train()
+ assert [e["step"] for e in _eval_entries(wrapper.trainer)] == [1]
+
+ def test_no_note_when_nothing_is_evaluated(self, tmp_path, monkeypatch, capsys):
+ _requires_train_extra()
+ self._build3(tmp_path, monkeypatch)
+ assert "grpo evaluates at batch" not in _plain(capsys.readouterr().out)
+
+ def test_no_note_when_the_train_batch_already_holds_whole_groups(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, "grpo", batch_size=4, eval_steps=1)
+ assert wrapper.trainer.args.per_device_eval_batch_size == 4
+ assert "grpo evaluates at batch" not in _plain(capsys.readouterr().out)
+
+
+class TestLayerStreamingEvaluates:
+ """``stream_layers: true`` is not special-cased: the streamed model runs the
+ evaluation pass on CPU, through the streamed decoder layers, and the loss it
+ reports is the resident model's (same checkpoint, same rows)."""
+
+ def test_a_streamed_run_evaluates_its_split(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ if not _trainer_default_device_is_cpu():
+ pytest.skip(
+ "transformers places the model on cuda/mps here while the wrapper "
+ "streams on cpu (see _trainer_default_device_is_cpu)"
+ )
+ monkeypatch.setenv("SOUP_LAYER_STREAM_CACHE_DIR", str(tmp_path / "cache"))
+ (tmp_path / "streamed").mkdir()
+ (tmp_path / "resident").mkdir()
+ streamed = _build(
+ tmp_path / "streamed",
+ monkeypatch,
+ "sft",
+ n_train=4,
+ batch_size=1,
+ stream_layers=True,
+ gradient_checkpointing=True,
+ )
+ assert _strategy(streamed.trainer.args) == "epoch"
+ loads = streamed._stream_runtime.pool.loads
+ streamed_loss = streamed.trainer.evaluate()["eval_loss"]
+ assert streamed._stream_runtime.pool.loads > loads, "no layer was streamed"
+
+ resident = _build(tmp_path / "resident", monkeypatch, "sft", n_train=4, batch_size=1)
+ resident_loss = resident.trainer.evaluate()["eval_loss"]
+ assert streamed_loss == pytest.approx(resident_loss, rel=1e-4)
+
+ streamed.trainer.train()
+ evals = _eval_entries(streamed.trainer)
+ assert len(evals) == 1 and math.isfinite(evals[0]["eval_loss"]), evals
+
+
+class TestTheStreamingSkipStaysNarrow:
+ """The streaming test above runs only where transformers' default device is
+ the CPU its wrapper streams on. Both edges are pinned: a condition that
+ quietly widened would skip the test everywhere, and a skipped test is the
+ same colour as a passing one."""
+
+ @pytest.mark.parametrize(
+ ("cuda", "mps", "runs"),
+ [(False, False, True), (False, True, False), (True, False, False), (True, True, False)],
+ )
+ def test_the_condition(self, monkeypatch, cuda, mps, runs):
+ torch = pytest.importorskip("torch")
+ monkeypatch.setattr(conftest, "cuda_available", lambda: cuda)
+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: mps)
+ assert _trainer_default_device_is_cpu() is runs
+
+
+class TestNoSplitNoEvaluation:
+ """The control: with no validation rows nothing is scheduled, so a run with
+ ``val_split: 0`` behaves exactly as it did."""
+
+ @pytest.mark.parametrize("task", ["sft", "dpo"])
+ def test_no_rows_no_schedule(self, tmp_path, monkeypatch, task):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, task, n_val=0)
+ trainer = _hf_trainer(wrapper)
+ assert trainer.eval_dataset is None
+ assert _strategy(trainer.args) == "no"
+ trainer.train()
+ assert _eval_entries(trainer) == []
+
+
+# ==========================================================================
+# the evaluation batch is the resolved train batch
+# ==========================================================================
+class TestTheEvalBatchIsTheTrainBatch:
+ """HF's default eval batch is 8. A card sized to train at 1 runs out of
+ memory at 8, so the pass must run at whatever the train batch resolved to,
+ including after ``batch_size: auto``."""
+
+ @pytest.mark.parametrize("batch", [1, 3])
+ def test_an_explicit_batch(self, tmp_path, monkeypatch, batch):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, "sft", batch_size=batch)
+ assert wrapper.trainer.args.per_device_train_batch_size == batch
+ assert wrapper.trainer.args.per_device_eval_batch_size == batch
+
+ def test_auto_resolves_before_the_eval_batch_is_taken(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ import soup_cli.utils.batch_probe as batch_probe
+
+ monkeypatch.setattr(batch_probe, "pick_batch_size", lambda **_: 3)
+ wrapper = _build(tmp_path, monkeypatch, "sft", batch_size="auto")
+ assert wrapper.trainer.args.per_device_train_batch_size == 3
+ assert wrapper.trainer.args.per_device_eval_batch_size == 3
+
+ def test_auto_on_a_preference_wrapper(self, tmp_path, monkeypatch):
+ """DPO halves its estimate for the chosen/rejected pair; the eval batch
+ follows the halved value, not the estimate and not HF's 8."""
+ _requires_train_extra()
+ import soup_cli.trainer.dpo as dpo
+
+ monkeypatch.setattr(dpo, "estimate_batch_size", lambda **_: 6)
+ wrapper = _build(tmp_path, monkeypatch, "dpo", batch_size="auto")
+ assert wrapper.trainer.args.per_device_train_batch_size == 3
+ assert wrapper.trainer.args.per_device_eval_batch_size == 3
+
+
+# ==========================================================================
+# the schedule variants
+# ==========================================================================
+class TestScheduleVariants:
+ """16 train rows at batch 2 make 8 micro-batches per epoch. Steps counted
+ are optimizer steps, i.e. after gradient accumulation."""
+
+ @pytest.mark.parametrize(
+ ("training", "expected_steps"),
+ [
+ pytest.param({"eval_steps": 3}, [3, 6, 8], id="eval_steps-below-total"),
+ # Larger than the run: Hugging Face still evaluates at the last step.
+ pytest.param({"eval_steps": 100}, [8], id="eval_steps-above-total"),
+ pytest.param(
+ {"eval_steps": 2, "gradient_accumulation_steps": 2}, [2, 4], id="grad-accum"
+ ),
+ pytest.param(
+ {"epochs": 2, "gradient_accumulation_steps": 2}, [4, 8], id="epoch-ends"
+ ),
+ pytest.param(
+ {"epochs": 2, "eval_steps": 3}, [3, 6, 9, 12, 15, 16], id="epochs-with-steps"
+ ),
+ ],
+ )
+ def test_evaluations_land_where_the_schedule_says(
+ self, tmp_path, monkeypatch, training, expected_steps
+ ):
+ _requires_train_extra()
+ wrapper = _build(tmp_path, monkeypatch, "sft", n_train=16, **training)
+ wrapper.trainer.train()
+ steps = [e["step"] for e in _eval_entries(wrapper.trainer)]
+ assert steps == expected_steps
+
+
+# ==========================================================================
+# end to end: `soup train` records the validation loss
+# ==========================================================================
+class TestSoupTrainRecordsValLoss:
+ """The issue's acceptance run, through the CLI: default ``val_split``, a real
+ tiny SFT run on CPU, and every sink #713 added receiving a value."""
+
+ _ROWS = 20
+
+ def _run_cli(self, tmp_path, monkeypatch, *, val_split: str = ""):
+ import transformers
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ weights = _tiny_llama_dir(tmp_path)
+ rows = [
+ {
+ "messages": [
+ {"role": "user", "content": f"hi {i}"},
+ {"role": "assistant", "content": "good answer"},
+ ]
+ }
+ for i in range(self._ROWS)
+ ]
+ (tmp_path / "chat.jsonl").write_text(
+ "\n".join(json.dumps(r) for r in rows) + "\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"
+ f"{val_split}"
+ "training:\n"
+ " epochs: 2\n"
+ " batch_size: 2\n"
+ " gradient_accumulation_steps: 1\n"
+ " logging_steps: 1\n"
+ " save_steps: 1000\n"
+ " quantization: none\n"
+ " lora:\n"
+ " r: 4\n"
+ " alpha: 8\n"
+ " target_modules: [q_proj, v_proj]\n"
+ "output: ./out\n",
+ encoding="utf-8",
+ )
+ seen = {"evaluate_calls": 0, "log_history": None}
+ real_train = transformers.Trainer.train
+ real_evaluate = transformers.Trainer.evaluate
+
+ def train(self, *args, **kwargs):
+ out = real_train(self, *args, **kwargs)
+ seen["log_history"] = list(self.state.log_history)
+ return out
+
+ def evaluate(self, *args, **kwargs):
+ seen["evaluate_calls"] += 1
+ return real_evaluate(self, *args, **kwargs)
+
+ monkeypatch.setattr(transformers.Trainer, "train", train)
+ monkeypatch.setattr(transformers.Trainer, "evaluate", evaluate)
+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+ from soup_cli.experiment.tracker import ExperimentTracker
+
+ tracker = ExperimentTracker()
+ runs = tracker.list_runs()
+ assert len(runs) == 1, runs
+ metrics = tracker.get_metrics(runs[0]["run_id"])
+ return seen, metrics, _plain(result.output)
+
+ def test_the_default_split_is_evaluated_and_recorded(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ seen, metrics, out = self._run_cli(tmp_path, monkeypatch)
+ assert f"Loaded: {self._ROWS - 2} train samples" in out
+ # Two epochs, evaluated at the end of each.
+ assert seen["evaluate_calls"] == 2
+ evals = [e for e in seen["log_history"] if "eval_loss" in e]
+ assert len(evals) == 2
+ assert all(math.isfinite(e["eval_loss"]) for e in evals)
+ recorded = [row["val_loss"] for row in metrics if row["val_loss"] is not None]
+ assert len(recorded) == 2
+ assert recorded == pytest.approx([e["eval_loss"] for e in evals])
+ assert "Val loss" in out
+
+ def test_control_val_split_zero_evaluates_nothing_and_withholds_nothing(
+ self, tmp_path, monkeypatch
+ ):
+ _requires_train_extra()
+ seen, metrics, out = self._run_cli(tmp_path, monkeypatch, val_split=" val_split: 0\n")
+ assert f"Loaded: {self._ROWS} train samples" in out
+ assert seen["evaluate_calls"] == 0
+ assert not [e for e in seen["log_history"] if "eval_loss" in e]
+ assert metrics, "the run logged no metrics at all"
+ assert all(row["val_loss"] is None for row in metrics)
+ assert "Val loss" not in out
+
+
+# ==========================================================================
+# the guard that survives the next wrapper being added
+# ==========================================================================
+def _trainer_sources() -> dict[str, str]:
+ import importlib.util
+
+ spec = importlib.util.find_spec("soup_cli.trainer")
+ return {
+ path.stem: path.read_text(encoding="utf-8")
+ for path in sorted(Path(spec.origin).parent.glob("*.py"))
+ }
+
+
+class TestEveryWrapperUsesTheHelper:
+ """A wrapper that hands its trainer an ``eval_dataset`` must build its
+ schedule with ``training_eval_kwargs``, or it withholds rows it never
+ evaluates. Derived from the source, so a new wrapper is covered unasked."""
+
+ @staticmethod
+ def _passing_an_eval_dataset() -> list[str]:
+ return [
+ name
+ for name, source in _trainer_sources().items()
+ if "eval_dataset=" in source or '"eval_dataset":' in source
+ ]
+
+ def test_the_derivation_found_the_wrappers(self):
+ """Non-vacuity: an empty derivation would pass the test below."""
+ assert {"sft", "grpo", "prm", "asr", "embedding"} <= set(
+ self._passing_an_eval_dataset()
+ )
+
+ def test_each_one_threads_the_helper(self):
+ sources = _trainer_sources()
+ missing = [
+ name
+ for name in self._passing_an_eval_dataset()
+ if "training_eval_kwargs(" not in sources[name]
+ ]
+ assert not missing, (
+ f"soup_cli.trainer.{missing} pass an eval_dataset without "
+ "training_eval_kwargs(), so the split is withheld and never evaluated"
+ )
diff --git a/tests/test_issue1223_rl_signal_eval_isolation.py b/tests/test_issue1223_rl_signal_eval_isolation.py
new file mode 100644
index 00000000..f987a576
--- /dev/null
+++ b/tests/test_issue1223_rl_signal_eval_isolation.py
@@ -0,0 +1,466 @@
+"""#1223 — an evaluation pass must not reach the reward-hack / echo-trap signal.
+
+With ``training.eval_steps`` set, GRPO evaluates held-out prompts by generating
+completions and scoring them with the SAME wrapped reward functions training
+uses. Those functions also feed the shared ``RLSignalBuffer`` that the
+reward-hack detector, the mitigation controller and the echo-trap detector read
+at every step end. An evaluation's rewards describe held-out prompts, not a
+training step, so they must never reach those readers.
+
+When is the leak real? TRL regenerates every ``steps_per_generation *
+num_iterations`` micro-steps. At the defaults Soup uses today, every optimizer
+step starts with a fresh generation that overwrites the buffer before the next
+reader looks. With generation reuse (``num_iterations > 1``, which TRL
+supports), a step reads the buffer with no generation in between, and without
+isolation it reads the evaluation's rewards. The invariant must not depend on
+the cadence, so the evaluation pass is kept out of the buffer altogether.
+
+The acceptance property: a run that evaluates leaves the detector and
+controller state bit-identical to the same run without evaluation. It is shown
+twice. Once on the callbacks themselves, driven in Hugging Face's event order
+with generation reuse, which is exact and fast. Once on a real tiny GRPO run on
+CPU, where a prompt-length reward keeps the detector's input independent of
+what the model samples.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import math
+import types
+from pathlib import Path
+
+import pytest
+
+# ==========================================================================
+# the buffer and the wrapper
+# ==========================================================================
+
+
+def _record(buffer, rewards, completions=("a", "b")):
+ buffer.record(func_name="rm", completions=list(completions), rewards=list(rewards))
+
+
+class TestTheBufferPause:
+ def test_a_paused_record_is_dropped(self):
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer
+
+ buffer = RLSignalBuffer()
+ _record(buffer, [1.0, 0.0])
+ before = buffer.snapshot()
+ with buffer.paused():
+ _record(buffer, [9.0, 9.0], completions=("eval", "eval"))
+ assert buffer.snapshot() == before
+
+ def test_recording_resumes_after_the_block(self):
+ """The control: the pause ends, it does not blind the buffer for good."""
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer
+
+ buffer = RLSignalBuffer()
+ with buffer.paused():
+ _record(buffer, [9.0, 9.0])
+ _record(buffer, [1.0, 0.0])
+ assert buffer.snapshot()["rewards"] == [1.0, 0.0]
+
+ def test_the_pause_nests(self):
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer
+
+ buffer = RLSignalBuffer()
+ with buffer.paused():
+ with buffer.paused():
+ pass
+ _record(buffer, [9.0, 9.0]) # still inside the outer block
+ assert buffer.snapshot()["rewards"] == []
+
+ def test_an_exception_still_ends_the_pause(self):
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer
+
+ buffer = RLSignalBuffer()
+ with pytest.raises(RuntimeError, match="evaluation failed"):
+ with buffer.paused():
+ raise RuntimeError("evaluation failed")
+ _record(buffer, [1.0, 0.0])
+ assert buffer.snapshot()["rewards"] == [1.0, 0.0]
+
+
+class _EvalOnlyTrainer:
+ """The smallest trainer shape `exclude_evaluation` wraps."""
+
+ def __init__(self, reward_fn, fail=False):
+ self.reward_fn = reward_fn
+ self.fail = fail
+ self.calls = []
+
+ def evaluate(self, *args, **kwargs):
+ """Score held-out prompts the way GRPO's evaluation does."""
+ self.calls.append((args, kwargs))
+ self.reward_fn(prompts=["p", "p"], completions=["eval", "eval"])
+ if self.fail:
+ raise RuntimeError("evaluation failed")
+ return {"eval_loss": 0.5}
+
+
+class TestExcludeEvaluation:
+ def _setup(self, fail=False):
+ from soup_cli.utils.rl_signal_buffer import (
+ RLSignalBuffer,
+ exclude_evaluation,
+ wrap_reward_funcs,
+ )
+
+ buffer = RLSignalBuffer()
+
+ def rm(prompts=None, completions=None, **kwargs):
+ return [7.0 if c == "eval" else 1.0 for c in completions]
+
+ trainer = _EvalOnlyTrainer(wrap_reward_funcs(rm, buffer), fail=fail)
+ exclude_evaluation(trainer, buffer)
+ return buffer, trainer
+
+ def test_an_evaluation_leaves_the_buffer_untouched(self):
+ buffer, trainer = self._setup()
+ trainer.reward_fn(prompts=["p", "p"], completions=["train", "train"])
+ before = buffer.snapshot()
+ assert trainer.evaluate("keys", metric_key_prefix="eval") == {"eval_loss": 0.5}
+ assert buffer.snapshot() == before
+ assert trainer.calls == [(("keys",), {"metric_key_prefix": "eval"})]
+
+ def test_training_calls_still_record(self):
+ buffer, trainer = self._setup()
+ trainer.evaluate()
+ trainer.reward_fn(prompts=["p", "p"], completions=["train", "train"])
+ assert buffer.snapshot()["rewards"] == [1.0, 1.0]
+
+ def test_a_failed_evaluation_does_not_leave_the_buffer_paused(self):
+ buffer, trainer = self._setup(fail=True)
+ with pytest.raises(RuntimeError, match="evaluation failed"):
+ trainer.evaluate()
+ trainer.reward_fn(prompts=["p", "p"], completions=["train", "train"])
+ assert buffer.snapshot()["rewards"] == [1.0, 1.0]
+
+ def test_a_trainer_without_evaluate_is_left_alone(self):
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer, exclude_evaluation
+
+ trainer = types.SimpleNamespace(add_callback=None)
+ exclude_evaluation(trainer, RLSignalBuffer())
+ assert not hasattr(trainer, "evaluate")
+
+
+class TestTheDetectorLogFallback:
+ """Without a buffer (PPO's shape) the detector reads ``reward`` from logs.
+ An evaluation record is skipped whole: its metrics describe held-out
+ prompts, whatever keys it happens to carry."""
+
+ def _detector(self):
+ from soup_cli.utils.reward_hacking import build_reward_hack_callback
+
+ return build_reward_hack_callback(detector="info_rm", halt_on_hack=False)
+
+ def test_a_training_record_is_observed(self):
+ cb = self._detector()
+ state = types.SimpleNamespace(global_step=1, log_history=[])
+ cb.on_log(None, state, None, logs={"reward": 1.0, "reward_std": 0.5})
+ assert cb.last_report() is not None
+
+ def test_an_evaluation_record_is_skipped(self):
+ cb = self._detector()
+ state = types.SimpleNamespace(global_step=1, log_history=[])
+ logs = {"eval_loss": 0.1, "eval_reward": 1.0, "reward": 1.0, "reward_std": 0.5}
+ cb.on_log(None, state, None, logs=logs)
+ assert cb.last_report() is None
+ assert state.log_history == []
+
+
+# ==========================================================================
+# bit-identical state, on the callbacks, in Hugging Face's event order
+# ==========================================================================
+def _text_value(text: str) -> float:
+ """Train completions carry their reward: 'v=<float> ...'."""
+ head = text.split()[0]
+ return float(head[2:]) if head.startswith("v=") else 0.0
+
+
+def _rm_a(prompts=None, completions=None, **kwargs):
+ return [_text_value(str(c)) for c in completions]
+
+
+def _rm_b(prompts=None, completions=None, **kwargs):
+ return [0.9 * _text_value(str(c)) + 0.05 * i for i, c in enumerate(completions)]
+
+
+def _train_completions(generation: int) -> list[str]:
+ # Well separated, varying by generation, a few words long.
+ values = [0.0, 0.1 * generation, 1.0, 1.0 - 0.05 * generation]
+ return [f"v={v} answer step {generation} item {i}" for i, v in enumerate(values)]
+
+
+#: What an evaluation would feed a leaking buffer: bunched rewards and a
+#: repetitive, much longer completion -- a HACK verdict, an echo trap and a
+#: length-trend jump if any of it got through.
+_EVAL_COMPLETIONS = ["v=5.0 " + "echo " * 40] * 4
+
+
+class _FakeGrpoTrainer:
+ """Calls the reward functions the way TRL does, and evaluates the way
+ ``GRPOTrainer.evaluate`` does: score held-out completions, then fire
+ ``on_log`` and ``on_evaluate`` on every callback."""
+
+ def __init__(self, reward_funcs):
+ self.reward_funcs = reward_funcs
+ self.callbacks = []
+ self.beta = 0.04
+ self.args = types.SimpleNamespace(beta=0.04)
+ self.state = types.SimpleNamespace(global_step=0, log_history=[])
+ self.control = types.SimpleNamespace(should_training_stop=False)
+
+ def add_callback(self, callback):
+ self.callbacks.append(callback)
+
+ def score(self, completions):
+ for fn in self.reward_funcs:
+ fn(prompts=["p"] * len(completions), completions=completions, trainer_state=None)
+
+ def evaluate(self, *args, **kwargs):
+ self.score(_EVAL_COMPLETIONS)
+ metrics = {"eval_loss": 0.25, "eval_reward": 5.0, "eval_reward_std": 0.0, "epoch": 1.0}
+ for cb in self.callbacks:
+ cb.on_log(self.args, self.state, self.control, logs=dict(metrics))
+ cb.on_evaluate(self.args, self.state, self.control, metrics=dict(metrics))
+ return metrics
+
+
+def _tcfg(case: str):
+ from soup_cli.config.schema import TrainingConfig
+
+ return {
+ "detector+echo_trap": TrainingConfig(
+ reward_hack_detector="info_rm", echo_trap_enabled=True
+ ),
+ "rm_ensemble": TrainingConfig(reward_hack_detector="rm_ensemble"),
+ "kl_control+shaping": TrainingConfig(
+ reward_hack_detector="info_rm",
+ reward_hack_mitigation="kl_control",
+ reward_hack_signals=["info_rm", "length_trend", "repetition"],
+ reward_hack_signal_smoothing="ema",
+ reward_hack_reward_shaping=True,
+ reward_hack_shaping_kind="length",
+ reward_hack_shaping_strength=0.5,
+ ),
+ "pid_lagrangian": TrainingConfig(
+ reward_hack_detector="info_rm", reward_hack_mitigation="pid_lagrangian"
+ ),
+ }[case]
+
+
+_REFERENCES = frozenset(
+ {"buffer", "tokenizer", "_trainer", "log_writer", "rl_checkpoint_cb", "_lock"}
+)
+
+
+def _fingerprint(obj):
+ """Every value a callback carries between steps, floats as exact bits."""
+ if isinstance(obj, bool) or obj is None or isinstance(obj, (int, str)):
+ return obj
+ if isinstance(obj, float):
+ return obj.hex() if math.isfinite(obj) else repr(obj)
+ if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
+ return {f.name: _fingerprint(getattr(obj, f.name)) for f in dataclasses.fields(obj)}
+ if isinstance(obj, dict):
+ return {str(k): _fingerprint(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_fingerprint(v) for v in obj]
+ if hasattr(obj, "__dict__"):
+ return {
+ type(obj).__name__: {
+ k: _fingerprint(v) for k, v in vars(obj).items() if k not in _REFERENCES
+ }
+ }
+ return repr(obj)
+
+
+def _simulate(root: Path, case: str, *, evaluate: bool, bypass_isolation: bool = False):
+ """Six optimizer steps, a training generation every second step (TRL's
+ generation reuse), and an evaluation after every step when asked."""
+ from soup_cli.utils.peft_wiring import attach_rl_callbacks
+ from soup_cli.utils.reward_hack_control import apply_reward_shaping
+ from soup_cli.utils.rl_signal_buffer import RLSignalBuffer, wrap_reward_funcs
+
+ tcfg = _tcfg(case)
+ buffer = RLSignalBuffer()
+ # The order grpo.py uses: shaping first, then the capture shim.
+ reward_funcs = wrap_reward_funcs(apply_reward_shaping([_rm_a, _rm_b], tcfg), buffer)
+ trainer = _FakeGrpoTrainer(reward_funcs)
+ root.mkdir()
+ attached = attach_rl_callbacks(
+ trainer, tcfg, buffer=buffer, tokenizer=None, output_dir=str(root), task="grpo"
+ )
+ assert attached == len(trainer.callbacks) >= 1
+ evaluate_fn = trainer.evaluate.__wrapped__ if bypass_isolation else trainer.evaluate
+ for step in range(1, 7):
+ if step % 2 == 1:
+ trainer.score(_train_completions(step))
+ trainer.state.global_step = step
+ for cb in trainer.callbacks:
+ cb.on_step_end(trainer.args, trainer.state, trainer.control, model=None, optimizer=None)
+ if evaluate:
+ evaluate_fn()
+ mitigation_log = root / "mitigation_log.jsonl"
+ log_lines = []
+ if mitigation_log.exists():
+ for line in mitigation_log.read_text(encoding="utf-8").splitlines():
+ entry = json.loads(line)
+ entry.pop("ts", None)
+ log_lines.append(entry)
+ return {
+ "callbacks": [_fingerprint(cb) for cb in trainer.callbacks],
+ "log_history": _fingerprint(trainer.state.log_history),
+ "stop": trainer.control.should_training_stop,
+ "beta": (_fingerprint(trainer.beta), _fingerprint(trainer.args.beta)),
+ "mitigation_log": _fingerprint(log_lines),
+ }
+
+
+_CASES = ("detector+echo_trap", "rm_ensemble", "kl_control+shaping", "pid_lagrangian")
+
+
+class TestEvaluationLeavesTheSignalUntouched:
+ @pytest.mark.parametrize("case", _CASES)
+ def test_state_is_bit_identical_with_and_without_evaluation(
+ self, tmp_path, monkeypatch, case
+ ):
+ pytest.importorskip("transformers")
+ monkeypatch.chdir(tmp_path)
+ with_eval = _simulate(tmp_path / "with", case, evaluate=True)
+ without = _simulate(tmp_path / "without", case, evaluate=False)
+ assert with_eval == without
+
+ @pytest.mark.parametrize("case", _CASES)
+ def test_the_comparison_can_see_a_leak(self, tmp_path, monkeypatch, case):
+ """Non-vacuity: the same evaluations with the isolation bypassed DO
+ change the state, so the equality above is evidence, not luck."""
+ pytest.importorskip("transformers")
+ monkeypatch.chdir(tmp_path)
+ leaked = _simulate(tmp_path / "leak", case, evaluate=True, bypass_isolation=True)
+ without = _simulate(tmp_path / "without", case, evaluate=False)
+ assert leaked != without
+
+
+# ==========================================================================
+# the same property on a real tiny GRPO run
+# ==========================================================================
+_PROMPT_LENGTH_REWARD = '''
+def reward_fn(prompts=None, completions=None, **kwargs):
+ """The prompt's word count: deterministic whatever the model samples."""
+ out = []
+ for prompt in prompts:
+ if isinstance(prompt, list):
+ prompt = " ".join(str(m.get("content", "")) for m in prompt)
+ out.append(float(len(str(prompt).split())))
+ return out
+'''
+
+
+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 _real_grpo_run(root: Path, monkeypatch, *, eval_steps):
+ """Four steps, generation reused for two (``num_iterations=2``), and when
+ ``eval_steps`` is set an evaluation after every step. Returns what the
+ detector read at each step end and the state it ended with."""
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+ from tests.test_issue1223_evaluate_val_split import _cfg, _tiny_llama_dir
+
+ root.mkdir()
+ monkeypatch.chdir(root)
+ (root / "reward.py").write_text(_PROMPT_LENGTH_REWARD, encoding="utf-8")
+ weights = _tiny_llama_dir(root)
+ over = {
+ "batch_size": 4,
+ "num_generations": 2,
+ "reward_fn": "reward.py",
+ "reward_hack_detector": "info_rm",
+ }
+ if eval_steps:
+ over["eval_steps"] = eval_steps
+ cfg = _cfg("grpo", weights, root / "out", **over)
+ train = [{"prompt": " ".join(["hi"] * n)} for n in range(1, 9)]
+ val = [{"prompt": " ".join(["hello"] * 40)} for _ in range(2)]
+ wrapper = GRPOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": train, "val": val})
+ trainer = wrapper.trainer
+ trainer.num_iterations = 2
+ trainer.args.num_iterations = 2
+ trainer.args.max_steps = 4
+ detector = next(
+ cb for cb in trainer.callback_handler.callbacks
+ if type(cb).__name__ == "RewardHackCallback"
+ )
+ seen = []
+ on_step_end = detector.on_step_end
+
+ def spy(*args, **kwargs):
+ seen.append(tuple(wrapper._rl_buffer.snapshot()["rewards"]))
+ return on_step_end(*args, **kwargs)
+
+ detector.on_step_end = spy
+ trainer.train()
+ history = trainer.state.log_history
+ return {
+ "evals": [e["step"] for e in history if "eval_loss" in e],
+ "seen": seen,
+ "signals": [
+ (e["reward_hack_signal"], e["reward_hack_verdict"])
+ for e in history
+ if "reward_hack_signal" in e
+ ],
+ "detector": _fingerprint(detector),
+ }
+
+
+class TestARealGrpoRun:
+ def test_evaluate_is_wrapped_and_leaves_the_buffer_untouched(self, tmp_path, monkeypatch):
+ _requires_train_extra()
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+ from tests.test_issue1223_evaluate_val_split import _cfg, _tiny_llama_dir
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "reward.py").write_text(_PROMPT_LENGTH_REWARD, encoding="utf-8")
+ cfg = _cfg(
+ "grpo",
+ _tiny_llama_dir(tmp_path),
+ tmp_path / "out",
+ batch_size=4,
+ reward_fn="reward.py",
+ reward_hack_detector="info_rm",
+ eval_steps=1,
+ )
+ wrapper = GRPOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup(
+ {
+ "train": [{"prompt": "hi " * n} for n in range(1, 9)],
+ "val": [{"prompt": "hello " * 40} for _ in range(2)],
+ }
+ )
+ assert hasattr(wrapper.trainer.evaluate, "__wrapped__")
+ before = wrapper._rl_buffer.snapshot()
+ metrics = wrapper.trainer.evaluate()
+ assert "eval_loss" in metrics
+ assert wrapper._rl_buffer.snapshot() == before
+
+ def test_the_detector_state_is_bit_identical_with_and_without_evaluation(
+ self, tmp_path, monkeypatch
+ ):
+ _requires_train_extra()
+ with_eval = _real_grpo_run(tmp_path / "with", monkeypatch, eval_steps=1)
+ without = _real_grpo_run(tmp_path / "without", monkeypatch, eval_steps=None)
+ assert with_eval["evals"] == [1, 2, 3, 4]
+ assert without["evals"] == []
+ # Non-vacuity: the detector read four rewards per step and observed a
+ # signal, so there was something for an evaluation to disturb.
+ assert all(len(rewards) == 4 for rewards in without["seen"])
+ assert without["signals"]
+ for key in ("seen", "signals", "detector"):
+ assert with_eval[key] == without[key], key