omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / om / gpu / dsv41 / check-head.py
| 1 | """Compare every vocabulary logit against an independent CPU head using the pinned BF16 shard.""" |
| 2 | import hashlib |
| 3 | import json |
| 4 | import struct |
| 5 | import sys |
| 6 | from urllib.request import Request, urlopen |
| 7 | from pathlib import Path |
| 8 | |
| 9 | import numpy as np |
| 10 | |
| 11 | |
| 12 | def widened(words): |
| 13 | return (words.astype(np.uint32) << 16).view(np.float32) |
| 14 | |
| 15 | |
| 16 | def rounded(x): |
| 17 | bits = np.ascontiguousarray(x, dtype="<f4").view(np.uint32) |
| 18 | return ((bits + 32767 + ((bits >> 16) & 1)) & 0xffff0000).view(np.float32) |
| 19 | |
| 20 | |
| 21 | def load_tensors(path): |
| 22 | expected = "d762b688f138e00a24eac96f27b842715bb4b534ecc9ca39076bed2b8c33201e" |
| 23 | with path.open("rb") as f: |
| 24 | if hashlib.file_digest(f, "sha256").hexdigest() != expected: |
| 25 | raise ValueError("checkpoint shard SHA-256 mismatch") |
| 26 | f.seek(0) |
| 27 | n, = struct.unpack("<Q", f.read(8)) |
| 28 | meta = json.loads(f.read(n)) |
| 29 | def tensor(key): |
| 30 | info = meta[key] |
| 31 | return np.memmap(path, mode="r", dtype="<u2", shape=tuple(info["shape"]), |
| 32 | offset=8+n+info["data_offsets"][0]) |
| 33 | return tensor("head.weight"), widened(tensor("norm.weight")) |
| 34 | |
| 35 | |
| 36 | def fixture(path): |
| 37 | """Fetch only embedding rows 1234..1241 from the pinned public shard.""" |
| 38 | base = ("https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/resolve/" |
| 39 | "314113f8a7dadb388215396ba5fbee2c610a04d6/model-00002-of-00048.safetensors") |
| 40 | start = 8 + 344 + 1234 * 10240 |
| 41 | stop = start + 81920 - 1 |
| 42 | req = Request(f"{base}?omega-range={start}-{stop}", headers={"Range": f"bytes={start}-{stop}"}) |
| 43 | with urlopen(req, timeout=60) as resp: |
| 44 | if resp.status != 206 or not resp.headers.get("Content-Range", "").startswith(f"bytes {start}-{stop}/"): |
| 45 | raise ValueError("embedding server did not honor the byte range") |
| 46 | rows = resp.read(81921) |
| 47 | if hashlib.sha256(rows).hexdigest() != "bbbf862be017006ae7d4e4e6dfe9d6883364ef74314a7c17825bd0c8dd9cc7a6": |
| 48 | raise ValueError("embedding slice SHA-256 mismatch") |
| 49 | frames = (rows[:40960] + struct.pack("<4f", .1, .3, .6, 0.) + |
| 50 | rows[40960:] + struct.pack("<4f", -.2, .4, 1., .25)) |
| 51 | cancellation = b"".join(struct.pack("<H", word) * 5120 for word in (0xbf80, 0x3f81, 0, 0)) |
| 52 | frames += cancellation + struct.pack("<4f", 8454145/16777216, 8388609/16777216, .5, .5) |
| 53 | # BF16 2**70 is finite. Its FP32 square overflows, giving this frame zero RMS gain. |
| 54 | frames += struct.pack("<H", 0x6280) * 5120 + bytes(30720) + struct.pack("<4f", 1, 0, 0, 0) |
| 55 | with path.open("xb") as f: |
| 56 | f.write(frames) |
| 57 | |
| 58 | |
| 59 | def verify(shard, frames, logits): |
| 60 | weights, gain = load_tensors(shard) |
| 61 | width = gain.size |
| 62 | data = frames.read_bytes() |
| 63 | record_size = 8 * width + 16 |
| 64 | count, tail = divmod(len(data), record_size) |
| 65 | if tail or not count: |
| 66 | raise ValueError("expected one or more complete residual frames") |
| 67 | if logits.stat().st_size != count * weights.shape[0] * 4: |
| 68 | raise ValueError("output byte length does not match complete frames") |
| 69 | actual = np.fromfile(logits, "<f4").reshape(count, weights.shape[0]) |
| 70 | hidden = [] |
| 71 | for i in range(count): |
| 72 | offset = i * record_size |
| 73 | streams = widened(np.frombuffer(data, "<u2", 4*width, offset).reshape(4, width)) |
| 74 | mix = np.frombuffer(data, "<f4", 4, offset+8*width) |
| 75 | state = rounded((streams * mix[:, None]).sum(axis=0, dtype=np.float32)) |
| 76 | with np.errstate(over="ignore"): |
| 77 | var = np.mean(np.square(state), dtype=np.float32) |
| 78 | rms = np.float32(1) / np.sqrt(var + np.float32(1e-20)) |
| 79 | hidden.append(rounded(state*rms*gain)) |
| 80 | hidden = np.stack(hidden) |
| 81 | reference = np.empty_like(actual) |
| 82 | for lo in range(0, weights.shape[0], 1024): |
| 83 | block = widened(weights[lo:lo+1024]).astype(np.float64) |
| 84 | reference[:,lo:lo+len(block)] = hidden.astype(np.float64) @ block.T |
| 85 | for i, (got, want) in enumerate(zip(actual, reference)): |
| 86 | if not np.isfinite(got).all(): |
| 87 | raise ValueError(f"frame {i} contains nonfinite logits") |
| 88 | np.testing.assert_allclose(got, want, rtol=4e-5, atol=4e-5) |
| 89 | if got.argmax() != want.argmax(): |
| 90 | raise AssertionError(f"frame {i} greedy token mismatch") |
| 91 | print(f"PASS frame={i} logits={len(got)} max_abs_error={np.max(np.abs(got-want)):.8g} " |
| 92 | f"greedy_token_id={got.argmax()}") |
| 93 | |
| 94 | |
| 95 | if __name__ == "__main__": |
| 96 | if len(sys.argv) == 3 and sys.argv[1] == "--fixture": |
| 97 | fixture(Path(sys.argv[2])) |
| 98 | elif len(sys.argv) == 4: |
| 99 | verify(*(Path(arg) for arg in sys.argv[1:])) |
| 100 | else: |
| 101 | sys.exit("usage: check-head.py --fixture FRAMES | SHARD FRAMES LOGITS") |