Upload code/common.py with huggingface_hub
Browse files- code/common.py +105 -0
code/common.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared machinery for the compose-audit. Imports mergeschool.core READ-ONLY."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import os, sys, json, time, math, gc
|
| 4 |
+
for v in ("OMP_NUM_THREADS","MKL_NUM_THREADS","OPENBLAS_NUM_THREADS","NUMEXPR_NUM_THREADS"):
|
| 5 |
+
os.environ.setdefault(v, "8")
|
| 6 |
+
sys.path.insert(0, "/root/mergeability/src")
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
torch.set_num_threads(8)
|
| 10 |
+
|
| 11 |
+
from mergeschool.core import merge as MG
|
| 12 |
+
from mergeschool.core import alignment as AL
|
| 13 |
+
from mergeschool.core import metrics as MT
|
| 14 |
+
from mergeschool.core import eval as EV
|
| 15 |
+
|
| 16 |
+
DATA = "/root/goldfish-alignment/data"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ------------------------------------------------------------------ corpora
|
| 20 |
+
def flores_lines(code):
|
| 21 |
+
out = []
|
| 22 |
+
with open(f"{DATA}/{code}.jsonl", encoding="utf-8") as f:
|
| 23 |
+
for line in f:
|
| 24 |
+
r = json.loads(line)
|
| 25 |
+
if r.get("text"):
|
| 26 |
+
out.append(r["text"])
|
| 27 |
+
return out
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def make_blocks(tok, lines, block=512, max_blocks=64, sep="\n\n"):
|
| 31 |
+
ids = tok(sep.join(lines), return_tensors=None)["input_ids"]
|
| 32 |
+
n = min(max_blocks, len(ids) // block)
|
| 33 |
+
if n == 0:
|
| 34 |
+
n, block = 1, min(block, len(ids))
|
| 35 |
+
arr = np.asarray(ids[: n * block], dtype=np.int64).reshape(n, block)
|
| 36 |
+
return torch.from_numpy(arr)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ------------------------------------------------------------------ state dicts
|
| 40 |
+
def sd_np(model):
|
| 41 |
+
return {k: v.detach().float().cpu().numpy() for k, v in model.state_dict().items()}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def sd_load(model, sd, dev, dtype=torch.float32):
|
| 45 |
+
with torch.no_grad():
|
| 46 |
+
msd = model.state_dict()
|
| 47 |
+
for k, v in sd.items():
|
| 48 |
+
if k in msd:
|
| 49 |
+
msd[k].copy_(torch.as_tensor(np.asarray(v), dtype=dtype))
|
| 50 |
+
return model
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ------------------------------------------------------------------ eval
|
| 54 |
+
@torch.no_grad()
|
| 55 |
+
def nll_nats(model, blocks, dev, bs=8):
|
| 56 |
+
"""Mean nats/token on the held-out blocks (next-token CE)."""
|
| 57 |
+
tot, ntok = 0.0, 0
|
| 58 |
+
for i in range(0, blocks.shape[0], bs):
|
| 59 |
+
x = blocks[i:i + bs].to(dev)
|
| 60 |
+
logits = model(x).logits.float()
|
| 61 |
+
lp = torch.log_softmax(logits[:, :-1], -1)
|
| 62 |
+
tgt = x[:, 1:]
|
| 63 |
+
nll = -lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1)
|
| 64 |
+
tot += nll.sum().item(); ntok += tgt.numel()
|
| 65 |
+
return tot / ntok
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@torch.no_grad()
|
| 69 |
+
def capture_acts(model, blocks, dev, n_rows=2048, bs=8, seed=0):
|
| 70 |
+
"""{layer_idx: (n_rows, d)} residual-stream activations on the shared corpus."""
|
| 71 |
+
outs = None
|
| 72 |
+
for i in range(0, blocks.shape[0], bs):
|
| 73 |
+
x = blocks[i:i + bs].to(dev)
|
| 74 |
+
hs = model(x, output_hidden_states=True).hidden_states
|
| 75 |
+
if outs is None:
|
| 76 |
+
outs = [[] for _ in hs]
|
| 77 |
+
for j, h in enumerate(hs):
|
| 78 |
+
outs[j].append(h.float().reshape(-1, h.shape[-1]).cpu())
|
| 79 |
+
acts = {}
|
| 80 |
+
rng = np.random.default_rng(seed)
|
| 81 |
+
N = torch.cat(outs[0]).shape[0]
|
| 82 |
+
idx = rng.choice(N, size=min(n_rows, N), replace=False)
|
| 83 |
+
idx = np.sort(idx)
|
| 84 |
+
for j in range(len(outs)):
|
| 85 |
+
acts[j] = torch.cat(outs[j])[idx].numpy().astype(np.float64)
|
| 86 |
+
return acts
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ predictors
|
| 90 |
+
def flat(sd, keys):
|
| 91 |
+
return np.concatenate([np.asarray(sd[k], float).ravel() for k in keys])
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def shared_keys(a, b):
|
| 95 |
+
return [k for k, v in a.items() if k in b and np.shape(b[k]) == np.shape(v)]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def mean_cka(acts_a, acts_b, layers=None):
|
| 99 |
+
L = sorted(set(acts_a) & set(acts_b)) if layers is None else layers
|
| 100 |
+
vals = [MT.cka(acts_a[l], acts_b[l]) for l in L]
|
| 101 |
+
return float(np.mean(vals)), {int(l): float(v) for l, v in zip(L, vals)}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def interp_sd(a, b, t):
|
| 105 |
+
return {k: (1 - t) * np.asarray(a[k], float) + t * np.asarray(b[k], float) for k in a}
|