File size: 15,905 Bytes
f1adc24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/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