upleb.uk

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

summaryrefslogtreecommitdiff
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
parentf447410b49eb4eed2c94a19f7945d219f3f74b39 (diff)
parentc542d871c196eaa5ad32bf05733464ecbe800c00 (diff)
Merge #5029 (fuzz/f16misc-diff)
-rw-r--r--docs/shader_validation.md53
-rw-r--r--tests/test_f16misc_diff.py354
-rw-r--r--tools/f16misc_diff.py1269
3 files changed, 1676 insertions, 0 deletions
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index a9578696b..1289a2947 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -1573,6 +1573,59 @@ test `test_valu_mul_legacy_denorm.py` checks the exact bit patterns and the two
1573output scaling. This is a translation for the **inferred game MODE**, not a claim of correctly handling dynamic 1573output scaling. This is a translation for the **inferred game MODE**, not a claim of correctly handling dynamic
1574denormal-preserving or IEEE modes; native gfx1013 measurements of these new fixtures were not available. 1574denormal-preserving or IEEE modes; native gfx1013 measurements of these new fixtures were not available.
1575 1575
1576### f16 misc ops (`tools/f16misc_diff.py`)
1577
1578None of the other fuzzers generates these eleven f16 ops: `v_min3_f16`, `v_max3_f16`, `v_frexp_mant_f16`,
1579`v_frexp_exp_i16_f16`, `v_ldexp_f16`, `v_fmamk_f16`, `v_fmaak_f16`, `v_pk_fmac_f16`, `v_fma_mix_f32`,
1580`v_fma_mixlo_f16` and `v_fma_mixhi_f16`. `tools/f16misc_diff.py` runs them through the translator and
1581`tests/semantic/spirv_mini_interp.py`, against an exact-rational model of the `docs/design.md` rows that shares no
1582code with the translator, and compares the four exported words bit for bit. The model:
1583
1584- f16 operands and results keep denormals. An f32 operand of `v_fma_mix*` reads a denormal as a zero of its sign
1585 (SHADER-298).
1586- Every fma rounds once, from the exact value.
1587- `min3`/`max3` ignore a NaN operand and order -0 below +0.
1588- `frexp_mant` sets the exponent to 14, `frexp_exp` gives the exponent that goes with it, `ldexp` takes S1 as an
1589 i16 clamped to [-64, 64] and rounds to nearest even into the denormal range.
1590- `clamp` on `frexp_mant` and `ldexp` takes a NaN or a negative result to +0.
1591- An output multiplier (`mul:2`, `mul:4`, `div:2`) changes nothing on these f16 results, and `clamp` still acts. On
1592 `frexp_exp`'s integer result `clamp` changes nothing either. Both were measured on gfx1036 in the game's MODE
1593 (f16 denormals kept); see the `design.md` rows for the f16 output modifiers and for `v_frexp`/`v_ldexp_f16`.
1594
1595`tests/test_f16misc_diff.py` pins the model to the gfx1036 words in `tests/semantic`: all 120 `min3`/`max3` rows of
1596`test_alu_min3_max3_med3_16_hw.py`, 718 of the 719 `v_fma_mix*` rows of `test_alu_vop3_mods_hw.py` (the other is a
1597clamp of -0, not judged) and the 24 measured `frexp`/`ldexp` rows. It also checks the model against the semantic
1598reference of `test_alu_frexp_ldexp_f16.py` on every f16 input.
1599
1600Sources are VGPRs, SGPRs, a literal and integer and float inline constants, within the GFX10 literal and
1601constant-bus limits. Modifiers are `neg`/`abs` on VOP3 register sources, `op_sel` on sources and the destination,
1602`op_sel_hi` on the `v_fma_mix*` sources, `clamp`, and an output multiplier on the VOP3 forms of `min3`/`max3`,
1603`frexp_mant`, `frexp_exp` and `ldexp`. `--self-test` pins the two refused forms, `neg` and `clamp` on
1604`v_pk_fmac_f16`, as expected rejections.
1605
1606A NaN the model computes matches any NaN, since payloads are not modelled. A NaN that only passes through is
1607compared exactly. Some programs are counted as not judged, with the reason:
1608- reading such a NaN as bits;
1609- an all-NaN `min3`/`max3` (the hardware returns src0's bits);
1610- the clamp of a NaN or a -0 through `FClamp`;
1611- an f32 denormal result of `v_fma_mix_f32`.
1612
1613Stages:
16141. A sweep of every source kind with every op and form.
16152. An edge grid of special values with fma near ties and cancellations.
1616 - Some near ties are off the tie by less than half an f32 ulp. There, an fma rounded to f32 and then to f16
1617 gives a different word, which is the bug class SHADER-55 fixed.
16183. Random seeded programs.
1619
1620`--exhaustive-f16` adds every f16 input through `frexp_mant`, `frexp_exp` and `ldexp`. A translator skip exits 1,
1621as a mismatch does.
1622
1623```
1624python -I tools/f16misc_diff.py --programs 3000 --seed 11 --max-ops 8
1625python -I tools/f16misc_diff.py --exhaustive-f16 --programs 0 --no-sweep
1626python -I tests/test_f16misc_diff.py
1627```
1628
1576 1629
1577### f16 transcendentals on the hardware (`tools/f16_trans_sweep.py`, FUZZ-29) 1630### f16 transcendentals on the hardware (`tools/f16_trans_sweep.py`, FUZZ-29)
1578 1631
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()
diff --git a/tools/f16misc_diff.py b/tools/f16misc_diff.py
new file mode 100644
index 000000000..a6d27f88a
--- /dev/null
+++ b/tools/f16misc_diff.py
@@ -0,0 +1,1269 @@
1r"""Differential fuzzer for the RDNA2 f16 VALU ops no other fuzzer generates (standard library only).
2
3Covers eleven opcodes that are on no `--list-ops` list and in no generator of the other fuzzers:
4
5 v_min3_f16 v_max3_f16 VOP3, three f16 -> f16, op_sel:[a,b,c,d], clamp
6 v_frexp_mant_f16 v_frexp_exp_i16_f16 VOP1 (_e32, _e64), f16 -> f16 / i16, op_sel:[a,d]
7 v_ldexp_f16 VOP2 (_e32, _e64), f16 * 2^i16 -> f16, op_sel:[a,b,d]
8 v_fmamk_f16 v_fmaak_f16 VOP2 with a literal K, f16 fma
9 v_pk_fmac_f16 VOP2, two f16 fmas into the packed accumulator
10 v_fma_mix_f32 v_fma_mixlo_f16 v_fma_mixhi_f16 VOP3P, f32 fma of f32 or f16 sources (op_sel_hi), clamp
11
12Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared:
13
14 * the reference below, written from the rules docs/design.md records for these ops, with exact rationals
15 (fractions.Fraction) and one round-to-nearest-even per result. It shares no code with the translator:
16 - f16 operands and results keep denormals (the MODE inferred for the game, denorm_mode_16_64 = 3); an f32
17 operand of v_fma_mix_* reads as a zero of its sign when it is denormal (denorm_mode_32 = 0, SHADER-298).
18 - fma: x * y + z exact, then rounded once (to f16, or to f32 for v_fma_mix_f32); |x| at or past the
19 rounding boundary of the largest finite value gives +-inf. An exact zero sum is -0 only when both the
20 product and the addend are -0.
21 - min3 / max3: a NaN operand is ignored, -0 orders below +0; the result is the chosen operand.
22 - frexp_mant: the input with its exponent set to 14 (mantissa in [0.5, 1), sign kept); frexp_exp: the
23 exponent that goes with it, as an i16. ldexp: S0 * 2^clamp(S1.i16, -64, 64), rounded to nearest even.
24 Zero gives a signed zero (exponent 0); inf and NaN pass through unchanged (exponent 0).
25 - clamp: to [0, 1] after the operation, before the rounding. On frexp_mant / ldexp a negative result and a
26 NaN give +0 (measured on gfx1036).
27 - output multipliers (mul:2, mul:4, div:2) change nothing: the hardware ignores them on an f16 result with
28 f16 denormals kept, and clamp still acts; on frexp_exp's integer result clamp changes nothing either
29 (measured on gfx1036, docs/design.md's f16 output modifier and v_frexp/ldexp_f16 rows).
30 - destinations: an f16 result goes to the half op_sel's last bit names (the low half for VOP1/VOP2 and
31 v_fma_mixlo_f16, the high half for v_fma_mixhi_f16) and the other half is kept; v_pk_fmac_f16 writes both
32 halves; v_fma_mix_f32 writes the word.
33 tests/test_f16misc_diff.py pins it to the words measured on RDNA2 that tests/semantic records, and
34 * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py.
35
36Comparison: bit for bit, except that a NaN the reference computed (an fma or a min3/max3 of all-NaN operands)
37matches any NaN: payloads are not modelled. A NaN that only passes through (frexp_mant, ldexp, a min3 operand)
38is compared exactly. A program is not judged (counted with the reason, not a failure) when it reads such a NaN as
39bits (an f32 operand made of an f16 NaN half, an i16 exponent, half of an f32 NaN), clamps a NaN or a -0 through
40min3/max3/fma_mix (the translator's FClamp of a NaN is undefined in SPIR-V; docs/design.md does not pin -0), or
41when v_fma_mix_f32 returns an f32 denormal (whether f32 denormal results flush is the MODE question, SHADER-35).
42
43Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` so every result
44is observed. Every destination is v8..v11, so later ops read earlier results.
45
46Sources: VGPR v8..v15, SGPR s4..s7, a hex literal, an integer inline constant (-16..64) and a float inline
47constant (0.5, 1.0, 2.0, 4.0, their negatives, 0.15915494). A 16-bit float operand reads the low half of a
48register or literal, a float inline constant as its f16 value, and an integer inline constant as the low half of
49its word (docs/design.md, "f16 inline constants"). An f32 operand of v_fma_mix_* reads a float inline constant as
50its f32 value. Every program is encodable on GFX10: at most one literal, at most two constant-bus reads in a VOP3
51or VOP3P op, and a VOP2 literal or SGPR only in src0.
52
53Modifiers: neg/abs on the register sources of the VOP3/VOP3P forms (not on ldexp's exponent); op_sel on register
54sources and the destination bit; clamp on min3/max3, frexp_mant, frexp_exp, ldexp and the fma_mix ops; an output
55multiplier on the VOP3 forms of min3/max3, frexp_mant, frexp_exp and ldexp. Not generated, on purpose: the
56modifiers the translator refuses (--self-test pins those as expected rejections), SDWA and DPP forms
57(tools/sdwa_diff.py's domain), and op_sel on a constant (only measured for some ops).
58
59Stages:
60 1. a sweep: every encodable source-kind combination of every op and form, twice, with random modifiers;
61 2. an edge grid: special values (zeros, denormals, the normal bounds, 1, the largest finite, inf, quiet and
62 signalling NaNs) through every op, frexp_mant and ldexp also with clamp, and fma near ties and cancellations,
63 four cases per program. Some near ties are off the tie by less than half an f32 ulp (NEAR_ONE), so an fma
64 rounded first to f32 and then to f16 gives a different word there;
65 3. random seeded programs.
66--exhaustive-f16 adds every f16 input through v_frexp_mant_f16, v_frexp_exp_i16_f16 and v_ldexp_f16 (eight
67exponents in turn).
68
69Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a
70translator skip (every generated form is one the translator takes), 2 on a harness error.
71
72Usage:
73 python -I tools/f16misc_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_ldexp_f16,v_fma_mix_f32]
74 python -I tools/f16misc_diff.py --exhaustive-f16 --programs 0 --no-sweep
75 python -I tools/f16misc_diff.py --list-ops
76 python -I tools/f16misc_diff.py --self-test
77"""
78import argparse
79import gc
80import os
81import random
82import re
83import struct
84import sys
85import tempfile
86import warnings
87from collections import Counter
88from fractions import Fraction
89
90HERE = os.path.dirname(os.path.abspath(__file__))
91TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE
92sys.dont_write_bytecode = True
93if TOOLS_DIR not in sys.path:
94 sys.path.insert(0, TOOLS_DIR)
95SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic")
96if SEM_DIR not in sys.path:
97 sys.path.insert(0, SEM_DIR)
98
99import rdna2spirv # noqa: E402
100from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402
101
102M32 = 0xFFFFFFFF
103M16 = 0xFFFF
104STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
105
106EXPORT = "exp mrt0 v8, v9, v10, v11 done vm"
107EXPORT_REGS = (8, 9, 10, 11)
108DSTS = (8, 9, 10, 11)
109VGPRS = tuple(range(8, 16))
110SGPRS = (4, 5, 6, 7)
111
112# op -> kind
113FAMILY = {
114 "v_min3_f16": "min3", "v_max3_f16": "max3",
115 "v_frexp_mant_f16": "mant", "v_frexp_exp_i16_f16": "exp", "v_ldexp_f16": "ldexp",
116 "v_fmamk_f16": "fmamk", "v_fmaak_f16": "fmaak",
117 "v_pk_fmac_f16": "pkfmac",
118 "v_fma_mix_f32": "mix32", "v_fma_mixlo_f16": "mixlo", "v_fma_mixhi_f16": "mixhi",
119}
120MIX = ("v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16")
121OP_FORMS = {
122 "v_min3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]",
123 "v_max3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]",
124 "v_frexp_mant_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]] [clamp]",
125 "v_frexp_exp_i16_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]]",
126 "v_ldexp_f16": "_e32 d, s0, vs1 | _e64 d, [-][|]s0[|], s1 [op_sel:[a,b,d]] [clamp]",
127 "v_fmamk_f16": "d, s0, K, vs1",
128 "v_fmaak_f16": "d, s0, vs1, K",
129 "v_pk_fmac_f16": "d, s0, vs1 (d is the accumulator)",
130 "v_fma_mix_f32": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]",
131 "v_fma_mixlo_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]",
132 "v_fma_mixhi_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]",
133}
134
135KINDS = ("vgpr", "sgpr", "lit", "int", "float")
136MODS = ("", "-", "|", "-|") # source modifiers on a register: none, neg, abs, neg(abs)
137FLOAT_INLINE = { # token -> (f32 word, f16 half)
138 "0.5": (0x3F000000, 0x3800), "-0.5": (0xBF000000, 0xB800), "1.0": (0x3F800000, 0x3C00),
139 "-1.0": (0xBF800000, 0xBC00), "2.0": (0x40000000, 0x4000), "-2.0": (0xC0000000, 0xC000),
140 "4.0": (0x40800000, 0x4400), "-4.0": (0xC0800000, 0xC400), "0.15915494": (0x3E22F983, 0x3118),
141}
142INT_INLINE = tuple(range(0, 65)) + tuple(range(-16, 0))
143OMODS = ("mul:2", "mul:4", "div:2")
144OMOD_KINDS = ("min3", "max3", "mant", "exp", "ldexp") # the VOP3 forms that have an omod field
145
146# Half states in the reference's register file: None (known bits), "nan" (an f16 NaN whose payload the reference
147# does not model) and "w32" (half of an f32 NaN whose payload it does not model).
148NAN16 = 0x7E00
149NAN32 = 0x7FC00000
150
151
152class HarnessError(Exception):
153 """The generator or the reference met something outside the modelled forms."""
154
155
156class NotJudged(Exception):
157 """The reference does not judge this program (the reason is counted)."""
158
159
160# ---- numbers: (kind, sign, magnitude), kind "num" / "inf" / "nan", magnitude a Fraction ----
161
162F16 = (11, -14, 15) # precision, smallest normal exponent, largest exponent
163F32 = (24, -126, 127)
164
165
166def _ilog2(q):
167 """floor(log2(q)) of a positive Fraction."""
168 e = q.numerator.bit_length() - q.denominator.bit_length()
169 if Fraction(2) ** e > q:
170 e -= 1
171 elif Fraction(2) ** (e + 1) <= q:
172 e += 1
173 return e
174
175
176def _round_even(q):
177 n = q.numerator // q.denominator
178 d = q - n
179 if d > Fraction(1, 2) or (d == Fraction(1, 2) and n % 2):
180 n += 1
181 return n
182
183
184def decode16(h):
185 sign = h >> 15
186 e, m = (h >> 10) & 0x1F, h & 0x3FF
187 if e == 0x1F:
188 return ("nan" if m else "inf", sign, None)
189 mag = Fraction(m, 1 << 24) if e == 0 else Fraction((1 << 10) | m) * Fraction(2) ** (e - 25)
190 return ("num", sign, mag)
191
192
193def decode32(w, flush=True):
194 """An f32 word; a denormal reads as a zero of its sign when ``flush``."""
195 sign = w >> 31
196 e, m = (w >> 23) & 0xFF, w & 0x7FFFFF
197 if e == 0xFF:
198 return ("nan" if m else "inf", sign, None)
199 if e == 0:
200 return ("num", sign, Fraction(0) if flush else Fraction(m, 1 << 149))
201 return ("num", sign, Fraction((1 << 23) | m) * Fraction(2) ** (e - 150))
202
203
204def round_to(value, fmt, events=None):
205 """Round a ("num", sign, exact magnitude) to the format, nearest even; past the largest finite gives inf."""
206 kind, sign, mag = value
207 if kind != "num" or mag == 0:
208 return value
209 p, emin, emax = fmt
210 e = max(_ilog2(mag), emin)
211 ulp = Fraction(2) ** (e - p + 1)
212 q = mag / ulp
213 if events is not None and q.denominator == 2:
214 events["tie"] += 1
215 r = _round_even(q) * ulp
216 if r > (Fraction(2) ** p - 1) * Fraction(2) ** (emax - p + 1):
217 if events is not None:
218 events["overflow"] += 1
219 return ("inf", sign, None)
220 if events is not None and 0 < r < Fraction(2) ** emin:
221 events["denormal result"] += 1
222 return ("num", sign, r)
223
224
225def encode16(value):
226 kind, sign, mag = value
227 if kind == "nan":
228 return (sign << 15) | NAN16
229 if kind == "inf":
230 return (sign << 15) | 0x7C00
231 if mag == 0:
232 return sign << 15
233 e = _ilog2(mag)
234 if e < -14:
235 m = mag * (1 << 24)
236 assert m.denominator == 1 and m < 1024, value
237 return (sign << 15) | int(m)
238 m = mag / Fraction(2) ** (e - 10) - 1024
239 assert m.denominator == 1 and 0 <= m < 1024 and e <= 15, value
240 return (sign << 15) | ((e + 15) << 10) | int(m)
241
242
243def encode32(value):
244 kind, sign, mag = value
245 if kind == "nan":
246 return (sign << 31) | NAN32
247 if kind == "inf":
248 return (sign << 31) | 0x7F800000
249 if mag == 0:
250 return sign << 31
251 e = _ilog2(mag)
252 if e < -126:
253 raise NotJudged("v_fma_mix_f32 gives an f32 denormal")
254 m = mag / Fraction(2) ** (e - 23) - (1 << 23)
255 assert m.denominator == 1 and 0 <= m < (1 << 23) and e <= 127, value
256 return (sign << 31) | ((e + 127) << 23) | int(m)
257
258
259def fma(x, y, z):
260 """x * y + z, exact (not rounded). Any NaN, inf * 0 and inf - inf give ("nan", 0, None)."""
261 if "nan" in (x[0], y[0], z[0]):
262 return ("nan", 0, None)
263 ps = x[1] ^ y[1]
264 if x[0] == "inf" or y[0] == "inf":
265 if (x[0] == "num" and x[2] == 0) or (y[0] == "num" and y[2] == 0):
266 return ("nan", 0, None)
267 if z[0] == "inf" and z[1] != ps:
268 return ("nan", 0, None)
269 return ("inf", ps, None)
270 if z[0] == "inf":
271 return z
272 pm = x[2] * y[2]
273 total = (-pm if ps else pm) + (-z[2] if z[1] else z[2])
274 if total == 0:
275 return ("num", 1 if (pm == 0 and z[2] == 0 and ps and z[1]) else 0, Fraction(0))
276 return ("num", 1 if total < 0 else 0, abs(total))
277
278
279def _key(v):
280 """Order for min/max: -inf < negative < -0 < +0 < positive < +inf."""
281 kind, sign, mag = v
282 if kind == "inf":
283 return (2 if not sign else 0, 0, 0)
284 return (1, -mag if sign else mag, 0 if sign else 1)
285
286
287def clamp01(v, nan_to_zero=False):
288 """Clamp to [0, 1]. A NaN gives +0 when ``nan_to_zero`` (frexp_mant, ldexp), else it is not judged; a -0
289 through FClamp is not judged either."""
290 kind, sign, mag = v
291 if kind == "nan":
292 if nan_to_zero:
293 return ("num", 0, Fraction(0))
294 raise NotJudged("clamp of a NaN")
295 if sign:
296 if kind == "num" and mag == 0 and not nan_to_zero:
297 raise NotJudged("clamp of -0")
298 return ("num", 0, Fraction(0))
299 if kind == "inf" or mag > 1:
300 return ("num", 0, Fraction(1))
301 return v
302
303
304# ---- the program text ----
305
306_REG = re.compile(r"([sv])(\d+)$")
307_SRC = re.compile(r"(-?)(\|?)([sv]\d+)\|?$")
308_MOD = re.compile(r"\s+(op_sel:\[[01](?:,[01])*\]|op_sel_hi:\[[01],[01],[01]\]|clamp|mul:[24]|div:2)$")
309
310
311def split_line(line):
312 """'op d, a, b mods' -> (op, [operands], [mods])."""
313 mods = []
314 while True:
315 m = _MOD.search(line)
316 if not m:
317 break
318 mods.insert(0, m.group(1))
319 line = line[:m.start()]
320 op, _, rest = line.partition(" ")
321 return op, [t.strip() for t in rest.split(",")], mods
322
323
324def _bits(mods, name, n):
325 m = next((x for x in mods if x.startswith(name + ":")), None)
326 if m is None:
327 return [0] * n
328 b = [int(x) for x in m.split("[")[1].rstrip("]").split(",")]
329 if len(b) != n:
330 raise HarnessError(f"{m}: want {n} bits")
331 return b
332
333
334class Machine:
335 """The reference's register file: words plus per-half NaN states (see NAN16 above)."""
336
337 def __init__(self):
338 self.v = {}
339 self.s = {}
340 self.st = {} # vgpr -> [lo state, hi state]
341
342 def state(self, r):
343 return self.st.setdefault(r, [None, None])
344
345 def raw(self, tok):
346 """(32-bit word, [lo state, hi state], kind) of a source token, modifiers stripped."""
347 m = _SRC.match(tok)
348 if m:
349 reg = m.group(3)
350 k, i = reg[0], int(reg[1:])
351 if k == "v":
352 if i not in self.v:
353 raise HarnessError(f"v{i} read before it is written")
354 return self.v[i], list(self.state(i)), "vgpr"
355 if i not in self.s:
356 raise HarnessError(f"s{i} read before it is written")
357 return self.s[i], [None, None], "sgpr"
358 if tok in FLOAT_INLINE:
359 return None, [None, None], "float"
360 if tok.startswith("0x"):
361 return int(tok, 16), [None, None], "lit"
362 try:
363 n = int(tok)
364 except ValueError:
365 raise HarnessError(f"unknown source {tok!r}") from None
366 if n not in INT_INLINE:
367 raise HarnessError(f"{n} is not an inline constant")
368 return n & M32, [None, None], "int"
369
370 def f16(self, tok, hi=0):
371 """An f16 operand: (value, known bits or None). neg/abs applied."""
372 m = _SRC.match(tok)
373 mod = (m.group(1) + m.group(2)) if m else ""
374 base = m.group(3) if m else tok
375 if base in FLOAT_INLINE:
376 h = 0 if hi else FLOAT_INLINE[base][1]
377 st = None
378 else:
379 w, sts, _ = self.raw(base)
380 h = (w >> 16) & M16 if hi else w & M16
381 st = sts[1 if hi else 0]
382 if st == "w32":
383 raise NotJudged("half of an f32 NaN read as an f16")
384 if "|" in mod:
385 h &= 0x7FFF
386 if mod.startswith("-"):
387 h ^= 0x8000
388 if st == "nan":
389 return ("nan", h >> 15, None), None
390 return decode16(h), h
391
392 def f32(self, tok):
393 """An f32 operand of v_fma_mix_*: (value, None); a denormal reads as a signed zero."""
394 m = _SRC.match(tok)
395 mod = (m.group(1) + m.group(2)) if m else ""
396 base = m.group(3) if m else tok
397 if base in FLOAT_INLINE:
398 w, sts = FLOAT_INLINE[base][0], [None, None]
399 else:
400 w, sts, _ = self.raw(base)
401 if sts == ["w32", "w32"]:
402 return ("nan", 0, None)
403 if sts != [None, None]:
404 raise NotJudged("an f16 NaN of unmodelled payload read as f32 bits")
405 if "|" in mod:
406 w &= 0x7FFFFFFF
407 if mod.startswith("-"):
408 w ^= 0x80000000
409 return decode32(w, flush=True)
410
411 def i16(self, tok, hi=0):
412 if _SRC.match(tok) and tok[0] in "-|":
413 raise HarnessError("modifier on an integer operand")
414 w, sts, kind = self.raw(tok)
415 if kind == "float":
416 raise HarnessError("float constant as an i16")
417 if sts[1 if hi else 0] is not None:
418 raise NotJudged("an unmodelled NaN payload read as an i16")
419 h = (w >> 16) & M16 if hi else w & M16
420 return h - 0x10000 if h & 0x8000 else h
421
422 def dst(self, tok):
423 m = _REG.match(tok)
424 if not m or m.group(1) != "v":
425 raise HarnessError(f"destination {tok!r}")
426 return int(m.group(2))
427
428 def write_half(self, r, hi, h, st=None):
429 old = self.v.get(r, 0)
430 sts = self.state(r)
431 if hi:
432 self.v[r] = (old & M16) | ((h & M16) << 16)
433 else:
434 self.v[r] = (old & 0xFFFF0000) | (h & M16)
435 sts[1 if hi else 0] = st
436
437 def write_word(self, r, w, st=None):
438 self.v[r] = w & M32
439 self.st[r] = [st, st]
440
441
442def _out16(value):
443 """(bits, state) of an f16 result; a NaN the reference computed has no modelled payload."""
444 if value[0] == "nan":
445 return NAN16, "nan"
446 return encode16(value), None
447
448
449def _count_in(events, op, *vals):
450 if events is None:
451 return
452 ev = events.setdefault(op, Counter())
453 for v in vals:
454 if v[0] == "nan":
455 ev["NaN"] += 1
456 elif v[0] == "inf":
457 ev["inf"] += 1
458 elif v[2] != 0 and v[2] < Fraction(1, 1 << 14):
459 ev["denormal"] += 1
460
461
462def step(line, mc, events=None):
463 """Run one op line on the Machine."""
464 op_full, args, mods = split_line(line)
465 op = op_full
466 for suf in ("_e32", "_e64"):
467 if op.endswith(suf):
468 op = op[:-len(suf)]
469 kind = FAMILY.get(op)
470 if kind is None:
471 raise HarnessError(f"op {op_full!r} is not in the family")
472 ev = None if events is None else events.setdefault(op, Counter())
473 d = mc.dst(args[0])
474 clamp = "clamp" in mods
475 # An output multiplier is a no-op on these f16 (and i16) results in the game's MODE (gfx1036): nothing to apply.
476 if any(m in OMODS for m in mods) and (kind not in OMOD_KINDS or op_full.endswith("_e32")):
477 raise HarnessError(f"output modifier on a form without one: {line}")
478 if kind in ("min3", "max3"):
479 sel = _bits(mods, "op_sel", 4)
480 vals = [mc.f16(t, sel[i])[0] for i, t in enumerate(args[1:4])]
481 _count_in(events, op, *vals)
482 live = [v for v in vals if v[0] != "nan"]
483 if not live:
484 r = ("nan", 0, None) # the hardware returns src0's bits, the translator a quiet NaN: any NaN
485 else:
486 r = (min if kind == "min3" else max)(live, key=_key)
487 if clamp:
488 r = clamp01(r)
489 h, st = _out16(r)
490 mc.write_half(d, sel[3], h, st)
491 elif kind in ("mant", "exp"):
492 sel = _bits(mods, "op_sel", 2)
493 v, h = mc.f16(args[1], sel[0])
494 _count_in(events, op, v)
495 if kind == "exp": # clamp (and an omod) leave the integer result as it is (gfx1036)
496 e = _ilog2(v[2]) + 1 if v[0] == "num" and v[2] != 0 else 0
497 mc.write_half(d, sel[1], e & M16)
498 return
499 if v[0] == "num" and v[2] != 0:
500 r = ("num", v[1], v[2] / Fraction(2) ** (_ilog2(v[2]) + 1))
501 else:
502 r = v
503 if clamp:
504 r = clamp01(r, nan_to_zero=True)
505 if r[0] == "nan":
506 mc.write_half(d, sel[1], NAN16 if h is None else h, "nan" if h is None else None)
507 else:
508 mc.write_half(d, sel[1], encode16(r))
509 elif kind == "ldexp":
510 sel = _bits(mods, "op_sel", 3)
511 v, h = mc.f16(args[1], sel[0])
512 n = max(-64, min(64, mc.i16(args[2], sel[1])))
513 _count_in(events, op, v)
514 if v[0] == "num" and v[2] != 0:
515 r = round_to(("num", v[1], v[2] * Fraction(2) ** n), F16, ev)
516 else:
517 r = v
518 if clamp:
519 r = clamp01(r, nan_to_zero=True)
520 if r[0] == "nan":
521 mc.write_half(d, sel[2], NAN16 if h is None else h, "nan" if h is None else None)
522 else:
523 mc.write_half(d, sel[2], encode16(r))
524 elif kind in ("fmamk", "fmaak"):
525 a = mc.f16(args[1])[0]
526 b = mc.f16(args[2])[0]
527 c = mc.f16(args[3])[0]
528 _count_in(events, op, a, b, c)
529 h, st = _out16(round_to(fma(a, b, c), F16, ev))
530 mc.write_half(d, 0, h, st)
531 elif kind == "pkfmac":
532 acc = []
533 for hi in (0, 1):
534 a = mc.f16(args[1], hi)[0]
535 b = mc.f16(args[2], hi)[0]
536 c = mc.f16(args[0], hi)[0]
537 _count_in(events, op, a, b, c)
538 acc.append(_out16(round_to(fma(a, b, c), F16, ev)))
539 for hi in (0, 1):
540 mc.write_half(d, hi, acc[hi][0], acc[hi][1])
541 else: # v_fma_mix_*
542 sel = _bits(mods, "op_sel", 3)
543 shi = _bits(mods, "op_sel_hi", 3)
544 vals = [mc.f16(t, sel[i])[0] if shi[i] else mc.f32(t) for i, t in enumerate(args[1:4])]
545 _count_in(events, op, *vals)
546 r = fma(*vals)
547 if clamp:
548 r = clamp01(r)
549 if kind == "mix32":
550 r = round_to(r, F32, ev)
551 if r[0] == "nan":
552 mc.write_word(d, NAN32, "w32")
553 else:
554 mc.write_word(d, encode32(r))
555 else:
556 h, st = _out16(round_to(r, F16, ev))
557 mc.write_half(d, 1 if kind == "mixhi" else 0, h, st)
558
559
560def reference(lines, events=None):
561 """Run the program; returns (four exported words, per-word half states). Raises NotJudged."""
562 mc = Machine()
563 for line in lines:
564 op, args, _ = split_line(line)
565 if op == "v_mov_b32":
566 mc.write_word(mc.dst(args[0]), int(args[1], 16))
567 elif op == "s_mov_b32":
568 mc.s[int(args[0][1:])] = int(args[1], 16) & M32
569 else:
570 step(line, mc, events)
571 return [mc.v[r] for r in EXPORT_REGS], [list(mc.state(r)) for r in EXPORT_REGS]
572
573
574def compare(want, states, got):
575 """None when every judged bit agrees, else a description of the first difference."""
576 for i, (w, sts, g) in enumerate(zip(want, states, got)):
577 g &= M32
578 if sts == ["w32", "w32"]:
579 if not ((g >> 23) & 0xFF == 0xFF and g & 0x7FFFFF):
580 return f"word {i} (v{EXPORT_REGS[i]}): expected an f32 NaN, actual 0x{g:08x}"
581 continue
582 for hi in (0, 1):
583 st = sts[hi]
584 wh, gh = (w >> (16 * hi)) & M16, (g >> (16 * hi)) & M16
585 if st == "w32":
586 continue
587 if st == "nan":
588 if not ((gh >> 10) & 0x1F == 0x1F and gh & 0x3FF):
589 return (f"word {i} (v{EXPORT_REGS[i]}) {'high' if hi else 'low'} half: expected an f16 NaN, "
590 f"actual 0x{g:08x}")
591 elif wh != gh:
592 return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}"
593 return None
594
595
596# ---- the generator ----
597
598F16_EDGES = (0x0000, 0x8000, 0x0001, 0x8001, 0x0200, 0x03FF, 0x83FF, 0x0400, 0x8400, 0x0401, 0x3555, 0x3800,
599 0xB800, 0x3BFF, 0x3C00, 0xBC00, 0x3C01, 0x4000, 0xC000, 0x5640, 0x7800, 0x7BFF, 0xFBFF, 0x7C00,
600 0xFC00, 0x7C01, 0xFC01, 0x7D00, 0x7E00, 0xFE00, 0x7FFF)
601F32_EDGES = (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF, 0x00800000, 0x3F800000, 0xBF800000, 0x3F000000,
602 0x477FE000, 0x477FF000, 0x477FEFFF, 0x387FC000, 0x33800000, 0x33000000, 0x7F7FFFFF, 0x7F800000,
603 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7FA00000, 0x40490FDB)
604I16_EDGES = (0, 1, -1, 2, -2, 10, -10, 14, -14, 15, -15, 16, -16, 24, -24, 25, -25, 29, 30, -30, 31, 40, -40,
605 63, -63, 64, -64, 65, -65, 100, -100, 32767, -32768)
606
607
608def _rand_f16(rng):
609 r = rng.random()
610 if r < 0.3:
611 return rng.choice(F16_EDGES)
612 if r < 0.4:
613 return (rng.getrandbits(1) << 15) | rng.randrange(1, 0x400) # denormal
614 if r < 0.5:
615 return rng.getrandbits(16)
616 e = rng.randrange(1, 31) if rng.random() < 0.3 else rng.randrange(11, 20) # mostly near 1
617 return (rng.getrandbits(1) << 15) | (e << 10) | rng.getrandbits(10)
618
619
620def _rand_f32(rng):
621 r = rng.random()
622 if r < 0.3:
623 return rng.choice(F32_EDGES)
624 if r < 0.4:
625 return rng.getrandbits(32)
626 e = rng.randrange(1, 255) if rng.random() < 0.3 else rng.randrange(100, 145)
627 return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23)
628
629
630def _seed_word(rng):
631 r = rng.random()
632 if r < 0.6:
633 return _rand_f16(rng) | (_rand_f16(rng) << 16)
634 if r < 0.8:
635 return _rand_f32(rng)
636 return (rng.choice(I16_EDGES) & M16) | (_rand_f16(rng) << 16)
637
638
639def _source(rng, kind):
640 """A source token of ``kind`` (no modifier)."""
641 if kind == "vgpr":
642 return f"v{rng.choice(VGPRS)}"
643 if kind == "sgpr":
644 return f"s{rng.choice(SGPRS)}"
645 if kind == "lit":
646 r = rng.random()
647 if r < 0.5:
648 return f"0x{_rand_f16(rng) | (_rand_f16(rng) << 16):08x}"
649 if r < 0.8:
650 return f"0x{_rand_f32(rng):08x}"
651 return f"0x{(rng.choice(I16_EDGES) & M16) | (rng.getrandbits(16) << 16):08x}"
652 if kind == "int":
653 return str(rng.choice(INT_INLINE))
654 return rng.choice(tuple(FLOAT_INLINE))
655
656
657def encodable(kinds, form):
658 """GFX10: one literal, VOP3/VOP3P at most two constant-bus reads (SGPRs and the literal); VOP1/VOP2 e32 take a
659 literal or SGPR only in src0 (and VOP2 vsrc1 is a VGPR)."""
660 lits = sum(k == "lit" for k in kinds)
661 bus = sum(k in ("sgpr", "lit") for k in kinds)
662 if lits > 1:
663 return False
664 if form == "vop3":
665 return bus <= 2
666 return all(k == "vgpr" for k in kinds[1:])
667
668
669def _reg_mod(rng, tok, kind):
670 if kind not in ("vgpr", "sgpr"):
671 return tok
672 m = rng.choice(MODS)
673 return f"{'-' if m.startswith('-') else ''}{'|' if '|' in m else ''}{tok}{'|' if '|' in m else ''}"
674
675
676def op_line(rng, op, kinds=None, form=None, mods=True, values=None):
677 """One line of ``op``. ``kinds`` fixes the source kinds (else random), ``form`` the encoding ("e32"/"e64" for
678 VOP1/VOP2 ops), ``values`` optional exact source tokens."""
679 kind = FAMILY[op]
680 d = f"v{rng.choice(DSTS)}"
681
682 def pick(n, allowed=KINDS, vop3=True):
683 while True:
684 ks = list(kinds) if kinds else [rng.choice(allowed) for _ in range(n)]
685 if encodable(ks, "vop3" if vop3 else "vop2"):
686 return ks
687 if kinds:
688 raise HarnessError(f"{op}: {kinds} not encodable")
689
690 if kind in ("min3", "max3") or kind in ("mix32", "mixlo", "mixhi"):
691 ks = pick(3)
692 toks = values or [_source(rng, k) for k in ks]
693 srcs = [_reg_mod(rng, t, k) if mods else t for t, k in zip(toks, ks)]
694 if kind in ("min3", "max3"):
695 sel = [rng.getrandbits(1) if k in ("vgpr", "sgpr") else 0 for k in ks] + [rng.getrandbits(1)]
696 extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else ""
697 else:
698 shi = [rng.getrandbits(1) for _ in ks]
699 sel = [rng.getrandbits(1) if (k in ("vgpr", "sgpr") and h) else 0 for k, h in zip(ks, shi)]
700 extra = f" op_sel:[{','.join(map(str, sel))}] op_sel_hi:[{','.join(map(str, shi))}]"
701 if mods and rng.random() < 0.25:
702 extra += " clamp"
703 if kind in ("min3", "max3") and mods and rng.random() < 0.2:
704 extra += " " + rng.choice(OMODS)
705 return f"{op} {d}, {', '.join(srcs)}{extra}", ks
706 if kind in ("mant", "exp"):
707 form = form or rng.choice(("e32", "e64"))
708 ks = pick(1)
709 tok = values[0] if values else _source(rng, ks[0])
710 if form == "e32":
711 return f"{op}_e32 {d}, {tok}", ks
712 src = _reg_mod(rng, tok, ks[0]) if mods else tok
713 sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)]
714 extra = f" op_sel:[{sel[0]},{sel[1]}]" if any(sel) or rng.random() < 0.2 else ""
715 if mods and rng.random() < 0.25:
716 extra += " clamp"
717 if mods and rng.random() < 0.2:
718 extra += " " + rng.choice(OMODS)
719 return f"{op}_e64 {d}, {src}{extra}", ks
720 if kind == "ldexp":
721 form = form or rng.choice(("e32", "e64"))
722 if form == "e32":
723 ks = pick(2, vop3=False) if kinds else [rng.choice(KINDS), "vgpr"]
724 toks = values or [_source(rng, ks[0]), _source(rng, "vgpr")]
725 return f"{op}_e32 {d}, {toks[0]}, {toks[1]}", ks
726 while True:
727 ks = list(kinds) if kinds else [rng.choice(KINDS), rng.choice(("vgpr", "sgpr", "lit", "int"))]
728 if ks[1] == "float":
729 raise HarnessError("float constant as ldexp's exponent")
730 if encodable(ks, "vop3"):
731 break
732 if kinds:
733 raise HarnessError(f"{op}: {kinds} not encodable")
734 toks = values or [_source(rng, k) for k in ks]
735 src0 = _reg_mod(rng, toks[0], ks[0]) if mods else toks[0]
736 sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0,
737 rng.getrandbits(1) if ks[1] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)]
738 extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else ""
739 if mods and rng.random() < 0.25:
740 extra += " clamp"
741 if mods and rng.random() < 0.2:
742 extra += " " + rng.choice(OMODS)
743 return f"{op}_e64 {d}, {src0}, {toks[1]}{extra}", ks
744 if kind in ("fmamk", "fmaak"):
745 k0 = kinds[0] if kinds else rng.choice(("vgpr", "sgpr", "int", "float"))
746 ks = [k0, "vgpr"]
747 toks = values or [_source(rng, k0), _source(rng, "vgpr"), f"0x{_rand_f16(rng):04x}"]
748 if kind == "fmamk":
749 return f"{op} {d}, {toks[0]}, {toks[2]}, {toks[1]}", ks
750 return f"{op} {d}, {toks[0]}, {toks[1]}, {toks[2]}", ks
751 # v_pk_fmac_f16
752 k0 = kinds[0] if kinds else rng.choice(KINDS)
753 ks = [k0, "vgpr"]
754 toks = values or [_source(rng, k0), _source(rng, "vgpr")]
755 return f"{op} {d}, {toks[0]}, {toks[1]}", ks
756
757
758def seeds(rng):
759 lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in VGPRS]
760 lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in SGPRS]
761 return lines
762
763
764def program(rng, n_ops, ops=None):
765 """A random program: seeds, n_ops family ops, the export. Returns (lines, the ops used)."""
766 ops = list(ops or FAMILY)
767 lines = seeds(rng)
768 used = []
769 for _ in range(n_ops):
770 op = rng.choice(ops)
771 lines.append(op_line(rng, op)[0])
772 used.append(op)
773 return lines, used
774
775
776def sweep_cases(ops=None):
777 """(op, form, kinds) for every encodable source-kind combination of every op and form."""
778 cases = []
779 for op in ops or FAMILY:
780 kind = FAMILY[op]
781 if kind in ("min3", "max3", "mix32", "mixlo", "mixhi"):
782 for a in KINDS:
783 for b in KINDS:
784 for c in KINDS:
785 if encodable([a, b, c], "vop3"):
786 cases.append((op, None, (a, b, c)))
787 elif kind in ("mant", "exp"):
788 for form in ("e32", "e64"):
789 for a in KINDS:
790 cases.append((op, form, (a,)))
791 elif kind == "ldexp":
792 for a in KINDS:
793 cases.append((op, "e32", (a, "vgpr")))
794 for b in ("vgpr", "sgpr", "lit", "int"):
795 if encodable([a, b], "vop3"):
796 cases.append((op, "e64", (a, b)))
797 elif kind in ("fmamk", "fmaak"):
798 for a in ("vgpr", "sgpr", "int", "float"):
799 cases.append((op, None, (a, "vgpr")))
800 else:
801 for a in KINDS:
802 cases.append((op, None, (a, "vgpr")))
803 return cases
804
805
806SWEEP_REPEAT = 2
807
808
809def sweep_program(case, rng):
810 op, form, kinds = case
811 return seeds(rng) + [op_line(rng, op, kinds, form)[0]]
812
813
814GRID_PER_PROGRAM = 4
815_GRID_RNG_SEED = "f16misc_diff:grid"
816
817
818def grid_cases(ops=None):
819 """(op, source words[, "clamp"]) cases: special values through every op. Each case is one op line reading
820 v12..v15; frexp_mant and ldexp also run the edges with clamp (a NaN gives +0)."""
821 rng = random.Random(_GRID_RNG_SEED)
822 ops = list(ops or FAMILY)
823 cases = []
824 edges = F16_EDGES
825 for op in ops:
826 kind = FAMILY[op]
827 if kind in ("mant", "exp"):
828 for h in edges:
829 cases.append((op, (h | (rng.getrandbits(16) << 16),)))
830 if kind == "mant":
831 for h in edges:
832 cases.append((op, (h | (rng.getrandbits(16) << 16),), "clamp"))
833 elif kind == "ldexp":
834 for h in edges:
835 for n in (-64, -25, -24, -15, -1, 0, 1, 15, 29, 30, 64, 100):
836 cases.append((op, (h, n & M16)))
837 for h in edges:
838 for n in (-1, 0, 1):
839 cases.append((op, (h, n & M16), "clamp"))
840 elif kind in ("min3", "max3"):
841 pick = (0x0000, 0x8000, 0x0001, 0x3C00, 0xBC00, 0x7C00, 0xFC00, 0x7E00, 0x7D00, 0x4000)
842 for a in pick:
843 for b in pick:
844 for c in pick:
845 if (a, b, c).count(0x7E00) + (a, b, c).count(0x7D00) == 3:
846 continue # every operand NaN: payload not modelled, see the docstring
847 cases.append((op, (a, b, c)))
848 else:
849 for _ in range(240):
850 cases.append((op, _fma_case(rng, kind)))
851 return cases
852
853
854def _pow2_16(e, mant=0):
855 """The f16 2^e * (1 + mant/1024), e in [-14, 15]."""
856 return ((e + 15) << 10) | mant
857
858
859# (a, c, d): the f16 mantissas 1 + a/1024 and (2048 - c)/2048 multiply to 1 + d/2^21 with 0 < |d| < 256. Added to
860# half an ulp of an f16 z, that product is off the tie by less than half an f32 ulp of the sum: an f32 fma rounds
861# it onto the tie and the f16 rounding then goes to even, so an fma rounded twice is wrong in about half the cases.
862NEAR_ONE = tuple((a, c, (1024 + a) * (2048 - c) - (1 << 21))
863 for a in range(1, 64) for c in range(max(1, 2 * a - 3), 2 * a + 4)
864 if 0 < abs((1024 + a) * (2048 - c) - (1 << 21)) < 256)
865
866
867def _tie_case(rng, f32_addend):
868 """x * y + z with x * y = +-half an ulp of z, or a hair above or below it: z + x*y is a rounding tie (or the
869 nearest non-tie) of the result format (f16, or f32 when ``f32_addend``). x and y are f16 powers of two times
870 1, 1 + 2^-10 or 1 - 2^-11, or a NEAR_ONE pair (x * y = 2^k (1 + d/2^21))."""
871 if f32_addend:
872 ez = rng.randrange(125, 170) # biased f32 exponent of z; half its ulp is 2^(ez - 151)
873 z = (rng.getrandbits(1) << 31) | (ez << 23) | rng.getrandbits(23)
874 k = ez - 151
875 else:
876 ez = rng.randrange(5, 31) # biased f16 exponent; half an ulp is 2^(ez - 26)
877 z = (rng.getrandbits(1) << 15) | (ez << 10) | rng.getrandbits(10)
878 k = ez - 26
879 a = max(-14, min(15, k // 2))
880 b = k - a
881 if not -14 <= b <= 15:
882 return (0x3C00, 0x3C00, z)
883 sx = rng.getrandbits(1) << 15
884 if rng.random() < 0.4 and b - 1 >= -14:
885 am, c, _ = rng.choice(NEAR_ONE)
886 return (_pow2_16(a, am) | sx, _pow2_16(b - 1, 1024 - c), z)
887 mant, eb = rng.choice(((0, b), (0, b), (1, b), (0x3FF, b - 1))) # 1, 1 + 2^-10, (2 - 2^-10) / 2
888 if not -14 <= eb <= 15:
889 mant, eb = 0, b
890 return (_pow2_16(a) | sx, _pow2_16(eb, mant), z)
891
892
893def _fma_case(rng, kind):
894 """Three source words for an fma op, aimed at ties, cancellation, overflow and the denormal range."""
895 r = rng.random()
896 if kind == "mix32" or (kind in ("mixlo", "mixhi") and rng.random() < 0.5):
897 f = _rand_f32
898 else:
899 f = _rand_f16
900 x, y = f(rng), f(rng)
901 if r < 0.3:
902 return _tie_case(rng, kind == "mix32")
903 if r < 0.45:
904 z = f(rng)
905 elif r < 0.6:
906 # z = -(x*y) rounded: the sum cancels to the product's rounding error
907 z = _neg_product(x, y, f is _rand_f16)
908 elif r < 0.8:
909 z = rng.choice(F16_EDGES if f is _rand_f16 else F32_EDGES)
910 else:
911 z = 0 if rng.random() < 0.5 else (0x8000 if f is _rand_f16 else 0x80000000)
912 return (x, y, z)
913
914
915def _neg_product(x, y, half):
916 a = decode16(x) if half else decode32(x, flush=False)
917 b = decode16(y) if half else decode32(y, flush=False)
918 p = fma(a, b, ("num", 0, Fraction(0)))
919 if p[0] != "num":
920 return x
921 r = round_to(("num", p[1] ^ 1, p[2]), F16 if half else F32)
922 if r[0] != "num":
923 return x
924 try:
925 return encode16(r) if half else encode32(r)
926 except NotJudged:
927 return 0
928
929
930def grid_program(chunk, rng):
931 """A program for up to GRID_PER_PROGRAM grid cases. Case i reads only its own registers and writes v{8+i}."""
932 lines = [f"v_mov_b32 v{r}, 0x{rng.getrandbits(32):08x}" for r in VGPRS]
933 lines += [f"s_mov_b32 s{r}, 0x{rng.getrandbits(32):08x}" for r in SGPRS]
934 body = []
935 for i, (op, words, *flags) in enumerate(chunk):
936 kind = FAMILY[op]
937 d = f"v{DSTS[i]}"
938 clamp = " clamp" if "clamp" in flags else ""
939 if kind in ("mant", "exp"):
940 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}")
941 body.append(f"{op}_e64 {d}, v{12 + i}{clamp}")
942 elif kind == "ldexp":
943 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}")
944 body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]{clamp}")
945 elif kind in ("min3", "max3"):
946 # the three halves: v{12+i} lo, v{12+i} hi and d's own high half (read before it is written)
947 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}")
948 lines.append(f"v_mov_b32 {d}, 0x{(words[2] << 16) | 0x1234:08x}")
949 body.append(f"{op} {d}, v{12 + i}, v{12 + i}, {d} op_sel:[0,1,1,0]")
950 elif kind in ("fmamk", "fmaak"):
951 # words are (x, y, z) of x * y + z: fmamk D = S0 * K + S1 takes y as K, fmaak D = S0 * S1 + K takes z
952 kw, dw = (words[1], words[2]) if kind == "fmamk" else (words[2], words[1])
953 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (rng.getrandbits(16) << 16):08x}")
954 lines.append(f"v_mov_b32 {d}, 0x{dw | (rng.getrandbits(16) << 16):08x}")
955 k = f"0x{kw:04x}"
956 if kind == "fmamk":
957 body.append(f"{op} {d}, v{12 + i}, {k}, {d}")
958 else:
959 body.append(f"{op} {d}, v{12 + i}, {d}, {k}")
960 elif kind == "pkfmac":
961 # lane 0: words, lane 1: the same values negated
962 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | ((words[0] ^ 0x8000) << 16):08x}")
963 lines.append(f"v_mov_b32 {d}, 0x{words[2] | ((words[2] ^ 0x8000) << 16):08x}")
964 lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1] | (words[1] << 16):08x}")
965 body.append(f"{op} {d}, s{4 + i}, v{12 + i}")
966 else:
967 # f32 words are read whole (op_sel_hi 0), f16 values from the low half (op_sel_hi 1)
968 regs = [f"v{12 + i}", f"s{4 + i}", d]
969 lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}")
970 lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1]:08x}")
971 lines.append(f"v_mov_b32 {d}, 0x{words[2]:08x}")
972 shi = [0 if w > M16 else 1 for w in words]
973 body.append(f"{op} {d}, {', '.join(regs)} op_sel:[0,0,0] op_sel_hi:[{','.join(map(str, shi))}]")
974 return lines + body
975
976
977def exhaustive_programs(ops=None):
978 """(op, lines) programs: every f16 input through the frexp ops and ldexp, four inputs per program, yielded one at
979 a time."""
980 exps = (-64, -25, -15, -1, 1, 15, 30, 64)
981 for op in ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16"):
982 if ops and op not in ops:
983 continue
984 for base in range(0, 0x10000, GRID_PER_PROGRAM):
985 lines, body = [], []
986 for i in range(GRID_PER_PROGRAM):
987 h = base + i
988 d = f"v{DSTS[i]}"
989 if op == "v_ldexp_f16":
990 n = exps[(h >> 2) % len(exps)] & M16
991 lines.append(f"v_mov_b32 v{12 + i}, 0x{h | (n << 16):08x}")
992 body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]")
993 else:
994 lines.append(f"v_mov_b32 v{12 + i}, 0x{h | 0xabcd0000:08x}")
995 body.append(f"{op}_e32 {d}, v{12 + i}")
996 yield op, [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in DSTS] + lines + body
997
998
999# ---- the oracles ----
1000
1001def write_listing(path, lines, name):
1002 with open(path, "w", encoding="utf-8", newline="\n") as f:
1003 f.write(f"; {name} code 0x0..0x1000\n")
1004 for line in lines:
1005 f.write("\t" + line + "\n")
1006 f.write("\t" + EXPORT + "\n")
1007 f.write("\ts_endpgm\n")
1008
1009
1010def translate_listing(lines, name, tmpdir):
1011 """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's
1012 UnsupportedConstruct) for anything outside the oracles' model."""
1013 dis = os.path.join(tmpdir, "disasm")
1014 os.makedirs(dis, exist_ok=True)
1015 path = os.path.join(dis, name + ".s")
1016 write_listing(path, lines, name)
1017 with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f:
1018 f.write(STUB_DXBC)
1019 with warnings.catch_warnings():
1020 warnings.simplefilter("ignore", ResourceWarning)
1021 spvasm = rdna2spirv.translate(path)
1022 gc.collect()
1023 out = run_fragment(spvasm)
1024 if list(out) != ["%out_mrt0"]:
1025 raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0")
1026 return [w & M32 for w in out["%out_mrt0"]]
1027
1028
1029def check(lines, name="ps_f16m_case"):
1030 """None when both oracles agree, else the first difference."""
1031 with tempfile.TemporaryDirectory(prefix="f16m-diff-") as tmp:
1032 want, states = reference(lines)
1033 got = translate_listing(lines, name, tmp)
1034 return compare(want, states, got)
1035
1036
1037def run_one(lines, name, tmpdir, events=None):
1038 """(status, detail) with status in {"match", "mismatch", "skip", "unjudged"}."""
1039 try:
1040 want, states = reference(lines, events)
1041 except NotJudged as e:
1042 return ("unjudged", str(e))
1043 try:
1044 got = translate_listing(lines, name, tmpdir)
1045 except (rdna2spirv.Unsupported, UnsupportedConstruct) as e:
1046 return ("skip", f"{type(e).__name__}: {e}")
1047 except (IndexError, KeyError, ValueError) as e:
1048 return ("skip", f"translator error {type(e).__name__}: {e}")
1049 diff = compare(want, states, got)
1050 if diff:
1051 return ("mismatch", diff)
1052 return ("match", "")
1053
1054
1055# ---- the suites ----
1056
1057def _new_counts():
1058 return {"pass": 0, "mismatch": 0, "skip": Counter(), "unjudged": Counter(), "ops": Counter(), "events": {}}
1059
1060
1061def _tally(counts, status, detail):
1062 if status == "match":
1063 counts["pass"] += 1
1064 elif status in ("skip", "unjudged"):
1065 counts[status][detail] += 1
1066 else:
1067 counts["mismatch"] += 1
1068
1069
1070def _run(counts, items, tag):
1071 failure = None
1072 with tempfile.TemporaryDirectory(prefix=f"f16m-diff-{tag}-") as tmp:
1073 for i, (label, lines, used) in enumerate(items):
1074 counts["ops"].update(used)
1075 status, detail = run_one(lines, f"ps_f16m_{tag}{i:05d}", tmp, counts["events"])
1076 _tally(counts, status, detail)
1077 if status == "mismatch" and failure is None:
1078 failure = (label, lines, detail)
1079 return failure
1080
1081
1082# Each stage yields its (label, lines, ops) items one at a time, so a run holds one program's text, not the whole list.
1083def sweep_items(seed, ops=None):
1084 for case in sweep_cases(ops):
1085 op, form, kinds = case
1086 for rep in range(SWEEP_REPEAT):
1087 tag = f"{op}:{form}:{'/'.join(kinds)}:{rep}"
1088 rng = random.Random(f"{seed}:{tag}")
1089 yield f"sweep {tag} (seed {seed})", sweep_program(case, rng), [op]
1090
1091
1092def grid_items(ops=None):
1093 cases = grid_cases(ops)
1094 rng = random.Random("f16misc_diff:grid-programs")
1095 for i in range(0, len(cases), GRID_PER_PROGRAM):
1096 chunk = cases[i:i + GRID_PER_PROGRAM]
1097 yield f"edge grid program {i // GRID_PER_PROGRAM}", grid_program(chunk, rng), [c[0] for c in chunk]
1098
1099
1100def suite_items(programs, seed, max_ops=6, ops=None):
1101 rng = random.Random(f"suite:{seed}")
1102 for i in range(programs):
1103 lines, used = program(rng, rng.randint(1, max_ops), ops)
1104 yield f"program {i} (seed {seed})", lines, used
1105
1106
1107def run_sweep(seed, ops=None):
1108 counts = _new_counts()
1109 return counts, _run(counts, sweep_items(seed, ops), "sw")
1110
1111
1112def run_grid(ops=None):
1113 counts = _new_counts()
1114 return counts, _run(counts, grid_items(ops), "gr")
1115
1116
1117def run_exhaustive(ops=None):
1118 counts = _new_counts()
1119 items = ((f"exhaustive f16 program {i} ({op})", lines, [op] * GRID_PER_PROGRAM)
1120 for i, (op, lines) in enumerate(exhaustive_programs(ops)))
1121 return counts, _run(counts, items, "ex")
1122
1123
1124def run_suite(programs, seed, max_ops=6, ops=None):
1125 counts = _new_counts()
1126 return counts, _run(counts, suite_items(programs, seed, max_ops, ops), "rn")
1127
1128
1129REJECTED = (
1130 ("neg on v_pk_fmac_f16", "v_pk_fmac_f16 v8, -v9, v10"),
1131 ("clamp on v_pk_fmac_f16", "v_pk_fmac_f16 v8, v9, v10 clamp"),
1132)
1133
1134
1135def self_test():
1136 ok = True
1137
1138 def report(good, what):
1139 nonlocal ok
1140 ok &= good
1141 print(("ok " if good else "FAIL ") + what)
1142
1143 # reference spot checks, from docs/design.md and tests/semantic
1144 mc = Machine()
1145 mc.write_word(9, 0x00010001)
1146 step("v_frexp_mant_f16_e32 v8, v9", mc)
1147 report(mc.v[8] & M16 == 0x3800, "frexp_mant(0x0001) = 0.5 (0x3800)")
1148 step("v_frexp_exp_i16_f16_e32 v8, v9", mc)
1149 report(mc.v[8] & M16 == (-23) & M16, "frexp_exp(0x0001) = -23")
1150 mc.write_word(9, 0x000003FF)
1151 step("v_frexp_mant_f16_e32 v8, v9", mc)
1152 report(mc.v[8] & M16 == 0x3BFE, "frexp_mant(0x03ff) = 0x3bfe")
1153 for h, n, want in ((0x3C00, -15, 0x0200), (0x3E00, -24, 0x0002), (0x3C00, -25, 0x0000), (0x7BFF, -30, 0x0400)):
1154 mc.write_word(9, h | ((n & M16) << 16))
1155 step("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", mc)
1156 report(mc.v[8] & M16 == want, f"ldexp(0x{h:04x}, {n}) = 0x{want:04x}")
1157 for words, want in (((0x3C00, 0x0000, 0x3C00), 0x0000), ((0x0000, 0x8000, 0x0000), 0x8000),
1158 ((0xBC00, 0x7C01, 0x0000), 0xBC00), ((0x0001, 0x4000, 0x8000), 0x8000)):
1159 mc.write_word(9, words[0])
1160 mc.write_word(10, words[1])
1161 mc.write_word(11, words[2])
1162 mc.write_word(8, 0xDEADBEEF)
1163 step("v_min3_f16 v8, v9, v10, v11", mc)
1164 report(mc.v[8] == 0xDEAD0000 | want, f"min3{tuple(hex(w) for w in words)} = 0xdead{want:04x}")
1165 # output multipliers are no-ops on f16 results and clamp still acts; frexp_exp ignores both (gfx1036)
1166 mc.write_word(9, 0x12343A00)
1167 mc.write_word(11, 0x9ABC4100)
1168 mc.write_word(12, 3)
1169 for line, want in (("v_frexp_mant_f16_e64 v8, v11 mul:4", 0x3900),
1170 ("v_frexp_exp_i16_f16_e64 v8, v11 clamp mul:2", 2),
1171 ("v_ldexp_f16_e64 v8, v9, v12 div:2", 0x4600),
1172 ("v_ldexp_f16_e64 v8, v11, v12 clamp mul:2", 0x3C00)):
1173 step(line, mc)
1174 report(mc.v[8] & M16 == want, f"{line} = 0x{want:04x}")
1175 # the translator rejects the forms the generator leaves out
1176 for what, line in REJECTED:
1177 try:
1178 with tempfile.TemporaryDirectory(prefix="f16m-diff-st-") as tmp:
1179 translate_listing(seeds(random.Random(1)) + [line], "ps_f16m_rej", tmp)
1180 report(False, f"{what}: the translator accepted it")
1181 except (rdna2spirv.Unsupported, UnsupportedConstruct):
1182 report(True, f"{what}: the translator rejected it")
1183 a = program(random.Random("st"), 5)[0]
1184 b = program(random.Random("st"), 5)[0]
1185 report(a == b, "generation is deterministic for a seed")
1186 counts, failure = run_suite(8, 1)
1187 report(failure is None and not counts["skip"],
1188 f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})")
1189 return ok
1190
1191
1192def main():
1193 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
1194 ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep")
1195 ap.add_argument("--seed", type=int, default=1)
1196 ap.add_argument("--max-ops", type=int, default=6, help="ops per random program")
1197 ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all eleven)")
1198 ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid")
1199 ap.add_argument("--exhaustive-f16", action="store_true", help="also run every f16 input through frexp/ldexp")
1200 ap.add_argument("--list-ops", action="store_true")
1201 ap.add_argument("--self-test", action="store_true")
1202 args = ap.parse_args()
1203 if args.list_ops:
1204 for op in FAMILY:
1205 print(f"{op:22s} {OP_FORMS[op]}")
1206 return 0
1207 if args.self_test:
1208 return 0 if self_test() else 1
1209 ops = None
1210 if args.ops:
1211 ops = [o.strip() for o in args.ops.split(",") if o.strip()]
1212 bad = [o for o in ops if o not in FAMILY]
1213 if bad:
1214 print(f"unknown op(s): {', '.join(bad)} (see --list-ops)", file=sys.stderr)
1215 return 2
1216 stages = []
1217 if not args.no_sweep:
1218 stages += [("sweep", lambda: run_sweep(args.seed, ops)), ("edge grid", lambda: run_grid(ops))]
1219 if args.exhaustive_f16:
1220 stages.append(("exhaustive f16", lambda: run_exhaustive(ops)))
1221 if args.programs > 0:
1222 stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops)))
1223 total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "ops": Counter(), "events": {}}
1224 first = None
1225 try:
1226 for name, fn in stages:
1227 counts, failure = fn()
1228 n = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) + sum(counts["unjudged"].values())
1229 print(f"{name}: {counts['pass']}/{n} programs match, {counts['mismatch']} mismatch; "
1230 f"skips: {dict(counts['skip'])}; not judged: {sum(counts['unjudged'].values())}")
1231 total["pass"] += counts["pass"]
1232 total["mismatch"] += counts["mismatch"]
1233 total["skip"] += sum(counts["skip"].values())
1234 total["unjudged"].update(counts["unjudged"])
1235 total["ops"].update(counts["ops"])
1236 for op, ev in counts["events"].items():
1237 total["events"].setdefault(op, Counter()).update(ev)
1238 if failure and first is None:
1239 first = failure
1240 except HarnessError as e:
1241 print(f"harness error: {e}", file=sys.stderr)
1242 return 2
1243 print("op lines per op: " + ", ".join(f"{op} {n}" for op, n in sorted(total["ops"].items())))
1244 print("inputs/results per op (NaN / inf / denormal / tie / overflow): " + ", ".join(
1245 f"{op} {ev['NaN']}/{ev['inf']}/{ev['denormal'] + ev['denormal result']}/{ev['tie']}/{ev['overflow']}"
1246 for op, ev in sorted(total["events"].items())))
1247 if total["unjudged"]:
1248 print("not judged: " + ", ".join(f"{why} {n}" for why, n in total["unjudged"].most_common()))
1249 judged = total["pass"] + total["mismatch"] + total["skip"]
1250 print(f"f16 misc family: {total['pass']}/{judged} judged programs match, {total['mismatch']} mismatch "
1251 f"({len(total['ops'])} of {len(FAMILY)} ops)")
1252 if first:
1253 _report(first)
1254 return 1
1255 if total["skip"]:
1256 print(f"SKIPPED {total['skip']} program(s): every generated form should translate (reasons above)")
1257 return 1
1258 return 0
1259
1260
1261def _report(failure):
1262 label, lines, detail = failure
1263 print(f"\nFIRST MISMATCH: {label}: {detail}")
1264 for line in lines:
1265 print(" " + line)
1266
1267
1268if __name__ == "__main__":
1269 sys.exit(main())