summaryrefslogtreecommitdiff
path: root/src/train.py
blob: aa0fb4b78948d9b53eb5cace1e6d7351290a0c98 (plain)
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
"""Training loop. Usage: python -m src.train [model] [seed] [--flag ...]"""
import csv
import json
import math
import os
import random
import sys

import numpy as np
import torch
import torch.nn as nn

from src.config import Config, parse_args
from src.data import build_examples, decode_tokens, get_splits, make_batch
from src.model_api import build_model


def set_seed(s: int) -> None:
    random.seed(s)
    np.random.seed(s)
    torch.manual_seed(s)


@torch.no_grad()
def evaluate(model, examples, cfg: Config):
    """Token accuracy (teacher-forced) + exact-match accuracy (batched greedy) + per-example detail.

    BATCHED: all examples in ONE forward pass (greedy decode batch-wide). Valid because
    models are batch-invariant by construction (global fixed layout, pad no-ops — see
    tests/test_codex_fixes.py). ~50x fewer forwards than the per-example version."""
    model.eval()
    batch = make_batch(examples, cfg)
    out = model(batch["x"], batch["y_in"])
    logits = out["logits"]                                  # (B,T_out,vocab)
    y = batch["y"]
    mask = batch["y_mask"]
    pred_tok = logits.argmax(-1)
    token_correct = int((pred_tok[mask] == y[mask]).sum())
    token_total = int(mask.sum())
    # batched greedy decode
    B = batch["x"].shape[0]
    y_in = torch.full((B, 1), cfg.eos_id, dtype=torch.long)
    for _ in range(cfg.max_out_len):
        o = model(batch["x"], y_in)
        nxt = o["logits"][:, -1].argmax(-1)
        y_in = torch.cat([y_in, nxt[:, None]], dim=1)
    gen = y_in[:, 1:]                                        # (B, max_out_len)
    em_correct = 0
    per_example = []
    for i, (xrow, target) in enumerate(examples):
        pred = decode_tokens(gen[i].tolist(), cfg)
        target_n = decode_tokens(target, cfg)
        ok = pred == target_n
        em_correct += int(ok)
        per_example.append((tuple(xrow), target_n, pred, ok))
    model.train()
    return token_correct / max(1, token_total), em_correct / len(examples), per_example


def log_example_rows(log_examples, val_per_example):
    """Format the fixed 10 logged val inputs as '42:ok' strings, in fixed order."""
    by_x = {x: (target, pred, ok) for x, target, pred, ok in val_per_example}
    rows = []
    for x, _target in log_examples:
        t, p, ok = by_x[tuple(x)]
        label = "".join(map(str, x))  # "42" in both vocab modes
        rows.append(f"{label}:{'ok' if ok else f'{p}~{t}'}")
    return ";".join(rows)


def main() -> None:
    cfg = parse_args()
    set_seed(cfg.seed)
    out_dir = os.path.join(cfg.out_dir, cfg.model, f"seed{cfg.seed}")
    csv_path = os.path.join(out_dir, "metrics.csv")
    if os.path.exists(csv_path):
        raise SystemExit(f"REFUSING to rerun in place: {csv_path} exists. Use a fresh --out_dir "
                         f"(reruns would corrupt the CSV and checkpoint provenance).")
    os.makedirs(out_dir, exist_ok=True)
    cfg.save(os.path.join(out_dir, "config.json"))
    with open(os.path.join(out_dir, "run_meta.json"), "w") as fh:
        json.dump({
            "python": sys.version.split()[0],
            "torch": torch.__version__,
            "numpy": np.__version__,
            "device": "cpu",
            "torch_threads": torch.get_num_threads(),
            "cmd": sys.argv,
        }, fh, indent=2)

    train_in, val_in = get_splits(cfg)
    train_ex = build_examples(train_in, cfg)
    val_ex = build_examples(val_in, cfg)
    model = build_model(cfg)
    print(f"model={cfg.model} params={model.param_count()} train={len(train_ex)} val={len(val_ex)} "
          f"vocab={cfg.vocab} eos={cfg.eos_id} pad={cfg.pad_id}")

    opt = torch.optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
    ce = nn.CrossEntropyLoss(reduction="none")

    log_examples = sorted(val_ex, key=lambda ex: (len(ex[0]), ex[0]))[: cfg.log_n_examples]

    fieldnames = ["step", "train_loss", "train_token_acc", "train_em", "val_token_acc",
                  "val_em", "mean_halt_steps", "log_examples", "param_count"]
    best_val_em = -1.0
    patience_left = cfg.early_stop_patience
    best_path = os.path.join(out_dir, "best.pt")

    n_batches = math.ceil(len(train_ex) / cfg.batch_size)
    rng = random.Random(cfg.seed)
    step = 0
    done = False
    first_row = True

    def _eval_pass(cur_loss, halt_steps):
        nonlocal best_val_em, patience_left, done, first_row
        train_tok, train_em, _ = evaluate(model, train_ex, cfg)
        val_tok, val_em, val_per = evaluate(model, val_ex, cfg)
        mean_halt = float(halt_steps.mean()) if halt_steps is not None else float("nan")
        row = {
            "step": step, "train_loss": float(cur_loss), "train_token_acc": train_tok,
            "train_em": train_em, "val_token_acc": val_tok, "val_em": val_em,
            "mean_halt_steps": mean_halt,
            "log_examples": log_example_rows(log_examples, val_per),
            "param_count": model.param_count(),
        }
        with open(csv_path, "a", newline="") as fh:
            w = csv.DictWriter(fh, fieldnames=fieldnames)
            if first_row:
                w.writeheader()
                first_row = False
            w.writerow(row)
        if val_em > best_val_em:
            best_val_em = val_em
            torch.save(model.state_dict(), best_path)
        if val_em >= cfg.early_stop_em:
            patience_left -= 1
        else:
            patience_left = cfg.early_stop_patience
        if patience_left <= 0:
            done = True
        print(f"step {step} loss {float(cur_loss):.4f} train_em {train_em:.3f} "
              f"val_em {val_em:.3f} val_tok {val_tok:.3f} halt {mean_halt:.2f}")

    while step < cfg.max_train_steps and not done:
        rng.shuffle(train_ex)
        for bi in range(n_batches):
            sl = train_ex[bi * cfg.batch_size: (bi + 1) * cfg.batch_size]
            if not sl:
                continue
            batch = make_batch(sl, cfg)
            out = model(batch["x"], batch["y_in"])
            logits = out["logits"]
            y_safe = batch["y"].clamp(max=cfg.vocab - 1)   # CE index guard for pad positions
            loss_tokens = ce(logits.reshape(-1, cfg.vocab), y_safe.reshape(-1)).reshape(
                logits.shape[0], -1) * batch["y_mask"].float()
            loss_tokens = loss_tokens.sum() / batch["y_mask"].sum().clamp(min=1)
            if cfg.halting and step >= cfg.halt_warmup_steps:
                if step >= cfg.halt_ramp_end_steps:
                    lam = cfg.halt_penalty
                else:
                    frac = (step - cfg.halt_warmup_steps) / max(1, cfg.halt_ramp_end_steps - cfg.halt_warmup_steps)
                    lam = cfg.halt_penalty * frac
            else:
                lam = 0.0
            halt = out["halt_steps"]
            penalty = halt.float().mean() * lam if halt is not None and lam > 0 else 0.0
            loss = loss_tokens + penalty
            opt.zero_grad()
            loss.backward()
            opt.step()
            step += 1
            if step % cfg.eval_every == 0 or step >= cfg.max_train_steps:
                _eval_pass(loss.detach(), halt.detach() if halt is not None else None)
                if done:
                    break
            if step >= cfg.max_train_steps:
                break

    torch.save(model.state_dict(), os.path.join(out_dir, "last.pt"))
    print(f"DONE steps={step} best_val_em={best_val_em:.4f}")


if __name__ == "__main__":
    main()