"""STaR — Self-Taught Reasoner. The first method audited, and the cheapest to run. Sample rationales, keep the ones that reach the correct answer, fine-tune on those, repeat. That is the whole algorithm, and the reason it goes first: unlike R-Zero or AZR it needs no RL infrastructure, no rollout workers, and no execution sandbox, so a full audit of it on a real backbone costs ~$150 rather than four weeks of porting. If STaR's ledger shows nothing interesting, the expensive methods were never worth committing to. Two things it shares with every other audited method, and both are easy to get wrong: **The evolution stream must be disjoint from the evaluation set.** Training on MATH-500 problems and then reporting transitions on them would measure memorisation. The stream is drawn from the MATH *training* split; evaluation uses the frozen 200-problem MATH-500 subset, which the model never trains on. **Checkpoints must be far enough apart to move.** Transitions are only detectable if the model actually changes between checkpoints; three near-identical checkpoints produce a ledger indistinguishable from the no-op control. """ from __future__ import annotations import json import time from dataclasses import asdict, dataclass, field from typing import Sequence from ..config import RUNS_DIR, WORKHORSE_MODEL, EvalConfig from ..data.math500 import Problem, load_subset from ..data.benchmarks import resolve from ..evaluate import actual_cost, build_prompt, evaluate_checkpoint from ..grading.verify import grade from ..ledger import build_ledger, measure_noise_floor from ..records import MODE_GREEDY, MODE_SAMPLED, RecordWriter, write_json_atomic @dataclass(slots=True) class StarRound: """What one STaR iteration did — kept for the paper's method-behaviour section.""" checkpoint_t: int n_attempted: int n_solved: int n_training_examples: int @property def solve_rate(self) -> float: return self.n_solved / self.n_attempted if self.n_attempted else 0.0 @dataclass(slots=True) class StarConfig: n_rounds: int = 3 # evolution steps; with t=0 this gives 4 checkpoints problems_per_round: int = 256 samples_per_problem: int = 4 # candidate rationales to filter temperature: float = 0.9 max_tokens: int = 1_024 learning_rate: float = 1e-4 max_examples_per_problem: int = 1 # keep the first correct rationale only # STaR trains to convergence on its filtered set each round. A single pass over ~50 # examples is ~7 optimizer steps and leaves the model unmoved — the first pilot # produced a ledger indistinguishable from the no-op control. epochs: int = 3 batch_size: int = 8 rounds: list[StarRound] = field(default_factory=list) def collect_training_examples( generator, problems: Sequence[Problem], config: StarConfig, ) -> tuple[list[tuple[str, str]], StarRound]: """Sample candidate rationales and keep those that reach the correct answer. This is STaR's only quality signal: the answer check. It is weaker grounding than an execution verifier and stronger than pure self-consistency, which is exactly why STaR is a useful first datapoint for H1 (corruption rate inversely related to grounding strength). """ prompts = [build_prompt(problem) for problem in problems] batches = generator.generate( prompts, n=config.samples_per_problem, temperature=config.temperature, max_tokens=config.max_tokens, ) examples: list[tuple[str, str]] = [] n_solved = 0 for problem, prompt, generations in zip(problems, prompts, batches): kept = 0 for generation in generations: if kept >= config.max_examples_per_problem: break if grade(generation.text, problem.answer).correct: examples.append((prompt, generation.text)) kept += 1 n_solved += int(kept > 0) return examples, StarRound( checkpoint_t=-1, # filled in by the caller n_attempted=len(problems), n_solved=n_solved, n_training_examples=len(examples), ) def run_star_audit( model: str = WORKHORSE_MODEL, *, config: StarConfig | None = None, eval_config: EvalConfig | None = None, n_eval_problems: int = 200, max_inflight: int = 64, run_id: str | None = None, lora_rank: int = 32, seed: int | None = None, resume: bool = True, benchmark: str = "math500", stream: str = "math-train", ) -> dict: """Run STaR for N rounds, evaluating the frozen eval set at every checkpoint. Checkpoint 0 is the untrained base model — the baseline every transition is measured against — so a T-round run produces T+1 checkpoints. Evaluation always uses the same frozen problems; only the model changes. The evolution stream comes from the MATH *training* split and is verified disjoint from those problems (`data/math_train.load_stream`), so a "learned" transition cannot be memorisation of something we then scored. """ from ..backends.tinker_trainer import TinkerTrainer config = config or StarConfig() eval_config = eval_config or EvalConfig(model=model, n_problems=n_eval_problems) run_id = run_id or f"star-{model.split('/')[-1]}-r{config.n_rounds}k{eval_config.k}" run_dir = RUNS_DIR / run_id records_path = run_dir / "records.jsonl" state_path = run_dir / "state.json" # Resume support exists because these runs are long and the service is not always # up: a mid-sweep service outage should cost the minutes # since the last checkpoint, not the whole run. `done` skips evaluations already on # disk; `resume_state` restores the trainer to the round it left off at. done: set = set() resume_state: dict = {} if resume and records_path.exists(): from ..evaluate import completed_units done = completed_units(records_path) if state_path.exists(): resume_state = json.loads(state_path.read_text(encoding="utf-8")) finished = sorted({t for t, _, _ in done}) print(f"[{run_id}] resuming — checkpoints with data on disk: {finished}") elif records_path.exists(): records_path.unlink() spec = resolve( benchmark, stream, n_eval=n_eval_problems, n_stream=config.problems_per_round * config.n_rounds, ) eval_problems, stream = spec.eval_problems, spec.stream_problems print(f"[{run_id}] {spec.description}") if spec.stream_is_eval: print(f"[{run_id}] NOTE: stream IS the evaluation set (unlabelled) — " f"not protocol-matched to disjoint-stream runs") trainer = TinkerTrainer( model, rank=lora_rank, seed=seed, learning_rate=config.learning_rate ) started_round = 0 if resume_state.get("train_state"): trainer.load_training_state(resume_state["train_state"]) started_round = int(resume_state.get("last_round", 0)) print(f"[{run_id}] trainer restored to end of round {started_round}") started = time.time() rounds: list[StarRound] = [] with RecordWriter(records_path) as writer: # t = 0: the untrained base model. generator = trainer.base_sampler(max_inflight=max_inflight) print("[t=0] evaluating base model ...", flush=True) evaluate_checkpoint( generator, eval_problems, run_id=run_id, method="star", checkpoint_t=0, config=eval_config, writer=writer, chunk_size=max_inflight, done=done, progress=False, ) for t in range(1, config.n_rounds + 1): if t <= started_round: continue # this round's training and evaluation are already on disk batch = stream[(t - 1) * config.problems_per_round : t * config.problems_per_round] print(f"[t={t}] collecting rationales from {len(batch)} problems ...", flush=True) examples, round_stats = collect_training_examples(generator, batch, config) round_stats.checkpoint_t = t if not examples: # Nothing passed the correctness filter. Recording it rather than # crashing: a method that stops producing usable data is itself a # finding, and the ledger should show the checkpoint standing still. print(f"[t={t}] no examples survived filtering — skipping training") else: stats = trainer.train( examples, batch_size=config.batch_size, epochs=config.epochs ) print( f"[t={t}] trained on {stats.n_examples} examples " f"({round_stats.solve_rate:.1%} solve rate) — " f"{stats.n_steps} steps, loss {stats.mean_loss}", flush=True, ) checkpoint = trainer.save_checkpoint(t, name=f"{run_id}-t{t}") generator = trainer.sampler_for(checkpoint, max_inflight=max_inflight) rounds.append(round_stats) # Persist the trainer's optimizer state too, not just the sampling weights. # Sampling weights alone cannot continue training, so a resumed run would # otherwise have to redo every earlier round. train_state = trainer.save_training_state(f"{run_id}-state-t{t}") write_json_atomic( state_path, { "last_round": t, "train_state": train_state, "checkpoints": { str(c.step): c.path for c in trainer.checkpoints }, }, ) print(f"[t={t}] evaluating ...", flush=True) evaluate_checkpoint( generator, eval_problems, run_id=run_id, method="star", checkpoint_t=t, config=eval_config, writer=writer, chunk_size=max_inflight, done=done, progress=False, ) elapsed = time.time() - started report = { "run_id": run_id, "model": model, "config": asdict(config), "eval_config": asdict(eval_config), "n_eval_problems": len(eval_problems), "stream": spec.stream, "benchmark": spec.benchmark, "elapsed_seconds": round(elapsed, 1), "cost": actual_cost(records_path), "checkpoints": [ {"step": c.step, "path": c.path} for c in trainer.checkpoints ], "rounds": [asdict(r) for r in rounds], } for mode in (MODE_SAMPLED, MODE_GREEDY): summary = build_ledger(records_path, mode=mode) report[mode] = { "accuracy_first": round(summary.accuracy_first, 4), "accuracy_last": round(summary.accuracy_last, 4), "band": [round(summary.band.theta_lo, 4), round(summary.band.theta_hi, 4)], "label_counts": summary.label_counts, "learned": summary.learned_endpoint, "corrupted": summary.corrupted_endpoint, "clr": summary.clr, "clr_trajectory": summary.clr_trajectory, "net_learned": summary.net_learned, "expansion_rate": summary.expansion_rate, "base_unsolvable_at_k": summary.base_unsolvable_at_k, "expanded_at_k": summary.expanded_at_k, "learned_sharpened": summary.learned_sharpened, "learned_expanded": summary.learned_expanded, "sharpening_fraction": summary.sharpening_fraction, } write_json_atomic(run_dir / "audit.json", report) return report def print_audit(report: dict, noise_floor: dict | None = None) -> None: """Render the headline table — this is the W3 gate in one screen.""" print(f"\n{'=' * 72}\nSTaR AUDIT — {report['run_id']}\n{'=' * 72}") print( f"{report['model']} | {report['n_eval_problems']} problems | " f"{report['elapsed_seconds'] / 60:.1f} min | ${report['cost']['usd']:.2f}" ) print("\nrounds (evolution stream):") for r in report["rounds"]: rate = r["n_solved"] / r["n_attempted"] if r["n_attempted"] else 0 print( f" t={r['checkpoint_t']} solved {r['n_solved']}/{r['n_attempted']} " f"({rate:.1%}) -> {r['n_training_examples']} training examples" ) for mode in (MODE_SAMPLED, MODE_GREEDY): block = report[mode] clr = block["clr"] clr_text = "n/a (nothing learned)" if clr is None else f"{clr:.2f}" verdict = " <-- destroys more than it creates" if clr and clr > 1 else "" print(f"\n[{mode}] band {block['band']}") print(f" accuracy {block['accuracy_first']:.3f} -> {block['accuracy_last']:.3f}") print(f" learned {block['learned']}") print(f" corrupted {block['corrupted']}") print(f" net {block['net_learned']:+d}") print(f" CLR {clr_text}{verdict}") if mode == MODE_SAMPLED: frac = block["sharpening_fraction"] print( f" sharpened {block['learned_sharpened']} of " f"{block['learned_sharpened'] + block['learned_expanded']} newly-solved" f"{'' if frac is None else f' ({frac:.0%})'}" ) rate = block["expansion_rate"] rate_text = "n/a" if rate is None else f"{rate:.2f}" print( f" expansion {block['expanded_at_k']}/" f"{block['base_unsolvable_at_k']} = {rate_text}" ) if noise_floor and mode in noise_floor: floor = noise_floor[mode] print( f" noise floor learned {floor['apparent_learned']}, " f"corrupted {floor['apparent_corrupted']} " f"-> {'CLEARS' if block['corrupted'] > floor['apparent_corrupted'] else 'DOES NOT CLEAR'}" ) print() def main() -> None: import argparse parser = argparse.ArgumentParser(description="Run a STaR audit on Tinker.") parser.add_argument("--model", default=WORKHORSE_MODEL) parser.add_argument("--rounds", type=int, default=3) parser.add_argument("--eval-problems", type=int, default=200) parser.add_argument("--k", type=int, default=128) parser.add_argument("--max-tokens", type=int, default=2048) parser.add_argument("--problems-per-round", type=int, default=256) parser.add_argument("--samples-per-problem", type=int, default=4) parser.add_argument("--epochs", type=int, default=3) parser.add_argument("--max-inflight", type=int, default=64) parser.add_argument("--lora-rank", type=int, default=32) parser.add_argument("--benchmark", choices=("math500","aime","hardband","hardband-l"), default="math500") parser.add_argument("--stream", choices=("math-train","math-train-hard","self"), default="math-train") parser.add_argument("--seed", type=int) parser.add_argument("--run-id") parser.add_argument("--estimate-only", action="store_true") parser.add_argument( "--approved", action="store_true", help="record explicit approval for a run above the $300 threshold (rule 3b). " "Deliberately a flag rather than an env var: approval should appear in the " "command that spent the money, and in the shell history that reproduces it.", ) args = parser.parse_args() from ..evaluate import estimate_cost eval_config = EvalConfig( model=args.model, k=args.k, max_tokens=args.max_tokens, n_problems=args.eval_problems ) estimate = estimate_cost( eval_config, n_checkpoints=args.rounds + 1, n_problems=args.eval_problems, benchmark=args.benchmark, ) print(estimate.summary()) if args.estimate_only: return if estimate.needs_approval and not args.approved: raise SystemExit( "Projected cost exceeds the $300 threshold. " "Get explicit approval before running this, then pass --approved." ) if estimate.needs_approval: print(f" APPROVED by operator — proceeding with a ${estimate.usd:,.2f} run.", flush=True) config = StarConfig( n_rounds=args.rounds, problems_per_round=args.problems_per_round, samples_per_problem=args.samples_per_problem, max_tokens=args.max_tokens, epochs=args.epochs, ) report = run_star_audit( args.model, config=config, eval_config=eval_config, n_eval_problems=args.eval_problems, max_inflight=args.max_inflight, run_id=args.run_id, lora_rank=args.lora_rank, benchmark=args.benchmark, stream=args.stream, seed=args.seed, ) print_audit(report) if __name__ == "__main__": main()