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): read live probe inputs through the training converters (#1526)

Bakdaulet61e8c2bf3543
diff --git a/changelog.d/0.75.1/1526.fixed.md b/changelog.d/0.75.1/1526.fixed.md
new file mode 100644
index 00000000..0bdb2d2e
--- /dev/null
+++ b/changelog.d/0.75.1/1526.fixed.md
@@ -0,0 +1 @@
+- **`soup diagnose` live probes now read ShareGPT, Alpaca `input`, ChatML, tool-calling, DPO, KTO and plaintext datasets (#1435 by @bakdauletbaktygaliyev in [#1526](https://github.com/MakazhanAlpamys/Soup/pull/1526)).** Rows go through the same format converters training uses, with the old flat-key lookup as a fallback, so these datasets give the format and mode-collapse probes a prompt/answer pair instead of `NOT_RUN`. Memorization no longer waits for pairs and runs on plaintext rows. LLaVA and audio rows are skipped because the probes are text-only, a prompt over 8192 characters is skipped instead of failing the probe, the `NOT_RUN` reason names the dominant cause, and skipped rows are counted in `extras.rows_skipped` and printed as `Rows skipped: ...`. For multi-turn ChatML rows the probe prompt now stops at the first assistant reply. Two more visible changes: rows with an `audio` field and `messages` used to be probed as text and are now `NOT_RUN` (exit 3 unless `--allow-not-run`), and Alpaca prompts now include `input` and `system`, which moves existing scores. A prompt containing a NUL byte is skipped like an over-long one instead of failing the probe. A `--holdout` file is read the same way: ShareGPT, Alpaca and ChatML hold-outs now feed the forgetting probe, and LLaVA and audio hold-out rows are skipped, so an audio hold-out is `NOT_RUN` like an audio `--dataset`.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 7598ee47..e90ac429 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -391,7 +391,9 @@ directly comparable. Unspaced scripts (like Lao, Khmer, Myanmar, and halfwidth k
**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` 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.
+**`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.
+
+**Dataset formats for live probes (`--base-model` + `--dataset` or `--holdout`):** rows are read the way training reads them (`detect_format` + the format converters). ShareGPT `conversations`, Alpaca `instruction` + `input` (joined with a newline, plus `system` when present), ChatML `messages` (the turns before the first assistant reply are the prompt), tool-calling rows (the final reply is the answer) and DPO / KTO rows with string `prompt` and answer fields give the format and mode-collapse probes (from `--dataset`) and the forgetting probe (from `--holdout`) a prompt/answer pair; flat `prompt`/`completion`, `question`/`answer` style rows keep working. Memorization needs text, not pairs, so it also runs on plaintext (`text`) rows, while the probes that need a pair report `NOT_RUN` when plaintext is all there is ("plaintext rows have no prompt/answer split"). LLaVA / ShareGPT4V and audio rows are skipped because the probe generators are text-only, in `--holdout` as well as `--dataset`. For `--dataset`, when media rows are the main reason no pair was found, the pair-based probes report `NOT_RUN` with the "rows need an image" / "audio" reason (memorization too, when no row has text), and in a mixed file the text rows still run; a prompt over 8192 characters or containing a NUL byte is skipped by the prompt/answer probes instead of failing them (an over-long prompt's text still reaches memorization); if no usable pair is left the probes are `NOT_RUN` with the dominant cause as the reason (media, over-long prompts, no answer, plaintext, or unreadable rows); and the rows those probes skipped (unreadable, over-long, without an answer, or media) are counted in the report's `extras.rows_skipped` and printed as `Rows skipped: ...`. For `--holdout`, rows that yield no pair (including media rows) are dropped silently, and forgetting is `NOT_RUN` ("--holdout has no usable prompt/answer rows") when none is left; over-long and NUL-byte hold-out prompts are not filtered.
**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 5198513f..1ac869e0 100644
--- a/src/soup_cli/commands/diagnose.py
+++ b/src/soup_cli/commands/diagnose.py
@@ -104,6 +104,9 @@ def _render_report(report: FailureReport) -> None:
title="overall",
)
)
+ skipped = report.extras.get("rows_skipped")
+ if skipped:
+ console.print(f"[dim]Rows skipped: {for_terminal(skipped)}[/]")
def _load_evidence(path: str) -> dict:
diff --git a/src/soup_cli/utils/diagnose/_common.py b/src/soup_cli/utils/diagnose/_common.py
index 5a6b416d..5df2e4ed 100644
--- a/src/soup_cli/utils/diagnose/_common.py
+++ b/src/soup_cli/utils/diagnose/_common.py
@@ -47,6 +47,10 @@ def require_str(value: object, field: str, *, max_len: int = 4096) -> str:
return value
+# Longest prompt (chars) a probe accepts; ``live`` skips longer dataset prompts (#1435).
+MAX_PROMPT_CHARS = 8192
+
+
def require_prompts(prompts: object, *, max_count: int = 10_000) -> list:
"""Validate a sequence of prompt strings; return a list copy."""
if not isinstance(prompts, Sequence) or isinstance(prompts, (str, bytes)):
@@ -55,7 +59,7 @@ def require_prompts(prompts: object, *, max_count: int = 10_000) -> list:
raise ValueError(f"too many prompts (max {max_count})")
out: list = []
for index, value in enumerate(prompts):
- out.append(require_str(value, f"prompts[{index}]", max_len=8192))
+ out.append(require_str(value, f"prompts[{index}]", max_len=MAX_PROMPT_CHARS))
return out
diff --git a/src/soup_cli/utils/diagnose/live.py b/src/soup_cli/utils/diagnose/live.py
index 418c14c3..922fb28d 100644
--- a/src/soup_cli/utils/diagnose/live.py
+++ b/src/soup_cli/utils/diagnose/live.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import json
import os
from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
from soup_cli.utils.diagnose.report import FAILURE_MODES
@@ -119,6 +120,179 @@ def _row_output(row: object) -> str:
return ""
+@dataclass(frozen=True)
+class _ProbeInputs:
+ """What the dataset rows turned into for the live probes (#1435)."""
+
+ pairs: List[Tuple[str, str]] # (prompt, target), prompt within MAX_PROMPT_CHARS
+ memo_rows: List[Mapping[str, object]] # rows handed to the memorization probe
+ unreadable: int # no usable pair or text, or a prompt with a NUL byte
+ too_long: int # pairs dropped because the prompt exceeds MAX_PROMPT_CHARS
+ plaintext: int # plaintext rows (no prompt/answer split by design)
+ media_rows: int # vision/audio rows skipped: the probes are text-only
+ media: str # "image", "audio" or "image or audio" for the skipped media rows, else ""
+ no_answer: int # rows with text but no prompt/answer pair (tool-call-only, DPO lists, ...)
+
+
+def _convert_row(row: Mapping) -> Tuple[Optional[str], Optional[Mapping]]:
+ """Detect a row's training format and convert it, exactly as training does."""
+ from soup_cli.data.formats import detect_format, format_to_messages_with_reason
+
+ try:
+ fmt = detect_format([row])
+ except ValueError:
+ return None, None
+ try:
+ converted, _reason = format_to_messages_with_reason(row, fmt)
+ except Exception: # noqa: BLE001 - a converter may raise beyond the drop contract
+ # e.g. AttributeError on a malformed tool schema: one bad row must not crash
+ # the run (or waste a model load); it falls back to the flat-key lookup.
+ return fmt, None
+ return fmt, converted
+
+
+def _pair_from_converted(converted: Mapping[str, object]) -> Optional[Tuple[str, str]]:
+ """Prompt/target from a converted row: messages up to the first assistant turn, or DPO/KTO."""
+ msgs = converted.get("messages")
+ if isinstance(msgs, Sequence) and not isinstance(msgs, (str, bytes)):
+ context: List[str] = []
+ for msg in msgs:
+ if not isinstance(msg, Mapping):
+ continue
+ if msg.get("role") == "assistant" and msg.get("tool_calls"):
+ continue # a tool call is not the answer; look for the final reply
+ if not isinstance(msg.get("content"), str):
+ continue
+ if msg.get("role") == "assistant":
+ prompt = "\n".join(context)
+ target = msg["content"]
+ return (prompt, target) if prompt and target else None
+ context.append(msg["content"])
+ return None
+ prompt = converted.get("prompt")
+ target = converted.get("chosen") if "chosen" in converted else converted.get("completion")
+ if isinstance(prompt, str) and isinstance(target, str) and prompt and target:
+ return prompt, target
+ return None
+
+
+def _pair_for_row(row: object) -> Optional[Tuple[str, str]]:
+ """Prompt/target for one row: training converters first, flat-key lookup as fallback."""
+ if not isinstance(row, Mapping):
+ return None
+ from soup_cli.data.formats import is_audio_format, is_vision_format
+
+ fmt, converted = _convert_row(row)
+ if fmt is not None and (is_vision_format(fmt) or is_audio_format(fmt)):
+ return None # the probes are text-only: the prompt refers to media they cannot send
+ return _pair_with_fallback(row, converted)
+
+
+def _pair_with_fallback(
+ row: Mapping, converted: Optional[Mapping]
+) -> Optional[Tuple[str, str]]:
+ """Pair from an already-converted row, falling back to the flat-key lookup."""
+ pair = _pair_from_converted(converted) if converted else None
+ if pair is None:
+ prompt, target = _row_input(row), _row_output(row)
+ pair = (prompt, target) if prompt and target else None
+ return pair
+
+
+def _memo_row(
+ row: Mapping, converted: Optional[Mapping], pair: Optional[Tuple[str, str]]
+) -> Optional[Mapping[str, object]]:
+ """The row the memorization probe should scan, or ``None`` if the row has no text.
+
+ Rows ``extract_row_text`` already reads are passed through unchanged, so a row's
+ own text is never altered; only rows it cannot read fall back. (Text-less and media
+ rows are left out, so in a mixed file the 32-row window can still shift.)
+ """
+ from soup_cli.utils.diagnose._common import extract_row_text
+
+ if extract_row_text(row):
+ return row
+ if converted and extract_row_text(converted):
+ return converted
+ if pair:
+ return {"text": f"{pair[0]}\n{pair[1]}"}
+ return None
+
+
+def _analyse_rows(rows: Sequence[Mapping[str, object]]) -> _ProbeInputs:
+ from soup_cli.data.formats import is_audio_format, is_vision_format
+ from soup_cli.utils.diagnose._common import MAX_PROMPT_CHARS
+
+ pairs: List[Tuple[str, str]] = []
+ memo_rows: List[Mapping[str, object]] = []
+ unreadable = too_long = plaintext = media_rows = no_answer = 0
+ media_kinds: set = set()
+ for row in rows:
+ if not isinstance(row, Mapping):
+ unreadable += 1
+ continue
+ fmt, converted = _convert_row(row)
+ if fmt is not None and (is_vision_format(fmt) or is_audio_format(fmt)):
+ media_rows += 1
+ media_kinds.add("image" if is_vision_format(fmt) else "audio")
+ continue
+ pair = _pair_with_fallback(row, converted)
+ text_row = _memo_row(row, converted, pair)
+ if fmt == "plaintext":
+ plaintext += 1
+ if pair is None and text_row is None:
+ unreadable += 1
+ continue
+ if text_row is not None:
+ memo_rows.append(text_row)
+ if pair is None and fmt != "plaintext":
+ no_answer += 1
+ if pair is not None:
+ if len(pair[0]) > MAX_PROMPT_CHARS:
+ too_long += 1
+ elif "\x00" in pair[0]:
+ unreadable += 1 # require_prompts rejects NUL bytes; skip the row, keep the probe
+ else:
+ pairs.append(pair)
+ media = " or ".join(sorted(media_kinds))
+ return _ProbeInputs(
+ pairs, memo_rows, unreadable, too_long, plaintext, media_rows, media, no_answer
+ )
+
+
+def _skipped_note(probe: _ProbeInputs) -> str:
+ parts = []
+ if probe.unreadable:
+ parts.append(f"{probe.unreadable} unreadable")
+ if probe.too_long:
+ parts.append(f"{probe.too_long} over-long")
+ if probe.no_answer:
+ parts.append(f"{probe.no_answer} without an answer")
+ if probe.media_rows:
+ parts.append(f"{probe.media_rows} need {probe.media}")
+ return ", ".join(parts)
+
+
+def _media_reason(probe: _ProbeInputs) -> str:
+ noun = {"image": "an image", "audio": "audio"}.get(probe.media, "an image or audio")
+ return f"rows need {noun}; the probes are text-only"
+
+
+def _no_pairs_reason(probe: _ProbeInputs) -> str:
+ from soup_cli.utils.diagnose._common import MAX_PROMPT_CHARS
+
+ # The dominant cause wins; ties go media > too long > no answer > plaintext > unreadable.
+ candidates = [
+ (probe.media_rows, 4, _media_reason(probe)),
+ (probe.too_long, 3, f"prompts over {MAX_PROMPT_CHARS} chars were skipped"),
+ (probe.no_answer, 2, "rows have no prompt/answer pair"),
+ (probe.plaintext, 1, "plaintext rows have no prompt/answer split"),
+ (probe.unreadable, 0, "rows could not be read as prompt/answer pairs"),
+ ]
+ count, _rank, reason = max(candidates, key=lambda item: (item[0], item[1]))
+ return reason if count else "no usable prompt/answer rows in --dataset"
+
+
def _load_dataset_rows(
dataset_path: str, label: str = "dataset path"
) -> List[Mapping[str, object]]:
@@ -202,12 +376,11 @@ def load_adapter_pair(
}
-def _looks_like_json_dataset(rows: Sequence[Mapping[str, object]]) -> bool:
- """True iff a sample of dataset outputs parse as JSON objects/arrays."""
- sample = [_row_output(r) for r in rows[:20]]
+def _targets_look_like_json(targets: Sequence[str]) -> bool:
+ """True iff a sample of dataset targets parse as JSON objects/arrays."""
parsed = 0
seen = 0
- for out in sample:
+ for out in targets[:20]:
out = out.strip()
if not out:
continue
@@ -221,6 +394,15 @@ def _looks_like_json_dataset(rows: Sequence[Mapping[str, object]]) -> bool:
return seen > 0 and parsed / seen >= 0.6
+def _looks_like_json_dataset(rows: Sequence[Mapping[str, object]]) -> bool:
+ """True iff a sample of dataset outputs parse as JSON objects/arrays."""
+ targets = []
+ for row in rows[:20]:
+ pair = _pair_for_row(row)
+ targets.append(pair[1] if pair else _row_output(row))
+ return _targets_look_like_json(targets)
+
+
def run_live_diagnose(
*,
run_id: str,
@@ -256,7 +438,6 @@ def run_live_diagnose(
"""
if not isinstance(base, str) or not base.strip():
raise ValueError("base must be a non-empty string")
- from soup_cli.utils.diagnose._common import extract_row_text
from soup_cli.utils.diagnose.forgetting import score_forgetting
from soup_cli.utils.diagnose.format import score_format
from soup_cli.utils.diagnose.memorization import score_memorization
@@ -273,6 +454,8 @@ def run_live_diagnose(
rows: List[Mapping[str, object]] = []
if dataset_path:
rows = _load_dataset_rows(dataset_path)
+ # Read the rows before any model loads, so a problem there costs nothing.
+ probe = _analyse_rows(rows)
holdout_rows: List[Mapping[str, object]] = []
if holdout_path:
@@ -299,12 +482,7 @@ def run_live_diagnose(
# --- 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]
+ forgetting_pairs = [p for p in map(_pair_for_row, holdout_rows) if p]
else:
forgetting_pairs = list(_DEFAULT_FORGETTING_PROBES)
@@ -325,19 +503,14 @@ def run_live_diagnose(
"forgetting", "--holdout has no usable prompt/answer rows"
)
- # The dataset-driven probes need rows.
- pairs = [
- (_row_input(r), _row_output(r))
- for r in rows
- if isinstance(r, Mapping)
- ]
- pairs = [(p, t) for p, t in pairs if p and t]
+ # The dataset-driven probes need rows, read through the training converters.
+ pairs = probe.pairs
if pairs:
prompts = [p for p, _ in pairs[:_PROBE_PROMPTS]]
# --- format (only when the dataset targets look like JSON) ---
- if _looks_like_json_dataset(rows):
+ if _targets_look_like_json([t for _, t in pairs]):
try:
scores["format"] = score_format(prompts, adapter_gen, kind="json")
except (ValueError, TypeError) as exc:
@@ -354,30 +527,28 @@ def run_live_diagnose(
)
except (ValueError, TypeError) as exc:
scores["mode_collapse"] = _probe_failed("mode_collapse", exc)
+ elif dataset_path:
+ # A dataset was supplied but nothing in it could be turned into a prompt/answer
+ # pair: these probes were requested and did not run (#1435).
+ reason = _no_pairs_reason(probe)
+ for mode in ("format", "mode_collapse"):
+ scores[mode] = not_run_score(mode, reason)
- # --- memorization (training-prefix echo) ---
- # score_memorization reads only text/content/prompt/instruction/messages, while
- # the pair builder also accepts question/answer, query/response and
- # input/output rows; for those it answers "nothing to check" with OK 1.00.
- if not any(extract_row_text(row) for row in rows[:_MEMORIZATION_ROWS]):
- scores["memorization"] = not_run_score(
- "memorization",
- "none of the first rows has a text, content, prompt, instruction "
- "or messages field to split",
+ # --- memorization (training-prefix echo): needs text, not prompt/answer pairs ---
+ if probe.memo_rows:
+ try:
+ scores["memorization"] = score_memorization(
+ probe.memo_rows[:_MEMORIZATION_ROWS], adapter_gen, tokenizer=tokenizer
)
- else:
- try:
- scores["memorization"] = score_memorization(
- rows[:_MEMORIZATION_ROWS], adapter_gen, tokenizer=tokenizer
- )
- except (ValueError, TypeError) as exc:
- scores["memorization"] = _probe_failed("memorization", exc)
+ except (ValueError, TypeError) as exc:
+ scores["memorization"] = _probe_failed("memorization", exc)
elif dataset_path:
- # 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 ("format", "mode_collapse", "memorization"):
- scores[mode] = not_run_score(mode, reason)
+ scores["memorization"] = not_run_score(
+ "memorization",
+ _media_reason(probe)
+ if probe.media_rows and probe.media_rows >= probe.unreadable
+ else "no row has text to split into a prefix and a suffix",
+ )
# --- contamination (no benchmark corpus supplied → neutral) ---
scores.setdefault(
@@ -404,12 +575,14 @@ def run_live_diagnose(
for mode in FAILURE_MODES:
scores.setdefault(mode, neutral_score(mode, "probe inputs unavailable"))
+ skipped = _skipped_note(probe)
return build_report(
run_id=run_id,
base=base,
adapter=adapter or "",
scores=scores,
soup_version=soup_version,
+ extras={"rows_skipped": skipped} if skipped else None,
)
diff --git a/tests/test_issue1435_diagnose_not_run.py b/tests/test_issue1435_diagnose_not_run.py
index 19de18bc..13f4adcf 100644
--- a/tests/test_issue1435_diagnose_not_run.py
+++ b/tests/test_issue1435_diagnose_not_run.py
@@ -405,13 +405,26 @@ class TestEveryProbeSite:
[QUESTION_ANSWER, QUERY_RESPONSE, INPUT_OUTPUT],
ids=["question_answer", "query_response", "input_output"],
)
- def test_memorization_with_no_splittable_text_is_not_run(self, tmp_path, monkeypatch, rows):
+ def test_memorization_reads_question_answer_style_rows(self, tmp_path, monkeypatch, rows):
+ # These rows form prompt/answer pairs but have no text-like field of their own;
+ # the pair text (prompt + answer) is what memorization scans, so it must run
+ # instead of answering "nothing to check" with OK 1.00.
report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
score = report.scores["memorization"]
- assert score.verdict == "NOT_RUN", score
- assert "text, content" in score.evidence # the new guard, not "no usable rows"
- assert report.scores["forgetting"].verdict != "NOT_RUN" # the rows do form pairs
- assert report.overall == "NOT_RUN"
+ assert score.verdict != "NOT_RUN", score
+ assert "scanned=" in score.evidence
+ assert all(s.verdict != "NOT_RUN" for s in report.scores.values())
+
+ def test_memorization_runs_when_only_some_rows_have_a_text_field(
+ self, tmp_path, monkeypatch
+ ):
+ # Half the rows carry a prompt field, half are question/answer rows: every row
+ # is scanned (any row with text is enough; one text-less row must not stop it).
+ rows = RECOGNISED[:6] + QUESTION_ANSWER[:6]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ score = report.scores["memorization"]
+ assert score.verdict != "NOT_RUN", score
+ assert "scanned=" in score.evidence
# ---------------------------------------------------------------------------
diff --git a/tests/test_issue1435_diagnose_probe_rows.py b/tests/test_issue1435_diagnose_probe_rows.py
new file mode 100644
index 00000000..186120a9
--- /dev/null
+++ b/tests/test_issue1435_diagnose_probe_rows.py
@@ -0,0 +1,473 @@
+"""Tests for Issue #1435 (PR 2): live diagnose probe inputs from real dataset formats.
+
+PR 1 reports a dataset the row builders cannot read as NOT_RUN. These tests pin that the
+common training formats (ShareGPT, Alpaca with ``input``, plaintext, mixed) now reach the
+probes as the model saw them, that vision rows and over-long prompts are handled
+explicitly, and that skipped rows are reported.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from soup_cli.utils.diagnose.memorization import split_prefix
+from tests.conftest import strip_ansi
+from tests.test_issue1435_diagnose_not_run import DATASET_MODES, _cli, _gens, _run_live
+
+SKIPPABLE = ("format", "mode_collapse")
+
+
+def _words(tag: str, count: int = 24) -> str:
+ return " ".join(f"{tag}word{j}" for j in range(count))
+
+
+def _sharegpt(i: int, answer: str | None = None) -> dict:
+ return {
+ "conversations": [
+ {"from": "human", "value": f"question {i} {_words(f'q{i}', 12)}"},
+ {"from": "gpt", "value": answer or f"answer {i} {_words(f'a{i}', 12)}"},
+ ]
+ }
+
+
+def _not_run_modes(report) -> set:
+ return {m for m, s in report.scores.items() if s.verdict == "NOT_RUN"}
+
+
+class TestPlaintext:
+ TEXTS = [_words(f"topic{i}") for i in range(12)]
+
+ def _regurgitating(self):
+ suffix = dict(split_prefix(text) for text in self.TEXTS)
+ return _gens(adapter_gen=lambda prompt: suffix.get(prompt, "ok"))
+
+ def test_memorization_runs_and_catches_regurgitation(self, tmp_path, monkeypatch):
+ rows = [{"text": text} for text in self.TEXTS]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, self._regurgitating())
+ assert report.scores["memorization"].verdict == "MAJOR"
+ assert report.overall == "MAJOR"
+
+ def test_probes_needing_a_prompt_answer_split_say_so(self, tmp_path, monkeypatch):
+ rows = [{"text": text} for text in self.TEXTS]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, self._regurgitating())
+ for mode in SKIPPABLE:
+ score = report.scores[mode]
+ assert score.verdict == "NOT_RUN", mode
+ assert "plaintext" in score.evidence
+
+ def test_cli_exit_2_on_regurgitating_plaintext(self, tmp_path, monkeypatch):
+ rows = [{"text": text} for text in self.TEXTS]
+ result, _, _ = _cli(tmp_path, monkeypatch, rows, self._regurgitating())
+ assert result.exit_code == 2
+
+
+class TestShareGPT:
+ def test_probes_run(self, tmp_path, monkeypatch):
+ rows = [_sharegpt(i) for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in DATASET_MODES:
+ assert report.scores[mode].verdict != "NOT_RUN", mode
+ assert report.overall != "NOT_RUN"
+
+ def test_conversation_text_reaches_memorization(self, tmp_path, monkeypatch):
+ rows = [_sharegpt(i) for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert "scanned=" in report.scores["memorization"].evidence
+
+ def test_json_targets_are_seen_by_the_format_probe(self, tmp_path, monkeypatch):
+ rows = [_sharegpt(i, answer=json.dumps({"n": i})) for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens()) # adapter never emits JSON
+ assert report.scores["format"].verdict == "MAJOR"
+
+
+class TestAlpaca:
+ def test_input_is_joined_to_the_instruction(self, tmp_path, monkeypatch):
+ seen: list = []
+
+ def adapter_multi(prompt, k):
+ seen.append(prompt)
+ return [f"adapter{j} p{j}q r{j}s" for j in range(k)]
+
+ rows = [
+ {"instruction": "Translate to French:", "input": f"Good morning {i}",
+ "output": f"Bonjour {i}"}
+ for i in range(12)
+ ]
+ _run_live(tmp_path, monkeypatch, rows, _gens(adapter_multi=adapter_multi))
+ assert "Translate to French:\nGood morning 0" in seen
+
+ def test_alpaca_without_input_still_works(self, tmp_path, monkeypatch):
+ rows = [{"instruction": f"Say {i}", "output": f"Said {i}"} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert not _not_run_modes(report)
+
+
+class TestFlatAndMixedRows:
+ def test_flat_question_answer_rows_keep_working(self, tmp_path, monkeypatch):
+ rows = [{"question": f"What is {i}?", "answer": f"It is {i}."} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert not _not_run_modes(report)
+
+ def test_flat_rows_reach_memorization(self, tmp_path, monkeypatch):
+ rows = [
+ {"question": f"What is {_words(f'n{i}', 10)}?", "answer": _words(f"a{i}", 12)}
+ for i in range(12)
+ ]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert "scanned=" in report.scores["memorization"].evidence
+
+ def test_mixed_formats_in_one_file(self, tmp_path, monkeypatch):
+ seen: list = []
+
+ def adapter_multi(prompt, k):
+ seen.append(prompt)
+ return [f"adapter{j} p{j}q r{j}s" for j in range(k)]
+
+ rows = []
+ for i in range(6):
+ rows.append(_sharegpt(i))
+ rows.append({"instruction": f"Say {i}", "input": "now", "output": f"Said {i}"})
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens(adapter_multi=adapter_multi))
+ assert not _not_run_modes(report)
+ # Both halves reach the probes, not just the format that used to be readable.
+ assert any(prompt.startswith("question 0") for prompt in seen)
+ assert any(prompt.startswith("Say 0\nnow") for prompt in seen)
+
+
+class TestVision:
+ def test_llava_rows_are_not_run_with_the_image_reason(self, tmp_path, monkeypatch):
+ rows = [dict(_sharegpt(i), image=f"img{i}.jpg") for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in DATASET_MODES:
+ score = report.scores[mode]
+ assert score.verdict == "NOT_RUN", mode
+ assert "image" in score.evidence
+
+
+class TestLongPrompts:
+ @staticmethod
+ def _rows():
+ return [
+ {"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
+ for i in range(12)
+ ]
+
+ def test_one_long_prompt_is_skipped_not_fatal(self, tmp_path, monkeypatch):
+ rows = self._rows()
+ rows[0]["prompt"] = "x" * 9000
+ collapsed = _gens(adapter_multi=lambda prompt, k: ["same reply"] * k)
+ report, _ = _run_live(tmp_path, monkeypatch, rows, collapsed)
+ assert report.scores["mode_collapse"].verdict == "MAJOR" # other rows still scored
+
+ def test_all_prompts_too_long_is_not_run_with_the_limit(self, tmp_path, monkeypatch):
+ rows = [dict(row, prompt="x" * 9000) for row in self._rows()]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in SKIPPABLE:
+ score = report.scores[mode]
+ assert score.verdict == "NOT_RUN", mode
+ assert "8192" in score.evidence
+
+ def test_prompt_limit_constant_matches_require_prompts(self):
+ from soup_cli.utils.diagnose import _common
+
+ assert _common.MAX_PROMPT_CHARS == 8192
+ with pytest.raises(ValueError, match="8192"):
+ _common.require_prompts(["x" * (_common.MAX_PROMPT_CHARS + 1)])
+
+
+class TestSkippedRows:
+ def _rows(self):
+ rows = [
+ {"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
+ for i in range(12)
+ ]
+ rows[0]["prompt"] = "x" * 9000
+ rows += [{"foo": 1}, {"foo": 2}]
+ return rows
+
+ def test_skips_are_counted_in_extras(self, tmp_path, monkeypatch):
+ report, _ = _run_live(tmp_path, monkeypatch, self._rows(), _gens())
+ assert report.extras["rows_skipped"] == "2 unreadable, 1 over-long"
+
+ def test_no_extras_when_nothing_is_skipped(self, tmp_path, monkeypatch):
+ rows = [{"prompt": f"Story {i}.", "completion": f"Once {i}."} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert "rows_skipped" not in report.extras
+
+ def test_cli_prints_the_skipped_note(self, tmp_path, monkeypatch):
+ _, out, _ = _cli(tmp_path, monkeypatch, self._rows(), _gens())
+ assert "Rows skipped: 2 unreadable, 1 over-long" in strip_ansi(out)
+
+
+def test_looks_like_json_dataset_keeps_its_call_shape():
+ from soup_cli.utils.diagnose.live import _looks_like_json_dataset
+
+ assert _looks_like_json_dataset([{"output": '{"a": 1}'}] * 5) is True
+ assert _looks_like_json_dataset([{"output": "plain"}] * 5) is False
+ # ShareGPT targets are read through the converters too.
+ sharegpt_json = [_sharegpt(i, answer=json.dumps({"n": i})) for i in range(5)]
+ assert _looks_like_json_dataset(sharegpt_json) is True
+
+
+TOOL_ROW = {
+ "messages": [
+ {"role": "system", "content": "You can call tools."},
+ {"role": "user", "content": "Weather in Paris?"},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "c1", "type": "function",
+ "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}]},
+ {"role": "tool", "tool_call_id": "c1", "content": "Sunny"},
+ {"role": "assistant", "content": "It is sunny in Paris."},
+ ],
+ "tools": [{"type": "function", "function": {
+ "name": "get_weather", "description": "d",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}],
+}
+
+
+def _recording(seen: list):
+ def gen(prompt):
+ seen.append(prompt)
+ return "ok"
+
+ return gen
+
+
+def _recording_multi(seen: list):
+ def gen(prompt, k):
+ seen.append(prompt)
+ return [f"adapter{j} p{j}q r{j}s" for j in range(k)]
+
+ return gen
+
+
+class TestRobustness:
+ def test_malformed_tool_schema_row_does_not_crash(self, tmp_path, monkeypatch):
+ bad = {"messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"function": "get_weather"}]}
+ rows = [
+ {"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
+ for i in range(12)
+ ] + [bad]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert report.extras["rows_skipped"] == "1 without an answer"
+ assert not _not_run_modes(report)
+
+ def test_rows_without_an_answer_are_counted(self, tmp_path, monkeypatch):
+ rows = [{"prompt": f"only a prompt {i}"} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert report.extras["rows_skipped"] == "12 without an answer"
+ for mode in SKIPPABLE:
+ assert report.scores[mode].verdict == "NOT_RUN"
+
+ def test_tool_calling_rows_give_a_pair_from_the_final_reply(self, tmp_path, monkeypatch):
+ seen: list = []
+ rows = [TOOL_ROW] * 12
+ gens = _gens(adapter_multi=_recording_multi(seen))
+ report, _ = _run_live(tmp_path, monkeypatch, rows, gens)
+ assert not _not_run_modes(report)
+ assert any("Weather in Paris?" in prompt for prompt in seen)
+ assert "rows_skipped" not in report.extras
+
+
+class TestOtherFormats:
+ def test_audio_rows_are_not_run_with_the_audio_reason(self, tmp_path, monkeypatch):
+ rows = [{"audio": f"a{i}.wav", "messages": [
+ {"role": "user", "content": "hi"}, {"role": "assistant", "content": "yo"}]}
+ for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in DATASET_MODES:
+ score = report.scores[mode]
+ assert score.verdict == "NOT_RUN", mode
+ assert "audio" in score.evidence
+
+ def test_dpo_rows_probe_with_the_prompt(self, tmp_path, monkeypatch):
+ seen: list = []
+ rows = [{"prompt": f"Pick one {i}", "chosen": f"good {i}", "rejected": f"bad {i}"}
+ for i in range(12)]
+ gens = _gens(adapter_multi=_recording_multi(seen))
+ report, _ = _run_live(tmp_path, monkeypatch, rows, gens)
+ assert "Pick one 0" in seen
+ assert not _not_run_modes(report)
+
+ def test_kto_rows_probe_with_the_prompt(self, tmp_path, monkeypatch):
+ seen: list = []
+ rows = [{"prompt": f"Rate {i}", "completion": f"fine {i}", "label": True}
+ for i in range(12)]
+ gens = _gens(adapter_multi=_recording_multi(seen))
+ report, _ = _run_live(tmp_path, monkeypatch, rows, gens)
+ assert "Rate 0" in seen
+ assert not _not_run_modes(report)
+
+ def test_multi_turn_prompt_stops_at_the_first_assistant_reply(self, tmp_path, monkeypatch):
+ seen: list = []
+ rows = [{"messages": [
+ {"role": "user", "content": f"first question {i}"},
+ {"role": "assistant", "content": f"first answer {i}"},
+ {"role": "user", "content": f"second question {i}"},
+ {"role": "assistant", "content": f"second answer {i}"}]} for i in range(12)]
+ _run_live(tmp_path, monkeypatch, rows, _gens(adapter_multi=_recording_multi(seen)))
+ assert "first question 0" in seen
+ assert not any("second question" in prompt for prompt in seen)
+
+ def test_alpaca_system_text_is_part_of_the_prompt(self, tmp_path, monkeypatch):
+ seen: list = []
+ rows = [{"instruction": f"Say {i}", "output": f"Said {i}", "system": "Be terse."}
+ for i in range(12)]
+ _run_live(tmp_path, monkeypatch, rows, _gens(adapter_multi=_recording_multi(seen)))
+ assert "Be terse.\nSay 0" in seen
+
+ def test_raft_rows_still_feed_citation_the_raw_rows(self, tmp_path, monkeypatch):
+ from unittest import mock
+
+ from soup_cli.utils.diagnose.runner import neutral_score
+
+ rows = [{"query": f"What is {i}?", "golden_doc": f"doc {i}", "answer": f"It is {i}."}
+ for i in range(12)]
+ with mock.patch(
+ "soup_cli.utils.diagnose.citation.score_citation",
+ return_value=neutral_score("citation", "mock"),
+ ) as citation:
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ passed = citation.call_args.args[0]
+ assert passed[0].get("golden_doc") == "doc 0" # raw RAFT rows, not converted ones
+ assert not _not_run_modes(report) # the flat query/answer pair is still built
+
+
+class TestReasons:
+ def test_memorization_not_run_reason_names_the_missing_text(self, tmp_path, monkeypatch):
+ rows = [{"foo": f"bar {i}"} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert "no row has text" in report.scores["memorization"].evidence
+
+ def test_dominant_cause_picks_the_reason(self, tmp_path, monkeypatch):
+ rows = [dict(_sharegpt(0), image="i.jpg")] + [
+ {"text": _words(f"t{i}")} for i in range(11)
+ ]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in SKIPPABLE:
+ evidence = report.scores[mode].evidence
+ assert "plaintext" in evidence and "image" not in evidence
+
+ def test_no_answer_rows_can_be_the_dominant_cause(self, tmp_path, monkeypatch):
+ long_row = {"prompt": "x" * 9000, "completion": "done"}
+ rows = [long_row] + [{"prompt": f"only a prompt {i}"} for i in range(11)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in SKIPPABLE:
+ evidence = report.scores[mode].evidence
+ assert "no prompt/answer pair" in evidence and "8192" not in evidence
+
+ def test_no_answer_beats_a_lone_plaintext_row(self, tmp_path, monkeypatch):
+ rows = [{"text": _words("t0")}] + [
+ {"messages": [{"role": "user", "content": f"question {i}"}]} for i in range(11)
+ ]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ for mode in SKIPPABLE:
+ evidence = report.scores[mode].evidence
+ assert "no prompt/answer pair" in evidence and "plaintext" not in evidence
+
+ def test_unreadable_rows_beat_a_lone_media_row_for_memorization(
+ self, tmp_path, monkeypatch
+ ):
+ rows = [dict(_sharegpt(0), image="i.jpg")] + [{"foo": f"bar {i}"} for i in range(11)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ evidence = report.scores["memorization"].evidence
+ assert "no row has text" in evidence and "image" not in evidence
+
+ def test_mixed_media_kinds_are_named_together(self, tmp_path, monkeypatch):
+ rows = [dict(_sharegpt(i), image=f"i{i}.jpg") for i in range(6)] + [
+ {"audio": f"a{i}.wav", "messages": [
+ {"role": "user", "content": "hi"}, {"role": "assistant", "content": "yo"}]}
+ for i in range(6)
+ ]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert report.extras["rows_skipped"] == "12 need audio or image"
+ assert "an image or audio" in report.scores["format"].evidence
+
+ def test_over_long_rows_still_reach_memorization(self, tmp_path, monkeypatch):
+ seen: list = []
+ long_prompt = " ".join(["word"] * 3000) # ~15000 chars, over the prompt limit
+ rows = [{"prompt": long_prompt, "completion": "done"} for _ in range(12)]
+ _run_live(tmp_path, monkeypatch, rows, _gens(adapter_gen=_recording(seen)))
+ assert max(len(prompt) for prompt in seen) > 3000
+
+
+def test_dpo_target_is_the_chosen_answer(tmp_path, monkeypatch):
+ # JSON in `chosen`, prose in `rejected`: the format probe only fires if chosen is the target.
+ rows = [
+ {"prompt": f"Give json {i}", "chosen": json.dumps({"n": i}), "rejected": f"plain {i}"}
+ for i in range(12)
+ ]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens()) # adapter never emits JSON
+ assert report.scores["format"].verdict == "MAJOR", report.scores["format"]
+
+
+def test_rows_are_read_before_the_model_loads(tmp_path, monkeypatch):
+ import soup_cli.utils.diagnose.live as live
+
+ order: list = []
+ real_analyse = live._analyse_rows
+
+ def analyse(rows):
+ order.append("rows")
+ return real_analyse(rows)
+
+ def fake_pair(base, adapter=None, **kw):
+ order.append("model")
+ return _gens()
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "d.jsonl").write_text(
+ "\n".join(json.dumps({"prompt": f"p{i}", "completion": f"c{i}"}) for i in range(12)),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(live, "_analyse_rows", analyse)
+ monkeypatch.setattr(live, "load_adapter_pair", fake_pair)
+ live.run_live_diagnose(run_id="r", base="b", adapter="a", dataset_path="d.jsonl")
+ assert order == ["rows", "model"]
+
+
+def test_a_null_byte_prompt_is_skipped_not_fatal(tmp_path, monkeypatch):
+ rows = [
+ {"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
+ for i in range(12)
+ ]
+ rows[0]["prompt"] = "nul\x00byte"
+ collapsed = _gens(adapter_multi=lambda prompt, k: ["same reply"] * k)
+ report, _ = _run_live(tmp_path, monkeypatch, rows, collapsed)
+ assert report.scores["mode_collapse"].verdict == "MAJOR", report.scores["mode_collapse"]
+ assert report.extras["rows_skipped"] == "1 unreadable"
+
+
+def test_rows_skipped_from_an_evidence_file_has_no_control_bytes(tmp_path, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ esc, csi = chr(0x1B), chr(0x9B)
+ (tmp_path / "ev.json").write_text(
+ json.dumps(
+ {
+ "scores": {"forgetting": {"score": 1.0, "verdict": "OK", "evidence": "fine"}},
+ "extras": {"rows_skipped": f"{esc}]0;T{esc}[2J{csi}31m3 unreadable [bold red]x[/]"},
+ }
+ ),
+ encoding="utf-8",
+ )
+ result = CliRunner().invoke(app, ["diagnose", "r1", "--evidence", "ev.json"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert f"{esc}]0;T" not in result.output
+ assert f"{esc}[2J" not in result.output
+ assert csi not in result.output
+ flat = "".join(strip_ansi(result.output).split())
+ assert "3unreadable[boldred]x[/]" in flat, result.output
+
+
+def test_an_assistant_only_row_is_not_a_pair(tmp_path, monkeypatch):
+ rows = [{"messages": [{"role": "assistant", "content": f"greeting {i}"}]} for i in range(12)]
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ assert report.scores["mode_collapse"].verdict == "NOT_RUN"
+ assert report.extras["rows_skipped"] == "12 without an answer"
diff --git a/tests/test_issue1436_forgetting_holdout.py b/tests/test_issue1436_forgetting_holdout.py
index 7e39d362..dc58667a 100644
--- a/tests/test_issue1436_forgetting_holdout.py
+++ b/tests/test_issue1436_forgetting_holdout.py
@@ -221,6 +221,64 @@ class TestForgettingProbeHoldout:
},
)
+ def test_llava_holdout_rows_are_not_a_text_only_measurement(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ holdout = tmp_path / "holdout.jsonl"
+ rows = [
+ {
+ "image": f"img{i}.png",
+ "conversations": [
+ {"from": "human", "value": f"<image>\nWhat is in picture {i}?"},
+ {"from": "gpt", "value": f"A cat {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)
+ 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"]
+ assert not any("picture" in prompt for prompt in asked)
+
+ def test_audio_holdout_rows_are_not_a_text_only_measurement(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ holdout = tmp_path / "holdout.jsonl"
+ rows = [
+ {
+ "audio": f"a{i}.wav",
+ "messages": [
+ {"role": "user", "content": f"Transcribe clip {i}"},
+ {"role": "assistant", "content": f"Hello {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)
+ 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"]
+ assert not any("clip" in prompt for prompt in asked)
+
def test_bad_holdout_path_fails_before_the_model_loads(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -256,6 +314,34 @@ class TestForgettingProbeHoldout:
assert {r["prompt"] for r in rows} <= set(asked)
assert not builtin & set(asked)
+ def test_sharegpt_holdout_rows_are_read_like_training_rows(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ holdout = tmp_path / "holdout.jsonl"
+ rows = [
+ {
+ "conversations": [
+ {"from": "human", "value": f"Held out {i}"},
+ {"from": "gpt", "value": 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)
+ report = live.run_live_diagnose(
+ run_id="r", base="b", adapter="a", holdout_path=str(holdout)
+ )
+ assert {f"Held out {i}" for i in range(5)} <= set(asked)
+ assert report.scores["forgetting"].verdict != "NOT_RUN"
+
@pytest.mark.parametrize("content", [[], [{"foo": "bar"}]])
def test_unusable_holdout_is_not_run_not_ok(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: list