upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 21:45:02 +0000
committerTreXito <81475944+TreXito@users.noreply.github.com>2026-11-23 21:45:02 +0000
commit3fede91c3f908cf42e7bf1843f0d0a4ddc11b7fe (patch)
treeb4c1b5e8c95166bec956f885c5ac9500a922559c /tests
parentf447410b49eb4eed2c94a19f7945d219f3f74b39 (diff)
parentc542d871c196eaa5ad32bf05733464ecbe800c00 (diff)
Merge #5029 (fuzz/f16misc-diff)
Diffstat (limited to 'tests')
-rw-r--r--tests/test_f16misc_diff.py354
1 files changed, 354 insertions, 0 deletions
diff --git a/tests/test_f16misc_diff.py b/tests/test_f16misc_diff.py
new file mode 100644
index 000000000..c3c9d5c86
--- /dev/null
+++ b/tests/test_f16misc_diff.py
@@ -0,0 +1,354 @@
1"""tools/f16misc_diff.py: the f16 reference against the words measured on RDNA2 hardware and the semantic tests'
2references, the generator's encoding rules, the sweep and edge grid, and short seeded differential runs. Standard
3library only; no GPU, no game files.
4
5The family is v_min3_f16, v_max3_f16, v_frexp_mant_f16, v_frexp_exp_i16_f16, v_ldexp_f16, v_fmamk_f16, v_fmaak_f16,
6v_pk_fmac_f16, v_fma_mix_f32, v_fma_mixlo_f16 and v_fma_mixhi_f16.
7
8The two single-rounding cases below are worked out by hand (f16: ulp 2^-10 on [1, 2), ties at the odd multiples of
92^-11; f32: ulp 2^-23 on [1, 2)). x * y is 2^-11 (1 + d / 2^21), so x * y + z is off an f16 tie by |d| 2^-32, less
10than half an f32 ulp:
11
12 P 0x2816 * 0x23d5 = 2^-11 (1 + 78 / 2^21); + 1.0 (0x3c00): once -> above the tie -> 0x3c01; f32 lands on the tie,
13 even is 0x3c00
14 M 0x2817 * 0x23d3 = 2^-11 (1 - 11 / 2^21); + (1 + 2^-10) (0x3c01): once -> below the tie -> 0x3c01; f32 lands on
15 the tie 1 + 3 * 2^-11, even is 0x3c02
16"""
17import inspect
18import io
19import os
20import random
21import re
22import sys
23import unittest
24from collections import Counter
25from contextlib import redirect_stdout
26
27ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28sys.path.insert(0, os.path.join(ROOT, "tools"))
29import f16misc_diff as f # noqa: E402 (puts tests/semantic on sys.path)
30import test_alu_frexp_ldexp_f16 as fl # noqa: E402
31import test_alu_min3_max3_med3_16_hw as mm # noqa: E402 (the gfx1036-measured min3/max3/med3 words)
32import test_alu_vop3_mods_hw as vm # noqa: E402 (the gfx1036-measured v_fma_mix_* words, among others)
33
34M16 = 0xFFFF
35BY_HAND = ( # (x, y, z, single rounding, double rounding)
36 (0x2816, 0x23D5, 0x3C00, 0x3C01, 0x3C00),
37 (0x2817, 0x23D3, 0x3C01, 0x3C01, 0x3C02),
38)
39
40
41def base_op(line):
42 return re.sub(r"_e(32|64)$", "", line.split()[0])
43
44
45def measured(rows):
46 """Run the hardware-oracle rows (text, v1, v2, v3, word in v4) of the family through the reference.
47 Returns (Counter of ok / unjudged reasons, the mismatching rows)."""
48 res, bad = Counter(), []
49 for text, v1, v2, v3, want in rows:
50 lines = text.split("\n")
51 if base_op(lines[-1]) not in f.FAMILY:
52 continue
53 mc = f.Machine()
54 for r, w in ((1, v1), (2, v2), (3, v3), (4, 0xDEADBEEF)):
55 mc.write_word(r, w)
56 try:
57 for line in lines:
58 op, args, _ = f.split_line(line)
59 if op == "s_mov_b32":
60 mc.s[int(args[0][1:])] = int(args[1], 16)
61 elif op == "v_mov_b32":
62 mc.write_word(mc.dst(args[0]), mc.v[int(args[1][1:])])
63 else:
64 f.step(line, mc)
65 except f.NotJudged as e:
66 res[str(e)] += 1
67 continue
68 none = [None, None]
69 if f.compare([mc.v[4], 0, 0, 0], [mc.state(4), none, none, none], [want, 0, 0, 0]):
70 bad.append((text, hex(v1), hex(v2), hex(v3), hex(want), hex(mc.v[4])))
71 else:
72 res["ok " + base_op(lines[-1])] += 1
73 return res, bad
74
75
76def one(line, **regs):
77 """The word left in v8 by ``line`` after the given v<n> words."""
78 mc = f.Machine()
79 mc.write_word(8, 0x5A5A5A5A)
80 for name, w in regs.items():
81 mc.write_word(int(name[1:]), w)
82 f.step(line, mc)
83 return mc.v[8], mc.state(8)
84
85
86class Reference(unittest.TestCase):
87 def test_min3_max3_match_every_measured_gfx1036_row(self):
88 res, bad = measured(mm.MEASURED)
89 self.assertEqual(bad, [])
90 want = sum(base_op(r[0]) in ("v_min3_f16", "v_max3_f16") for r in mm.MEASURED)
91 self.assertEqual(res["ok v_min3_f16"] + res["ok v_max3_f16"], want)
92 self.assertGreaterEqual(want, 100)
93
94 def test_fma_mix_matches_the_measured_gfx1036_rows(self):
95 res, bad = measured(vm.MEASURED)
96 self.assertEqual(bad, [])
97 self.assertGreaterEqual(res["ok v_fma_mix_f32"], 600)
98 self.assertGreaterEqual(res["ok v_fma_mixlo_f16"], 40)
99 self.assertGreaterEqual(res["ok v_fma_mixhi_f16"], 5)
100 self.assertEqual({k for k in res if not k.startswith("ok ")} - {"clamp of -0"}, set())
101
102 def test_frexp_ldexp_measured_rows(self):
103 for h, mant, ex in fl.MEASURED_FREXP:
104 self.assertEqual(one("v_frexp_mant_f16_e32 v8, v9", v9=h)[0] & M16, mant, hex(h))
105 self.assertEqual(one("v_frexp_exp_i16_f16_e32 v8, v9", v9=h)[0] & M16, ex, hex(h))
106 for h, n, word in fl.MEASURED_LDEXP:
107 got = one("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", v9=h | ((n & M16) << 16))[0] & M16
108 self.assertEqual(got, word, (hex(h), n))
109
110 def test_frexp_ldexp_match_the_semantic_reference_for_every_half(self):
111 mc = f.Machine()
112 bad = []
113 for h in range(1 << 16):
114 mc.write_word(9, h)
115 f.step("v_frexp_mant_f16_e32 v8, v9", mc)
116 f.step("v_frexp_exp_i16_f16_e32 v10, v9", mc)
117 if (mc.v[8] & M16, mc.v[10] & M16) != (fl.ref_mant(h), fl.ref_exp(h)):
118 bad.append(("frexp", hex(h)))
119 n = (-64, -25, -15, 1, 30, 100)[h % 6]
120 mc.write_word(9, h | ((n & M16) << 16))
121 f.step("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", mc)
122 if mc.v[8] & M16 != fl.ref_ldexp(h, n):
123 bad.append(("ldexp", hex(h), n))
124 self.assertEqual(bad[:5], [])
125
126 def test_fma_rounds_once(self):
127 for x, y, z, single, double in BY_HAND:
128 exact = f.fma(f.decode16(x), f.decode16(y), f.decode16(z))
129 self.assertEqual(f.encode16(f.round_to(exact, f.F16)), single)
130 self.assertEqual(f.encode16(f.round_to(f.round_to(exact, f.F32), f.F16)), double)
131 w, _ = one(f"v_fmamk_f16 v8, v9, 0x{y:04x}, v10", v9=x, v10=0xABCD0000 | z)
132 self.assertEqual(w, 0x5A5A0000 | single)
133 # lane 1 negates y and the accumulator: -(x * y + z)
134 w, _ = one("v_pk_fmac_f16 v8, v9, v10", v8=z | ((z ^ 0x8000) << 16), v9=x | (x << 16),
135 v10=y | ((y ^ 0x8000) << 16))
136 self.assertEqual(w, single | ((single ^ 0x8000) << 16))
137 w, _ = one("v_fma_mixhi_f16 v8, v9, v10, v11 op_sel:[0,0,0] op_sel_hi:[1,1,1]", v9=x, v10=y, v11=z)
138 self.assertEqual(w, (single << 16) | 0x5A5A)
139
140 def test_near_one_pairs(self):
141 self.assertGreaterEqual(len(f.NEAR_ONE), 20)
142 for a, c, d in f.NEAR_ONE:
143 self.assertEqual((1024 + a) * (2048 - c), (1 << 21) + d)
144 self.assertTrue(0 < abs(d) < 256 and 1 <= c <= 1023, (a, c, d))
145 self.assertTrue(any(d > 0 for _, _, d in f.NEAR_ONE) and any(d < 0 for _, _, d in f.NEAR_ONE))
146
147 def test_the_edge_grid_tells_single_from_double_rounding(self):
148 witnesses = Counter()
149 for op, words, *_ in f.grid_cases():
150 if f.FAMILY[op] not in ("fmamk", "fmaak", "pkfmac", "mixlo", "mixhi"):
151 continue
152 vals = [f.decode16(w) if w <= M16 else f.decode32(w) for w in words]
153 exact = f.fma(*vals)
154 if exact[0] == "num" and f.round_to(exact, f.F16) != f.round_to(f.round_to(exact, f.F32), f.F16):
155 witnesses[op] += 1
156 for op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16", "v_fma_mixlo_f16", "v_fma_mixhi_f16"):
157 self.assertGreaterEqual(witnesses[op], 4, op)
158
159 def test_min3_max3_nan_and_signed_zero(self):
160 cases = (("v_min3_f16", (0x7E00, 0x3C00, 0x4000), 0x3C00), ("v_max3_f16", (0x7E00, 0x3C00, 0xFE00), 0x3C00),
161 ("v_min3_f16", (0x0000, 0x8000, 0x0000), 0x8000), ("v_max3_f16", (0x8000, 0x0000, 0x8000), 0x0000),
162 ("v_min3_f16", (0xFC00, 0x7E00, 0x0001), 0xFC00), ("v_max3_f16", (0x7C01, 0x0001, 0x8001), 0x0001))
163 for op, (a, b, c), want in cases:
164 w, st = one(f"{op} v8, v9, v10, v11", v9=a, v10=b, v11=c)
165 self.assertEqual((w, st), (0x5A5A0000 | want, [None, None]), (op, a, b, c))
166 w, st = one("v_min3_f16 v8, v9, v10, v11 op_sel:[0,0,0,1]", v9=0x7E00, v10=0x7D00, v11=0xFE00)
167 self.assertEqual((w & M16, st), (0x5A5A, [None, "nan"])) # every operand NaN: any NaN
168
169 def test_output_modifiers(self):
170 # mul:2/mul:4/div:2 leave an f16 result as it is and clamp still acts; frexp_exp ignores both. The words
171 # main's translator gives, as measured on gfx1036 (docs/design.md).
172 for line, want in (("v_min3_f16 v8, v9, v10, v11 mul:2", 0xB800),
173 ("v_max3_f16 v8, v9, v10, v11 clamp div:2", 0x3C00),
174 ("v_frexp_mant_f16_e64 v8, v11 mul:4", 0x3900),
175 ("v_frexp_exp_i16_f16_e64 v8, v11 clamp mul:2", 0x0002),
176 ("v_ldexp_f16_e64 v8, v9, v12 div:2", 0x4600),
177 ("v_ldexp_f16_e64 v8, v11, v12 clamp mul:2", 0x3C00)):
178 w, st = one(line, v9=0x12343A00, v10=0x5678B800, v11=0x9ABC4100, v12=3)
179 self.assertEqual((w, st), (0x5A5A0000 | want, [None, None]), line)
180
181 def test_clamp(self):
182 for line, v9, want in (("v_frexp_mant_f16_e64 v8, v9 clamp", 0x7E00, 0x0000),
183 ("v_frexp_mant_f16_e64 v8, v9 clamp", 0xC400, 0x0000),
184 ("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0] clamp", 0x0003_4200, 0x3C00),
185 ("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0] clamp", 0x0001_7E00, 0x0000),
186 ("v_min3_f16 v8, v9, v9, v9 clamp", 0x0000_4000, 0x3C00)):
187 self.assertEqual(one(line, v9=v9)[0] & M16, want, line)
188 with self.assertRaises(f.NotJudged):
189 one("v_max3_f16 v8, v9, v9, v9 clamp", v9=0x7E00) # FClamp of a NaN is undefined in SPIR-V
190
191 def test_f32_operands_of_fma_mix_flush_denormals(self):
192 # 1 * (+denormal) + -0: the denormal reads as +0, so +0 + -0 = +0 (unflushed it would be the denormal)
193 w, _ = one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x3F800000, v10=0x007FFFFF, v11=0x80000000)
194 self.assertEqual(w, 0x00000000)
195 # 1 * (-denormal) + -0 = -0 + -0 = -0
196 w, _ = one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x3F800000, v10=0x80000001, v11=0x80000000)
197 self.assertEqual(w, 0x80000000)
198
199 def test_unjudged(self):
200 with self.assertRaises(f.NotJudged): # an f32 denormal result
201 one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x00800000, v10=0x3F000000, v11=0)
202 mc = f.Machine()
203 mc.write_word(9, 0x7FC00000, "w32")
204 with self.assertRaises(f.NotJudged): # half of an f32 NaN read as an f16
205 f.step("v_frexp_mant_f16_e32 v8, v9", mc)
206
207 def test_compare(self):
208 none = [None, None]
209 self.assertIsNone(f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none], [0x7FFF0000, 0, 0, 0]))
210 self.assertIn("f16 NaN", f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none],
211 [0x7C000000, 0, 0, 0]))
212 self.assertIn("expected 0x12340000", f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none],
213 [0x7E000001, 0, 0, 0]))
214 self.assertIsNone(f.compare([0, 0, 0, 0], [["w32", "w32"], none, none, none], [0xFFC00001, 0, 0, 0]))
215 self.assertIn("f32 NaN", f.compare([0, 0, 0, 0], [["w32", "w32"], none, none, none], [0x7F800000, 0, 0, 0]))
216
217 def test_harness_errors(self):
218 for line in ("v_add_f16 v8, v9, v10", "v_fmamk_f16 v8, v9, 0x3c00, v10 mul:2",
219 "v_frexp_mant_f16_e32 v8, v9 div:2", "v_ldexp_f16_e64 v8, v9, -v9"):
220 with self.assertRaises(f.HarnessError, msg=line):
221 one(line, v9=0x3C00, v10=0x3C00)
222
223
224class Generator(unittest.TestCase):
225 def test_generation_is_deterministic(self):
226 self.assertEqual(f.program(random.Random(5), 6), f.program(random.Random(5), 6))
227 self.assertEqual(f.grid_cases(), f.grid_cases())
228
229 def test_ops_subset_is_respected(self):
230 lines, used = f.program(random.Random(2), 20, ["v_ldexp_f16", "v_fma_mixhi_f16"])
231 self.assertEqual(set(used), {"v_ldexp_f16", "v_fma_mixhi_f16"})
232 self.assertTrue(all(base_op(line) in ("v_mov_b32", "s_mov_b32") + tuple(used) for line in lines))
233
234 def test_sweep_covers_every_op_and_kind(self):
235 cases = f.sweep_cases()
236 self.assertEqual({c[0] for c in cases}, set(f.FAMILY))
237 for op in f.FAMILY:
238 kinds = {k for c in cases if c[0] == op for k in c[2][:1]}
239 want = {"vgpr", "sgpr", "int", "float"} if f.FAMILY[op] in ("fmamk", "fmaak") else set(f.KINDS)
240 self.assertEqual(kinds, want, op)
241 # ldexp: 5 _e32 forms (src1 a VGPR) and 5 x 4 _e64 kind pairs but literal with literal
242 self.assertEqual(sum(c[0] == "v_ldexp_f16" for c in cases), 5 + 19)
243
244 def test_programs_are_encodable(self):
245 rng = random.Random(9)
246 for _ in range(400):
247 lines, _ = f.program(rng, 6)
248 for line in lines:
249 op, args, mods = f.split_line(line)
250 if op in ("v_mov_b32", "s_mov_b32"):
251 continue
252 srcs = args[1:]
253 lits = [a for a in srcs if a.startswith("0x")]
254 sgprs = [a for a in srcs if a.lstrip("-|").startswith("s")]
255 self.assertLessEqual(len(lits), 1, line)
256 if op.endswith("_e32") or op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16"):
257 vsrc = [a for i, a in enumerate(srcs) if i > 0 and not (op in ("v_fmamk_f16", "v_fmaak_f16")
258 and a.startswith("0x"))]
259 self.assertTrue(all(a.startswith("v") for a in vsrc), line)
260 else:
261 self.assertLessEqual(len(lits) + len(sgprs), 2, line)
262 if base_op(line) in f.MIX:
263 self.assertIn("op_sel_hi:", line)
264
265 def test_edge_grid(self):
266 cases = f.grid_cases()
267 by_op = Counter(c[0] for c in cases)
268 for op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16", "v_fma_mix_f32", "v_fma_mixlo_f16",
269 "v_fma_mixhi_f16"):
270 self.assertEqual(by_op[op], 240, op)
271 self.assertEqual(by_op["v_frexp_mant_f16"], 2 * len(f.F16_EDGES)) # plain and clamped
272 self.assertEqual(by_op["v_frexp_exp_i16_f16"], len(f.F16_EDGES))
273 self.assertEqual(by_op["v_ldexp_f16"], (12 + 3) * len(f.F16_EDGES))
274 clamped = {c[0] for c in cases if c[2:] == ("clamp",)}
275 self.assertEqual(clamped, {"v_frexp_mant_f16", "v_ldexp_f16"})
276 nans = (0x7E00, 0x7D00)
277 triples = [c[1] for c in cases if c[0] == "v_min3_f16"]
278 self.assertEqual(len(triples), 10 ** 3 - 8)
279 self.assertFalse(any(all(v in nans for v in w) for w in triples))
280
281 def test_exhaustive_programs_cover_every_half(self):
282 progs = list(f.exhaustive_programs(["v_frexp_exp_i16_f16"]))
283 self.assertEqual(len(progs), (1 << 16) // f.GRID_PER_PROGRAM)
284 seen = {int(line.split("0x")[1], 16) & M16 for _, lines in progs for line in lines
285 if re.match(r"v_mov_b32 v1[2-5], ", line)}
286 self.assertEqual(len(seen), 1 << 16)
287
288
289class Translated(unittest.TestCase):
290 def test_harness_canaries(self):
291 with redirect_stdout(io.StringIO()) as out:
292 ok = f.self_test()
293 self.assertTrue(ok, out.getvalue())
294
295 def test_short_seeded_run_matches(self):
296 counts, failure = f.run_suite(20, 3, 5)
297 self.assertEqual((failure, counts["skip"]), (None, {}))
298 self.assertEqual(counts["pass"] + sum(counts["unjudged"].values()), 20)
299
300 def test_sweep_matches_for_ldexp_and_mixhi(self):
301 counts, failure = f.run_sweep(4, ["v_ldexp_f16", "v_fma_mixhi_f16"])
302 self.assertEqual((failure, counts["skip"]), (None, {}))
303 self.assertGreater(counts["pass"], 100)
304
305 def test_edge_grid_matches_for_fmamk_and_min3(self):
306 counts, failure = f.run_grid(["v_fmamk_f16", "v_min3_f16"])
307 self.assertEqual((failure, counts["skip"]), (None, {}))
308 self.assertGreater(counts["events"]["v_fmamk_f16"]["tie"], 10)
309 self.assertGreater(counts["events"]["v_min3_f16"]["NaN"], 100)
310
311 def test_each_program_is_checked_before_the_next_is_made(self):
312 # a run holds one program's text at a time, not the whole --programs list
313 made, seen = [], []
314 real = f.program, f.sweep_program, f.grid_program, f.run_one
315
316 def count(fn):
317 return lambda *a: made.append(1) or fn(*a)
318 try:
319 f.program, f.sweep_program, f.grid_program = (count(fn) for fn in real[:3])
320 f.run_one = lambda lines, name, tmp, events=None: seen.append(len(made)) or ("match", None)
321 f.run_suite(5, 1)
322 f.run_sweep(1, ["v_ldexp_f16"])
323 f.run_grid(["v_min3_f16"])
324 finally:
325 f.program, f.sweep_program, f.grid_program, f.run_one = real
326 self.assertGreater(len(seen), 10)
327 self.assertEqual(seen, list(range(1, len(seen) + 1)))
328 self.assertTrue(inspect.isgenerator(f.exhaustive_programs()))
329
330 def test_fma_rounds_once_through_the_translator(self):
331 for x, y, z, single, _ in BY_HAND:
332 for line in (f"v_fmamk_f16 v8, v12, 0x{y:04x}, v8", f"v_fmaak_f16 v8, v12, v13, 0x{z:04x}",
333 "v_fma_mixlo_f16 v8, v12, v13, v14 op_sel:[0,0,0] op_sel_hi:[1,1,1]"):
334 lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in f.VGPRS]
335 lines += ["v_mov_b32 v8, 0x%08x" % (0xABCD0000 | z), "v_mov_b32 v12, 0x%08x" % x,
336 "v_mov_b32 v13, 0x%08x" % y, "v_mov_b32 v14, 0x%08x" % z, line]
337 self.assertEqual(f.reference(lines)[0][0] & M16, single, line)
338 self.assertIsNone(f.check(lines), line)
339
340 def test_a_wrong_translation_is_caught(self):
341 x, y, z, single, double = BY_HAND[0]
342 lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in f.VGPRS]
343 lines += [f"v_mov_b32 v8, 0x{z:08x}", f"v_mov_b32 v12, 0x{x:08x}", f"v_fmamk_f16 v8, v12, 0x{y:04x}, v8"]
344 self.assertIsNone(f.check(lines))
345 real = f.translate_listing
346 try:
347 f.translate_listing = lambda l, n, t: [(real(l, n, t)[0] & ~M16) | double] + real(l, n, t)[1:]
348 self.assertIn(f"expected 0x0000{single:04x}, actual 0x0000{double:04x}", f.check(lines))
349 finally:
350 f.translate_listing = real
351
352
353if __name__ == "__main__":
354 unittest.main()