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(eval): score custom tasks by stated answer; token-bound contains (#1342) (#1490)
Momoyeyu2aeda018094c
diff --git a/changelog.d/0.75.1/1490.fixed.md b/changelog.d/0.75.1/1490.fixed.mdnew file mode 100644index 00000000..05e273ff--- /dev/null+++ b/changelog.d/0.75.1/1490.fixed.md@@ -0,0 +1 @@+- `soup eval`'s custom-task `contains` scorer now requires the expected string to appear as a whole token, so `14` no longer counts as containing `4` and `#### 420` no longer contains `42`. This changes scores: a gate baseline or a `soup eval custom --run-id` result recorded with the old substring `contains` can be higher than the same outputs score now, and the baseline's scorer stamp does not notice, so re-measure those before comparing. A new `scoring: "answer"` mode compares the final answer the model states (via the same parser GRPO's `accuracy` reward uses) instead of substring-matching, and refuses task rows whose `expected` states no single answer instead of silently scoring 0 (#1342 by @Momoyeyu in #1490).diff --git a/docs/evaluation.md b/docs/evaluation.mdindex e16a06ff..c7db1e8d 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -815,11 +815,34 @@ canary search. Ordinary patterns, including single-character alternation,remain valid.```jsonl-{"prompt": "What is 2+2?", "expected": "4", "category": "math", "scoring": "exact"}+{"prompt": "What is 2+2?", "expected": "4", "category": "math", "scoring": "answer"}{"prompt": "Explain gravity", "expected": "force.*attraction", "scoring": "regex"}{"prompt": "Capital of France?", "expected": "Paris", "scoring": "contains"}```+How the string scorers read an output:++| `scoring` | Scores | `expected: "4"` vs `The answer is 4.` | vs `14` |+|---|---|---|---|+| `answer` | The final answer each side states, read with the parser GRPO's `accuracy` reward uses (`#### 4`, `\boxed{4}`, `The answer is 4.`); numbers compare by value | match | no match |+| `contains` | `expected` as a whole alphanumeric-bounded token, case-insensitive | match | no match |+| `exact` | The whole stripped output, case-insensitive | no match | no match |++`answer` refuses, at load time, an `expected` that states no single answer (a multi-line+worked solution with no `####`, an empty `\boxed{}`, a hedge between values), naming the line.+`contains` cannot read negation: `It is not 4, so 5.` still contains `4`. Its bound is an+ASCII alphanumeric run, so `4` still matches inside `3.4`, `4.5` and `v1.42.3`. `answer`+reads the answer a model *states*: `The capital of France is Paris.` scores `False` for a+gold `Paris` while `Answer: Paris` and `Paris` score `True` — prefer `answer` for math and+short-answer tasks, where the model states its answer. The eval gate's `scorer:` override+accepts `answer` too.++**Changed:** `contains` used to be a raw substring test, so it paid `14` for an expected `4`.+Scores recorded with the old test (a `soup eval gate --baseline` file or `registry://` row, or+a `soup eval custom --run-id` result) can be higher than the same outputs score now. The+baseline scorer stamp covers the bundled suites only and will not warn: re-measure those+baselines, or compare new runs only with runs made on this version.+### Auto-Eval Config (soup.yaml)```yamldiff --git a/src/soup_cli/eval/custom.py b/src/soup_cli/eval/custom.pyindex bf4bbbbe..78a891bf 100644--- a/src/soup_cli/eval/custom.py+++ b/src/soup_cli/eval/custom.py@@ -8,6 +8,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Optional+from soup_cli.utils.final_answer import answers_match, parse_completion, parse_referencefrom soup_cli.utils.safe_regex import check_config_regexMAX_EVAL_TASKS = 10_000@@ -16,7 +17,7 @@ MAX_REGEX_INPUT_LEN = 50_000TASK_NAME = "custom"VALID_SCORING = {- "exact", "contains", "regex", "semantic",+ "exact", "contains", "answer", "regex", "semantic","tool_call_match", "tool_call_name_match", "tool_call_args_subset",}@@ -124,10 +125,13 @@ def load_eval_tasks(path: "Path | str") -> list[EvalTask]:f"Line {line_num}: invalid scoring '{scoring}', "f"must be one of: {', '.join(sorted(VALID_SCORING))}")+ expected = str(row.get("expected", ""))+ if scoring == "answer":+ require_single_answer(expected, f"Line {line_num}")tasks.append(EvalTask(prompt=str(row["prompt"]),- expected=str(row.get("expected", "")),+ expected=expected,category=str(row.get("category", "default")),scoring=scoring,metadata={@@ -142,14 +146,38 @@ def load_eval_tasks(path: "Path | str") -> list[EvalTask]:return tasks+def require_single_answer(expected: str, where: str) -> None:+ """Refuse an ``expected`` that states no single answer for ``scoring: "answer"``."""+ if parse_reference(expected) is None:+ raise ValueError(+ f"{where}: 'expected' {expected!r} states no single answer for scoring 'answer'; "+ "give a bare answer, or end it with '#### <answer>' or \\boxed{<answer>}"+ )++def score_exact(output: str, expected: str) -> bool:- """Exact string match (case-insensitive, stripped)."""+ """Whole-output match (case-insensitive, stripped); ``The answer is 4.`` is not ``4``."""return output.strip().lower() == expected.strip().lower()def score_contains(output: str, expected: str) -> bool:- """Check if expected string is contained in output (case-insensitive)."""- return expected.strip().lower() in output.strip().lower()+ """True when ``expected`` appears in ``output`` as a whole alnum-bounded token.++ Case-insensitive. ``14`` does not contain ``4``, and ``#### 420`` does not contain+ ``42``. A token match cannot read negation (``not 42, so 41`` still contains ``42``);+ use ``scoring: "answer"`` to compare the answer a model states.+ """+ needle = expected.strip()+ if not needle:+ return True+ pattern = r"(?<![A-Za-z0-9])" + re.escape(needle) + r"(?![A-Za-z0-9])"+ return re.search(pattern, output, re.IGNORECASE) is not None+++def score_answer(output: str, expected: str) -> bool:+ """Compare the final answers both sides state, with GRPO's ``accuracy`` parser."""+ reference = parse_reference(expected)+ return reference is not None and answers_match(parse_completion(output), reference)def score_regex(output: str, expected: str) -> bool:@@ -289,6 +317,7 @@ def tool_call_args_subset(output: str, expected: str) -> float:SCORING_FUNCTIONS = {"exact": score_exact,"contains": score_contains,+ "answer": score_answer,"regex": score_regex,"tool_call_match": tool_call_match,"tool_call_name_match": tool_call_name_match,diff --git a/src/soup_cli/eval/gate.py b/src/soup_cli/eval/gate.pyindex 020dafe0..624fb43d 100644--- a/src/soup_cli/eval/gate.py+++ b/src/soup_cli/eval/gate.py@@ -63,7 +63,7 @@ class GateTask(BaseModel):tasks: Optional[str] = Field(default=None, description="JSONL file of custom eval tasks",)- scorer: Optional[Literal["exact", "contains", "regex", "semantic"]] = Field(+ scorer: Optional[Literal["exact", "contains", "answer", "regex", "semantic"]] = Field(default=None, description="Scorer for type=custom",)# type=judge@@ -534,7 +534,7 @@ def _run_custom_task("""Run a type=custom task and return its aggregate score in [0, 1]."""from dataclasses import replace- from soup_cli.eval.custom import load_eval_tasks, score_task+ from soup_cli.eval.custom import load_eval_tasks, require_single_answer, score_taskif not task.tasks:raise ValueError(f"task '{task.name}' is type=custom but 'tasks' is missing")@@ -542,6 +542,9 @@ def _run_custom_task(if not tasks:return 0.0# Override scoring if the suite specified one (EvalTask.scoring field)+ if task.scorer == "answer":+ for row, eval_task in enumerate(tasks, start=1):+ require_single_answer(eval_task.expected, f"task '{task.name}' row {row}")if task.scorer is not None:tasks = [replace(t, scoring=task.scorer) for t in tasks]total = 0.0diff --git a/tests/test_issue1342_custom_eval_answer_scoring.py b/tests/test_issue1342_custom_eval_answer_scoring.pynew file mode 100644index 00000000..70f4e1b3--- /dev/null+++ b/tests/test_issue1342_custom_eval_answer_scoring.py@@ -0,0 +1,118 @@+"""#1342: custom eval scores the answer a model states, not its raw string.++``scoring: "answer"`` reads ``expected`` and the output with ``soup_cli.utils.final_answer``+(the parser GRPO's ``accuracy`` reward uses). ``contains`` only matches ``expected`` as a whole+alnum-bounded token, so ``14`` no longer pays for ``4``. ``exact`` still compares the output.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from soup_cli.eval.custom import EvalTask, load_eval_tasks, score_contains, score_task+from soup_cli.eval.gate import EvalSuite, GateTask, run_gate++# (expected, output, truth) -- the table in #1342.+_TABLE = [+ ("4", "4.", True),+ ("4", "2 + 2 = 4", True),+ ("4", "The answer is 4.", True),+ ("4", "#### 4", True),+ ("4", "14", False),+ ("42", "#### 420", False),+ ("42", "It is not 42, so the answer is 41.", False),+ ("6*7=42\n#### 42", "#### 42", True),+]+++def _write(path: Path, rows: list[dict]) -> Path:+ path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")+ return path++[email protected](("expected", "output", "truth"), _TABLE)+def test_answer_mode_gets_every_row_right(expected, output, truth):+ result = score_task(EvalTask(prompt="q", expected=expected, scoring="answer"), output)+ assert result.matched is truth+ assert result.score == (1.0 if truth else 0.0)++[email protected](("expected", "output"), [("4", "14"), ("42", "#### 420")])+def test_contains_no_longer_pays_digits_inside_another_number(expected, output):+ assert score_contains(output, expected) is False+++ ("expected", "output"),+ [("4", "2 + 2 = 4"), ("4", "#### 4"), ("Paris", "It is paris."), ("-3", "x = -3")],+)+def test_contains_still_pays_a_standalone_token(expected, output):+ assert score_contains(output, expected) is True+++def test_contains_negation_is_a_documented_limit():+ # A token match cannot tell "not 42" from "42"; use scoring "answer" for that.+ assert score_contains("It is not 42, so the answer is 41.", "42") is True+++def test_contains_with_an_empty_expected_keeps_matching():+ assert score_contains("anything", "") is True+++def test_answer_mode_loads_a_readable_expected(tmp_path):+ path = _write(tmp_path / "t.jsonl", [{"prompt": "2+2?", "expected": "4", "scoring": "answer"}])+ assert load_eval_tasks(str(path))[0].scoring == "answer"+++ "expected",+ ["", "Step 1.\nStep 2.", "6*7=42\n####", r"\boxed{}", "The answer is either 41 or 42."],+)+def test_answer_mode_refuses_an_expected_with_no_single_answer(tmp_path, expected):+ rows = [+ {"prompt": "ok", "expected": "4", "scoring": "answer"},+ {"prompt": "bad", "expected": expected, "scoring": "answer"},+ ]+ with pytest.raises(ValueError, match=r"^Line 2: .*scoring 'answer'"):+ load_eval_tasks(str(_write(tmp_path / "t.jsonl", rows)))+++def test_gate_answer_scorer_overrides_the_rows(tmp_path):+ path = _write(tmp_path / "t.jsonl", [{"prompt": "2+2?", "expected": "4"}])+ suite = EvalSuite(+ suite="s",+ tasks=[GateTask(type="custom", name="m", threshold=1.0, tasks=str(path), scorer="answer")]+ )+ result = run_gate(suite, generate_fn=lambda _prompt: "The answer is 4.")+ assert result.task_results[0].score == 1.0+++def test_gate_answer_scorer_refuses_an_unreadable_expected(tmp_path):+ path = _write(tmp_path / "t.jsonl", [{"prompt": "q", "expected": "Step 1.\nStep 2."}])+ suite = EvalSuite(+ suite="s",+ tasks=[GateTask(type="custom", name="m", threshold=1.0, tasks=str(path), scorer="answer")]+ )+ (task,) = run_gate(suite, generate_fn=lambda _prompt: "4").task_results+ assert task.score is None and not task.passed+ assert "row 1" in task.error and "scoring 'answer'" in task.error++++ ("expected", "output", "truth"),+ [+ ("C++", "I like C++ a lot", True),+ ("a.b", "axb", False),+ ("a.b", "see a.b here", True),+ ("4|5", "5", False),+ ("[0]", "x [0] y", True),+ ("(", "a ( b", True),+ ],+)+def test_contains_reads_expected_literally(expected, output, truth):+ """`expected` is data, never a pattern: regex metacharacters match themselves."""+ assert score_contains(output, expected) is truth