"""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 without bias (N = number of weights), which allows model-level controls later without downloading anything again. Output per group, pushed as one commit to // (resumable: a group with manifest.json is done): deltas/.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(" 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": " ~= (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}: 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])