Skip to content
Closed
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
162 changes: 161 additions & 1 deletion tests/test_crosslane_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,8 @@ def translate(work, emulate):
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.object(X, "assemble", side_effect=lambda mc, p, *a: names.append(p.name)), \
with mock.patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": ""}), \
mock.patch.object(X, "assemble", side_effect=lambda mc, p, *a: names.append(p.name)), \
mock.patch.object(X, "translate", side_effect=translate), \
mock.patch.object(X, "run_gpu", side_effect=run_gpu), \
mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", exe] + argv), \
Expand Down Expand Up @@ -945,5 +946,164 @@ def test_native_kernel_has_a_label_for_every_loop(self):
self.assertGreater(loops, 10)


class PcTailUbo(unittest.TestCase):
"""--pc-tail-ubo and LEONIDA_PC_TAIL_UBO forward the 128-byte push-constant layout to both translator and harness."""

def test_translate_forwards_pc_tail_ubo(self):
cmds = []

def fake_run(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_run):
X.translate(work, False)
X.translate(work, False, pc_tail=True)
X.translate(work, True, pc_tail=True)
self.assertNotIn("--pc-tail-ubo", cmds[0])
self.assertIn("--pc-tail-ubo", cmds[1])
self.assertNotIn("--wave64-emulate", cmds[1])
self.assertIn("--pc-tail-ubo", cmds[2])
self.assertIn("--wave64-emulate", cmds[2])

def test_gpu_env_and_run_gpu_set_pc_tail_env(self):
prog = X.make_program(1, 32, 4)
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")
self.assertEqual(
X.gpu_env(prog, False, "d.bin", base={"LEONIDA_PC_TAIL_UBO": "0"}, pc_tail=True)["LEONIDA_PC_TAIL_UBO"],
"1",
)

seen_envs = []

def fake_run(cmd, **kw):
seen_envs.append(kw["env"])
with open(kw["env"]["VKC_DUMP"], "wb") as f:
f.write(b"\x00" * (4 * prog.group * len(X.OUT_REGS)))
return subprocess.CompletedProcess(cmd, 0, "compute subgroup size: 32\n", "")

with tempfile.TemporaryDirectory() as work, \
mock.patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": ""}), \
mock.patch.object(X.subprocess, "run", side_effect=fake_run):
os.environ.pop("LEONIDA_PC_TAIL_UBO", None)
X.run_gpu("vk_compute_test", "p.spv", prog, work, False)
X.run_gpu("vk_compute_test", "p.spv", prog, work, False, pc_tail=True)
self.assertNotIn("LEONIDA_PC_TAIL_UBO", seen_envs[0])
self.assertEqual(seen_envs[1]["LEONIDA_PC_TAIL_UBO"], "1")

def test_main_enables_pc_tail_ubo_from_flag_or_env(self):
cases = (
([], "", False),
(["--pc-tail-ubo"], "", True),
([], "1", True),
([], "true", True),
([], " YES ", True),
([], "on", True),
([], "0", False),
(["--pc-tail-ubo"], "0", True),
)
for extra, env_val, want in cases:
with self.subTest(extra=extra, env_val=env_val):
names, seen_t, seen_g = [], [], []

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 HarnessErrors._expected_words(prog)

out = io.StringIO()
with tempfile.TemporaryDirectory() as build:
exe = os.path.join(build, "vk_compute_test.exe")
open(exe, "wb").close()
with mock.patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": env_val}), \
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(X.mc_command, "mc_command", return_value=["llvm-mc"]), \
mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", exe,
"--programs", "1", "--wave", "32",
"--modes", "native", "--no-maskdata"] + extra), \
contextlib.redirect_stdout(out):
code = X.main()
self.assertEqual(code, 0, out.getvalue())
self.assertEqual(seen_t, [want])
self.assertEqual(seen_g, [want])

def test_minimize_and_still_fails_forward_pc_tail_ubo(self):
prog = X.make_program(1, 32, 2, allow_maskdata=False)
for ctx, want in (((["llvm-mc"], "vk_compute_test"), False),
((["llvm-mc"], "vk_compute_test", True), True)):
with self.subTest(want=want):
seen_t, seen_g = [], []

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)
open(os.path.join(spdir, prog.name + ".spv"), "wb").close()
return spdir, ""

def fake_run_gpu(exe, spv, p, work, emulate, pc_tail=False):
seen_g.append(pc_tail)
words = HarnessErrors._expected_words(p)
words[0] ^= 1
return words

with mock.patch.object(X, "assemble"), \
mock.patch.object(X, "translate", side_effect=fake_translate), \
mock.patch.object(X, "run_gpu", side_effect=fake_run_gpu):
self.assertTrue(X.still_fails(prog, prog.ops, "native", ctx))
self.assertEqual(seen_t, [want])
self.assertEqual(seen_g, [want])

# Also verify main() threads --pc-tail-ubo into minimize() on a mismatch.
names, min_ctxs = [], []

def fake_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:
open(os.path.join(spdir, name + ".spv"), "wb").close()
return spdir, ""

def fake_run_gpu(exe, spv, p, work, emulate, pc_tail=False):
words = HarnessErrors._expected_words(p)
words[0] ^= 1
return words

def fake_minimize(p, mode, ctx):
min_ctxs.append(ctx)
return p.ops

out = io.StringIO()
with tempfile.TemporaryDirectory() as build:
exe = os.path.join(build, "vk_compute_test.exe")
open(exe, "wb").close()
with mock.patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": ""}), \
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(X, "minimize", side_effect=fake_minimize), \
mock.patch.object(X.mc_command, "mc_command", return_value=["llvm-mc"]), \
mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", exe,
"--programs", "1", "--wave", "32", "--ops", "2",
"--modes", "native", "--no-maskdata",
"--pc-tail-ubo", "--minimize"]), \
contextlib.redirect_stdout(out):
code = X.main()
self.assertEqual(code, 1)
self.assertEqual(len(min_ctxs), 1)
self.assertEqual(len(min_ctxs[0]), 3)
self.assertTrue(min_ctxs[0][2])


if __name__ == "__main__":
unittest.main()
45 changes: 35 additions & 10 deletions tools/crosslane_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -1305,23 +1305,32 @@ 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)."""
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 pc_tail:
env["LEONIDA_PC_TAIL_UBO"] = "1"
if prog.wave == 32 or emulate:
env["VKC_SUBGROUP_SIZE"] = "32"
return env
Expand All @@ -1340,11 +1349,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 +1405,27 @@ def minimize(prog, mode, ctx):


def still_fails(prog, ops, mode, ctx):
mc, exe = ctx
if len(ctx) == 3:
mc, exe, pc_tail = ctx
else:
mc, exe = ctx
pc_tail = False
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=True)
if pc_tail else translate(work, mode == "emulate"))
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)
got = (run_gpu(exe, spv, prog, work, mode == "emulate", pc_tail=True)
if pc_tail else run_gpu(exe, spv, prog, work, mode == "emulate"))
bad, hyp = compare(prog, got, 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 +1496,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 +1588,8 @@ 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))
ctx = (mc, args.exe, True) if args.pc_tail_ubo else (mc, args.exe)
ops = minimize(p, mode, ctx)
else:
continue
hyp_ops = p.expected(ops)[1]
Expand Down Expand Up @@ -1675,6 +1696,7 @@ def fails_with(ops):


def run_translator(args, mc, progs, waves, modes, stats, fails):
pc_tail = bool(getattr(args, "pc_tail_ubo", False))
with tempfile.TemporaryDirectory(prefix="crosslane-") as work:
disasm, fssm = os.path.join(work, "disasm"), os.path.join(work, "fssm")
os.mkdir(disasm)
Expand All @@ -1684,7 +1706,8 @@ 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=True)
if pc_tail else translate(work, mode == "emulate"))
for p in progs:
if mode == "emulate" and p.wave != 64:
continue
Expand All @@ -1700,7 +1723,9 @@ 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"))
got = (run_gpu(args.exe, spv, p, work, mode == "emulate", pc_tail=True)
if pc_tail else run_gpu(args.exe, spv, p, work, mode == "emulate"))
bad, hyp = compare(p, got)
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