File size: 1,731 Bytes
e9ff27f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Check the symmetry action really preserves the function, and that fit_g recovers it."""
import numpy as np, torch, ma_common as C, gmap
from mergeschool.core import alignment as AL
m = C.load_model("EleutherAI/pythia-1.4b","step143000",dev="cuda",dtype=torch.float32)
tk = C.load_tok("EleutherAI/pythia-1.4b","step143000")
sd = C.sd_np(m); HID, NH = m.config.hidden_size, m.config.num_attention_heads
x = tk("The capital city of France is called", return_tensors="pt").input_ids.cuda()
with torch.no_grad(): l0 = m(x).logits.float().cpu().numpy()
rng = np.random.default_rng(0)
axes = AL.free_hidden_axes(sd, HID)
print("free hidden axes:", len(axes), "width", (list(axes.values())[0]["f"] if axes else None), flush=True)
hp = {p: rng.permutation(a["f"]) for p,a in axes.items()}
sd2 = AL.apply_hidden_perms(sd, hp, HID)
pres = sorted({p for p in (AL._layer_prefix(n) for n in sd) if p})
ap = {p: rng.permutation(NH) for p in pres}
sd3 = AL.apply_head_perms(sd2, ap, HID, NH)
for tag, s in (("hidden-only", sd2), ("hidden+heads", sd3)):
    C.sd_load(m, s)
    with torch.no_grad(): l1 = m(x).logits.float().cpu().numpy()
    print(tag, "max|dlogit|=%.3e"%np.abs(l0-l1).max(), "rel=%.3e"%(np.abs(l0-l1).max()/np.abs(l0).max()), flush=True)
g, info = gmap.fit_g(sd, sd3, HID, NH, None, None, verbose=False)
print("recover: coord_share=%.4f identity=%s hidden=%d heads=%d bnd %.4f -> %.4f"%(
    info["coord_share_bn"], info["is_identity"], info["hidden"], info["heads"], info["bnd_raw"], info["bnd_final"]), flush=True)
back = gmap.apply_g(sd3, g, HID, NH)
d = max(float(np.abs(np.asarray(back[k])-sd[k]).max()) for k in sd if k in back)
print("max|g(sd_perm) - sd_orig| = %.3e"%d, flush=True)
print("VALIDATE_DONE", flush=True)