upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/bench_wave64.py
blob: 3872c7b37156e159fa36f7a616759b14518b370e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""Time a wave64 compute shader (runtime/test/shaders/cs_bench_mix.asm) on AMD/NVIDIA or the current Vulkan device.

    python -I scripts/bench_wave64.py [--build DIR] [--llvm-mc PATH] [--groups N] [--reps N] [--procs N]
        [--shader NAME] [--emulated-only]

Three configurations: AMD with its native 64-wide subgroup (no flag), AMD with --wave64-emulate, NVIDIA with
--wave64-emulate (the GPU is chosen with VK_LOADER_DRIVERS_SELECT='*amd*,*radeon*' / '*nv*'). Each runs `procs` processes of
vk_compute_test with VKC_BENCH=`reps` timed dispatches of `groups` workgroups; the table gives the median over all
dispatches, the spread of the per-process medians (other programs share the GPU, so look at it), the number of
translated segments (static: blocks + continuation segments; every continuation segment is one more workgroup barrier
on the path through it) and whether the output bytes of the emulated runs equal the native AMD run, which is the reference (they must).

With --emulated-only, run one emulated configuration on the current Vulkan device. This is for a machine without a
native 64-wide subgroup, such as Apple Silicon. Every process must complete the shader's self-check and return the same
output hash; there is deliberately no claim that the hash was compared with a native Wave64 device.
"""
import argparse
import os
import re
import statistics
import subprocess
import sys
import tempfile

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders")
BUILD_PY = os.path.join(SHADER_DIR, "build.py")
sys.path.insert(0, SHADER_DIR)
from check import EXE, pick_build_dir  # noqa: E402

COMPUTE_TEST = "vk_compute_test" + EXE
CONFIGS = [("AMD native", "*amd*,*radeon*", False), ("AMD --wave64-emulate", "*amd*,*radeon*", True),
           ("NVIDIA --wave64-emulate", "*nv*", True)]
EMULATED_ONLY_CONFIG = ("Current device --wave64-emulate", None, True)


def build(work, name, emulate, llvm_mc):
    out = os.path.join(work, "emu" if emulate else "native")
    env = dict(os.environ, LLVM_MC=llvm_mc)
    env.pop("LEONIDA_W64_EMULATE", None)
    if emulate:
        env["LEONIDA_W64_EMULATE"] = "1"
    r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True)
    if r.returncode:
        sys.exit(r.stdout + r.stderr)
    spv = os.path.join(out, "spirv", name + ".spv")
    if not os.path.isfile(spv):
        mode = "emulated" if emulate else "native"
        message = f"{name}: {mode} build did not produce a SPIR-V module"
        reason = (r.stdout + r.stderr).strip()
        sys.exit(f"{message}\n{reason}" if reason else message)
    return spv


def segments(spv: str) -> tuple[int, int] | None:
    """Count scheduler cases and continuations, including inner switches in a partitioned dispatch."""
    with open(spv[:-4] + ".spvasm", encoding="utf-8") as source:
        text = source.read()
    tables = re.findall(r"^[ \t]*OpSwitch %pcv %(?:sw_default|swm\d+) ([^\n]+)", text, re.MULTILINE)
    if not tables:
        return None
    cases = sorted(int(case) for table in tables for case in re.findall(r"(\d+) %blk\d+", table))
    blocks = next((i for i, c in enumerate(cases) if c != i), len(cases))   # blocks 0..n-1, then "done" = n, then segments
    return len(cases), len(cases) - blocks


def run(tools, spv, groups, reps, driver, emulate):
    env = dict(os.environ, VKC_BENCH=str(reps))
    if driver is not None:
        env["VK_LOADER_DRIVERS_SELECT"] = driver
    args = [os.path.join(tools, COMPUTE_TEST), spv, str(groups), "dump"]
    if not emulate:
        args.append("--require-wave64")
    try:
        r = subprocess.run(args, env=env, capture_output=True, text=True)
    except OSError as e:
        return None, f"{args[0]}: {e}", None
    out = r.stdout + r.stderr
    m = re.search(r"bench ms: median=([\d.]+) min=([\d.]+) max=([\d.]+)", out)
    h = re.search(r"bench out fnv1a: (\w+)", out)
    dev = re.search(r"device: (.*) \(subgroup", out)
    if r.returncode or not m or not h or "0 mismatches" not in out:
        why = f"exit {r.returncode}" if r.returncode else "no 'bench ms' / 'bench out fnv1a' line (rebuild vk_compute_test)"
        return None, why + ": " + (out.strip().splitlines()[-1:] or ["no output"])[0], None
    return (float(m.group(1)), float(m.group(2))), h.group(1), dev.group(1) if dev else "?"


def positive_int(text):
    value = int(text)
    if value <= 0:
        raise argparse.ArgumentTypeError(f"must be a positive integer, got {text!r}")
    return value


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
                    help="CMake build directory or a configuration directory such as RelWithDebInfo")
    # Empty means unset to build.py: mc_command() then finds llvm-mc on PATH or a versioned llvm-mc-<N>.
    ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", ""))
    # Vulkan guarantees support for at least 65,535 groups along X in one dispatch.
    ap.add_argument("--groups", type=positive_int, default=65535)
    ap.add_argument("--reps", type=positive_int, default=30)
    ap.add_argument("--procs", type=positive_int, default=5)
    ap.add_argument("--shader", default="cs_bench_mix")
    ap.add_argument("--emulated-only", action="store_true",
                    help="benchmark Wave64 emulation on the current device without requiring a native AMD reference")
    a = ap.parse_args()
    configs = [EMULATED_ONLY_CONFIG] if a.emulated_only else CONFIGS
    tools = pick_build_dir(a.build, (COMPUTE_TEST,))
    with tempfile.TemporaryDirectory(prefix="bench-w64-") as work:
        modes = sorted({emulate for _, _, emulate in configs})
        spv = {emulate: build(work, a.shader, emulate, a.llvm_mc) for emulate in modes}
        seg = segments(spv[True])
        print(f"{a.shader}: {a.groups} workgroups of the shader's group size, {a.procs} x {a.reps} timed dispatches")
        if seg:
            print(f"emulated: {seg[0]} segments, {seg[1]} of them continuation segments (one extra round each)")
        hashes, rows = {}, []
        for name, driver, emulate in configs:
            med, mins, seen, dev = [], [], set(), None
            for _ in range(a.procs):
                t, h, dev = run(tools, spv[emulate], a.groups, a.reps, driver, emulate)
                if t is None:
                    med = None
                    print(f"{name}: failed or unsupported: {h}")
                    break
                med.append(t[0])
                mins.append(t[1])
                seen.add(h)
            if med:
                # Only a configuration whose every process ran counts: the hashes of the processes before a
                # failed one used to be kept, so the failure passed as a configuration that had run.
                hashes[name] = seen
                rows.append((name, dev, statistics.median(med), min(mins), min(med), max(med)))
        for name, dev, m, lo, a_, b_ in rows:
            print(f"{name:26} {dev:34} median {m:8.3f} ms   best {lo:8.3f}   process medians {a_:.3f}..{b_:.3f}")
        if a.emulated_only:
            name = EMULATED_ONLY_CONFIG[0]
            result = hashes.get(name)
            if not result:
                print(f"no complete result from {name}")
                return 1
            if len(result) != 1:
                print(f"OUTPUT HASH CHANGED between processes: {', '.join(sorted(result))}")
                return 1
            print(f"stable output hash: {next(iter(result))} (self-checked; no native reference)")
            return 0
        ref_name = configs[0][0]
        ref = hashes.get(ref_name)
        if not ref or len(ref) != 1:
            print(f"no reference output from {ref_name}: cannot compare")
            return 1
        bad = [n for n, _, _ in configs[1:] if n in hashes and hashes[n] != ref]
        missing = [n for n, _, _ in configs[1:] if n not in hashes]
        print(f"reference output hash: {next(iter(ref))} ({ref_name})")
        if bad:
            print(f"OUTPUT DIFFERS from the reference: {', '.join(bad)}")
        if missing:
            print(f"incomplete comparison: no complete result from {', '.join(missing)}")
        if bad or missing:
            return 1
        print("emulated output equals the reference")
        return 0


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())