diff --git a/docs/design.md b/docs/design.md index 953c10ba35..460f2bc6cc 100644 --- a/docs/design.md +++ b/docs/design.md @@ -523,6 +523,7 @@ How the generated SPIR-V expects the runtime to work: | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | +| Computed I/J barycentrics without `PerVertexKHR` (`--f16-interp-fallback`) | Under `--f16-interp-fallback` (without `--bary-fallback`), pixel shaders have no `PerVertexKHR` `[3 x vec4]` attribute arrays (neither Metal/MoltenVK nor devices without `VK_KHR_fragment_shader_barycentric` support them; `tools/vk_subgroup_info.py` sets `per_vertex_inputs: false` there, causing `make_game.py` to pass `--f16-interp-fallback`). Previously, `interp_ij_analysis` in `tools/rdna2spirv.py` raised `Unsupported` on any computed `v_interp_p1/p2` `(I, J)` pair under `--f16-interp-fallback`, refusing all 207 computed-barycentric pixel shaders in the corpus (`26,296 / 26,503`). Neither `InterpolateAtOffset` (`OpCapability InterpolationFunction` requires `sampleRateShading`, which the runtime does not enable, and SPIRV-Cross MSL rejects `interpolate_at_offset` on `BuiltIn BaryCoordKHR`) nor a geometry shader is required: in real arithmetic, because `%bary` (`BuiltIn BaryCoordKHR`) carries perspective-correct barycentrics `(1 − I_c − J_c, I_c, J_c)`, every smooth attribute or decoded f16 half (`%in_attrN` / `%in_f16hN_{lo,hi}`) is affine in `(I, J)` across a 2x2 fragment quad (`P^(q) = P_0 + I^(q) P_10 + J^(q) P_20`) even under perspective foreshortening. `tools/rdna2spirv.py` (`Gen.ij_quad_eval` and `assemble`) declares `OpCapability FragmentBarycentricKHR` + `SPV_KHR_fragment_shader_barycentric` for `%bary` (recording `features: ["fragmentShaderBarycentric"]` in `index.json`, so the device must support `VK_KHR_fragment_shader_barycentric` for `BaryCoordKHR`, though not `PerVertexKHR` compilation: MoltenVK runs it natively, while drivers without `VK_KHR_fragment_shader_barycentric` such as KosmicKrisp skip it) alongside core Vulkan 1.0 `OpCapability DerivativeControl` (which adds no extra `VkPhysicalDeviceFeatures` bit and consumes zero extra `Location` slots), and hoists all `OpDPdxFine` / `OpDPdyFine` evaluations into the uniform `%entry` block (satisfying SPIR-V uniform control flow when `v_interp_p1/p2` sits inside divergent `EXEC` branches): `%entry` computes `(dI_x, dI_y)` and `(dJ_x, dJ_y)` of `%bc.y` / `%bc.z`, the 2x2 screen-quad Jacobian determinant `det = dI_x · dJ_y − dI_y · dJ_x`, and `(P_c, dP_x, dP_y)` for each computed `(input, component)`, while each computed site solves pixel steps `alpha = ((I − I_c) · dJ_y − (J − J_c) · dI_y) / det`, `beta = (dI_x · (J − J_c) − dJ_x · (I − I_c)) / det` and evaluates `P_c + alpha · dP_x + beta · dP_y`. **Shortcut (finite-difference amplification and `det == 0` fallback):** smooth fragment inputs and `BaryCoordKHR` arrive from the rasterizer quantized to binary32 (per-lane residual `\|e_q\| <= 0.5·ulp(P_q) + \|P_10\|·0.5·ulp(I_q) + \|P_20\|·0.5·ulp(J_q)`), and 1-pixel quad differences amplify that rounding by `1 + 2\|alpha\| + 2\|beta\|` (`alpha ~ (I − I_c) / (dI/dx)`, proportional to pixel step up to the primitive's pixel span): sub-pixel barycentric offsets (`\|alpha\|, \|beta\| <= 1` px) stay near input precision (`~2e-6` on `1920x1080` `W = (1, 2.5, 4)`), ~1,000-pixel constant jumps on `[-2.75, 10]` reach `1.09e-3` in IEEE binary32 (`2.04e-3` / `1` f16 ulp at `1.5 → 1.4990234375` on an RTX 4090, `@ecox982745`, NVIDIA `616.64`, #2239), and >1,100-pixel jumps to `(0, 0)` across a `2048`-pixel perspective triangle with `P in [1.5, 4096]` reach `0.358` (`>300` f16 ulps at `1.5`, bounded by `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp`). To guard degenerate zero-area, subnormal, infinite, or NaN determinants without `OpFDiv`-by-zero, `1 / det` overflow, or MoltenVK's `OpFOrdNotEqual` NaN bug (`!=` in SPIRV-Cross MSL), `%entry` checks `0x00800000 <= (OpBitcast_u32(det) & 0x7FFFFFFF) < 0x7F800000` in integer ops (`OpUGreaterThanEqual` / `OpULessThan`), clamping the divisor to `1.0` and returning `P_c` when outside the IEEE-754 normal f32 range (including 1D/line primitives where `J` is constant across the quad, `det == 0`, so computed `I` is ignored in favour of `P_c`). Like the non-computed path, `v_interp_p1lv_f16` takes `P_0` from the interpolated attribute (`vsrc2` is unread; the corpus has `0` computed `*_f16` ops), while `--bary-fallback`, `mixed_f32` (flat + smooth f32 on one location), `v_interp_mov_f32` `p10`/`p20`, and computed 32-bit reads of 16-bit-flagged interpolants remain `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VINTRP) and Khronos SPIR-V 1.3 (`OpDPdxFine`, `OpDPdyFine`, `DerivativeControl`). Confirmed across the full shader corpus: all `207 / 207` previously refused pixel shaders (`1,139` `v_interp_p1_f32` / `v_interp_p2_f32` computed pairs; `0` computed `*_f16` ops, `2` shaders also reading non-computed `*_f16` inputs) translate and pass `spirv-val --target-env vulkan1.2 --allow-offset-texture-operand` under `--f16-interp-fallback`, bringing `--f16-interp-fallback` corpus translation from `26,296 / 26,503` (`99.22%`) to `26,503 / 26,503` (`100%`), while default-flag outputs stay byte-identical across all 207 shaders. Checked on the CPU (`spirv_mini_interp` 2x2 quad evaluation across dyadic weights, `64x64`, `1920x1080`, and `2048`-pixel perspective `w` foreshortening with tight binary64 Jacobian and `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp` error bounds, non-uniform `EXEC`-masked branches, non-`v0`/`v1` operand registers, between-ops `J` writes, `v_interp_p1lv_f16` `vsrc2` invariance, line-primitive `det == 0` / subnormal / `±inf` / `NaN` determinants, and `f16_halves` metadata) and with `spirv-val` by `tests/semantic/test_interp_computed_ij_fallback.py` (`tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm`) and `tests/semantic/test_interp_computed_ij.py`. **GPU-verified through Vulkan** on `Apple M3` (`@EvgHaze`, MoltenVK `1.4.2`, #2239), `Apple M3 Pro` (`@wavehs`, MoltenVK `1.4.0`, #2239), `NVIDIA GeForce RTX 3090` (Windows driver `610.88`, Vulkan `1.4.341`, `VK_LAYER_KHRONOS_validation` `1.4.363`, `LEONIDA_F16_INTERP_FALLBACK=1`, `LEONIDA_BARY_FALLBACK=0`), and `NVIDIA GeForce RTX 5070` (`@lixonik`, Windows driver `610.88`, #2239): `runtime/test/shaders/ps_ij_computed.asm` drawn with `vs_ids` passes `vk_pipeline_check`, `runtime/test/shaders/check.py`, and `scripts/run_gpu_tests.py` (`4,096 / 4,096` pixels exact on RTX 3090/5070 and within `1e-6` natively on MoltenVK, `0` validation errors). | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | | `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 377f7025e0..94d90c3f77 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -22,8 +22,8 @@ With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). With the variable unset, build.py/check.py follow the Mesa ANV probe automatically. -Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR -inputs, and check.py reports it as SKIP. +Under that, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR inputs (or --f16-interp-fallback +without --bary-fallback), and check.py reports it as SKIP. With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h). @@ -45,7 +45,7 @@ MC = mc_command.mc_command() RSRC2, GROUP = 0x8088, (64, 1, 1) -# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main). +# Not built under LEONIDA_BARY_FALLBACK=1 (see main). NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",) sys.path.insert(0, HERE) # this script is also run with python -I from compute_fixture import compute_header, shift_user_data, user_data_shift # noqa: E402 @@ -225,9 +225,9 @@ def main(): if skipped: print("not built (need a DXBC container with signatures):", ", ".join(skipped)) names = [n for n in names if n not in skipped] - # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there, - # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch. - if barycentric_fallback() or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": + # A computed I/J pair is refused under --bary-fallback (whereas --f16-interp-fallback lowers it via + # DerivativeControl): check.py and run_gpu_tests.py report it as SKIP under --bary-fallback. + if barycentric_fallback(): per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS] if per_vertex: print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):", diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 5abe2ab0a0..6a26b00eb5 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -760,7 +760,7 @@ def salu_ext_test(tools, spirv, env=None): # LEONIDA_BARY_FALLBACK=1/0 overrides the device probe for raw barycentrics. Unset, Mesa ANV selects the fallback. BARY_FALLBACK = barycentric_fallback() # LEONIDA_F16_INTERP_FALLBACK=1 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no -# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. +# PerVertexKHR inputs (computed I/J pairs use DerivativeControl instead). F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -2097,9 +2097,10 @@ def nan_payload_problem(px, out): def pixel_test(tools, spirv, name): path = os.path.join(spirv, name + ".spv") - if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv). - return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)") + if name == "ps_ij_computed" and BARY_FALLBACK: + # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair (no .spv). + return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " + "unsupported under --bary-fallback)") if not os.path.isfile(path): return f"missing {name}.spv" if name == "ps_cbv_modulate": diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 8263b54a17..e0303951e9 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1013,11 +1013,11 @@ def run_suite(a, work: str) -> int: for fname in asm_files: name = os.path.splitext(fname)[0] spv = os.path.join(spirv_dir, f"{name}.spv") - if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there - # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). - results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " - "no --bary-fallback / --f16-interp-fallback)")) + if name == "ps_ij_computed" and bary_fallback(): + # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair, so there + # is no .spv (--f16-interp-fallback alone lowers it via DerivativeControl + BaryCoordKHR). + results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " + "unsupported under --bary-fallback)")) continue if not os.path.isfile(spv): results.append((name, False, "missing .spv (translation failed)")) diff --git a/tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm b/tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm new file mode 100644 index 0000000000..2f1a15321a --- /dev/null +++ b/tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm @@ -0,0 +1,30 @@ +; Hand-written synthetic pixel shader exercising computed I/J interpolation without PerVertexKHR: +; 1. Pristine center f32 read of attr0.x first (matching the 200-shader corpus pattern). +; 2. EXEC-masked branch modifying (v0, v1) on lanes where I > 0.20 (non-uniform across a 2x2 quad), +; then evaluating computed f32 attr0.y and computed f16 low/high halves of attr1.x inside a branch. + v_interp_p1_f32_e32 v6, v0, attr0.x ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p2_f32_e32 v6, v1, attr0.x ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p1_f32_e32 v2, v0, attr0.y ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p2_f32_e32 v2, v1, attr0.y ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v10, v0 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v11, v1 ; encoding: [0x00,0x00,0x00,0x00] + v_cmp_lt_f32_e32 vcc_lo, 0x3e4ccccd, v0 ; encoding: [0xff,0x00,0x02,0x7c,0xcd,0xcc,0x4c,0x3e] + s_and_saveexec_b32 s4, vcc_lo ; encoding: [0x00,0x00,0x00,0x00] + s_cbranch_execz 4 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v0, 0.25 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v1, 0.25 ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p1_f32_e32 v2, v0, attr0.y ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p2_f32_e32 v2, v1, attr0.y ; encoding: [0x00,0x00,0x00,0x00] + s_mov_b32 exec_lo, s4 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v0, 0 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v1, 0 ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p1ll_f16 v3, v0, attr1.x ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] + v_interp_p2_f16 v3, v1, attr1.x, v3 ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] + v_cvt_f32_f16_e32 v3, v3 ; encoding: [0x00,0x00,0x00,0x00] + v_mul_f32_e32 v1, 0.5, v11 ; encoding: [0x00,0x00,0x00,0x00] + v_mov_b32_e32 v0, v10 ; encoding: [0x00,0x00,0x00,0x00] + v_interp_p1ll_f16 v4, v0, attr1.x high ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] + v_interp_p2_f16 v4, v1, attr1.x, v4 high ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] + v_cvt_f32_f16_e32 v4, v4 ; encoding: [0x00,0x00,0x00,0x00] + exp mrt0 v6, v2, v3, v4 done vm ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] + s_endpgm ; encoding: [0x00,0x00,0x00,0x00] diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 61a416de24..3d7ebd5f25 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -521,6 +521,18 @@ def advance(i, value): f"{subgroup_size}-wide subgroup") ident %= subgroup_size results.append(group[ident][2] if ident in group else UNDEF) + elif kind in ("OpDPdxFine", "OpDPdyFine"): + # SPIR-V 3.32.16: fine screen-quad derivatives over 2x2 quads (lanes 0:(0,0), 1:(1,0), 2:(0,1), + # 3:(1,1) within each group of 4 contiguous invocations; helper invocations participate). + if invocations % 4 or slots != list(range(invocations)): + raise UnsupportedConstruct(f"{kind} requires complete 2x2 pixel quads (4*n contiguous invocations)") + qbase = i & ~3 + lo_idx, hi_idx = ((qbase + (i & 2), qbase + (i & 2) + 1) if kind == "OpDPdxFine" + else (qbase + (i & 1), qbase + 2 + (i & 1))) + lo_v, hi_v = pending[lo_idx][2], pending[hi_idx][2] + diff = lambda h, l: f32(ieee_nan(h - l, h, l)) # noqa: E731 + results.append(tuple(diff(h, l) for h, l in zip(hi_v, lo_v)) if isinstance(lo_v, tuple) + else diff(hi_v, lo_v)) else: raise UnsupportedConstruct(kind) for i in range(invocations): @@ -528,6 +540,13 @@ def advance(i, value): return (memory, invocation_outputs) if return_outputs else memory +def run_quad(text, inputs_for, push_constants=None, memory=None, resources=None): + """Execute one 2x2 pixel quad (lanes 0:(x,y), 1:(x+1,y), 2:(x,y+1), 3:(x+1,y+1)) and return its four Output dicts.""" + _, outs = run_workgroup(text, 4, 4, inputs_for=inputs_for, push_constants=push_constants, memory=memory, + return_outputs=True, resources=resources) + return outs + + _TICK = ("tick", None, None, None) _PARSED = {} @@ -1237,6 +1256,11 @@ def _fdiv(p, q): elif op == "OpConvertUToPtr": values[res] = ("psb", val(a[1])) pointers[res] = values[res] + elif op in ("OpDPdxFine", "OpDPdyFine"): + v = val(a[1]) + if not (isinstance(v, float) or (isinstance(v, tuple) and all(isinstance(c, float) for c in v))): + raise UnsupportedConstruct(f"{op} on non-float") + values[res] = yield (op, pc - 1, v, None) elif op == "OpExtInst": if len(a) < 3 or a[1] != "%glsl": raise UnsupportedConstruct("extended instruction set") diff --git a/tests/semantic/test_interp_computed_ij.py b/tests/semantic/test_interp_computed_ij.py index 7b30f29f7e..f2aec2eb95 100644 --- a/tests/semantic/test_interp_computed_ij.py +++ b/tests/semantic/test_interp_computed_ij.py @@ -293,22 +293,22 @@ def test_computed_pair_under_bary_fallback(self): self.refuse(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"], - "computed I/J pair under --bary-fallback") + "bary-fallback") finally: rdna2spirv.BARY_FALLBACK = old def test_computed_pair_under_f16_interp_fallback(self): - # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs to - # weight with a computed pair (same regime as --bary-fallback) old = rdna2spirv.F16_HALVES rdna2spirv.F16_HALVES = True try: - self.refuse(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"], - "computed I/J pair under --f16-interp-fallback") + spv = support.translate_lines("ps_ij_f16_fb", [ + "v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", + "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"]) finally: rdna2spirv.F16_HALVES = old + self.assertNotIn("PerVertexKHR", spv) + self.assertIn("OpCapability DerivativeControl", spv) if __name__ == "__main__": diff --git a/tests/semantic/test_interp_computed_ij_fallback.py b/tests/semantic/test_interp_computed_ij_fallback.py new file mode 100644 index 0000000000..7cccca54ea --- /dev/null +++ b/tests/semantic/test_interp_computed_ij_fallback.py @@ -0,0 +1,545 @@ +"""Computed I/J interpolation without PerVertexKHR (--f16-interp-fallback). + +Verifies the uniform %entry screen-quad barycentric Jacobian shortcut lowering (OpCapability DerivativeControl + +FragmentBarycentricKHR + OpDPdxFine / OpDPdyFine + integer IEEE-754 normal determinant guard): + * perspective-projected 2x2 pixel quad evaluation (w0 != w1 != w2) at 64x64, 1920x1080, and 2048x2048 + for snapped constants, zeroed provoking-vertex reads, sub-pixel offsets, halved weights, and J written + between p1 and p2, pinned against a binary64 Jacobian oracle and the analytical finite-difference + error bound (1 + 2*|alpha| + 2*|beta|) * m_ulp; + * --f16-interp-fallback (without --bary-fallback) on both f32 and decoded low/high f16 attributes, + including fragmentShaderBarycentric feature recording and v_interp_p1lv_f16 vsrc2 invariance; + * non-uniform per-lane branching / EXEC masking (all OpDPdxFine / OpDPdyFine instructions stay in %entry); + * degenerate zero-area, 1D line-primitive (constant J -> det == 0), signed-zero, subnormal, infinite, + and NaN barycentric determinants fall back cleanly to P_c without OpFDiv-by-zero or non-finite contamination; + * existing refusals (--bary-fallback, mixed flat+smooth f32, v_interp_mov_f32 p10/p20, computed f32 on + 16-bit-flagged interpolant) remain intact. + +Hand-written synthetic programs only; no game files. +""" +from __future__ import annotations + +import math +import os +import pathlib +import re +import shutil +import struct +import subprocess +import tempfile +import unittest + +import support +import rdna2spirv +import spirv_asm +from spirv_mini_interp import f32, half_to_float, run_quad + +HERE = pathlib.Path(__file__).resolve().parent +FIXTURE = HERE / "fixtures" / "ps_ij_computed_deriv_fallback.asm" + + +def f32_bits(x: float) -> int: + return struct.unpack(" float: + return struct.unpack(" int: + return struct.unpack(" float: + """Binary32 ULP of f32(x) (subnormal-aware, distinct from Python's binary64 math.ulp).""" + v = abs(f32(x)) + if v == 0.0: + return math.ldexp(1.0, -149) + _, exp = math.frexp(v) + return math.ldexp(1.0, max(exp - 24, -149)) + + +def quad_jacobian_ref64(quad: list[dict[str, object]], lane: int, target_i: float, target_j: float, + var_name: str, ch: int) -> tuple[float, float, float]: + """Exact binary64 Jacobian solve on the binary32-quantized 2x2 quad inputs for lane.""" + x0, x1 = lane & ~1, (lane & ~1) | 1 + y0, y1 = lane & ~2, (lane & ~2) | 2 + _, ic, jc = quad[lane]["%bary"] + pc = quad[lane][var_name][ch] + dix = quad[x1]["%bary"][1] - quad[x0]["%bary"][1] + diy = quad[y1]["%bary"][1] - quad[y0]["%bary"][1] + djx = quad[x1]["%bary"][2] - quad[x0]["%bary"][2] + djy = quad[y1]["%bary"][2] - quad[y0]["%bary"][2] + det64 = dix * djy - diy * djx + alp64 = ((target_i - ic) * djy - (target_j - jc) * diy) / det64 + bet64 = (dix * (target_j - jc) - djx * (target_i - ic)) / det64 + dpx = quad[x1][var_name][ch] - quad[x0][var_name][ch] + dpy = quad[y1][var_name][ch] - quad[y0][var_name][ch] + return pc + alp64 * dpx + bet64 * dpy, alp64, bet64 + + +def translate_with(name: str, lines: list[str], *, f16: bool = False, bary: bool = False, fssm=None): + old_f16, old_bary = rdna2spirv.F16_HALVES, rdna2spirv.BARY_FALLBACK + rdna2spirv.F16_HALVES = f16 + rdna2spirv.BARY_FALLBACK = bary + try: + spv = support.translate_lines(name, lines, fssm=fssm) + meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) + finally: + rdna2spirv.F16_HALVES = old_f16 + rdna2spirv.BARY_FALLBACK = old_bary + return spv, meta + + +def perspective_quad_inputs( + spvasm: str, + verts_xyw: tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]], + attrs_words: dict[int, list[tuple[int, int, int, int]]], + pixel_xy: tuple[float, float] = (8.5, 12.5), +): + """Binary32-quantized Vulkan perspective-correct fragment inputs for a 2x2 pixel quad (lanes 0..3) and (I, J).""" + (x0, y0, w0), (x1, y1, w1), (x2, y2, w2) = verts_xyw + area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + quad = [] + ij_per_lane = [] + for q in range(4): + px = pixel_xy[0] + (q & 1) + py = pixel_xy[1] + ((q >> 1) & 1) + b = ((px - x0) * (y2 - y0) - (py - y0) * (x2 - x0)) / area + c = ((x1 - x0) * (py - y0) - (y1 - y0) * (px - x0)) / area + a = 1.0 - b - c + inv_w = a / w0 + b / w1 + c / w2 + k = f32((a / w0) / inv_w) + i = f32((b / w1) / inv_w) + j = f32((c / w2) / inv_w) + ij_per_lane.append((i, j)) + inp: dict[str, object] = {"%bary": (k, i, j), "%frag_coord": (f32(px), f32(py), 0.5, f32(inv_w))} + for n, vwords in attrs_words.items(): + fv = [[bits_f32(w) for w in vw] for vw in vwords] + raw_name = f"%in_attr{n}" + if f"{raw_name} = OpVariable" in spvasm: + if f"OpDecorate {raw_name} Flat" in spvasm: + inp[raw_name] = tuple(fv[0]) + else: + inp[raw_name] = tuple( + f32((a / w0 * fv[0][ch] + b / w1 * fv[1][ch] + c / w2 * fv[2][ch]) / inv_w) + for ch in range(4) + ) + for half in (0, 1): + hname = f"%in_f16h{n}_{half}" + if f"{hname} = OpVariable" in spvasm: + hv = [[half_to_float((vw[ch] >> (16 * half)) & 0xFFFF) for ch in range(4)] for vw in vwords] + inp[hname] = tuple( + f32((a / w0 * hv[0][ch] + b / w1 * hv[1][ch] + c / w2 * hv[2][ch]) / inv_w) + for ch in range(4) + ) + quad.append(inp) + return quad, ij_per_lane + + +class ComputedIJDerivativeFallbackTests(unittest.TestCase): + # Perspective-skewed 64x64 triangle (w0 != w1 != w2) with non-zero provoking vertex values. + VERTS_PERSP = ((0.0, 0.0, 1.0), (64.0, 0.0, 2.5), (0.0, 64.0, 4.0)) + ATTR0_FLOATS = ((1.25, -2.0, 3.5, 0.5), (5.25, 6.0, -0.5, 2.5), (-2.75, 10.0, 7.5, 4.5)) + ATTR0_WORDS = [tuple(f32_bits(x) for x in v) for v in ATTR0_FLOATS] + LO_HALVES = (1.5, 3.5, 5.5) + HI_HALVES = (-2.0, 6.0, 14.0) + ATTR1_WORDS = [(pack_f16_pair(lo, hi), 0, 0, 0) for lo, hi in zip(LO_HALVES, HI_HALVES)] + + def _validate_spirv(self, spvasm: str) -> None: + binary = spirv_asm.assemble(spvasm, target_env="vulkan1.2") + self.assertGreater(len(binary), 20) + spirv_val = shutil.which("spirv-val") + if spirv_val: + with tempfile.TemporaryDirectory() as tmp: + spv_path = os.path.join(tmp, "mod.spv") + pathlib.Path(spv_path).write_bytes(binary) + r = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spv_path], + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def test_ortho_dyadic_triangle_is_bit_exact_under_f16_interp_fallback(self): + """On vs_ids's 64x64 ortho triangle (ps_ij_computed pattern), snapped (0.25,0.25), zeroed P0, and (i, j/2) + are bit-for-bit exact across all 4 quad lanes under --f16-interp-fallback.""" + lines = [ + "v_mov_b32_e32 v10, v0", + "v_mov_b32_e32 v11, v1", + "v_mov_b32_e32 v0, 0.25", + "v_mov_b32_e32 v1, 0.25", + "v_interp_p1_f32_e32 v2, v0, attr0.x", + "v_interp_p2_f32_e32 v2, v1, attr0.x", + "v_mov_b32_e32 v0, 0", + "v_mov_b32_e32 v1, 0", + "v_interp_p1_f32_e32 v3, v0, attr0.y", + "v_interp_p2_f32_e32 v3, v1, attr0.y", + "v_mul_f32_e32 v11, 0.5, v11", + "v_mov_b32_e32 v0, v10", + "v_mov_b32_e32 v1, v11", + "v_interp_p1_f32_e32 v4, v0, attr0.y", + "v_interp_p2_f32_e32 v4, v1, attr0.y", + "exp mrt0 v2, v3, v4, v2 done vm", + "s_endpgm", + ] + ortho_verts = ((0.0, 0.0, 1.0), (128.0, 0.0, 1.0), (0.0, 128.0, 1.0)) + uv_words = [tuple(f32_bits(x) for x in v) for v in ((0.0, 0.0, 0.0, 1.0), + (2.0, 0.0, 0.0, 1.0), + (0.0, 2.0, 0.0, 1.0))] + spv, meta = translate_with("ps_ij_ortho", lines, f16=True, bary=False) + self._validate_spirv(spv) + self.assertNotIn("PerVertexKHR", spv) + self.assertIn("OpDecorate %bary BuiltIn BaryCoordKHR", spv) + self.assertIn("DerivativeControl", meta["capabilities"]) + self.assertIn("FragmentBarycentricKHR", meta["capabilities"]) + self.assertIn("fragmentShaderBarycentric", meta["features"]) + self.assertNotIn("DerivativeControl", meta["features"]) + quad, ij = perspective_quad_inputs(spv, ortho_verts, {0: uv_words}, pixel_xy=(16.5, 24.5)) + outs = run_quad(spv, lambda lane: quad[lane]) + for lane in range(4): + w = outs[lane]["%out_mrt0"] + self.assertEqual(w[0], f32_bits(0.5)) + self.assertEqual(w[1], f32_bits(0.0)) + self.assertEqual(w[2], f32_bits(ij[lane][1])) # 2 * (j / 2) == j + self.assertEqual(w[3], f32_bits(0.5)) + + def test_perspective_fixture_branch_and_f16_halves(self): + """Hand-written fixture mixing pristine f32, non-uniform EXEC-masked computed f32, and computed low/high f16 + under strong perspective foreshortening (w = 1.0, 2.5, 4.0) with --f16-interp-fallback.""" + raw_lines = [ln for ln in FIXTURE.read_text(encoding="utf-8").splitlines() + if ln.strip() and not ln.strip().startswith(";")] + attrs = {0: self.ATTR0_WORDS, 1: self.ATTR1_WORDS} + # Pick pixel_xy=(21.5, 10.5) so lane 0 has I < 0.20 (untaken) and lanes 1..3 have I > 0.20 (taken): non-uniform quad! + spv, meta = translate_with("ps_ij_persp_fix", raw_lines, f16=True, bary=False) + self._validate_spirv(spv) + self.assertNotIn("PerVertexKHR", spv) + self.assertEqual(meta["f16_halves"], {"1": [26, 27]}) + # Every OpDPdxFine / OpDPdyFine must sit in %entry before the first branch. + first_branch = spv.index("OpBranch ") + for m in re.finditer(r"OpDPd[xy]Fine", spv): + self.assertLess(m.start(), first_branch) + + quad, ij = perspective_quad_inputs(spv, self.VERTS_PERSP, attrs, pixel_xy=(21.5, 10.5)) + # Confirm the 2x2 quad genuinely straddles the I > 0.20 branch condition! + conds = [ij[q][0] > f32(0.2) for q in range(4)] + self.assertEqual(set(conds), {False, True}) + + outs = run_quad(spv, lambda lane: quad[lane]) + p0_x, p1_x, p2_x = (v[0] for v in self.ATTR0_FLOATS) + p0_y, p1_y, p2_y = (v[1] for v in self.ATTR0_FLOATS) + for lane in range(4): + got = [bits_f32(w) for w in outs[lane]["%out_mrt0"]] + il, jl = ij[lane] + want_x = p0_x + il * (p1_x - p0_x) + jl * (p2_x - p0_x) + ii, jj = (0.25, 0.25) if conds[lane] else (il, jl) + want_y = p0_y + ii * (p1_y - p0_y) + jj * (p2_y - p0_y) + want_f16_lo = self.LO_HALVES[0] # I' = J' = 0 -> P0 low half = 1.5 + want_f16_hi = self.HI_HALVES[0] + il * (self.HI_HALVES[1] - self.HI_HALVES[0]) + ( + 0.5 * jl) * (self.HI_HALVES[2] - self.HI_HALVES[0]) + ref_y, _, _ = quad_jacobian_ref64(quad, lane, ii, jj, "%in_attr0", 1) + ref_lo, _, _ = quad_jacobian_ref64(quad, lane, 0.0, 0.0, "%in_f16h1_0", 0) + ref_hi, _, _ = quad_jacobian_ref64(quad, lane, il, f32(0.5 * jl), "%in_f16h1_1", 0) + # Channel 0 is a pristine center read: bit-exact to the smooth input word. + self.assertEqual(outs[lane]["%out_mrt0"][0], f32_bits(quad[lane]["%in_attr0"][0])) + self.assertLess(abs(got[0] - want_x), 2e-6) + self.assertLess(abs(got[1] - ref_y), 2e-6) + self.assertLess(abs(got[1] - want_y), 1e-4) + # On 64x64 (|alpha| + |beta| <= 32 px), 1.5 narrows to exact f16 (0 ulp); see 2048px test below for wide drift. + self.assertEqual(got[2], float(struct.unpack(" list[str]: + return [ + f"v_mov_b32_e32 v10, {v10_imm}", + "v_mov_b32_e32 v0, 0.25", + "v_mov_b32_e32 v1, 0.5", + "v_interp_p1lv_f16 v2, v0, attr1.x, v10", + "v_interp_p2_f16 v2, v1, attr1.x, v2", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ] + + spv_zero, _ = translate_with("ps_p1lv_ij_0", make_lines("0"), f16=True, bary=False) + spv_one, _ = translate_with("ps_p1lv_ij_1", make_lines("0x3f800000"), f16=True, bary=False) + self._validate_spirv(spv_zero) + self._validate_spirv(spv_one) + self.assertIn("OpStore %reg_v10 ", spv_zero) + self.assertIn("OpStore %reg_v10 ", spv_one) + self.assertNotIn("OpLoad %uint %reg_v10", spv_zero) + self.assertNotIn("OpLoad %uint %reg_v10", spv_one) + strip_v10 = lambda s: [ln for ln in s.splitlines() + if "OpStore %reg_v10 " not in ln and not ln.startswith("%c3f800000 =")] + self.assertEqual(strip_v10(spv_zero), strip_v10(spv_one)) + + quad0, _ = perspective_quad_inputs(spv_zero, self.VERTS_PERSP, {1: self.ATTR1_WORDS}) + quad1, _ = perspective_quad_inputs(spv_one, self.VERTS_PERSP, {1: self.ATTR1_WORDS}) + outs0 = run_quad(spv_zero, lambda lane: quad0[lane]) + outs1 = run_quad(spv_one, lambda lane: quad1[lane]) + # LO_HALVES = (1.5, 3.5, 5.5) at (0.25, 0.5) -> 1.5 + 0.25*2.0 + 0.5*4.0 = 4.0 (f16 0x4400). + for lane in range(4): + self.assertEqual(outs0[lane]["%out_mrt0"], outs1[lane]["%out_mrt0"]) + self.assertEqual(outs0[lane]["%out_mrt0"][0] & 0xFFFF, 0x4400) + + def test_1080p_perspective_precision_subpixel_vs_full_viewport_jump(self): + """At 1920x1080 with perspective W = (1.0, 2.5, 4.0), sub-pixel barycentric shifts stay within ~5e-6, while + ~1,000-pixel jumps to fixed constants reflect 1-pixel binary32 input quantization (< 2e-3, <= 1 f16 ulp) and + agree with an exact binary64 Jacobian solve on the same binary32 quad inputs within 2e-6.""" + verts_1080p = ((0.0, 0.0, 1.0), (1920.0, 0.0, 2.5), (0.0, 1080.0, 4.0)) + subpix_lines = [ + "v_add_f32_e32 v8, 0x38800000, v0", # I + 2^-14 (~0.1 px at 1080p) + "v_add_f32_e32 v9, 0xb8800000, v1", # J - 2^-14 + "v_interp_p1_f32_e32 v2, v8, attr0.y", + "v_interp_p2_f32_e32 v2, v9, attr0.y", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ] + spv_sub, _ = translate_with("ps_ij_1080p_sub", subpix_lines, f16=True, bary=False) + self._validate_spirv(spv_sub) + + raw_lines = [ln for ln in FIXTURE.read_text(encoding="utf-8").splitlines() + if ln.strip() and not ln.strip().startswith(";")] + spv_fix, _ = translate_with("ps_ij_1080p_fix", raw_lines, f16=True, bary=False) + attrs = {0: self.ATTR0_WORDS, 1: self.ATTR1_WORDS} + p0_y, p1_y, p2_y = (v[1] for v in self.ATTR0_FLOATS) + delta = bits_f32(0x38800000) + + for qx, qy in ((1794.5, 50.5), (1580.5, 96.5), (640.5, 360.5), (32.5, 900.5)): + with self.subTest(quad_xy=(qx, qy)): + q_sub, ij_sub = perspective_quad_inputs(spv_sub, verts_1080p, {0: self.ATTR0_WORDS}, pixel_xy=(qx, qy)) + outs_sub = run_quad(spv_sub, lambda lane, qs=q_sub: qs[lane]) + for lane in range(4): + it = f32(ij_sub[lane][0] + delta) + jt = f32(ij_sub[lane][1] - delta) + want_sub = p0_y + it * (p1_y - p0_y) + jt * (p2_y - p0_y) + self.assertLess(abs(bits_f32(outs_sub[lane]["%out_mrt0"][0]) - want_sub), 5e-6) + + q_fix, ij_fix = perspective_quad_inputs(spv_fix, verts_1080p, attrs, pixel_xy=(qx, qy)) + outs_fix = run_quad(spv_fix, lambda lane, qf=q_fix: qf[lane]) + for lane in range(4): + got = [bits_f32(w) for w in outs_fix[lane]["%out_mrt0"]] + if ij_fix[lane][0] > f32(0.2): + # Binary64 Jacobian solve on the identical binary32 quad inputs: proves error is input rounding. + x0, x1 = lane & ~1, (lane & ~1) | 1 + y0, y1 = lane & ~2, (lane & ~2) | 2 + ic, jc = ij_fix[lane] + pc = q_fix[lane]["%in_attr0"][1] + dix = q_fix[x1]["%bary"][1] - q_fix[x0]["%bary"][1] + diy = q_fix[y1]["%bary"][1] - q_fix[y0]["%bary"][1] + djx = q_fix[x1]["%bary"][2] - q_fix[x0]["%bary"][2] + djy = q_fix[y1]["%bary"][2] - q_fix[y0]["%bary"][2] + det64 = dix * djy - diy * djx + alp64 = ((0.25 - ic) * djy - (0.25 - jc) * diy) / det64 + bet64 = (dix * (0.25 - jc) - djx * (0.25 - ic)) / det64 + ref64 = pc + alp64 * (q_fix[x1]["%in_attr0"][1] - q_fix[x0]["%in_attr0"][1]) + ( + bet64 * (q_fix[y1]["%in_attr0"][1] - q_fix[y0]["%in_attr0"][1])) + self.assertLess(abs(got[1] - 3.0), 2e-3) + self.assertLess(abs(got[1] - ref64), 2e-6) + # Channel 2 exports v_cvt_f32_f16(v3), where I' = J' = 0 targets LO_HALVES[0] = 1.5 (<= 1 f16 ulp). + self.assertLessEqual(abs(got[2] - 1.5), 2**-10) + + def test_wide_2048px_perspective_extrapolation_bound_and_line_det_zero_fallback(self): + """Characterizes the shortcut's finite-difference amplification on a 2048px perspective triangle with P in + [1.5, 4096.0] (distant (0, 0) jump reaches >0.30 / >300 f16 ulps while obeying (1 + 2|alpha| + 2|beta|)*m_ulp, + whereas local sub-pixel shifts stay <2e-3), and verifies 1D line primitives (constant J -> det == 0) return P_c.""" + lines = [ + "v_add_f32_e32 v8, 0x39800000, v0", # local sub-pixel offset I + 2^-12 (< 1 px on 2048px) + "v_add_f32_e32 v9, 0xb9800000, v1", # J - 2^-12 + "v_interp_p1_f32_e32 v4, v8, attr0.x", + "v_interp_p2_f32_e32 v4, v9, attr0.x", + "v_mov_b32_e32 v0, 0", + "v_mov_b32_e32 v1, 0", + "v_interp_p1_f32_e32 v2, v0, attr0.x", + "v_interp_p2_f32_e32 v2, v1, attr0.x", + "v_interp_p1ll_f16 v3, v0, attr1.x", + "v_interp_p2_f16 v3, v1, attr1.x, v3", + "v_cvt_f32_f16_e32 v3, v3", + "exp mrt0 v2, v3, v4, v2 done vm", + "s_endpgm", + ] + spv, _ = translate_with("ps_ij_wide_2048", lines, f16=True, bary=False) + self._validate_spirv(spv) + + verts_2048 = ((0.0, 0.0, 1.0), (2048.0, 0.0, 1.3), (0.0, 2048.0, 1.7)) + p_vals = (1.5, 4096.0, 5.5) + p10, p20 = p_vals[1] - p_vals[0], p_vals[2] - p_vals[0] + a0 = [tuple(f32_bits(x) for x in (p, 0.0, 0.0, 0.0)) for p in p_vals] + a1 = [(pack_f16_pair(p, 0.0), 0, 0, 0) for p in p_vals] + attrs = {0: a0, 1: a1} + delta = bits_f32(0x39800000) + + peak_far_f32_err = 0.0 + peak_far_f16_err = 0.0 + for qx in (64.5, 512.5, 1024.5, 1387.5, 1750.5, 2000.5): + quad, ij = perspective_quad_inputs(spv, verts_2048, attrs, pixel_xy=(qx, 10.5)) + outs = run_quad(spv, lambda lane, qs=quad: qs[lane]) + m_ulp = max( + 0.5 * ulp32(quad[q]["%in_attr0"][0]) + + abs(p10) * 0.5 * ulp32(quad[q]["%bary"][1]) + + abs(p20) * 0.5 * ulp32(quad[q]["%bary"][2]) + for q in range(4) + ) + residuals = [ + quad[q]["%in_attr0"][0] - (p_vals[0] + quad[q]["%bary"][1] * p10 + quad[q]["%bary"][2] * p20) + for q in range(4) + ] + for lane in range(4): + got_far_f32, got_far_f16, got_local_f32, _ = [bits_f32(w) for w in outs[lane]["%out_mrt0"]] + ref_far, alp_far, bet_far = quad_jacobian_ref64(quad, lane, 0.0, 0.0, "%in_attr0", 0) + x0, x1 = lane & ~1, (lane & ~1) | 1 + y0, y1 = lane & ~2, (lane & ~2) | 2 + # Exact linear-functional identity on quantized inputs: ref64 - P0 == e_c + alp*(e_x1-e_x0) + bet*(e_y1-e_y0). + linear_err = (residuals[lane] + + alp_far * (residuals[x1] - residuals[x0]) + + bet_far * (residuals[y1] - residuals[y0])) + self.assertLess(abs((ref_far - p_vals[0]) - linear_err), 1e-9) + + dpx = quad[x1]["%in_attr0"][0] - quad[x0]["%in_attr0"][0] + dpy = quad[y1]["%in_attr0"][0] - quad[y0]["%in_attr0"][0] + alu_tol = 8.0 * ulp32(max(abs(quad[lane]["%in_attr0"][0]), abs(alp_far * dpx), abs(bet_far * dpy), 1.0)) + self.assertLessEqual(abs(got_far_f32 - ref_far), alu_tol) + bound_far = (1.0 + 2.0 * abs(alp_far) + 2.0 * abs(bet_far)) * m_ulp + alu_tol + far_err = abs(got_far_f32 - p_vals[0]) + self.assertLessEqual(far_err, bound_far) + peak_far_f32_err = max(peak_far_f32_err, far_err) + peak_far_f16_err = max(peak_far_f16_err, abs(got_far_f16 - p_vals[0])) + + # Local sub-pixel offset on the same 2048px wide triangle stays small (< 2e-3). + it = f32(ij[lane][0] + delta) + jt = f32(ij[lane][1] - delta) + want_local = p_vals[0] + it * p10 + jt * p20 + _, alp_loc, bet_loc = quad_jacobian_ref64(quad, lane, it, jt, "%in_attr0", 0) + self.assertLess(max(abs(alp_loc), abs(bet_loc)), 1.0) + bound_loc = (1.0 + 2.0 * abs(alp_loc) + 2.0 * abs(bet_loc)) * m_ulp + 8.0 * ulp32(want_local) + self.assertLessEqual(abs(got_local_f32 - want_local), bound_loc) + self.assertLess(abs(got_local_f32 - want_local), 2e-3) + + # Pin that distant jumps across a 2048px primitive genuinely incur O(span * ulp) drift (> 300 f16 ulps at 1.5). + self.assertGreater(peak_far_f32_err, 0.30) + self.assertGreater(peak_far_f16_err, 300 * (2**-10)) + + # 1D line primitive: J == 0 across all 4 quad lanes -> dJ/dx = dJ/dy = 0 -> det == 0 -> returns P_c, not P(0,0). + line_asm = [ + "v_mov_b32_e32 v0, 0", + "v_mov_b32_e32 v1, 0", + "v_interp_p1_f32_e32 v2, v0, attr0.x", + "v_interp_p2_f32_e32 v2, v1, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm", + ] + spv_def, _ = translate_with("ps_line_def", line_asm, f16=False, bary=False) + spv_f16, _ = translate_with("ps_line_f16", line_asm, f16=True, bary=False) + line_bary = [(0.75, 0.25, 0.0), (0.50, 0.50, 0.0), (0.75, 0.25, 0.0), (0.50, 0.50, 0.0)] + line_pc = [(2.0, 0.0, 0.0, 0.0), (4.0, 0.0, 0.0, 0.0), (2.0, 0.0, 0.0, 0.0), (4.0, 0.0, 0.0, 0.0)] + line_pv = [(0.0, 0.0, 0.0, 0.0), (8.0, 0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0)] + outs_def = run_quad(spv_def, lambda l: {"%bary": line_bary[l], "%in_attr0": line_pv, + "%frag_coord": (float(l & 1), float(l >> 1), 0.5, 1.0)}) + outs_f16 = run_quad(spv_f16, lambda l: {"%bary": line_bary[l], "%in_attr0": line_pc[l], + "%frag_coord": (float(l & 1), float(l >> 1), 0.5, 1.0)}) + for l in range(4): + self.assertEqual(bits_f32(outs_def[l]["%out_mrt0"][0]), 0.0) + self.assertEqual(bits_f32(outs_f16[l]["%out_mrt0"][0]), line_pc[l][0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_run_gpu_tests.py b/tests/test_run_gpu_tests.py index 16c355b105..312aa5a46a 100644 --- a/tests/test_run_gpu_tests.py +++ b/tests/test_run_gpu_tests.py @@ -709,9 +709,10 @@ def test_only_wave_width_fixtures_carry_the_rule(self): class ComputedIJWithoutPerVertexInputs(unittest.TestCase): - """ps_ij_computed (SHADER-177): without PerVertexKHR inputs (--bary-fallback, --f16-interp-fallback, the latter on - by default on MoltenVK) the translator refuses the computed I/J pair, so there is no .spv. Both runners SKIP it - there, before their missing-.spv check; a missing .spv without a fallback stays a translation failure.""" + """ps_ij_computed (SHADER-177): under --bary-fallback (neither PerVertexKHR inputs nor BaryCoordKHR) the translator + refuses the computed I/J pair, so there is no .spv; --f16-interp-fallback alone lowers it via DerivativeControl + + BaryCoordKHR. Both runners SKIP it under --bary-fallback before their missing-.spv check; a missing .spv without + --bary-fallback stays a translation failure.""" NAME = "ps_ij_computed" def run_suite(self, bary, f16): @@ -727,29 +728,34 @@ def run_suite(self, bary, f16): rc = rgt.run_suite(args, tmp) return rc, out.getvalue() - def test_run_gpu_tests_skips_under_either_fallback(self): - for bary, f16 in ((True, False), (False, True)): - with self.subTest(bary=bary, f16=f16): - rc, out = self.run_suite(bary, f16) - self.assertIn("SKIP (computed I/J pairs need PerVertexKHR inputs", out) + def test_run_gpu_tests_skips_under_bary_fallback(self): + for f16 in (False, True): + with self.subTest(f16=f16): + rc, out = self.run_suite(True, f16) + self.assertIn("SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " + "unsupported under --bary-fallback)", out) self.assertIn("0/1 passed, 1 skipped", out) self.assertNotIn("missing .spv", out) self.assertEqual(rc, 0, out) - def test_run_gpu_tests_missing_spv_without_fallback_still_fails(self): - rc, out = self.run_suite(False, False) - self.assertIn("missing .spv (translation failed)", out) - self.assertEqual(rc, 1, out) + def test_run_gpu_tests_missing_spv_without_bary_fallback_fails(self): + for f16 in (False, True): + with self.subTest(f16=f16): + rc, out = self.run_suite(False, f16) + self.assertIn("missing .spv (translation failed)", out) + self.assertEqual(rc, 1, out) def test_check_py_skips_before_its_spv_check(self): import check with tempfile.TemporaryDirectory() as tmp: - for bary, f16 in ((True, False), (False, True)): - with self.subTest(bary=bary, f16=f16), \ - patch.object(check, "BARY_FALLBACK", bary), patch.object(check, "F16_HALVES", f16): + for f16 in (False, True): + with self.subTest(bary=True, f16=f16), \ + patch.object(check, "BARY_FALLBACK", True), patch.object(check, "F16_HALVES", f16): self.assertIsInstance(check.pixel_test("unused", tmp, self.NAME), check.Skip) - with patch.object(check, "BARY_FALLBACK", False), patch.object(check, "F16_HALVES", False): - self.assertEqual(check.pixel_test("unused", tmp, self.NAME), f"missing {self.NAME}.spv") + for f16 in (False, True): + with self.subTest(bary=False, f16=f16), \ + patch.object(check, "BARY_FALLBACK", False), patch.object(check, "F16_HALVES", f16): + self.assertEqual(check.pixel_test("unused", tmp, self.NAME), f"missing {self.NAME}.spv") class F16InterpUnderBaryFallback(unittest.TestCase): diff --git a/tests/test_shader_build_fallbacks.py b/tests/test_shader_build_fallbacks.py index e205bfe956..c23168923f 100644 --- a/tests/test_shader_build_fallbacks.py +++ b/tests/test_shader_build_fallbacks.py @@ -50,13 +50,13 @@ def fresh(self): def fake_translate(self, work, names): """What rdna2spirv.py leaves in /spirv: a module and an index entry per shader it validated.""" self.asked.append(list(names)) - fallback = any(os.environ.get(v) == "1" for v in FALLBACKS) + bary = os.environ.get("LEONIDA_BARY_FALLBACK") == "1" spirv = Path(work) / "spirv" spirv.mkdir(parents=True) index = {} for n in names: - if n == "ps_ij_computed" and fallback: - continue # "computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs" + if n == "ps_ij_computed" and bary: + continue # "computed I/J pair under --bary-fallback: no PerVertexKHR inputs" (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") (spirv / (n + ".spvasm")).write_text("; SPIR-V\n", encoding="utf-8") index[n] = {"stage": n[:2]} @@ -67,6 +67,7 @@ def run_build(self, names, env): stubs = {"spirv_stubs": types.SimpleNamespace(generate_for_index=lambda *a: None), "bary_fallback_gs": types.SimpleNamespace(build_for_index=lambda *a: None)} clean = {k: v for k, v in os.environ.items() if k not in FALLBACKS} + clean.setdefault("LEONIDA_BARY_FALLBACK", "0") stdout = io.StringIO() with mock.patch.dict(os.environ, {**clean, **env}, clear=True), \ mock.patch.dict(sys.modules, stubs), \ @@ -79,17 +80,24 @@ def run_build(self, names, env): status = e.code return status, stdout.getvalue() - def test_each_fallback_builds_the_rest_without_ps_ij_computed(self): - for var in FALLBACKS: - with self.subTest(fallback=var): - self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"}) - self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store"]]) - self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) - self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) - self.assertIn("ps_ij_computed", printed) - self.assertIn("PerVertexKHR", printed) + def test_bary_fallback_builds_the_rest_without_ps_ij_computed(self): + self.fresh() + status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_BARY_FALLBACK": "1"}) + self.assertEqual(status, 0, printed) + self.assertEqual(self.asked, [["cs_store"]]) + self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) + self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) + self.assertIn("ps_ij_computed", printed) + self.assertIn("PerVertexKHR", printed) + + def test_f16_interp_fallback_builds_ps_ij_computed(self): + self.fresh() + status, printed = self.run_build(["cs_store", "ps_ij_computed"], + {"LEONIDA_F16_INTERP_FALLBACK": "1", "LEONIDA_BARY_FALLBACK": "0"}) + self.assertEqual(status, 0, printed) + self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) + self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) + self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self): status, printed = self.run_build(["ps_mullit"], {}) @@ -97,12 +105,18 @@ def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self): self.assertEqual(self.asked, []) def test_the_whole_list_builds_under_a_fallback(self): - # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty /spirv. - status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) + # Under LEONIDA_BARY_FALLBACK=1 ps_ij_computed is skipped; under LEONIDA_F16_INTERP_FALLBACK=1 alone it builds. + status, printed = self.run_build([], {"LEONIDA_BARY_FALLBACK": "1"}) self.assertEqual(status, 0, printed) self.assertNotIn("ps_ij_computed", self.asked[0]) published = {p.stem for p in (self.out / "spirv").glob("*.spv")} self.assertEqual(published, set(self.asked[0])) + self.fresh() + status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1", "LEONIDA_BARY_FALLBACK": "0"}) + self.assertEqual(status, 0, printed) + self.assertIn("ps_ij_computed", self.asked[0]) + published = {p.stem for p in (self.out / "spirv").glob("*.spv")} + self.assertEqual(published, set(self.asked[0])) self.assertIn("ps_interp_f16_high", published) # the f16 halves still translate under this fallback def test_without_a_fallback_ps_ij_computed_is_still_built(self): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index d6787c79bb..999a5867e8 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -455,6 +455,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.param_max = -1 # VS/MS: the highest exp paramN (--f16-interp-fallback keeps halves above it) self.f16_half_outs = {} # VS/MS, --f16-interp-fallback: param n -> its two decoded-half output names self.ij_capture = {} # computed-I/J pairs: pair key -> the I float id the p1 loaded (SHADER-177) + self.ij_deriv = {} # PS without PerVertexKHR: (input_name, comp) -> tag for quad-derivative IJ self.uses_psb = False self.uses_active = False self.vm_latch = False # PS: EXEC can change after a `vm` or color export, so EXEC at those is kept @@ -15153,6 +15154,38 @@ def pair_value(self, r): self.emit(f"{t} = OpBitcast %float {u}") return t + # shortcut: --f16-interp-fallback has no PerVertexKHR inputs, so computed (i, j) reconstructs P(i, j) from the + # smooth input P_c and 1-pixel OpDPdxFine / OpDPdyFine differences of (%bary.y, %bary.z, P). Binary32 rasterizer + # quantization on (%bary, P) (~0.5*ulp(P_c) + |P10|*0.5*ulp(I_c) + |P20|*0.5*ulp(J_c)) is amplified by the pixel + # step (1 + 2*|alpha| + 2*|beta|, ~|i - I_c| / |dI/dx| up to the primitive's pixel span), and det == 0 (including + # line primitives where J is constant across the quad) returns P_c instead of extrapolating along one axis. + def ij_quad_eval(self, name, comp, ij): + """Approximate P(i, j) = P0 + i*(P1 - P0) + j*(P2 - P0) without PerVertexKHR inputs (--f16-interp-fallback). + In real arithmetic perspective-correct BaryCoordKHR (%bary) makes smooth P affine in (I, J) across a 2x2 quad, + but binary32 quad finite differences scale input rounding by (|alpha| + |beta|) pixels and fall back to P_c on + a zero/subnormal/non-finite determinant. %entry precomputes the uniform 2x2 Jacobian and (P_c, dPdxFine, + dPdyFine) so sites inside non-uniform branches or loops execute pure scalar ALU with no derivative ops.""" + key = (name, comp) + tag = self.ij_deriv.setdefault(key, len(self.ij_deriv)) + i, j = ij + di, dj, na0, na1, na, alp, nb0, nb1, nb, bet, mx, s, my, r0, r = (self.tmp() for _ in range(15)) + self.emit(f"{di} = OpFSub %float {i} %ij_ic") + self.emit(f"{dj} = OpFSub %float {j} %ij_jc") + self.emit(f"{na0} = OpFMul %float {di} %ij_djy") + self.emit(f"{na1} = OpFMul %float {dj} %ij_diy") + self.emit(f"{na} = OpFSub %float {na0} {na1}") + self.emit(f"{alp} = OpFMul %float {na} %ij_idet") + self.emit(f"{nb0} = OpFMul %float %ij_dix {dj}") + self.emit(f"{nb1} = OpFMul %float %ij_djx {di}") + self.emit(f"{nb} = OpFSub %float {nb0} {nb1}") + self.emit(f"{bet} = OpFMul %float {nb} %ij_idet") + self.emit(f"{mx} = OpFMul %float {alp} %ijx_{tag}") + self.emit(f"{s} = OpFAdd %float %ijc_{tag} {mx}") + self.emit(f"{my} = OpFMul %float {bet} %ijy_{tag}") + self.emit(f"{r0} = OpFAdd %float {s} {my}") + self.emit(f"{r} = OpSelect %float %ij_nz {r0} %ijc_{tag}") + return r + def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). @@ -15165,11 +15198,15 @@ def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): --f16-interp-fallback: an f16 read (`half` 0/1) of an attribute in f16_halves is component `comp` of the smooth input at f16_half_location(n, half), which the producer fills with that half decoded to f32 (F16_HALVES). - Other reads of such an attribute take the raw word as on any location (smooth, or flat = provoking vertex).""" + Other reads of such an attribute take the raw word as on any location (smooth, or flat = provoking vertex). + Without per_vertex (--f16-interp-fallback), a computed-I/J read (`ij` not None) evaluates + P(i, j) from the smooth input's %entry quad derivatives through `ij_quad_eval`.""" if half is not None and n in self.f16_halves: name = f"%in_f16h{n}_{half}" self.inputs.setdefault(name, None) # resolved in assemble() once every raw attribute is known self.interpolated.add(name) + if ij is not None: + return self.ij_quad_eval(name, comp, ij) p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") self.emit(f"{v} = OpLoad %float {p}") @@ -15179,6 +15216,8 @@ def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): if not flat: self.interpolated.add(name) if n not in self.per_vertex: + if ij is not None: + return self.ij_quad_eval(name, comp, ij) p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") self.emit(f"{v} = OpLoad %float {p}") @@ -16346,7 +16385,7 @@ def assemble(gen): if gen.uses_viewport: iface += ["%out_viewport"] iface += [f"%vin{reg}" for reg, _ in gen.vertex_inputs] + ["%user_data"] + (["%pc_tail"] if gen.uses_pc_tail else []) - bary = any(str(c).startswith("bary") for c in gen.frag_inputs.values()) or bool(gen.per_vertex) + bary = any(str(c).startswith("bary") for c in gen.frag_inputs.values()) or bool(gen.per_vertex) or bool(gen.ij_deriv) # --bary-fallback: %bary is a plain input at the lowest location no attribute uses, so no capability or # extension. Lowest free, not one past the highest: a PS whose only input is attr30 would otherwise put it at 31, # past what drivers with 128 input components accept (#804 review). @@ -16378,6 +16417,8 @@ def assemble(gen): (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ (["MinLod"] if gen.uses_minlod else []) + (["ImageGatherExtended"] if gen.uses_img_offset else []) + \ (["FragmentBarycentricKHR"] if bary_builtin else []) + if gen.ij_deriv: + caps.append("DerivativeControl") if gen.uses_vote: caps += [c for c in ("GroupNonUniform", "GroupNonUniformVote") if c not in caps] if gen.uses_ballot or gen.uses_bcast_first: @@ -17073,6 +17114,34 @@ def assemble(gen): continue fn += [f"%fc{c} = OpCompositeExtract %float %fc {c}", f"%fcu{c} = OpBitcast %uint %fc{c}", f"%fcp{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %fcp{c} %fcu{c}"] + elif gen.ij_deriv: + fn += ["%bc = OpLoad %v3float %bary"] + if gen.ij_deriv: + # Uniform %entry screen-quad barycentric Jacobian for computed-I/J pairs without PerVertexKHR (shortcut: see + # Gen.ij_quad_eval for finite-difference error amplification proportional to pixel step and det == 0 -> P_c). + # Test IEEE-754 normal range (0x00800000 <= |det|_bits < 0x7F800000) on integer bits so +-0, subnormals, + # +-inf and NaNs fall back cleanly to P_c without OpFDiv-by-zero or MoltenVK OpFOrdNotEqual NaN hazards. + fn += ["%ij_ic = OpCompositeExtract %float %bc 1", + "%ij_jc = OpCompositeExtract %float %bc 2", + "%ij_dix = OpDPdxFine %float %ij_ic", + "%ij_diy = OpDPdyFine %float %ij_ic", + "%ij_djx = OpDPdxFine %float %ij_jc", + "%ij_djy = OpDPdyFine %float %ij_jc", + "%ij_ad = OpFMul %float %ij_dix %ij_djy", + "%ij_bc_m = OpFMul %float %ij_diy %ij_djx", + "%ij_det = OpFSub %float %ij_ad %ij_bc_m", + "%ij_du = OpBitcast %uint %ij_det", + f"%ij_dabs = OpBitwiseAnd %uint %ij_du {gen.cu(0x7FFFFFFF)}", + f"%ij_dlo = OpUGreaterThanEqual %bool %ij_dabs {gen.cu(0x00800000)}", + f"%ij_dhi = OpULessThan %bool %ij_dabs {gen.cu(0x7F800000)}", + "%ij_nz = OpLogicalAnd %bool %ij_dlo %ij_dhi", + "%ij_sdet = OpSelect %float %ij_nz %ij_det %f1", + "%ij_idet = OpFDiv %float %f1 %ij_sdet"] + for (iname, icomp), tag in sorted(gen.ij_deriv.items(), key=lambda kv: kv[1]): + fn += [f"%ijp_{tag} = OpAccessChain %_ptr_Input_float {iname} {gen.cu(icomp)}", + f"%ijc_{tag} = OpLoad %float %ijp_{tag}", + f"%ijx_{tag} = OpDPdxFine %float %ijc_{tag}", + f"%ijy_{tag} = OpDPdyFine %float %ijc_{tag}"] for reg, ctype in gen.vertex_inputs: vt = {1: "%v4uint_in", 2: "%v4int_in"}.get(ctype, "%v4float") st = {1: "%uint", 2: "%int"}.get(ctype, "%float") @@ -17693,11 +17762,13 @@ def interp_ij_analysis(insns, g): keeping its bit-identical .spv. Refused here (Unsupported, naming the pattern): a computed pair whose ops are not in one basic block (the captured I would not dominate the p2), whose shared partial register -- the f32 vdst, or the f16 p2's fourth operand naming the p1's vdst -- is written - between the ops, or read between them by anything but a p2's partial operand, any computed site - under --bary-fallback or --f16-interp-fallback (neither has PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged - interpolant (which half the 32-bit op reads is not established). Over the corpus all of these are - empty: 213 PS hold computed pairs, every pair sits in one block, and no partial is touched - between the ops. + between the ops, or read between them by anything but a p2's partial operand, any computed pair under + --bary-fallback (no PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged interpolant + (which half the 32-bit op reads is not established). Under --f16-interp-fallback (without --bary-fallback), + Gen.ij_quad_eval approximates P(i, j) from the smooth input via its %entry 2x2 screen-quad barycentric Jacobian + instead of refusing (shortcut: see Gen.ij_quad_eval). Over the corpus all refused classes are empty under + --f16-interp-fallback: 213 PS hold candidate pairs (207 reaching), every pair sits in one block, and no partial + is touched between the ops. Returns the set of attribute numbers the computed pairs need in g.per_vertex.""" P1 = ("v_interp_p1_f32", "v_interp_p1ll_f16", "v_interp_p1lv_f16") @@ -17896,9 +17967,6 @@ def partner(k, s): attrs.add(s["attr"]) if attrs and BARY_FALLBACK: raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs") - if attrs and F16_HALVES: - # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either - raise Unsupported("computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs") return attrs @@ -18962,8 +19030,11 @@ def _translate(path): if stage == "ps": g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) # SHADER-177: annotate v_interp sites whose I/J operand is a computed pair, and let those - # attributes be read per-vertex (attribute() weights them with the operand values). - g.per_vertex |= interp_ij_analysis(insns, g) + # attributes be read per-vertex when PerVertexKHR is available; under --f16-interp-fallback + # (without --bary-fallback), Gen.ij_quad_eval evaluates them from smooth inputs + %entry fine derivatives. + ij_attrs = interp_ij_analysis(insns, g) + if not F16_HALVES: + g.per_vertex |= ij_attrs if any("ij" in i for i in insns): # Computed v_interp sites load their I/J VGPRs at runtime; no_bary above stripped all # v_interp sources, so an untouched (or conditionally/EXEC-masked written) v0/v1 still