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-mv/blob/main/seed/omc/float-lits.py # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / seed / omc / float-lits.py` 320 lines ยท 11058 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Float literal oracle for omc (OMEGESE 9.9, omega-mv#1024). 3 4 The oracle rounds the literal's exact rational value (fractions.Fraction) once to nearest even in 5 binary32 or binary64; binary64 results are also checked against Python's float(). It never reads 6 omc's answer to build an expectation. 7 8 float-lits.py table rewrite tests/float/lit_round.om and lit_round.want (fixed cases) 9 float-lits.py diff OMC N SEED compile N random literals with OMC and compare every bit pattern 10 11 diff prints FLOATDIFF PASS|FAIL total=N f64=.. f32=.. overflow=.. mismatch=.. and exits 0 only on PASS. 12 """ 13 import os 14 import random 15 import struct 16 import subprocess 17 import sys 18 import tempfile 19 from fractions import Fraction 20 21 FMT = {"f64": (53, -1022, 1023, 64), "f32": (24, -126, 127, 32)} 22 MAXND = 2**63 - 1 23 24 25 def value(lit): 26 """The exact rational value of an omc float literal; None if omc must refuse its digits.""" 27 s = lit 28 neg = s.startswith("-") 29 if neg: 30 s = s[1:] 31 mant, _, ex = s.replace("E", "e").partition("e") 32 whole, _, frac = mant.partition(".") 33 digits = int(whole + frac) 34 if digits > MAXND: 35 return None 36 p10 = (int(ex) if ex else 0) - len(frac) 37 v = Fraction(digits) * Fraction(10) ** p10 38 return (neg, v) 39 40 41 def rne(neg, x, ty): 42 """IEEE bits of x rounded once to nearest even; None when it rounds to infinity.""" 43 p, emin, emax, w = FMT[ty] 44 sign = (1 << (w - 1)) if neg else 0 45 if x == 0: 46 return sign 47 e = x.numerator.bit_length() - x.denominator.bit_length() 48 if x < Fraction(2) ** e: 49 e -= 1 50 e = max(e, emin) 51 m = x / Fraction(2) ** (e - (p - 1)) 52 q = m.numerator // m.denominator 53 r = m - q 54 if r > Fraction(1, 2) or (r == Fraction(1, 2) and q & 1): 55 q += 1 56 if q == 1 << p: 57 q >>= 1 58 e += 1 59 if e > emax: 60 return None 61 if q < 1 << (p - 1): 62 return sign | q 63 return sign | ((e + (1 << (w - p - 1)) - 1) << (p - 1)) | (q - (1 << (p - 1))) 64 65 66 def expect(lit, ty): 67 v = value(lit) 68 if v is None: 69 return None 70 bits = rne(v[0], v[1], ty) 71 if ty == "f64": 72 try: 73 ref = struct.unpack("> 52 & 2047 == 2047: 77 ref = None 78 assert bits == ref, (lit, bits, ref) 79 return bits 80 81 82 def program(lits): 83 """One omc program: the bits of every literal, eight bytes each, little-endian, on stdout.""" 84 n = len(lits) 85 out = ["global g ulong %d" % n, "fn main to int"] 86 for i, (lit, ty) in enumerate(lits): 87 if ty == "f64": 88 out.append("put g %d bitcast ulong f64 %s" % (i, lit)) 89 else: 90 out.append("put g %d ulong bitcast uint f32 %s" % (i, lit)) 91 out += [ 92 "b = new uchar %d 0" % (8 * n), 93 "for i ulong %d" % n, 94 "v = get g i", 95 "for j ulong 8", 96 "put b add mul i 8 j uchar and shr v mul j 8 255", 97 "end", 98 "end", 99 "n = write 1 b 0 %d" % (8 * n), 100 "ret 0", 101 "end", 102 ] 103 return "\n".join(out) + "\n" 104 105 106 def digits_lit(rng, nd, p10, neg): 107 """A literal of nd significant digits whose value is D * 10^p10, written in a random style.""" 108 while True: 109 d = rng.randrange(10 ** (nd - 1), 10**nd) 110 if d <= MAXND: 111 break 112 s = str(d) 113 style = rng.randrange(4) 114 if style == 0: 115 k = rng.randrange(1, len(s)) if len(s) > 1 else 1 116 lit = s[:k] + "." + (s[k:] or "0") + "e" + str(p10 + len(s) - k) 117 elif style == 1: 118 lit = s + "e" + str(p10) 119 elif style == 2: 120 z = rng.randrange(0, 30) 121 lit = "0." + "0" * z + s + "E" + str(p10 + len(s) + z) 122 else: 123 x = p10 + len(s) - 1 124 lit = s[0] + "." + (s[1:] or "0") + "e" + ("+" if x >= 0 and rng.randrange(2) else "") + str(x) 125 return ("-" if neg else "") + lit 126 127 128 def halfway_lit(rng, ty, neg): 129 """A literal within one 19th digit of the midpoint between two neighbouring floats.""" 130 p, emin, emax, w = FMT[ty] 131 e = rng.randrange(emin - p, emax) 132 if e < emin: 133 q = rng.randrange(1, 1 << (p - 1)) 134 m = Fraction(2 * q + 1) * Fraction(2) ** (emin - p) 135 else: 136 q = rng.randrange(1 << (p - 1), (1 << p) - 1) 137 m = Fraction(2 * q + 1) * Fraction(2) ** (e - p) 138 k = 0 139 t = m 140 while t >= 10: 141 t /= 10 142 k += 1 143 while t < 1: 144 t *= 10 145 k -= 1 146 nd = rng.randrange(16, 20) 147 scaled = m / Fraction(10) ** (k - nd + 1) 148 d = scaled.numerator // scaled.denominator + rng.choice((-1, 0, 0, 1, 2)) 149 if d < 1 or d > MAXND: 150 d = scaled.numerator // scaled.denominator 151 if d > MAXND: 152 d //= 10 153 k += 1 154 return ("-" if neg else "") + "%de%d" % (d, k - nd + 1) 155 156 157 def random_lits(rng, n): 158 out = [] 159 for _ in range(n): 160 ty = "f64" if rng.randrange(3) else "f32" 161 neg = rng.randrange(5) == 0 162 kind = rng.randrange(10) 163 if kind < 4: 164 out.append((halfway_lit(rng, ty, neg), ty)) 165 continue 166 nd = rng.randrange(1, 20) 167 if ty == "f64": 168 p10 = rng.randrange(-345 - nd, 310 - nd) 169 else: 170 p10 = rng.randrange(-47 - nd, 40 - nd) 171 if kind == 9: 172 p10 = rng.randrange(-30, 30) 173 out.append((digits_lit(rng, nd, p10, neg), ty)) 174 return out 175 176 177 def run_omc(omc, lits, tmp): 178 src = os.path.join(tmp, "p.om") 179 exe = os.path.join(tmp, "p") 180 with open(src, "w") as f: 181 f.write(program(lits)) 182 with open(src) as fi, open(exe, "wb") as fo: 183 r = subprocess.run([omc], stdin=fi, stdout=fo, stderr=subprocess.PIPE) 184 if r.returncode != 0: 185 return None, r.returncode, r.stderr.decode() 186 # Keep the generated oracle private; the same permission repair appears in #1027. 187 os.chmod(exe, 0o700) 188 r = subprocess.run([exe], stdout=subprocess.PIPE) 189 if r.returncode != 0: 190 raise SystemExit("FLOATDIFF INVALID program exit %d" % r.returncode) 191 return struct.unpack("<%dQ" % len(lits), r.stdout), 0, "" 192 193 194 def one_refusal(omc, lit, ty, tmp): 195 """The compiler status for a program holding only this literal (expected: error 8).""" 196 _, rc, err = run_omc(omc, [(lit, ty)], tmp) 197 return rc, err 198 199 200 def diff(omc, total, seed): 201 rng = random.Random(seed) 202 lits = random_lits(rng, total) 203 cnt = {"f64": 0, "f32": 0, "overflow": 0, "mismatch": 0} 204 good = [] 205 with tempfile.TemporaryDirectory() as tmp: 206 for lit, ty in lits: 207 if expect(lit, ty) is None: 208 cnt["overflow"] += 1 209 if cnt["overflow"] <= 200: 210 rc, err = one_refusal(omc, lit, ty, tmp) 211 if rc != 8: 212 cnt["mismatch"] += 1 213 print("MISMATCH %s %s refused rc=%d %s" % (ty, lit, rc, err.strip())) 214 else: 215 good.append((lit, ty)) 216 for i in range(0, len(good), 2000): 217 batch = good[i : i + 2000] 218 got, rc, err = run_omc(omc, batch, tmp) 219 if got is None: 220 raise SystemExit("FLOATDIFF INVALID compile rc=%d %s" % (rc, err.strip())) 221 for (lit, ty), g in zip(batch, got): 222 cnt[ty] += 1 223 want = expect(lit, ty) 224 if g != want: 225 cnt["mismatch"] += 1 226 if cnt["mismatch"] <= 40: 227 print("MISMATCH %s %s got %x want %x" % (ty, lit, g, want)) 228 ok = cnt["mismatch"] == 0 and cnt["f64"] + cnt["f32"] + cnt["overflow"] == total 229 print( 230 "FLOATDIFF %s total=%d f64=%d f32=%d overflow=%d overflow_checked=%d mismatch=%d seed=%d" 231 % ("PASS" if ok else "FAIL", total, cnt["f64"], cnt["f32"], cnt["overflow"], 232 min(cnt["overflow"], 200), cnt["mismatch"], seed) 233 ) 234 return 0 if ok else 1 235 236 237 # Fixed cases: #1024's two literals, halfway and subnormal boundaries, both ends of the range, 238 # 19-digit significands and long fractions. Each row is (literal, type). 239 TABLE = [ 240 ("6816.`702656e`-27", "f64"), 241 ("2.`4703282292062328e`-324", "f64"), 242 ("2.`4703282292062327e`-324", "f64"), 243 ("2.`470328229206232720e`-324", "f64"), 244 ("2.`470328229206232721e`-324", "f64"), 245 ("4.`9406564584124654e`-324", "f64"), 246 ("7.`4109846876186981e`-324", "f64"), 247 ("2.`2250738585072011e`-308", "f64"), 248 ("2.`2250738585072012e`-308", "f64"), 249 ("2.`2250738585072014e`-308", "f64"), 250 ("1.`7976931348623157e308`", "f64"), 251 ("1.`7976931348623158e308`", "f64"), 252 ("`9007199254740993`.0", "f64"), 253 ("`9007199254740993`.001", "f64"), 254 ("`9007199254740992`.999", "f64"), 255 ("`9007199254740995`.0", "f64"), 256 ("`4503599627370496`.5", "f64"), 257 ("`4503599627370497`.5", "f64"), 258 ("1.`000000000000000111e0`", "f64"), 259 ("1.`000000000000000110e0`", "f64"), 260 ("0.1", "f64"), 261 ("0.3", "f64"), 262 ("`123456789012345678e`-20", "f64"), 263 ("`9223372036854775807e`-342", "f64"), 264 ("`9223372036854775807e289`", "f64"), 265 ("8.`98846567431158e307`", "f64"), 266 ("5.0e-324", "f64"), 267 ("4.9e-324", "f64"), 268 ("1e-999", "f64"), 269 ("-1e-999", "f64"), 270 ("0.`000000000000000000000000000000000000000000000000000001e`-270", "f64"), 271 ("1e23", "f64"), 272 ("8.533e-308", "f64"), 273 ("3.`4028234663852886e38`", "f32"), 274 ("3.`4028235677973366e38`", "f32"), 275 ("1.`1754943508222875e`-38", "f32"), 276 ("1.`1754942807573643e`-38", "f32"), 277 ("1.`1754942807573644e`-38", "f32"), 278 ("1.`4012984643248171e`-45", "f32"), 279 ("7.`0064923216240854e`-46", "f32"), 280 ("7.`0064923216240853e`-46", "f32"), 281 ("`16777217`.0", "f32"), 282 ("`16777217`.`000000001`", "f32"), 283 ("`16777219`.0", "f32"), 284 ("0.1", "f32"), 285 ("1.`000000059604644776`", "f32"), 286 ("1.`000000059604644775`", "f32"), 287 ("-2.`718281828459045235`", "f32"), 288 ("6816.`702656e`-27", "f32"), 289 ] 290 291 292 def table(): 293 here = os.path.dirname(os.path.abspath(__file__)) 294 t = os.path.join(here, "tests", "float") 295 rng = random.Random(1024) 296 rows = list(TABLE) 297 while len(rows) < 512: 298 ty = "f64" if len(rows) % 3 else "f32" 299 lit = halfway_lit(rng, ty, rng.randrange(4) == 0) 300 if expect(lit, ty) is not None: 301 rows.append((lit, ty)) 302 for lit, ty in rows: 303 assert expect(lit, ty) is not None, lit 304 with open(os.path.join(t, "lit_round.om"), "w") as f: 305 f.write("note generated by seed/omc/float-lits.py table: 512 literals (omega-mv#1024); expected\n") 306 f.write("note bits are in lit_round.want, computed by the script's exact rational oracle.\n") 307 f.write(program(rows)) 308 with open(os.path.join(t, "lit_round.want"), "w") as f: 309 for lit, ty in rows: 310 f.write("%016x %s %s\n" % (expect(lit, ty), ty, lit)) 311 print("wrote %d rows" % len(rows)) 312 313 314 if __name__ == "__main__": 315 if sys.argv[1:2] == ["table"]: 316 table() 317 elif sys.argv[1:2] == ["diff"] and len(sys.argv) == 5: 318 sys.exit(diff(sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))) 319 else: 320 sys.exit(__doc__)