Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-train/blob/main/tests/omegallm/oracle.py # aien-train AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-train / tests / omegallm / oracle.py` 1667 lines · 61637 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Omega LLM referee (aien-train#52): v0 (CONTRACT.md) and v1 (CONTRACT-V1.md). 3 4 Python 3 standard library only. Implements docs/omegallm/CONTRACT.md and CONTRACT-V1.md 5 independently of the .om product and cross-checks the `ollm` binary against it. Verification 6 only; never part of the build. 7 8 Usage: see tests/omegallm/ORACLE.md. 9 """ 10 11 import array 12 import hashlib 13 import contextlib 14 import json 15 import math 16 import os 17 import random 18 import re 19 import shutil 20 import struct 21 import subprocess 22 import sys 23 import tempfile 24 import time 25 from collections import Counter 26 from operator import mul 27 28 M64 = (1 << 64) - 1 29 GOLDEN = 0x9E3779B97F4A7C15 30 EPS_RMS = 1e-5 31 INIT_SCALE = 0.`034641016151377546` # Wolfram: N[0.02 Sqrt[3]] -> 0.`034641016151377546` 32 BETA1, BETA2, ADAM_EPS = 0.9, 0.99, 1e-8 33 FNV_OFFSET, FNV_PRIME = 0xCBF29CE484222325, 0x100000001B3 34 MAXS = {"V": 256, "T": 64, "D": 64, "H": 8, "F": 256, "L": 4, "B": 16} 35 SMALL = dict(V=256, T=8, D=16, H=2, F=32, L=2, B=2) 36 V0 = dict(V=256, T=64, D=64, H=4, F=256, L=2, B=16) 37 SEP = b"<|endoftext|>" 38 39 # Cross-check tolerance (see ORACLE.md "Tolerance"). Each entry error is 40 # |a-b| / max(|b|, FLOOR_FRAC * maxabs(tensor of b)), and must be <= RTOL. 41 RTOL = 1e-9 42 FLOOR_FRAC = 1e-3 43 44 45 46 @contextlib.contextmanager 47 def scratch(): 48 """A temporary directory, under $OLLM_TMP when it is set. The path is made relative to the 49 current directory there, so receipts that log commands name no absolute (private) path.""" 50 base = os.environ.get("OLLM_TMP") 51 if not base: 52 with tempfile.TemporaryDirectory() as d: 53 yield d 54 return 55 os.makedirs(base, exist_ok=True) 56 d = os.path.relpath(tempfile.mkdtemp(dir=base)) 57 try: 58 yield d 59 finally: 60 shutil.rmtree(d) 61 62 # ---------------------------------------------------------------- integers and hashes 63 64 def splitmix64(x): 65 z = (x + GOLDEN) & M64 66 z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M64 67 z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M64 68 return z ^ (z >> 31) 69 70 71 def fnv1a64(data): 72 h = FNV_OFFSET 73 for c in data: 74 h = ((h ^ c) * FNV_PRIME) & M64 75 return h 76 77 78 def f2bits(x): 79 return struct.unpack("= 0.5: 91 q += 1 if v > 0 else -1 92 return int(q) 93 94 95 # ---------------------------------------------------------------- layout 96 97 def tensor_specs(c): 98 V, T, D, F, L = c["V"], c["T"], c["D"], c["F"], c["L"] 99 specs = [("wte", V, D), ("wpe", T, D)] 100 for l in range(L): 101 specs += [("g1.%d" % l, 1, D), ("wq.%d" % l, D, D), ("wk.%d" % l, D, D), 102 ("wv.%d" % l, D, D), ("wo.%d" % l, D, D), ("g2.%d" % l, 1, D), 103 ("w1.%d" % l, D, F), ("w2.%d" % l, F, D)] 104 specs.append(("gf", 1, D)) 105 out, off = [], 0 106 for name, r, cc in specs: 107 out.append((name, off, r, cc)) 108 off += r * cc 109 return out 110 111 112 def param_count(c): 113 V, T, D, F, L = c["V"], c["T"], c["D"], c["F"], c["L"] 114 return V * D + T * D + L * (4 * D * D + 2 * D * F + 2 * D) + D 115 116 117 def unpack(c, flat): 118 t = {} 119 for name, off, r, cc in tensor_specs(c): 120 if name.startswith("g"): 121 t[name] = flat[off:off + cc] 122 else: 123 t[name] = [flat[off + i * cc: off + (i + 1) * cc] for i in range(r)] 124 return t 125 126 127 def pack(c, t): 128 flat = [] 129 for name, _, _, _ in tensor_specs(c): 130 v = t[name] 131 if name.startswith("g"): 132 flat.extend(v) 133 else: 134 for row in v: 135 flat.extend(row) 136 return flat 137 138 139 def zeros_like(c): 140 t = {} 141 for name, _, r, cc in tensor_specs(c): 142 t[name] = [0.0] * cc if name.startswith("g") else [[0.0] * cc for _ in range(r)] 143 return t 144 145 146 # ---------------------------------------------------------------- init (§5) 147 148 def init_params(c, seed): 149 L = c["L"] 150 scale_res = 1.0 / math.sqrt(2 * L) 151 flat = [] 152 for name, off, r, cc in tensor_specs(c): 153 base = name.split(".")[0] 154 for i in range(off, off + r * cc): 155 if base in ("g1", "g2", "gf"): 156 flat.append(1.0) 157 continue 158 ri = (splitmix64((seed + i) & M64) >> 11) * 2.0 ** -53 159 v = (2.0 * ri - 1.0) * INIT_SCALE 160 if base in ("wo", "w2"): 161 v = v * scale_res 162 flat.append(v) 163 return flat 164 165 166 # ---------------------------------------------------------------- files (§6) 167 168 def write_file(path, magic, c, seed, step, total, lr, payloads): 169 P = param_count(c) 170 body = b"".join(struct.pack("<%dd" % P, *p) for p in payloads) 171 hdr = magic + struct.pack("<7Q", *(c[k] for k in "VTDHFLB")) 172 hdr += struct.pack("<4Q", seed & M64, step, total, f2bits(lr)) + struct.pack(" MAXS[k] or v == 0: 198 raise FormatError("shape %s=%d out of range" % (k, v)) 199 if c["D"] % c["H"]: 200 raise FormatError("D not divisible by H") 201 if P != param_count(c): 202 raise FormatError("P=%d disagrees with shapes (%d)" % (P, param_count(c))) 203 if len(raw) != 112 + 8 * P * npay: 204 raise FormatError("length %d != %d" % (len(raw), 112 + 8 * P * npay)) 205 body = raw[112:] 206 if fnv1a64(body) != h: 207 raise FormatError("hash mismatch") 208 pays = [list(struct.unpack("<%dd" % P, body[8 * P * i: 8 * P * (i + 1)])) for i in range(npay)] 209 return dict(c=c, seed=seed, step=step, total=total, lr=bits2f(lrb), lr_bits=lrb, P=P, 210 hash=h, payloads=pays, raw=raw) 211 212 213 def write_ck(path, ck): 214 write_file(path, b"OLLMCK01", ck["c"], ck["seed"], ck["step"], ck["total"], ck["lr"], 215 [ck["params"], ck["m"], ck["v"]]) 216 217 218 def read_ck(path): 219 r = read_file(path, b"OLLMCK01", 3) 220 r["params"], r["m"], r["v"] = r.pop("payloads") 221 return r 222 223 224 def read_gr(path): 225 r = read_file(path, b"OLLMGR01", 1) 226 r["grad"] = r.pop("payloads")[0] 227 return r 228 229 230 # ---------------------------------------------------------------- model (§3) 231 232 def rms_fwd(v, g): 233 D = len(v) 234 den = math.sqrt(sum(map(mul, v, v)) / D + EPS_RMS) 235 return [v[i] / den * g[i] for i in range(D)], den 236 237 238 def rms_bwd(v, g, den, dy, dg): 239 D = len(v) 240 for i in range(D): 241 dg[i] += dy[i] * v[i] / den 242 s = sum(dy[i] * g[i] * v[i] for i in range(D)) 243 k = s / (D * den * den * den) 244 return [g[i] * dy[i] / den - v[i] * k for i in range(D)] 245 246 247 def transpose(W): 248 return [list(col) for col in zip(*W)] 249 250 251 def vecmat(x, WT): 252 """y = x . W with WT the transpose (columns of W).""" 253 return [sum(map(mul, x, col)) for col in WT] 254 255 256 def outer_acc(dW, x, dy): 257 for r, xr in enumerate(x): 258 if xr != 0.0: 259 row = dW[r] 260 dW[r] = [a + xr * b for a, b in zip(row, dy)] 261 262 263 def seq_loss_grad(c, P, PT, x, y, scale, G): 264 """Loss of one sequence; accumulates scale * d(loss)/d(params) into G (dict of tensors).""" 265 T, D, H, L, V = c["T"], c["D"], c["H"], c["L"], c["V"] 266 E = D // H 267 sE = math.sqrt(E) 268 rs = 1.0 / sE 269 wte, wpe = P["wte"], P["wpe"] 270 h = [[a + b for a, b in zip(wte[x[t]], wpe[t])] for t in range(T)] 271 caches = [] 272 for l in range(L): 273 g1, g2 = P["g1.%d" % l], P["g2.%d" % l] 274 hin = h 275 an = [rms_fwd(v, g1) for v in hin] 276 a = [p[0] for p in an] 277 q = [vecmat(r, PT["wq.%d" % l]) for r in a] 278 k = [vecmat(r, PT["wk.%d" % l]) for r in a] 279 u = [vecmat(r, PT["wv.%d" % l]) for r in a] 280 o = [[0.0] * D for _ in range(T)] 281 probs = [] 282 for n in range(H): 283 lo, hi = n * E, n * E + E 284 pn = [] 285 for t in range(T): 286 qt = q[t][lo:hi] 287 s = [sum(map(mul, qt, k[j][lo:hi])) / sE for j in range(t + 1)] 288 mx = max(s) 289 e = [math.exp(v - mx) for v in s] 290 z = sum(e) 291 p = [v / z for v in e] 292 pn.append(p) 293 ot = o[t] 294 for j in range(t + 1): 295 pj = p[j] 296 uj = u[j] 297 for i in range(lo, hi): 298 ot[i] += pj * uj[i] 299 probs.append(pn) 300 att = [vecmat(r, PT["wo.%d" % l]) for r in o] 301 h1 = [[a_ + b_ for a_, b_ in zip(hv, av)] for hv, av in zip(hin, att)] 302 bn = [rms_fwd(v, g2) for v in h1] 303 b = [p[0] for p in bn] 304 f = [vecmat(r, PT["w1.%d" % l]) for r in b] 305 rf = [[v if v > 0.0 else 0.0 for v in r] for r in f] 306 ff = [vecmat(r, PT["w2.%d" % l]) for r in rf] 307 h2 = [[a_ + b_ for a_, b_ in zip(hv, fv)] for hv, fv in zip(h1, ff)] 308 caches.append((hin, an, a, q, k, u, o, probs, h1, bn, b, f, rf)) 309 h = h2 310 gf = P["gf"] 311 zn = [rms_fwd(v, gf) for v in h] 312 loss = 0.0 313 dh = [] 314 dgf = G["gf"] 315 dwte = G["wte"] 316 for t in range(T): 317 z = zn[t][0] 318 lg = [sum(map(mul, z, wte[cc])) for cc in range(V)] 319 mx = max(lg) 320 e = [math.exp(v - mx) for v in lg] 321 se = sum(e) 322 loss += -(lg[y[t]] - mx - math.log(se)) 323 w = scale / T 324 dl = [ev / se * w for ev in e] 325 dl[y[t]] -= w 326 dz = [0.0] * D 327 for cc in range(V): 328 d = dl[cc] 329 row = wte[cc] 330 dz = [a_ + d * b_ for a_, b_ in zip(dz, row)] 331 dwte[cc] = [a_ + d * b_ for a_, b_ in zip(dwte[cc], z)] 332 dh.append(rms_bwd(h[t], gf, zn[t][1], dz, dgf)) 333 loss /= T 334 for l in range(L - 1, -1, -1): 335 hin, an, a, q, k, u, o, probs, h1, bn, b, f, rf = caches[l] 336 W = {n: P["%s.%d" % (n, l)] for n in ("wq", "wk", "wv", "wo", "w1", "w2")} 337 dW = {n: G["%s.%d" % (n, l)] for n in ("wq", "wk", "wv", "wo", "w1", "w2")} 338 g1, g2 = P["g1.%d" % l], P["g2.%d" % l] 339 dg1, dg2 = G["g1.%d" % l], G["g2.%d" % l] 340 dh1 = [] 341 for t in range(T): 342 d = dh[t] 343 outer_acc(dW["w2"], rf[t], d) 344 drf = [sum(map(mul, d, row)) for row in W["w2"]] 345 df = [dv if fv > 0.0 else 0.0 for dv, fv in zip(drf, f[t])] 346 outer_acc(dW["w1"], b[t], df) 347 db = [sum(map(mul, df, row)) for row in W["w1"]] 348 dr = rms_bwd(h1[t], g2, bn[t][1], db, dg2) 349 dh1.append([a_ + b_ for a_, b_ in zip(d, dr)]) 350 do = [] 351 for t in range(T): 352 outer_acc(dW["wo"], o[t], dh1[t]) 353 do.append([sum(map(mul, dh1[t], row)) for row in W["wo"]]) 354 dq = [[0.0] * D for _ in range(T)] 355 dk = [[0.0] * D for _ in range(T)] 356 du = [[0.0] * D for _ in range(T)] 357 for n in range(H): 358 lo, hi = n * E, n * E + E 359 for t in range(T): 360 p = probs[n][t] 361 dot = do[t][lo:hi] 362 dp = [sum(map(mul, dot, u[j][lo:hi])) for j in range(t + 1)] 363 for j in range(t + 1): 364 duj = du[j] 365 pj = p[j] 366 for i in range(lo, hi): 367 duj[i] += pj * do[t][i] 368 sdp = sum(map(mul, p, dp)) 369 ds = [p[j] * (dp[j] - sdp) * rs for j in range(t + 1)] 370 dqt = dq[t] 371 qt = q[t] 372 for j in range(t + 1): 373 dsj = ds[j] 374 kj = k[j] 375 dkj = dk[j] 376 for i in range(lo, hi): 377 dqt[i] += dsj * kj[i] 378 dkj[i] += dsj * qt[i] 379 dhin = [] 380 for t in range(T): 381 outer_acc(dW["wq"], a[t], dq[t]) 382 outer_acc(dW["wk"], a[t], dk[t]) 383 outer_acc(dW["wv"], a[t], du[t]) 384 da = [sum(map(mul, dq[t], r1)) + sum(map(mul, dk[t], r2)) + sum(map(mul, du[t], r3)) 385 for r1, r2, r3 in zip(W["wq"], W["wk"], W["wv"])] 386 dr = rms_bwd(hin[t], g1, an[t][1], da, dg1) 387 dhin.append([a_ + b_ for a_, b_ in zip(dh1[t], dr)]) 388 dh = dhin 389 for t in range(T): 390 G["wte"][x[t]] = [a_ + b_ for a_, b_ in zip(G["wte"][x[t]], dh[t])] 391 G["wpe"][t] = [a_ + b_ for a_, b_ in zip(G["wpe"][t], dh[t])] 392 return loss 393 394 395 def loss_and_grad(c, flat, seqs): 396 """seqs: list of (x, y). Returns (mean loss, flat gradient of the mean loss).""" 397 P = unpack(c, flat) 398 PT = {n: transpose(v) for n, v in P.items() if not n.startswith("g")} 399 G = zeros_like(c) 400 scale = 1.0 / len(seqs) 401 tot = 0.0 402 for x, y in seqs: 403 tot += seq_loss_grad(c, P, PT, x, y, scale, G) 404 return tot / len(seqs), pack(c, G) 405 406 407 def loss_only(c, flat, seqs): 408 return loss_and_grad(c, flat, seqs)[0] 409 410 411 # ---------------------------------------------------------------- data (§4) 412 413 def batch_offsets(seed, step, B, N, T): 414 return [splitmix64((seed ^ (((step * B + b) * GOLDEN) & M64)) & M64) % (N - T) 415 for b in range(B)] 416 417 418 def seqs_at(data, offs, T): 419 return [(list(data[o:o + T]), list(data[o + 1:o + T + 1])) for o in offs] 420 421 422 def prep(inp): 423 stories = [s.strip(b"\t\n\r ") for s in inp.split(SEP)] 424 stories = [s for s in stories if s] 425 train, held = bytearray(), bytearray() 426 nt = nh = 0 427 for i, s in enumerate(stories): 428 if i % 10 == 9: 429 held += s + b"\0" 430 nh += 1 431 else: 432 train += s + b"\0" 433 nt += 1 434 return bytes(train), bytes(held), (len(stories), nt, nh, len(train), len(held)) 435 436 437 def base(train, held): 438 N = len(train) 439 uni = Counter(train) 440 pair = Counter(zip(train, train[1:])) 441 rowtot = [0] * 256 442 for (a, _), n in pair.items(): 443 rowtot[a] += n 444 hpair = Counter(zip(held, held[1:])) 445 hn = len(held) - 1 446 ln2 = math.log(2.0) 447 su = sb = 0.0 448 for (a, b), n in hpair.items(): 449 su += n * -math.log((uni[b] + 1) / (N + 256)) / ln2 450 sb += n * -math.log((pair[(a, b)] + 1) / (rowtot[a] + 256)) / ln2 451 return su / hn, sb / hn 452 453 454 def eval_held(c, flat, held, W): 455 T = c["T"] 456 offs = [w * T for w in range(W)] 457 tot = 0.0 458 for o in offs: 459 tot += loss_only(c, flat, seqs_at(held, [o], T)) 460 return tot / W 461 462 463 # ---------------------------------------------------------------- optimizer (§5) 464 465 def lr_at(lr, s, total): 466 if s < 100: 467 return lr * (s + 1) / 100 468 return lr * (1 - 0.9 * (s - 100) / max(1, total - 100)) 469 470 471 def adam_step(ck, grad): 472 """Returns (new ck dict, info). Uses the pre-increment step s.""" 473 s = ck["step"] 474 g = list(grad) 475 n = math.sqrt(sum(v * v for v in g)) 476 clipped = n > 1.0 477 if clipped: 478 inv = 1.0 / n 479 g = [v * inv for v in g] 480 lrs = lr_at(ck["lr"], s, ck["total"]) 481 pw1 = pw2 = 1.0 482 for _ in range(s + 1): # agreed reading A3: powers by repeated multiplication 483 pw1 *= BETA1 484 pw2 *= BETA2 485 c1 = 1.0 - pw1 486 c2 = 1.0 - pw2 487 p2, m2, v2 = [], [], [] 488 for p, m, v, gi in zip(ck["params"], ck["m"], ck["v"], g): 489 m = BETA1 * m + (1 - BETA1) * gi 490 v = BETA2 * v + (1 - BETA2) * gi * gi 491 p = p - lrs * (m / c1) / (math.sqrt(v / c2) + ADAM_EPS) 492 p2.append(p) 493 m2.append(m) 494 v2.append(v) 495 out = dict(ck) 496 out.update(params=p2, m=m2, v=v2, step=s + 1) 497 return out, dict(norm=n, clipped=clipped, lr_s=lrs) 498 499 500 # ---------------------------------------------------------------- comparison helpers 501 502 def compare_flat(c, got, ref, rtol=RTOL): 503 """Per-tensor max mixed relative error; returns (ok, {tensor: (maxerr, argmax, got, ref)}).""" 504 res, ok = {}, True 505 for name, off, r, cc in tensor_specs(c): 506 seg_r = ref[off:off + r * cc] 507 seg_g = got[off:off + r * cc] 508 floor = FLOOR_FRAC * max(abs(v) for v in seg_r) 509 worst = (0.0, -1, 0.0, 0.0) 510 for i, (a, b) in enumerate(zip(seg_g, seg_r)): 511 den = max(abs(b), floor) 512 err = abs(a - b) / den if den > 0 else (0.0 if a == b else math.inf) 513 if not err <= worst[0] and not (err == 0.0 and worst[1] >= 0): 514 worst = (err, i, a, b) 515 if worst[1] < 0: 516 worst = (0.0, 0, seg_g[0], seg_r[0]) 517 res[name] = worst 518 if not worst[0] <= rtol: 519 ok = False 520 return ok, res 521 522 523 def fmt_tensor_errs(res): 524 return "\n".join(" %-6s maxerr %.3e at %d (got %.17g ref %.17g)" % (n, e, i, a, b) 525 for n, (e, i, a, b) in res.items()) 526 527 528 def max_err_by_base(res): 529 out = {} 530 for n, (e, *_) in res.items(): 531 k = n.split(".")[0] 532 out[k] = max(out.get(k, 0.0), e) 533 return out 534 535 536 # ---------------------------------------------------------------- selftest 537 538 def selftest(): 539 fails = [] 540 541 def check(cond, msg): 542 print(("PASS " if cond else "FAIL ") + msg) 543 if not cond: 544 fails.append(msg) 545 546 # Known answers, all computed with Wolfram (see ORACLE.md, query W1). 547 kat_fnv = {b"": 0xCBF29CE484222325, b"a": 0xAF63DC4C8601EC8C, 548 b"foobar": 0x85944171F73967E8, b"OLLMCK01": 0x29C48BB36358F164} 549 for k, v in kat_fnv.items(): 550 check(fnv1a64(k) == v, "fnv1a64(%r) = %016x" % (k, v)) 551 kat_sm = {0: 0xE220A8397B1DCDAF, 1: 0x910A2DEC89025CC1, M64: 0xE4D971771B652C20, 552 42: 0xBDD732262FEB6E95} 553 for k, v in kat_sm.items(): 554 check(splitmix64(k) == v, "splitmix64(%d) = %016x" % (k, v)) 555 # Batch rule: S=7, s=3, B=2, b=1 -> splitmix64(7 xor (7*G mod 2^64)) mod 1000 = 533 (Wolfram W1). 556 check(batch_offsets(7, 3, 2, 1000 + 8, 8)[1] == 533, "batch offset KAT 533") 557 # Init draw: (splitmix64(42+5) >> 11) = `4352384759967643` (Wolfram W1). 558 check(splitmix64(47) >> 11 == `4352384759967643`, "init draw KAT S=42 i=5") 559 c = SMALL 560 P = param_count(c) 561 check(P == 8400, "small P = 8400") 562 check(param_count(V0) == 119104, "v0 P = 119104") 563 flat = init_params(c, 42) 564 check(flat[5] == (2.0 * (`4352384759967643` * 2.0 ** -53) - 1.0) * INIT_SCALE, "init value i=5") 565 # checkpoint round trip 566 rng = random.Random(1) 567 ck = dict(c=dict(c), seed=42, step=3, total=50, lr=3e-3, params=flat, 568 m=[rng.uniform(-1, 1) for _ in range(P)], v=[rng.random() for _ in range(P)]) 569 with scratch() as d: 570 p = os.path.join(d, "ck") 571 write_ck(p, ck) 572 r = read_ck(p) 573 check(all(r[k] == ck[k] for k in ("seed", "step", "total", "lr", "params", "m", "v")) 574 and r["c"] == ck["c"] and not os.path.exists(p + ".tmp"), "checkpoint round trip") 575 raw = bytearray(r["raw"]) 576 raw[200] ^= 1 577 with open(p, "wb") as f: 578 f.write(raw) 579 try: 580 read_ck(p) 581 check(False, "hash mismatch refused") 582 except FormatError: 583 check(True, "hash mismatch refused") 584 # gradient vs central differences. Perturb params away from init so gains/ReLU are generic. 585 data = bytes(rng.randrange(1, 256) for _ in range(200)) 586 seqs = seqs_at(data, [5, 77], c["T"]) 587 pf = [v + rng.gauss(0, 0.3) for v in flat] 588 loss, g = loss_and_grad(c, pf, seqs) 589 check(math.isfinite(loss) and loss > 0, "loss finite %.6f" % loss) 590 hstep = 1e-5 591 worst = 0.0 592 for name, off, r, cc in tensor_specs(c): 593 n = r * cc 594 idxs = [off + rng.randrange(n) for _ in range(3)] 595 if name == "wte": 596 idxs.append(off + seqs[0][0][2] * cc + 1) # a row that is also an input 597 for i in idxs: 598 sv = pf[i] 599 pf[i] = sv + hstep 600 lp = loss_only(c, pf, seqs) 601 pf[i] = sv - hstep 602 lm = loss_only(c, pf, seqs) 603 pf[i] = sv 604 num = (lp - lm) / (2 * hstep) 605 err = abs(num - g[i]) / max(abs(g[i]), abs(num), 1e-6) 606 worst = max(worst, err) 607 check(err < 1e-5, "grad %-6s [%d] analytic %.10e numeric %.10e relerr %.2e" 608 % (name, i - off, g[i], num, err)) 609 print("selftest worst finite-difference relerr %.3e" % worst) 610 # adam: step 0 update equals -lr_0 * sign(g) up to eps for unclipped g. 611 ck0 = dict(c=dict(c), seed=1, step=0, total=10, lr=1e-2, params=[0.0] * P, 612 m=[0.0] * P, v=[0.0] * P) 613 gg = [1e-3] * P 614 n = math.sqrt(P) * 1e-3 615 ck1, info = adam_step(ck0, gg) 616 want = -1e-4 * 1e-3 / (1e-3 + ADAM_EPS) # lr_0 = lr/100; mhat = g, sqrt(vhat) = |g| 617 check(abs(ck1["params"][0] - want) < 1e-15 and not info["clipped"] and n < 1, 618 "adam step 0 = -lr/100 * g/(|g|+eps)") 619 ck1, info = adam_step(ck0, [1.0] * P) 620 check(info["clipped"] and abs(ck1["m"][0] - 0.1 / math.sqrt(P)) < 1e-15, "clip to norm 1") 621 # prep: separators, trimming, empty-story drop, i mod 10 == 9 to HELD, 0 terminators. 622 parts = [b" s%d\r\n" % i for i in range(11)] 623 parts.insert(3, b"\t \n") # empty after trim: dropped, does not count 624 tr, he, st = prep(SEP.join(parts)) 625 want_tr = b"".join(b"s%d\0" % i for i in range(11) if i != 9) 626 check(tr == want_tr and he == b"s9\0" and st == (11, 10, 1, len(want_tr), 3), "prep KAT") 627 # base: direct per-transition evaluation equals the counted form. 628 trn, hld = b"abcab\0aab\0", b"abz\0ba\0" 629 u, b = base(trn, hld) 630 N = len(trn) 631 pairs = list(zip(trn, trn[1:])) 632 ud = bd = 0.0 633 for a_, b_ in zip(hld, hld[1:]): 634 ud += -math.log2((trn.count(bytes([b_])) + 1) / (N + 256)) 635 row = [p for p in pairs if p[0] == a_] 636 bd += -math.log2((row.count((a_, b_)) + 1) / (len(row) + 256)) 637 check(abs(u - ud / 6) < 1e-12 and abs(b - bd / 6) < 1e-12, "base direct = counted") 638 print("SELFTEST %s (%d failures)" % ("PASS" if not fails else "FAIL", len(fails))) 639 return 0 if not fails else 1 640 641 642 # ---------------------------------------------------------------- cross-checks 643 644 def sha256_file(p): 645 h = hashlib.sha256() 646 with open(p, "rb") as f: 647 for blk in iter(lambda: f.read(1 << 20), b""): 648 h.update(blk) 649 return h.hexdigest() 650 651 652 class Receipt: 653 def __init__(self, check, binary): 654 self.r = dict(check=check, binary=binary, 655 binary_sha256=sha256_file(binary) if os.path.exists(binary) else None, 656 oracle_sha256=sha256_file(os.path.abspath(__file__)), 657 started=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), 658 affinity=sorted(os.sched_getaffinity(0)), nice=os.nice(0), 659 commands=[], results=[], verdict=None) 660 661 def run(self, argv): 662 t0 = time.monotonic() 663 p = subprocess.run(argv, capture_output=True) 664 dt = time.monotonic() - t0 665 rec = dict(argv=argv, rc=p.returncode, stdout=p.stdout.decode("latin-1"), 666 stderr=p.stderr.decode("latin-1")[-2000:], seconds=round(dt, 3)) 667 self.r["commands"].append(rec) 668 print("$ %s\n rc=%d %.2fs stdout=%r" % (" ".join(argv), p.returncode, dt, rec["stdout"][:300])) 669 if rec["stderr"]: 670 print(" stderr=%r" % rec["stderr"][:300]) 671 return rec 672 673 def result(self, name, ok, **kw): 674 kw.update(name=name, ok=ok) 675 self.r["results"].append(kw) 676 print(("PASS " if ok else "FAIL ") + name) 677 678 def finish(self, out): 679 ok = all(x["ok"] for x in self.r["results"]) and bool(self.r["results"]) 680 self.r["verdict"] = "PASS" if ok else "FAIL" 681 self.r["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) 682 if out: 683 os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True) 684 with open(out, "w") as f: 685 json.dump(self.r, f, indent=1) 686 print("%s %s" % (self.r["check"].upper(), self.r["verdict"])) 687 return 0 if ok else 1 688 689 690 def cfg_args(c): 691 return [str(c[k]) for k in "VTDHFLB"] 692 693 694 def make_ck(c, seed, total, lrmicro): 695 return dict(c=dict(c), seed=seed, step=0, total=total, lr=float(lrmicro) / `1000000`.0, 696 params=init_params(c, seed), m=[0.0] * param_count(c), v=[0.0] * param_count(c)) 697 698 699 def x_init(a): 700 R = Receipt("xinit", a.ollm) 701 c, seed, total, lrm = load_cfg(a.cfg), a.seed, 50, 3000 702 with scratch() as d: 703 ckp = os.path.join(d, "ck") 704 rec = R.run([a.ollm, "init", ckp] + cfg_args(c) + [str(seed), str(total), str(lrm)]) 705 P = param_count(c) 706 R.result("rc 0", rec["rc"] == 0, rc=rec["rc"]) 707 R.result("stdout 'I P'", rec["stdout"].split() == ["I", str(P)], stdout=rec["stdout"]) 708 if rec["rc"] != 0: 709 return R.finish(a.receipt) 710 got = read_ck(ckp) 711 ref = make_ck(c, seed, total, lrm) 712 diff = [i for i in range(P) if f2bits(got["params"][i]) != f2bits(ref["params"][i])] 713 R.result("params bit-identical", not diff, ndiff=len(diff), first=diff[:5]) 714 R.result("m, v zero", all(v == 0.0 for v in got["m"] + got["v"])) 715 R.result("header", got["c"] == c and got["seed"] == seed and got["step"] == 0 716 and got["total"] == total and got["P"] == P, 717 header=dict(c=got["c"], seed=got["seed"], step=got["step"], total=got["total"])) 718 lrb = f2bits(float(lrm) / `1000000`.0) # agreed reading A8: one f64 division 719 R.result("lr bits = 3000/1e6", got["lr_bits"] == lrb, 720 got="%016x" % got["lr_bits"], ref="%016x" % lrb) 721 refp = os.path.join(d, "ref") 722 write_ck(refp, ref) 723 R.result("whole file sha256 identical", sha256_file(refp) == sha256_file(ckp), 724 got=sha256_file(ckp), ref=sha256_file(refp)) 725 return R.finish(a.receipt) 726 727 728 def load_cfg(name): 729 return dict(SMALL if name == "small" else V0) 730 731 732 def synth_ck(c, seed, step, total, lr, scale): 733 """Init params plus seeded noise, nonzero m and v (exercises gains, clip and step>0 paths).""" 734 rng = random.Random(seed) 735 P = param_count(c) 736 p = [v + rng.gauss(0, scale) for v in init_params(c, seed)] 737 m = [rng.gauss(0, 1e-3) for _ in range(P)] 738 v = [rng.random() * 1e-5 for _ in range(P)] 739 return dict(c=dict(c), seed=seed, step=step, total=total, lr=lr, params=p, m=m, v=v) 740 741 742 def x_grad(a): 743 R = Receipt("xgrad", a.ollm) 744 c = load_cfg(a.cfg) 745 if a.batch: 746 c["B"] = a.batch 747 with open(a.data, "rb") as f: 748 data = f.read() 749 R.r["data"] = dict(path=a.data, sha256=hashlib.sha256(data).hexdigest(), bytes=len(data)) 750 with scratch() as d: 751 cases = [("init", make_ck(c, a.seed, 1000, 3000)), 752 ("perturbed", synth_ck(c, a.seed + 1, 7, 1000, 3e-3, 0.3))] 753 for label, ck in cases: 754 ckp = os.path.join(d, "ck." + label) 755 write_ck(ckp, ck) 756 offs = batch_offsets(ck["seed"], ck["step"], c["B"], len(data), c["T"]) 757 offp = os.path.join(d, "offs." + label) 758 with open(offp, "wb") as f: 759 f.write(struct.pack("<%dQ" % len(offs), *offs)) 760 outp = os.path.join(d, "gr." + label) 761 rec = R.run([a.ollm, "grad", ckp, a.data, offp, outp]) 762 t0 = time.monotonic() 763 loss, g = loss_and_grad(c, ck["params"], seqs_at(data, offs, c["T"])) 764 R.r.setdefault("oracle_seconds", {})[label] = round(time.monotonic() - t0, 2) 765 R.result(label + ": rc 0", rec["rc"] == 0, rc=rec["rc"], offsets=offs) 766 if rec["rc"] != 0: 767 continue 768 f_ = rec["stdout"].split() 769 ok = len(f_) == 3 and f_[0] == "G" 770 gl = bits2f(int(f_[1], 16)) if ok else math.nan 771 lerr = abs(gl - loss) / loss 772 R.result(label + ": loss", ok and lerr <= RTOL and int(f_[2]) == micro(loss), 773 got=gl, ref=loss, relerr=lerr, got_micro=f_[2] if ok else None, 774 ref_micro=micro(loss)) 775 gr = read_gr(outp) 776 R.result(label + ": OLLMGR01 header", gr["c"] == c and gr["step"] == c["B"] 777 and gr["seed"] == ck["seed"] and gr["total"] == ck["total"] 778 and gr["lr_bits"] == f2bits(ck["lr"]), 779 header=dict(c=gr["c"], step=gr["step"], seed=gr["seed"], total=gr["total"], 780 lr="%016x" % gr["lr_bits"])) 781 okg, res = compare_flat(c, gr["grad"], g) 782 print(fmt_tensor_errs(res)) 783 R.result(label + ": gradient (rtol %g)" % RTOL, okg, 784 max_err_per_tensor={n: e for n, (e, *_) in res.items()}, 785 max_err_by_kind=max_err_by_base(res), 786 grad_norm=math.sqrt(sum(v * v for v in g))) 787 return R.finish(a.receipt) 788 789 790 def x_step(a): 791 R = Receipt("xstep", a.ollm) 792 c = load_cfg(a.cfg) 793 with open(a.data, "rb") as f: 794 data = f.read() 795 R.r["data"] = dict(path=a.data, sha256=hashlib.sha256(data).hexdigest(), bytes=len(data)) 796 with scratch() as d: 797 small_gf = make_ck(c, a.seed + 1, 300, 3000) 798 small_gf["step"] = 2 799 _, off, _, cc = tensor_specs(c)[-1] 800 for i in range(off, off + cc): 801 small_gf["params"][i] = 0.1 # gf = 0.1 keeps the gradient norm below 1 (no clip) 802 # (label, checkpoint or None = the binary's previous output, clip expected) 803 cases = [("step0-init", make_ck(c, a.seed, 300, 3000), True), 804 ("step1-chain", None, True), 805 ("step2-unclipped", small_gf, False), 806 ("step150-synthetic-clip", synth_ck(c, a.seed + 2, 150, 300, 3e-3, 0.5), True)] 807 prev = None 808 for label, ck, want_clip in cases: 809 ckp = os.path.join(d, "ck." + label) 810 if ck is None and prev is None: 811 R.result(label + ": previous case produced no checkpoint", False) 812 continue 813 if ck is None: 814 # continue from the binary's own step-1 output (m, v nonzero, step 1) 815 ck = read_ck(prev) 816 ck["c"] = dict(ck["c"]) 817 write_ck(ckp, ck) 818 s = ck["step"] 819 offs = batch_offsets(ck["seed"], s, c["B"], len(data), c["T"]) 820 loss, g = loss_and_grad(c, ck["params"], seqs_at(data, offs, c["T"])) 821 ref, info = adam_step(ck, g) 822 R.result(label + ": covers clip=%s" % want_clip, info["clipped"] == want_clip, 823 norm=info["norm"]) 824 rec = R.run([a.ollm, "train", ckp, a.data, str(s + 1), "1"]) 825 R.result(label + ": rc 0", rec["rc"] == 0, rc=rec["rc"]) 826 if rec["rc"] != 0: 827 continue 828 want = ["T", str(s + 1), str(micro(loss))] 829 got_line = rec["stdout"].split() 830 R.result(label + ": stdout", got_line == want, got=got_line, want=want, 831 loss=loss, **info) 832 got = read_ck(ckp) 833 R.result(label + ": step", got["step"] == s + 1, got=got["step"]) 834 R.result(label + ": header unchanged", got["c"] == c and got["seed"] == ck["seed"] 835 and got["total"] == ck["total"] and got["lr_bits"] == f2bits(ck["lr"])) 836 for k in ("params", "m", "v"): 837 okk, res = compare_flat(c, got[k], ref[k]) 838 print(k) 839 print(fmt_tensor_errs(res)) 840 R.result("%s: %s (rtol %g)" % (label, k, RTOL), okk, 841 max_err_by_kind=max_err_by_base(res)) 842 prev = os.path.join(d, "keep.%s" % label) 843 os.rename(ckp, prev) 844 return R.finish(a.receipt) 845 846 847 def x_prep(a): 848 R = Receipt("xprep", a.ollm) 849 with open(a.data, "rb") as f: 850 inp = f.read() 851 R.r["data"] = dict(path=a.data, sha256=hashlib.sha256(inp).hexdigest(), bytes=len(inp)) 852 tr, he, st = prep(inp) 853 os.makedirs(a.outdir, exist_ok=True) 854 otr, ohe = os.path.join(a.outdir, "oracle-train.bin"), os.path.join(a.outdir, "oracle-held.bin") 855 for p, b in ((otr, tr), (ohe, he)): 856 with open(p, "wb") as f: 857 f.write(b) 858 btr, bhe = os.path.join(a.outdir, "ollm-train.bin"), os.path.join(a.outdir, "ollm-held.bin") 859 rec = R.run([a.ollm, "prep", a.data, btr, bhe]) 860 R.result("rc 0", rec["rc"] == 0, rc=rec["rc"]) 861 want = ["P"] + [str(v) for v in st] 862 R.result("stdout", rec["stdout"].split() == want, got=rec["stdout"].split(), want=want) 863 if rec["rc"] == 0: 864 for lab, o, b in (("TRAIN", otr, btr), ("HELD", ohe, bhe)): 865 so, sb = sha256_file(o), sha256_file(b) 866 R.result(lab + " sha256 identical", so == sb, oracle=so, ollm=sb, 867 bytes=os.path.getsize(o)) 868 return R.finish(a.receipt) 869 870 871 def x_base(a): 872 R = Receipt("xbase", a.ollm) 873 with open(a.train, "rb") as f: 874 tr = f.read() 875 with open(a.held, "rb") as f: 876 he = f.read() 877 R.r["data"] = dict(train=sha256_file(a.train), held=sha256_file(a.held)) 878 u, b = base(tr, he) 879 rec = R.run([a.ollm, "base", a.train, a.held]) 880 want = ["B", str(micro(u)), str(micro(b))] 881 R.result("rc 0", rec["rc"] == 0, rc=rec["rc"]) 882 R.result("stdout micro values", rec["stdout"].split() == want, got=rec["stdout"].split(), 883 want=want, uni_bpb=u, bi_bpb=b) 884 return R.finish(a.receipt) 885 886 887 def x_eval(a): 888 R = Receipt("xeval", a.ollm) 889 c = load_cfg(a.cfg) 890 with open(a.held, "rb") as f: 891 he = f.read() 892 with scratch() as d: 893 ck = synth_ck(c, a.seed + 3, 5, 100, 1e-3, 0.3) 894 ckp = os.path.join(d, "ck") 895 write_ck(ckp, ck) 896 W = 4 897 loss = eval_held(c, ck["params"], he, W) 898 rec = R.run([a.ollm, "eval", ckp, a.held, str(W)]) 899 want = ["E", "5", str(W), str(micro(loss)), str(micro(loss / math.log(2)))] 900 R.result("rc 0", rec["rc"] == 0, rc=rec["rc"]) 901 R.result("stdout", rec["stdout"].split() == want, got=rec["stdout"].split(), want=want, 902 loss=loss) 903 return R.finish(a.receipt) 904 905 906 # ---------------------------------------------------------------- v1 (CONTRACT-V1.md) 907 # 908 # `ollm` below emulates the product's v1 command line: same argv, stdout bytes, exit codes and 909 # output files. Tokenizer files and init are exact; model arithmetic is the v0 referee's 910 # (libm, its own summation order), compared with `cmp` at the v0 tolerance (CONTRACT-V1 §9.3). 911 912 # shape maxima: CONTRACT-V3 §1 (v1 with D 256 -> 384 and F 1024 -> 1536 in V2, L 8 -> 16 in V3) 913 MAXS2 = {"V": 4096, "T": 256, "D": 384, "H": 16, "F": 1536, "L": 16, "B": 64} 914 SMALL1 = dict(V=300, T=8, D=16, H=2, F=32, L=2, B=4) 915 LN2 = 0.`6931471805599453` 916 CK01, CK02, GR01, BPE1 = b"OLLMCK01", b"OLLMCK02", b"OLLMGR01", b"OLLMBPE1" 917 918 # Planted defects for negative controls (OLLM_ORACLE_MUTANT); each must turn a check to FAIL. 919 MUTANTS = { 920 "tiemaxa": "bpefit ties go to the largest a", 921 "chunk63": "long chunks are cut into 63-byte pieces", 922 "blockscale": "block gradients scaled by 1/(T*R) instead of 1/(T*B)", 923 "bpbv0": "eval at V > 256 prints the v0 bpb = loss/ln2", 924 } 925 926 927 def mutant(): 928 m = os.environ.get("OLLM_ORACLE_MUTANT", "") 929 if m and m not in MUTANTS: 930 raise SystemExit("unknown OLLM_ORACLE_MUTANT %r (known: %s)" % (m, ", ".join(MUTANTS))) 931 return m 932 933 934 class Refuse(Exception): 935 """A contract refusal: the product exits with this code.""" 936 937 def __init__(self, code): 938 super().__init__(code) 939 self.code = code 940 941 942 # ---- tokenizer (§2) 943 944 CHUNK_RE = re.compile(rb"[0-9A-Za-z\x80-\xff]+| [0-9A-Za-z\x80-\xff]+|[^0-9A-Za-z\x80-\xff]") 945 946 947 def text_parts(text, size=1 << 23): 948 """Slices of text that each end just after a byte 0 (a chunk boundary), about `size` long.""" 949 i, n = 0, len(text) 950 while i < n: 951 j = min(n, i + size) 952 if j < n: 953 k = text.rfind(b"\0", i, j) 954 if k < 0: 955 k = text.find(b"\0", j) 956 j = n if k < 0 else k + 1 957 yield text[i:j] 958 i = j 959 960 961 def chunks(text): 962 piece = 63 if mutant() == "chunk63" else 64 963 for part in text_parts(text): 964 for s in CHUNK_RE.findall(part): 965 if len(s) <= piece: 966 yield s 967 else: 968 for i in range(0, len(s), piece): 969 yield s[i:i + piece] 970 971 972 def merge_seq(t, a, b, new): 973 out, i, n = [], 0, len(t) 974 while i < n: 975 if i + 1 < n and t[i] == a and t[i + 1] == b: 976 out.append(new) 977 i += 2 978 else: 979 out.append(t[i]) 980 i += 1 981 return out 982 983 984 def fit_counts(cnt, nmerge): 985 """§2.2 on chunk-type counts; returns the merge pairs. Raises Refuse(28) when pairs run out.""" 986 toks = [list(s) for s in cnt] 987 ws = list(cnt.values()) 988 pc, where = Counter(), {} 989 for ti, t in enumerate(toks): 990 for p in zip(t, t[1:]): 991 pc[p] += ws[ti] 992 where.setdefault(p, set()).add(ti) 993 if mutant() == "tiemaxa": 994 key = lambda p: (pc[p], p[0], -p[1]) # noqa: E731 995 else: 996 key = lambda p: (pc[p], -p[0], -p[1]) # noqa: E731 997 merges = [] 998 for k in range(nmerge): 999 if not pc: 1000 raise Refuse(28) 1001 best = max(pc, key=key) 1002 a, b = best 1003 new = 256 + k 1004 for ti in where.pop(best): 1005 t, w = toks[ti], ws[ti] 1006 nt = merge_seq(t, a, b, new) 1007 if len(nt) == len(t): 1008 continue # stale index entry 1009 for p in zip(t, t[1:]): 1010 v = pc[p] - w 1011 if v: 1012 pc[p] = v 1013 else: 1014 del pc[p] 1015 for p in zip(nt, nt[1:]): 1016 pc[p] += w 1017 where.setdefault(p, set()).add(ti) 1018 toks[ti] = nt 1019 assert best not in pc 1020 merges.append(best) 1021 return merges 1022 1023 1024 def bpe_fit(text, V, maxbytes=None): 1025 """Returns (merges, types, chunks, fitbytes).""" 1026 if maxbytes is not None: 1027 pre = text[:maxbytes] 1028 k = pre.rfind(b"\0") 1029 if k < 0: 1030 raise Refuse(21) 1031 text = pre[:k + 1] 1032 cnt = Counter(chunks(text)) 1033 merges = fit_counts(cnt, V - 256) 1034 return merges, len(cnt), sum(cnt.values()), len(text) 1035 1036 1037 def merges_bytes(V, merges): 1038 body = struct.pack("<%dH" % (2 * len(merges)), *[x for p in merges for x in p]) 1039 return BPE1 + struct.pack(" 4096 or len(raw) != 24 + 4 * (Vm - 256) or fnv1a64(raw[24:]) != h: 1050 raise Refuse(26) 1051 ab = struct.unpack("<%dH" % (2 * (Vm - 256)), raw[24:]) 1052 merges = list(zip(ab[0::2], ab[1::2])) 1053 for k, (a, b) in enumerate(merges): 1054 if a >= 256 + k or b >= 256 + k: 1055 raise Refuse(26) 1056 V = Vm if V is None else V 1057 if V > Vm: 1058 raise Refuse(27) 1059 return Vm, merges[:max(0, V - 256)] 1060 1061 1062 class BPE: 1063 def __init__(self, merges): 1064 self.rank = {} 1065 for k, p in enumerate(merges): 1066 self.rank.setdefault(p, k) 1067 self.dec = [bytes([i]) for i in range(256)] 1068 for a, b in merges: 1069 self.dec.append(self.dec[a] + self.dec[b]) 1070 self.V = 256 + len(merges) 1071 self.cache = {} 1072 1073 def enc_chunk(self, s): 1074 """Merges in rank order. Equal to applying k = 0, 1, ... in turn: a merge only creates 1075 pairs holding the new token 256+k, and those pairs have ranks above k.""" 1076 t, rank = list(s), self.rank 1077 while len(t) > 1: 1078 br = None 1079 for p in zip(t, t[1:]): 1080 r = rank.get(p) 1081 if r is not None and (br is None or r < br): 1082 br, best = r, p 1083 if br is None: 1084 break 1085 t = merge_seq(t, best[0], best[1], 256 + br) 1086 return t 1087 1088 def encode(self, text): 1089 out, cache = array.array("H"), self.cache 1090 for s in chunks(text): 1091 t = cache.get(s) 1092 if t is None: 1093 t = cache[s] = self.enc_chunk(s) 1094 out.extend(t) 1095 return out 1096 1097 def tlen(self, t): 1098 return len(self.dec[t]) 1099 1100 def decode(self, toks): 1101 if toks and max(toks) >= self.V: 1102 raise Refuse(25) 1103 return b"".join(self.dec[t] for t in toks) 1104 1105 1106 def tok_bytes(toks): 1107 a = array.array("H", toks) 1108 if sys.byteorder != "little": 1109 a.byteswap() 1110 return a.tobytes() 1111 1112 1113 def read_tokens(path): 1114 with open(path, "rb") as f: 1115 raw = f.read() 1116 if len(raw) % 2: 1117 raise Refuse(21) 1118 a = array.array("H") 1119 a.frombytes(raw) 1120 if sys.byteorder != "little": 1121 a.byteswap() 1122 return a 1123 1124 1125 def write_atomic(path, data): 1126 tmp = path + ".tmp" 1127 with open(tmp, "wb") as f: 1128 f.write(data) 1129 os.rename(tmp, path) 1130 1131 1132 # ---- checkpoints (§6) 1133 1134 def ck1_bytes(ck): 1135 c, P = ck["c"], param_count(ck["c"]) 1136 body = b"".join(struct.pack("<%dd" % P, *ck[k]) for k in ("params", "m", "v")) 1137 hdr = ck["magic"] + struct.pack("<7Q", *(c[k] for k in "VTDHFLB")) 1138 hdr += struct.pack("<5Q", ck["seed"] & M64, ck["step"], ck["total"], ck["lr_bits"], P) 1139 if ck["magic"] == CK02: 1140 hdr += struct.pack("= 256 1146 and c["D"] % c["H"] == 0) 1147 1148 1149 def read_ck1(path): 1150 """CK01 or CK02 at v1 shapes, with the refusal codes 10-15 (Refuse).""" 1151 with open(path, "rb") as f: 1152 raw = f.read() 1153 if len(raw) < 112: 1154 raise Refuse(10) 1155 magic = raw[:8] 1156 if magic not in (CK01, CK02): 1157 raise Refuse(11) 1158 hl = 120 if magic == CK02 else 112 1159 if len(raw) < hl: 1160 raise Refuse(10) 1161 c = dict(zip("VTDHFLB", struct.unpack("<7Q", raw[8:64]))) 1162 seed, step, total, lrb, P = struct.unpack("<5Q", raw[64:104]) 1163 G = struct.unpack(" 999999 or G == 0 or G > c["B"] or c["B"] % G: 1165 raise Refuse(12) 1166 if P != param_count(c): 1167 raise Refuse(13) 1168 if len(raw) < hl + 24 * P: 1169 raise Refuse(10) 1170 if len(raw) > hl + 24 * P: 1171 raise Refuse(15) 1172 body = raw[hl:] 1173 if fnv1a64(body) != struct.unpack("= V is exit 25 only in a row actually read.""" 1219 T, out = c["T"], [] 1220 for o in offs: 1221 w = list(data[o:o + T + 1]) 1222 if max(w) >= c["V"]: 1223 raise Refuse(25) 1224 out.append((w[:T], w[1:])) 1225 return out 1226 1227 1228 def prepared(c, flat): 1229 Pd = unpack(c, flat) 1230 return Pd, {n: transpose(v) for n, v in Pd.items() if not n.startswith("g")} 1231 1232 1233 def grad_blocks(c, flat, seqs, G): 1234 """§5: G blocks of R = B/G sequences, each into its own buffer; blocks summed in ascending j; 1235 losses summed in ascending b and divided by B.""" 1236 B = len(seqs) 1237 R = B // G 1238 Pd, PT = prepared(c, flat) 1239 scale = 1.0 / (R if mutant() == "blockscale" else B) 1240 losses, acc = [], None 1241 for j in range(G): 1242 Gj = zeros_like(c) 1243 for x, y in seqs[j * R:(j + 1) * R]: 1244 losses.append(seq_loss_grad(c, Pd, PT, x, y, scale, Gj)) 1245 fj = pack(c, Gj) 1246 acc = fj if acc is None else [a + b for a, b in zip(acc, fj)] 1247 tot = 0.0 1248 for v in losses: 1249 tot += v 1250 return tot / B, acc 1251 1252 1253 def logits_last(c, Pd, PT, x): 1254 """Forward over a context of len(x) <= T positions; the logits at the last one.""" 1255 D, H, L, V = c["D"], c["H"], c["L"], c["V"] 1256 E = D // H 1257 sE = math.sqrt(E) 1258 n = len(x) 1259 wte, wpe = Pd["wte"], Pd["wpe"] 1260 h = [[a + b for a, b in zip(wte[x[t]], wpe[t])] for t in range(n)] 1261 for l in range(L): 1262 g1, g2 = Pd["g1.%d" % l], Pd["g2.%d" % l] 1263 a = [rms_fwd(v, g1)[0] for v in h] 1264 q = [vecmat(r, PT["wq.%d" % l]) for r in a] 1265 k = [vecmat(r, PT["wk.%d" % l]) for r in a] 1266 u = [vecmat(r, PT["wv.%d" % l]) for r in a] 1267 o = [[0.0] * D for _ in range(n)] 1268 for hh in range(H): 1269 lo, hi = hh * E, hh * E + E 1270 for t in range(n): 1271 s = [sum(map(mul, q[t][lo:hi], k[j][lo:hi])) / sE for j in range(t + 1)] 1272 mx = max(s) 1273 e = [math.exp(v - mx) for v in s] 1274 z = sum(e) 1275 for j in range(t + 1): 1276 pj = e[j] / z 1277 for i in range(lo, hi): 1278 o[t][i] += pj * u[j][i] 1279 att = [vecmat(r, PT["wo.%d" % l]) for r in o] 1280 h1 = [[a_ + b_ for a_, b_ in zip(hv, av)] for hv, av in zip(h, att)] 1281 b = [rms_fwd(v, g2)[0] for v in h1] 1282 f = [[v if v > 0.0 else 0.0 for v in vecmat(r, PT["w1.%d" % l])] for r in b] 1283 ff = [vecmat(r, PT["w2.%d" % l]) for r in f] 1284 h = [[a_ + b_ for a_, b_ in zip(hv, fv)] for hv, fv in zip(h1, ff)] 1285 z = rms_fwd(h[-1], Pd["gf"])[0] 1286 return [sum(map(mul, z, wte[cc])) for cc in range(V)] 1287 1288 1289 def sample_v1(ck, seed, N, tm, prompt, bpe): 1290 c = ck["c"] 1291 T = c["T"] 1292 ctx = [0] + (list(prompt) if bpe is None else list(bpe.encode(prompt))) 1293 ctx = ctx[-T:] 1294 Pd, PT = prepared(c, ck["params"]) 1295 st, out = seed & M64, bytearray() 1296 for _ in range(N): 1297 lg = logits_last(c, Pd, PT, ctx) 1298 if tm == 0: 1299 k = max(range(len(lg)), key=lambda i: (lg[i], -i)) 1300 else: 1301 tau = tm / 1000.0 1302 xs = [v / tau for v in lg] 1303 mx = max(xs) 1304 e = [math.exp(v - mx) for v in xs] 1305 se = sum(e) 1306 p = [v / se for v in e] 1307 u = (splitmix64(st) >> 11) * 2.0 ** -53 1308 st = (st + GOLDEN) & M64 1309 acc, k = 0.0, None 1310 for i, pi in enumerate(p): 1311 acc += pi 1312 if u < acc: 1313 k = i 1314 break 1315 if k is None: 1316 k = max(i for i, pi in enumerate(p) if pi > 0.0) 1317 if k == 0: 1318 break 1319 out += bytes([k]) if bpe is None else bpe.dec[k] 1320 ctx = (ctx + [k])[-T:] 1321 return bytes(out) 1322 1323 1324 # ---- the v1 command line, emulated 1325 1326 def _ints(args): 1327 try: 1328 v = [int(a) for a in args] 1329 except ValueError: 1330 raise Refuse(2) 1331 if any(x < 0 for x in v): 1332 raise Refuse(2) 1333 return v 1334 1335 1336 def ollm(argv, out): 1337 """Run one product command; writes stdout bytes to `out`; returns the exit code.""" 1338 try: 1339 _ollm(argv, out) 1340 return 0 1341 except Refuse as r: 1342 return r.code 1343 1344 1345 def _ollm(argv, out): 1346 if not argv: 1347 raise Refuse(2) 1348 cmd, a = argv[0], argv[1:] 1349 if cmd == "prep" and len(a) == 3: 1350 with open(a[0], "rb") as f: 1351 tr, he, st = prep(f.read()) 1352 for p_, b_ in ((a[1], tr), (a[2], he)): 1353 with open(p_, "wb") as f: 1354 f.write(b_) 1355 out.write(b"P %d %d %d %d %d\n" % st) 1356 elif cmd == "bpefit" and len(a) in (3, 4): 1357 (V,) = _ints(a[2:3]) 1358 mb = _ints(a[3:4])[0] if len(a) == 4 else None 1359 if V < 257 or V > 4096: 1360 raise Refuse(2) 1361 with open(a[0], "rb") as f: 1362 text = f.read() 1363 merges, types, nch, nb = bpe_fit(text, V, mb) 1364 write_atomic(a[1], merges_bytes(V, merges)) 1365 out.write(b"M %d %d %d %d\n" % (V, types, nch, nb)) 1366 elif cmd == "bpeenc" and len(a) == 4: 1367 (V,) = _ints(a[1:2]) 1368 _, merges = load_merges(a[0], V) 1369 if V <= 256: 1370 raise Refuse(27) 1371 with open(a[2], "rb") as f: 1372 text = f.read() 1373 toks = BPE(merges).encode(text) 1374 with open(a[3], "wb") as f: 1375 f.write(tok_bytes(toks)) 1376 out.write(b"K %d %d\n" % (len(text), len(toks))) 1377 elif cmd == "bpedec" and len(a) == 3: 1378 _, merges = load_merges(a[0]) 1379 toks = read_tokens(a[1]) 1380 data = BPE(merges).decode(toks) 1381 with open(a[2], "wb") as f: 1382 f.write(data) 1383 out.write(b"D %d %d\n" % (len(toks), len(data))) 1384 elif cmd == "init" and len(a) in (11, 12): 1385 v = _ints(a[1:]) 1386 c = dict(zip("VTDHFLB", v[:7])) 1387 seed, total, lrm = v[7:10] 1388 G = v[10] if len(a) == 12 else 1 1389 if not shapes_ok(c) or total > 999999 or G == 0 or G > c["B"] or c["B"] % G: 1390 raise Refuse(12) 1391 P = param_count(c) 1392 ck = dict(magic=CK02 if len(a) == 12 else CK01, c=c, seed=seed, step=0, total=total, 1393 lr_bits=f2bits(float(lrm) / `1000000`.0), G=G, params=init_params(c, seed), 1394 m=[0.0] * P, v=[0.0] * P) 1395 write_atomic(a[0], ck1_bytes(ck)) 1396 out.write(b"I %d\n" % P) 1397 elif cmd == "grad" and len(a) == 4: 1398 ck = read_ck1(a[0]) 1399 c = ck["c"] 1400 data = load_data(a[1], c) 1401 with open(a[2], "rb") as f: 1402 raw = f.read() 1403 if len(raw) != 8 * c["B"]: 1404 raise Refuse(21) 1405 offs = struct.unpack("<%dQ" % c["B"], raw) 1406 if any(o >= len(data) - c["T"] for o in offs): 1407 raise Refuse(22) 1408 loss, g = grad_blocks(c, ck["params"], seqs_v1(data, offs, c), ck["G"]) 1409 write_atomic(a[3], gr1_bytes(ck, g)) 1410 out.write(b"G %016x %d\n" % (f2bits(loss), micro(loss))) 1411 elif cmd == "train" and len(a) in (4, 5): 1412 ck = read_ck1(a[0]) 1413 c = ck["c"] 1414 until, every = _ints(a[2:4]) 1415 K = _ints(a[4:5])[0] if len(a) == 5 else 1 1416 if every == 0: 1417 raise Refuse(2) 1418 if K < 1 or K > ck["G"] or ck["G"] % K: 1419 raise Refuse(29) 1420 data = load_data(a[1], c) 1421 end = min(until, ck["total"]) 1422 while ck["step"] < end: 1423 s = ck["step"] 1424 offs = batch_offsets(ck["seed"], s, c["B"], len(data), c["T"]) 1425 loss, g = grad_blocks(c, ck["params"], seqs_v1(data, offs, c), ck["G"]) 1426 nk, _ = adam_step(ck, g) 1427 ck.update(params=nk["params"], m=nk["m"], v=nk["v"], step=s + 1) 1428 if (s + 1) % every == 0 or s + 1 == end: 1429 write_atomic(a[0], ck1_bytes(ck)) 1430 out.write(b"T %d %d\n" % (s + 1, micro(loss))) 1431 elif cmd == "eval" and len(a) in (3, 4): 1432 ck = read_ck1(a[0]) 1433 c = ck["c"] 1434 (W,) = _ints(a[2:3]) 1435 if c["V"] > 256 and len(a) == 3: 1436 raise Refuse(2) 1437 bpe = BPE(load_merges(a[3], c["V"])[1]) if c["V"] > 256 else None 1438 data = load_data(a[1], c) 1439 T = c["T"] 1440 if W == 0 or W * T + 1 > len(data): 1441 raise Refuse(23) 1442 tot = 0.0 1443 nbytes = 0 1444 for w in range(W): 1445 seqs = seqs_v1(data, [w * T], c) 1446 tot += loss_only(c, ck["params"], seqs) 1447 if bpe is not None: 1448 nbytes += sum(bpe.tlen(y) for y in seqs[0][1]) 1449 loss = tot / W 1450 if bpe is None or mutant() == "bpbv0": 1451 bpb = loss / LN2 1452 else: 1453 bpb = ((loss / LN2) * float(W * T)) / float(nbytes) 1454 out.write(b"E %d %d %d %d\n" % (ck["step"], W, micro(loss), micro(bpb))) 1455 elif cmd == "sample" and len(a) in (5, 6): 1456 ck = read_ck1(a[0]) 1457 c = ck["c"] 1458 seed, N, tm = _ints(a[1:4]) 1459 prompt = os.fsencode(a[4]) 1460 if N > 999999: 1461 raise Refuse(2) 1462 if c["V"] > 256: 1463 if len(a) == 5 or len(prompt) > 4000: 1464 raise Refuse(2) 1465 bpe = BPE(load_merges(a[5], c["V"])[1]) 1466 else: 1467 if len(prompt) > 4096: 1468 raise Refuse(2) 1469 bpe = None 1470 out.write(sample_v1(ck, seed, N, tm, prompt, bpe)) 1471 else: 1472 raise Refuse(2) 1473 1474 1475 # ---- comparison of product files against referee files (§9.3 standard) 1476 1477 def cmp_v1(kind, got, ref): 1478 """ck: header fields exact, params/m/v per entry within RTOL. gr: header exact, grad within 1479 RTOL. tok/bytes: exact bytes, first differing offset. Prints one verdict line; 0 = PASS.""" 1480 if kind in ("tok", "bytes"): 1481 with open(got, "rb") as f: 1482 g = f.read() 1483 with open(ref, "rb") as f: 1484 r = f.read() 1485 if g == r: 1486 print("PASS %s identical (%d bytes)" % (kind, len(g))) 1487 return 0 1488 i = next((i for i in range(min(len(g), len(r))) if g[i] != r[i]), min(len(g), len(r))) 1489 print("FAIL %s first difference at byte %d (got %d bytes, ref %d bytes)" 1490 % (kind, i, len(g), len(r))) 1491 return 1 1492 try: 1493 if kind == "gline": 1494 # `G hex micro`: micro exact, the loss within RTOL (its bits are not required equal) 1495 g, r = [open(p, "rb").read().split() for p in (got, ref)] 1496 ok = (len(g) == len(r) == 3 and g[0] == r[0] == b"G" and g[2] == r[2] 1497 and len(g[1]) == 16) 1498 if ok: 1499 lg, lr = bits2f(int(g[1], 16)), bits2f(int(r[1], 16)) 1500 ok = abs(lg - lr) <= RTOL * abs(lr) 1501 print("%s gline got %r ref %r" % ("PASS" if ok else "FAIL", g, r)) 1502 return 0 if ok else 1 1503 if kind == "ck": 1504 G, R = read_ck1(got), read_ck1(ref) 1505 hoff, pays = G["hl"] - 8, ("params", "m", "v") 1506 else: 1507 G, R = read_gr1(got), read_gr1(ref) 1508 hoff, pays = 104, ("grad",) 1509 except (Refuse, FormatError, ValueError, OSError) as e: 1510 print("FAIL %s unreadable: %r" % (kind, e)) 1511 return 1 1512 ok = True 1513 if G["raw"][:hoff] != R["raw"][:hoff]: 1514 i = next(i for i in range(hoff) if G["raw"][i] != R["raw"][i]) 1515 print("FAIL %s header field differs at byte %d" % (kind, i)) 1516 ok = False 1517 for k in pays: 1518 okk, res = compare_flat(G["c"], G[k], R[k]) 1519 worst = max(e for e, *_ in res.values()) 1520 print(" %s %s max relerr %.3e" % (kind, k, worst)) 1521 if not okk: 1522 print(fmt_tensor_errs({n: v for n, v in res.items() if not v[0] <= RTOL})) 1523 ok = False 1524 print("%s %s (header exact, rtol %g)" % ("PASS" if ok else "FAIL", kind, RTOL)) 1525 return 0 if ok else 1 1526 1527 1528 def selftest_v1(): 1529 fails = [] 1530 1531 def check(cond, msg): 1532 print(("PASS " if cond else "FAIL ") + msg) 1533 if not cond: 1534 fails.append(msg) 1535 1536 # §2.1 chunk rule 1537 t = b"Hi there,\nyou 3x" + bytes([0xC3, 0xA9]) + b"! " + b"a" * 130 + b" \0" 1538 want = [b"Hi", b" ", b" there", b",", b"\n", b"you", b" 3x\xc3\xa9", b"!", b" " + b"a" * 63, 1539 b"a" * 64, b"aaa", b" ", b"\0"] 1540 check(list(chunks(t)) == want, "chunk rule KAT") 1541 # §2.2 overlapping counts and the tie rule: "aaa" holds (a,a) twice -> it beats (b,c) x1 1542 m = fit_counts(Counter({b"aaa": 1, b"bc": 1}), 1) 1543 check(m == [(97, 97)], "overlapping count (a,a)=2") 1544 m = fit_counts(Counter({b"cd": 1, b"ab": 1, b"ae": 1}), 3) 1545 check(m == [(97, 98), (97, 101), (99, 100)], "tie: smallest a, then smallest b") 1546 try: 1547 fit_counts(Counter({b"ab": 1}), 2) 1548 check(False, "exit 28 when pairs run out") 1549 except Refuse as r: 1550 check(r.code == 28, "exit 28 when pairs run out") 1551 # encode = merges applied in order; decode inverts 1552 text = b"the cat sat on the mat\0the hat\0" * 3 + bytes(range(1, 256)) 1553 merges, *_ = bpe_fit(text, 270) 1554 bpe = BPE(merges) 1555 toks = bpe.encode(text) 1556 seq = [] 1557 for s in chunks(text): 1558 t = list(s) 1559 for k, (a, b) in enumerate(merges): 1560 t = merge_seq(t, a, b, 256 + k) 1561 seq += t 1562 check(list(toks) == seq, "rank-order encode = sequential merges") 1563 check(bpe.decode(toks) == text, "decode(encode(text)) == text") 1564 with scratch() as d: 1565 p = os.path.join(d, "m") 1566 write_atomic(p, merges_bytes(270, merges)) 1567 check(load_merges(p, 260)[1] == merges[:4], "merges round trip, prefix use") 1568 raw = bytearray(open(p, "rb").read()) 1569 raw[30] ^= 1 1570 open(p, "wb").write(raw) 1571 try: 1572 load_merges(p) 1573 check(False, "merges hash refused 26") 1574 except Refuse as r: 1575 check(r.code == 26, "merges hash refused 26") 1576 # CK02 round trip and G=2 blocks equal G=1 within RTOL 1577 c = dict(SMALL1) 1578 P = param_count(c) 1579 rng = random.Random(3) 1580 ck = dict(magic=CK02, c=c, seed=9, step=4, total=50, lr_bits=f2bits(3e-3), G=2, 1581 params=init_params(c, 9), m=[rng.random() for _ in range(P)], 1582 v=[rng.random() for _ in range(P)]) 1583 with scratch() as d: 1584 p = os.path.join(d, "ck") 1585 write_atomic(p, ck1_bytes(ck)) 1586 r = read_ck1(p) 1587 check(r["G"] == 2 and r["params"] == ck["params"] and r["v"] == ck["v"] 1588 and len(r["raw"]) == 120 + 24 * P, "CK02 round trip") 1589 data = [rng.randrange(1, 300) for _ in range(200)] 1590 seqs = seqs_v1(data, [3, 50, 90, 130], c) 1591 l1, g1 = grad_blocks(c, ck["params"], seqs, 1) 1592 l2, g2 = grad_blocks(c, ck["params"], seqs, 2) 1593 ok, res = compare_flat(c, g2, g1) 1594 check(ok and abs(l1 - l2) <= RTOL * l1, "G=2 gradient = G=1 within rtol") 1595 print("SELFTEST-V1 %s (%d failures)" % ("PASS" if not fails else "FAIL", len(fails))) 1596 return 0 if not fails else 1 1597 1598 1599 # ---------------------------------------------------------------- CLI 1600 1601 def main(argv): 1602 import argparse 1603 ap = argparse.ArgumentParser(prog="oracle.py") 1604 sp = ap.add_subparsers(dest="cmd", required=True) 1605 sp.add_parser("selftest") 1606 sp.add_parser("selftest-v1") 1607 p = sp.add_parser("ollm", help="emulate the v1 product command line") 1608 p.add_argument("argv", nargs=argparse.REMAINDER) 1609 p = sp.add_parser("cmp", help="compare a product file with a referee file") 1610 p.add_argument("kind", choices=("ck", "gr", "gline", "tok", "bytes")) 1611 p.add_argument("got") 1612 p.add_argument("ref") 1613 for name in ("xinit", "xgrad", "xstep", "xprep", "xbase", "xeval"): 1614 p = sp.add_parser(name) 1615 p.add_argument("--ollm", required=True) 1616 p.add_argument("--receipt") 1617 p.add_argument("--seed", type=int, default=42) 1618 if name in ("xgrad", "xstep", "xprep"): 1619 p.add_argument("--data", required=True) 1620 if name in ("xinit", "xgrad", "xstep", "xeval"): 1621 p.add_argument("--cfg", choices=("small", "v0"), default="small") 1622 if name == "xgrad": 1623 p.add_argument("--batch", type=int, help="override B") 1624 if name == "xprep": 1625 p.add_argument("--outdir", required=True) 1626 if name == "xbase": 1627 p.add_argument("--train", required=True) 1628 if name in ("xbase", "xeval"): 1629 p.add_argument("--held", required=True) 1630 p = sp.add_parser("prep") 1631 p.add_argument("inp"); p.add_argument("train"); p.add_argument("held") 1632 p = sp.add_parser("base") 1633 p.add_argument("train"); p.add_argument("held") 1634 a = ap.parse_args(argv) 1635 if a.cmd == "selftest": 1636 return selftest() 1637 if a.cmd == "selftest-v1": 1638 return selftest_v1() 1639 if a.cmd == "ollm": 1640 mutant() 1641 rc = ollm(a.argv, sys.stdout.buffer) 1642 sys.stdout.buffer.flush() 1643 return rc 1644 if a.cmd == "cmp": 1645 return cmp_v1(a.kind, a.got, a.ref) 1646 if a.cmd == "prep": 1647 with open(a.inp, "rb") as f: 1648 tr, he, st = prep(f.read()) 1649 for p_, b_ in ((a.train, tr), (a.held, he)): 1650 with open(p_, "wb") as f: 1651 f.write(b_) 1652 print("P %d %d %d %d %d" % st) 1653 return 0 1654 if a.cmd == "base": 1655 with open(a.train, "rb") as f: 1656 tr = f.read() 1657 with open(a.held, "rb") as f: 1658 he = f.read() 1659 u, b = base(tr, he) 1660 print("B %d %d" % (micro(u), micro(b))) 1661 return 0 1662 return dict(xinit=x_init, xgrad=x_grad, xstep=x_step, xprep=x_prep, xbase=x_base, 1663 xeval=x_eval)[a.cmd](a) 1664 1665 1666 if __name__ == "__main__": 1667 sys.exit(main(sys.argv[1:]))