shortlist / code /training /grpo_proof.py
JagritGumber's picture
Add the can-it-be-gamed check, the maze forward test notebook, license, and wording fixes
2c7f145 verified
Raw History Blame Contribute Delete
10.8 kB
"""Training proof: do Shortlist's verdicts predict which environments GRPO can improve a small model on?
For each Reasoning Gym family (the tasks behind OpenEnv's reasoning_gym_env, whose reward is the family's
own `score_answer`), in two separate runs:
python grpo_proof.py --predict-only --out results # 1. write predictions.json (and its SHA-256) first
python grpo_proof.py --out results # 2. train, then compare with the predictions
1. Predict with Shortlist's rule (shortlist/trainee.py, the same rule the shortlist uses for the small model)
from the trainee's own samples, drawn exactly as GRPO draws them (same prompt, temperature and length).
2. Score 200 held-out tasks before training (greedy), train with GRPO + LoRA on the environment's reward,
score the same 200 tasks after. "Improved" means a paired bootstrap on those 200 tasks puts the gain
above zero (p <= 0.05).
Full precision (fp32): a T4 has no bf16, and fp16 can give NaN losses with Qwen3.
"""
from __future__ import annotations
import argparse
import json
import random
import time
from pathlib import Path
import hashlib
import os
import sys
# TRL's GRPO trainer can't use nn.DataParallel, which Trainer picks when several GPUs are visible (Kaggle's T4 x2).
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
import numpy as np
import reasoning_gym
import torch
from datasets import Dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import GRPOConfig, GRPOTrainer
# The trainee's prompt, sampling and Shortlist's rule live in shortlist/trainee.py; on Kaggle or Colab the
# notebook writes that file next to this one.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent))
try:
from shortlist import trainee
except ImportError:
import trainee # type: ignore
messages, clean = trainee.messages, trainee.clean
def tasks(family: str, seeds: range) -> list[dict]:
out = []
for seed in seeds:
entry = reasoning_gym.create_dataset(family, seed=seed, size=1)[0]
out.append({"family": family, "seed": seed, "question": entry["question"], "entry": json.dumps(entry, default=str)})
return out
def score(family: str, seed: int, answer: str) -> float:
ds = reasoning_gym.create_dataset(family, seed=seed, size=1)
try:
return float(ds.score_answer(answer=answer, entry=ds[0]))
except Exception: # a malformed answer earns nothing, as in the environment
return 0.0
@torch.no_grad()
def sample(model, tok, rows: list[dict], n: int, greedy: bool, max_new: int, batch: int = 16) -> list[list[str]]:
"""n completions per row, generated in batches of rows (left-padded)."""
tok.padding_side = "left"
if tok.pad_token is None:
tok.pad_token = tok.eos_token
outs: list[list[str]] = []
batch = max(1, 32 // n) # at most 32 sequences in memory at once
for i in range(0, len(rows), batch):
chunk = rows[i:i + batch]
prompts = [tok.apply_chat_template(messages(r["question"]), tokenize=False, add_generation_prompt=True, enable_thinking=False)
for r in chunk]
enc = tok(prompts, return_tensors="pt", padding=True).to(model.device)
gen = model.generate(**enc, max_new_tokens=max_new, do_sample=not greedy,
temperature=trainee.TEMPERATURE if not greedy else None, top_p=1.0 if not greedy else None,
num_return_sequences=n, pad_token_id=tok.pad_token_id)
texts = [clean(tok.decode(g[enc["input_ids"].shape[1]:], skip_special_tokens=True)) for g in gen]
outs += [texts[j * n:(j + 1) * n] for j in range(len(chunk))]
return outs
def predict(model, tok, family: str, k: int, n_tasks: int, max_new: int) -> dict:
rows = tasks(family, range(500, 500 + n_tasks))
groups = sample(model, tok, rows, k, greedy=False, max_new=max_new)
scores = [[score(family, r["seed"], a) for a in g] for r, g in zip(rows, groups)]
flat = [s for g in scores for s in g]
pass1 = sum(s >= 1.0 for s in flat) / len(flat)
passk = sum(any(s >= 1.0 for s in g) for g in scores) / len(scores)
mean = sum(flat) / len(flat)
disagree = sum(max(g) - min(g) > 1e-9 for g in scores) / len(scores)
verdict = trainee.rule(pass1, mean, disagree)
return {"family": family, "pass@1": pass1, f"pass@{k}": passk, "mean_score": mean, "grpo_signal": disagree,
"shortlist_verdict": verdict, "prediction": "improves" if verdict == "improves" else "no change"}
def evaluate(model, tok, family: str, n: int, max_new: int) -> dict:
rows = tasks(family, range(100_000, 100_000 + n))
answers = [g[0] for g in sample(model, tok, rows, 1, greedy=True, max_new=max_new)]
scores = [score(family, r["seed"], a) for r, a in zip(rows, answers)]
return {"accuracy": sum(s >= 1.0 for s in scores) / n, "mean_score": sum(scores) / n, "scores": scores,
"examples": [{"seed": r["seed"], "answer": a, "score": s} for r, a, s in list(zip(rows, answers, scores))[:5]],
"answers": answers} # every answer, in seed order, so the result can be re-scored later
def paired_gain(before: list[float], after: list[float], n: int = 10000) -> dict:
"""Mean gain on the same tasks, with a paired bootstrap p-value for 'gain <= 0'."""
d = np.asarray(after) - np.asarray(before)
rng = np.random.default_rng(0)
boots = rng.choice(d, (n, len(d))).mean(1)
return {"gain": float(d.mean()), "ci95": [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))],
"p": float(np.mean(boots <= 0))}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--families", default="basic_arithmetic,propositional_logic,word_sorting,leg_counting,letter_counting,chain_sum")
ap.add_argument("--model", default=trainee.MODEL)
ap.add_argument("--steps", type=int, default=100)
ap.add_argument("--group", type=int, default=8)
ap.add_argument("--prompts-per-step", type=int, default=4)
ap.add_argument("--max-new", type=int, default=trainee.MAX_NEW_TOKENS)
ap.add_argument("--eval-n", type=int, default=200)
ap.add_argument("--predict-only", action="store_true", help="write predictions.json and stop")
ap.add_argument("--predict-tasks", type=int, default=24)
ap.add_argument("--lr", type=float, default=5e-5)
ap.add_argument("--out", default="results")
ap.add_argument("--predictions", help="a prediction file written in advance (default: <out>/predictions.json)")
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float32
tok = AutoTokenizer.from_pretrained(args.model)
families = args.families.split(",")
pred_path = Path(args.predictions) if args.predictions and not args.predict_only else out / "predictions.json"
# 1. Predictions, as a separate run, written down before any training.
if args.predict_only:
base = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(device)
predictions = [predict(base, tok, f, args.group, args.predict_tasks, args.max_new) for f in families]
body = json.dumps({"written_at": time.strftime("%Y-%m-%d %H:%M:%S %Z"), "model": args.model,
"rule": f"shortlist/trainee.py: improves if mean score > {trainee.PASS_MIN}, pass@1 < {trainee.PASS_MAX}, "
f"GRPO signal >= {trainee.GRPO_SIGNAL_MIN}",
"settings": vars(args), "predictions": predictions}, indent=2)
pred_path.write_text(body)
digest = hashlib.sha256(body.encode()).hexdigest()
(out / "predictions.sha256").write_text(digest + " predictions.json\n")
print(body, f"\nSHA-256 {digest}", flush=True)
return
if not pred_path.exists():
raise SystemExit("Run with --predict-only first, so the predictions exist before any training.")
predictions = json.loads(pred_path.read_text())["predictions"]
results = []
for pred in predictions:
family = pred["family"]
model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(device)
before = evaluate(model, tok, family, args.eval_n, args.max_new)
train_rows = tasks(family, range(0, args.steps * args.prompts_per_step))
random.Random(0).shuffle(train_rows)
ds = Dataset.from_list([{"prompt": messages(r["question"]), "seed": r["seed"]} for r in train_rows])
def reward(prompts, completions, seed, **_):
texts = [c[0]["content"] if isinstance(c, list) else c for c in completions]
return [score(family, s, clean(t)) for s, t in zip(seed, texts)]
cfg = GRPOConfig(
output_dir=str(out / f"ckpt-{family}"), max_steps=args.steps, learning_rate=args.lr,
per_device_train_batch_size=4, gradient_accumulation_steps=args.group * args.prompts_per_step // 4, num_generations=args.group,
max_completion_length=args.max_new, temperature=1.0, logging_steps=5, save_strategy="no",
report_to=[], fp16=False, bf16=False, gradient_checkpointing=False, seed=0,
)
trainer = GRPOTrainer(model=model, reward_funcs=[reward], args=cfg, train_dataset=ds,
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"))
started = time.time()
trainer.train()
trained = trainer.model.merge_and_unload() if hasattr(trainer.model, "merge_and_unload") else trainer.model
after = evaluate(trained, tok, family, args.eval_n, args.max_new)
curve = [{"step": h.get("step"), "reward": h.get("reward")} for h in trainer.state.log_history if "reward" in h]
gain = paired_gain(before["scores"], after["scores"])
improved = gain["p"] <= 0.05 and gain["gain"] > 0
res = {**pred, "before": {k: v for k, v in before.items() if k != "scores"}, "after": {k: v for k, v in after.items() if k != "scores"},
"gain": gain, "improved": improved, "held": improved == (pred["prediction"] == "improves"),
"reward_curve": curve, "minutes": round((time.time() - started) / 60, 1)}
results.append(res)
(out / "results.json").write_text(json.dumps(results, indent=2))
print(f"{family}: predicted {pred['prediction']}; mean score {before['mean_score']:.3f} -> {after['mean_score']:.3f} "
f"(gain {gain['gain']:+.3f}, p={gain['p']:.3f}); prediction held: {res['held']}", flush=True)
del model, trainer, trained
if device == "cuda":
torch.cuda.empty_cache()
if __name__ == "__main__":
main()