exp2-means / code /submean.py
mild-rgb's picture
submean: CPU version (chunked, coordinate samples)
d33dc21 verified
Raw History Blame Contribute Delete
19.7 kB
"""Stage 1: one mean fine-tune (a "sub-mean") per group of runs, streamed straight from Hugging Face.
For each group in meta/groups.json, and each weight tensor, computes the mean update
mean_dW = mean_i (W_i - W_base) (fp32 on the device, saved as bf16)
without ever holding a whole model: models are read one unit at a time (a layer, or embed / final norm / lm_head)
with HTTP byte-range requests, and each tensor is processed in flat chunks, so RAM and disk stay small (a standard
2-core CPU runtime is enough).
Alongside the mean it records, for every member and every tensor, |dW|_F, the share of weights that changed and
max |dW|, and a coordinate sample of dW for each 2-D weight matrix: dW at 16,384 fixed random positions (drawn with
replacement, the same positions for every model). (N / k) * sum over the sample of x * y estimates <dW_i, dW_j>
without bias (N = number of weights), which allows model-level controls later without downloading anything again.
Output per group, pushed as one commit to <repo>/<group>/ (resumable: a group with manifest.json is done):
deltas/<unit>.safetensors + deltas/index.json mean dW in bf16, tensor names as in the model
sketches.safetensors "sketch": [n_members, n_sketched, 16384] fp32 samples
manifest.json members, sizes, per-tensor bf16 rounding error, member stats
Env: HF_TOKEN; WORK (default /content/exp2); THREADS (default 2); ONLY (comma list of group names);
UNITS (comma list, e.g. L27,norm); FILTER (regex on tensor names); NOUPLOAD=1; SELFTEST=1 (structured checks);
BASE_LOCAL=1 (download the base model to disk and read it from there).
"""
import os, re, json, time, struct, threading, collections, shutil, traceback, random
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import requests
import torch
from safetensors.torch import save_file
HERE = Path(__file__).resolve().parent
TOKEN = os.environ["HF_TOKEN"]
WORK = Path(os.environ.get("WORK", "/content/exp2"))
DEV = "cpu"
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"}
STATUS_REPO = "mild-rgb/exp2-means"
ORDER = ["loop", "gibberish", "short", "degraded", "healthy"]
D_SK = 16384
WINDOW_BYTES = int(float(os.environ.get("WINDOW_GB", "2.5")) * 1e9)
WORKERS = int(os.environ.get("WORKERS", "8"))
UNITS_ENV = [u for u in os.environ.get("UNITS", "").split(",") if u]
FILTER = re.compile(os.environ.get("FILTER", ".*"))
NOUPLOAD = os.environ.get("NOUPLOAD") == "1"
SELFTEST = os.environ.get("SELFTEST") == "1"
torch.backends.cuda.matmul.allow_tf32 = False
H = {"Authorization": f"Bearer {TOKEN}"}
TLS = threading.local()
LOG = WORK / "submean.log"
WORK.mkdir(parents=True, exist_ok=True)
STAT = dict(started=time.time(), bytes=0, groups_done=[], current=None, unit=None, errors=0)
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")
def sess():
if not hasattr(TLS, "s"):
TLS.s = requests.Session()
return TLS.s
def http_get(url, rng=None, stream=False):
hdr = dict(H)
if rng:
hdr["Range"] = f"bytes={rng[0]}-{rng[1] - 1}"
for k in range(10):
try:
r = sess().get(url, headers=hdr, stream=stream, timeout=120)
if r.status_code in (200, 206):
if rng and r.status_code != 206:
raise RuntimeError("range ignored")
return r
if r.status_code in (429, 500, 502, 503, 504):
wait = float(r.headers.get("Retry-After", 0) or 0) or 10 * (k + 1)
log("http", r.status_code, url[-60:], "wait", wait)
STAT["errors"] += 1
time.sleep(min(wait, 300))
continue
raise RuntimeError(f"HTTP {r.status_code} {url}")
except (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError) as e:
log("net", repr(e)[:120], "retry", k)
STAT["errors"] += 1
time.sleep(10 * (k + 1))
raise RuntimeError(f"gave up {url}")
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]
UNIT_ORDER = [f"L{i:02d}" for i in range(28)] + ["embed", "norm", "lm_head"]
class Model:
"""Byte-level access to one model's safetensors shards, remote (resolve URL at a fixed revision) or local."""
def __init__(self, repo, rev="main", local=None):
self.repo, self.rev, self.local = repo, rev, local
idx = self._json("model.safetensors.index.json")
files = sorted(set(idx["weight_map"].values()))
self.t = {} # name -> (file, abs_start, abs_end, dtype, shape)
for f in files:
n = struct.unpack("<Q", self._read(f, 0, 8))[0]
hd = json.loads(self._read(f, 8, 8 + n))
hd.pop("__metadata__", None)
for k, v in hd.items():
a, b = v["data_offsets"]
self.t[k] = (f, 8 + n + a, 8 + n + b, v["dtype"], v["shape"])
def _url(self, f):
return f"https://huggingface.co/{self.repo}/resolve/{self.rev}/{f}"
def _json(self, f):
if self.local:
return json.load(open(Path(self.local) / f))
return http_get(self._url(f)).json()
def _read(self, f, a, b):
if self.local:
with open(Path(self.local) / f, "rb") as fh:
fh.seek(a)
return fh.read(b - a)
r = http_get(self._url(f), (a, b), stream=True)
buf = bytearray(b - a)
mv, pos = memoryview(buf), 0
for c in r.iter_content(1 << 22):
mv[pos:pos + len(c)] = c
pos += len(c)
r.close()
if pos != b - a:
raise RuntimeError(f"short read {pos} of {b - a}")
STAT["bytes"] += b - a
return buf
def pieces(self, unit, names):
"""Contiguous byte runs covering `names` (all in `unit`), grouped per file."""
items = sorted((self.t[n][0], self.t[n][1], self.t[n][2], n) for n in names)
out = []
for f, a, b, n in items:
if out and out[-1][0] == f and out[-1][2] == a:
out[-1][2] = b
out[-1][3].append((n, a, b))
else:
out.append([f, a, b, [(n, a, b)]])
return out
def fetch(self, unit, names):
res = {}
for f, a, b, lst in self.pieces(unit, names):
buf = self._read(f, a, b)
for n, x, y in lst:
dt, shape = self.t[n][3], self.t[n][4]
assert dt == "BF16", (self.repo, n, dt)
res[n] = torch.frombuffer(buf, dtype=torch.bfloat16, offset=x - a, count=(y - x) // 2).view(shape)
return res
def nbytes(self, names):
return sum(self.t[n][2] - self.t[n][1] for n in names)
# ---------------- coordinate sample ----------------
CHUNK = int(os.environ.get("CHUNK", str(1 << 24)))
_SKI = {}
def sk_positions(numel):
"""Fixed sorted sample positions for a tensor size (same for every model; seed depends only on numel)."""
if numel not in _SKI:
g = torch.Generator().manual_seed(20261109 + numel % 1_000_003)
_SKI[numel] = torch.randint(0, numel, (D_SK,), generator=g, dtype=torch.int64).sort().values
return _SKI[numel]
# ---------------- one group ----------------
def run_group(g, base, names_by_unit, sk_names, members_src=None):
name, members = g["name"], g["members"]
n = len(members)
runs = {r["repo"]: r for r in RUNS} if RUNS else {}
srcs = members_src or [Model(m, runs.get(m, {}).get("sha", "main")) for m in members]
for s in srcs:
assert set(s.t) == set(base.t), (s.repo, "tensor set differs from base")
for k in names_by_unit_flat:
assert s.t[k][4] == base.t[k][4], (s.repo, k)
stage = WORK / "stage" / name
if stage.exists():
shutil.rmtree(stage)
(stage / "deltas").mkdir(parents=True)
sk_index = {k: i for i, k in enumerate(sk_names)}
SK = torch.zeros((n, len(sk_names), D_SK), dtype=torch.float32)
mstats = [dict() for _ in range(n)]
round_err, mean_norm, weight_map = {}, {}, {}
units = [u for u in UNIT_ORDER if names_by_unit.get(u)]
tasks = [(u, j) for u in units for j in range(n)]
pool = ThreadPoolExecutor(WORKERS)
inflight = collections.deque()
ti, cur_u, base_t, acc, t_unit = 0, None, None, None, time.time()
selftest_dw = {}
while ti < len(tasks) or inflight:
while ti < len(tasks) and (not inflight or sum(x[2] for x in inflight) < WINDOW_BYTES) and len(inflight) < 3 * WORKERS:
u, j = tasks[ti]
nb = srcs[j].nbytes(names_by_unit[u])
inflight.append((u, j, nb, pool.submit(srcs[j].fetch, u, names_by_unit[u])))
ti += 1
u, j, nb, fut = inflight.popleft()
got = fut.result()
if u != cur_u:
cur_u, STAT["unit"] = u, u
bt = base.fetch(u, names_by_unit[u])
base_t = {k: (v.to(torch.float32) if v.numel() < 100_000_000 else v.clone()) for k, v in bt.items()}
del bt
acc = {k: torch.zeros(v.shape, dtype=torch.float32) for k, v in base_t.items()}
t_unit = time.time()
for k, w in got.items():
wf, bf, af = w.reshape(-1), base_t[k].reshape(-1), acc[k].reshape(-1)
N = wf.numel()
ss, nnz, mx = 0.0, 0, 0.0
skp = sk_positions(N) if k in sk_index else None
samp = torch.empty(D_SK, dtype=torch.float32) if skp is not None else None
keep = [] if SELFTEST else None
for s0 in range(0, N, CHUNK):
s1 = min(N, s0 + CHUNK)
d = wf[s0:s1].float()
d.sub_(bf[s0:s1])
af[s0:s1].add_(d)
ss += torch.dot(d, d).item()
nnz += int(torch.count_nonzero(d).item())
lo_, hi_ = torch.aminmax(d)
mx = max(mx, -lo_.item(), hi_.item())
if skp is not None:
i0, i1 = int(torch.searchsorted(skp, s0)), int(torch.searchsorted(skp, s1))
samp[i0:i1] = d[skp[i0:i1] - s0]
if keep is not None:
keep.append(d.clone())
del d
mstats[j][k] = [ss ** 0.5, nnz / N, mx]
if skp is not None:
SK[j, sk_index[k]] = samp
if keep is not None:
selftest_dw[(j, k)] = torch.cat(keep).view(w.shape)
del got
if j == n - 1: # unit complete
out = {}
for k, a in acc.items():
af = a.reshape(-1)
N = af.numel()
mb = torch.empty(N, dtype=torch.bfloat16)
n2 = e2 = 0.0
for s0 in range(0, N, CHUNK):
s1 = min(N, s0 + CHUNK)
m = af[s0:s1] / n
mb[s0:s1] = m.to(torch.bfloat16)
n2 += torch.dot(m, m).item()
r = mb[s0:s1].float() - m
e2 += torch.dot(r, r).item()
if SELFTEST:
af[s0:s1] = m
nm = n2 ** 0.5
mean_norm[k] = nm
round_err[k] = (e2 ** 0.5 / nm) if nm > 0 else 0.0
out[k] = mb.view(a.shape)
weight_map[k] = f"{u}.safetensors"
if SELFTEST:
SELF[(name, k)] = a.clone()
save_file(out, str(stage / "deltas" / f"{u}.safetensors"),
metadata={"kind": "mean_delta_vs_base_bf16", "group": name, "n": str(n), "base": BASE})
log(f"{name} {u} done n={n} {time.time() - t_unit:.1f}s GB so far {STAT['bytes'] / 1e9:.1f}")
base_t = acc = out = None
pool.shutdown()
json.dump({"metadata": {"kind": "mean_delta_vs_base_bf16"}, "weight_map": weight_map},
open(stage / "deltas" / "index.json", "w"), indent=1)
save_file({"sketch": SK.contiguous()}, str(stage / "sketches.safetensors"),
metadata={"members": json.dumps(members), "tensors": json.dumps(sk_names), "d": str(D_SK),
"positions": "torch.randint(0, N, (16384,), generator=Generator().manual_seed(20261109 + N % 1000003)).sort()",
"estimator": "<x, y> ~= (N / 16384) * sum(sample_x * sample_y)"})
man = dict(group=name, category=g["category"], n=n, members=members,
revisions=[s.rev for s in srcs], base=BASE, units=units,
mean_norm=mean_norm, bf16_rel_rounding_error=round_err,
member_stats_fields=["fro_norm", "share_changed", "max_abs"],
member_stats={members[j]: mstats[j] for j in range(n)},
sketched_tensors=sk_names, d_sketch=D_SK, created=time.strftime("%Y-%m-%d %H:%M:%S"))
json.dump(man, open(stage / "manifest.json", "w"))
if SELFTEST:
SELFDW.update({(name, j, k): v for (j, k), v in selftest_dw.items()})
SELFSK[name] = SK
return stage
def upload(stage, repo, name):
from huggingface_hub import HfApi
api = HfApi(token=TOKEN)
for k in range(5):
try:
t = time.time()
api.upload_folder(repo_id=repo, folder_path=str(stage), path_in_repo=name,
commit_message=f"sub-mean {name}")
gb = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file()) / 1e9
log(f"uploaded {name} -> {repo} {gb:.1f} GB in {time.time() - t:.0f}s")
shutil.rmtree(stage)
STAT["groups_done"].append(name)
return
except Exception as e:
log("upload failed", name, repr(e)[:200])
time.sleep(60 * (k + 1))
raise RuntimeError("upload failed " + name)
def heartbeat():
from huggingface_hub import HfApi
api = HfApi(token=TOKEN)
while True:
time.sleep(600)
try:
s = dict(STAT, now=time.strftime("%Y-%m-%d %H:%M:%S"),
rate_MBps=STAT["bytes"] / 1e6 / max(1, time.time() - STAT["started"]))
p = WORK / "status.json"
json.dump(s, open(p, "w"), indent=1)
api.upload_file(path_or_fileobj=str(p), path_in_repo="status/submean.json", repo_id=STATUS_REPO,
commit_message="heartbeat")
api.upload_file(path_or_fileobj=str(LOG), path_in_repo="status/submean.log", repo_id=STATUS_REPO,
commit_message="log")
except Exception as e:
log("heartbeat failed", repr(e)[:120])
# ---------------- main ----------------
G = json.load(open(HERE / "meta" / "groups.json"))
RUNS = []
if (HERE / "meta" / "usable.csv").exists():
import csv
RUNS = list(csv.DictReader(open(HERE / "meta" / "usable.csv")))
SELF, SELFDW, SELFSK = {}, {}, {}
if os.environ.get("BASE_LOCAL") == "1":
from huggingface_hub import snapshot_download
bdir = snapshot_download(BASE, allow_patterns=["*.safetensors", "*.json"], token=TOKEN,
local_dir=str(WORK / "base"))
base = Model(BASE, local=bdir)
else:
base = Model(BASE)
all_names = sorted(k for k in base.t if FILTER.search(k))
names_by_unit = collections.defaultdict(list)
for k in all_names:
names_by_unit[unit_of(k)].append(k)
if UNITS_ENV:
names_by_unit = {u: v for u, v in names_by_unit.items() if u in UNITS_ENV}
names_by_unit_flat = [k for v in names_by_unit.values() for k in v]
sk_names = [k for u in UNIT_ORDER for k in sorted(names_by_unit.get(u, [])) if len(base.t[k][4]) == 2]
log("base tensors", len(base.t), "selected", len(names_by_unit_flat), "sketched", len(sk_names), "device", DEV)
if SELFTEST:
usable = [r["repo"] for r in RUNS]
m1, m2 = usable[0], usable[1]
tests = [dict(name="T_base_base", category="test", members=[BASE, BASE]),
dict(name="T_m1_m1", category="test", members=[m1, m1]),
dict(name="T_m1_m2", category="test", members=[m1, m2])]
for g in tests:
srcs = [base if m == BASE else Model(m) for m in g["members"]]
run_group(g, base, names_by_unit, sk_names, members_src=srcs)
ok = True
for k in names_by_unit_flat:
z = SELF[("T_base_base", k)]
ok &= bool((z == 0).all())
a = SELF[("T_m1_m1", k)]
ok &= bool(torch.equal(a, SELFDW[("T_m1_m1", 0, k)]))
# independent path: read the two tensors directly by name
w1 = Model(m1).fetch(None, [k])[k].float()
w2 = Model(m2).fetch(None, [k])[k].float()
w0 = base.fetch(None, [k])[k].float()
ref = ((w1 - w0) + (w2 - w0)) / 2
err = (SELF[("T_m1_m2", k)] - ref).abs().max().item()
ok &= err < 1e-6
print(f"{k}: base-base max {z.abs().max().item():.2e}, m1m1==dW {torch.equal(a, SELFDW[('T_m1_m1', 0, k)])}, "
f"m1m2 vs independent max err {err:.2e}")
SK = SELFSK["T_m1_m2"]
for i, k in enumerate(sk_names):
d1, d2 = SELFDW[("T_m1_m2", 0, k)], SELFDW[("T_m1_m2", 1, k)]
Nn = d1.numel()
ex, es = (d1 * d2).sum().item(), Nn / D_SK * (SK[0, i] * SK[1, i]).sum().item()
n1, n2 = d1.norm().item(), d2.norm().item()
print(f"sketch {k}: <d1,d2> exact {ex:.4e} sketch {es:.4e} | err/(|d1||d2|) {(es - ex) / (n1 * n2):+.4f} "
f"(rough scale 1/sqrt({D_SK}) = {D_SK ** -0.5:.4f}, larger if dW is sparse) | |d1|^2 exact {n1 ** 2:.4e} sketch {Nn / D_SK * (SK[0, i] ** 2).sum().item():.4e}")
print("SELFTEST", "PASS" if ok else "FAIL")
raise SystemExit(0 if ok else 1)
threading.Thread(target=heartbeat, daemon=True).start()
from huggingface_hub import HfApi
api = HfApi(token=TOKEN)
done = set()
for R in set(REPO.values()):
for f in api.list_repo_files(R):
if f.endswith("/manifest.json"):
done.add(f.split("/")[0])
only = [x for x in os.environ.get("ONLY", "").split(",") if x]
todo = [g for c in ORDER for g in G["groups"] if g["category"] == c and g["name"] not in done
and (not only or g["name"] in only)]
log("groups done", len(done), "to do", len(todo), [g["name"] for g in todo])
up = None
for g in todo:
STAT["current"] = g["name"]
t = time.time()
stage = run_group(g, base, names_by_unit, sk_names)
log(f"group {g['name']} computed in {time.time() - t:.0f}s")
if up:
up.join()
if NOUPLOAD:
log("NOUPLOAD: kept", stage)
continue
up = threading.Thread(target=upload, args=(stage, REPO[g["category"]], g["name"]))
up.start()
if up:
up.join()
STAT["current"] = "DONE"
log("ALL DONE")
try:
json.dump(dict(STAT, now=time.strftime("%Y-%m-%d %H:%M:%S")), open(WORK / "status.json", "w"), indent=1)
api.upload_file(path_or_fileobj=str(WORK / "status.json"), path_in_repo="status/submean.json",
repo_id=STATUS_REPO, commit_message="submean done")
api.upload_file(path_or_fileobj=str(LOG), path_in_repo="status/submean.log", repo_id=STATUS_REPO,
commit_message="log")
except Exception as e:
log("final status upload failed", repr(e)[:120])