omega-bridge
Omega-first language interoperability: checked conversion backends and native language bindings
Brought by drakestapleton
omega-bridge / tests / seeded_float.py
| 1 | """Seeded-only internal binary32/binary64 differential and fail-closed controls. |
| 2 | |
| 3 | The seeded omc executable is the reference: every case below compares its AArch64 |
| 4 | output bytes with the generated C on this host and, when the cross tools exist, on |
| 5 | x86-64 under qemu-x86_64. Float constants are also checked against an exact |
| 6 | round-to-nearest-even decimal oracle written with fractions.Fraction. |
| 7 | No GPU, CUDA runtime, driver or hardware access. |
| 8 | """ |
| 9 | import fractions |
| 10 | import os |
| 11 | import pathlib |
| 12 | import re |
| 13 | import shutil |
| 14 | import struct |
| 15 | import subprocess |
| 16 | import sys |
| 17 | |
| 18 | root = pathlib.Path(__file__).resolve().parents[1] |
| 19 | os.chdir(root) |
| 20 | b = root / 'build/seeded-float' |
| 21 | b.mkdir(parents=True, exist_ok=True) |
| 22 | seed = os.environ.get('OMEGA_SEEDED_OMC') |
| 23 | if not seed: |
| 24 | sys.exit('NOT_RUN: set OMEGA_SEEDED_OMC to the pinned e5b32567 compiler') |
| 25 | x86 = shutil.which('x86_64-linux-gnu-gcc') and shutil.which('qemu-x86_64') |
| 26 | |
| 27 | def run(args, data=None): |
| 28 | return subprocess.run(list(map(str, args)), input=data, capture_output=True, timeout=120) |
| 29 | |
| 30 | def checked(args, data=None): |
| 31 | p = run(args, data) |
| 32 | assert p.returncode == 0, (args, p.returncode, p.stderr) |
| 33 | return p.stdout |
| 34 | |
| 35 | def differential(name, source): |
| 36 | """Native seeded executable bytes == generated C bytes (host and x86-64).""" |
| 37 | f = b / (name + '.om') |
| 38 | f.write_text(source) |
| 39 | native = b / (name + '.native') |
| 40 | native.write_bytes(checked([seed], source.encode())) |
| 41 | native.chmod(0o755) |
| 42 | expected = checked([native]) |
| 43 | c = b / (name + '.c') |
| 44 | c.write_bytes(checked(['sh', 'tools/bridge-seeded', 'c', f])) |
| 45 | checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', c, '-o', b / (name + '.host')]) |
| 46 | assert checked([b / (name + '.host')]) == expected, name |
| 47 | if x86: |
| 48 | checked(['x86_64-linux-gnu-gcc', '-static', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', |
| 49 | c, '-o', b / (name + '.x86')]) |
| 50 | assert checked(['qemu-x86_64', b / (name + '.x86')]) == expected, name |
| 51 | return f, c, expected |
| 52 | |
| 53 | def nearest(text, frac, ebits): |
| 54 | """Exact decimal -> IEEE binary bits, round to nearest, ties to even.""" |
| 55 | q = fractions.Fraction(text) |
| 56 | sign = 1 if text.startswith('-') else 0 |
| 57 | q = abs(q) |
| 58 | bias = (1 << (ebits - 1)) - 1 |
| 59 | if q == 0: |
| 60 | return sign << (frac + ebits) |
| 61 | e = q.numerator.bit_length() - q.denominator.bit_length() |
| 62 | while fractions.Fraction(2) ** e > q: |
| 63 | e -= 1 |
| 64 | while fractions.Fraction(2) ** (e + 1) <= q: |
| 65 | e += 1 |
| 66 | e = max(e, 1 - bias) |
| 67 | m = q * fractions.Fraction(2) ** (frac - e) |
| 68 | n = m.numerator // m.denominator |
| 69 | rest = m - n |
| 70 | if rest > fractions.Fraction(1, 2) or (rest == fractions.Fraction(1, 2) and n % 2): |
| 71 | n += 1 |
| 72 | if n == 1 << (frac + 1): |
| 73 | n >>= 1 |
| 74 | e += 1 |
| 75 | field = 0 if n < 1 << frac else e + bias |
| 76 | assert field < (1 << ebits) - 1, ('overflow fixture', text) |
| 77 | return (sign << (frac + ebits)) | (field << frac) | (n & ((1 << frac) - 1)) |
| 78 | |
| 79 | io = '''fn w64 v ulong to ulong |
| 80 | out = new uchar 8 0 |
| 81 | for i ulong 8 |
| 82 | put out i uchar and shr v mul i 8 255 |
| 83 | end |
| 84 | n = write 1 out 0 8 |
| 85 | ret 0 |
| 86 | end |
| 87 | fn w64s v long to ulong |
| 88 | if lt v 0 |
| 89 | ret w64 sub 18446744073709551615 ulong neg add v 1 |
| 90 | end |
| 91 | ret w64 ulong v |
| 92 | end |
| 93 | ''' |
| 94 | |
| 95 | def compares(x, y): |
| 96 | s = 'c = ulong 0\n' |
| 97 | for bit, op in enumerate(['eq', 'ne', 'lt', 'le', 'gt', 'ge']): |
| 98 | s += f'if {op} {x} {y}\nc = or c {1 << bit}\nend\n' |
| 99 | return s + 'r = w64 c\n' |
| 100 | |
| 101 | def grouped(prefix, calls, size=40): |
| 102 | s, names = '', [] |
| 103 | for g in range(0, len(calls), size): |
| 104 | names.append(f'{prefix}{g // size}') |
| 105 | s += f'fn {names[-1]} to ulong\n' + ''.join(f'r = {c}\n' for c in calls[g:g + size]) + 'ret 0\nend\n' |
| 106 | return s, names |
| 107 | |
| 108 | # 1. Arithmetic, comparisons, conversions and bitcasts over edge bit patterns. |
| 109 | F64 = [0, 1 << 63, 0x3ff0000000000000, 0xbff0000000000000, 0x3fb999999999999a, 1, |
| 110 | 0x000fffffffffffff, 0x0010000000000000, 0x7fefffffffffffff, 0x7ff0000000000000, |
| 111 | 0xfff0000000000000, 0x7ff8000000000000, 0x7ff4000000000001, 0xfff8000000000123, |
| 112 | 0x43e0000000000000, 0x43f0000000000000, 0xc3e0000000000000, 0x41dfffffffc00000, |
| 113 | 0x4340000000000001, 0x3fe0000000000000, 0xc08f400000000000, 0x47efffffe0000000, |
| 114 | 0x36a0000000000000, 0x380fffffffffffff, 0xc1e0000000200000] |
| 115 | F32 = [0, 1 << 31, 0x3f800000, 0xbf800000, 0x3dcccccd, 1, 0x007fffff, 0x00800000, 0x7f7fffff, |
| 116 | 0x7f800000, 0xff800000, 0x7fc00000, 0x7fa00001, 0xffc00123, 0x5f000000, 0x5f800000, |
| 117 | 0xdf000000, 0x4effffff, 0x3f000000, 0xcf000000, 0x4f000000] |
| 118 | SIGNED = [0, 1, -1, 9007199254740993, -9007199254740993, 9223372036854775807, |
| 119 | -9223372036854775807, 16777217, -16777217, 2147483647, -2147483647] |
| 120 | source = io + '''fn f64ops a ulong b ulong to ulong |
| 121 | x = bitcast f64 a |
| 122 | y = bitcast f64 b |
| 123 | r = w64 bitcast ulong add x y |
| 124 | r = w64 bitcast ulong sub x y |
| 125 | r = w64 bitcast ulong mul x y |
| 126 | r = w64 bitcast ulong div x y |
| 127 | r = w64 bitcast ulong neg x |
| 128 | r = w64 bitcast ulong fabs x |
| 129 | r = w64 bitcast ulong fsqrt x |
| 130 | ''' + compares('x', 'y') + '''ret 0 |
| 131 | end |
| 132 | fn f32ops a uint b uint to ulong |
| 133 | x = bitcast f32 a |
| 134 | y = bitcast f32 b |
| 135 | r = w64 ulong bitcast uint add x y |
| 136 | r = w64 ulong bitcast uint sub x y |
| 137 | r = w64 ulong bitcast uint mul x y |
| 138 | r = w64 ulong bitcast uint div x y |
| 139 | r = w64 ulong bitcast uint neg x |
| 140 | r = w64 ulong bitcast uint fabs x |
| 141 | r = w64 ulong bitcast uint fsqrt x |
| 142 | ''' + compares('x', 'y') + '''ret 0 |
| 143 | end |
| 144 | fn f64cv a ulong to ulong |
| 145 | x = bitcast f64 a |
| 146 | r = w64 ulong x |
| 147 | r = w64s long x |
| 148 | r = w64s long int x |
| 149 | r = w64s long short x |
| 150 | r = w64s long byte x |
| 151 | r = w64 ulong uint x |
| 152 | r = w64 ulong ushort x |
| 153 | r = w64 ulong uchar x |
| 154 | r = w64 ulong bitcast uint f32 x |
| 155 | r = w64 bitcast ulong mul x 0.5 |
| 156 | r = w64 bitcast ulong f64 a |
| 157 | r = w64 ulong bitcast uint f32 a |
| 158 | r = w64s bitcast long x |
| 159 | ret 0 |
| 160 | end |
| 161 | fn f32cv a uint to ulong |
| 162 | x = bitcast f32 a |
| 163 | r = w64 bitcast ulong f64 x |
| 164 | r = w64 ulong x |
| 165 | r = w64s long x |
| 166 | r = w64s long int x |
| 167 | r = w64 ulong uint x |
| 168 | r = w64 ulong bitcast uint f32 a |
| 169 | r = w64 ulong bitcast uint sub x 1.5 |
| 170 | ret 0 |
| 171 | end |
| 172 | fn sgn s long to ulong |
| 173 | r = w64 bitcast ulong f64 s |
| 174 | r = w64 ulong bitcast uint f32 s |
| 175 | r = w64 bitcast ulong bitcast f64 s |
| 176 | ret 0 |
| 177 | end |
| 178 | fn lit to ulong |
| 179 | r = w64 bitcast ulong f64 1 |
| 180 | r = w64 bitcast ulong f64 -1 |
| 181 | r = w64 bitcast ulong f64 9007199254740993 |
| 182 | r = w64 bitcast ulong f64 9223372036854775807 |
| 183 | r = w64 bitcast ulong f64 -9223372036854775807 |
| 184 | r = w64 ulong bitcast uint f32 16777217 |
| 185 | r = w64 ulong bitcast uint f32 -3 |
| 186 | ret 0 |
| 187 | end |
| 188 | ''' |
| 189 | calls = [f'f64ops {a} {c}' for a in F64 for c in F64] + [f'f32ops {a} {c}' for a in F32 for c in F32] |
| 190 | calls += [f'f64cv {a}' for a in F64] + [f'f32cv {a}' for a in F32] + [f'sgn {s}' for s in SIGNED] + ['lit'] |
| 191 | groups, names = grouped('g', calls) |
| 192 | source += groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n' |
| 193 | f, c, expected = differential('ops', source) |
| 194 | records = (len(F64) ** 2) * 8 + (len(F32) ** 2) * 8 + len(F64) * 13 + len(F32) * 7 + len(SIGNED) * 3 + 7 |
| 195 | assert len(expected) == 8 * records, (len(expected), records) |
| 196 | # Each square-root width is exercised on both hosts above and has an independent mutant. |
| 197 | sqrt_text = c.read_text() |
| 198 | for width in (32, 64): |
| 199 | site = f'case 20:z=o_sqrt{width}(x);break;' |
| 200 | assert sqrt_text.count(site) == 1 |
| 201 | bad = b / f'sqrt{width}-mutant.c' |
| 202 | bad.write_text(sqrt_text.replace(site, 'case 20:z=x;break;')) |
| 203 | exe = b / f'sqrt{width}-mutant' |
| 204 | checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', bad, '-o', exe]) |
| 205 | assert checked([exe]) != expected, ('sqrt mutant survived', width) |
| 206 | print(f'PASS killed fsqrt{width} mutant') |
| 207 | # Integer literals under a float conversion are typed long and rounded to nearest even (omc SCVTF). |
| 208 | lits = [struct.pack('<d', float(v)) for v in (1, -1, 9007199254740993, 9223372036854775807, -9223372036854775807)] |
| 209 | lits += [struct.pack('<f', float(v)) + bytes(4) for v in (16777217, -3)] |
| 210 | assert expected[-56:] == b''.join(lits), expected[-56:].hex() |
| 211 | for target in ['python']: |
| 212 | p = run(['sh', 'tools/bridge-seeded', target, f]) |
| 213 | assert p.returncode != 0 and not p.stdout |
| 214 | p = run(['sh', 'tools/bridge', 'c', f]) |
| 215 | assert p.returncode != 0 and not p.stdout |
| 216 | # Compile-time arithmetic-mode refusal is not an ignored warning. |
| 217 | p = run(['gcc', '-std=gnu11', '-O2', '-ffast-math', c, '-o', b / 'unsafe']) |
| 218 | assert p.returncode != 0 and b'fast math' in p.stderr |
| 219 | |
| 220 | # 2. A constant table beyond the former 32/99 limits, emitted bit-exactly. The significant digits of a |
| 221 | # float literal must fit in 2^63-1 (omc and the converter: error 8), so long literals are kept to 19 digits. |
| 222 | D = ['0.1', '-0.0', '1.0', '3.141592653589793', '2.2250738585072014e-308', '4.9406564584124654e-324', |
| 223 | '2.225073858507201e-308', '1.7976931348623157e308', '9007199254740993.0', '0.30000000000000004', |
| 224 | '1.0e23', '2.2250738585072011e-308', '2.4703282292062327e-324', '2.4703282292062328e-324', |
| 225 | '1.7976931348623158e308', '123456789012345678.9e11', '0.6931471805599453', |
| 226 | '1.5707963267948966', '-2.5e-1', '0.1000000000000000055'] |
| 227 | for k in range(len(D), 100): |
| 228 | D.append(('-' if k % 3 == 0 else '') + f'{(k * 7919) % 100000}.{(k * 104729) % 1000000:06d}e{(k % 61) - 30}') |
| 229 | S = ['0.1', '5.9604645e-8', '3.4028235e38', '1.4e-45', '7.0e-46', '7.1e-46', '1.17549435e-38', |
| 230 | '16777217.0', '16777219.0', '-2.5', '0.0', '-0.0', '3.4028235677e38', '0.33333334', |
| 231 | '1.0000001', '2.7182817'] |
| 232 | for k in range(len(S), 30): |
| 233 | S.append(('-' if k % 2 else '') + f'{(k * 31337) % 10000}.{(k * 7) % 1000:03d}e{(k % 21) - 10}') |
| 234 | consts = 'const NI ulong 7\nconst NS long -3\n' |
| 235 | consts += ''.join(f'const D{i} f64 {t}\n' for i, t in enumerate(D)) |
| 236 | consts += ''.join(f'const S{i} f32 {t}\n' for i, t in enumerate(S)) |
| 237 | calls = [f'w64 bitcast ulong D{i}' for i in range(len(D))] + [f'w64 ulong bitcast uint S{i}' for i in range(len(S))] |
| 238 | calls += ['w64 NI', 'w64s NS', 'w64 bitcast ulong mul D3 D1', 'w64 ulong bitcast uint add S0 S14'] |
| 239 | groups, names = grouped('k', calls) |
| 240 | source = consts + io + groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n' |
| 241 | f, c, expected = differential('consts', source) |
| 242 | words = [int.from_bytes(expected[i:i + 8], 'little') for i in range(0, len(expected), 8)] |
| 243 | oracle = [nearest(t, 52, 11) for t in D] + [nearest(t, 23, 8) for t in S] |
| 244 | # The converter reproduces omc e5b32567 bit for bit. omc misrounds two of these literals by one ulp |
| 245 | # (aien-dev/omega-mv#1024, checked against an exact rational oracle); any other difference, or a |
| 246 | # change in these two, fails. |
| 247 | OMC_MISROUNDED = {'2.4703282292062328e-324': 0, '6816.702656e-27': 0x3b207b55a6d4a12f} |
| 248 | for t, w, o in zip(D + S, words, oracle): |
| 249 | if t in OMC_MISROUNDED: |
| 250 | assert w == OMC_MISROUNDED[t] and abs(w - o) == 1, (t, hex(w), hex(o)) |
| 251 | else: |
| 252 | assert w == o, (t, hex(w), hex(o)) |
| 253 | assert all(t in D for t in OMC_MISROUNDED) |
| 254 | assert words[len(oracle):len(oracle) + 2] == [7, (1 << 64) - 3] |
| 255 | # Negative control: a one-ulp change to one emitted constant is detected. |
| 256 | text = c.read_text() |
| 257 | lit = str(oracle[0]) |
| 258 | assert lit + 'ULL' in text, 'constant not emitted as its exact bit pattern' |
| 259 | bad = b / 'consts-mutant.c' |
| 260 | bad.write_text(text.replace(lit + 'ULL', str(oracle[0] + 1) + 'ULL', 1)) |
| 261 | checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', bad, '-o', b / 'consts-mutant']) |
| 262 | assert checked([b / 'consts-mutant']) != expected |
| 263 | |
| 264 | # 3. Fail-closed converter checks (seeded C frontend only, after the seeded omc accepts). |
| 265 | for name, body in { |
| 266 | 'f64_array': 'fn root x view f64 2 to uint\nret 0\nend\n', |
| 267 | }.items(): |
| 268 | f = b / (name + '.om') |
| 269 | f.write_text(body) |
| 270 | for target in ['c', 'h']: |
| 271 | p = run(['sh', 'tools/bridge-seeded', target, f]) |
| 272 | assert p.returncode != 0 and not p.stdout, (name, target, p.stderr) |
| 273 | # Converter-level semantic refusals with their exact error codes (input straight to the converter). |
| 274 | # Each case is also compiled by the seeded omc: where omc refuses, the converter reports omc's code; |
| 275 | # where omc accepts, the converter's refusal must be a capability (24) or capacity (14) code. |
| 276 | many = ''.join(f'const C{i} f64 1.5\n' for i in range(1025)) + 'fn root to ulong\nret 0\nend\n' |
| 277 | for name, body, code in [ |
| 278 | ('int_literal_f64', 'const K f64 1\nfn root to ulong\nret 0\nend\n', 16), |
| 279 | ('float_literal_ulong', 'const K ulong 1.0\nfn root to ulong\nret 0\nend\n', 16), |
| 280 | ('suffix_mismatch', 'const K f64 1.0f32\nfn root to ulong\nret 0\nend\n', 16), |
| 281 | ('suffix_const', 'const K f64 1.0f64\nfn root to ulong\nret 0\nend\n', 16), |
| 282 | ('f32_overflow', 'const K f32 3.4028236e38\nfn root to ulong\nret 0\nend\n', 8), |
| 283 | ('f64_overflow', 'const K f64 1.7976931348623159e308\nfn root to ulong\nret 0\nend\n', 8), |
| 284 | ('float_length', 'const K f64 4.0\nfn root to ulong\na = new uchar K 0\nret len a\nend\n', 16), |
| 285 | ('float_rem', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = rem x x\nret bitcast ulong y\nend\n', 7), |
| 286 | ('float_xor', 'fn root a uint to uint\nx = bitcast f32 a\ny = xor x x\nret bitcast uint y\nend\n', 7), |
| 287 | ('float_shift_count', 'fn root a ulong to ulong\nx = bitcast f64 a\nret shl a x\nend\n', 24), |
| 288 | ('int_literal_operand', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = add x 1\nret bitcast ulong y\nend\n', 7), |
| 289 | ('int_literal_left', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = mul 2 x\nret bitcast ulong y\nend\n', 7), |
| 290 | ('int_literal_long_range', 'fn root to ulong\ny = f64 9223372036854775808\nret bitcast ulong y\nend\n', 8), |
| 291 | ('untyped_float', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = add 1.0 x\nret bitcast ulong y\nend\n', 24), |
| 292 | ('bitcast_int_f32', 'fn root a int to ulong\nx = bitcast f32 a\nret 0\nend\n', 24), |
| 293 | ('bitcast_ulong_f32', 'fn root a ulong to ulong\nx = bitcast f32 a\nret 0\nend\n', 7), |
| 294 | ('bitcast_bool_f64', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = bitcast bool x\nret 0\nend\n', 7), |
| 295 | ('bool_float', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = bool x\nret 0\nend\n', 9), |
| 296 | ('float_of_bool', 'fn root to ulong\nq = true\ny = f64 q\nret 0\nend\n', 7), |
| 297 | ('fabs_int', 'fn root a ulong to ulong\nret fabs a\nend\n', 7), |
| 298 | ('long_significand', 'const K f64 9223372036854775808.0\nfn root to ulong\nret 0\nend\n', 8), |
| 299 | ('consts_1025', many, 14), |
| 300 | ]: |
| 301 | p = run(['build/bridge'], ('D' + body).encode()) |
| 302 | assert p.returncode != 0 and not p.stdout, (name, p.returncode) |
| 303 | assert re.search(rb'error ' + str(code).encode() + rb'\b', p.stderr), (name, p.stderr) |
| 304 | o = run([seed], (body + 'fn main to int\nret 0\nend\n').encode()) |
| 305 | assert o.returncode == code if o.returncode else code in (14, 24), (name, o.returncode, code) |
| 306 | print('PASS seeded binary32/binary64 byte differential (native/C' + ('/x86' if x86 else '') + |
| 307 | ', %d constants vs exact oracle, one-ulp mutant detected); baseline/Python/f64-array/' |
| 308 | 'converter refusals' % (len(D) + len(S) + 2) + ('' if x86 else '; x86 NOT_RUN')) |