mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 22:18:37 +00:00
open(path, "w") without newline= turns each \n into \r\n on Windows, so the same JSON report, manifest or assembly listing was CRLF there and LF elsewhere. 91 text-mode writes (open, os.fdopen, Path.write_text) under tools/, scripts/, make_game.py and runtime/test/shaders/ now pass newline="\n". tests/test_text_write_line_endings.py reads the source with ast and fails for a writer that forgets it; CONTRIBUTING.md names the convention. AI-assisted (Claude), on behalf of dev-ewann.
633 lines
30 KiB
Python
633 lines
30 KiB
Python
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.
|
|
|
|
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. 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 [--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 re
|
|
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"
|
|
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"),
|
|
}
|
|
SIZES = (8, 16, 32, 64)
|
|
DMASKS = (0xf, *range(1, 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/<name>.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 translate(work: str) -> str:
|
|
"""Translate work/disasm into work/spirv and return that directory."""
|
|
spirv = os.path.join(work, "spirv")
|
|
r = subprocess.run([sys.executable, "-I", TRANSLATOR, os.path.join(work, "disasm"), "--out", spirv],
|
|
capture_output=True, text=True)
|
|
if r.returncode:
|
|
raise SystemExit(f"translator failed:\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 = 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 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("<e", struct.pack("<e", v))[0] for v in specials]
|
|
+ [rng.uniform(-64.0, 64.0)]) if rng.random() < 0.2 else rng.uniform(-64.0, 64.0)
|
|
raw += struct.pack("<e", value)
|
|
elif model == "float4":
|
|
for _ in range(4):
|
|
value = rng.choice(specials) if rng.random() < 0.2 else rng.uniform(-1e6, 1e6)
|
|
raw += struct.pack("<f", value)
|
|
else: # float1
|
|
value = rng.choice(specials) if rng.random() < 0.2 else rng.uniform(-1e6, 1e6)
|
|
raw += struct.pack("<f", value)
|
|
# A T# key: word 1 FORMAT [28:20] decides the numeric type, the rest only has to be unique and stable.
|
|
tsharp = [0x1000, code << 20, (width - 1) | ((height - 1) << 16), 0, 0, 0, 0, 0]
|
|
return bytes(raw), tsharp
|
|
|
|
|
|
def f32(value: float) -> float:
|
|
"""The float32 the GPU gets; the UNORM divide happens in float, not in Python's double."""
|
|
return struct.unpack("<f", struct.pack("<f", value))[0]
|
|
|
|
|
|
def oracle(fmt_name: str, texels: bytes, width: int, height: int) -> 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("<e", chunk, 2 * c)[0] for c in range(4)])
|
|
elif model == "float4":
|
|
texel.append([struct.unpack_from("<f", chunk, 4 * c)[0] for c in range(4)])
|
|
else:
|
|
texel.append([struct.unpack_from("<f", chunk, 0)[0], 0.0, 0.0, 1.0])
|
|
return texel
|
|
|
|
|
|
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("<f", a), struct.pack("<f", b)
|
|
if packed_a == packed_b:
|
|
return True
|
|
bits_a = struct.unpack("<I", packed_a)[0]
|
|
bits_b = struct.unpack("<I", packed_b)[0]
|
|
nan_a = (bits_a & 0x7F800000) == 0x7F800000 and bits_a & 0x007FFFFF
|
|
nan_b = (bits_b & 0x7F800000) == 0x7F800000 and bits_b & 0x007FFFFF
|
|
return bool(nan_a and nan_b)
|
|
|
|
|
|
def compare(fmt_name, texels, width, height, got, dmask=0xf) -> list:
|
|
expected = oracle(fmt_name, texels, width, height)
|
|
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]
|
|
if all(same_component(have[c], want[c]) for c in range(4)):
|
|
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 run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, data=None) -> 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)
|
|
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 <build> --target {HARNESS})")
|
|
r = subprocess.run([harness, os.path.join(spirv, "vs_ids.spv"), os.path.join(spirv, "ps_image_load.spv"),
|
|
out_path, spec_path], capture_output=True, text=True)
|
|
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 False
|
|
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(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)}
|
|
|
|
|
|
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)",
|
|
}
|
|
|
|
|
|
def f32_bits(value: float) -> int:
|
|
return struct.unpack("<I", struct.pack("<f", value))[0]
|
|
|
|
|
|
def expected_words(fmt_name, texels, width, height, dmask):
|
|
"""The dwords the hardware stores for every texel (texel index * 4 words): the four result registers after an
|
|
image_load with this dmask, written over the sentinels. Integer formats come back as integers, the rest as f32."""
|
|
_, _, bpp, model = FORMATS[fmt_name]
|
|
values = oracle(fmt_name, texels, width, height)
|
|
if "unorm_256" in PERTURB and model == "unorm8":
|
|
values = [[f32(texels[i * 4 + c] / 256.0) for c in range(4)] for i in range(width * height)]
|
|
if "swap_rb" in PERTURB:
|
|
values = [[v[2], v[1], v[0], v[3]] for v in values]
|
|
if "sint_unsigned" in PERTURB and model == "sint8":
|
|
values = [[x & 0xff for x in v] for v in values]
|
|
if "alpha_zero" in PERTURB and model == "float1":
|
|
values = [[v[0], v[1], v[2], 0.0] for v in values]
|
|
if "transpose" in PERTURB:
|
|
values = [values[(i % width) * height + i // width] for i in range(width * height)]
|
|
sentinels = [0.0] * 4 if "no_sentinels" in PERTURB else list(SENTINELS)
|
|
integer = model in ("uint8", "sint8")
|
|
words = []
|
|
for v in values:
|
|
if "dmask_in_place" in PERTURB:
|
|
regs = [v[c] if dmask & (1 << c) else sentinels[c] for c in range(4)]
|
|
else:
|
|
picked = [v[c] for c in range(4) if dmask & (1 << c)]
|
|
regs = picked + sentinels[len(picked):]
|
|
for x in regs:
|
|
words.append(x & 0xFFFFFFFF if integer and isinstance(x, int) else f32_bits(x))
|
|
return words
|
|
|
|
|
|
def word_equal(have: int, want: int, model: str) -> 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"):
|
|
return False
|
|
return all((x & 0x7F800000) == 0x7F800000 and x & 0x007FFFFF for x in (have, want))
|
|
|
|
|
|
def compare_hw(case, got):
|
|
"""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)
|
|
model = 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):
|
|
"""The native kernel of a case (fmt_override: build the T# with another format's code, for the negative control)."""
|
|
bpp = 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[FORMATS[case.fmt][3]])
|
|
threads, _ = tsharp.lanes(case.width, case.height)
|
|
return hw_asm.Kernel(lines, case.wave, threads, case.width * case.height * 4, raw=True)
|
|
|
|
|
|
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})."""
|
|
kernels = [hw_kernel(oracle.arch, c, fmt_override(c) if fmt_override else None) 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)
|
|
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."""
|
|
_, 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():
|
|
PERTURB.add(name)
|
|
try:
|
|
n = sum(bool(compare_hw(c, words[c.index])) 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):
|
|
return FORMAT_ORDER[(FORMAT_ORDER.index(fmt) + 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
|
|
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, {case index: True/False/None})."""
|
|
passed = failed = skipped = 0
|
|
verdicts = {}
|
|
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)
|
|
verdicts[c.index] = result
|
|
if result is None:
|
|
skipped += 1
|
|
elif result:
|
|
passed += 1
|
|
else:
|
|
failed += 1
|
|
print(f" work dir kept: {work}")
|
|
break
|
|
return passed, failed, skipped, 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")
|
|
ap.add_argument("--show", action="store_true")
|
|
ap.add_argument("--formats", default=",".join(FORMATS))
|
|
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("--self-test", action="store_true")
|
|
a = ap.parse_args()
|
|
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()]
|
|
unknown = [f for f in formats if f not in FORMATS]
|
|
if unknown:
|
|
print(f"unknown format(s): {', '.join(unknown)}; known: {', '.join(FORMATS)}", file=sys.stderr)
|
|
return 2
|
|
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
|
|
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)
|
|
work = a.work or tempfile.mkdtemp(prefix="image_fuzz_")
|
|
os.makedirs(work, exist_ok=True)
|
|
code = 0
|
|
verdicts = {}
|
|
try:
|
|
if "translator" in backends:
|
|
passed, failed, skipped, 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"
|
|
print("translator: " + summary)
|
|
code = 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"image_load 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"}.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 = 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())
|