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
20 changes: 17 additions & 3 deletions runtime/test/shaders/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def not_found_message(build, missing):
CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800]
CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c]
WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2")
# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is.
WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap")
CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM),
# SHADER-52: wave32 lane select is & 31; lane 40 wraps to 8
("cs_w32_lane_wrap", [25, 16, 777, 777]),
Expand Down Expand Up @@ -245,8 +248,17 @@ def partial_wave_test(tools, spirv, name, expected_words):
return failure(code, out, 2)


def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None):
"""Return an empty string for a pass, None for unsupported wave64, or a failure diagnostic."""
def narrow_subgroup_skip(out):
"""A Skip when vk_compute_test's "device: ... (subgroup MIN..MAX)" line says MAX is below 32 lanes, else None."""
m = re.search(r"subgroup \d+\.\.(\d+)", out)
if m and int(m.group(1)) < 32:
return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)")
return None


def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False):
"""Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device
narrower than 32 lanes (needs_32_lanes), or a failure diagnostic."""
shader = os.path.join(spirv, name + ".spv")
args = []
if require_wave64:
Expand All @@ -256,6 +268,8 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe
code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, groups, mode, *args)
if require_wave64 and code == 77: # vk_compute_test: the device cannot run a 64-wide compute subgroup
return None
if needs_32_lanes and (skip := narrow_subgroup_skip(out)):
return skip
if code != 0:
return failure(code, out, 2)
if require_wave64 and "compute subgroup size: 64" not in out.splitlines():
Expand Down Expand Up @@ -532,7 +546,7 @@ def main():
for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated
results.append((name, compute_test(tools, spirv, name, "1", "dump",
require_wave64=name not in WAVE32_DUMPS and not W64_EMULATED,
expected_words=want)))
expected_words=want, needs_32_lanes=name in WAVE32_LANE_DUMPS)))
for name, want in BOUNDS:
results.append((name, compute_test(tools, spirv, name, "1", "dump", expected_words=want)))
results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump",
Expand Down
9 changes: 7 additions & 2 deletions scripts/run_gpu_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from check import (CMPX_CLASS_WORDS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, Skip,
mesh_v5_test, not_found_message, pick_build_dir, start_failure, texture_mip_test)
from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
from check import WAVE32_LANE_DUMPS, narrow_subgroup_skip # wave32 lane-mask dumps skip below 32 lanes, as in check.py


def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes:
Expand Down Expand Up @@ -697,8 +698,12 @@ def run_suite(a, work: str) -> int:
if partial and not emulated:
cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64")
rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env)
ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated,
hexwords=name in ("cs_store", "cs_smem_soffset_imm"))
skip = narrow_subgroup_skip(msg) if name in WAVE32_LANE_DUMPS else None
if skip: # e.g. Mesa llvmpipe's 8-wide subgroups: these 32-lane masks can't come out right
ok, detail = None, str(skip)
else:
ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated,
hexwords=name in ("cs_store", "cs_smem_soffset_imm"))
results.append((name, ok, detail))
elif name == "cs_imgstore":
rc, msg = run_cmd([vk_store, spv])
Expand Down
117 changes: 117 additions & 0 deletions tests/semantic/test_alu_lerp_u8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
"""Semantic interpreter tests for RDNA2 v_lerp_u8.

Per byte i: D.byte[i] = (S0.byte[i] + S1.byte[i] + (bit 0 of S2.byte[i])) >> 1, an unsigned average of the two
bytes whose rounding (down or up) comes from S2 (RDNA ISA pseudocode). Each case translates a synthetic pixel shader
with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python
reference. D leaves through exp as two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or
denormal pattern that a float round trip could change.
"""
import os
import random
import struct
import sys
import tempfile
import unittest
import warnings

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")

sys.dont_write_bytecode = True
sys.path.insert(0, TOOLS_DIR)
sys.path.insert(0, HERE)

import rdna2spirv # noqa: E402
import spirv_mini_interp as si # noqa: E402

STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)


def ref(x: int, y: int, z: int) -> int:
out = 0
for i in range(4):
b = lambda v: (v >> (8 * i)) & 0xFF # noqa: E731
out |= ((b(x) + b(y) + (b(z) & 1)) >> 1) << (8 * i)
return out


VALUES = [0, 0xFFFFFFFF, 0x01010101, 0xFF00FF00, 0x00FF00FF, 0x80808080, 0x7F7F7F7F, 0x12345678, 0xFEDCBA98]
ROUND = [0, 0xFFFFFFFF, 0x01010101, 0x01000100, 0xFEFEFEFE]

_TMP_DIR = None
_SRC_PATH = None


def setUpModule():
global _TMP_DIR, _SRC_PATH
_TMP_DIR = tempfile.TemporaryDirectory()
disasm_dir = os.path.join(_TMP_DIR.name, "disasm")
os.mkdir(disasm_dir)
_SRC_PATH = os.path.join(disasm_dir, "ps_lerp_u8.s")
with open(os.path.join(_TMP_DIR.name, "ps_lerp_u8.dxbc"), "wb") as f:
f.write(STUB_DXBC)


def tearDownModule():
global _TMP_DIR
if _TMP_DIR is not None:
_TMP_DIR.cleanup()
_TMP_DIR = None


def run_lines(lines) -> int:
"""Run the lines, return v0 (exported as two 16-bit halves, see the module docstring)."""
if _TMP_DIR is None:
setUpModule()
lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0",
"v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"]
asm = "; test_lerp_u8\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n"
with open(_SRC_PATH, "w", encoding="utf-8") as f:
f.write(asm)
with warnings.catch_warnings():
warnings.simplefilter("ignore", ResourceWarning)
spv = rdna2spirv.translate(_SRC_PATH)
lo, hi = si.run_fragment(spv)["%out_mrt0"][:2]
assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi))
return (lo & 0xFFFF) | (hi & 0xFFFF) << 16


def run_op(x: int, y: int, z: int) -> int:
return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"v_mov_b32 v3, {z:#x}",
"v_lerp_u8 v0, v1, v2, v3"])


class LerpU8Tests(unittest.TestCase):
def test_reference(self):
self.assertEqual(ref(0xFF, 0xFF, 1), 0xFF) # 511 >> 1: never carries into byte 1
self.assertEqual(ref(0x01, 0x02, 0), 0x01) # 3 >> 1, rounded down
self.assertEqual(ref(0x01, 0x02, 1), 0x02) # rounded up by S2's bit 0
self.assertEqual(ref(0x00000300, 0x00000400, 0x00000100), 0x00000400)
self.assertEqual(ref(0x01, 0x02, 0xFE), 0x01) # only bit 0 of S2's byte counts

def test_edge_values(self):
for x in VALUES:
for y in VALUES:
for z in ROUND:
with self.subTest(x=hex(x), y=hex(y), z=hex(z)):
self.assertEqual(run_op(x, y, z), ref(x, y, z))

def test_seeded(self):
rng = random.Random(0x1E8)
for _ in range(40):
x, y, z = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32)
with self.subTest(x=hex(x), y=hex(y), z=hex(z)):
self.assertEqual(run_op(x, y, z), ref(x, y, z))

def test_scalar_and_inline_operands(self):
self.assertEqual(run_lines(["s_mov_b32 s2, 0x10203040", "v_mov_b32 v1, 0x30405060", "v_lerp_u8 v0, s2, v1, 1"]),
ref(0x10203040, 0x30405060, 1))

def test_clamp_is_rejected_not_guessed(self):
with self.assertRaises(rdna2spirv.Unsupported):
run_lines(["v_mov_b32 v1, 1", "v_lerp_u8 v0, v1, v1, v1 clamp"])


if __name__ == "__main__":
unittest.main()
16 changes: 16 additions & 0 deletions tests/test_run_gpu_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,21 @@ def test_set_bit_without_8_fails(self):
self.assertFalse(self.judge([(7, 1, 0.5), (8, 0, 0.1), (7, 0, 0.1)])[0])


class Wave32LaneDumps(unittest.TestCase):
"""run_gpu_tests.py skips cs_wqm_w32 and cs_w32_lane_wrap below 32 lanes with check.py's rule."""
def test_uses_check_py_rule(self):
import check
self.assertIs(rgt.narrow_subgroup_skip, check.narrow_subgroup_skip)
self.assertEqual(rgt.WAVE32_LANE_DUMPS, ("cs_wqm_w32", "cs_w32_lane_wrap"))

def test_rule(self):
self.assertEqual(rgt.narrow_subgroup_skip("device: llvmpipe (subgroup 8..8)\n"),
"SKIP (subgroup 8 is narrower than 32 lanes)")
for out in ("device: X (subgroup 32..32)\n", "device: X (subgroup 8..32)\n", "device: X (subgroup 32..64)\n",
"no device line\n"):
with self.subTest(out=out):
self.assertIsNone(rgt.narrow_subgroup_skip(out))


if __name__ == "__main__":
unittest.main()
45 changes: 45 additions & 0 deletions tests/test_shader_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,5 +348,50 @@ def test_device_without_maintenance8_is_a_skip(self):
self.assertEqual(result, "SKIP (unsupported: VK_KHR_maintenance8 (non-constant texel Offset))")


class Wave32LaneDumps(unittest.TestCase):
"""cs_wqm_w32 and cs_w32_lane_wrap need 32 lanes: skipped where the widest subgroup is narrower (llvmpipe: 8)."""
def run_dump(self, name, code, out):
want = dict(check.CS_DUMPS)[name]
with patch.object(check, "run", return_value=(code, out)):
return check.compute_test("tools", "spirv", name, "1", "dump", expected_words=want,
needs_32_lanes=name in check.WAVE32_LANE_DUMPS)

@staticmethod
def words(name, flip=False):
w = list(dict(check.CS_DUMPS)[name])
if flip:
w[0] ^= 1
return "out[0..7] = " + " ".join(map(str, (w + [0] * 8)[:8])) + "\n"

def test_lane_dumps_are_wave32_dumps(self):
self.assertTrue(set(check.WAVE32_LANE_DUMPS) <= set(check.WAVE32_DUMPS))
self.assertTrue(set(check.WAVE32_LANE_DUMPS) <= set(dict(check.CS_DUMPS)))

def test_skipped_below_32_lanes_whatever_the_words(self):
for name in check.WAVE32_LANE_DUMPS:
for flip in (False, True):
with self.subTest(name=name, flip=flip):
problem = self.run_dump(name, 0, "device: llvmpipe (subgroup 8..8)\n" + self.words(name, flip))
self.assertIsInstance(problem, check.Skip)
self.assertEqual(problem, "SKIP (subgroup 8 is narrower than 32 lanes)")

def test_judged_on_32_lanes_and_wider(self):
for name in check.WAVE32_LANE_DUMPS:
for dev in ("device: gpu (subgroup 32..32)\n", "device: gpu (subgroup 32..64)\n",
"device: gpu (subgroup 8..32)\n", ""):
with self.subTest(name=name, dev=dev):
self.assertEqual(self.run_dump(name, 0, dev + self.words(name)), "")
problem = self.run_dump(name, 0, dev + self.words(name, flip=True))
self.assertTrue(problem)
self.assertNotIsInstance(problem, check.Skip)

def test_other_dumps_are_not_skipped_on_narrow_devices(self):
out = "device: llvmpipe (subgroup 8..8)\nout[0..7] = 1 2 3 4 5 6 7 8\n"
with patch.object(check, "run", return_value=(0, out)):
problem = check.compute_test("tools", "spirv", "cs_store", "1", "dump", expected_words=check.CS_STORE)
self.assertTrue(problem)
self.assertNotIsInstance(problem, check.Skip)


if __name__ == "__main__":
unittest.main()
23 changes: 23 additions & 0 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -2690,6 +2690,29 @@ def f64(sv):
self.emit(f"{r2} = OpIAdd %uint {r} {self.src_u(a[3])}")
r = r2
self.dst(a[0], r)
elif op == "v_lerp_u8":
# Per byte: D.b = (S0.b + S1.b + (bit 0 of S2.b)) >> 1, an unsigned average whose rounding comes from
# S2 (RDNA ISA pseudocode). The 9-bit sum never reaches past its own byte after the shift.
if "clamp" in mods:
raise Unsupported(op + " clamp")
x, y, z = (self.src_u(t) for t in a[1:4])
r = None
for off in (0, 8, 16, 24):
xb, yb, zb, t1, t2, avg = (self.tmp() for _ in range(6))
self.emit(f"{xb} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(8)}")
self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}")
self.emit(f"{zb} = OpBitFieldUExtract %uint {z} {self.cu(off)} {self.cu(1)}")
self.emit(f"{t1} = OpIAdd %uint {xb} {yb}")
self.emit(f"{t2} = OpIAdd %uint {t1} {zb}")
self.emit(f"{avg} = OpShiftRightLogical %uint {t2} {self.cu(1)}")
if r is None:
r = avg
else:
sh, o = self.tmp(), self.tmp()
self.emit(f"{sh} = OpShiftLeftLogical %uint {avg} {self.cu(off)}")
self.emit(f"{o} = OpBitwiseOr %uint {r} {sh}")
r = o
self.dst(a[0], r)
elif op == "v_xnor_b32":
x, y = self.src_u(a[1]), self.src_u(a[2])
t, r = self.tmp(), self.tmp()
Expand Down
Loading