upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/pk16_diff.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/pk16_diff.py')
-rw-r--r--tools/pk16_diff.py572
1 files changed, 572 insertions, 0 deletions
diff --git a/tools/pk16_diff.py b/tools/pk16_diff.py
new file mode 100644
index 000000000..0dc48929d
--- /dev/null
+++ b/tools/pk16_diff.py
@@ -0,0 +1,572 @@
1r"""Differential fuzzing of packed and 16-bit integer VALU (v_pk_* integer ops, 16-bit VOP3 integer ops). Standard
2library only.
3
4Generates seeded straight-line programs of 16-bit integer vector instructions, one lane, runs them through
5
6 * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode, and
7 * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py (lane 0 of a wave32),
8
9and compares four exported words bit for bit (v8..v11). The reference does not share code with the translator, with
10tools/cpu_ref.py or with the other fuzzers. tools/valu_fuzz.py --family f16 runs some of the same opcodes on the GPU
11with VGPR sources; this one adds the packed add/sub/mul/min/max/mad, the signed add/sub, min3/max3/med3 and mad,
12clamp, and SGPR, inline-constant and literal sources in every position the encoding allows.
13
14What is modelled, per instruction:
15 * v_pk_* (VOP3P, OPS_PK): each result half is the op on the halves its sources select: op_sel bit i picks the
16 half of source i for the low result, op_sel_hi bit i for the high result (default op_sel:[0,..],
17 op_sel_hi:[1,..]). clamp saturates the exact result of add/sub/mad to [0, 0xffff] or [-32768, 32767];
18 without it the result wraps to 16 bits. Shift amounts are their low 4 bits.
19 * 16-bit VOP3 ops (OPS_16): op_sel bits 0..n-1 pick source halves, bit n (the last) the destination half. The
20 result is written to that half and the other half of vD is kept. clamp as above (v_add_nc_*16, v_sub_nc_*16,
21 v_mad_*16). On GFX10 these are VOP3 only: the VOP2 forms of v_mul_lo_u16, v_min/max_u16/i16 and the 16-bit
22 shifts do not exist (the assembler refuses v_mul_lo_u16_e32). LLVM prints their VOP3 form without a suffix
23 and the translator tells it from a VOP2 write (which zeroes the high half) by the listing's encoding bytes.
24 A program here has no encodings, so these are written with _e64.
25 * sources: VGPRs v0..v7 and v12..v19, SGPRs s4..s19, integer inline constants -16..64, float inline constants
26 (0.5, 1.0, 2.0, 4.0, their negatives, 1/(2*pi)) and literals, at most one literal and two scalar values per
27 instruction (the GFX10 constant bus). A constant is its 32-bit value split into halves like a register: -16 is
28 0xfff0 / 0xffff, 1.0 is 0x0000 / 0x3f80 (its f32 bits, not the f16 constant of the f16 ops), a literal of a
29 16-bit VOP3 op has 16 bits (the assembler rejects a wider one), so its high half is 0.
30Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with --oracle hw.
31
32Not generated: neg_lo/neg_hi on the integer packed ops (the translator rejects them, their meaning on integers is
33unmeasured), clamp on min/max/mul_lo/shifts, DPP and SDWA forms (tools/sdwa_diff.py), v_mad_u32_u16 and the other
3416x16->32 ops (tools/vint_diff.py), v_dot* (#2229), f16 ops (tools/valu_fuzz.py --family f16).
35
36Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to
37differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always
38has them):
39 * pk-const-hi: a constant (inline or literal) in a packed add/sub/mul_lo/min/max/mad source whose high half
40 op_sel or op_sel_hi reads. The translator raises Unsupported (counted as a skip); #2224 removes that.
41
42With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/), one lane of a wave32 compute
43dispatch, and the four words are compared with the reference: that validates the reference itself. Without the
44oracle tools the run exits 77.
45
46Usage:
47 python -I tools/pk16_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_pk_mad_u16,v_med3_i16]
48 python -I tools/pk16_diff.py --no-literals # sources without literals
49 python -I tools/pk16_diff.py --known # also the forms in KNOWN_DIVERGENCES
50 python -I tools/pk16_diff.py --oracle hw # hardware vs reference only
51 python -I tools/pk16_diff.py --oracle translator,hw
52 python -I tools/pk16_diff.py --list-ops
53 python -I tools/pk16_diff.py --self-test
54
55Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing
56instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable.
57Skips are counted with their reasons.
58"""
59import argparse
60import gc
61import os
62import random
63import re
64import struct
65import sys
66import tempfile
67import warnings
68
69HERE = os.path.dirname(os.path.abspath(__file__))
70sys.dont_write_bytecode = True
71if HERE not in sys.path:
72 sys.path.insert(0, HERE)
73SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic")
74if SEM_DIR not in sys.path:
75 sys.path.insert(0, SEM_DIR)
76
77M16 = 0xFFFF
78M32 = 0xFFFFFFFF
79STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
80
81VREGS = tuple(range(0, 8)) + tuple(range(12, 20)) # data VGPRs; v8..v11 are the observation
82SREGS = tuple(range(4, 20)) # data SGPRs
83N_SEED = len(VREGS) + len(SREGS)
84N_OBS = 4
85INLINE_F = {"0.5": 0x3F000000, "-0.5": 0xBF000000, "1.0": 0x3F800000, "-1.0": 0xBF800000, "2.0": 0x40000000,
86 "-2.0": 0xC0000000, "4.0": 0x40800000, "-4.0": 0xC0800000, "0.15915494": 0x3E22F983}
87HALVES = (0, 1, 2, 15, 16, 17, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0xFFFE, 0x00FF, 0x0100, 0x5555, 0xAAAA, 0x1234,
88 0xFF00, 0x4000, 0xC000, 0x00F0)
89
90
91class Skip(Exception):
92 pass
93
94
95class RefError(Exception):
96 pass
97
98
99def sx16(x):
100 x &= M16
101 return x - 0x10000 if x & 0x8000 else x
102
103
104def satu(v):
105 return max(0, min(M16, v))
106
107
108def sati(v):
109 return max(-32768, min(32767, v))
110
111
112def med3(a, b, c):
113 return sorted((a, b, c))[1]
114
115
116# name -> (nsrc, fn on 16-bit source halves -> exact integer, clamp fn or None). The result keeps its low 16 bits.
117OPS_PK = {
118 "v_pk_add_u16": (2, lambda a, b: a + b, satu),
119 "v_pk_add_i16": (2, lambda a, b: sx16(a) + sx16(b), sati),
120 "v_pk_sub_u16": (2, lambda a, b: a - b, satu),
121 "v_pk_sub_i16": (2, lambda a, b: sx16(a) - sx16(b), sati),
122 "v_pk_mul_lo_u16": (2, lambda a, b: a * b, None),
123 "v_pk_min_u16": (2, min, None),
124 "v_pk_max_u16": (2, max, None),
125 "v_pk_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None),
126 "v_pk_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None),
127 "v_pk_lshlrev_b16": (2, lambda a, b: b << (a & 15), None),
128 "v_pk_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None),
129 "v_pk_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None),
130 "v_pk_mad_u16": (3, lambda a, b, c: a * b + c, satu),
131 "v_pk_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati),
132}
133PK_SHIFTS = ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16")
134OPS_16 = {
135 "v_add_nc_u16": (2, lambda a, b: a + b, satu),
136 "v_sub_nc_u16": (2, lambda a, b: a - b, satu),
137 "v_add_nc_i16": (2, lambda a, b: sx16(a) + sx16(b), sati),
138 "v_sub_nc_i16": (2, lambda a, b: sx16(a) - sx16(b), sati),
139 "v_mul_lo_u16": (2, lambda a, b: a * b, None),
140 "v_min_u16": (2, min, None),
141 "v_max_u16": (2, max, None),
142 "v_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None),
143 "v_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None),
144 "v_lshlrev_b16": (2, lambda a, b: b << (a & 15), None),
145 "v_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None),
146 "v_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None),
147 "v_min3_u16": (3, min, None),
148 "v_max3_u16": (3, max, None),
149 "v_med3_u16": (3, med3, None),
150 "v_min3_i16": (3, lambda a, b, c: min(sx16(a), sx16(b), sx16(c)), None),
151 "v_max3_i16": (3, lambda a, b, c: max(sx16(a), sx16(b), sx16(c)), None),
152 "v_med3_i16": (3, lambda a, b, c: med3(sx16(a), sx16(b), sx16(c)), None),
153 "v_mad_u16": (3, lambda a, b, c: a * b + c, satu),
154 "v_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati),
155}
156# GFX10 has only the VOP3 encoding of these (VOP2 names on earlier chips). LLVM prints them without a suffix and the
157# translator then tells VOP3 from VOP2 by the listing's encoding bytes; a program here has none, so it says _e64.
158E64 = ("v_mul_lo_u16", "v_min_u16", "v_max_u16", "v_min_i16", "v_max_i16", "v_lshlrev_b16", "v_lshrrev_b16",
159 "v_ashrrev_i16")
160ALL_OPS = sorted(OPS_PK) + sorted(OPS_16)
161
162KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run)
163LITERALS = True
164KNOWN_DIVERGENCES = {
165 "pk-const-hi": "a constant in a packed add/sub/mul_lo/min/max/mad source whose high half op_sel or op_sel_hi "
166 "reads: the translator raises Unsupported, #2224 reads the constant's 32-bit value",
167}
168
169
170# ---- program generation -------------------------------------------------------------------------------------
171
172def rand_value(rng):
173 r = rng.random()
174 if r < 0.5:
175 return rng.choice(HALVES) | (rng.choice(HALVES) << 16)
176 if r < 0.6:
177 return rng.randrange(0, 64)
178 return rng.getrandbits(32)
179
180
181def is_const(tok):
182 return not re.fullmatch(r"[vs]\d+", tok)
183
184
185class Gen:
186 def __init__(self, rng):
187 self.r = rng
188
189 def vreg(self):
190 return f"v{self.r.choice(VREGS)}"
191
192 def const(self, lit_ok, lit16):
193 r = self.r
194 k = r.random()
195 if k < 0.25:
196 return r.choice(tuple(INLINE_F))
197 if k < 0.6 or not lit_ok:
198 return str(r.randint(-16, 64))
199 v = rand_value(r) & (M16 if lit16 else M32)
200 if v <= 64:
201 v = 0x1234 if lit16 else 0x12345678
202 return f"0x{v:x}"
203
204 def srcs(self, n, lit16, const_ok):
205 """n sources: at most one literal and two scalar values (the literal counted among them). const_ok[i]: a
206 constant may go in source i."""
207 r = self.r
208 out, bus, lit = [], set(), False
209 for i in range(n):
210 k = r.random()
211 if k < 0.5:
212 out.append(self.vreg())
213 elif k < 0.75 or not const_ok[i]:
214 s = f"s{r.choice(SREGS)}"
215 if s not in bus and len(bus) >= 2:
216 out.append(self.vreg())
217 continue
218 bus.add(s)
219 out.append(s)
220 else:
221 c = self.const(LITERALS and not lit and len(bus) < 2, lit16)
222 if c.startswith("0x"):
223 lit = True
224 bus.add("lit")
225 out.append(c)
226 return out
227
228 def op(self, ops):
229 r = self.r
230 name = r.choice(ops)
231 d = r.choice(VREGS)
232 if name in OPS_PK:
233 n, _, cl = OPS_PK[name]
234 sel = [int(r.random() < 0.3) for _ in range(n)]
235 hi = [int(r.random() < 0.7) for _ in range(n)]
236 free = KNOWN or name in PK_SHIFTS
237 srcs = self.srcs(n, False, [free or not (sel[i] or hi[i]) for i in range(n)])
238 line = f"{name} v{d}, {', '.join(srcs)}"
239 if any(sel):
240 line += f" op_sel:[{','.join(map(str, sel))}]"
241 if not all(hi):
242 line += f" op_sel_hi:[{','.join(map(str, hi))}]"
243 if cl and r.random() < 0.3:
244 line += " clamp"
245 return [line]
246 n, _, cl = OPS_16[name]
247 line = f"{name}{'_e64' if name in E64 else ''} v{d}, {', '.join(self.srcs(n, True, [True] * n))}"
248 sel = [int(r.random() < 0.3) for _ in range(n + 1)]
249 if any(sel):
250 line += f" op_sel:[{','.join(map(str, sel))}]"
251 if cl and r.random() < 0.3:
252 line += " clamp"
253 return [line]
254
255
256def seeds(rng):
257 return ([f"v_mov_b32_e32 v{v}, 0x{rand_value(rng):x}" for v in VREGS]
258 + [f"s_mov_b32 s{s}, 0x{rand_value(rng):x}" for s in SREGS])
259
260
261def observe(regs):
262 return [f"v_mov_b32_e32 v{8 + i}, v{r}" for i, r in enumerate(regs)]
263
264
265def generate(rng, n_ops, ops):
266 gen = Gen(rng)
267 body = []
268 for _ in range(n_ops):
269 body += gen.op(ops)
270 written = []
271 for line in reversed(body):
272 dst = int(line.split()[1].rstrip(",")[1:])
273 if dst not in written:
274 written.append(dst)
275 regs = written[:4]
276 regs += [rng.choice(VREGS) for _ in range(4 - len(regs))]
277 return seeds(rng) + body + observe(regs)
278
279
280# ---- the reference interpreter --------------------------------------------------------------------------------
281
282_MOD = re.compile(r"\s+(op_sel|op_sel_hi):\[([01,]+)\]|\s+(clamp)\b")
283
284
285def parse(rest):
286 """Operands and modifiers of one instruction."""
287 mods = {}
288 for m in _MOD.finditer(rest):
289 if m.group(3):
290 mods["clamp"] = True
291 else:
292 mods[m.group(1)] = [int(x) for x in m.group(2).split(",")]
293 rest = _MOD.sub("", rest)
294 return [a.strip() for a in rest.split(",")], mods
295
296
297def value(tok, st):
298 if re.fullmatch(r"v\d+", tok):
299 return st["v"].get(int(tok[1:]), 0)
300 if re.fullmatch(r"s\d+", tok):
301 if tok not in st["s"]:
302 raise RefError(f"{tok} read before it is written")
303 return st["s"][tok]
304 if tok in INLINE_F:
305 return INLINE_F[tok]
306 return int(tok, 0) & M32
307
308
309def half(v, hi):
310 return (v >> 16) & M16 if hi else v & M16
311
312
313def reference(lines):
314 """Run the program; returns the four exported words."""
315 st = {"v": {}, "s": {}}
316 for line in lines:
317 op, _, rest = line.partition(" ")
318 args, mods = parse(rest)
319 if op == "s_mov_b32":
320 st["s"][args[0]] = value(args[1], st)
321 continue
322 d = int(args[0][1:])
323 vals = [value(a, st) for a in args[1:]]
324 if op == "v_mov_b32_e32":
325 st["v"][d] = vals[0]
326 continue
327 if op in OPS_PK:
328 n, fn, cl = OPS_PK[op]
329 out = 0
330 for k, sel in enumerate((mods.get("op_sel", [0] * n), mods.get("op_sel_hi", [1] * n))):
331 r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)])
332 if mods.get("clamp") and cl:
333 r = cl(r)
334 out |= (r & M16) << (16 * k)
335 st["v"][d] = out
336 continue
337 op = op[:-4] if op.endswith("_e64") and op[:-4] in E64 else op
338 if op not in OPS_16:
339 raise RefError(f"{op} is not modelled")
340 n, fn, cl = OPS_16[op]
341 sel = mods.get("op_sel", [0] * (n + 1))
342 r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)])
343 if mods.get("clamp") and cl:
344 r = cl(r)
345 old = st["v"].get(d, 0)
346 st["v"][d] = ((old & M16) | ((r & M16) << 16)) if sel[n] else ((old & 0xFFFF0000) | (r & M16))
347 return [st["v"].get(8 + i, 0) for i in range(4)]
348
349
350# ---- the translator side -----------------------------------------------------------------------------------
351
352def translated(lines, name="ps_pk16"):
353 """Translate and execute; returns the four exported words, or raises Skip."""
354 import rdna2spirv
355 from spirv_mini_interp import run_fragment
356 with tempfile.TemporaryDirectory(prefix="pk16-diff-") as tmp:
357 dis = os.path.join(tmp, "disasm")
358 os.mkdir(dis)
359 path = os.path.join(dis, name + ".s")
360 with open(path, "w", encoding="utf-8", newline="\n") as f:
361 f.write(f"; {name} pk16_diff case\n")
362 for line in lines:
363 f.write("\t" + line + "\n")
364 f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n")
365 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
366 f.write(STUB_DXBC)
367 try:
368 with warnings.catch_warnings():
369 warnings.simplefilter("ignore", ResourceWarning)
370 spvasm = rdna2spirv.translate(path)
371 gc.collect()
372 except rdna2spirv.Unsupported as e:
373 raise Skip(f"translator unsupported: {e}") from None
374 try:
375 out = run_fragment(spvasm)
376 except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass
377 raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None
378 return [w & M32 for w in out["%out_mrt0"]]
379
380
381def hw_kernel(lines):
382 """A raw kernel for tools/hw_oracle: the program on one lane, then v8..v11 stored at the output pointer."""
383 from hw_oracle import asm
384 return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"],
385 wave=32, threads=1, words=4, raw=True)
386
387
388# ---- comparison, shrinking, the run --------------------------------------------------------------------------
389
390def _diff(lines, want, got, label):
391 bad = [k for k in range(4) if want[k] != got[k]]
392 if not bad:
393 return None
394 i = bad[0]
395 return f"word {i} ({lines[-N_OBS + i].split(', ')[1]}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}"
396
397
398def check(lines, backends=("translator",), hw=None):
399 """None on a match, else a description. Raises Skip (every backend skipped) / RefError.
400 hw is the hardware result for this program (four words or a str reason), or a callable lines -> that."""
401 want = reference(lines)
402 problems, skips = [], []
403 if "translator" in backends:
404 try:
405 problems.append(_diff(lines, want, translated(lines), "translated"))
406 except Skip as e:
407 skips.append(e)
408 if "hw" in backends:
409 got = hw(lines) if callable(hw) else hw
410 if isinstance(got, str):
411 skips.append(Skip(f"hardware: {got}"))
412 else:
413 problems.append(_diff(lines, want, got, "hardware"))
414 if skips and len(skips) == len(backends):
415 raise skips[0]
416 return "; ".join(p for p in problems if p) or None
417
418
419def shrink(lines, check_fn=check):
420 """Observe one register if that still fails, drop instructions while the program still mismatches, then the
421 seeds of registers nothing reads."""
422 def fails(trial):
423 try:
424 return bool(check_fn(trial))
425 except (Skip, RefError):
426 return False
427 seed, body, obs = lines[:N_SEED], lines[N_SEED:-N_OBS], lines[-N_OBS:]
428 for line in obs:
429 one = [line.replace(line.split()[1], f"v{8 + i},") for i in range(4)]
430 if fails(seed + body + one):
431 obs = one
432 break
433 changed = True
434 while changed:
435 changed = False
436 for i in range(len(body) - 1, -1, -1):
437 trial = body[:i] + body[i + 1:]
438 if fails(seed + trial + obs):
439 body, changed = trial, True
440 used = set()
441 for line in body:
442 used |= set(re.findall(r"\b[vs]\d+\b", line)) # a 16-bit write keeps the other half of vD: it reads vD
443 for line in obs:
444 used |= set(re.findall(r"\b[vs]\d+\b", line.partition(" ")[2]))
445 seed = [line for line in seed if line.split()[1].rstrip(",") in used]
446 return seed + body + obs
447
448
449def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None):
450 counts = {"pass": 0, "mismatch": 0, "skip": {}}
451 failures = []
452 rng = random.Random(seed)
453 progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)]
454 hw = oracle.run([hw_kernel(p) for p in progs]) if "hw" in backends else [None] * programs
455 for i, lines in enumerate(progs):
456 try:
457 problem = check(lines, backends, hw[i])
458 except Skip as e:
459 counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1
460 continue
461 if problem is None:
462 counts["pass"] += 1
463 continue
464 counts["mismatch"] += 1
465 failures.append((i, problem, lines))
466 return counts, failures
467
468
469def self_test():
470 """Harness canaries: a hand program matches, the reference gives hand-worked values, a bad form is a skip."""
471 base = [f"v_mov_b32_e32 v{v}, 0x{0x00010001 * v:x}" for v in VREGS] + [f"s_mov_b32 s{s}, {s}" for s in SREGS]
472 body = ["v_pk_add_u16 v1, v2, s4 op_sel:[1,0] op_sel_hi:[0,0]", # lo: 2 + 4, hi: 2 + 4
473 "v_pk_mad_i16 v3, v3, -1, v5 op_sel_hi:[1,0,1] clamp", # -1 in both halves: 5 - 3
474 "v_mad_u16 v4, v6, 0x8000, v7 op_sel:[0,0,0,1] clamp", # 6 * 0x8000 + 7 saturates; high half
475 "v_max3_i16 v2, v2, -16, s5 op_sel:[0,0,0,0]"]
476 lines = base + body + observe([1, 3, 4, 2])
477 ok = check(lines) is None
478 worked = reference(lines) == [0x00060006, 0x00020002, 0xFFFF0004, 0x00020005]
479 try:
480 translated(base + ["v_pk_add_u16_sdwa_dpp v1, v2, v3"] + observe([1, 2, 3, 4]))
481 skipped = False
482 except Skip:
483 skipped = True
484 print(f"self-test: match {ok}, hand values {worked}, unsupported form skipped {skipped}")
485 return ok and worked and skipped
486
487
488def main(argv=None):
489 ap = argparse.ArgumentParser(description="Packed and 16-bit integer VALU differential fuzzing.")
490 ap.add_argument("--programs", type=int, default=300)
491 ap.add_argument("--seed", type=int, default=1)
492 ap.add_argument("--max-ops", type=int, default=6)
493 ap.add_argument("--ops", default=None, help="comma-separated opcodes (--list-ops)")
494 ap.add_argument("--no-literals", action="store_true", help="no literal sources")
495 ap.add_argument("--list-ops", action="store_true")
496 ap.add_argument("--self-test", action="store_true")
497 ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first")
498 ap.add_argument("--known", action="store_true",
499 help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; "
500 "always on with --oracle hw alone)")
501 ap.add_argument("--oracle", default="translator",
502 help="comma-separated comparison targets: translator (default), hw (natively on an AMD GPU; see "
503 "tools/hw_oracle/). 'hw' alone compares the hardware with the reference only")
504 ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)")
505 a = ap.parse_args(argv)
506 if a.programs < 1 or a.max_ops < 1:
507 ap.error("--programs and --max-ops must be at least 1")
508 backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(",")))
509 if not backends or any(t not in ("translator", "hw") for t in backends):
510 ap.error("--oracle takes translator, hw or translator,hw")
511 global KNOWN, LITERALS
512 KNOWN = a.known or backends == ("hw",)
513 LITERALS = not a.no_literals
514 if a.list_ops:
515 for name in ALL_OPS:
516 if name in OPS_PK:
517 n, _, cl = OPS_PK[name]
518 print(f"{name:18} VOP3P, {n} sources, op_sel/op_sel_hi{', clamp' if cl else ''}")
519 else:
520 n, _, cl = OPS_16[name]
521 print(f"{name:18} VOP3, {n} sources, op_sel (sources and destination half){', clamp' if cl else ''}")
522 return 0
523 if a.self_test:
524 return 0 if self_test() else 1
525 if a.ops is not None:
526 tokens = [t.strip() for t in a.ops.split(",")]
527 if not any(tokens) or any(not t for t in tokens):
528 ap.error("--ops must be a comma-separated list of opcodes")
529 ops = sorted(set(tokens))
530 else:
531 ops = list(ALL_OPS)
532 unknown = [o for o in ops if o not in ALL_OPS]
533 if unknown:
534 ap.error("unknown ops: " + ", ".join(unknown))
535 oracle = None
536 if "hw" in backends:
537 from hw_oracle import runner
538 try:
539 oracle = runner.open_oracle(arch=a.hw_arch)
540 except runner.Unavailable as e:
541 print(f"hardware oracle unavailable: {e}")
542 return 77
543 print(f"hardware oracle: {oracle.device}")
544 try:
545 counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle)
546 skips = sum(counts["skip"].values())
547 print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}{', known' if KNOWN else ''}): "
548 f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped")
549 for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]):
550 print(f" skip x{n}: {reason}")
551
552 def check_fn(lines):
553 return check(lines, backends, (lambda l: oracle.run([hw_kernel(l)])[0]) if oracle else None)
554 for i, problem, lines in failures[: None if a.all_failures else 1]:
555 small = shrink(lines, check_fn)
556 print(f"MISMATCH program {i}: {check_fn(small) or problem}")
557 print("\n".join("\t" + line for line in small))
558 except (RefError, RuntimeError) as e:
559 print(f"harness error: {e}")
560 return 2
561 finally:
562 if oracle:
563 oracle.close()
564 return 1 if failures else 0
565
566
567if __name__ == "__main__":
568 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
569 sys.stdout.reconfigure(errors="replace")
570 except (AttributeError, ValueError, OSError):
571 pass
572 sys.exit(main())