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_next.py

188 lines · 6999 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Explicit draft-1049 profile: fused FMA and exact decimal lowering.
3
4WolframLanguageEvaluator:
5{Table[{w,3*w/8*256,w/8*256,3*w/8,w/8},{w,{32,64}}],2^20}
6-> {{{32,3072,1024,12,4},{64,6144,2048,24,8}},1048576}.
7Expected arithmetic is executed by the separately pinned seeded compiler.
8"""
9import hashlib
10import itertools
11import os
12from pathlib import Path
13import random
14import subprocess
15import tempfile
16
17ROOT = Path(__file__).resolve().parents[1]
18PIN = "d89bdc08ca21ea9726f1117adc791f683287d3698ea112a9db5519df2e79aeec"
19OMC = Path(os.environ["OMEGA_SEEDED_NEXT_OMC"])
20assert hashlib.sha256(OMC.read_bytes()).hexdigest() == PIN
21
22
23def run(cmd, data=None):
24 p = subprocess.run([str(x) for x in cmd], input=data, capture_output=True, timeout=300)
25 assert p.returncode == 0, (cmd, p.returncode, p.stderr.decode(errors="replace"))
26 return p.stdout
27
28
29def compile_c(code, path):
30 source = path.with_suffix(".c")
31 source.write_bytes(code)
32 run([os.environ.get("CC", "cc"), "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", source, "-o", path])
33
34
35def program(width, ilen, olen, stride, size):
36 it = "uint" if width == 32 else "ulong"
37 return f"""fn readword input view uchar {ilen} off ulong to {it}
38x = {it} 0
39for j ulong {size}
40v = {it} get input add off j
41shift = {it} mul j 8
42x = or x shl v shift
43end
44ret x
45end
46fn word out edit uchar {olen} off ulong value {it} to void
47for j ulong {size}
48shift = {it} mul j 8
49part = and shr value shift 255
50put out add off j uchar part
51end
52ret
53end
54fn process input view uchar {ilen} output edit uchar {olen} to void
55for i ulong 256
56off = mul i {stride}
57a = bitcast f{width} readword view input off
58b = bitcast f{width} readword view input add off {size}
59c = bitcast f{width} readword view input add off {size + size}
60r = fma a b c
61word output mul i {size} bitcast {it} r
62end
63ret
64end
65fn main to int
66input = new uchar {ilen} 0
67output = new uchar {olen} 0
68more = true
69while more
70have = ulong 0
71while lt have {ilen}
72n = read 0 input have sub {ilen} have
73if lt n 0
74ret 9
75end
76if eq n 0
77if ne have 0
78ret 8
79end
80more = false
81break
82end
83have = add have ulong n
84end
85if more
86process view input output
87sent = ulong 0
88while lt sent {olen}
89n = write 1 output sent sub {olen} sent
90if le n 0
91ret 7
92end
93sent = add sent ulong n
94end
95end
96end
97ret 0
98end
99"""
100
101
102def main():
103 with tempfile.TemporaryDirectory(prefix="omega-seeded-next-") as td:
104 w = Path(td)
105 for width, ilen, olen, stride, size in ((32, 3072, 1024, 12, 4), (64, 6144, 2048, 24, 8)):
106 edges = ([0, 0x80000000, 1, 0x007fffff, 0x00800000, 0x3f800000, 0xbf800000, 0x7f7fffff,
107 0x7f800000, 0xff800000, 0x7f800001, 0x7fc12345, 0xff800001, 0xffc12345] if width == 32 else
108 [0, 0x8000000000000000, 1, 0xfffffffffffff, 0x10000000000000, 0x3ff0000000000000,
109 0xbff0000000000000, 0x7fefffffffffffff, 0x7ff0000000000000, 0xfff0000000000000,
110 0x7ff0000000000001, 0x7ff8000000012345, 0xfff0000000000001, 0xfff8000000012345])
111 data = bytearray()
112 for triple in itertools.product(edges, repeat=3):
113 for bits in triple:
114 data.extend(bits.to_bytes(size, "little"))
115 rng = random.Random(0x1049)
116 for _ in range(1048576):
117 for _ in range(3):
118 data.extend(rng.getrandbits(width).to_bytes(size, "little"))
119 data.extend(bytes(-len(data) % ilen))
120 source = w / f"fma{width}.om"
121 source.write_text(program(width, ilen, olen, stride, size))
122 oracle = w / f"oracle{width}"
123 oracle.write_bytes(run([OMC], source.read_bytes()))
124 oracle.chmod(0o755)
125 expected = run([oracle], data)
126 generated = run([ROOT / "tools/bridge-seeded", "--float-next", "c", source])
127 header_source = w / f"fused{width}.om"
128 header_source.write_text(f"fn fused a f{width} b f{width} c f{width} to f{width}\nret fma a b c\nend\n")
129 assert run([ROOT / "tools/bridge-seeded", "--float-next", "h", header_source])
130 host = w / f"host{width}"
131 compile_c(generated, host)
132 assert run([host], data) == expected, (width, "fma differential")
133 opcode = b"fmadd %s0" if width == 32 else b"fmadd %d0"
134 replacement = b"fmsub %s0" if width == 32 else b"fmsub %d0"
135 assert generated.count(opcode) == 1
136 mutant = w / f"mutant{width}"
137 compile_c(generated.replace(opcode, replacement), mutant)
138 assert run([mutant], data) != expected, (width, "FMA mutant survived")
139 print(f"PASS fma f{width}: edge triples + 1048576 random triples, wrong-opcode mutant killed")
140 # The copied #1024 table is independently checked by the Wolfram query
141 # in omega-mv#1049 evidence/SEED-0/fma-exact-literals/oracle.wl.
142 rows = [line.split() for line in (ROOT / "tests/seeded_next_literals.want").read_text().splitlines()]
143 assert len(rows) == 512
144 expected_bits = b"".join(int(bits, 16).to_bytes(8, "little") for bits, _, _ in rows)
145 statements = []
146 for index, (_, typ, decimal) in enumerate(rows):
147 cast = "ulong bitcast uint" if typ == "f32" else "bitcast ulong"
148 statements.append(f"word out {index * 8} {cast} {typ} {decimal}\n")
149 source = w / "literals.om"
150 source.write_text("""fn word out edit uchar 4096 off ulong value ulong to void
151for j ulong 8
152shift = mul j 8
153part = and shr value shift 255
154put out add off j uchar part
155end
156ret
157end
158fn main to int
159out = new uchar 4096 0
160""" + "".join(statements) + """n = write 1 out 0 4096
161ret 0
162end
163""")
164 oracle = w / "literals-oracle"
165 oracle.write_bytes(run([OMC], source.read_bytes()))
166 oracle.chmod(0o755)
167 expected = run([oracle])
168 assert expected == expected_bits, "compiler disagrees with verified 512-literal table"
169 generated = run([ROOT / "tools/bridge-seeded", "--float-next", "c", source])
170 host = w / "literals-host"
171 compile_c(generated, host)
172 assert run([host]) == expected
173 literal = str(int.from_bytes(expected[:8], "little")).encode() + b"ULL"
174 assert generated.count(literal) == 1
175 mutant = w / "literals-mutant"
176 compile_c(generated.replace(literal, b"0ULL"), mutant)
177 assert run([mutant]) != expected
178 print("PASS #1024 512 exact f32/f64 literal patterns and killed literal mutant")
179 # A candidate compiler cannot be passed to the frozen e5 profile silently.
180 env = dict(os.environ, OMEGA_SEEDED_OMC=str(OMC))
181 p = subprocess.run([ROOT / "tools/bridge-seeded", "c", source], capture_output=True, env=env)
182 assert p.returncode == 65 and not p.stdout and b"fingerprint mismatch" in p.stderr
183 print("PASS candidate compiler refused by frozen e5 profile")
184 print("SEEDED-NEXT PASS")
185
186
187if __name__ == "__main__":
188 main()