upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools/image_query_probe.py
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
commit46a196cde9328e2a232ee15c19556eb962cda0ab (patch)
treed1cd03326530912d925ee1a7ba7fa735006f004f /tools/image_query_probe.py
parentd3fab00a78967adf357596996190afdf33dc09d5 (diff)
parentec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff)
Merge upstream main into first-light shader identity
Diffstat (limited to 'tools/image_query_probe.py')
-rw-r--r--tools/image_query_probe.py307
1 files changed, 307 insertions, 0 deletions
diff --git a/tools/image_query_probe.py b/tools/image_query_probe.py
new file mode 100644
index 000000000..29fabe517
--- /dev/null
+++ b/tools/image_query_probe.py
@@ -0,0 +1,307 @@
1r"""What `image_get_resinfo` and `image_get_lod` return on an RDNA2 GPU (SHADER-388). Standard library only.
2
3docs/design.md ("Image atomics, size and LOD queries") left three answers unverified: resinfo's depth word for a 2D
4image, the clamped LOD `image_get_lod` returns under a linear mip filter, and the order of u and v in the LOD query.
5This probe runs both instructions natively (through tools/hw_oracle/) on hand-built descriptors and compares every
6result word with the rules below. Neither instruction reads memory, so the T# has no texture behind it.
7
8image_get_resinfo, dmask 0xf, address VGPR = mip level (unsigned), T# with BASE_LEVEL b and LAST_LEVEL l:
9 n = l - b + 1 levels; past the last level (level >= n) width, height and depth are 0; otherwise
10 width = max(1, WIDTH >> (b + level)), height likewise, and the depth word is
11 2D: 0, whatever T# WORD4 DEPTH holds (a linear GFX10.3 T# keeps its pitch there)
12 2D array: max(1, (DEPTH + 1) >> (b + level)): the layer count is minified like a 3D depth
13 and the fourth word is n.
14image_get_lod, dmask 0x3, 2D, S# MIN_LOD lo, MAX_LOD hi, LOD_BIAS s, n levels; one 2x2 quad of lanes whose u steps
15by du across x and v by dv across y (so the LOD is log2(max(du * width, dv * height))):
16 VGPR 1 (raw) = that LOD + s
17 VGPR 0 (clamped) = 0 with MIP_FILTER none; else c = min(max(min(raw, hi), lo), n - 1) (lo wins over hi when
18 lo > hi, and the level count caps both), then floor(c + 0.5) with MIP_FILTER point (the level it would read,
19 ties up) and c with MIP_FILTER linear.
20That is the definition of OpImageQueryLod / textureQueryLod (the level read, or a fraction between the two read).
21
22Every case runs in wave32 and wave64; every lane of a quad must agree.
23
24Usage:
25 python -I tools/image_query_probe.py [--waves 32,64] [--json out.json]
26 python -I tools/image_query_probe.py --self-test # the rules against values measured on gfx1036, no GPU
27
28Exit 0 when every word matches the rules, 1 on a mismatch (a finding: the rules above are wrong on this GPU), 2 on a
29harness error, 77 when the hardware oracle is unavailable or the GPU is not GFX10 (the T# layout is GFX10's).
30Nothing here reads game files.
31"""
32import argparse
33import json
34import math
35import os
36import struct
37import sys
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40sys.dont_write_bytecode = True
41if HERE not in sys.path:
42 sys.path.insert(0, HERE)
43
44TYPE_2D, TYPE_2D_ARRAY = 9, 10 # SQ_RSRC_IMG_* in T# WORD3 [31:28]
45DIMS = {TYPE_2D: "SQ_RSRC_IMG_2D", TYPE_2D_ARRAY: "SQ_RSRC_IMG_2D_ARRAY"}
46MIP_NONE, MIP_POINT, MIP_LINEAR = 0, 1, 2 # SQ_TEX_MIP_FILTER in S# WORD2 [27:26]
47SENTINEL = 0xDEAD0000
48
49
50def f2u(f):
51 return struct.unpack("<I", struct.pack("<f", f))[0]
52
53
54def u2f(u):
55 return struct.unpack("<f", struct.pack("<I", u & 0xFFFFFFFF))[0]
56
57
58# ---- the rules ----
59
60def resinfo_model(width, height, typ, depth_field, base, last, level):
61 """[width, height, depth, levels] that image_get_resinfo dmask:0xf returns (see the module docstring)."""
62 n = last - base + 1
63 if level >= n:
64 return [0, 0, 0, n]
65 shift = base + level
66 w, h = max(1, width >> shift), max(1, height >> shift)
67 depth = 0 if typ == TYPE_2D else max(1, (depth_field + 1) >> shift)
68 return [w, h, depth, n]
69
70
71def lod_model(lod, mip, lo, hi, bias, levels):
72 """(clamped, raw) that image_get_lod dmask:0x3 returns for a quad whose computed LOD is `lod`."""
73 raw = lod + bias
74 if mip == MIP_NONE:
75 return 0.0, raw
76 c = min(max(min(raw, hi), lo), levels - 1)
77 return (math.floor(c + 0.5) if mip == MIP_POINT else c), raw
78
79
80# ---- descriptors ----
81
82def tsharp_words(arch, width, height, typ=TYPE_2D, depth_field=None, base=0, last=0):
83 """A GFX10 T# (tools/hw_oracle/tsharp.py's linear 2D one) with the type, levels and WORD4 DEPTH set.
84 depth_field None keeps what tsharp writes there (the pitch on GFX10.3)."""
85 from hw_oracle import tsharp
86 t = tsharp.image_words(arch, "R8G8B8A8_UNORM", width, height, 4)
87 t[3] = (t[3] & ~(0xF << 28) & ~(0xFF << 12)) | (typ << 28) | (base << 12) | (last << 16)
88 if depth_field is not None:
89 t[4] = (t[4] & ~0x1FFF) | depth_field
90 return t
91
92
93def ssharp_words(mip, lo, hi, bias=0.0):
94 """A GFX10 S#: wrap, bilinear min/mag, MIP_FILTER mip, MIN_LOD/MAX_LOD (unsigned 4.8), LOD_BIAS (signed 5.8)
95 (runtime/src/gfx10_descriptors.h encode() has the same layout)."""
96 word1 = int(lo * 256) | int(hi * 256) << 12
97 word2 = (int(bias * 256) & 0x3FFF) | 1 << 20 | 1 << 22 | mip << 26
98 return [0, word1, word2, 0]
99
100
101# ---- kernels ----
102
103def resinfo_kernel(t, level, typ, wave):
104 from hw_oracle import asm
105 lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)]
106 lines += [f"v_mov_b32 v{8 + i}, 0x{SENTINEL + i:08x}" for i in range(4)]
107 lines += [f"v_mov_b32 v2, {level}",
108 f"image_get_resinfo v[8:11], v2, s[8:15] dmask:0xf dim:{DIMS[typ]}",
109 "s_waitcnt vmcnt(0)",
110 "v_lshlrev_b32 v4, 4, v0",
111 "global_store_b128 v4, v[8:11], s[2:3]",
112 "s_endpgm"]
113 return asm.Kernel(lines, wave=wave, threads=1, words=4, raw=True)
114
115
116def lod_kernel(t, s, du, dv, wave):
117 """One quad: lane i reads u = 0.5 + (i & 1) * du, v = 0.5 + (i >> 1) * dv. Each lane stores clamped, raw, u, v."""
118 from hw_oracle import asm
119 lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)]
120 lines += [f"s_mov_b32 s{16 + i}, 0x{w:08x}" for i, w in enumerate(s)]
121 lines += ["v_and_b32 v5, 1, v0", "v_lshrrev_b32 v6, 1, v0", "v_cvt_f32_u32 v5, v5", "v_cvt_f32_u32 v6, v6",
122 f"v_mul_f32 v2, 0x{f2u(du):08x}, v5", f"v_mul_f32 v3, 0x{f2u(dv):08x}, v6",
123 "v_add_f32 v2, 0.5, v2", "v_add_f32 v3, 0.5, v3",
124 f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SENTINEL + 1:08x}",
125 "image_get_lod v[8:9], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D",
126 "s_waitcnt vmcnt(0)",
127 "v_mov_b32 v10, v2", "v_mov_b32 v11, v3",
128 "v_lshlrev_b32 v4, 4, v0",
129 "global_store_b128 v4, v[8:11], s[2:3]",
130 "s_endpgm"]
131 return asm.Kernel(lines, wave=wave, threads=4, words=16, raw=True)
132
133
134# ---- cases ----
135
136def resinfo_cases():
137 """(name, width, height, type, DEPTH field or None, base, last, level)."""
138 out = []
139 for w, h in ((16, 4), (64, 64)):
140 for depth in (None, 0, 5, 0x1FFF):
141 for level in (0, 1, 4, 5, 20):
142 out.append((f"2D {w}x{h} depth={depth} level={level}", w, h, TYPE_2D, depth, 0, 4, level))
143 for base, last in ((1, 4), (2, 3)):
144 for level in (0, 1, 2, 3):
145 out.append((f"2D 16x4 base={base} last={last} level={level}", 16, 4, TYPE_2D, 0, base, last, level))
146 for layers in (1, 6, 7, 16, 100):
147 for base in (0, 1):
148 for level in (0, 1, 2, 3, 5, 9):
149 out.append((f"2D array 256x256x{layers} base={base} level={level}",
150 256, 256, TYPE_2D_ARRAY, layers - 1, base, 8, level))
151 return out
152
153
154LODS = (-1.0, 0.0, 0.25, 0.5, 1.25, 2.75, 3.5, 7.0)
155SAMPLERS = [(mip, lo, hi, bias) for mip in (MIP_NONE, MIP_POINT, MIP_LINEAR)
156 for lo, hi, bias in ((0, 15, 0), (0, 0.25, 0), (0.5, 2.25, 0), (1, 1, 0), (5.5, 15, 0), (3, 2, 0),
157 (0, 15, 1.0), (0, 15, -0.5))]
158
159
160def lod_cases():
161 """(name, width, height, last, du, dv, sampler, expected LOD before bias). A 16x16 five-level image steps both
162 axes by the same texel count; the 64x4 seven-level image steps one axis only, which tells u from v."""
163 out = []
164 for samp in SAMPLERS:
165 for lod in LODS:
166 d = 2.0 ** lod / 16
167 out.append((f"16x16 mip={samp[0]} lod=[{samp[1]},{samp[2]}] bias={samp[3]} L={lod}", 16, 16, 4, d, d,
168 samp, lod))
169 for tx, ty, lod in ((1, 0, 0.0), (0, 1, 0.0), (4, 0, 2.0), (0, 4, 2.0), (4, 1, 2.0), (1, 4, 2.0), (8, 2, 3.0)):
170 out.append((f"64x4 du={tx} texels dv={ty} texels", 64, 4, 6, tx / 64, ty / 4, (MIP_LINEAR, 0, 15, 0), lod))
171 return out
172
173
174# ---- comparison ----
175
176def compare_resinfo(case, got):
177 name, w, h, typ, depth, base, last, level = case
178 want = resinfo_model(w, h, typ, depth if depth is not None else 0, base, last, level)
179 if typ == TYPE_2D_ARRAY and depth is None:
180 raise ValueError("a 2D array case needs its DEPTH field")
181 return want == list(got[:4]), want
182
183
184def compare_lod(case, got):
185 name, w, h, last, du, dv, (mip, lo, hi, bias), lod = case
186 want = lod_model(lod, mip, lo, hi, bias, last + 1)
187 lanes = [(u2f(got[4 * i]), u2f(got[4 * i + 1])) for i in range(4)]
188 return all(lane == want for lane in lanes), want, lanes
189
190
191def run(oracle, waves):
192 arch = oracle.arch
193 rcases, lcases = resinfo_cases(), lod_cases()
194 report = {"arch": arch, "resinfo": [], "lod": []}
195 bad = 0
196 for wave in waves:
197 kernels = [resinfo_kernel(tsharp_words(arch, w, h, typ, d, b, l), lv, typ, wave)
198 for _, w, h, typ, d, b, l, lv in rcases]
199 for case, got in zip(rcases, oracle.run(kernels)):
200 if isinstance(got, str) or len(got) < 4:
201 raise RuntimeError(f"{case[0]} wave{wave}: {got}")
202 ok, want = compare_resinfo(case, got)
203 bad += not ok
204 report["resinfo"].append({"case": case[0], "wave": wave, "got": got[:4], "rule": want, "match": ok})
205 if not ok:
206 print(f"MISMATCH resinfo wave{wave} {case[0]}: got {got[:4]}, rule {want}")
207 kernels = [lod_kernel(tsharp_words(arch, w, h, last=l), ssharp_words(*s), du, dv, wave)
208 for _, w, h, l, du, dv, s, _ in lcases]
209 for case, got in zip(lcases, oracle.run(kernels, words=16)):
210 if isinstance(got, str) or len(got) < 16:
211 raise RuntimeError(f"{case[0]} wave{wave}: {got}")
212 ok, want, lanes = compare_lod(case, got)
213 bad += not ok
214 report["lod"].append({"case": case[0], "wave": wave, "got": lanes, "rule": want, "match": ok})
215 if not ok:
216 print(f"MISMATCH get_lod wave{wave} {case[0]}: got {lanes}, rule {want}")
217 print(f"wave{wave}: image_get_resinfo {len(rcases)} cases, image_get_lod {len(lcases)} cases")
218 return bad, report
219
220
221# ---- self-test: values read on gfx1036 (Radeon Graphics of a Ryzen 9 9950X3D, Windows driver 32.0.21045.16010) ----
222
223MEASURED_RESINFO = [
224 ((16, 4, TYPE_2D, 0x3F, 0, 4, 0), [16, 4, 0, 5]),
225 ((16, 4, TYPE_2D, 0x1FFF, 0, 4, 1), [8, 2, 0, 5]),
226 ((16, 4, TYPE_2D, 0, 0, 4, 5), [0, 0, 0, 5]),
227 ((16, 4, TYPE_2D, 0, 1, 4, 0), [8, 2, 0, 4]),
228 ((16, 4, TYPE_2D, 0, 2, 3, 1), [2, 1, 0, 2]),
229 ((256, 256, TYPE_2D_ARRAY, 5, 0, 8, 1), [128, 128, 3, 9]),
230 ((256, 256, TYPE_2D_ARRAY, 6, 0, 8, 2), [64, 64, 1, 9]),
231 ((256, 256, TYPE_2D_ARRAY, 99, 1, 8, 3), [16, 16, 6, 8]),
232 ((16, 4, TYPE_2D_ARRAY, 5, 0, 2, 3), [0, 0, 0, 3]),
233]
234MEASURED_LOD = [ # (lod, mip, lo, hi, bias, levels) -> (clamped, raw)
235 ((0.25, MIP_NONE, 0, 15, 0, 5), (0.0, 0.25)),
236 ((0.5, MIP_POINT, 0, 15, 0, 5), (1.0, 0.5)),
237 ((2.75, MIP_POINT, 0.5, 2.25, 0, 5), (2.0, 2.75)),
238 ((6.0, MIP_POINT, 0, 15, 0, 5), (4.0, 6.0)),
239 ((0.5, MIP_LINEAR, 0, 0.25, 0, 5), (0.25, 0.5)),
240 ((-1.0, MIP_LINEAR, 0.5, 2.25, 0, 5), (0.5, -1.0)),
241 ((2.75, MIP_LINEAR, 0, 15, 0, 5), (2.75, 2.75)),
242 ((0.0, MIP_LINEAR, 5.5, 15, 0, 5), (4.0, 0.0)),
243 ((7.0, MIP_LINEAR, 3, 2, 0, 5), (3.0, 7.0)),
244 ((1.25, MIP_LINEAR, 0, 15, 1.0, 5), (2.25, 2.25)),
245 ((1.25, MIP_POINT, 0, 15, -0.5, 5), (1.0, 0.75)),
246]
247
248
249def self_test():
250 bad = 0
251 for args, want in MEASURED_RESINFO:
252 got = resinfo_model(*args)
253 if got != want:
254 print(f"resinfo {args}: rule {got}, measured {want}")
255 bad += 1
256 for args, want in MEASURED_LOD:
257 got = lod_model(*args)
258 if got != want:
259 print(f"get_lod {args}: rule {got}, measured {want}")
260 bad += 1
261 print(f"self-test: {len(MEASURED_RESINFO) + len(MEASURED_LOD)} measured values, {bad} disagree with the rules")
262 return 1 if bad else 0
263
264
265def main(argv=None):
266 p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
267 p.add_argument("--waves", default="32,64")
268 p.add_argument("--json", help="write every case, its result and the rule's answer here")
269 p.add_argument("--self-test", action="store_true")
270 a = p.parse_args(argv)
271 if a.self_test:
272 return self_test()
273 waves = [int(w) for w in a.waves.split(",")]
274 if any(w not in (32, 64) for w in waves):
275 p.error("--waves takes 32 and/or 64")
276 from hw_oracle import asm, runner
277 try:
278 oracle = runner.open_oracle()
279 except runner.Unavailable as e:
280 print(f"hardware oracle unavailable: {e}")
281 return 77
282 try:
283 if asm.family(oracle.arch) != "gfx10":
284 print(f"{oracle.arch} is not GFX10; this probe builds GFX10 descriptors")
285 return 77
286 print(f"hardware oracle: arch={oracle.arch}")
287 try:
288 bad, report = run(oracle, waves)
289 except RuntimeError as e:
290 print(f"harness error: {e}")
291 return 2
292 finally:
293 oracle.close()
294 if a.json:
295 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
296 json.dump(report, f, indent=1)
297 total = len(report["resinfo"]) + len(report["lod"])
298 print(f"{total - bad} of {total} results follow the rules, {bad} do not")
299 return 1 if bad else 0
300
301
302if __name__ == "__main__":
303 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
304 sys.stdout.reconfigure(errors="replace")
305 except (AttributeError, ValueError, OSError):
306 pass
307 sys.exit(main())