Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(data): give data score real benchmark evidence (#1448 slice) (#1518)
Tala3a04d9a44dc
diff --git a/changelog.d/0.75.1/1518.changed.md b/changelog.d/0.75.1/1518.changed.mdnew file mode 100644index 00000000..e8e3bc9c--- /dev/null+++ b/changelog.d/0.75.1/1518.changed.md@@ -0,0 +1 @@+- **Breaking for `soup data score --benchmarks` / `-b` without comparison texts:** benchmark names are labels, not bundled corpora; the command now refuses labels alone by name and asks for `--benchmark-file`. With a file, labels are validated only, not corpus selectors; help, docs and an execution note state that all file texts are compared. Plain scoring reports decontamination as not run instead of a misleading zero. The new cwd-contained operator JSONL option passes actual text and `--threshold` to the existing 8-gram scorecard kernel, without benchmark downloads or a new scoring algorithm. Invalid, empty, truncated or unusable benchmark evidence fails before a scorecard is printed. The shared loader's strict mode is opt-in; other callers retain their previous behavior. This covers only the data-score item, not the remaining command paths. (#1448 by @taljeon in #1518)diff --git a/docs/commands.md b/docs/commands.mdindex 89c251f6..19d8f2b7 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -151,6 +151,8 @@ soup data mix BETA mixture-weight optimiser (prosoup data forge --docs ./docs --task sft --target-rows 1000 Synthetic data pipeline + provenancesoup data forge --docs ./docs --hub modelscope --teacher owner/name Pre-fetch the teacher from an alternative hubsoup data score --input rows.jsonl Composite quality scorecard (PII + keyword triage + lang + edu)+soup data score --input rows.jsonl --benchmark-file benchmark.jsonl --threshold 0.8 Score with real n-gram comparison texts+soup data score ... -b gsm8k --benchmark-file benchmark.jsonl Labels are validated only, not corpus selectors; all file texts are comparedsoup data decontaminate --input rows.jsonl --benchmarks mmlu,gsm8k Drop benchmark-overlap rowssoup data toxicity --input rows.jsonl -o tox.jsonl Flag abuse-keyword matches (heuristic)soup data langdetect --input rows.jsonl -o tagged.jsonl Tag each row with language codediff --git a/docs/data.md b/docs/data.mdindex cdad0c55..5e75077c 100644--- a/docs/data.md+++ b/docs/data.md@@ -1064,6 +1064,9 @@ Composite, lightweight data-quality triage — no GPU, no 200 MB Presidio model:# Single-shot composite scorecardsoup data score --input training.jsonl+# Include real operator-supplied comparison texts (no benchmark corpora are bundled)+soup data score --input training.jsonl --benchmark-file benchmark.jsonl --threshold 0.8+# Standalone subcommands — JSONL-in, enriched JSONL-outsoup data pii --input training.jsonl --output pii_flagged.jsonlsoup data toxicity --input training.jsonl --output tox_flagged.jsonl --threshold 0.1@@ -1072,7 +1075,24 @@ soup data educational --input training.jsonl --output scored.jsonlsoup data decontaminate --input training.jsonl --benchmarks mmlu,gsm8k,humaneval --output clean.jsonl```-The scorecard reports PII matches, abuse-keyword matches, language distribution, mean heuristic educational value, and decontamination removals. PII detection uses a narrow ReDoS-hardened regex set (email / phone / SSN / credit-card) with a 50 KB pre-cap on every input. Language detection is a stopword heuristic across six languages. `soup data toxicity` is retained as a compatible command name, but its output is explicitly an abuse-keyword heuristic, not a toxicity classifier. Ambiguous technical and medical terms such as process `kill`, thread `die`, and heart `attack` are not treated as standalone safety signals. This trades one known failure mode for explicit limitations: in maintainer review, 9 of 10 held-out abusive examples scored zero and 10 of 12 benign technical or editorial examples were flagged at the default threshold. Use it only for keyword triage, never as a safety decision. The default Magpie quality filter therefore applies only non-empty and educational heuristics; provide an explicit model-backed policy outside Soup when safety classification is required. The `[data-pro]` extra currently adds `langdetect` and Presidio only; it does not install Llama Guard or FineWeb-Edu. Decontamination uses n-gram containment against benchmark corpora: use `--benchmarks mmlu,gsm8k` for built-in allowlist, or `--benchmark-file custom_benchmark.jsonl` for your own corpus.+`data score` shows decontamination as **not run**, not a measured zero, unless+`--benchmark-file` supplies actual comparison texts. `--benchmarks` / `-b`+contains allowlisted labels only and now requires that file; names alone do not+download or bundle benchmark corpora. This is a breaking refusal for the formerly+silent `data score -b ...` path (#1448). Use `--benchmark-file` with or without+labels. With a file, labels are **validated only**: they do not select or filter+its rows, and the command prints a note saying so. All supplied file texts enter+the same comparison corpus, so omitting labels or changing one valid label to+another does not change the removal count. The file's JSONL is bounded and+cwd-contained by the shared loader, with strict+parsing: malformed/non-object rows, empty files and rows without usable 8-gram+text are refused before the scorecard is printed. Text comes from `text`,+`content`, or `messages[].content`, via the shared extractor. The fixed 8-gram+heuristic uses `--threshold`; a resulting zero describes only those supplied+texts, not absence of contamination against every public benchmark. The other+input/standalone loader paths keep their previous tolerant behavior.++The scorecard reports PII matches, abuse-keyword matches, language distribution, mean heuristic educational value, and decontamination removals. PII detection uses a narrow ReDoS-hardened regex set (email / phone / SSN / credit-card) with a 50 KB pre-cap on every input. Language detection is a stopword heuristic across six languages. `soup data toxicity` is retained as a compatible command name, but its output is explicitly an abuse-keyword heuristic, not a toxicity classifier. Ambiguous technical and medical terms such as process `kill`, thread `die`, and heart `attack` are not treated as standalone safety signals. This trades one known failure mode for explicit limitations: in maintainer review, 9 of 10 held-out abusive examples scored zero and 10 of 12 benign technical or editorial examples were flagged at the default threshold. Use it only for keyword triage, never as a safety decision. The default Magpie quality filter therefore applies only non-empty and educational heuristics; provide an explicit model-backed policy outside Soup when safety classification is required. The `[data-pro]` extra currently adds `langdetect` and Presidio only; it does not install Llama Guard or FineWeb-Edu. Decontamination uses n-gram containment against caller-supplied texts: `--benchmarks mmlu,gsm8k` selects allowlisted labels only; use `--benchmark-file custom_benchmark.jsonl` for actual comparison data.## Remote Datasets (S3 / GCS / Azure / OCI)diff --git a/src/soup_cli/commands/data_score.py b/src/soup_cli/commands/data_score.pyindex e5a5ade0..c9a99976 100644--- a/src/soup_cli/commands/data_score.py+++ b/src/soup_cli/commands/data_score.py@@ -48,7 +48,14 @@ def score(input: str = typer.Option(..., "--input", "-i", help="JSONL input under cwd."),benchmarks: Optional[str] = typer.Option(None, "--benchmarks", "-b",- help="Comma-separated benchmark names (e.g. mmlu,gsm8k).",+ help=(+ "Benchmark labels (e.g. mmlu,gsm8k), validated only; they do not select or filter "+ "--benchmark-file texts. Requires --benchmark-file; corpora are not bundled."+ ),+ ),+ benchmark_file: Optional[str] = typer.Option(+ None, "--benchmark-file",+ help="Operator-supplied benchmark JSONL under cwd, with usable 8-gram text in every row.",),threshold: float = typer.Option(0.8, "--threshold",@@ -57,7 +64,13 @@ def score(),):"""Composite data-quality scorecard (PII + keyword triage + lang + edu + dec)."""- from soup_cli.utils.data_score import BENCHMARKS, compute_scorecard+ from soup_cli.utils.data_score import (+ BENCHMARKS,+ compute_scorecard,+ extract_row_text,+ load_jsonl_rows,+ ngram_set,+ )rows = _read_rows(input)bench_list: List[str] = []@@ -73,11 +86,35 @@ def score()bench_list.append(canonical)+ if bench_list and not benchmark_file:+ _exit("score --benchmarks labels need --benchmark-file; benchmark corpora are not bundled")+ benchmark_texts: List[str] = []+ if benchmark_file:+ try:+ bench_rows = load_jsonl_rows(benchmark_file, strict=True)+ for index, row in enumerate(bench_rows, 1):+ text = extract_row_text(row)+ if not ngram_set(text, n=8):+ raise ValueError(f"row {index} has no usable 8-gram text")+ benchmark_texts.append(text)+ if not benchmark_texts:+ raise ValueError("no benchmark texts were supplied")+ except (TypeError, ValueError, FileNotFoundError, OSError) as exc:+ _exit(f"--benchmark-file: {exc}")+ console.print(f"[cyan]Loaded {len(benchmark_texts)} operator-supplied benchmark texts[/]")+ if bench_list:+ console.print(+ "[yellow]Note:[/] "+ f"--benchmarks labels ({', '.join(bench_list)}) are validated only; "+ "they do not select or filter comparison texts. "+ "All --benchmark-file texts are compared."+ )+try:report = compute_scorecard(rows,benchmarks=bench_list,- decontaminate_texts=None,+ benchmark_texts=benchmark_texts if benchmark_file else None,decontaminate_threshold=threshold,)except (TypeError, ValueError) as exc:@@ -90,7 +127,10 @@ def score(table.add_row("PII flagged", str(report.pii_flagged))table.add_row("Abuse-keyword flagged", str(report.toxic_flagged))table.add_row("Edu mean", f"{report.educational_mean:.3f}")- table.add_row("Decontaminated", str(report.decontaminated_removed))+ table.add_row(+ "Decontaminated",+ str(report.decontaminated_removed) if benchmark_file else "not run (no benchmark texts)",+ )for lang, count in sorted(report.languages.items(), key=lambda kv: -kv[1]):table.add_row(f"lang:{escape(lang)}", str(count))console.print(table)diff --git a/src/soup_cli/utils/data_score.py b/src/soup_cli/utils/data_score.pyindex a0a36f8c..0444197b 100644--- a/src/soup_cli/utils/data_score.py+++ b/src/soup_cli/utils/data_score.py@@ -39,8 +39,8 @@ _MAX_ROWS = 1_000_000_MAX_FILE_BYTES = 1024 * 1024 * 1024 # 1 GiB_MAX_PATH_LEN = 4096-# Closed allowlist for `--benchmarks`. Live n-gram corpora for these-# benchmarks ship in v0.47.1; for now we accept caller-supplied texts.+# Closed label allowlist for `--benchmarks`. Corpora are not bundled;+# decontamination requires caller-supplied texts.BENCHMARKS: Mapping[str, str] = MappingProxyType({"mmlu": "MMLU multiple-choice questions",@@ -487,13 +487,17 @@ def compute_scorecard(*,benchmarks: Sequence[str] = (),decontaminate_texts: Optional[Mapping[str, Sequence[str]]] = None,+ benchmark_texts: Optional[Sequence[str]] = None,decontaminate_threshold: float = 0.8,) -> ScoreReport:"""Compute the composite scorecard over a row sequence.``benchmarks`` is the closed allowlist of benchmark names to consider;``decontaminate_texts`` maps benchmark name → list of texts (caller- supplies the corpora; live MMLU/GSM8K loaders ship in v0.47.1).+ supplies the corpora). ``benchmark_texts`` supplies an operator corpus+ without pretending it is one of the named benchmarks. An explicit corpus+ must be nonempty and each text must have usable 8-grams; None keeps the+ legacy no-comparison behavior. No corpora are bundled."""_require_unit_float(decontaminate_threshold, name="decontaminate_threshold")for b in benchmarks:@@ -501,6 +505,16 @@ def compute_scorecard(raise ValueError(f"unknown benchmark: {b!r}")dec_texts: List[str] = []+ if benchmark_texts is not None:+ if isinstance(benchmark_texts, (str, bytes)) or not isinstance(benchmark_texts, Sequence):+ raise TypeError("benchmark_texts must be a sequence of texts, not a string")+ if not benchmark_texts:+ raise ValueError("benchmark_texts must contain usable 8-gram texts")+ for text in benchmark_texts:+ text = _require_str(text, name="benchmark text")+ if not ngram_set(text, n=8):+ raise ValueError("benchmark_texts must contain usable 8-gram texts")+ dec_texts.append(text)if decontaminate_texts:for b in benchmarks:seq = decontaminate_texts.get(b) or []@@ -587,26 +601,32 @@ def _check_input_path(path: Any) -> str:return os.path.realpath(path)-def load_jsonl_rows(path: Any) -> List[Mapping[str, Any]]:- """Read a JSONL file under cwd; skip malformed lines silently."""+def load_jsonl_rows(path: Any, *, strict: bool = False) -> List[Mapping[str, Any]]:+ """Read bounded JSONL under cwd; optionally refuse malformed/non-object rows."""target = _check_input_path(path)size = os.path.getsize(target)if size > _MAX_FILE_BYTES:raise ValueError(f"file exceeds {_MAX_FILE_BYTES} bytes")out: List[Mapping[str, Any]] = []with open(target, "r", encoding="utf-8-sig") as fh:- for line in fh:+ for line_number, line in enumerate(fh, 1):line = line.strip()if not line:continueif len(out) >= _MAX_ROWS:+ if strict:+ raise ValueError(f"file exceeds {_MAX_ROWS} rows")breaktry:row = json.loads(line)- except json.JSONDecodeError:+ except json.JSONDecodeError as exc:+ if strict:+ raise ValueError(f"line {line_number} is not valid JSON") from exccontinueif isinstance(row, Mapping):out.append(row)+ elif strict:+ raise ValueError(f"line {line_number} must be a JSON object")return outdiff --git a/tests/test_issue1448_data_score_benchmarks.py b/tests/test_issue1448_data_score_benchmarks.pynew file mode 100644index 00000000..47d7c814--- /dev/null+++ b/tests/test_issue1448_data_score_benchmarks.py@@ -0,0 +1,204 @@+"""#1448 data-score slice: comparison evidence reaches the real consumer."""++import json+import re++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.utils import data_score+from tests.conftest import strip_ansi++CORPUS = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima"+PARTIAL = "alpha bravo charlie delta echo foxtrot golf hotel other fresh tokens today"+++def score_input(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ path = tmp_path / "rows.jsonl"+ path.write_text(json.dumps({"text": CORPUS}) + "\n", encoding="utf-8")+ return path+++def _file(tmp_path, rows):+ path = tmp_path / "bench.jsonl"+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+ return path+++def _score(path, *args):+ return CliRunner().invoke(app, ["data", "score", "-i", str(path), *args])+++def _plain(result):+ return " ".join(strip_ansi(result.output).replace("│", " ").split())++[email protected]("labels", [[], ["-b", "gsm8k,mmlu"]], ids=["file", "labels-and-file"])+def test_file_texts_and_threshold_reach_real_decontamination(+ score_input, tmp_path, monkeypatch, labels+):+ seen = []+ original = data_score.decontaminate_rows++ def spy(rows, texts, **kwargs):+ seen.append((texts, kwargs))+ return original(rows, texts, **kwargs)++ monkeypatch.setattr(data_score, "decontaminate_rows", spy)+ bench = _file(tmp_path, [{"text": CORPUS}])+ result = _score(score_input, *labels, "--benchmark-file", str(bench), "--threshold", "0.73")+ assert result.exit_code == 0, result.output+ assert seen == [([CORPUS], {"n": 8, "threshold": 0.73})]+ assert re.search(r"Decontaminated\s+1", _plain(result))++[email protected]("threshold,removed", [("0.1", 1), ("0.9", 0)])+def test_threshold_changes_real_removed_count(score_input, tmp_path, threshold, removed):+ score_input.write_text(json.dumps({"text": PARTIAL}) + "\n", encoding="utf-8")+ bench = _file(tmp_path, [{"text": CORPUS}])+ result = _score(score_input, "--benchmark-file", str(bench), "--threshold", threshold)+ assert result.exit_code == 0, result.output+ assert re.search(rf"Decontaminated\s+{removed}", _plain(result))+++def test_labels_alone_are_refused_instead_of_a_clean_zero(score_input):+ result = _score(score_input, "-b", "gsm8k,mmlu", "--threshold", "0.01")+ assert result.exit_code != 0+ output = _plain(result)+ assert "--benchmarks" in output and "--benchmark-file" in output+ assert "not bundled" in output+ assert "Data Scorecard" not in output+++def test_plain_scoring_distinguishes_not_run_from_measured_zero(score_input):+ result = _score(score_input)+ assert result.exit_code == 0, result.output+ assert "Decontaminated" in _plain(result)+ assert "not run" in _plain(result)+++ "row", [{"content": CORPUS}, {"messages": [{"role": "user", "content": CORPUS}]}]+)+def test_file_uses_the_shared_text_extractor(score_input, tmp_path, row):+ bench = _file(tmp_path, [row])+ result = _score(score_input, "--benchmark-file", str(bench))+ assert result.exit_code == 0, result.output+ assert re.search(r"Decontaminated\s+1", _plain(result))++[email protected]("rows", [[], [{"text": ""}], [{"number": 42}], [{"text": "too short"}]])+def test_unusable_corpus_is_refused(score_input, tmp_path, rows):+ bench = _file(tmp_path, rows)+ result = _score(score_input, "--benchmark-file", str(bench))+ assert result.exit_code != 0+ assert "--benchmark-file" in _plain(result)+ assert "Data Scorecard" not in _plain(result)+++def test_bad_corpus_path_is_refused(score_input, tmp_path):+ result = _score(score_input, "--benchmark-file", str(tmp_path.parent / "outside.jsonl"))+ assert result.exit_code != 0+ assert "--benchmark-file" in _plain(result)+ assert "Data Scorecard" not in _plain(result)+++def test_unknown_label_still_fails_with_a_corpus(score_input, tmp_path):+ bench = _file(tmp_path, [{"text": CORPUS}])+ result = _score(score_input, "-b", "unknown", "--benchmark-file", str(bench))+ assert result.exit_code != 0+ assert "unknown benchmark" in _plain(result)+++def test_help_explains_labels_do_not_select_comparison_texts():+ result = CliRunner().invoke(app, ["data", "score", "--help"])+ assert result.exit_code == 0, result.output+ output = _plain(result)+ assert "validated only" in output+ assert "do not select or filter" in output++[email protected]("label", ["gsm8k", "mmlu"])+def test_labels_with_file_report_validation_only_without_selecting_texts(+ score_input, tmp_path, label+):+ bench = _file(tmp_path, [{"text": CORPUS}])+ result = _score(score_input, "-b", label, "--benchmark-file", str(bench))+ assert result.exit_code == 0, result.output+ output = _plain(result)+ assert f"--benchmarks labels ({label}) are validated only" in output+ assert "do not select or filter" in output+ assert re.search(r"Decontaminated\s+1", output)+++def test_file_without_labels_does_not_print_a_label_note(score_input, tmp_path):+ bench = _file(tmp_path, [{"text": CORPUS}])+ result = _score(score_input, "--benchmark-file", str(bench))+ assert result.exit_code == 0, result.output+ assert "validated only" not in _plain(result)+ assert re.search(r"Decontaminated\s+1", _plain(result))++[email protected]("bad_row", ["not-json", "[]", '{"number": 42}'])+def test_partially_unusable_corpus_cannot_report_a_clean_result(score_input, tmp_path, bad_row):+ bench = _file(tmp_path, [{"text": CORPUS}])+ bench.write_text(bench.read_text(encoding="utf-8") + bad_row + "\n", encoding="utf-8")+ result = _score(score_input, "--benchmark-file", str(bench))+ assert result.exit_code != 0+ assert "--benchmark-file" in _plain(result)+ assert "Data Scorecard" not in _plain(result)+++def test_strict_loader_is_opt_in(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ path = _file(tmp_path, [{"text": CORPUS}])+ path.write_text(path.read_text(encoding="utf-8") + "bad-json\n", encoding="utf-8")+ assert data_score.load_jsonl_rows(str(path)) == [{"text": CORPUS}]+ with pytest.raises(ValueError, match="line 2"):+ data_score.load_jsonl_rows(str(path), strict=True)+++def test_row_cap_cannot_silently_truncate_the_benchmark_evidence(+ score_input, tmp_path, monkeypatch+):+ monkeypatch.setattr(data_score, "_MAX_ROWS", 1)+ bench = _file(tmp_path, [{"text": CORPUS}, {"text": CORPUS}])+ result = _score(score_input, "--benchmark-file", str(bench))+ assert result.exit_code != 0+ assert "--benchmark-file" in _plain(result)+ assert "exceeds 1 rows" in _plain(result)+ assert "Data Scorecard" not in _plain(result)+++def test_explicit_texts_do_not_need_a_false_builtin_label():+ report = data_score.compute_scorecard([{"text": CORPUS}], benchmark_texts=[CORPUS])+ assert report.decontaminated_removed == 1+++def test_legacy_named_corpora_remain_supported():+ report = data_score.compute_scorecard(+ [{"text": CORPUS}], benchmarks=["mmlu"], decontaminate_texts={"mmlu": [CORPUS]}+ )+ assert report.decontaminated_removed == 1++[email protected]("bad", [CORPUS, True, [42]])+def test_core_rejects_invalid_explicit_text_shapes(bad):+ with pytest.raises(TypeError):+ data_score.compute_scorecard([{"text": CORPUS}], benchmark_texts=bad)++[email protected]("texts", [[], [""], ["too short"], ["!!!"], [CORPUS, "short"]])+def test_core_cannot_present_unusable_explicit_corpus_as_a_measured_zero(texts):+ with pytest.raises(ValueError, match="usable 8-gram"):+ data_score.compute_scorecard([{"text": CORPUS}], benchmark_texts=texts)+++def test_core_none_preserves_legacy_no_comparison():+ report = data_score.compute_scorecard([{"text": CORPUS}], benchmark_texts=None)+ plain = data_score.compute_scorecard([{"text": CORPUS}])+ assert report.decontaminated_removed == plain.decontaminated_removed == 0+ assert report.total == plain.total == 1