Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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]"
```
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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<br/>math or code]
Ver --> Dec[adaption-kit decontaminate<br/>against benchmarks]
Dec --> Est[adaption-kit estimate]
Est --> Run[adaption-kit run<br/>pilot first]
Run --> Q2{number look good?}
Q2 -- no --> Tune[change one lever]
Expand All @@ -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;
```

Expand Down Expand Up @@ -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<br/>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<br/>a recipe or a brand control]
Expand All @@ -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;
```

Expand Down
66 changes: 65 additions & 1 deletion adaption_kit/cli.py
Original file line number Diff line number Diff line change
@@ -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``
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
220 changes: 220 additions & 0 deletions adaption_kit/decontaminate.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading