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
54 changes: 54 additions & 0 deletions docs/shader_validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2256,6 +2256,60 @@ reads per vertex. Not shown: the 61 individually (a 12-shader subset of the 190
the RTX 4080 SUPER; draws of these shaders take about 20 s each). Only 9 of the 480 read raw
barycentrics and need the geometry shader; all 9 agree on both GPUs.

### What tier C costs in pixels: one AMD GPU at subgroup 64 and 32 (SHADER-836)

The two-GPU sweep above cannot show tier C (`tools/wave64_halves.py`): the RTX 4080 SUPER and the UHD 770 are both
32-wide, so a tier C shader is inexact the same way on both. An AMD RDNA GPU whose driver lists the fragment stage in
`requiredSubgroupSizeStages` can draw one translated pixel shader twice, at subgroup 64 (the wave64 it was written for)
and at 32 (what a 32-wide GPU gives it). Nothing else changes between the two draws, so a difference is tier C (or a
mis-tiered shader) and not filter weights or a vendor. `vk_ps_sweep` takes the size from `VKS_SUBGROUP` (exit 77 when
the device cannot require it), and `ps_sweep.py run --subgroup 64|32` passes it on. `ps_sweep.py sample --tier-n` samples
each tier on its own so that the rare tiers get a count of their own.

AMD Radeon RX 9060 XT (RDNA4), AMD driver 26.10.44, Windows 11. Pixel shaders translated by `make_game --stages shaders`
from `main` `659654236`, own 1.0.2.1 copy. Population: 12,101 pixel shaders, A 3,396 / B 27 / C 7,551 (wave64_halves
census; the same counts as SHADER-836b's). Sample `--tier-n C=240,B=27,A=60 --seed 836`: 360 shaders, A 93 (the stratum
floors add 33), all 27 of tier B, C 240. Every one of the 360 draws at both sizes in both variants (no unsupported
feature, no timeout, no device loss).

| class | variant z (fallback images) | variant t (gradient textures) |
|---|---|---|
| same at 64 and 32 | 351 | 336 |
| differs beyond tolerance | 5 (4 by > 0.1) | 19 (all by > 0.1) |
| NaN, zero or unwritten at one size only | 4 | 5 |

By tier (variant t; variant z in brackets):

| tier | sampled | same | differ | NaN / zero / unwritten at one size |
|---|---:|---:|---:|---:|
| A | 93 | 93 (93) | 0 (0) | 0 (0) |
| B | 27 | 24 (24) | 3 (3) | 0 (0) |
| C | 240 | 219 (234) | 16 (2) | 5 (4) |

- **Tier C, 21 of 240 (8.8 %) in variant t, 6 of 240 in variant z.** A tier C shader lists several reasons, so these
overlap. Among the 21 (variant t): cross-lane 20, tainted-exec 20, unsafe-vote-branch 17, tainted-branch 8,
mask-half 5, stale-scalar 4, lane-id 1; first-lane (0 of 9) and unsafe-execz-branch (0 of 17) never differ here.
Nearly all of the cost sits with cross-lane data flow. Variant z hides most of it, because with zero textures most
tier C shaders compute nothing that depends on the lane.
- **Tier B is not always exact.** 3 of the 27 differ by more than 0.1 in both variants. All 3 carry the
`readfirstlane-uniform` idiom (26 of the 27 sampled tier B shaders carry it, one carries `lane-spill`). The
analysis proves that value uniform, but on 3 shaders it is not uniform across the two 32-lane halves.
- **Tier A is exact:** 93 of 93 in both variants, which also shows that the 64-wide and the 32-wide pipelines are
otherwise the same.
- **The bit-exact compare gives the same counts.** The tolerance compare treats integer words that are bit-cast to
float as equal, because they are denormals. `compare --exact`, which now prints the same tier breakdown, finds the
same 24 draws in variant t (tier B 3, tier C 21) and the same 9 in variant z. No sampled shader differs only in such
words.
- **The usable denominator is smaller than 240.** In variant t, 104 of the 240 tier C shaders write nothing but the
clear colour. Most of them read their inputs from the zeroed heap and discard, so they cannot show a difference.
Of the 136 that do write, 21 differ (15 %). Tier A has 31 such clear-only draws of 93, tier B has 1 of 27.
- **The differences are the subgroup size, not noise.** All 24 shaders that differ in variant t, drawn again at 64, are
bit-identical to the first draw at 64, and the same holds at 32. The 9 shaders that differ in variant z, drawn again
at 64, match too. The second 64 draw against the second 32 draw reproduces the same 19 + 5 classes.
- The limit is the synthetic input of this sweep (zeroed heap, fallback or gradient images, generated varyings). It
gives a floor on how often tier C shows, not how much a real frame changes. Shaders whose tier C path needs real
descriptors or data stay equal here.

## Coverage plan and cost

Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and
Expand Down
28 changes: 26 additions & 2 deletions runtime/test/vk_ps_sweep.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
// push s0..s31 from VKS_SGPRS (like VKH_SGPRS), then the heap base
// heap VKS_HEAP_KB KiB (default 1024), zero unless VKS_HEAP_FILL=<offset>,<bytes>,<seed> fills a range with
// floats in [0.25, 1)
// VKS_SUBGROUP=32|64 draws the pixel shader with that required subgroup size (subgroupSizeControl, the fragment
// stage in requiredSubgroupSizeStages; else exit 77). On a device whose fragment subgroups can be 64
// and 32 wide (AMD RDNA), 64 is the wave64 the shader was written for and 32 is what a 32-wide GPU
// gives it, so the two runs of one shader on one GPU measure tier C of tools/wave64_halves.py alone
// Output: the targets back to back, each width * height * 16 bytes, cleared to -1 so a pixel that was never
// written stays clear. --depth also writes <out.raw>.depth, one D32_SFLOAT word per pixel, cleared to 1.
// It enables precise occlusion counting, depth test ALWAYS, depth writes, and no stencil or depth bounds test.
Expand Down Expand Up @@ -238,9 +242,11 @@ int main(int argc, char** argv) {
VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary_have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock_have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
VkPhysicalDeviceVulkan13Features have13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
have.pNext = &have12;
have12.pNext = &lock_have;
have12.pNext = &have13;
have13.pNext = &lock_have;
lock_have.pNext = &bary_have;
vkGetPhysicalDeviceFeatures2(pd, &have);
VkPhysicalDeviceSubgroupProperties sub{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
Expand Down Expand Up @@ -305,6 +311,18 @@ int main(int argc, char** argv) {
need((sub.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0, "subgroup operations in fragment shaders");
need((sub.supportedOperations & subgroup_ops) == subgroup_ops, "a subgroup operation class");
}
// VKS_SUBGROUP: a required fragment subgroup size, within what the device allows for that stage.
uint32_t required_subgroup = 0;
if (const char* s = std::getenv("VKS_SUBGROUP"); s && *s) {
required_subgroup = uint32_t(std::strtoul(s, nullptr, 10));
VkPhysicalDeviceVulkan13Properties p13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_PROPERTIES};
VkPhysicalDeviceProperties2 p13w{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &p13};
vkGetPhysicalDeviceProperties2(pd, &p13w);
need(have13.subgroupSizeControl && (p13.requiredSubgroupSizeStages & VK_SHADER_STAGE_FRAGMENT_BIT) &&
required_subgroup >= p13.minSubgroupSize && required_subgroup <= p13.maxSubgroupSize &&
(required_subgroup & (required_subgroup - 1)) == 0,
"the requested fragment subgroup size (VKS_SUBGROUP)");
}
leonida::vk_test::ShaderFma fma;
fma.query(gipa, inst, pd);
if (!fma.accepts(fs_code.data(), fs_code.size() * 4, argv[2])) return 77;
Expand Down Expand Up @@ -362,8 +380,11 @@ int main(int argc, char** argv) {
en12.descriptorBindingPartiallyBound = flags.partially_bound;
en12.runtimeDescriptorArray = VK_TRUE;
en12.bufferDeviceAddress = VK_TRUE;
// pNext chain: features2 -> vulkan12 -> [barycentric] -> [interlock] -> [maintenance8] -> [fma]
VkPhysicalDeviceVulkan13Features en13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
en13.subgroupSizeControl = required_subgroup ? VK_TRUE : VK_FALSE;
// pNext chain: features2 -> vulkan12 -> [vulkan13] -> [barycentric] -> [interlock] -> [maintenance8] -> [fma]
void** tail = &en12.pNext;
if (required_subgroup) { *tail = &en13; tail = &en13.pNext; }
if (bary.fragmentShaderBarycentric) { *tail = &bary; tail = &bary.pNext; }
if (lock.fragmentShaderPixelInterlock) { *tail = &lock; tail = &lock.pNext; }
#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
Expand Down Expand Up @@ -651,6 +672,9 @@ int main(int argc, char** argv) {
stages[stage_count].stage = VK_SHADER_STAGE_GEOMETRY_BIT; stages[stage_count].module = gs;
stages[stage_count++].pName = "main";
}
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo rss{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO};
rss.requiredSubgroupSize = required_subgroup;
if (required_subgroup) stages[stage_count].pNext = &rss;
stages[stage_count].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stages[stage_count].module = fs;
stages[stage_count++].pName = "main";
VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
Expand Down
48 changes: 48 additions & 0 deletions tests/test_ps_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,28 @@ def test_strata_and_pixel_shaders_only(self):
self.assertTrue(all(sampled >= min(10, size) for size, sampled in per.values()))
self.assertEqual(sum(sampled for _, sampled in per.values()), len(picked))

def test_tier_weighted_sample(self):
# SHADER-836: --tier-n samples each wave64_graphics tier on its own, so the rare tier C gets its own count.
index = synthetic_index()
for i, k in enumerate(sorted(k for k, v in index.items() if v["stage"] == "ps")):
index[k]["wave64_graphics"] = "C" if i % 10 == 0 else "A"
if i % 10 == 0:
index[k]["wave64_graphics_reasons"] = ["LANE_COUNT", "LANE_COUNT"]
with tempfile.TemporaryDirectory() as tmp:
spirv, out = os.path.join(tmp, "spirv"), os.path.join(tmp, "out")
os.makedirs(spirv)
with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump(index, f)
with contextlib.redirect_stdout(io.StringIO()):
ps_sweep.main(["sample", "--spirv", spirv, "--out", out, "--tier-n", "C=100,A=20", "--seed", "3"])
with open(os.path.join(out, "sample.json"), encoding="utf-8") as f:
sample = json.load(f)
tiers = [s["tier"] for s in sample]
self.assertEqual(tiers.count("C"), 14) # all 14 tier C shaders: fewer than asked for
self.assertGreaterEqual(tiers.count("A"), 20) # the stratum floors may add a few more
self.assertEqual({tuple(s["reasons"]) for s in sample if s["tier"] == "C"}, {("LANE_COUNT",)})
self.assertEqual(len({s["name"] for s in sample}), len(sample))

def test_fixed_seed_is_stable_and_seed_matters(self):
ps = {k: v for k, v in synthetic_index().items() if v["stage"] == "ps"}
first = ps_sweep.pick_sample(ps, 40, 7)[0]
Expand Down Expand Up @@ -120,6 +142,11 @@ def test_job_env_drops_inherited_per_job_variables(self):
env = ps_sweep.job_env(base, 9, "t", {"needs_maintenance8": True}, "g.spv")
self.assertEqual((env["VKS_GS"], env["VKS_TEX"], env["VKS_NEED_MAINTENANCE8"]), ("g.spv", "1", "1"))

def test_subgroup_is_set_only_when_asked(self):
base = {"PATH": "p", "VKS_SUBGROUP": "64"} # left in the shell by an earlier run
self.assertNotIn("VKS_SUBGROUP", ps_sweep.job_env(base, 9, "z", {}, None))
self.assertEqual(ps_sweep.job_env(base, 9, "z", {}, None, 32)["VKS_SUBGROUP"], "32")

def test_gs_is_the_bary_gs_file_beside_the_pixel_shader(self):
with tempfile.TemporaryDirectory() as d:
self.assertIsNone(ps_sweep.gs_for(d, "x1"))
Expand Down Expand Up @@ -267,6 +294,27 @@ def test_exact_readbacks_and_rerun(self):
self.assertEqual(report["rows"][-1]["samples_passed"], [None, 0])
self.assertNotIn("samples_passed", report["rows"][6])

def test_tier_breakdown(self):
sample = [{"tier": "A"}, {"tier": "B"}, {"tier": "C", "reasons": ["r1", "r2"]},
{"tier": "C", "reasons": ["r1"]}, {"tier": "C"}]
rows = [{"class": c} for c in ("OK on both", "differs", "differs", "OK on both", "OK on both")]
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
ps_sweep.print_tier_breakdown(sample, rows)
lines = buf.getvalue().splitlines()
self.assertEqual(lines, [
" tier A: OK on both 1",
" tier B: differs 1",
" tier C: OK on both 2, differs 1",
" tier C reason (none): OK on both 1",
" tier C reason r1: OK on both 1, differs 1", # a shader with two reasons counts under each
" tier C reason r2: differs 1",
])
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
ps_sweep.print_tier_breakdown([{}, {}], rows[:2]) # a sample made without --tier-n prints nothing
self.assertEqual(buf.getvalue(), "")

def test_incomplete_depth_measurements(self):
with tempfile.TemporaryDirectory() as tmp:
rec = {"depth": True, "code": 0, "dir": tmp, "samples_passed": 0}
Expand Down
56 changes: 50 additions & 6 deletions tools/ps_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,12 @@ def gs_for(spirv, name):
return path if os.path.isfile(path) else None


JOB_VARS = ("VKS_GS", "VKS_TEX", "VKS_NEED_MAINTENANCE8")
JOB_VARS = ("VKS_GS", "VKS_TEX", "VKS_NEED_MAINTENANCE8", "VKS_SUBGROUP")


def job_env(base, timeout, variant, meta, gs):
"""The environment of one draw: the parent's, minus every per-job variable it may have inherited, plus this job's."""
def job_env(base, timeout, variant, meta, gs, subgroup=0):
"""The environment of one draw: the parent's, minus every per-job variable it may have inherited, plus this job's.
A VKS_SUBGROUP left in the shell is dropped too, so only run --subgroup asks for a required size."""
env = {k: v for k, v in base.items() if k not in JOB_VARS}
env.update(VKS_TIMEOUT_S=str(timeout), VKS_HEAP_KB="1024")
if variant == "t":
Expand All @@ -149,6 +150,8 @@ def job_env(base, timeout, variant, meta, gs):
env["VKS_GS"] = gs
if meta.get("needs_maintenance8"):
env["VKS_NEED_MAINTENANCE8"] = "1"
if subgroup:
env["VKS_SUBGROUP"] = str(subgroup)
return env


Expand All @@ -169,12 +172,28 @@ def make_vs(glslang, meta, cache_dir):
return spv


def tier(meta):
"""The wave64_graphics tier (tools/wave64_halves.py) of a wave64 pixel shader, '-' for a wave32 or unmarked one."""
return meta.get("wave64_graphics") or "-"


def cmd_sample(a):
ps = load_ps(a.spirv)
picked, per = pick_sample(ps, a.n, a.seed)
if a.tier_n:
# A sample weighted by tier: each tier's shaders are sampled on their own (still stratified as above), so a
# rare tier gets the count asked for instead of its share of the population.
picked, per = [], {}
for t, n in sorted(a.tier_n.items()):
sub = {k: v for k, v in ps.items() if tier(v) == t}
p, q = pick_sample(sub, min(n, len(sub)), a.seed)
picked += p
per.update({(t,) + s: v for s, v in q.items()})
else:
picked, per = pick_sample(ps, a.n, a.seed)
os.makedirs(a.out, exist_ok=True)
with open(os.path.join(a.out, "sample.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump([{"name": k, "stratum": list(stratum(ps[k]))} for k in picked], f)
json.dump([{"name": k, "stratum": list(stratum(ps[k])), "tier": tier(ps[k]),
"reasons": sorted(set(ps[k].get("wave64_graphics_reasons", [])))} for k in picked], f)
print(f"population {len(ps)} strata {len(per)} sampled {len(picked)}")
for s in sorted(per, key=str):
print(f" stratum {s}: population {per[s][0]} sampled {per[s][1]}")
Expand Down Expand Up @@ -224,7 +243,7 @@ def cmd_run(a):
with open(log, "a", encoding="utf-8", newline="\n") as f:
f.write(json.dumps({"i": i, "code": NOT_TRANSLATED, "reason": "no bary_gs companion", "targets": 0, "sec": 0}) + "\n")
continue
env = job_env(os.environ, a.timeout, a.variant, meta, gs)
env = job_env(os.environ, a.timeout, a.variant, meta, gs, a.subgroup)
cmd = [a.exe, make_vs(a.glslang, meta, cache), os.path.join(a.spirv, s["name"] + ".spv"), raw,
str(W), str(H), str(targets)]
if a.depth:
Expand Down Expand Up @@ -474,6 +493,26 @@ def compare_exact(a, sample, ra, rb):
print(label, "total", sum(counts.values()))
for outcome, n in sorted(counts.items()):
print(f" {outcome}: {n}")
print_tier_breakdown(sample, rows)


def print_tier_breakdown(sample, rows):
"""By wave64_graphics tier, and tier C by reason code (a shader with several reasons counts under each).
Also for --exact: integer outputs bit-cast to float are denormals that the tolerance compare calls equal."""
if not any("tier" in s for s in sample):
return
by_tier, by_reason = {}, {}
for s, row in zip(sample, rows):
t = s.get("tier", "-")
by_tier.setdefault(t, {})[row["class"]] = by_tier.setdefault(t, {}).get(row["class"], 0) + 1
if t == "C":
for r in s.get("reasons") or ["(none)"]:
d = by_reason.setdefault(r, {})
d[row["class"]] = d.get(row["class"], 0) + 1
for t in sorted(by_tier):
print(f" tier {t}: " + ", ".join(f"{c} {n}" for c, n in sorted(by_tier[t].items())))
for r in sorted(by_reason):
print(f" tier C reason {r}: " + ", ".join(f"{c} {n}" for c, n in sorted(by_reason[r].items())))


def cmd_compare(a):
Expand Down Expand Up @@ -504,6 +543,7 @@ def cmd_compare(a):
for (c, sc), n in sorted(sub.items()):
if sc:
print(f" {c} / {sc}: {n}")
print_tier_breakdown(sample, rows)


WARNING = ("warning (run): a few sampled shaders hang NVIDIA GPUs with the zeroed heap (VK_ERROR_DEVICE_LOST, a\n"
Expand Down Expand Up @@ -534,6 +574,10 @@ def main(argv=None):
ap.add_argument("--hi", type=int, default=0)
ap.add_argument("--only", type=lambda s: [int(x) for x in s.split(",")], default=None)
ap.add_argument("--suffix", default="", help="results folder suffix (a re-run uses _re)")
ap.add_argument("--tier-n", type=lambda s: {k: int(v) for k, v in (p.split("=") for p in s.split(","))},
default=None, help="sample: shaders per wave64_graphics tier instead of --n, e.g. C=240,B=60,A=60")
ap.add_argument("--subgroup", type=int, default=0,
help="run: required fragment subgroup size (VKS_SUBGROUP), e.g. 64 and 32 on one AMD GPU")
a = ap.parse_args(argv)
a.depth |= a.two_clear
if a.depth and a.cmd != "run":
Expand Down