Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 73 additions & 5 deletions tests/test_crosslane_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,74 @@ def test_buffer_size_and_dump(self):
str(max(len(X.OUT_REGS), 64)))


class PcTailUbo(unittest.TestCase):
"""--pc-tail-ubo (or LEONIDA_PC_TAIL_UBO) translates with rdna2spirv.py --pc-tail-ubo and runs vk_compute_test
with LEONIDA_PC_TAIL_UBO=1, as lds_fuzz.py and valu_fuzz.py do (128-byte push constants, e.g. AMD iGPUs)."""

def test_translate_forwards_the_flag(self):
cmds = []

def fake(cmd, **kw):
cmds.append(list(cmd))
return subprocess.CompletedProcess(cmd, 0, "", "")

with tempfile.TemporaryDirectory() as work, \
mock.patch.object(X.subprocess, "run", side_effect=fake):
X.translate(work, False)
X.translate(work, False, pc_tail=True)
self.assertNotIn("--pc-tail-ubo", cmds[0])
self.assertIn("--pc-tail-ubo", cmds[1])

def test_gpu_env_sets_the_harness_variable(self):
prog = X.Program("p", 32, 64, [], {}, [])
self.assertNotIn("LEONIDA_PC_TAIL_UBO", X.gpu_env(prog, False, "d.bin", base={}))
self.assertEqual(X.gpu_env(prog, False, "d.bin", base={}, pc_tail=True)["LEONIDA_PC_TAIL_UBO"], "1")

def test_flag_or_env_turns_it_on(self):
seen_t, seen_g, names = [], [], []

def fake_translate(work, emulate, pc_tail=False):
seen_t.append(pc_tail)
spdir = os.path.join(work, "spirv_emu" if emulate else "spirv_nat")
os.makedirs(spdir, exist_ok=True)
for name in names:
open(os.path.join(spdir, name + ".spv"), "wb").close()
return spdir, ""

def fake_run_gpu(exe, spv, prog, work, emulate, pc_tail=False):
seen_g.append(pc_tail)
return [0] * (prog.group * len(X.OUT_REGS))

for extra, env_val, want in (
([], "", False),
(["--pc-tail-ubo"], "", True),
([], "1", True),
([], "yes", True),
([], "0", False),
):
with self.subTest(extra=extra, env_val=env_val):
seen_t.clear()
seen_g.clear()
names.clear()
env = {k: v for k, v in os.environ.items() if k != "LEONIDA_PC_TAIL_UBO"}
if env_val:
env["LEONIDA_PC_TAIL_UBO"] = env_val
with tempfile.TemporaryDirectory() as build:
exe = os.path.join(build, "vk_compute_test.exe") # only has to exist: run_gpu is replaced
open(exe, "wb").close()
with mock.patch.dict(os.environ, env, clear=True), \
mock.patch.object(X, "assemble", side_effect=lambda mc, p, *a: names.append(p.name)), \
mock.patch.object(X, "translate", side_effect=fake_translate), \
mock.patch.object(X, "run_gpu", side_effect=fake_run_gpu), \
mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", exe, "--programs", "1",
"--wave", "32", "--modes", "native", "--no-maskdata",
*extra]), \
contextlib.redirect_stdout(io.StringIO()):
X.main()
self.assertEqual(seen_t, [want])
self.assertEqual(seen_g, [want])


class UnpinnedSubgroup(unittest.TestCase):
"""A wave32 run vk_compute_test couldn't pin to 32 lanes is a skip; an emulated wave64 one is still compared."""

Expand Down Expand Up @@ -597,7 +665,7 @@ def test_missing_dump_is_a_harness_error_with_the_exit_code(self):

def _main(self, run_gpu, argv):
"""main() with the assembler, translator and GPU replaced: every program 'translates'."""
def translate(work, emulate):
def translate(work, emulate, pc_tail=False):
spdir = os.path.join(work, "spirv_emu" if emulate else "spirv_nat")
os.makedirs(spdir, exist_ok=True)
for name in names:
Expand Down Expand Up @@ -628,7 +696,7 @@ def _expected_words(prog):
def test_run_goes_on_after_a_hang_and_exits_2(self):
calls = []

def run_gpu(exe, spv, prog, work, emulate):
def run_gpu(exe, spv, prog, work, emulate, pc_tail=False):
calls.append(prog.name)
if len(calls) == 2:
raise X.HarnessError("vk_compute_test timed out after 60 s")
Expand All @@ -645,7 +713,7 @@ def run_gpu(exe, spv, prog, work, emulate):
self.assertEqual(kept, [f"{calls[1]}_native.asm"])

def test_every_program_skipped_exits_2(self):
def run_gpu(exe, spv, prog, work, emulate):
def run_gpu(exe, spv, prog, work, emulate, pc_tail=False):
raise X.Unpinned("the device can't run it at 32 lanes")

code, out = self._main(run_gpu, ["--programs", "4", "--wave", "32", "--modes", "native"])
Expand All @@ -655,7 +723,7 @@ def run_gpu(exe, spv, prog, work, emulate):
self.assertNotIn("mismatch;", out)

def test_skips_beside_matches_exit_0(self):
def run_gpu(exe, spv, prog, work, emulate):
def run_gpu(exe, spv, prog, work, emulate, pc_tail=False):
if prog.wave == 32:
raise X.Unpinned("the device can't run it at 32 lanes")
return self._expected_words(prog)
Expand All @@ -667,7 +735,7 @@ def run_gpu(exe, spv, prog, work, emulate):
self.assertIn("wave64 emulate: programs 2, match 2", out)

def test_clean_run_still_exits_0(self):
code, out = self._main(lambda exe, spv, prog, work, emulate: self._expected_words(prog),
code, out = self._main(lambda exe, spv, prog, work, emulate, pc_tail=False: self._expected_words(prog),
["--programs", "3", "--wave", "32", "--modes", "native", "--no-maskdata"])
self.assertEqual(code, 0)
self.assertIn("match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 0", out)
Expand Down
38 changes: 27 additions & 11 deletions tools/crosslane_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -1305,25 +1305,36 @@ def resolve_branches(cmd, prog, src):
return "\n".join(branch_offsets(lines, dict(zip(insns, sizes)))) + "\n"


def translate(work, emulate):
def pc_tail_env():
"""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, emulate, pc_tail=False):
out = os.path.join(work, "spirv_emu" if emulate else "spirv_nat")
cmd = [sys.executable, "-I", TRANSLATOR[0], os.path.join(work, "disasm"), "--out", out]
if emulate:
cmd.append("--wave64-emulate")
if pc_tail:
cmd.append("--pc-tail-ubo")
r = subprocess.run(cmd, capture_output=True, text=True)
return out, r.stdout + r.stderr


def gpu_env(prog, emulate, dump, base=None):
def gpu_env(prog, emulate, dump, base=None, pc_tail=False):
"""vk_compute_test's environment (FUZZ-6, tools/lds_fuzz.py): VKC_OUT_WORDS sizes the buffer, VKC_DUMP gets its
raw bytes. A wave32 program, or a wave64 one translated with --wave64-emulate, is written for 32-wide subgroups,
so it asks for them with VKC_SUBGROUP_SIZE=32, as lds_fuzz.py and valu_fuzz.py do (FUZZ-13): on AMD, whose
compute default is 64, a group over 32 would otherwise run as one 64-wide subgroup and mismatch in wave 1.
A native wave64 program keeps the device default (--w64-native runs it on whatever the GPU has)."""
A native wave64 program keeps the device default (--w64-native runs it on whatever the GPU has).
pc_tail runs a --pc-tail-ubo translation, so the harness needs LEONIDA_PC_TAIL_UBO=1 too (the UBO tail layout is
baked into the SPIR-V; without it vk_compute_test reports every word as the anti-fold fill)."""
env = dict(os.environ if base is None else base, VKC_OUT_WORDS=str(max(prog.group * len(OUT_REGS), 64)),
VKC_DUMP=dump)
if prog.wave == 32 or emulate:
env["VKC_SUBGROUP_SIZE"] = "32"
if pc_tail:
env["LEONIDA_PC_TAIL_UBO"] = "1"
return env


Expand All @@ -1340,11 +1351,11 @@ class Unpinned(RuntimeError):
GPU_TIMEOUT = 60 # seconds for one program; a translated program that never ends shows up as this


def run_gpu(exe, spv, prog, work, emulate):
def run_gpu(exe, spv, prog, work, emulate, pc_tail=False):
dump = os.path.join(work, "dump.bin")
if os.path.exists(dump):
os.remove(dump) # never compare a stale dump
env = gpu_env(prog, emulate, dump)
env = gpu_env(prog, emulate, dump, pc_tail=pc_tail)
try:
r = subprocess.run([exe, spv, "1", "dump"], capture_output=True, text=True, env=env, timeout=GPU_TIMEOUT)
except subprocess.TimeoutExpired:
Expand Down Expand Up @@ -1396,20 +1407,20 @@ def minimize(prog, mode, ctx):


def still_fails(prog, ops, mode, ctx):
mc, exe = ctx
mc, exe, pc_tail = ctx
with tempfile.TemporaryDirectory(prefix="xlmin-") as work:
for d in ("disasm", "fssm"):
os.mkdir(os.path.join(work, d))
try:
assemble(mc, prog, prog.source(ops), os.path.join(work, "disasm"), os.path.join(work, "fssm"))
except RuntimeError:
return False
spdir, _ = translate(work, mode == "emulate")
spdir, _ = translate(work, mode == "emulate", pc_tail=pc_tail)
spv = os.path.join(spdir, prog.name + ".spv")
if not os.path.exists(spv):
return False
try:
bad, hyp = compare(prog, run_gpu(exe, spv, prog, work, mode == "emulate"), ops)
bad, hyp = compare(prog, run_gpu(exe, spv, prog, work, mode == "emulate", pc_tail=pc_tail), ops)
except (HarnessError, Unpinned):
return False # a reduction that hangs or crashes is not the mismatch being reduced
return bool(bad) and not hyp
Expand Down Expand Up @@ -1480,8 +1491,12 @@ def main():
ap.add_argument("--no-hw-guard", action="store_true",
help="no s_nop 7 after each instruction in the native kernels (hazards then show up as mismatches)")
ap.add_argument("--translator", help="rdna2spirv.py to test (default: the one next to this file)")
ap.add_argument("--pc-tail-ubo", action="store_true",
help="translate with --pc-tail-ubo and run vk_compute_test with LEONIDA_PC_TAIL_UBO=1 "
"(128-byte push constants; also set by LEONIDA_PC_TAIL_UBO=1)")
ap.add_argument("--self-test", action="store_true")
args = ap.parse_args()
args.pc_tail_ubo = args.pc_tail_ubo or pc_tail_env()
if not os.path.isfile(args.exe): # a Visual Studio build puts it in a configuration subfolder
folder, name = os.path.split(args.exe)
for config in ("RelWithDebInfo", "Release"):
Expand Down Expand Up @@ -1568,7 +1583,7 @@ def main():
if mode == "hw":
ops = minimize_hw(p, oracle, not args.no_hw_guard)
elif mc is not None:
ops = minimize(p, mode, (mc, args.exe))
ops = minimize(p, mode, (mc, args.exe, args.pc_tail_ubo))
else:
continue
hyp_ops = p.expected(ops)[1]
Expand Down Expand Up @@ -1684,7 +1699,7 @@ def run_translator(args, mc, progs, waves, modes, stats, fails):
for mode in modes:
if mode == "emulate" and 64 not in waves:
continue
spdir, log = translate(work, mode == "emulate")
spdir, log = translate(work, mode == "emulate", pc_tail=args.pc_tail_ubo)
for p in progs:
if mode == "emulate" and p.wave != 64:
continue
Expand All @@ -1700,7 +1715,8 @@ def run_translator(args, mc, progs, waves, modes, stats, fails):
fails.append((p, mode, "not translated", None))
continue
try:
bad, hyp = compare(p, run_gpu(args.exe, spv, p, work, mode == "emulate"))
bad, hyp = compare(p, run_gpu(args.exe, spv, p, work, mode == "emulate",
pc_tail=args.pc_tail_ubo))
except HarnessError as e:
# One program that hangs or crashes the harness used to end the run with a traceback and
# lose every result before it. It is reported like the other failures and the run goes on.
Expand Down
Loading