File size: 4,079 Bytes
74b7543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Does the recurrence converge to a fixed point, or oscillate?

TV(p_n, p_{n-1}) plateauing above zero means the state still moves at every loop.
That is consistent either with a limit cycle or with a slow drift. To tell them
apart we also measure the lag-2 distance: for a period-2 cycle TV(p_n, p_{n-2})
goes to 0 while TV(p_n, p_{n-1}) stays high. We additionally report how often the
top-1 token flips between consecutive loops.

Usage:
  python loop_cycle_check.py --ckpt <ckpt> --data <dataset> --max-length 8 --max-loops 20
"""

import argparse
import json
from pathlib import Path

import torch
import torch.nn.functional as F
from transformers import default_data_collator

import train_twin_hyper as m
from loop_dynamics import build_model, run_n_loops


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", type=Path, required=True)
    ap.add_argument("--data", type=Path, required=True)
    ap.add_argument("--max-length", type=int, required=True)
    ap.add_argument("--max-loops", type=int, default=20)
    ap.add_argument("--n-samples", type=int, default=1000)
    ap.add_argument("--batch-size", type=int, default=500)
    ap.add_argument("--norm-policy", choices=["last", "own"], default="last")
    ap.add_argument("--device", type=str, default="cuda")
    ap.add_argument("--out", type=Path, default=None)
    args = ap.parse_args()

    dev = torch.device(args.device)
    model, tok, hc, saved = build_model(args.ckpt, args.data, None, dev)
    n_trained_disco = hc["num_stages"] - 1

    splits = {}
    tp = args.data / "train.json"
    if tp.exists():
        for h, r in sorted(m.group_by_hops(json.loads(tp.read_text())).items()):
            splits[f"train_{'atom' if h == 1 else str(h) + 'hop'}"] = r
    for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json")):
        p = args.data / fn
        if p.exists():
            for h, r in sorted(m.group_by_hops(json.loads(p.read_text())).items()):
                splits[f"{tag}_{h}hop"] = r

    print(f"{'split':12s} {'n':>3s} {'TV(n,n-1)':>10s} {'TV(n,n-2)':>10s} "
          f"{'cos(n,n-1)':>11s} {'cos(n,n-2)':>11s} {'top1 flip':>10s}")
    out = {}
    for name, recs in splits.items():
        recs = recs[: args.n_samples]
        ds = m.JsonTextDataset(recs, tok, args.max_length, "answer")
        L = args.max_loops
        acc = {k: torch.zeros(L + 1) for k in ("tv1", "tv2", "cos1", "cos2", "flip")}
        cnt = 0
        for s in range(0, len(recs), args.batch_size):
            b = default_data_collator([ds[i] for i in range(s, min(s + args.batch_size, len(recs)))])
            b = {k: v.to(dev) for k, v in b.items()}
            il = b["input_len"]; ar = torch.arange(len(il), device=dev); pos = il - 1
            hist_h, hist_p = {}, {}
            for n in range(1, L + 1):
                h = run_n_loops(model, b["input_ids"], n, n_trained_disco, args.norm_policy)
                hn = h[ar, pos].float()
                pn = torch.softmax(model.lm_head(h)[ar, pos].float(), dim=-1)
                for lag in (1, 2):
                    if n - lag in hist_h:
                        acc[f"tv{lag}"][n] += (0.5 * (pn - hist_p[n - lag]).abs().sum(-1)).sum().cpu()
                        acc[f"cos{lag}"][n] += F.cosine_similarity(hn, hist_h[n - lag], dim=-1).sum().cpu()
                if n - 1 in hist_p:
                    acc["flip"][n] += (pn.argmax(-1) != hist_p[n - 1].argmax(-1)).float().sum().cpu()
                hist_h[n], hist_p[n] = hn, pn
            cnt += len(il)
        out[name] = {k: [float(v[n] / cnt) for n in range(1, L + 1)] for k, v in acc.items()}
        for n in (L - 2, L - 1, L):
            r = out[name]
            print(f"{name:12s} {n:3d} {r['tv1'][n-1]:10.3f} {r['tv2'][n-1]:10.3f} "
                  f"{r['cos1'][n-1]:11.4f} {r['cos2'][n-1]:11.4f} {r['flip'][n-1]:10.3f}")
        print()
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(out, indent=2))
        print(f"written to {args.out}")


if __name__ == "__main__":
    main()