| |
|
|
| """ |
| Ablation script: loads a checkpoint and the next iteration's training data, |
| then trains copies of the agent with different hyperparameter configs |
| (number of updates, learning rate, batch size, etc.) and evaluates each. |
| |
| Usage: |
| python ablate_updates.py |
| |
| Edit the ABLATION_CONFIGS list below to define the hyperparameter grid. |
| """ |
|
|
| import os |
| import io |
| import copy |
| import json |
| import random |
| import datetime |
| import argparse |
|
|
| import torch |
| import wandb |
| from tqdm import tqdm |
|
|
| |
| |
| |
|
|
| |
| CHECKPOINT_PATH = "/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/0.pt" |
|
|
| |
| EXAMPLES_PATH = "/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/examples_0.json" |
|
|
| |
| OUTPUT_ROOT = None |
|
|
| |
| CUDA_DEVICE = 0 |
|
|
| |
| WANDB_PROJECT = "peano-ablation" |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| ABLATION_CONFIGS = [ |
| |
| |
| |
| |
|
|
| |
| |
| {"mode": "epoch", "batch_size": 64, "n_epochs": 2, "save_every": 1}, |
| |
|
|
| |
| |
| |
| ] |
|
|
| |
| |
| |
|
|
| def now() -> str: |
| return "[" + datetime.datetime.now().isoformat() + "]" |
|
|
|
|
| def load_examples(path: str) -> list[str]: |
| """Load training examples (list of strings) from a JSON file.""" |
| with open(path) as f: |
| examples = json.load(f) |
| |
| out = [] |
| for e in examples: |
| if isinstance(e, str): |
| out.append(e) |
| elif isinstance(e, dict) and "str" in e: |
| out.append(e["str"]) |
| else: |
| raise ValueError(f"Unexpected example format: {type(e)}") |
| return out |
|
|
|
|
| def ckpt_num(path: str) -> str: |
| """Extract checkpoint number from path, e.g. '/foo/0.pt' -> '0'.""" |
| return os.path.splitext(os.path.basename(path))[0] |
|
|
|
|
| def make_run_name(cfg: dict, checkpoint_path: str) -> str: |
| """Build directory name: updates_{ckpt_num}_{mode}_{params}.""" |
| cn = ckpt_num(checkpoint_path) |
| mode = cfg.get("mode", "sample") |
| parts = [f"updates_{cn}", mode] |
| if mode == "sample": |
| parts.append(f"{cfg.get('n_steps', 8000)}steps") |
| bs = cfg.get('batch_size') or 10000 |
| parts.append(f"bs{bs}") |
| elif mode == "epoch": |
| parts.append(f"{cfg.get('n_epochs', 1)}ep") |
| bs = cfg.get('batch_size') or 64 |
| parts.append(f"bs{bs}") |
| if cfg.get("lr") is not None: |
| parts.append(f"lr{cfg['lr']}") |
| return "_".join(parts) |
|
|
|
|
| def deep_copy_agent(agent): |
| """Deep-copy an agent via serialize/deserialize (handles CUDA tensors).""" |
| buf = io.BytesIO() |
| torch.save(agent, buf) |
| buf.seek(0) |
| return torch.load(buf, weights_only=False) |
|
|
|
|
| def set_lr(optimizer, lr: float): |
| """Override learning rate on all param groups.""" |
| for pg in optimizer.param_groups: |
| pg["lr"] = lr |
|
|
|
|
| def train_agent_sample(agent, examples: list[str], n_steps: int, |
| batch_size: int | None = None, |
| lr: float | None = None, |
| verbose: bool = True): |
| """ |
| Original training mode: sample batches with replacement. |
| |
| - n_steps: number of gradient steps |
| - batch_size: total character-token budget per batch (default from agent) |
| - lr: learning rate override |
| """ |
| lm_policy = agent._policy |
| lm = lm_policy._lm |
|
|
| bs = batch_size if batch_size is not None else lm_policy._batch_size |
|
|
| if lr is not None: |
| set_lr(lm._optimizer, lr) |
|
|
| lm.fit(examples, bs, n_steps, verbose=verbose) |
| lm.eval() |
| return n_steps |
|
|
|
|
| def train_agent_epoch(agent, examples: list[str], |
| batch_size: int = 64, |
| n_epochs: int = 1, |
| lr: float | None = None, |
| save_every: int | None = None, |
| run_dir: str | None = None, |
| verbose: bool = True): |
| """ |
| Epoch-based training: deduplicate, then train for n_epochs epochs |
| with re-shuffling each epoch and fixed example-count batches. |
| |
| - batch_size: number of examples per batch |
| - n_epochs: number of passes over the dataset |
| - lr: learning rate override |
| - save_every: save a checkpoint every N epochs (None = only final) |
| - run_dir: directory to save intermediate checkpoints into |
| """ |
| lm = agent._policy._lm |
|
|
| if lr is not None: |
| set_lr(lm._optimizer, lr) |
|
|
| |
| unique_examples = list(dict.fromkeys(examples)) |
| print(f" Dedup: {len(examples)} -> {len(unique_examples)} unique examples") |
|
|
| lm._lm.train() |
| batches_per_epoch = (len(unique_examples) + batch_size - 1) // batch_size |
| total_steps = 0 |
| saved_epochs = set() |
|
|
| for epoch in range(n_epochs): |
| |
| random.shuffle(unique_examples) |
|
|
| rng = range(batches_per_epoch) |
| if verbose: |
| rng = tqdm(rng, desc=f"Epoch {epoch+1}/{n_epochs}") |
|
|
| for i in rng: |
| batch = unique_examples[i * batch_size : (i + 1) * batch_size] |
| lm._optimizer.zero_grad() |
| loss = lm.get_loss(batch) |
| loss.backward() |
| wandb.log({"train_loss": loss, "epoch": epoch + 1}) |
| lm._optimizer.step() |
| total_steps += 1 |
|
|
| |
| if save_every and run_dir and (epoch + 1) % save_every == 0: |
| lm._lm.eval() |
| ckpt_path = os.path.join(run_dir, f"epoch_{epoch+1}.pt") |
| torch.save(agent, ckpt_path) |
| print(f" {now()} Saved checkpoint at epoch {epoch+1} -> {ckpt_path}") |
| saved_epochs.add(epoch + 1) |
| lm._lm.train() |
|
|
| lm._lm.eval() |
|
|
| |
| if run_dir and n_epochs not in saved_epochs: |
| final_path = os.path.join(run_dir, f"epoch_{n_epochs}.pt") |
| torch.save(agent, final_path) |
| print(f" {now()} Saved final checkpoint -> {final_path}") |
|
|
| print(f" Done: {n_epochs} epoch(s), {total_steps} total steps, " |
| f"{len(unique_examples)} unique examples (batch_size={batch_size})") |
| return total_steps |
|
|
|
|
| |
| |
| |
|
|
| def run_ablation(cfg: dict, base_agent, examples: list[str], output_root: str, |
| checkpoint_path: str, examples_path: str = None): |
| tag = cfg.get("tag") or make_run_name(cfg, checkpoint_path) |
| mode = cfg.get("mode", "sample") |
| n_steps = cfg.get("n_steps", 8000) |
| batch_size = cfg.get("batch_size", None) |
| lr = cfg.get("lr", None) |
|
|
| run_dir = os.path.join(output_root, tag) |
| os.makedirs(run_dir, exist_ok=True) |
|
|
| |
| saved_cfg = {**cfg, "checkpoint": checkpoint_path, "examples": examples_path} |
| with open(os.path.join(run_dir, "ablation_config.json"), "w") as f: |
| json.dump(saved_cfg, f, indent=2) |
|
|
| |
| print(f"\n{'='*60}") |
| print(f"{now()} Starting ablation: {tag} (mode={mode})") |
| print(f" n_steps={n_steps}, batch_size={batch_size}, lr={lr}") |
| print(f" output -> {run_dir}") |
| print(f"{'='*60}") |
|
|
| agent = deep_copy_agent(base_agent) |
|
|
| |
| wandb_config = { |
| "checkpoint": CHECKPOINT_PATH, |
| "examples": EXAMPLES_PATH, |
| "mode": mode, |
| "batch_size": batch_size or agent._policy._batch_size, |
| "lr": lr or agent._policy._lm._optimizer.param_groups[0]["lr"], |
| "tag": tag, |
| } |
| if mode == "sample": |
| wandb_config["n_steps"] = n_steps |
| elif mode == "epoch": |
| wandb_config["n_epochs"] = cfg.get("n_epochs", 1) |
| if WANDB_PROJECT: |
| wandb.init( |
| project=WANDB_PROJECT, |
| name=tag, |
| config=wandb_config, |
| reinit=True, |
| ) |
|
|
| if mode == "sample": |
| total_steps = train_agent_sample(agent, examples, n_steps=n_steps, |
| batch_size=batch_size, lr=lr) |
| elif mode == "epoch": |
| total_steps = train_agent_epoch(agent, examples, |
| batch_size=batch_size or 64, |
| n_epochs=cfg.get("n_epochs", 1), lr=lr, |
| save_every=cfg.get("save_every"), |
| run_dir=run_dir) |
| else: |
| raise ValueError(f"Unknown training mode: {mode}") |
|
|
| |
| out_path = os.path.join(run_dir, "1.pt") |
| torch.save(agent, out_path) |
| print(f"{now()} Saved trained agent to {out_path}") |
|
|
| |
| stats = {"total_gradient_steps": total_steps} |
| with open(os.path.join(run_dir, "train_stats.json"), "w") as f: |
| json.dump(stats, f, indent=2) |
|
|
| if WANDB_PROJECT: |
| wandb.finish() |
|
|
| return out_path, total_steps |
|
|
|
|
| def main(): |
| global WANDB_PROJECT |
| parser = argparse.ArgumentParser(description="Ablation over training hyperparameters") |
| parser.add_argument("--checkpoint", default=CHECKPOINT_PATH, |
| help="Path to the base .pt checkpoint") |
| parser.add_argument("--examples", default=EXAMPLES_PATH, |
| help="Path to examples JSON file") |
| parser.add_argument("--output", default=None, |
| help="Root output directory (default: <checkpoint_dir>/ablations/)") |
| parser.add_argument("--device", type=int, default=CUDA_DEVICE, |
| help="CUDA device index (use -1 for CPU)") |
| parser.add_argument("--seed", type=int, default=None, |
| help="Random seed for reproducible shuffling/training (default: unseeded).") |
| parser.add_argument("--wandb-project", default=WANDB_PROJECT, |
| help="W&B project name (empty string to disable)") |
| parser.add_argument("--configs", nargs="+", default=None, |
| help="Run only ablations whose tags match these (default: all)") |
| args = parser.parse_args() |
|
|
| |
| if args.device >= 0 and torch.cuda.is_available(): |
| os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device) |
|
|
| |
| if args.seed is not None: |
| random.seed(args.seed) |
| torch.manual_seed(args.seed) |
| torch.cuda.manual_seed_all(args.seed) |
| print(f"{now()} Seeded RNGs with seed={args.seed}") |
|
|
| WANDB_PROJECT = args.wandb_project or None |
|
|
| |
| if not WANDB_PROJECT: |
| wandb.log = lambda *args, **kwargs: None |
|
|
| |
| ckpt_dir = os.path.dirname(os.path.abspath(args.checkpoint)) |
| timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") |
| output_root = os.path.join(args.output or os.path.join(ckpt_dir, "ablations"), timestamp) |
| os.makedirs(output_root, exist_ok=True) |
|
|
| print(f"{now()} Loading checkpoint from {args.checkpoint}") |
| base_agent = torch.load(args.checkpoint, weights_only=False) |
|
|
| print(f"{now()} Loading examples from {args.examples}") |
| examples = load_examples(args.examples) |
| print(f" {len(examples)} training examples loaded.") |
|
|
| configs = ABLATION_CONFIGS |
| if args.configs: |
| configs = [c for c in configs if |
| (c.get("tag") or make_run_name(c, args.checkpoint)) in args.configs] |
| print(f" Running subset: {[c.get('tag') or make_run_name(c, args.checkpoint) for c in configs]}") |
|
|
| results = {} |
|
|
| for cfg in configs: |
| agent_path, total_steps = run_ablation(cfg, base_agent, examples, output_root, |
| args.checkpoint, |
| examples_path=os.path.abspath(args.examples)) |
| run_name = cfg.get("tag") or make_run_name(cfg, args.checkpoint) |
| results[run_name] = {"path": agent_path, "total_gradient_steps": total_steps} |
|
|
| |
| print(f"\n{'='*60}") |
| print(f"{now()} All ablations complete.") |
| print(f"{'='*60}") |
| summary_path = os.path.join(output_root, "summary.json") |
| with open(summary_path, "w") as f: |
| json.dump({ |
| "checkpoint": os.path.abspath(args.checkpoint), |
| "examples": os.path.abspath(args.examples), |
| "configs": ABLATION_CONFIGS, |
| "results": results, |
| }, f, indent=2) |
| print(f"Summary saved to {summary_path}") |
|
|
| for tag, path in results.items(): |
| print(f" {tag}: {path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|
| |
|
|
| |
|
|
| |
|
|
| |