omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tests / test_reversible.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Pillar 2 (Reversible Residual Blocks) pure-Python-stdlib f64 oracle & test suite. |
| 3 | |
| 4 | Verifies `native/rev.om` across: |
| 5 | 1. Compilation with `native/{math,data,lpool,model,adam,ckpt,bpe,mio/lio,nogpu}.om` |
| 6 | for both `target a64macos` (OM-1 & OM-2) and `gb10` (Linux AArch64 OM-2). |
| 7 | 2. Built-in `rev_selftest` and `mode0` (model.om pool integration). |
| 8 | 3. Algebraic inverse reconstruction error < 1e-12 across L layers & looped cores. |
| 9 | 4. Analytical vs central finite-difference gradient check < 1e-8 across all tensor kinds. |
| 10 | 5. Zero-activation-buffer (`rev_act_bytes_used == 0`) training equivalence vs |
| 11 | cached-activation Python `f64` reference across multi-step Adam / AdamW runs. |
| 12 | 6. `OLLMCK04` checkpoint & `arch_flags` (`FL_REV = 128` + RoPE/SwiGLU/GQA/QKNorm/ |
| 13 | Untied/GELU/GeGLU/LoopedCore) compatibility. |
| 14 | |
| 15 | Run with: |
| 16 | python3 -W error::ResourceWarning tests/test_reversible.py |
| 17 | """ |
| 18 | |
| 19 | import math |
| 20 | import os |
| 21 | import platform |
| 22 | import shutil |
| 23 | import struct |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import tempfile |
| 27 | |
| 28 | M64 = (1 << 64) - 1 |
| 29 | GOLDEN = 0x9E3779B97F4A7C15 |
| 30 | FNV_OFFSET = 0xCBF29CE484222325 |
| 31 | FNV_PRIME = 0x100000001B3 |
| 32 | SQRT_2_OVER_PI = 0.79788456080286536 |
| 33 | MAGIC_CK4 = b"OLLMCK04" |
| 34 | CKHDR = 208 |
| 35 | |
| 36 | FL_ROPE = 1 |
| 37 | FL_SWIGLU = 2 |
| 38 | FL_UNTIED = 4 |
| 39 | FL_QKNORM = 8 |
| 40 | FL_ADAMW = 16 |
| 41 | FL_GELU = 32 |
| 42 | FL_GEGLU = 64 |
| 43 | FL_REV = 128 |
| 44 | FL_Q32 = 256 |
| 45 | Q32_SCALE = 1073741824.0 |
| 46 | |
| 47 | |
| 48 | def find_repo_root(): |
| 49 | here = os.path.dirname(os.path.abspath(__file__)) |
| 50 | return os.path.dirname(here) |
| 51 | |
| 52 | |
| 53 | def find_omc(): |
| 54 | cands = [ |
| 55 | os.environ.get("OMC", ""), |
| 56 | shutil.which("omc") or "", |
| 57 | os.path.expanduser("~/.local/bin/omc"), |
| 58 | ] |
| 59 | for c in cands: |
| 60 | if c and os.path.isfile(c) and os.access(c, os.X_OK): |
| 61 | return c |
| 62 | raise RuntimeError("omc compiler not found") |
| 63 | |
| 64 | |
| 65 | def splitmix64(x): |
| 66 | z = (x + GOLDEN) & M64 |
| 67 | z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & M64 |
| 68 | z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M64 |
| 69 | return z ^ (z >> 31) |
| 70 | |
| 71 | |
| 72 | def fnv1a64(data): |
| 73 | h = FNV_OFFSET |
| 74 | for b in data: |
| 75 | h = ((h ^ b) * FNV_PRIME) & M64 |
| 76 | return h |
| 77 | |
| 78 | |
| 79 | def bits2f(u): |
| 80 | return struct.unpack("<d", struct.pack("<Q", u))[0] |
| 81 | |
| 82 | |
| 83 | def f2bits(x): |
| 84 | return struct.unpack("<Q", struct.pack("<d", x))[0] |
| 85 | |
| 86 | |
| 87 | def sigmoid(x): |
| 88 | if x >= 0.0: |
| 89 | return 1.0 / (1.0 + math.exp(-x)) |
| 90 | e = math.exp(x) |
| 91 | return e / (1.0 + e) |
| 92 | |
| 93 | |
| 94 | def gelu(x): |
| 95 | c = SQRT_2_OVER_PI * (x + 0.044715 * x * x * x) |
| 96 | return 0.5 * x * (1.0 + math.tanh(c)) |
| 97 | |
| 98 | |
| 99 | def gelu_d(x): |
| 100 | x2 = x * x |
| 101 | c = SQRT_2_OVER_PI * (x + 0.044715 * x2 * x) |
| 102 | th = math.tanh(c) |
| 103 | sech2 = 1.0 - th * th |
| 104 | dc = SQRT_2_OVER_PI * (1.0 + 0.134145 * x2) |
| 105 | return 0.5 * (1.0 + th) + 0.5 * x * sech2 * dc |
| 106 | |
| 107 | |
| 108 | # ---------------------------------------------------------------- geometry & CK04 |
| 109 | |
| 110 | def phys_layer(cfg, l): |
| 111 | np_ = cfg.get("NP", 0) |
| 112 | if np_ <= 1: |
| 113 | return l |
| 114 | lp, lc = cfg["LP"], cfg["LC"] |
| 115 | if l < lp: |
| 116 | return l |
| 117 | j = l - lp |
| 118 | if j < lc * np_: |
| 119 | return lp + (j % lc) |
| 120 | return l - lc * (np_ - 1) |
| 121 | |
| 122 | |
| 123 | def enrich_cfg(cfg): |
| 124 | out = dict(cfg) |
| 125 | D, H, H_kv = cfg["D"], cfg["H"], cfg["H_kv"] |
| 126 | assert D % H == 0 and H % H_kv == 0 |
| 127 | E = D // H |
| 128 | fl = cfg["arch_flags"] |
| 129 | np_ = cfg.get("NP", 0) |
| 130 | lp, lc = cfg.get("LP", 0), cfg.get("LC", 0) |
| 131 | L = cfg["L"] |
| 132 | LV = L + lc * (np_ - 1) if np_ > 1 else L |
| 133 | out["E"] = E |
| 134 | out["KVD"] = H_kv * E |
| 135 | out["LV"] = LV |
| 136 | out["has_rope"] = bool(fl & FL_ROPE) |
| 137 | out["is_gated"] = bool(fl & (FL_SWIGLU | FL_GEGLU)) |
| 138 | out["has_untied"] = bool(fl & FL_UNTIED) |
| 139 | out["has_qknorm"] = bool(fl & FL_QKNORM) |
| 140 | out["is_adamw"] = bool(fl & FL_ADAMW) |
| 141 | out["has_gelu"] = bool(fl & FL_GELU) |
| 142 | out["has_swiglu"] = bool(fl & FL_SWIGLU) |
| 143 | out["has_geglu"] = bool(fl & FL_GEGLU) |
| 144 | out["has_rev"] = bool(fl & FL_REV) |
| 145 | return out |
| 146 | |
| 147 | |
| 148 | def tensor_specs(g): |
| 149 | V, T, D, F, L = g["V"], g["T"], g["D"], g["F"], g["L"] |
| 150 | E, KVD = g["E"], g["KVD"] |
| 151 | specs = [("wte", V, D)] |
| 152 | if not g["has_rope"]: |
| 153 | specs.append(("wpe", T, D)) |
| 154 | for l in range(L): |
| 155 | specs.append((f"g1.{l}", 1, D)) |
| 156 | specs.append((f"wq.{l}", D, D)) |
| 157 | specs.append((f"wk.{l}", D, KVD)) |
| 158 | specs.append((f"wv.{l}", D, KVD)) |
| 159 | specs.append((f"wo.{l}", D, D)) |
| 160 | if g["has_qknorm"]: |
| 161 | specs.append((f"qn.{l}", 1, E)) |
| 162 | specs.append((f"kn.{l}", 1, E)) |
| 163 | specs.append((f"g2.{l}", 1, D)) |
| 164 | specs.append((f"w1.{l}", D, F)) |
| 165 | if g["is_gated"]: |
| 166 | specs.append((f"wup.{l}", D, F)) |
| 167 | specs.append((f"w2.{l}", F, D)) |
| 168 | specs.append(("gf", 1, D)) |
| 169 | if g["has_untied"]: |
| 170 | specs.append(("lmh", V, D)) |
| 171 | out, off = [], 0 |
| 172 | for name, r, c in specs: |
| 173 | out.append((name, off, r, c)) |
| 174 | off += r * c |
| 175 | return out, off |
| 176 | |
| 177 | |
| 178 | def is_gain_name(name): |
| 179 | return name.split(".")[0] in ("g1", "g2", "qn", "kn", "gf") |
| 180 | |
| 181 | |
| 182 | def unpack_params(g, flat): |
| 183 | specs, _ = tensor_specs(g) |
| 184 | out = {} |
| 185 | for name, off, r, c in specs: |
| 186 | if r == 1 and is_gain_name(name): |
| 187 | out[name] = list(flat[off:off + c]) |
| 188 | else: |
| 189 | out[name] = [list(flat[off + i * c:off + (i + 1) * c]) for i in range(r)] |
| 190 | return out |
| 191 | |
| 192 | |
| 193 | def pack_params(g, tdict): |
| 194 | specs, _ = tensor_specs(g) |
| 195 | flat = [] |
| 196 | for name, _, r, _ in specs: |
| 197 | v = tdict[name] |
| 198 | if r == 1 and is_gain_name(name): |
| 199 | flat.extend(v) |
| 200 | else: |
| 201 | for row in v: |
| 202 | flat.extend(row) |
| 203 | return flat |
| 204 | |
| 205 | |
| 206 | def zeros_like(g): |
| 207 | specs, _ = tensor_specs(g) |
| 208 | out = {} |
| 209 | for name, _, r, c in specs: |
| 210 | out[name] = [0.0] * c if (r == 1 and is_gain_name(name)) else [[0.0] * c for _ in range(r)] |
| 211 | return out |
| 212 | |
| 213 | |
| 214 | def read_ck4(path): |
| 215 | with open(path, "rb") as f: |
| 216 | raw = f.read() |
| 217 | assert len(raw) >= CKHDR |
| 218 | assert raw[:8] == MAGIC_CK4, f"bad magic {raw[:8]!r}" |
| 219 | V, T, D, H, H_kv, F, L, B = struct.unpack("<8Q", raw[8:72]) |
| 220 | seed, step, total, lr_bits, P = struct.unpack("<5Q", raw[72:112]) |
| 221 | fl, rope_milli, eps_bits, wd_bits, warmup = struct.unpack("<5Q", raw[112:152]) |
| 222 | LP, LC, NP = struct.unpack("<3Q", raw[152:176]) |
| 223 | (fnv_got,) = struct.unpack("<Q", raw[200:208]) |
| 224 | assert len(raw) == CKHDR + 24 * P |
| 225 | body = raw[CKHDR:] |
| 226 | assert fnv1a64(body) == fnv_got, "CK04 FNV-1a mismatch" |
| 227 | pays = [list(struct.unpack(f"<{P}d", body[8 * P * k:8 * P * (k + 1)])) for k in range(3)] |
| 228 | return dict( |
| 229 | V=V, T=T, D=D, H=H, H_kv=H_kv, F=F, L=L, B=B, |
| 230 | seed=seed, step=step, total=total, lr=bits2f(lr_bits), P=P, |
| 231 | arch_flags=fl, rope_theta_milli=rope_milli, rms_eps=bits2f(eps_bits), |
| 232 | wd=bits2f(wd_bits), warmup=warmup, LP=LP, LC=LC, NP=NP, |
| 233 | params=pays[0], m=pays[1], v=pays[2], |
| 234 | ) |
| 235 | |
| 236 | |
| 237 | # ---------------------------------------------------------------- Python f64 Reversible Oracle |
| 238 | |
| 239 | def rms_fwd_mat(X, g, eps): |
| 240 | T, D = len(X), len(g) |
| 241 | Y, dens = [], [] |
| 242 | for t in range(T): |
| 243 | row = X[t] |
| 244 | s = math.sqrt(sum(v * v for v in row) / D + eps) |
| 245 | dens.append(s) |
| 246 | Y.append([row[j] / s * g[j] for j in range(D)]) |
| 247 | return Y, dens |
| 248 | |
| 249 | |
| 250 | def rms_bwd_mat(X, g, dens, dY, dg): |
| 251 | T, D = len(X), len(g) |
| 252 | dX = [] |
| 253 | for t in range(T): |
| 254 | row, dy, s = X[t], dY[t], dens[t] |
| 255 | for j in range(D): |
| 256 | dg[j] += dy[j] * row[j] / s |
| 257 | dot = sum(dy[j] * g[j] * row[j] for j in range(D)) |
| 258 | k = dot / (D * s * s) |
| 259 | dX.append([(dy[j] * g[j] - row[j] * k) / s for j in range(D)]) |
| 260 | return dX |
| 261 | |
| 262 | |
| 263 | def mm_fwd(X, W): |
| 264 | T, K, N = len(X), len(W), len(W[0]) |
| 265 | return [[sum(X[t][p] * W[p][j] for p in range(K)) for j in range(N)] for t in range(T)] |
| 266 | |
| 267 | |
| 268 | def mm_dx(dY, W): |
| 269 | T, K, N = len(dY), len(W), len(W[0]) |
| 270 | return [[sum(dY[t][j] * W[p][j] for j in range(N)) for p in range(K)] for t in range(T)] |
| 271 | |
| 272 | |
| 273 | def mm_dw(X, dY, dW): |
| 274 | T, K, N = len(X), len(dW), len(dW[0]) |
| 275 | for t in range(T): |
| 276 | xt, dyt = X[t], dY[t] |
| 277 | for p in range(K): |
| 278 | xv = xt[p] |
| 279 | if xv != 0.0: |
| 280 | row = dW[p] |
| 281 | for j in range(N): |
| 282 | row[j] += xv * dyt[j] |
| 283 | |
| 284 | |
| 285 | def build_rope_tables(g): |
| 286 | T, E = g["T"], g["E"] |
| 287 | he = E // 2 |
| 288 | th = g["rope_theta_milli"] / 1000.0 |
| 289 | if th <= 0.0: |
| 290 | th = 10000.0 |
| 291 | lth = math.log(th) |
| 292 | cos_t = [[0.0] * he for _ in range(T)] |
| 293 | sin_t = [[0.0] * he for _ in range(T)] |
| 294 | for i in range(he): |
| 295 | freq = math.exp(-lth * (2.0 * i) / E) |
| 296 | for pos in range(T): |
| 297 | ang = pos * freq |
| 298 | cos_t[pos][i] = math.cos(ang) |
| 299 | sin_t[pos][i] = math.sin(ang) |
| 300 | return cos_t, sin_t |
| 301 | |
| 302 | |
| 303 | def apply_rope_vec(v, pos, cos_t, sin_t, inv=False): |
| 304 | he = len(cos_t[0]) |
| 305 | out = list(v) |
| 306 | c_row, s_row = cos_t[pos], sin_t[pos] |
| 307 | for i in range(he): |
| 308 | x0, x1 = v[i], v[i + he] |
| 309 | c, s = c_row[i], s_row[i] |
| 310 | if inv: |
| 311 | out[i] = x0 * c + x1 * s |
| 312 | out[i + he] = x1 * c - x0 * s |
| 313 | else: |
| 314 | out[i] = x0 * c - x1 * s |
| 315 | out[i + he] = x0 * s + x1 * c |
| 316 | return out |
| 317 | |
| 318 | |
| 319 | def F_fwd(g, P, pl, x2, rope_tab): |
| 320 | T, D, H, H_kv, E, KVD = g["T"], g["D"], g["H"], g["H_kv"], g["E"], g["KVD"] |
| 321 | eps = g["rms_eps"] |
| 322 | g1 = P[f"g1.{pl}"] |
| 323 | a, s1 = rms_fwd_mat(x2, g1, eps) |
| 324 | q = mm_fwd(a, P[f"wq.{pl}"]) |
| 325 | k = mm_fwd(a, P[f"wk.{pl}"]) |
| 326 | u = mm_fwd(a, P[f"wv.{pl}"]) |
| 327 | qpre, kpre, qns, kns = None, None, None, None |
| 328 | if g["has_qknorm"]: |
| 329 | qpre = [list(r) for r in q] |
| 330 | kpre = [list(r) for r in k] |
| 331 | qn_w, kn_w = P[f"qn.{pl}"], P[f"kn.{pl}"] |
| 332 | qns = [[0.0] * H for _ in range(T)] |
| 333 | kns = [[0.0] * H_kv for _ in range(T)] |
| 334 | for t in range(T): |
| 335 | for hi in range(H): |
| 336 | sl = qpre[t][hi * E:(hi + 1) * E] |
| 337 | s = math.sqrt(sum(v * v for v in sl) / E + eps) |
| 338 | qns[t][hi] = s |
| 339 | q[t][hi * E:(hi + 1) * E] = [sl[j] / s * qn_w[j] for j in range(E)] |
| 340 | for kh in range(H_kv): |
| 341 | sl = kpre[t][kh * E:(kh + 1) * E] |
| 342 | s = math.sqrt(sum(v * v for v in sl) / E + eps) |
| 343 | kns[t][kh] = s |
| 344 | k[t][kh * E:(kh + 1) * E] = [sl[j] / s * kn_w[j] for j in range(E)] |
| 345 | if g["has_rope"]: |
| 346 | cos_t, sin_t = rope_tab |
| 347 | for t in range(T): |
| 348 | for hi in range(H): |
| 349 | q[t][hi * E:(hi + 1) * E] = apply_rope_vec(q[t][hi * E:(hi + 1) * E], t, cos_t, sin_t, False) |
| 350 | for kh in range(H_kv): |
| 351 | k[t][kh * E:(kh + 1) * E] = apply_rope_vec(k[t][kh * E:(kh + 1) * E], t, cos_t, sin_t, False) |
| 352 | sE = math.sqrt(E) |
| 353 | o = [[0.0] * D for _ in range(T)] |
| 354 | pa = [] |
| 355 | grp = H // H_kv |
| 356 | for hi in range(H): |
| 357 | kh = hi // grp |
| 358 | qh_off, kh_off = hi * E, kh * E |
| 359 | p_h = [] |
| 360 | for t in range(T): |
| 361 | qt = q[t][qh_off:qh_off + E] |
| 362 | sc = [sum(qt[c] * k[j][kh_off + c] for c in range(E)) / sE for j in range(t + 1)] |
| 363 | mx = max(sc) |
| 364 | ew = [math.exp(v - mx) for v in sc] |
| 365 | sm = sum(ew) |
| 366 | pr = [v / sm for v in ew] |
| 367 | p_h.append(pr) |
| 368 | for j in range(t + 1): |
| 369 | pj = pr[j] |
| 370 | uj = u[j] |
| 371 | for c in range(E): |
| 372 | o[t][qh_off + c] += pj * uj[kh_off + c] |
| 373 | pa.append(p_h) |
| 374 | fout = mm_fwd(o, P[f"wo.{pl}"]) |
| 375 | cache = dict(a=a, s1=s1, q=q, k=k, u=u, qpre=qpre, kpre=kpre, qns=qns, kns=kns, pa=pa, o=o) |
| 376 | return fout, cache |
| 377 | |
| 378 | |
| 379 | def F_bwd(g, P, G, pl, x2, dy1, cache, rope_tab): |
| 380 | T, D, H, H_kv, E, KVD = g["T"], g["D"], g["H"], g["H_kv"], g["E"], g["KVD"] |
| 381 | a, s1 = cache["a"], cache["s1"] |
| 382 | q, k, u, pa, o = cache["q"], cache["k"], cache["u"], cache["pa"], cache["o"] |
| 383 | mm_dw(o, dy1, G[f"wo.{pl}"]) |
| 384 | do = mm_dx(dy1, P[f"wo.{pl}"]) |
| 385 | dq = [[0.0] * D for _ in range(T)] |
| 386 | dk = [[0.0] * KVD for _ in range(T)] |
| 387 | du = [[0.0] * KVD for _ in range(T)] |
| 388 | sE = math.sqrt(E) |
| 389 | grp = H // H_kv |
| 390 | for hi in range(H): |
| 391 | kh = hi // grp |
| 392 | qh_off, kh_off = hi * E, kh * E |
| 393 | for t in range(T): |
| 394 | pr = pa[hi][t] |
| 395 | dot = do[t][qh_off:qh_off + E] |
| 396 | dp = [sum(dot[c] * u[j][kh_off + c] for c in range(E)) for j in range(t + 1)] |
| 397 | for j in range(t + 1): |
| 398 | pj = pr[j] |
| 399 | for c in range(E): |
| 400 | du[j][kh_off + c] += pj * dot[c] |
| 401 | sdp = sum(pr[j] * dp[j] for j in range(t + 1)) |
| 402 | ds = [pr[j] * (dp[j] - sdp) / sE for j in range(t + 1)] |
| 403 | qt = q[t][qh_off:qh_off + E] |
| 404 | for j in range(t + 1): |
| 405 | dsj = ds[j] |
| 406 | for c in range(E): |
| 407 | dq[t][qh_off + c] += dsj * k[j][kh_off + c] |
| 408 | dk[j][kh_off + c] += dsj * qt[c] |
| 409 | if g["has_rope"]: |
| 410 | cos_t, sin_t = rope_tab |
| 411 | for t in range(T): |
| 412 | for hi in range(H): |
| 413 | dq[t][hi * E:(hi + 1) * E] = apply_rope_vec(dq[t][hi * E:(hi + 1) * E], t, cos_t, sin_t, True) |
| 414 | for kh in range(H_kv): |
| 415 | dk[t][kh * E:(kh + 1) * E] = apply_rope_vec(dk[t][kh * E:(kh + 1) * E], t, cos_t, sin_t, True) |
| 416 | if g["has_qknorm"]: |
| 417 | qpre, kpre, qns, kns = cache["qpre"], cache["kpre"], cache["qns"], cache["kns"] |
| 418 | qn_w, kn_w = P[f"qn.{pl}"], P[f"kn.{pl}"] |
| 419 | dqn, dkn = G[f"qn.{pl}"], G[f"kn.{pl}"] |
| 420 | for t in range(T): |
| 421 | for hi in range(H): |
| 422 | pre = qpre[t][hi * E:(hi + 1) * E] |
| 423 | dv = dq[t][hi * E:(hi + 1) * E] |
| 424 | s = qns[t][hi] |
| 425 | for j in range(E): |
| 426 | dqn[j] += dv[j] * pre[j] / s |
| 427 | dot = sum(dv[j] * qn_w[j] * pre[j] for j in range(E)) |
| 428 | kk = dot / (E * s * s) |
| 429 | dq[t][hi * E:(hi + 1) * E] = [(dv[j] * qn_w[j] - pre[j] * kk) / s for j in range(E)] |
| 430 | for kh in range(H_kv): |
| 431 | pre = kpre[t][kh * E:(kh + 1) * E] |
| 432 | dv = dk[t][kh * E:(kh + 1) * E] |
| 433 | s = kns[t][kh] |
| 434 | for j in range(E): |
| 435 | dkn[j] += dv[j] * pre[j] / s |
| 436 | dot = sum(dv[j] * kn_w[j] * pre[j] for j in range(E)) |
| 437 | kk = dot / (E * s * s) |
| 438 | dk[t][kh * E:(kh + 1) * E] = [(dv[j] * kn_w[j] - pre[j] * kk) / s for j in range(E)] |
| 439 | mm_dw(a, dq, G[f"wq.{pl}"]) |
| 440 | mm_dw(a, dk, G[f"wk.{pl}"]) |
| 441 | mm_dw(a, du, G[f"wv.{pl}"]) |
| 442 | da_q = mm_dx(dq, P[f"wq.{pl}"]) |
| 443 | da_k = mm_dx(dk, P[f"wk.{pl}"]) |
| 444 | da_u = mm_dx(du, P[f"wv.{pl}"]) |
| 445 | da = [[da_q[t][j] + da_k[t][j] + da_u[t][j] for j in range(D)] for t in range(T)] |
| 446 | return rms_bwd_mat(x2, P[f"g1.{pl}"], s1, da, G[f"g1.{pl}"]) |
| 447 | |
| 448 | |
| 449 | def G_fwd(g, P, pl, y1): |
| 450 | T, F = g["T"], g["F"] |
| 451 | eps = g["rms_eps"] |
| 452 | b, s2 = rms_fwd_mat(y1, P[f"g2.{pl}"], eps) |
| 453 | fp = mm_fwd(b, P[f"w1.{pl}"]) |
| 454 | up = mm_fwd(b, P[f"wup.{pl}"]) if g["is_gated"] else None |
| 455 | if g["has_swiglu"]: |
| 456 | rl = [[fp[t][i] * sigmoid(fp[t][i]) * up[t][i] for i in range(F)] for t in range(T)] |
| 457 | elif g["has_geglu"]: |
| 458 | rl = [[gelu(fp[t][i]) * up[t][i] for i in range(F)] for t in range(T)] |
| 459 | elif g["has_gelu"]: |
| 460 | rl = [[gelu(fp[t][i]) for i in range(F)] for t in range(T)] |
| 461 | else: |
| 462 | rl = [[v if v > 0.0 else 0.0 for v in row] for row in fp] |
| 463 | gout = mm_fwd(rl, P[f"w2.{pl}"]) |
| 464 | return gout, dict(b=b, s2=s2, fp=fp, up=up, rl=rl) |
| 465 | |
| 466 | |
| 467 | def G_bwd(g, P, G, pl, y1, dy2, cache): |
| 468 | T, D, F = g["T"], g["D"], g["F"] |
| 469 | b, s2, fp, up, rl = cache["b"], cache["s2"], cache["fp"], cache["up"], cache["rl"] |
| 470 | mm_dw(rl, dy2, G[f"w2.{pl}"]) |
| 471 | df1 = mm_dx(dy2, P[f"w2.{pl}"]) |
| 472 | df2 = None |
| 473 | if g["has_swiglu"]: |
| 474 | df2 = [[0.0] * F for _ in range(T)] |
| 475 | for t in range(T): |
| 476 | for i in range(F): |
| 477 | dy, gv, uv = df1[t][i], fp[t][i], up[t][i] |
| 478 | sig = sigmoid(gv) |
| 479 | df2[t][i] = dy * gv * sig |
| 480 | ds = sig * (1.0 + gv * (1.0 - sig)) |
| 481 | df1[t][i] = dy * uv * ds |
| 482 | elif g["has_geglu"]: |
| 483 | df2 = [[0.0] * F for _ in range(T)] |
| 484 | for t in range(T): |
| 485 | for i in range(F): |
| 486 | dy, gv, uv = df1[t][i], fp[t][i], up[t][i] |
| 487 | df2[t][i] = dy * gelu(gv) |
| 488 | df1[t][i] = dy * uv * gelu_d(gv) |
| 489 | elif g["has_gelu"]: |
| 490 | df1 = [[df1[t][i] * gelu_d(fp[t][i]) for i in range(F)] for t in range(T)] |
| 491 | else: |
| 492 | df1 = [[df1[t][i] if fp[t][i] > 0.0 else 0.0 for i in range(F)] for t in range(T)] |
| 493 | mm_dw(b, df1, G[f"w1.{pl}"]) |
| 494 | db = mm_dx(df1, P[f"w1.{pl}"]) |
| 495 | if g["is_gated"]: |
| 496 | mm_dw(b, df2, G[f"wup.{pl}"]) |
| 497 | db_up = mm_dx(df2, P[f"wup.{pl}"]) |
| 498 | db = [[db[t][j] + db_up[t][j] for j in range(D)] for t in range(T)] |
| 499 | return rms_bwd_mat(y1, P[f"g2.{pl}"], s2, db, G[f"g2.{pl}"]) |
| 500 | |
| 501 | |
| 502 | def rev_seq_loss_grad(g, P, G, xs, ys, scale, rope_tab, zero_act_cache=True): |
| 503 | T, D, V, LV = g["T"], g["D"], g["V"], g["LV"] |
| 504 | wte = P["wte"] |
| 505 | if g["has_rope"]: |
| 506 | h0 = [[wte[xs[t]][j] for j in range(D)] for t in range(T)] |
| 507 | else: |
| 508 | wpe = P["wpe"] |
| 509 | h0 = [[wte[xs[t]][j] + wpe[t][j] for j in range(D)] for t in range(T)] |
| 510 | x1 = [list(r) for r in h0] |
| 511 | x2 = [list(r) for r in h0] |
| 512 | layer_caches = [] if not zero_act_cache else None |
| 513 | for l in range(LV): |
| 514 | pl = phys_layer(g, l) |
| 515 | fout, fcache = F_fwd(g, P, pl, x2, rope_tab) |
| 516 | y1 = [[x1[t][j] + fout[t][j] for j in range(D)] for t in range(T)] |
| 517 | gout, gcache = G_fwd(g, P, pl, y1) |
| 518 | y2 = [[x2[t][j] + gout[t][j] for j in range(D)] for t in range(T)] |
| 519 | if not zero_act_cache: |
| 520 | layer_caches.append((x1, x2, y1, y2, fcache, gcache)) |
| 521 | x1, x2 = y1, y2 |
| 522 | hf = [[0.5 * (x1[t][j] + x2[t][j]) for j in range(D)] for t in range(T)] |
| 523 | gf = P["gf"] |
| 524 | z, sf = rms_fwd_mat(hf, gf, g["rms_eps"]) |
| 525 | lmw = P["lmh"] if g["has_untied"] else P["wte"] |
| 526 | dlmw = G["lmh"] if g["has_untied"] else G["wte"] |
| 527 | lsum = 0.0 |
| 528 | dz = [[0.0] * D for _ in range(T)] |
| 529 | for t in range(T): |
| 530 | lg = [sum(z[t][j] * lmw[c][j] for j in range(D)) for c in range(V)] |
| 531 | mx = max(lg) |
| 532 | ew = [math.exp(v - mx) for v in lg] |
| 533 | sm = sum(ew) |
| 534 | pr = [v / sm for v in ew] |
| 535 | lsum += -(lg[ys[t]] - mx - math.log(sm)) |
| 536 | for c in range(V): |
| 537 | dl = (pr[c] - (1.0 if c == ys[t] else 0.0)) * scale |
| 538 | for j in range(D): |
| 539 | dlmw[c][j] += dl * z[t][j] |
| 540 | dz[t][j] += dl * lmw[c][j] |
| 541 | dhf = rms_bwd_mat(hf, gf, sf, dz, G["gf"]) |
| 542 | dy1 = [[0.5 * dhf[t][j] for j in range(D)] for t in range(T)] |
| 543 | dy2 = [[0.5 * dhf[t][j] for j in range(D)] for t in range(T)] |
| 544 | y1, y2 = x1, x2 |
| 545 | for l in range(LV - 1, -1, -1): |
| 546 | pl = phys_layer(g, l) |
| 547 | if zero_act_cache: |
| 548 | gout, gcache = G_fwd(g, P, pl, y1) |
| 549 | x2_rec = [[y2[t][j] - gout[t][j] for j in range(D)] for t in range(T)] |
| 550 | dy1_g = G_bwd(g, P, G, pl, y1, dy2, gcache) |
| 551 | dy1 = [[dy1[t][j] + dy1_g[t][j] for j in range(D)] for t in range(T)] |
| 552 | fout, fcache = F_fwd(g, P, pl, x2_rec, rope_tab) |
| 553 | x1_rec = [[y1[t][j] - fout[t][j] for j in range(D)] for t in range(T)] |
| 554 | dx2_f = F_bwd(g, P, G, pl, x2_rec, dy1, fcache, rope_tab) |
| 555 | dy2 = [[dy2[t][j] + dx2_f[t][j] for j in range(D)] for t in range(T)] |
| 556 | y1, y2 = x1_rec, x2_rec |
| 557 | else: |
| 558 | x1_c, x2_c, y1_c, y2_c, fcache, gcache = layer_caches[l] |
| 559 | dy1_g = G_bwd(g, P, G, pl, y1_c, dy2, gcache) |
| 560 | dy1 = [[dy1[t][j] + dy1_g[t][j] for j in range(D)] for t in range(T)] |
| 561 | dx2_f = F_bwd(g, P, G, pl, x2_c, dy1, fcache, rope_tab) |
| 562 | dy2 = [[dy2[t][j] + dx2_f[t][j] for j in range(D)] for t in range(T)] |
| 563 | for t in range(T): |
| 564 | dh0 = [dy1[t][j] + dy2[t][j] for j in range(D)] |
| 565 | for j in range(D): |
| 566 | G["wte"][xs[t]][j] += dh0[j] |
| 567 | if not g["has_rope"]: |
| 568 | G["wpe"][t][j] += dh0[j] |
| 569 | return lsum / T |
| 570 | |
| 571 | |
| 572 | def rev_loss_and_grad(g, flat, batch_seqs, zero_act_cache=True): |
| 573 | P = unpack_params(g, flat) |
| 574 | G = zeros_like(g) |
| 575 | rope_tab = build_rope_tables(g) if g["has_rope"] else None |
| 576 | B, T = g["B"], g["T"] |
| 577 | sc = 1.0 / (B * T) |
| 578 | tot = 0.0 |
| 579 | for xs, ys in batch_seqs: |
| 580 | tot += rev_seq_loss_grad(g, P, G, xs, ys, sc, rope_tab, zero_act_cache=zero_act_cache) |
| 581 | return tot / B, pack_params(g, G) |
| 582 | |
| 583 | |
| 584 | def rev_inv_error(g, flat, xs): |
| 585 | T, D, LV = g["T"], g["D"], g["LV"] |
| 586 | P = unpack_params(g, flat) |
| 587 | rope_tab = build_rope_tables(g) if g["has_rope"] else None |
| 588 | if g["has_rope"]: |
| 589 | h0 = [[P["wte"][xs[t]][j] for j in range(D)] for t in range(T)] |
| 590 | else: |
| 591 | h0 = [[P["wte"][xs[t]][j] + P["wpe"][t][j] for j in range(D)] for t in range(T)] |
| 592 | x1_init = [list(r) for r in h0] |
| 593 | x2_init = [list(r) for r in h0] |
| 594 | x1, x2 = [list(r) for r in h0], [list(r) for r in h0] |
| 595 | for l in range(LV): |
| 596 | pl = phys_layer(g, l) |
| 597 | fout, _ = F_fwd(g, P, pl, x2, rope_tab) |
| 598 | y1 = [[x1[t][j] + fout[t][j] for j in range(D)] for t in range(T)] |
| 599 | gout, _ = G_fwd(g, P, pl, y1) |
| 600 | y2 = [[x2[t][j] + gout[t][j] for j in range(D)] for t in range(T)] |
| 601 | x1, x2 = y1, y2 |
| 602 | for l in range(LV - 1, -1, -1): |
| 603 | pl = phys_layer(g, l) |
| 604 | gout, _ = G_fwd(g, P, pl, x1) |
| 605 | x2_rec = [[x2[t][j] - gout[t][j] for j in range(D)] for t in range(T)] |
| 606 | fout, _ = F_fwd(g, P, pl, x2_rec, rope_tab) |
| 607 | x1_rec = [[x1[t][j] - fout[t][j] for j in range(D)] for t in range(T)] |
| 608 | x1, x2 = x1_rec, x2_rec |
| 609 | mx = 0.0 |
| 610 | for t in range(T): |
| 611 | for j in range(D): |
| 612 | mx = max(mx, abs(x1[t][j] - x1_init[t][j]), abs(x2[t][j] - x2_init[t][j])) |
| 613 | return mx |
| 614 | |
| 615 | |
| 616 | def adam_step(g, params, m, v, grad, step): |
| 617 | lr = g["lr"] |
| 618 | wu = g["warmup"] |
| 619 | tot = g["total"] |
| 620 | if wu > 0 and step < wu: |
| 621 | lrs = lr * (step + 1) / wu |
| 622 | else: |
| 623 | rt = max(1, tot - wu) |
| 624 | prog = min(1.0, (step - wu) / rt) |
| 625 | if g["is_adamw"]: |
| 626 | lrs = lr * (0.1 + 0.45 * (1.0 + math.cos(math.pi * prog))) |
| 627 | else: |
| 628 | lrs = lr * (1.0 - 0.9 * prog) |
| 629 | gn = math.sqrt(sum(gv * gv for gv in grad)) |
| 630 | if gn > 1.0: |
| 631 | sc = 1.0 / gn |
| 632 | grad = [gv * sc for gv in grad] |
| 633 | b1 = 0.9 |
| 634 | b2 = 0.95 if g["is_adamw"] else 0.99 |
| 635 | bc1 = 1.0 / (1.0 - b1 ** (step + 1)) |
| 636 | bc2 = 1.0 / (1.0 - b2 ** (step + 1)) |
| 637 | wd = g["wd"] if g["is_adamw"] else 0.0 |
| 638 | specs, _ = tensor_specs(g) |
| 639 | gain_mask = [] |
| 640 | for name, _, r, c in specs: |
| 641 | gain_mask.extend([is_gain_name(name)] * (r * c)) |
| 642 | p_new, m_new, v_new = [], [], [] |
| 643 | for i, (w, mi, vi, gi) in enumerate(zip(params, m, v, grad)): |
| 644 | m2 = b1 * mi + (1.0 - b1) * gi |
| 645 | v2 = b2 * vi + (1.0 - b2) * gi * gi |
| 646 | if wd > 0.0 and not gain_mask[i]: |
| 647 | w = w - lrs * wd * w |
| 648 | upd = (lrs * m2 * bc1) / (math.sqrt(v2 * bc2) + 1e-8) |
| 649 | p_new.append(w - upd) |
| 650 | m_new.append(m2) |
| 651 | v_new.append(v2) |
| 652 | return p_new, m_new, v_new |
| 653 | |
| 654 | |
| 655 | # ---------------------------------------------------------------- compiler & test runner |
| 656 | |
| 657 | def compile_target(omc, root, out_path, mode): |
| 658 | nat = os.path.join(root, "native") |
| 659 | units = ["math.om", "data.om", "lpool.om", "model.om", "adam.om", "ckpt.om", "bpe.om"] |
| 660 | if mode in ("mac_om1", "mac_om2"): |
| 661 | units.append("mio.om") |
| 662 | hdr = "target a64macos\n" + ("om2\n" if mode == "mac_om2" else "") |
| 663 | elif mode == "gb10_om2": |
| 664 | units.append("lio.om") |
| 665 | hdr = "om2\n" |
| 666 | else: |
| 667 | raise ValueError(mode) |
| 668 | units.extend(["nogpu.om", "rev.om"]) |
| 669 | parts = [hdr] |
| 670 | for u in units: |
| 671 | with open(os.path.join(nat, u), "r", encoding="utf-8") as f: |
| 672 | parts.append(f.read()) |
| 673 | parts.append("\nfn olast to void\nend\nfn ocmd to int\nret rev_cli\nend\n") |
| 674 | src = "\n".join(parts) |
| 675 | res = subprocess.run([omc], input=src.encode("utf-8"), capture_output=True) |
| 676 | if res.returncode != 0: |
| 677 | raise RuntimeError(f"omc failed for {mode}: {res.stderr.decode('utf-8', 'replace')}") |
| 678 | with open(out_path, "wb") as f: |
| 679 | f.write(res.stdout) |
| 680 | os.chmod(out_path, 0o755) |
| 681 | if mode in ("mac_om1", "mac_om2") and shutil.which("codesign"): |
| 682 | cs = subprocess.run(["codesign", "-s", "-", "-f", out_path], capture_output=True) |
| 683 | if cs.returncode != 0: |
| 684 | raise RuntimeError(f"codesign failed: {cs.stderr.decode('utf-8', 'replace')}") |
| 685 | |
| 686 | |
| 687 | def run_oracle_case(bin_path, tmpdir, label, cfg): |
| 688 | g = enrich_cfg(cfg) |
| 689 | out_bin = os.path.join(tmpdir, f"{label}.bin") |
| 690 | ck4_path = os.path.join(tmpdir, f"{label}.ck4") |
| 691 | steps = 5 |
| 692 | argv = [ |
| 693 | bin_path, "oracle", |
| 694 | str(g["arch_flags"]), str(g["V"]), str(g["T"]), str(g["D"]), |
| 695 | str(g["H"]), str(g["H_kv"]), str(g["F"]), str(g["L"]), str(g["B"]), |
| 696 | str(g.get("LP", 0)), str(g.get("LC", 0)), str(g.get("NP", 0)), |
| 697 | str(g["seed"]), str(steps), out_bin, ck4_path, |
| 698 | ] |
| 699 | res = subprocess.run(argv, capture_output=True, text=True) |
| 700 | assert res.returncode == 0, f"{label} oracle failed: rc={res.returncode} {res.stderr}" |
| 701 | |
| 702 | with open(out_bin, "rb") as f: |
| 703 | raw = f.read() |
| 704 | P, inv_err_om, ls_om, act_bytes, pair_bytes = struct.unpack("<QddQQ", raw[:40]) |
| 705 | _, exp_P = tensor_specs(g) |
| 706 | assert P == exp_P, f"{label}: P mismatch {P} != {exp_P}" |
| 707 | assert act_bytes == 0, f"{label}: expected rev_act_bytes_used == 0, got {act_bytes}" |
| 708 | assert pair_bytes == 2 * g["T"] * g["D"] * 8, f"{label}: pair_bytes={pair_bytes}" |
| 709 | assert inv_err_om < 1e-12, f"{label}: OM inverse error {inv_err_om:.3e} >= 1e-12" |
| 710 | |
| 711 | pos = 40 |
| 712 | params0 = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P |
| 713 | grads_om = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P |
| 714 | step_losses_om = list(struct.unpack(f"<{steps}d", raw[pos:pos + 8 * steps])); pos += 8 * steps |
| 715 | params_final_om = list(struct.unpack(f"<{P}d", raw[pos:pos + 8 * P])); pos += 8 * P |
| 716 | assert pos == len(raw) |
| 717 | |
| 718 | batch_seqs = [ |
| 719 | ([splitmix64(101 + b * 31 + t) % g["V"] for t in range(g["T"])], |
| 720 | [splitmix64(701 + b * 31 + t) % g["V"] for t in range(g["T"])]) |
| 721 | for b in range(g["B"]) |
| 722 | ] |
| 723 | |
| 724 | # 1. Python algebraic inverse reconstruction check |
| 725 | py_inv_err = rev_inv_error(g, params0, batch_seqs[0][0]) |
| 726 | assert py_inv_err < 1e-12, f"{label}: Python inverse error {py_inv_err:.3e}" |
| 727 | |
| 728 | # 2. Zero-activation vs cached-activation equivalence in Python + vs rev.om |
| 729 | py_loss_z, py_grad_z = rev_loss_and_grad(g, params0, batch_seqs, zero_act_cache=True) |
| 730 | py_loss_c, py_grad_c = rev_loss_and_grad(g, params0, batch_seqs, zero_act_cache=False) |
| 731 | assert abs(py_loss_z - ls_om) < 1e-10, f"{label}: loss diff {abs(py_loss_z - ls_om):.3e}" |
| 732 | assert abs(py_loss_z - py_loss_c) < 1e-12 |
| 733 | |
| 734 | max_g_om_vs_cached = 0.0 |
| 735 | max_g_z_vs_c = 0.0 |
| 736 | g_scale = max(1.0, max(abs(x) for x in py_grad_c)) |
| 737 | for a, b, c in zip(grads_om, py_grad_z, py_grad_c): |
| 738 | max_g_om_vs_cached = max(max_g_om_vs_cached, abs(a - c) / g_scale) |
| 739 | max_g_z_vs_c = max(max_g_z_vs_c, abs(b - c) / g_scale) |
| 740 | assert max_g_om_vs_cached < 1e-10, f"{label}: grad OM vs cached err {max_g_om_vs_cached:.3e}" |
| 741 | assert max_g_z_vs_c < 1e-12, f"{label}: grad zero vs cached err {max_g_z_vs_c:.3e}" |
| 742 | |
| 743 | # 3. Central finite-difference check across every tensor type (4-point O(h^4) central FD) |
| 744 | h = 1e-4 |
| 745 | specs, _ = tensor_specs(g) |
| 746 | p_work = list(params0) |
| 747 | worst_fd = 0.0 |
| 748 | for name, off, r, cc in specs: |
| 749 | n = r * cc |
| 750 | idxs = [off, off + n // 2, off + n - 1] |
| 751 | for idx in idxs: |
| 752 | orig = p_work[idx] |
| 753 | p_work[idx] = orig + 2.0 * h |
| 754 | lp2, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) |
| 755 | p_work[idx] = orig + h |
| 756 | lp1, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) |
| 757 | p_work[idx] = orig - h |
| 758 | lm1, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) |
| 759 | p_work[idx] = orig - 2.0 * h |
| 760 | lm2, _ = rev_loss_and_grad(g, p_work, batch_seqs, zero_act_cache=True) |
| 761 | p_work[idx] = orig |
| 762 | gn = (-lp2 + 8.0 * lp1 - 8.0 * lm1 + lm2) / (12.0 * h) |
| 763 | ga = grads_om[idx] |
| 764 | rel = abs(gn - ga) / max(abs(ga), abs(gn), 1e-2) |
| 765 | worst_fd = max(worst_fd, rel) |
| 766 | assert rel < 1e-8, f"{label} {name}[{idx - off}]: FD rel={rel:.3e} ga={ga:.10e} gn={gn:.10e}" |
| 767 | |
| 768 | # 4. Multi-step Adam/AdamW training equivalence vs cached-activation Python reference |
| 769 | p_cur = list(params0) |
| 770 | m_cur = [0.0] * P |
| 771 | v_cur = [0.0] * P |
| 772 | for stp in range(steps): |
| 773 | l_ref, g_ref = rev_loss_and_grad(g, p_cur, batch_seqs, zero_act_cache=False) |
| 774 | assert abs(l_ref - step_losses_om[stp]) < 1e-10, ( |
| 775 | f"{label} step {stp}: loss {step_losses_om[stp]} != {l_ref}" |
| 776 | ) |
| 777 | p_cur, m_cur, v_cur = adam_step(g, p_cur, m_cur, v_cur, g_ref, stp) |
| 778 | assert step_losses_om[-1] < step_losses_om[0], ( |
| 779 | f"{label}: loss did not decrease ({step_losses_om[0]:.6f} -> {step_losses_om[-1]:.6f})" |
| 780 | ) |
| 781 | max_p_diff = max(abs(a - b) for a, b in zip(params_final_om, p_cur)) |
| 782 | assert max_p_diff < 1e-10, f"{label}: final params diff {max_p_diff:.3e}" |
| 783 | |
| 784 | # 5. OLLMCK04 checkpoint & flag compatibility check |
| 785 | ck = read_ck4(ck4_path) |
| 786 | assert ck["arch_flags"] == g["arch_flags"], f"{label}: CK04 flags {ck['arch_flags']} != {g['arch_flags']}" |
| 787 | assert ck["arch_flags"] & FL_REV, f"{label}: FL_REV bit missing in CK04" |
| 788 | assert ck["step"] == steps and ck["P"] == P |
| 789 | assert ck["LP"] == g.get("LP", 0) and ck["LC"] == g.get("LC", 0) and ck["NP"] == g.get("NP", 0) |
| 790 | assert max(abs(a - b) for a, b in zip(ck["params"], params_final_om)) == 0.0 |
| 791 | ck_res = subprocess.run([bin_path, "ck4load", ck4_path], capture_output=True, text=True) |
| 792 | assert ck_res.returncode == 0, f"{label}: ck4load failed: {ck_res.stderr}" |
| 793 | ck_toks = ck_res.stdout.strip().split() |
| 794 | assert ck_toks == ["C4", str(P), str(g["arch_flags"]), str(g["LV"])], f"unexpected ck4load: {ck_toks}" |
| 795 | |
| 796 | print( |
| 797 | f"PASS {label:18s} inv={inv_err_om:.2e} py_inv={py_inv_err:.2e} " |
| 798 | f"grad_eq={max_g_om_vs_cached:.2e} fd={worst_fd:.2e} " |
| 799 | f"loss={step_losses_om[0]:.4f}->{step_losses_om[-1]:.4f} act_bytes={act_bytes} ck4_flags={ck['arch_flags']}" |
| 800 | ) |
| 801 | |
| 802 | |
| 803 | def f32_round(x): |
| 804 | return struct.unpack("<f", struct.pack("<f", x))[0] |
| 805 | |
| 806 | |
| 807 | def bf16_sim(x): |
| 808 | bits = struct.unpack("<I", struct.pack("<f", x))[0] & 0xFFFF0000 |
| 809 | return struct.unpack("<f", struct.pack("<I", bits))[0] |
| 810 | |
| 811 | |
| 812 | def q32_quant(x): |
| 813 | s = x * Q32_SCALE |
| 814 | return int(s + 0.5) if s >= 0.0 else int(s - 0.5) |
| 815 | |
| 816 | |
| 817 | def run_q32_contrast_test(oracle_bin, tmpdir): |
| 818 | # 1. Demonstrate FP32 & BF16 bit-loss at 1e5 / 1e-4 ratio (1e9 dynamic range) |
| 819 | n = 64 |
| 820 | nl = 8 |
| 821 | x_init = [ |
| 822 | (100000.0 + ((splitmix64(5000 + i) >> 11) * (2.0 ** -53)) * 1000.0) * (-1.0 if (i & 1) else 1.0) |
| 823 | for i in range(n) |
| 824 | ] |
| 825 | perts = [] |
| 826 | for l in range(nl): |
| 827 | layer_p = [] |
| 828 | for i in range(n): |
| 829 | r = (splitmix64(l * 1009 + i * 17 + 31337) >> 11) * (2.0 ** -53) |
| 830 | v = (2.0 * r - 1.0) * 1.5e-4 |
| 831 | if abs(v) < 5.0e-5: |
| 832 | v = v + 5.0e-5 if v >= 0.0 else v - 5.0e-5 |
| 833 | layer_p.append(bf16_sim(v)) |
| 834 | perts.append(layer_p) |
| 835 | |
| 836 | # In FP32, adding 1e-4 perturbations onto ~1e5 magnitudes loses bits completely |
| 837 | x_f32 = [f32_round(v) for v in x_init] |
| 838 | for l in range(nl): |
| 839 | for i in range(n): |
| 840 | x_f32[i] = f32_round(x_f32[i] + perts[l][i]) |
| 841 | assert x_f32 == [f32_round(v) for v in x_init], "expected FP32 to drop 1e-4 updates on 1e5 residuals" |
| 842 | |
| 843 | # Even with slightly larger BF16-scale perturbations, float addition+subtraction fails bit-reversibility |
| 844 | x_bf = bf16_sim(100000.0) |
| 845 | f_bf = bf16_sim(512.0 * 0.25) |
| 846 | assert bf16_sim(bf16_sim(x_bf + f_bf) - f_bf) != x_bf, "expected BF16 (x+F)-F != x" |
| 847 | |
| 848 | # Q30 i64 integer stream preserves every bit of the 1e-4 updates and reverses to 0 bit diff |
| 849 | x_q = [q32_quant(v) for v in x_init] |
| 850 | x_q_orig = list(x_q) |
| 851 | for l in range(nl): |
| 852 | for i in range(n): |
| 853 | x_q[i] += q32_quant(perts[l][i]) |
| 854 | assert x_q != x_q_orig, "Q30 stream failed to accumulate 1e-4 updates" |
| 855 | for l in range(nl - 1, -1, -1): |
| 856 | for i in range(n): |
| 857 | x_q[i] -= q32_quant(perts[l][i]) |
| 858 | assert x_q == x_q_orig, "Q30 inverse stream failed bit-exact reconstruction" |
| 859 | |
| 860 | # 2. Full transformer oracle check with FL_REV | FL_Q32 (flag 256) enabled |
| 861 | out_bin = os.path.join(tmpdir, "q32_rev.bin") |
| 862 | ck4_path = os.path.join(tmpdir, "q32_rev.ck4") |
| 863 | fl = FL_REV | FL_Q32 | FL_ROPE | FL_SWIGLU | FL_ADAMW |
| 864 | argv = [ |
| 865 | oracle_bin, "oracle", |
| 866 | str(fl), "32", "4", "8", "2", "1", "16", "2", "2", |
| 867 | "0", "0", "0", "77", "2", out_bin, ck4_path, |
| 868 | ] |
| 869 | res = subprocess.run(argv, capture_output=True, text=True) |
| 870 | assert res.returncode == 0, f"q32_rev oracle failed: rc={res.returncode} {res.stderr}" |
| 871 | with open(out_bin, "rb") as f: |
| 872 | raw = f.read() |
| 873 | P, inv_err_om, ls_om, act_bytes, pair_bytes = struct.unpack("<QddQQ", raw[:40]) |
| 874 | assert inv_err_om == 0.0, f"expected exact 0.0 inverse error with FL_Q32, got {inv_err_om:.3e}" |
| 875 | assert act_bytes == 0 |
| 876 | ck = read_ck4(ck4_path) |
| 877 | assert ck["arch_flags"] & FL_Q32 |
| 878 | print( |
| 879 | f"PASS q32_lock4 fp32_dropped=True q30_inv_bits=0 " |
| 880 | f"model_q32_inv={inv_err_om:.2e} loss={ls_om:.4f} ck4_flags={ck['arch_flags']}" |
| 881 | ) |
| 882 | |
| 883 | |
| 884 | def main(): |
| 885 | root = find_repo_root() |
| 886 | omc = find_omc() |
| 887 | is_mac = platform.system() == "Darwin" |
| 888 | is_a64_linux = platform.system() == "Linux" and platform.machine() == "aarch64" |
| 889 | with tempfile.TemporaryDirectory() as tmpdir: |
| 890 | gb10_om2 = os.path.join(tmpdir, "rev-gb10-om2") |
| 891 | compile_target(omc, root, gb10_om2, "gb10_om2") |
| 892 | assert os.path.getsize(gb10_om2) > 0 |
| 893 | |
| 894 | if is_mac: |
| 895 | mac_om1 = os.path.join(tmpdir, "rev-mac-om1") |
| 896 | mac_om2 = os.path.join(tmpdir, "rev-mac-om2") |
| 897 | compile_target(omc, root, mac_om1, "mac_om1") |
| 898 | compile_target(omc, root, mac_om2, "mac_om2") |
| 899 | print( |
| 900 | f"PASS compile mac_om1={os.path.getsize(mac_om1)}B " |
| 901 | f"mac_om2={os.path.getsize(mac_om2)}B gb10_om2={os.path.getsize(gb10_om2)}B" |
| 902 | ) |
| 903 | run_pairs = [("mac_om1", mac_om1), ("mac_om2", mac_om2)] |
| 904 | oracle_bin = mac_om2 |
| 905 | elif is_a64_linux: |
| 906 | print(f"PASS compile gb10_om2={os.path.getsize(gb10_om2)}B") |
| 907 | run_pairs = [("gb10_om2", gb10_om2)] |
| 908 | oracle_bin = gb10_om2 |
| 909 | else: |
| 910 | print(f"PASS compile gb10_om2={os.path.getsize(gb10_om2)}B (non-arm64 runtime skipped)") |
| 911 | return |
| 912 | |
| 913 | for label, bin_p in run_pairs: |
| 914 | st = subprocess.run([bin_p, "selftest"], capture_output=True, text=True) |
| 915 | assert st.returncode == 0, f"{label} selftest failed:\n{st.stdout}\n{st.stderr}" |
| 916 | for tok in ("PASS I1 ", "PASS G1 ", "PASS I2 ", "PASS G2 ", "PASS TR ", "PASS Q32 0 ", "PASS DETBWD 0 "): |
| 917 | assert tok in st.stdout, f"{label} selftest missing {tok!r} in:\n{st.stdout}" |
| 918 | m0 = subprocess.run([bin_p, "mode0"], capture_output=True, text=True) |
| 919 | assert m0.returncode == 0, f"{label} mode0 failed:\n{m0.stdout}\n{m0.stderr}" |
| 920 | q32 = subprocess.run([bin_p, "q32"], capture_output=True, text=True) |
| 921 | assert q32.returncode == 0 and "PASS Q32 0 8" in q32.stdout, ( |
| 922 | f"{label} q32 failed:\n{q32.stdout}\n{q32.stderr}" |
| 923 | ) |
| 924 | det = subprocess.run([bin_p, "detbwd"], capture_output=True, text=True) |
| 925 | assert det.returncode == 0 and "PASS DETBWD 0 " in det.stdout, ( |
| 926 | f"{label} detbwd failed:\n{det.stdout}\n{det.stderr}" |
| 927 | ) |
| 928 | print(f"PASS selftest+mode0 {[lbl for lbl, _ in run_pairs]} passed built-in self-tests (incl. Q32 & DETBWD)") |
| 929 | |
| 930 | # Verify Lock 4 contrast: FP32/BF16 stream drops/corrupts 1e-4 updates on 1e5 residuals, |
| 931 | # whereas Q30 i64 fixed-point stream preserves every bit across 8 layers and reverses to 0 bit diff. |
| 932 | run_q32_contrast_test(oracle_bin, tmpdir) |
| 933 | |
| 934 | cases = [ |
| 935 | ("gpt_relu_rev", dict( |
| 936 | arch_flags=FL_REV, V=32, T=4, D=8, H=2, H_kv=2, F=16, L=2, B=2, |
| 937 | LP=0, LC=0, NP=0, seed=42, total=50, lr=0.01, |
| 938 | rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, |
| 939 | )), |
| 940 | ("llama_rope_gqa", dict( |
| 941 | arch_flags=FL_REV | FL_ROPE | FL_SWIGLU | FL_ADAMW, |
| 942 | V=32, T=4, D=8, H=2, H_kv=1, F=16, L=2, B=2, |
| 943 | LP=0, LC=0, NP=0, seed=101, total=50, lr=0.01, |
| 944 | rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, |
| 945 | )), |
| 946 | ("qwen3_looped_np3", dict( |
| 947 | arch_flags=FL_REV | FL_ROPE | FL_SWIGLU | FL_UNTIED | FL_QKNORM | FL_ADAMW, |
| 948 | V=32, T=4, D=8, H=2, H_kv=1, F=16, L=3, B=2, |
| 949 | LP=1, LC=1, NP=3, seed=202, total=50, lr=0.01, |
| 950 | rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, |
| 951 | )), |
| 952 | ("gelu_rev", dict( |
| 953 | arch_flags=FL_REV | FL_GELU, |
| 954 | V=24, T=4, D=8, H=2, H_kv=2, F=16, L=2, B=2, |
| 955 | LP=0, LC=0, NP=0, seed=303, total=50, lr=0.01, |
| 956 | rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, |
| 957 | )), |
| 958 | ("geglu_rope_rev", dict( |
| 959 | arch_flags=FL_REV | FL_ROPE | FL_GEGLU | FL_ADAMW, |
| 960 | V=24, T=4, D=8, H=2, H_kv=1, F=16, L=2, B=2, |
| 961 | LP=0, LC=0, NP=0, seed=404, total=50, lr=0.01, |
| 962 | rope_theta_milli=10_000_000, rms_eps=1e-5, wd=0.05, warmup=10, |
| 963 | )), |
| 964 | ] |
| 965 | for label, cfg in cases: |
| 966 | run_oracle_case(oracle_bin, tmpdir, label, cfg) |
| 967 | |
| 968 | print("ALL PILLAR 2 REVERSIBLE CHECKS PASSED") |
| 969 | |
| 970 | |
| 971 | if __name__ == "__main__": |
| 972 | main() |