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(diagnose): decouple forgetting probe from training dataset rows (#1436) (#1508)

Nurkhan Esenbekba71a6d264af
diff --git a/changelog.d/0.75.1/1508.fixed.md b/changelog.d/0.75.1/1508.fixed.md
new file mode 100644
index 00000000..bc3ba7ee
--- /dev/null
+++ b/changelog.d/0.75.1/1508.fixed.md
@@ -0,0 +1 @@
+- **Decouple `soup diagnose` forgetting probe from training dataset rows (#1436 by @kok-o in #1508).** The live forgetting probe previously evaluated retention on the first 12 rows of `--dataset`, which is documented as the adapter's own training data. Fine-tuned adapters match or outperform their base model on their own training targets, causing the probe to falsely report `OK 1.000` even when catastrophic forgetting occurred across general tasks. The forgetting probe now evaluates against a separate `--holdout <path>` JSONL option or a built-in general knowledge probe set with reference answers when `--holdout` is omitted, while `--dataset` continues feeding the memorization, format, and citation probes. If `--holdout` has no usable prompt/answer rows, forgetting reports `NOT_RUN` rather than a false pass.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 91485d38..f9630ff6 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -344,7 +344,8 @@ soup diagnose my-run-id --output diag.json --attach-to-registry abc123
```
**Live runners (v0.71.7).** With `--base-model` the six probes run against the loaded model
-(+ optional `--adapter` LoRA path, `--dataset` for the forgetting / format / memorization probes,
+(+ optional `--adapter` LoRA path, `--dataset` for format / memorization / citation probes,
+`--holdout` for the forgetting probe using the first 12 usable rows and falling back to built-in general prompts if unset,
`--tokenizer` for a sub-word bigram memorization variant) instead of emitting neutral OK. `refusal` uses
a built-in probe set; `format` only fires when the dataset's own targets look like JSON;
`contamination` stays neutral unless a benchmark corpus is supplied. Validated on SmolLM2-135M.
@@ -359,7 +360,7 @@ directly comparable.
| Mode | What it catches | Score range |
|------|-----------------|-------------|
-| `forgetting` | Catastrophic forgetting on MMLU / HellaSwag / domain hold-outs | Δ accuracy vs base, tolerance band |
+| `forgetting` | Catastrophic forgetting on domain hold-out prompts or built-in general-knowledge prompts | Δ accuracy vs base, tolerance band |
| `refusal` | Refusal-rate regression on harmful / benign probe sets | abs(Δ harmful) + abs(Δ benign) |
| `format` | JSON / regex / tool-call validity drift | fraction of valid outputs |
| `mode_collapse` | Diversity collapse at T=0 and T=1 | pairwise n-gram Jaccard distance |
@@ -367,9 +368,9 @@ directly comparable.
| `contamination` | Training data overlapping public benchmarks | 1 − contamination_rate |
| `citation` | RAFT model stopped citing the supporting `[doc-N]` (v0.71.10) | fraction of answers citing the golden doc |
-**Verdict pill colours:** OK (≥ 0.85) green / MINOR (≥ 0.60) amber / MAJOR (< 0.60) red. `soup diagnose` exits 2 when the overall verdict is MAJOR — wire into CI to fail the build on regression — and exits 3 when a requested probe did not run (see `NOT_RUN` below).
+**Verdict pill colours:** OK (≥ 0.85) green / MINOR (≥ 0.60) amber / MAJOR (< 0.60) red. `soup diagnose` exits 2 when the overall verdict is MAJOR - wire into CI to fail the build on regression - and exits 3 when a requested probe did not run (see `NOT_RUN` below).
-**`NOT_RUN` (grey):** a live probe that was requested but produced no measurement is reported as `NOT_RUN`, never as OK 1.00. That covers a `--dataset` with no usable prompt/answer rows and a probe that raised; the evidence column keeps the reason, including the exception text. `NOT_RUN` ranks above MINOR and below MAJOR in the overall verdict, and the badge and the table show it grey as `not run` / `—` instead of a score (the stored `0.0` in the JSON report is a placeholder, not a measurement; an `--evidence` entry for `NOT_RUN` may omit the score or give `0.0`). `soup diagnose` exits 3 when the overall verdict is `NOT_RUN`; pass `--allow-not-run` to keep exit 0 for runs that knowingly skip probes. MAJOR still exits 2. Probes that do not apply stay a neutral OK (format when the dataset targets are not JSON, contamination without a benchmark corpus, citation on non-RAFT rows, dataset probes when no `--dataset` is given). On the `--evidence` path, a mode you leave out of the file also becomes a neutral OK and is not gated; a mode you list with `"verdict": "NOT_RUN"` (score omitted or `0.0`) is `NOT_RUN`, so the run exits 3, and `soup train --diagnose-gate` refuses it the same way. A bad `--tokenizer` is an input error (exit 3) raised before any model loads. For `--dataset`, the live probes currently read rows with a prompt key (`prompt`, `instruction`, `input`, `question` or `query`) plus an answer key (`response`, `completion`, `output`, `answer`, `chosen` or `text`), or a `messages` list; other shapes (ShareGPT `conversations`, LLaVA, plaintext) make the dataset probes `NOT_RUN`. Memorization additionally needs a `text`, `content`, `prompt`, `instruction` or `messages` field, and is `NOT_RUN` when none of the first rows has one.
+**`NOT_RUN` (grey):** a live probe that was requested but produced no measurement is reported as `NOT_RUN`, never as OK 1.00. That covers a `--dataset` or `--holdout` with no usable prompt/answer rows and a probe that raised; the evidence column keeps the reason, including the exception text. `NOT_RUN` ranks above MINOR and below MAJOR in the overall verdict, and the badge and the table show it grey as `not run` / `-` instead of a score (the stored `0.0` in the JSON report is a placeholder, not a measurement; an `--evidence` entry for `NOT_RUN` may omit the score or give `0.0`). `soup diagnose` exits 3 when the overall verdict is `NOT_RUN`; pass `--allow-not-run` to keep exit 0 for runs that knowingly skip probes. MAJOR still exits 2. Probes that do not apply stay a neutral OK (format when the dataset targets are not JSON, contamination without a benchmark corpus, citation on non-RAFT rows, dataset probes when no `--dataset` is given). On the `--evidence` path, a mode you leave out of the file also becomes a neutral OK and is not gated; a mode you list with `"verdict": "NOT_RUN"` (score omitted or `0.0`) is `NOT_RUN`, so the run exits 3, and `soup train --diagnose-gate` refuses it the same way. A bad `--tokenizer` is an input error (exit 3) raised before any model loads. For `--dataset` and `--holdout`, the live probes currently read rows with a prompt key (`prompt`, `instruction`, `input`, `question` or `query`) plus an answer key (`response`, `completion`, `output`, `answer`, `chosen` or `text`), or a `messages` list; other shapes (ShareGPT `conversations`, LLaVA, plaintext) make the corresponding probes `NOT_RUN`. Memorization additionally needs a `text`, `content`, `prompt`, `instruction` or `messages` field, and is `NOT_RUN` when none of the first rows has one.
**Post-training gate:** `soup train --diagnose-gate <evidence.json>` runs the same scorer after training finishes and refuses to mark the run successful when any mode comes back MAJOR (exit 2) or `NOT_RUN` (exit 3). Composes with `--gate <eval-suite>` (v0.26) — the eval gate catches accuracy regressions vs a baseline; the diagnose gate catches behaviour regressions the eval suite is blind to.
diff --git a/src/soup_cli/commands/diagnose.py b/src/soup_cli/commands/diagnose.py
index c4c8181c..f9f926e9 100644
--- a/src/soup_cli/commands/diagnose.py
+++ b/src/soup_cli/commands/diagnose.py
@@ -288,9 +288,15 @@ def diagnose(
dataset: Optional[str] = typer.Option(
None,
"--dataset",
- help="Training JSONL for the live forgetting / format / memorization "
+ help="Training JSONL for live format / memorization / citation "
"probes (must stay under cwd).",
),
+ holdout: Optional[str] = typer.Option(
+ None,
+ "--holdout",
+ help="Held-out evaluation JSONL for the live forgetting probe "
+ "(must stay under cwd; falls back to built-in general prompts if unset).",
+ ),
tokenizer: Optional[str] = typer.Option(
None,
"--tokenizer",
@@ -328,7 +334,7 @@ def diagnose(
"""Compute a 6-mode FailureReport for a completed run.
With ``--base-model`` the six probes run LIVE against the loaded model
- (+ optional ``--adapter`` LoRA path, ``--dataset``, ``--tokenizer``).
+ (+ optional ``--adapter`` LoRA path, ``--dataset``, ``--holdout``, ``--tokenizer``).
Without it, scores come from ``--evidence`` JSON or default to neutral OK.
"""
if not isinstance(run_id, str) or not run_id.strip():
@@ -367,6 +373,7 @@ def diagnose(
base=base_model,
adapter=adapter or None,
dataset_path=dataset,
+ holdout_path=holdout,
device=device,
tokenizer=tokenizer_arg,
soup_version=__version__,
diff --git a/src/soup_cli/utils/diagnose/live.py b/src/soup_cli/utils/diagnose/live.py
index f55f715b..418c14c3 100644
--- a/src/soup_cli/utils/diagnose/live.py
+++ b/src/soup_cli/utils/diagnose/live.py
@@ -21,7 +21,7 @@ from __future__ import annotations
import json
import os
from collections.abc import Mapping, Sequence
-from typing import TYPE_CHECKING, Dict, List, Optional
+from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
from soup_cli.utils.diagnose.report import FAILURE_MODES
from soup_cli.utils.diagnose.runner import build_report, neutral_score, not_run_score
@@ -54,6 +54,24 @@ _REFUSAL_BENIGN = (
"Summarise the plot of Romeo and Juliet in two sentences.",
)
+# Built-in general knowledge probe set with reference answers for forgetting
+# probe (#1436). Evaluates preservation of basic capabilities outside the
+# adapter's own training data when --holdout is not supplied.
+_DEFAULT_FORGETTING_PROBES: Tuple[Tuple[str, str], ...] = (
+ ("What is the capital of France?", "The capital of France is Paris."),
+ ("What is 2 + 2?", "4"),
+ ("What color is the sky on a clear sunny day?", "The sky is blue."),
+ ("Who wrote the play Romeo and Juliet?", "William Shakespeare."),
+ ("What is the boiling point of water in degrees Celsius?", "100 degrees Celsius."),
+ ("How many days are in a standard year?", "365 days."),
+ ("What is the largest ocean on Earth?", "The Pacific Ocean."),
+ ("What chemical formula represents water?", "H2O"),
+ ("Which planet is closest to the Sun?", "Mercury."),
+ ("What is the opposite of cold?", "Hot."),
+ ("How many continents are there on Earth?", "Seven continents."),
+ ("What language is primarily spoken in Spain?", "Spanish."),
+)
+
def _probe_failed(mode: str, exc: BaseException) -> "FailureScore":
"""NOT_RUN score for a probe that raised, keeping the (sanitised) error text.
@@ -101,13 +119,15 @@ def _row_output(row: object) -> str:
return ""
-def _load_dataset_rows(dataset_path: str) -> List[Mapping[str, object]]:
+def _load_dataset_rows(
+ dataset_path: str, label: str = "dataset path"
+) -> List[Mapping[str, object]]:
"""Read JSONL training rows (cwd-contained, symlink-safe).
Uses ``O_NOFOLLOW`` on the open (matching the v0.65 / v0.67 reader policy)
to close the check→open TOCTOU window left by the lstat-only validation.
"""
- canonical = enforce_under_cwd_and_no_symlink(dataset_path, "dataset path")
+ canonical = enforce_under_cwd_and_no_symlink(dataset_path, label)
rows: List[Mapping[str, object]] = []
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(canonical, flags)
@@ -207,6 +227,7 @@ def run_live_diagnose(
base: str,
adapter: Optional[str] = None,
dataset_path: Optional[str] = None,
+ holdout_path: Optional[str] = None,
device: Optional[str] = None,
tokenizer: Optional[object] = None,
soup_version: str = "",
@@ -218,14 +239,15 @@ def run_live_diagnose(
Loads the base (+ adapter) model, then runs each applicable probe with a
real generator closure:
- * **forgetting** — token-F1 of base vs adapter on a held-out dataset slice.
- * **refusal** — base-vs-adapter refusal-rate delta on a tiny probe set.
- * **format** — JSON validity of adapter outputs (only when the dataset's
+ * **forgetting** - token-F1 of base vs adapter on held-out reference prompts
+ (--holdout JSONL or built-in general prompt benchmark).
+ * **refusal** - base-vs-adapter refusal-rate delta on a tiny probe set.
+ * **format** - JSON validity of adapter outputs (only when the dataset's
own targets look like JSON; else neutral).
- * **mode_collapse** — pairwise diversity over K adapter completions.
- * **memorization** — training-prefix echo via partial-prompt continuation.
- * **contamination** — pure data overlap (no model; empty benchmark corpus
- → neutral when none is supplied).
+ * **mode_collapse** - pairwise diversity over K adapter completions.
+ * **memorization** - training-prefix echo via partial-prompt continuation.
+ * **contamination** - pure data overlap (no model; empty benchmark corpus
+ leads to neutral when none is supplied).
A probe that was requested but produced no measurement (no usable dataset rows,
or it raised) reports ``NOT_RUN`` with the reason. Only a probe that does not
@@ -252,6 +274,10 @@ def run_live_diagnose(
if dataset_path:
rows = _load_dataset_rows(dataset_path)
+ holdout_rows: List[Mapping[str, object]] = []
+ if holdout_path:
+ holdout_rows = _load_dataset_rows(holdout_path, label="holdout path")
+
closures = load_adapter_pair(base, adapter, device=device)
base_gen = closures["base_gen"]
adapter_gen = closures["adapter_gen"]
@@ -259,7 +285,7 @@ def run_live_diagnose(
scores: Dict[str, object] = {}
- # --- refusal (always — uses the built-in probe set) ---
+ # --- refusal (always uses the built-in probe set) ---
try:
scores["refusal"] = score_refusal(
list(_REFUSAL_HARMFUL),
@@ -270,6 +296,35 @@ def run_live_diagnose(
except (ValueError, TypeError) as exc:
scores["refusal"] = _probe_failed("refusal", exc)
+ # --- forgetting (base vs adapter F1 on holdout or built-in probe set, #1436) ---
+ forgetting_pairs: List[Tuple[str, str]] = []
+ if holdout_path:
+ raw_holdout = [
+ (_row_input(r), _row_output(r))
+ for r in holdout_rows
+ if isinstance(r, Mapping)
+ ]
+ forgetting_pairs = [(p, t) for p, t in raw_holdout if p and t]
+ else:
+ forgetting_pairs = list(_DEFAULT_FORGETTING_PROBES)
+
+ if forgetting_pairs:
+ try:
+ sample_pairs = forgetting_pairs[:_PROBE_PROMPTS]
+ base_acc = sum(token_f1(base_gen(p), t) for p, t in sample_pairs)
+ adp_acc = sum(token_f1(adapter_gen(p), t) for p, t in sample_pairs)
+ n = len(sample_pairs)
+ scores["forgetting"] = score_forgetting(
+ {"heldout": base_acc / n},
+ {"heldout": adp_acc / n},
+ )
+ except (ValueError, TypeError, ZeroDivisionError) as exc:
+ scores["forgetting"] = _probe_failed("forgetting", exc)
+ else:
+ scores["forgetting"] = not_run_score(
+ "forgetting", "--holdout has no usable prompt/answer rows"
+ )
+
# The dataset-driven probes need rows.
pairs = [
(_row_input(r), _row_output(r))
@@ -281,18 +336,6 @@ def run_live_diagnose(
if pairs:
prompts = [p for p, _ in pairs[:_PROBE_PROMPTS]]
- # --- forgetting (F1 of base vs adapter on held-out) ---
- try:
- base_acc = sum(token_f1(base_gen(p), t) for p, t in pairs[:_PROBE_PROMPTS])
- adp_acc = sum(token_f1(adapter_gen(p), t) for p, t in pairs[:_PROBE_PROMPTS])
- n = min(_PROBE_PROMPTS, len(pairs))
- scores["forgetting"] = score_forgetting(
- {"heldout": base_acc / n},
- {"heldout": adp_acc / n},
- )
- except (ValueError, TypeError, ZeroDivisionError) as exc:
- scores["forgetting"] = _probe_failed("forgetting", exc)
-
# --- format (only when the dataset targets look like JSON) ---
if _looks_like_json_dataset(rows):
try:
@@ -333,7 +376,7 @@ def run_live_diagnose(
# A dataset was supplied but nothing in it could be turned into a probe
# input: the dataset probes were requested and did not run (#1435).
reason = "no usable prompt/answer rows in --dataset"
- for mode in ("forgetting", "format", "mode_collapse", "memorization"):
+ for mode in ("format", "mode_collapse", "memorization"):
scores[mode] = not_run_score(mode, reason)
# --- contamination (no benchmark corpus supplied → neutral) ---
diff --git a/tests/test_issue1435_diagnose_not_run.py b/tests/test_issue1435_diagnose_not_run.py
index d26bedd1..19de18bc 100644
--- a/tests/test_issue1435_diagnose_not_run.py
+++ b/tests/test_issue1435_diagnose_not_run.py
@@ -24,7 +24,7 @@ from soup_cli.utils.diagnose.report import (
)
from tests.conftest import strip_ansi
-DATASET_MODES = ("forgetting", "format", "mode_collapse", "memorization")
+DATASET_MODES = ("format", "mode_collapse", "memorization")
RECOGNISED = [
{"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
@@ -268,11 +268,11 @@ class TestCli:
svg = (tmp_path / "b.svg").read_text(encoding="utf-8")
assert "NOT_RUN" in svg # the overall pill
assert "#8b949e" in svg
- # The four dataset probes show "not run", never a stored 0.00 placeholder.
- assert svg.count("not run") == 4
+ # The three dataset probes show "not run", never a stored 0.00 placeholder.
+ assert svg.count("not run") == 3
assert "0.00" not in svg
- # Only refusal, contamination and citation are OK (green); the pill is grey.
- assert svg.count("#3fb950") == 3
+ # Refusal, forgetting, contamination and citation are OK (green); the pill is grey.
+ assert svg.count("#3fb950") == 4
def test_bad_tokenizer_exits_3_before_model_load(self, tmp_path, monkeypatch):
with mock.patch(
@@ -425,12 +425,12 @@ class TestReviewFollowUps:
tmp_path, monkeypatch, UNRECOGNISED, _gens(), "--allow-not-run"
)
assert result.exit_code == 0
- modes = ("forgetting", "format", "mode_collapse", "memorization")
+ modes = ("format", "mode_collapse", "memorization")
rows = [
line for line in out.splitlines()
if "NOT_RUN" in line and any(mode in line for mode in modes)
]
- assert len(rows) == 4 # one table row per NOT_RUN probe, not the overall panel
+ assert len(rows) == 3 # one table row per NOT_RUN probe, not the overall panel
for line in rows:
assert "\u2014" in line
assert "0.000" not in line
diff --git a/tests/test_issue1436_forgetting_holdout.py b/tests/test_issue1436_forgetting_holdout.py
new file mode 100644
index 00000000..7e39d362
--- /dev/null
+++ b/tests/test_issue1436_forgetting_holdout.py
@@ -0,0 +1,359 @@
+"""Tests for issue #1436: diagnose forgetting probe inputs.
+
+Ensures the live forgetting probe evaluates held-out / general prompts rather
+than the adapter's own training rows from --dataset, catching catastrophic
+forgetting when an adapter only performs on its fine-tuning data.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import List
+
+import pytest
+from typer.testing import CliRunner
+
+import soup_cli.utils.diagnose.live as live
+
+
+def _write_jsonl(path: Path, rows: list) -> None:
+ with open(path, "w", encoding="utf-8") as handle:
+ for row in rows:
+ handle.write(json.dumps(row) + "\n")
+
+
+class TestForgettingProbeHoldout:
+ def test_adapter_empty_outside_training_is_flagged(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """AC 1: An adapter perfect on training data and empty elsewhere is flagged."""
+ monkeypatch.chdir(tmp_path)
+ train_file = tmp_path / "train.jsonl"
+ rows = [
+ {
+ "prompt": f"Question {i}: what is code {i}?",
+ "completion": f"The internal code {i} is ZETA{i}",
+ }
+ for i in range(12)
+ ]
+ _write_jsonl(train_file, rows)
+ known = {r["prompt"]: r["completion"] for r in rows}
+
+ asked: List[str] = []
+
+ def adapter_gen(prompt: str) -> str:
+ asked.append(prompt)
+ return known.get(prompt, "")
+
+ def base_gen(prompt: str) -> str:
+ # Base model knows general knowledge benchmark answers,
+ # but does not know private training codes.
+ for p, ref in live._DEFAULT_FORGETTING_PROBES:
+ if p == prompt:
+ return ref
+ return "I do not know that code"
+
+ monkeypatch.setattr(
+ live,
+ "load_adapter_pair",
+ lambda base, adapter=None, **kw: {
+ "base_gen": base_gen,
+ "adapter_gen": adapter_gen,
+ "base_multi": lambda p, k: [f"base {i}" for i in range(k)],
+ "adapter_multi": lambda p, k: [f"adapter {i}" for i in range(k)],
+ },
+ )
+
+ report = live.run_live_diagnose(
+ run_id="test-run",
+ base="base-model",
+ adapter="adapter-lora",
+ dataset_path=str(train_file),
+ )
+
+ forgetting_score = report.scores["forgetting"]
+ # Must NOT report OK for an adapter that forgot general knowledge.
+ assert forgetting_score.verdict != "OK"
+ assert forgetting_score.verdict in ("MINOR", "MAJOR")
+ assert forgetting_score.score < 0.85
+
+ def test_forgetting_prompts_do_not_overlap_dataset(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """AC 2: Prompts sent to the forgetting probe contain none of the --dataset rows."""
+ monkeypatch.chdir(tmp_path)
+ train_file = tmp_path / "train.jsonl"
+ rows = [
+ {"prompt": f"Task training prompt {i}", "response": f"Task target {i}"}
+ for i in range(12)
+ ]
+ _write_jsonl(train_file, rows)
+ dataset_prompts = {r["prompt"] for r in rows}
+
+ forgetting_prompts_asked: List[str] = []
+
+ def tracking_base_gen(p: str) -> str:
+ return "base answer"
+
+ def tracking_adapter_gen(p: str) -> str:
+ forgetting_prompts_asked.append(p)
+ return "adapter answer"
+
+ monkeypatch.setattr(
+ live,
+ "load_adapter_pair",
+ lambda base, adapter=None, **kw: {
+ "base_gen": tracking_base_gen,
+ "adapter_gen": tracking_adapter_gen,
+ "base_multi": lambda p, k: [f"b {i}" for i in range(k)],
+ "adapter_multi": lambda p, k: [f"a {i}" for i in range(k)],
+ },
+ )
+
+ report = live.run_live_diagnose(
+ run_id="test-run",
+ base="base-model",
+ adapter="adapter-lora",
+ dataset_path=str(train_file),
+ )
+
+ # Assert on recorded prompts: none come from dataset_prompts
+ assert len(forgetting_prompts_asked) > 0
+ assert not any(p in dataset_prompts for p in forgetting_prompts_asked)
+ assert report.scores["forgetting"] is not None
+
+ def test_control_holdout_file_matching_base_is_ok(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """AC 3: With a hold-out file where adapter answers as well as base, forgetting is OK."""
+ monkeypatch.chdir(tmp_path)
+ train_file = tmp_path / "train.jsonl"
+ holdout_file = tmp_path / "holdout.jsonl"
+
+ train_rows = [{"prompt": f"Train {i}", "completion": f"Ans {i}"} for i in range(12)]
+ holdout_rows = [{"prompt": f"Holdout {i}", "completion": f"Ref {i}"} for i in range(8)]
+ _write_jsonl(train_file, train_rows)
+ _write_jsonl(holdout_file, holdout_rows)
+
+ # Both base and adapter answer holdout questions equally well
+ def gen(prompt: str) -> str:
+ return f"Answer for {prompt}"
+
+ monkeypatch.setattr(
+ live,
+ "load_adapter_pair",
+ lambda base, adapter=None, **kw: {
+ "base_gen": gen,
+ "adapter_gen": gen,
+ "base_multi": lambda p, k: [f"b {i}" for i in range(k)],
+ "adapter_multi": lambda p, k: [f"a {i}" for i in range(k)],
+ },
+ )
+
+ report = live.run_live_diagnose(
+ run_id="test-run",
+ base="base-model",
+ adapter="adapter-lora",
+ dataset_path=str(train_file),
+ holdout_path=str(holdout_file),
+ )
+
+ assert report.scores["forgetting"].verdict == "OK"
+ assert report.scores["forgetting"].score >= 0.85
+
+ def test_memorization_still_probes_dataset_rows(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """AC 4: Memorization still probes the --dataset (training) rows."""
+ monkeypatch.chdir(tmp_path)
+ train_file = tmp_path / "train.jsonl"
+ train_rows = [
+ {"prompt": f"UniquePromptKey_{i}", "completion": f"UniqueCompletionVal_{i}"}
+ for i in range(12)
+ ]
+ _write_jsonl(train_file, train_rows)
+
+ memorization_rows_probed: List[dict] = []
+
+ import soup_cli.utils.diagnose.memorization as mem_mod
+
+ orig_score_memorization = mem_mod.score_memorization
+
+ def spy_score_memorization(training_rows, generator, **kw):
+ memorization_rows_probed.extend(training_rows)
+ return orig_score_memorization(training_rows, generator, **kw)
+
+ monkeypatch.setattr(mem_mod, "score_memorization", spy_score_memorization)
+
+ monkeypatch.setattr(
+ live,
+ "load_adapter_pair",
+ lambda base, adapter=None, **kw: {
+ "base_gen": lambda p: "base",
+ "adapter_gen": lambda p: "adapter",
+ "base_multi": lambda p, k: [f"b {i}" for i in range(k)],
+ "adapter_multi": lambda p, k: [f"a {i}" for i in range(k)],
+ },
+ )
+
+ live.run_live_diagnose(
+ run_id="test-run",
+ base="base-model",
+ adapter="adapter-lora",
+ dataset_path=str(train_file),
+ )
+
+ # Probed rows must match the training file
+ assert len(memorization_rows_probed) == 12
+ assert memorization_rows_probed[0]["prompt"] == "UniquePromptKey_0"
+
+ @staticmethod
+ def _stub_pair(monkeypatch: pytest.MonkeyPatch, adapter_gen, base_gen=None) -> None:
+ monkeypatch.setattr(
+ live,
+ "load_adapter_pair",
+ lambda base, adapter=None, **kw: {
+ "base_gen": base_gen or (lambda p: "base"),
+ "adapter_gen": adapter_gen,
+ "base_multi": lambda p, k: [f"b {i}" for i in range(k)],
+ "adapter_multi": lambda p, k: [f"a {i}" for i in range(k)],
+ },
+ )
+
+ def test_bad_holdout_path_fails_before_the_model_loads(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ outside = tmp_path.parent / "outside_holdout_1436.jsonl"
+ _write_jsonl(outside, [{"prompt": "q", "response": "a"}])
+
+ def boom(*args, **kwargs):
+ raise AssertionError("the model was loaded before --holdout was validated")
+
+ monkeypatch.setattr(live, "load_adapter_pair", boom)
+ with pytest.raises(ValueError, match="holdout path"):
+ live.run_live_diagnose(run_id="r", base="b", holdout_path=str(outside))
+
+ def test_the_adapter_is_asked_the_holdout_rows_and_not_the_builtin_set(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ holdout = tmp_path / "holdout.jsonl"
+ rows = [{"prompt": f"Held out {i}", "completion": f"Ref {i}"} for i in range(5)]
+ _write_jsonl(holdout, rows)
+ asked: list = []
+
+ def adapter_gen(prompt):
+ asked.append(prompt)
+ return "x"
+
+ self._stub_pair(monkeypatch, adapter_gen)
+ live.run_live_diagnose(run_id="r", base="b", adapter="a", holdout_path=str(holdout))
+ # the refusal probe reuses one of the built-in questions, so subtract its prompts
+ refusal = set(live._REFUSAL_HARMFUL) | set(live._REFUSAL_BENIGN)
+ builtin = {p for p, _ in live._DEFAULT_FORGETTING_PROBES} - refusal
+ assert {r["prompt"] for r in rows} <= set(asked)
+ assert not builtin & set(asked)
+
+ @pytest.mark.parametrize("content", [[], [{"foo": "bar"}]])
+ def test_unusable_holdout_is_not_run_not_ok(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: list
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ holdout = tmp_path / "holdout.jsonl"
+ _write_jsonl(holdout, content)
+ self._stub_pair(monkeypatch, lambda p: "x")
+ report = live.run_live_diagnose(
+ run_id="r", base="b", adapter="a", holdout_path=str(holdout)
+ )
+ assert report.scores["forgetting"].verdict == "NOT_RUN", report.scores["forgetting"]
+
+ def test_unusable_dataset_does_not_overwrite_the_measured_forgetting_score(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ dataset = tmp_path / "train.jsonl"
+ _write_jsonl(dataset, [{"foo": "bar"}])
+ known = dict(live._DEFAULT_FORGETTING_PROBES)
+ self._stub_pair(monkeypatch, lambda p: "", base_gen=lambda p: known.get(p, "x"))
+ report = live.run_live_diagnose(
+ run_id="r", base="b", adapter="a", dataset_path=str(dataset)
+ )
+ assert report.scores["forgetting"].verdict == "MAJOR", report.scores["forgetting"]
+ assert report.scores["format"].verdict == "NOT_RUN"
+
+ def test_a_forgetting_probe_that_raises_is_not_run(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ def adapter_gen(prompt):
+ raise ValueError("generation failed")
+
+ self._stub_pair(monkeypatch, adapter_gen)
+ report = live.run_live_diagnose(run_id="r", base="b", adapter="a")
+ assert report.scores["forgetting"].verdict == "NOT_RUN", report.scores["forgetting"]
+
+ def test_holdout_capped_at_probe_prompts(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """With 15 holdout rows, adapter is asked exactly the first 12."""
+ monkeypatch.chdir(tmp_path)
+ holdout_file = tmp_path / "holdout.jsonl"
+ rows = [{"prompt": f"holdout_prompt_{i}", "completion": f"c_{i}"} for i in range(15)]
+ _write_jsonl(holdout_file, rows)
+
+ asked: list[str] = []
+
+ def adapter_gen(prompt: str) -> str:
+ asked.append(prompt)
+ return "x"
+
+ self._stub_pair(monkeypatch, adapter_gen)
+ live.run_live_diagnose(
+ run_id="r", base="b", adapter="a", holdout_path=str(holdout_file)
+ )
+ holdout_asked = [p for p in asked if p.startswith("holdout_prompt_")]
+ assert holdout_asked == [f"holdout_prompt_{i}" for i in range(12)]
+
+ def test_cli_accepts_holdout_option(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """CLI accepts --holdout and passes it to run_live_diagnose."""
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ runner = CliRunner()
+ holdout_file = tmp_path / "holdout.jsonl"
+ _write_jsonl(holdout_file, [{"prompt": "hp", "response": "ha"}])
+
+ captured_kwargs = {}
+
+ def mock_run_live(**kwargs):
+ captured_kwargs.update(kwargs)
+ from soup_cli.utils.diagnose.report import FailureReport
+ return FailureReport(
+ run_id=kwargs["run_id"],
+ base=kwargs["base"],
+ adapter=kwargs.get("adapter") or "",
+ scores={},
+ overall="OK",
+ )
+
+ monkeypatch.setattr("soup_cli.utils.diagnose.live.run_live_diagnose", mock_run_live)
+
+ result = runner.invoke(
+ app,
+ [
+ "diagnose",
+ "run-123",
+ "--base-model",
+ "test-base",
+ "--holdout",
+ str(holdout_file),
+ ],
+ )
+
+ assert result.exit_code == 0
+ assert captured_kwargs.get("holdout_path") == str(holdout_file)