upleb.uk

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

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