File size: 11,427 Bytes
3970207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Mechanistic analysis of a trained vanilla looped transformer (Section 3.2).

Takes a vanilla looped model with K=2 trained by train_twin_hyper.py on the symbolic
two-hop task (scripts/symbolic_2hop.sh vanilla), re-creates the run's data splits
(same seeded sampling as the trainer) and computes:

1. Table 1a: Stage-1 / Stage-2 accuracy on train_atom, train_2hop (train_id in the
   paper), test_id and test_ood. Stage 1 reads the LM head off the hidden states H1
   after the first loop, Stage 2 off the hidden states after both loops.
2. Table 1b: logit lens at position 1 after the first loop, on test_id and test_ood:
   P(b | H1_1) = softmax(W H1_1)_b and cos(H1_1, W[b]) for the ground-truth bridge b.
3. Figure 2: the training-free intervention of Eq. 3. Between the two loops, at
   position 1 only, H1_1 <- (1 - alpha) * H1_1 + alpha * Norm(W[b_max]), where
   b_max = argmax(W H1_1) and Norm(x) = x / RMS(x) (no learned scale); test_id and
   test_ood accuracy for each alpha in ALPHAS.

Usage, from the repository root (a run stores its --data-dir relative to the directory
it was launched from, which train_twin_hyper.sh sets to the repository root;
--data-dir overrides it):
  python interp_intervention.py --run-dir <run_dir> [--device cuda:0] [--out file.json] [--data-dir DIR]

Results are printed and written to <run_dir>/interp_section3.json (or --out).
"""

import argparse
import json
import random
import types
from pathlib import Path

import torch
import torch.nn.functional as F

import train_twin_hyper as m

ALPHAS = [0.0, 0.1, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1.0]


# --------------------------------------------------------------------------- io
def load_model(ckpt, data_dir: Path, device):
    """Rebuild the model saved in a stage2_hyper/hyper_model.pt checkpoint."""
    hc = ckpt["hyper_config"]
    loop_scheme = hc.get("loop_scheme", "vanillaloop")
    architecture = hc.get("architecture", "looping")
    if loop_scheme != "vanillaloop" or hc["num_stages"] != 2 or architecture != "looping":
        # stage1_hidden / stage2_logits run the plain loop H(k+1) = f(H(k)) with no update in between.
        raise ValueError(
            "this analysis supports only vanilla looped models with K=2 (DiscoLoop, the stacked "
            "baseline and other K are not supported), "
            f"got loop_scheme={loop_scheme}, architecture={architecture}, num_stages={hc['num_stages']}"
        )
    # HyperConnectionGPT2LM always adds position embeddings and ties the input/output embeddings.
    if not hc.get("use_position_embeddings", True) or hc.get("untied_embeddings", False):
        raise ValueError("checkpoints without position embeddings or with untied embeddings are not supported")
    args_ns = types.SimpleNamespace(model_name=ckpt["args"]["model_name"], data_dir=data_dir)
    tokenizer = m.build_tokenizer(args_ns)
    model = m.HyperConnectionGPT2LM(
        base_model=m.build_base_model(args_ns, tokenizer),
        num_stages=hc["num_stages"],
        architecture=hc["architecture"],
        gate_mode=hc["gate_mode"],
        fixed_alpha=hc["fixed_alpha"],
        fixed_beta=hc["fixed_beta"],
        loop_scheme=loop_scheme,
    )
    model.load_state_dict(ckpt["state_dict"])  # strict: no missing or unexpected keys
    return model.eval().to(device), tokenizer


def rebuild_splits(data_dir: Path, seed: int, train_twohop_count: int, eval_id_count: int, eval_ood_count: int):
    """The run's splits, sampled as in train_twin_hyper.main (same rng calls in the same order)."""
    if train_twohop_count < 0 or (data_dir / "test_id.json").exists() or (data_dir / "test_ood.json").exists():
        raise ValueError("expected a run on train.json/test.json with a held-out ID split (--train-twohop-count >= 0)")
    train_groups = m.group_by_hops(m.load_json(data_dir / "train.json"))
    rng = random.Random(seed)
    multihop = [item for hops in sorted(train_groups) if hops > 1 for item in train_groups[hops]]
    rng.shuffle(multihop)

    def subsample_groups(pool, count):
        groups = m.group_by_hops(pool)
        if count >= 0:
            groups = {k: (rng.sample(v, count) if count < len(v) else v) for k, v in groups.items()}
        return groups

    id_groups = subsample_groups(multihop[train_twohop_count:], eval_id_count)
    ood_groups = subsample_groups(m.load_json(data_dir / "test.json"), eval_ood_count)
    return {
        "train_atom": train_groups.get(1, []),
        "train_2hop": m.group_by_hops(multihop[:train_twohop_count])[2],
        "test_id": id_groups[2],
        "test_ood": ood_groups[2],
    }


def build_graph(data_dir: Path):
    """adjacency (head, rel) -> tail, used to look up the ground-truth bridge."""
    adj = {}
    for x in m.load_json(data_dir / "train.json"):
        if len(x["target_text"]) != 3:
            continue
        h, r, t = x["target_text"]
        adj[(h, r)] = t
    return adj


# ---------------------------------------------------------------- model pieces
def encode(records, tokenizer, device):
    ids = torch.tensor(
        [[tokenizer.token_to_id[t] for t in r["input_text"]] for r in records],
        dtype=torch.long, device=device,
    )
    ans = torch.tensor([tokenizer.token_to_id[r["target_text"][-1]] for r in records],
                       dtype=torch.long, device=device)
    return ids, ans


@torch.no_grad()
def stage1_hidden(model, input_ids):
    """H(1): hidden states after the first loop (vanillaloop: plain f)."""
    h0, h, mask = model._prepare_inputs(input_ids, None)
    blocks, ln_f = model._stage_blocks(0)
    h1 = m._run_gpt2_blocks(h, mask, blocks, ln_f)
    return h1, mask


@torch.no_grad()
def stage2_logits(model, h1, mask):
    """Logits after the second loop, H(2) = f(H(1))."""
    blocks, ln_f = model._stage_blocks(1)
    h2 = m._run_gpt2_blocks(h1, mask, blocks, ln_f)
    return model.lm_head(h2)


def rms_normalize(e):
    return e / e.float().pow(2).mean(dim=-1, keepdim=True).sqrt().to(e.dtype)


def batched(n, bs=2048):
    for i in range(0, n, bs):
        yield slice(i, min(i + bs, n))


# ---------------------------------------------------------------- experiments
@torch.no_grad()
def baseline_and_lens(model, splits, tokenizer, adj, device):
    W = model.transformer.wte.weight
    print("\n=== Stage-wise accuracy (Table 1a) ===")
    print(f"{'split':12s} {'stage1':>8s} {'stage2':>8s}   n")
    results = {}
    h1_cache = {}
    for name, recs in splits.items():
        ids, ans = encode(recs, tokenizer, device)
        pos = ids.shape[1] - 1  # answer readout position (atoms: 1, twohop: 2)
        s1_hit = s2_hit = 0
        h1_parts = []
        for sl in batched(len(recs)):
            h1, mask = stage1_hidden(model, ids[sl])
            logits1 = model.lm_head(h1)
            logits2 = stage2_logits(model, h1, mask)
            s1_hit += (logits1[:, pos].argmax(-1) == ans[sl]).sum().item()
            s2_hit += (logits2[:, pos].argmax(-1) == ans[sl]).sum().item()
            h1_parts.append(h1)
        results[name] = {"stage1": s1_hit / len(recs), "stage2": s2_hit / len(recs)}
        h1_cache[name] = torch.cat(h1_parts)
        print(f"{name:12s} {results[name]['stage1']:8.4f} {results[name]['stage2']:8.4f}   {len(recs)}")

    print("\n=== Logit lens at position 1, post-first-loop (Table 1b) ===")
    print(f"{'split':12s} {'P(bridge)':>10s} {'cos(H1,W[b])':>13s}")
    lens = {}
    for name in ("test_id", "test_ood"):
        recs = splits[name]
        h1_1 = h1_cache[name][:, 1]
        bridge_ids = torch.tensor(
            [tokenizer.token_to_id[adj[(r["input_text"][0], r["input_text"][1])]] for r in recs],
            device=device,
        )
        probs = torch.softmax(model.lm_head(h1_1).float(), dim=-1)
        p_bridge = probs.gather(1, bridge_ids[:, None]).squeeze(1).mean().item()
        cos = F.cosine_similarity(h1_1.float(), W[bridge_ids].float(), dim=-1).mean().item()
        lens[name] = {"p_bridge": p_bridge, "cos": cos}
        print(f"{name:12s} {p_bridge:10.4f} {cos:13.4f}")
    return results, lens


@torch.no_grad()
def intervention_sweep(model, splits, tokenizer, device):
    """Eq. 3 intervention with the decoded bridge embedding, on test_id and test_ood."""
    W = model.transformer.wte.weight
    out = {}
    print("\n=== Intervention at position 1 between loops (Eq. 3): "
          "H1_1 <- (1-a)*H1_1 + a*Norm(W[b_max]) ===")
    for name in ("test_id", "test_ood"):
        recs = splits[name]
        ids, ans = encode(recs, tokenizer, device)
        pos = ids.shape[1] - 1
        h1_full, mask = stage1_hidden(model, ids)
        h1_1 = h1_full[:, 1]

        # b_max = argmax of the LM head at position 1
        dec_ids = model.lm_head(h1_1).argmax(-1)
        e = rms_normalize(W[dec_ids])

        print(f"\n[{name}]\n{'alpha':>6s} {'decoded_acc':>16s}")
        sweep = []
        for alpha in ALPHAS:
            h1_mod = h1_full.clone()
            h1_mod[:, 1] = (1 - alpha) * h1_1 + alpha * e
            pred = stage2_logits(model, h1_mod, mask)[:, pos].argmax(-1)
            row = {"alpha": alpha, "decoded_acc": (pred == ans).float().mean().item()}
            print(f"{alpha:6.2f} {row['decoded_acc']:16.4f}")
            sweep.append(row)
        out[name] = {"sweep": sweep}
    return out


def main():
    ap = argparse.ArgumentParser(description="Section 3.2 analysis (Table 1, Figure 2) of a vanilla looped model.")
    ap.add_argument("--run-dir", type=Path, required=True, help="training output dir (with stage2_hyper/hyper_model.pt)")
    ap.add_argument("--data-dir", type=Path, default=None, help="dataset dir (default: the run's --data-dir)")
    ap.add_argument("--device", type=str, default="cuda:0")
    ap.add_argument("--out", type=Path, default=None, help="output json (default: <run-dir>/interp_section3.json)")
    args = ap.parse_args()

    device = torch.device(args.device)
    ckpt = torch.load(args.run_dir / "stage2_hyper" / "hyper_model.pt", map_location="cpu", weights_only=False)
    saved = ckpt["args"]
    data_dir = args.data_dir or Path(saved["data_dir"])
    model, tokenizer = load_model(ckpt, data_dir, device)
    splits = rebuild_splits(
        data_dir, saved["seed"], saved.get("train_twohop_count", -1),
        saved.get("eval_id_count", 2000), saved.get("eval_ood_count", 2000),
    )
    adj = build_graph(data_dir)
    print(f"model: {args.run_dir.name}\nsplits: " + "  ".join(f"{k}={len(v)}" for k, v in splits.items()))

    ref = args.run_dir / "stage2_hyper" / "final_metrics.json"
    if ref.exists():
        rm = json.loads(ref.read_text())
        # split names test_2hop_* (test_twohop_* in some earlier runs)
        id_s2, ood_s2 = (
            rm.get(f"test_2hop_{s}_stage2_acc", rm.get(f"test_twohop_{s}_stage2_acc")) for s in ("id", "ood")
        )
        if id_s2 is not None and ood_s2 is not None:
            print(f"reference final_metrics: id_s2={id_s2:.4f} ood_s2={ood_s2:.4f}")

    baseline, lens = baseline_and_lens(model, splits, tokenizer, adj, device)
    sweep = intervention_sweep(model, splits, tokenizer, device)

    out_path = args.out or (args.run_dir / "interp_section3.json")
    out_path.write_text(json.dumps({
        "run": args.run_dir.name,
        "baseline": baseline, "logit_lens": lens, "intervention": sweep,
    }, indent=2))
    print(f"\nresults written to {out_path}")


if __name__ == "__main__":
    main()