interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / tests / seeded_float.py

308 lines · 14731 bytes Raw Blame History
1"""Seeded-only internal binary32/binary64 differential and fail-closed controls.
2
3The seeded omc executable is the reference: every case below compares its AArch64
4output bytes with the generated C on this host and, when the cross tools exist, on
5x86-64 under qemu-x86_64. Float constants are also checked against an exact
6round-to-nearest-even decimal oracle written with fractions.Fraction.
7No GPU, CUDA runtime, driver or hardware access.
8"""
9import fractions
10import os
11import pathlib
12import re
13import shutil
14import struct
15import subprocess
16import sys
17
18root = pathlib.Path(__file__).resolve().parents[1]
19os.chdir(root)
20b = root / 'build/seeded-float'
21b.mkdir(parents=True, exist_ok=True)
22seed = os.environ.get('OMEGA_SEEDED_OMC')
23if not seed:
24 sys.exit('NOT_RUN: set OMEGA_SEEDED_OMC to the pinned e5b32567 compiler')
25x86 = shutil.which('x86_64-linux-gnu-gcc') and shutil.which('qemu-x86_64')
26
27def run(args, data=None):
28 return subprocess.run(list(map(str, args)), input=data, capture_output=True, timeout=120)
29
30def checked(args, data=None):
31 p = run(args, data)
32 assert p.returncode == 0, (args, p.returncode, p.stderr)
33 return p.stdout
34
35def 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
53def 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
79io = '''fn w64 v ulong to ulong
80out = new uchar 8 0
81for i ulong 8
82put out i uchar and shr v mul i 8 255
83end
84n = write 1 out 0 8
85ret 0
86end
87fn w64s v long to ulong
88if lt v 0
89ret w64 sub 18446744073709551615 ulong neg add v 1
90end
91ret w64 ulong v
92end
93'''
94
95def 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
101def 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.
109F64 = [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]
115F32 = [0, 1 << 31, 0x3f800000, 0xbf800000, 0x3dcccccd, 1, 0x007fffff, 0x00800000, 0x7f7fffff,
116 0x7f800000, 0xff800000, 0x7fc00000, 0x7fa00001, 0xffc00123, 0x5f000000, 0x5f800000,
117 0xdf000000, 0x4effffff, 0x3f000000, 0xcf000000, 0x4f000000]
118SIGNED = [0, 1, -1, 9007199254740993, -9007199254740993, 9223372036854775807,
119 -9223372036854775807, 16777217, -16777217, 2147483647, -2147483647]
120source = io + '''fn f64ops a ulong b ulong to ulong
121x = bitcast f64 a
122y = bitcast f64 b
123r = w64 bitcast ulong add x y
124r = w64 bitcast ulong sub x y
125r = w64 bitcast ulong mul x y
126r = w64 bitcast ulong div x y
127r = w64 bitcast ulong neg x
128r = w64 bitcast ulong fabs x
129r = w64 bitcast ulong fsqrt x
130''' + compares('x', 'y') + '''ret 0
131end
132fn f32ops a uint b uint to ulong
133x = bitcast f32 a
134y = bitcast f32 b
135r = w64 ulong bitcast uint add x y
136r = w64 ulong bitcast uint sub x y
137r = w64 ulong bitcast uint mul x y
138r = w64 ulong bitcast uint div x y
139r = w64 ulong bitcast uint neg x
140r = w64 ulong bitcast uint fabs x
141r = w64 ulong bitcast uint fsqrt x
142''' + compares('x', 'y') + '''ret 0
143end
144fn f64cv a ulong to ulong
145x = bitcast f64 a
146r = w64 ulong x
147r = w64s long x
148r = w64s long int x
149r = w64s long short x
150r = w64s long byte x
151r = w64 ulong uint x
152r = w64 ulong ushort x
153r = w64 ulong uchar x
154r = w64 ulong bitcast uint f32 x
155r = w64 bitcast ulong mul x 0.5
156r = w64 bitcast ulong f64 a
157r = w64 ulong bitcast uint f32 a
158r = w64s bitcast long x
159ret 0
160end
161fn f32cv a uint to ulong
162x = bitcast f32 a
163r = w64 bitcast ulong f64 x
164r = w64 ulong x
165r = w64s long x
166r = w64s long int x
167r = w64 ulong uint x
168r = w64 ulong bitcast uint f32 a
169r = w64 ulong bitcast uint sub x 1.5
170ret 0
171end
172fn sgn s long to ulong
173r = w64 bitcast ulong f64 s
174r = w64 ulong bitcast uint f32 s
175r = w64 bitcast ulong bitcast f64 s
176ret 0
177end
178fn lit to ulong
179r = w64 bitcast ulong f64 1
180r = w64 bitcast ulong f64 -1
181r = w64 bitcast ulong f64 9007199254740993
182r = w64 bitcast ulong f64 9223372036854775807
183r = w64 bitcast ulong f64 -9223372036854775807
184r = w64 ulong bitcast uint f32 16777217
185r = w64 ulong bitcast uint f32 -3
186ret 0
187end
188'''
189calls = [f'f64ops {a} {c}' for a in F64 for c in F64] + [f'f32ops {a} {c}' for a in F32 for c in F32]
190calls += [f'f64cv {a}' for a in F64] + [f'f32cv {a}' for a in F32] + [f'sgn {s}' for s in SIGNED] + ['lit']
191groups, names = grouped('g', calls)
192source += groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n'
193f, c, expected = differential('ops', source)
194records = (len(F64) ** 2) * 8 + (len(F32) ** 2) * 8 + len(F64) * 13 + len(F32) * 7 + len(SIGNED) * 3 + 7
195assert len(expected) == 8 * records, (len(expected), records)
196# Each square-root width is exercised on both hosts above and has an independent mutant.
197sqrt_text = c.read_text()
198for 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).
208lits = [struct.pack('<d', float(v)) for v in (1, -1, 9007199254740993, 9223372036854775807, -9223372036854775807)]
209lits += [struct.pack('<f', float(v)) + bytes(4) for v in (16777217, -3)]
210assert expected[-56:] == b''.join(lits), expected[-56:].hex()
211for target in ['python']:
212 p = run(['sh', 'tools/bridge-seeded', target, f])
213 assert p.returncode != 0 and not p.stdout
214p = run(['sh', 'tools/bridge', 'c', f])
215assert p.returncode != 0 and not p.stdout
216# Compile-time arithmetic-mode refusal is not an ignored warning.
217p = run(['gcc', '-std=gnu11', '-O2', '-ffast-math', c, '-o', b / 'unsafe'])
218assert 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.
222D = ['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']
227for 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}')
229S = ['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']
232for 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}')
234consts = 'const NI ulong 7\nconst NS long -3\n'
235consts += ''.join(f'const D{i} f64 {t}\n' for i, t in enumerate(D))
236consts += ''.join(f'const S{i} f32 {t}\n' for i, t in enumerate(S))
237calls = [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))]
238calls += ['w64 NI', 'w64s NS', 'w64 bitcast ulong mul D3 D1', 'w64 ulong bitcast uint add S0 S14']
239groups, names = grouped('k', calls)
240source = consts + io + groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n'
241f, c, expected = differential('consts', source)
242words = [int.from_bytes(expected[i:i + 8], 'little') for i in range(0, len(expected), 8)]
243oracle = [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.
247OMC_MISROUNDED = {'2.4703282292062328e-324': 0, '6816.702656e-27': 0x3b207b55a6d4a12f}
248for 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))
253assert all(t in D for t in OMC_MISROUNDED)
254assert words[len(oracle):len(oracle) + 2] == [7, (1 << 64) - 3]
255# Negative control: a one-ulp change to one emitted constant is detected.
256text = c.read_text()
257lit = str(oracle[0])
258assert lit + 'ULL' in text, 'constant not emitted as its exact bit pattern'
259bad = b / 'consts-mutant.c'
260bad.write_text(text.replace(lit + 'ULL', str(oracle[0] + 1) + 'ULL', 1))
261checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', bad, '-o', b / 'consts-mutant'])
262assert checked([b / 'consts-mutant']) != expected
263
264# 3. Fail-closed converter checks (seeded C frontend only, after the seeded omc accepts).
265for 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.
276many = ''.join(f'const C{i} f64 1.5\n' for i in range(1025)) + 'fn root to ulong\nret 0\nend\n'
277for 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)
306print('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'))