Repository navigation
Expand file tree
/
Copy pathverify.py
More file actions
93 lines (70 loc) · 3.26 KB
/
Copy pathverify.py
File metadata and controls
93 lines (70 loc) · 3.26 KB
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
#!/usr/bin/env python3
"""Recompute every headline number from saved outputs and check it against the paper.
Run from the repo root (expects results/*.json and results/acts_qwen7b_inst.pkl): python verify.py
Dependencies: numpy, torch (torch only to load the saved activation tensors).
"""
import os, json, pickle
import numpy as np
OUT = "results"
L = 14 # pre-registered read layer
def load(name):
return json.load(open(os.path.join(OUT, name)))
def cohens_d(x, y):
x = np.asarray(x, float); y = np.asarray(y, float)
sp = np.sqrt(((len(x) - 1) * x.var(ddof=1) + (len(y) - 1) * y.var(ddof=1))
/ (len(x) + len(y) - 2) + 1e-12)
return float((x.mean() - y.mean()) / sp)
def direction(P, N):
raw = P.mean(0) - N.mean(0)
return raw / (raw.norm() + 1e-8)
def proj(A, u):
return (A @ u).tolist()
def project_out(A, u):
u = u / (u.norm() + 1e-8)
return A - (A @ u).unsqueeze(1) * u.unsqueeze(0)
def heldout_d(AF, AD, seed=0):
n = AF.shape[0]; rng = np.random.default_rng(seed); idx = rng.permutation(n)
tr, te = idx[:n // 2], idx[n // 2:]
u = direction(AF[tr], AD[tr])
return cohens_d(proj(AF[te], u), proj(AD[te], u))
def check(name, got, exp, tol=0.02):
ok = abs(got - exp) <= tol
print(f" [{'PASS' if ok else 'FAIL'}] {name}: recomputed {got:.3f} vs paper {exp:.3f}")
return ok
def main():
import torch # noqa: F401 (needed to unpickle saved tensors)
print("== Re-derive headline numbers from RAW activations (independent of the JSONs) ==")
a = pickle.load(open(os.path.join(OUT, "acts_qwen7b_inst.pkl"), "rb"))
AF, AD = a["fl_2"][L], a["di_2"][L]
u = direction(AF, AD)
SP, SN = a["sent_pos"][L], a["sent_neg"][L]
us = direction(SP, SN)
ok = []
ok.append(check("separation held-out d", heldout_d(AF, AD), 9.67))
ok.append(check("sentiment-residual d", heldout_d(project_out(AF, us), project_out(AD, us)), 8.80))
cos = float((u @ us) / (u.norm() * us.norm()))
ok.append(check("cos(valence,sentiment)", cos, 0.57, tol=0.03))
print("\n== Cross-check the logged confirmatory file ==")
c = load("p3_03_confirm.json")["headline"]
ok.append(check("logged held-out d", c["cohens_d_heldout"], 9.67))
ok.append(check("logged cluster-CI low", c["cluster_boot_ci95"][0], 7.23, tol=0.1))
print("\n== 12-model generality (p35_fullbattery.json) ==")
fb = load("p35_fullbattery.json")
models = [k for k in fb if "error" not in fb[k]]
ds = [fb[m]["heldout_d"] for m in models]
caus = sum(1 for m in models if fb[m].get("causal_beats_all"))
aro_ok = sum(1 for m in models if fb[m]["arousal_auroc"] < 0.5)
print(f" models: {len(models)} | d range {min(ds):.1f}-{max(ds):.1f} "
f"| causal beats-all: {caus}/{len(models)} | arousal<0.5: {aro_ok}/{len(models)}")
ok.append(len(models) == 12)
ok.append(caus >= 11)
print("\n== External validation (p35_external.json) ==")
ext = load("p35_external.json")
for ds_name in ("emotion_twitter", "go_emotions_reddit"):
au = ext[ds_name]["our_probe_auroc"]
print(f" {ds_name}: probe AUROC {au:.3f}")
ok.append(au > 0.8)
print("\n" + "=" * 50)
print("ALL CHECKS PASSED" if all(ok) else "SOME CHECKS FAILED (see above)")
if __name__ == "__main__":
main()