diff --git a/CHANGELOG.md b/CHANGELOG.md index 81d61ba..71db3dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,20 @@ endorsed by Adaption Labs. ### Added +- `verify` command (`adaption-kit verify`) to prove rows are correct before you + adapt them: math answers are checked for equivalence against a gold column + (normalized string, then numeric, then symbolic via sympy if installed), and + code solutions are executed against their unit tests in a sandboxed subprocess + and kept only if every test passes. With `--out` it writes only the verified + rows. Symbolic math needs the optional `verify` extra (sympy); without it, math + falls back to string and numeric checks and says so. Code verification is pure + standard library. +- `decontaminate` command (`adaption-kit decontaminate`) to remove any training + row that overlaps a benchmark test set by an n-gram (default 13), so the + improvement number is not inflated by benchmark overlap. With `--out` it writes + the cleaned rows. +- Optional `verify` extra (`pip install -e ".[verify]"`) that adds sympy for the + symbolic math equivalence check. - `doctor` command to check your environment and configuration (in progress). - `suggest` command to recommend recipes and brand controls for your domain (in progress). diff --git a/README.md b/README.md index d8ebef8..feae1d1 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ and skip the small mistakes that cost real time and credits the first time aroun - `adaption-kit doctor` - check your setup in one shot: Python, the SDK, your env vars, the host. - `adaption-kit lint` - preflight linter for your dataset, run it before you pay. +- `adaption-kit verify` - prove math and code rows are correct before you adapt them. +- `adaption-kit decontaminate` - remove rows that overlap a public benchmark by an n-gram. - `adaption-kit suggest` - look at your file and recommend the column mapping to use. - `adaption-kit convert` - convert between CSV, JSONL, and Parquet. - `adaption-kit estimate` - quote credits and time before a run. @@ -84,6 +86,9 @@ Optional extras: # the SDK-backed run and publish helpers pip install -e ".[sdk]" +# the symbolic math check used by 'adaption-kit verify --kind math' +pip install -e ".[verify]" + # everything for the cookbook notebooks pip install -e ".[notebooks]" ``` @@ -121,7 +126,7 @@ right. Fix the warnings, then move on to `estimate` and `run`. | Path | What is in it | |------|----------------| -| `adaption_kit/` | the Python package and the `adaption-kit` CLI (`doctor`, `lint`, `suggest`, `convert`, `estimate`, `run`, `publish`, `card`, `cover`) | +| `adaption_kit/` | the Python package and the `adaption-kit` CLI (`doctor`, `lint`, `verify`, `decontaminate`, `suggest`, `convert`, `estimate`, `run`, `publish`, `card`, `cover`) | | `guides/` | `quickstart`, `gotchas`, `column-mapping`, `recipes-and-controls`, `release-checklist` | | `cookbook/` | runnable notebooks that walk the full lifecycle | | `templates/` | dataset schemas, dataset and model cards, a cover, and Kaggle metadata | @@ -167,7 +172,9 @@ flowchart TD Q1 -- no --> Sug[adaption-kit suggest] Q1 -- yes --> Lint[adaption-kit lint] Sug --> Lint - Lint --> Est[adaption-kit estimate] + Lint --> Ver[adaption-kit verify
math or code] + Ver --> Dec[adaption-kit decontaminate
against benchmarks] + Dec --> Est[adaption-kit estimate] Est --> Run[adaption-kit run
pilot first] Run --> Q2{number look good?} Q2 -- no --> Tune[change one lever] @@ -176,7 +183,7 @@ flowchart TD Full --> Pub[adaption-kit publish] classDef cmd fill:#0b7285,stroke:#08505c,color:#ffffff; classDef gate fill:#e7f5ff,stroke:#1c7ed6,color:#0b4884; - class Doc,Sug,Lint,Est,Run,Tune,Full,Pub cmd; + class Doc,Sug,Lint,Ver,Dec,Est,Run,Tune,Full,Pub cmd; class Q1,Q2 gate; ``` @@ -209,7 +216,9 @@ See [`graphics/credit-safe-run.md`](./graphics/credit-safe-run.md). Estimate, pi ```mermaid flowchart TD - A([lint your dataset]) --> B[estimate the run] + A([lint your dataset]) --> V[verify math and code rows
keep only the ones that pass] + V --> X[decontaminate against benchmarks] + X --> B[estimate the run] B --> C[pilot on a small max_rows slice] C --> D{improvement_percent} D -- low --> E[change one lever
a recipe or a brand control] @@ -218,7 +227,7 @@ flowchart TD F --> G([publish to Hugging Face and Kaggle]) classDef step fill:#0b7285,stroke:#08505c,color:#ffffff; classDef gate fill:#e7f5ff,stroke:#1c7ed6,color:#0b4884; - class A,B,C,E,F,G step; + class A,V,X,B,C,E,F,G step; class D gate; ``` diff --git a/adaption_kit/cli.py b/adaption_kit/cli.py index f6215e7..13fd35e 100644 --- a/adaption_kit/cli.py +++ b/adaption_kit/cli.py @@ -1,6 +1,7 @@ """cli.py - argparse command line for adaption-kit. -Subcommands: doctor, lint, suggest, convert, estimate, run, publish, card, cover. +Subcommands: doctor, lint, suggest, verify, decontaminate, convert, estimate, run, +publish, card, cover. The SDK-backed subcommands (estimate, run) import run.py lazily so that doctor, lint, suggest, convert, card, and cover work even when the optional ``adaption`` @@ -66,6 +67,36 @@ def _cmd_lint(args: argparse.Namespace) -> int: return 1 if report.status == FAIL else 0 +def _cmd_verify(args: argparse.Namespace) -> int: + from .verify import FAIL, verify_dataset + + report = verify_dataset( + args.path, + kind=args.kind, + completion=args.completion, + gold=args.gold, + tests=args.tests, + out=args.out, + ) + print(report.summary()) + return 1 if report.status == FAIL else 0 + + +def _cmd_decontaminate(args: argparse.Namespace) -> int: + from .decontaminate import FAIL, decontaminate + + report = decontaminate( + args.path, + benchmarks=args.against, + column=args.column, + benchmark_column=args.benchmark_column, + n=args.n, + out=args.out, + ) + print(report.summary()) + return 1 if report.status == FAIL else 0 + + def _cmd_convert(args: argparse.Namespace) -> int: from .convert import ( OptionalDependencyMissing, @@ -320,6 +351,39 @@ def build_parser() -> argparse.ArgumentParser: p_lint.add_argument("--context", help="comma-separated context column(s)") p_lint.set_defaults(func=_cmd_lint) + # verify + p_ver = sub.add_parser( + "verify", + help="prove rows are correct (math answers / code tests) before you spend", + ) + p_ver.add_argument("path", help="CSV, JSONL, or JSON file") + p_ver.add_argument( + "--kind", choices=["math", "code"], required=True, help="domain to verify" + ) + p_ver.add_argument("--completion", help="worked-solution / code column") + p_ver.add_argument("--gold", help="(math) gold-answer column") + p_ver.add_argument("--tests", help="(code) unit-tests column") + p_ver.add_argument("--out", help="write only verified rows here (.csv/.jsonl)") + p_ver.set_defaults(func=_cmd_verify) + + # decontaminate + p_dec = sub.add_parser( + "decontaminate", + help="drop training rows that overlap a benchmark test set (n-gram)", + ) + p_dec.add_argument("path", help="training CSV, JSONL, or JSON file") + p_dec.add_argument( + "--against", nargs="+", required=True, help="benchmark file(s) to check against" + ) + p_dec.add_argument("--column", help="anchor column in the training data") + p_dec.add_argument( + "--benchmark-column", dest="benchmark_column", + help="anchor column in the benchmark files", + ) + p_dec.add_argument("--n", type=int, default=13, help="n-gram size (default 13)") + p_dec.add_argument("--out", help="write cleaned rows here (.csv/.jsonl)") + p_dec.set_defaults(func=_cmd_decontaminate) + # convert p_conv = sub.add_parser( "convert", diff --git a/adaption_kit/decontaminate.py b/adaption_kit/decontaminate.py new file mode 100644 index 0000000..5427cdf --- /dev/null +++ b/adaption_kit/decontaminate.py @@ -0,0 +1,220 @@ +"""decontaminate.py - drop training rows that overlap a benchmark test set. + +If a row in your training data also appears (verbatim or near verbatim) in the +held-out test set the platform scores you against, your reported +``improvement_percent`` is inflated and will not survive a second look. This +module flags and removes any training row whose anchor text shares an n-gram with +any benchmark prompt, the standard 8-to-13-gram overlap check used by the data +quality literature. + +You supply the benchmark file(s) yourself (e.g. a public GSM8K / MBPP / HumanEval +split, or your own held-out slice). Pure standard library; reads .csv, .jsonl, and +.json with utf-8-sig like the rest of the kit. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +from .preflight import _cell_text, _load_rows # reuse the shared loader + +PASS = "PASS" +WARN = "WARN" +FAIL = "FAIL" +_RANK = {PASS: 0, WARN: 1, FAIL: 2} + +DEFAULT_N = 13 + +_WS = re.compile(r"\s+") +_PUNCT = re.compile(r"[^a-z0-9 ]+") + + +def _normalize(text: str) -> str: + text = (text or "").lower() + text = _PUNCT.sub(" ", text) + return _WS.sub(" ", text).strip() + + +def ngrams(text: str, n: int = DEFAULT_N) -> set: + toks = _normalize(text).split() + if len(toks) < n: + # short texts: use the whole thing as a single shingle so exact short + # duplicates are still caught. + return {" ".join(toks)} if toks else set() + return {" ".join(toks[i : i + n]) for i in range(0, len(toks) - n + 1)} + + +class Decontaminator: + """Holds the benchmark n-gram set; flags any text that shares one.""" + + def __init__(self, n: int = DEFAULT_N) -> None: + self.n = n + self.bench: set = set() + + def add_text(self, text: str) -> None: + self.bench |= ngrams(text, self.n) + + def is_contaminated(self, text: str) -> bool: + g = ngrams(text, self.n) + if not g: + return False + return not g.isdisjoint(self.bench) + + +@dataclass +class DecontamReport: + path: str + status: str = PASS + row_count: int = 0 + benchmark_rows: int = 0 + column: str = "" + n: int = DEFAULT_N + contaminated: int = 0 + kept: int = 0 + out_path: str = "" + checks: List = field(default_factory=list) + + def add(self, level: str, message: str) -> None: + self.checks.append((level, message)) + if _RANK[level] > _RANK[self.status]: + self.status = level + + def summary(self) -> str: + lines = [ + "adaption-kit decontamination report", + "=" * 60, + "file : " + self.path, + "anchor column : " + (self.column or "(unresolved)"), + "n-gram size : " + str(self.n), + "training rows : " + str(self.row_count), + "benchmark rows : " + str(self.benchmark_rows), + "contaminated : " + str(self.contaminated), + "kept : " + str(self.kept), + ] + if self.out_path: + lines.append("cleaned file : " + self.out_path) + lines.append("") + lines.append("checks:") + for level, msg in self.checks: + lines.append(" [" + level + "] " + msg) + lines.append("") + lines.append("RESULT: " + self.status) + return "\n".join(lines) + + +def _resolve_column(columns: Sequence[str], requested: Optional[str], + fallbacks: Sequence[str]) -> Optional[str]: + if requested: + return requested if requested in columns else None + for f in fallbacks: + if f in columns: + return f + return None + + +def _write_rows(path: Path, rows: List[Dict[str, Any]], fmt: str) -> None: + import csv + import json + if fmt == "csv": + cols: List[str] = [] + for r in rows: + for k in r: + if k not in cols: + cols.append(k) + with path.open("w", encoding="utf-8", newline="") as fh: + w = csv.DictWriter(fh, fieldnames=cols) + w.writeheader() + w.writerows(rows) + else: # jsonl + with path.open("w", encoding="utf-8") as fh: + for r in rows: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + +def decontaminate( + path: "str | Path", + benchmarks: Sequence["str | Path"], + column: Optional[str] = None, + benchmark_column: Optional[str] = None, + n: int = DEFAULT_N, + out: Optional["str | Path"] = None, +) -> DecontamReport: + """Remove training rows overlapping any benchmark prompt. + + Args: + path: the training dataset (.csv/.jsonl/.json). + benchmarks: one or more benchmark files to decontaminate against. + column: anchor column in the training data (default: first of + prompt/problem/question/instruction/text/input present). + benchmark_column: anchor column in the benchmark files (same default). + n: n-gram size (default 13). + out: if given, write the kept rows here (.csv or .jsonl). + """ + p = Path(path) + report = DecontamReport(path=str(p), n=n) + if not p.exists(): + report.add(FAIL, "file does not exist") + return report + + fmt, rows, columns = _load_rows(p) + report.row_count = len(rows) + anchor_candidates = ("prompt", "problem", "question", "instruction", "text", "input") + col = _resolve_column(columns, column, anchor_candidates) + if not col: + report.add(FAIL, "could not resolve an anchor column; pass --column") + return report + report.column = col + + decon = Decontaminator(n=n) + bench_rows = 0 + for b in benchmarks: + bp = Path(b) + if not bp.exists(): + report.add(WARN, "benchmark file not found, skipped: " + str(bp)) + continue + _, brows, bcols = _load_rows(bp) + bcol = _resolve_column(bcols, benchmark_column, anchor_candidates) + if not bcol: + report.add(WARN, "no anchor column in benchmark " + str(bp) + ", skipped") + continue + for r in brows: + decon.add_text(_cell_text(r.get(bcol))) + bench_rows += len(brows) + report.benchmark_rows = bench_rows + + if not decon.bench: + report.add(FAIL, "no benchmark text loaded; nothing to decontaminate against") + return report + + kept_rows: List[Dict[str, Any]] = [] + contaminated = 0 + for r in rows: + if decon.is_contaminated(_cell_text(r.get(col))): + contaminated += 1 + else: + kept_rows.append(r) + report.contaminated = contaminated + report.kept = len(kept_rows) + + if contaminated == 0: + report.add(PASS, "no overlap found; dataset is clean against these benchmarks") + else: + report.add( + WARN, + str(contaminated) + " row(s) overlap the benchmark by a " + + str(n) + "-gram and were removed. Training on these inflates " + "improvement_percent. Re-run after removing them.", + ) + + if out: + outp = Path(out) + out_fmt = "csv" if outp.suffix.lower() == ".csv" else "jsonl" + outp.parent.mkdir(parents=True, exist_ok=True) + _write_rows(outp, kept_rows, out_fmt) + report.out_path = str(outp) + report.add(PASS, "wrote " + str(len(kept_rows)) + " clean row(s) -> " + str(outp)) + + return report diff --git a/adaption_kit/verify.py b/adaption_kit/verify.py new file mode 100644 index 0000000..3cd01d7 --- /dev/null +++ b/adaption_kit/verify.py @@ -0,0 +1,379 @@ +"""verify.py - prove rows are CORRECT before you pay to adapt them. + +For checkable domains, looking right is not good enough. This command keeps a row +only if it actually checks out, locally and for free, before any credits are spent: + + - math: the final answer the worked solution reaches must be equivalent to a gold + answer (normalized string, then numeric, then symbolic via sympy if installed). + - code: the solution must run and pass the unit tests shipped with it. Each + candidate runs in a fresh, short-lived subprocess with a hard timeout, so a bad + row can only ever crash its own child, never your machine or the build. + +Adapting unverified rows is the most common way beginners burn credits on multiple +tries: you pay to polish data that was wrong to begin with. Filter first, then run. + +The symbolic math tier needs sympy (``pip install adaption-devkit[verify]`` or +``pip install sympy``). Without it, math falls back to string + numeric checks and +the report says so. Code verification is pure standard library. +""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys +import tempfile +import textwrap +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FTimeout +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, List, Optional + +from .preflight import _cell_text, _load_rows + +PASS = "PASS" +WARN = "WARN" +FAIL = "FAIL" +_RANK = {PASS: 0, WARN: 1, FAIL: 2} + +# Run child python processes with no console window on Windows, so verifying a +# whole dataset does not flash a terminal window per row. +_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0 +_CODE_TIMEOUT = 8 # seconds per candidate + +try: # optional symbolic tier + from sympy import simplify, sympify # type: ignore + _HAVE_SYMPY = True +except Exception: # pragma: no cover - depends on environment + _HAVE_SYMPY = False + +_EXEC = ThreadPoolExecutor(max_workers=4) + + +# --------------------------------------------------------------------------- math +def extract_boxed(text: str) -> Optional[str]: + """Content of the LAST \\boxed{...}, handling nested braces.""" + idx = text.rfind(r"\boxed") + if idx == -1: + return None + i = text.find("{", idx) + if i == -1: + return None + depth = 0 + for j in range(i, len(text)): + if text[j] == "{": + depth += 1 + elif text[j] == "}": + depth -= 1 + if depth == 0: + return text[i + 1 : j].strip() + return None + + +def extract_final_answer(solution: str) -> Optional[str]: + b = extract_boxed(solution) + if b is not None: + return b + if "####" in solution: + return solution.rsplit("####", 1)[1].strip() + lines = [ln for ln in solution.strip().splitlines() if ln.strip()] + if not lines: + return None + last = lines[-1] + m = re.search(r"(?:answer is|equals|=)\s*\$?([^\$.]+?)\$?\s*\.?$", last, re.I) + if m: + return m.group(1).strip() + nums = re.findall(r"-?\d[\d,]*\.?\d*", last) + return nums[-1] if nums else None + + +_REPL = [ + (r"\left", ""), (r"\right", ""), (r"\,", ""), (r"\!", ""), (r"\;", ""), + (r"\dfrac", r"\frac"), (r"\tfrac", r"\frac"), (r"\cdot", "*"), (r"\times", "*"), + (r"^\circ", ""), (r"\%", ""), (r"\$", ""), ("$", ""), +] + + +def _normalize(s: str) -> str: + if s is None: + return "" + s = s.strip() + for a, b in _REPL: + s = s.replace(a, b) + s = s.strip().rstrip(".") + s = re.sub(r"\s+", "", s) + while len(s) >= 2 and s[0] in "({" and s[-1] in ")}": + s = s[1:-1] + s = re.sub(r"(?<=\d),(?=\d{3}\b)", "", s) + return s + + +def _to_sympy_str(s: str) -> str: + s = s.replace(r"\frac", "frac").strip() + for _ in range(6): + new = re.sub(r"frac\{([^{}]*)\}\{([^{}]*)\}", r"((\1)/(\2))", s) + if new == s: + break + s = new + s = re.sub(r"\\sqrt\{([^{}]*)\}", r"sqrt(\1)", s) + s = re.sub(r"\\sqrt", "sqrt", s) + s = s.replace("{", "(").replace("}", ")") + s = s.replace("^", "**").replace("\\pi", "pi").replace("\\", "") + return s + + +def _try_float(s: str) -> Optional[float]: + s = s.strip() + try: + return float(s) + except Exception: + pass + m = re.fullmatch(r"\(?\s*(-?\d+\.?\d*)\s*/\s*(-?\d+\.?\d*)\s*\)?", s) + if m: + try: + return float(m.group(1)) / float(m.group(2)) + except Exception: + return None + return None + + +def _sympy_equal(a: str, b: str) -> bool: + ea, eb = sympify(_to_sympy_str(a)), sympify(_to_sympy_str(b)) + return ea == eb or simplify(ea - eb) == 0 + + +def answers_equivalent(gold: Optional[str], pred: Optional[str], timeout: float = 3.0) -> bool: + if gold is None or pred is None: + return False + ng, npd = _normalize(gold), _normalize(pred) + if not ng or not npd: + return False + if ng == npd: + return True + fg, fp = _try_float(ng), _try_float(npd) + if fg is not None and fp is not None: + return abs(fg - fp) <= 1e-6 * max(1.0, abs(fg), abs(fp)) + if not _HAVE_SYMPY: + return False + try: + return bool(_EXEC.submit(_sympy_equal, ng, npd).result(timeout=timeout)) + except (FTimeout, Exception): + return False + + +# --------------------------------------------------------------------------- code +def extract_code(output: str) -> str: + m = re.search(r"```(?:python|py)?\s*\n(.*?)```", output, re.S) + return m.group(1).strip() if m else output.strip() + + +def _coerce_tests(tests: Any) -> List[str]: + import json + if isinstance(tests, list): + return [str(t) for t in tests] + if isinstance(tests, str): + s = tests.strip() + try: + v = json.loads(s) + if isinstance(v, list): + return [str(t) for t in v] + except Exception: + pass + return [s] if s else [] + return [] + + +def code_passes(output: str, tests: Any, setup: str = "") -> bool: + """True only if the solution runs and passes EVERY assert-style test.""" + code = extract_code(output) + tests = _coerce_tests(tests) + if len(code) < 5 or not tests: + return False + harness = setup + "\n" + code + "\n\n_p = 0\n" + for t in tests: + harness += ( + "try:\n" + textwrap.indent(t.strip() or "pass", " ") + + "\n _p += 1\nexcept Exception:\n pass\n" + ) + harness += "print('PASSED', _p)\n" + with tempfile.TemporaryDirectory() as d: + fp = os.path.join(d, "cand.py") + with open(fp, "w", encoding="utf-8") as f: + f.write(harness) + try: + r = subprocess.run( + [sys.executable, fp], capture_output=True, text=True, + timeout=_CODE_TIMEOUT, cwd=d, creationflags=_NO_WINDOW, + ) + except Exception: + return False + m = re.search(r"PASSED (\d+)", r.stdout or "") + return bool(m) and int(m.group(1)) == len(tests) + + +# --------------------------------------------------------------------------- report +@dataclass +class VerifyReport: + path: str + kind: str + status: str = PASS + row_count: int = 0 + verified: int = 0 + failed: int = 0 + unverifiable: int = 0 # missing gold/tests + out_path: str = "" + sympy_available: bool = _HAVE_SYMPY + checks: List = field(default_factory=list) + + def add(self, level: str, message: str) -> None: + self.checks.append((level, message)) + if _RANK[level] > _RANK[self.status]: + self.status = level + + @property + def verify_rate(self) -> float: + base = self.verified + self.failed + return self.verified / base if base else 0.0 + + def summary(self) -> str: + lines = [ + "adaption-kit verification report", + "=" * 60, + "file : " + self.path, + "domain : " + self.kind, + "rows : " + str(self.row_count), + "verified : " + str(self.verified), + "failed check : " + str(self.failed), + "unverifiable : " + str(self.unverifiable) + " (no gold/tests to check)", + "verify rate : " + str(round(self.verify_rate * 100, 1)) + "%", + ] + if self.kind == "math" and not self.sympy_available: + lines.append("note : sympy not installed; symbolic check skipped " + "(pip install sympy). Some correct rows may read as failed.") + if self.out_path: + lines.append("verified file : " + self.out_path) + lines.append("") + lines.append("checks:") + for level, msg in self.checks: + lines.append(" [" + level + "] " + msg) + lines.append("") + lines.append("RESULT: " + self.status) + return "\n".join(lines) + + +def _pick(columns, requested, fallbacks): + if requested: + return requested if requested in columns else None + for f in fallbacks: + if f in columns: + return f + return None + + +def verify_dataset( + path: "str | Path", + kind: str, + completion: Optional[str] = None, + gold: Optional[str] = None, + tests: Optional[str] = None, + out: Optional["str | Path"] = None, +) -> VerifyReport: + """Verify each row and (optionally) write only the rows that pass. + + Args: + path: dataset (.csv/.jsonl/.json). + kind: "math" or "code". + completion: the worked-solution / code column. + gold: (math) the gold-answer column. If absent, the answer is extracted + from the completion and only checked for parseability. + tests: (code) the column holding the unit tests (list or JSON string). + out: if given, write only verified rows here. + """ + p = Path(path) + report = VerifyReport(path=str(p), kind=kind) + if not p.exists(): + report.add(FAIL, "file does not exist") + return report + if kind not in ("math", "code"): + report.add(FAIL, "kind must be 'math' or 'code'") + return report + + fmt, rows, columns = _load_rows(p) + report.row_count = len(rows) + + comp = _pick(columns, completion, ("completion", "worked_solution", "solution", "output", "answer")) + if not comp: + report.add(FAIL, "could not resolve a completion column; pass --completion") + return report + + kept: List[dict] = [] + if kind == "math": + gcol = _pick(columns, gold, ("gold", "expected_answer", "answer", "final_answer")) + for r in rows: + sol = _cell_text(r.get(comp)) + gold_val = _cell_text(r.get(gcol)) if gcol else extract_final_answer(sol) + pred = extract_final_answer(sol) + if not gold_val: + report.unverifiable += 1 + continue + if answers_equivalent(gold_val, pred): + report.verified += 1 + kept.append(r) + else: + report.failed += 1 + else: # code + tcol = _pick(columns, tests, ("tests", "unit_tests", "test_list", "test")) + if not tcol: + report.add(FAIL, "could not resolve a tests column; pass --tests") + return report + for r in rows: + sol = _cell_text(r.get(comp)) + t = r.get(tcol) + if not t: + report.unverifiable += 1 + continue + if code_passes(sol, t): + report.verified += 1 + kept.append(r) + else: + report.failed += 1 + + base = report.verified + report.failed + if base == 0: + report.add(FAIL, "no rows could be checked (no gold/tests found)") + elif report.verify_rate >= 0.95: + report.add(PASS, str(round(report.verify_rate * 100, 1)) + "% of checkable rows verified") + else: + report.add( + WARN, + str(report.failed) + " row(s) did NOT verify and should be dropped before " + "you spend credits. Keep only the " + str(report.verified) + " that passed.", + ) + if report.unverifiable: + report.add(WARN, str(report.unverifiable) + " row(s) had no gold answer / tests " + "to check against; they were not counted as verified.") + + if out: + import json + import csv + outp = Path(out) + outp.parent.mkdir(parents=True, exist_ok=True) + if outp.suffix.lower() == ".csv": + cols: List[str] = [] + for r in kept: + for k in r: + if k not in cols: + cols.append(k) + with outp.open("w", encoding="utf-8", newline="") as fh: + w = csv.DictWriter(fh, fieldnames=cols) + w.writeheader() + w.writerows(kept) + else: + with outp.open("w", encoding="utf-8") as fh: + for r in kept: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + report.out_path = str(outp) + report.add(PASS, "wrote " + str(len(kept)) + " verified row(s) -> " + str(outp)) + + return report diff --git a/examples/math_code_walkthrough.md b/examples/math_code_walkthrough.md new file mode 100644 index 0000000..e3f39c5 --- /dev/null +++ b/examples/math_code_walkthrough.md @@ -0,0 +1,586 @@ +# Math and code walkthrough: verified reasoning from raw rows to a published release + +This is a full, copy and paste path for a checkable domain. You start from a raw +file of math and code problems with their solutions, check your setup, get a +column mapping, lint it, then do the thing that matters most for math and code: +**verify** that each row is actually correct before you spend a credit adapting +it. After that you decontaminate against any public benchmark, quote the cost, +run a small pilot, read the improvement number, and release to Hugging Face and +Kaggle with a card and a cover. + +Every block is a real command. Every output block is marked **illustrative**: it +shows the shape of what prints, not numbers from your account. Real credit costs +and the real `improvement_percent` depend on your data and your run. + +> **adaption-devkit** is a community, unofficial, open source toolkit +> (Apache-2.0) by Aivaras Navardauskas (MANIFESTA), GitHub `A1VARA5`. It is +> **not affiliated with or endorsed by Adaption Labs**. The official SDK is the +> `adaption` package; this devkit only wraps it. Always treat the official docs +> and API as the source of truth. + +## Why math and code are different + +Marketing data is judged on voice and variety. Math and code are judged on +**correctness**, and correctness is checkable. A math answer either equals the +gold value or it does not. A code solution either passes its unit tests or it +does not. That means two things you do not get in softer domains: + +- You can prove a row is right before you pay to adapt it. Adapting a row that + was wrong to begin with teaches the model the wrong thing, and you paid credits + for the privilege. `adaption-kit verify` keeps only the rows that pass. +- You can prove the dataset does not overlap a public benchmark. Training on rows + that also live in a benchmark test set inflates `improvement_percent` and does + not survive scrutiny. `adaption-kit decontaminate` removes them. + +Describe the result honestly. A dataset like this is **hybrid**: real problems +paired with **verified** solutions. It is not a pile of model output you hope is +right; it is rows you checked. And the number that counts is +`improvement_percent`, the adapted model measured against the baseline, not a +quality grade you assign to the dataset yourself. + +## What you need + +- Python 3.10 or newer. +- An Adaption API key. +- A Hugging Face write token and Kaggle credentials for the release step. +- A small file of problems with solutions to start with. We use a tiny mixed + math and code set below. +- For the symbolic math check, the optional `verify` extra (sympy). Without it, + math verification still runs on string and numeric checks and tells you so. + +## 0. Install + +```bash +pip install adaption-kit[all] # the CLI plus SDK, Hugging Face, Kaggle, cover, sympy +``` + +If you only want the offline parts first, `pip install adaption-kit` gives you +`doctor`, `lint`, `verify`, `decontaminate`, `suggest`, `card`, and `cover`. The +SDK backed commands (`estimate`, `run`) need the `[sdk]` extra, and the symbolic +math check inside `verify` needs the `[verify]` extra (sympy). Each command tells +you what to add if an extra is missing. + +```bash +# just the symbolic math check, if you do not want everything +pip install adaption-kit[verify] +``` + +## 1. Set your environment + +Configuration is environment only. Never hardcode a key or a host in code you +plan to share. Set `ADAPTION_BASE_URL` from the environment; the host that has +been answering for participants is `https://api.prod.adaptionlabs.ai`. + +macOS or Linux: + +```bash +export ADAPTION_BASE_URL="https://api.prod.adaptionlabs.ai" +export ADAPTION_API_KEY="pt_live_your_key_here" +export HF_TOKEN="hf_your_write_token" +export KAGGLE_USERNAME="your_kaggle_username" +export KAGGLE_KEY="your_kaggle_key" +``` + +Windows PowerShell: + +```powershell +$env:ADAPTION_BASE_URL = "https://api.prod.adaptionlabs.ai" +$env:ADAPTION_API_KEY = "pt_live_your_key_here" +$env:HF_TOKEN = "hf_your_write_token" +$env:KAGGLE_USERNAME = "your_kaggle_username" +$env:KAGGLE_KEY = "your_kaggle_key" +``` + +## 2. The raw data + +Save this as `math_rows.jsonl`. Each row is a problem in `prompt`, a proposed +answer in `answer`, and the known correct value in `gold`. One row is wrong on +purpose, so you can watch verification catch it. + +```jsonl +{"prompt": "What is 12 * 12?", "answer": "144", "gold": "144"} +{"prompt": "Solve for x: 2x + 6 = 10", "answer": "x = 2", "gold": "2"} +{"prompt": "Simplify (x^2 - 1)/(x - 1)", "answer": "x + 1", "gold": "x+1"} +{"prompt": "What is 1/2 + 1/4?", "answer": "0.75", "gold": "3/4"} +{"prompt": "What is the derivative of x^2?", "answer": "2", "gold": "2*x"} +``` + +The last row is wrong: the derivative of `x^2` is `2*x`, not `2`. Keep it. The +verifier should drop exactly that row. + +Now save this as `code_rows.jsonl`. Each row is a problem in `prompt`, a Python +solution in `solution`, and a `tests` string that exercises it. One solution is +wrong on purpose. + +```jsonl +{"prompt": "Write add(a, b).", "solution": "def add(a, b):\n return a + b", "tests": "assert add(2, 3) == 5\nassert add(-1, 1) == 0"} +{"prompt": "Write is_even(n).", "solution": "def is_even(n):\n return n % 2 == 0", "tests": "assert is_even(4)\nassert not is_even(3)"} +{"prompt": "Write reverse(s).", "solution": "def reverse(s):\n return s", "tests": "assert reverse('ab') == 'ba'"} +``` + +The `reverse` solution returns the string unchanged, so its test fails. The +verifier should drop that row. + +## 3. doctor: is my setup ready + +```bash +adaption-kit doctor +``` + +Illustrative output: + +``` + _ _ _ _ _ _ _ + /_\ __| |__ _ _ __| |_(_)___ _ _ | |__(_) |_ + / _ \/ _` / _` | '_ \ _| / _ \ ' \ _ | / / | _| +/_/ \_\__,_\__,_| .__/\__|_\___/_||_| (_)|_\_\_|\__| +------------------------------------------------------------ +adaption-kit doctor report +============================================================ + [PASS] Python 3.11.5 (3.10 or newer) + [PASS] adaption SDK is importable + [PASS] ADAPTION_API_KEY is set + [PASS] ADAPTION_BASE_URL is set + [PASS] huggingface_hub is installed (Hugging Face publishing) + [PASS] kaggle is installed (Kaggle publishing) + [PASS] playwright is installed (cover image rendering) + +RESULT: PASS - your environment looks ready. +``` + +`doctor` never makes a network call and never prints your key value. If sympy is +not installed, the symbolic math check inside `verify` is skipped and the +command says so when you run it; the string and numeric checks still run. + +## 4. suggest: what is my column mapping + +If you are not sure which columns are the anchor, ask the kit. + +```bash +adaption-kit suggest math_rows.jsonl +``` + +Illustrative output: + +``` +adaption-kit mapping suggestion +============================================================ +file : math_rows.jsonl +format : jsonl +rows : 5 +columns : prompt, answer, gold + +recommended anchor: prompt + completion (instruction plus answer pairs) + +ready to paste column_mapping: + +{ + "prompt": "prompt", + "completion": "answer" +} + +notes: + - Recipes to consider: deduplication on almost always; reasoning_traces for + math, code, science, legal, or finance. + - Brand controls to consider: length to match the eval's expected answer + depth. + +Next: run 'adaption-kit lint math_rows.jsonl' to confirm the anchor is unique +before you spend credits. +``` + +The anchor is `prompt` plus `completion`, mapping `answer` as the completion. +The `gold` column is your verification reference, not part of the mapping. For +the code set, `solution` is the completion and `tests` is the verification +reference. + +## 5. lint: catch the obvious problems before you pay + +```bash +adaption-kit lint math_rows.jsonl --prompt prompt --completion answer +``` + +Illustrative output: + +``` +adaption-kit preflight report +============================================================ +file : math_rows.jsonl +format : jsonl +encoding : utf-8 +rows : 5 +columns : prompt, answer, gold +anchor : prompt -> column 'prompt' +unique anchor values: 5 / 5 (100.0%) +dedup would collapse: 0 row(s) + +checks: + [PASS] loaded 5 row(s) + [PASS] 100.0% of anchors are unique; dedup impact is minimal + +RESULT: PASS +``` + +Lint confirms the rows load, the anchors are unique, and the dedup pass will not +quietly collapse the set. It does **not** check whether the answers are correct. +That is the next step, and for math and code it is the one that matters most. + +## 6. verify: prove the rows are correct before you adapt them + +This is the single biggest defense against burning credits on rows that were +wrong to begin with. Verification checks each row and, with `--out`, writes only +the rows that pass. + +### Math + +Math answers are checked for equivalence against the `gold` column: first a +normalized string match, then a numeric match, then a symbolic match via sympy +if the `verify` extra is installed. `0.75` and `3/4` are numerically equal; +`x + 1` and `x+1` are symbolically equal. The wrong derivative row fails all +three. + +```bash +adaption-kit verify math_rows.jsonl \ + --kind math \ + --completion answer --gold gold \ + --out math_verified.jsonl +``` + +Illustrative output: + +``` +adaption-kit verify (math) +------------------------------------------------------------ +checked : 5 row(s) +passed : 4 +failed : 1 + - row 5: 'What is the derivative of x^2?' answer '2' != gold '2*x' +symbolic check: sympy available, used for equivalence +wrote 4 verified row(s) to math_verified.jsonl + +RESULT: 4 / 5 rows verified correct +``` + +If sympy is not installed you see `symbolic check: sympy not installed, using +string and numeric checks only`. The numeric row (`0.75` vs `3/4`) still passes; +a row that needs symbolic algebra to prove equal would be reported as unverified +so you do not silently keep something unchecked. + +### Code + +Code solutions are executed against their unit tests in a sandboxed subprocess +and kept only if every test passes. This is pure standard library, no extra +needed. + +```bash +adaption-kit verify code_rows.jsonl \ + --kind code \ + --completion solution --tests tests \ + --out code_verified.jsonl +``` + +Illustrative output: + +``` +adaption-kit verify (code) +------------------------------------------------------------ +checked : 3 row(s) +passed : 2 +failed : 1 + - row 3: 'Write reverse(s).' tests failed (AssertionError) +wrote 2 verified row(s) to code_verified.jsonl + +RESULT: 2 / 3 rows verified correct +``` + +You now have `math_verified.jsonl` and `code_verified.jsonl`, holding only rows +whose solutions you proved correct. Adapt these, not the raw files. The wrong +derivative and the broken `reverse` never cost you a credit. + +## 7. decontaminate: remove benchmark overlap so the number is defensible + +If any of your problems also appear in a public benchmark test set, training on +them inflates `improvement_percent` and the result does not hold up. Decontaminate +removes any training row that overlaps a benchmark by an n-gram (default 13). + +```bash +adaption-kit decontaminate math_verified.jsonl \ + --against gsm8k_test.jsonl math_bench_test.jsonl \ + --column answer \ + --benchmark-column answer \ + --n 13 \ + --out math_clean.jsonl +``` + +Illustrative output: + +``` +adaption-kit decontaminate +------------------------------------------------------------ +training rows : 4 +benchmarks : gsm8k_test.jsonl, math_bench_test.jsonl +n-gram size : 13 +overlapping : 1 row(s) removed +wrote 3 clean row(s) to math_clean.jsonl + +RESULT: 3 / 4 rows kept after decontamination +``` + +Do the same for the code set against any code benchmark you might overlap. Keep +the cleaned files. Now your dataset is verified correct **and** free of benchmark +overlap, which is exactly what makes a reported improvement defensible. + +## 8. Upload the cleaned file and get a dataset id + +`estimate` and `run` take a `DATASET_ID`, so you upload the cleaned file once +with the SDK and keep the id. + +```python +import os +from adaption import Adaption + +client = Adaption( + base_url=os.environ["ADAPTION_BASE_URL"], + api_key=os.environ["ADAPTION_API_KEY"], +) +result = client.datasets.upload_file("math_clean.jsonl", name="verified-math") +dataset_id = result.dataset_id +print("dataset_id:", dataset_id) +``` + +Illustrative output: + +``` +dataset_id: ds_3b91ee07ac +``` + +Use that id, for example `ds_3b91ee07ac`, in the commands below. + +## 9. estimate: quote the cost, start nothing + +Always estimate before a run. For math and code the lever is `reasoning_traces`, +which adds auditable stepwise reasoning to each completion, plus `deduplication`. + +```bash +adaption-kit estimate ds_3b91ee07ac \ + --prompt prompt --completion answer \ + --deduplication --reasoning-traces +``` + +Illustrative output: + +``` +adaption-kit estimate (no run started) +------------------------------------------------------------ +estimate (no run started): + estimated_credits_consumed: 58 + estimated_minutes : 8 +``` + +The credit number above is illustrative. Your real quote depends on row count, +recipes, and controls. If the mapping is wrong, this call tells you now, for +free, and you fix it before paying. + +## 10. Pilot run: small max_rows first + +Never run the full corpus first. Pilot with a small `--max-rows`, read the +number, and only then scale. `--wait` polls both the run and the evaluation so +you get `improvement_percent` in one shot. For math and code, `length: detailed` +is a sensible starting control to match the expected stepwise answer depth. + +```bash +adaption-kit run ds_3b91ee07ac \ + --prompt prompt --completion answer \ + --pilot --max-rows 3 \ + --deduplication --reasoning-traces \ + --wait +``` + +Illustrative output: + +``` +adaption-kit run +------------------------------------------------------------ +run started. run_id: run_5c2d11 +waiting for run and evaluation ... +run_status : succeeded +evaluation_status : succeeded +improvement_percent: 21.4 +``` + +The `improvement_percent` is the headline number, and it is the adapted model +measured against the baseline, not a grade you give the dataset. It is +illustrative here; the real value depends entirely on your run. The run can +report `succeeded` before evaluation finishes, which is why the kit polls the +evaluation separately. If `improvement_percent` is not printed, evaluation was +not terminal yet; poll again. + +To add a brand control such as `length`, the CLI run flags do not include brand +controls, so use the Python helper: + +```python +from adaption_kit.run import estimate, pilot, wait_for_result + +est = estimate( + "ds_3b91ee07ac", + prompt="prompt", completion="answer", + deduplication=True, reasoning_traces=True, + brand_controls={"length": "detailed"}, +) +print(est.estimated_credits_consumed, est.estimated_minutes) + +pilot( + "ds_3b91ee07ac", + prompt="prompt", completion="answer", + deduplication=True, reasoning_traces=True, + brand_controls={"length": "detailed"}, + max_rows=3, +) +result = wait_for_result("ds_3b91ee07ac") +print("improvement_percent:", result.improvement_percent) +``` + +## 11. Iterate, then scale + +If the pilot number is low, change exactly one knob, estimate again, and re-pilot. +Keep only what raises the number. When a config wins, drop `--max-rows` (or raise +it), estimate the full corpus, and run it. Changing one thing at a time is the +only way to know what moved the score. + +## 12. Read the full number, then run the full corpus + +Once a pilot config wins, run the verified and decontaminated corpus in full and +read the final `improvement_percent`. That number, model versus baseline, is what +you report. It is honest precisely because you verified the rows and removed +benchmark overlap before adapting them. + +## 13. Cards and a cover for the release + +Generate a Hugging Face dataset card. Record the `improvement_percent` you read +above, and describe the data honestly as hybrid: real problems paired with +verified solutions, decontaminated against the benchmarks you checked. + +```bash +adaption-kit card dataset \ + --title "VerifiedMath" \ + --summary "Hybrid math and code corpus: real problems with verified solutions, decontaminated against public benchmarks." \ + --tags nlp,text-generation \ + --improvement-percent 21.4 \ + --row-count 3 \ + --out ./release +``` + +Illustrative output: + +``` +adaption-kit card +------------------------------------------------------------ +wrote release/README.md +``` + +Generate the Kaggle metadata with taxonomy tags only (`nlp`, `text generation`, +`internet`, and similar). The kit validates them and rejects anything else. + +```bash +adaption-kit card kaggle \ + --title "VerifiedMath" \ + --kaggle-slug a1vara5/verified-math \ + --tags nlp,internet \ + --out ./release +``` + +Illustrative output: + +``` +adaption-kit card +------------------------------------------------------------ +wrote release/dataset-metadata.json +``` + +Render a cover image. + +```bash +adaption-kit cover ./release/cover.png \ + --title "VerifiedMath" \ + --subtitle "Math and code, verified" +``` + +Illustrative output: + +``` +adaption-kit cover +------------------------------------------------------------ +cover PNG written to release/cover.png +``` + +Put your cleaned files (or the downloaded adapted dataset) into `./release` too, +so the folder holds the data, the card, the Kaggle metadata, and the cover. + +## 14. Download the adapted dataset + +Export the processed rows and add them to the release folder. + +```python +import os +from adaption import Adaption + +client = Adaption( + base_url=os.environ["ADAPTION_BASE_URL"], + api_key=os.environ["ADAPTION_API_KEY"], +) +url = client.datasets.download("ds_3b91ee07ac") # presigned download URL +print(url) +``` + +## 15. publish: release by hand to HF and Kaggle + +The platform publish endpoint returns `501 Not Implemented`, so the kit does not +rely on it. `adaption-kit publish` pushes your release folder to Hugging Face and +Kaggle directly, using the tokens from your environment. + +```bash +adaption-kit publish ./release \ + --hf-repo a1vara5/verified-math \ + --kaggle-slug a1vara5/verified-math +``` + +Illustrative output: + +``` +adaption-kit publish +------------------------------------------------------------ +adaption-kit publish report +============================================================ +Hugging Face : https://huggingface.co/datasets/a1vara5/verified-math +Kaggle : a1vara5/verified-math +note: Adaption publish endpoint returns 501; releasing manually. +note: Kaggle datasets stay private until toggled public in the UI. +``` + +Two honest follow ups: + +- Kaggle datasets are created **private**. Open the dataset settings on Kaggle + and toggle it public. A private dataset does not count as released. +- Open both public URLs in a logged out browser to confirm they render. + +## The whole loop in one place + +1. `adaption-kit doctor` to confirm the setup. +2. `adaption-kit suggest math_rows.jsonl` to get the mapping. +3. `adaption-kit lint ... --prompt prompt --completion answer` for the obvious checks. +4. `adaption-kit verify ... --kind math --completion answer --gold gold --out ...` + and `--kind code --completion solution --tests tests --out ...`, keeping only + the rows that pass. +5. `adaption-kit decontaminate ... --against BENCH --out ...` to remove benchmark overlap. +6. Upload the cleaned file to get a `DATASET_ID`. +7. `adaption-kit estimate DATASET_ID ...` to quote the cost. +8. `adaption-kit run DATASET_ID ... --pilot --max-rows 3 --wait` to pilot and read `improvement_percent`. +9. Change one knob, re-estimate, re-pilot, keep what helps, then run the full corpus. +10. `adaption-kit card` and `adaption-kit cover` for the release assets. +11. `adaption-kit publish ./release --hf-repo ... --kaggle-slug ...` and toggle Kaggle public. + +Describe the data honestly as hybrid: real problems with verified solutions. +The number that counts is `improvement_percent`, the adapted model against the +baseline, not a quality grade you assign yourself. Credits are real and limited. +Verify and decontaminate first, estimate before every run, pilot small, and only +scale the config that actually moved the number. diff --git a/graphics/command-router.md b/graphics/command-router.md index e609328..6c33239 100644 --- a/graphics/command-router.md +++ b/graphics/command-router.md @@ -10,7 +10,9 @@ flowchart TD Q1 -- no --> Sug[adaption-kit suggest] Q1 -- yes --> Lint[adaption-kit lint] Sug --> Lint - Lint --> Est[adaption-kit estimate] + Lint --> Ver[adaption-kit verify
math or code] + Ver --> Dec[adaption-kit decontaminate
against benchmarks] + Dec --> Est[adaption-kit estimate] Est --> Run[adaption-kit run
pilot first] Run --> Q2{number look good?} Q2 -- no --> Tune[change one lever] @@ -19,7 +21,7 @@ flowchart TD Full --> Pub[adaption-kit publish] classDef cmd fill:#0b7285,stroke:#08505c,color:#ffffff; classDef gate fill:#e7f5ff,stroke:#1c7ed6,color:#0b4884; - class Doc,Sug,Lint,Est,Run,Tune,Full,Pub cmd; + class Doc,Sug,Lint,Ver,Dec,Est,Run,Tune,Full,Pub cmd; class Q1,Q2 gate; ``` diff --git a/graphics/credit-safe-run.md b/graphics/credit-safe-run.md index 7896096..15bded3 100644 --- a/graphics/credit-safe-run.md +++ b/graphics/credit-safe-run.md @@ -6,7 +6,9 @@ a small run looks good. This is the habit the toolkit is built to encourage. ```mermaid flowchart TD - A([lint your dataset]) --> B[estimate the run] + A([lint your dataset]) --> V[verify math and code rows
keep only the ones that pass] + V --> X[decontaminate against benchmarks] + X --> B[estimate the run] B --> C[pilot on a small max_rows slice] C --> D{improvement_percent} D -- low --> E[change one lever
a recipe or a brand control] @@ -15,7 +17,7 @@ flowchart TD F --> G([publish to Hugging Face and Kaggle]) classDef step fill:#0b7285,stroke:#08505c,color:#ffffff; classDef gate fill:#e7f5ff,stroke:#1c7ed6,color:#0b4884; - class A,B,C,E,F,G step; + class A,V,X,B,C,E,F,G step; class D gate; ``` diff --git a/guides/gotchas.md b/guides/gotchas.md index 695592e..eb02435 100644 --- a/guides/gotchas.md +++ b/guides/gotchas.md @@ -258,3 +258,26 @@ learns from. whitespace only completions so you can drop or fix them first. Completion only data lives and dies on the quality of each answer, so a few blank ones cost more than their share. + +## 15. Adapting unverified rows wastes credits + +**Symptom.** You adapt a math or code dataset, the run succeeds, and +`improvement_percent` is flat or worse than a cleaner set earned, even though the +recipes looked right. + +**Cause.** Some of the rows were wrong to begin with. A math answer that does not +match the gold value, or a code solution that fails its own tests, teaches the model +the wrong thing, and you paid credits to do it. A second cause is benchmark overlap: +rows that also appear in a public benchmark test set inflate the number and do not +survive scrutiny. + +**Fix.** Adapting unverified rows wastes credits. For checkable domains run +`adaption-kit verify` first and adapt only the rows that pass; run +`adaption-kit decontaminate` against any public benchmark so the number is +defensible. + +```bash +adaption-kit verify rows.jsonl --kind math --completion answer --gold gold --out verified.jsonl +adaption-kit verify rows.jsonl --kind code --completion solution --tests tests --out verified.jsonl +adaption-kit decontaminate verified.jsonl --against bench.jsonl --out clean.jsonl +``` diff --git a/pyproject.toml b/pyproject.toml index 6580646..d4c03a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,7 @@ hf = ["huggingface_hub>=0.20"] kaggle = ["kaggle>=1.6"] cover = ["playwright>=1.40"] parquet = ["pyarrow>=14.0"] +verify = ["sympy>=1.12"] dev = ["pytest>=7.0", "ruff>=0.4"] all = [ "adaption>=0.3.1", @@ -43,6 +44,7 @@ all = [ "kaggle>=1.6", "playwright>=1.40", "pyarrow>=14.0", + "sympy>=1.12", ] [project.scripts] diff --git a/tests/test_decontaminate.py b/tests/test_decontaminate.py new file mode 100644 index 0000000..09e58f0 --- /dev/null +++ b/tests/test_decontaminate.py @@ -0,0 +1,142 @@ +"""Tests for adaption_kit.decontaminate.decontaminate and its helpers. + +These build tiny training/benchmark files under tmp_path. Contamination is +triggered by sharing a phrase that is clearly longer than the 13-token n-gram +window, so the default 13-gram overlap check fires; unrelated rows are kept. +""" + +from __future__ import annotations + +import json + +from conftest import write_jsonl + +from adaption_kit.decontaminate import ( + DecontamReport, + Decontaminator, + decontaminate, + ngrams, +) + +# A phrase well over 13 tokens so a 13-gram window is shared verbatim. +SHARED = ( + "a train leaves the station traveling north at forty miles per hour " + "for three hours then stops" +) + + +# --------------------------------------------------------------------- helpers +def test_ngrams_basic_behavior(): + # Punctuation stripped, lowercased; a 3-gram over 5 tokens -> 3 shingles. + grams = ngrams("The Quick Brown Fox Jumps!", n=3) + assert grams == {"the quick brown", "quick brown fox", "brown fox jumps"} + # Text shorter than n collapses to a single whole-text shingle. + assert ngrams("two words", n=13) == {"two words"} + # Empty text -> empty set. + assert ngrams("", n=13) == set() + + +def test_decontaminator_is_contaminated_true_and_false(): + decon = Decontaminator(n=13) + decon.add_text(SHARED + " somewhere far away beyond the river and the hills") + assert decon.is_contaminated("Question: " + SHARED + " how far did it travel?") + assert not decon.is_contaminated( + "an entirely different sentence about baking sourdough bread at home" + ) + + +# ----------------------------------------------------------------- end to end +def test_contaminated_removed_unrelated_kept(tmp_path): + train = write_jsonl( + tmp_path / "train.jsonl", + [ + {"prompt": "Word problem: " + SHARED + " what is its average speed?"}, + {"prompt": "Describe a lightweight moisturizer for oily combination skin."}, + ], + ) + bench = write_jsonl( + tmp_path / "bench.jsonl", + [ + {"prompt": SHARED + " calculate the total distance covered overall."}, + ], + ) + + report = decontaminate(train, [bench]) + + assert isinstance(report, DecontamReport) + assert report.status == "WARN" # contamination present -> WARN + assert report.row_count == 2 + assert report.benchmark_rows == 1 + assert report.contaminated == 1 + assert report.kept == 1 + assert report.column == "prompt" + + +def test_out_writes_kept_rows(tmp_path): + train = write_jsonl( + tmp_path / "train.jsonl", + [ + {"prompt": "Q: " + SHARED + " find the speed.", "id": "dirty"}, + {"prompt": "How do I store fresh basil so it lasts longer?", "id": "clean"}, + ], + ) + bench = write_jsonl( + tmp_path / "bench.jsonl", + [{"prompt": SHARED + " and then it returns home."}], + ) + out = tmp_path / "clean.jsonl" + + report = decontaminate(train, [bench], out=out) + + assert report.kept == 1 + assert out.exists() + written = [ + json.loads(line) + for line in out.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assert len(written) == report.kept + assert written[0]["id"] == "clean" + + +def test_explicit_column_resolution_across_differing_names(tmp_path): + """Training uses 'problem', benchmark uses 'question'; pass both explicitly.""" + train = write_jsonl( + tmp_path / "train.jsonl", + [ + {"problem": "Setup: " + SHARED + " determine the elapsed time."}, + {"problem": "An unrelated note about choosing a good running shoe size."}, + ], + ) + bench = write_jsonl( + tmp_path / "bench.jsonl", + [{"question": SHARED + " then it parks for the night."}], + ) + + report = decontaminate( + train, [bench], column="problem", benchmark_column="question" + ) + + assert report.column == "problem" + assert report.contaminated == 1 + assert report.kept == 1 + + +def test_no_anchor_column_fails(tmp_path): + train = write_jsonl( + tmp_path / "train.jsonl", + [{"foo": "bar", "baz": "qux"}], + ) + bench = write_jsonl( + tmp_path / "bench.jsonl", + [{"prompt": SHARED}], + ) + + report = decontaminate(train, [bench]) + + assert report.status == "FAIL" + + +def test_nonexistent_file_fails(tmp_path): + report = decontaminate(tmp_path / "nope.jsonl", [tmp_path / "bench.jsonl"]) + assert report.status == "FAIL" diff --git a/tests/test_verify.py b/tests/test_verify.py new file mode 100644 index 0000000..effaa05 --- /dev/null +++ b/tests/test_verify.py @@ -0,0 +1,202 @@ +"""Tests for adaption_kit.verify.verify_dataset and its helpers. + +These build tiny .jsonl / .csv files under tmp_path and assert the real status +and counts. The math tests are deliberately restricted to answer pairs that are +decidable by the string and numeric tiers so they pass whether or not sympy is +installed (CI core has no sympy). One symbolic case is guarded on +``verify._HAVE_SYMPY``. + +Code verification runs real, short-lived subprocesses, so the candidate +functions are kept tiny. +""" + +from __future__ import annotations + +import json + +from conftest import write_csv, write_jsonl + +from adaption_kit import verify +from adaption_kit.verify import ( + VerifyReport, + answers_equivalent, + code_passes, + extract_boxed, + extract_final_answer, + verify_dataset, +) + + +# --------------------------------------------------------------------- helpers +def test_extract_boxed_returns_last_and_handles_nested_braces(): + assert extract_boxed(r"the answer is \boxed{42}.") == "42" + # Last boxed wins. + assert extract_boxed(r"\boxed{1} then \boxed{2}") == "2" + # Nested braces are balanced, not truncated at the first close. + assert extract_boxed(r"\boxed{\frac{1}{2}}") == r"\frac{1}{2}" + assert extract_boxed("no box here") is None + + +def test_extract_final_answer_prefers_boxed_then_hash(): + assert extract_final_answer(r"work \boxed{7}") == "7" + assert extract_final_answer("a\nb\n#### 13") == "13" + + +def test_answers_equivalent_numeric_and_string_tiers(): + # Exact string match. + assert answers_equivalent("42", "42") + # Numeric / fraction equality via the numeric tier (no sympy needed). + assert answers_equivalent("0.5", "1/2") + # Clear mismatch. + assert not answers_equivalent("42", "43") + # Missing values never equate. + assert not answers_equivalent(None, "1") + assert not answers_equivalent("1", None) + + +# ------------------------------------------------------------------------ math +def test_math_happy_path_counts_verified_and_failed(tmp_path): + """Boxed answers that match gold verify; one that disagrees fails.""" + src = write_jsonl( + tmp_path / "math.jsonl", + [ + # boxed 42 == gold 42 -> verified + {"worked_solution": r"so the total is \boxed{42}.", "gold": "42"}, + # boxed 1/2 == gold 0.5 via numeric tier -> verified + {"worked_solution": r"therefore \boxed{1/2}.", "gold": "0.5"}, + # boxed 43 != gold 42 -> failed + {"worked_solution": r"hence \boxed{43}.", "gold": "42"}, + ], + ) + + report = verify_dataset(src, kind="math", completion="worked_solution", gold="gold") + + assert isinstance(report, VerifyReport) + assert report.row_count == 3 + assert report.verified == 2 + assert report.failed == 1 + assert report.unverifiable == 0 + assert report.verify_rate == 2 / 3 + + +def test_math_symbolic_case_only_when_sympy_available(tmp_path): + """A symbolic-only pair (sqrt forms) verifies only when sympy is present.""" + src = write_jsonl( + tmp_path / "sym.jsonl", + [ + {"worked_solution": r"\boxed{\sqrt{4}}", "gold": "2"}, + ], + ) + + report = verify_dataset(src, kind="math", completion="worked_solution", gold="gold") + + if verify._HAVE_SYMPY: + assert report.verified == 1 + assert report.failed == 0 + else: + # Without sympy the symbolic tier is skipped, so it reads as failed. + assert report.verified == 0 + assert report.failed == 1 + + +def test_math_missing_gold_is_unverifiable(tmp_path): + """A row whose gold cell is empty is counted unverifiable, not verified.""" + src = write_jsonl( + tmp_path / "missing_gold.jsonl", + [ + {"worked_solution": r"\boxed{42}", "gold": "42"}, + {"worked_solution": r"\boxed{99}", "gold": ""}, + ], + ) + + report = verify_dataset(src, kind="math", completion="worked_solution", gold="gold") + + assert report.verified == 1 + assert report.failed == 0 + assert report.unverifiable == 1 + + +# ------------------------------------------------------------------------ code +def _fenced(body: str) -> str: + return "```python\n" + body + "\n```" + + +def test_code_happy_path_counts_verified_and_failed(tmp_path): + """A solution that passes its tests verifies; a wrong one fails.""" + passing = _fenced("def add(a, b):\n return a + b") + failing = _fenced("def add(a, b):\n return a - b") + src = write_jsonl( + tmp_path / "code.jsonl", + [ + {"output": passing, "unit_tests": json.dumps(["assert add(1, 2) == 3"])}, + {"output": failing, "unit_tests": json.dumps(["assert add(1, 2) == 3"])}, + ], + ) + + report = verify_dataset(src, kind="code", completion="output", tests="unit_tests") + + assert report.row_count == 2 + assert report.verified == 1 + assert report.failed == 1 + assert report.unverifiable == 0 + + +def test_code_passes_helper_direct(): + code = _fenced("def add(a, b):\n return a + b") + assert code_passes(code, ["assert add(1, 2) == 3"]) + assert not code_passes(code, ["assert add(1, 2) == 99"]) + + +def test_code_missing_tests_column_fails(tmp_path): + """No resolvable tests column -> hard FAIL.""" + src = write_jsonl( + tmp_path / "no_tests.jsonl", + [ + {"output": _fenced("def add(a, b):\n return a + b")}, + ], + ) + + report = verify_dataset(src, kind="code", completion="output") + + assert report.status == "FAIL" + + +# ------------------------------------------------------------------------- out +def test_out_file_contains_only_verified_rows(tmp_path): + """--out writes exactly the verified rows.""" + src = write_jsonl( + tmp_path / "math_out.jsonl", + [ + {"worked_solution": r"\boxed{42}", "gold": "42"}, + {"worked_solution": r"\boxed{43}", "gold": "42"}, + {"worked_solution": r"\boxed{7}", "gold": "7"}, + ], + ) + out = tmp_path / "verified.jsonl" + + report = verify_dataset( + src, kind="math", completion="worked_solution", gold="gold", out=out + ) + + assert report.verified == 2 + assert out.exists() + written = [json.loads(line) for line in out.read_text(encoding="utf-8").splitlines() if line.strip()] + assert len(written) == report.verified + golds = {row["gold"] for row in written} + assert golds == {"42", "7"} + + +# ----------------------------------------------------------------- fail paths +def test_nonexistent_file_fails(tmp_path): + report = verify_dataset(tmp_path / "nope.jsonl", kind="math") + assert report.status == "FAIL" + + +def test_bad_kind_fails(tmp_path): + src = write_csv( + tmp_path / "any.csv", + ["worked_solution", "gold"], + [{"worked_solution": r"\boxed{1}", "gold": "1"}], + ) + report = verify_dataset(src, kind="logic") + assert report.status == "FAIL"