diff options
| author | TreXito <81475944+TreXito@users.noreply.github.com> | 2026-11-23 07:40:20 +0000 |
|---|---|---|
| committer | TreXito <81475944+TreXito@users.noreply.github.com> | 2026-11-23 12:12:19 +0000 |
| commit | 5ec5431c88cd1353c3298d6bcd8db712fcdb9804 (patch) | |
| tree | 3d951072e11a8e46864860f552268b481072cb55 /tools/f16misc_diff.py | |
| parent | 561b65a832218fbb9e6d2effd392a8eef093a3f8 (diff) | |
f16misc_diff.py: differential fuzzer for eleven f16 ops no fuzzer generates
v_min3/max3_f16, v_frexp_mant/exp_i16_f16, v_ldexp_f16, v_fmamk/fmaak_f16,
v_pk_fmac_f16 and v_fma_mix_f32/mixlo_f16/mixhi_f16 were in no --list-ops
and no generator. The tool compares the translation, run in
spirv_mini_interp, bit for bit with an exact-rational reference built from
the docs/design.md rows: a source-kind sweep, an edge grid with fma near
ties, random seeded programs, and --exhaustive-f16 for frexp/ldexp.
tests/test_f16misc_diff.py pins the reference to the gfx1036 words already
in tests/semantic.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/f16misc_diff.py')
| -rw-r--r-- | tools/f16misc_diff.py | 1244 |
1 files changed, 1244 insertions, 0 deletions
diff --git a/tools/f16misc_diff.py b/tools/f16misc_diff.py new file mode 100644 index 000000000..0adddc046 --- /dev/null +++ b/tools/f16misc_diff.py | |||
| @@ -0,0 +1,1244 @@ | |||
| 1 | r"""Differential fuzzer for the RDNA2 f16 VALU ops no other fuzzer generates (standard library only). | ||
| 2 | |||
| 3 | Covers eleven opcodes that are on no `--list-ops` list and in no generator of the other fuzzers: | ||
| 4 | |||
| 5 | v_min3_f16 v_max3_f16 VOP3, three f16 -> f16, op_sel:[a,b,c,d], clamp | ||
| 6 | v_frexp_mant_f16 v_frexp_exp_i16_f16 VOP1 (_e32, _e64), f16 -> f16 / i16, op_sel:[a,d] | ||
| 7 | v_ldexp_f16 VOP2 (_e32, _e64), f16 * 2^i16 -> f16, op_sel:[a,b,d] | ||
| 8 | v_fmamk_f16 v_fmaak_f16 VOP2 with a literal K, f16 fma | ||
| 9 | v_pk_fmac_f16 VOP2, two f16 fmas into the packed accumulator | ||
| 10 | v_fma_mix_f32 v_fma_mixlo_f16 v_fma_mixhi_f16 VOP3P, f32 fma of f32 or f16 sources (op_sel_hi), clamp | ||
| 11 | |||
| 12 | Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared: | ||
| 13 | |||
| 14 | * the reference below, written from the rules docs/design.md records for these ops, with exact rationals | ||
| 15 | (fractions.Fraction) and one round-to-nearest-even per result. It shares no code with the translator: | ||
| 16 | - f16 operands and results keep denormals (the MODE inferred for the game, denorm_mode_16_64 = 3); an f32 | ||
| 17 | operand of v_fma_mix_* reads as a zero of its sign when it is denormal (denorm_mode_32 = 0, SHADER-298). | ||
| 18 | - fma: x * y + z exact, then rounded once (to f16, or to f32 for v_fma_mix_f32); |x| at or past the | ||
| 19 | rounding boundary of the largest finite value gives +-inf. An exact zero sum is -0 only when both the | ||
| 20 | product and the addend are -0. | ||
| 21 | - min3 / max3: a NaN operand is ignored, -0 orders below +0; the result is the chosen operand. | ||
| 22 | - frexp_mant: the input with its exponent set to 14 (mantissa in [0.5, 1), sign kept); frexp_exp: the | ||
| 23 | exponent that goes with it, as an i16. ldexp: S0 * 2^clamp(S1.i16, -64, 64), rounded to nearest even. | ||
| 24 | Zero gives a signed zero (exponent 0); inf and NaN pass through unchanged (exponent 0). | ||
| 25 | - clamp: to [0, 1] after the operation, before the rounding. On frexp_mant / ldexp a negative result and a | ||
| 26 | NaN give +0 (measured on gfx1036). | ||
| 27 | - destinations: an f16 result goes to the half op_sel's last bit names (the low half for VOP1/VOP2 and | ||
| 28 | v_fma_mixlo_f16, the high half for v_fma_mixhi_f16) and the other half is kept; v_pk_fmac_f16 writes both | ||
| 29 | halves; v_fma_mix_f32 writes the word. | ||
| 30 | tests/test_f16misc_diff.py pins it to the words measured on RDNA2 that tests/semantic records, and | ||
| 31 | * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. | ||
| 32 | |||
| 33 | Comparison: bit for bit, except that a NaN the reference computed (an fma or a min3/max3 of all-NaN operands) | ||
| 34 | matches any NaN: payloads are not modelled. A NaN that only passes through (frexp_mant, ldexp, a min3 operand) | ||
| 35 | is compared exactly. A program is not judged (counted with the reason, not a failure) when it reads such a NaN as | ||
| 36 | bits (an f32 operand made of an f16 NaN half, an i16 exponent, half of an f32 NaN), clamps a NaN or a -0 through | ||
| 37 | min3/max3/fma_mix (the translator's FClamp of a NaN is undefined in SPIR-V; docs/design.md does not pin -0), or | ||
| 38 | when v_fma_mix_f32 returns an f32 denormal (whether f32 denormal results flush is the MODE question, SHADER-35). | ||
| 39 | |||
| 40 | Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` so every result | ||
| 41 | is observed. Every destination is v8..v11, so later ops read earlier results. | ||
| 42 | |||
| 43 | Sources: VGPR v8..v15, SGPR s4..s7, a hex literal, an integer inline constant (-16..64) and a float inline | ||
| 44 | constant (0.5, 1.0, 2.0, 4.0, their negatives, 0.15915494). A 16-bit float operand reads the low half of a | ||
| 45 | register or literal, a float inline constant as its f16 value, and an integer inline constant as the low half of | ||
| 46 | its word (docs/design.md, "f16 inline constants"). An f32 operand of v_fma_mix_* reads a float inline constant as | ||
| 47 | its f32 value. Every program is encodable on GFX10: at most one literal, at most two constant-bus reads in a VOP3 | ||
| 48 | or VOP3P op, and a VOP2 literal or SGPR only in src0. | ||
| 49 | |||
| 50 | Modifiers: neg/abs on the register sources of the VOP3/VOP3P forms (not on ldexp's exponent); op_sel on register | ||
| 51 | sources and the destination bit; clamp on min3/max3, frexp_mant, ldexp and the fma_mix ops. Not generated, on | ||
| 52 | purpose: output multipliers (whether they apply to f16 results is SHADER-297, open), clamp on v_frexp_exp_i16_f16 | ||
| 53 | and the modifiers the translator refuses (--self-test pins those as expected rejections), SDWA and DPP forms | ||
| 54 | (tools/sdwa_diff.py's domain), and op_sel on a constant (only measured for some ops). | ||
| 55 | |||
| 56 | Stages: | ||
| 57 | 1. a sweep: every encodable source-kind combination of every op and form, twice, with random modifiers; | ||
| 58 | 2. an edge grid: special values (zeros, denormals, the normal bounds, 1, the largest finite, inf, quiet and | ||
| 59 | signalling NaNs) through every op, frexp_mant and ldexp also with clamp, and fma near ties and cancellations, | ||
| 60 | four cases per program. Some near ties are off the tie by less than half an f32 ulp (NEAR_ONE), so an fma | ||
| 61 | rounded first to f32 and then to f16 gives a different word there; | ||
| 62 | 3. random seeded programs. | ||
| 63 | --exhaustive-f16 adds every f16 input through v_frexp_mant_f16, v_frexp_exp_i16_f16 and v_ldexp_f16 (eight | ||
| 64 | exponents in turn). | ||
| 65 | |||
| 66 | Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a | ||
| 67 | translator skip (every generated form is one the translator takes), 2 on a harness error. | ||
| 68 | |||
| 69 | Usage: | ||
| 70 | python -I tools/f16misc_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_ldexp_f16,v_fma_mix_f32] | ||
| 71 | python -I tools/f16misc_diff.py --exhaustive-f16 --programs 0 --no-sweep | ||
| 72 | python -I tools/f16misc_diff.py --list-ops | ||
| 73 | python -I tools/f16misc_diff.py --self-test | ||
| 74 | """ | ||
| 75 | import argparse | ||
| 76 | import gc | ||
| 77 | import os | ||
| 78 | import random | ||
| 79 | import re | ||
| 80 | import struct | ||
| 81 | import sys | ||
| 82 | import tempfile | ||
| 83 | import warnings | ||
| 84 | from collections import Counter | ||
| 85 | from fractions import Fraction | ||
| 86 | |||
| 87 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 88 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE | ||
| 89 | sys.dont_write_bytecode = True | ||
| 90 | if TOOLS_DIR not in sys.path: | ||
| 91 | sys.path.insert(0, TOOLS_DIR) | ||
| 92 | SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") | ||
| 93 | if SEM_DIR not in sys.path: | ||
| 94 | sys.path.insert(0, SEM_DIR) | ||
| 95 | |||
| 96 | import rdna2spirv # noqa: E402 | ||
| 97 | from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 | ||
| 98 | |||
| 99 | M32 = 0xFFFFFFFF | ||
| 100 | M16 = 0xFFFF | ||
| 101 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 102 | |||
| 103 | EXPORT = "exp mrt0 v8, v9, v10, v11 done vm" | ||
| 104 | EXPORT_REGS = (8, 9, 10, 11) | ||
| 105 | DSTS = (8, 9, 10, 11) | ||
| 106 | VGPRS = tuple(range(8, 16)) | ||
| 107 | SGPRS = (4, 5, 6, 7) | ||
| 108 | |||
| 109 | # op -> kind | ||
| 110 | FAMILY = { | ||
| 111 | "v_min3_f16": "min3", "v_max3_f16": "max3", | ||
| 112 | "v_frexp_mant_f16": "mant", "v_frexp_exp_i16_f16": "exp", "v_ldexp_f16": "ldexp", | ||
| 113 | "v_fmamk_f16": "fmamk", "v_fmaak_f16": "fmaak", | ||
| 114 | "v_pk_fmac_f16": "pkfmac", | ||
| 115 | "v_fma_mix_f32": "mix32", "v_fma_mixlo_f16": "mixlo", "v_fma_mixhi_f16": "mixhi", | ||
| 116 | } | ||
| 117 | MIX = ("v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16") | ||
| 118 | OP_FORMS = { | ||
| 119 | "v_min3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]", | ||
| 120 | "v_max3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]", | ||
| 121 | "v_frexp_mant_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]] [clamp]", | ||
| 122 | "v_frexp_exp_i16_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]]", | ||
| 123 | "v_ldexp_f16": "_e32 d, s0, vs1 | _e64 d, [-][|]s0[|], s1 [op_sel:[a,b,d]] [clamp]", | ||
| 124 | "v_fmamk_f16": "d, s0, K, vs1", | ||
| 125 | "v_fmaak_f16": "d, s0, vs1, K", | ||
| 126 | "v_pk_fmac_f16": "d, s0, vs1 (d is the accumulator)", | ||
| 127 | "v_fma_mix_f32": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", | ||
| 128 | "v_fma_mixlo_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", | ||
| 129 | "v_fma_mixhi_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", | ||
| 130 | } | ||
| 131 | |||
| 132 | KINDS = ("vgpr", "sgpr", "lit", "int", "float") | ||
| 133 | MODS = ("", "-", "|", "-|") # source modifiers on a register: none, neg, abs, neg(abs) | ||
| 134 | FLOAT_INLINE = { # token -> (f32 word, f16 half) | ||
| 135 | "0.5": (0x3F000000, 0x3800), "-0.5": (0xBF000000, 0xB800), "1.0": (0x3F800000, 0x3C00), | ||
| 136 | "-1.0": (0xBF800000, 0xBC00), "2.0": (0x40000000, 0x4000), "-2.0": (0xC0000000, 0xC000), | ||
| 137 | "4.0": (0x40800000, 0x4400), "-4.0": (0xC0800000, 0xC400), "0.15915494": (0x3E22F983, 0x3118), | ||
| 138 | } | ||
| 139 | INT_INLINE = tuple(range(0, 65)) + tuple(range(-16, 0)) | ||
| 140 | |||
| 141 | # Half states in the reference's register file: None (known bits), "nan" (an f16 NaN whose payload the reference | ||
| 142 | # does not model) and "w32" (half of an f32 NaN whose payload it does not model). | ||
| 143 | NAN16 = 0x7E00 | ||
| 144 | NAN32 = 0x7FC00000 | ||
| 145 | |||
| 146 | |||
| 147 | class HarnessError(Exception): | ||
| 148 | """The generator or the reference met something outside the modelled forms.""" | ||
| 149 | |||
| 150 | |||
| 151 | class NotJudged(Exception): | ||
| 152 | """The reference does not judge this program (the reason is counted).""" | ||
| 153 | |||
| 154 | |||
| 155 | # ---- numbers: (kind, sign, magnitude), kind "num" / "inf" / "nan", magnitude a Fraction ---- | ||
| 156 | |||
| 157 | F16 = (11, -14, 15) # precision, smallest normal exponent, largest exponent | ||
| 158 | F32 = (24, -126, 127) | ||
| 159 | |||
| 160 | |||
| 161 | def _ilog2(q): | ||
| 162 | """floor(log2(q)) of a positive Fraction.""" | ||
| 163 | e = q.numerator.bit_length() - q.denominator.bit_length() | ||
| 164 | if Fraction(2) ** e > q: | ||
| 165 | e -= 1 | ||
| 166 | elif Fraction(2) ** (e + 1) <= q: | ||
| 167 | e += 1 | ||
| 168 | return e | ||
| 169 | |||
| 170 | |||
| 171 | def _round_even(q): | ||
| 172 | n = q.numerator // q.denominator | ||
| 173 | d = q - n | ||
| 174 | if d > Fraction(1, 2) or (d == Fraction(1, 2) and n % 2): | ||
| 175 | n += 1 | ||
| 176 | return n | ||
| 177 | |||
| 178 | |||
| 179 | def decode16(h): | ||
| 180 | sign = h >> 15 | ||
| 181 | e, m = (h >> 10) & 0x1F, h & 0x3FF | ||
| 182 | if e == 0x1F: | ||
| 183 | return ("nan" if m else "inf", sign, None) | ||
| 184 | mag = Fraction(m, 1 << 24) if e == 0 else Fraction((1 << 10) | m) * Fraction(2) ** (e - 25) | ||
| 185 | return ("num", sign, mag) | ||
| 186 | |||
| 187 | |||
| 188 | def decode32(w, flush=True): | ||
| 189 | """An f32 word; a denormal reads as a zero of its sign when ``flush``.""" | ||
| 190 | sign = w >> 31 | ||
| 191 | e, m = (w >> 23) & 0xFF, w & 0x7FFFFF | ||
| 192 | if e == 0xFF: | ||
| 193 | return ("nan" if m else "inf", sign, None) | ||
| 194 | if e == 0: | ||
| 195 | return ("num", sign, Fraction(0) if flush else Fraction(m, 1 << 149)) | ||
| 196 | return ("num", sign, Fraction((1 << 23) | m) * Fraction(2) ** (e - 150)) | ||
| 197 | |||
| 198 | |||
| 199 | def round_to(value, fmt, events=None): | ||
| 200 | """Round a ("num", sign, exact magnitude) to the format, nearest even; past the largest finite gives inf.""" | ||
| 201 | kind, sign, mag = value | ||
| 202 | if kind != "num" or mag == 0: | ||
| 203 | return value | ||
| 204 | p, emin, emax = fmt | ||
| 205 | e = max(_ilog2(mag), emin) | ||
| 206 | ulp = Fraction(2) ** (e - p + 1) | ||
| 207 | q = mag / ulp | ||
| 208 | if events is not None and q.denominator == 2: | ||
| 209 | events["tie"] += 1 | ||
| 210 | r = _round_even(q) * ulp | ||
| 211 | if r > (Fraction(2) ** p - 1) * Fraction(2) ** (emax - p + 1): | ||
| 212 | if events is not None: | ||
| 213 | events["overflow"] += 1 | ||
| 214 | return ("inf", sign, None) | ||
| 215 | if events is not None and 0 < r < Fraction(2) ** emin: | ||
| 216 | events["denormal result"] += 1 | ||
| 217 | return ("num", sign, r) | ||
| 218 | |||
| 219 | |||
| 220 | def encode16(value): | ||
| 221 | kind, sign, mag = value | ||
| 222 | if kind == "nan": | ||
| 223 | return (sign << 15) | NAN16 | ||
| 224 | if kind == "inf": | ||
| 225 | return (sign << 15) | 0x7C00 | ||
| 226 | if mag == 0: | ||
| 227 | return sign << 15 | ||
| 228 | e = _ilog2(mag) | ||
| 229 | if e < -14: | ||
| 230 | m = mag * (1 << 24) | ||
| 231 | assert m.denominator == 1 and m < 1024, value | ||
| 232 | return (sign << 15) | int(m) | ||
| 233 | m = mag / Fraction(2) ** (e - 10) - 1024 | ||
| 234 | assert m.denominator == 1 and 0 <= m < 1024 and e <= 15, value | ||
| 235 | return (sign << 15) | ((e + 15) << 10) | int(m) | ||
| 236 | |||
| 237 | |||
| 238 | def encode32(value): | ||
| 239 | kind, sign, mag = value | ||
| 240 | if kind == "nan": | ||
| 241 | return (sign << 31) | NAN32 | ||
| 242 | if kind == "inf": | ||
| 243 | return (sign << 31) | 0x7F800000 | ||
| 244 | if mag == 0: | ||
| 245 | return sign << 31 | ||
| 246 | e = _ilog2(mag) | ||
| 247 | if e < -126: | ||
| 248 | raise NotJudged("v_fma_mix_f32 gives an f32 denormal") | ||
| 249 | m = mag / Fraction(2) ** (e - 23) - (1 << 23) | ||
| 250 | assert m.denominator == 1 and 0 <= m < (1 << 23) and e <= 127, value | ||
| 251 | return (sign << 31) | ((e + 127) << 23) | int(m) | ||
| 252 | |||
| 253 | |||
| 254 | def fma(x, y, z): | ||
| 255 | """x * y + z, exact (not rounded). Any NaN, inf * 0 and inf - inf give ("nan", 0, None).""" | ||
| 256 | if "nan" in (x[0], y[0], z[0]): | ||
| 257 | return ("nan", 0, None) | ||
| 258 | ps = x[1] ^ y[1] | ||
| 259 | if x[0] == "inf" or y[0] == "inf": | ||
| 260 | if (x[0] == "num" and x[2] == 0) or (y[0] == "num" and y[2] == 0): | ||
| 261 | return ("nan", 0, None) | ||
| 262 | if z[0] == "inf" and z[1] != ps: | ||
| 263 | return ("nan", 0, None) | ||
| 264 | return ("inf", ps, None) | ||
| 265 | if z[0] == "inf": | ||
| 266 | return z | ||
| 267 | pm = x[2] * y[2] | ||
| 268 | total = (-pm if ps else pm) + (-z[2] if z[1] else z[2]) | ||
| 269 | if total == 0: | ||
| 270 | return ("num", 1 if (pm == 0 and z[2] == 0 and ps and z[1]) else 0, Fraction(0)) | ||
| 271 | return ("num", 1 if total < 0 else 0, abs(total)) | ||
| 272 | |||
| 273 | |||
| 274 | def _key(v): | ||
| 275 | """Order for min/max: -inf < negative < -0 < +0 < positive < +inf.""" | ||
| 276 | kind, sign, mag = v | ||
| 277 | if kind == "inf": | ||
| 278 | return (2 if not sign else 0, 0, 0) | ||
| 279 | return (1, -mag if sign else mag, 0 if sign else 1) | ||
| 280 | |||
| 281 | |||
| 282 | def clamp01(v, nan_to_zero=False): | ||
| 283 | """Clamp to [0, 1]. A NaN gives +0 when ``nan_to_zero`` (frexp_mant, ldexp), else it is not judged; a -0 | ||
| 284 | through FClamp is not judged either.""" | ||
| 285 | kind, sign, mag = v | ||
| 286 | if kind == "nan": | ||
| 287 | if nan_to_zero: | ||
| 288 | return ("num", 0, Fraction(0)) | ||
| 289 | raise NotJudged("clamp of a NaN") | ||
| 290 | if sign: | ||
| 291 | if kind == "num" and mag == 0 and not nan_to_zero: | ||
| 292 | raise NotJudged("clamp of -0") | ||
| 293 | return ("num", 0, Fraction(0)) | ||
| 294 | if kind == "inf" or mag > 1: | ||
| 295 | return ("num", 0, Fraction(1)) | ||
| 296 | return v | ||
| 297 | |||
| 298 | |||
| 299 | # ---- the program text ---- | ||
| 300 | |||
| 301 | _REG = re.compile(r"([sv])(\d+)$") | ||
| 302 | _SRC = re.compile(r"(-?)(\|?)([sv]\d+)\|?$") | ||
| 303 | _MOD = re.compile(r"\s+(op_sel:\[[01](?:,[01])*\]|op_sel_hi:\[[01],[01],[01]\]|clamp)$") | ||
| 304 | |||
| 305 | |||
| 306 | def split_line(line): | ||
| 307 | """'op d, a, b mods' -> (op, [operands], [mods]).""" | ||
| 308 | mods = [] | ||
| 309 | while True: | ||
| 310 | m = _MOD.search(line) | ||
| 311 | if not m: | ||
| 312 | break | ||
| 313 | mods.insert(0, m.group(1)) | ||
| 314 | line = line[:m.start()] | ||
| 315 | op, _, rest = line.partition(" ") | ||
| 316 | return op, [t.strip() for t in rest.split(",")], mods | ||
| 317 | |||
| 318 | |||
| 319 | def _bits(mods, name, n): | ||
| 320 | m = next((x for x in mods if x.startswith(name + ":")), None) | ||
| 321 | if m is None: | ||
| 322 | return [0] * n | ||
| 323 | b = [int(x) for x in m.split("[")[1].rstrip("]").split(",")] | ||
| 324 | if len(b) != n: | ||
| 325 | raise HarnessError(f"{m}: want {n} bits") | ||
| 326 | return b | ||
| 327 | |||
| 328 | |||
| 329 | class Machine: | ||
| 330 | """The reference's register file: words plus per-half NaN states (see NAN16 above).""" | ||
| 331 | |||
| 332 | def __init__(self): | ||
| 333 | self.v = {} | ||
| 334 | self.s = {} | ||
| 335 | self.st = {} # vgpr -> [lo state, hi state] | ||
| 336 | |||
| 337 | def state(self, r): | ||
| 338 | return self.st.setdefault(r, [None, None]) | ||
| 339 | |||
| 340 | def raw(self, tok): | ||
| 341 | """(32-bit word, [lo state, hi state], kind) of a source token, modifiers stripped.""" | ||
| 342 | m = _SRC.match(tok) | ||
| 343 | if m: | ||
| 344 | reg = m.group(3) | ||
| 345 | k, i = reg[0], int(reg[1:]) | ||
| 346 | if k == "v": | ||
| 347 | if i not in self.v: | ||
| 348 | raise HarnessError(f"v{i} read before it is written") | ||
| 349 | return self.v[i], list(self.state(i)), "vgpr" | ||
| 350 | if i not in self.s: | ||
| 351 | raise HarnessError(f"s{i} read before it is written") | ||
| 352 | return self.s[i], [None, None], "sgpr" | ||
| 353 | if tok in FLOAT_INLINE: | ||
| 354 | return None, [None, None], "float" | ||
| 355 | if tok.startswith("0x"): | ||
| 356 | return int(tok, 16), [None, None], "lit" | ||
| 357 | try: | ||
| 358 | n = int(tok) | ||
| 359 | except ValueError: | ||
| 360 | raise HarnessError(f"unknown source {tok!r}") from None | ||
| 361 | if n not in INT_INLINE: | ||
| 362 | raise HarnessError(f"{n} is not an inline constant") | ||
| 363 | return n & M32, [None, None], "int" | ||
| 364 | |||
| 365 | def f16(self, tok, hi=0): | ||
| 366 | """An f16 operand: (value, known bits or None). neg/abs applied.""" | ||
| 367 | m = _SRC.match(tok) | ||
| 368 | mod = (m.group(1) + m.group(2)) if m else "" | ||
| 369 | base = m.group(3) if m else tok | ||
| 370 | if base in FLOAT_INLINE: | ||
| 371 | h = 0 if hi else FLOAT_INLINE[base][1] | ||
| 372 | st = None | ||
| 373 | else: | ||
| 374 | w, sts, _ = self.raw(base) | ||
| 375 | h = (w >> 16) & M16 if hi else w & M16 | ||
| 376 | st = sts[1 if hi else 0] | ||
| 377 | if st == "w32": | ||
| 378 | raise NotJudged("half of an f32 NaN read as an f16") | ||
| 379 | if "|" in mod: | ||
| 380 | h &= 0x7FFF | ||
| 381 | if mod.startswith("-"): | ||
| 382 | h ^= 0x8000 | ||
| 383 | if st == "nan": | ||
| 384 | return ("nan", h >> 15, None), None | ||
| 385 | return decode16(h), h | ||
| 386 | |||
| 387 | def f32(self, tok): | ||
| 388 | """An f32 operand of v_fma_mix_*: (value, None); a denormal reads as a signed zero.""" | ||
| 389 | m = _SRC.match(tok) | ||
| 390 | mod = (m.group(1) + m.group(2)) if m else "" | ||
| 391 | base = m.group(3) if m else tok | ||
| 392 | if base in FLOAT_INLINE: | ||
| 393 | w, sts = FLOAT_INLINE[base][0], [None, None] | ||
| 394 | else: | ||
| 395 | w, sts, _ = self.raw(base) | ||
| 396 | if sts == ["w32", "w32"]: | ||
| 397 | return ("nan", 0, None) | ||
| 398 | if sts != [None, None]: | ||
| 399 | raise NotJudged("an f16 NaN of unmodelled payload read as f32 bits") | ||
| 400 | if "|" in mod: | ||
| 401 | w &= 0x7FFFFFFF | ||
| 402 | if mod.startswith("-"): | ||
| 403 | w ^= 0x80000000 | ||
| 404 | return decode32(w, flush=True) | ||
| 405 | |||
| 406 | def i16(self, tok, hi=0): | ||
| 407 | if _SRC.match(tok) and tok[0] in "-|": | ||
| 408 | raise HarnessError("modifier on an integer operand") | ||
| 409 | w, sts, kind = self.raw(tok) | ||
| 410 | if kind == "float": | ||
| 411 | raise HarnessError("float constant as an i16") | ||
| 412 | if sts[1 if hi else 0] is not None: | ||
| 413 | raise NotJudged("an unmodelled NaN payload read as an i16") | ||
| 414 | h = (w >> 16) & M16 if hi else w & M16 | ||
| 415 | return h - 0x10000 if h & 0x8000 else h | ||
| 416 | |||
| 417 | def dst(self, tok): | ||
| 418 | m = _REG.match(tok) | ||
| 419 | if not m or m.group(1) != "v": | ||
| 420 | raise HarnessError(f"destination {tok!r}") | ||
| 421 | return int(m.group(2)) | ||
| 422 | |||
| 423 | def write_half(self, r, hi, h, st=None): | ||
| 424 | old = self.v.get(r, 0) | ||
| 425 | sts = self.state(r) | ||
| 426 | if hi: | ||
| 427 | self.v[r] = (old & M16) | ((h & M16) << 16) | ||
| 428 | else: | ||
| 429 | self.v[r] = (old & 0xFFFF0000) | (h & M16) | ||
| 430 | sts[1 if hi else 0] = st | ||
| 431 | |||
| 432 | def write_word(self, r, w, st=None): | ||
| 433 | self.v[r] = w & M32 | ||
| 434 | self.st[r] = [st, st] | ||
| 435 | |||
| 436 | |||
| 437 | def _out16(value): | ||
| 438 | """(bits, state) of an f16 result; a NaN the reference computed has no modelled payload.""" | ||
| 439 | if value[0] == "nan": | ||
| 440 | return NAN16, "nan" | ||
| 441 | return encode16(value), None | ||
| 442 | |||
| 443 | |||
| 444 | def _count_in(events, op, *vals): | ||
| 445 | if events is None: | ||
| 446 | return | ||
| 447 | ev = events.setdefault(op, Counter()) | ||
| 448 | for v in vals: | ||
| 449 | if v[0] == "nan": | ||
| 450 | ev["NaN"] += 1 | ||
| 451 | elif v[0] == "inf": | ||
| 452 | ev["inf"] += 1 | ||
| 453 | elif v[2] != 0 and v[2] < Fraction(1, 1 << 14): | ||
| 454 | ev["denormal"] += 1 | ||
| 455 | |||
| 456 | |||
| 457 | def step(line, mc, events=None): | ||
| 458 | """Run one op line on the Machine.""" | ||
| 459 | op_full, args, mods = split_line(line) | ||
| 460 | op = op_full | ||
| 461 | for suf in ("_e32", "_e64"): | ||
| 462 | if op.endswith(suf): | ||
| 463 | op = op[:-len(suf)] | ||
| 464 | kind = FAMILY.get(op) | ||
| 465 | if kind is None: | ||
| 466 | raise HarnessError(f"op {op_full!r} is not in the family") | ||
| 467 | ev = None if events is None else events.setdefault(op, Counter()) | ||
| 468 | d = mc.dst(args[0]) | ||
| 469 | clamp = "clamp" in mods | ||
| 470 | if kind in ("min3", "max3"): | ||
| 471 | sel = _bits(mods, "op_sel", 4) | ||
| 472 | vals = [mc.f16(t, sel[i])[0] for i, t in enumerate(args[1:4])] | ||
| 473 | _count_in(events, op, *vals) | ||
| 474 | live = [v for v in vals if v[0] != "nan"] | ||
| 475 | if not live: | ||
| 476 | r = ("nan", 0, None) # the hardware returns src0's bits, the translator a quiet NaN: any NaN | ||
| 477 | else: | ||
| 478 | r = (min if kind == "min3" else max)(live, key=_key) | ||
| 479 | if clamp: | ||
| 480 | r = clamp01(r) | ||
| 481 | h, st = _out16(r) | ||
| 482 | mc.write_half(d, sel[3], h, st) | ||
| 483 | elif kind in ("mant", "exp"): | ||
| 484 | sel = _bits(mods, "op_sel", 2) | ||
| 485 | v, h = mc.f16(args[1], sel[0]) | ||
| 486 | _count_in(events, op, v) | ||
| 487 | if kind == "exp": | ||
| 488 | if clamp: | ||
| 489 | raise HarnessError("clamp on v_frexp_exp_i16_f16") | ||
| 490 | e = _ilog2(v[2]) + 1 if v[0] == "num" and v[2] != 0 else 0 | ||
| 491 | mc.write_half(d, sel[1], e & M16) | ||
| 492 | return | ||
| 493 | if v[0] == "num" and v[2] != 0: | ||
| 494 | r = ("num", v[1], v[2] / Fraction(2) ** (_ilog2(v[2]) + 1)) | ||
| 495 | else: | ||
| 496 | r = v | ||
| 497 | if clamp: | ||
| 498 | r = clamp01(r, nan_to_zero=True) | ||
| 499 | if r[0] == "nan": | ||
| 500 | mc.write_half(d, sel[1], NAN16 if h is None else h, "nan" if h is None else None) | ||
| 501 | else: | ||
| 502 | mc.write_half(d, sel[1], encode16(r)) | ||
| 503 | elif kind == "ldexp": | ||
| 504 | sel = _bits(mods, "op_sel", 3) | ||
| 505 | v, h = mc.f16(args[1], sel[0]) | ||
| 506 | n = max(-64, min(64, mc.i16(args[2], sel[1]))) | ||
| 507 | _count_in(events, op, v) | ||
| 508 | if v[0] == "num" and v[2] != 0: | ||
| 509 | r = round_to(("num", v[1], v[2] * Fraction(2) ** n), F16, ev) | ||
| 510 | else: | ||
| 511 | r = v | ||
| 512 | if clamp: | ||
| 513 | r = clamp01(r, nan_to_zero=True) | ||
| 514 | if r[0] == "nan": | ||
| 515 | mc.write_half(d, sel[2], NAN16 if h is None else h, "nan" if h is None else None) | ||
| 516 | else: | ||
| 517 | mc.write_half(d, sel[2], encode16(r)) | ||
| 518 | elif kind in ("fmamk", "fmaak"): | ||
| 519 | a = mc.f16(args[1])[0] | ||
| 520 | b = mc.f16(args[2])[0] | ||
| 521 | c = mc.f16(args[3])[0] | ||
| 522 | _count_in(events, op, a, b, c) | ||
| 523 | h, st = _out16(round_to(fma(a, b, c), F16, ev)) | ||
| 524 | mc.write_half(d, 0, h, st) | ||
| 525 | elif kind == "pkfmac": | ||
| 526 | acc = [] | ||
| 527 | for hi in (0, 1): | ||
| 528 | a = mc.f16(args[1], hi)[0] | ||
| 529 | b = mc.f16(args[2], hi)[0] | ||
| 530 | c = mc.f16(args[0], hi)[0] | ||
| 531 | _count_in(events, op, a, b, c) | ||
| 532 | acc.append(_out16(round_to(fma(a, b, c), F16, ev))) | ||
| 533 | for hi in (0, 1): | ||
| 534 | mc.write_half(d, hi, acc[hi][0], acc[hi][1]) | ||
| 535 | else: # v_fma_mix_* | ||
| 536 | sel = _bits(mods, "op_sel", 3) | ||
| 537 | shi = _bits(mods, "op_sel_hi", 3) | ||
| 538 | vals = [mc.f16(t, sel[i])[0] if shi[i] else mc.f32(t) for i, t in enumerate(args[1:4])] | ||
| 539 | _count_in(events, op, *vals) | ||
| 540 | r = fma(*vals) | ||
| 541 | if clamp: | ||
| 542 | r = clamp01(r) | ||
| 543 | if kind == "mix32": | ||
| 544 | r = round_to(r, F32, ev) | ||
| 545 | if r[0] == "nan": | ||
| 546 | mc.write_word(d, NAN32, "w32") | ||
| 547 | else: | ||
| 548 | mc.write_word(d, encode32(r)) | ||
| 549 | else: | ||
| 550 | h, st = _out16(round_to(r, F16, ev)) | ||
| 551 | mc.write_half(d, 1 if kind == "mixhi" else 0, h, st) | ||
| 552 | |||
| 553 | |||
| 554 | def reference(lines, events=None): | ||
| 555 | """Run the program; returns (four exported words, per-word half states). Raises NotJudged.""" | ||
| 556 | mc = Machine() | ||
| 557 | for line in lines: | ||
| 558 | op, args, _ = split_line(line) | ||
| 559 | if op == "v_mov_b32": | ||
| 560 | mc.write_word(mc.dst(args[0]), int(args[1], 16)) | ||
| 561 | elif op == "s_mov_b32": | ||
| 562 | mc.s[int(args[0][1:])] = int(args[1], 16) & M32 | ||
| 563 | else: | ||
| 564 | step(line, mc, events) | ||
| 565 | return [mc.v[r] for r in EXPORT_REGS], [list(mc.state(r)) for r in EXPORT_REGS] | ||
| 566 | |||
| 567 | |||
| 568 | def compare(want, states, got): | ||
| 569 | """None when every judged bit agrees, else a description of the first difference.""" | ||
| 570 | for i, (w, sts, g) in enumerate(zip(want, states, got)): | ||
| 571 | g &= M32 | ||
| 572 | if sts == ["w32", "w32"]: | ||
| 573 | if not ((g >> 23) & 0xFF == 0xFF and g & 0x7FFFFF): | ||
| 574 | return f"word {i} (v{EXPORT_REGS[i]}): expected an f32 NaN, actual 0x{g:08x}" | ||
| 575 | continue | ||
| 576 | for hi in (0, 1): | ||
| 577 | st = sts[hi] | ||
| 578 | wh, gh = (w >> (16 * hi)) & M16, (g >> (16 * hi)) & M16 | ||
| 579 | if st == "w32": | ||
| 580 | continue | ||
| 581 | if st == "nan": | ||
| 582 | if not ((gh >> 10) & 0x1F == 0x1F and gh & 0x3FF): | ||
| 583 | return (f"word {i} (v{EXPORT_REGS[i]}) {'high' if hi else 'low'} half: expected an f16 NaN, " | ||
| 584 | f"actual 0x{g:08x}") | ||
| 585 | elif wh != gh: | ||
| 586 | return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" | ||
| 587 | return None | ||
| 588 | |||
| 589 | |||
| 590 | # ---- the generator ---- | ||
| 591 | |||
| 592 | F16_EDGES = (0x0000, 0x8000, 0x0001, 0x8001, 0x0200, 0x03FF, 0x83FF, 0x0400, 0x8400, 0x0401, 0x3555, 0x3800, | ||
| 593 | 0xB800, 0x3BFF, 0x3C00, 0xBC00, 0x3C01, 0x4000, 0xC000, 0x5640, 0x7800, 0x7BFF, 0xFBFF, 0x7C00, | ||
| 594 | 0xFC00, 0x7C01, 0xFC01, 0x7D00, 0x7E00, 0xFE00, 0x7FFF) | ||
| 595 | F32_EDGES = (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF, 0x00800000, 0x3F800000, 0xBF800000, 0x3F000000, | ||
| 596 | 0x477FE000, 0x477FF000, 0x477FEFFF, 0x387FC000, 0x33800000, 0x33000000, 0x7F7FFFFF, 0x7F800000, | ||
| 597 | 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7FA00000, 0x40490FDB) | ||
| 598 | I16_EDGES = (0, 1, -1, 2, -2, 10, -10, 14, -14, 15, -15, 16, -16, 24, -24, 25, -25, 29, 30, -30, 31, 40, -40, | ||
| 599 | 63, -63, 64, -64, 65, -65, 100, -100, 32767, -32768) | ||
| 600 | |||
| 601 | |||
| 602 | def _rand_f16(rng): | ||
| 603 | r = rng.random() | ||
| 604 | if r < 0.3: | ||
| 605 | return rng.choice(F16_EDGES) | ||
| 606 | if r < 0.4: | ||
| 607 | return (rng.getrandbits(1) << 15) | rng.randrange(1, 0x400) # denormal | ||
| 608 | if r < 0.5: | ||
| 609 | return rng.getrandbits(16) | ||
| 610 | e = rng.randrange(1, 31) if rng.random() < 0.3 else rng.randrange(11, 20) # mostly near 1 | ||
| 611 | return (rng.getrandbits(1) << 15) | (e << 10) | rng.getrandbits(10) | ||
| 612 | |||
| 613 | |||
| 614 | def _rand_f32(rng): | ||
| 615 | r = rng.random() | ||
| 616 | if r < 0.3: | ||
| 617 | return rng.choice(F32_EDGES) | ||
| 618 | if r < 0.4: | ||
| 619 | return rng.getrandbits(32) | ||
| 620 | e = rng.randrange(1, 255) if rng.random() < 0.3 else rng.randrange(100, 145) | ||
| 621 | return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23) | ||
| 622 | |||
| 623 | |||
| 624 | def _seed_word(rng): | ||
| 625 | r = rng.random() | ||
| 626 | if r < 0.6: | ||
| 627 | return _rand_f16(rng) | (_rand_f16(rng) << 16) | ||
| 628 | if r < 0.8: | ||
| 629 | return _rand_f32(rng) | ||
| 630 | return (rng.choice(I16_EDGES) & M16) | (_rand_f16(rng) << 16) | ||
| 631 | |||
| 632 | |||
| 633 | def _source(rng, kind): | ||
| 634 | """A source token of ``kind`` (no modifier).""" | ||
| 635 | if kind == "vgpr": | ||
| 636 | return f"v{rng.choice(VGPRS)}" | ||
| 637 | if kind == "sgpr": | ||
| 638 | return f"s{rng.choice(SGPRS)}" | ||
| 639 | if kind == "lit": | ||
| 640 | r = rng.random() | ||
| 641 | if r < 0.5: | ||
| 642 | return f"0x{_rand_f16(rng) | (_rand_f16(rng) << 16):08x}" | ||
| 643 | if r < 0.8: | ||
| 644 | return f"0x{_rand_f32(rng):08x}" | ||
| 645 | return f"0x{(rng.choice(I16_EDGES) & M16) | (rng.getrandbits(16) << 16):08x}" | ||
| 646 | if kind == "int": | ||
| 647 | return str(rng.choice(INT_INLINE)) | ||
| 648 | return rng.choice(tuple(FLOAT_INLINE)) | ||
| 649 | |||
| 650 | |||
| 651 | def encodable(kinds, form): | ||
| 652 | """GFX10: one literal, VOP3/VOP3P at most two constant-bus reads (SGPRs and the literal); VOP1/VOP2 e32 take a | ||
| 653 | literal or SGPR only in src0 (and VOP2 vsrc1 is a VGPR).""" | ||
| 654 | lits = sum(k == "lit" for k in kinds) | ||
| 655 | bus = sum(k in ("sgpr", "lit") for k in kinds) | ||
| 656 | if lits > 1: | ||
| 657 | return False | ||
| 658 | if form == "vop3": | ||
| 659 | return bus <= 2 | ||
| 660 | return all(k == "vgpr" for k in kinds[1:]) | ||
| 661 | |||
| 662 | |||
| 663 | def _reg_mod(rng, tok, kind): | ||
| 664 | if kind not in ("vgpr", "sgpr"): | ||
| 665 | return tok | ||
| 666 | m = rng.choice(MODS) | ||
| 667 | return f"{'-' if m.startswith('-') else ''}{'|' if '|' in m else ''}{tok}{'|' if '|' in m else ''}" | ||
| 668 | |||
| 669 | |||
| 670 | def op_line(rng, op, kinds=None, form=None, mods=True, values=None): | ||
| 671 | """One line of ``op``. ``kinds`` fixes the source kinds (else random), ``form`` the encoding ("e32"/"e64" for | ||
| 672 | VOP1/VOP2 ops), ``values`` optional exact source tokens.""" | ||
| 673 | kind = FAMILY[op] | ||
| 674 | d = f"v{rng.choice(DSTS)}" | ||
| 675 | |||
| 676 | def pick(n, allowed=KINDS, vop3=True): | ||
| 677 | while True: | ||
| 678 | ks = list(kinds) if kinds else [rng.choice(allowed) for _ in range(n)] | ||
| 679 | if encodable(ks, "vop3" if vop3 else "vop2"): | ||
| 680 | return ks | ||
| 681 | if kinds: | ||
| 682 | raise HarnessError(f"{op}: {kinds} not encodable") | ||
| 683 | |||
| 684 | if kind in ("min3", "max3") or kind in ("mix32", "mixlo", "mixhi"): | ||
| 685 | ks = pick(3) | ||
| 686 | toks = values or [_source(rng, k) for k in ks] | ||
| 687 | srcs = [_reg_mod(rng, t, k) if mods else t for t, k in zip(toks, ks)] | ||
| 688 | if kind in ("min3", "max3"): | ||
| 689 | sel = [rng.getrandbits(1) if k in ("vgpr", "sgpr") else 0 for k in ks] + [rng.getrandbits(1)] | ||
| 690 | extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else "" | ||
| 691 | else: | ||
| 692 | shi = [rng.getrandbits(1) for _ in ks] | ||
| 693 | sel = [rng.getrandbits(1) if (k in ("vgpr", "sgpr") and h) else 0 for k, h in zip(ks, shi)] | ||
| 694 | extra = f" op_sel:[{','.join(map(str, sel))}] op_sel_hi:[{','.join(map(str, shi))}]" | ||
| 695 | if mods and rng.random() < 0.25: | ||
| 696 | extra += " clamp" | ||
| 697 | return f"{op} {d}, {', '.join(srcs)}{extra}", ks | ||
| 698 | if kind in ("mant", "exp"): | ||
| 699 | form = form or rng.choice(("e32", "e64")) | ||
| 700 | ks = pick(1) | ||
| 701 | tok = values[0] if values else _source(rng, ks[0]) | ||
| 702 | if form == "e32": | ||
| 703 | return f"{op}_e32 {d}, {tok}", ks | ||
| 704 | src = _reg_mod(rng, tok, ks[0]) if mods else tok | ||
| 705 | sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)] | ||
| 706 | extra = f" op_sel:[{sel[0]},{sel[1]}]" if any(sel) or rng.random() < 0.2 else "" | ||
| 707 | if kind == "mant" and mods and rng.random() < 0.25: | ||
| 708 | extra += " clamp" | ||
| 709 | return f"{op}_e64 {d}, {src}{extra}", ks | ||
| 710 | if kind == "ldexp": | ||
| 711 | form = form or rng.choice(("e32", "e64")) | ||
| 712 | if form == "e32": | ||
| 713 | ks = pick(2, vop3=False) if kinds else [rng.choice(KINDS), "vgpr"] | ||
| 714 | toks = values or [_source(rng, ks[0]), _source(rng, "vgpr")] | ||
| 715 | return f"{op}_e32 {d}, {toks[0]}, {toks[1]}", ks | ||
| 716 | while True: | ||
| 717 | ks = list(kinds) if kinds else [rng.choice(KINDS), rng.choice(("vgpr", "sgpr", "lit", "int"))] | ||
| 718 | if ks[1] == "float": | ||
| 719 | raise HarnessError("float constant as ldexp's exponent") | ||
| 720 | if encodable(ks, "vop3"): | ||
| 721 | break | ||
| 722 | if kinds: | ||
| 723 | raise HarnessError(f"{op}: {kinds} not encodable") | ||
| 724 | toks = values or [_source(rng, k) for k in ks] | ||
| 725 | src0 = _reg_mod(rng, toks[0], ks[0]) if mods else toks[0] | ||
| 726 | sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0, | ||
| 727 | rng.getrandbits(1) if ks[1] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)] | ||
| 728 | extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else "" | ||
| 729 | if mods and rng.random() < 0.25: | ||
| 730 | extra += " clamp" | ||
| 731 | return f"{op}_e64 {d}, {src0}, {toks[1]}{extra}", ks | ||
| 732 | if kind in ("fmamk", "fmaak"): | ||
| 733 | k0 = kinds[0] if kinds else rng.choice(("vgpr", "sgpr", "int", "float")) | ||
| 734 | ks = [k0, "vgpr"] | ||
| 735 | toks = values or [_source(rng, k0), _source(rng, "vgpr"), f"0x{_rand_f16(rng):04x}"] | ||
| 736 | if kind == "fmamk": | ||
| 737 | return f"{op} {d}, {toks[0]}, {toks[2]}, {toks[1]}", ks | ||
| 738 | return f"{op} {d}, {toks[0]}, {toks[1]}, {toks[2]}", ks | ||
| 739 | # v_pk_fmac_f16 | ||
| 740 | k0 = kinds[0] if kinds else rng.choice(KINDS) | ||
| 741 | ks = [k0, "vgpr"] | ||
| 742 | toks = values or [_source(rng, k0), _source(rng, "vgpr")] | ||
| 743 | return f"{op} {d}, {toks[0]}, {toks[1]}", ks | ||
| 744 | |||
| 745 | |||
| 746 | def seeds(rng): | ||
| 747 | lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in VGPRS] | ||
| 748 | lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in SGPRS] | ||
| 749 | return lines | ||
| 750 | |||
| 751 | |||
| 752 | def program(rng, n_ops, ops=None): | ||
| 753 | """A random program: seeds, n_ops family ops, the export. Returns (lines, the ops used).""" | ||
| 754 | ops = list(ops or FAMILY) | ||
| 755 | lines = seeds(rng) | ||
| 756 | used = [] | ||
| 757 | for _ in range(n_ops): | ||
| 758 | op = rng.choice(ops) | ||
| 759 | lines.append(op_line(rng, op)[0]) | ||
| 760 | used.append(op) | ||
| 761 | return lines, used | ||
| 762 | |||
| 763 | |||
| 764 | def sweep_cases(ops=None): | ||
| 765 | """(op, form, kinds) for every encodable source-kind combination of every op and form.""" | ||
| 766 | cases = [] | ||
| 767 | for op in ops or FAMILY: | ||
| 768 | kind = FAMILY[op] | ||
| 769 | if kind in ("min3", "max3", "mix32", "mixlo", "mixhi"): | ||
| 770 | for a in KINDS: | ||
| 771 | for b in KINDS: | ||
| 772 | for c in KINDS: | ||
| 773 | if encodable([a, b, c], "vop3"): | ||
| 774 | cases.append((op, None, (a, b, c))) | ||
| 775 | elif kind in ("mant", "exp"): | ||
| 776 | for form in ("e32", "e64"): | ||
| 777 | for a in KINDS: | ||
| 778 | cases.append((op, form, (a,))) | ||
| 779 | elif kind == "ldexp": | ||
| 780 | for a in KINDS: | ||
| 781 | cases.append((op, "e32", (a, "vgpr"))) | ||
| 782 | for b in ("vgpr", "sgpr", "lit", "int"): | ||
| 783 | if encodable([a, b], "vop3"): | ||
| 784 | cases.append((op, "e64", (a, b))) | ||
| 785 | elif kind in ("fmamk", "fmaak"): | ||
| 786 | for a in ("vgpr", "sgpr", "int", "float"): | ||
| 787 | cases.append((op, None, (a, "vgpr"))) | ||
| 788 | else: | ||
| 789 | for a in KINDS: | ||
| 790 | cases.append((op, None, (a, "vgpr"))) | ||
| 791 | return cases | ||
| 792 | |||
| 793 | |||
| 794 | SWEEP_REPEAT = 2 | ||
| 795 | |||
| 796 | |||
| 797 | def sweep_program(case, rng): | ||
| 798 | op, form, kinds = case | ||
| 799 | return seeds(rng) + [op_line(rng, op, kinds, form)[0]] | ||
| 800 | |||
| 801 | |||
| 802 | GRID_PER_PROGRAM = 4 | ||
| 803 | _GRID_RNG_SEED = "f16misc_diff:grid" | ||
| 804 | |||
| 805 | |||
| 806 | def grid_cases(ops=None): | ||
| 807 | """(op, source words[, "clamp"]) cases: special values through every op. Each case is one op line reading | ||
| 808 | v12..v15; frexp_mant and ldexp also run the edges with clamp (a NaN gives +0).""" | ||
| 809 | rng = random.Random(_GRID_RNG_SEED) | ||
| 810 | ops = list(ops or FAMILY) | ||
| 811 | cases = [] | ||
| 812 | edges = F16_EDGES | ||
| 813 | for op in ops: | ||
| 814 | kind = FAMILY[op] | ||
| 815 | if kind in ("mant", "exp"): | ||
| 816 | for h in edges: | ||
| 817 | cases.append((op, (h | (rng.getrandbits(16) << 16),))) | ||
| 818 | if kind == "mant": | ||
| 819 | for h in edges: | ||
| 820 | cases.append((op, (h | (rng.getrandbits(16) << 16),), "clamp")) | ||
| 821 | elif kind == "ldexp": | ||
| 822 | for h in edges: | ||
| 823 | for n in (-64, -25, -24, -15, -1, 0, 1, 15, 29, 30, 64, 100): | ||
| 824 | cases.append((op, (h, n & M16))) | ||
| 825 | for h in edges: | ||
| 826 | for n in (-1, 0, 1): | ||
| 827 | cases.append((op, (h, n & M16), "clamp")) | ||
| 828 | elif kind in ("min3", "max3"): | ||
| 829 | pick = (0x0000, 0x8000, 0x0001, 0x3C00, 0xBC00, 0x7C00, 0xFC00, 0x7E00, 0x7D00, 0x4000) | ||
| 830 | for a in pick: | ||
| 831 | for b in pick: | ||
| 832 | for c in pick: | ||
| 833 | if (a, b, c).count(0x7E00) + (a, b, c).count(0x7D00) == 3: | ||
| 834 | continue # every operand NaN: payload not modelled, see the docstring | ||
| 835 | cases.append((op, (a, b, c))) | ||
| 836 | else: | ||
| 837 | for _ in range(240): | ||
| 838 | cases.append((op, _fma_case(rng, kind))) | ||
| 839 | return cases | ||
| 840 | |||
| 841 | |||
| 842 | def _pow2_16(e, mant=0): | ||
| 843 | """The f16 2^e * (1 + mant/1024), e in [-14, 15].""" | ||
| 844 | return ((e + 15) << 10) | mant | ||
| 845 | |||
| 846 | |||
| 847 | # (a, c, d): the f16 mantissas 1 + a/1024 and (2048 - c)/2048 multiply to 1 + d/2^21 with 0 < |d| < 256. Added to | ||
| 848 | # half an ulp of an f16 z, that product is off the tie by less than half an f32 ulp of the sum: an f32 fma rounds | ||
| 849 | # it onto the tie and the f16 rounding then goes to even, so an fma rounded twice is wrong in about half the cases. | ||
| 850 | NEAR_ONE = tuple((a, c, (1024 + a) * (2048 - c) - (1 << 21)) | ||
| 851 | for a in range(1, 64) for c in range(max(1, 2 * a - 3), 2 * a + 4) | ||
| 852 | if 0 < abs((1024 + a) * (2048 - c) - (1 << 21)) < 256) | ||
| 853 | |||
| 854 | |||
| 855 | def _tie_case(rng, f32_addend): | ||
| 856 | """x * y + z with x * y = +-half an ulp of z, or a hair above or below it: z + x*y is a rounding tie (or the | ||
| 857 | nearest non-tie) of the result format (f16, or f32 when ``f32_addend``). x and y are f16 powers of two times | ||
| 858 | 1, 1 + 2^-10 or 1 - 2^-11, or a NEAR_ONE pair (x * y = 2^k (1 + d/2^21)).""" | ||
| 859 | if f32_addend: | ||
| 860 | ez = rng.randrange(125, 170) # biased f32 exponent of z; half its ulp is 2^(ez - 151) | ||
| 861 | z = (rng.getrandbits(1) << 31) | (ez << 23) | rng.getrandbits(23) | ||
| 862 | k = ez - 151 | ||
| 863 | else: | ||
| 864 | ez = rng.randrange(5, 31) # biased f16 exponent; half an ulp is 2^(ez - 26) | ||
| 865 | z = (rng.getrandbits(1) << 15) | (ez << 10) | rng.getrandbits(10) | ||
| 866 | k = ez - 26 | ||
| 867 | a = max(-14, min(15, k // 2)) | ||
| 868 | b = k - a | ||
| 869 | if not -14 <= b <= 15: | ||
| 870 | return (0x3C00, 0x3C00, z) | ||
| 871 | sx = rng.getrandbits(1) << 15 | ||
| 872 | if rng.random() < 0.4 and b - 1 >= -14: | ||
| 873 | am, c, _ = rng.choice(NEAR_ONE) | ||
| 874 | return (_pow2_16(a, am) | sx, _pow2_16(b - 1, 1024 - c), z) | ||
| 875 | mant, eb = rng.choice(((0, b), (0, b), (1, b), (0x3FF, b - 1))) # 1, 1 + 2^-10, (2 - 2^-10) / 2 | ||
| 876 | if not -14 <= eb <= 15: | ||
| 877 | mant, eb = 0, b | ||
| 878 | return (_pow2_16(a) | sx, _pow2_16(eb, mant), z) | ||
| 879 | |||
| 880 | |||
| 881 | def _fma_case(rng, kind): | ||
| 882 | """Three source words for an fma op, aimed at ties, cancellation, overflow and the denormal range.""" | ||
| 883 | r = rng.random() | ||
| 884 | if kind == "mix32" or (kind in ("mixlo", "mixhi") and rng.random() < 0.5): | ||
| 885 | f = _rand_f32 | ||
| 886 | else: | ||
| 887 | f = _rand_f16 | ||
| 888 | x, y = f(rng), f(rng) | ||
| 889 | if r < 0.3: | ||
| 890 | return _tie_case(rng, kind == "mix32") | ||
| 891 | if r < 0.45: | ||
| 892 | z = f(rng) | ||
| 893 | elif r < 0.6: | ||
| 894 | # z = -(x*y) rounded: the sum cancels to the product's rounding error | ||
| 895 | z = _neg_product(x, y, f is _rand_f16) | ||
| 896 | elif r < 0.8: | ||
| 897 | z = rng.choice(F16_EDGES if f is _rand_f16 else F32_EDGES) | ||
| 898 | else: | ||
| 899 | z = 0 if rng.random() < 0.5 else (0x8000 if f is _rand_f16 else 0x80000000) | ||
| 900 | return (x, y, z) | ||
| 901 | |||
| 902 | |||
| 903 | def _neg_product(x, y, half): | ||
| 904 | a = decode16(x) if half else decode32(x, flush=False) | ||
| 905 | b = decode16(y) if half else decode32(y, flush=False) | ||
| 906 | p = fma(a, b, ("num", 0, Fraction(0))) | ||
| 907 | if p[0] != "num": | ||
| 908 | return x | ||
| 909 | r = round_to(("num", p[1] ^ 1, p[2]), F16 if half else F32) | ||
| 910 | if r[0] != "num": | ||
| 911 | return x | ||
| 912 | try: | ||
| 913 | return encode16(r) if half else encode32(r) | ||
| 914 | except NotJudged: | ||
| 915 | return 0 | ||
| 916 | |||
| 917 | |||
| 918 | def grid_program(chunk, rng): | ||
| 919 | """A program for up to GRID_PER_PROGRAM grid cases. Case i reads only its own registers and writes v{8+i}.""" | ||
| 920 | lines = [f"v_mov_b32 v{r}, 0x{rng.getrandbits(32):08x}" for r in VGPRS] | ||
| 921 | lines += [f"s_mov_b32 s{r}, 0x{rng.getrandbits(32):08x}" for r in SGPRS] | ||
| 922 | body = [] | ||
| 923 | for i, (op, words, *flags) in enumerate(chunk): | ||
| 924 | kind = FAMILY[op] | ||
| 925 | d = f"v{DSTS[i]}" | ||
| 926 | clamp = " clamp" if "clamp" in flags else "" | ||
| 927 | if kind in ("mant", "exp"): | ||
| 928 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}") | ||
| 929 | body.append(f"{op}_e64 {d}, v{12 + i}{clamp}") | ||
| 930 | elif kind == "ldexp": | ||
| 931 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}") | ||
| 932 | body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]{clamp}") | ||
| 933 | elif kind in ("min3", "max3"): | ||
| 934 | # the three halves: v{12+i} lo, v{12+i} hi and d's own high half (read before it is written) | ||
| 935 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}") | ||
| 936 | lines.append(f"v_mov_b32 {d}, 0x{(words[2] << 16) | 0x1234:08x}") | ||
| 937 | body.append(f"{op} {d}, v{12 + i}, v{12 + i}, {d} op_sel:[0,1,1,0]") | ||
| 938 | elif kind in ("fmamk", "fmaak"): | ||
| 939 | # words are (x, y, z) of x * y + z: fmamk D = S0 * K + S1 takes y as K, fmaak D = S0 * S1 + K takes z | ||
| 940 | kw, dw = (words[1], words[2]) if kind == "fmamk" else (words[2], words[1]) | ||
| 941 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (rng.getrandbits(16) << 16):08x}") | ||
| 942 | lines.append(f"v_mov_b32 {d}, 0x{dw | (rng.getrandbits(16) << 16):08x}") | ||
| 943 | k = f"0x{kw:04x}" | ||
| 944 | if kind == "fmamk": | ||
| 945 | body.append(f"{op} {d}, v{12 + i}, {k}, {d}") | ||
| 946 | else: | ||
| 947 | body.append(f"{op} {d}, v{12 + i}, {d}, {k}") | ||
| 948 | elif kind == "pkfmac": | ||
| 949 | # lane 0: words, lane 1: the same values negated | ||
| 950 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | ((words[0] ^ 0x8000) << 16):08x}") | ||
| 951 | lines.append(f"v_mov_b32 {d}, 0x{words[2] | ((words[2] ^ 0x8000) << 16):08x}") | ||
| 952 | lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1] | (words[1] << 16):08x}") | ||
| 953 | body.append(f"{op} {d}, s{4 + i}, v{12 + i}") | ||
| 954 | else: | ||
| 955 | # f32 words are read whole (op_sel_hi 0), f16 values from the low half (op_sel_hi 1) | ||
| 956 | regs = [f"v{12 + i}", f"s{4 + i}", d] | ||
| 957 | lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}") | ||
| 958 | lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1]:08x}") | ||
| 959 | lines.append(f"v_mov_b32 {d}, 0x{words[2]:08x}") | ||
| 960 | shi = [0 if w > M16 else 1 for w in words] | ||
| 961 | body.append(f"{op} {d}, {', '.join(regs)} op_sel:[0,0,0] op_sel_hi:[{','.join(map(str, shi))}]") | ||
| 962 | return lines + body | ||
| 963 | |||
| 964 | |||
| 965 | def exhaustive_programs(ops=None): | ||
| 966 | """(op, lines) programs: every f16 input through the frexp ops and ldexp, four inputs per program.""" | ||
| 967 | exps = (-64, -25, -15, -1, 1, 15, 30, 64) | ||
| 968 | out = [] | ||
| 969 | for op in ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16"): | ||
| 970 | if ops and op not in ops: | ||
| 971 | continue | ||
| 972 | for base in range(0, 0x10000, GRID_PER_PROGRAM): | ||
| 973 | lines, body = [], [] | ||
| 974 | for i in range(GRID_PER_PROGRAM): | ||
| 975 | h = base + i | ||
| 976 | d = f"v{DSTS[i]}" | ||
| 977 | if op == "v_ldexp_f16": | ||
| 978 | n = exps[(h >> 2) % len(exps)] & M16 | ||
| 979 | lines.append(f"v_mov_b32 v{12 + i}, 0x{h | (n << 16):08x}") | ||
| 980 | body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]") | ||
| 981 | else: | ||
| 982 | lines.append(f"v_mov_b32 v{12 + i}, 0x{h | 0xabcd0000:08x}") | ||
| 983 | body.append(f"{op}_e32 {d}, v{12 + i}") | ||
| 984 | out.append((op, [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in DSTS] + lines + body)) | ||
| 985 | return out | ||
| 986 | |||
| 987 | |||
| 988 | # ---- the oracles ---- | ||
| 989 | |||
| 990 | def write_listing(path, lines, name): | ||
| 991 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 992 | f.write(f"; {name} code 0x0..0x1000\n") | ||
| 993 | for line in lines: | ||
| 994 | f.write("\t" + line + "\n") | ||
| 995 | f.write("\t" + EXPORT + "\n") | ||
| 996 | f.write("\ts_endpgm\n") | ||
| 997 | |||
| 998 | |||
| 999 | def translate_listing(lines, name, tmpdir): | ||
| 1000 | """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's | ||
| 1001 | UnsupportedConstruct) for anything outside the oracles' model.""" | ||
| 1002 | dis = os.path.join(tmpdir, "disasm") | ||
| 1003 | os.makedirs(dis, exist_ok=True) | ||
| 1004 | path = os.path.join(dis, name + ".s") | ||
| 1005 | write_listing(path, lines, name) | ||
| 1006 | with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: | ||
| 1007 | f.write(STUB_DXBC) | ||
| 1008 | with warnings.catch_warnings(): | ||
| 1009 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 1010 | spvasm = rdna2spirv.translate(path) | ||
| 1011 | gc.collect() | ||
| 1012 | out = run_fragment(spvasm) | ||
| 1013 | if list(out) != ["%out_mrt0"]: | ||
| 1014 | raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") | ||
| 1015 | return [w & M32 for w in out["%out_mrt0"]] | ||
| 1016 | |||
| 1017 | |||
| 1018 | def check(lines, name="ps_f16m_case"): | ||
| 1019 | """None when both oracles agree, else the first difference.""" | ||
| 1020 | with tempfile.TemporaryDirectory(prefix="f16m-diff-") as tmp: | ||
| 1021 | want, states = reference(lines) | ||
| 1022 | got = translate_listing(lines, name, tmp) | ||
| 1023 | return compare(want, states, got) | ||
| 1024 | |||
| 1025 | |||
| 1026 | def run_one(lines, name, tmpdir, events=None): | ||
| 1027 | """(status, detail) with status in {"match", "mismatch", "skip", "unjudged"}.""" | ||
| 1028 | try: | ||
| 1029 | want, states = reference(lines, events) | ||
| 1030 | except NotJudged as e: | ||
| 1031 | return ("unjudged", str(e)) | ||
| 1032 | try: | ||
| 1033 | got = translate_listing(lines, name, tmpdir) | ||
| 1034 | except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: | ||
| 1035 | return ("skip", f"{type(e).__name__}: {e}") | ||
| 1036 | except (IndexError, KeyError, ValueError) as e: | ||
| 1037 | return ("skip", f"translator error {type(e).__name__}: {e}") | ||
| 1038 | diff = compare(want, states, got) | ||
| 1039 | if diff: | ||
| 1040 | return ("mismatch", diff) | ||
| 1041 | return ("match", "") | ||
| 1042 | |||
| 1043 | |||
| 1044 | # ---- the suites ---- | ||
| 1045 | |||
| 1046 | def _new_counts(): | ||
| 1047 | return {"pass": 0, "mismatch": 0, "skip": Counter(), "unjudged": Counter(), "ops": Counter(), "events": {}} | ||
| 1048 | |||
| 1049 | |||
| 1050 | def _tally(counts, status, detail): | ||
| 1051 | if status == "match": | ||
| 1052 | counts["pass"] += 1 | ||
| 1053 | elif status in ("skip", "unjudged"): | ||
| 1054 | counts[status][detail] += 1 | ||
| 1055 | else: | ||
| 1056 | counts["mismatch"] += 1 | ||
| 1057 | |||
| 1058 | |||
| 1059 | def _run(counts, items, tag): | ||
| 1060 | failure = None | ||
| 1061 | with tempfile.TemporaryDirectory(prefix=f"f16m-diff-{tag}-") as tmp: | ||
| 1062 | for i, (label, lines, used) in enumerate(items): | ||
| 1063 | counts["ops"].update(used) | ||
| 1064 | status, detail = run_one(lines, f"ps_f16m_{tag}{i:05d}", tmp, counts["events"]) | ||
| 1065 | _tally(counts, status, detail) | ||
| 1066 | if status == "mismatch" and failure is None: | ||
| 1067 | failure = (label, lines, detail) | ||
| 1068 | return failure | ||
| 1069 | |||
| 1070 | |||
| 1071 | def run_sweep(seed, ops=None): | ||
| 1072 | counts = _new_counts() | ||
| 1073 | items = [] | ||
| 1074 | for case in sweep_cases(ops): | ||
| 1075 | op, form, kinds = case | ||
| 1076 | for rep in range(SWEEP_REPEAT): | ||
| 1077 | tag = f"{op}:{form}:{'/'.join(kinds)}:{rep}" | ||
| 1078 | rng = random.Random(f"{seed}:{tag}") | ||
| 1079 | items.append((f"sweep {tag} (seed {seed})", sweep_program(case, rng), [op])) | ||
| 1080 | return counts, _run(counts, items, "sw") | ||
| 1081 | |||
| 1082 | |||
| 1083 | def run_grid(ops=None): | ||
| 1084 | counts = _new_counts() | ||
| 1085 | cases = grid_cases(ops) | ||
| 1086 | rng = random.Random("f16misc_diff:grid-programs") | ||
| 1087 | items = [] | ||
| 1088 | for i in range(0, len(cases), GRID_PER_PROGRAM): | ||
| 1089 | chunk = cases[i:i + GRID_PER_PROGRAM] | ||
| 1090 | items.append((f"edge grid program {i // GRID_PER_PROGRAM}", grid_program(chunk, rng), [c[0] for c in chunk])) | ||
| 1091 | return counts, _run(counts, items, "gr") | ||
| 1092 | |||
| 1093 | |||
| 1094 | def run_exhaustive(ops=None): | ||
| 1095 | counts = _new_counts() | ||
| 1096 | items = [(f"exhaustive f16 program {i} ({op})", lines, [op] * GRID_PER_PROGRAM) | ||
| 1097 | for i, (op, lines) in enumerate(exhaustive_programs(ops))] | ||
| 1098 | return counts, _run(counts, items, "ex") | ||
| 1099 | |||
| 1100 | |||
| 1101 | def run_suite(programs, seed, max_ops=6, ops=None): | ||
| 1102 | counts = _new_counts() | ||
| 1103 | rng = random.Random(f"suite:{seed}") | ||
| 1104 | items = [] | ||
| 1105 | for i in range(programs): | ||
| 1106 | lines, used = program(rng, rng.randint(1, max_ops), ops) | ||
| 1107 | items.append((f"program {i} (seed {seed})", lines, used)) | ||
| 1108 | return counts, _run(counts, items, "rn") | ||
| 1109 | |||
| 1110 | |||
| 1111 | REJECTED = ( | ||
| 1112 | ("clamp on v_frexp_exp_i16_f16", "v_frexp_exp_i16_f16_e64 v8, v9 clamp"), | ||
| 1113 | ("mul:2 on v_frexp_mant_f16", "v_frexp_mant_f16_e64 v8, v9 mul:2"), | ||
| 1114 | ("div:2 on v_ldexp_f16", "v_ldexp_f16_e64 v8, v9, v10 div:2"), | ||
| 1115 | ("neg on v_pk_fmac_f16", "v_pk_fmac_f16 v8, -v9, v10"), | ||
| 1116 | ("clamp on v_pk_fmac_f16", "v_pk_fmac_f16 v8, v9, v10 clamp"), | ||
| 1117 | ) | ||
| 1118 | |||
| 1119 | |||
| 1120 | def self_test(): | ||
| 1121 | ok = True | ||
| 1122 | |||
| 1123 | def report(good, what): | ||
| 1124 | nonlocal ok | ||
| 1125 | ok &= good | ||
| 1126 | print(("ok " if good else "FAIL ") + what) | ||
| 1127 | |||
| 1128 | # reference spot checks, from docs/design.md and tests/semantic | ||
| 1129 | mc = Machine() | ||
| 1130 | mc.write_word(9, 0x00010001) | ||
| 1131 | step("v_frexp_mant_f16_e32 v8, v9", mc) | ||
| 1132 | report(mc.v[8] & M16 == 0x3800, "frexp_mant(0x0001) = 0.5 (0x3800)") | ||
| 1133 | step("v_frexp_exp_i16_f16_e32 v8, v9", mc) | ||
| 1134 | report(mc.v[8] & M16 == (-23) & M16, "frexp_exp(0x0001) = -23") | ||
| 1135 | mc.write_word(9, 0x000003FF) | ||
| 1136 | step("v_frexp_mant_f16_e32 v8, v9", mc) | ||
| 1137 | report(mc.v[8] & M16 == 0x3BFE, "frexp_mant(0x03ff) = 0x3bfe") | ||
| 1138 | for h, n, want in ((0x3C00, -15, 0x0200), (0x3E00, -24, 0x0002), (0x3C00, -25, 0x0000), (0x7BFF, -30, 0x0400)): | ||
| 1139 | mc.write_word(9, h | ((n & M16) << 16)) | ||
| 1140 | step("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", mc) | ||
| 1141 | report(mc.v[8] & M16 == want, f"ldexp(0x{h:04x}, {n}) = 0x{want:04x}") | ||
| 1142 | for words, want in (((0x3C00, 0x0000, 0x3C00), 0x0000), ((0x0000, 0x8000, 0x0000), 0x8000), | ||
| 1143 | ((0xBC00, 0x7C01, 0x0000), 0xBC00), ((0x0001, 0x4000, 0x8000), 0x8000)): | ||
| 1144 | mc.write_word(9, words[0]) | ||
| 1145 | mc.write_word(10, words[1]) | ||
| 1146 | mc.write_word(11, words[2]) | ||
| 1147 | mc.write_word(8, 0xDEADBEEF) | ||
| 1148 | step("v_min3_f16 v8, v9, v10, v11", mc) | ||
| 1149 | report(mc.v[8] == 0xDEAD0000 | want, f"min3{tuple(hex(w) for w in words)} = 0xdead{want:04x}") | ||
| 1150 | # the translator rejects the forms the generator leaves out | ||
| 1151 | for what, line in REJECTED: | ||
| 1152 | try: | ||
| 1153 | with tempfile.TemporaryDirectory(prefix="f16m-diff-st-") as tmp: | ||
| 1154 | translate_listing(seeds(random.Random(1)) + [line], "ps_f16m_rej", tmp) | ||
| 1155 | report(False, f"{what}: the translator accepted it") | ||
| 1156 | except (rdna2spirv.Unsupported, UnsupportedConstruct): | ||
| 1157 | report(True, f"{what}: the translator rejected it") | ||
| 1158 | a = program(random.Random("st"), 5)[0] | ||
| 1159 | b = program(random.Random("st"), 5)[0] | ||
| 1160 | report(a == b, "generation is deterministic for a seed") | ||
| 1161 | counts, failure = run_suite(8, 1) | ||
| 1162 | report(failure is None and not counts["skip"], | ||
| 1163 | f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") | ||
| 1164 | return ok | ||
| 1165 | |||
| 1166 | |||
| 1167 | def main(): | ||
| 1168 | ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | ||
| 1169 | ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") | ||
| 1170 | ap.add_argument("--seed", type=int, default=1) | ||
| 1171 | ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") | ||
| 1172 | ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all eleven)") | ||
| 1173 | ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid") | ||
| 1174 | ap.add_argument("--exhaustive-f16", action="store_true", help="also run every f16 input through frexp/ldexp") | ||
| 1175 | ap.add_argument("--list-ops", action="store_true") | ||
| 1176 | ap.add_argument("--self-test", action="store_true") | ||
| 1177 | args = ap.parse_args() | ||
| 1178 | if args.list_ops: | ||
| 1179 | for op in FAMILY: | ||
| 1180 | print(f"{op:22s} {OP_FORMS[op]}") | ||
| 1181 | return 0 | ||
| 1182 | if args.self_test: | ||
| 1183 | return 0 if self_test() else 1 | ||
| 1184 | ops = None | ||
| 1185 | if args.ops: | ||
| 1186 | ops = [o.strip() for o in args.ops.split(",") if o.strip()] | ||
| 1187 | bad = [o for o in ops if o not in FAMILY] | ||
| 1188 | if bad: | ||
| 1189 | print(f"unknown op(s): {', '.join(bad)} (see --list-ops)", file=sys.stderr) | ||
| 1190 | return 2 | ||
| 1191 | stages = [] | ||
| 1192 | if not args.no_sweep: | ||
| 1193 | stages += [("sweep", lambda: run_sweep(args.seed, ops)), ("edge grid", lambda: run_grid(ops))] | ||
| 1194 | if args.exhaustive_f16: | ||
| 1195 | stages.append(("exhaustive f16", lambda: run_exhaustive(ops))) | ||
| 1196 | if args.programs > 0: | ||
| 1197 | stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) | ||
| 1198 | total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "ops": Counter(), "events": {}} | ||
| 1199 | first = None | ||
| 1200 | try: | ||
| 1201 | for name, fn in stages: | ||
| 1202 | counts, failure = fn() | ||
| 1203 | n = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) + sum(counts["unjudged"].values()) | ||
| 1204 | print(f"{name}: {counts['pass']}/{n} programs match, {counts['mismatch']} mismatch; " | ||
| 1205 | f"skips: {dict(counts['skip'])}; not judged: {sum(counts['unjudged'].values())}") | ||
| 1206 | total["pass"] += counts["pass"] | ||
| 1207 | total["mismatch"] += counts["mismatch"] | ||
| 1208 | total["skip"] += sum(counts["skip"].values()) | ||
| 1209 | total["unjudged"].update(counts["unjudged"]) | ||
| 1210 | total["ops"].update(counts["ops"]) | ||
| 1211 | for op, ev in counts["events"].items(): | ||
| 1212 | total["events"].setdefault(op, Counter()).update(ev) | ||
| 1213 | if failure and first is None: | ||
| 1214 | first = failure | ||
| 1215 | except HarnessError as e: | ||
| 1216 | print(f"harness error: {e}", file=sys.stderr) | ||
| 1217 | return 2 | ||
| 1218 | print("op lines per op: " + ", ".join(f"{op} {n}" for op, n in sorted(total["ops"].items()))) | ||
| 1219 | print("inputs/results per op (NaN / inf / denormal / tie / overflow): " + ", ".join( | ||
| 1220 | f"{op} {ev['NaN']}/{ev['inf']}/{ev['denormal'] + ev['denormal result']}/{ev['tie']}/{ev['overflow']}" | ||
| 1221 | for op, ev in sorted(total["events"].items()))) | ||
| 1222 | if total["unjudged"]: | ||
| 1223 | print("not judged: " + ", ".join(f"{why} {n}" for why, n in total["unjudged"].most_common())) | ||
| 1224 | judged = total["pass"] + total["mismatch"] + total["skip"] | ||
| 1225 | print(f"f16 misc family: {total['pass']}/{judged} judged programs match, {total['mismatch']} mismatch " | ||
| 1226 | f"({len(total['ops'])} of {len(FAMILY)} ops)") | ||
| 1227 | if first: | ||
| 1228 | _report(first) | ||
| 1229 | return 1 | ||
| 1230 | if total["skip"]: | ||
| 1231 | print(f"SKIPPED {total['skip']} program(s): every generated form should translate (reasons above)") | ||
| 1232 | return 1 | ||
| 1233 | return 0 | ||
| 1234 | |||
| 1235 | |||
| 1236 | def _report(failure): | ||
| 1237 | label, lines, detail = failure | ||
| 1238 | print(f"\nFIRST MISMATCH: {label}: {detail}") | ||
| 1239 | for line in lines: | ||
| 1240 | print(" " + line) | ||
| 1241 | |||
| 1242 | |||
| 1243 | if __name__ == "__main__": | ||
| 1244 | sys.exit(main()) | ||