r"""Differential fuzzer for the translator's image path, starting with `image_load` (standard library only). Each case is a hand-written RDNA2 pixel shader that reads one texel with `image_load` and exports it to `mrt0`. It runs on the GPU through `runtime/test/vk_image_fuzz.cpp` against a synthetic texture of a chosen format, and every RGBA32F pixel is compared with an independent CPU oracle that models the RDNA2 texel fetch for that T# format. A texel fetch is a memory read: no filtering, no borders, no LOD selection. What this covers today: 2D `image_load`, nonzero `dmask` values, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`, `R32G32B32A32_SFLOAT` and `R32_SFLOAT`, at sizes that divide the 64x64 draw (8/16/32/64), every texel read at least once. `--op image_load_pck` / `image_load_pck_sgn` run on the hardware oracle only: the raw texel dwords, including texels under 4 bytes. Integer coverage uses 8-bit UINT/SINT sampled images (the translator reads them through uint/sint aliases of the sampled array) and converts loaded integers to exactly representable floats. Not covered yet: wider integer formats, mips, 1D/2D-array/3D/cube, `image_sample`/`gather` with filters and borders, and texel offsets with `VK_KHR_maintenance8`. Oracles (--oracle translator|hw|translator,hw): translator (default) is the path above. hw runs the same fetches as raw compute kernels natively on the AMD GPU through tools/hw_oracle/ (docs/shader_validation.md, "Hardware oracle for the image fetches"): a linear texture in device memory, a T# built for the GPU's family (hw_oracle/tsharp.py: GFX11 on gfx11xx, GFX10 on gfx103x), `image_load ... dmask:.. dim:SQ_RSRC_IMG_2D unorm` for every texel, every result register stored and compared word for word with this file's CPU model. `--op` picks the fetch: `image_load` (default), or `image_load_pck` / `image_load_pck_sgn`, which return the raw texel dwords (no `unorm`) and which the CPU model `pck_oracle` covers, sub-4-byte texels included; the translator oracle does not translate them and is skipped. It tests the MODEL (and, with translator,hw, shows what the translator did on a case the hardware disagrees with). A local gfx1150 is RDNA3.5, not RDNA2: a match supports the model, it does not prove RDNA2. --negative-control checks that deliberately wrong models and a wrong T# FORMAT are caught. Usage: python -I tools/image_fuzz.py [--programs N] [--seed S] [--build DIR] [--work DIR] [--show] python -I tools/image_fuzz.py --oracle hw [--op image_load_pck|image_load_pck_sgn] [--programs N] [--seed S] [--negative-control] python -I tools/image_fuzz.py --self-test Exit code: 0 when every case matches, 1 on a mismatch, 2 on a setup or harness error, 77 when --oracle hw was asked for and the hardware oracle's tools or GPU are missing. Nothing here reads game files. """ import argparse import os import random import signal import struct import subprocess import sys import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS = os.path.join(ROOT, "tools") SHADERS = os.path.join(ROOT, "runtime", "test", "shaders") TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py") sys.path.insert(0, TOOLS) sys.path.insert(0, SHADERS) import mc_command # noqa: E402 from compute_fixture import find_test_program # noqa: E402 from hw_oracle import asm as hw_asm, tsharp # noqa: E402 HARNESS = "vk_image_fuzz" HARNESS_ERROR = "harness" # run_case result: the harness ended before producing results DRAW = 64 # the harness draws a 64x64 full-screen triangle # name -> (Vulkan format for the spec and the image, GFX10 FORMAT code for T# word 1, bytes per texel, model) FORMATS = { "R8G8B8A8_UNORM": ("R8G8B8A8_UNORM", 56, 4, "unorm8"), "R16G16B16A16_SFLOAT": ("R16G16B16A16_SFLOAT", 71, 8, "half4"), "R32G32B32A32_SFLOAT": ("R32G32B32A32_SFLOAT", 77, 16, "float4"), "R32_SFLOAT": ("R32_SFLOAT", 22, 4, "float1"), "R8G8B8A8_UINT": ("R8G8B8A8_UINT", 60, 4, "uint8"), "R8G8B8A8_SINT": ("R8G8B8A8_SINT", 61, 4, "sint8"), } # Texel formats only the hardware oracle's pck ops run: sub-4-byte texels the raw-dword model covers. The # translator oracle has no image_load model for them and the pck ops never reach it. PCK_FORMATS = { "R8_UINT": ("R8_UINT", 5, 1, "raw"), "R8_SINT": ("R8_SINT", 6, 1, "raw"), "R16_UINT": ("R16_UINT", 11, 2, "raw"), "R16_SINT": ("R16_SINT", 12, 2, "raw"), "R8G8_UINT": ("R8G8_UINT", 18, 2, "raw"), "R8G8_SINT": ("R8G8_SINT", 19, 2, "raw"), "R16G16_SINT": ("R16G16_SINT", 28, 4, "raw"), } HW_FORMATS = {**FORMATS, **PCK_FORMATS} SIZES = (8, 16, 32, 64) # The default run reaches only the first two masks. Use a gap to check that selected components pack down. DMASKS = (0xf, 0x5, *range(1, 0x5), *range(0x6, 0xf)) STDERR_TAIL = 20 # lines of the harness's output a failure prints # Windows reports a crash as an NTSTATUS exit code (unsigned); the ones a driver crash tends to end with NTSTATUS = { 0xC0000005: "access violation", 0xC000001D: "illegal instruction", 0xC0000094: "integer divide by zero", 0xC00000FD: "stack overflow", 0xC0000374: "heap corruption", 0xC0000409: "stack buffer overrun", } def assemble(asm: str, name: str, work: str) -> None: """Assemble with llvm-mc like runtime/test/shaders/build.py, into work/disasm/.s.""" cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] r = mc_command.run(cmd, input=asm, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise SystemExit(f"llvm-mc rejected {name}:\n{r.stderr}") code = "".join(line for line in r.stdout.splitlines(keepends=True) if not line.lstrip().startswith(".")) disasm = os.path.join(work, "disasm") os.makedirs(disasm, exist_ok=True) with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} generated by tools/image_fuzz.py\n{code}") with open(os.path.join(work, name + ".dxbc"), "wb") as f: f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name def pc_tail_env() -> bool: """True when LEONIDA_PC_TAIL_UBO asks for rdna2spirv.py --pc-tail-ubo (128-byte push constants).""" return (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on") def translate(work: str, pc_tail: bool = False) -> str: """Translate work/disasm into work/spirv and return that directory.""" spirv = os.path.join(work, "spirv") cmd = [sys.executable, "-I", TRANSLATOR, os.path.join(work, "disasm"), "--out", spirv] if pc_tail: cmd.append("--pc-tail-ubo") r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode: raise SystemExit(f"translator failed:\n{r.stdout}\n{r.stderr}") # The batch translator can exit successfully even when an individual shader is rejected. missing = [name for name in ("vs_ids.spv", "ps_image_load.spv") if not os.path.isfile(os.path.join(spirv, name))] if missing: raise SystemExit(f"translator did not emit {', '.join(missing)}:\n{r.stdout}\n{r.stderr}") return spirv SENTINELS = (1.0, 2.0, 3.0, 4.0) def masked_components(rgba, dmask): """Selected R/G/B/A components occupy consecutive VGPRs; remaining VGPRs keep their sentinels.""" selected = [rgba[c] for c in range(4) if dmask & (1 << c)] return selected + list(SENTINELS[len(selected):]) def pixel_shader(width: int, height: int, dmask: int = 0xf, model: str = "") -> str: """image_load of a 2D texture at the texel under each pixel, exported to mrt0.""" count = dmask.bit_count() dst = "v4" if count == 1 else f"v[4:{3 + count}]" init = "".join(f"\tv_mov_b32_e32 v{reg}, {value}\n" for reg, value in enumerate(SENTINELS, 4)) convert = "" if model in ("uint8", "sint8"): kind = "u32" if model == "uint8" else "i32" convert = "".join(f"\tv_cvt_f32_{kind}_e32 v{r}, v{r}\n" for r in range(4, 4 + count)) return ( "; image_load probe generated by tools/image_fuzz.py\n" "\tv_interp_p1_f32_e32 v2, v0, attr0.x\n" "\tv_interp_p2_f32_e32 v2, v1, attr0.x\n" "\tv_interp_p1_f32_e32 v3, v0, attr0.y\n" "\tv_interp_p2_f32_e32 v3, v1, attr0.y\n" f"\tv_mul_f32_e32 v2, {float(width)}, v2\n" f"\tv_mul_f32_e32 v3, {float(height)}, v3\n" "\tv_cvt_u32_f32_e32 v2, v2\n" "\tv_cvt_u32_f32_e32 v3, v3\n" f"{init}" f"\timage_load {dst}, v[2:3], s[8:15] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_2D\n" "\ts_waitcnt vmcnt(0)\n" f"{convert}" "\texp mrt0 v4, v5, v6, v7 done vm\n" "\ts_endpgm\n" ) def make_texels(fmt_name: str, width: int, height: int, rng: random.Random): """Raw texel bytes and the T# words (the key; word 1 carries FORMAT for the translator).""" vk_format, code, bpp, model = HW_FORMATS[fmt_name] # A fifth of the values are specials: a fetch is a memory read, so NaN/inf/+-0/denormal payloads must # survive it unchanged (the comparison treats every NaN as equal to every NaN). specials = [0.0, -0.0, float("inf"), float("-inf"), float("nan"), 1e-40, -1e-40] raw = bytearray() for _ in range(width * height): if model == "raw": raw += rng.randbytes(bpp) elif model in ("unorm8", "uint8", "sint8"): raw += bytes([rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)]) elif model == "half4": for _ in range(4): value = rng.choice([struct.unpack(" float: """The float32 the GPU gets; the UNORM divide happens in float, not in Python's double.""" return struct.unpack(" list: """Every texel as RGBA floats, the way an RDNA2 image_load of that format reads it.""" _, _, bpp, model = FORMATS[fmt_name] texel = [] for i in range(width * height): chunk = texels[i * bpp:(i + 1) * bpp] if model == "unorm8": texel.append([f32(chunk[c] / 255.0) for c in range(4)]) elif model in ("uint8", "sint8"): texel.append(list(struct.unpack("<4B" if model == "uint8" else "<4b", chunk))) elif model == "half4": texel.append([struct.unpack_from("> (8 * bpp - 1): dword |= ~((1 << (8 * bpp)) - 1) & 0xFFFFFFFF dwords = [dword] else: dwords = [int.from_bytes(chunk[j:j + 4], "little") for j in range(0, bpp, 4)] if "dmask_in_place" in PERTURB: regs = [(dwords[r] if r < n_dwords else 0) if dmask & (1 << r) else sentinels[r] for r in range(4)] else: regs = [dwords[r] if r < n_dwords else 0 for r in range(4) if dmask & (1 << r)] regs += sentinels[len(regs):] words.extend(regs) return words def texel_of_pixel(x: int, y: int, width: int, height: int) -> tuple: """The texel the generated shader reads for pixel (x, y): floor(uv * size) with uv = (pixel + 0.5) / 64.""" return (x * width) // DRAW, (y * height) // DRAW def read_rgba(path: str) -> list: with open(path, "rb") as f: data = f.read() want = DRAW * DRAW * 16 if len(data) != want: raise SystemExit(f"{path}: {len(data)} bytes, expected {want}") return list(struct.unpack(f"<{DRAW * DRAW * 4}f", data)) def same_component(a: float, b: float) -> bool: """Bit equality of two f32 values, except that any NaN matches any NaN. Ordinary float equality would hide a wrong binding that returns -0 where +0 is expected (and the reverse): +0.0 == -0.0 is true in Python, but the 32-bit words differ and a texture fetch must preserve the sign. """ packed_a, packed_b = struct.pack(" float conversion is the # driver's, not the translated code's. RDNA2 returns the correctly rounded c / 255 (--oracle hw checks that bit for # bit); llvmpipe multiplies by an f32 1/255 instead, one ulp above it for 126 of the 256 values (27: 0x3dd8d8da, not # 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first R8G8B8A8_UNORM one ran. # A wrong format, swizzle, binding or dmask is never that close (c / 256 is ~0.4% off), so the translator oracle # accepts one ulp on a UNORM8 texel component and counts how often it needed to. UNORM8_ULPS = 1 unorm8_near = 0 # UNORM8 components accepted one ulp from the exact quotient, for the summary def near_component(a: float, b: float, ulps: int) -> bool: """Finite f32 values of the same sign at most `ulps` units in the last place apart.""" bits_a = struct.unpack(" list: global unorm8_near expected = oracle(fmt_name, texels, width, height) # Only the components the texel supplies; the registers dmask leaves unwritten must keep their sentinels exactly. near_ok = dmask.bit_count() if FORMATS[fmt_name][3] == "unorm8" else 0 problems = [] for y in range(DRAW): for x in range(DRAW): tx, ty = texel_of_pixel(x, y, width, height) want = masked_components(expected[ty * width + tx], dmask) base = (y * DRAW + x) * 4 have = got[base:base + 4] exact = [same_component(have[c], want[c]) for c in range(4)] if all(exact): continue if all(exact[c] or (c < near_ok and near_component(have[c], want[c], UNORM8_ULPS)) for c in range(4)): unorm8_near += exact.count(False) continue problems.append((x, y, want, have)) if len(problems) >= 6: return problems return problems def exit_status(returncode: int) -> str: """How the harness ended, for a failure line: "exit 1", "killed by SIGSEGV", "exit 0xc0000005 (access violation)".""" if returncode < 0: # POSIX: subprocess reports a fatal signal as its negative number try: name = signal.Signals(-returncode).name except ValueError: name = f"signal {-returncode}" return f"killed by {name}" status = returncode & 0xFFFFFFFF if status >= 0xC0000000: return f"exit 0x{status:08x}" + (f" ({NTSTATUS[status]})" if status in NTSTATUS else "") return f"exit {returncode}" def fatal_process_status(returncode: int) -> bool: """True when the process died rather than returning an ordinary error status.""" return returncode < 0 or (returncode & 0xFFFFFFFF) >= 0xC0000000 def reached_device(result) -> bool: """True when the harness got far enough to print its selected device. vk_image_fuzz prints ``device:`` before it creates the shader modules. A fatal exit before that line is startup noise in the loader, validation layer or driver initialization; it cannot be a crash caused by the shader under test, so one retry is sound. A crash after the line can be caused by the module and is never retried. """ return any(line.startswith("device:") for line in (result.stdout or "").splitlines()) def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, data=None, pc_tail=False) -> bool: """data: the (texel bytes, T# words) to use instead of drawing them from rng (main draws all cases up front, so the translator and the hardware oracle see the same textures).""" vk_format, _, _, model = FORMATS[fmt_name] asm = pixel_shader(width, height, dmask, model) assemble(asm, "ps_image_load", work) if not os.path.exists(os.path.join(work, "disasm", "vs_ids.s")): with open(os.path.join(SHADERS, "vs_ids.asm"), encoding="utf-8") as f: assemble(f.read(), "vs_ids", work) spirv = translate(work, pc_tail=True) if pc_tail else translate(work) texels, tsharp = data if data is not None else make_texels(fmt_name, width, height, rng) texels_path = os.path.join(work, "texels.bin") with open(texels_path, "wb") as f: f.write(texels) spec_path = os.path.join(work, "spec.txt") with open(spec_path, "w", encoding="utf-8", newline="\n") as f: f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n" f"tsharp={','.join(hex(w) for w in tsharp)}\n") out_path = os.path.join(work, "out.raw") harness = os.path.join(build, HARNESS + (".exe" if os.name == "nt" else "")) if not os.path.exists(harness): raise SystemExit(f"{harness} not found: build the runtime first " f"(cmake --build --target {HARNESS})") run_kw = {"capture_output": True, "text": True} if pc_tail: run_kw["env"] = dict(os.environ, LEONIDA_PC_TAIL_UBO="1") cmd = [harness, os.path.join(spirv, "vs_ids.spv"), os.path.join(spirv, "ps_image_load.spv"), out_path, spec_path] r = subprocess.run(cmd, **run_kw) if r.returncode not in (0, 77) and fatal_process_status(r.returncode) and not reached_device(r): print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: harness startup {exit_status(r.returncode)} " "before device selection; retrying once") r = subprocess.run(cmd, **run_kw) if r.returncode == 77: # a device limit or missing feature, named on the harness's "unsupported:" line why = next((ln for ln in f"{r.stdout}\n{r.stderr}".splitlines() if ln.startswith("unsupported:")), "the device does not support the set") print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: SKIP ({why})") return None if r.returncode != 0: status = exit_status(r.returncode) stream, lines = "stderr", (r.stderr or "").strip().splitlines() if not lines: stream, lines = "stdout", (r.stdout or "").strip().splitlines() reason = f"{HARNESS} {status}" + (f": {lines[-1]}" if lines else ", no output") print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: FAIL ({reason})") if len(lines) > 1: shown = lines[-STDERR_TAIL:] print(f" {HARNESS} {stream}" + (f" (last {len(shown)} of {len(lines)} lines)" if len(shown) < len(lines) else "") + ":") for line in shown: print(f" {line}") return HARNESS_ERROR got = read_rgba(out_path) problems = compare(fmt_name, texels, width, height, got, dmask) if not problems: if show: print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: pass (every pixel matches)") return True print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: {len(problems)}+ mismatched pixels") for x, y, want, have in problems: print(f" pixel ({x}, {y}) texel ({texel_of_pixel(x, y, width, height)}): " f"want {want} got {have}") if keep: print(f" case kept in {work} (spec.txt, ps_image_load.s, texels.bin, out.raw)") return False # ---- the hardware oracle ---- HW_CHUNK = 24 # kernels per assembled module: each carries its texture, up to 64 KB of data WAVES = (32, 64) # alternated from case to case: a texel fetch must not depend on the wave size FORMAT_ORDER = list(HW_FORMATS) _X, _Y, _Z, _W, _0, _1 = (tsharp.SEL_X, tsharp.SEL_Y, tsharp.SEL_Z, tsharp.SEL_W, tsharp.SEL_0, tsharp.SEL_1) # DST_SEL per model. A one-channel format reads (r, 0, 0, 1): what the translator's image view gives it # (format_swizzle in runtime/src/gfx10_descriptors.h) and what the CPU model says. FORMAT_SWIZZLE = {"unorm8": (_X, _Y, _Z, _W), "half4": (_X, _Y, _Z, _W), "float4": (_X, _Y, _Z, _W), "float1": (_X, _0, _0, _1), "uint8": (_X, _Y, _Z, _W), "sint8": (_X, _Y, _Z, _W), "raw": (_X, _Y, _Z, _W)} class Case: """One fetch: a format, a texture size, a dmask and the texture bytes (drawn once, shared by every oracle).""" def __init__(self, index, fmt, width, height, dmask, data, wave): self.index, self.fmt, self.width, self.height = index, fmt, width, height self.dmask, self.data, self.wave = dmask, data, wave @property def name(self): return f"#{self.index} {self.fmt} {self.width}x{self.height} dmask:0x{self.dmask:x} wave{self.wave}" def make_cases(programs, seed, formats): """The cases of a run, drawn in the order main always used (width, height, then the texels of each case), so a seed names the same textures whichever oracle runs them.""" rng = random.Random(seed) cases = [] for i in range(programs): fmt = formats[i % len(formats)] width, height = rng.choice(SIZES), rng.choice(SIZES) dmask = DMASKS[(i // len(formats)) % len(DMASKS)] cases.append(Case(i, fmt, width, height, dmask, make_texels(fmt, width, height, rng), WAVES[(i // len(formats)) % 2])) return cases # What the model gets wrong on purpose (--negative-control): each name switches one deliberate error on in # expected_words, and the hardware words must then disagree with it somewhere. PERTURB = set() PERTURBATIONS = { "unorm_256": "UNORM8 divides by 256 instead of 255", "swap_rb": "red and blue swapped", "sint_unsigned": "SINT8 read as unsigned", "alpha_zero": "R32_SFLOAT missing alpha is 0, not 1", "dmask_in_place": "dmask components stay in their own register instead of packing downwards", "no_sentinels": "registers dmask does not write read as 0 instead of keeping their value", "transpose": "texel (x, y) read as (y, x)", "pck_sgn_zero_extend": "image_load_pck_sgn zero-extends a sub-4-byte texel instead of sign-extending", } # The --op each perturbation can affect; the negative control only requires the ones for the run's op. PERTURB_OPS = { "unorm_256": ("image_load",), "swap_rb": ("image_load",), "sint_unsigned": ("image_load",), "alpha_zero": ("image_load",), "dmask_in_place": ("image_load", "image_load_pck", "image_load_pck_sgn"), "no_sentinels": ("image_load", "image_load_pck", "image_load_pck_sgn"), "transpose": ("image_load", "image_load_pck", "image_load_pck_sgn"), "pck_sgn_zero_extend": ("image_load_pck_sgn",), } def f32_bits(value: float) -> int: return struct.unpack(" bool: """Bit equality; for the float formats any NaN equals any NaN (payloads are not modelled).""" if have == want: return True if model in ("uint8", "sint8", "pck"): return False return all((x & 0x7F800000) == 0x7F800000 and x & 0x007FFFFF for x in (have, want)) def compare_hw(case, got, op="image_load"): """Mismatches (texel x, y, register, want, have) of one case's output words against the model.""" want = expected_words(case.fmt, case.data[0], case.width, case.height, case.dmask, op) model = "pck" if op != "image_load" else FORMATS[case.fmt][3] problems = [] if len(got) != len(want): return [(-1, -1, -1, len(want), len(got))] for i, (h, w) in enumerate(zip(got, want)): if not word_equal(h, w, model): texel = i // 4 problems.append((texel % case.width, texel // case.width, i % 4, w, h)) return problems def hw_kernel(arch, case, fmt_override=None, op="image_load"): """The native kernel of a case (fmt_override: build the T# with another format's code, for the negative control). op: the fetch; the pck forms replace the opcode and drop `unorm`, as tsharp.kernel_lines emits image_load.""" bpp = HW_FORMATS[case.fmt][2] texture = tsharp.lay_out(case.data[0], case.width, case.height, bpp) lines = tsharp.kernel_lines(arch, case.index, fmt_override or case.fmt, case.width, case.height, bpp, case.dmask, texture, FORMAT_SWIZZLE[HW_FORMATS[case.fmt][3]]) if op != "image_load": lines = [_pck_line(ln, op) for ln in lines] threads, _ = tsharp.lanes(case.width, case.height) return hw_asm.Kernel(lines, case.wave, threads, case.width * case.height * 4, raw=True) def _pck_line(line, op): """kernel_lines' `image_load ... unorm` as `op` (the pck forms return raw bits: no `unorm`).""" if "image_load " not in line: return line line = line.replace("image_load ", op + " ", 1) return line[:-6] if line.endswith(" unorm") else line def run_hw(oracle, cases, a, quiet=False, fmt_override=None): """Run every case natively and judge it against the model. Returns (stats, mismatching cases, {index: words}).""" op = getattr(a, "op", "image_load") kernels = [hw_kernel(oracle.arch, c, fmt_override(c) if fmt_override else None, op=op) for c in cases] stats = {} failed, words = [], {} for c, got in zip(cases, oracle.run(kernels)): st = stats.setdefault(c.wave, {"cases": 0, "match": 0, "mismatch": 0, "rejected": 0}) st["cases"] += 1 if isinstance(got, str): st["rejected"] += 1 print(f"REJECTED {c.name} [hw]: {got}") continue if got and all(w == tsharp.POISON for w in got): st["rejected"] += 1 print(f"ERROR {c.name} [hw]: the texture in the kernel is not 256-byte aligned (every word is the poison)") continue words[c.index] = got problems = compare_hw(c, got, op) if not problems: st["match"] += 1 continue st["mismatch"] += 1 failed.append(c) if quiet: continue print(f"MISMATCH {c.name} [hw]: {len(problems)} words; reproduce with --oracle hw --seed {a.seed} " f"--programs {c.index + 1}") for x, y, reg, want, have in problems[:a.max_report]: print(f" texel ({x}, {y}) register {reg}: want 0x{want:08x} have 0x{have:08x}") return stats, failed, words def negative_control(oracle, cases, a): """Every deliberately wrong model, and a kernel with the wrong T# FORMAT, must be caught by the hardware words: the real model passes, each perturbed one has to mismatch on at least one case. Exit 0 when all are caught.""" op = getattr(a, "op", "image_load") _, failed, words = run_hw(oracle, cases, a) ran = [c for c in cases if c.index in words] code = 1 if failed or not ran else 0 print(f"unperturbed model: {len(failed)} of {len(ran)} cases mismatch") for name, what in PERTURBATIONS.items(): if op not in PERTURB_OPS[name]: print(f"perturbation {name} ({what}): not applicable to {op}, skipped") continue PERTURB.add(name) try: n = sum(bool(compare_hw(c, words[c.index], op)) for c in ran) finally: PERTURB.discard(name) print(f"perturbation {name} ({what}): caught by {n} of {len(ran)} cases" + ("" if n else " <-- NOT CAUGHT")) code = code or (0 if n else 1) def wrong_of(fmt): # image_load_pck ignores the FORMAT's numeric type (measured: R8G8B8A8_UINT/SINT/UNORM, R16_UINT/SINT and # R8G8_UINT/SINT give the same words), so a wrong FORMAT is only visible when it changes the texel size: # for the pck ops take the next format of another size. i = FORMAT_ORDER.index(fmt) for k in range(1, len(FORMAT_ORDER)): other = FORMAT_ORDER[(i + k) % len(FORMAT_ORDER)] if op == "image_load" or HW_FORMATS[other][2] != HW_FORMATS[fmt][2]: return other return FORMAT_ORDER[(i + 1) % len(FORMAT_ORDER)] _, bad, _ = run_hw(oracle, cases, a, quiet=True, fmt_override=lambda c: wrong_of(c.fmt)) for fmt in dict.fromkeys(c.fmt for c in cases): n_all = sum(c.fmt == fmt for c in cases) n_bad = sum(c.fmt == fmt for c in bad) print(f"wrong T# FORMAT ({fmt} built as {wrong_of(fmt)}): caught by {n_bad} of {n_all} cases" + ("" if n_bad else " <-- NOT CAUGHT")) code = code or (0 if n_bad else 1) return code def self_test() -> int: """CPU-only: the oracle, the texel mapping and the generated shader without a GPU.""" rng = random.Random(7) for name, (vk, code, bpp, model) in FORMATS.items(): width, height = 8, 8 texels, tsharp = make_texels(name, width, height, rng) assert len(texels) == width * height * bpp, name assert tsharp[1] == code << 20, name values = oracle(name, texels, width, height) assert len(values) == width * height, name assert all(len(v) == 4 for v in values), name assert texel_of_pixel(0, 0, 8, 8) == (0, 0) assert texel_of_pixel(63, 63, 8, 8) == (7, 7) assert texel_of_pixel(63, 63, 64, 64) == (63, 63) asm = pixel_shader(16, 8) assert "\timage_load" in asm and "16.0" in asm and "8.0" in asm # The measured pck values (docs/shader_validation.md): raw texel dwords, sign-extended for _sgn under 4 bytes. assert pck_oracle("R8G8B8A8_UNORM", bytes([0x81, 0x7f, 0xff, 0x02]), 0xf, False) == [0x02ff7f81, 0, 0, 0] assert pck_oracle("R8_UINT", bytes([0x81]), 0x1, False) == [0x81, 0x40000000, 0x40400000, 0x40800000] assert pck_oracle("R8_UINT", bytes([0x81]), 0x1, True) == [0xFFFFFF81, 0x40000000, 0x40400000, 0x40800000] print(f"image_fuzz self-test: ok ({len(FORMATS)} formats, {DRAW}x{DRAW} draw)") return 0 def run_translator(cases, a, work) -> tuple: """The translator oracle over the cases. Returns (passed, failed, skipped, harness errors, verdicts).""" passed = failed = skipped = harness_errors = 0 verdicts = {} pc_tail = bool(getattr(a, "pc_tail_ubo", False)) for c in cases: if a.show: print(f"[{c.index + 1}/{len(cases)}] {c.fmt} {c.width}x{c.height} (work {work})") result = run_case(c.fmt, c.width, c.height, None, work, a.build, False, a.show, c.dmask, c.data, pc_tail=pc_tail) verdicts[c.index] = result if result is None: skipped += 1 elif result == HARNESS_ERROR: harness_errors += 1 print(f" work dir kept: {work}") break elif result: passed += 1 else: failed += 1 print(f" work dir kept: {work}") break return passed, failed, skipped, harness_errors, verdicts def main() -> int: ap = argparse.ArgumentParser(description="Differential fuzzer for the translator's image_load path") ap.add_argument("--programs", type=int, default=8) ap.add_argument("--seed", type=int, default=1) # runtime/build, as docs/shader_validation.md builds it and lds_fuzz/valu_fuzz default to; a Visual Studio build's # RelWithDebInfo/Release subfolder is found below. ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) ap.add_argument("--work", help="keep each run's generated files in a new subfolder here") ap.add_argument("--show", action="store_true") ap.add_argument("--formats", default=None, help="comma-separated formats (default: every format the selected op models: the translator " "set for image_load, plus the sub-4-byte texel formats for the pck ops)") ap.add_argument("--op", default="image_load", choices=("image_load", "image_load_pck", "image_load_pck_sgn"), help="hw: the fetch opcode. The pck forms return the raw texel dwords (no unorm) and add the " "sub-4-byte texel formats; the translator oracle does not translate them and is skipped") ap.add_argument("--oracle", default="translator", help="comma-separated: translator (default; the shader through the translator and Vulkan), hw (the same " "fetches as native kernels on the AMD GPU through tools/hw_oracle/; exit 77 when it is not " "there) or translator,hw") ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") ap.add_argument("--negative-control", action="store_true", help="hw: check that deliberately wrong models and a wrong T# FORMAT are caught by the hardware words") ap.add_argument("--max-report", type=int, default=6, help="hw: mismatching words to print per case") ap.add_argument("--pc-tail-ubo", action="store_true", help="translate with rdna2spirv.py --pc-tail-ubo and run vk_image_fuzz with 128-byte push " "constants (also set by LEONIDA_PC_TAIL_UBO=1)") ap.add_argument("--self-test", action="store_true") a = ap.parse_args() a.pc_tail_ubo = a.pc_tail_ubo or pc_tail_env() if a.self_test: return self_test() backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) if not backends or any(t not in ("translator", "hw") for t in backends): ap.error("--oracle takes translator, hw or translator,hw") if a.negative_control and "hw" not in backends: ap.error("--negative-control needs --oracle hw") formats = ([f.strip() for f in a.formats.split(",") if f.strip()] if a.formats is not None else list(HW_FORMATS if a.op != "image_load" else FORMATS)) if not formats: ap.error("--formats must select at least one format") unknown = [f for f in formats if f not in HW_FORMATS] if unknown: print(f"unknown format(s): {', '.join(unknown)}; known: {', '.join(HW_FORMATS)}", file=sys.stderr) return 2 if a.op == "image_load": pck_only = [f for f in formats if f in PCK_FORMATS] if pck_only: print(f"{', '.join(pck_only)}: only the pck ops model these formats " f"(--op image_load_pck or image_load_pck_sgn)", file=sys.stderr) return 2 if a.op != "image_load" and "translator" in backends: # The translator does not translate the pck ops; the hardware oracle is the only model for them. print(f"oracle translator: {a.op} is not translated, skipping it " f"(the hardware oracle's pck_oracle is the model)") backends = tuple(t for t in backends if t != "translator") if not backends: return 77 if a.programs < 1: print("--programs must be at least 1", file=sys.stderr) return 2 if a.max_report < 1: print("--max-report must be at least 1", file=sys.stderr) return 2 if a.work: # Reject a --work that is a file, or sits under one, before any fuzz work: os.makedirs would raise a # FileExistsError traceback after the cases were built, and nothing here is retryable anyway. probe = os.path.abspath(a.work) while not os.path.lexists(probe): parent = os.path.dirname(probe) if parent == probe: break probe = parent if os.path.lexists(probe) and not os.path.isdir(probe): print(f"ERROR: --work is not a folder: {a.work}", file=sys.stderr) return 2 hw_oracle = None if "hw" in backends: from hw_oracle import runner try: hw_oracle = runner.open_oracle(arch=a.hw_arch) fam = tsharp.check_arch(hw_oracle.arch) except runner.Unavailable as e: print(f"hardware oracle unavailable: {e}") return 77 except ValueError as e: print(f"hardware oracle unavailable: {e}") hw_oracle.close() return 77 hw_oracle.chunk = HW_CHUNK print(f"hardware oracle: {hw_oracle.device} ({hw_oracle.arch}, {fam} T# layout)") if fam == "gfx11": print("note: GFX11 is RDNA3 or newer, not RDNA2: a match supports the model and does not prove RDNA2") a.build = find_test_program(a.build, HARNESS) or a.build cases = make_cases(a.programs, a.seed, formats) code = 0 verdicts = {} try: try: parent = os.path.abspath(a.work) if a.work else None if parent is not None: os.makedirs(parent, exist_ok=True) work = tempfile.mkdtemp(prefix="image_fuzz_", dir=parent) except OSError as e: print(f"ERROR: cannot create work directory: {e}", file=sys.stderr) return 2 print(f"work dir {work}") if "translator" in backends: passed, failed, skipped, harness_errors, verdicts = run_translator(cases, a, work) summary = f"{passed}/{passed + failed} programs that ran match" if failed: summary += f"; {failed} mismatched" if skipped: summary += f"; {skipped} skipped" if harness_errors: summary += f"; {harness_errors} harness error" + ("s" if harness_errors != 1 else "") if unorm8_near: summary += (f"; {unorm8_near} R8G8B8A8_UNORM components one ulp from the exact c / 255 " "(the driver's conversion)") print("translator: " + summary) code = 2 if harness_errors else (1 if failed else 0) if hw_oracle: if a.negative_control: return max(code, negative_control(hw_oracle, cases, a)) stats, failed_cases, _ = run_hw(hw_oracle, cases, a) for wave, st in sorted(stats.items()): print(f"{a.op} wave{wave} hw: " + ", ".join(f"{k} {v}" for k, v in st.items())) if "translator" in backends: for c in failed_cases: seen = verdicts.get(c.index, "not run") seen = {True: "matches the model", False: "mismatches the model", None: "was skipped", HARNESS_ERROR: "hit a harness error"}.get(seen, seen) print(f" {c.name}: hardware disagrees with the model; the translator {seen}") if any(st["mismatch"] or st["rejected"] for st in stats.values()): code = max(code, 1) if sum(st["match"] for st in stats.values()) == 0: code = max(code, 2) finally: if hw_oracle: hw_oracle.close() return code if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())