alea-runs / alea /loop.py
Akahsizrr's picture
Upload alea/loop.py with huggingface_hub
cc53259 verified
Raw History Blame
4.98 kB
"""Iterative training loop: generate -> train -> eval -> repeat.
Each round generates a FRESH corpus (new seed -> new instances), trains from
the previous round's checkpoint, and evaluates on a FIXED test set so metrics
are comparable across rounds. Appends to runs/loop_history.jsonl.
Usage:
python -m alea.loop --rounds 4 --init runs\alea_v3\final.pt
"""
import argparse
import json
import os
import subprocess
import sys
import time
def run(cmd, **kw):
print("+", " ".join(cmd), flush=True)
return subprocess.run(cmd, **kw)
def gen_corpus(round_idx, n, out_path, shares, seed_base):
from .gen_all import build
rows = build(n, seed=seed_base + round_idx, shares=shares)
from .genbase import write_jsonl
write_jsonl(rows, out_path)
return len(rows)
def eval_metrics(ckpt, test_path, max_items=1500):
r = run([sys.executable, "-m", "alea.eval", "--ckpt", ckpt,
"--data", test_path, "--max-items", str(max_items),
"--skip-structural"], capture_output=True, text=True)
out = r.stdout
start = out.find("{")
end = out.rfind("}") + 1
if start < 0 or end <= start:
print(out[-2000:], r.stderr[-2000:])
return {}
try:
return json.loads(out[start:end])
except json.JSONDecodeError:
print(out[-2000:])
return {}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--rounds", type=int, default=4)
ap.add_argument("--init", required=True, help="starting checkpoint")
ap.add_argument("--n-per-round", type=int, default=60000)
ap.add_argument("--epochs-per-round", type=float, default=1.0)
ap.add_argument("--batch", type=int, default=16)
ap.add_argument("--accum", type=int, default=2)
ap.add_argument("--test", default="data/test_loop.jsonl")
ap.add_argument("--shares", default=None)
ap.add_argument("--lr-head", type=float, default=1e-4)
ap.add_argument("--lr-backbone", type=float, default=1e-5)
ap.add_argument("--eval-items", type=int, default=1500)
ap.add_argument("--history", default="runs/loop_history.jsonl")
args = ap.parse_args()
env = dict(os.environ)
env.setdefault("PYTHONIOENCODING", "utf-8")
shares = json.loads(args.shares) if args.shares else {
"gen_stoch": 0.9, "gen_enterprise": 1.0, "gen_structured": 0.8,
"gen_adversarial": 0.6, "gen_numeric": 0.7, "gen_long": 0.5,
"base": 0.4, "gen_kaggle_cls": 1.0, "gen_kaggle_reg": 0.7,
"gen_hf": 1.3}
# drop shares for modules that don't exist yet
from . import gen_all
avail = gen_all.sources()
shares = {k: w for k, w in shares.items() if k in avail}
print("active sources:", shares, flush=True)
# fixed test set for comparable metrics across rounds
if not os.path.exists(args.test):
print("generating fixed loop test set...", flush=True)
rows = gen_all.build(3000, seed=777, shares=shares)
from .genbase import write_jsonl
write_jsonl(rows, args.test)
print(f" wrote {len(rows)} -> {args.test}", flush=True)
ckpt = args.init
prev_loop_ckpt = None
for r in range(args.rounds):
t0 = time.time()
print(f"\n===== ROUND {r} (init={ckpt}) =====", flush=True)
corpus = f"data/loop_train_r{r}.jsonl"
if not os.path.exists(corpus):
n = gen_corpus(r, args.n_per_round, corpus, shares,
seed_base=1000)
print(f"corpus: {n} rows -> {corpus}", flush=True)
else:
print(f"corpus exists: {corpus}", flush=True)
outdir = f"runs/loop_r{r}"
run([sys.executable, "-m", "alea.train",
"--train", corpus, "--dev", args.test,
"--out", outdir, "--init-from", ckpt,
"--train-mode", "full",
"--epochs", str(args.epochs_per_round),
"--batch", str(args.batch), "--accum", str(args.accum),
"--lr-head", str(args.lr_head),
"--lr-backbone", str(args.lr_backbone),
"--attn", "sdpa", "--save-every", "100000",
"--max-len", "4096"], env=env)
ckpt = os.path.join(outdir, "final.pt")
if not os.path.exists(ckpt):
print(f"ROUND {r} TRAIN FAILED - stopping", flush=True)
break
# keep only the newest loop checkpoint (each ~1.3GB); the --init
# base is outside runs/loop_* and untouched
if prev_loop_ckpt and os.path.exists(prev_loop_ckpt):
os.remove(prev_loop_ckpt)
prev_loop_ckpt = ckpt
m = eval_metrics(ckpt, args.test, args.eval_items)
rec = {"round": r, "ckpt": ckpt, "minutes":
round((time.time() - t0) / 60, 1), **m}
with open(args.history, "a", encoding="utf-8") as fh:
fh.write(json.dumps(rec) + "\n")
print(f"ROUND {r} METRICS {json.dumps(m)}", flush=True)
print("\nloop done. history:", args.history)
if __name__ == "__main__":
main()