"""Interpretability experiments for the rebuttal (paper Section 3). Given a trained looped model checkpoint (stage2_hyper/hyper_model.pt), this script reproduces and extends the Section-3 analysis: 1. Baseline: stage-1 / stage-2 accuracy on train_atom / train_2hop / test_id / test_ood (cross-checked against the run's final_metrics.json), plus the logit-lens table: P(bridge | H1_pos1) and cos(H1_pos1, W[bridge]). 2. Paper intervention (Eq. 3): between the two loops, at position 1 only, H1_1 <- (1-alpha) * H1_1 + alpha * Norm(W[argmax decode]), sweeping alpha. 3. Reviewer control (a): same intervention but injecting a norm-matched WRONG entity embedding (random entity of the same graph that has relation r2, != bridge). Reports accuracy of the true answer c AND of the "hijacked" answer c' = a2 --r2--> tail. Also a norm-matched Gaussian control, and the norms of the original hidden state / injected embeddings. 4. Reviewer probe (b): position-wise logit-lens decoding of the two-hop answer at every non-answer position, and a 1-hidden-layer ReLU probe trained on concatenated post-first-loop hidden states (3d -> d), read out through the frozen tied embedding. Trained on train_2hop only, tested on all splits. Usage: python interp_intervention.py --run-dir outputs/hyper_run....seed14 [--device cuda:0] """ import argparse import json import random import types from pathlib import Path import numpy as np import torch import torch.nn as nn 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] PROBE_STEPS = 1000 PROBE_BS = 256 PROBE_LR = 1e-3 # --------------------------------------------------------------------------- io def load_model(run_dir: Path, device): ckpt = torch.load(run_dir / "stage2_hyper" / "hyper_model.pt", map_location="cpu", weights_only=False) saved = ckpt["args"] hc = ckpt["hyper_config"] args_ns = types.SimpleNamespace( model_name=saved["model_name"], from_scratch=True, trust_remote_code=False, use_small_tokenizer=True, create_special_token=True, data_dir=Path(saved["data_dir"]), init_one_hot=0, freeze_embeddings=0, ) tokenizer = m.build_tokenizer(args_ns) base = m.build_base_model(args_ns, tokenizer) model = m.HyperConnectionGPT2LM( base_model=base, num_stages=hc["num_stages"], architecture=hc["architecture"], gate_mode=hc["gate_mode"], fixed_alpha=hc["fixed_alpha"], fixed_beta=hc["fixed_beta"], norm_type=saved.get("norm_type", "rms"), zero_final_gate=hc["zero_final_gate"], sg_phi=hc["sg_phi"], use_position_embeddings=hc["use_position_embeddings"], loop_scheme=hc.get("loop_scheme", "vanillaloop"), ) missing, unexpected = model.load_state_dict(ckpt["state_dict"], strict=False) assert not missing and not unexpected, f"state dict mismatch: {missing} {unexpected}" return model.eval().to(device), tokenizer, saved def rebuild_splits(data_dir: Path, seed: int, train_twohop_count: int, eval_id: int, eval_ood: int): """Exact replication of the sampling in train_twin_hyper.main (same rng order).""" train_data = json.loads((data_dir / "train.json").read_text()) test_data = json.loads((data_dir / "test.json").read_text()) groups = m.group_by_hops(train_data) atoms = groups.get(1, []) rng = random.Random(seed) multihop = [item for hops in sorted(groups) if hops > 1 for item in groups[hops]] rng.shuffle(multihop) kept = multihop[:train_twohop_count] id_pool = multihop[train_twohop_count:] test_id = rng.sample(id_pool, eval_id) if 0 <= eval_id < len(id_pool) else id_pool ood_pool = m.group_by_hops(test_data).get(2, []) test_ood = rng.sample(ood_pool, eval_ood) if 0 <= eval_ood < len(ood_pool) else ood_pool return {"train_atom": atoms, "train_2hop": kept, "test_id": test_id, "test_ood": test_ood} def build_graph(data_dir: Path): """adjacency (head, rel) -> tail and per-graph relation -> entities index.""" train_data = json.loads((data_dir / "train.json").read_text()) adj, rel_ents = {}, {"a": {}, "b": {}} for x in train_data: if len(x["target_text"]) != 3: continue h, r, t = x["target_text"] adj[(h, r)] = t rel_ents[h[1]].setdefault(r, []).append(h) return adj, rel_ents # ---------------------------------------------------------------- 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): 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=== 1. Baseline stage-wise accuracy (reproduction of 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 (reproduction of Table 1b) ===") print(f"{'split':12s} {'P(bridge)':>10s} {'cos(H1,W[b])':>13s} {'P@top1==b':>10s}") lens = {} for name in ("test_id", "test_ood", "train_2hop"): 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() top1_is_b = (probs.argmax(-1) == bridge_ids).float().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, "top1_is_bridge": top1_is_b} print(f"{name:12s} {p_bridge:10.4f} {cos:13.4f} {top1_is_b:10.4f}") return results, lens, h1_cache @torch.no_grad() def intervention_sweep(model, splits, tokenizer, adj, rel_ents, device, seed=0): """Paper intervention + reviewer controls, on test_id and test_ood.""" W = model.transformer.wte.weight d = W.shape[1] rng = random.Random(seed) out = {} print("\n=== 2/3. Intervention at position 1 between loops: " "H1_1 <- (1-a)*H1_1 + a*Norm(e) ===") 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] # decoded (paper): argmax of LM head at position 1 dec_ids = model.lm_head(h1_1).argmax(-1) e_dec = W[dec_ids] # random wrong entity of the same graph that HAS relation r2 (so the # hijacked answer a2 --r2--> c' exists); norm-matched via the same Norm. a2_tokens, alt_ans = [], [] for r in recs: a1, r1, r2 = r["input_text"] bridge = adj[(a1, r1)] cands = [e for e in rel_ents[a1[1]][r2] if e != bridge] a2 = rng.choice(cands) a2_tokens.append(a2) alt_ans.append(tokenizer.token_to_id[adj[(a2, r2)]]) a2_ids = torch.tensor([tokenizer.token_to_id[t] for t in a2_tokens], device=device) alt_ans = torch.tensor(alt_ans, device=device) e_rand_ent = W[a2_ids] # norm-matched gaussian control g = torch.Generator(device="cpu").manual_seed(seed) e_gauss = torch.randn(len(recs), d, generator=g).to(device=device, dtype=W.dtype) norms = { "hidden_H1_pos1": h1_1.float().norm(dim=-1).mean().item(), "W[decoded] raw": e_dec.float().norm(dim=-1).mean().item(), "Norm(W[decoded])": rms_normalize(e_dec).float().norm(dim=-1).mean().item(), "W[rand entity] raw": e_rand_ent.float().norm(dim=-1).mean().item(), "Norm(W[rand entity])": rms_normalize(e_rand_ent).float().norm(dim=-1).mean().item(), "Norm(gaussian)": rms_normalize(e_gauss).float().norm(dim=-1).mean().item(), } print(f"\n[{name}] norms (L2, mean over samples): " + " ".join(f"{k}={v:.2f}" for k, v in norms.items())) variants = { "decoded": (rms_normalize(e_dec), None), "rand_entity": (rms_normalize(e_rand_ent), alt_ans), "gaussian": (rms_normalize(e_gauss), None), } res = {"norms": norms} header = f"{'alpha':>6s}" + "".join(f" {v+'_acc':>16s}" for v in variants) header += f" {'rand_ent_hijack':>16s}" print(header) for alpha in ALPHAS: row = {"alpha": alpha} for vname, (e, alt) in variants.items(): 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[f"{vname}_acc"] = (pred == ans).float().mean().item() if alt is not None: row["rand_entity_hijack"] = (pred == alt).float().mean().item() print(f"{alpha:6.2f}" + "".join(f" {row[f'{v}_acc']:16.4f}" for v in variants) + f" {row['rand_entity_hijack']:16.4f}") res.setdefault("sweep", []).append(row) out[name] = res return out @torch.no_grad() def positionwise_decode(model, splits, tokenizer, adj, h1_cache, device): """(b1) logit-lens decode of the two-hop ANSWER at each non-answer position.""" print("\n=== 4a. Position-wise logit-lens after loop 1 " "(answer position excluded: answer token is not in the input) ===") print(f"{'split':12s} {'pos':>4s} {'top1==answer':>13s} {'top1==bridge':>13s}") out = {} for name in ("train_2hop", "test_id", "test_ood"): recs = splits[name] _, ans = encode(recs, tokenizer, device) bridge_ids = torch.tensor( [tokenizer.token_to_id[adj[(r["input_text"][0], r["input_text"][1])]] for r in recs], device=device, ) h1 = h1_cache[name] out[name] = {} for pos in range(h1.shape[1]): # positions 0,1,2 == a1, r1, r2 top1 = model.lm_head(h1[:, pos]).argmax(-1) acc_ans = (top1 == ans).float().mean().item() acc_bridge = (top1 == bridge_ids).float().mean().item() out[name][f"pos{pos}"] = {"answer": acc_ans, "bridge": acc_bridge} print(f"{name:12s} {pos:4d} {acc_ans:13.4f} {acc_bridge:13.4f}") return out def nonlinear_probe(model, splits, tokenizer, h1_cache, device, seed=0): """(b2) 1-hidden-layer ReLU probe: concat(H1_0,H1_1,H1_2) -> d, read out through the frozen tied embedding; trained on train_2hop only.""" torch.manual_seed(seed) W = model.transformer.wte.weight.detach().float() d = W.shape[1] feats, answers = {}, {} for name in ("train_2hop", "test_id", "test_ood"): h1 = h1_cache[name] feats[name] = h1.reshape(h1.shape[0], -1).float() # (n, 3d) _, answers[name] = encode(splits[name], tokenizer, device) probe = nn.Sequential(nn.Linear(3 * d, d), nn.ReLU(), nn.Linear(d, d)).to(device) opt = torch.optim.Adam(probe.parameters(), lr=PROBE_LR) x, y = feats["train_2hop"], answers["train_2hop"] n = x.shape[0] print(f"\n=== 4b. Nonlinear probe (Linear(3d,d)+ReLU+Linear(d,d), logits via frozen W^T), " f"{PROBE_STEPS} steps on train_2hop only ===") for step in range(PROBE_STEPS): idx = torch.randint(0, n, (PROBE_BS,), device=device) logits = probe(x[idx]) @ W.T loss = F.cross_entropy(logits, y[idx]) opt.zero_grad(); loss.backward(); opt.step() if (step + 1) % 200 == 0: print(f" step {step+1:4d} loss {loss.item():.4f}") probe.eval() out = {} with torch.no_grad(): for name in feats: pred = (probe(feats[name]) @ W.T).argmax(-1) out[name] = (pred == answers[name]).float().mean().item() print(f"probe accuracy: " + " ".join(f"{k}={v:.4f}" for k, v in out.items())) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--run-dir", type=Path, required=True) ap.add_argument("--device", type=str, default="cuda:0") ap.add_argument("--out", type=Path, default=None, help="output json (default: /interp_rebuttal.json)") args = ap.parse_args() device = torch.device(args.device) model, tokenizer, saved = load_model(args.run_dir, device) data_dir = Path(saved["data_dir"]) splits = rebuild_splits( data_dir, saved["seed"], saved["train_twohop_count"], saved.get("eval_id_count", 2000), saved.get("eval_ood_count", 2000), ) adj, rel_ents = 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()) print("reference final_metrics: " f"id_s2={rm.get('test_twohop_id_stage2_acc', rm.get('test_2hop_id_stage2_acc')):.4f} " f"ood_s2={rm.get('test_twohop_ood_stage2_acc', rm.get('test_2hop_ood_stage2_acc')):.4f}") baseline, lens, h1_cache = baseline_and_lens(model, splits, tokenizer, adj, device) sweep = intervention_sweep(model, splits, tokenizer, adj, rel_ents, device) posdec = positionwise_decode(model, splits, tokenizer, adj, h1_cache, device) probe = nonlinear_probe(model, splits, tokenizer, h1_cache, device) out_path = args.out or (args.run_dir / "interp_rebuttal.json") out_path.write_text(json.dumps({ "run": args.run_dir.name, "baseline": baseline, "logit_lens": lens, "intervention": sweep, "positionwise_decode": posdec, "nonlinear_probe": probe, }, indent=2)) print(f"\nresults written to {out_path}") if __name__ == "__main__": main()