File size: 5,956 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
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
"""What are the oscillating top-1 predictions, and is there a pattern?

For a k-hop chain <a> r_1 ... r_k the recurrence should walk through the intermediate
bridge entities b_1 ... b_{k-1} and stop at the answer. When the recurrence fails to
converge we can ask *which* tokens it cycles between: are they the chain's own bridge
entities (i.e. the model keeps re-walking the chain), unrelated entities, or relations?

For every loop n we classify the top-1 token at the answer position as
  answer | b_j (the j-th intermediate bridge) | head | other entity | relation
and we report the size of the set of distinct predictions in the late regime.

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

import argparse
import json
from collections import Counter
from pathlib import Path

import torch
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("--atoms-from", type=Path, default=Path("data/twin_twohop_truood_diff.500.50.10"))
    ap.add_argument("--max-length", type=int, required=True)
    ap.add_argument("--max-loops", type=int, default=20)
    ap.add_argument("--late-from", type=int, default=11, help="first loop of the 'late' regime")
    ap.add_argument("--n-samples", type=int, default=1000)
    ap.add_argument("--batch-size", type=int, default=500)
    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, _ = build_model(args.ckpt, args.data, None, dev)
    n_trained = hc["num_stages"] - 1

    # adjacency, to name the intermediate bridges of each chain
    adj = {}
    for r in json.loads((args.atoms_from / "train.json").read_text()):
        if len(r["target_text"]) == 3:
            h, rel, t = r["target_text"]
            adj[(h, rel)] = t

    splits = {}
    for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json")):
        p = args.data / fn
        if p.exists():
            for h, recs in sorted(m.group_by_hops(json.loads(p.read_text())).items()):
                splits[f"{tag}_{h}hop"] = recs

    report = {}
    for name, recs in splits.items():
        recs = recs[: args.n_samples]
        hops = len(recs[0]["target_text"]) - 2
        ds = m.JsonTextDataset(recs, tok, args.max_length, "answer")

        # role of every token for every chain: answer / b_j / head
        roles = []
        for rec in recs:
            toks = rec["target_text"]
            cur, chain = toks[0], {toks[0]: "head"}
            for j, rel in enumerate(toks[1:-1], start=1):
                cur = adj[(cur, rel)]
                chain[cur] = "answer" if j == hops else f"b{j}"
            roles.append(chain)

        top1 = [[] for _ in recs]                       # per sample, per n
        for s in range(0, len(recs), args.batch_size):
            idx = list(range(s, min(s + args.batch_size, len(recs))))
            b = default_data_collator([ds[i] for i in idx])
            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
            for n in range(1, args.max_loops + 1):
                h = run_n_loops(model, b["input_ids"], n, n_trained, "last")
                t = model.lm_head(h)[ar, pos].argmax(-1).tolist()
                for k, i in enumerate(idx):
                    top1[i].append(tok.id_to_token[t[k]])

        def role_of(sample_i, token):
            r = roles[sample_i].get(token)
            if r:
                return r
            return "relation" if token.startswith("<r_") else "other entity"

        # (a) how many distinct predictions in the late regime
        late = [set(t[args.late_from - 1:]) for t in top1]
        sizes = Counter(len(s) for s in late)
        n_tot = len(recs)
        # (b) role mix per loop
        per_n = {n: Counter(role_of(i, top1[i][n - 1]) for i in range(n_tot))
                 for n in range(1, args.max_loops + 1)}
        # (c) for the oscillating samples, which roles do they alternate between?
        pairs = Counter()
        for i, s in enumerate(late):
            if 2 <= len(s) <= 3:
                pairs[tuple(sorted(role_of(i, t) for t in s))] += 1

        print(f"===== {name}  ({hops}-hop, n={n_tot}) =====")
        print("  distinct top-1 tokens over loops "
              f"{args.late_from}..{args.max_loops}:")
        for k in sorted(sizes):
            print(f"     {k} distinct: {sizes[k] / n_tot:6.1%}")
        print("  role of the top-1 prediction by loop:")
        order = ["answer"] + [f"b{j}" for j in range(hops - 1, 0, -1)] + ["head", "other entity", "relation"]
        hdr = "   n  " + "".join(f"{o:>14s}" for o in order)
        print(hdr)
        for n in list(range(1, min(8, args.max_loops + 1))) + [args.max_loops // 2, args.max_loops]:
            c = per_n[n]
            print(f"  {n:2d}  " + "".join(f"{c.get(o, 0) / n_tot:13.1%} " for o in order))
        if pairs:
            print("  most common role sets among oscillating samples:")
            for combo, cnt in pairs.most_common(5):
                print(f"     {'+'.join(combo):40s} {cnt / n_tot:6.1%}")
        print()
        report[name] = {
            "hops": hops,
            "distinct_sizes": {str(k): v for k, v in sizes.items()},
            "role_by_loop": {str(n): dict(c) for n, c in per_n.items()},
            "oscillating_role_sets": {"+".join(k): v for k, v in pairs.items()},
        }

    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(report, indent=2))
        print(f"written to {args.out}")


if __name__ == "__main__":
    main()