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/omega-bridge/blob/main/conformance/oracle.py # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings 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 `omega-bridge / conformance / oracle.py` 378 lines ยท 12823 bytes Raw Blame History 1 # Vendored from omega-mv tests/max-interop/oracle.py (Apache-2.0 WITH LLVM-exception), 2 # frozen contract ids `647116fc`... and `003696e4`.... The copy is byte-identical 3 # apart from this header; sha256 is recorded in conformance/EVIDENCE.md. 4 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 5 """Independent pure-Python reference for the MAX interop contracts. 6 7 This module deliberately uses only the Python standard library. It does not 8 call CUDApp, Omega, or any compiled helper: every number here is produced from 9 the contract semantics by ordinary Python code. 10 11 Conventions 12 ----------- 13 * bf16 values are carried as unsigned 16-bit integers (their bit pattern). 14 * f32 values are carried as unsigned 32-bit integers (their bit pattern). 15 * matmul accumulates exact bf16 products in fp64 (Python float), in k order. 16 * attention accumulates fp64 scores and fp64 weighted sums, with causal 17 inclusive masking and max-subtracted softmax. 18 """ 19 20 from __future__ import annotations 21 22 import hashlib 23 import json 24 import math 25 import struct 26 27 MATMUL_CONTRACT_ID = "`647116fc1ba1e1394982fc8ba181ce565293f160a6b56afc0f02b2128a675704`" 28 GQA_CONTRACT_ID = "`003696e422bba7274877ba9e01a61076ea0f862f32760cbaa06c60f85a115359`" 29 30 HEAD_DIM = 128 31 MATMUL_TOL = 1e-5 32 ATTN_REL_NORMAL = 2e-4 33 ATTN_ABS_NORMAL = 2e-5 34 ATTN_REL_LARGE = 1e-3 35 ATTN_ABS_LARGE = 1e-4 36 37 38 # --------------------------------------------------------------------------- 39 # bit-level helpers 40 41 42 def f32_bits(value: float) -> int: 43 return struct.unpack(" float: 47 return struct.unpack(" float: 51 """Round a double to the nearest IEEE binary32 value (ties to even).""" 52 return f32_from_bits(f32_bits(value)) 53 54 55 def bf16_from_bits(bits: int) -> float: 56 """Exact bf16 -> double conversion (bf16 is the high half of f32).""" 57 return f32_from_bits((bits & 0xFFFF) << 16) 58 59 60 def bf16_bits(value: float) -> int: 61 """Round a double to bf16 with round-to-nearest-even, rejecting Inf/NaN.""" 62 bits = f32_bits(value) 63 if (bits & 0x7F800000) == 0x7F800000: 64 raise ValueError("bf16: non-finite input") 65 rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) >> 16 66 if (rounded & 0x7F80) == 0x7F80: 67 raise ValueError("bf16: rounding overflow") 68 return rounded & 0xFFFF 69 70 71 def bf16_is_finite(bits: int) -> bool: 72 return ((bits >> 7) & 0xFF) != 0xFF 73 74 75 def bits_hex16(bits: list[int]) -> list[str]: 76 return [f"0x{b:04x}" for b in bits] 77 78 79 def bits_hex32(bits: list[int]) -> list[str]: 80 return [f"0x{b:08x}" for b in bits] 81 82 83 def parse_bits16(items: list[str]) -> list[int]: 84 return [int(x, 16) for x in items] 85 86 87 def parse_bits32(items: list[str]) -> list[int]: 88 return [int(x, 16) for x in items] 89 90 91 # --------------------------------------------------------------------------- 92 # matmul 93 94 95 def _flat_index(i: int, j: int, cols: int) -> int: 96 return i * cols + j 97 98 99 def matmul_bf16_ref( 100 a_bits: list[int], b_bits: list[int], m: int, k: int, n: int 101 ) -> list[float]: 102 """fp64 reference: C[i,j] = sum_p exact_bf16(A[i,p]) * exact_bf16(B[p,j]).""" 103 if m < 1 or k < 1 or n < 1: 104 raise ValueError("matmul: dimensions must be positive") 105 if len(a_bits) != m * k or len(b_bits) != k * n: 106 raise ValueError("matmul: buffer length does not match shape") 107 for bits in a_bits: 108 if not bf16_is_finite(bits): 109 raise ValueError("matmul: non-finite A") 110 for bits in b_bits: 111 if not bf16_is_finite(bits): 112 raise ValueError("matmul: non-finite B") 113 a = [bf16_from_bits(x) for x in a_bits] 114 b = [bf16_from_bits(x) for x in b_bits] 115 out: list[float] = [0.0] * (m * n) 116 for i in range(m): 117 for j in range(n): 118 acc = 0.0 119 for p in range(k): 120 acc += a[_flat_index(i, p, k)] * b[_flat_index(p, j, n)] 121 out[_flat_index(i, j, n)] = acc 122 return out 123 124 125 def matmul_fp32_output(ref: list[float]) -> list[float]: 126 return [fp32(x) for x in ref] 127 128 129 def matmul_error(out: list[float], ref: list[float]) -> float: 130 if len(out) != len(ref): 131 raise ValueError("matmul: output length does not match reference") 132 worst = 0.0 133 for got, want in zip(out, ref): 134 if not math.isfinite(got): 135 return math.inf 136 err = abs(got - want) 137 allowed = MATMUL_TOL * max(1.0, abs(want)) 138 if err > allowed: 139 worst = max(worst, err / allowed) 140 return worst 141 142 143 def matmul_matches(out: list[float], ref: list[float]) -> bool: 144 return len(out) == len(ref) and matmul_error(out, ref) <= 1.0 145 146 147 # --------------------------------------------------------------------------- 148 # causal grouped-query attention 149 150 151 def _attention_shape( 152 q: list[float], k: list[float], v: list[float], hq: int, hkv: int, head_dim: int 153 ) -> tuple[int, int]: 154 if hq < 1 or hkv < 1 or head_dim < 1: 155 raise ValueError("attention: dimensions must be positive") 156 if hq % hkv != 0: 157 raise ValueError("attention: q_heads must be a multiple of kv_heads") 158 if len(q) % (hq * head_dim) != 0: 159 raise ValueError("attention: q length does not match heads") 160 r = len(q) // (hq * head_dim) 161 if len(k) != len(v) or len(k) % (hkv * head_dim) != 0: 162 raise ValueError("attention: k/v length does not match heads") 163 t = len(k) // (hkv * head_dim) 164 return r, t 165 166 167 def attention_ref( 168 q: list[float], 169 k: list[float], 170 v: list[float], 171 base: int, 172 hq: int, 173 hkv: int, 174 head_dim: int = HEAD_DIM, 175 causal: bool = True, 176 head_map: str = "div", 177 ) -> list[float]: 178 """fp64 reference for the rows/causal GQA variant. 179 180 q is [R][Hq][D], k/v are [T][Hkv][D], flat. For causal rows, query row i 181 attends tokens 0..base+i inclusive; the contract shape requires T = base+R. 182 `head_map='mod'` is the deliberate wrong variant used by the mutation test. 183 """ 184 r, t = _attention_shape(q, k, v, hq, hkv, head_dim) 185 for buf in (q, k, v): 186 for x in buf: 187 if not math.isfinite(x): 188 raise ValueError("attention: non-finite input") 189 if r == 0: 190 return [] 191 if t == 0: 192 return [0.0] * (r * hq * head_dim) 193 if causal and t < base + r: 194 raise ValueError("attention: T must be at least base + R") 195 ratio = hq // hkv 196 scale = 1.0 / math.sqrt(head_dim) 197 out = [0.0] * (r * hq * head_dim) 198 for i in range(r): 199 if causal: 200 allowed = base + i + 1 201 else: 202 allowed = t 203 if allowed > t: 204 raise ValueError("attention: mask exceeds T") 205 for h in range(hq): 206 if head_map == "div": 207 hk = h // ratio 208 elif head_map == "mod": 209 hk = h % hkv 210 else: 211 raise ValueError("attention: unknown head map") 212 scores: list[float] = [] 213 for tok in range(allowed): 214 score = 0.0 215 q_off = (i * hq + h) * head_dim 216 k_off = (tok * hkv + hk) * head_dim 217 for d in range(head_dim): 218 score += q[q_off + d] * k[k_off + d] 219 scores.append(score * scale) 220 top = max(scores) 221 exps = [math.exp(s - top) for s in scores] 222 total = sum(exps) 223 acc = [0.0] * head_dim 224 for tok, weight in enumerate(exps): 225 p = weight / total 226 v_off = (tok * hkv + hk) * head_dim 227 for d in range(head_dim): 228 acc[d] += p * v[v_off + d] 229 o_off = (i * hq + h) * head_dim 230 out[o_off : o_off + head_dim] = acc 231 return out 232 233 234 def attention_fp32_output(ref: list[float]) -> list[float]: 235 return [fp32(x) for x in ref] 236 237 238 def attention_error( 239 out: list[float], ref: list[float], rel: float, abs_tol: float 240 ) -> float: 241 if len(out) != len(ref): 242 raise ValueError("attention: output length does not match reference") 243 worst = 0.0 244 for got, want in zip(out, ref): 245 if not math.isfinite(got): 246 return math.inf 247 err = abs(got - want) 248 allowed = max(abs_tol, rel * abs(want)) 249 if err > allowed: 250 worst = max(worst, err / allowed) 251 return worst 252 253 254 def attention_matches( 255 out: list[float], 256 ref: list[float], 257 rel: float = ATTN_REL_NORMAL, 258 abs_tol: float = ATTN_ABS_NORMAL, 259 ) -> bool: 260 return len(out) == len(ref) and attention_error(out, ref, rel, abs_tol) <= 1.0 261 262 263 def attention_matches_large(out: list[float], ref: list[float]) -> bool: 264 return attention_matches(out, ref, ATTN_REL_LARGE, ATTN_ABS_LARGE) 265 266 267 # --------------------------------------------------------------------------- 268 # deterministic fixtures 269 270 271 MASK64 = (1 << 64) - 1 272 273 274 class SplitMix64: 275 def __init__(self, seed: int): 276 self.state = seed & MASK64 277 278 def next_u64(self) -> int: 279 self.state = (self.state + 0x9E3779B97F4A7C15) & MASK64 280 z = self.state 281 z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK64 282 z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK64 283 return (z ^ (z >> 31)) & MASK64 284 285 def next_bf16_value(self) -> float: 286 # |numerator| <= 255 needs at most 8 significant bits, exactly bf16. 287 return ((self.next_u64() % 511) - 255) / 64.0 288 289 def next_f32_value(self) -> float: 290 # |numerator| <= 2048 needs at most 12 significant bits, exactly f32. 291 return ((self.next_u64() % 4097) - 2048) / 1024.0 292 293 294 def input_checksum(bits: list[str]) -> str: 295 """Checksum over the canonical JSON form of one bit-string input array.""" 296 return hashlib.sha256( 297 json.dumps(bits, separators=(",", ":")).encode("ascii") 298 ).hexdigest() 299 300 301 def make_matmul_fixture(seed: int = 680) -> dict: 302 rng = SplitMix64(seed) 303 m, k, n = 4, 5, 3 304 a_bits = [bf16_bits(rng.next_bf16_value()) for _ in range(m * k)] 305 b_bits = [bf16_bits(rng.next_bf16_value()) for _ in range(k * n)] 306 ref = matmul_bf16_ref(a_bits, b_bits, m, k, n) 307 out_bits = [f32_bits(fp32(x)) for x in ref] 308 a_hex = bits_hex16(a_bits) 309 b_hex = bits_hex16(b_bits) 310 return { 311 "format": "omega-fixture/1", 312 "name": "matmul-v1", 313 "contract": "matmul-bf16-v1", 314 "contract_id": MATMUL_CONTRACT_ID, 315 "generator": {"algorithm": "splitmix64", "seed": seed}, 316 "shape": {"m": m, "k": k, "n": n}, 317 "dtype": {"a": "bf16", "b": "bf16", "c": "f32"}, 318 "layout": {"a": "row-major", "b": "row-major", "c": "row-major"}, 319 "checksum_format": "sha256 of json.dumps(bits, separators=(',', ':'))", 320 "inputs": {"a": a_hex, "b": b_hex}, 321 "input_sha256": { 322 "a": input_checksum(a_hex), 323 "b": input_checksum(b_hex), 324 }, 325 "reference": {"c": bits_hex32(out_bits)}, 326 "tolerance": "abs<=1e-5*max(1,abs(ref))", 327 } 328 329 330 def make_attention_fixture(seed: int = 680) -> dict: 331 rng = SplitMix64(seed ^ 0xA77E0710) 332 r, base, hq, hkv, head_dim = 2, 1, 4, 2, HEAD_DIM 333 t = base + r 334 q_bits = [f32_bits(fp32(rng.next_f32_value())) for _ in range(r * hq * head_dim)] 335 k_bits = [f32_bits(fp32(rng.next_f32_value())) for _ in range(t * hkv * head_dim)] 336 v_bits = [f32_bits(fp32(rng.next_f32_value())) for _ in range(t * hkv * head_dim)] 337 q = [f32_from_bits(x) for x in q_bits] 338 k = [f32_from_bits(x) for x in k_bits] 339 v = [f32_from_bits(x) for x in v_bits] 340 ref = attention_ref(q, k, v, base, hq, hkv, head_dim) 341 out_bits = [f32_bits(fp32(x)) for x in ref] 342 q_hex = bits_hex32(q_bits) 343 k_hex = bits_hex32(k_bits) 344 v_hex = bits_hex32(v_bits) 345 return { 346 "format": "omega-fixture/1", 347 "name": "gqa-causal-v1", 348 "contract": "gqa-causal-v1", 349 "contract_id": GQA_CONTRACT_ID, 350 "generator": {"algorithm": "splitmix64", "seed": seed ^ 0xA77E0710}, 351 "shape": { 352 "r": r, 353 "base": base, 354 "t": t, 355 "hq": hq, 356 "hkv": hkv, 357 "head_dim": head_dim, 358 }, 359 "dtype": {"q": "f32", "k": "f32", "v": "f32", "out": "f32"}, 360 "layout": "token-head-dim", 361 "mask": "causal-inclusive", 362 "checksum_format": "sha256 of json.dumps(bits, separators=(',', ':'))", 363 "inputs": {"q": q_hex, "k": k_hex, "v": v_hex}, 364 "input_sha256": { 365 "q": input_checksum(q_hex), 366 "k": input_checksum(k_hex), 367 "v": input_checksum(v_hex), 368 }, 369 "reference": {"out": bits_hex32(out_bits)}, 370 "tolerance": { 371 "normal": "rel<=2e-4,abs<=2e-5", 372 "large_scores": "rel<=1e-3,abs<=1e-4", 373 }, 374 } 375 376 377 def fixture_bytes(fixture: dict) -> bytes: 378 return (json.dumps(fixture, indent=2, sort_keys=True) + "\n").encode("utf-8")