Files
mandy/tools/vk_fuzz_run.py
whoalin1 41c49ee83c vk_fuzz_run: document and cover crash skips across signal exits
VK_FUZZ_SKIP_CRASH treats every vk_compute_test exit outside 0/1/2/77 as a
driver crash skip, including the negative return codes Python uses for signal
deaths on POSIX. Spell that out in the module contract and cover it beside the
Windows access-violation case so exits 1/2 staying fatal is unambiguous.

Co-Authored-By: Devin <noreply@cognition.ai>
2026-11-30 22:27:17 +00:00

255 lines
14 KiB
Python

r"""Run assembled RDNA2 programs through the translator on a real Vulkan GPU (standard library only).
The differential fuzzers that judge the translator in tests/semantic/spirv_mini_interp.py (Python floats and integers)
cannot see what a driver does with the SPIR-V: its denormal, NaN and rounding rules, and what it makes of an input
the SPIR-V leaves undefined. This module runs the same programs on the GPU: llvm-mc assembles each one for gfx1013
as a compute program of one wave (32 or 64 lanes, every lane the same), rdna2spirv.py translates them in one go,
runtime/build/vk_compute_test executes each (LEONIDA_VK_DEVICE picks the device) and lane 0's stored words come back.
results = run_programs(texts, words=4, wave=32, build="runtime/build")
`rewrite=False` leaves the lines as they are (they already spell wave64); `uniform=False` skips the check that every lane gave lane 0's words (programs that seed VCC with data); `per_lane=True` returns every lane's words
(a list of `wave` lists) for programs whose lanes differ, instead of lane 0's. `texts` are the instruction lines of each program (strings, one instruction per line). Each program gets the prologue
(EXEC all ones, the lane id saved in v20) and an epilogue that stores v8..v(8+words-1) of every lane at lane *
words * 4 through the V# in s[0:3]. The result list has, per program, a list of `words` ints (lane 0) or a str: why
there is no result (llvm-mc rejected it, the translator refused it, the device cannot run it, the lanes disagree).
wave64_text() rewrites the wave32 spellings of lane masks (vcc_lo, s20, s21) as the 64-bit ones.
`encoded=True` takes complete synthetic disassembly listings with `; encoding:` byte counts (as generated by
cf_diff), bypassing llvm-mc while keeping the same translation and per-lane Vulkan execution path.
For wave64 on a 32-wide GPU, LEONIDA_W64_EMULATE=1 passes --wave64-emulate to the translator.
LEONIDA_PC_TAIL_UBO=1 translates with rdna2spirv.py --pc-tail-ubo and passes the same variable to vk_compute_test
for 128-byte push-constant devices. VK_FUZZ_SKIP_CRASH=1 records any vk_compute_test exit other than 0, 1, 2 or 77
as a skip, including signal deaths (which Python reports as negative return codes); exits 1 and 2 stay fatal because
they are harness/check failures, not driver crashes.
opaque=True (the default of run_programs) keeps the driver from folding the program: a `v_mov_b32 vN, K` seed becomes
`v_xor_b32 vN, K ^ FILL, vF`, where vF is read from the output buffer, which vk_compute_test fills with 0xEEEEEEEE.
The program computes the same values at run time, but a compiler that sees literal operands folds them itself, and
the AMD Windows driver (26.10.1) folds an ordered compare of a literal NaN to true in a wave32 pipeline, which says
nothing about what the translated shader does with a NaN it is given.
"""
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SHADERS = os.path.join(os.path.dirname(HERE), "runtime", "test", "shaders")
LANE_ID_REG = 20 # v20 holds the lane id for the epilogue; programs must leave it alone
ADDR_REG = 21 # v21 is the store address
def wave64_text(line, masks=("s20", "s21")):
"""The wave32 line with its lane masks as 64-bit pairs: vcc_lo -> vcc, s20 -> s[20:21], s21 -> s[22:23]."""
out = re.sub(r"\bs_mov_b32 vcc_lo, ", "s_mov_b64 vcc, ", line)
out = re.sub(r"\bvcc_lo\b", "vcc", out)
for m in masks:
n = int(m[1:])
base = 20 if n == 20 else 22
out = re.sub(rf"\b{m}\b", f"s[{base}:{base + 1}]", out)
return out
FILL = 0xEEEEEEEE # what vk_compute_test puts in the output buffer before the dispatch
FILL_REG = 22
SEED_RE = re.compile(r"^v_mov_b32(?:_e32)? v(\d+), (0x[0-9a-fA-F]+|\d+)$")
def opaque_seed(line):
"""`v_mov_b32 vN, K` as the same value computed from the buffer fill; other lines unchanged."""
m = SEED_RE.match(line)
if not m or int(m.group(1)) in (LANE_ID_REG, ADDR_REG, FILL_REG):
return line
return f"v_xor_b32_e32 v{m.group(1)}, 0x{(int(m.group(2), 0) & 0xFFFFFFFF) ^ FILL:x}, v{FILL_REG}"
def program_text(name, lines, words, wave, opaque=False, rewrite=True):
"""The compute program: prologue, the lines, the stores."""
head = [f"; {name}", f"; group: {wave},1,1", "; rsrc2: 0x8088"]
if wave == 64:
head.append("; mattr: +wavefrontsize64,-wavefrontsize32")
if rewrite:
lines = [wave64_text(ln) for ln in lines]
out = head + ["s_mov_b64 exec, -1" if wave == 64 else "s_mov_b32 exec_lo, -1", f"v_mov_b32 v{LANE_ID_REG}, v0",
f"v_lshlrev_b32 v{ADDR_REG}, {(4 * words).bit_length() - 1}, v{LANE_ID_REG}"]
if opaque:
out += [f"buffer_load_dword v{FILL_REG}, v{ADDR_REG}, s[0:3], 0 offen", "s_waitcnt vmcnt(0)"]
lines = [opaque_seed(ln) for ln in lines]
out += list(lines)
for k in range(words):
out.append(f"buffer_store_dword v{8 + k}, v{ADDR_REG}, s[0:3], 0 offen" + (f" offset:{4 * k}" if k else ""))
out.append("s_endpgm")
return "\n".join(out) + "\n"
def read_dump(path, words, wave):
"""The `wave` lanes of `words` words each from a VKC_DUMP file, or None when it is missing or too short.
vk_compute_test's output buffer is at least one 64-thread group of words (VKC_OUT_WORDS only raises it), and
VKC_DUMP writes the whole buffer, so a request under 64 words (wave32 with words=1) gives a larger file: only its
first words * wave words are the program's stores, the rest keep the fill."""
need = 4 * words * wave
if not os.path.isfile(path) or os.path.getsize(path) < need:
return None
with open(path, "rb") as f:
flat = struct.unpack(f"<{words * wave}I", f.read(need))
return [list(flat[k:k + words]) for k in range(0, words * wave, words)]
def run_programs(texts, words=4, wave=32, build=None, work_parent=None, retries=2, opaque=True, rewrite=True,
per_lane=False, uniform=True, encoded=False):
"""Per program lane 0's `words` words, or a str (see the module docstring). words must be 1, 2, 4 or 8."""
if words not in (1, 2, 4, 8):
raise ValueError("words must be 1, 2, 4 or 8")
if wave not in (32, 64):
raise ValueError("wave must be 32 or 64")
if SHADERS not in sys.path:
sys.path.insert(0, SHADERS)
import mc_command
from compute_fixture import compute_header, find_test_program, unpinned_subgroup
build = build or os.path.join(os.path.dirname(HERE), "runtime", "build")
folder = find_test_program(build, "vk_compute_test") # the folder holding it (a Visual Studio config subfolder)
if not folder:
raise FileNotFoundError(f"vk_compute_test not found in {build}; build it first "
"(cmake --build <build dir> --target vk_compute_test)")
exe = os.path.join(folder, "vk_compute_test" + (".exe" if os.name == "nt" else ""))
work = tempfile.mkdtemp(prefix="vk_fuzz_", dir=work_parent)
try:
disasm, fssm, spirv = (os.path.join(work, d) for d in ("disasm", "fssm", "spirv"))
for d in (disasm, fssm):
os.mkdir(d)
mc = None # encoded listings are already disassembly: no llvm-mc
if not encoded:
mc = mc_command.mc_command() + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"]
if wave == 64:
mc.append("-mattr=+wavefrontsize64,-wavefrontsize32")
names, results = [], []
for i, lines in enumerate(texts):
name = f"cs_vkfuzz_{i}"
text = lines if encoded else program_text(name, lines, words, wave, opaque, rewrite)
path = os.path.join(work, name + ".asm")
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
if encoded:
code = text
else:
r = mc_command.run(mc, input=text, capture_output=True, text=True)
if r.returncode or "error:" in r.stderr:
names.append(None)
results.append("llvm-mc: " + (r.stderr.strip().splitlines() or ["failed"])[0][:100])
continue
code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith("."))
with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f:
f.write(f"; {name}\n{code}")
with open(os.path.join(fssm, name + ".fssm"), "wb") as f:
f.write(compute_header(path))
names.append(name)
results.append(None)
cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), disasm, "--out", spirv]
emulate = wave == 64 and os.environ.get("LEONIDA_W64_EMULATE") == "1"
if emulate:
cmd.append("--wave64-emulate")
# LEONIDA_PC_TAIL_UBO=1 (the convention the other fuzzers' --pc-tail-ubo flag sets): translate with
# rdna2spirv.py --pc-tail-ubo so the modules fit a device's 128-byte push-constant range; vk_compute_test
# reads the same variable for its own range.
if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"):
cmd.append("--pc-tail-ubo")
translation = subprocess.run(cmd, capture_output=True, text=True)
index = {}
index_path = os.path.join(spirv, "index.json")
if os.path.isfile(index_path):
with open(index_path, encoding="utf-8-sig") as f:
index = json.load(f)
for i, name in enumerate(names):
if name is None:
continue
spv = os.path.join(spirv, name + ".spv")
if name not in index or not os.path.isfile(spv):
reason = translation.stderr.strip().splitlines()
results[i] = "translator: not translated" + (f" ({reason[-1]})" if reason else "")
continue
dump = os.path.join(work, name + ".bin")
env = dict(os.environ, VKC_OUT_WORDS=str(words * wave), VKC_DUMP=dump)
args = [exe, spv, "1", "dump"]
if wave == 64 and not emulate:
args.append("--require-wave64")
else:
env["VKC_SUBGROUP_SIZE"] = "32"
for _ in range(retries + 1):
if os.path.isfile(dump):
os.remove(dump)
r = subprocess.run(args, capture_output=True, text=True, env=env)
if r.returncode in (0, 77):
break
msg = (r.stdout + r.stderr).strip()
# VK_FUZZ_SKIP_CRASH=1: a vk_compute_test that dies (the AMD Windows shader compiler's access
# violation, exit 3221225477, or any other crash code) is recorded as a skip instead of aborting the
# whole batch — the crash is a driver/harness finding, not a result for this program.
skip_crash = (os.environ.get("VK_FUZZ_SKIP_CRASH") or "").strip().lower() in ("1", "true", "yes", "on")
if r.returncode not in (0, 77) and skip_crash and r.returncode not in (1, 2):
results[i] = f"vk_compute_test: crashed (exit {r.returncode})"
continue
if r.returncode not in (0, 77):
detail = f": {msg[-400:]}" if msg else ""
raise RuntimeError(f"{name}: vk_compute_test exit {r.returncode}{detail}")
if r.returncode == 77:
results[i] = "vk_compute_test: " + (msg.splitlines()[-1] if msg else "unsupported")
elif wave == 32 and unpinned_subgroup(msg):
results[i] = f"the device can't run 32-lane subgroups ({unpinned_subgroup(msg)} lanes)"
elif r.returncode:
results[i] = f"vk_compute_test exit {r.returncode}"
elif (lanes := read_dump(dump, words, wave)) is None:
results[i] = f"vk_compute_test: no dump of {4 * words * wave} bytes or more"
else:
odd = [k for k, w in enumerate(lanes) if w != lanes[0]]
if per_lane:
results[i] = lanes
elif not uniform:
results[i] = lanes[0]
else:
results[i] = lanes[0] if not odd else f"lanes {odd[:3]} differ from lane 0 on identical inputs"
return results
finally:
if not os.environ.get("VK_FUZZ_KEEP"):
shutil.rmtree(work, ignore_errors=True)
def judge(progs, hw, verdict, wave=32, words=4, build=None, work_parent=None, opaque=True, uniform=True):
"""Run progs (lists of lines) on the Vulkan GPU and judge each against hw[i] (words, or a str: why there are none)
with verdict(lines, hw_words, got_words) -> (class, detail). Returns ({class: n}, [(i, detail, lines)] for the
class "mismatch")."""
got = run_programs(progs, words, wave, build, work_parent, opaque=opaque, uniform=uniform)
counts, bad = {}, []
for i, lines in enumerate(progs):
if isinstance(hw[i], str) or isinstance(got[i], str):
why = "skip: " + (("hardware: " + hw[i]) if isinstance(hw[i], str) else got[i])
counts[why] = counts.get(why, 0) + 1
continue
klass, detail = verdict(lines, hw[i], got[i])
counts[klass] = counts.get(klass, 0) + 1
if klass == "mismatch":
bad.append((i, detail, lines))
return counts, bad
def all_skipped(counts):
"""True when a Vulkan run compared no program (every entry is a skip, or none ran)."""
return not any(n > 0 and not k.startswith("skip") for k, n in counts.items())
def exact_verdict(lines, hw, got, n_obs=4):
"""match, or mismatch naming the first word that differs (the observation lines end the program)."""
if len(hw) != len(got):
return "mismatch", f"word count differs: hardware {len(hw)}, translated on the GPU {len(got)}"
for k in range(len(hw)):
if hw[k] != got[k]:
obs = lines[-n_obs + k] if k < n_obs and len(lines) >= n_obs else ""
parts = obs.split(", ", 1)
reg = parts[1] if len(parts) == 2 else f"word {k}"
return "mismatch", f"word {k} ({reg}): hardware 0x{hw[k]:08x}, translated on the GPU 0x{got[k]:08x}"
return "match", ""