File size: 15,198 Bytes
f93f1b8 | 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | #!/usr/bin/env python3
"""record.py - which experts do what (ARCHITECTURE.md 6.2, T6 in section 7).
python3 record.py --texts /srv/prune/data/texts/calib --domains chat,code,math,multi,wiki,tools,agent,think \
--out /srv/prune/out --model /srv/prune/models/hf_orig --max-mem-gib 12 \
[--max-tokens-per-domain N] [--max-chunks N] [--tiny-random]
For every layer l, pass p, expert e, summed over tokens where e was picked: n (1), sw (router weight w),
sa (||f||, the L2 norm of the expert's own output before weighting), swa (w * ||f||). Arrays [layers, 3, 128]
float64; non-looped layers use pass 0 only. Writes out/stats_<domain>.npz plus _even/_odd (by chunk number),
out/t6.json, out/record_speed.json. Resumable: a domain whose stats_<domain>.npz exists is skipped.
HOW f IS OBTAINED (read from transformers main, models/inkling2_loop/modeling_inkling2_loop.py)
Inkling2LoopSparseMoeBlock.forward(h): _, w, idx = self.gate(h); return self.experts(h, idx, w)
There is no shared expert and no other additive term: the block output is exactly the routed sum.
Inkling2LoopExperts (decorated with @use_experts_implementation, so eager / grouped_mm / batched_mm all
dispatch through it) computes sum_k w[:, k] * down(softcapped_swiglu(gate_up(h)))[expert idx[:, k]].
So f for slot k is `mlp.experts(h, idx[:, k:k+1], ones(T, 1))`: the library's own computation, one slot, weight
1.0. The activation is never re-implemented. This runs inside a forward hook on `mlp`, with (w, idx) captured by
a forward hook on `mlp.gate`; the pass index comes from a call counter (pre-hook on `mlp`, reset per forward).
T6: on the first chunk of this invocation, for every layer visit, ||sum_k w_k f_k - y|| / ||y|| (y = the block's
real output, all tokens of the chunk) must be <= 2%. If any visit fails, t6.json is written and the run stops.
"""
import argparse
import itertools
import json
import os
import signal
import sys
import time
import numpy as np
import torch
WINDOW = 1024
T6_TOL = 0.02
FIELDS = ("n", "sw", "sa", "swa")
T0 = time.time()
def log(msg):
print(f"[{time.time() - T0:7.1f}s] {msg}", flush=True)
def write_json(path, obj):
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f, indent=1)
os.replace(tmp, path)
def save_npz(path, arr, ntok):
"""arr: [layers, passes, 4, experts] float64 -> npz with n, sw, sa, swa [layers, passes, experts] and ntok."""
tmp = path + ".tmp"
with open(tmp, "wb") as f:
np.savez(f, ntok=np.float64(ntok), **{k: arr[:, :, j, :] for j, k in enumerate(FIELDS)})
os.replace(tmp, path)
# --------------------------------------------------------------------------------------------------------------
# model (from legacy passlab.py load_model)
# --------------------------------------------------------------------------------------------------------------
def load_model(args):
if args.tiny_random:
from transformers import Inkling2LoopForCausalLM, Inkling2LoopTextConfig
torch.manual_seed(0)
cfg = Inkling2LoopTextConfig(
hidden_size=64, num_attention_heads=4, num_key_value_heads=2, head_dim=16, swa_num_attention_heads=4,
swa_num_key_value_heads=2, swa_head_dim=16, moe_intermediate_size=32, n_routed_experts=128,
num_experts_per_tok=8, loop_gate_rank=8,
) # fmt: skip
model = Inkling2LoopForCausalLM(cfg).to(torch.bfloat16)
for name, tensor in itertools.chain(model.named_parameters(), model.named_buffers()):
if any(key in name for key in model._keep_in_fp32_modules_strict):
tensor.data = tensor.data.float()
for layer in model.model.layers:
torch.nn.init.normal_(layer.mlp.gate.weight, std=0.5)
torch.nn.init.normal_(layer.mlp.experts.gate_up_proj, std=0.2)
torch.nn.init.normal_(layer.mlp.experts.down_proj, std=0.2)
else:
from transformers import AutoModelForMultimodalLM
kw = {"dtype": torch.bfloat16, "device_map": "auto"}
if args.max_mem_gib:
kw["max_memory"] = {i: f"{args.max_mem_gib}GiB" for i in range(torch.cuda.device_count())}
log(f"loading {args.model} (bf16, device_map=auto)")
model = AutoModelForMultimodalLM.from_pretrained(args.model, **kw)
placed = {str(v) for v in getattr(model, "hf_device_map", {}).values()}
if placed & {"cpu", "disk"}:
raise RuntimeError(f"part of the model was offloaded to {placed & {'cpu', 'disk'}}; raise --max-mem-gib")
model.eval()
found = [m for _, m in model.named_modules() if hasattr(m, "layers") and hasattr(m, "message_input")]
if len(found) != 1:
raise RuntimeError(f"expected exactly one loop text model, found {len(found)}")
text_model = found[0]
log(f"model ready: {len(text_model.layers)} layers, experts {list(text_model.layers[0].mlp.experts.gate_up_proj.shape)}, "
f"backend {getattr(text_model.config, '_experts_implementation', None)}") # fmt: skip
return model, text_model
# --------------------------------------------------------------------------------------------------------------
# text
# --------------------------------------------------------------------------------------------------------------
def domain_windows(tok, path, max_tokens, max_chunks):
"""Render every row (chat template, no generation prompt; plain text for rows with "text"), concatenate into
one token stream, cut into 1,024-token windows. Returns LongTensor (n_windows, 1024)."""
limit = max_tokens if max_tokens else None
if max_chunks:
limit = min(limit or 1 << 62, max_chunks * WINDOW)
ids = []
with open(path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
row = json.loads(line)
if "messages" in row:
# Lead decision: render at the test setting (effort 0); think rows at the effort they were made with.
effort = 0.9 if os.path.basename(path).startswith("think") else 0
text = tok.apply_chat_template(row["messages"], tokenize=False, add_generation_prompt=False,
reasoning_effort=effort)
else:
text = row["text"]
ids.extend(tok(text, add_special_tokens=False)["input_ids"])
if limit and len(ids) >= limit:
break
if limit:
ids = ids[:limit]
n = len(ids) // WINDOW
return torch.tensor(ids[: n * WINDOW], dtype=torch.long).view(n, WINDOW)
# --------------------------------------------------------------------------------------------------------------
# recorder
# --------------------------------------------------------------------------------------------------------------
class Recorder:
def __init__(self, text_model):
cfg = text_model.config
self.layers = text_model.layers
self.embed_device = text_model.embed_tokens.weight.device
core = range(cfg.loop_layer_index_start, cfg.loop_layer_index_end)
self.n_pass = cfg.loop_num_passes
self.expected = [self.n_pass if i in core else 1 for i in range(len(self.layers))]
self.n_exp = self.layers[0].mlp.experts.num_experts
self.count = [0] * len(self.layers)
self.routed = {}
self.parity = 0
self.t6 = None # list collecting per-visit errors while the T6 chunk runs
self.acc = None
for i, layer in enumerate(self.layers):
layer.mlp.register_forward_pre_hook(lambda m, inp, i=i: self._pre(i))
layer.mlp.gate.register_forward_hook(lambda m, inp, out, i=i: self._router(i, out))
layer.mlp.register_forward_hook(lambda m, inp, out, i=i: self._moe(i, m, inp[0], out))
def reset(self):
"""Accumulators [parity][layer] -> (passes, 4, experts) float64 on that layer's device."""
self.acc = [[torch.zeros(self.n_pass, len(FIELDS), self.n_exp, dtype=torch.float64,
device=layer.mlp.experts.gate_up_proj.device) for layer in self.layers]
for _ in range(2)] # fmt: skip
def _pre(self, i):
self.count[i] += 1
def _router(self, i, out):
self.routed[i] = (out[1], out[2]) # weights (T, k) fp32, indices (T, k)
@torch.no_grad()
def _moe(self, i, mlp, h, y):
p = self.count[i] - 1
dev = mlp.experts.gate_up_proj.device # hooks see the raw call args; put everything on the experts' card
w, idx = (x.to(dev) for x in self.routed.pop(i))
h, y = h.reshape(-1, h.shape[-1]).to(dev), y.to(dev)
t, k = idx.shape
ones = torch.ones(t, 1, dtype=w.dtype, device=w.device)
norms = torch.empty(t, k, dtype=torch.float32, device=w.device)
recon = torch.zeros(t, h.shape[-1], dtype=torch.float32, device=w.device) if self.t6 is not None else None
for s in range(k):
f = mlp.experts(h, idx[:, s : s + 1], ones).float() # library's own expert computation, one slot
norms[:, s] = f.norm(dim=-1)
if recon is not None:
recon += w[:, s : s + 1].float() * f
acc = self.acc[self.parity][i][p]
flat = idx.reshape(-1).to(acc.device)
wf, nf = w.reshape(-1).double().to(acc.device), norms.reshape(-1).double().to(acc.device)
acc[0].index_add_(0, flat, torch.ones_like(wf))
acc[1].index_add_(0, flat, wf)
acc[2].index_add_(0, flat, nf)
acc[3].index_add_(0, flat, wf * nf)
if recon is not None:
yf = y.reshape(-1, y.shape[-1]).float()
err = ((recon - yf).norm() / yf.norm().clamp_min(1e-30)).item()
self.t6.append({"layer": i, "pass": p, "rel_err": err, "ok": err <= T6_TOL})
@torch.no_grad()
def forward(self, model, ids, parity):
self.count = [0] * len(self.layers)
self.parity = parity
model(input_ids=ids[None].to(self.embed_device), use_cache=False)
if self.count != self.expected:
raise RuntimeError(f"MoE call counts {self.count} != expected {self.expected}")
def result(self, parity):
return np.stack([a.cpu().numpy() for a in self.acc[parity]]) # [layers, passes, 4, experts]
# --------------------------------------------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--texts", required=True, help="folder with <domain>.jsonl")
ap.add_argument("--domains", required=True, help="comma-separated")
ap.add_argument("--out", required=True)
ap.add_argument("--model", default="/srv/prune/models/hf_orig")
ap.add_argument("--tokenizer", default=None, help="defaults to --model (tiny-random: --model if it exists, "
"else thinkingmachines/Inkling-2-Mini)") # fmt: skip
ap.add_argument("--max-mem-gib", type=int, default=None)
ap.add_argument("--max-tokens-per-domain", type=int, default=None)
ap.add_argument("--max-chunks", type=int, default=None, help="cap windows per domain")
ap.add_argument("--tiny-random", action="store_true", help="plumbing check on CPU, numbers meaningless")
ap.add_argument("--pid-file", default="/srv/prune/pids/record.pid")
args = ap.parse_args()
if not args.tokenizer:
args.tokenizer = args.model if (not args.tiny_random or os.path.exists(args.model)) else \
"thinkingmachines/Inkling-2-Mini" # fmt: skip
os.makedirs(args.out, exist_ok=True)
os.makedirs(os.path.dirname(args.pid_file), exist_ok=True)
with open(args.pid_file, "w") as f:
f.write(str(os.getpid()))
signal.signal(signal.SIGTERM, lambda *a: sys.exit(143)) # so the pid file is removed on kill
try:
run(args)
finally:
if os.path.exists(args.pid_file):
os.remove(args.pid_file)
def run(args):
from transformers import AutoTokenizer
domains = [d for d in args.domains.split(",") if d]
todo = [d for d in domains if not os.path.exists(os.path.join(args.out, f"stats_{d}.npz"))]
for d in domains:
if d not in todo:
log(f"{d}: stats_{d}.npz exists, skipped")
for d in todo:
if not os.path.exists(os.path.join(args.texts, f"{d}.jsonl")):
raise SystemExit(f"missing {args.texts}/{d}.jsonl")
if not todo:
return
torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained(args.tokenizer)
model, text_model = load_model(args)
rec = Recorder(text_model)
chunks_done, speed_s, speed_written = 0, 0.0, False
for d in todo:
windows = domain_windows(tok, os.path.join(args.texts, f"{d}.jsonl"), args.max_tokens_per_domain,
args.max_chunks) # fmt: skip
if windows.shape[0] == 0:
raise SystemExit(f"{d}: fewer than {WINDOW} tokens of text")
log(f"{d}: {windows.shape[0]} windows x {WINDOW} tokens")
rec.reset()
for c in range(windows.shape[0]):
t = time.time()
if chunks_done == 0:
rec.t6 = []
rec.forward(model, windows[c], c % 2)
if rec.t6 is not None:
check(args, rec.t6)
rec.t6 = None
chunks_done += 1
dt = time.time() - t
if chunks_done == 2:
speed_s = dt # chunk 1 is warm-up plus the T6 check
log(f"{d} chunk {c + 1}/{windows.shape[0]}: {WINDOW / dt:.0f} tok/s")
if chunks_done == 2 and not speed_written:
tps = WINDOW / speed_s
write_json(os.path.join(args.out, "record_speed.json"), {"tokens_per_s": tps, "chunks_timed": 1,
"domain": d, "note": "second chunk of this run; the first is warm-up plus T6"}) # fmt: skip
speed_written = True
log(f"record speed: {tps:.0f} tokens/s")
n_even, n_odd = (windows.shape[0] + 1) // 2, windows.shape[0] // 2
even, odd = rec.result(0), rec.result(1)
save_npz(os.path.join(args.out, f"stats_{d}_even.npz"), even, n_even * WINDOW)
save_npz(os.path.join(args.out, f"stats_{d}_odd.npz"), odd, n_odd * WINDOW)
save_npz(os.path.join(args.out, f"stats_{d}.npz"), even + odd, windows.shape[0] * WINDOW) # last: marks done
log(f"{d}: wrote stats_{d}.npz (+_even, _odd), {windows.shape[0] * WINDOW} tokens")
if not speed_written:
log("fewer than 2 chunks in this run: record_speed.json not written")
def check(args, visits):
worst = max(v["rel_err"] for v in visits)
ok = all(v["ok"] for v in visits)
write_json(os.path.join(args.out, "t6.json"), {"threshold": T6_TOL, "max_rel_err": worst, "pass": ok,
"visits": len(visits), "per_visit": visits}) # fmt: skip
log(f"T6: {len(visits)} layer visits, max relative error {worst:.5f} -> {'PASS' if ok else 'FAIL'}")
if not ok:
raise SystemExit("T6 failed: recorded expert outputs do not add up to the MoE output; see t6.json")
if __name__ == "__main__":
sys.exit(main())
|