diff options
| author | Eremia Brinzoi Razvan Andrei <razvaneremia04@gmail.com> | 2026-11-22 13:25:04 +0200 |
|---|---|---|
| committer | Eremia Brinzoi Razvan Andrei <razvaneremia04@gmail.com> | 2026-11-22 13:25:04 +0200 |
| commit | 013cfb3966885cb6b7b81d5708d4e2e1dfd16fe6 (patch) | |
| tree | 48f09ee2b0f53a2416c16e66a3a95a994a884a77 | |
| parent | c2967a5e60060e4068fb992196d8f4b494a5046c (diff) | |
tools: fma_mix_probe tells single from double f16 rounding of v_fma_mix
docs/design.md leaves one f16 question open: in round-to-nearest mode, does
v_fma_mixlo/hi_f16 round the exact x * y + z once to f16, or to f32 first
and then narrow? The translator does the second (f32 Fma, then f16_res).
The RX 6800 word behind the toward-zero rule can't settle it, because
1 * 2 - 2^-30 gives 0x4000 under both readings in nearest mode.
tools/fma_mix_probe.py has seven inputs where the two rules differ by one
f16 ulp, plus a control:
- ties just above and below, for both signs;
- the subnormal tie at 2^-25;
- the overflow tie at 65520;
- a tie made by the product;
- the same with f16 operands.
It reports which rule each side follows:
- the translator, on the CPU interpreter;
- --oracle hw: the native instruction on an AMD GPU, through
tools/hw_oracle, under the game's inferred MODE;
- --oracle vulkan: the translated compute shader through vk_compute_test,
with operands in user SGPRs so the driver can't fold them.
tests/test_fma_mix_probe.py checks:
- the expected words against a derivation written out by hand;
- that the translator follows the double rule today;
- that the compute listing gives the pixel shader's words;
- the verdict and exit codes.
On an RTX 5060 (621.24) the translated shader follows the translator's rule
on all eight inputs. A translator copy that uses fma_mix_odd in nearest mode
gives the single-rounded words on the CPU and on the GPU. That is the fix
if AMD hardware turns out to round once. The translator itself is unchanged.
AI-assisted (Claude Code).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | docs/design.md | 2 | ||||
| -rw-r--r-- | docs/shader_validation.md | 43 | ||||
| -rw-r--r-- | tests/test_fma_mix_probe.py | 173 | ||||
| -rw-r--r-- | tools/fma_mix_probe.py | 367 |
4 files changed, 584 insertions, 1 deletions
diff --git a/docs/design.md b/docs/design.md index 0d617534d..09e12a801 100644 --- a/docs/design.md +++ b/docs/design.md | |||
| @@ -320,7 +320,7 @@ How the generated SPIR-V expects the runtime to work: | |||
| 320 | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. | | 320 | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. | |
| 321 | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). | | 321 | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). | |
| 322 | | 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | | 322 | | 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | |
| 323 | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | 323 | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | |
| 324 | | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | | 324 | | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | |
| 325 | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | | 325 | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | |
| 326 | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | | 326 | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | |
diff --git a/docs/shader_validation.md b/docs/shader_validation.md index 1f6719176..5447785fd 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md | |||
| @@ -784,6 +784,49 @@ reset in the kernel log. | |||
| 784 | inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks | 784 | inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks |
| 785 | exp2 of integers and wave32 = wave64. | 785 | exp2 of integers and wave32 = wave64. |
| 786 | 786 | ||
| 787 | ### `v_fma_mix*` f16 rounding in nearest mode (`tools/fma_mix_probe.py`) | ||
| 788 | |||
| 789 | `docs/design.md` leaves one f16 question open. In round-to-nearest mode, does `v_fma_mixlo_f16` / `v_fma_mixhi_f16` | ||
| 790 | round the exact x · y + z once, straight to f16? Or does it round to f32 first and then narrow, which is what the | ||
| 791 | translator does (f32 `Fma`, then `f16_res`)? The RX 6800 word behind the toward-zero rule can't answer this. For | ||
| 792 | 1 · 2 - 2^-30 both readings give 0x4000 in nearest mode, and toward zero two truncations equal one. | ||
| 793 | |||
| 794 | The two readings only differ when the f32 rounding lands exactly on an f16 tie, or moves a value off one. The probe has | ||
| 795 | seven such inputs, each one f16 ulp apart under the two rules, plus one control: | ||
| 796 | - a tie just above and just below, for both signs; | ||
| 797 | - the subnormal tie at 2^-25; | ||
| 798 | - the overflow tie at 65520 (inf against 65504); | ||
| 799 | - a tie made by the product rather than by z; | ||
| 800 | - the same with f16 operands (`op_sel_hi:[1,1,1]`). | ||
| 801 | |||
| 802 | Every side reports which rule its words follow: | ||
| 803 | |||
| 804 | ``` | ||
| 805 | python -I tools/fma_mix_probe.py # the translator, on the CPU interpreter | ||
| 806 | python -I tools/fma_mix_probe.py --oracle hw # also the native instruction on an AMD GPU (hardware oracle) | ||
| 807 | python -I tools/fma_mix_probe.py --oracle vulkan --build runtime/build # also the translated shader on this GPU | ||
| 808 | ``` | ||
| 809 | |||
| 810 | The `hw` side is the measurement. It runs one wave32 lane per input, under the MODE inferred for the game: IEEE 0, | ||
| 811 | DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept, nearest. The `vulkan` side only shows that a driver runs the | ||
| 812 | translator's sequence as written. Its operands come in user SGPRs, so the driver can't fold them. Exit 0 means every | ||
| 813 | side follows the same rule. Exit 1 means they differ, or a side follows neither rule. Exit 77 means a requested side | ||
| 814 | is unavailable. | ||
| 815 | |||
| 816 | `tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that | ||
| 817 | the translator follows the double rule today, and that the compute shader gives the pixel shader's words on the | ||
| 818 | interpreter. If the hardware rounds once, the fix is to use `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at | ||
| 819 | f32 then narrows exactly. With that change the translator gives the single-rounded word on all seven inputs. | ||
| 820 | |||
| 821 | Results: | ||
| 822 | |||
| 823 | | GPU | Driver | `translator` | `vulkan` | `hw` | | ||
| 824 | |---|---|---|---|---| | ||
| 825 | | NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | double | double, 8 of 8 words | not AMD | | ||
| 826 | |||
| 827 | The `hw` column is still empty: the question needs an RDNA GPU. On the RTX 5060, a translator copy changed to use | ||
| 828 | `fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well. | ||
| 829 | |||
| 787 | ## Coverage plan and cost | 830 | ## Coverage plan and cost |
| 788 | 831 | ||
| 789 | Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and | 832 | Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and |
diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py new file mode 100644 index 000000000..db85fcd08 --- /dev/null +++ b/tests/test_fma_mix_probe.py | |||
| @@ -0,0 +1,173 @@ | |||
| 1 | """tools/fma_mix_probe.py: the inputs tell single from double f16 rounding of v_fma_mixlo/hi_f16, and each side is | ||
| 2 | judged right. Standard library only; no GPU, no LLVM, no game files. | ||
| 3 | |||
| 4 | The words below are worked out by hand, not taken from the tool's own model (f16: ulp 2^-10 on [1, 2), ties at the odd | ||
| 5 | multiples of 2^-11; f32: ulp 2^-23 on [1, 2)): | ||
| 6 | |||
| 7 | A exact 1 + 2^-11 + 2^-40: once -> above the tie -> 0x3c01; f32 drops 2^-40 (< 2^-24), the tie goes to even 0x3c00 | ||
| 8 | B exact 1 + 3 * 2^-11 - 2^-40: once -> below the tie -> 0x3c01; f32 lands on the tie, even is 0x3c02 | ||
| 9 | C A negated: 0xbc01 / 0xbc00 | ||
| 10 | D exact 2^-25 + 2^-60: once -> above half the smallest subnormal -> 0x0001; f32 keeps 2^-25 exactly, the tie | ||
| 11 | between 0 and 2^-24 goes to even 0x0000 | ||
| 12 | E exact 65520 - 2^-20: once -> below the overflow tie -> 65504 0x7bff; f32 (ulp 2^-8) gives 65520, which rounds to | ||
| 13 | inf 0x7c00 | ||
| 14 | F (1 + 2^-12)^2 = 1 + 2^-11 + 2^-24: once -> 0x3c01; f32 ties (2^-24 is half its ulp) to even 1 + 2^-11 -> 0x3c00 | ||
| 15 | G (1 + 2^-7)(1 - 2^-7) 2^-11 + (1 + 2^-10) = 1 + 3 * 2^-11 - 2^-25: once 0x3c01; f32 ties onto 1 + 3 * 2^-11 -> 0x3c02 | ||
| 16 | H 2.5 = 0x4100 either way | ||
| 17 | """ | ||
| 18 | import os | ||
| 19 | import sys | ||
| 20 | import tempfile | ||
| 21 | import unittest | ||
| 22 | |||
| 23 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 24 | sys.dont_write_bytecode = True | ||
| 25 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 26 | sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) | ||
| 27 | |||
| 28 | import fma_mix_probe as probe # noqa: E402 | ||
| 29 | import spirv_mini_interp # noqa: E402 | ||
| 30 | |||
| 31 | BY_HAND = { # name: (single, double) | ||
| 32 | "A": (0x3C01, 0x3C00), "B": (0x3C01, 0x3C02), "C": (0xBC01, 0xBC00), "D": (0x0001, 0x0000), | ||
| 33 | "E": (0x7BFF, 0x7C00), "F": (0x3C01, 0x3C00), "G": (0x3C01, 0x3C02), "H": (0x4100, 0x4100), | ||
| 34 | } | ||
| 35 | VSHARP = [0, 0, 0x1000, 0x31016FAC] # s[0:3]: base 0, 4 KiB, as in tests/semantic/test_lds_atomics_values.py | ||
| 36 | |||
| 37 | |||
| 38 | def word(case, f16): | ||
| 39 | """The destination word a correct op leaves: the f16 in its half, the sentinel in the other.""" | ||
| 40 | s = probe.SENTINEL | ||
| 41 | return (s & 0xFFFF) | f16 << 16 if case.hi else (s & 0xFFFF0000) | f16 | ||
| 42 | |||
| 43 | |||
| 44 | class Inputs(unittest.TestCase): | ||
| 45 | def test_model_matches_hand_derivation(self): | ||
| 46 | self.assertEqual(sorted(c.name for c in probe.CASES), sorted(BY_HAND)) | ||
| 47 | for case in probe.CASES: | ||
| 48 | with self.subTest(case=case.name): | ||
| 49 | want = probe.expected(case) | ||
| 50 | self.assertEqual((want[probe.SINGLE], want[probe.DOUBLE]), BY_HAND[case.name]) | ||
| 51 | |||
| 52 | def test_every_case_but_the_control_discriminates(self): | ||
| 53 | for case in probe.CASES: | ||
| 54 | single, double = BY_HAND[case.name] | ||
| 55 | self.assertEqual(single == double, case.what.startswith("control"), case.name) | ||
| 56 | |||
| 57 | def test_both_ops_and_both_operand_kinds_are_covered(self): | ||
| 58 | self.assertEqual({c.op for c in probe.CASES}, {"v_fma_mixlo_f16", "v_fma_mixhi_f16"}) | ||
| 59 | self.assertTrue(any(c.f16 for c in probe.CASES) and any(not c.f16 for c in probe.CASES)) | ||
| 60 | |||
| 61 | def test_operand_refuses_what_the_model_does_not_cover(self): | ||
| 62 | for w, f16 in ((0x7F800000, False), (0x00000001, False), (0x7C00, True)): | ||
| 63 | with self.assertRaises(ValueError): | ||
| 64 | probe.operand(w, f16) | ||
| 65 | |||
| 66 | |||
| 67 | class Translator(unittest.TestCase): | ||
| 68 | def test_translator_rounds_twice(self): | ||
| 69 | # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the | ||
| 70 | # translator is changed to round once (after a hardware measurement), this test and that sentence change too. | ||
| 71 | got = probe.run_translator() | ||
| 72 | rule, _ = probe.verdict(list(zip(probe.CASES, got))) | ||
| 73 | self.assertEqual(rule, probe.DOUBLE) | ||
| 74 | for case, w in zip(probe.CASES, got): | ||
| 75 | self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) | ||
| 76 | |||
| 77 | def test_compute_listing_gives_the_pixel_shader_words(self): | ||
| 78 | # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the | ||
| 79 | # V# and the operand words as push constants the way vk_compute_test passes s0..s31. | ||
| 80 | with tempfile.TemporaryDirectory() as work: | ||
| 81 | spv = probe.translate_cs(work) | ||
| 82 | pc = VSHARP + probe.sgpr_words() | ||
| 83 | mem = spirv_mini_interp.run_workgroup( | ||
| 84 | spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, | ||
| 85 | push_constants=pc + [0] * (32 - len(pc)), memory={}) | ||
| 86 | self.assertEqual([mem.get(4 * k) for k in range(len(probe.CASES))], probe.run_translator()) | ||
| 87 | |||
| 88 | def test_compute_header_declares_every_operand_sgpr(self): | ||
| 89 | rsrc2 = probe.cs_rsrc2(probe.CASES) | ||
| 90 | self.assertEqual((rsrc2 >> 1) & 31, 4 + 3 * len(probe.CASES)) | ||
| 91 | self.assertLessEqual(len(probe.sgpr_words()), 28) # VKC_SGPRS takes s4..s31 | ||
| 92 | |||
| 93 | |||
| 94 | class Verdict(unittest.TestCase): | ||
| 95 | def results(self, rule, **override): | ||
| 96 | out = [] | ||
| 97 | for case in probe.CASES: | ||
| 98 | single, double = BY_HAND[case.name] | ||
| 99 | f16 = single if rule == probe.SINGLE else double | ||
| 100 | out.append((case, override.get(case.name, word(case, f16)))) | ||
| 101 | return out | ||
| 102 | |||
| 103 | def test_each_rule_is_recognised(self): | ||
| 104 | for rule in (probe.SINGLE, probe.DOUBLE): | ||
| 105 | self.assertEqual(probe.verdict(self.results(rule))[0], rule) | ||
| 106 | |||
| 107 | def test_a_mix_of_rules_is_neither(self): | ||
| 108 | a = probe.CASES[0] | ||
| 109 | self.assertIsNone(probe.verdict(self.results(probe.DOUBLE, A=word(a, BY_HAND["A"][0])))[0]) | ||
| 110 | |||
| 111 | def test_a_third_value_is_neither(self): | ||
| 112 | self.assertIsNone(probe.verdict(self.results(probe.SINGLE, E=word(probe.CASES[4], 0x7BFE)))[0]) | ||
| 113 | |||
| 114 | def test_a_wrong_control_is_neither(self): | ||
| 115 | self.assertIsNone(probe.verdict(self.results(probe.SINGLE, H=word(probe.CASES[7], 0x4101)))[0]) | ||
| 116 | |||
| 117 | def test_the_other_half_must_be_kept(self): | ||
| 118 | b = probe.CASES[1] # mixhi: the low half keeps the sentinel's | ||
| 119 | self.assertIsNone(probe.verdict(self.results(probe.DOUBLE, B=BY_HAND["B"][1] << 16))[0]) | ||
| 120 | self.assertEqual(probe.half(b, word(b, 0x3C02)), 0x3C02) | ||
| 121 | |||
| 122 | def test_a_missing_result_is_neither(self): | ||
| 123 | rule, lines = probe.verdict(self.results(probe.SINGLE, D=None)) | ||
| 124 | self.assertIsNone(rule) | ||
| 125 | self.assertIn("missing", lines[3]) | ||
| 126 | |||
| 127 | |||
| 128 | class HardwareKernel(unittest.TestCase): | ||
| 129 | def test_kernel_body(self): | ||
| 130 | g = next(c for c in probe.CASES if c.f16) | ||
| 131 | lines = probe.hw_lines(g) | ||
| 132 | self.assertIn(f"{g.op} v8, v1, v2, v3 op_sel_hi:[1,1,1]", lines) | ||
| 133 | self.assertEqual(lines[-2:], ["global_store_b32 v20, v8, s[2:3]", "s_endpgm"]) | ||
| 134 | |||
| 135 | def test_gfx10_kernel_text_sets_the_float_mode(self): | ||
| 136 | from hw_oracle import asm | ||
| 137 | text = asm.raw_kernel_text("k0", probe.hw_lines(probe.CASES[0]), "gfx1030", mode=probe.HW_MODE) | ||
| 138 | self.assertIn("global_store_dword v20, v8, s[2:3]", text) # GFX10 spelling | ||
| 139 | for directive in (".amdhsa_float_denorm_mode_16_64 3", ".amdhsa_float_round_mode_16_64 0", | ||
| 140 | ".amdhsa_ieee_mode 0"): | ||
| 141 | self.assertIn(directive, text) | ||
| 142 | |||
| 143 | |||
| 144 | class Command(unittest.TestCase): | ||
| 145 | def test_translator_only_run_exits_0(self): | ||
| 146 | import contextlib | ||
| 147 | import io | ||
| 148 | buf = io.StringIO() | ||
| 149 | with contextlib.redirect_stdout(buf): | ||
| 150 | rc = probe.main([]) | ||
| 151 | self.assertEqual(rc, 0) | ||
| 152 | self.assertIn("translator: follows double rounding", buf.getvalue()) | ||
| 153 | |||
| 154 | def test_unknown_side_and_missing_build_are_usage_errors(self): | ||
| 155 | import contextlib | ||
| 156 | import io | ||
| 157 | for argv in (["--oracle", "gpu"], ["--oracle", "vulkan"]): | ||
| 158 | with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()): | ||
| 159 | with self.assertRaises(SystemExit) as cm: | ||
| 160 | probe.main(argv) | ||
| 161 | self.assertEqual(cm.exception.code, 2) | ||
| 162 | |||
| 163 | def test_vulkan_side_without_a_build_is_unavailable(self): | ||
| 164 | import contextlib | ||
| 165 | import io | ||
| 166 | with tempfile.TemporaryDirectory() as empty, contextlib.redirect_stdout(io.StringIO()) as buf: | ||
| 167 | rc = probe.main(["--oracle", "vulkan", "--build", empty]) | ||
| 168 | self.assertEqual(rc, 77) | ||
| 169 | self.assertIn("vk_compute_test is not built", buf.getvalue()) | ||
| 170 | |||
| 171 | |||
| 172 | if __name__ == "__main__": | ||
| 173 | unittest.main() | ||
diff --git a/tools/fma_mix_probe.py b/tools/fma_mix_probe.py new file mode 100644 index 000000000..2e97edafa --- /dev/null +++ b/tools/fma_mix_probe.py | |||
| @@ -0,0 +1,367 @@ | |||
| 1 | r"""Does v_fma_mixlo_f16 / v_fma_mixhi_f16 round once or twice to nearest even? A probe, standard library only. | ||
| 2 | |||
| 3 | docs/design.md (Known approximations) leaves this open. The translator computes the f32 `Fma` and narrows that to | ||
| 4 | f16 ("double": two roundings, f32 then f16). The hardware may instead round the exact x * y + z once, straight to f16 | ||
| 5 | ("single"). The RX 6800 word behind the toward-zero path (1 * 2 - 2^-30 -> 0x3fff) can't tell them apart in nearest | ||
| 6 | mode: there both give 0x4000, and toward zero, two truncations equal one. | ||
| 7 | |||
| 8 | The two rules differ only when the f32 rounding lands exactly on an f16 tie (or moves the value off one). CASES holds | ||
| 9 | seven such inputs, each one f16 ulp apart under the two rules, and one control where both agree: | ||
| 10 | |||
| 11 | A 1 * 2^-40 + (1 + 2^-11) just above a tie, f32 rounds onto it, ties-to-even goes down | ||
| 12 | B 1 * -2^-40 + (1 + 3 * 2^-11) just below a tie with an odd lower neighbour: double goes up | ||
| 13 | C -1 * 2^-40 - (1 + 2^-11) A negated | ||
| 14 | D 2^-30 * 2^-30 + 2^-25 the tie between 0 and the smallest f16 subnormal (needs f16 denormals) | ||
| 15 | E 1 * -2^-20 + 65520 the overflow tie: double gives inf, single 65504 | ||
| 16 | F (1 + 2^-12) * (1 + 2^-12) + 0 the tie comes from the product (1 + 2^-11 + 2^-24), not from z | ||
| 17 | G f16 operands: (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) as B, through op_sel_hi:[1,1,1] | ||
| 18 | H 1 * 2 + 0.5 = 2.5 control | ||
| 19 | |||
| 20 | Sides (each prints the f16 word per case and the rule its words follow): | ||
| 21 | |||
| 22 | translator tools/rdna2spirv.py -> tests/semantic/spirv_mini_interp.py, on the CPU. Always runs. | ||
| 23 | hw the native instruction on an AMD GPU (tools/hw_oracle: HIP on Windows, libdrm on Linux), one wave32 | ||
| 24 | lane, MODE as inferred for the game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 kept, nearest). | ||
| 25 | This is the measurement the docs lack. | ||
| 26 | vulkan the translated compute shader on this machine's Vulkan GPU through vk_compute_test (--build DIR, | ||
| 27 | needs spirv-as). The operands come in user SGPRs (VKC_SGPRS), so the driver can't fold them. It checks | ||
| 28 | that the driver runs the translator's sequence as written; it says nothing about RDNA2 itself. | ||
| 29 | |||
| 30 | python -I tools/fma_mix_probe.py # translator side only | ||
| 31 | python -I tools/fma_mix_probe.py --oracle hw # + the AMD GPU in this machine | ||
| 32 | python -I tools/fma_mix_probe.py --oracle vulkan --build runtime/build | ||
| 33 | |||
| 34 | Exit code: 0 when every side that ran follows the same rule, 1 when they differ or a side follows neither rule (or | ||
| 35 | its control is wrong), 2 on a harness error, 77 when a requested side is unavailable. Nothing here reads game files. | ||
| 36 | """ | ||
| 37 | import argparse | ||
| 38 | import os | ||
| 39 | import re | ||
| 40 | import struct | ||
| 41 | import subprocess | ||
| 42 | import sys | ||
| 43 | import tempfile | ||
| 44 | import warnings | ||
| 45 | from fractions import Fraction | ||
| 46 | |||
| 47 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 48 | ROOT = os.path.dirname(HERE) | ||
| 49 | sys.dont_write_bytecode = True | ||
| 50 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE | ||
| 51 | for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")): | ||
| 52 | if p not in sys.path: | ||
| 53 | sys.path.insert(0, p) | ||
| 54 | |||
| 55 | import rdna2spirv # noqa: E402 | ||
| 56 | import spirv_mini_interp # noqa: E402 | ||
| 57 | |||
| 58 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 59 | SENTINEL = 0x5A5A5A5A # the destination's previous value: the half the op doesn't write must keep it | ||
| 60 | SINGLE, DOUBLE = "single", "double" | ||
| 61 | |||
| 62 | |||
| 63 | class Case: | ||
| 64 | __slots__ = ("name", "op", "f16", "words", "what") | ||
| 65 | |||
| 66 | def __init__(self, name, op, f16, words, what): | ||
| 67 | self.name, self.op, self.f16, self.words, self.what = name, op, f16, words, what | ||
| 68 | |||
| 69 | @property | ||
| 70 | def hi(self): | ||
| 71 | return self.op == "v_fma_mixhi_f16" | ||
| 72 | |||
| 73 | @property | ||
| 74 | def mods(self): | ||
| 75 | return " op_sel_hi:[1,1,1]" if self.f16 else "" | ||
| 76 | |||
| 77 | |||
| 78 | # x, y, z as raw words: f32, or (f16 = True) an f16 in the low half. | ||
| 79 | CASES = ( | ||
| 80 | Case("A", "v_fma_mixlo_f16", False, (0x3F800000, 0x2B800000, 0x3F801000), "1 * 2^-40 + (1 + 2^-11)"), | ||
| 81 | Case("B", "v_fma_mixhi_f16", False, (0x3F800000, 0xAB800000, 0x3F803000), "1 * -2^-40 + (1 + 3 * 2^-11)"), | ||
| 82 | Case("C", "v_fma_mixlo_f16", False, (0xBF800000, 0x2B800000, 0xBF801000), "-1 * 2^-40 - (1 + 2^-11)"), | ||
| 83 | Case("D", "v_fma_mixhi_f16", False, (0x30800000, 0x30800000, 0x33000000), "2^-30 * 2^-30 + 2^-25"), | ||
| 84 | Case("E", "v_fma_mixlo_f16", False, (0x3F800000, 0xB5800000, 0x477FF000), "1 * -2^-20 + 65520"), | ||
| 85 | Case("F", "v_fma_mixhi_f16", False, (0x3F800800, 0x3F800800, 0x00000000), "(1 + 2^-12)^2 + 0"), | ||
| 86 | Case("G", "v_fma_mixlo_f16", True, (0x3C08, 0x0FF0, 0x3C01), "f16 (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10)"), | ||
| 87 | Case("H", "v_fma_mixhi_f16", False, (0x3F800000, 0x40000000, 0x3F000000), "control: 1 * 2 + 0.5"), | ||
| 88 | ) | ||
| 89 | |||
| 90 | |||
| 91 | # ---- the two rules, in exact arithmetic (finite normal or zero operands only; CASES has nothing else) ---- | ||
| 92 | |||
| 93 | def operand(word, f16): | ||
| 94 | """The exact value of an f32 word, or of the f16 in its low half.""" | ||
| 95 | if f16: | ||
| 96 | e, m, s = (word >> 10) & 0x1F, word & 0x3FF, -1 if word & 0x8000 else 1 | ||
| 97 | if e == 0x1F: | ||
| 98 | raise ValueError(f"f16 0x{word:04x} is not finite") | ||
| 99 | return s * (Fraction(m, 1 << 24) if e == 0 else Fraction(0x400 | m, 1 << 10) * Fraction(2) ** (e - 15)) | ||
| 100 | e, m, s = (word >> 23) & 0xFF, word & 0x7FFFFF, -1 if word >> 31 else 1 | ||
| 101 | if e == 0xFF or (e == 0 and m): | ||
| 102 | raise ValueError(f"f32 0x{word:08x} is not a finite normal or zero") | ||
| 103 | return Fraction(0) if e == 0 else s * Fraction(0x800000 | m, 1 << 23) * Fraction(2) ** (e - 127) | ||
| 104 | |||
| 105 | |||
| 106 | def round_rne(x, bits, emin): | ||
| 107 | """x rounded to nearest even with `bits` significand bits and subnormals below 2^emin (no overflow).""" | ||
| 108 | if x == 0: | ||
| 109 | return x | ||
| 110 | a, e = abs(x), emin | ||
| 111 | while a >= Fraction(2) ** (e + 1): | ||
| 112 | e += 1 | ||
| 113 | q = Fraction(2) ** (e - bits + 1) # the ulp at a's binade (or the subnormal ulp) | ||
| 114 | n = a / q | ||
| 115 | k, rem = n.numerator // n.denominator, n - n.numerator // n.denominator | ||
| 116 | if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and k % 2): | ||
| 117 | k += 1 | ||
| 118 | return (k * q) if x > 0 else -(k * q) | ||
| 119 | |||
| 120 | |||
| 121 | def f16_word(x): | ||
| 122 | """f16 bits of x rounded to nearest even; |x| >= 65520 is inf.""" | ||
| 123 | r = round_rne(x, 11, -14) | ||
| 124 | s = 0x8000 if x < 0 else 0 | ||
| 125 | a = abs(r) | ||
| 126 | if a > 65504: | ||
| 127 | return s | 0x7C00 | ||
| 128 | if a < Fraction(1, 1 << 14): | ||
| 129 | return s | int(a * (1 << 24)) | ||
| 130 | e = 0 | ||
| 131 | while a >= Fraction(2) ** (e + 1): | ||
| 132 | e += 1 | ||
| 133 | while a < Fraction(2) ** e: | ||
| 134 | e -= 1 | ||
| 135 | return s | (e + 15) << 10 | int((a / Fraction(2) ** e - 1) * 1024) | ||
| 136 | |||
| 137 | |||
| 138 | def expected(case): | ||
| 139 | """{"single": word, "double": word}: the f16 result under each rule.""" | ||
| 140 | x, y, z = (operand(w, case.f16) for w in case.words) | ||
| 141 | exact = x * y + z | ||
| 142 | return {SINGLE: f16_word(exact), DOUBLE: f16_word(round_rne(exact, 24, -126))} | ||
| 143 | |||
| 144 | |||
| 145 | def half(case, word): | ||
| 146 | """The f16 a case wrote, or None when the other half of the destination lost the sentinel.""" | ||
| 147 | keep, mine = (word & 0xFFFF, word >> 16) if case.hi else (word >> 16, word & 0xFFFF) | ||
| 148 | other = SENTINEL & 0xFFFF | ||
| 149 | return mine if keep == other else None | ||
| 150 | |||
| 151 | |||
| 152 | def verdict(results): | ||
| 153 | """results: [(case, word or None)]. Returns (rule or None, one line per case). The rule is the one every | ||
| 154 | discriminating case follows, with the control right; None when the words follow neither or a mix.""" | ||
| 155 | rules, lines = set(), [] | ||
| 156 | for case, word in results: | ||
| 157 | want = expected(case) | ||
| 158 | h = None if word is None else half(case, word) | ||
| 159 | if word is None: | ||
| 160 | got, tag = "no result", "missing" | ||
| 161 | elif h is None: | ||
| 162 | got, tag = f"0x{word:08x}", "other half not kept" | ||
| 163 | else: | ||
| 164 | got = f"0x{h:04x}" | ||
| 165 | tag = [r for r in (SINGLE, DOUBLE) if want[r] == h] | ||
| 166 | tag = ("both (control)" if want[SINGLE] == want[DOUBLE] else tag[0]) if tag else "neither" | ||
| 167 | if tag in (SINGLE, DOUBLE): | ||
| 168 | rules.add(tag) | ||
| 169 | elif tag != "both (control)": | ||
| 170 | rules.add(None) | ||
| 171 | lines.append(f" {case.name} {case.op:<16} {got:<12} single 0x{want[SINGLE]:04x} double 0x{want[DOUBLE]:04x}" | ||
| 172 | f" -> {tag:<16} {case.what}") | ||
| 173 | rule = rules.pop() if len(rules) == 1 else None | ||
| 174 | return rule, lines | ||
| 175 | |||
| 176 | |||
| 177 | # ---- the translator, on the CPU ---- | ||
| 178 | |||
| 179 | def _translate(work, name, text, fssm=None): | ||
| 180 | os.makedirs(os.path.join(work, "disasm"), exist_ok=True) | ||
| 181 | src = os.path.join(work, "disasm", name + ".s") | ||
| 182 | with open(src, "w", encoding="utf-8") as f: | ||
| 183 | f.write(text) | ||
| 184 | with open(os.path.join(work, name + ".dxbc"), "wb") as f: | ||
| 185 | f.write(STUB_DXBC) | ||
| 186 | if fssm is not None: | ||
| 187 | os.makedirs(os.path.join(work, "fssm"), exist_ok=True) | ||
| 188 | with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as f: | ||
| 189 | f.write(fssm) | ||
| 190 | with warnings.catch_warnings(): | ||
| 191 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 192 | return rdna2spirv.translate(src) | ||
| 193 | |||
| 194 | |||
| 195 | def ps_listing(case): | ||
| 196 | """A pixel shader that runs one case and exports the destination word as mrt0.x.""" | ||
| 197 | x, y, z = case.words | ||
| 198 | body = [f"v_mov_b32 v1, 0x{x:x}", f"v_mov_b32 v2, 0x{y:x}", f"v_mov_b32 v3, 0x{z:x}", | ||
| 199 | f"v_mov_b32 v0, 0x{SENTINEL:x}", f"{case.op} v0, v1, v2, v3{case.mods}", "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 200 | "s_endpgm"] | ||
| 201 | return "; fma_mix_probe\n" + "".join(f"\t{ln}\n" for ln in body) | ||
| 202 | |||
| 203 | |||
| 204 | def run_translator(cases=CASES): | ||
| 205 | out = [] | ||
| 206 | with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: | ||
| 207 | for case in cases: | ||
| 208 | spv = _translate(work, f"ps_fma_mix_{case.name}", ps_listing(case)) | ||
| 209 | out.append(spirv_mini_interp.run_fragment(spv)["%out_mrt0"][0]) | ||
| 210 | return out | ||
| 211 | |||
| 212 | |||
| 213 | # ---- the translated compute shader on a Vulkan GPU ---- | ||
| 214 | # s[0:3] is the output V#, then three operand words per case in s4.. (VKC_SGPRS), the workgroup id after them. | ||
| 215 | |||
| 216 | FIRST_RESULT = 10 | ||
| 217 | |||
| 218 | |||
| 219 | def cs_rsrc2(cases): | ||
| 220 | user = 4 + 3 * len(cases) | ||
| 221 | if user > 32: | ||
| 222 | raise ValueError("too many cases for the user SGPRs") | ||
| 223 | return 0x8080 | user << 1 # USER_SGPR [5:1], TGID_X_EN, 512 bytes of LDS (as build.py's default) | ||
| 224 | |||
| 225 | |||
| 226 | def cs_listing(cases=CASES): | ||
| 227 | """One thread runs every case from its SGPR operands and stores the destination words at offset 0, 4, ...""" | ||
| 228 | body = [] | ||
| 229 | for k, case in enumerate(cases): | ||
| 230 | s = 4 + 3 * k | ||
| 231 | d = FIRST_RESULT + k | ||
| 232 | body += [f"v_mov_b32 v1, s{s}", f"v_mov_b32 v2, s{s + 1}", f"v_mov_b32 v3, s{s + 2}", | ||
| 233 | f"v_mov_b32 v{d}, 0x{SENTINEL:x}", f"{case.op} v{d}, v1, v2, v3{case.mods}"] | ||
| 234 | for k in range(len(cases)): | ||
| 235 | body += [f"v_mov_b32 v4, {4 * k}", f"buffer_store_dword v{FIRST_RESULT + k}, v4, s[0:3], 0 offen"] | ||
| 236 | body.append("s_endpgm") | ||
| 237 | return "; fma_mix_probe\n" + "".join(f"\t{ln}\n" for ln in body) | ||
| 238 | |||
| 239 | |||
| 240 | def cs_fssm(cases=CASES): | ||
| 241 | header = bytearray(0x148) | ||
| 242 | struct.pack_into("<4I", header, 0x138, cs_rsrc2(cases), 1, 1, 1) | ||
| 243 | return bytes(header) | ||
| 244 | |||
| 245 | |||
| 246 | def sgpr_words(cases=CASES): | ||
| 247 | return [w for case in cases for w in case.words] | ||
| 248 | |||
| 249 | |||
| 250 | def translate_cs(work, cases=CASES): | ||
| 251 | return _translate(work, "cs_fma_mix_probe", cs_listing(cases), cs_fssm(cases)) | ||
| 252 | |||
| 253 | |||
| 254 | def run_vulkan(build, cases=CASES): | ||
| 255 | """[word per case] from vk_compute_test, or raise RuntimeError with the reason (Unavailable-like: FileNotFound).""" | ||
| 256 | sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) | ||
| 257 | from compute_fixture import find_test_program | ||
| 258 | folder = find_test_program(build, "vk_compute_test") | ||
| 259 | if folder is None: | ||
| 260 | raise FileNotFoundError(f"vk_compute_test is not built in {build}") | ||
| 261 | exe = os.path.join(folder, "vk_compute_test" + (".exe" if os.name == "nt" else "")) | ||
| 262 | if len(cases) > 8: | ||
| 263 | raise ValueError("vk_compute_test prints eight words") | ||
| 264 | with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: | ||
| 265 | text = translate_cs(work, cases) | ||
| 266 | sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv") | ||
| 267 | with open(sa, "w", encoding="utf-8") as f: | ||
| 268 | f.write(text) | ||
| 269 | try: | ||
| 270 | r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) | ||
| 271 | except FileNotFoundError: | ||
| 272 | raise FileNotFoundError("spirv-as is not on PATH (SPIRV-Tools)") from None | ||
| 273 | if r.returncode: | ||
| 274 | raise RuntimeError("spirv-as failed: " + (r.stderr or r.stdout).strip()[:300]) | ||
| 275 | env = dict(os.environ, VKC_SGPRS=",".join(f"0x{w:x}" for w in sgpr_words(cases))) | ||
| 276 | r = subprocess.run([exe, sv, "1", "dump"], capture_output=True, text=True, env=env, timeout=120) | ||
| 277 | msg = r.stdout + r.stderr | ||
| 278 | m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", msg, re.MULTILINE) | ||
| 279 | if r.returncode == 77: | ||
| 280 | raise FileNotFoundError("vk_compute_test: no usable Vulkan device (exit 77)") | ||
| 281 | if r.returncode or not m: | ||
| 282 | raise RuntimeError(f"vk_compute_test exited {r.returncode}: {msg.strip()[-300:]}") | ||
| 283 | return [int(x) for x in m.group(1).split()][:len(cases)] | ||
| 284 | |||
| 285 | |||
| 286 | # ---- the native instruction on an AMD GPU ---- | ||
| 287 | |||
| 288 | HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 0} | ||
| 289 | |||
| 290 | |||
| 291 | def hw_lines(case): | ||
| 292 | x, y, z = case.words | ||
| 293 | return [f"v_mov_b32 v1, 0x{x:x}", f"v_mov_b32 v2, 0x{y:x}", f"v_mov_b32 v3, 0x{z:x}", | ||
| 294 | f"v_mov_b32 v8, 0x{SENTINEL:x}", f"{case.op} v8, v1, v2, v3{case.mods}", "v_mov_b32 v20, 0", | ||
| 295 | "global_store_b32 v20, v8, s[2:3]", "s_endpgm"] | ||
| 296 | |||
| 297 | |||
| 298 | def run_hw(oracle, cases=CASES): | ||
| 299 | from hw_oracle import asm | ||
| 300 | got = oracle.run([asm.Kernel(hw_lines(c), 32, 1, 1, raw=True, mode=HW_MODE) for c in cases], words=1) | ||
| 301 | return [None if isinstance(w, str) else w[0] for w in got], [w for w in got if isinstance(w, str)] | ||
| 302 | |||
| 303 | |||
| 304 | # ---- driver ---- | ||
| 305 | |||
| 306 | def report(side, results): | ||
| 307 | rule, lines = verdict(results) | ||
| 308 | print(f"{side}: {'follows ' + rule + ' rounding' if rule else 'follows neither rule'}") | ||
| 309 | for ln in lines: | ||
| 310 | print(ln) | ||
| 311 | return rule | ||
| 312 | |||
| 313 | |||
| 314 | def main(argv=None): | ||
| 315 | ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) | ||
| 316 | ap.add_argument("--oracle", default="translator", | ||
| 317 | help="comma-separated sides besides the translator, which always runs: hw, vulkan") | ||
| 318 | ap.add_argument("--build", help="the runtime build folder holding vk_compute_test (for --oracle vulkan)") | ||
| 319 | ap.add_argument("--hw-arch", help="GPU architecture to assemble for (default: detected; LEONIDA_HW_ARCH)") | ||
| 320 | a = ap.parse_args(argv) | ||
| 321 | sides = {s.strip() for s in a.oracle.split(",") if s.strip()} - {"translator"} | ||
| 322 | if sides - {"hw", "vulkan"}: | ||
| 323 | ap.error(f"unknown --oracle side(s): {', '.join(sorted(sides - {'hw', 'vulkan'}))}") | ||
| 324 | if "vulkan" in sides and not a.build: | ||
| 325 | ap.error("--oracle vulkan needs --build DIR") | ||
| 326 | for case in CASES: # the table itself: seven inputs that tell the rules apart, one that doesn't | ||
| 327 | want = expected(case) | ||
| 328 | if (want[SINGLE] == want[DOUBLE]) != case.what.startswith("control"): | ||
| 329 | print(f"harness error: case {case.name} does not discriminate as described") | ||
| 330 | return 2 | ||
| 331 | rules = [] | ||
| 332 | try: | ||
| 333 | rules.append(report("translator", list(zip(CASES, run_translator())))) | ||
| 334 | if "vulkan" in sides: | ||
| 335 | try: | ||
| 336 | words = run_vulkan(a.build) | ||
| 337 | except FileNotFoundError as e: | ||
| 338 | print(f"vulkan side unavailable: {e}") | ||
| 339 | return 77 | ||
| 340 | rules.append(report("vulkan (translated, this GPU)", list(zip(CASES, words)))) | ||
| 341 | if "hw" in sides: | ||
| 342 | from hw_oracle import runner | ||
| 343 | try: | ||
| 344 | oracle = runner.open_oracle(arch=a.hw_arch) | ||
| 345 | except runner.Unavailable as e: | ||
| 346 | print(f"hardware oracle unavailable: {e}") | ||
| 347 | return 77 | ||
| 348 | try: | ||
| 349 | print(f"hardware oracle: {oracle.device}") | ||
| 350 | words, rejected = run_hw(oracle) | ||
| 351 | finally: | ||
| 352 | oracle.close() | ||
| 353 | for why in rejected: | ||
| 354 | print(f" {why}") | ||
| 355 | rules.append(report(f"hw (native, {oracle.arch})", list(zip(CASES, words)))) | ||
| 356 | except (RuntimeError, OSError, subprocess.SubprocessError, spirv_mini_interp.UnsupportedConstruct) as e: | ||
| 357 | print(f"harness error: {e}") | ||
| 358 | return 2 | ||
| 359 | if None in rules or len(set(rules)) != 1: | ||
| 360 | print("sides disagree" if None not in rules else "a side follows neither rule") | ||
| 361 | return 1 | ||
| 362 | print(f"all sides follow {rules[0]} rounding") | ||
| 363 | return 0 | ||
| 364 | |||
| 365 | |||
| 366 | if __name__ == "__main__": | ||
| 367 | sys.exit(main()) | ||