File size: 6,589 Bytes
0b21f71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Structured fake-data test of fuse.py (local, CPU, tiny model). Known answers:
  sub-mean k of category c: S_k = a_c * P + small noise, with P a fixed rank-1 matrix (per 2-D tensor) and a_loop = 3,
  others 1 -> loop - nonloop = 2 P (+ noise): its top singular direction must match P (|cos| ~ 1), and top1 energy ~ 1.
  Checks: Gram == exact inner products; fused loop / nonloop finals == base + exact weighted means; norm check passes.
"""
import os, sys, json, shutil, types, random, subprocess
from pathlib import Path
import torch
from safetensors.torch import save_file, load_file

T = Path(os.environ.get("TDIR", "/tmp/fuse_test"))
shutil.rmtree(T, ignore_errors=True)
(T / "code" / "meta").mkdir(parents=True)
shutil.copy(Path(__file__).parents[1] / "fuse.py", T / "code" / "fuse.py")
torch.manual_seed(0)
V, Hd, I, L = 151646, 64, 96, 2
shapes = {"model.embed_tokens.weight": (V, Hd), "model.norm.weight": (Hd,), "lm_head.weight": (V, Hd)}
for l in range(L):
    p = f"model.layers.{l}."
    shapes.update({p + "self_attn.q_proj.weight": (Hd, Hd), p + "self_attn.q_proj.bias": (Hd,),
                   p + "self_attn.o_proj.weight": (Hd, Hd), p + "mlp.down_proj.weight": (Hd, I),
                   p + "mlp.up_proj.weight": (I, Hd), p + "input_layernorm.weight": (Hd,)})
unit = lambda n: (f"L{int(n.split('.')[2]):02d}" if n.startswith("model.layers.") else
                  {"model.embed_tokens.weight": "embed", "model.norm.weight": "norm", "lm_head.weight": "lm_head"}[n])
base = {n: torch.randn(s) * 0.02 for n, s in shapes.items()}
bdir = T / "base"; bdir.mkdir()
files = {}
for n in shapes: files.setdefault(unit(n), []).append(n)
wm = {}
for u, ns in files.items():
    save_file({n: base[n].bfloat16() for n in ns}, str(bdir / f"b-{u}.safetensors")); wm.update({n: f"b-{u}.safetensors" for n in ns})
json.dump({"weight_map": wm}, open(bdir / "model.safetensors.index.json", "w"))
json.dump({"model_type": "qwen2"}, open(bdir / "config.json", "w"))
cats = ["loop"] * 4 + ["gibberish"] * 2 + ["short"] * 2 + ["degraded"] * 2 + ["healthy"] * 4
groups, hub = [], T / "hub"
Pm = {n: (torch.randn(s[0], 1) @ torch.randn(1, s[1])) * 1e-3 for n, s in shapes.items() if len(s) == 2}
S = {}
for k, c in enumerate(cats):
    g = dict(name=f"{c}_g{k:02d}", category=c, members=[f"x/{c}{k}_{j}" for j in range(k % 3 + 2)])
    g["n"] = len(g["members"]); groups.append(g)
    a = 3.0 if c == "loop" else 1.0
    d = {}
    for n, s in shapes.items():
        v = (a * Pm[n] if n in Pm else torch.zeros(s)) + torch.randn(s) * 1e-5
        d[n] = v.bfloat16()                                   # stored as bf16, like stage 1
    S[g["name"]] = {n: v.float() for n, v in d.items()}
    gd = hub / g["name"] / "deltas"; gd.mkdir(parents=True)
    for u, ns in files.items():
        save_file({n: d[n] for n in ns}, str(gd / f"{u}.safetensors"))
    json.dump(dict(n=g["n"], members=g["members"], mean_norm={n: S[g["name"]][n].norm().item() for n in shapes},
                   bf16_rel_rounding_error={n: 0.0 for n in shapes}), open(hub / g["name"] / "manifest.json", "w"))
json.dump({"groups": groups}, open(T / "code" / "meta" / "groups.json", "w"))
# stubs for huggingface_hub and transformers
stub = T / "stubs"; (stub / "huggingface_hub").mkdir(parents=True); (stub / "transformers").mkdir()
(stub / "huggingface_hub" / "__init__.py").write_text(f'''
import os
HUB, BASE = {str(hub)!r}, {str(bdir)!r}
class HfApi:
    def __init__(self, **k): pass
    def upload_folder(self, **k): raise RuntimeError("no uploads in test")
def hf_hub_download(repo, filename, token=None, local_dir=None): return os.path.join(HUB, filename)
def snapshot_download(repo, **k): return BASE
''')
(stub / "transformers" / "__init__.py").write_text('''
class _T:
    def decode(self, ids): return "t%d" % ids[0]
class AutoTokenizer:
    @staticmethod
    def from_pretrained(p): return _T()
''')
env = dict(os.environ, HF_TOKEN="x", WORK=str(T / "work"), THREADS="1", NOUPLOAD="1", CHUNK="100000",
           PYTHONPATH=str(stub))
r = subprocess.run([sys.executable, str(T / "code" / "fuse.py")], env=env, capture_output=True, text=True)
print(r.stdout[-3000:]); print(r.stderr[-3000:] if r.returncode else "")
assert r.returncode == 0, "fuse.py failed"
W = T / "work"
from safetensors import safe_open
f = safe_open(str(W / "analysis" / "gram.safetensors"), "pt")
meta = f.metadata(); gram = f.get_tensor("gram"); tn = json.loads(meta["tensors"]); subs = json.loads(meta["subs"])
ok = True
for i, n in enumerate(tn):
    X = torch.stack([S[s][n].reshape(-1).double() for s in subs])
    err = (gram[i] - X @ X.T).abs().max().item() / (X @ X.T).abs().max().item()
    ok &= err < 1e-9
print("gram max rel err", max((gram[i] - torch.stack([S[s][n].reshape(-1).double() for s in subs]) @ torch.stack([S[s][n].reshape(-1).double() for s in subs]).T).abs().max().item() for i, n in enumerate(tn)))
nk = {g["name"]: g["n"] for g in groups}; cg = {g["name"]: g["category"] for g in groups}
def wmean(cs, n):
    tot = sum(nk[s] for s in subs if cg[s] in cs)
    return sum(nk[s] * S[s][n].double() for s in subs if cg[s] in cs) / tot
fl = {}
for u in files:
    fl.update(load_file(str(W / "final" / "loop_mean" / f"{u}.safetensors")))
fn = {}
for u in files:
    fn.update(load_file(str(W / "final" / "nonloop_mean" / f"{u}.safetensors")))
e1 = max((fl[n].double() - (base[n].bfloat16().double() + wmean(["loop"], n))).abs().max().item() for n in shapes)
e2 = max((fn[n].double() - (base[n].bfloat16().double() + wmean(["gibberish", "short", "degraded", "healthy"], n))).abs().max().item() for n in shapes)
print("final loop max abs err", e1, "nonloop", e2, "dtype", fl["lm_head.weight"].dtype)
ok &= e1 < 1e-6 and e2 < 1e-6
sp = json.load(open(W / "analysis" / "spectra.json"))
sv = load_file(str(W / "analysis" / "svd_loop-nonloop.safetensors"))
for n in Pm:
    if not n.startswith("model.layers."): continue
    u = sv[n + ".U8"][:, 0]; p = Pm[n][:, 0] / Pm[n][:, 0].norm()
    c = abs(torch.dot(u, p)).item()
    t1 = sp["loop-nonloop"][n]["top1"]
    print(f"{n}: |cos(U1, P)| {c:.4f} top1 {t1:.3f} pr {sp['loop-nonloop'][n]['pr_rank']:.2f} noise-ctrl top1 {sp['ctrl_loop_noise'][n]['top1']:.2f} fro {sp['ctrl_loop_noise'][n]['fro']:.2e} vs {sp['loop-nonloop'][n]['fro']:.2e}")
    ok &= c > 0.999 and t1 > 0.99
    if "o_proj" in n or "down_proj" in n:
        ok &= "lens_u1" in sp["loop-nonloop"][n] and "eos_write" in sp["loop-nonloop"][n]
rows = json.load(open(W / "analysis" / "rows.json"))
print("rows keys", list(rows), list(rows["lm_head.weight"])[:3])
print("TEST", "PASS" if ok else "FAIL")