Skip to content
Open
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
6 changes: 6 additions & 0 deletions docs/SHADERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,12 @@ The console branches once per wave, but the translator normally branches once pe

A [GPU check](../tools/check_lockstep_gpu.py) compares both paths with a model of the console on an RTX 4070 Ti SUPER: 245 cases match. Programs that translate through the targeted checks still branch once per thread. With the final branch that routes them to whole-wave translation removed, 160 of 210 cases of the same programs give wrong results, so some shaders that translate today are likely to compute wrong values. This hasn't been traced to anything visible in a game.

### Lane masks read as numbers

Each thread of a translated program holds only its own bit of a lane mask. Counting a mask's lanes, finding its first one or counting those before a lane reads the other bits too, and gave 0 or 1 for a whole wave. Compute programs now take the wave's ballot where such a mask is computed and read that ([analysis](../tools/shader-compiler/src/hlsl/mask_ballots.rs)). Both words of a wave64 mask have to come from the same lane masks on every path to the read, and the ballot is only taken where every lane that can be in the mask runs together: not in code that a branch on another mask skips or repeats, nor after some lanes have left. The program then runs in complete waves of the guest's width, so a wave64 one needs an adapter with wave64. Ray tracing resolve programs keep whole masks already and are left alone. Otherwise the old translation stays.

A [GPU check](../tools/check_mask_ballots_gpu.py) compares both widths with a model of the console on an RX 9060 XT: 300 cases match, and 200 of them don't without the ballots. In ProjectScarlett this affects the passes that hand out shadow mask tiles, where most lit tiles shared a few slots and shadows showed as 16-pixel blocks.

Most wave reduction refusals come from programs over 6,000 instructions, where the translator doesn't try its one-lane-per-wave form. In a trial on an earlier set of 1,442 such compute shaders, removing that limit translated 1,211. Six sampled outputs compiled in 2 to 12 seconds with DXC optimization off, and mostly produced 1 to 2 MB of DXIL. Large compiles in a recorded run took the driver 6 minutes or more, so the limit stays until the generated code compiles faster. The outputs weren't tested in a game.

### Earlier survey
Expand Down
4 changes: 2 additions & 2 deletions tools/check_lockstep_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ def program(body, resolve=False):
]


def words_of(items, llvm_mc):
def words_of(items, llvm_mc, *options):
lines = [item for item in items if isinstance(item, str)]
sizes, encoded = [], []
for line in lines:
encoded.append(assemble([line], llvm_mc))
encoded.append(assemble([line], llvm_mc, *options))
offsets, position, queue = {}, 0, iter(encoded)
for item in items:
if isinstance(item, str):
Expand Down
203 changes: 203 additions & 0 deletions tools/check_mask_ballots_gpu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
"""Check on a real GPU that lane masks read as numbers hold the whole wave's lanes.

Each synthetic program counts a mask's lanes, finds its first one or counts
those before each lane, some of them after EXEC was narrowed to one elected
lane. The reference models the console. Each program runs in waves of its own
width. Only the translator's input and output are instrumented. No game data is
needed.
"""
import argparse
import json
from pathlib import Path
import struct
import subprocess
import sys
from tempfile import TemporaryDirectory

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tools"))
from check_lockstep_gpu import LIMIT, branch, label, words_of # noqa: E402
from check_wave_guard import cases # noqa: E402
from frosty_gpu_guest import run_gpu_guest # noqa: E402
from project_tuxbox.inspect import digest # noqa: E402

# Results go to v10, v11 and v12. s12 holds the entry EXEC and v14 the lane's index.
WAVE_OPTIONS = {32: (), 64: ("-mattr=-wavefrontsize32,+wavefrontsize64",)}
WAVE32 = {
# A compare's own mask.
"compare": ["v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0", "s_bcnt1_i32_b32 s20, vcc_lo", "v_mov_b32_e32 v10, s20",
"v_mbcnt_lo_u32_b32 v11, vcc_lo, 0", "s_ff1_i32_b32 s21, vcc_lo", "v_mov_b32_e32 v12, s21"],
# A copy of EXEC, read after one lane of it was elected.
"elected": ["v_mbcnt_lo_u32_b32 v14, -1, 0", "v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0",
"s_and_saveexec_b32 s10, vcc_lo", branch("s_cbranch_execz", "end"),
"s_mov_b32 s11, exec_lo", "v_mbcnt_lo_u32_b32 v11, s11, 0",
"s_ff1_i32_b32 s21, s11", "v_mov_b32_e32 v12, s21",
"v_cmpx_eq_u32_e32 s21, v14", "s_bcnt1_i32_b32 s20, s11", "v_mov_b32_e32 v10, s20",
label("end")],
# A mask gathered over a loop.
"gathered": ["s_mov_b32 s11, 0", "s_mov_b32 s22, 0", label("again"),
"v_and_b32_e32 v15, 3, v0", "v_cmp_eq_u32_e32 vcc_lo, s22, v15", "s_or_b32 s11, s11, vcc_lo",
"s_add_u32 s22, s22, 1", "s_cmp_lt_u32 s22, 3", branch("s_cbranch_scc1", "again"),
"s_bcnt1_i32_b32 s20, s11", "v_mov_b32_e32 v10, s20", "v_mbcnt_lo_u32_b32 v11, s11, 0",
"v_mov_b32_e32 v12, 0"],
# The lanes left out, and a branch on their number.
"others": ["v_cmp_lt_u32_e32 vcc_lo, 0x3e8, v0", "s_andn2_b32 s11, exec_lo, vcc_lo",
"s_bcnt1_i32_b32 s20, s11", branch("s_cbranch_scc0", "end"), "v_mov_b32_e32 v10, s20",
"v_mbcnt_lo_u32_b32 v11, s11, 0", "v_mov_b32_e32 v12, 1", label("end")],
}
WAVE64 = {
"compare": ["v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_bcnt1_i32_b64 s20, vcc", "v_mov_b32_e32 v10, s20",
"v_mbcnt_lo_u32_b32 v11, vcc_lo, 0", "v_mbcnt_hi_u32_b32 v11, vcc_hi, v11",
"s_ff1_i32_b64 s21, vcc", "v_mov_b32_e32 v12, s21"],
"elected": ["v_mbcnt_lo_u32_b32 v14, -1, 0", "v_mbcnt_hi_u32_b32 v14, -1, v14",
"v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_and_saveexec_b64 s[10:11], vcc", branch("s_cbranch_execz", "end"),
"s_mov_b64 s[14:15], exec", "v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11",
"s_ff1_i32_b64 s21, s[14:15]", "v_mov_b32_e32 v12, s21",
"v_cmpx_eq_u32_e32 s21, v14", "s_bcnt1_i32_b64 s20, s[14:15]", "v_mov_b32_e32 v10, s20",
label("end")],
"gathered": ["s_mov_b64 s[14:15], 0", "s_mov_b32 s22, 0", label("again"),
"v_and_b32_e32 v15, 3, v0", "v_cmp_eq_u32_e32 vcc, s22, v15", "s_or_b64 s[14:15], s[14:15], vcc",
"s_add_u32 s22, s22, 1", "s_cmp_lt_u32 s22, 3", branch("s_cbranch_scc1", "again"),
"s_bcnt1_i32_b64 s20, s[14:15]", "v_mov_b32_e32 v10, s20",
"v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11", "v_mov_b32_e32 v12, 0"],
"others": ["v_cmp_lt_u32_e32 vcc, 0x3e8, v0", "s_andn2_b64 s[14:15], exec, vcc",
"s_bcnt1_i32_b64 s20, s[14:15]", branch("s_cbranch_scc0", "end"), "v_mov_b32_e32 v10, s20",
"v_mbcnt_lo_u32_b32 v11, s14, 0", "v_mbcnt_hi_u32_b32 v11, s15, v11", "v_mov_b32_e32 v12, 1",
label("end")],
}


def program(body, width):
size = "64" if width == 64 else "32"
exec_, saved = ("exec", "s[12:13]") if width == 64 else ("exec_lo", "s12")
return [f"s_mov_b{size} {saved}, {exec_}", *body, f"s_mov_b{size} {exec_}, {saved}", "s_endpgm"]


def model(name, active, values, host):
"""v10, v11 and v12 of every lane, with the group run as waves of `host` lanes."""
rows = []
for start in range(0, len(values), host):
lanes = range(host)
on = [active[start + i] for i in lanes]
value = values[start:start + host]
over = [on[i] and value[i] > LIMIT for i in lanes]
mask = {"compare": over, "elected": over, "gathered": [on[i] and value[i] & 3 < 3 for i in lanes],
"others": [on[i] and not over[i] for i in lanes]}[name]
count, first = sum(mask), mask.index(True) if any(mask) else 0xffffffff
for i in lanes:
rank = sum(mask[:i])
if not on[i] or not any(mask) and name in ("elected", "others"):
rows.append((0, 0, 0))
elif name == "compare":
rows.append((count, rank, first))
elif name == "elected":
rows.append((count if i == first else 0, rank, first) if mask[i] else (0, 0, 0))
else:
rows.append((count, rank, int(name == "others")))
return rows


def instrument(hlsl, width):
start = " v0 = gtid.x; v1 = gtid.y; v2 = gtid.z;"
load = (" uint input = output[gtid.x];\n exec_lo = input >> 31;\n"
" v0 = input & 0x7fffffffu; v1 = gtid.y; v2 = gtid.z;")
if hlsl.count(start) != 1 or "WaveActiveBallot" not in hlsl or f"[WaveSize({width})]" not in hlsl:
raise ValueError("fixture must take a ballot in waves of its own width")
stores = (f" output[{width}u + gtid.x] = v10 | (v11 << 8u) | (WaveGetLaneCount() << 16u);\n"
f" output[{2 * width}u + gtid.x] = v12;\n")
hlsl = hlsl.replace(start, load)
end = hlsl.rstrip().rfind("}")
return "RWBuffer<uint> output : register(u0);\n" + hlsl[:end] + stores + "}\n"


def inputs(width):
yield from cases(width)
yield "below", (1 << width) - 1, list(range(width))
yield "one_above", (1 << width) - 1, [LIMIT + 1 if lane == 17 else lane for lane in range(width)]
yield "some_above", (1 << width) - 1, [LIMIT - 20 + lane for lane in range(width)]
yield "inactive_above", 0x0000ffff, [lane if lane < 16 else LIMIT + lane for lane in range(width)]


def seed_for(mask, values):
width = len(values)
seed = [0x76540000 + i for i in range(384)]
seed[96:96 + width] = [v | (((mask >> lane) & 1) << 31) for lane, v in enumerate(values)]
return seed


def difference(name, seed, mask, values, data):
"""The first word that is wrong, if any."""
if len(data) != 4 * len(seed):
return "no readback"
actual, expected, width = struct.unpack("<384I", data), list(seed), len(values)
host = actual[96 + width] >> 16
if host != width:
return f"host wave of {host}"
rows = model(name, [bool((mask >> lane) & 1) for lane in range(width)], values, host)
for lane, (count, rank, last) in enumerate(rows):
expected[96 + width + lane] = count | rank << 8 | host << 16
expected[96 + 2 * width + lane] = last
return next((dict(word=i, got=a, wanted=b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b), None)


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
for name in ("emitter", "llvm-mc", "dxc", "dxv", "provider", "proton", "prefix", "compiler-dir", "work",
"output"):
parser.add_argument("--" + name, type=Path, required=True)
parser.add_argument("--adapter", required=True)
args = parser.parse_args(argv)
work = args.work.resolve()
work.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(dir=work) as tmp:
trial = Path(tmp)
trials, shaders = {}, {}
for width, bodies in ((32, WAVE32), (64, WAVE64)):
for name, body in bodies.items():
words = words_of(program(body, width), args.llvm_mc, *WAVE_OPTIONS[width])
emitted = subprocess.check_output(
[args.emitter.resolve(), str(width), *(f"{word:08x}" for word in words)], text=True, timeout=30)
source = trial / f"{name}{width}.hlsl"
source.write_text(instrument(emitted, width))
blob = trial / f"{name}{width}.cso"
subprocess.run([args.dxc, "-T", "cs_6_6", "-E", "main", "-Fo", blob, source], check=True, timeout=30,
capture_output=True)
subprocess.run([args.dxv, blob], check=True, timeout=30, capture_output=True)
shaders[f"{name}{width}"] = dict(hlsl_sha256=digest(source), dxil_sha256=digest(blob))
for case, mask, values in inputs(width):
trial_name = f"{name}{width}_{case}"
trials[trial_name] = name, seed_for(mask, values), mask, values
(trial / f"{trial_name}.seed").write_bytes(struct.pack("<384I", *trials[trial_name][1]))
(trial / f"{trial_name}.cso").hardlink_to(blob)
(trial / "cases.txt").write_text("".join(f"{name} 0 uint 1\n" for name in trials))
exe, status, fields = run_gpu_guest(
ROOT / "tools/reference/independent-shaders/compute.cpp", "ballots.exe", trial, work,
args.proton.resolve(), args.prefix, args.provider, args.compiler_dir)
wrong = {}
for trial_name, (name, seed, mask, values) in trials.items():
path = trial / f"{trial_name}.bin"
found = difference(name, seed, mask, values, path.read_bytes() if path.is_file() else b"")
if found:
wrong[trial_name] = found
passed = status == 0 and fields.get("adapter") == args.adapter and not wrong
report = dict(passed=passed, scope="Synthetic programs reading lane masks as numbers",
adapter=fields.get("adapter"), guest_exit=status, cases=len(trials),
compared_words=len(trials) * 384, wrong=wrong, shaders=shaders,
emitter_sha256=digest(args.emitter), guest_sha256=digest(exe))
if fields.get("error"):
report["error"] = fields["error"]
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
for name, detail in wrong.items():
print(f"WRONG {name}: {detail}")
if not passed:
print(f"FAIL: {len(wrong)} of {len(trials)} cases, guest exit {status}")
return 1
print(f"PASS: {len(trials)} cases, {len(trials) * 384} words, adapter {fields['adapter']}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
4 changes: 2 additions & 2 deletions tools/check_packed_integer_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()

def assemble(lines,llvm):
result=subprocess.run([str(llvm),"-triple=amdgcn-amd-amdhsa","-mcpu=gfx1030","-show-encoding"],
def assemble(lines,llvm,*options):
result=subprocess.run([str(llvm),"-triple=amdgcn-amd-amdhsa","-mcpu=gfx1030","-show-encoding",*options],
input="\n".join(lines)+"\n",text=True,capture_output=True,check=True,timeout=20)
encoded=re.findall(r"encoding: \[([^\]]+)\]",result.stdout)
if len(encoded)!=len(lines):
Expand Down
1 change: 1 addition & 0 deletions tools/check_translator_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def assembled(tool, *extra):
extra=("--width", str(width), "--variant", variant))
for width in (32, 64) for variant in ("original", "chain", "chain-zero")},
"lockstep": Check("check_lockstep_gpu", emitter="lockstep", llvm=True, dxc=True),
"mask-ballots": Check("check_mask_ballots_gpu", emitter="mask_ballots", llvm=True, dxc=True),
"dpp8-exchange": Check("check_dpp8_exchange", emitter="lone_lane_probe", dxc=True),
"pixel-heap-offsets": Check("check_pixel_heap_offsets", emitter="pixel_heap_offsets", dxc=True),
"pixel-link": Check("check_portable_pixel_link", emitter="xshader", dxc=True),
Expand Down
30 changes: 30 additions & 0 deletions tools/shader-compiler/examples/mask_ballots.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! Translate a synthetic compute program, supplied as native words, that reads
//! lane masks as numbers. Its thread group is one guest wave.
use tuxbox_xshader::{ShaderExtract, Stage, hlsl};

mod fixture {
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/support/wave_guard_fixture.rs"));
}

fn main() {
let mut args = std::env::args().skip(1);
let width: u32 = args.next().expect("wave width").parse().expect("integer");
assert!(matches!(width, 32 | 64));
let words: Vec<u32> = args.map(|s| u32::from_str_radix(&s, 16).expect("hex native word")).collect();
assert!(!words.is_empty() && words.len() <= 512 && words.last() == Some(&0xbf810000));
let (mut shader, _, _): (ShaderExtract, _, _) = fixture::shader(width);
shader.isa = words.iter().flat_map(|word| word.to_le_bytes()).collect();
shader.isa_data = shader.isa.clone();
assert!(matches!(shader.stage, Stage::Compute));
match hlsl::translate(&shader) {
Ok(result) => {
// A ballot holds the lanes of one guest wave.
assert_eq!(result.required_wave_size, Some(width));
print!("{}", result.hlsl);
}
Err(reason) => {
eprintln!("{reason}");
std::process::exit(65);
}
}
}
3 changes: 3 additions & 0 deletions tools/shader-compiler/src/hlsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ mod fspx_wave;
mod singleton_wave;
mod wave_sum;
mod lockstep;
mod mask_ballots;
mod wave_loops;
mod raw_index;
mod reflection_compact;
Expand Down Expand Up @@ -328,6 +329,8 @@ struct Emitter<'a> {
compute_swizzle: bool,
vote_defs: BTreeSet<usize>,
vote_uses: BTreeMap<usize, usize>,
/// Lane masks read as numbers.
mask_ballots: Option<mask_ballots::Ballots>,
exec_snapshots: exec_snapshot::Snapshots,
reflected_lds_words: Option<u32>,
hoisted_swizzle: Option<usize>,
Expand Down
Loading
Loading