From 933b8e6926149a7127d46227c6e22173320a83ed Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 05:57:28 +0000 Subject: [PATCH 1/5] shader: lower binary16 VOP1 reciprocal square root and exponent --- CMakeLists.txt | 6 + docs/experiments.md | 4 + tests/form_coverage_check.py | 38 +++ tests/pixel_aot_check.py | 446 +++++++++++++++++++++++++++++- tests/rdna2_tools_check.py | 11 +- tools/pixel_aot.py | 172 +++++++++++- tools/scan_unsupported_shaders.py | 2 +- 7 files changed, 653 insertions(+), 26 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 57c821c564..03b30a9d31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11372,6 +11372,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rcp-sqrt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME pixel_aot_f16_rsq_exp_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rsq-exp "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_f16_fmac_ldexp_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-fmac-ldexp "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -11660,6 +11664,8 @@ if(EXISTS "${INTAKE_PYTHON}") ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_round_${adapter}.txt") set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rcp_sqrt_${adapter}.txt") + set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rsq_exp_${adapter}.txt") set_tests_properties(pixel_aot_f16_fmac_ldexp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_fmac_ldexp_${adapter}.txt") set_tests_properties(pixel_aot_f16_cvt_int16_${adapter} PROPERTIES diff --git a/docs/experiments.md b/docs/experiments.md index 799b08847d..bd3fa70a5b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9003,6 +9003,10 @@ Plain binary16 `VOP1` reciprocal and square root (issue #839) `v_rcp_f16` and `v The controls (`check_f16_rcp_sqrt_controls`, no GPU) cover the bare, `_e32` and `_e64` spellings, every source kind, the finite, register, modifier, mode, scheduling, sample and reader refusals, and chains of both operations. The Python reference (`f16_rcp_sqrt_reference`) applies the same two rounds from the semantics without `pixel_aot`, handles the binary16 overflow threshold and compares with the translator's `f16_rcp_sqrt_result` on every finite encoding. The draw (`tests/pixel_aot_check.py draw-f16-rcp-sqrt`, tests `pixel_aot_f16_rcp_sqrt_hardware` and `pixel_aot_f16_rcp_sqrt_warp`, 60 s limit, capability skip 77) runs five baked programs over 20 source values through both ops in a rotation of e32, e64, SGPR and literal forms and packs two results per word with SDWA `WORD_0` and `WORD_1`; four reader programs and two chains read both result tags. Bits 31:16 of every source word hold junk. The lossless `R32G32B32A32_UINT` readback is compared with the Python reference. Two deviations must each mismatch, one batch per mutation with the statuses printed (reciprocal and square root swapped, and a source read from bits 31:16), and a source with no finite proof is refused at translation. Both tests passed on WARP and on the RX 9060 XT. In `gfx1013.tsv` and `rdna2.tsv` the two operations add their VOP1 and VOP3 rows, so the fixture records four newly covered forms (rcp and sqrt, each e32 and e64); the two operations themselves are the +2. `tests/form_coverage_check.py check_f16_rcp_sqrt_forms` pins that the DPP, SDWA and rsq neighbours stay uncovered. `tools/scan_unsupported_shaders.py` accepts the syntactic source forms and `tests/rdna2_tools_check.py test_binary16_e64_scanner_translator_agreement` checks that its acceptance agrees with `pixel_aot.lower`. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN payloads and special-function results beyond the modelled infinities, runtime sources, the DPP and SDWA spellings, the hardware behaviour of integer inline constants on binary16 operands, and whether any title executes these paths. +Plain binary16 `VOP1` reciprocal square root and exponent (issue #839), `v_rsq_f16` and `v_exp_f16`, extend the unary entry above: the unsuffixed, `_e32` and `_e64` spellings widen the low half with `widen16`, evaluate the direct compute path's `rsqrt` or `exp2` in binary32, narrow with `narrow16`, and then select RDNA 2's special results from the source half. `v_rsq_f16` maps any source above `+infinity` (every negative finite encoding) to the canonical quiet NaN `0x7e00`, `+infinity` to zero and a zero magnitude to `source | 0x7c00`, so `-0` gives `-infinity`; `v_exp_f16` applies the 70 midpoint corrections of `exp_f16_midpoints` from `src/gfx1013_direct_compute.inl`, maps `2^-25` (`0xce40`) to zero and a magnitude above `+infinity` to `0x7e00`. The emitted helpers are `f16_rsq_result` and `f16_exp2_result`, and `tools/pixel_aot.py` carries the same table as `EXP_F16_MIDPOINTS`. The translator tracks each result with `f16_rsq_exp_result`: a positive finite reciprocal square root is rounded exactly to binary16 with a 90-digit reference, a negative one is the canonical NaN above, and `exp` rounds the exact `2^S0` after the table corrections. Every finite source therefore has a modelled result and the function does not return None; its signature keeps the None contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the reciprocal and square root entry; the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused, and `v_log_f16`, `v_sin_f16` and `v_cos_f16` remain unlowered. + +The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining log, sin and cos forms, and whether any title executes these paths. + Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. `tools/scan_unsupported_shaders.py` reports the `_e64` spelling of the four `VOP2` arithmetic ops and the four `VOP1` rounding ops above as supported, matching what `tools/pixel_aot.py` lowers: two sources of the `_e32` source set (a binary16 inline constant, 0, a 16-bit literal, a VGPR or an SGPR; the `_e64` src1 need not be a VGPR) or one source for the rounding ops, with no modifier, `clamp`, `mul:`, `div:` or `op_sel`. The `_e64` spellings of `v_cvt_f16_i16` and `v_cvt_f16_u16` and of `v_fract_f16` stay unsupported. This is a syntactic match only: whether a source is statically proven finite is decided by the translator. `tests/rdna2_tools_check.py` (`test_binary16_e64_scanner_translator_agreement`) lowers each accepted and each refused form through `pixel_aot.lower` and requires the scanner to agree with it. No lowering changed here, so this adds no new shader readback; the existing binary16 draws in `tests/pixel_aot_check.py` already cover the `_e64` lowering. It shows scanner and translator agreement, not that any title runs. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 752413a081..0ed8799184 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -721,6 +721,43 @@ def check_f16_rcp_sqrt_forms(): pixel.ACCEPTED.update(saved) +def check_f16_rsq_exp_forms(): + """The four plain binary16 VOP1 reciprocal-square-root and exponent forms (e32 and e64 spellings of rsq and + exp) count as covered once the translator accepts their fixtures; the DPP and SDWA spellings and log, sin and + cos stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for key in pixel.F16_RSQ_EXP_PROGRAMS: + pixel.translate_f16(pixel.f16_rsq_exp_program(*key)) + ops = ("rsq", "exp") + forms = {("VOP1", f"v_{op}_f16") for op in ops} | {("VOP3", f"v_{op}_f16_e64") for op in ops} + assert len(forms) == 4 + neighbours = { + ("VOP1", "v_log_f16"), ("VOP3", "v_log_f16_e64"), + ("VOP1", "v_sin_f16"), ("VOP3", "v_cos_f16_e64"), + ("DPP16", "v_rsq_f16_dpp"), ("DPP16", "v_exp_f16_dpp"), + ("DPP8", "v_rsq_f16_dpp"), ("DPP8", "v_exp_f16_dpp"), + ("SDWA", "v_rsq_f16_sdwa"), ("SDWA", "v_exp_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not neighbours & covered, (name, sorted(neighbours & covered)) + # Without the rsq/exp fixtures none of the four forms is covered, not even through the other unary ones. + pixel.ACCEPTED.clear() + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + assert not forms & fc.gfx_forms(pixel.ACCEPTED, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + def check_f16_fmac_ldexp_forms(): """The two plain e32 binary16 forms v_fmac_f16 and v_ldexp_f16 count as covered once the translator accepts their fixtures; their e64, DPP and SDWA spellings and the arithmetic they resemble stay uncovered.""" @@ -1803,6 +1840,7 @@ def check_f16_cvt_norm_forms(): check_f16_arith_forms() check_f16_round_forms() check_f16_rcp_sqrt_forms() + check_f16_rsq_exp_forms() check_f16_fmac_ldexp_forms() check_f16_cvt_int16_forms() check_f16_to_int16_forms() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 79b3f37e25..99ba08801d 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -1,4 +1,5 @@ """Exercise offline pixel translation with independently assembled test programs.""" +from decimal import Decimal, localcontext from fractions import Fraction from pathlib import Path import bisect @@ -7824,7 +7825,7 @@ def refuse(line, message): for line in ("v_add_nc_u16 v24, v18, v19 op_sel:[0,0,1]", "v_add_nc_u16 v24, v18, v19 clamp", "v_add_nc_u16_dpp v24, v18, v19 quad_perm:[0,1,2,3]", "v_add_nc_u16_sdwa v24, v18, v19 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_rsq_f16_e64 v24, v18"): + "v_log_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") refuse("v_add_nc_u16 v24, v18, -v19", "Unsupported 16-bit integer operand") refuse("v_add_nc_u16 v24, v18, 1.0", "Unsupported 16-bit integer operand") @@ -16906,8 +16907,8 @@ def refuse(line, message, translator=translate_f16): for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_rsq_f16_e64 v24, v18", - "v_exp_f16_e32 v24, v18"): + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_log_f16_e64 v24, v18", + "v_log_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -17735,8 +17736,8 @@ def refuse(line, message, translator=translate_f16): "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_rsq_f16_e32 v24, v18", - "v_rsq_f16_e64 v24, v18", "v_exp_f16_e64 v24, v18"): + "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", + "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -17961,7 +17962,7 @@ def check_f16_rcp_sqrt_reference(): assert theirs is None, (op, hex(half), theirs) else: assert ours == theirs, (op, hex(half), hex(ours), theirs) - assert len(pixel_aot.VOP1_F16_UNARY) == 2 + assert len(pixel_aot.VOP1_F16_UNARY) == 4 def check_f16_rcp_sqrt_mutation_coverage(): @@ -18058,8 +18059,8 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_e64 v24, v18 mul:4", "v_sqrt_f16_e64 v24, v18 op_sel:[0,1]", "v_rcp_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_sqrt_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_rsq_f16_e32 v24, v18", - "v_exp_f16_e64 v24, v18", "v_log_f16_e32 v24, v18"): + "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_log_f16_e32 v24, v18", + "v_log_f16_e64 v24, v18", "v_sin_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18101,6 +18102,375 @@ def float_f16(instructions): expect_value_error(translate_f16, program(*produced, line), message) +# Plain binary16 VOP1 reciprocal square root and exponent (issue #839): v_rsq_f16 and v_exp_f16, e32 and e64. The +# lowering follows the direct compute path: widen16, one binary32 rsqrt or exp2, narrow16, then the RDNA 2 special +# selects from the source half (rsq: above +infinity to 0x7e00, +infinity to zero, zero magnitude to source | 0x7c00; +# exp: the 70 midpoint corrections, 2^-25 to zero, a magnitude above +infinity to 0x7e00). The Python reference +# evaluates the exact reciprocal square root and 2^S0 without pixel_aot. The chosen rsq sources avoid the 8 f32 ULP +# window of a binary16 rounding midpoint where the D3D rsqrt error allows either encoding. +F16_RSQ_EXP_OPS = ("rsq", "exp") +F16_RSQ_EXP_VALUES = ( + 0x3c00, 0x4400, 0xbc00, 0x0000, # 1 and 4 are exact roots; -1 is the canonical NaN; +0 is +infinity + 0x8000, 0x4000, 0x3800, 0xb800, # -0 gives -infinity; 2 and 0.5 are inexact; -0.5 is the canonical NaN + 0x0001, 0x0400, 0x7bff, 0x8001, # smallest subnormal, smallest normal, largest finite, -subnormal + 0x4900, 0x5100, 0x5b00, 0x6400, # 10, 40, 112 and 1024: exp overflows from 40 on + 0xce40, 0xc500, 0x11c3, 0x8dc6, # 2^-25 (exact tie to zero), -5, and two exp midpoint table rows + 0x4bff, 0x4c00, 0x3bff, 0x3c01, # just below 16, 16, 1 - ulp and 1 + ulp +) +F16_RSQ_EXP_READER_VALUES = (0x4400, 0x3c00, 0x0400, 0x0001) +# Chains (a, b): rsq(a), exp(rsq(a)), exp(b), rsq(exp(b)). Both orders stay finite in either operation order. +F16_RSQ_EXP_CHAINS = ((0x4400, 0x3c00), (0x3c00, 0x4000)) +F16_RSQ_EXP_MUTATIONS = ("ops_swapped", "src_high") + +_F16_EXP_MIDPOINT_CACHE = None + + +def f16_exp2_midpoints(): + """The direct compute exp2 midpoint corrections, generated by tests/f16_exp_midpoints.py.""" + global _F16_EXP_MIDPOINT_CACHE + if _F16_EXP_MIDPOINT_CACHE is None: + from f16_exp_midpoints import exp_f16_midpoints + _F16_EXP_MIDPOINT_CACHE = exp_f16_midpoints() + return _F16_EXP_MIDPOINT_CACHE + + +def f16_rsq_exp_reference(op, word, *, mutation=None): + """Binary16 result bits of v_rsq_f16 or v_exp_f16 on the low half of word, from the semantics only. + + The positive reciprocal square root is decided on the binary16 grid by exact integer comparisons (the search + boundary and every midpoint are squared against the source), so no rounding formula is shared with the + translator. A negative finite source is the canonical quiet NaN the direct compute path selects. Exp2 uses a + 90-digit reference and the same 70 midpoint corrections as the direct compute array; 2^-25 is the exact tie to + zero and 2^16 overflows. mutation models a deliberate deviation of the draw's mutated shaders. + """ + if mutation == "ops_swapped": + op = "exp" if op == "rsq" else "rsq" + half = (word >> 16 if mutation == "src_high" else word) & 0xffff + if op == "rsq": + if (half & 0x7fff) == 0: + return half | 0x7c00 + if half & 0x8000: + return 0x7e00 + source = f16_grid_value(half) + + def below(value): + return source * value * value < 1 + + low, high = 0x0400, 0x6c01 + while high - low > 1: + middle = (low + high) // 2 + if below(f16_grid_value(middle)): + low = middle + else: + high = middle + if source * f16_grid_value(high) ** 2 == 1: + return high + midpoint = (f16_grid_value(low) + f16_grid_value(high)) / 2 + if source * midpoint ** 2 == 1: + return low if low % 2 == 0 else high + return high if below(midpoint) else low + assert op == "exp" and (half & 0x7fff) < 0x7c00, hex(half) + if half == 0xce40: + return 0 + entry = f16_exp2_midpoints().get(half) + if entry is not None: + return entry + value = f16_grid_value(half) + if value >= 16: + return 0x7c00 + if value <= -25: + return 0 + with localcontext() as context: + context.prec = 90 + exponent = Decimal(value.numerator) / Decimal(value.denominator) + exact = Fraction((exponent * Decimal(2).ln()).exp()) + result = f16_grid_nearest(exact) + assert result is not None + return result + + +def f16_rsq_exp_word(index, slot): + """The 32-bit source word of F16_RSQ_EXP_VALUES[4 * index + slot], with junk in bits 31:16.""" + value = 4 * index + slot + return (F16_ARITH_JUNK[value % 4] << 16) | F16_RSQ_EXP_VALUES[value] + + +def f16_widen_any(bits): + """The binary32 encoding of any binary16 encoding as the widen16 helper reads it: finite exact, NaN payload + shifted into bits 22:13.""" + sign, exponent, mantissa = bits >> 15, (bits >> 10) & 31, bits & 1023 + if exponent == 0x1f: + return (sign << 31) | 0x7f800000 | (mantissa << 13) + return f16_widen_word(bits) + + +def f16_rsq_exp_program(kind, index): + """One draw program. Kinds: main (four values, both ops, two results packed per word), reader (one value through + the four readers) and chain (both ops in both orders).""" + pack = "v_mov_b32_sdwa v{dst}, v{src} dst_sel:{sel} dst_unused:{unused} src0_sel:WORD_0" + body = [] + if kind == "main": + for slot in range(4): + value = 4 * index + slot + word = f16_rsq_exp_word(index, slot) + reg, sgpr = 18 + slot, 60 + slot + body += [f"v_mov_b32_e32 v{reg}, {word:#x}", f"s_mov_b32 s{sgpr}, {word:#x}"] + literal = f16_arith_token(word & 0xffff) + for k, op in enumerate(F16_RSQ_EXP_OPS): + dst, form = 24 + 2 * slot + k, (value + k) % 4 + if form == 3 and literal is None: + form = 0 + body.append([f"v_{op}_f16_e32 v{dst}, v{reg}", f"v_{op}_f16_e64 v{dst}, v{reg}", + f"v_{op}_f16_e64 v{dst}, s{sgpr}", f"v_{op}_f16_e32 v{dst}, {literal}"][form]) + for word in range(4): + body.append(pack.format(dst=12 + word, src=24 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=25 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + elif kind == "reader": + word = (F16_ARITH_JUNK[index] << 16) | F16_RSQ_EXP_READER_VALUES[index] + body += [f"v_mov_b32_e32 v18, {word:#x}", "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v18"] + body += [line.format(24 + (r + index) % 2) for r, line in enumerate(F16_ROUND_READERS)] + else: + word_a, word_b = ((F16_ARITH_JUNK[k] << 16) | half for k, half in enumerate(F16_RSQ_EXP_CHAINS[index])) + body += [f"v_mov_b32_e32 v18, {word_a:#x}", f"v_mov_b32_e32 v19, {word_b:#x}", + "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v24", + "v_exp_f16_e32 v26, v19", "v_rsq_f16_e64 v27, v26"] + body += [f"v_cvt_f32_f16_e32 v{12 + slot}, v{24 + slot}" for slot in range(4)] + return uncompressed_export(body) + + +def f16_rsq_exp_source_halves(kind, index): + """The binary16 source encodings of one draw program.""" + if kind == "main": + return list(F16_RSQ_EXP_VALUES[4 * index:4 * index + 4]) + return [F16_RSQ_EXP_READER_VALUES[index]] if kind == "reader" else list(F16_RSQ_EXP_CHAINS[index]) + + +def f16_rsq_exp_expected(kind, index, mutation=None): + """The four exported words of f16_rsq_exp_program(kind, index).""" + def result(op, word): + return f16_rsq_exp_reference(op, word, mutation=mutation) + + if kind == "main": + results = [] + for slot in range(4): + results += [result(op, f16_rsq_exp_word(index, slot)) for op in F16_RSQ_EXP_OPS] + return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) + if kind == "reader": + word = (F16_ARITH_JUNK[index] << 16) | F16_RSQ_EXP_READER_VALUES[index] + results = [result(op, word) for op in F16_RSQ_EXP_OPS] + chosen = [results[(r + index) % 2] for r in range(4)] + return (*(f16_widen_any(bits) for bits in chosen[:3]), chosen[3]) + word_a, word_b = ((F16_ARITH_JUNK[k] << 16) | half for k, half in enumerate(F16_RSQ_EXP_CHAINS[index])) + root = result("rsq", word_a) + other_exp = result("exp", word_b) + return tuple(f16_widen_any(bits) for bits in (root, result("exp", root), other_exp, result("rsq", other_exp))) + + +F16_RSQ_EXP_PROGRAMS = (*(('main', i) for i in range(len(F16_RSQ_EXP_VALUES) // 4)), + *(('reader', i) for i in range(len(F16_RSQ_EXP_READER_VALUES))), + *(('chain', i) for i in range(len(F16_RSQ_EXP_CHAINS)))) + + +def f16_rsq_exp_mutated(mutation, program): + """The lowered source of program with one deviation applied.""" + if mutation == "ops_swapped": + swapped = [re.sub(r"v_(rsq|exp)_f16", lambda m: "v_exp_f16" if m[1] == "rsq" else "v_rsq_f16", line) + for line in program] + assert swapped != program, mutation + return translate_f16(swapped) + text = translate_f16(program) + mutated = re.sub(r"uint (hf\d+_0) = \((.+)\) & 0xffffu;", r"uint \1 = ((\2) >> 16u) & 0xffffu;", text) + assert mutated != text, mutation + return mutated + + +def f16_rsq_exp_detecting_program(mutation): + """The first program whose expected words the modelled mutation changes.""" + for kind, index in F16_RSQ_EXP_PROGRAMS: + if f16_rsq_exp_expected(kind, index, mutation) != f16_rsq_exp_expected(kind, index): + return kind, index + raise AssertionError(f"No program separates {mutation}") + + +def check_f16_rsq_exp_reference(): + """Pinned rows, the exp2 midpoint table against the direct compute source, and the translator's own result on + every finite binary16 source (all 65,536 encodings).""" + from f16_exp_midpoints import check_cpp_table + check_cpp_table() + table = f16_exp2_midpoints() + assert len(table) == 70 and pixel_aot.EXP_F16_MIDPOINTS == table + assert len(F16_RSQ_EXP_VALUES) == 24 and len(set(F16_RSQ_EXP_VALUES)) == 24 + assert all((half >> 10) & 31 != 31 for half in F16_RSQ_EXP_VALUES + F16_RSQ_EXP_READER_VALUES) + for op, half, expected in ( + ("rsq", 0x3c00, 0x3c00), ("rsq", 0x4400, 0x3800), ("rsq", 0x4000, 0x39a8), + ("rsq", 0x0400, 0x5800), ("rsq", 0x0001, 0x6c00), ("rsq", 0x7bff, 0x1c00), + ("rsq", 0x0000, 0x7c00), ("rsq", 0x8000, 0xfc00), ("rsq", 0x8001, 0x7e00), + ("rsq", 0xbc00, 0x7e00), + ("exp", 0x0000, 0x3c00), ("exp", 0x8000, 0x3c00), ("exp", 0x3c00, 0x4000), + ("exp", 0xbc00, 0x3800), ("exp", 0x3bff, 0x3fff), ("exp", 0x3c01, 0x4001), + ("exp", 0x4c00, 0x7c00), ("exp", 0xce40, 0x0000), ("exp", 0x11c3, 0x3c00), + ("exp", 0x8dc6, 0x3bff)): + assert f16_rsq_exp_reference(op, 0xa5c3_0000 | half) == expected, (op, hex(half), hex(expected)) + for half in range(0x10000): + if (half >> 10) & 31 == 31: + continue + for op in F16_RSQ_EXP_OPS: + ours = f16_rsq_exp_reference(op, 0x1234_0000 | half) + theirs = pixel_aot.f16_rsq_exp_result(op, half) + assert ours == theirs, (op, hex(half), hex(ours), theirs) + assert len(pixel_aot.VOP1_F16_UNARY) == 4 + + +def check_f16_rsq_exp_mutation_coverage(): + """Every deviation changes an expected word of some program.""" + for kind, index in F16_RSQ_EXP_PROGRAMS: + assert len(f16_rsq_exp_expected(kind, index)) == 4, (kind, index) + for mutation in F16_RSQ_EXP_MUTATIONS: + f16_rsq_exp_detecting_program(mutation) + assert f16_rsq_exp_reference("rsq", 0x4400) == 0x3800 + assert f16_rsq_exp_reference("rsq", 0x4400, mutation="ops_swapped") == 0x4c00 + assert f16_rsq_exp_reference("exp", 0x3c00) == 0x4000 + assert f16_rsq_exp_reference("exp", 0x3c00, mutation="ops_swapped") == 0x3c00 + assert f16_widen_any(0x7e00) == 0x7fc00000 and f16_widen_any(0x7c00) == 0x7f800000 + + +def check_f16_rsq_exp_controls(): + """Lowering, spelling, input proof, mode, modifier, special-result and reader refusals of v_rsq_f16 and + v_exp_f16.""" + check_f16_rsq_exp_reference() + check_f16_rsq_exp_mutation_coverage() + prefix = ["v_mov_b32_e32 v18, 0x35554000", "v_mov_b32_e32 v19, 0xd1a74400", "s_mov_b32 s60, 0x35550400"] + calls = {"rsq": "rsqrt(", "exp": "exp2("} + helpers = {"rsq": "f16_rsq_result(", "exp": "f16_exp2_result("} + + def program(*lines): + return uncompressed_export([*prefix, *lines]) + + def refuse(line, message, translator=translate_f16): + expect_value_error(translator, program(line), message) + + # Lowering and spelling: the bare, _e32 and _e64 spellings are one lowering, with the special-result select. + for op in F16_RSQ_EXP_OPS: + spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] + assert spelled[0] == spelled[1] == spelled[2], op + body = spelled[0].split("uint4 main", 1)[1] + assert calls[op] + "widen16(hf" in body, (op, body) + assert "narrow16(hs" in body and helpers[op] in body, op + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, (op, forbidden) + # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals. + for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), + ("0x7bff", 0x7bff)): + for op in F16_RSQ_EXP_OPS: + for encoding in ("_e32", "_e64"): + assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_{op}_f16{encoding} v24, {token}")), token + for line in ("v_rsq_f16_e64 v24, s60", "v_exp_f16_e32 v24, s60", "v_rsq_f16_e32 v24, v18"): + translate_f16(program(line)) + # A finite source is enough even when the result is not finite: rsq(0) is a signed infinity, rsq(-1) the + # canonical NaN and exp(16) an infinity; the canonical NaN can be read but does not stay a proven source. + for op, token in (("rsq", "0x0001"), ("rsq", "0"), ("rsq", "0x8000"), ("rsq", "-2.0"), + ("exp", "0x4c00"), ("exp", "0xce40"), ("exp", "0x7bff"), ("exp", "-2.0")): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + translate_f16(program("v_mov_b32_e32 v20, v18", "v_rsq_f16 v24, v20")) + translate_f16(program("s_mov_b32 s61, s60", "v_exp_f16_e64 v24, s61")) + translate_f16(program("v_rsq_f16 v24, 0x4400", "v_exp_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " + "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) + translate_f16(program("v_exp_f16 v24, 0xce40", "v_rsq_f16 v25, v24")) + expect_value_error(translate_f16, program("v_rsq_f16 v24, 0", "v_exp_f16 v25, v24"), + "binary16 operand is not finite: v24") + expect_value_error(translate_f16, program("v_exp_f16 v24, 0xce40", "v_rsq_f16 v25, v24", "v_exp_f16 v26, v25"), + "binary16 operand is not finite: v25") + expect_value_error(translate_f16, program("v_rsq_f16 v24, 0xbc00", "v_exp_f16 v25, v24"), + "binary16 operand is not finite: v24") + # Entry profile: unknown or an unsupported declaration refuses every spelling. + for op in F16_RSQ_EXP_OPS: + for suffix in ("", "_e32", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_{op}_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") + for state in ("flush", "ftz", "", False): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, + half_denorm=state), program("v_rsq_f16 v24, v18"), + "Invalid binary16 denormal entry state") + # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. + for line, token in (("v_rsq_f16_e64 v24, s44", "s44"), ("v_exp_f16 v24, v30", "v30"), + ("v_rsq_f16_e64 v24, v12", "v12")): + refuse(line, f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", "v_exp_f16 v24, v20"), + "binary16 operand lacks a finite proof: v20") + expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", "v_rsq_f16 v24, v25"), + "binary16 operand lacks a finite proof: v25") + # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. + for op in F16_RSQ_EXP_OPS: + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", "v_exp_f16 v24, v20"), + "binary16 operand is not finite: v20") + # Source modifiers, integer inline constants, floats and other operands. + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_rsq_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") + refuse(f"v_exp_f16_e32 v24, {token}", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_exp_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_rsq_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") + refuse("v_exp_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") + refuse("v_rsq_f16_e64 v256, 1.0", "Register out of range: v256") + refuse("v_exp_f16_e64 v24, v256", "Register out of range: v256") + refuse("v_rsq_f16_e64 v24, s106", "Register out of range: s106") + # Unmodelled modifiers and neighbouring forms fall through to the generic refusal. + for line in ("v_rsq_f16_e64 v24, v18 clamp", "v_exp_f16_e64 v24, v18 clamp", + "v_rsq_f16_e64 v24, v18 mul:2", "v_exp_f16_e64 v24, v18 div:2", + "v_rsq_f16_e64 v24, v18 mul:4", "v_exp_f16_e64 v24, v18 op_sel:[0,1]", + "v_rsq_f16_e32 v24, v18 clamp", "v_exp_f16_e32 v24, v18 clamp", + "v_rsq_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_exp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_exp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_log_f16_e32 v24, v18", + "v_log_f16_e64 v24, v18", "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18"): + refuse(line, "Unsupported instruction") + + # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. + def float_f16(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, half_denorm=pixel_aot.HALF_DENORM_PRESERVE) + + base = with_constants([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(float_f16, base[:load + 1] + ["v_rsq_f16_e64 v24, s44"] + base[load + 1:], + "Constant read before load completion") + expect_value_error(float_f16, base[:sample + 1] + ["v_exp_f16_e64 v12, 1.0"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(float_f16, base[:sample + 1] + ["v_rsq_f16_e64 v24, v12"] + base[sample + 1:], + "Sample used before vmcnt wait") + float_f16(base[:sample + 1] + ["v_exp_f16_e64 v20, 1.0"] + base[sample + 1:]) + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(float_f16, base[:masked] + ["v_rsq_f16_e64 v24, 1.0"] + base[masked:], + "Invalid binary16 unary operation") + # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. + for spelling in (f"v_{op}_f16{suffix}" for op in F16_RSQ_EXP_OPS for suffix in ("_e32", "_e64")): + line = f"{spelling} v24, v18" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + # Readers. The audited ones read a unary result; every other reader of the tag refuses it. + produced = [*prefix, "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v18"] + for register in (24, 25): + for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", + f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v{register} {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + (f"v_mov_b32_e32 v12, v{register}", "Expected a numeric register"), + (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) + + # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer # reader: a runtime i16 source needs no proof (every i16 is finite) but its result carries no known value; a u16 source must @@ -18462,9 +18832,9 @@ def refuse(line, message, translator=translate_f16): "v_cvt_f16_u16_e64 v24, v18 div:2", "v_cvt_f16_i16_e64 v24, v18 op_sel:[0,1]", "v_cvt_f16_i16_e64 v24, -v18 clamp", "v_cvt_f16_i16_e32 v24, v18 clamp", "v_cvt_f16_u16_e32 v24, 1 clamp", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", - "v_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -18825,9 +19195,9 @@ def refuse(line, message, translator=translate_f16): "v_cvt_u16_f16_e64 v24, v18 div:2", "v_cvt_i16_f16_e64 v24, v18 mul:4", "v_cvt_i16_f16_e64 v24, v18 op_sel:[0,1]", "v_cvt_i16_f16_e64 v24, -v18 clamp", "v_cvt_i16_f16_e32 v24, v18 clamp", "v_cvt_u16_f16_e32 v24, 1.0 clamp", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", - "v_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -19732,9 +20102,9 @@ def _check_controls_inline(directory): for expected in ("= ceil(alu", "= round(alu", "= round(params[1].x);", "= ceil((-params[1].y));"): assert expected in source, expected # Neighbouring forms: other widths, output modifiers, a second source and the IEEE-flag reciprocal. - for old, new in (("v_ceil_f32_e32 v12, v18", "v_rsq_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_log_f16_e32 v12, v18"), ("v_ceil_f32_e32 v12, v18", "v_ceil_f64_e32 v[12:13], v[18:19]"), - ("v_rndne_f32_e32 v13, v19", "v_rsq_f16_e32 v13, v19"), + ("v_rndne_f32_e32 v13, v19", "v_log_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), ("v_rndne_f32_e64 v14, s45", "v_rndne_f32_e64 v14, s45 mul:2"), ("v_ceil_f32_e64 v15, -s46", "v_ceil_f32_e64 v15, -s46 div:2"), @@ -20992,6 +21362,7 @@ def _check_controls_inline(directory): "check_f16_arith_controls", "check_f16_round_controls", "check_f16_rcp_sqrt_controls", + "check_f16_rsq_exp_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -21001,6 +21372,7 @@ def _check_controls_inline(directory): "check_s_version", "check_f16_round_controls", "check_f16_rcp_sqrt_controls", + "check_f16_rsq_exp_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -28111,6 +28483,49 @@ def case(kind, index, tag): "binary16 operand lacks a finite proof: s44") +def check_f16_rsq_exp_draw(directory, compiler, renderer, backend): + """v_rsq_f16 and v_exp_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. + + Six baked programs run 24 sources through both ops in a rotation of e32, e64, SGPR and literal forms and pack two + results per word; four reader programs and two chains cover the audited readers and both result orders. The values + cover exact roots and powers, inexact results, signed zeros, subnormals, the largest finite half, the 2^-25 underflow + tie, two exp2 midpoint corrections, an overflowing exp and the canonical negative-root NaN. Two deviations must + each mismatch (one batch per mutation; the statuses are printed): rsq and exp swapped, and a source read from bits + 31:16. A source nothing proves is refused at translation. + + Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's + high half is not measured here; the source-high mutation is the high-half control for the sources. + """ + check_f16_rsq_exp_mutation_coverage() + source = directory / "f16_rsq_exp.hlsl" + shader = directory / "f16_rsq_exp.cso" + constants = bytes(256) + + def build(text): + source.write_text(text, encoding="ascii") + compile_shader(compiler, source, shader) + + def case(kind, index, tag): + path = directory / f"f16_rsq_exp-{tag}-{kind}-{index}.case" + write_case(path, constants, tuple(as_float(word) for word in f16_rsq_exp_expected(kind, index)), integer_rt=True) + return path + + programs = {key: f16_rsq_exp_program(*key) for key in F16_RSQ_EXP_PROGRAMS} + for key in F16_RSQ_EXP_PROGRAMS: + build(translate_f16(programs[key])) + run_pixel_batch(renderer, backend, shader, [(case(*key, "ref"), "pass")]) + for mutation in F16_RSQ_EXP_MUTATIONS: + key = f16_rsq_exp_detecting_program(mutation) + build(f16_rsq_exp_mutated(mutation, programs[key])) + statuses, _ = run_pixel_batch_statuses(renderer, backend, shader, [case(*key, "mut")]) + print(f"f16_rsq_exp mutation {mutation}: program {key} statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"Mutating {mutation} escaped detection") + for op in F16_RSQ_EXP_OPS: + expect_value_error(translate_f16, uncompressed_export([f"v_{op}_f16_e64 v24, s44"]), + "binary16 operand lacks a finite proof: s44") + + def check_f16_fmac_ldexp_draw(directory, compiler, renderer, backend): """v_fmac_f16 and v_ldexp_f16 against the independent Python reference: 24 baked fused multiply-accumulate rows (cancellation, rows where rounding the product first gives another result, signed zero results, ties into the @@ -28372,7 +28787,7 @@ def main(): "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-cmpx-e64", "draw-cmpx-sdwa", "draw-scc-skip", "draw-s-call", "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", - "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", + "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, @@ -28410,6 +28825,7 @@ def main(): "draw-f16-arith": check_f16_arith_draw, "draw-f16-round": check_f16_round_draw, "draw-f16-rcp-sqrt": check_f16_rcp_sqrt_draw, + "draw-f16-rsq-exp": check_f16_rsq_exp_draw, "draw-f16-fmac-ldexp": check_f16_fmac_ldexp_draw, "draw-f16-cvt-int16": check_f16_cvt_int16_draw, "draw-f16-to-int16": check_f16_to_int16_draw, diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index bcd6178a77..479fa95654 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6282,7 +6282,7 @@ def test_low16_binary16_e32_scanner_support(self): f"v_{op}_f16_e32 v24, 0x3c00, v19", f"v_{op}_f16_e32 v24, 0, v19"] for op in ("floor", "ceil", "trunc", "rndne"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] - for op in ("rcp", "sqrt"): + for op in ("rcp", "sqrt", "rsq", "exp"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] for kind in ("i16", "u16"): supported += [f"v_cvt_f16_{kind}_e32 v24, v18", f"v_cvt_f16_{kind}_e32 v24, s45", @@ -6312,6 +6312,8 @@ def test_low16_binary16_e32_scanner_support(self): "v_floor_f16_e32 v24, v18 clamp", "v_rcp_f16_e32 v24, -v18", "v_sqrt_f16_e32 v24, v18 clamp", + "v_rsq_f16_e32 v24, -v18", + "v_exp_f16_e32 v24, v18 clamp", "v_fract_f16_e32 v24, v18", "v_cvt_f16_i16_e32 v24, 65", "v_cvt_f16_u16_e32 v24, 0x10000", @@ -6322,6 +6324,7 @@ def test_low16_binary16_e32_scanner_support(self): for line in refused: self.assertFalse(is_instruction_supported(line), line) for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_rcp_f16", "v_sqrt_f16", + "v_rsq_f16", "v_exp_f16", "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): self.assertIn(opcode, KNOWN_RDNA2_BASE_OPCODES) @@ -6350,7 +6353,7 @@ def translator_accepts(line): for op in ("floor", "ceil", "trunc", "rndne"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] - for op in ("rcp", "sqrt"): + for op in ("rcp", "sqrt", "rsq", "exp"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] refused = [ @@ -6361,12 +6364,14 @@ def translator_accepts(line): "v_add_f16_e64 v24, 3, v19", "v_add_f16_e64 v24, v18, 3", "v_add_f16_e64 v24, 3.0, v19", "v_add_f16_e64 v24, 0x10000, v19", "v_add_f16_e64 v24, v256, v19", "v_add_f16_e64 v256, v18, v19", "v_add_f16_e64 v24, s106, v19", "v_add_f16_e64 v24, v18", "v_add_f16_e64 v24, v18, v19, v19", - "v_fma_f16_e64 v24, v18, v19, v19", "v_rsq_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", + "v_fma_f16_e64 v24, v18, v19, v19", "v_log_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", "v_floor_f16_e64 v24, -v18", "v_floor_f16_e64 v24, |v18|", "v_floor_f16_e64 v24, v18 clamp", "v_floor_f16_e64 v24, v18 mul:2", "v_floor_f16_e64 v24, 3", "v_floor_f16_e64 v24, 0x10000", "v_floor_f16_e64 v24, v256", "v_floor_f16_e64 v24, v18, v19", "v_rndne_f16_e64 v24", "v_rcp_f16_e64 v24, -v18", "v_sqrt_f16_e64 v24, |v18|", "v_rcp_f16_e64 v24, v18 clamp", "v_sqrt_f16_e64 v24, v18 mul:2", "v_rcp_f16_e64 v24, 3", "v_sqrt_f16_e64 v24, 0x10000", + "v_rsq_f16_e64 v24, -v18", "v_exp_f16_e64 v24, |v18|", "v_rsq_f16_e64 v24, v18 clamp", + "v_exp_f16_e64 v24, v18 mul:2", "v_rsq_f16_e64 v24, 3", "v_exp_f16_e64 v24, 0x10000", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 9ad32beaea..30def60a3d 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1,6 +1,7 @@ """Offline lowering for selected gfx1013 and gfx1030 pixel shaders.""" import argparse import ctypes as C +from decimal import Decimal, localcontext from fractions import Fraction import hashlib import json @@ -1089,6 +1090,59 @@ def check_vopc_e32_dst(enc, dst): " return sa > sb ? (a & 0xffffu) : (b & 0xffffu);\n" "}" ), + # The RDNA 2 special results of v_rsq_f16 and v_exp_f16 from the source half bits, as the direct compute path + # selects them after packed_half_rne. The exp2 corrections are the 70 sources whose exact 2^S0 lies within the + # D3D exp2 error window of a binary16 rounding midpoint. + "f16_rsq_result": ( + "uint f16_rsq_result(uint source, uint rounded) {\n" + " if ((source & 0x7fffu) == 0u) return source | 0x7c00u;\n" + " if (source == 0x7c00u) return 0u;\n" + " if (source > 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), + "f16_exp2_result": ( + "uint f16_exp2_result(uint source, uint rounded) {\n" + " if (source == 0x11c3u) return 0x3c00u; if (source == 0x11c4u) return 0x3c00u;\n" + " if (source == 0x11c5u) return 0x3c01u; if (source == 0x11c6u) return 0x3c01u;\n" + " if (source == 0x11c7u) return 0x3c01u; if (source == 0x1853u) return 0x3c01u;\n" + " if (source == 0x1b34u) return 0x3c02u; if (source == 0x1b35u) return 0x3c03u;\n" + " if (source == 0x1e7au) return 0x3c04u; if (source == 0x1feau) return 0x3c06u;\n" + " if (source == 0x2164u) return 0x3c08u; if (source == 0x221bu) return 0x3c08u;\n" + " if (source == 0x2389u) return 0x3c0au; if (source == 0x2bdbu) return 0x3c2cu;\n" + " if (source == 0x2e7cu) return 0x3c4au; if (source == 0x2ea7u) return 0x3c4cu;\n" + " if (source == 0x2fe7u) return 0x3c5bu; if (source == 0x36b6u) return 0x3d5au;\n" + " if (source == 0x3863u) return 0x3dd9u; if (source == 0x39f8u) return 0x3eb5u;\n" + " if (source == 0x3a8au) return 0x3f0cu; if (source == 0x3b12u) return 0x3f62u;\n" + " if (source == 0x3b82u) return 0x3faau; if (source == 0x3efcu) return 0x42b5u;\n" + " if (source == 0x3f45u) return 0x430cu; if (source == 0x3f89u) return 0x4362u;\n" + " if (source == 0x3fc1u) return 0x43aau; if (source == 0x417eu) return 0x46b5u;\n" + " if (source == 0x437eu) return 0x4ab5u; if (source == 0x44bfu) return 0x4eb5u;\n" + " if (source == 0x45bfu) return 0x52b5u; if (source == 0x46bfu) return 0x56b5u;\n" + " if (source == 0x47bfu) return 0x5ab5u; if (source == 0x8dc3u) return 0x3c00u;\n" + " if (source == 0x8dc4u) return 0x3c00u; if (source == 0x8dc5u) return 0x3c00u;\n" + " if (source == 0x8dc6u) return 0x3bffu; if (source == 0x8dc7u) return 0x3bffu;\n" + " if (source == 0x8dc8u) return 0x3bffu; if (source == 0x9454u) return 0x3bffu;\n" + " if (source == 0x9455u) return 0x3bfeu; if (source == 0x9738u) return 0x3bfdu;\n" + " if (source == 0x990eu) return 0x3bfcu; if (source == 0x9a80u) return 0x3bfbu;\n" + " if (source == 0x9bf2u) return 0x3bfbu; if (source == 0x9e25u) return 0x3bf7u;\n" + " if (source == 0x9f98u) return 0x3bf5u; if (source == 0xa2b4u) return 0x3bedu;\n" + " if (source == 0xa52du) return 0x3be3u; if (source == 0xa86du) return 0x3bd0u;\n" + " if (source == 0xa8b4u) return 0x3bccu; if (source == 0xa9d1u) return 0x3bc0u;\n" + " if (source == 0xabe0u) return 0x3baau; if (source == 0xaf57u) return 0x3b63u;\n" + " if (source == 0xaf70u) return 0x3b62u; if (source == 0xb1d8u) return 0x3b0cu;\n" + " if (source == 0xb410u) return 0x3ab5u; if (source == 0xb4dbu) return 0x3a7cu;\n" + " if (source == 0xb73au) return 0x39d9u; if (source == 0xb8a5u) return 0x395au;\n" + " if (source == 0xbc3fu) return 0x37aau; if (source == 0xbc77u) return 0x3762u;\n" + " if (source == 0xbcbbu) return 0x370cu; if (source == 0xbd04u) return 0x36b5u;\n" + " if (source == 0xc082u) return 0x32b5u; if (source == 0xc282u) return 0x2eb5u;\n" + " if (source == 0xc441u) return 0x2ab5u; if (source == 0xc541u) return 0x26b5u;\n" + " if (source == 0xc641u) return 0x22b5u; if (source == 0xc741u) return 0x1eb5u;\n" + " if (source == 0xce40u) return 0u;\n" + " if ((source & 0x7fffu) > 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), "frexp_mant_f16": ( "uint frexp_mant_f16(uint bits) {\n" " uint h = bits & 0xffffu;\n" @@ -2109,8 +2163,34 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi # Plain binary16 VOP1 unary arithmetic (issue #839). These follow the direct compute lowering: widen the low half # exactly, evaluate one binary32 operation, then narrow with the same integer nearest-even conversion v_cvt_f16_f32 -# uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16 and D.f16 = sqrt(S0.f16). -VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})"} +# uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16, sqrt(S0.f16), 1.0 / sqrt(S0.f16) and 2^S0.f16. The +# rsqrt and exp2 approximations have a measured error window, so the lowered shader also applies the special-result +# and midpoint corrections of src/gfx1013_direct_compute.inl to the narrowed half. +VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})", "rsq": "rsqrt({0})", "exp": "exp2({0})"} + +# The 70 finite binary16 sources whose exact 2^S0 lies within the D3D exp2 error window of a binary16 rounding +# midpoint, with the RDNA 2 result. This is the exp_f16_midpoints table of src/gfx1013_direct_compute.inl; +# tests/f16_exp_midpoints.py regenerates the C++ array, and check_f16_rsq_exp_reference pins this copy to it. +EXP_F16_MIDPOINTS = { + 0x11c3: 0x3c00, 0x11c4: 0x3c00, 0x11c5: 0x3c01, 0x11c6: 0x3c01, + 0x11c7: 0x3c01, 0x1853: 0x3c01, 0x1b34: 0x3c02, 0x1b35: 0x3c03, + 0x1e7a: 0x3c04, 0x1fea: 0x3c06, 0x2164: 0x3c08, 0x221b: 0x3c08, + 0x2389: 0x3c0a, 0x2bdb: 0x3c2c, 0x2e7c: 0x3c4a, 0x2ea7: 0x3c4c, + 0x2fe7: 0x3c5b, 0x36b6: 0x3d5a, 0x3863: 0x3dd9, 0x39f8: 0x3eb5, + 0x3a8a: 0x3f0c, 0x3b12: 0x3f62, 0x3b82: 0x3faa, 0x3efc: 0x42b5, + 0x3f45: 0x430c, 0x3f89: 0x4362, 0x3fc1: 0x43aa, 0x417e: 0x46b5, + 0x437e: 0x4ab5, 0x44bf: 0x4eb5, 0x45bf: 0x52b5, 0x46bf: 0x56b5, + 0x47bf: 0x5ab5, 0x8dc3: 0x3c00, 0x8dc4: 0x3c00, 0x8dc5: 0x3c00, + 0x8dc6: 0x3bff, 0x8dc7: 0x3bff, 0x8dc8: 0x3bff, 0x9454: 0x3bff, + 0x9455: 0x3bfe, 0x9738: 0x3bfd, 0x990e: 0x3bfc, 0x9a80: 0x3bfb, + 0x9bf2: 0x3bfb, 0x9e25: 0x3bf7, 0x9f98: 0x3bf5, 0xa2b4: 0x3bed, + 0xa52d: 0x3be3, 0xa86d: 0x3bd0, 0xa8b4: 0x3bcc, 0xa9d1: 0x3bc0, + 0xabe0: 0x3baa, 0xaf57: 0x3b63, 0xaf70: 0x3b62, 0xb1d8: 0x3b0c, + 0xb410: 0x3ab5, 0xb4db: 0x3a7c, 0xb73a: 0x39d9, 0xb8a5: 0x395a, + 0xbc3f: 0x37aa, 0xbc77: 0x3762, 0xbcbb: 0x370c, 0xbd04: 0x36b5, + 0xc082: 0x32b5, 0xc282: 0x2eb5, 0xc441: 0x2ab5, 0xc541: 0x26b5, + 0xc641: 0x22b5, 0xc741: 0x1eb5, +} def _f16_fraction(bits): @@ -2239,6 +2319,76 @@ def f16_rcp_sqrt_result(name, bits): return _fraction_to_f16(_f32_fraction(_f32_sqrt_bits(value))) +_F16_LN2 = None + + +def _f16_ln2(): + """ln(2) to 90 significant digits, computed once for the exact exp2 references.""" + global _F16_LN2 + if _F16_LN2 is None: + with localcontext() as context: + context.prec = 90 + _F16_LN2 = Decimal(2).ln() + return _F16_LN2 + + +def _f16_rsq_result(value): + """Binary16 encoding nearest to 1/sqrt(value) for a positive finite Fraction, ties to even. + + No positive finite binary16 has a reciprocal square root that is exactly a binary16 rounding midpoint, so a + 90-digit reference decides every encoding; the rounding itself uses the translator's integer narrow16 rule. + """ + with localcontext() as context: + context.prec = 90 + root = (Decimal(value.numerator) / Decimal(value.denominator)).sqrt() + return _fraction_to_f16(Fraction(1 / root)) + + +def _f16_exp2_result(value): + """Binary16 encoding nearest to 2^value for a finite Fraction whose result is finite and nontrivial. + + The exact power is evaluated with a 90-digit Decimal instead of the binary32 exp2 intrinsic; the 70 sources + whose exact result lies inside that intrinsic's error window of a rounding midpoint are corrected from + EXP_F16_MIDPOINTS before this call, so every remaining source rounds deterministically. + """ + if value >= 16: + return 0x7c00 + if value <= -25: + return 0 + with localcontext() as context: + context.prec = 90 + exponent = Decimal(value.numerator) / Decimal(value.denominator) + return _fraction_to_f16(Fraction((exponent * _f16_ln2()).exp())) + + +def f16_rsq_exp_result(name, bits): + """Binary16 result bits of v_rsq_f16 or v_exp_f16 on a finite operand. + + The direct compute lowering widens with widen16, calls unary.f32 opcode 25 (rsqrt) or 21 (exp2), narrows with + packed_half_rne and then applies the RDNA 2 special results from the source half: rsq maps a source above + +infinity to 0x7e00, +infinity to zero and a zero magnitude to source | 0x7c00; exp pins the 70 midpoint + sources, 2^-25 to zero and a magnitude above +infinity to 0x7e00. The two approximations are not reproduced + bit for bit: every other rsq source rounds the exact reciprocal square root, and every other exp source rounds + the exact 2^S0, which is what the error windows guarantee after the midpoint corrections. The negative + reciprocal square root is the direct compute path's canonical quiet NaN, so both operations have a modelled + result on every finite source; None is never returned today. + """ + value = _f16_fraction(bits) + if name == "rsq": + if value == 0: + return bits | 0x7c00 + if value < 0: + return 0x7e00 + return _f16_rsq_result(value) + assert name == "exp" + if bits == 0xce40: + return 0 + entry = EXP_F16_MIDPOINTS.get(bits) + if entry is not None: + return entry + return _f16_exp2_result(value) + + def f16_round_result(name, bits): """Exact binary16 result bits of one VOP1_F16_ROUND op on a finite operand. @@ -7930,9 +8080,11 @@ def known_sample_float(reg): vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result elif m := match(rf"v_({'|'.join(VOP1_F16_UNARY)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): - # Plain binary16 VOP1 reciprocal and square root under the rules of the VOP2 arithmetic above: a statically - # proven finite source, the declared entry profile, no modifier, clamp or omod. These match the direct - # compute lowering: widen16, one binary32 division or sqrt, then narrow16. The result is ("half16", alu). + # Plain binary16 VOP1 reciprocal, square root, reciprocal square root and exponent under the rules of the + # VOP2 arithmetic above: a statically proven finite source, the declared entry profile, no modifier, clamp + # or omod. These match the direct compute lowering: widen16, one binary32 division, sqrt, rsqrt or exp2, + # then narrow16. rsq and exp additionally select the RDNA 2 special results from the source half bits. + # The result is ("half16", alu). name, encoding, dst, token = m.groups() if mask != "entry": raise ValueError("Invalid binary16 unary operation") @@ -7943,10 +8095,16 @@ def known_sample_float(reg): if dst in sample_dest: raise ValueError("Write overlaps an outstanding sample") word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) - result = f16_rcp_sqrt_result(name, proven) + result = (f16_rcp_sqrt_result(name, proven) if name in ("rcp", "sqrt") + else f16_rsq_exp_result(name, proven)) lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") lines.append(f" precise float hs{i} = {VOP1_F16_UNARY[name].format(f'widen16(hf{i}_0)')};") - lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + if name in ("rsq", "exp"): + helper = "f16_rsq_result" if name == "rsq" else "f16_exp2_result" + helpers.add(helper) + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, narrow16(hs{i})));") + else: + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") if result is not None: known_half[f"alu{i}"] = result diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index c376543339..02a562c0e0 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -473,7 +473,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: # Decoding only: no translator lowers these binary16 VOP1/VOP2 forms. "v_cvt_u16_f16", "v_cvt_i16_f16", "v_fract_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_rsq_f16", "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", + "v_log_f16", "v_sin_f16", "v_cos_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_fmac_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", "v_pk_fmac_f16", } From 4f5a88f3431b8a2b78216ead96db6acddb45ad45 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 06:23:34 +0000 Subject: [PATCH 2/5] shader: lower binary16 VOP1 logarithm --- CMakeLists.txt | 6 + docs/experiments.md | 8 +- tests/form_coverage_check.py | 37 +++ tests/pixel_aot_check.py | 395 ++++++++++++++++++++++++++++-- tests/rdna2_tools_check.py | 12 +- tools/pixel_aot.py | 118 ++++++++- tools/scan_unsupported_shaders.py | 4 +- 7 files changed, 549 insertions(+), 31 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 03b30a9d31..8506dd6ced 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11376,6 +11376,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rsq-exp "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME pixel_aot_f16_log_trig_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-log-trig "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_log_trig_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_f16_fmac_ldexp_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-fmac-ldexp "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -11666,6 +11670,8 @@ if(EXISTS "${INTAKE_PYTHON}") ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rcp_sqrt_${adapter}.txt") set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rsq_exp_${adapter}.txt") + set_tests_properties(pixel_aot_f16_log_trig_${adapter} PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_log_trig_${adapter}.txt") set_tests_properties(pixel_aot_f16_fmac_ldexp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_fmac_ldexp_${adapter}.txt") set_tests_properties(pixel_aot_f16_cvt_int16_${adapter} PROPERTIES diff --git a/docs/experiments.md b/docs/experiments.md index bd3fa70a5b..d76ee19772 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8999,13 +8999,15 @@ Plain non-fused binary16 `VOP2` arithmetic (issue #839) `v_add_f16`, `v_sub_f16` Plain binary16 `VOP1` rounding (issue #839) `v_floor_f16`, `v_ceil_f16`, `v_trunc_f16` and `v_rndne_f16`, in the unsuffixed, `_e32` and `_e64` spellings, rounds the low 16 bits of one source to an integer under the rules of the `VOP2` arithmetic above. LLVM 15.0.7 `VOP1Instructions.td` (lines 449-452) selects `ffloor`, `fceil`, `ftrunc` and `frint` for them; `frint` is round to nearest even under the default rounding mode. The half is widened exactly with `widen16`, one binary32 `floor`, `ceil`, `trunc` or `round` is evaluated under `precise` (HLSL `round` is round-half-to-even in DXIL, as the binary32 `rndne` entry already relies on), and `narrow16` narrows the result. The integer of a finite binary16 is at most 65504 in magnitude and therefore representable, so the narrowing is exact and no rounding rule for the result is needed; an exact zero keeps the sign of the source (`trunc(-0.5)`, `ceil(-0.3)` and `rndne(-0.4)` are `-0`, `floor(-0)` is `-0`). The source proof, the entry profile, the result tag and the audited readers are those of the `VOP2` arithmetic: a source is accepted only when its low half is statically proven finite (a binary16 inline constant, `0`, a 16-bit literal, a tracked SGPR, a VGPR copied from a constant, or the result of an earlier accepted binary16 op), `lower(..., half_denorm="preserve")` must declare the entry state (`binary16 denormal mode unknown at entry` otherwise, `Invalid binary16 denormal entry state` for another value), the destination is tagged `("half16", alu)`, and the translator computes the result with an exact integer reference (`f16_round_result`) so that a chain stays proven (`v_floor_f16 v24, 0x7bff` followed by `v_add_f16 v25, v24, 0x4bff` is accepted and `0x4c00` is refused as an overflow). The refusals carry exact messages: `binary16 operand lacks a finite proof: `, `binary16 operand is not finite: ` for a NaN or infinity constant in any provenance, `Unsupported binary16 source modifier `, `Unsupported binary16 integer inline constant `, `Unsupported binary16 operand `, `Invalid binary16 rounding operation` outside the entry mask, `Unsupported binary16 or binary64 operation under round toward zero: `, and `Unsupported instruction` for `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, a second source and the neighbouring `v_fract_f16` and `v_rsq_f16`. `clamp` and the output modifiers assemble on `_e64` (pinned in `check_f16_round_binary`, together with the encodings `v_floor_f16_e32 v1, v2` = `02 b7 02 7e`, `v_ceil_f16_e64 v1, v2` = `01 00 dc d5 02 01 00 00`, `v_trunc_f16_e32 v1, 1.0` and `v_rndne_f16_e32 v1, v2` = `02 bd 02 7e` from LLVM 15) and are refused. Every other reader of the tag refuses it as for the arithmetic results (`Expected a numeric register`, `Reads the undefined high half of a 16-bit result`, `Modifiers on a binary16 arithmetic result are not lowered`, `Unsupported export`). The controls (`check_f16_round_controls`, no GPU) cover each spelling, every operand kind, the refusals above, the scheduling and mask checks, the mode instructions before and after the op, the readers, pinned rows of the Python reference and a full comparison of the reference with `struct` format `e` plus `math.floor`, `math.ceil`, `math.trunc` and Python `round` (half-even) over every finite binary16 value, including the sign of zero, and with the translator's own copy. The draw (`tests/pixel_aot_check.py draw-f16-round`, tests `pixel_aot_f16_round_hardware` and `pixel_aot_f16_round_warp`, 60 s limit, capability skip 77) bakes every operand into the program: 21 programs run 42 values through all four ops in a rotation of e32, e64, SGPR and literal forms and pack two results per word with SDWA `WORD_0` and `WORD_1`; four programs read the four results through the four audited readers; two programs chain a `v_mul_f16` result into `v_trunc_f16` and `v_rndne_f16` and the `v_trunc_f16` result into `v_sub_f16`. The values cover both signs of zero, negative inputs that round to `-0`, the halfway cases 0.5, 1.5, 2.5, 3.5 and their negatives, 0.5 plus and minus one ulp, 1022.5 and 1023.5 (ulp 0.5, so halfway cases still exist), values from 1024 up (already integers, ulp 1, then ulp 2 from 2048) and +-65504, the subnormals `0x0001` and `0x03ff` with both signs and the smallest normal. A half-integer such as 2047.5 is not representable, the largest halfway case is 1023.5. Bits 31:16 of every source word hold junk. The readback is the lossless `R32G32B32A32_UINT` target against `f16_round_reference`, an integer implementation without `pixel_aot`; the programs with subnormal operands also run under a binary32 `-denorm ftz` build and must still pass. Five deviations must each mismatch, one batch per mutation with the statuses printed (`floor` and `ceil` swapped, `trunc` lowered as `floor`, `rndne` lowered as round half away from zero, the sign of a `-0` result lost, and a source read from bits 31:16), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands, the hardware reading of integer inline constants on binary16 operands, and the `frint` rounding mode of the console beyond the default mode that the entry assumption names. -Plain binary16 `VOP1` reciprocal and square root (issue #839) `v_rcp_f16` and `v_sqrt_f16`, in the unsuffixed, `_e32` and `_e64` spellings, reproduce the direct compute lowering under the source-proof and entry-profile rules of the binary16 forms above. The 16-bit source is widened exactly with `widen16`, `v_rcp_f16` evaluates `1.0f / S0` in binary32, `v_sqrt_f16` evaluates the direct compute path's square root (`unary.f32` opcode 24), and `narrow16` performs one binary16 round to nearest even. The intermediate binary32 round is significant: the translator tracks the result with `f16_rcp_sqrt_result`, which rounds the exact quotient or root once to binary32 and then to binary16 instead of double-rounding the exact value straight to binary16. A reciprocal at or above the binary16 overflow threshold is a signed infinity; zero gives the signed infinity; the negative square root is a NaN whose payload is not modelled, so it can be read but does not stay a proven value for a chain. `2.0` gives `0.5` for `rcp` and `4.0` gives `2.0` for `sqrt`; the draw also covers values that exercise the two rounding steps, subnormals, the largest finite half and an overflowing reciprocal. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. Source modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, an extra operand and the neighbouring `v_rsq_f16`, `v_exp_f16` and `v_log_f16` stay refused; the exact messages are the binary16 source, range and modifier refusals above plus `Invalid binary16 unary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. Round toward zero refuses both spellings through the shared binary16 mode check. +Plain binary16 `VOP1` reciprocal and square root (issue #839) `v_rcp_f16` and `v_sqrt_f16`, in the unsuffixed, `_e32` and `_e64` spellings, reproduce the direct compute lowering under the source-proof and entry-profile rules of the binary16 forms above. The 16-bit source is widened exactly with `widen16`, `v_rcp_f16` evaluates `1.0f / S0` in binary32, `v_sqrt_f16` evaluates the direct compute path's square root (`unary.f32` opcode 24), and `narrow16` performs one binary16 round to nearest even. The intermediate binary32 round is significant: the translator tracks the result with `f16_rcp_sqrt_result`, which rounds the exact quotient or root once to binary32 and then to binary16 instead of double-rounding the exact value straight to binary16. A reciprocal at or above the binary16 overflow threshold is a signed infinity; zero gives the signed infinity; the negative square root is a NaN whose payload is not modelled, so it can be read but does not stay a proven value for a chain. `2.0` gives `0.5` for `rcp` and `4.0` gives `2.0` for `sqrt`; the draw also covers values that exercise the two rounding steps, subnormals, the largest finite half and an overflowing reciprocal. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. Source modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA, an extra operand and the neighbouring `v_rsq_f16` and `v_exp_f16` stay refused; the exact messages are the binary16 source, range and modifier refusals above plus `Invalid binary16 unary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. Round toward zero refuses both spellings through the shared binary16 mode check. The controls (`check_f16_rcp_sqrt_controls`, no GPU) cover the bare, `_e32` and `_e64` spellings, every source kind, the finite, register, modifier, mode, scheduling, sample and reader refusals, and chains of both operations. The Python reference (`f16_rcp_sqrt_reference`) applies the same two rounds from the semantics without `pixel_aot`, handles the binary16 overflow threshold and compares with the translator's `f16_rcp_sqrt_result` on every finite encoding. The draw (`tests/pixel_aot_check.py draw-f16-rcp-sqrt`, tests `pixel_aot_f16_rcp_sqrt_hardware` and `pixel_aot_f16_rcp_sqrt_warp`, 60 s limit, capability skip 77) runs five baked programs over 20 source values through both ops in a rotation of e32, e64, SGPR and literal forms and packs two results per word with SDWA `WORD_0` and `WORD_1`; four reader programs and two chains read both result tags. Bits 31:16 of every source word hold junk. The lossless `R32G32B32A32_UINT` readback is compared with the Python reference. Two deviations must each mismatch, one batch per mutation with the statuses printed (reciprocal and square root swapped, and a source read from bits 31:16), and a source with no finite proof is refused at translation. Both tests passed on WARP and on the RX 9060 XT. In `gfx1013.tsv` and `rdna2.tsv` the two operations add their VOP1 and VOP3 rows, so the fixture records four newly covered forms (rcp and sqrt, each e32 and e64); the two operations themselves are the +2. `tests/form_coverage_check.py check_f16_rcp_sqrt_forms` pins that the DPP, SDWA and rsq neighbours stay uncovered. `tools/scan_unsupported_shaders.py` accepts the syntactic source forms and `tests/rdna2_tools_check.py test_binary16_e64_scanner_translator_agreement` checks that its acceptance agrees with `pixel_aot.lower`. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN payloads and special-function results beyond the modelled infinities, runtime sources, the DPP and SDWA spellings, the hardware behaviour of integer inline constants on binary16 operands, and whether any title executes these paths. -Plain binary16 `VOP1` reciprocal square root and exponent (issue #839), `v_rsq_f16` and `v_exp_f16`, extend the unary entry above: the unsuffixed, `_e32` and `_e64` spellings widen the low half with `widen16`, evaluate the direct compute path's `rsqrt` or `exp2` in binary32, narrow with `narrow16`, and then select RDNA 2's special results from the source half. `v_rsq_f16` maps any source above `+infinity` (every negative finite encoding) to the canonical quiet NaN `0x7e00`, `+infinity` to zero and a zero magnitude to `source | 0x7c00`, so `-0` gives `-infinity`; `v_exp_f16` applies the 70 midpoint corrections of `exp_f16_midpoints` from `src/gfx1013_direct_compute.inl`, maps `2^-25` (`0xce40`) to zero and a magnitude above `+infinity` to `0x7e00`. The emitted helpers are `f16_rsq_result` and `f16_exp2_result`, and `tools/pixel_aot.py` carries the same table as `EXP_F16_MIDPOINTS`. The translator tracks each result with `f16_rsq_exp_result`: a positive finite reciprocal square root is rounded exactly to binary16 with a 90-digit reference, a negative one is the canonical NaN above, and `exp` rounds the exact `2^S0` after the table corrections. Every finite source therefore has a modelled result and the function does not return None; its signature keeps the None contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the reciprocal and square root entry; the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused, and `v_log_f16`, `v_sin_f16` and `v_cos_f16` remain unlowered. +Plain binary16 `VOP1` reciprocal square root and exponent (issue #839), `v_rsq_f16` and `v_exp_f16`, extend the unary entry above: the unsuffixed, `_e32` and `_e64` spellings widen the low half with `widen16`, evaluate the direct compute path's `rsqrt` or `exp2` in binary32, narrow with `narrow16`, and then select RDNA 2's special results from the source half. `v_rsq_f16` maps any source above `+infinity` (every negative finite encoding) to the canonical quiet NaN `0x7e00`, `+infinity` to zero and a zero magnitude to `source | 0x7c00`, so `-0` gives `-infinity`; `v_exp_f16` applies the 70 midpoint corrections of `exp_f16_midpoints` from `src/gfx1013_direct_compute.inl`, maps `2^-25` (`0xce40`) to zero and a magnitude above `+infinity` to `0x7e00`. The emitted helpers are `f16_rsq_result` and `f16_exp2_result`, and `tools/pixel_aot.py` carries the same table as `EXP_F16_MIDPOINTS`. The translator tracks each result with `f16_rsq_exp_result`: a positive finite reciprocal square root is rounded exactly to binary16 with a 90-digit reference, a negative one is the canonical NaN above, and `exp` rounds the exact `2^S0` after the table corrections. Every finite source therefore has a modelled result and the function does not return None; its signature keeps the None contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the reciprocal and square root entry; the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused, and `v_sin_f16` and `v_cos_f16` remain unlowered. -The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining log, sin and cos forms, and whether any title executes these paths. +The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining sin and cos forms, and whether any title executes these paths. + +Plain binary16 `VOP1` logarithm (issue #839) `v_log_f16`, in the unsuffixed, `_e32` and `_e64` spellings, extends the unary entry above: the low half is widened exactly with `widen16`, the direct compute path's `log2` (`unary.f32` opcode 23) is evaluated in binary32, `narrow16` rounds once, and then the RDNA 2 special results and midpoint corrections are selected from the source half. `+infinity` stays `+infinity`, every NaN and every negative nonzero source becomes the canonical quiet NaN `0x7e00`, and either zero becomes `-infinity` (`0xfc00`). The emitter carries the 73 sources whose exact log2 lies within the D3D Log error window of a binary16 rounding midpoint; `tests/f16_log_midpoints.py` regenerates and checks the C++ `log_f16_midpoints` array, and `tools/pixel_aot.py` carries the same table as `LOG_F16_MIDPOINTS`. The translator tracks each result with `f16_log_trig_result`, which returns the table entry or rounds the exact log2 of every other positive finite source with a 90-digit Decimal reference. Every encoding has a modelled result, so None is never returned today; the signature keeps that contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the unary forms above, and the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused. The controls (`check_f16_log_trig_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, pin `LOG_F16_MIDPOINTS` to the C++ array through `tests/f16_log_midpoints.py check_cpp_table`, and compare the reference with `f16_log_trig_result` on all 65,536 encodings. The draw (`tests/pixel_aot_check.py draw-f16-log-trig`, tests `pixel_aot_f16_log_trig_hardware` and `pixel_aot_f16_log_trig_warp`, 60 s limit, capability skip 77) runs three baked programs over 24 values in a rotation of e32, e64, SGPR and literal forms, packs two results per word with SDWA `WORD_0` and `WORD_1`, and adds one chain that computes `log2(log2(x))` for eight values above 1; the values cover exact powers, inexact results, both signed zeros, subnormals, the largest finite half, negative sources, the `log2(1)` row and three midpoint-table rows. The lossless `R32G32B32A32_UINT` readback is compared with `f16_log_trig_reference`, a 90-digit reference without `pixel_aot`. Three deviations must each mismatch, one batch per mutation with the statuses printed (a source read from bits 31:16, the `1 + ulp` midpoint correction off by one encoding, and `log2` replaced by the natural log), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_log_trig_forms` pins the two newly covered forms (log e32 and e64) and leaves the DPP, SDWA, sin and cos neighbours uncovered; the two forms take the measured totals from 1550/1968 and 1541/1863 to 1552/1968 and 1543/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D Log error window beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining sin and cos forms, and whether any title executes these paths. Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 0ed8799184..edca5bb0b2 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -758,6 +758,42 @@ def check_f16_rsq_exp_forms(): pixel.ACCEPTED.update(saved) +def check_f16_log_trig_forms(): + """The two plain binary16 VOP1 logarithm forms (e32 and e64 spellings of log) count as covered once the + translator accepts their fixtures; the DPP and SDWA spellings stay uncovered, and sin and cos have their own + fixture.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for key in pixel.F16_LOG_TRIG_PROGRAMS: + pixel.translate_f16(pixel.f16_log_trig_program(*key)) + ops = ("log",) + forms = {("VOP1", f"v_{op}_f16") for op in ops} | {("VOP3", f"v_{op}_f16_e64") for op in ops} + assert len(forms) == 2 + neighbours = { + ("VOP1", "v_sin_f16"), ("VOP3", "v_sin_f16_e64"), + ("VOP1", "v_cos_f16"), ("VOP3", "v_cos_f16_e64"), + ("DPP16", "v_log_f16_dpp"), ("DPP8", "v_log_f16_dpp"), + ("SDWA", "v_log_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not neighbours & covered, (name, sorted(neighbours & covered)) + # Without the log fixtures neither form is covered, not even through the other unary ones. + pixel.ACCEPTED.clear() + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + assert not forms & fc.gfx_forms(pixel.ACCEPTED, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + def check_f16_fmac_ldexp_forms(): """The two plain e32 binary16 forms v_fmac_f16 and v_ldexp_f16 count as covered once the translator accepts their fixtures; their e64, DPP and SDWA spellings and the arithmetic they resemble stay uncovered.""" @@ -1841,6 +1877,7 @@ def check_f16_cvt_norm_forms(): check_f16_round_forms() check_f16_rcp_sqrt_forms() check_f16_rsq_exp_forms() + check_f16_log_trig_forms() check_f16_fmac_ldexp_forms() check_f16_cvt_int16_forms() check_f16_to_int16_forms() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 99ba08801d..f3bddc6c56 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -7825,7 +7825,7 @@ def refuse(line, message): for line in ("v_add_nc_u16 v24, v18, v19 op_sel:[0,0,1]", "v_add_nc_u16 v24, v18, v19 clamp", "v_add_nc_u16_dpp v24, v18, v19 quad_perm:[0,1,2,3]", "v_add_nc_u16_sdwa v24, v18, v19 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_log_f16_e64 v24, v18"): + "v_sin_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") refuse("v_add_nc_u16 v24, v18, -v19", "Unsupported 16-bit integer operand") refuse("v_add_nc_u16 v24, v18, 1.0", "Unsupported 16-bit integer operand") @@ -16907,8 +16907,8 @@ def refuse(line, message, translator=translate_f16): for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_log_f16_e64 v24, v18", - "v_log_f16_e32 v24, v18"): + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_sin_f16_e64 v24, v18", + "v_cos_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -17736,7 +17736,7 @@ def refuse(line, message, translator=translate_f16): "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", + "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") @@ -17962,7 +17962,7 @@ def check_f16_rcp_sqrt_reference(): assert theirs is None, (op, hex(half), theirs) else: assert ours == theirs, (op, hex(half), hex(ours), theirs) - assert len(pixel_aot.VOP1_F16_UNARY) == 4 + assert {"rcp", "sqrt", "rsq", "exp"} <= set(pixel_aot.VOP1_F16_UNARY) def check_f16_rcp_sqrt_mutation_coverage(): @@ -18059,8 +18059,8 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_e64 v24, v18 mul:4", "v_sqrt_f16_e64 v24, v18 op_sel:[0,1]", "v_rcp_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_sqrt_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_log_f16_e32 v24, v18", - "v_log_f16_e64 v24, v18", "v_sin_f16_e32 v24, v18"): + "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", + "v_sin_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18318,7 +18318,7 @@ def check_f16_rsq_exp_reference(): ours = f16_rsq_exp_reference(op, 0x1234_0000 | half) theirs = pixel_aot.f16_rsq_exp_result(op, half) assert ours == theirs, (op, hex(half), hex(ours), theirs) - assert len(pixel_aot.VOP1_F16_UNARY) == 4 + assert {"rcp", "sqrt", "rsq", "exp"} <= set(pixel_aot.VOP1_F16_UNARY) def check_f16_rsq_exp_mutation_coverage(): @@ -18428,8 +18428,8 @@ def refuse(line, message, translator=translate_f16): "v_exp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_exp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_log_f16_e32 v24, v18", - "v_log_f16_e64 v24, v18", "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18"): + "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_sin_f16_e32 v24, v18", + "v_cos_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18471,6 +18471,326 @@ def float_f16(instructions): expect_value_error(translate_f16, program(*produced, line), message) +# Plain binary16 VOP1 logarithm (issue #839): v_log_f16, e32 and e64. The lowering follows the direct compute path: +# widen16, one binary32 log2, narrow16, then the RDNA 2 special selects and the 73 midpoint corrections from the +# source half (+infinity stays +infinity, NaN and negative nonzero become 0x7e00, either zero becomes 0xfc00). +# The reference evaluates the exact log2 with a 90-digit Decimal and uses the generated midpoint table, so it shares +# no rounding formula with pixel_aot. +F16_LOG_TRIG_OPS = ("log",) +F16_LOG_TRIG_VALUES = { + "log": ( + 0x0000, 0x8000, 0x0001, 0x03ff, 0x0400, 0x3c00, # zeros, subnormals, min normal, 1 + 0x3c01, 0x3bff, 0x4000, 0x3800, 0x3400, 0x4400, # 1 +- ulp, 2, 0.5, 0.25, 4 + 0x4800, 0x6400, 0x7bff, 0xfbff, 0xbc00, 0x8001, # 8, 1024, +-max, -1, -min subnormal + 0x4200, 0x4900, 0x2e66, 0x0144, 0x7aa3, 0x4089, # 3, 10, 0.1, three midpoint rows + ), +} +# Chains: eight positive values above 1 whose log2 is finite and positive, so log2(log2(x)) is finite. +F16_LOG_TRIG_CHAINS = ((0x4000, 0x4400, 0x4800, 0x6400, 0x4200, 0x4900, 0x3c01, 0x7bff),) +F16_LOG_TRIG_MUTATIONS = ("src_high", "table_off", "natural_log") + +_F16_LOG_MIDPOINT_CACHE = None + + +def f16_log_midpoints(): + """The direct compute log2 midpoint corrections, generated by tests/f16_log_midpoints.py.""" + global _F16_LOG_MIDPOINT_CACHE + if _F16_LOG_MIDPOINT_CACHE is None: + from f16_log_midpoints import log_f16_midpoints + _F16_LOG_MIDPOINT_CACHE = log_f16_midpoints() + return _F16_LOG_MIDPOINT_CACHE + + +def f16_log_trig_reference(op, word, *, mutation=None): + """Binary16 result bits of v_log_f16 on the low half of word, from the semantics only. + + Log2 uses a 90-digit reference and the same 73 midpoint corrections as the direct compute array. The special + results follow RDNA 2: +-0 gives -infinity, +infinity stays +infinity, and every NaN or negative nonzero source + gives the canonical quiet NaN 0x7e00. mutation models a deliberate deviation of the draw's mutated shaders: + src_high reads bits 31:16, table_off mis-corrects the 1 + ulp midpoint row by one encoding, and natural_log + computes ln instead of log2. + """ + assert op == "log" + half = (word >> 16 if mutation == "src_high" else word) & 0xffff + magnitude = half & 0x7fff + if magnitude == 0: + return 0xfc00 + if half == 0x7c00: + return 0x7c00 + if magnitude >= 0x7c00 or half & 0x8000: + return 0x7e00 + if mutation == "table_off" and half == 0x3c01: + return 0x15c4 + if mutation != "natural_log": + entry = f16_log_midpoints().get(half) + if entry is not None: + return entry + value = f16_grid_value(half) + with localcontext() as context: + context.prec = 90 + operand = Decimal(value.numerator) / Decimal(value.denominator) + logarithm = operand.ln() if mutation == "natural_log" else operand.ln() / Decimal(2).ln() + result = f16_grid_nearest(Fraction(logarithm)) + assert result is not None + return result + + +def f16_log_trig_word(index, slot): + """The 32-bit source word of F16_LOG_TRIG_VALUES["log"][8 * index + slot], with junk in bits 31:16.""" + value = 8 * index + slot + return (F16_ARITH_JUNK[value % 4] << 16) | F16_LOG_TRIG_VALUES["log"][value] + + +def f16_log_trig_program(kind, index): + """One draw program. Kinds: main (eight values, packed two results per word) and chain (log2(log2(x))).""" + pack = "v_mov_b32_sdwa v{dst}, v{src} dst_sel:{sel} dst_unused:{unused} src0_sel:WORD_0" + body = [] + if kind == "main": + for slot in range(8): + word = f16_log_trig_word(index, slot) + body += [f"v_mov_b32_e32 v{18 + slot}, {word:#x}", f"s_mov_b32 s{60 + slot}, {word:#x}"] + for slot in range(8): + half = F16_LOG_TRIG_VALUES["log"][8 * index + slot] + literal = f16_arith_token(half) + form = (8 * index + slot) % 4 + if form == 3 and literal is None: + form = 0 + body.append([ + f"v_log_f16_e32 v{26 + slot}, v{18 + slot}", + f"v_log_f16_e64 v{26 + slot}, v{18 + slot}", + f"v_log_f16_e64 v{26 + slot}, s{60 + slot}", + f"v_log_f16_e32 v{26 + slot}, {literal}", + ][form]) + for word in range(4): + body.append(pack.format(dst=12 + word, src=26 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=27 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + else: + for slot, half in enumerate(F16_LOG_TRIG_CHAINS[index]): + word = (F16_ARITH_JUNK[slot % 4] << 16) | half + body += [f"v_mov_b32_e32 v{18 + slot}, {word:#x}", f"s_mov_b32 s{60 + slot}, {word:#x}", + f"v_mov_b32_e32 v{26 + slot}, {(F16_ARITH_JUNK[(slot + 1) % 4] << 16) | 0:#x}"] + literal = f16_arith_token(half) + form = slot % 4 + if form == 3 and literal is None: + form = 0 + body.append([ + f"v_log_f16_e32 v{26 + slot}, v{18 + slot}", + f"v_log_f16_e64 v{26 + slot}, v{18 + slot}", + f"v_log_f16_e64 v{26 + slot}, s{60 + slot}", + f"v_log_f16_e32 v{26 + slot}, {literal}", + ][form]) + body.append([f"v_log_f16_e32 v{34 + slot}, v{26 + slot}", + f"v_log_f16_e64 v{34 + slot}, v{26 + slot}"][slot % 2]) + for word in range(4): + body.append(pack.format(dst=12 + word, src=34 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=35 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + return uncompressed_export(body) + + +def f16_log_trig_source_halves(kind, index): + """The binary16 source encodings of one draw program.""" + if kind == "main": + return list(F16_LOG_TRIG_VALUES["log"][8 * index:8 * index + 8]) + return list(F16_LOG_TRIG_CHAINS[index]) + + +def f16_log_trig_expected(kind, index, mutation=None): + """The four exported words of f16_log_trig_program(kind, index).""" + if kind == "main": + results = [f16_log_trig_reference("log", f16_log_trig_word(index, slot), mutation=mutation) + for slot in range(8)] + return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) + assert mutation is None + results = [] + for half in F16_LOG_TRIG_CHAINS[index]: + first = f16_log_trig_reference("log", half) + results.append(f16_log_trig_reference("log", first)) + return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) + + +F16_LOG_TRIG_PROGRAMS = (*(("main", i) for i in range(len(F16_LOG_TRIG_VALUES["log"]) // 8)), + *(("chain", i) for i in range(len(F16_LOG_TRIG_CHAINS)))) + + +def f16_log_trig_mutated(mutation, program): + """The lowered source of program (instruction lines) with one deviation applied.""" + text = translate_f16(program) + if mutation == "src_high": + mutated = re.sub(r"uint (hf\d+_0) = \((.+)\) & 0xffffu;", r"uint \1 = ((\2) >> 16u) & 0xffffu;", text) + elif mutation == "table_off": + mutated = text.replace("if (source == 0x3c01u) return 0x15c5u;", + "if (source == 0x3c01u) return 0x15c4u;") + else: + assert mutation == "natural_log" + mutated = text.replace("log2(widen16(hf", "log(widen16(hf") + assert mutated != text, mutation + return mutated + + +def f16_log_trig_detecting_program(mutation): + """The first program whose expected words the modelled mutation changes.""" + for kind, index in F16_LOG_TRIG_PROGRAMS: + if kind != "main": + continue + if f16_log_trig_expected(kind, index, mutation) != f16_log_trig_expected(kind, index): + return kind, index + raise AssertionError(f"No program separates {mutation}") + + +def check_f16_log_trig_reference(): + """Pinned rows, the log2 midpoint table against the direct compute source, and the translator's own result on + every binary16 encoding.""" + from f16_log_midpoints import check_cpp_table + check_cpp_table() + table = f16_log_midpoints() + assert len(table) == 73 and pixel_aot.LOG_F16_MIDPOINTS == table + for half, expected in ( + (0x3c00, 0x0000), (0x4000, 0x3c00), (0x3800, 0xbc00), (0x3400, 0xc000), + (0x0000, 0xfc00), (0x8000, 0xfc00), (0x0001, 0xce00), (0x7bff, 0x4c00), + (0xbc00, 0x7e00), (0xfbff, 0x7e00), (0x7c00, 0x7c00), (0xfc00, 0x7e00), + (0x7e00, 0x7e00), (0xfe01, 0x7e00), + (0x0144, 0xcbd4), (0x3c01, 0x15c5), (0x7aa3, 0x4bde), (0x4089, 0x3cb9)): + assert f16_log_trig_reference("log", 0xa5c3_0000 | half) == expected, (hex(half), hex(expected)) + for half in range(0x10000): + ours = f16_log_trig_reference("log", 0x1234_0000 | half) + theirs = pixel_aot.f16_log_trig_result("log", half) + assert ours == theirs, (hex(half), hex(ours), theirs) + assert "log" in pixel_aot.VOP1_F16_UNARY + + +def check_f16_log_trig_mutation_coverage(): + """Every deviation changes an expected word of some program.""" + for kind, index in F16_LOG_TRIG_PROGRAMS: + assert len(f16_log_trig_expected(kind, index)) == 4, (kind, index) + for mutation in F16_LOG_TRIG_MUTATIONS: + f16_log_trig_detecting_program(mutation) + assert f16_log_trig_reference("log", 0x3c01) == 0x15c5 + assert f16_log_trig_reference("log", 0x3c01, mutation="table_off") == 0x15c4 + assert f16_log_trig_reference("log", 0x4000) == 0x3c00 + assert f16_log_trig_reference("log", 0x4000, mutation="natural_log") != 0x3c00 + + +def check_f16_log_trig_controls(): + """Lowering, spelling, input proof, mode, modifier, special-result and reader refusals of v_log_f16.""" + check_f16_log_trig_reference() + check_f16_log_trig_mutation_coverage() + prefix = ["v_mov_b32_e32 v18, 0x35554000", "v_mov_b32_e32 v19, 0xd1a74400", "s_mov_b32 s60, 0x35550400"] + + def program(*lines): + return uncompressed_export([*prefix, *lines]) + + def refuse(line, message, translator=translate_f16): + expect_value_error(translator, program(line), message) + + # Lowering and spelling: the bare, _e32 and _e64 spellings are one lowering, with the special-result select. + spelled = [translate_f16(program(f"v_log_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] + assert spelled[0] == spelled[1] == spelled[2] + body = spelled[0].split("uint4 main", 1)[1] + assert "log2(widen16(hf" in body and "f16_log_result(" in body + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, forbidden + # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals. + for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), + ("0x7bff", 0x7bff)): + for encoding in ("_e32", "_e64"): + assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_log_f16{encoding} v24, {token}")), token + for line in ("v_log_f16_e64 v24, s60", "v_log_f16_e32 v24, s60", "v_log_f16_e32 v24, v18"): + translate_f16(program(line)) + # A finite source is enough even when the result is not finite: log2(0) is -infinity and a negative source is + # the canonical NaN; the canonical NaN can be read but does not stay a proven source. + for token in ("0x0001", "0", "0x8000", "-1.0", "0x7bff", "0xfbff"): + translate_f16(program(f"v_log_f16_e64 v24, {token}")) + translate_f16(program("v_mov_b32_e32 v20, v18", "v_log_f16 v24, v20")) + translate_f16(program("s_mov_b32 s61, s60", "v_log_f16_e64 v24, s61")) + translate_f16(program("v_log_f16 v24, 0x3c01", "v_log_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " + "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) + expect_value_error(translate_f16, program("v_log_f16 v24, 0", "v_log_f16 v25, v24"), + "binary16 operand is not finite: v24") + expect_value_error(translate_f16, program("v_log_f16 v24, -1.0", "v_log_f16 v25, v24"), + "binary16 operand is not finite: v24") + # Entry profile: unknown or an unsupported declaration refuses every spelling. + for suffix in ("", "_e32", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_log_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") + for state in ("flush", "ftz", "", False): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, + half_denorm=state), program("v_log_f16 v24, v18"), + "Invalid binary16 denormal entry state") + # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. + for line, token in (("v_log_f16_e64 v24, s44", "s44"), ("v_log_f16 v24, v30", "v30"), + ("v_log_f16_e64 v24, v12", "v12")): + refuse(line, f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", "v_log_f16 v24, v20"), + "binary16 operand lacks a finite proof: v20") + expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", "v_log_f16 v24, v25"), + "binary16 operand lacks a finite proof: v25") + # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_log_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_log_f16_e64 v24, {token}")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", "v_log_f16 v24, v20"), + "binary16 operand is not finite: v20") + # Source modifiers, integer inline constants, floats and other operands. + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") + refuse("v_log_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") + refuse("v_log_f16_e64 v256, 1.0", "Register out of range: v256") + refuse("v_log_f16_e64 v24, v256", "Register out of range: v256") + refuse("v_log_f16_e64 v24, s106", "Register out of range: s106") + # Unmodelled modifiers and neighbouring forms fall through to the generic refusal. + for line in ("v_log_f16_e64 v24, v18 clamp", "v_log_f16_e64 v24, v18 mul:2", + "v_log_f16_e64 v24, v18 div:2", "v_log_f16_e64 v24, v18 op_sel:[0,1]", + "v_log_f16_e32 v24, v18 clamp", + "v_log_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_log_f16 v24, v18, v19", "v_log_f16 v24", "v_sin_f16_e32 v24, v18", + "v_cos_f16_e64 v24, v18"): + refuse(line, "Unsupported instruction") + + # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. + def float_f16(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, + half_denorm=pixel_aot.HALF_DENORM_PRESERVE) + + base = with_constants([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(float_f16, base[:load + 1] + ["v_log_f16_e64 v24, s44"] + base[load + 1:], + "Constant read before load completion") + expect_value_error(float_f16, base[:sample + 1] + ["v_log_f16_e64 v12, 1.0"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(float_f16, base[:sample + 1] + ["v_log_f16_e64 v24, v12"] + base[sample + 1:], + "Sample used before vmcnt wait") + float_f16(base[:sample + 1] + ["v_log_f16_e64 v20, 1.0"] + base[sample + 1:]) + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(float_f16, base[:masked] + ["v_log_f16_e64 v24, 1.0"] + base[masked:], + "Invalid binary16 unary operation") + # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. + for spelling in ("v_log_f16", "v_log_f16_e32", "v_log_f16_e64"): + line = f"{spelling} v24, v18" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + # Readers. The audited ones read a unary result; every other reader of the tag refuses it. + produced = [*prefix, "v_log_f16_e32 v24, v18"] + for line in ("v_cvt_f32_f16_e32 v12, v24", "v_cvt_f32_f16_e64 v12, v24", + "v_cvt_f32_f16_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v24 {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + ("v_mov_b32_e32 v12, v24", "Expected a numeric register"), + ("v_add_nc_u16 v12, v24, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) + + # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer # reader: a runtime i16 source needs no proof (every i16 is finite) but its result carries no known value; a u16 source must @@ -18834,7 +19154,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", - "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -19197,7 +19517,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", - "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -20102,9 +20422,9 @@ def _check_controls_inline(directory): for expected in ("= ceil(alu", "= round(alu", "= round(params[1].x);", "= ceil((-params[1].y));"): assert expected in source, expected # Neighbouring forms: other widths, output modifiers, a second source and the IEEE-flag reciprocal. - for old, new in (("v_ceil_f32_e32 v12, v18", "v_log_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_sin_f16_e32 v12, v18"), ("v_ceil_f32_e32 v12, v18", "v_ceil_f64_e32 v[12:13], v[18:19]"), - ("v_rndne_f32_e32 v13, v19", "v_log_f16_e32 v13, v19"), + ("v_rndne_f32_e32 v13, v19", "v_cos_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), ("v_rndne_f32_e64 v14, s45", "v_rndne_f32_e64 v14, s45 mul:2"), ("v_ceil_f32_e64 v15, -s46", "v_ceil_f32_e64 v15, -s46 div:2"), @@ -21363,6 +21683,7 @@ def _check_controls_inline(directory): "check_f16_round_controls", "check_f16_rcp_sqrt_controls", "check_f16_rsq_exp_controls", + "check_f16_log_trig_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -21373,6 +21694,7 @@ def _check_controls_inline(directory): "check_f16_round_controls", "check_f16_rcp_sqrt_controls", "check_f16_rsq_exp_controls", + "check_f16_log_trig_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -28526,6 +28848,48 @@ def case(kind, index, tag): "binary16 operand lacks a finite proof: s44") +def check_f16_log_trig_draw(directory, compiler, renderer, backend): + """v_log_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. + + Three baked programs run 24 sources in a rotation of e32, e64, SGPR and literal forms and pack two results per + word; one chain program computes log2(log2(x)) for eight values above 1. The values cover exact powers, inexact + results, both signed zeros, subnormals, the largest finite half, negative sources and three midpoint-table rows. + Three deviations must each mismatch (one batch per mutation; the statuses are printed): a source read from bits + 31:16, the midpoint corrections dropped, and log2 replaced by the natural log. A source nothing proves is + refused at translation. + + Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's + high half is not measured here; the source-high mutation is the high-half control for the sources. + """ + check_f16_log_trig_mutation_coverage() + source = directory / "f16_log_trig.hlsl" + shader = directory / "f16_log_trig.cso" + constants = bytes(256) + + def build(text): + source.write_text(text, encoding="ascii") + compile_shader(compiler, source, shader) + + def case(kind, index, tag): + path = directory / f"f16_log_trig-{tag}-{kind}-{index}.case" + write_case(path, constants, tuple(as_float(word) for word in f16_log_trig_expected(kind, index)), integer_rt=True) + return path + + programs = {key: f16_log_trig_program(*key) for key in F16_LOG_TRIG_PROGRAMS} + for key in F16_LOG_TRIG_PROGRAMS: + build(translate_f16(programs[key])) + run_pixel_batch(renderer, backend, shader, [(case(*key, "ref"), "pass")]) + for mutation in F16_LOG_TRIG_MUTATIONS: + key = f16_log_trig_detecting_program(mutation) + build(f16_log_trig_mutated(mutation, programs[key])) + statuses, _ = run_pixel_batch_statuses(renderer, backend, shader, [case(*key, "mut")]) + print(f"f16_log_trig mutation {mutation}: program {key} statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"Mutating {mutation} escaped detection") + expect_value_error(translate_f16, uncompressed_export(["v_log_f16_e64 v24, s44"]), + "binary16 operand lacks a finite proof: s44") + + def check_f16_fmac_ldexp_draw(directory, compiler, renderer, backend): """v_fmac_f16 and v_ldexp_f16 against the independent Python reference: 24 baked fused multiply-accumulate rows (cancellation, rows where rounding the product first gives another result, signed zero results, ties into the @@ -28787,7 +29151,7 @@ def main(): "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-cmpx-e64", "draw-cmpx-sdwa", "draw-scc-skip", "draw-s-call", "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", - "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", + "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "draw-f16-log-trig", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, @@ -28826,6 +29190,7 @@ def main(): "draw-f16-round": check_f16_round_draw, "draw-f16-rcp-sqrt": check_f16_rcp_sqrt_draw, "draw-f16-rsq-exp": check_f16_rsq_exp_draw, + "draw-f16-log-trig": check_f16_log_trig_draw, "draw-f16-fmac-ldexp": check_f16_fmac_ldexp_draw, "draw-f16-cvt-int16": check_f16_cvt_int16_draw, "draw-f16-to-int16": check_f16_to_int16_draw, diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 479fa95654..a4d9048036 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6282,7 +6282,7 @@ def test_low16_binary16_e32_scanner_support(self): f"v_{op}_f16_e32 v24, 0x3c00, v19", f"v_{op}_f16_e32 v24, 0, v19"] for op in ("floor", "ceil", "trunc", "rndne"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] - for op in ("rcp", "sqrt", "rsq", "exp"): + for op in ("rcp", "sqrt", "rsq", "exp", "log"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] for kind in ("i16", "u16"): supported += [f"v_cvt_f16_{kind}_e32 v24, v18", f"v_cvt_f16_{kind}_e32 v24, s45", @@ -6314,6 +6314,8 @@ def test_low16_binary16_e32_scanner_support(self): "v_sqrt_f16_e32 v24, v18 clamp", "v_rsq_f16_e32 v24, -v18", "v_exp_f16_e32 v24, v18 clamp", + "v_log_f16_e32 v24, -v18", + "v_log_f16_e32 v24, v18 clamp", "v_fract_f16_e32 v24, v18", "v_cvt_f16_i16_e32 v24, 65", "v_cvt_f16_u16_e32 v24, 0x10000", @@ -6324,7 +6326,7 @@ def test_low16_binary16_e32_scanner_support(self): for line in refused: self.assertFalse(is_instruction_supported(line), line) for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_rcp_f16", "v_sqrt_f16", - "v_rsq_f16", "v_exp_f16", + "v_rsq_f16", "v_exp_f16", "v_log_f16", "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): self.assertIn(opcode, KNOWN_RDNA2_BASE_OPCODES) @@ -6353,7 +6355,7 @@ def translator_accepts(line): for op in ("floor", "ceil", "trunc", "rndne"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] - for op in ("rcp", "sqrt", "rsq", "exp"): + for op in ("rcp", "sqrt", "rsq", "exp", "log"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] refused = [ @@ -6364,7 +6366,7 @@ def translator_accepts(line): "v_add_f16_e64 v24, 3, v19", "v_add_f16_e64 v24, v18, 3", "v_add_f16_e64 v24, 3.0, v19", "v_add_f16_e64 v24, 0x10000, v19", "v_add_f16_e64 v24, v256, v19", "v_add_f16_e64 v256, v18, v19", "v_add_f16_e64 v24, s106, v19", "v_add_f16_e64 v24, v18", "v_add_f16_e64 v24, v18, v19, v19", - "v_fma_f16_e64 v24, v18, v19, v19", "v_log_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", + "v_fma_f16_e64 v24, v18, v19, v19", "v_mul_f16_e64 v24, v18, v19 clamp", "v_floor_f16_e64 v24, -v18", "v_floor_f16_e64 v24, |v18|", "v_floor_f16_e64 v24, v18 clamp", "v_floor_f16_e64 v24, v18 mul:2", "v_floor_f16_e64 v24, 3", "v_floor_f16_e64 v24, 0x10000", "v_floor_f16_e64 v24, v256", "v_floor_f16_e64 v24, v18, v19", "v_rndne_f16_e64 v24", @@ -6372,6 +6374,8 @@ def translator_accepts(line): "v_sqrt_f16_e64 v24, v18 mul:2", "v_rcp_f16_e64 v24, 3", "v_sqrt_f16_e64 v24, 0x10000", "v_rsq_f16_e64 v24, -v18", "v_exp_f16_e64 v24, |v18|", "v_rsq_f16_e64 v24, v18 clamp", "v_exp_f16_e64 v24, v18 mul:2", "v_rsq_f16_e64 v24, 3", "v_exp_f16_e64 v24, 0x10000", + "v_log_f16_e64 v24, -v18", "v_log_f16_e64 v24, |v18|", "v_log_f16_e64 v24, v18 clamp", + "v_log_f16_e64 v24, v18 mul:2", "v_log_f16_e64 v24, 3", "v_log_f16_e64 v24, 0x10000", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 30def60a3d..525e3d3e7b 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1143,6 +1143,37 @@ def check_vopc_e32_dst(enc, dst): " return rounded;\n" "}" ), + # The RDNA 2 special results of v_log_f16 from the source half bits, as the direct compute path selects them + # after packed_half_rne. The 73 corrections are the positive finite sources whose exact log2 lies within the + # D3D Log error window of a binary16 rounding midpoint. + "f16_log_result": ( + "uint f16_log_result(uint source, uint rounded) {\n" + " if (source == 0x144u) return 0xcbd4u; if (source == 0x288u) return 0xcb54u; if (source == 0x509u) return 0xcad5u; if (source == 0x510u) return 0xcad4u;\n" + " if (source == 0x6a3u) return 0xcaa2u; if (source == 0x909u) return 0xca55u; if (source == 0xaa3u) return 0xca22u; if (source == 0xd09u) return 0xc9d5u;\n" + " if (source == 0xea3u) return 0xc9a2u; if (source == 0x12a3u) return 0xc922u; if (source == 0x16a3u) return 0xc8a2u; if (source == 0x1aa3u) return 0xc822u;\n" + " if (source == 0x1c29u) return 0xc7f2u; if (source == 0x1c80u) return 0xc7d4u; if (source == 0x1cb3u) return 0xc7c5u; if (source == 0x2029u) return 0xc6f2u;\n" + " if (source == 0x2080u) return 0xc6d4u; if (source == 0x20b3u) return 0xc6c5u; if (source == 0x24b3u) return 0xc5c5u; if (source == 0x28b3u) return 0xc4c5u;\n" + " if (source == 0x2c79u) return 0xc3aeu; if (source == 0x2e00u) return 0xc2d4u; if (source == 0x3079u) return 0xc1aeu; if (source == 0x3489u) return 0xbf47u;\n" + " if (source == 0x34ffu) return 0xbeb8u; if (source == 0x3548u) return 0xbe65u; if (source == 0x3ab1u) return 0xb420u; if (source == 0x3abdu) return 0xb3ecu;\n" + " if (source == 0x3ae8u) return 0xb2cau; if (source == 0x3b13u) return 0xb1adu; if (source == 0x3b80u) return 0xadf6u; if (source == 0x3ba3u) return 0xac4au;\n" + " if (source == 0x3bcbu) return 0xa8d8u; if (source == 0x3bedu) return 0xa2e3u; if (source == 0x3bfau) return 0x9c56u; if (source == 0x3bfeu) return 0x95c6u;\n" + " if (source == 0x3bffu) return 0x91c6u; if (source == 0x3c00u) return 0x0u; if (source == 0x3c01u) return 0x15c5u; if (source == 0x3c04u) return 0x1dc2u;\n" + " if (source == 0x3c0bu) return 0x23e4u; if (source == 0x3c28u) return 0x2b13u; if (source == 0x3c3eu) return 0x2d6eu; if (source == 0x3c8cu) return 0x31eau;\n" + " if (source == 0x3e80u) return 0x399bu; if (source == 0x4089u) return 0x3cb9u; if (source == 0x40ffu) return 0x3d48u; if (source == 0x4148u) return 0x3d9bu;\n" + " if (source == 0x4479u) return 0x4052u; if (source == 0x4879u) return 0x4252u; if (source == 0x4a00u) return 0x432cu; if (source == 0x4cb3u) return 0x443bu;\n" + " if (source == 0x50b3u) return 0x453bu; if (source == 0x54b3u) return 0x463bu; if (source == 0x5829u) return 0x470eu; if (source == 0x5880u) return 0x472cu;\n" + " if (source == 0x58b3u) return 0x473bu; if (source == 0x5ea3u) return 0x485eu; if (source == 0x62a3u) return 0x48deu; if (source == 0x66a3u) return 0x495eu;\n" + " if (source == 0x6909u) return 0x49abu; if (source == 0x6aa3u) return 0x49deu; if (source == 0x6d09u) return 0x4a2bu; if (source == 0x6ea3u) return 0x4a5eu;\n" + " if (source == 0x7109u) return 0x4aabu; if (source == 0x7110u) return 0x4aacu; if (source == 0x72a3u) return 0x4adeu; if (source == 0x7509u) return 0x4b2bu;\n" + " if (source == 0x7510u) return 0x4b2cu; if (source == 0x76a3u) return 0x4b5eu; if (source == 0x7909u) return 0x4babu; if (source == 0x7910u) return 0x4bacu;\n" + " if (source == 0x7aa3u) return 0x4bdeu;\n" + " if ((source & 0x7fffu) == 0u) return 0xfc00u;\n" + " if (source == 0x7c00u) return 0x7c00u;\n" + " if ((source & 0x7fffu) > 0x7c00u) return 0x7e00u;\n" + " if (source > 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), "frexp_mant_f16": ( "uint frexp_mant_f16(uint bits) {\n" " uint h = bits & 0xffffu;\n" @@ -2166,7 +2197,8 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi # uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16, sqrt(S0.f16), 1.0 / sqrt(S0.f16) and 2^S0.f16. The # rsqrt and exp2 approximations have a measured error window, so the lowered shader also applies the special-result # and midpoint corrections of src/gfx1013_direct_compute.inl to the narrowed half. -VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})", "rsq": "rsqrt({0})", "exp": "exp2({0})"} +VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})", "rsq": "rsqrt({0})", "exp": "exp2({0})", + "log": "log2({0})"} # The 70 finite binary16 sources whose exact 2^S0 lies within the D3D exp2 error window of a binary16 rounding # midpoint, with the RDNA 2 result. This is the exp_f16_midpoints table of src/gfx1013_direct_compute.inl; @@ -2192,6 +2224,31 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi 0xc641: 0x22b5, 0xc741: 0x1eb5, } +# The 73 positive finite binary16 sources whose exact log2 lies within the D3D Log error window of a binary16 +# rounding midpoint, with the RDNA 2 result. This is the log_f16_midpoints table of src/gfx1013_direct_compute.inl; +# tests/f16_log_midpoints.py regenerates the C++ array, and check_f16_log_trig_reference pins this copy to it. +LOG_F16_MIDPOINTS = { + 0x144: 0xcbd4, 0x288: 0xcb54, 0x509: 0xcad5, 0x510: 0xcad4, + 0x6a3: 0xcaa2, 0x909: 0xca55, 0xaa3: 0xca22, 0xd09: 0xc9d5, + 0xea3: 0xc9a2, 0x12a3: 0xc922, 0x16a3: 0xc8a2, 0x1aa3: 0xc822, + 0x1c29: 0xc7f2, 0x1c80: 0xc7d4, 0x1cb3: 0xc7c5, 0x2029: 0xc6f2, + 0x2080: 0xc6d4, 0x20b3: 0xc6c5, 0x24b3: 0xc5c5, 0x28b3: 0xc4c5, + 0x2c79: 0xc3ae, 0x2e00: 0xc2d4, 0x3079: 0xc1ae, 0x3489: 0xbf47, + 0x34ff: 0xbeb8, 0x3548: 0xbe65, 0x3ab1: 0xb420, 0x3abd: 0xb3ec, + 0x3ae8: 0xb2ca, 0x3b13: 0xb1ad, 0x3b80: 0xadf6, 0x3ba3: 0xac4a, + 0x3bcb: 0xa8d8, 0x3bed: 0xa2e3, 0x3bfa: 0x9c56, 0x3bfe: 0x95c6, + 0x3bff: 0x91c6, 0x3c00: 0x0, 0x3c01: 0x15c5, 0x3c04: 0x1dc2, + 0x3c0b: 0x23e4, 0x3c28: 0x2b13, 0x3c3e: 0x2d6e, 0x3c8c: 0x31ea, + 0x3e80: 0x399b, 0x4089: 0x3cb9, 0x40ff: 0x3d48, 0x4148: 0x3d9b, + 0x4479: 0x4052, 0x4879: 0x4252, 0x4a00: 0x432c, 0x4cb3: 0x443b, + 0x50b3: 0x453b, 0x54b3: 0x463b, 0x5829: 0x470e, 0x5880: 0x472c, + 0x58b3: 0x473b, 0x5ea3: 0x485e, 0x62a3: 0x48de, 0x66a3: 0x495e, + 0x6909: 0x49ab, 0x6aa3: 0x49de, 0x6d09: 0x4a2b, 0x6ea3: 0x4a5e, + 0x7109: 0x4aab, 0x7110: 0x4aac, 0x72a3: 0x4ade, 0x7509: 0x4b2b, + 0x7510: 0x4b2c, 0x76a3: 0x4b5e, 0x7909: 0x4bab, 0x7910: 0x4bac, + 0x7aa3: 0x4bde, +} + def _f16_fraction(bits): """The exact value of a finite binary16 encoding.""" @@ -2389,6 +2446,45 @@ def f16_rsq_exp_result(name, bits): return _f16_exp2_result(value) +def _f16_log2_result(value): + """Binary16 encoding nearest to log2(value) for a positive finite Fraction. + + No binary16 log2 is exactly a rounding midpoint (tests/f16_log_midpoints.py asserts it), so a 90-digit Decimal + reference decides every encoding; the midpoint exceptions are applied by f16_log_trig_result before this call. + """ + with localcontext() as context: + context.prec = 90 + operand = Decimal(value.numerator) / Decimal(value.denominator) + logarithm = operand.ln() / Decimal(2).ln() + return _fraction_to_f16(Fraction(logarithm)) + + +def f16_log_trig_result(name, bits): + """Binary16 result bits of v_log_f16 on any binary16 encoding. + + The direct compute lowering widens the low half with widen16, calls unary.f32 opcode 23 (log2), narrows with + packed_half_rne and then applies the RDNA 2 special results and the 73 midpoint corrections from the source half: + +infinity stays +infinity, every NaN and every negative nonzero source becomes 0x7e00, and either zero becomes + 0xfc00. The exact log2 of every other positive finite source is rounded to binary16; the midpoint table pins the + sources whose exact result lies inside the D3D Log error window of a rounding midpoint. Every source encoding has + a modelled result, so None is never returned today. Used at translation time so that a chained result stays a + proven value. + """ + assert name == "log" + bits &= 0xffff + magnitude = bits & 0x7fff + if magnitude == 0: + return 0xfc00 + if bits == 0x7c00: + return 0x7c00 + if magnitude >= 0x7c00 or bits & 0x8000: + return 0x7e00 + entry = LOG_F16_MIDPOINTS.get(bits) + if entry is not None: + return entry + return _f16_log2_result(_f16_fraction(bits)) + + def f16_round_result(name, bits): """Exact binary16 result bits of one VOP1_F16_ROUND op on a finite operand. @@ -8080,10 +8176,11 @@ def known_sample_float(reg): vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result elif m := match(rf"v_({'|'.join(VOP1_F16_UNARY)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): - # Plain binary16 VOP1 reciprocal, square root, reciprocal square root and exponent under the rules of the - # VOP2 arithmetic above: a statically proven finite source, the declared entry profile, no modifier, clamp - # or omod. These match the direct compute lowering: widen16, one binary32 division, sqrt, rsqrt or exp2, - # then narrow16. rsq and exp additionally select the RDNA 2 special results from the source half bits. + # Plain binary16 VOP1 reciprocal, square root, reciprocal square root, exponent and logarithm under the + # rules of the VOP2 arithmetic above: a statically proven finite source, the declared entry profile, no + # modifier, clamp or omod. These match the direct compute lowering: widen16, one binary32 division, sqrt, + # rsqrt, exp2 or log2, then narrow16. rsq, exp and log additionally select the RDNA 2 special results and + # midpoint corrections from the source half bits. # The result is ("half16", alu). name, encoding, dst, token = m.groups() if mask != "entry": @@ -8095,14 +8192,21 @@ def known_sample_float(reg): if dst in sample_dest: raise ValueError("Write overlaps an outstanding sample") word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) - result = (f16_rcp_sqrt_result(name, proven) if name in ("rcp", "sqrt") - else f16_rsq_exp_result(name, proven)) + if name in ("rcp", "sqrt"): + result = f16_rcp_sqrt_result(name, proven) + elif name in ("rsq", "exp"): + result = f16_rsq_exp_result(name, proven) + else: + result = f16_log_trig_result(name, proven) lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") lines.append(f" precise float hs{i} = {VOP1_F16_UNARY[name].format(f'widen16(hf{i}_0)')};") if name in ("rsq", "exp"): helper = "f16_rsq_result" if name == "rsq" else "f16_exp2_result" helpers.add(helper) lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, narrow16(hs{i})));") + elif name == "log": + helpers.add("f16_log_result") + lines.append(f" precise float alu{i} = asfloat(f16_log_result(hf{i}_0, narrow16(hs{i})));") else: lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 02a562c0e0..f8dec1ada7 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -470,10 +470,10 @@ def lower_rejection_causes(results: list[dict]) -> dict: PIXEL_VOP2_F16 + PIXEL_VOP2_F16_FUSED_SCALE + PIXEL_VOP1_F16_ROUND + PIXEL_VOP1_F16_UNARY} | {"v_cvt_f16_i16", "v_cvt_f16_u16"} | { - # Decoding only: no translator lowers these binary16 VOP1/VOP2 forms. + # Decoding only: the tables above cover the binary16 VOP1/VOP2 forms a translator lowers. "v_cvt_u16_f16", "v_cvt_i16_f16", "v_fract_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_log_f16", "v_sin_f16", "v_cos_f16", + "v_sin_f16", "v_cos_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_fmac_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", "v_pk_fmac_f16", } From e3a3c6e90e2871c0b8ab35f5b7994bb727ab8d53 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 06:56:58 +0000 Subject: [PATCH 3/5] shader: lower binary16 VOP1 sine and cosine --- docs/experiments.md | 4 +- tests/form_coverage_check.py | 17 +- tests/pixel_aot_check.py | 379 +++++++++++++++++++----------- tests/rdna2_tools_check.py | 14 +- tools/pixel_aot.py | 111 +++++++-- tools/scan_unsupported_shaders.py | 1 - 6 files changed, 353 insertions(+), 173 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index d76ee19772..19a8353387 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9005,9 +9005,9 @@ The controls (`check_f16_rcp_sqrt_controls`, no GPU) cover the bare, `_e32` and Plain binary16 `VOP1` reciprocal square root and exponent (issue #839), `v_rsq_f16` and `v_exp_f16`, extend the unary entry above: the unsuffixed, `_e32` and `_e64` spellings widen the low half with `widen16`, evaluate the direct compute path's `rsqrt` or `exp2` in binary32, narrow with `narrow16`, and then select RDNA 2's special results from the source half. `v_rsq_f16` maps any source above `+infinity` (every negative finite encoding) to the canonical quiet NaN `0x7e00`, `+infinity` to zero and a zero magnitude to `source | 0x7c00`, so `-0` gives `-infinity`; `v_exp_f16` applies the 70 midpoint corrections of `exp_f16_midpoints` from `src/gfx1013_direct_compute.inl`, maps `2^-25` (`0xce40`) to zero and a magnitude above `+infinity` to `0x7e00`. The emitted helpers are `f16_rsq_result` and `f16_exp2_result`, and `tools/pixel_aot.py` carries the same table as `EXP_F16_MIDPOINTS`. The translator tracks each result with `f16_rsq_exp_result`: a positive finite reciprocal square root is rounded exactly to binary16 with a 90-digit reference, a negative one is the canonical NaN above, and `exp` rounds the exact `2^S0` after the table corrections. Every finite source therefore has a modelled result and the function does not return None; its signature keeps the None contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the reciprocal and square root entry; the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused, and `v_sin_f16` and `v_cos_f16` remain unlowered. -The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining sin and cos forms, and whether any title executes these paths. +The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining sine and cosine forms, and whether any title executes these paths. -Plain binary16 `VOP1` logarithm (issue #839) `v_log_f16`, in the unsuffixed, `_e32` and `_e64` spellings, extends the unary entry above: the low half is widened exactly with `widen16`, the direct compute path's `log2` (`unary.f32` opcode 23) is evaluated in binary32, `narrow16` rounds once, and then the RDNA 2 special results and midpoint corrections are selected from the source half. `+infinity` stays `+infinity`, every NaN and every negative nonzero source becomes the canonical quiet NaN `0x7e00`, and either zero becomes `-infinity` (`0xfc00`). The emitter carries the 73 sources whose exact log2 lies within the D3D Log error window of a binary16 rounding midpoint; `tests/f16_log_midpoints.py` regenerates and checks the C++ `log_f16_midpoints` array, and `tools/pixel_aot.py` carries the same table as `LOG_F16_MIDPOINTS`. The translator tracks each result with `f16_log_trig_result`, which returns the table entry or rounds the exact log2 of every other positive finite source with a 90-digit Decimal reference. Every encoding has a modelled result, so None is never returned today; the signature keeps that contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the unary forms above, and the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused. The controls (`check_f16_log_trig_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, pin `LOG_F16_MIDPOINTS` to the C++ array through `tests/f16_log_midpoints.py check_cpp_table`, and compare the reference with `f16_log_trig_result` on all 65,536 encodings. The draw (`tests/pixel_aot_check.py draw-f16-log-trig`, tests `pixel_aot_f16_log_trig_hardware` and `pixel_aot_f16_log_trig_warp`, 60 s limit, capability skip 77) runs three baked programs over 24 values in a rotation of e32, e64, SGPR and literal forms, packs two results per word with SDWA `WORD_0` and `WORD_1`, and adds one chain that computes `log2(log2(x))` for eight values above 1; the values cover exact powers, inexact results, both signed zeros, subnormals, the largest finite half, negative sources, the `log2(1)` row and three midpoint-table rows. The lossless `R32G32B32A32_UINT` readback is compared with `f16_log_trig_reference`, a 90-digit reference without `pixel_aot`. Three deviations must each mismatch, one batch per mutation with the statuses printed (a source read from bits 31:16, the `1 + ulp` midpoint correction off by one encoding, and `log2` replaced by the natural log), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_log_trig_forms` pins the two newly covered forms (log e32 and e64) and leaves the DPP, SDWA, sin and cos neighbours uncovered; the two forms take the measured totals from 1550/1968 and 1541/1863 to 1552/1968 and 1543/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D Log error window beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining sin and cos forms, and whether any title executes these paths. +Plain binary16 `VOP1` logarithm, sine and cosine (issue #839) `v_log_f16`, `v_sin_f16` and `v_cos_f16`, in the unsuffixed, `_e32` and `_e64` spellings, extend the unary entry above. The low half is widened exactly with `widen16`; `v_log_f16` evaluates the direct compute path's `log2` (`unary.f32` opcode 23), while `v_sin_f16` and `v_cos_f16` use the same turn reduction as `trig_turns` (subtract `Round_ne` in binary32, keep a zero angle's sign, select the exact zero at half a turn for sin and a quarter turn for cos, then multiply by the binary32 2*pi constant and evaluate the intrinsic). `narrow16` rounds once, then the RDNA 2 special results are selected from the source half: log keeps `+infinity`, maps every NaN and negative nonzero source to `0x7e00` and either zero to `-infinity` (`0xfc00`); sin and cos map an infinity or NaN magnitude to `0x7e00`, and sin preserves `-0`. The emitter carries the 73 log midpoint corrections of `log_f16_midpoints` (regenerated and checked by `tests/f16_log_midpoints.py`) as `LOG_F16_MIDPOINTS`, and the helpers `f16_log_result`, `f16_sin_result` and `f16_cos_result`. The translator tracks each result with `f16_log_trig_result`: log returns the table entry or rounds the exact log2 of every other positive finite source with a 90-digit Decimal reference, and sin/cos reproduce the turn reduction and host intrinsic in binary32. Every encoding has a modelled result, so None is never returned today; the signature keeps that contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the unary forms above, and the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused. The controls (`check_f16_log_trig_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, pin `LOG_F16_MIDPOINTS` to the C++ array through `tests/f16_log_midpoints.py check_cpp_table`, and compare the reference with `f16_log_trig_result` on all 65,536 encodings of all three ops. The draw (`tests/pixel_aot_check.py draw-f16-log-trig`, tests `pixel_aot_f16_log_trig_hardware` and `pixel_aot_f16_log_trig_warp`, 60 s limit, capability skip 77) runs nine baked programs, three per op, over 24 values each in a rotation of e32, e64, SGPR and literal forms, packs two results per word with SDWA `WORD_0` and `WORD_1`, and adds two chains (`log2(log2(x))` and `cos(sin(x))`). The values cover exact powers and whole turns, inexact results, both signed zeros, subnormals, the largest finite half, negative sources, the `log2(1)` row, the exact zero turns of sin and cos, and three log midpoint-table rows; the inexact sin and cos values keep the binary32 result at least 5e-5 from a binary16 rounding midpoint, except the exact selected zeros. The lossless `R32G32B32A32_UINT` readback is compared with `f16_log_trig_reference`, a 90-digit or host-intrinsic reference without `pixel_aot`. Five deviations must each mismatch, one batch per mutation with the statuses printed: the mnemonic cycled, a source read from bits 31:16, the `1 + ulp` midpoint correction off by one encoding, `log2` replaced by the natural log, and the exact zero selections dropped. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_log_trig_forms` pins the six newly covered forms (log, sin and cos, each e32 and e64) and leaves the DPP and SDWA neighbours uncovered; the six forms take the measured totals from 1550/1968 and 1541/1863 to 1556/1968 and 1547/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D Log error window beyond the modelled midpoint corrections and the exact reference, the D3D Sin/Cos error beyond the chosen midpoint margin, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, and whether any title executes these paths. Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index edca5bb0b2..3c97b1fe45 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -759,23 +759,22 @@ def check_f16_rsq_exp_forms(): def check_f16_log_trig_forms(): - """The two plain binary16 VOP1 logarithm forms (e32 and e64 spellings of log) count as covered once the - translator accepts their fixtures; the DPP and SDWA spellings stay uncovered, and sin and cos have their own - fixture.""" + """The six plain binary16 VOP1 logarithm, sine and cosine forms (e32 and e64 spellings of log, sin and cos) + count as covered once the translator accepts their fixtures; the DPP and SDWA spellings stay uncovered.""" import pixel_aot_check as pixel saved = set(pixel.ACCEPTED) pixel.ACCEPTED.clear() try: for key in pixel.F16_LOG_TRIG_PROGRAMS: pixel.translate_f16(pixel.f16_log_trig_program(*key)) - ops = ("log",) + ops = ("log", "sin", "cos") forms = {("VOP1", f"v_{op}_f16") for op in ops} | {("VOP3", f"v_{op}_f16_e64") for op in ops} - assert len(forms) == 2 + assert len(forms) == 6 neighbours = { - ("VOP1", "v_sin_f16"), ("VOP3", "v_sin_f16_e64"), - ("VOP1", "v_cos_f16"), ("VOP3", "v_cos_f16_e64"), ("DPP16", "v_log_f16_dpp"), ("DPP8", "v_log_f16_dpp"), - ("SDWA", "v_log_f16_sdwa"), + ("DPP16", "v_sin_f16_dpp"), ("DPP8", "v_sin_f16_dpp"), + ("DPP16", "v_cos_f16_dpp"), ("DPP8", "v_cos_f16_dpp"), + ("SDWA", "v_log_f16_sdwa"), ("SDWA", "v_sin_f16_sdwa"), ("SDWA", "v_cos_f16_sdwa"), } for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) @@ -784,7 +783,7 @@ def check_f16_log_trig_forms(): covered = fc.gfx_forms(pixel.ACCEPTED, reference) assert forms <= covered, (name, sorted(forms - covered)) assert not neighbours & covered, (name, sorted(neighbours & covered)) - # Without the log fixtures neither form is covered, not even through the other unary ones. + # Without the fixtures none of the six forms is covered, not even through the other unary ones. pixel.ACCEPTED.clear() for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): pixel.translate_f16(pixel.uncompressed_export(body)) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index f3bddc6c56..779d065c70 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -7825,7 +7825,7 @@ def refuse(line, message): for line in ("v_add_nc_u16 v24, v18, v19 op_sel:[0,0,1]", "v_add_nc_u16 v24, v18, v19 clamp", "v_add_nc_u16_dpp v24, v18, v19 quad_perm:[0,1,2,3]", "v_add_nc_u16_sdwa v24, v18, v19 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_sin_f16_e64 v24, v18"): + "v_cvt_f16_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") refuse("v_add_nc_u16 v24, v18, -v19", "Unsupported 16-bit integer operand") refuse("v_add_nc_u16 v24, v18, 1.0", "Unsupported 16-bit integer operand") @@ -16907,8 +16907,8 @@ def refuse(line, message, translator=translate_f16): for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_sin_f16_e64 v24, v18", - "v_cos_f16_e32 v24, v18"): + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_cvt_f16_f16_e64 v24, v18", + "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -17737,7 +17737,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", - "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18"): + "v_cvt_f16_f16_e32 v24, v18", "v_cvt_f16_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18060,7 +18060,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_sqrt_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", - "v_sin_f16_e32 v24, v18"): + "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18428,8 +18428,8 @@ def refuse(line, message, translator=translate_f16): "v_exp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_exp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_sin_f16_e32 v24, v18", - "v_cos_f16_e64 v24, v18"): + "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_cvt_f16_f16_e32 v24, v18", + "v_cvt_f16_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18476,7 +18476,7 @@ def float_f16(instructions): # source half (+infinity stays +infinity, NaN and negative nonzero become 0x7e00, either zero becomes 0xfc00). # The reference evaluates the exact log2 with a 90-digit Decimal and uses the generated midpoint table, so it shares # no rounding formula with pixel_aot. -F16_LOG_TRIG_OPS = ("log",) +F16_LOG_TRIG_OPS = ("log", "sin", "cos") F16_LOG_TRIG_VALUES = { "log": ( 0x0000, 0x8000, 0x0001, 0x03ff, 0x0400, 0x3c00, # zeros, subnormals, min normal, 1 @@ -18484,10 +18484,26 @@ def float_f16(instructions): 0x4800, 0x6400, 0x7bff, 0xfbff, 0xbc00, 0x8001, # 8, 1024, +-max, -1, -min subnormal 0x4200, 0x4900, 0x2e66, 0x0144, 0x7aa3, 0x4089, # 3, 10, 0.1, three midpoint rows ), + "sin": ( + 0x0000, 0x8000, 0x3c00, 0x4000, 0x6800, 0x7bff, # +0, -0, whole turns (including 2048 and 65504) + 0x3800, 0xb800, 0x3400, 0xb400, 0x3a00, 0xba00, # +-0.5 (exact zero), +-0.25 (+-1), +-0.75 (-+1) + 0x3e00, 0xbf00, 0x3000, 0x5555, 0x3bff, 0x2b22, # 1.5 (zero), -1.75 (+1), then inexact values + 0x32fb, 0x3600, 0x2f00, 0x3d80, 0x3aff, 0x3c7f, # inexact values with a wide margin to the half midpoint + ), + "cos": ( + 0x0000, 0x8000, 0x3c00, 0x4000, 0x6800, 0x7bff, # +0, -0, whole turns (including 2048 and 65504) + 0x3400, 0xb400, 0x3a00, 0xba00, 0xbf00, 0x3800, # +-0.25, 0.75, -1.75 (exact zero), 0.5 (-1) + 0x3e00, 0xb800, 0x2c00, 0x3000, 0x5555, 0x2e66, # -0.5 and 1.5 (-1), then inexact values + 0x3bff, 0x2b22, 0x32fb, 0x3600, 0x3b00, 0x2f00, # inexact values with a wide margin to the half midpoint + ), } # Chains: eight positive values above 1 whose log2 is finite and positive, so log2(log2(x)) is finite. -F16_LOG_TRIG_CHAINS = ((0x4000, 0x4400, 0x4800, 0x6400, 0x4200, 0x4900, 0x3c01, 0x7bff),) -F16_LOG_TRIG_MUTATIONS = ("src_high", "table_off", "natural_log") +F16_LOG_TRIG_CHAINS = ( + (0x4000, 0x4400, 0x4800, 0x6400, 0x4200, 0x4900, 0x3c01, 0x7bff), + (0x2c00, 0x3000, 0x5555, 0x3bff, 0x3400, 0x3800, 0xb800, 0x3a00), +) +F16_LOG_TRIG_CHAIN_OPS = (("log", "log"), ("sin", "cos")) +F16_LOG_TRIG_MUTATIONS = ("ops_swapped", "src_high", "table_off", "natural_log", "no_exact_zero") _F16_LOG_MIDPOINT_CACHE = None @@ -18501,17 +18517,43 @@ def f16_log_midpoints(): return _F16_LOG_MIDPOINT_CACHE -def f16_log_trig_reference(op, word, *, mutation=None): - """Binary16 result bits of v_log_f16 on the low half of word, from the semantics only. +_F16_TRIG_TWO_PI_F32 = struct.unpack( + 'd', bytes.fromhex('401921FB60000000'))[0]))[0] - Log2 uses a 90-digit reference and the same 73 midpoint corrections as the direct compute array. The special - results follow RDNA 2: +-0 gives -infinity, +infinity stays +infinity, and every NaN or negative nonzero source - gives the canonical quiet NaN 0x7e00. mutation models a deliberate deviation of the draw's mutated shaders: - src_high reads bits 31:16, table_off mis-corrects the 1 + ulp midpoint row by one encoding, and natural_log - computes ln instead of log2. + +def _f32_round(value): + """Round a Python float to binary32, as the direct compute path's fmul and intrinsic results do.""" + return struct.unpack('> 16 if mutation == "src_high" else word) & 0xffff + if op != "log": + if (half & 0x7fff) >= 0x7c00: + return 0x7e00 + if op == "sin" and half == 0x8000: + return 0x8000 + value = float(f16_grid_value(half)) + part = value if value == 0 else _f32_round(value - round(value)) + if abs(part) == (0.25 if op == "cos" else 0.5) and mutation != "no_exact_zero": + return 0 + radians = _f32_round(part * _F16_TRIG_TWO_PI_F32) + widened = _f32_round(math.cos(radians) if op == "cos" else math.sin(radians)) + result = f16_grid_nearest(Fraction(widened)) + assert result is not None + return result magnitude = half & 0x7fff if magnitude == 0: return 0xfc00 @@ -18535,36 +18577,37 @@ def f16_log_trig_reference(op, word, *, mutation=None): return result -def f16_log_trig_word(index, slot): - """The 32-bit source word of F16_LOG_TRIG_VALUES["log"][8 * index + slot], with junk in bits 31:16.""" +def f16_log_trig_word(op, index, slot): + """The 32-bit source word of F16_LOG_TRIG_VALUES[op][8 * index + slot], with junk in bits 31:16.""" value = 8 * index + slot - return (F16_ARITH_JUNK[value % 4] << 16) | F16_LOG_TRIG_VALUES["log"][value] + return (F16_ARITH_JUNK[value % 4] << 16) | F16_LOG_TRIG_VALUES[op][value] def f16_log_trig_program(kind, index): - """One draw program. Kinds: main (eight values, packed two results per word) and chain (log2(log2(x))).""" + """One draw program. Kinds: an op name (eight values, packed two results per word) and chain.""" pack = "v_mov_b32_sdwa v{dst}, v{src} dst_sel:{sel} dst_unused:{unused} src0_sel:WORD_0" body = [] - if kind == "main": + if kind != "chain": for slot in range(8): - word = f16_log_trig_word(index, slot) + word = f16_log_trig_word(kind, index, slot) body += [f"v_mov_b32_e32 v{18 + slot}, {word:#x}", f"s_mov_b32 s{60 + slot}, {word:#x}"] for slot in range(8): - half = F16_LOG_TRIG_VALUES["log"][8 * index + slot] + half = F16_LOG_TRIG_VALUES[kind][8 * index + slot] literal = f16_arith_token(half) form = (8 * index + slot) % 4 if form == 3 and literal is None: form = 0 body.append([ - f"v_log_f16_e32 v{26 + slot}, v{18 + slot}", - f"v_log_f16_e64 v{26 + slot}, v{18 + slot}", - f"v_log_f16_e64 v{26 + slot}, s{60 + slot}", - f"v_log_f16_e32 v{26 + slot}, {literal}", + f"v_{kind}_f16_e32 v{26 + slot}, v{18 + slot}", + f"v_{kind}_f16_e64 v{26 + slot}, v{18 + slot}", + f"v_{kind}_f16_e64 v{26 + slot}, s{60 + slot}", + f"v_{kind}_f16_e32 v{26 + slot}, {literal}", ][form]) for word in range(4): body.append(pack.format(dst=12 + word, src=26 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) body.append(pack.format(dst=12 + word, src=27 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) else: + first_op, second_op = F16_LOG_TRIG_CHAIN_OPS[index] for slot, half in enumerate(F16_LOG_TRIG_CHAINS[index]): word = (F16_ARITH_JUNK[slot % 4] << 16) | half body += [f"v_mov_b32_e32 v{18 + slot}, {word:#x}", f"s_mov_b32 s{60 + slot}, {word:#x}", @@ -18574,13 +18617,13 @@ def f16_log_trig_program(kind, index): if form == 3 and literal is None: form = 0 body.append([ - f"v_log_f16_e32 v{26 + slot}, v{18 + slot}", - f"v_log_f16_e64 v{26 + slot}, v{18 + slot}", - f"v_log_f16_e64 v{26 + slot}, s{60 + slot}", - f"v_log_f16_e32 v{26 + slot}, {literal}", + f"v_{first_op}_f16_e32 v{26 + slot}, v{18 + slot}", + f"v_{first_op}_f16_e64 v{26 + slot}, v{18 + slot}", + f"v_{first_op}_f16_e64 v{26 + slot}, s{60 + slot}", + f"v_{first_op}_f16_e32 v{26 + slot}, {literal}", ][form]) - body.append([f"v_log_f16_e32 v{34 + slot}, v{26 + slot}", - f"v_log_f16_e64 v{34 + slot}, v{26 + slot}"][slot % 2]) + body.append([f"v_{second_op}_f16_e32 v{34 + slot}, v{26 + slot}", + f"v_{second_op}_f16_e64 v{34 + slot}, v{26 + slot}"][slot % 2]) for word in range(4): body.append(pack.format(dst=12 + word, src=34 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) body.append(pack.format(dst=12 + word, src=35 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) @@ -18589,40 +18632,52 @@ def f16_log_trig_program(kind, index): def f16_log_trig_source_halves(kind, index): """The binary16 source encodings of one draw program.""" - if kind == "main": - return list(F16_LOG_TRIG_VALUES["log"][8 * index:8 * index + 8]) + if kind != "chain": + return list(F16_LOG_TRIG_VALUES[kind][8 * index:8 * index + 8]) return list(F16_LOG_TRIG_CHAINS[index]) def f16_log_trig_expected(kind, index, mutation=None): """The four exported words of f16_log_trig_program(kind, index).""" - if kind == "main": - results = [f16_log_trig_reference("log", f16_log_trig_word(index, slot), mutation=mutation) + if kind != "chain": + results = [f16_log_trig_reference(kind, f16_log_trig_word(kind, index, slot), mutation=mutation) for slot in range(8)] return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) assert mutation is None + first_op, second_op = F16_LOG_TRIG_CHAIN_OPS[index] results = [] for half in F16_LOG_TRIG_CHAINS[index]: - first = f16_log_trig_reference("log", half) - results.append(f16_log_trig_reference("log", first)) + first = f16_log_trig_reference(first_op, half) + results.append(f16_log_trig_reference(second_op, first)) return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) -F16_LOG_TRIG_PROGRAMS = (*(("main", i) for i in range(len(F16_LOG_TRIG_VALUES["log"]) // 8)), +F16_LOG_TRIG_PROGRAMS = (*( (op, i) for op in F16_LOG_TRIG_OPS + for i in range(len(F16_LOG_TRIG_VALUES[op]) // 8)), *(("chain", i) for i in range(len(F16_LOG_TRIG_CHAINS)))) def f16_log_trig_mutated(mutation, program): """The lowered source of program (instruction lines) with one deviation applied.""" + if mutation == "ops_swapped": + step = {"log": "sin", "sin": "cos", "cos": "log"} + swapped = [re.sub(r"v_(log|sin|cos)_f16", lambda m: f"v_{step[m.group(1)]}_f16", line) for line in program] + assert swapped != program, mutation + return translate_f16(swapped) text = translate_f16(program) if mutation == "src_high": mutated = re.sub(r"uint (hf\d+_0) = \((.+)\) & 0xffffu;", r"uint \1 = ((\2) >> 16u) & 0xffffu;", text) elif mutation == "table_off": mutated = text.replace("if (source == 0x3c01u) return 0x15c5u;", "if (source == 0x3c01u) return 0x15c4u;") - else: - assert mutation == "natural_log" + elif mutation == "natural_log": mutated = text.replace("log2(widen16(hf", "log(widen16(hf") + else: + assert mutation == "no_exact_zero" + mutated = text.replace("return abs(part) == 0.5f ? 0.0f : sin(part * 6.28318548f);", + "return sin(part * 6.28318548f);") + mutated = mutated.replace("return abs(part) == 0.25f ? 0.0f : cos(part * 6.28318548f);", + "return cos(part * 6.28318548f);") assert mutated != text, mutation return mutated @@ -18630,8 +18685,10 @@ def f16_log_trig_mutated(mutation, program): def f16_log_trig_detecting_program(mutation): """The first program whose expected words the modelled mutation changes.""" for kind, index in F16_LOG_TRIG_PROGRAMS: - if kind != "main": + if kind == "chain": continue + if mutation == "ops_swapped": + return kind, index if f16_log_trig_expected(kind, index, mutation) != f16_log_trig_expected(kind, index): return kind, index raise AssertionError(f"No program separates {mutation}") @@ -18639,7 +18696,7 @@ def f16_log_trig_detecting_program(mutation): def check_f16_log_trig_reference(): """Pinned rows, the log2 midpoint table against the direct compute source, and the translator's own result on - every binary16 encoding.""" + every binary16 encoding of all three ops.""" from f16_log_midpoints import check_cpp_table check_cpp_table() table = f16_log_midpoints() @@ -18651,11 +18708,26 @@ def check_f16_log_trig_reference(): (0x7e00, 0x7e00), (0xfe01, 0x7e00), (0x0144, 0xcbd4), (0x3c01, 0x15c5), (0x7aa3, 0x4bde), (0x4089, 0x3cb9)): assert f16_log_trig_reference("log", 0xa5c3_0000 | half) == expected, (hex(half), hex(expected)) - for half in range(0x10000): - ours = f16_log_trig_reference("log", 0x1234_0000 | half) - theirs = pixel_aot.f16_log_trig_result("log", half) - assert ours == theirs, (hex(half), hex(ours), theirs) - assert "log" in pixel_aot.VOP1_F16_UNARY + for half, expected in ( + (0x0000, 0x0000), (0x8000, 0x8000), (0x3c00, 0x0000), (0x4000, 0x0000), (0x6800, 0x0000), + (0x7bff, 0x0000), (0x3800, 0x0000), (0xb800, 0x0000), (0x3400, 0x3c00), (0xb400, 0xbc00), + (0x3a00, 0xbc00), (0xba00, 0x3c00), (0x3e00, 0x0000), (0xbf00, 0x3c00), + (0x7c00, 0x7e00), (0xfc00, 0x7e00), (0x7e00, 0x7e00), (0xfe01, 0x7e00), + (0x3000, 0x39a8), (0x5555, 0x3b64), (0x3bff, 0x9a48)): + assert f16_log_trig_reference("sin", 0xa5c3_0000 | half) == expected, ("sin", hex(half), hex(expected)) + for half, expected in ( + (0x0000, 0x3c00), (0x8000, 0x3c00), (0x3c00, 0x3c00), (0x4000, 0x3c00), (0x6800, 0x3c00), + (0x7bff, 0x3c00), (0x3400, 0x0000), (0xb400, 0x0000), (0x3a00, 0x0000), (0xba00, 0x0000), + (0xbf00, 0x0000), (0x3800, 0xbc00), (0xb800, 0xbc00), (0x3e00, 0xbc00), + (0x7c00, 0x7e00), (0xfc00, 0x7e00), (0x7e00, 0x7e00), + (0x2c00, 0x3b64), (0x3000, 0x39a8), (0x5555, 0xb61f), (0x3bff, 0x3c00)): + assert f16_log_trig_reference("cos", 0xa5c3_0000 | half) == expected, ("cos", hex(half), hex(expected)) + for op in F16_LOG_TRIG_OPS: + for half in range(0x10000): + ours = f16_log_trig_reference(op, 0x1234_0000 | half) + theirs = pixel_aot.f16_log_trig_result(op, half) + assert ours == theirs, (op, hex(half), hex(ours), theirs) + assert set(F16_LOG_TRIG_OPS) <= set(pixel_aot.VOP1_F16_UNARY) def check_f16_log_trig_mutation_coverage(): @@ -18668,13 +18740,22 @@ def check_f16_log_trig_mutation_coverage(): assert f16_log_trig_reference("log", 0x3c01, mutation="table_off") == 0x15c4 assert f16_log_trig_reference("log", 0x4000) == 0x3c00 assert f16_log_trig_reference("log", 0x4000, mutation="natural_log") != 0x3c00 + assert f16_log_trig_reference("sin", 0x3400) == 0x3c00 + assert f16_log_trig_reference("sin", 0x3800) == 0x0000 + assert f16_log_trig_reference("sin", 0x3800, mutation="no_exact_zero") != 0x0000 + assert f16_log_trig_reference("cos", 0x3400) == 0x0000 + assert f16_log_trig_reference("cos", 0x3400, mutation="no_exact_zero") != 0x0000 + assert f16_log_trig_reference("cos", 0x3800) == 0xbc00 def check_f16_log_trig_controls(): - """Lowering, spelling, input proof, mode, modifier, special-result and reader refusals of v_log_f16.""" + """Lowering, spelling, input proof, mode, modifier, special-result and reader refusals of v_log_f16, + v_sin_f16 and v_cos_f16.""" check_f16_log_trig_reference() check_f16_log_trig_mutation_coverage() prefix = ["v_mov_b32_e32 v18, 0x35554000", "v_mov_b32_e32 v19, 0xd1a74400", "s_mov_b32 s60, 0x35550400"] + calls = {"log": "log2(", "sin": "sin16(", "cos": "cos16("} + helpers = {"log": "f16_log_result(", "sin": "f16_sin_result(", "cos": "f16_cos_result("} def program(*lines): return uncompressed_export([*prefix, *lines]) @@ -18683,73 +18764,90 @@ def refuse(line, message, translator=translate_f16): expect_value_error(translator, program(line), message) # Lowering and spelling: the bare, _e32 and _e64 spellings are one lowering, with the special-result select. - spelled = [translate_f16(program(f"v_log_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] - assert spelled[0] == spelled[1] == spelled[2] - body = spelled[0].split("uint4 main", 1)[1] - assert "log2(widen16(hf" in body and "f16_log_result(" in body - for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): - assert forbidden not in body, forbidden + for op in F16_LOG_TRIG_OPS: + spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] + assert spelled[0] == spelled[1] == spelled[2], op + body = spelled[0].split("uint4 main", 1)[1] + assert calls[op] + "widen16(hf" in body, (op, body) + assert "narrow16(hs" in body and helpers[op] in body, op + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, (op, forbidden) # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals. - for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), - ("0x7bff", 0x7bff)): - for encoding in ("_e32", "_e64"): - assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_log_f16{encoding} v24, {token}")), token - for line in ("v_log_f16_e64 v24, s60", "v_log_f16_e32 v24, s60", "v_log_f16_e32 v24, v18"): - translate_f16(program(line)) + for op in F16_LOG_TRIG_OPS: + for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), + ("0x7bff", 0x7bff)): + for encoding in ("_e32", "_e64"): + assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_{op}_f16{encoding} v24, {token}")), token + for line in (f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e32 v24, s60", f"v_{op}_f16_e32 v24, v18"): + translate_f16(program(line)) # A finite source is enough even when the result is not finite: log2(0) is -infinity and a negative source is - # the canonical NaN; the canonical NaN can be read but does not stay a proven source. - for token in ("0x0001", "0", "0x8000", "-1.0", "0x7bff", "0xfbff"): - translate_f16(program(f"v_log_f16_e64 v24, {token}")) - translate_f16(program("v_mov_b32_e32 v20, v18", "v_log_f16 v24, v20")) - translate_f16(program("s_mov_b32 s61, s60", "v_log_f16_e64 v24, s61")) + # the canonical NaN; sin and cos of every finite source are finite. The canonical NaN can be read but does not + # stay a proven source. + for op in F16_LOG_TRIG_OPS: + for token in ("0x0001", "0", "0x8000", "-1.0", "0x7bff", "0xfbff"): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + translate_f16(program("v_mov_b32_e32 v20, v18", f"v_{op}_f16 v24, v20")) + translate_f16(program("s_mov_b32 s61, s60", f"v_{op}_f16_e64 v24, s61")) translate_f16(program("v_log_f16 v24, 0x3c01", "v_log_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) + translate_f16(program("v_sin_f16 v24, 0x3c00", "v_cos_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " + "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) + translate_f16(program("v_cos_f16 v24, 0x3400", "v_sin_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " + "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) expect_value_error(translate_f16, program("v_log_f16 v24, 0", "v_log_f16 v25, v24"), "binary16 operand is not finite: v24") - expect_value_error(translate_f16, program("v_log_f16 v24, -1.0", "v_log_f16 v25, v24"), + expect_value_error(translate_f16, program("v_log_f16 v24, -1.0", "v_sin_f16 v25, v24"), + "binary16 operand is not finite: v24") + expect_value_error(translate_f16, program("v_log_f16 v24, 0", "v_cos_f16 v25, v24"), "binary16 operand is not finite: v24") # Entry profile: unknown or an unsupported declaration refuses every spelling. - for suffix in ("", "_e32", "_e64"): - expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), - program(f"v_log_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") + for op in F16_LOG_TRIG_OPS: + for suffix in ("", "_e32", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_{op}_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") for state in ("flush", "ftz", "", False): expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, - half_denorm=state), program("v_log_f16 v24, v18"), + half_denorm=state), program("v_sin_f16 v24, v18"), "Invalid binary16 denormal entry state") # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. - for line, token in (("v_log_f16_e64 v24, s44", "s44"), ("v_log_f16 v24, v30", "v30"), - ("v_log_f16_e64 v24, v12", "v12")): - refuse(line, f"binary16 operand lacks a finite proof: {token}") - expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", "v_log_f16 v24, v20"), - "binary16 operand lacks a finite proof: v20") - expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", "v_log_f16 v24, v25"), - "binary16 operand lacks a finite proof: v25") + for op in F16_LOG_TRIG_OPS: + for line, token in ((f"v_{op}_f16_e64 v24, s44", "s44"), (f"v_{op}_f16 v24, v30", "v30"), + (f"v_{op}_f16_e64 v24, v12", "v12")): + refuse(line, f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", f"v_{op}_f16 v24, v20"), + "binary16 operand lacks a finite proof: v20") + expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", f"v_{op}_f16 v24, v25"), + "binary16 operand lacks a finite proof: v25") # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. - for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): - refuse(f"v_log_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") - for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): - translate_f16(program(f"v_log_f16_e64 v24, {token}")) - expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", "v_log_f16 v24, v20"), - "binary16 operand is not finite: v20") + for op in F16_LOG_TRIG_OPS: + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", f"v_{op}_f16 v24, v20"), + "binary16 operand is not finite: v20") # Source modifiers, integer inline constants, floats and other operands. - for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): - refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") - for token in ("1", "64", "-1", "-16", "5"): - refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") - for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): - refuse(f"v_log_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") - refuse("v_log_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") - refuse("v_log_f16_e64 v256, 1.0", "Register out of range: v256") - refuse("v_log_f16_e64 v24, v256", "Register out of range: v256") - refuse("v_log_f16_e64 v24, s106", "Register out of range: s106") + for op in F16_LOG_TRIG_OPS: + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") + refuse(f"v_{op}_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") + refuse(f"v_{op}_f16_e64 v256, 1.0", "Register out of range: v256") + refuse(f"v_{op}_f16_e64 v24, v256", "Register out of range: v256") + refuse(f"v_{op}_f16_e64 v24, s106", "Register out of range: s106") # Unmodelled modifiers and neighbouring forms fall through to the generic refusal. - for line in ("v_log_f16_e64 v24, v18 clamp", "v_log_f16_e64 v24, v18 mul:2", - "v_log_f16_e64 v24, v18 div:2", "v_log_f16_e64 v24, v18 op_sel:[0,1]", - "v_log_f16_e32 v24, v18 clamp", - "v_log_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_log_f16 v24, v18, v19", "v_log_f16 v24", "v_sin_f16_e32 v24, v18", - "v_cos_f16_e64 v24, v18"): + for op in F16_LOG_TRIG_OPS: + for line in (f"v_{op}_f16_e64 v24, v18 clamp", f"v_{op}_f16_e64 v24, v18 mul:2", + f"v_{op}_f16_e64 v24, v18 div:2", f"v_{op}_f16_e64 v24, v18 op_sel:[0,1]", + f"v_{op}_f16_e32 v24, v18 clamp", + f"v_{op}_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + f"v_{op}_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_{op}_f16 v24, v18, v19", f"v_{op}_f16 v24"): + refuse(line, "Unsupported instruction") + for line in ("v_cvt_f16_f16_e32 v24, v18", "v_cvt_f16_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18760,36 +18858,37 @@ def float_f16(instructions): base = with_constants([]) load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) - expect_value_error(float_f16, base[:load + 1] + ["v_log_f16_e64 v24, s44"] + base[load + 1:], + expect_value_error(float_f16, base[:load + 1] + ["v_sin_f16_e64 v24, s44"] + base[load + 1:], "Constant read before load completion") - expect_value_error(float_f16, base[:sample + 1] + ["v_log_f16_e64 v12, 1.0"] + base[sample + 1:], + expect_value_error(float_f16, base[:sample + 1] + ["v_cos_f16_e64 v12, 1.0"] + base[sample + 1:], "Write overlaps an outstanding sample") - expect_value_error(float_f16, base[:sample + 1] + ["v_log_f16_e64 v24, v12"] + base[sample + 1:], + expect_value_error(float_f16, base[:sample + 1] + ["v_sin_f16_e64 v24, v12"] + base[sample + 1:], "Sample used before vmcnt wait") - float_f16(base[:sample + 1] + ["v_log_f16_e64 v20, 1.0"] + base[sample + 1:]) + float_f16(base[:sample + 1] + ["v_cos_f16_e64 v20, 1.0"] + base[sample + 1:]) masked = base.index("s_wqm_b64 exec, exec") + 1 - expect_value_error(float_f16, base[:masked] + ["v_log_f16_e64 v24, 1.0"] + base[masked:], + expect_value_error(float_f16, base[:masked] + ["v_sin_f16_e64 v24, 1.0"] + base[masked:], "Invalid binary16 unary operation") # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. - for spelling in ("v_log_f16", "v_log_f16_e32", "v_log_f16_e64"): - line = f"{spelling} v24, v18" - expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), - f"under round toward zero: {spelling}") - assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( - uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + for op in F16_LOG_TRIG_OPS: + for spelling in (f"v_{op}_f16", f"v_{op}_f16_e32", f"v_{op}_f16_e64"): + line = f"{spelling} v24, v18" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) # Readers. The audited ones read a unary result; every other reader of the tag refuses it. - produced = [*prefix, "v_log_f16_e32 v24, v18"] - for line in ("v_cvt_f32_f16_e32 v12, v24", "v_cvt_f32_f16_e64 v12, v24", - "v_cvt_f32_f16_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): - translate_f16(program(*produced, line)) - sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" - for line, message in ((f"v_cvt_f32_f16_sdwa v12, v24 {sdwa}WORD_1", - "Reads the undefined high half of a 16-bit result"), - ("v_mov_b32_e32 v12, v24", "Expected a numeric register"), - ("v_add_nc_u16 v12, v24, v18", "Expected a numeric register")): - expect_value_error(translate_f16, program(*produced, line), message) - + produced = [*prefix, "v_log_f16_e32 v24, v18", "v_sin_f16_e64 v25, v18", "v_cos_f16_e32 v26, v18"] + for register in (24, 25, 26): + for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", + f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v{register} {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + (f"v_mov_b32_e32 v12, v{register}", "Expected a numeric register"), + (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer @@ -19154,7 +19253,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", - "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_cvt_f16_f16_e32 v24, v18", "v_cvt_f16_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -19517,7 +19616,7 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_log_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", - "v_sin_f16_e32 v24, v18", "v_cos_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_cvt_f16_f16_e32 v24, v18", "v_cvt_f16_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -20422,9 +20521,9 @@ def _check_controls_inline(directory): for expected in ("= ceil(alu", "= round(alu", "= round(params[1].x);", "= ceil((-params[1].y));"): assert expected in source, expected # Neighbouring forms: other widths, output modifiers, a second source and the IEEE-flag reciprocal. - for old, new in (("v_ceil_f32_e32 v12, v18", "v_sin_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_cvt_f16_f16_e32 v12, v18"), ("v_ceil_f32_e32 v12, v18", "v_ceil_f64_e32 v[12:13], v[18:19]"), - ("v_rndne_f32_e32 v13, v19", "v_cos_f16_e32 v13, v19"), + ("v_rndne_f32_e32 v13, v19", "v_cvt_f16_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), ("v_rndne_f32_e64 v14, s45", "v_rndne_f32_e64 v14, s45 mul:2"), ("v_ceil_f32_e64 v15, -s46", "v_ceil_f32_e64 v15, -s46 div:2"), @@ -28849,14 +28948,16 @@ def case(kind, index, tag): def check_f16_log_trig_draw(directory, compiler, renderer, backend): - """v_log_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. - - Three baked programs run 24 sources in a rotation of e32, e64, SGPR and literal forms and pack two results per - word; one chain program computes log2(log2(x)) for eight values above 1. The values cover exact powers, inexact - results, both signed zeros, subnormals, the largest finite half, negative sources and three midpoint-table rows. - Three deviations must each mismatch (one batch per mutation; the statuses are printed): a source read from bits - 31:16, the midpoint corrections dropped, and log2 replaced by the natural log. A source nothing proves is - refused at translation. + """v_log_f16, v_sin_f16 and v_cos_f16 against the Python reference, through the lossless R32G32B32A32_UINT + readback. + + Nine baked programs (three per op) run 24 values each in a rotation of e32, e64, SGPR and literal forms and pack + two results per word; two chain programs compute log2(log2(x)) for eight values above 1 and cos(sin(x)). The values + cover exact powers and whole turns, inexact results, both signed zeros, subnormals, the largest finite half, + negative sources, the exact zero turns of sin and cos, and three log midpoint-table rows. Five deviations must each + mismatch (one batch per mutation; the statuses are printed): the mnemonic cycled, a source read from bits 31:16, + the 1 + ulp midpoint correction off by one encoding, log2 replaced by the natural log, and the exact zero + selections dropped. A source nothing proves is refused at translation. Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's high half is not measured here; the source-high mutation is the high-half control for the sources. diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index a4d9048036..ceb477dd1f 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6282,7 +6282,7 @@ def test_low16_binary16_e32_scanner_support(self): f"v_{op}_f16_e32 v24, 0x3c00, v19", f"v_{op}_f16_e32 v24, 0, v19"] for op in ("floor", "ceil", "trunc", "rndne"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] - for op in ("rcp", "sqrt", "rsq", "exp", "log"): + for op in ("rcp", "sqrt", "rsq", "exp", "log", "sin", "cos"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] for kind in ("i16", "u16"): supported += [f"v_cvt_f16_{kind}_e32 v24, v18", f"v_cvt_f16_{kind}_e32 v24, s45", @@ -6316,6 +6316,10 @@ def test_low16_binary16_e32_scanner_support(self): "v_exp_f16_e32 v24, v18 clamp", "v_log_f16_e32 v24, -v18", "v_log_f16_e32 v24, v18 clamp", + "v_sin_f16_e32 v24, -v18", + "v_sin_f16_e32 v24, v18 clamp", + "v_cos_f16_e32 v24, -v18", + "v_cos_f16_e32 v24, v18 clamp", "v_fract_f16_e32 v24, v18", "v_cvt_f16_i16_e32 v24, 65", "v_cvt_f16_u16_e32 v24, 0x10000", @@ -6326,7 +6330,7 @@ def test_low16_binary16_e32_scanner_support(self): for line in refused: self.assertFalse(is_instruction_supported(line), line) for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_rcp_f16", "v_sqrt_f16", - "v_rsq_f16", "v_exp_f16", "v_log_f16", + "v_rsq_f16", "v_exp_f16", "v_log_f16", "v_sin_f16", "v_cos_f16", "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): self.assertIn(opcode, KNOWN_RDNA2_BASE_OPCODES) @@ -6355,7 +6359,7 @@ def translator_accepts(line): for op in ("floor", "ceil", "trunc", "rndne"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] - for op in ("rcp", "sqrt", "rsq", "exp", "log"): + for op in ("rcp", "sqrt", "rsq", "exp", "log", "sin", "cos"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] refused = [ @@ -6376,6 +6380,10 @@ def translator_accepts(line): "v_exp_f16_e64 v24, v18 mul:2", "v_rsq_f16_e64 v24, 3", "v_exp_f16_e64 v24, 0x10000", "v_log_f16_e64 v24, -v18", "v_log_f16_e64 v24, |v18|", "v_log_f16_e64 v24, v18 clamp", "v_log_f16_e64 v24, v18 mul:2", "v_log_f16_e64 v24, 3", "v_log_f16_e64 v24, 0x10000", + "v_sin_f16_e64 v24, -v18", "v_sin_f16_e64 v24, |v18|", "v_sin_f16_e64 v24, v18 clamp", + "v_sin_f16_e64 v24, v18 mul:2", "v_sin_f16_e64 v24, 3", "v_sin_f16_e64 v24, 0x10000", + "v_cos_f16_e64 v24, -v18", "v_cos_f16_e64 v24, |v18|", "v_cos_f16_e64 v24, v18 clamp", + "v_cos_f16_e64 v24, v18 mul:2", "v_cos_f16_e64 v24, 3", "v_cos_f16_e64 v24, 0x10000", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 525e3d3e7b..14e0061683 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -566,6 +566,20 @@ def comparison_resources(state): float cos32(float value) { return cos(turns(value) * 6.28318548f); } +// v_sin_f16 and v_cos_f16 take turns like their binary32 forms, but the direct compute path also +// selects the exact zero at half a turn for sin and a quarter turn for cos after reducing. +float turns16(float value) { + float part = value - round(value); + return value == 0.0f ? value : part; +} +float sin16(float value) { + float part = turns16(value); + return abs(part) == 0.5f ? 0.0f : sin(part * 6.28318548f); +} +float cos16(float value) { + float part = turns16(value); + return abs(part) == 0.25f ? 0.0f : cos(part * 6.28318548f); +} // v_cvt_f32_f16: widen the binary16 in the low half of a word, built from its encoding so that // desktop denormal handling cannot change it. Subnormal halves stay exact as m * 2^-24; NaN payloads widen. float widen16(uint word) { @@ -1174,6 +1188,21 @@ def check_vopc_e32_dst(enc, dst): " return rounded;\n" "}" ), + # The RDNA 2 special results of v_sin_f16 and v_cos_f16 from the source half bits: every infinity and NaN is + # the canonical quiet NaN, and v_sin_f16 preserves -0. + "f16_sin_result": ( + "uint f16_sin_result(uint source, uint rounded) {\n" + " if ((source & 0x7fffu) >= 0x7c00u) return 0x7e00u;\n" + " if (source == 0x8000u) return 0x8000u;\n" + " return rounded;\n" + "}" + ), + "f16_cos_result": ( + "uint f16_cos_result(uint source, uint rounded) {\n" + " if ((source & 0x7fffu) >= 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), "frexp_mant_f16": ( "uint frexp_mant_f16(uint bits) {\n" " uint h = bits & 0xffffu;\n" @@ -2198,7 +2227,7 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi # rsqrt and exp2 approximations have a measured error window, so the lowered shader also applies the special-result # and midpoint corrections of src/gfx1013_direct_compute.inl to the narrowed half. VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})", "rsq": "rsqrt({0})", "exp": "exp2({0})", - "log": "log2({0})"} + "log": "log2({0})", "sin": "sin16({0})", "cos": "cos16({0})"} # The 70 finite binary16 sources whose exact 2^S0 lies within the D3D exp2 error window of a binary16 rounding # midpoint, with the RDNA 2 result. This is the exp_f16_midpoints table of src/gfx1013_direct_compute.inl; @@ -2459,19 +2488,62 @@ def _f16_log2_result(value): return _fraction_to_f16(Fraction(logarithm)) +# The direct compute trig_turns radian constant: double 0x401921FB60000000 rounded to binary32. +_F16_TWO_PI_F32 = struct.unpack('d', bytes.fromhex('401921FB60000000'))[0]))[0] + + +def _f16_round_f32(value): + """Round a Python float to binary32, as the direct compute path's fmul and intrinsic results do.""" + return struct.unpack('> 23) != 0xff + return (0x8000 if sign else 0) | _fraction_to_f16(_f32_fraction(magnitude)) + + +def _f16_sin_cos_result(name, bits): + """Binary16 result bits of v_sin_f16 or v_cos_f16 on a finite operand. + + The direct compute lowering widens the low half, subtracts the nearest integer in binary32 (Round_ne), and + evaluates sin or cos of the remainder times the same binary32 2*pi constant, then narrows with packed_half_rne. + The exact zeros at half a turn for sin and a quarter turn for cos are selected as +0 before the intrinsic, as + trig_turns does; a zero angle keeps the sign of the source, so sin(-0) stays -0. + """ + value = float(_f16_fraction(bits)) + part = value if value == 0 else _f16_round_f32(value - round(value)) + if abs(part) == (0.25 if name == "cos" else 0.5): + return 0 + radians = _f16_round_f32(part * _F16_TWO_PI_F32) + widened = _f16_round_f32(math.cos(radians) if name == "cos" else math.sin(radians)) + return _f16_from_f32(widened) + + def f16_log_trig_result(name, bits): - """Binary16 result bits of v_log_f16 on any binary16 encoding. - - The direct compute lowering widens the low half with widen16, calls unary.f32 opcode 23 (log2), narrows with - packed_half_rne and then applies the RDNA 2 special results and the 73 midpoint corrections from the source half: - +infinity stays +infinity, every NaN and every negative nonzero source becomes 0x7e00, and either zero becomes - 0xfc00. The exact log2 of every other positive finite source is rounded to binary16; the midpoint table pins the - sources whose exact result lies inside the D3D Log error window of a rounding midpoint. Every source encoding has - a modelled result, so None is never returned today. Used at translation time so that a chained result stays a - proven value. + """Binary16 result bits of v_log_f16, v_sin_f16 or v_cos_f16 on any binary16 encoding. + + Log widens the low half, calls unary.f32 opcode 23 (log2), narrows with packed_half_rne and applies the RDNA 2 + special results and the 73 midpoint corrections from the source half: +infinity stays +infinity, every NaN and + every negative nonzero source becomes 0x7e00, and either zero becomes 0xfc00. The exact log2 of every other + positive finite source is rounded to binary16; the midpoint table pins the sources whose exact result lies inside + the D3D Log error window of a rounding midpoint. Sin and cos widen the low half, reduce the turn count and evaluate + the same binary32 intrinsic as the direct compute trig_turns helper, with its exact zero selections; every source + of magnitude at or above +infinity is the canonical quiet NaN 0x7e00, and v_sin_f16 preserves -0. Every source + encoding has a modelled result, so None is never returned today. Used at translation time so that a chained + result stays a proven value. """ - assert name == "log" + assert name in ("log", "sin", "cos") bits &= 0xffff + if name != "log": + if (bits & 0x7fff) >= 0x7c00: + return 0x7e00 + if name == "sin" and bits == 0x8000: + return 0x8000 + return _f16_sin_cos_result(name, bits) magnitude = bits & 0x7fff if magnitude == 0: return 0xfc00 @@ -8176,11 +8248,11 @@ def known_sample_float(reg): vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result elif m := match(rf"v_({'|'.join(VOP1_F16_UNARY)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): - # Plain binary16 VOP1 reciprocal, square root, reciprocal square root, exponent and logarithm under the - # rules of the VOP2 arithmetic above: a statically proven finite source, the declared entry profile, no - # modifier, clamp or omod. These match the direct compute lowering: widen16, one binary32 division, sqrt, - # rsqrt, exp2 or log2, then narrow16. rsq, exp and log additionally select the RDNA 2 special results and - # midpoint corrections from the source half bits. + # Plain binary16 VOP1 reciprocal, square root, reciprocal square root, exponent, logarithm, sine and cosine + # under the rules of the VOP2 arithmetic above: a statically proven finite source, the declared entry + # profile, no modifier, clamp or omod. These match the direct compute lowering: widen16, one binary32 + # division, sqrt, rsqrt, exp2, log2, sin or cos, then narrow16. rsq, exp, log, sin and cos additionally + # select the RDNA 2 special results from the source half bits; log adds its midpoint corrections. # The result is ("half16", alu). name, encoding, dst, token = m.groups() if mask != "entry": @@ -8204,9 +8276,10 @@ def known_sample_float(reg): helper = "f16_rsq_result" if name == "rsq" else "f16_exp2_result" helpers.add(helper) lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, narrow16(hs{i})));") - elif name == "log": - helpers.add("f16_log_result") - lines.append(f" precise float alu{i} = asfloat(f16_log_result(hf{i}_0, narrow16(hs{i})));") + elif name in ("log", "sin", "cos"): + helper = {"log": "f16_log_result", "sin": "f16_sin_result", "cos": "f16_cos_result"}[name] + helpers.add(helper) + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, narrow16(hs{i})));") else: lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index f8dec1ada7..06a6b14fab 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -473,7 +473,6 @@ def lower_rejection_causes(results: list[dict]) -> dict: # Decoding only: the tables above cover the binary16 VOP1/VOP2 forms a translator lowers. "v_cvt_u16_f16", "v_cvt_i16_f16", "v_fract_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_sin_f16", "v_cos_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_fmac_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", "v_pk_fmac_f16", } From b17b206ccc627466abd7590790c1dbe0926b9be9 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 08:11:06 +0000 Subject: [PATCH 4/5] shader: lower binary16 VOP3 three-way minimum and maximum --- CMakeLists.txt | 6 + docs/experiments.md | 4 + tests/form_coverage_check.py | 30 ++ tests/pixel_aot_check.py | 443 +++++++++++++++++++++++++++++- tests/rdna2_tools_check.py | 14 +- tools/pixel_aot.py | 86 ++++++ tools/scan_unsupported_shaders.py | 9 + 7 files changed, 590 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8506dd6ced..9f69e9cb6d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11380,6 +11380,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-log-trig "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(pixel_aot_f16_log_trig_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME pixel_aot_f16_minmax3_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-minmax3 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_minmax3_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_f16_fmac_ldexp_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-fmac-ldexp "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -11672,6 +11676,8 @@ if(EXISTS "${INTAKE_PYTHON}") ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rsq_exp_${adapter}.txt") set_tests_properties(pixel_aot_f16_log_trig_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_log_trig_${adapter}.txt") + set_tests_properties(pixel_aot_f16_minmax3_${adapter} PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_minmax3_${adapter}.txt") set_tests_properties(pixel_aot_f16_fmac_ldexp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_fmac_ldexp_${adapter}.txt") set_tests_properties(pixel_aot_f16_cvt_int16_${adapter} PROPERTIES diff --git a/docs/experiments.md b/docs/experiments.md index 19a8353387..4d11c97847 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9009,6 +9009,10 @@ The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operan Plain binary16 `VOP1` logarithm, sine and cosine (issue #839) `v_log_f16`, `v_sin_f16` and `v_cos_f16`, in the unsuffixed, `_e32` and `_e64` spellings, extend the unary entry above. The low half is widened exactly with `widen16`; `v_log_f16` evaluates the direct compute path's `log2` (`unary.f32` opcode 23), while `v_sin_f16` and `v_cos_f16` use the same turn reduction as `trig_turns` (subtract `Round_ne` in binary32, keep a zero angle's sign, select the exact zero at half a turn for sin and a quarter turn for cos, then multiply by the binary32 2*pi constant and evaluate the intrinsic). `narrow16` rounds once, then the RDNA 2 special results are selected from the source half: log keeps `+infinity`, maps every NaN and negative nonzero source to `0x7e00` and either zero to `-infinity` (`0xfc00`); sin and cos map an infinity or NaN magnitude to `0x7e00`, and sin preserves `-0`. The emitter carries the 73 log midpoint corrections of `log_f16_midpoints` (regenerated and checked by `tests/f16_log_midpoints.py`) as `LOG_F16_MIDPOINTS`, and the helpers `f16_log_result`, `f16_sin_result` and `f16_cos_result`. The translator tracks each result with `f16_log_trig_result`: log returns the table entry or rounds the exact log2 of every other positive finite source with a 90-digit Decimal reference, and sin/cos reproduce the turn reduction and host intrinsic in binary32. Every encoding has a modelled result, so None is never returned today; the signature keeps that contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the unary forms above, and the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused. The controls (`check_f16_log_trig_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, pin `LOG_F16_MIDPOINTS` to the C++ array through `tests/f16_log_midpoints.py check_cpp_table`, and compare the reference with `f16_log_trig_result` on all 65,536 encodings of all three ops. The draw (`tests/pixel_aot_check.py draw-f16-log-trig`, tests `pixel_aot_f16_log_trig_hardware` and `pixel_aot_f16_log_trig_warp`, 60 s limit, capability skip 77) runs nine baked programs, three per op, over 24 values each in a rotation of e32, e64, SGPR and literal forms, packs two results per word with SDWA `WORD_0` and `WORD_1`, and adds two chains (`log2(log2(x))` and `cos(sin(x))`). The values cover exact powers and whole turns, inexact results, both signed zeros, subnormals, the largest finite half, negative sources, the `log2(1)` row, the exact zero turns of sin and cos, and three log midpoint-table rows; the inexact sin and cos values keep the binary32 result at least 5e-5 from a binary16 rounding midpoint, except the exact selected zeros. The lossless `R32G32B32A32_UINT` readback is compared with `f16_log_trig_reference`, a 90-digit or host-intrinsic reference without `pixel_aot`. Five deviations must each mismatch, one batch per mutation with the statuses printed: the mnemonic cycled, a source read from bits 31:16, the `1 + ulp` midpoint correction off by one encoding, `log2` replaced by the natural log, and the exact zero selections dropped. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_log_trig_forms` pins the six newly covered forms (log, sin and cos, each e32 and e64) and leaves the DPP and SDWA neighbours uncovered; the six forms take the measured totals from 1550/1968 and 1541/1863 to 1556/1968 and 1547/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D Log error window beyond the modelled midpoint corrections and the exact reference, the D3D Sin/Cos error beyond the chosen midpoint margin, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, and whether any title executes these paths. +Plain binary16 `VOP3` three-operand minimum and maximum (issue #839), `v_min3_f16` and `v_max3_f16`, in the unsuffixed and `_e64` spellings, extend the binary16 entries above. These are VOP3-only forms and LLVM 15 prints no encoding suffix for them. The lowering follows the direct compute block in `src/gfx1013_direct_compute.inl`: the three finite low halves are ordered by the unsigned sign-magnitude key `x ^ (x >= 0x8000 ? 0xffff : 0x8000)`, so `-0.0h` sorts below `+0.0h` and every negative finite value below every positive one; `v_min3_f16` folds the pair with `false` and `v_max3_f16` with `true`, and the result is one whole source encoding, so no rounding occurs. `clamp` maps a negative result, including `-0.0h`, to `+0.0h` and a result above `0x3bff` to `1.0h` (`0x3c00`). The emitted helpers are `f16_minmax2_bits`, `f16_min3_bits` and `f16_max3_bits`, and the translator tracks the exact bits with `f16_minmax3_result` so a result stays a proven source for a later binary16 op. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. An `_e32` suffix, DPP, SDWA, `op_sel`, `mul:`, `div:`, source modifiers, non-finite encodings and the neighbouring `v_med3_f16` stay refused; the exact messages are the shared binary16 source, range and modifier refusals plus `Invalid binary16 ternary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. + +The controls (`check_f16_minmax3_controls`, no GPU) cover every spelling, operand kind, the clamp, the proof, modifier, mode, scheduling and reader refusals and chains of both operations, and compare the independent Python reference with `f16_minmax3_result` on every finite encoding of the first source, on every triple of a 16-value special set and on a deterministic 20,000-triple sample. The draw (`tests/pixel_aot_check.py draw-f16-minmax3`, tests `pixel_aot_f16_minmax3_hardware` and `pixel_aot_f16_minmax3_warp`, 60 s limit, capability skip 77) runs two main programs over eight triples with both ops in a rotation of the bare and `_e64` spellings and VGPR/SGPR operand banks, one clamp program over four triples, one inline program whose every source is a binary16 inline constant or 16-bit literal, two chains where a min3 or max3 result feeds the next op, and two reader programs through the four audited readers; two results are packed per word with SDWA `WORD_0` and `WORD_1`. The triples cover three distinct values, negative values, equalities, `-0` against `+0`, the largest finite halves and the clamp boundaries. The lossless `R32G32B32A32_UINT` readback is compared with `f16_minmax3_reference`, a reference without `pixel_aot` that folds the sign-magnitude key and applies the clamp. Four deviations must each mismatch, one batch per mutation with the statuses printed: the two operations swapped, a signed comparison of the raw halves, the clamp dropped, and a source read from bits 31:16. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_minmax3_forms` pins the two newly covered forms (`v_min3_f16` and `v_max3_f16`, both `VOP3`) and leaves `v_med3_f16` uncovered; the two forms add two to each reference, taking the stack totals from 1556/1968 and 1547/1863 to 1558/1968 and 1549/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN and infinity sources (refused before lowering), NaN payloads, runtime sources, the DPP, SDWA and `op_sel` spellings, `v_med3_f16`, and whether any title executes these paths. + Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. `tools/scan_unsupported_shaders.py` reports the `_e64` spelling of the four `VOP2` arithmetic ops and the four `VOP1` rounding ops above as supported, matching what `tools/pixel_aot.py` lowers: two sources of the `_e32` source set (a binary16 inline constant, 0, a 16-bit literal, a VGPR or an SGPR; the `_e64` src1 need not be a VGPR) or one source for the rounding ops, with no modifier, `clamp`, `mul:`, `div:` or `op_sel`. The `_e64` spellings of `v_cvt_f16_i16` and `v_cvt_f16_u16` and of `v_fract_f16` stay unsupported. This is a syntactic match only: whether a source is statically proven finite is decided by the translator. `tests/rdna2_tools_check.py` (`test_binary16_e64_scanner_translator_agreement`) lowers each accepted and each refused form through `pixel_aot.lower` and requires the scanner to agree with it. No lowering changed here, so this adds no new shader readback; the existing binary16 draws in `tests/pixel_aot_check.py` already cover the `_e64` lowering. It shows scanner and translator agreement, not that any title runs. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 3c97b1fe45..0d33660049 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -793,6 +793,35 @@ def check_f16_log_trig_forms(): pixel.ACCEPTED.update(saved) +def check_f16_minmax3_forms(): + """The two plain VOP3 binary16 three-operand min/max forms count as covered once the translator accepts their + fixtures; the med3 neighbour stays uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for key in pixel.F16_MINMAX3_PROGRAMS: + pixel.translate_f16(pixel.f16_minmax3_program(*key)) + forms = {("VOP3", "v_min3_f16"), ("VOP3", "v_max3_f16")} + assert len(forms) == 2 + neighbours = {("VOP3", "v_med3_f16")} + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not neighbours & covered, (name, sorted(neighbours & covered)) + # Without the fixtures none of the two forms is covered. + pixel.ACCEPTED.clear() + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + assert not forms & fc.gfx_forms(pixel.ACCEPTED, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + def check_f16_fmac_ldexp_forms(): """The two plain e32 binary16 forms v_fmac_f16 and v_ldexp_f16 count as covered once the translator accepts their fixtures; their e64, DPP and SDWA spellings and the arithmetic they resemble stay uncovered.""" @@ -1877,6 +1906,7 @@ def check_f16_cvt_norm_forms(): check_f16_rcp_sqrt_forms() check_f16_rsq_exp_forms() check_f16_log_trig_forms() + check_f16_minmax3_forms() check_f16_fmac_ldexp_forms() check_f16_cvt_int16_forms() check_f16_to_int16_forms() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 779d065c70..b0fc02066c 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -18890,6 +18890,400 @@ def float_f16(instructions): (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): expect_value_error(translate_f16, program(*produced, line), message) + +# Plain VOP3 binary16 three-operand minimum and maximum (issue #839): v_min3_f16 and v_max3_f16. The direct compute +# path orders the encodings with the unsigned sign-magnitude key x ^ (x >= 0x8000 ? 0xffff : 0x8000), so -0.0h sorts +# below +0.0h and every negative below every positive value, and it selects one whole source: there is no rounding. +# clamp maps a negative result (including -0.0h) to +0.0h and a result above 0x3bff to 1.0h (0x3c00). The translator +# refuses every source whose finite proof fails and every encoding other than the plain VOP3 one. +F16_MINMAX3_OPS = ("min3", "max3") +F16_MINMAX3_TRIPLES = ( + (0xbc00, 0x3c00, 0x0000), # -1, 1, +0 + (0xc000, 0xb800, 0xbe00), # -2, -0.5, -1.5 + (0x8000, 0x0000, 0x3c00), # -0, +0, 1 + (0x0000, 0x8000, 0xbc00), # +0, -0, -1 + (0x3e00, 0x3e00, 0x3e00), # three equal 1.5 + (0x3c00, 0x3c00, 0x4000), # 1, 1, 2 + (0x7bff, 0x3c00, 0x0000), # 65504, 1, +0 + (0xfbff, 0x7bff, 0x0000), # -65504, 65504, +0 +) +F16_MINMAX3_CLAMP_TRIPLES = ( + (0xbc00, 0x3800, 0x3e00), # min -1 -> +0; max 1.5 -> 1.0 + (0x8000, 0x3c00, 0x4000), # min -0 -> +0; max 2 -> 1.0 + (0x3bff, 0x3c00, 0x3bff), # 0x3bff and 1.0 stay inside the clamp + (0x4400, 0x0000, 0x8001), # min -subnormal -> +0; max 4 -> 1.0 +) +F16_MINMAX3_INLINE_TRIPLES = ( + (0x3c00, 0x4000, 0xc000), # 1, 2, -2 + (0x3800, 0xb800, 0x0000), # 0.5, -0.5, +0 + (0x4400, 0xc400, 0x3bff), # 4, -4, 0x3bff + (0x3118, 0x7bff, 0x8000), # 0.15915494, 65504, -0 +) +# Chains (a, b, c, d): min3(a, b, c), max3(previous, c, d), min3(c, d, a), clamp(max3(previous, a, d)). +F16_MINMAX3_CHAINS = ( + (0xbc00, 0x4000, 0x8000, 0x3c00), + (0x3c00, 0xc000, 0x3800, 0x3e00), +) +F16_MINMAX3_MUTATIONS = ("ops_swapped", "order_signed", "clamp_removed", "src_high") + + +def f16_minmax3_reference(op, word0, word1, word2, *, clamp=False, mutation=None): + """Binary16 result bits of v_min3_f16 or v_max3_f16 on the low halves of three source words. + + The order is the direct compute sign-magnitude key (so -0.0 sorts below +0.0), the operation folds a pair twice, + and clamp maps a negative result to +0 and one above 0x3bff to 1.0. mutation models the draw's deviations: the + operation swapped, a signed comparison of the raw halves, the clamp dropped, or a source read from bits 31:16. + """ + if mutation == "ops_swapped": + op = "max3" if op == "min3" else "min3" + + def operand(word): + return (word >> 16 if mutation == "src_high" else word) & 0xffff + + a, b, c = operand(word0), operand(word1), operand(word2) + + def key(bits): + return bits ^ (0xffff if bits & 0x8000 else 0x8000) + + def pick(x, y): + if mutation == "order_signed": + sx = x - 0x10000 if x & 0x8000 else x + sy = y - 0x10000 if y & 0x8000 else y + win = sx > sy if op == "max3" else sx < sy + else: + win = key(x) > key(y) if op == "max3" else key(x) < key(y) + return x if win else y + + result = pick(pick(a, b), c) + if clamp and mutation != "clamp_removed": + if result & 0x8000: + return 0 + if result > 0x3bff: + return 0x3c00 + return result + + +def f16_minmax3_token(bits): + """The source token of an inline/literal form, as LLVM 15 prints it.""" + inverse = {value: token for token, value in pixel_aot.INLINE_F16.items()} + if bits in inverse: + return inverse[bits] + return "0" if bits == 0 else f"{bits:#x}" + + +def f16_minmax3_triples(kind, index): + table = {"main": F16_MINMAX3_TRIPLES, "clamp": F16_MINMAX3_CLAMP_TRIPLES, + "inline": F16_MINMAX3_INLINE_TRIPLES, + "reader": F16_MINMAX3_TRIPLES}[kind] + return table[4 * index:4 * index + 4] if kind != "reader" else table[2 * index:2 * index + 2] + + +def f16_minmax3_source_words(triple, salt=0): + """The three 32-bit source words of a triple, with junk in bits 31:16.""" + return tuple((F16_ARITH_JUNK[(salt + k) % 4] << 16) | bits for k, bits in enumerate(triple)) + + +def f16_minmax3_program(kind, index): + """One draw program. Kinds: main and clamp (four triples, both ops, two results packed per word), inline (every + source an inline constant or 16-bit literal), reader (one triple through the four readers) and chain (both ops + where a min3/max3 result feeds the next one).""" + pack = "v_mov_b32_sdwa v{dst}, v{src} dst_sel:{sel} dst_unused:{unused} src0_sel:WORD_0" + body = [] + if kind in ("main", "clamp"): + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + regs, sgprs = (18 + 3 * slot, 19 + 3 * slot, 20 + 3 * slot), (60 + 3 * slot, 61 + 3 * slot, 62 + 3 * slot) + for k, word in enumerate(f16_minmax3_source_words(triple, index * 12 + 3 * slot)): + body += [f"v_mov_b32_e32 v{regs[k]}, {word:#x}", f"s_mov_b32 s{sgprs[k]}, {word:#x}"] + for k, op in enumerate(F16_MINMAX3_OPS): + dst, form = 32 + 2 * slot + k, (slot + k + index) % 4 + sources = {0: (f"v{regs[0]}", f"v{regs[1]}", f"v{regs[2]}"), + 1: (f"v{regs[0]}", f"v{regs[1]}", f"v{regs[2]}"), + 2: (f"s{sgprs[0]}", f"v{regs[1]}", f"s{sgprs[2]}"), + 3: (f"v{regs[0]}", f"s{sgprs[1]}", f"v{regs[2]}")}[form] + line = f"v_{op}_f16{'_e64' if form == 1 else ''} v{dst}, {sources[0]}, {sources[1]}, {sources[2]}" + body.append(line + (" clamp" if kind == "clamp" else "")) + for word in range(4): + body.append(pack.format(dst=12 + word, src=32 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=33 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + elif kind == "inline": + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + tokens = [f16_minmax3_token(bits) for bits in triple] + for k, op in enumerate(F16_MINMAX3_OPS): + dst, form = 32 + 2 * slot + k, (slot + k) % 2 + body.append(f"v_{op}_f16{'_e64' if form else ''} v{dst}, {tokens[0]}, {tokens[1]}, {tokens[2]}") + for word in range(4): + body.append(pack.format(dst=12 + word, src=32 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=33 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + elif kind == "chain": + words = f16_minmax3_source_words(F16_MINMAX3_CHAINS[index], index * 4) + body += [f"v_mov_b32_e32 v{18 + k}, {word:#x}" for k, word in enumerate(words)] + body += ["v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v24, v20, v21", + "v_min3_f16 v26, v20, v21, v18", "v_max3_f16 v27, v26, v18, v21 clamp"] + body += [f"v_cvt_f32_f16_e32 v{12 + k}, v{24 + k}" for k in range(4)] + else: + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + regs = (18 + 3 * slot, 19 + 3 * slot, 20 + 3 * slot) + body += [f"v_mov_b32_e32 v{regs[k]}, {word:#x}" + for k, word in enumerate(f16_minmax3_source_words(triple, index * 6 + 3 * slot))] + body += [f"v_min3_f16 v{24 + 2 * slot}, v{regs[0]}, v{regs[1]}, v{regs[2]}", + f"v_max3_f16 v{25 + 2 * slot}, v{regs[0]}, v{regs[1]}, v{regs[2]}"] + body += [line.format(24 + (r + index) % 4) for r, line in enumerate(F16_ROUND_READERS)] + return uncompressed_export(body) + + +def f16_minmax3_group_results(kind, index, mutation=None): + """The eight results of a main, clamp or inline program (or four for a reader program).""" + clamp = kind == "clamp" + results = [] + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + words = f16_minmax3_source_words(triple, index * (12 if kind != "reader" else 6) + 3 * slot) + results += [f16_minmax3_reference(op, *words, clamp=clamp, mutation=mutation) for op in F16_MINMAX3_OPS] + return results + + +def f16_minmax3_expected(kind, index, mutation=None): + """The four exported words of f16_minmax3_program(kind, index).""" + if kind in ("main", "clamp", "inline"): + results = f16_minmax3_group_results(kind, index, mutation) + return tuple(results[2 * w] | results[2 * w + 1] << 16 for w in range(4)) + if kind == "reader": + results = f16_minmax3_group_results(kind, index, mutation) + chosen = [results[(r + index) % 4] for r in range(4)] + return (*(f16_widen_word(bits) for bits in chosen[:3]), chosen[3]) + words = f16_minmax3_source_words(F16_MINMAX3_CHAINS[index], index * 4) + first = f16_minmax3_reference("min3", words[0], words[1], words[2], mutation=mutation) + second = f16_minmax3_reference("max3", first, words[2], words[3], mutation=mutation) + third = f16_minmax3_reference("min3", words[2], words[3], words[0], mutation=mutation) + fourth = f16_minmax3_reference("max3", third, words[0], words[3], clamp=True, mutation=mutation) + return tuple(f16_widen_word(bits) for bits in (first, second, third, fourth)) + + +F16_MINMAX3_PROGRAMS = (("main", 0), ("main", 1), ("clamp", 0), ("inline", 0), + ("chain", 0), ("chain", 1), ("reader", 0), ("reader", 1)) + + +def f16_minmax3_mutated(mutation, program): + """The lowered source of program with one deviation applied to the helpers.""" + text = translate_f16(program) + if mutation == "ops_swapped": + low = "uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, false), c, false);" + high = "uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, true), c, true);" + mutated = text.replace(low, "@@LOW@@").replace(high, low).replace("@@LOW@@", high) + elif mutation == "order_signed": + old = " return (is_max ? (ka > kb) : (ka < kb)) ? a : b;" + new = (" return (is_max ? (asint(a << 16) > asint(b << 16)) " + ": (asint(a << 16) < asint(b << 16))) ? a : b;") + mutated = text.replace(old, new) + elif mutation == "clamp_removed": + mutated = text.replace(" if (!clamp_result) return result;", " return result;") + else: + mutated = re.sub(r"uint (hf\d+_\d+) = \((.+)\) & 0xffffu;", r"uint \1 = ((\2) >> 16u) & 0xffffu;", text) + assert mutated != text, mutation + return mutated + + +def f16_minmax3_detecting_program(mutation): + """The first program whose expected words the modelled mutation changes.""" + for kind, index in F16_MINMAX3_PROGRAMS: + if f16_minmax3_expected(kind, index, mutation) != f16_minmax3_expected(kind, index): + return kind, index + raise AssertionError(f"No program separates {mutation}") + + +def check_f16_minmax3_reference(): + """The Python side of the draw: pinned rows, the special triples and the translator's own result on every + finite encoding of the first source (the other two fixed) and on every triple of a small special set.""" + assert len(F16_MINMAX3_TRIPLES) == 8 and len(set(F16_MINMAX3_TRIPLES)) == 8 + assert len(F16_MINMAX3_CLAMP_TRIPLES) == 4 and len(F16_MINMAX3_INLINE_TRIPLES) == 4 + for op, triple, expected in ( + ("min3", (0xbc00, 0x3c00, 0x0000), 0xbc00), ("max3", (0xbc00, 0x3c00, 0x0000), 0x3c00), + ("min3", (0xc000, 0xb800, 0xbe00), 0xc000), ("max3", (0xc000, 0xb800, 0xbe00), 0xb800), + ("min3", (0x8000, 0x0000, 0x3c00), 0x8000), ("max3", (0x8000, 0x0000, 0x3c00), 0x3c00), + ("min3", (0x3e00, 0x3e00, 0x3e00), 0x3e00), ("max3", (0x3c00, 0x3c00, 0x4000), 0x4000), + ("min3", (0xbc00, 0x3800, 0x3e00), 0xbc00), ("max3", (0x4400, 0x0000, 0x8001), 0x4400)): + assert f16_minmax3_reference(op, *triple) == expected, (op, triple) + assert f16_minmax3_reference("min3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x0000 + assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x3c00 + assert f16_minmax3_reference("min3", 0x8000, 0x3c00, 0x4000, clamp=True) == 0x0000 + assert f16_minmax3_reference("min3", 0x3bff, 0x3c00, 0x3bff, clamp=True) == 0x3bff + assert f16_minmax3_reference("max3", 0x3bff, 0x3c00, 0x3bff, clamp=True) == 0x3c00 + for half in range(0x10000): + if (half >> 10) & 0x1f == 0x1f: + continue + for op in F16_MINMAX3_OPS: + for clamp in (False, True): + ours = f16_minmax3_reference(op, 0xa5c3_0000 | half, 0x1234_bc00, 0x4248_3c00, clamp=clamp) + theirs = pixel_aot.f16_minmax3_result(op, half, 0xbc00, 0x3c00, clamp=clamp) + assert ours == theirs, (op, hex(half), clamp, hex(ours), hex(theirs)) + specials = (0x0000, 0x8000, 0x0001, 0x8001, 0x3c00, 0xbc00, 0x7bff, 0xfbff, 0x3bff, 0xbbff, + 0x0400, 0x8400, 0x3e00, 0xbe00, 0x3800, 0xb800) + for a in specials: + for b in specials: + for c in specials: + for op in F16_MINMAX3_OPS: + for clamp in (False, True): + ours = f16_minmax3_reference(op, 0x3555_0000 | a, 0xd1a7_0000 | b, 0x4248_0000 | c, + clamp=clamp) + theirs = pixel_aot.f16_minmax3_result(op, a, b, c, clamp=clamp) + assert ours == theirs, (op, hex(a), hex(b), hex(c), clamp) + rng = random.Random(839) + finite = [bits for bits in range(0x10000) if (bits >> 10) & 0x1f != 0x1f] + for _ in range(20_000): + a, b, c = (rng.choice(finite) for _ in range(3)) + for op in F16_MINMAX3_OPS: + for clamp in (False, True): + assert f16_minmax3_reference(op, a, b, c, clamp=clamp) == pixel_aot.f16_minmax3_result( + op, a, b, c, clamp=clamp), (op, hex(a), hex(b), hex(c), clamp) + assert set(pixel_aot.VOP3_F16_MINMAX3) == {"min3", "max3"} + + +def check_f16_minmax3_mutation_coverage(): + """Every deviation changes an expected word of some program.""" + for kind, index in F16_MINMAX3_PROGRAMS: + assert len(f16_minmax3_expected(kind, index)) == 4, (kind, index) + for mutation in F16_MINMAX3_MUTATIONS: + f16_minmax3_detecting_program(mutation) + assert f16_minmax3_reference("min3", 0xbc00, 0x3c00, 0x0000) == 0xbc00 + assert f16_minmax3_reference("min3", 0xbc00, 0x3c00, 0x0000, mutation="ops_swapped") == 0x3c00 + assert f16_minmax3_reference("min3", 0x8000, 0x0000, 0xbc00) == 0xbc00 + assert f16_minmax3_reference("min3", 0x8000, 0x0000, 0xbc00, mutation="order_signed") == 0x8000 + assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x3c00 + assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True, mutation="clamp_removed") == 0x3e00 + + +def check_f16_minmax3_controls(): + """Lowering, spelling, source proof, clamp, mode, modifier and reader refusals of v_min3_f16 and v_max3_f16.""" + check_f16_minmax3_reference() + check_f16_minmax3_mutation_coverage() + prefix = ["v_mov_b32_e32 v18, 0x3555bc00", "v_mov_b32_e32 v19, 0xd1a73c00", + "v_mov_b32_e32 v20, 0x42480000", "s_mov_b32 s60, 0x35550400", "s_mov_b32 s61, 0xd1a73c00"] + helpers = {"min3": "f16_min3_bits(", "max3": "f16_max3_bits("} + + def program(*lines): + return uncompressed_export([*prefix, *lines]) + + def refuse(line, message, translator=translate_f16): + expect_value_error(translator, program(line), message) + + # Lowering and spelling: the bare and _e64 spellings are one VOP3 lowering; clamp selects the clamp in the helper. + for op in F16_MINMAX3_OPS: + spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18, v19, v20")) for suffix in ("", "_e64")] + assert spelled[0] == spelled[1], op + body = spelled[0].split("uint4 main", 1)[1] + assert helpers[op] + "hf" in body and ", false));" in body, (op, body) + clamped = translate_f16(program(f"v_{op}_f16 v24, v18, v19, v20 clamp")).split("uint4 main", 1)[1] + assert helpers[op] + "hf" in clamped and ", true));" in clamped, (op, clamped) + assert f"uint f16_minmax2_bits(" in spelled[0] and helpers[op][:-1] in spelled[0], op + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, (op, forbidden) + # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals, in every source position. + tokens = [*pixel_aot.INLINE_F16, "0", "0x3555", "0x7bff", "0x8000", "0xfbff"] + for op in F16_MINMAX3_OPS: + for token in tokens: + for position in range(3): + sources = ["v18", "v19", "v20"] + sources[position] = token + translate_f16(program(f"v_{op}_f16 v24, {sources[0]}, {sources[1]}, {sources[2]}")) + translate_f16(program(f"v_{op}_f16_e64 v24, {sources[0]}, {sources[1]}, {sources[2]} clamp")) + translate_f16(program(f"v_{op}_f16 v24, s60, v19, s61")) + translate_f16(program("v_mov_b32_e32 v21, v18", f"v_{op}_f16 v24, v21, v19, v20")) + translate_f16(program("s_mov_b32 s61, s60", f"v_{op}_f16 v24, s61, v19, v20")) + # A result is one source and stays a proven binary16 value for a later ternary op or a reader. + translate_f16(program("v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v24, v19, v20", + "v_min3_f16 v26, v25, 0x3c00, 0", "v_cvt_f32_f16_e32 v12, v26")) + translate_f16(program("v_max3_f16 v24, v18, v19, v20 clamp", "v_min3_f16 v25, v24, 1.0, -2.0 clamp")) + # Entry profile: unknown or an unsupported declaration refuses every spelling. + for op in F16_MINMAX3_OPS: + for suffix in ("", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_{op}_f16{suffix} v24, v18, v19, v20"), + "binary16 denormal mode unknown at entry") + for state in ("flush", "ftz", "", False): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, + half_denorm=state), program("v_min3_f16 v24, v18, v19, v20"), + "Invalid binary16 denormal entry state") + # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. + for op in F16_MINMAX3_OPS: + for lines, token in (([f"v_{op}_f16 v24, s44, v19, v20"], "s44"), + ([f"v_{op}_f16 v24, v18, v30, v20"], "v30"), + ([f"v_{op}_f16_e64 v24, v18, v19, v12"], "v12")): + expect_value_error(translate_f16, program(*lines), f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v21, s44", f"v_{op}_f16 v24, v21, v19, v20"), + "binary16 operand lacks a finite proof: v21") + expect_value_error(translate_f16, program("v_add_nc_u16 v21, v18, v19", f"v_{op}_f16 v24, v21, v19, v20"), + "binary16 operand lacks a finite proof: v21") + # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. + for op in F16_MINMAX3_OPS: + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"binary16 operand is not finite: {token}") + refuse(f"v_{op}_f16 v24, v18, v19, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_{op}_f16 v24, {token}, v19, v20")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v21, 0x7e00", f"v_{op}_f16 v24, v18, v21, v20"), + "binary16 operand is not finite: v21") + # Source modifiers, integer inline constants, floats and other operands. + for op in F16_MINMAX3_OPS: + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"Unsupported binary16 operand {token}") + refuse(f"v_{op}_f16 v24, 0x10000, v19, v20", "16-bit literal out of range: 0x10000") + refuse(f"v_{op}_f16 v256, v18, v19, v20", "Register out of range: v256") + refuse(f"v_{op}_f16 v24, v256, v19, v20", "Register out of range: v256") + refuse(f"v_{op}_f16 v24, v18, v19, s106", "Register out of range: s106") + # Unmodelled encodings and modifiers fall through to the generic refusal; med3 is a separate slice. + for op in F16_MINMAX3_OPS: + for line in (f"v_{op}_f16_e32 v24, v18, v19, v20", f"v_{op}_f16_dpp v24, v18, v19, v20 quad_perm:[0,1,2,3] " + "row_mask:0xf bank_mask:0xf", f"v_{op}_f16_sdwa v24, v18, v19, v20 dst_sel:DWORD " + "dst_unused:UNUSED_PAD src0_sel:WORD_0", f"v_{op}_f16 v24, v18, v19, v20 op_sel:[0,0,0,1]", + f"v_{op}_f16 v24, v18, v19, v20 mul:2", f"v_{op}_f16 v24, v18, v19, v20 div:2", + f"v_{op}_f16 v24, v18, v19, v20 clamp op_sel:[0,0,0,1]", + f"v_{op}_f16 v24, v18, v19", f"v_{op}_f16 v24, v18, v19, v20, v21", f"v_{op}_f16 v24"): + refuse(line, "Unsupported instruction") + refuse("v_med3_f16 v24, v18, v19, v20", "Unsupported instruction") + + # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. + def float_f16(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, + half_denorm=pixel_aot.HALF_DENORM_PRESERVE) + + base = with_constants([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(float_f16, base[:load + 1] + ["v_min3_f16 v24, s44, v19, v20"] + base[load + 1:], + "Constant read before load completion") + expect_value_error(float_f16, base[:sample + 1] + ["v_max3_f16 v12, 1.0, 2.0, 4.0"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(float_f16, base[:sample + 1] + ["v_min3_f16 v24, v12, 1.0, 2.0"] + base[sample + 1:], + "Sample used before vmcnt wait") + float_f16(base[:sample + 1] + ["v_max3_f16 v20, 1.0, 2.0, 4.0"] + base[sample + 1:]) + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(float_f16, base[:masked] + ["v_min3_f16 v24, 1.0, 2.0, 4.0"] + base[masked:], + "Invalid binary16 ternary operation") + # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. + for op in F16_MINMAX3_OPS: + for spelling in (f"v_{op}_f16", f"v_{op}_f16_e64"): + line = f"{spelling} v24, v18, v19, v20" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + # Readers. The audited ones read a ternary result; every other reader of the tag refuses it. + produced = [*prefix, "v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v18, v19, v20 clamp"] + for register in (24, 25): + for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", + f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v{register} {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + (f"v_mov_b32_e32 v12, v{register}", "Expected a numeric register"), + (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) + # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer # reader: a runtime i16 source needs no proof (every i16 is finite) but its result carries no known value; a u16 source must @@ -21783,6 +22177,7 @@ def _check_controls_inline(directory): "check_f16_rcp_sqrt_controls", "check_f16_rsq_exp_controls", "check_f16_log_trig_controls", + "check_f16_minmax3_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -21794,6 +22189,7 @@ def _check_controls_inline(directory): "check_f16_rcp_sqrt_controls", "check_f16_rsq_exp_controls", "check_f16_log_trig_controls", + "check_f16_minmax3_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -28991,6 +29387,50 @@ def case(kind, index, tag): "binary16 operand lacks a finite proof: s44") +def check_f16_minmax3_draw(directory, compiler, renderer, backend): + """v_min3_f16 and v_max3_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. + + Two main programs run eight triples through both ops and pack two results per word in a rotation of the bare and + _e64 spellings and VGPR/SGPR operand banks; one clamp program runs four triples with clamp; one inline program + proves every source as a binary16 inline constant or 16-bit literal. Two chain programs feed a min3 or max3 + result into the next op and two reader programs read both results through the four audited readers. Four + deviations must each mismatch (one batch per mutation; the statuses are printed): the two operations swapped, a + signed comparison of the raw halves instead of the sign-magnitude key, the clamp dropped, and a source read from + bits 31:16. A source nothing proves is refused at translation. + + Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's + high half is not measured here; the source-high mutation is the high-half control for the sources. + """ + check_f16_minmax3_mutation_coverage() + source = directory / "f16_minmax3.hlsl" + shader = directory / "f16_minmax3.cso" + constants = bytes(256) + + def build(text): + source.write_text(text, encoding="ascii") + compile_shader(compiler, source, shader) + + def case(kind, index, tag): + path = directory / f"f16_minmax3-{tag}-{kind}-{index}.case" + write_case(path, constants, tuple(as_float(word) for word in f16_minmax3_expected(kind, index)), integer_rt=True) + return path + + programs = {key: f16_minmax3_program(*key) for key in F16_MINMAX3_PROGRAMS} + for key in F16_MINMAX3_PROGRAMS: + build(translate_f16(programs[key])) + run_pixel_batch(renderer, backend, shader, [(case(*key, "ref"), "pass")]) + for mutation in F16_MINMAX3_MUTATIONS: + key = f16_minmax3_detecting_program(mutation) + build(f16_minmax3_mutated(mutation, programs[key])) + statuses, _ = run_pixel_batch_statuses(renderer, backend, shader, [case(*key, "mut")]) + print(f"f16_minmax3 mutation {mutation}: program {key} statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"Mutating {mutation} escaped detection") + for op in F16_MINMAX3_OPS: + expect_value_error(translate_f16, uncompressed_export([f"v_{op}_f16 v24, s44, 1.0, 2.0"]), + "binary16 operand lacks a finite proof: s44") + + def check_f16_fmac_ldexp_draw(directory, compiler, renderer, backend): """v_fmac_f16 and v_ldexp_f16 against the independent Python reference: 24 baked fused multiply-accumulate rows (cancellation, rows where rounding the product first gives another result, signed zero results, ties into the @@ -29252,7 +29692,7 @@ def main(): "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-cmpx-e64", "draw-cmpx-sdwa", "draw-scc-skip", "draw-s-call", "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", - "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "draw-f16-log-trig", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", + "draw-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "draw-f16-log-trig", "draw-f16-minmax3", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, @@ -29292,6 +29732,7 @@ def main(): "draw-f16-rcp-sqrt": check_f16_rcp_sqrt_draw, "draw-f16-rsq-exp": check_f16_rsq_exp_draw, "draw-f16-log-trig": check_f16_log_trig_draw, + "draw-f16-minmax3": check_f16_minmax3_draw, "draw-f16-fmac-ldexp": check_f16_fmac_ldexp_draw, "draw-f16-cvt-int16": check_f16_cvt_int16_draw, "draw-f16-to-int16": check_f16_to_int16_draw, diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index ceb477dd1f..73a0fe6ee3 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6340,7 +6340,8 @@ def test_binary16_e64_scanner_translator_agreement(self): import pixel_aot from pixel_aot_check import uncompressed_export - prelude = ["s_mov_b32 s60, 0x3c00", "v_mov_b32_e32 v18, 0x3c00", "v_mov_b32_e32 v19, 0x4000"] + prelude = ["s_mov_b32 s60, 0x3c00", "v_mov_b32_e32 v18, 0x3c00", "v_mov_b32_e32 v19, 0x4000", + "v_mov_b32_e32 v20, 0xb800"] def translator_accepts(line): program = uncompressed_export([*prelude, line, "v_cvt_f32_f16_e32 v12, v24"]) @@ -6362,6 +6363,11 @@ def translator_accepts(line): for op in ("rcp", "sqrt", "rsq", "exp", "log", "sin", "cos"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] + for op in ("min3", "max3"): + accepted += [f"v_{op}_f16 v24, v18, v19, v20", f"v_{op}_f16_e64 v24, v18, v19, v20", + f"v_{op}_f16 v24, v18, v19, v20 clamp", f"v_{op}_f16_e64 v24, s60, v19, v20", + f"v_{op}_f16 v24, 1.0, v19, v20", f"v_{op}_f16 v24, v18, 0.5, -2.0", + f"v_{op}_f16 v24, v18, v19, 0x3555 clamp"] refused = [ "v_add_f16_e64 v24, -v18, v19", "v_add_f16_e64 v24, v18, -v19", "v_add_f16_e64 v24, |v18|, v19", "v_add_f16_e64 v24, abs(v18), v19", "v_add_f16_e64 v24, neg(v18), v19", @@ -6384,6 +6390,12 @@ def translator_accepts(line): "v_sin_f16_e64 v24, v18 mul:2", "v_sin_f16_e64 v24, 3", "v_sin_f16_e64 v24, 0x10000", "v_cos_f16_e64 v24, -v18", "v_cos_f16_e64 v24, |v18|", "v_cos_f16_e64 v24, v18 clamp", "v_cos_f16_e64 v24, v18 mul:2", "v_cos_f16_e64 v24, 3", "v_cos_f16_e64 v24, 0x10000", + "v_min3_f16_e32 v24, v18, v19, v20", "v_max3_f16_e32 v24, v18, v19, v20", + "v_min3_f16 v24, -v18, v19, v20", "v_max3_f16 v24, |v18|, v19, v20", + "v_min3_f16 v24, v18, v19, v20 mul:2", "v_max3_f16 v24, v18, v19, v20 div:2", + "v_min3_f16 v24, v18, v19, v20 op_sel:[0,0,0,1]", "v_max3_f16 v24, 3, v19, v20", + "v_min3_f16 v24, v18, v19, 0x10000", "v_max3_f16 v256, v18, v19, v20", + "v_med3_f16 v24, v18, v19, v20", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 14e0061683..c526a27367 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1090,6 +1090,34 @@ def check_vopc_e32_dst(enc, dst): " return asuint(int(exp) - 126);\n" "}" ), + # The direct compute v_min3_f16/v_max3_f16 order key, x ^ (x >= 0x8000 ? 0xffff : 0x8000): it sorts -0.0h + # below +0.0h and every negative encoding below every positive one, and the pair selects whole source bits so + # the ternary forms need no rounding. clamp maps a negative result (including -0.0h) to +0 and a result above + # 0x3bff to 1.0h; the NaN test mirrors the direct compute block even though the finite source proof excludes it. + "f16_minmax2_bits": ( + "uint f16_minmax2_bits(uint a, uint b, bool is_max) {\n" + " a &= 0xffffu; b &= 0xffffu;\n" + " uint ka = (a & 0x8000u) != 0u ? (~a & 0xffffu) : (a ^ 0x8000u);\n" + " uint kb = (b & 0x8000u) != 0u ? (~b & 0xffffu) : (b ^ 0x8000u);\n" + " return (is_max ? (ka > kb) : (ka < kb)) ? a : b;\n" + "}" + ), + "f16_min3_bits": ( + "uint f16_min3_bits(uint a, uint b, uint c, bool clamp_result) {\n" + " uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, false), c, false);\n" + " if (!clamp_result) return result;\n" + " if ((result & 0x7fffu) > 0x7c00u || (result & 0x8000u) != 0u) return 0u;\n" + " return result > 15359u ? 15360u : result;\n" + "}" + ), + "f16_max3_bits": ( + "uint f16_max3_bits(uint a, uint b, uint c, bool clamp_result) {\n" + " uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, true), c, true);\n" + " if (!clamp_result) return result;\n" + " if ((result & 0x7fffu) > 0x7c00u || (result & 0x8000u) != 0u) return 0u;\n" + " return result > 15359u ? 15360u : result;\n" + "}" + ), "f16_min_bits": ( "uint f16_min_bits(uint a, uint b) {\n" " int sa = (a & 0x8000u) != 0u ? -int(a & 0x7fffu) : int(a & 0x7fffu);\n" @@ -1693,6 +1721,9 @@ def check_vopc_e32_dst(enc, dst): "min3_i16": "min3_i16", "min3_u16": "min3_u16", "max3_i16": "max3_i16", "max3_u16": "max3_u16", "med3_i16": "med3_i16", "med3_u16": "med3_u16", } +# Plain VOP3 binary16 three-operand minimum and maximum. LLVM 15 prints these VOP3-only forms without an encoding +# suffix; the low halves of the three finite sources are compared and one whole source encoding is selected. +VOP3_F16_MINMAX3 = ("min3", "max3") # Quad-local DPP16/DPP8 extra f32, carry-in/carry-out, and dot-accumulate ops. # Tuple fields: (kind, allow_fp_mods, helper_name) @@ -2074,6 +2105,35 @@ def f16_minmax_result(name, b0, b1): return (b0 if s0 < s1 else b1) if name == "min" else (b0 if s0 > s1 else b1) +def f16_minmax3_result(name, b0, b1, b2, *, clamp=False): + """Exact binary16 result bits of v_min3_f16 or v_max3_f16 on three finite operands. + + Follows the direct compute block without a floating-point conversion: the unsigned sign-magnitude key + x ^ (x >= 0x8000 ? 0xffff : 0x8000) orders -0.0h below +0.0h, min3 and max3 fold the pair twice, and a tie keeps + the second operand as the select does. clamp maps a negative result (including -0.0h) to +0.0h and a result + above 0x3bff to 1.0h (0x3c00). Unlike the two-operand helpers, opposite-signed zeros are part of the semantics. + """ + if name not in ("min3", "max3"): + raise ValueError(f"Unknown binary16 ternary min/max: {name}") + if any((bits >> 10) & 0x1f == 0x1f for bits in (b0, b1, b2)): + raise ValueError(f"binary16 operand is not finite: v_{name}_f16") + + def key(bits): + return (bits ^ 0xffff) if bits & 0x8000 else (bits ^ 0x8000) + + def pick(x, y): + kx, ky = key(x), key(y) + return x if (kx > ky if name == "max3" else kx < ky) else y + + result = pick(pick(b0 & 0xffff, b1 & 0xffff), b2 & 0xffff) + if clamp: + if (result & 0x7fff) > 0x7c00 or result & 0x8000: + return 0 + if result > 0x3bff: + return 0x3c00 + return result + + def f16_fract_result(bits): """Exact binary16 result bits of v_fract_f16 (x - floor(x)) on a finite operand. @@ -8329,6 +8389,32 @@ def known_sample_float(reg): lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result + elif m := match(r"v_(min3|max3)_f16(?:_e64)? (v\d+), ([^,\s]+), ([^,\s]+), ([^,\s]+?)( clamp)?"): + # Plain VOP3 binary16 three-operand minimum and maximum. These are the only VOP3 spellings: an _e32 suffix, + # DPP, SDWA, op_sel and omod never match the anchored operands and fall through to the generic refusal. + # All three sources must have a statically proven finite low half (half16_arith_source), clamp is accepted, + # and the result is exactly one of the sources with no rounding. The helper applies the direct compute + # sign-magnitude order and clamp rule, and the result stays a proven value for a later binary16 op. + name, dst, *tokens, clamp = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 ternary operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + words, proven = zip(*(half16_arith_source(tok, scalar, vector, pending, sample_dest, known_ssa_bits, + known_half) for tok in tokens)) + result = f16_minmax3_result(name, *proven, clamp=bool(clamp)) + helper = f"f16_{name}_bits" + helpers.update(("f16_minmax2_bits", helper)) + for k, word in enumerate(words): + lines.append(f" uint hf{i}_{k} = ({word}) & 0xffffu;") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1, hf{i}_2, " + f"{'true' if clamp else 'false'}));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result elif m := match(r"v_fract_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): # Plain e32/e64 binary16 fractional part (x - floor(x)) under the exact finite-proof contract. encoding, dst, token = m.groups() diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 06a6b14fab..67272b8022 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -82,6 +82,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: PIXEL_INLINE_F16 = tuple(pixel_aot.INLINE_F16) if pixel_aot is not None else () PIXEL_VCC = r"(?:vcc(?:_lo)?)" PIXEL_VOP3_INT16_TERNARY = pixel_aot.VOP3_INT16_TERNARY if pixel_aot is not None else {} +PIXEL_VOP3_F16_MINMAX3 = tuple(pixel_aot.VOP3_F16_MINMAX3) if pixel_aot is not None else () PIXEL_LANE_MASK = pixel_aot.LANE_MASK if pixel_aot is not None else r"(?:vcc(?:_lo)?|s\d+|s\[\d+:\d+\])" # Explicit _e32 VOPC writes VCC only; suffix-less and _e64 may name an SGPR destination. PIXEL_VOPC_DST = rf"(?:_e32\s+{PIXEL_VCC}|(?:_e64)?\s+{PIXEL_LANE_MASK})" @@ -335,6 +336,13 @@ def lower_rejection_causes(results: list[dict]) -> dict: rf"v_(?:{'|'.join(map(re.escape, PIXEL_VOP3_INT16_TERNARY))})(?:_e64)?\s+{INT16_VGPR}," rf"\s+{INT16_SOURCE},\s+{INT16_SOURCE},\s+{INT16_SOURCE}" ) +# Plain VOP3 binary16 minimum and maximum of three finite sources; pixel_aot also proves each low half and accepts +# the optional clamp, while e32, DPP, SDWA, op_sel and omod stay unsupported here. +if PIXEL_VOP3_F16_MINMAX3: + SUPPORTED_INSTRUCTIONS_REGEX.append( + rf"v_(?:{'|'.join(map(re.escape, PIXEL_VOP3_F16_MINMAX3))})_f16(?:_e64)?\s+{INT16_VGPR}," + rf"\s+{F16_ARITH_SOURCE},\s+{F16_ARITH_SOURCE},\s+{F16_ARITH_SOURCE}(?: clamp)?" + ) # 64-bit VOP3 shifts (issue #928): a VGPR-pair destination, a 32-bit amount (VGPR, SGPR, inline integer or # literal) and a 64-bit value (VGPR pair, SGPR pair, inline integer or 32-bit hex literal), with at most one SGPR or literal source. # This matches syntax only; pixel_aot also checks the pair ranges and that the sources are tracked. @@ -468,6 +476,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: | {f"v_{name}" for name in PIXEL_VOP3_INT16_TERNARY} | {f"v_{name}_f16" for name in PIXEL_VOP2_F16 + PIXEL_VOP2_F16_FUSED_SCALE + PIXEL_VOP1_F16_ROUND + PIXEL_VOP1_F16_UNARY} + | {f"v_{name}_f16" for name in PIXEL_VOP3_F16_MINMAX3} | {"v_cvt_f16_i16", "v_cvt_f16_u16"} | { # Decoding only: the tables above cover the binary16 VOP1/VOP2 forms a translator lowers. From daa40d9cdc559898ba044d30a41b8693c8b1634b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 08:56:01 +0000 Subject: [PATCH 5/5] shader: lower binary16 VOP3 three-way median --- docs/experiments.md | 4 +- tests/form_coverage_check.py | 13 +-- tests/pixel_aot_check.py | 171 ++++++++++++++++++++++-------- tests/rdna2_tools_check.py | 10 +- tools/pixel_aot.py | 75 ++++++++----- tools/scan_unsupported_shaders.py | 12 +-- 6 files changed, 197 insertions(+), 88 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 4d11c97847..6c17086a23 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9009,9 +9009,9 @@ The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operan Plain binary16 `VOP1` logarithm, sine and cosine (issue #839) `v_log_f16`, `v_sin_f16` and `v_cos_f16`, in the unsuffixed, `_e32` and `_e64` spellings, extend the unary entry above. The low half is widened exactly with `widen16`; `v_log_f16` evaluates the direct compute path's `log2` (`unary.f32` opcode 23), while `v_sin_f16` and `v_cos_f16` use the same turn reduction as `trig_turns` (subtract `Round_ne` in binary32, keep a zero angle's sign, select the exact zero at half a turn for sin and a quarter turn for cos, then multiply by the binary32 2*pi constant and evaluate the intrinsic). `narrow16` rounds once, then the RDNA 2 special results are selected from the source half: log keeps `+infinity`, maps every NaN and negative nonzero source to `0x7e00` and either zero to `-infinity` (`0xfc00`); sin and cos map an infinity or NaN magnitude to `0x7e00`, and sin preserves `-0`. The emitter carries the 73 log midpoint corrections of `log_f16_midpoints` (regenerated and checked by `tests/f16_log_midpoints.py`) as `LOG_F16_MIDPOINTS`, and the helpers `f16_log_result`, `f16_sin_result` and `f16_cos_result`. The translator tracks each result with `f16_log_trig_result`: log returns the table entry or rounds the exact log2 of every other positive finite source with a 90-digit Decimal reference, and sin/cos reproduce the turn reduction and host intrinsic in binary32. Every encoding has a modelled result, so None is never returned today; the signature keeps that contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the unary forms above, and the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused. The controls (`check_f16_log_trig_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, pin `LOG_F16_MIDPOINTS` to the C++ array through `tests/f16_log_midpoints.py check_cpp_table`, and compare the reference with `f16_log_trig_result` on all 65,536 encodings of all three ops. The draw (`tests/pixel_aot_check.py draw-f16-log-trig`, tests `pixel_aot_f16_log_trig_hardware` and `pixel_aot_f16_log_trig_warp`, 60 s limit, capability skip 77) runs nine baked programs, three per op, over 24 values each in a rotation of e32, e64, SGPR and literal forms, packs two results per word with SDWA `WORD_0` and `WORD_1`, and adds two chains (`log2(log2(x))` and `cos(sin(x))`). The values cover exact powers and whole turns, inexact results, both signed zeros, subnormals, the largest finite half, negative sources, the `log2(1)` row, the exact zero turns of sin and cos, and three log midpoint-table rows; the inexact sin and cos values keep the binary32 result at least 5e-5 from a binary16 rounding midpoint, except the exact selected zeros. The lossless `R32G32B32A32_UINT` readback is compared with `f16_log_trig_reference`, a 90-digit or host-intrinsic reference without `pixel_aot`. Five deviations must each mismatch, one batch per mutation with the statuses printed: the mnemonic cycled, a source read from bits 31:16, the `1 + ulp` midpoint correction off by one encoding, `log2` replaced by the natural log, and the exact zero selections dropped. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_log_trig_forms` pins the six newly covered forms (log, sin and cos, each e32 and e64) and leaves the DPP and SDWA neighbours uncovered; the six forms take the measured totals from 1550/1968 and 1541/1863 to 1556/1968 and 1547/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D Log error window beyond the modelled midpoint corrections and the exact reference, the D3D Sin/Cos error beyond the chosen midpoint margin, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, and whether any title executes these paths. -Plain binary16 `VOP3` three-operand minimum and maximum (issue #839), `v_min3_f16` and `v_max3_f16`, in the unsuffixed and `_e64` spellings, extend the binary16 entries above. These are VOP3-only forms and LLVM 15 prints no encoding suffix for them. The lowering follows the direct compute block in `src/gfx1013_direct_compute.inl`: the three finite low halves are ordered by the unsigned sign-magnitude key `x ^ (x >= 0x8000 ? 0xffff : 0x8000)`, so `-0.0h` sorts below `+0.0h` and every negative finite value below every positive one; `v_min3_f16` folds the pair with `false` and `v_max3_f16` with `true`, and the result is one whole source encoding, so no rounding occurs. `clamp` maps a negative result, including `-0.0h`, to `+0.0h` and a result above `0x3bff` to `1.0h` (`0x3c00`). The emitted helpers are `f16_minmax2_bits`, `f16_min3_bits` and `f16_max3_bits`, and the translator tracks the exact bits with `f16_minmax3_result` so a result stays a proven source for a later binary16 op. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. An `_e32` suffix, DPP, SDWA, `op_sel`, `mul:`, `div:`, source modifiers, non-finite encodings and the neighbouring `v_med3_f16` stay refused; the exact messages are the shared binary16 source, range and modifier refusals plus `Invalid binary16 ternary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. +Plain binary16 `VOP3` three-operand minimum, maximum and median (issue #839), `v_min3_f16`, `v_max3_f16` and `v_med3_f16`, in the unsuffixed and `_e64` spellings, extend the binary16 entries above. These are VOP3-only forms and LLVM 15 prints no encoding suffix for them. The lowering follows the direct compute block in `src/gfx1013_direct_compute.inl`: the three finite low halves are ordered by the unsigned sign-magnitude key `x ^ (x >= 0x8000 ? 0xffff : 0x8000)`, so `-0.0h` sorts below `+0.0h` and every negative finite value below every positive one; `v_min3_f16` folds the pair with `false`, `v_max3_f16` with `true`, and `v_med3_f16` evaluates `max(min(a, b), min(max(a, b), c))`. The result is one whole source encoding, so no rounding occurs. `clamp` maps a negative result, including `-0.0h`, to `+0.0h` and a result above `0x3bff` to `1.0h` (`0x3c00`). The emitted helpers are `f16_minmax2_bits`, `f16_minmax3_clamp`, `f16_min3_bits`, `f16_max3_bits` and `f16_med3_bits`, and the translator tracks the exact bits with `f16_minmax3_result` so a result stays a proven source for a later binary16 op. Sources must be statically proven finite (binary16 inline constants, `0`, a 16-bit literal, a tracked SGPR, a VGPR copy, or an earlier accepted binary16 result), `lower(..., half_denorm="preserve")` must declare the entry state, the destination is limited to `v0` through `v255` and may not overlap an outstanding sample, and the result is tagged `("half16", alu)`. An `_e32` suffix, DPP, SDWA, `op_sel`, `mul:`, `div:`, source modifiers and non-finite encodings stay refused; the exact messages are the shared binary16 source, range and modifier refusals plus `Invalid binary16 ternary operation` outside the entry mask and `Unsupported instruction` for the unmodelled forms. -The controls (`check_f16_minmax3_controls`, no GPU) cover every spelling, operand kind, the clamp, the proof, modifier, mode, scheduling and reader refusals and chains of both operations, and compare the independent Python reference with `f16_minmax3_result` on every finite encoding of the first source, on every triple of a 16-value special set and on a deterministic 20,000-triple sample. The draw (`tests/pixel_aot_check.py draw-f16-minmax3`, tests `pixel_aot_f16_minmax3_hardware` and `pixel_aot_f16_minmax3_warp`, 60 s limit, capability skip 77) runs two main programs over eight triples with both ops in a rotation of the bare and `_e64` spellings and VGPR/SGPR operand banks, one clamp program over four triples, one inline program whose every source is a binary16 inline constant or 16-bit literal, two chains where a min3 or max3 result feeds the next op, and two reader programs through the four audited readers; two results are packed per word with SDWA `WORD_0` and `WORD_1`. The triples cover three distinct values, negative values, equalities, `-0` against `+0`, the largest finite halves and the clamp boundaries. The lossless `R32G32B32A32_UINT` readback is compared with `f16_minmax3_reference`, a reference without `pixel_aot` that folds the sign-magnitude key and applies the clamp. Four deviations must each mismatch, one batch per mutation with the statuses printed: the two operations swapped, a signed comparison of the raw halves, the clamp dropped, and a source read from bits 31:16. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_minmax3_forms` pins the two newly covered forms (`v_min3_f16` and `v_max3_f16`, both `VOP3`) and leaves `v_med3_f16` uncovered; the two forms add two to each reference, taking the stack totals from 1556/1968 and 1547/1863 to 1558/1968 and 1549/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN and infinity sources (refused before lowering), NaN payloads, runtime sources, the DPP, SDWA and `op_sel` spellings, `v_med3_f16`, and whether any title executes these paths. +The controls (`check_f16_minmax3_controls`, no GPU) cover every spelling, operand kind, the clamp, the proof, modifier, mode, scheduling and reader refusals and chains of all three operations, and compare the independent Python reference with `f16_minmax3_result` on every finite encoding of the first source, on every triple of a 16-value special set and on a deterministic 20,000-triple sample. The draw (`tests/pixel_aot_check.py draw-f16-minmax3`, tests `pixel_aot_f16_minmax3_hardware` and `pixel_aot_f16_minmax3_warp`, 60 s limit, capability skip 77) runs two main programs over eight triples with min3 and max3 in a rotation of the bare and `_e64` spellings and VGPR/SGPR operand banks, one clamp program over four triples, one inline program whose every source is a binary16 inline constant or 16-bit literal, two median programs over four triples each (unclamped then clamped, one widened result per word), two chains where a ternary result feeds the next op, and two reader programs through the four audited readers; the min3/max3 results are packed two per word with SDWA `WORD_0` and `WORD_1`. The triples cover three distinct values, negative values, equalities, `-0` against `+0`, the largest finite halves, the median of each mixed-sign triple and the clamp boundaries. The lossless `R32G32B32A32_UINT` readback is compared with `f16_minmax3_reference`, a reference without `pixel_aot` that folds the sign-magnitude key, the median formula and the clamp. Seven deviations must each mismatch, one batch per mutation with the statuses printed: min3 and max3 swapped, a signed comparison of the raw halves, the full key order reversed, the clamp dropped, a source read from bits 31:16, med3 replaced by min3, and med3 replaced by max3. A full key reversal leaves an odd-count median unchanged, so that deviation is detected by the min3/max3 programs; the signed comparison changes the median programs too. A source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_minmax3_forms` pins the three newly covered forms (`v_min3_f16`, `v_max3_f16` and `v_med3_f16`, all `VOP3`); the three forms add three to each reference, taking the stack totals from 1556/1968 and 1547/1863 to 1559/1968 and 1550/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN and infinity sources (refused before lowering), NaN payloads, runtime sources, the DPP, SDWA and `op_sel` spellings, and whether any title executes these paths. Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 0d33660049..5a0a9f5569 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -794,25 +794,22 @@ def check_f16_log_trig_forms(): def check_f16_minmax3_forms(): - """The two plain VOP3 binary16 three-operand min/max forms count as covered once the translator accepts their - fixtures; the med3 neighbour stays uncovered.""" + """The three plain VOP3 binary16 three-operand min/max/med3 forms count as covered once the translator accepts + their fixtures.""" import pixel_aot_check as pixel saved = set(pixel.ACCEPTED) pixel.ACCEPTED.clear() try: for key in pixel.F16_MINMAX3_PROGRAMS: pixel.translate_f16(pixel.f16_minmax3_program(*key)) - forms = {("VOP3", "v_min3_f16"), ("VOP3", "v_max3_f16")} - assert len(forms) == 2 - neighbours = {("VOP3", "v_med3_f16")} + forms = {("VOP3", "v_min3_f16"), ("VOP3", "v_max3_f16"), ("VOP3", "v_med3_f16")} + assert len(forms) == 3 for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) assert forms <= reference, (name, sorted(forms - reference)) - assert neighbours <= reference, (name, sorted(neighbours - reference)) covered = fc.gfx_forms(pixel.ACCEPTED, reference) assert forms <= covered, (name, sorted(forms - covered)) - assert not neighbours & covered, (name, sorted(neighbours & covered)) - # Without the fixtures none of the two forms is covered. + # Without the fixtures none of the three forms is covered. pixel.ACCEPTED.clear() for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): pixel.translate_f16(pixel.uncompressed_export(body)) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index b0fc02066c..f6f5c4cb2b 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -7763,8 +7763,12 @@ def refuse(line, message): # The two-operand forms keep their operand count; the neighbours that stay unsupported are still refused. refuse("v_add_nc_u16 v24, v18, v19, v20", "Wrong 16-bit integer operand count for v_add_nc_u16") for line in ("v_mad_u32_u16 v24, v18, v19, v20", "v_mad_i32_i16 v24, v18, v19, v20", - "v_med3_f16 v24, v18, v19, v20", "v_mad_f16 v24, v18, v19, v20"): + "v_mad_f16 v24, v18, v19, v20"): refuse(line, "Unsupported instruction") + # v_med3_f16 is an accepted binary16 ternary op now, so without the entry profile it stops on the mode check + # before the integer path. + expect_value_error(translate_int, uncompressed_export([*prefix, "v_med3_f16 v24, v18, v19, v20"]), + "binary16 denormal mode unknown at entry") sample = next(i for i, line in enumerate(with_constants([])) if line.startswith("image_sample")) overlap = with_constants([]) overlap.insert(sample + 1, "v_mad_u16 v12, 1, 2, 3") @@ -18891,12 +18895,14 @@ def float_f16(instructions): expect_value_error(translate_f16, program(*produced, line), message) -# Plain VOP3 binary16 three-operand minimum and maximum (issue #839): v_min3_f16 and v_max3_f16. The direct compute -# path orders the encodings with the unsigned sign-magnitude key x ^ (x >= 0x8000 ? 0xffff : 0x8000), so -0.0h sorts -# below +0.0h and every negative below every positive value, and it selects one whole source: there is no rounding. -# clamp maps a negative result (including -0.0h) to +0.0h and a result above 0x3bff to 1.0h (0x3c00). The translator -# refuses every source whose finite proof fails and every encoding other than the plain VOP3 one. +# Plain VOP3 binary16 three-operand minimum, maximum and median (issue #839): v_min3_f16, v_max3_f16 and +# v_med3_f16. The direct compute path orders the encodings with the unsigned sign-magnitude key +# x ^ (x >= 0x8000 ? 0xffff : 0x8000), so -0.0h sorts below +0.0h and every negative below every positive value, +# and it selects one whole source: there is no rounding. clamp maps a negative result (including -0.0h) to +0.0h +# and a result above 0x3bff to 1.0h (0x3c00). The translator refuses every source whose finite proof fails and every +# encoding other than the plain VOP3 one. F16_MINMAX3_OPS = ("min3", "max3") +F16_MINMAX3_TERNARY_OPS = ("min3", "max3", "med3") F16_MINMAX3_TRIPLES = ( (0xbc00, 0x3c00, 0x0000), # -1, 1, +0 (0xc000, 0xb800, 0xbe00), # -2, -0.5, -1.5 @@ -18919,23 +18925,35 @@ def float_f16(instructions): (0x4400, 0xc400, 0x3bff), # 4, -4, 0x3bff (0x3118, 0x7bff, 0x8000), # 0.15915494, 65504, -0 ) +F16_MINMAX3_MED3_CLAMP_TRIPLES = ( + (0xc000, 0xbc00, 0xbe00), # median -1.5 -> +0 + (0xbc00, 0x3800, 0x3e00), # median 0.5 stays + (0x8000, 0x3c00, 0x4000), # median 1.0 stays + (0x3bff, 0x3c00, 0x3bff), # median 0x3bff stays +) # Chains (a, b, c, d): min3(a, b, c), max3(previous, c, d), min3(c, d, a), clamp(max3(previous, a, d)). F16_MINMAX3_CHAINS = ( (0xbc00, 0x4000, 0x8000, 0x3c00), (0x3c00, 0xc000, 0x3800, 0x3e00), ) -F16_MINMAX3_MUTATIONS = ("ops_swapped", "order_signed", "clamp_removed", "src_high") +F16_MINMAX3_MUTATIONS = ("ops_swapped", "order_signed", "order_reversed", "clamp_removed", "src_high", + "med3_as_min", "med3_as_max") def f16_minmax3_reference(op, word0, word1, word2, *, clamp=False, mutation=None): - """Binary16 result bits of v_min3_f16 or v_max3_f16 on the low halves of three source words. + """Binary16 result bits of v_min3_f16, v_max3_f16 or v_med3_f16 on the low halves of three source words. - The order is the direct compute sign-magnitude key (so -0.0 sorts below +0.0), the operation folds a pair twice, - and clamp maps a negative result to +0 and one above 0x3bff to 1.0. mutation models the draw's deviations: the - operation swapped, a signed comparison of the raw halves, the clamp dropped, or a source read from bits 31:16. + The order is the direct compute sign-magnitude key (so -0.0 sorts below +0.0), min3 and max3 fold a pair twice, + med3 is max(min(a, b), min(max(a, b), c)), and clamp maps a negative result to +0 and one above 0x3bff to 1.0. + mutation models the draw's deviations: min3/max3 swapped, a signed comparison of the raw halves, the full key + order reversed, the clamp dropped, a source read from bits 31:16, or med3 replaced by min3 or max3. """ if mutation == "ops_swapped": - op = "max3" if op == "min3" else "min3" + op = {"min3": "max3", "max3": "min3"}.get(op, op) + elif mutation == "med3_as_min" and op == "med3": + op = "min3" + elif mutation == "med3_as_max" and op == "med3": + op = "max3" def operand(word): return (word >> 16 if mutation == "src_high" else word) & 0xffff @@ -18945,16 +18963,24 @@ def operand(word): def key(bits): return bits ^ (0xffff if bits & 0x8000 else 0x8000) - def pick(x, y): + def choose(x, y, is_max): if mutation == "order_signed": sx = x - 0x10000 if x & 0x8000 else x sy = y - 0x10000 if y & 0x8000 else y - win = sx > sy if op == "max3" else sx < sy + win = sx > sy if is_max else sx < sy + elif mutation == "order_reversed": + win = key(x) < key(y) if is_max else key(x) > key(y) else: - win = key(x) > key(y) if op == "max3" else key(x) < key(y) + win = key(x) > key(y) if is_max else key(x) < key(y) return x if win else y - result = pick(pick(a, b), c) + if op == "min3": + result = choose(choose(a, b, False), c, False) + elif op == "max3": + result = choose(choose(a, b, True), c, True) + else: + lo, hi = choose(a, b, False), choose(a, b, True) + result = choose(lo, choose(hi, c, False), True) if clamp and mutation != "clamp_removed": if result & 0x8000: return 0 @@ -18972,6 +18998,8 @@ def f16_minmax3_token(bits): def f16_minmax3_triples(kind, index): + if kind == "med3": + return F16_MINMAX3_TRIPLES[:4] if index == 0 else F16_MINMAX3_MED3_CLAMP_TRIPLES table = {"main": F16_MINMAX3_TRIPLES, "clamp": F16_MINMAX3_CLAMP_TRIPLES, "inline": F16_MINMAX3_INLINE_TRIPLES, "reader": F16_MINMAX3_TRIPLES}[kind] @@ -19014,6 +19042,20 @@ def f16_minmax3_program(kind, index): for word in range(4): body.append(pack.format(dst=12 + word, src=32 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) body.append(pack.format(dst=12 + word, src=33 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + elif kind == "med3": + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + regs, sgprs = (18 + 3 * slot, 19 + 3 * slot, 20 + 3 * slot), (60 + 3 * slot, 61 + 3 * slot, 62 + 3 * slot) + for k, word in enumerate(f16_minmax3_source_words(triple, index * 12 + 3 * slot)): + body += [f"v_mov_b32_e32 v{regs[k]}, {word:#x}", f"s_mov_b32 s{sgprs[k]}, {word:#x}"] + form = (slot + index) % 4 + sources = {0: (f"v{regs[0]}", f"v{regs[1]}", f"v{regs[2]}"), + 1: (f"v{regs[0]}", f"v{regs[1]}", f"v{regs[2]}"), + 2: (f"s{sgprs[0]}", f"v{regs[1]}", f"s{sgprs[2]}"), + 3: (f"v{regs[0]}", f"s{sgprs[1]}", f"v{regs[2]}")}[form] + line = (f"v_med3_f16{'_e64' if form == 1 else ''} v{40 + slot}, " + f"{sources[0]}, {sources[1]}, {sources[2]}") + body.append(line + (" clamp" if index == 1 else "")) + body += [f"v_cvt_f32_f16_e32 v{12 + k}, v{40 + k}" for k in range(4)] elif kind == "chain": words = f16_minmax3_source_words(F16_MINMAX3_CHAINS[index], index * 4) body += [f"v_mov_b32_e32 v{18 + k}, {word:#x}" for k, word in enumerate(words)] @@ -19046,6 +19088,12 @@ def f16_minmax3_expected(kind, index, mutation=None): if kind in ("main", "clamp", "inline"): results = f16_minmax3_group_results(kind, index, mutation) return tuple(results[2 * w] | results[2 * w + 1] << 16 for w in range(4)) + if kind == "med3": + results = [] + for slot, triple in enumerate(f16_minmax3_triples(kind, index)): + words = f16_minmax3_source_words(triple, index * 12 + 3 * slot) + results.append(f16_minmax3_reference("med3", *words, clamp=index == 1, mutation=mutation)) + return tuple(f16_widen_word(bits) for bits in results) if kind == "reader": results = f16_minmax3_group_results(kind, index, mutation) chosen = [results[(r + index) % 4] for r in range(4)] @@ -19059,7 +19107,8 @@ def f16_minmax3_expected(kind, index, mutation=None): F16_MINMAX3_PROGRAMS = (("main", 0), ("main", 1), ("clamp", 0), ("inline", 0), - ("chain", 0), ("chain", 1), ("reader", 0), ("reader", 1)) + ("med3", 0), ("med3", 1), ("chain", 0), ("chain", 1), + ("reader", 0), ("reader", 1)) def f16_minmax3_mutated(mutation, program): @@ -19074,6 +19123,17 @@ def f16_minmax3_mutated(mutation, program): new = (" return (is_max ? (asint(a << 16) > asint(b << 16)) " ": (asint(a << 16) < asint(b << 16))) ? a : b;") mutated = text.replace(old, new) + elif mutation == "order_reversed": + old = " return (is_max ? (ka > kb) : (ka < kb)) ? a : b;" + new = " return (is_max ? (ka < kb) : (ka > kb)) ? a : b;" + mutated = text.replace(old, new) + elif mutation in ("med3_as_min", "med3_as_max"): + fold = "false" if mutation == "med3_as_min" else "true" + old = (" uint lo = f16_minmax2_bits(a, b, false);\n" + " uint hi = f16_minmax2_bits(a, b, true);\n" + " uint result = f16_minmax2_bits(lo, f16_minmax2_bits(hi, c, false), true);") + new = f" uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, {fold}), c, {fold});" + mutated = text.replace(old, new) elif mutation == "clamp_removed": mutated = text.replace(" if (!clamp_result) return result;", " return result;") else: @@ -19095,22 +19155,31 @@ def check_f16_minmax3_reference(): finite encoding of the first source (the other two fixed) and on every triple of a small special set.""" assert len(F16_MINMAX3_TRIPLES) == 8 and len(set(F16_MINMAX3_TRIPLES)) == 8 assert len(F16_MINMAX3_CLAMP_TRIPLES) == 4 and len(F16_MINMAX3_INLINE_TRIPLES) == 4 + assert len(F16_MINMAX3_MED3_CLAMP_TRIPLES) == 4 for op, triple, expected in ( ("min3", (0xbc00, 0x3c00, 0x0000), 0xbc00), ("max3", (0xbc00, 0x3c00, 0x0000), 0x3c00), ("min3", (0xc000, 0xb800, 0xbe00), 0xc000), ("max3", (0xc000, 0xb800, 0xbe00), 0xb800), ("min3", (0x8000, 0x0000, 0x3c00), 0x8000), ("max3", (0x8000, 0x0000, 0x3c00), 0x3c00), ("min3", (0x3e00, 0x3e00, 0x3e00), 0x3e00), ("max3", (0x3c00, 0x3c00, 0x4000), 0x4000), - ("min3", (0xbc00, 0x3800, 0x3e00), 0xbc00), ("max3", (0x4400, 0x0000, 0x8001), 0x4400)): + ("min3", (0xbc00, 0x3800, 0x3e00), 0xbc00), ("max3", (0x4400, 0x0000, 0x8001), 0x4400), + ("med3", (0xbc00, 0x3c00, 0x0000), 0x0000), ("med3", (0xc000, 0xb800, 0xbe00), 0xbe00), + ("med3", (0x8000, 0x0000, 0x3c00), 0x0000), ("med3", (0x0000, 0x8000, 0xbc00), 0x8000), + ("med3", (0x3e00, 0x3e00, 0x3e00), 0x3e00), ("med3", (0x3c00, 0x3c00, 0x4000), 0x3c00), + ("med3", (0x7bff, 0x3c00, 0x0000), 0x3c00), ("med3", (0xfbff, 0x7bff, 0x0000), 0x0000)): assert f16_minmax3_reference(op, *triple) == expected, (op, triple) assert f16_minmax3_reference("min3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x0000 assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x3c00 assert f16_minmax3_reference("min3", 0x8000, 0x3c00, 0x4000, clamp=True) == 0x0000 assert f16_minmax3_reference("min3", 0x3bff, 0x3c00, 0x3bff, clamp=True) == 0x3bff assert f16_minmax3_reference("max3", 0x3bff, 0x3c00, 0x3bff, clamp=True) == 0x3c00 + assert f16_minmax3_reference("med3", 0xc000, 0xbc00, 0xbe00, clamp=True) == 0x0000 + assert f16_minmax3_reference("med3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x3800 + assert f16_minmax3_reference("med3", 0x8000, 0x3c00, 0x4000, clamp=True) == 0x3c00 + assert f16_minmax3_reference("med3", 0x3bff, 0x3c00, 0x3bff, clamp=True) == 0x3bff for half in range(0x10000): if (half >> 10) & 0x1f == 0x1f: continue - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for clamp in (False, True): ours = f16_minmax3_reference(op, 0xa5c3_0000 | half, 0x1234_bc00, 0x4248_3c00, clamp=clamp) theirs = pixel_aot.f16_minmax3_result(op, half, 0xbc00, 0x3c00, clamp=clamp) @@ -19120,7 +19189,7 @@ def check_f16_minmax3_reference(): for a in specials: for b in specials: for c in specials: - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for clamp in (False, True): ours = f16_minmax3_reference(op, 0x3555_0000 | a, 0xd1a7_0000 | b, 0x4248_0000 | c, clamp=clamp) @@ -19130,11 +19199,11 @@ def check_f16_minmax3_reference(): finite = [bits for bits in range(0x10000) if (bits >> 10) & 0x1f != 0x1f] for _ in range(20_000): a, b, c = (rng.choice(finite) for _ in range(3)) - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for clamp in (False, True): assert f16_minmax3_reference(op, a, b, c, clamp=clamp) == pixel_aot.f16_minmax3_result( op, a, b, c, clamp=clamp), (op, hex(a), hex(b), hex(c), clamp) - assert set(pixel_aot.VOP3_F16_MINMAX3) == {"min3", "max3"} + assert set(pixel_aot.VOP3_F16_TERNARY) == {"min3", "max3", "med3"} def check_f16_minmax3_mutation_coverage(): @@ -19143,21 +19212,33 @@ def check_f16_minmax3_mutation_coverage(): assert len(f16_minmax3_expected(kind, index)) == 4, (kind, index) for mutation in F16_MINMAX3_MUTATIONS: f16_minmax3_detecting_program(mutation) + assert f16_minmax3_detecting_program("med3_as_min")[0] == "med3" + assert f16_minmax3_detecting_program("med3_as_max")[0] == "med3" + assert any(f16_minmax3_expected("med3", i, "order_signed") != f16_minmax3_expected("med3", i) + for i in (0, 1)) + # A full reversal of the key order leaves a median unchanged; the min3/max3 programs detect that deviation. + assert all(f16_minmax3_expected("med3", i, "order_reversed") == f16_minmax3_expected("med3", i) + for i in (0, 1)) assert f16_minmax3_reference("min3", 0xbc00, 0x3c00, 0x0000) == 0xbc00 assert f16_minmax3_reference("min3", 0xbc00, 0x3c00, 0x0000, mutation="ops_swapped") == 0x3c00 assert f16_minmax3_reference("min3", 0x8000, 0x0000, 0xbc00) == 0xbc00 assert f16_minmax3_reference("min3", 0x8000, 0x0000, 0xbc00, mutation="order_signed") == 0x8000 assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True) == 0x3c00 assert f16_minmax3_reference("max3", 0xbc00, 0x3800, 0x3e00, clamp=True, mutation="clamp_removed") == 0x3e00 + assert f16_minmax3_reference("med3", 0xbc00, 0x3800, 0x3e00) == 0x3800 + assert f16_minmax3_reference("med3", 0xbc00, 0x3800, 0x3e00, mutation="med3_as_min") == 0xbc00 + assert f16_minmax3_reference("med3", 0xbc00, 0x3800, 0x3e00, mutation="med3_as_max") == 0x3e00 + assert f16_minmax3_reference("med3", 0xbc00, 0x3e00, 0xc000) == 0xbc00 + assert f16_minmax3_reference("med3", 0xbc00, 0x3e00, 0xc000, mutation="order_signed") == 0xc000 def check_f16_minmax3_controls(): - """Lowering, spelling, source proof, clamp, mode, modifier and reader refusals of v_min3_f16 and v_max3_f16.""" + """Lowering, spelling, source proof, clamp, mode, modifier and reader refusals of the three ternary ops.""" check_f16_minmax3_reference() check_f16_minmax3_mutation_coverage() prefix = ["v_mov_b32_e32 v18, 0x3555bc00", "v_mov_b32_e32 v19, 0xd1a73c00", "v_mov_b32_e32 v20, 0x42480000", "s_mov_b32 s60, 0x35550400", "s_mov_b32 s61, 0xd1a73c00"] - helpers = {"min3": "f16_min3_bits(", "max3": "f16_max3_bits("} + helpers = {"min3": "f16_min3_bits(", "max3": "f16_max3_bits(", "med3": "f16_med3_bits("} def program(*lines): return uncompressed_export([*prefix, *lines]) @@ -19166,7 +19247,7 @@ def refuse(line, message, translator=translate_f16): expect_value_error(translator, program(line), message) # Lowering and spelling: the bare and _e64 spellings are one VOP3 lowering; clamp selects the clamp in the helper. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18, v19, v20")) for suffix in ("", "_e64")] assert spelled[0] == spelled[1], op body = spelled[0].split("uint4 main", 1)[1] @@ -19178,7 +19259,7 @@ def refuse(line, message, translator=translate_f16): assert forbidden not in body, (op, forbidden) # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals, in every source position. tokens = [*pixel_aot.INLINE_F16, "0", "0x3555", "0x7bff", "0x8000", "0xfbff"] - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for token in tokens: for position in range(3): sources = ["v18", "v19", "v20"] @@ -19192,8 +19273,10 @@ def refuse(line, message, translator=translate_f16): translate_f16(program("v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v24, v19, v20", "v_min3_f16 v26, v25, 0x3c00, 0", "v_cvt_f32_f16_e32 v12, v26")) translate_f16(program("v_max3_f16 v24, v18, v19, v20 clamp", "v_min3_f16 v25, v24, 1.0, -2.0 clamp")) + translate_f16(program("v_med3_f16 v24, v18, v19, v20", "v_med3_f16 v25, v24, v19, v20 clamp", + "v_cvt_f32_f16_e32 v12, v25")) # Entry profile: unknown or an unsupported declaration refuses every spelling. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for suffix in ("", "_e64"): expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), program(f"v_{op}_f16{suffix} v24, v18, v19, v20"), @@ -19203,7 +19286,7 @@ def refuse(line, message, translator=translate_f16): half_denorm=state), program("v_min3_f16 v24, v18, v19, v20"), "Invalid binary16 denormal entry state") # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for lines, token in (([f"v_{op}_f16 v24, s44, v19, v20"], "s44"), ([f"v_{op}_f16 v24, v18, v30, v20"], "v30"), ([f"v_{op}_f16_e64 v24, v18, v19, v12"], "v12")): @@ -19213,7 +19296,7 @@ def refuse(line, message, translator=translate_f16): expect_value_error(translate_f16, program("v_add_nc_u16 v21, v18, v19", f"v_{op}_f16 v24, v21, v19, v20"), "binary16 operand lacks a finite proof: v21") # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"binary16 operand is not finite: {token}") refuse(f"v_{op}_f16 v24, v18, v19, {token}", f"binary16 operand is not finite: {token}") @@ -19222,7 +19305,7 @@ def refuse(line, message, translator=translate_f16): expect_value_error(translate_f16, program("v_mov_b32_e32 v21, 0x7e00", f"v_{op}_f16 v24, v18, v21, v20"), "binary16 operand is not finite: v21") # Source modifiers, integer inline constants, floats and other operands. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): refuse(f"v_{op}_f16 v24, {token}, v19, v20", f"Unsupported binary16 source modifier {token}") for token in ("1", "64", "-1", "-16", "5"): @@ -19233,8 +19316,8 @@ def refuse(line, message, translator=translate_f16): refuse(f"v_{op}_f16 v256, v18, v19, v20", "Register out of range: v256") refuse(f"v_{op}_f16 v24, v256, v19, v20", "Register out of range: v256") refuse(f"v_{op}_f16 v24, v18, v19, s106", "Register out of range: s106") - # Unmodelled encodings and modifiers fall through to the generic refusal; med3 is a separate slice. - for op in F16_MINMAX3_OPS: + # Unmodelled encodings and modifiers fall through to the generic refusal. + for op in F16_MINMAX3_TERNARY_OPS: for line in (f"v_{op}_f16_e32 v24, v18, v19, v20", f"v_{op}_f16_dpp v24, v18, v19, v20 quad_perm:[0,1,2,3] " "row_mask:0xf bank_mask:0xf", f"v_{op}_f16_sdwa v24, v18, v19, v20 dst_sel:DWORD " "dst_unused:UNUSED_PAD src0_sel:WORD_0", f"v_{op}_f16 v24, v18, v19, v20 op_sel:[0,0,0,1]", @@ -19242,8 +19325,6 @@ def refuse(line, message, translator=translate_f16): f"v_{op}_f16 v24, v18, v19, v20 clamp op_sel:[0,0,0,1]", f"v_{op}_f16 v24, v18, v19", f"v_{op}_f16 v24, v18, v19, v20, v21", f"v_{op}_f16 v24"): refuse(line, "Unsupported instruction") - refuse("v_med3_f16 v24, v18, v19, v20", "Unsupported instruction") - # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. def float_f16(instructions): return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, @@ -19263,7 +19344,7 @@ def float_f16(instructions): expect_value_error(float_f16, base[:masked] + ["v_min3_f16 v24, 1.0, 2.0, 4.0"] + base[masked:], "Invalid binary16 ternary operation") # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. - for op in F16_MINMAX3_OPS: + for op in F16_MINMAX3_TERNARY_OPS: for spelling in (f"v_{op}_f16", f"v_{op}_f16_e64"): line = f"{spelling} v24, v18, v19, v20" expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), @@ -19271,8 +19352,9 @@ def float_f16(instructions): assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) # Readers. The audited ones read a ternary result; every other reader of the tag refuses it. - produced = [*prefix, "v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v18, v19, v20 clamp"] - for register in (24, 25): + produced = [*prefix, "v_min3_f16 v24, v18, v19, v20", "v_max3_f16 v25, v18, v19, v20 clamp", + "v_med3_f16 v26, v18, v19, v20 clamp"] + for register in (24, 25, 26): for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): @@ -29390,13 +29472,14 @@ def case(kind, index, tag): def check_f16_minmax3_draw(directory, compiler, renderer, backend): """v_min3_f16 and v_max3_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. - Two main programs run eight triples through both ops and pack two results per word in a rotation of the bare and - _e64 spellings and VGPR/SGPR operand banks; one clamp program runs four triples with clamp; one inline program - proves every source as a binary16 inline constant or 16-bit literal. Two chain programs feed a min3 or max3 - result into the next op and two reader programs read both results through the four audited readers. Four - deviations must each mismatch (one batch per mutation; the statuses are printed): the two operations swapped, a - signed comparison of the raw halves instead of the sign-magnitude key, the clamp dropped, and a source read from - bits 31:16. A source nothing proves is refused at translation. + Two main programs run eight triples through min3 and max3 and pack two results per word in a rotation of the bare + and _e64 spellings and VGPR/SGPR operand banks; one clamp program runs four triples with clamp; one inline program + proves every source as a binary16 inline constant or 16-bit literal; two median programs run four triples each, + unclamped then clamped, and widen one result per word. Two chain programs feed a ternary result into the next op + and two reader programs read the results through the four audited readers. Seven deviations must each mismatch + (one batch per mutation; the statuses are printed): min3 and max3 swapped, a signed comparison of the raw halves, + the full key order reversed, the clamp dropped, a source read from bits 31:16, med3 replaced by min3, and med3 + replaced by max3. A source nothing proves is refused at translation. Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's high half is not measured here; the source-high mutation is the high-half control for the sources. diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 73a0fe6ee3..7c8030f047 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -5118,9 +5118,10 @@ def test_non_packed_int16_ternary_forms(self): f"v_{name} v5, v1, v2, s106"): self.assertFalse(is_instruction_supported(bad), bad) for line in ("v_mad_u16_e64 v5, v1, v2, v3", "v_max3_i16 v5, v1, v2, 4", "v_med3_u16 v5, v1, -16, 64", - "v_mad_i16 v5, v1, 0x0012, s105"): + "v_mad_i16 v5, v1, 0x0012, s105", "v_med3_f16 v5, v1, v2, v3", + "v_med3_f16 v5, v1, v2, v3 clamp"): self.assertTrue(is_instruction_supported(line), line) - for line in ("v_mad_u32_u16 v5, v1, v2, v3", "v_med3_f16 v5, v1, v2, v3"): + for line in ("v_mad_u32_u16 v5, v1, v2, v3",): self.assertFalse(is_instruction_supported(line), line) def test_float_to_word_conversions_e32_and_e64(self): @@ -6363,7 +6364,7 @@ def translator_accepts(line): for op in ("rcp", "sqrt", "rsq", "exp", "log", "sin", "cos"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] - for op in ("min3", "max3"): + for op in ("min3", "max3", "med3"): accepted += [f"v_{op}_f16 v24, v18, v19, v20", f"v_{op}_f16_e64 v24, v18, v19, v20", f"v_{op}_f16 v24, v18, v19, v20 clamp", f"v_{op}_f16_e64 v24, s60, v19, v20", f"v_{op}_f16 v24, 1.0, v19, v20", f"v_{op}_f16 v24, v18, 0.5, -2.0", @@ -6391,11 +6392,12 @@ def translator_accepts(line): "v_cos_f16_e64 v24, -v18", "v_cos_f16_e64 v24, |v18|", "v_cos_f16_e64 v24, v18 clamp", "v_cos_f16_e64 v24, v18 mul:2", "v_cos_f16_e64 v24, 3", "v_cos_f16_e64 v24, 0x10000", "v_min3_f16_e32 v24, v18, v19, v20", "v_max3_f16_e32 v24, v18, v19, v20", + "v_med3_f16_e32 v24, v18, v19, v20", "v_min3_f16 v24, -v18, v19, v20", "v_max3_f16 v24, |v18|, v19, v20", "v_min3_f16 v24, v18, v19, v20 mul:2", "v_max3_f16 v24, v18, v19, v20 div:2", + "v_med3_f16 v24, v18, v19, v20 mul:2", "v_min3_f16 v24, v18, v19, v20 op_sel:[0,0,0,1]", "v_max3_f16 v24, 3, v19, v20", "v_min3_f16 v24, v18, v19, 0x10000", "v_max3_f16 v256, v18, v19, v20", - "v_med3_f16 v24, v18, v19, v20", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index c526a27367..6ccc673284 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1090,7 +1090,7 @@ def check_vopc_e32_dst(enc, dst): " return asuint(int(exp) - 126);\n" "}" ), - # The direct compute v_min3_f16/v_max3_f16 order key, x ^ (x >= 0x8000 ? 0xffff : 0x8000): it sorts -0.0h + # The direct compute v_min3_f16/v_max3_f16/v_med3_f16 order key, x ^ (x >= 0x8000 ? 0xffff : 0x8000): it sorts -0.0h # below +0.0h and every negative encoding below every positive one, and the pair selects whole source bits so # the ternary forms need no rounding. clamp maps a negative result (including -0.0h) to +0 and a result above # 0x3bff to 1.0h; the NaN test mirrors the direct compute block even though the finite source proof excludes it. @@ -1102,20 +1102,35 @@ def check_vopc_e32_dst(enc, dst): " return (is_max ? (ka > kb) : (ka < kb)) ? a : b;\n" "}" ), + "f16_minmax3_clamp": ( + "uint f16_minmax3_clamp(uint result) {\n" + " if ((result & 0x7fffu) > 0x7c00u || (result & 0x8000u) != 0u) return 0u;\n" + " return result > 15359u ? 15360u : result;\n" + "}" + ), "f16_min3_bits": ( "uint f16_min3_bits(uint a, uint b, uint c, bool clamp_result) {\n" " uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, false), c, false);\n" " if (!clamp_result) return result;\n" - " if ((result & 0x7fffu) > 0x7c00u || (result & 0x8000u) != 0u) return 0u;\n" - " return result > 15359u ? 15360u : result;\n" + " return f16_minmax3_clamp(result);\n" "}" ), "f16_max3_bits": ( "uint f16_max3_bits(uint a, uint b, uint c, bool clamp_result) {\n" " uint result = f16_minmax2_bits(f16_minmax2_bits(a, b, true), c, true);\n" " if (!clamp_result) return result;\n" - " if ((result & 0x7fffu) > 0x7c00u || (result & 0x8000u) != 0u) return 0u;\n" - " return result > 15359u ? 15360u : result;\n" + " return f16_minmax3_clamp(result);\n" + "}" + ), + # The median is max(min(a, b), min(max(a, b), c)) under the same key. With finite sources every branch selects + # one whole source encoding; the NaN branch of the direct compute block is unreachable under the finite proof. + "f16_med3_bits": ( + "uint f16_med3_bits(uint a, uint b, uint c, bool clamp_result) {\n" + " uint lo = f16_minmax2_bits(a, b, false);\n" + " uint hi = f16_minmax2_bits(a, b, true);\n" + " uint result = f16_minmax2_bits(lo, f16_minmax2_bits(hi, c, false), true);\n" + " if (!clamp_result) return result;\n" + " return f16_minmax3_clamp(result);\n" "}" ), "f16_min_bits": ( @@ -1721,9 +1736,9 @@ def check_vopc_e32_dst(enc, dst): "min3_i16": "min3_i16", "min3_u16": "min3_u16", "max3_i16": "max3_i16", "max3_u16": "max3_u16", "med3_i16": "med3_i16", "med3_u16": "med3_u16", } -# Plain VOP3 binary16 three-operand minimum and maximum. LLVM 15 prints these VOP3-only forms without an encoding -# suffix; the low halves of the three finite sources are compared and one whole source encoding is selected. -VOP3_F16_MINMAX3 = ("min3", "max3") +# Plain VOP3 binary16 three-operand minimum, maximum and median. LLVM 15 prints these VOP3-only forms without an +# encoding suffix; the low halves of the three finite sources are compared and one whole source encoding is selected. +VOP3_F16_TERNARY = ("min3", "max3", "med3") # Quad-local DPP16/DPP8 extra f32, carry-in/carry-out, and dot-accumulate ops. # Tuple fields: (kind, allow_fp_mods, helper_name) @@ -2106,26 +2121,38 @@ def f16_minmax_result(name, b0, b1): def f16_minmax3_result(name, b0, b1, b2, *, clamp=False): - """Exact binary16 result bits of v_min3_f16 or v_max3_f16 on three finite operands. + """Exact binary16 result bits of v_min3_f16, v_max3_f16 or v_med3_f16 on three finite operands. Follows the direct compute block without a floating-point conversion: the unsigned sign-magnitude key - x ^ (x >= 0x8000 ? 0xffff : 0x8000) orders -0.0h below +0.0h, min3 and max3 fold the pair twice, and a tie keeps - the second operand as the select does. clamp maps a negative result (including -0.0h) to +0.0h and a result - above 0x3bff to 1.0h (0x3c00). Unlike the two-operand helpers, opposite-signed zeros are part of the semantics. + x ^ (x >= 0x8000 ? 0xffff : 0x8000) orders -0.0h below +0.0h, min3 and max3 fold the pair twice, and med3 is + max(min(a, b), min(max(a, b), c)). A tie keeps the second operand as the select does. clamp maps a negative + result (including -0.0h) to +0.0h and a result above 0x3bff to 1.0h (0x3c00). Unlike the two-operand helpers, + opposite-signed zeros are part of the semantics. """ - if name not in ("min3", "max3"): - raise ValueError(f"Unknown binary16 ternary min/max: {name}") + if name not in ("min3", "max3", "med3"): + raise ValueError(f"Unknown binary16 ternary op: {name}") if any((bits >> 10) & 0x1f == 0x1f for bits in (b0, b1, b2)): raise ValueError(f"binary16 operand is not finite: v_{name}_f16") def key(bits): return (bits ^ 0xffff) if bits & 0x8000 else (bits ^ 0x8000) - def pick(x, y): + def choose_min(x, y): kx, ky = key(x), key(y) - return x if (kx > ky if name == "max3" else kx < ky) else y + return x if kx < ky else y - result = pick(pick(b0 & 0xffff, b1 & 0xffff), b2 & 0xffff) + def choose_max(x, y): + kx, ky = key(x), key(y) + return x if kx > ky else y + + a, b, c = b0 & 0xffff, b1 & 0xffff, b2 & 0xffff + if name == "min3": + result = choose_min(choose_min(a, b), c) + elif name == "max3": + result = choose_max(choose_max(a, b), c) + else: + lo, hi = choose_min(a, b), choose_max(a, b) + result = choose_max(lo, choose_min(hi, c)) if clamp: if (result & 0x7fff) > 0x7c00 or result & 0x8000: return 0 @@ -8389,12 +8416,12 @@ def known_sample_float(reg): lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result - elif m := match(r"v_(min3|max3)_f16(?:_e64)? (v\d+), ([^,\s]+), ([^,\s]+), ([^,\s]+?)( clamp)?"): - # Plain VOP3 binary16 three-operand minimum and maximum. These are the only VOP3 spellings: an _e32 suffix, - # DPP, SDWA, op_sel and omod never match the anchored operands and fall through to the generic refusal. - # All three sources must have a statically proven finite low half (half16_arith_source), clamp is accepted, - # and the result is exactly one of the sources with no rounding. The helper applies the direct compute - # sign-magnitude order and clamp rule, and the result stays a proven value for a later binary16 op. + elif m := match(r"v_(min3|max3|med3)_f16(?:_e64)? (v\d+), ([^,\s]+), ([^,\s]+), ([^,\s]+?)( clamp)?"): + # Plain VOP3 binary16 three-operand minimum, maximum and median. These are the only VOP3 spellings: an + # _e32 suffix, DPP, SDWA, op_sel and omod never match the anchored operands and fall through to the generic + # refusal. All three sources must have a statically proven finite low half (half16_arith_source), clamp is + # accepted, and the result is exactly one of the sources with no rounding. The helper applies the direct + # compute sign-magnitude order and clamp rule, and the result stays a proven value for a later binary16 op. name, dst, *tokens, clamp = m.groups() if mask != "entry": raise ValueError("Invalid binary16 ternary operation") @@ -8408,7 +8435,7 @@ def known_sample_float(reg): known_half) for tok in tokens)) result = f16_minmax3_result(name, *proven, clamp=bool(clamp)) helper = f"f16_{name}_bits" - helpers.update(("f16_minmax2_bits", helper)) + helpers.update(("f16_minmax2_bits", "f16_minmax3_clamp", helper)) for k, word in enumerate(words): lines.append(f" uint hf{i}_{k} = ({word}) & 0xffffu;") lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1, hf{i}_2, " diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 67272b8022..cb259a563e 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -82,7 +82,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: PIXEL_INLINE_F16 = tuple(pixel_aot.INLINE_F16) if pixel_aot is not None else () PIXEL_VCC = r"(?:vcc(?:_lo)?)" PIXEL_VOP3_INT16_TERNARY = pixel_aot.VOP3_INT16_TERNARY if pixel_aot is not None else {} -PIXEL_VOP3_F16_MINMAX3 = tuple(pixel_aot.VOP3_F16_MINMAX3) if pixel_aot is not None else () +PIXEL_VOP3_F16_TERNARY = tuple(pixel_aot.VOP3_F16_TERNARY) if pixel_aot is not None else () PIXEL_LANE_MASK = pixel_aot.LANE_MASK if pixel_aot is not None else r"(?:vcc(?:_lo)?|s\d+|s\[\d+:\d+\])" # Explicit _e32 VOPC writes VCC only; suffix-less and _e64 may name an SGPR destination. PIXEL_VOPC_DST = rf"(?:_e32\s+{PIXEL_VCC}|(?:_e64)?\s+{PIXEL_LANE_MASK})" @@ -336,11 +336,11 @@ def lower_rejection_causes(results: list[dict]) -> dict: rf"v_(?:{'|'.join(map(re.escape, PIXEL_VOP3_INT16_TERNARY))})(?:_e64)?\s+{INT16_VGPR}," rf"\s+{INT16_SOURCE},\s+{INT16_SOURCE},\s+{INT16_SOURCE}" ) -# Plain VOP3 binary16 minimum and maximum of three finite sources; pixel_aot also proves each low half and accepts -# the optional clamp, while e32, DPP, SDWA, op_sel and omod stay unsupported here. -if PIXEL_VOP3_F16_MINMAX3: +# Plain VOP3 binary16 minimum, maximum and median of three finite sources; pixel_aot also proves each low half and +# accepts the optional clamp, while e32, DPP, SDWA, op_sel and omod stay unsupported here. +if PIXEL_VOP3_F16_TERNARY: SUPPORTED_INSTRUCTIONS_REGEX.append( - rf"v_(?:{'|'.join(map(re.escape, PIXEL_VOP3_F16_MINMAX3))})_f16(?:_e64)?\s+{INT16_VGPR}," + rf"v_(?:{'|'.join(map(re.escape, PIXEL_VOP3_F16_TERNARY))})_f16(?:_e64)?\s+{INT16_VGPR}," rf"\s+{F16_ARITH_SOURCE},\s+{F16_ARITH_SOURCE},\s+{F16_ARITH_SOURCE}(?: clamp)?" ) # 64-bit VOP3 shifts (issue #928): a VGPR-pair destination, a 32-bit amount (VGPR, SGPR, inline integer or @@ -476,7 +476,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: | {f"v_{name}" for name in PIXEL_VOP3_INT16_TERNARY} | {f"v_{name}_f16" for name in PIXEL_VOP2_F16 + PIXEL_VOP2_F16_FUSED_SCALE + PIXEL_VOP1_F16_ROUND + PIXEL_VOP1_F16_UNARY} - | {f"v_{name}_f16" for name in PIXEL_VOP3_F16_MINMAX3} + | {f"v_{name}_f16" for name in PIXEL_VOP3_F16_TERNARY} | {"v_cvt_f16_i16", "v_cvt_f16_u16"} | { # Decoding only: the tables above cover the binary16 VOP1/VOP2 forms a translator lowers.