File size: 6,422 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
140
141
142
143
144
"""Why does an embedding-only recurrence fail? (Reviewer i9hy, Q2)

Hypothesis: on a two-hop query <a> <r1> <r2>, the LM head at position 2 decodes an
ENTITY (that is what the model is trained to emit), so a recurrence that replaces the
residual stream with the decoded embedding overwrites the token that says WHICH relation
the second hop should apply. The second loop then knows the bridge entity but no longer
knows r2. Keeping the continuous state alongside the discrete one preserves it.

For each trained model we measure, at position 2 (the r2 slot) of the state that is fed
INTO loop 2:
  (a) what the LM head decodes there (relation vs entity), and
  (b) how recoverable r2 itself is, via a linear probe trained on train two-hop
      questions and evaluated on held-out ID / OOD questions.

Usage:
  python probe_relation_survival.py --batch-dir outputs --tag 20260724_184654
"""
import argparse
import json
import types
from pathlib import Path

import torch
import torch.nn.functional as F

import train_twin_hyper as m

SCHEMES = [
    ("DiscoLoop (two-channel)", "discoloop", "alpha1_beta0"),
    ("DiscoLoop (a=.5,b=.5)", "discoloop", "alpha0.5_beta0.5"),
    ("PonderLM_input (H + soft emb)", "ponderlm_input", "alpha0.5_beta0.5"),
    ("PonderLM (soft emb only)", "ponderlm", "alpha0.5_beta0.5"),
    ("Argmax (hard emb only)", "argmax", "alpha0.5_beta0.5"),
    ("Vanilla loop (continuous only)", "vanillaloop", "alpha0.5_beta0.5"),
]


def find_run(root: Path, tag: str, scheme: str, ab: str):
    for d in sorted(root.glob(f"hyper_run.twin_twohop_truood_diff.500.50.10.{tag}.looping.{scheme}.*")):
        if f".{ab}." in d.name and (d / "stage2_hyper" / "hyper_model.pt").exists():
            return d
    return None


@torch.no_grad()
def stage1_state(model, ids):
    """Hidden state that is fed INTO loop 2 (i.e. after the scheme's stage-0 update)."""
    h0, h, mask = model._prepare_inputs(ids, None)
    _, hidden, _ = model._run_stages(h0, h, mask, return_stage_hidden=True)
    return hidden[0], mask


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--batch-dir", type=Path, default=Path("outputs"))
    ap.add_argument("--tag", type=str, default="20260724_184654")
    ap.add_argument("--data", type=Path, default=Path("data/twin_twohop_truood_diff.500.50.10"))
    ap.add_argument("--device", type=str, default="cuda")
    ap.add_argument("--probe-steps", type=int, default=400)
    args = ap.parse_args()

    dev = torch.device(args.device)
    ns_args = types.SimpleNamespace(
        model_name="gpt2-big", from_scratch=True, trust_remote_code=False,
        use_small_tokenizer=True, create_special_token=True, tokenizer_name=None,
        data_dir=args.data, init_one_hot=0, freeze_embeddings=0,
    )
    tok = m.build_tokenizer(ns_args)
    is_rel = lambda t: t.startswith("<r_")

    # same splits the runs were trained/evaluated on
    train_data = json.loads((args.data / "train.json").read_text())
    groups = m.group_by_hops(train_data)
    rng_seed = 14
    import random
    rng = random.Random(rng_seed)
    multihop = [x for h in sorted(groups) if h > 1 for x in groups[h]]
    rng.shuffle(multihop)
    train_2hop, id_pool = multihop[:10000], multihop[10000:]
    test_id = rng.sample(id_pool, 2000)
    ood_pool = m.group_by_hops(json.loads((args.data / "test.json").read_text())).get(2, [])
    test_ood = rng.sample(ood_pool, 2000)

    def encode(recs):
        ids = torch.tensor([[tok.token_to_id[t] for t in r["input_text"]] for r in recs], device=dev)
        r2 = torch.tensor([tok.token_to_id[r["input_text"][2]] for r in recs], device=dev)
        return ids, r2

    sets = {k: encode(v) for k, v in [("train", train_2hop), ("id", test_id), ("ood", test_ood)]}

    print(f"probing position 2 (the r2 slot) of the state entering loop 2\n")
    print(f"{'model':32s} {'top1=r2':>8s} {'cos(state,W[r2])':>17s} {'probe r2 train/ID/OOD':>26s}")
    for label, scheme, ab in SCHEMES:
        run = find_run(args.batch_dir, args.tag, scheme, ab)
        if run is None:
            print(f"{label:32s} {'(run not found)':>26s}")
            continue
        blob = torch.load(run / "stage2_hyper" / "hyper_model.pt", map_location="cpu", weights_only=False)
        hc = blob["hyper_config"]
        base = m.build_base_model(ns_args, tok)
        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="rms", zero_final_gate=hc["zero_final_gate"], sg_phi=hc["sg_phi"],
            use_position_embeddings=hc["use_position_embeddings"], loop_scheme=hc["loop_scheme"],
        )
        model.load_state_dict(blob["state_dict"], strict=False)
        model = model.eval().to(dev)

        feats, labels = {}, {}
        for k, (ids, r2) in sets.items():
            hs, _ = stage1_state(model, ids)
            feats[k] = hs[:, 2].float()
            labels[k] = r2

        # (a) what does the LM head decode at position 2, and how aligned is the state
        #     with the CLEAN embedding of r2 that the next loop was trained to consume?
        with torch.no_grad():
            top1 = model.lm_head(feats["id"].to(model.lm_head.weight.dtype)).argmax(-1)
            W = model.transformer.wte.weight.float()
            cos = float(F.cosine_similarity(feats["id"], W[labels["id"]], dim=-1).mean())
        frac_exact = float((top1 == labels["id"]).float().mean())

        # (b) linear probe: does the state still identify r2?
        d = feats["train"].shape[1]
        probe = torch.nn.Linear(d, len(tok)).to(dev)
        opt = torch.optim.Adam(probe.parameters(), lr=1e-3)
        x, y = feats["train"], labels["train"]
        torch.manual_seed(0)
        for _ in range(args.probe_steps):
            idx = torch.randint(0, x.shape[0], (512,), device=dev)
            loss = F.cross_entropy(probe(x[idx]), y[idx])
            opt.zero_grad(); loss.backward(); opt.step()
        with torch.no_grad():
            accs = [float((probe(feats[k]).argmax(-1) == labels[k]).float().mean()) for k in ("train", "id", "ood")]
        print(f"{label:32s} {frac_exact:8.3f} {cos:17.3f} "
              f"{accs[0]:8.3f} {accs[1]:8.3f} {accs[2]:8.3f}")
        del model, probe, opt
        torch.cuda.empty_cache()


if __name__ == "__main__":
    main()