diff options
Diffstat (limited to 'tools/sdwa_diff.py')
| -rw-r--r-- | tools/sdwa_diff.py | 779 |
1 files changed, 779 insertions, 0 deletions
diff --git a/tools/sdwa_diff.py b/tools/sdwa_diff.py new file mode 100644 index 000000000..15348aa86 --- /dev/null +++ b/tools/sdwa_diff.py | |||
| @@ -0,0 +1,779 @@ | |||
| 1 | r"""Differential fuzzing of SDWA (sub-dword addressing) VALU forms. Standard library only. | ||
| 2 | |||
| 3 | Generates seeded straight-line programs of `_sdwa` VOP1/VOP2/VOPC instructions, one lane, runs them through | ||
| 4 | |||
| 5 | * the reference below, written from the RDNA2 ISA guide's SDWA description and each opcode's pseudocode, and | ||
| 6 | * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py, | ||
| 7 | |||
| 8 | and compares four exported words bit for bit: three VGPRs and VCC (through v_cndmask_b32_e64). The reference does | ||
| 9 | not share code with the translator or with tools/cpu_ref.py. | ||
| 10 | |||
| 11 | What is modelled, per instruction: | ||
| 12 | * sources: VGPRs v1..v7, SGPRs s4..s7 (seeded with s_mov_b32, so the translator knows them as constants), integer | ||
| 13 | inline constants -16..64 and float inline constants (0.5, 1.0, 2.0, 4.0 and their negatives). A float constant | ||
| 14 | in an f16 op (v_cmp_class_f16's mask included) is the f16 value over a zero high half, in any other op | ||
| 15 | (v_cvt_f16_{u16,i16} included) its f32 bits. A source is narrowed to src0_sel/src1_sel (BYTE_0..3, WORD_0/1, | ||
| 16 | DWORD), constants too, zero-extended, or sign-extended under sext() (integer ops); then neg/abs (f16 ops, on | ||
| 17 | the sign bit of the f16 word) and the op. | ||
| 18 | * dst_sel and dst_unused: the result's low bits go to the selected field; UNUSED_PAD zeroes the other bits, | ||
| 19 | UNUSED_SEXT fills the bits above the field with its top bit (bits below stay zero), UNUSED_PRESERVE keeps them. | ||
| 20 | A 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD zeroes the high half, | ||
| 21 | whatever dst_unused says: unlike the non-SDWA forms (docs/design.md "16-bit results"), which keep it. | ||
| 22 | * clamp: unsigned saturation on v_add/sub/subrev_nc_u32, [0, 1] on f16 results (clamp(-0) = +0) and on | ||
| 23 | v_cvt_f32_f16. | ||
| 24 | * f16 arithmetic rounds to nearest even with denormals kept (the MODE the translator assumes); min/max order -0 | ||
| 25 | below +0; v_fract_f16(-0) = +0 and the result stops at 0x3bff. | ||
| 26 | * VOPC writes VCC (one bit, this lane); v_cndmask_b32 reads it. | ||
| 27 | Every one of these rules was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with | ||
| 28 | --oracle hw, the f16 constant, dst_sel:DWORD and v_fract_f16(-0) rules included. | ||
| 29 | |||
| 30 | The int family is the 32-bit integer VOP2 ops, v_cndmask_b32, the integer VOP1 ops and v_cvt_f32_{u32,i32,ubyteN}, | ||
| 31 | and the 32- and 16-bit integer compares. The f16 family is v_add/sub/subrev/mul/min/max_f16, the f16 rounding ops | ||
| 32 | and v_fract_f16, the f16 <-> 16-bit integer and f16 -> f32 conversions, the f16 compares and v_cmp_class_f16. | ||
| 33 | --list-ops prints them. Not generated: omod, v_cmpx, an SGPR destination for VOPC, DPP, literals (SDWA has none), | ||
| 34 | transcendentals, f32 arithmetic. | ||
| 35 | |||
| 36 | Skips (counted with their reasons): an f16 NaN operand of an op whose NaN result or IEEE-mode NaN rule is not | ||
| 37 | modelled (the compares and v_cmp_class_f16 take NaNs), v_fract_f16 of an infinity, and anything the translator or | ||
| 38 | the interpreter does not take: on main that is v_cmp_class_f16 (no f16 class compare in any encoding) and clamp | ||
| 39 | on v_cvt_f16_{u16,i16}. | ||
| 40 | |||
| 41 | Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to | ||
| 42 | differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always | ||
| 43 | has them): | ||
| 44 | * a constant shift amount (inline constant or seeded SGPR) for v_lshlrev_b32 / v_lshrrev_b32 / v_ashrrev_i32 with | ||
| 45 | src0_sel other than DWORD or sext(): the translator's constant fold shifted by the whole constant (#2005); | ||
| 46 | * a 16-bit result with dst_sel:DWORD: the translator keeps the destination's high half (finding in #1902); | ||
| 47 | * a float inline constant with a src_sel other than DWORD in an f16 op: the translator reads the whole constant | ||
| 48 | (finding in #1902). | ||
| 49 | |||
| 50 | With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/) and the hardware's four words | ||
| 51 | are compared with the reference: that validates the reference itself. SDWA exists on GFX9 and GFX10 only, so the | ||
| 52 | hardware oracle needs an RDNA1/RDNA2 GPU; anything else exits 77, like a missing tool. The kernel runs on one lane | ||
| 53 | of a wave32 compute dispatch, so IEEE mode is on there (it only changes NaN rules, which are skipped). | ||
| 54 | |||
| 55 | Usage: | ||
| 56 | python -I tools/sdwa_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_add_f16,v_cmp_lt_u16] | ||
| 57 | python -I tools/sdwa_diff.py --family f16 # int, f16 or all (default) | ||
| 58 | python -I tools/sdwa_diff.py --known # also the forms in KNOWN_DIVERGENCES | ||
| 59 | python -I tools/sdwa_diff.py --oracle hw # hardware vs reference only | ||
| 60 | python -I tools/sdwa_diff.py --oracle translator,hw | ||
| 61 | python -I tools/sdwa_diff.py --list-ops | ||
| 62 | python -I tools/sdwa_diff.py --self-test | ||
| 63 | |||
| 64 | Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing | ||
| 65 | instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable. | ||
| 66 | """ | ||
| 67 | import argparse | ||
| 68 | import gc | ||
| 69 | import math | ||
| 70 | import os | ||
| 71 | import random | ||
| 72 | import re | ||
| 73 | import struct | ||
| 74 | import sys | ||
| 75 | import tempfile | ||
| 76 | import warnings | ||
| 77 | |||
| 78 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 79 | sys.dont_write_bytecode = True | ||
| 80 | if HERE not in sys.path: | ||
| 81 | sys.path.insert(0, HERE) | ||
| 82 | SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") | ||
| 83 | if SEM_DIR not in sys.path: | ||
| 84 | sys.path.insert(0, SEM_DIR) | ||
| 85 | |||
| 86 | M32 = 0xFFFFFFFF | ||
| 87 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 88 | |||
| 89 | VREGS = tuple(range(1, 8)) # data VGPRs v1..v7 (v0 is the hardware kernel's store offset) | ||
| 90 | SREGS = (4, 5, 6, 7) # data SGPRs s4..s7 | ||
| 91 | N_SEED = len(VREGS) + len(SREGS) + 1 # the seed lines: VGPRs, SGPRs, VCC | ||
| 92 | N_OBS = 4 # the observation lines: v8..v10 copies, v11 = VCC | ||
| 93 | |||
| 94 | SEL = {"BYTE_0": (0, 8), "BYTE_1": (8, 8), "BYTE_2": (16, 8), "BYTE_3": (24, 8), | ||
| 95 | "WORD_0": (0, 16), "WORD_1": (16, 16), "DWORD": (0, 32)} | ||
| 96 | UNUSED = ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE") | ||
| 97 | FLOAT_CONSTS = {"0.5": 0x3F000000, "-0.5": 0xBF000000, "1.0": 0x3F800000, "-1.0": 0xBF800000, | ||
| 98 | "2.0": 0x40000000, "-2.0": 0xC0000000, "4.0": 0x40800000, "-4.0": 0xC0800000} | ||
| 99 | FLOAT_CONSTS_F16 = {"0.5": 0x3800, "-0.5": 0xB800, "1.0": 0x3C00, "-1.0": 0xBC00, | ||
| 100 | "2.0": 0x4000, "-2.0": 0xC000, "4.0": 0x4400, "-4.0": 0xC400} | ||
| 101 | |||
| 102 | INTERESTING = (0, 1, 2, 0x7F, 0x80, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, M32, | ||
| 103 | 0x00FF00FF, 0x80808080, 0x8000FFFF, 0x12345678, 0xDEADBEEF, 31, 32, 33) | ||
| 104 | F16_INTERESTING = (0x0000, 0x8000, 0x3C00, 0xBC00, 0x3800, 0x3E00, 0xC100, 0x4200, 0x4400, 0x5640, 0xB400, | ||
| 105 | 0x7BFF, 0xFBFF, 0x7C00, 0xFC00, 0x0001, 0x83FF, 0x0400, 0x3BFF, 0x3C01, 0xC500, 0x4900) | ||
| 106 | |||
| 107 | |||
| 108 | class Skip(Exception): | ||
| 109 | pass | ||
| 110 | |||
| 111 | |||
| 112 | class RefError(Exception): | ||
| 113 | pass | ||
| 114 | |||
| 115 | |||
| 116 | def s32(x): | ||
| 117 | x &= M32 | ||
| 118 | return x - (1 << 32) if x >> 31 else x | ||
| 119 | |||
| 120 | |||
| 121 | def sx(x, w): | ||
| 122 | x &= (1 << w) - 1 | ||
| 123 | return x - (1 << w) if x >> (w - 1) else x | ||
| 124 | |||
| 125 | |||
| 126 | # ---- f16 helpers (bit patterns in, bit patterns out) ------------------------------------------------------ | ||
| 127 | |||
| 128 | def h2f(h): | ||
| 129 | return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0] | ||
| 130 | |||
| 131 | |||
| 132 | def f2h(x): | ||
| 133 | """Round a Python float (exact here: every f16 sum or product fits a double) to f16, nearest even.""" | ||
| 134 | if math.isnan(x): | ||
| 135 | raise Skip("reference: f16 NaN result (payload not modelled)") | ||
| 136 | try: | ||
| 137 | return struct.unpack("<H", struct.pack("<e", x))[0] | ||
| 138 | except OverflowError: | ||
| 139 | return 0x7C00 if x > 0 else 0xFC00 | ||
| 140 | |||
| 141 | |||
| 142 | def f2u(x): | ||
| 143 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 144 | |||
| 145 | |||
| 146 | def is_nan16(h): | ||
| 147 | return (h & 0x7C00) == 0x7C00 and (h & 0x3FF) != 0 | ||
| 148 | |||
| 149 | |||
| 150 | def _no_nan(*hs): | ||
| 151 | if any(is_nan16(h) for h in hs): | ||
| 152 | raise Skip("reference: f16 NaN operand (IEEE-mode NaN rules not modelled)") | ||
| 153 | |||
| 154 | |||
| 155 | def f16_bin(fn): | ||
| 156 | def op(a, b): | ||
| 157 | a, b = a & 0xFFFF, b & 0xFFFF | ||
| 158 | _no_nan(a, b) | ||
| 159 | return f2h(fn(h2f(a), h2f(b))) | ||
| 160 | return op | ||
| 161 | |||
| 162 | |||
| 163 | def f16_minmax(want_max): | ||
| 164 | def op(a, b): | ||
| 165 | a, b = a & 0xFFFF, b & 0xFFFF | ||
| 166 | _no_nan(a, b) | ||
| 167 | # -0 orders below +0; otherwise the numeric order | ||
| 168 | ka, kb = (h2f(a), a >> 15 == 0), (h2f(b), b >> 15 == 0) | ||
| 169 | if want_max: | ||
| 170 | return a if ka > kb else b | ||
| 171 | return a if ka < kb else b | ||
| 172 | return op | ||
| 173 | |||
| 174 | |||
| 175 | def f16_round(fn): | ||
| 176 | def op(a, b=0): | ||
| 177 | a &= 0xFFFF | ||
| 178 | _no_nan(a) | ||
| 179 | x = h2f(a) | ||
| 180 | if math.isinf(x): | ||
| 181 | return a | ||
| 182 | return f2h(math.copysign(float(fn(x)), x)) | ||
| 183 | return op | ||
| 184 | |||
| 185 | |||
| 186 | def f16_fract(a, b=0): | ||
| 187 | a &= 0xFFFF | ||
| 188 | _no_nan(a) | ||
| 189 | x = h2f(a) | ||
| 190 | if math.isinf(x): | ||
| 191 | raise Skip("reference: v_fract_f16 of an infinity (NaN result)") | ||
| 192 | # x + -floor(x): fract(-0) = -0 + +0 = +0 (gfx1036); the result stops at the largest f16 below 1.0 | ||
| 193 | fl = math.copysign(float(math.floor(x)), x) if math.floor(x) == 0 else float(math.floor(x)) # floor(-0) = -0 | ||
| 194 | return min(f2h(x + -fl), 0x3BFF) | ||
| 195 | |||
| 196 | |||
| 197 | def cvt_u16_f16(a, b=0): | ||
| 198 | a &= 0xFFFF | ||
| 199 | _no_nan(a) | ||
| 200 | x = h2f(a) | ||
| 201 | return 0 if x <= 0 else 0xFFFF if x >= 65535 else int(x) | ||
| 202 | |||
| 203 | |||
| 204 | def cvt_i16_f16(a, b=0): | ||
| 205 | a &= 0xFFFF | ||
| 206 | _no_nan(a) | ||
| 207 | x = h2f(a) | ||
| 208 | if x >= 32767: | ||
| 209 | return 0x7FFF | ||
| 210 | if x <= -32768: | ||
| 211 | return 0x8000 | ||
| 212 | return int(x) & 0xFFFF | ||
| 213 | |||
| 214 | |||
| 215 | def cmp_class_f16(a, b): | ||
| 216 | a &= 0xFFFF | ||
| 217 | e, m, neg = (a >> 10) & 0x1F, a & 0x3FF, a >> 15 | ||
| 218 | if e == 0x1F: | ||
| 219 | bit = (0 if not m >> 9 else 1) if m else (2 if neg else 9) | ||
| 220 | elif e == 0: | ||
| 221 | bit = (4 if neg else 7) if m else (5 if neg else 6) | ||
| 222 | else: | ||
| 223 | bit = 3 if neg else 8 | ||
| 224 | return (b >> bit) & 1 | ||
| 225 | |||
| 226 | |||
| 227 | def ffbh_i32(a): | ||
| 228 | a &= M32 | ||
| 229 | if a in (0, M32): | ||
| 230 | return M32 | ||
| 231 | x = a ^ M32 if a >> 31 else a | ||
| 232 | return 32 - x.bit_length() | ||
| 233 | |||
| 234 | |||
| 235 | # ---- the reference: one entry per opcode ------------------------------------------------------------- | ||
| 236 | # (family, form, width, fn). family "int" / "f16" decides the modifiers (sext vs neg/abs) and how a float inline | ||
| 237 | # constant reads. form: "vop2" d, a, b; "vop1" d, a; "vopc" vcc, a, b; "cndmask" d, a, b, vcc. | ||
| 238 | # width: bits of the result (16 or 32); a 16-bit result has a zero high half under dst_sel:DWORD. | ||
| 239 | # fn(a, b) gets the selected 32-bit sources and returns the result (a bit for "vopc"). | ||
| 240 | |||
| 241 | def _ops(): | ||
| 242 | ops = {} | ||
| 243 | |||
| 244 | def add(name, family, form, fn, width=32, clamp=None): | ||
| 245 | ops[name] = (family, form, width, fn, clamp) | ||
| 246 | |||
| 247 | usat = "usat" | ||
| 248 | add("v_add_nc_u32", "int", "vop2", lambda a, b: a + b, clamp=usat) | ||
| 249 | add("v_sub_nc_u32", "int", "vop2", lambda a, b: a - b, clamp=usat) | ||
| 250 | add("v_subrev_nc_u32", "int", "vop2", lambda a, b: b - a, clamp=usat) | ||
| 251 | add("v_and_b32", "int", "vop2", lambda a, b: a & b) | ||
| 252 | add("v_or_b32", "int", "vop2", lambda a, b: a | b) | ||
| 253 | add("v_xor_b32", "int", "vop2", lambda a, b: a ^ b) | ||
| 254 | add("v_xnor_b32", "int", "vop2", lambda a, b: ~(a ^ b)) | ||
| 255 | add("v_lshlrev_b32", "int", "vop2", lambda a, b: b << (a & 31)) | ||
| 256 | add("v_lshrrev_b32", "int", "vop2", lambda a, b: (b & M32) >> (a & 31)) | ||
| 257 | add("v_ashrrev_i32", "int", "vop2", lambda a, b: s32(b) >> (a & 31)) | ||
| 258 | add("v_mul_u32_u24", "int", "vop2", lambda a, b: (a & 0xFFFFFF) * (b & 0xFFFFFF)) | ||
| 259 | add("v_mul_hi_u32_u24", "int", "vop2", lambda a, b: ((a & 0xFFFFFF) * (b & 0xFFFFFF)) >> 32) | ||
| 260 | add("v_mul_i32_i24", "int", "vop2", lambda a, b: sx(a, 24) * sx(b, 24)) | ||
| 261 | add("v_mul_hi_i32_i24", "int", "vop2", lambda a, b: (sx(a, 24) * sx(b, 24)) >> 32) | ||
| 262 | add("v_min_u32", "int", "vop2", lambda a, b: min(a & M32, b & M32)) | ||
| 263 | add("v_max_u32", "int", "vop2", lambda a, b: max(a & M32, b & M32)) | ||
| 264 | add("v_min_i32", "int", "vop2", lambda a, b: min(s32(a), s32(b))) | ||
| 265 | add("v_max_i32", "int", "vop2", lambda a, b: max(s32(a), s32(b))) | ||
| 266 | add("v_cndmask_b32", "int", "cndmask", None) | ||
| 267 | add("v_mov_b32", "int", "vop1", lambda a, b: a) | ||
| 268 | add("v_not_b32", "int", "vop1", lambda a, b: ~a) | ||
| 269 | add("v_bfrev_b32", "int", "vop1", lambda a, b: int(f"{a & M32:032b}"[::-1], 2)) | ||
| 270 | add("v_ffbh_u32", "int", "vop1", lambda a, b: M32 if not a & M32 else 32 - (a & M32).bit_length()) | ||
| 271 | add("v_ffbl_b32", "int", "vop1", lambda a, b: M32 if not a & M32 else ((a & -a) & M32).bit_length() - 1) | ||
| 272 | add("v_ffbh_i32", "int", "vop1", lambda a, b: ffbh_i32(a)) | ||
| 273 | add("v_cvt_f32_u32", "int", "vop1", lambda a, b: f2u(float(a & M32))) | ||
| 274 | add("v_cvt_f32_i32", "int", "vop1", lambda a, b: f2u(float(s32(a)))) | ||
| 275 | for n in range(4): | ||
| 276 | add(f"v_cvt_f32_ubyte{n}", "int", "vop1", lambda a, b, n=n: f2u(float((a >> (8 * n)) & 0xFF))) | ||
| 277 | cmps = {"f": lambda a, b: False, "lt": lambda a, b: a < b, "eq": lambda a, b: a == b, | ||
| 278 | "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, "ne": lambda a, b: a != b, | ||
| 279 | "ge": lambda a, b: a >= b, "t": lambda a, b: True} | ||
| 280 | for c, f in cmps.items(): | ||
| 281 | add(f"v_cmp_{c}_u32", "int", "vopc", lambda a, b, f=f: f(a & M32, b & M32)) | ||
| 282 | add(f"v_cmp_{c}_i32", "int", "vopc", lambda a, b, f=f: f(s32(a), s32(b))) | ||
| 283 | if c not in ("f", "t"): # GFX10 has no v_cmp_f/t_{i16,u16} | ||
| 284 | add(f"v_cmp_{c}_u16", "int", "vopc", lambda a, b, f=f: f(a & 0xFFFF, b & 0xFFFF)) | ||
| 285 | add(f"v_cmp_{c}_i16", "int", "vopc", lambda a, b, f=f: f(sx(a, 16), sx(b, 16))) | ||
| 286 | |||
| 287 | fclamp = "f16" | ||
| 288 | add("v_add_f16", "f16", "vop2", f16_bin(lambda x, y: x + y), 16, fclamp) | ||
| 289 | add("v_sub_f16", "f16", "vop2", f16_bin(lambda x, y: x - y), 16, fclamp) | ||
| 290 | add("v_subrev_f16", "f16", "vop2", f16_bin(lambda x, y: y - x), 16, fclamp) | ||
| 291 | add("v_mul_f16", "f16", "vop2", f16_bin(lambda x, y: x * y), 16, fclamp) | ||
| 292 | add("v_max_f16", "f16", "vop2", f16_minmax(True), 16, fclamp) | ||
| 293 | add("v_min_f16", "f16", "vop2", f16_minmax(False), 16, fclamp) | ||
| 294 | add("v_floor_f16", "f16", "vop1", f16_round(math.floor), 16, fclamp) | ||
| 295 | add("v_ceil_f16", "f16", "vop1", f16_round(math.ceil), 16, fclamp) | ||
| 296 | add("v_trunc_f16", "f16", "vop1", f16_round(math.trunc), 16, fclamp) | ||
| 297 | add("v_rndne_f16", "f16", "vop1", f16_round(round), 16, fclamp) | ||
| 298 | add("v_fract_f16", "f16", "vop1", f16_fract, 16, fclamp) | ||
| 299 | add("v_cvt_f32_f16", "f16", "vop1", lambda a, b: f2u(h2f(a)) if not is_nan16(a) else _no_nan(a), 32, "f32") | ||
| 300 | add("v_cvt_u16_f16", "f16", "vop1", cvt_u16_f16, 16) | ||
| 301 | add("v_cvt_i16_f16", "f16", "vop1", cvt_i16_f16, 16) | ||
| 302 | add("v_cvt_f16_u16", "int16", "vop1", lambda a, b: f2h(float(a & 0xFFFF)), 16, fclamp) | ||
| 303 | add("v_cvt_f16_i16", "int16", "vop1", lambda a, b: f2h(float(sx(a, 16))), 16, fclamp) | ||
| 304 | |||
| 305 | def fcmp(pred): | ||
| 306 | def op(a, b): | ||
| 307 | a, b = a & 0xFFFF, b & 0xFFFF | ||
| 308 | x, y = h2f(a), h2f(b) | ||
| 309 | unordered = math.isnan(x) or math.isnan(y) | ||
| 310 | return pred(x, y, unordered) | ||
| 311 | return op | ||
| 312 | fcmps = {"f": lambda x, y, u: False, "lt": lambda x, y, u: x < y, "eq": lambda x, y, u: x == y, | ||
| 313 | "le": lambda x, y, u: x <= y, "gt": lambda x, y, u: x > y, "lg": lambda x, y, u: not u and x != y, | ||
| 314 | "ge": lambda x, y, u: x >= y, "o": lambda x, y, u: not u, "u": lambda x, y, u: u, | ||
| 315 | "nge": lambda x, y, u: not x >= y, "nlg": lambda x, y, u: u or x == y, "ngt": lambda x, y, u: not x > y, | ||
| 316 | "nle": lambda x, y, u: not x <= y, "neq": lambda x, y, u: not x == y, "nlt": lambda x, y, u: not x < y, | ||
| 317 | "tru": lambda x, y, u: True} | ||
| 318 | for c, p in fcmps.items(): | ||
| 319 | add(f"v_cmp_{c}_f16", "f16", "vopc", fcmp(p)) | ||
| 320 | add("v_cmp_class_f16", "f16", "vopc", lambda a, b: cmp_class_f16(a, b & 0x3FF)) | ||
| 321 | return ops | ||
| 322 | |||
| 323 | |||
| 324 | OPS = _ops() | ||
| 325 | CLAMP_OPS = tuple(sorted(o for o, v in OPS.items() if v[4])) | ||
| 326 | |||
| 327 | |||
| 328 | # ---- program text: parsing ---------------------------------------------------------------------------- | ||
| 329 | |||
| 330 | _SRC = re.compile(r"^(?P<neg>-)?(?P<abs>\|)?(?:sext\((?P<sx>[^)]+)\)|(?P<tok>[^|]+))\|?$") | ||
| 331 | |||
| 332 | |||
| 333 | def parse_src(tok): | ||
| 334 | """{'tok': register or constant text, 'neg', 'abs', 'sext'}.""" | ||
| 335 | tok = tok.strip() | ||
| 336 | if tok in FLOAT_CONSTS or re.fullmatch(r"-?\d+", tok): | ||
| 337 | return {"tok": tok, "neg": False, "abs": False, "sext": False} # -16 is a constant, not neg(16) | ||
| 338 | m = _SRC.match(tok) | ||
| 339 | if not m: | ||
| 340 | raise RefError(f"source {tok!r}") | ||
| 341 | t = m.group("sx") or m.group("tok") | ||
| 342 | return {"tok": t.strip(), "neg": bool(m.group("neg")), "abs": bool(m.group("abs")), "sext": bool(m.group("sx"))} | ||
| 343 | |||
| 344 | |||
| 345 | def parse(line): | ||
| 346 | """(op without _sdwa, [operand texts], {modifier: value}, clamp) for one SDWA line.""" | ||
| 347 | op, _, rest = line.partition(" ") | ||
| 348 | if not op.endswith("_sdwa"): | ||
| 349 | raise RefError(f"not an SDWA line: {line!r}") | ||
| 350 | mods = dict(m.split(":", 1) for m in re.findall(r"\b(?:src0_sel|src1_sel|dst_sel|dst_unused):\w+", rest)) | ||
| 351 | clamp = bool(re.search(r"\bclamp\b", rest)) | ||
| 352 | body = re.split(r"\s+(?:clamp|src0_sel|src1_sel|dst_sel|dst_unused)\b", rest, maxsplit=1)[0] | ||
| 353 | return op[:-len("_sdwa")], [a.strip() for a in body.split(",")], mods, clamp | ||
| 354 | |||
| 355 | |||
| 356 | # ---- the reference interpreter ------------------------------------------------------------------------ | ||
| 357 | |||
| 358 | class State: | ||
| 359 | def __init__(self): | ||
| 360 | self.v, self.s, self.vcc = {}, {}, 0 | ||
| 361 | |||
| 362 | |||
| 363 | def read_raw(st, tok, f16): | ||
| 364 | if tok.startswith("v") and tok[1:].isdigit(): | ||
| 365 | return st.v.get(int(tok[1:]), 0) | ||
| 366 | if tok.startswith("s") and tok[1:].isdigit(): | ||
| 367 | return st.s.get(int(tok[1:]), 0) | ||
| 368 | if tok in FLOAT_CONSTS: | ||
| 369 | return FLOAT_CONSTS_F16[tok] if f16 else FLOAT_CONSTS[tok] | ||
| 370 | return int(tok, 0) & M32 | ||
| 371 | |||
| 372 | |||
| 373 | def select(value, sel, sext): | ||
| 374 | off, w = SEL[sel] | ||
| 375 | v = (value >> off) & ((1 << w) - 1) | ||
| 376 | if sext and w < 32: | ||
| 377 | v = sx(v, w) & M32 | ||
| 378 | return v | ||
| 379 | |||
| 380 | |||
| 381 | def place(old, res, width, sel, unused): | ||
| 382 | off, w = SEL[sel] | ||
| 383 | res &= M32 | ||
| 384 | if w == 32: | ||
| 385 | return res & 0xFFFF if width == 16 else res | ||
| 386 | field = res & ((1 << w) - 1) | ||
| 387 | if unused == "UNUSED_PRESERVE": | ||
| 388 | mask = ((1 << w) - 1) << off | ||
| 389 | return (old & ~mask & M32) | (field << off) | ||
| 390 | if unused == "UNUSED_SEXT": | ||
| 391 | return (sx(field, w) << off) & M32 | ||
| 392 | return field << off | ||
| 393 | |||
| 394 | |||
| 395 | def _clamp(kind, r): | ||
| 396 | if kind == "usat": | ||
| 397 | return max(0, min(M32, r)) | ||
| 398 | if kind == "f16": | ||
| 399 | if r & 0x8000: # negative, -0 included | ||
| 400 | return 0 | ||
| 401 | return min(r, 0x3C00) # +inf and anything above 1.0 (NaN results are skipped) | ||
| 402 | if kind == "f32": | ||
| 403 | if r & 0x80000000: | ||
| 404 | return 0 | ||
| 405 | return min(r, 0x3F800000) | ||
| 406 | return r | ||
| 407 | |||
| 408 | |||
| 409 | def step(st, line): | ||
| 410 | op, args, mods, clamp = parse(line) | ||
| 411 | if op not in OPS: | ||
| 412 | raise RefError(f"{op} is not modelled") | ||
| 413 | family, form, width, fn, clamp_kind = OPS[op] | ||
| 414 | if clamp and not clamp_kind: | ||
| 415 | raise RefError(f"{op}: clamp not modelled") | ||
| 416 | f16 = family == "f16" | ||
| 417 | srcs = args[1:3] if form in ("vop2", "vopc", "cndmask") else args[1:2] | ||
| 418 | vals = [] | ||
| 419 | for i, text in enumerate(srcs): | ||
| 420 | s = parse_src(text) | ||
| 421 | v = select(read_raw(st, s["tok"], f16), | ||
| 422 | mods.get(f"src{i}_sel", "DWORD"), s["sext"]) | ||
| 423 | if s["abs"]: | ||
| 424 | v &= ~0x8000 if f16 else ~0x80000000 | ||
| 425 | if s["neg"]: | ||
| 426 | v ^= 0x8000 if f16 else 0x80000000 | ||
| 427 | vals.append(v & M32) | ||
| 428 | if form == "vopc": | ||
| 429 | st.vcc = int(bool(fn(vals[0], vals[1]))) | ||
| 430 | return | ||
| 431 | if form == "cndmask": | ||
| 432 | r = vals[1] if st.vcc else vals[0] | ||
| 433 | else: | ||
| 434 | r = fn(vals[0], vals[1] if len(vals) > 1 else 0) | ||
| 435 | r = _clamp(clamp_kind, r) if clamp else r | ||
| 436 | d = int(args[0][1:]) | ||
| 437 | st.v[d] = place(st.v.get(d, 0), r, width, mods.get("dst_sel", "DWORD"), mods.get("dst_unused", "UNUSED_PAD")) | ||
| 438 | |||
| 439 | |||
| 440 | def reference(lines): | ||
| 441 | """Run the program; returns the four exported words. Raises Skip for what the reference does not model.""" | ||
| 442 | st = State() | ||
| 443 | for line in lines: | ||
| 444 | op, _, rest = line.partition(" ") | ||
| 445 | args = [a.strip() for a in rest.split(",")] | ||
| 446 | if op == "v_mov_b32": | ||
| 447 | st.v[int(args[0][1:])] = read_raw(st, args[1], False) | ||
| 448 | elif op == "s_mov_b32": | ||
| 449 | if args[0] == "vcc_lo": | ||
| 450 | st.vcc = int(args[1], 0) & 1 | ||
| 451 | else: | ||
| 452 | st.s[int(args[0][1:])] = int(args[1], 0) & M32 | ||
| 453 | elif op == "v_cndmask_b32_e64": | ||
| 454 | st.v[int(args[0][1:])] = int(args[2], 0) if st.vcc else int(args[1], 0) | ||
| 455 | else: | ||
| 456 | step(st, line) | ||
| 457 | return [st.v.get(r, 0) for r in (8, 9, 10, 11)] | ||
| 458 | |||
| 459 | |||
| 460 | # ---- program generation ------------------------------------------------------------------------------- | ||
| 461 | |||
| 462 | def _word(rng): | ||
| 463 | r = rng.random() | ||
| 464 | if r < 0.35: | ||
| 465 | return rng.choice(INTERESTING) | ||
| 466 | if r < 0.7: | ||
| 467 | return _half(rng) | _half(rng) << 16 | ||
| 468 | return rng.getrandbits(32) | ||
| 469 | |||
| 470 | |||
| 471 | def _half(rng): | ||
| 472 | r = rng.random() | ||
| 473 | if r < 0.5: | ||
| 474 | return rng.choice(F16_INTERESTING) | ||
| 475 | if r < 0.65: | ||
| 476 | return rng.randrange(0, 0x400) | rng.choice((0, 0x8000)) # denormal | ||
| 477 | h = rng.getrandbits(16) | ||
| 478 | while is_nan16(h): | ||
| 479 | h = rng.getrandbits(16) | ||
| 480 | return h | ||
| 481 | |||
| 482 | |||
| 483 | def _src(rng, family, allow_const=True): | ||
| 484 | """An operand text for a source of an op of this family.""" | ||
| 485 | r = rng.random() | ||
| 486 | if r < 0.68 or not allow_const: | ||
| 487 | tok = f"v{rng.choice(VREGS)}" if r < 0.55 or not allow_const else f"s{rng.choice(SREGS)}" | ||
| 488 | elif r < 0.9: | ||
| 489 | tok = str(rng.choice((-16, -1, 0, 1, 2, 7, 15, 16, 24, 31, 32, 63, 64, rng.randrange(-16, 65)))) | ||
| 490 | else: | ||
| 491 | return rng.choice(tuple(FLOAT_CONSTS)) | ||
| 492 | if family == "cndmask": | ||
| 493 | return tok # llvm-mc takes no sext() on v_cndmask_b32_sdwa | ||
| 494 | if family in ("int", "int16"): | ||
| 495 | return f"sext({tok})" if rng.random() < 0.3 else tok | ||
| 496 | if not tok[0] in "vs": | ||
| 497 | return tok | ||
| 498 | if rng.random() < 0.2: | ||
| 499 | tok = f"|{tok}|" | ||
| 500 | if rng.random() < 0.25: | ||
| 501 | tok = "-" + tok | ||
| 502 | return tok | ||
| 503 | |||
| 504 | |||
| 505 | KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run) | ||
| 506 | SHIFTS = ("v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32") | ||
| 507 | KNOWN_DIVERGENCES = { | ||
| 508 | "shift-const-sel": "a constant shift amount (inline or seeded SGPR) with src0_sel or sext(): until #2005 the " | ||
| 509 | "translator shifts by the whole constant", | ||
| 510 | "dword-16bit": "a 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD: the " | ||
| 511 | "hardware zeroes the high half, the translator keeps it", | ||
| 512 | "f16-const-sel": "a float inline constant with a src_sel other than DWORD in an f16 op: the hardware selects from " | ||
| 513 | "the f16 value (0x3c00 for 1.0), the translator reads the whole constant", | ||
| 514 | } | ||
| 515 | |||
| 516 | |||
| 517 | def emit(rng, name): | ||
| 518 | family, form, width, fn, clamp_kind = OPS[name] | ||
| 519 | sels = tuple(SEL) | ||
| 520 | s0, s1 = rng.choice(sels), rng.choice(sels) | ||
| 521 | if form == "vopc": | ||
| 522 | src1_family = "int" if name == "v_cmp_class_f16" else family | ||
| 523 | a, b = _src(rng, family), _src(rng, src1_family) | ||
| 524 | else: | ||
| 525 | d = f"v{rng.choice(VREGS)}" | ||
| 526 | clamp = " clamp" if clamp_kind and rng.random() < 0.25 else "" | ||
| 527 | dsel = rng.choice(sels) | ||
| 528 | unused = rng.choice(UNUSED) | ||
| 529 | a = _src(rng, "cndmask" if form == "cndmask" else family) | ||
| 530 | b = _src(rng, "cndmask" if form == "cndmask" else family) if form != "vop1" else None | ||
| 531 | if form == "cndmask" and a[0] == b[0] == "s" and a != b: | ||
| 532 | b = f"v{rng.choice(VREGS)}" # VCC is on the constant bus too: at most one other SGPR (gfx1030) | ||
| 533 | if not KNOWN: | ||
| 534 | inner = a[5:-1] if a.startswith("sext(") else a | ||
| 535 | if name in SHIFTS and inner[0] != "v": | ||
| 536 | s0, a = "DWORD", inner | ||
| 537 | if family == "f16": | ||
| 538 | s0 = "DWORD" if a in FLOAT_CONSTS else s0 | ||
| 539 | s1 = "DWORD" if b in FLOAT_CONSTS and name != "v_cmp_class_f16" else s1 | ||
| 540 | if form != "vopc" and width == 16 and dsel == "DWORD": | ||
| 541 | dsel = rng.choice(sels[:-1]) | ||
| 542 | if form == "vopc": | ||
| 543 | return f"{name}_sdwa vcc_lo, {a}, {b} src0_sel:{s0} src1_sel:{s1}" | ||
| 544 | tail = f"{clamp} dst_sel:{dsel} dst_unused:{unused} src0_sel:{s0}" | ||
| 545 | if form == "vop1": | ||
| 546 | return f"{name}_sdwa {d}, {a}{tail}" | ||
| 547 | vcc = ", vcc_lo" if form == "cndmask" else "" | ||
| 548 | return f"{name}_sdwa {d}, {a}, {b}{vcc}{tail} src1_sel:{s1}" | ||
| 549 | |||
| 550 | |||
| 551 | def seeds(rng): | ||
| 552 | return ([f"v_mov_b32 v{r}, 0x{_word(rng):x}" for r in VREGS] + [f"s_mov_b32 s{r}, 0x{_word(rng):x}" for r in SREGS] | ||
| 553 | + [f"s_mov_b32 vcc_lo, {rng.randrange(2)}"]) | ||
| 554 | |||
| 555 | |||
| 556 | def observe(regs): | ||
| 557 | return [f"v_mov_b32 v8, v{regs[0]}", f"v_mov_b32 v9, v{regs[1]}", f"v_mov_b32 v10, v{regs[2]}", | ||
| 558 | "v_cndmask_b32_e64 v11, 0, 1, vcc_lo"] | ||
| 559 | |||
| 560 | |||
| 561 | def generate(rng, n_ops, ops): | ||
| 562 | body = [emit(rng, rng.choice(ops)) for _ in range(n_ops)] | ||
| 563 | written = [] | ||
| 564 | for line in reversed(body): | ||
| 565 | d = line.split()[1].rstrip(",") | ||
| 566 | if d[0] == "v" and d[1:].isdigit() and d not in written: | ||
| 567 | written.append(d) | ||
| 568 | regs = [int(d[1:]) for d in written[:3]] | ||
| 569 | regs += rng.sample([r for r in VREGS if r not in regs], 3 - len(regs)) | ||
| 570 | return seeds(rng) + body + observe(regs) | ||
| 571 | |||
| 572 | |||
| 573 | # ---- the translator side ------------------------------------------------------------------------------ | ||
| 574 | |||
| 575 | def translated(lines, name="ps_sdwa"): | ||
| 576 | """Translate and execute; returns the four exported words, or raises Skip.""" | ||
| 577 | import rdna2spirv | ||
| 578 | from spirv_mini_interp import run_fragment | ||
| 579 | with tempfile.TemporaryDirectory(prefix="sdwa-diff-") as tmp: | ||
| 580 | dis = os.path.join(tmp, "disasm") | ||
| 581 | os.mkdir(dis) | ||
| 582 | path = os.path.join(dis, name + ".s") | ||
| 583 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 584 | f.write(f"; {name} sdwa_diff case\n") | ||
| 585 | for line in lines: | ||
| 586 | f.write("\t" + line + "\n") | ||
| 587 | f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") | ||
| 588 | with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: | ||
| 589 | f.write(STUB_DXBC) | ||
| 590 | try: | ||
| 591 | with warnings.catch_warnings(): | ||
| 592 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 593 | spvasm = rdna2spirv.translate(path) | ||
| 594 | gc.collect() | ||
| 595 | except rdna2spirv.Unsupported as e: | ||
| 596 | raise Skip(f"translator unsupported: {e}") from None | ||
| 597 | try: | ||
| 598 | out = run_fragment(spvasm) | ||
| 599 | except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass | ||
| 600 | raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None | ||
| 601 | return [w & M32 for w in out["%out_mrt0"]] | ||
| 602 | |||
| 603 | |||
| 604 | def _diff(lines, want, got, label): | ||
| 605 | bad = [k for k in range(4) if want[k] != got[k]] | ||
| 606 | if not bad: | ||
| 607 | return None | ||
| 608 | i = bad[0] | ||
| 609 | what = "VCC" if i == 3 else lines[-N_OBS + i].split(", ")[1] | ||
| 610 | return f"word {i} ({what}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" | ||
| 611 | |||
| 612 | |||
| 613 | def check(lines, backends=("translator",), hw=None): | ||
| 614 | """None on a match, else a description. Raises Skip (the reference or every backend skipped) / RefError. | ||
| 615 | hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" | ||
| 616 | want = reference(lines) | ||
| 617 | problems, skips = [], [] | ||
| 618 | if "translator" in backends: | ||
| 619 | try: | ||
| 620 | problems.append(_diff(lines, want, translated(lines), "translated")) | ||
| 621 | except Skip as e: | ||
| 622 | skips.append(e) | ||
| 623 | if "hw" in backends: | ||
| 624 | got = hw(lines) if callable(hw) else hw | ||
| 625 | if isinstance(got, str): | ||
| 626 | skips.append(Skip(f"hardware: {got}")) | ||
| 627 | else: | ||
| 628 | problems.append(_diff(lines, want, got, "hardware")) | ||
| 629 | if skips and len(skips) == len(backends): | ||
| 630 | raise skips[0] | ||
| 631 | return "; ".join(p for p in problems if p) or None | ||
| 632 | |||
| 633 | |||
| 634 | def shrink(lines, check_fn=check): | ||
| 635 | """Drop instructions (not the seeds or the observation) while the program still mismatches.""" | ||
| 636 | body = lines[N_SEED:-N_OBS] | ||
| 637 | changed = True | ||
| 638 | while changed: | ||
| 639 | changed = False | ||
| 640 | for i in range(len(body)): | ||
| 641 | trial = lines[:N_SEED] + body[:i] + body[i + 1:] + lines[-N_OBS:] | ||
| 642 | try: | ||
| 643 | if check_fn(trial): | ||
| 644 | body = body[:i] + body[i + 1:] | ||
| 645 | changed = True | ||
| 646 | break | ||
| 647 | except (Skip, RefError): | ||
| 648 | continue | ||
| 649 | return lines[:N_SEED] + body + lines[-N_OBS:] | ||
| 650 | |||
| 651 | |||
| 652 | def hw_prepare(oracle, programs): | ||
| 653 | """Run every program on the hardware in batches. Returns per program the four words, or a str reason.""" | ||
| 654 | return oracle.run(programs) | ||
| 655 | |||
| 656 | |||
| 657 | def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None): | ||
| 658 | counts = {"pass": 0, "mismatch": 0, "skip": {}} | ||
| 659 | failures = [] | ||
| 660 | rng = random.Random(seed) | ||
| 661 | progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] | ||
| 662 | hw_words = hw_prepare(oracle, progs) if "hw" in backends else [None] * programs | ||
| 663 | for i, lines in enumerate(progs): | ||
| 664 | try: | ||
| 665 | problem = check(lines, backends, hw_words[i]) | ||
| 666 | except Skip as e: | ||
| 667 | counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 | ||
| 668 | continue | ||
| 669 | if problem is None: | ||
| 670 | counts["pass"] += 1 | ||
| 671 | continue | ||
| 672 | counts["mismatch"] += 1 | ||
| 673 | failures.append((i, problem, lines)) | ||
| 674 | return counts, failures | ||
| 675 | |||
| 676 | |||
| 677 | def self_test(): | ||
| 678 | base = [f"v_mov_b32 v{r}, 0x{0x11111111 * r:x}" for r in VREGS] + [f"s_mov_b32 s{r}, {r}" for r in SREGS] | ||
| 679 | base.append("s_mov_b32 vcc_lo, 0") | ||
| 680 | ok = check(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE " | ||
| 681 | "src0_sel:BYTE_1 src1_sel:WORD_0"] + observe([1, 2, 3])) is None | ||
| 682 | # 0x2222 + 0x33 = 0x2255 into the high word of v1 (0x11111111): 0x22551111 | ||
| 683 | placed = reference(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE " | ||
| 684 | "src0_sel:WORD_0 src1_sel:BYTE_0"] + observe([1, 2, 3]))[0] == 0x22551111 | ||
| 685 | try: | ||
| 686 | translated(base + ["v_add_nc_u32_dpp v1, v2, v3 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf" | ||
| 687 | .replace("_dpp", "_sdwa_dpp")] + observe([1, 2, 3])) | ||
| 688 | skipped = False | ||
| 689 | except Skip: | ||
| 690 | skipped = True | ||
| 691 | print(f"self-test: match {ok}, placement modelled {placed}, unsupported form skipped {skipped}") | ||
| 692 | return ok and placed and skipped | ||
| 693 | |||
| 694 | |||
| 695 | def main(argv=None): | ||
| 696 | ap = argparse.ArgumentParser(description="SDWA VOP1/VOP2/VOPC differential fuzzing.") | ||
| 697 | ap.add_argument("--programs", type=int, default=300) | ||
| 698 | ap.add_argument("--seed", type=int, default=1) | ||
| 699 | ap.add_argument("--max-ops", type=int, default=4) | ||
| 700 | ap.add_argument("--ops", default=None, help="comma-separated opcodes without _sdwa (default: the --family ones)") | ||
| 701 | ap.add_argument("--family", default="all", choices=("int", "f16", "all")) | ||
| 702 | ap.add_argument("--list-ops", action="store_true") | ||
| 703 | ap.add_argument("--self-test", action="store_true") | ||
| 704 | ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") | ||
| 705 | ap.add_argument("--oracle", default="translator", | ||
| 706 | help="comma-separated comparison targets: translator (default), hw (natively on an RDNA1/RDNA2 " | ||
| 707 | "GPU; see tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") | ||
| 708 | ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") | ||
| 709 | ap.add_argument("--known", action="store_true", | ||
| 710 | help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; " | ||
| 711 | "always on with --oracle hw alone)") | ||
| 712 | a = ap.parse_args(argv) | ||
| 713 | if a.programs < 1 or a.max_ops < 1: | ||
| 714 | ap.error("--programs and --max-ops must be at least 1") | ||
| 715 | backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) | ||
| 716 | if not backends or any(t not in ("translator", "hw") for t in backends): | ||
| 717 | ap.error("--oracle takes translator, hw or translator,hw") | ||
| 718 | global KNOWN | ||
| 719 | KNOWN = a.known or backends == ("hw",) | ||
| 720 | if a.list_ops: | ||
| 721 | for name in sorted(OPS): | ||
| 722 | family, form, width, _, clamp = OPS[name] | ||
| 723 | print(f"{name:20} {'f16' if family == 'f16' else 'int'} {form}{' clamp' if clamp else ''}") | ||
| 724 | return 0 | ||
| 725 | if a.self_test: | ||
| 726 | return 0 if self_test() else 1 | ||
| 727 | if a.ops is not None: | ||
| 728 | tokens = [t.strip() for t in a.ops.split(",")] | ||
| 729 | if not any(tokens) or any(not t for t in tokens): | ||
| 730 | ap.error("--ops must be a comma-separated list of opcodes") | ||
| 731 | ops = sorted(set(tokens)) | ||
| 732 | else: | ||
| 733 | ops = sorted(o for o, v in OPS.items() | ||
| 734 | if a.family == "all" or (a.family == "f16") == (v[0] == "f16")) | ||
| 735 | unknown = [o for o in ops if o not in OPS] | ||
| 736 | if unknown: | ||
| 737 | ap.error("unknown ops: " + ", ".join(unknown)) | ||
| 738 | oracle = None | ||
| 739 | if "hw" in backends: | ||
| 740 | from hw_oracle import asm, runner | ||
| 741 | try: | ||
| 742 | oracle = runner.open_oracle(arch=a.hw_arch) | ||
| 743 | except runner.Unavailable as e: | ||
| 744 | print(f"hardware oracle unavailable: {e}") | ||
| 745 | return 77 | ||
| 746 | if asm.family(oracle.arch) != "gfx10": | ||
| 747 | print(f"hardware oracle unavailable: {oracle.arch} has no SDWA (GFX9 and GFX10 only)") | ||
| 748 | oracle.close() | ||
| 749 | return 77 | ||
| 750 | print(f"hardware oracle: {oracle.device}") | ||
| 751 | try: | ||
| 752 | counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle) | ||
| 753 | skips = sum(counts["skip"].values()) | ||
| 754 | print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}): {counts['pass']} pass, " | ||
| 755 | f"{counts['mismatch']} mismatch, {skips} skipped") | ||
| 756 | for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): | ||
| 757 | print(f" skip x{n}: {reason}") | ||
| 758 | |||
| 759 | def check_fn(lines): | ||
| 760 | return check(lines, backends, (lambda l: oracle.run([l])[0]) if oracle else None) | ||
| 761 | for i, problem, lines in failures[: None if a.all_failures else 1]: | ||
| 762 | small = shrink(lines, check_fn) | ||
| 763 | print(f"MISMATCH program {i}: {check_fn(small) or problem}") | ||
| 764 | print("\n".join("\t" + line for line in small)) | ||
| 765 | except (RefError, RuntimeError) as e: | ||
| 766 | print(f"harness error: {e}") | ||
| 767 | return 2 | ||
| 768 | finally: | ||
| 769 | if oracle: | ||
| 770 | oracle.close() | ||
| 771 | return 1 if failures else 0 | ||
| 772 | |||
| 773 | |||
| 774 | if __name__ == "__main__": | ||
| 775 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 776 | sys.stdout.reconfigure(errors="replace") | ||
| 777 | except (AttributeError, ValueError, OSError): | ||
| 778 | pass | ||
| 779 | sys.exit(main()) | ||