exp2-means / code /fuse.py
mild-rgb's picture
fuse.py (stage 2) + fake-data test
0b21f71 verified
Raw History Blame Contribute Delete
17.6 kB
"""Stage 2: fuse the sub-means into category means, save the loop / non-loop mean fine-tunes, and compare them.
Reads the 24 sub-means from stage 1 (bf16 mean deltas, one per group). Works one unit at a time (a layer, or
embed / final norm / lm_head): the unit's 24 files are downloaded to disk (the next unit downloads in the background),
read in row chunks, and deleted. RAM stays under ~10 GB, so a standard CPU runtime is enough.
Fused means are exact weighted averages of sub-means: mean(C) = sum_k n_k S_k / sum_k n_k over the sub-means k in
category set C (S_k = sub-mean k). The only approximation is the bf16 storage of each S_k (rounding error per
tensor recorded in stage 1; the bound on its effect is saved here).
Outputs (pushed to mild-rgb/exp2-means):
loop_mean/, nonloop_mean/ loadable fp32 models: W_base + mean dW (fp32 so the small mean update is not rounded
away; a bf16 copy would lose part of it, see analysis/rounding.json)
analysis/gram.safetensors per tensor, the exact 24 x 24 Gram matrix <S_i, S_j> (float64). Every norm, cosine and
split-half statistic of any weighted combination of sub-means follows from it, so all
random-split controls can be computed afterwards on a laptop.
analysis/svd_<c>.safetensors for each contrast c and each 2-D layer weight: top-64 singular values, top-8 U and V
analysis/spectra.json per contrast and tensor: |D|_F, energy share in top 1/8/64 directions, participation
rank, logit lens of the top write direction (o_proj, down_proj), and how strongly the
update writes along the end-of-turn token directions vs 1,024 random tokens
analysis/rows.json embed / lm_head: per contrast, update norm of special-token rows vs the median row
analysis/rounding.json bf16 rounding audit of the fused means, and the sub-mean rounding bound
Env: HF_TOKEN; WORK (default /content/exp2f); THREADS (default 2); UNITS (comma list, for tests); NOUPLOAD=1.
"""
import os, re, json, time, threading, collections, shutil, random
from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
HERE = Path(__file__).resolve().parent
TOKEN = os.environ["HF_TOKEN"]
WORK = Path(os.environ.get("WORK", "/content/exp2f"))
torch.set_num_threads(int(os.environ.get("THREADS", "2")))
BASE = "Qwen/Qwen2.5-Math-7B"
REPO = {"loop": "mild-rgb/exp2-submeans-collapsed", "gibberish": "mild-rgb/exp2-submeans-collapsed",
"short": "mild-rgb/exp2-submeans-collapsed", "degraded": "mild-rgb/exp2-submeans-trained",
"healthy": "mild-rgb/exp2-submeans-trained"}
FINAL = "mild-rgb/exp2-means"
ORDER = ["loop", "gibberish", "short", "degraded", "healthy"]
CHUNK = int(os.environ.get("CHUNK", str(1 << 23))) # elements per row chunk
UNITS_ENV = [u for u in os.environ.get("UNITS", "").split(",") if u]
NOUPLOAD = os.environ.get("NOUPLOAD") == "1"
SPECIAL = {151643: "<|endoftext|>", 151645: "<|im_end|>", 151644: "<|im_start|>"}
WORK.mkdir(parents=True, exist_ok=True)
LOG = WORK / "fuse.log"
api = HfApi(token=TOKEN)
def log(*a):
s = time.strftime("%H:%M:%S") + " " + " ".join(str(x) for x in a)
print(s, flush=True)
with open(LOG, "a") as f:
f.write(s + "\n")
UNIT_ORDER = [f"L{i:02d}" for i in range(28)] + ["embed", "norm", "lm_head"]
# ---------------- sub-means and weights ----------------
G = json.load(open(HERE / "meta" / "groups.json"))["groups"]
G = sorted(G, key=lambda g: (ORDER.index(g["category"]), g["name"]))
K = len(G)
names = [g["name"] for g in G]
cat = [g["category"] for g in G]
nk = torch.tensor([g["n"] for g in G], dtype=torch.float64)
man = {}
for g in G:
p = hf_hub_download(REPO[g["category"]], f"{g['name']}/manifest.json", token=TOKEN, local_dir=WORK / "man")
man[g["name"]] = json.load(open(p))
assert man[g["name"]]["n"] == g["n"] and man[g["name"]]["members"] == g["members"], g["name"]
log("sub-means", K, dict(collections.Counter(cat)))
def mean_w(cats, mask=None):
w = torch.tensor([float(nk[i]) if (c in cats and (mask is None or mask[i])) else 0.0 for i, c in enumerate(cat)],
dtype=torch.float64)
return w / w.sum()
rng = random.Random(7)
half = {} # random half of the sub-mean set within each category
for c in ORDER:
ks = [i for i in range(K) if cat[i] == c]
rng.shuffle(ks)
for j, i in enumerate(ks):
half[i] = j % 2
A = [half[i] == 0 for i in range(K)]
B = [half[i] == 1 for i in range(K)]
others = [c for c in ORDER if c != "loop"]
perm = list(range(K)); rng.shuffle(perm)
fake_loop = set(perm[:sum(1 for c in cat if c == "loop")]) # label-permuted "loop" set (same number of sub-means)
W = collections.OrderedDict()
W["loop"] = mean_w(["loop"])
W["nonloop"] = mean_w(others)
W["healthy"] = mean_w(["healthy"])
W["all"] = mean_w(ORDER)
W["loop-nonloop"] = W["loop"] - W["nonloop"]
W["loop-healthy"] = W["loop"] - W["healthy"]
W["gibberish-healthy"] = mean_w(["gibberish"]) - W["healthy"]
W["short-healthy"] = mean_w(["short"]) - W["healthy"]
W["degraded-healthy"] = mean_w(["degraded"]) - W["healthy"]
W["loop-gibberish"] = W["loop"] - mean_w(["gibberish"])
W["ctrl_split_A"] = mean_w(["loop"], A) - mean_w(others, A) # loop - nonloop from half A of sub-means
W["ctrl_split_B"] = mean_w(["loop"], B) - mean_w(others, B) # ... from the other half
W["ctrl_loop_noise"] = mean_w(["loop"], A) - mean_w(["loop"], B) # same label, two halves: noise reference
w_fake = torch.tensor([float(nk[i]) if i in fake_loop else 0.0 for i in range(K)], dtype=torch.float64)
w_rest = torch.tensor([float(nk[i]) if i not in fake_loop else 0.0 for i in range(K)], dtype=torch.float64)
W["ctrl_perm"] = w_fake / w_fake.sum() - w_rest / w_rest.sum() # label-permuted contrast
CN = list(W)
WM = torch.stack([W[c] for c in CN]).float() # C x K
SVD_SET = [c for c in CN if c != "nonloop"]
LENS_SET = [c for c in CN if c not in ("loop", "nonloop", "healthy", "all")]
json.dump(dict(subs=names, category=cat, n=nk.tolist(), weights={c: W[c].tolist() for c in CN},
half=[half[i] for i in range(K)], fake_loop=sorted(fake_loop)),
open(WORK / "contrasts.json", "w"), indent=1)
# ---------------- base, lens ----------------
bdir = snapshot_download(BASE, allow_patterns=["*.safetensors", "*.json", "*.txt", "merges.txt", "vocab.json"],
token=TOKEN, local_dir=str(WORK / "base"))
bidx = json.load(open(Path(bdir) / "model.safetensors.index.json"))["weight_map"]
bfiles = {f: safe_open(str(Path(bdir) / f), "pt") for f in set(bidx.values())}
all_names = sorted(bidx)
def unit_of(name):
m = re.match(r"model\.layers\.(\d+)\.", name)
if m:
return f"L{int(m.group(1)):02d}"
return {"model.embed_tokens.weight": "embed", "model.norm.weight": "norm", "lm_head.weight": "lm_head"}[name]
by_unit = collections.defaultdict(list)
for k in all_names:
by_unit[unit_of(k)].append(k)
units = [u for u in UNIT_ORDER if by_unit.get(u) and (not UNITS_ENV or u in UNITS_ENV)]
lm = bfiles[bidx["lm_head.weight"]].get_tensor("lm_head.weight").float() # V x 3584
normw = bfiles[bidx["model.norm.weight"]].get_tensor("model.norm.weight").float()
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(bdir)
Wt = lm * normw[None, :]
gnull = torch.Generator().manual_seed(11)
null_ids = torch.randint(0, 151643, (1024,), generator=gnull)
probe_ids = torch.cat([torch.tensor(list(SPECIAL)), null_ids])
Wp = Wt[probe_ids]
Wp = Wp / Wp.norm(dim=1, keepdim=True) # (3 + 1024) x 3584
def lens(u, k=12):
lg = lm @ (normw * u)
return ([tok.decode([t]) for t in torch.topk(lg, k).indices.tolist()],
[tok.decode([t]) for t in torch.topk(-lg, k).indices.tolist()])
# ---------------- unit download with prefetch ----------------
def fetch_unit(u):
d = WORK / "units" / u
paths = []
for g in G:
for k in range(6):
try:
p = hf_hub_download(REPO[g["category"]], f"{g['name']}/deltas/{u}.safetensors", token=TOKEN,
local_dir=d / g["name"])
break
except Exception as e:
log("download retry", g["name"], u, repr(e)[:100])
time.sleep(30 * (k + 1))
else:
raise RuntimeError(f"download failed {g['name']} {u}")
paths.append(p)
return paths
class Prefetch(threading.Thread):
def __init__(self, u):
super().__init__(daemon=True)
self.u, self.res, self.err = u, None, None
self.start()
def run(self):
try:
self.res = fetch_unit(self.u)
except Exception as e:
self.err = e
# ---------------- main loop ----------------
gram = {}
spectra = collections.defaultdict(dict)
svd = collections.defaultdict(dict)
rows = collections.defaultdict(dict)
rounding = {}
fstage = {c: WORK / "final" / f"{c}_mean" for c in ("loop", "nonloop")}
for p in fstage.values():
p.mkdir(parents=True, exist_ok=True)
fmap = {c: {} for c in fstage}
fin_w = {c: W[c].float() for c in fstage}
t0 = time.time()
pre = Prefetch(units[0])
for ui, u in enumerate(units):
pre.join()
if pre.err:
raise pre.err
paths = pre.res
pre = Prefetch(units[ui + 1]) if ui + 1 < len(units) else None
fh = [safe_open(p, "pt") for p in paths]
fout = {c: {} for c in fstage}
for name in by_unit[u]:
shape = bfiles[bidx[name]].get_slice(name).get_shape()
N = 1
for s in shape:
N *= s
rows_n = shape[0]
cols = N // rows_n
rstep = max(1, CHUNK // cols)
is2d = len(shape) == 2 and u.startswith("L")
Gm = torch.zeros((K, K), dtype=torch.float64)
acc = {c: torch.empty(N, dtype=torch.float32) for c in SVD_SET} if is2d else None
fin = {c: torch.empty(N, dtype=torch.float32) for c in fstage}
r_err = {c: [0.0, 0.0] for c in fstage} # |bf16(W0+D) - (W0+D)|^2, |D|^2
rown = {c: torch.empty(rows_n, dtype=torch.float32) for c in CN} if u in ("embed", "lm_head") else None
bsl = bfiles[bidx[name]].get_slice(name)
sls = [f.get_slice(name) for f in fh]
for r0 in range(0, rows_n, rstep):
r1 = min(rows_n, r0 + rstep)
X = torch.stack([s[r0:r1].float().reshape(-1) for s in sls]) # K x c
Gm += (X.double() @ X.double().T)
Y = WM @ X # C x c
e0, e1 = r0 * cols, r1 * cols
if acc is not None:
for ci, c in enumerate(CN):
if c in acc:
acc[c][e0:e1] = Y[ci]
b = bsl[r0:r1].float().reshape(-1)
for c in fstage:
y = Y[CN.index(c)]
fv = b + y
fin[c][e0:e1] = fv
rr = fv.bfloat16().float() - fv
r_err[c][0] += torch.dot(rr, rr).item()
r_err[c][1] += torch.dot(y, y).item()
if rown is not None:
for ci, c in enumerate(CN):
rown[c][r0:r1] = Y[ci].view(r1 - r0, cols).norm(dim=1)
del X, Y, b
gram[name] = Gm
for i, g in enumerate(G): # check against stage-1 norms
ref = man[g["name"]]["mean_norm"][name]
got = Gm[i, i].sqrt().item()
if ref > 0 and abs(got - ref) / ref > 0.02:
log("WARNING norm mismatch", g["name"], name, ref, got)
for c in fstage:
fout[c][name] = fin[c].view(shape)
rounding[(c, name)] = dict(rel_bf16_loss=(r_err[c][0] ** 0.5) / max(r_err[c][1] ** 0.5, 1e-30),
delta_norm=r_err[c][1] ** 0.5)
fmap[c][name] = f"{u}.safetensors"
if rown is not None:
for c in CN:
rn = rown[c]
med = rn.median().item()
rows[name][c] = dict(median_row_norm=med, **{
SPECIAL[t]: dict(norm=rn[t].item(), ratio_to_median=rn[t].item() / med if med else None,
percentile=(rn < rn[t]).float().mean().item()) for t in SPECIAL})
if acc is not None:
for c in SVD_SET:
D = acc[c].view(shape)
fro2 = torch.dot(acc[c], acc[c]).item()
if fro2 == 0:
continue
if min(D.shape) <= 144:
Uq, S, Vh = torch.linalg.svd(D, full_matrices=False)
Vq = Vh.T
else:
Uq, S, Vq = torch.svd_lowrank(D, q=72, niter=3)
S = S[:64]
gz = torch.randn((D.shape[1], 128), generator=torch.Generator().manual_seed(5))
s4 = ((D.T @ (D @ gz)) ** 2).sum(0).mean().item() # Hutchinson |D^T D|_F^2
e = (S ** 2) / fro2
sp = dict(fro=fro2 ** 0.5, top1=e[:1].sum().item(), top8=e[:8].sum().item(),
top64=e[:64].sum().item(), pr_rank=fro2 ** 2 / s4, sv_top8=S[:8].tolist())
if (".o_proj." in name or ".down_proj." in name) and c in LENS_SET:
pos, neg = lens(Uq[:, 0])
sp["lens_u1"] = dict(one_end=pos, other_end=neg)
ew = ((Wp @ D) ** 2).sum(1) / (fro2 / D.shape[0]) # write energy along token dirs
nul = ew[len(SPECIAL):]
sp["eos_write"] = {SPECIAL[t]: dict(energy=ew[i].item(), percentile=(nul < ew[i]).float().mean().item())
for i, t in enumerate(SPECIAL)}
sp["eos_write"]["null_median"] = nul.median().item()
spectra[c][name] = sp
svd[c][name + ".U8"] = Uq[:, :8].contiguous()
svd[c][name + ".V8"] = Vq[:, :8].contiguous()
svd[c][name + ".S64"] = S.contiguous()
del D, Uq, Vq
del acc, fin, rown
for c in fstage:
save_file({k: v.contiguous() for k, v in fout[c].items()}, str(fstage[c] / f"{u}.safetensors"),
metadata={"format": "pt", "kind": f"{c}_mean_finetune_fp32", "base": BASE})
del fout, fh
shutil.rmtree(WORK / "units" / u, ignore_errors=True)
lc = spectra["loop-nonloop"]
ex = next((k for k in by_unit[u] if ".down_proj." in k), None)
log(f"{u} done ({ui + 1}/{len(units)}) {time.time() - t0:.0f}s" +
(f" | loop-nonloop down_proj |D| {lc[ex]['fro']:.4f} top1 {lc[ex]['top1']:.2f} lens {lc[ex].get('lens_u1', {}).get('one_end', [])[:5]}" if ex in lc else ""))
# ---------------- save ----------------
A_DIR = WORK / "analysis"
A_DIR.mkdir(exist_ok=True)
gn = sorted(gram)
save_file({"gram": torch.stack([gram[k] for k in gn]).contiguous()}, str(A_DIR / "gram.safetensors"),
metadata={"tensors": json.dumps(gn), "subs": json.dumps(names), "n": json.dumps(nk.tolist()),
"category": json.dumps(cat),
"numel": json.dumps([bfiles[bidx[k]].get_slice(k).get_shape() for k in gn])})
for c in svd:
save_file(svd[c], str(A_DIR / f"svd_{c}.safetensors"))
json.dump(spectra, open(A_DIR / "spectra.json", "w"))
json.dump(rows, open(A_DIR / "rows.json", "w"), indent=1)
bound = {}
for name in gn:
num = sum(abs(W["loop"][i].item()) * man[names[i]]["bf16_rel_rounding_error"][name] * man[names[i]]["mean_norm"][name]
for i in range(K))
nrm = rounding[("loop", name)]["delta_norm"]
bound[name] = num / nrm if nrm else 0.0
json.dump(dict(fused_bf16_loss={f"{c}|{n}": v for (c, n), v in rounding.items()},
submean_rounding_bound_loop_rel=bound), open(A_DIR / "rounding.json", "w"))
shutil.copy(WORK / "contrasts.json", A_DIR / "contrasts.json")
shutil.copy(LOG, A_DIR / "fuse.log")
cfg = json.load(open(Path(bdir) / "config.json"))
cfg["torch_dtype"] = "float32"
for c, p in fstage.items():
json.dump({"metadata": {"kind": f"{c}_mean_finetune_fp32"}, "weight_map": fmap[c]},
open(p / "model.safetensors.index.json", "w"), indent=1)
json.dump(cfg, open(p / "config.json", "w"), indent=1)
for f in os.listdir(bdir):
if f.endswith((".json", ".txt")) and f not in ("config.json", "model.safetensors.index.json"):
shutil.copy(Path(bdir) / f, p / f)
members = [m for i, g in enumerate(G) if W[c][i] > 0 for m in g["members"]]
(p / "README.md").write_text(
f"# {c} mean fine-tune\n\nMean of {len(members)} GRPO fine-tunes of {BASE} by luckeciano, "
f"category '{c}' (see code/groups.py in this repo for the rules), built by fusing sub-means "
f"(weighted by group size). Weights are fp32: W_base + mean(W_i - W_base).\n\nMembers:\n" +
"\n".join(f"- {m}" for m in members) + "\n")
log("saved locally", time.time() - t0)
if not NOUPLOAD:
api.upload_folder(repo_id=FINAL, folder_path=str(A_DIR), path_in_repo="analysis", commit_message="fuse: analysis")
log("analysis uploaded")
for c, p in fstage.items():
api.upload_folder(repo_id=FINAL, folder_path=str(p), path_in_repo=f"{c}_mean", commit_message=f"{c} mean fine-tune (fp32)")
log("uploaded", c)
log("FUSE DONE")