Upload code/validate_symmetry.py with huggingface_hub
Browse files- code/validate_symmetry.py +27 -0
code/validate_symmetry.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Check the symmetry action really preserves the function, and that fit_g recovers it."""
|
| 2 |
+
import numpy as np, torch, ma_common as C, gmap
|
| 3 |
+
from mergeschool.core import alignment as AL
|
| 4 |
+
m = C.load_model("EleutherAI/pythia-1.4b","step143000",dev="cuda",dtype=torch.float32)
|
| 5 |
+
tk = C.load_tok("EleutherAI/pythia-1.4b","step143000")
|
| 6 |
+
sd = C.sd_np(m); HID, NH = m.config.hidden_size, m.config.num_attention_heads
|
| 7 |
+
x = tk("The capital city of France is called", return_tensors="pt").input_ids.cuda()
|
| 8 |
+
with torch.no_grad(): l0 = m(x).logits.float().cpu().numpy()
|
| 9 |
+
rng = np.random.default_rng(0)
|
| 10 |
+
axes = AL.free_hidden_axes(sd, HID)
|
| 11 |
+
print("free hidden axes:", len(axes), "width", (list(axes.values())[0]["f"] if axes else None), flush=True)
|
| 12 |
+
hp = {p: rng.permutation(a["f"]) for p,a in axes.items()}
|
| 13 |
+
sd2 = AL.apply_hidden_perms(sd, hp, HID)
|
| 14 |
+
pres = sorted({p for p in (AL._layer_prefix(n) for n in sd) if p})
|
| 15 |
+
ap = {p: rng.permutation(NH) for p in pres}
|
| 16 |
+
sd3 = AL.apply_head_perms(sd2, ap, HID, NH)
|
| 17 |
+
for tag, s in (("hidden-only", sd2), ("hidden+heads", sd3)):
|
| 18 |
+
C.sd_load(m, s)
|
| 19 |
+
with torch.no_grad(): l1 = m(x).logits.float().cpu().numpy()
|
| 20 |
+
print(tag, "max|dlogit|=%.3e"%np.abs(l0-l1).max(), "rel=%.3e"%(np.abs(l0-l1).max()/np.abs(l0).max()), flush=True)
|
| 21 |
+
g, info = gmap.fit_g(sd, sd3, HID, NH, None, None, verbose=False)
|
| 22 |
+
print("recover: coord_share=%.4f identity=%s hidden=%d heads=%d bnd %.4f -> %.4f"%(
|
| 23 |
+
info["coord_share_bn"], info["is_identity"], info["hidden"], info["heads"], info["bnd_raw"], info["bnd_final"]), flush=True)
|
| 24 |
+
back = gmap.apply_g(sd3, g, HID, NH)
|
| 25 |
+
d = max(float(np.abs(np.asarray(back[k])-sd[k]).max()) for k in sd if k in back)
|
| 26 |
+
print("max|g(sd_perm) - sd_orig| = %.3e"%d, flush=True)
|
| 27 |
+
print("VALIDATE_DONE", flush=True)
|