Download experiments/learnability/ablate_updates.py from MilaAI4Math/OpenExpDatasets: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/ablate_updates.py
- Command line
-
hf download hf://datasets/MilaAI4Math/OpenExpDatasets@9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/ablate_updates.py
-
curl -L -o ablate_updates.py https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/ablate_updates.py
15.9 kB
| #!/usr/bin/env python3 | |
| """ | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| # Configuration | |
| # --------------------------------------------------------------------------- | |
| # Checkpoint to start from (all ablations fork from this). | |
| CHECKPOINT_PATH = "/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/0.pt" | |
| # Training examples generated in the *same* iteration (i.e. examples_0.json). | |
| EXAMPLES_PATH = "/datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/examples_0.json" | |
| # Where to write ablation outputs (default: alongside the checkpoint). | |
| OUTPUT_ROOT = None # If None, writes to <checkpoint_dir>/ablations/ | |
| # GPU device index (set to None for CPU). | |
| CUDA_DEVICE = 0 | |
| # wandb project (set to None to disable). | |
| WANDB_PROJECT = "peano-ablation" | |
| # Each dict specifies overrides. Keys: | |
| # mode – "sample" (original: sample with replacement, char-budget batches) | |
| # "epoch" (deduplicate, shuffle, epoch-based, fixed example-count batches) | |
| # n_steps – gradient steps (only for mode="sample"; default: 8000) | |
| # n_epochs – number of epochs (only for mode="epoch"; default: 1) | |
| # batch_size – for mode="sample": character-token budget per batch (default: 10000) | |
| # for mode="epoch": number of examples per batch (default: 64) | |
| # lr – learning rate for AdamW (default: 1e-4) | |
| # tag – human-readable name used in output dir & wandb run name | |
| ABLATION_CONFIGS = [ | |
| # --- Mode A: original sampling (with replacement, char-budget batches) --- | |
| # Dir names auto-generated: updates_{ckpt}_{mode}_{params} | |
| #{"mode": "sample", "n_steps": 2000, "batch_size": 10000}, | |
| #{"mode": "sample", "n_steps": 4000, "batch_size": 10000}, | |
| # --- Mode B: epoch training (deduplicate, shuffle, re-shuffle each epoch) --- | |
| #{"mode": "epoch", "batch_size": 32, "n_epochs": 4, "save_every": 1}, # also save intermediate checkpoints at epoch 2 | |
| {"mode": "epoch", "batch_size": 64, "n_epochs": 2, "save_every": 1}, # save per-epoch ckpts: epoch_1.pt (mid) + epoch_2.pt/1.pt (final) | |
| #{"mode": "epoch", "batch_size": 128, "n_epochs": 4, "save_every": 1}, # also save intermediate checkpoints at epoch 2 | |
| # --- optional: epoch with different lr --- | |
| # {"mode": "epoch", "batch_size": 64, "lr": 5e-5}, | |
| # {"mode": "epoch", "batch_size": 64, "lr": 3e-4}, | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Helpers | |
| # --------------------------------------------------------------------------- | |
| 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) | |
| # examples can be plain strings or dicts with a 'str' key | |
| 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 # LMPolicy | |
| lm = lm_policy._lm # TransformerLMPolicy | |
| 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 # TransformerLMPolicy | |
| if lr is not None: | |
| set_lr(lm._optimizer, lr) | |
| # Deduplicate | |
| unique_examples = list(dict.fromkeys(examples)) # preserves first occurrence order | |
| 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): | |
| # Re-shuffle each epoch | |
| 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 | |
| # Intermediate checkpoint | |
| 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() | |
| # Save final if not already saved by save_every | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| 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) | |
| # Save config (include checkpoint + examples paths for reproducibility) | |
| 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) | |
| # Deep-copy agent so each ablation starts from the same checkpoint | |
| 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) | |
| # Init wandb run for this ablation | |
| 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}") | |
| # Save the trained agent as 1.pt (next iteration checkpoint) | |
| out_path = os.path.join(run_dir, "1.pt") | |
| torch.save(agent, out_path) | |
| print(f"{now()} Saved trained agent to {out_path}") | |
| # Save training stats | |
| 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() | |
| # Set device | |
| if args.device >= 0 and torch.cuda.is_available(): | |
| os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device) | |
| # Seed for reproducible shuffles / training stochasticity (dropout, etc.) | |
| 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 wandb is disabled, make wandb.log a no-op (policy.py's fit() calls it directly) | |
| if not WANDB_PROJECT: | |
| wandb.log = lambda *args, **kwargs: None | |
| # Default output dir: <checkpoint_dir>/ablations/<timestamp>/ | |
| 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} | |
| # Summary | |
| 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() | |
| #command to run this script: | |
| # python ablate_updates.py --checkpoint /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_parallel/2026-01-19_12-06-16/0.pt --examples /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_parallel/2026-01-19_12-06-16/examples_0.json --wandb-project peano-ablation | |
| # python ablate_updates.py --checkpoint /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/0.pt --examples /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_bs_800_para_8000updates/2026-03-10_21-21-05/examples_0.json --wandb-project peano-ablation | |
| # python ablate_updates.py --checkpoint /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_itlearn_fresh_parallel/2026-01-25_12-18-11/0.pt --examples /datadrive/ayush/home/minimoX/learning/outputs/bootstrap_itlearn_fresh_parallel/2026-01-25_12-18-11/examples_5.json --wandb-project peano-ablation |