From 1d19671ebd7965371e89a467ddf932f4244ec394 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:15:03 +0100 Subject: [PATCH 01/14] rdna2spirv: --explicit-lod-bias applies the S# LOD bias in the shader where MoltenVK drops the sampler's (SHADER-EXPLICIT-LOD-BIAS-MVK) MoltenVK 1.4.2 drops VkSamplerCreateInfo::mipLodBias from both explicit and derivative-LOD samples, so ps_ssharp's S# LOD_BIAS cases fail on every Mac. With the flag the translator adds the S# bias (word 2 [13:0], signed 5.8) to explicit LODs and to _b biases, as a Bias operand on implicit samples, and as a 2^bias scale of Grad derivatives. tools/vk_subgroup_info.py reports explicit_lod_bias for MoltenVK's driver ID, and run_gpu_tests.py, build.py and make_game.py turn the flag on from it. ps_ssharp gains +-0.3 cases, which fail when the bias counts twice. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 1 + docs/testing.md | 1 + make_game.py | 25 +++- runtime/test/shaders/build.py | 18 +++ runtime/test/shaders/check.py | 3 + scripts/run_gpu_tests.py | 29 +++++ tests/semantic/test_explicit_lod_bias.py | 147 +++++++++++++++++++++++ tests/test_make_game_argparse.py | 1 + tests/test_make_game_translator_flags.py | 10 +- tests/test_shader_checks.py | 2 +- tests/test_vk_subgroup_info.py | 10 ++ tools/rdna2spirv.py | 78 +++++++++++- tools/vk_subgroup_info.py | 8 ++ 13 files changed, 327 insertions(+), 6 deletions(-) create mode 100644 tests/semantic/test_explicit_lod_bias.py diff --git a/docs/design.md b/docs/design.md index 7888e24f72..d6137e2b4b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,6 +502,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). | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 drops it from both: on an Apple M3, `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both. With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is chosen per device: `explicit_lod_bias` in `tools/vk_subgroup_info.py` (MoltenVK's driver ID), read by `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py`; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | | `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/docs/testing.md b/docs/testing.md index ffe729d24f..1c0fd73f82 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -780,6 +780,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | | `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | +| `ps_ssharp` fails on a Mac with MoltenVK 1.4.2: `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` on MoltenVK (`explicit_lod_bias` in `tools/vk_subgroup_info.py`; see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.3 cases | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | diff --git a/make_game.py b/make_game.py index 3eb0899458..b9ca5191f8 100644 --- a/make_game.py +++ b/make_game.py @@ -1775,7 +1775,7 @@ def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--bary-fallback", "bary_fallback"), ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), - ("--compact-spirv", "compact_spirv")) + ("--compact-spirv", "compact_spirv"), ("--explicit-lod-bias", "explicit_lod_bias")) def fallback_flags(a) -> tuple[str, ...]: @@ -1892,6 +1892,18 @@ def runtime_gpu_info() -> dict: return {} +def runtime_gpu_explicit_lod_bias(): + """explicit_lod_bias as tools/vk_subgroup_info.py answers for the GPU the runtime would use: True where the driver + drops the sampler's mipLodBias (MoltenVK), None when it can't tell.""" + try: + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], + capture_output=True, text=True, timeout=60) + v = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") + return None if v is None else bool(v) + except (OSError, ValueError, IndexError, subprocess.SubprocessError): + return None + + def runtime_gpu_per_vertex(): """per_vertex_inputs as tools/vk_subgroup_info.py answers for the GPU the runtime would use: False where the driver can't compile PerVertexKHR (MoltenVK) or lacks fragmentShaderBarycentric, None when it can't tell.""" @@ -3025,6 +3037,9 @@ def main() -> int: ap.add_argument("--texel-offset-fallback", action="store_true", help="fold the run-time texel offset of image_sample*_o into the coordinate, for devices " "without VK_KHR_maintenance8") + ap.add_argument("--explicit-lod-bias", action="store_true", + help="apply the S# LOD bias in the shaders, for a driver whose sampler drops it; on by itself " + "when the runtime's GPU is on MoltenVK") ap.add_argument("--f16-interp-fallback", action="store_true", help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") @@ -3122,6 +3137,14 @@ def main() -> int: a.f16_interp_fallback = True elif per_vertex is None: a.f16_interp_fallback = keep_recorded_fallback("--f16-interp-fallback", work) + if "shaders" in stages and not a.explicit_lod_bias: + drops_bias = runtime_gpu_explicit_lod_bias() + if drops_bias is True: + log("shaders: the GPU the runtime would use drops the sampler's LOD bias (MoltenVK): translating with " + "--explicit-lod-bias") + a.explicit_lod_bias = True + elif drops_bias is None: + a.explicit_lod_bias = keep_recorded_fallback("--explicit-lod-bias", work) if "shaders" in stages: if a.bary_fallback: # Command-line precedence: --bary-fallback wins over LEONIDA_BARY_FALLBACK=0. diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 03a7ecd229..bedb2f0b66 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -89,6 +89,22 @@ def asm_mattr(path): CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} +def explicit_lod_bias(): + """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0). Unset, it is on where tools/vk_subgroup_info.py reports explicit_lod_bias + (MoltenVK drops the sampler's mipLodBias), the rule of scripts/run_gpu_tests.py. No answer leaves it off.""" + v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() + if v in ("1", "true", "yes", "on"): + return True + if v in ("0", "false", "no", "off"): + return False + try: + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], + capture_output=True, text=True, timeout=60) + return json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") is True + except (OSError, ValueError, IndexError, subprocess.SubprocessError): + return False + + def asm_fssm_fields(path): """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" at, words = None, [] @@ -195,6 +211,8 @@ def translate_tests(work, names): cmd.append("--f16-interp-fallback") if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8 cmd.append("--texel-offset-fallback") + if explicit_lod_bias(): # the S# LOD bias in the shader, where the sampler drops it (MoltenVK) + cmd.append("--explicit-lod-bias") # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): cmd.append("--pc-tail-ubo") diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 4653a37f2d..bb6426be2c 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1593,6 +1593,9 @@ def ssharp_words(mip_filter, min_lod=0.0, max_lod=15.0, bias=0.0): ("point min_lod 1", ssharp_words(1, min_lod=1), (0, 1)), # 1 / 1: MIN_LOD clamps an explicit LOD too ("point bias +1", ssharp_words(1, bias=1), (0, 1)), # 1 / 1: the S# bias applies to an explicit LOD ("point bias -1", ssharp_words(1, bias=-1), (0, 1)), # 0 / 0 + # +-0.3 keeps LOD 0 / 1 on levels 0 / 1; the bias counted twice (+-0.6) moves one of them + ("point bias +0.3", ssharp_words(1, bias=0.3), (0, 1)), # 0 / 1 + ("point bias -0.3", ssharp_words(1, bias=-0.3), (0, 1)), # 0 / 1 ("none", ssharp_words(0), (0, 1)), # 0 / 0: MIP_FILTER_NONE reads the base level ("none min_lod 1", ssharp_words(0, min_lod=1), (0, 1)), # 0 / 0: and ignores the LOD clamp ("point base 1", ssharp_words(1), (1, 1))] # 1 / 1: the T#'s BASE_LEVEL starts the view diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 8ba62104d8..e5760f8ec0 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -356,6 +356,7 @@ def f16_interp_fallback() -> bool: _PER_VERTEX = [] _BARYCENTRIC_FALLBACK = [] +_EXPLICIT_LOD_BIAS = [] def _device_per_vertex(): @@ -387,6 +388,32 @@ def _device_barycentric_fallback(): return _BARYCENTRIC_FALLBACK[0] +def _device_explicit_lod_bias(): + """explicit_lod_bias from tools/vk_subgroup_info.py (MoltenVK), cached per suite, or None.""" + if not _EXPLICIT_LOD_BIAS: + answer = None + try: + r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], + capture_output=True, text=True, timeout=60) + answer = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") + except (OSError, ValueError, IndexError, subprocess.SubprocessError): + pass + _EXPLICIT_LOD_BIAS.append(answer) + return _EXPLICIT_LOD_BIAS[0] + + +def explicit_lod_bias() -> bool: + """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0): translate with --explicit-lod-bias, so an explicit-LOD sample takes the + S# LOD_BIAS in the shader. Unset, it is on where the driver drops mipLodBias there: tools/vk_subgroup_info.py + reports explicit_lod_bias true (MoltenVK).""" + v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() + if v in ("1", "true", "yes", "on"): + return True + if v in ("0", "false", "no", "off"): + return False + return _device_explicit_lod_bias() is True + + def w64_emulated() -> bool: # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates @@ -942,6 +969,8 @@ def run_suite(a, work: str) -> int: cmd.append("--f16-interp-fallback") if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 cmd.append("--texel-offset-fallback") + if explicit_lod_bias(): # the S# LOD bias added to explicit LODs, which MoltenVK's sampler drops + cmd.append("--explicit-lod-bias") if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py cmd.append("--mesh-compute") if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 diff --git a/tests/semantic/test_explicit_lod_bias.py b/tests/semantic/test_explicit_lod_bias.py new file mode 100644 index 0000000000..549ef93487 --- /dev/null +++ b/tests/semantic/test_explicit_lod_bias.py @@ -0,0 +1,147 @@ +"""rdna2spirv.py --explicit-lod-bias: the S# LOD_BIAS applied in the shader, for a driver whose sampler drops +VkSamplerCreateInfo::mipLodBias (MoltenVK 1.4.2; docs/design.md, "S# LOD bias without the sampler's mipLodBias"). + +The bias is the S#'s word 2 [13:0], signed 5.8 fixed point. With the flag: +* an explicit-LOD sample (image_sample_lz, _l, and the implicit forms outside the PS) adds it to its Lod; +* image_sample_b adds it to its own bias; +* an implicit sample in the PS that reads through Grad (the typed 2D read) scales both derivatives by 2^bias, and + one that stays implicit (3D) takes it as a Bias operand; +* a literal S# folds the bias to a constant, a zero bias adds nothing, and an S# loaded at run time is decoded from + its SGPR; +* without the flag nothing changes. +The GPU check is runtime/test/shaders/ps_ssharp (check.py SAMPLER_CASES, whose +-0.3 cases tell a bias counted once +from twice); scripts/run_gpu_tests.py turns the flag on where tools/vk_subgroup_info.py reports explicit_lod_bias. +Standard library only; no GPU, no game files. +""" +import re +import struct +import unittest + +import support + +D2 = "dim:SQ_RSRC_IMG_2D" +D3 = "dim:SQ_RSRC_IMG_3D" +CS_FSSM = bytearray(0x148) +struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) +CS_FSSM = bytes(CS_FSSM) + + +def literal_ssharp(bias_256): + """s_movs for a T# in s[8:15] and a point-mip S# in s[16:19] with LOD_BIAS = bias_256 / 256.""" + t = [0x2000, 0x1400000, 0, 0, 0, 0, 0, 0] + s = [0, 0, (bias_256 & 0x3fff) | 1 << 26, 0] + return [f"s_mov_b32 s{8 + i}, 0x{w:x}" for i, w in enumerate(t)] + \ + [f"s_mov_b32 s{16 + i}, 0x{w:x}" for i, w in enumerate(s)] + + +LOADED = ["s_load_dwordx8 s[8:15], s[0:1], 0x0", "s_load_dwordx4 s[16:19], s[0:1], 0x20", "s_waitcnt lgkmcnt(0)"] +COORDS = ["v_mov_b32 v2, 0.5", "v_mov_b32 v3, 0.25", "v_mov_b32 v4, 0.75", "v_mov_b32 v5, 1.0"] + + +def translate(name, prologue, line, flag): + fssm = CS_FSSM if name.startswith("cs_") else None + body = prologue + COORDS + [line] + (["s_waitcnt vmcnt(0)", "exp mrt0 v6, v7, v6, v7 done vm"] + if name.startswith("ps_") else []) + ["s_endpgm"] + prev = support.rdna2spirv.EXPLICIT_LOD_BIAS + support.rdna2spirv.EXPLICIT_LOD_BIAS = flag + try: + return support.translate_lines(name, body, fssm=fssm) + finally: + support.rdna2spirv.EXPLICIT_LOD_BIAS = prev + + +def samples(spv): + return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] + + +def defn(spv, ident): + """The right-hand side of `ident = ...`, or ''.""" + m = re.search(rf"^\s*{re.escape(ident)} = (.*)$", spv, re.M) + return m.group(1).strip() if m else "" + + +def float_const(spv, ident): + """The value of a float constant: the translator writes it as OpBitcast %float of a uint constant %c.""" + m = re.match(r"OpBitcast %float %c([0-9a-f]+)$", defn(spv, ident)) + if m: + return struct.unpack(" str: + """--explicit-lod-bias: lod + the S#'s LOD_BIAS.""" + b = self.ssharp_lod_bias(word_reg) + if b is None: + return lod + out = self.tmp() + self.emit(f"{out} = OpFAdd %float {lod} {b}") + return out + + def scale_grads_by_ssharp_bias(self, grads, width: int, word_reg: int): + """--explicit-lod-bias: (dx, dy) * 2^LOD_BIAS, which adds the bias to the LOD the derivatives give.""" + b = self.ssharp_lod_bias(word_reg) + if b is None: + return grads + k = self.tmp() + self.emit(f"{k} = OpExtInst %float %glsl Exp2 {b}") + out = [] + for g in grads: + t = self.tmp() + if width == 1: + self.emit(f"{t} = OpFMul %float {g} {k}") + else: + self.emit(f"{t} = OpVectorTimesScalar %v{width}float {g} {k}") + out.append(t) + return tuple(out) + def clamp_gather_lod(self, lod: str, word_reg: int) -> str: """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. @@ -13760,6 +13808,8 @@ def gather(image, cls, ty): bias = None if kind in ("_b", "_c_b"): bias, f = f[0], f[1:] + if EXPLICIT_LOD_BIAS: + bias = self.add_ssharp_lod_bias(bias, a[3]["r"] + 2) ref = None if kind.startswith("_c"): ref, f = f[0], f[1:] @@ -13775,6 +13825,8 @@ def gather(image, cls, ty): self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") grads = (gx, gy) + if EXPLICIT_LOD_BIAS: + grads = self.scale_grads_by_ssharp_bias(grads, grad_width, a[3]["r"] + 2) f = f[2 * grad_width:] if clamp: # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so @@ -13796,6 +13848,8 @@ def gather(image, cls, ty): uv = self.tmp() self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" + if EXPLICIT_LOD_BIAS and kind in ("_lz", "_l"): + lod = self.add_ssharp_lod_bias(lod, a[3]["r"] + 2) if typed_sample: # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its # 6-layer 2D-array view, which is what `img` was loaded from above. @@ -13806,6 +13860,8 @@ def gather(image, cls, ty): dx, dy = self.tmp(), self.tmp() self.emit(f"{dx} = OpDPdx %v2float {uv}") self.emit(f"{dy} = OpDPdy %v2float {uv}") + if EXPLICIT_LOD_BIAS: + dx, dy = self.scale_grads_by_ssharp_bias((dx, dy), 2, a[3]["r"] + 2) operands = f"Grad {dx} {dy}" def sample(image, cls, ty): @@ -13833,12 +13889,22 @@ def sample(image, cls, ty): if kind in ("_b", "_c_b") and not implicit and minlod is not None: bias_lod = self.tmp() self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") + if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"): + # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias). + lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2) + # Implicit samples without a bias of their own take the S# bias as a Bias operand. + sbias = (self.ssharp_lod_bias(a[3]["r"] + 2) + if EXPLICIT_LOD_BIAS and implicit and kind in ("", "_c") else None) grads_fb = None if off is not None and TEXEL_OFFSET_FALLBACK: fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, a[3]) off = None + if grads_fb is not None and sbias is not None: + # Grad, not Bias, carries these samples now: scale the derivatives instead. + grads_fb = self.scale_grads_by_ssharp_bias(grads_fb, 3 if is3d else ncoord, a[3]["r"] + 2) + sbias = None def opnd(mask, args): """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" @@ -13859,7 +13925,7 @@ def opnd(mask, args): self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") elif kind == "": - self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else + self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', sbias) if sbias else opnd('', '')}" if self.stage == "ps" else f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") elif kind in ("_lz", "_l"): self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") @@ -13871,6 +13937,8 @@ def opnd(mask, args): if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) + if EXPLICIT_LOD_BIAS and kind == "_c_l": + d_lod = self.add_ssharp_lod_bias(d_lod, a[3]["r"] + 2) self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") elif grads_fb is not None: self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " @@ -13878,7 +13946,7 @@ def opnd(mask, args): elif kind == "_c_b": self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") else: - self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('', '')}") + self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', sbias) if sbias else opnd('', '')}") if d16: # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). @@ -19498,6 +19566,9 @@ def main(): ap.add_argument("--texel-offset-fallback", action="store_true", help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " "the coordinate instead of the Offset operand") + ap.add_argument("--explicit-lod-bias", action="store_true", + help="add the S# LOD_BIAS to the Lod of explicit-LOD samples, for a driver that drops the sampler's " + "mipLodBias there (MoltenVK 1.4.2); elsewhere the bias would count twice") ap.add_argument("--mesh-compute", action="store_true", help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " @@ -19558,7 +19629,7 @@ def main(): DESCRIPTOR_HASH = a.descriptor_hash LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth - global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV + global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, EXPLICIT_LOD_BIAS, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV global PC_TAIL_UBO PC_TAIL_UBO = a.pc_tail_ubo global FMA_EXACT @@ -19572,6 +19643,7 @@ def main(): WAVE64_GRAPHICS = a.wave64_graphics BARY_FALLBACK = a.bary_fallback TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback + EXPLICIT_LOD_BIAS = a.explicit_lod_bias MESH_COMPUTE = a.mesh_compute F16_HALVES = a.f16_interp_fallback OPT_SPIRV = a.opt diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index d380fd279b..122dc41834 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -193,6 +193,13 @@ def barycentric_fallback(vendor_id: int, device_id: int, driver_id: int) -> bool or gfx90c_amd_windows(vendor_id, device_id, driver_id)) +def explicit_lod_bias(driver_id: int) -> bool: + """Drivers that drop VkSamplerCreateInfo::mipLodBias from explicit-LOD samples: MoltenVK 1.4.2 (ps_ssharp's + "point bias +1" reads level 0 through image_sample_lz). The translator then adds the S# bias itself + (rdna2spirv.py --explicit-lod-bias).""" + return driver_id == VK_DRIVER_ID_MOLTENVK + + def physical_devices(vk, instance): # The list can grow between the count and fetch. Recount, with a bound for a changing driver. for _ in range(3): @@ -366,6 +373,7 @@ def query(*, stage_caps=False) -> dict: "native64": compute64 and mesh64, "per_vertex_inputs": per_vertex, "barycentric_fallback": barycentric_fallback(vendor, device, driver), + "explicit_lod_bias": explicit_lod_bias(driver), "max_push_constants_size": max_push_constants_size, "vendor_id": vendor, "device_id": device, From 66b27ac6e20debe6bf22290e4dddaf2fb7a91503 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:29:16 +0100 Subject: [PATCH 02/14] lod_bias_probe: measure whether the sampler applies mipLodBias instead of keying --explicit-lod-bias on MoltenVK's driver ID (SHADER-EXPLICIT-LOD-BIAS-MVK) The same MoltenVK 1.4.2 drops the bias on an Apple M3 and applies it on an Apple M5 Pro (#1774 review), so the driver-ID rule turned ps_ssharp red on the M5 Pro. tools/lod_bias_probe.py translates vs_ids and ps_ssharp without the flag and draws LOD_BIAS 0, +1 and -1 with vk_sampler_test; the flag is on only when +1 and -1 read the no-bias levels. run_gpu_tests.py, build.py and make_game.py take its answer; vk_subgroup_info.py is back as on main. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime.yml | 2 + docs/design.md | 2 +- docs/testing.md | 2 +- make_game.py | 20 ++++--- runtime/test/shaders/build.py | 20 ++----- scripts/run_gpu_tests.py | 23 ++++---- tests/test_lod_bias_probe.py | 100 +++++++++++++++++++++++++++++++++ tests/test_vk_subgroup_info.py | 10 ---- tools/lod_bias_probe.py | 97 ++++++++++++++++++++++++++++++++ tools/rdna2spirv.py | 9 +-- tools/vk_subgroup_info.py | 8 --- 11 files changed, 238 insertions(+), 55 deletions(-) create mode 100644 tests/test_lod_bias_probe.py create mode 100644 tools/lod_bias_probe.py diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index eea330b483..752481f524 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -38,6 +38,7 @@ on: - "tools/gen_d3d12_stubs.py" - "tools/gfx10_formats.json" - "tools/lane_masks.py" + - "tools/lod_bias_probe.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" - "tools/native_pso_hashes.py" @@ -89,6 +90,7 @@ on: - "tools/gen_d3d12_stubs.py" - "tools/gfx10_formats.json" - "tools/lane_masks.py" + - "tools/lod_bias_probe.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" - "tools/native_pso_hashes.py" diff --git a/docs/design.md b/docs/design.md index d6137e2b4b..e000de3eba 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,7 +502,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 drops it from both: on an Apple M3, `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both. With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is chosen per device: `explicit_lod_bias` in `tools/vk_subgroup_info.py` (MoltenVK's driver ID), read by `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py`; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/lod_bias_probe.py` translates `vs_ids` and `ps_ssharp` without the flag, draws them with `vk_sampler_test` at LOD_BIAS 0, +1 and -1, and answers true only when +1 and -1 read the no-bias levels (false when both move as expected, null otherwise). `scripts/run_gpu_tests.py` and `make_game.py` take its answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it there, and `runtime/test/shaders/build.py` (which also runs inside the CMake build, before the test programs exist) takes only that variable. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | | `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/docs/testing.md b/docs/testing.md index 1c0fd73f82..d0845e739b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -780,7 +780,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | | `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | -| `ps_ssharp` fails on a Mac with MoltenVK 1.4.2: `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` on MoltenVK (`explicit_lod_bias` in `tools/vk_subgroup_info.py`; see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.3 cases | +| `ps_ssharp` fails on some Macs with MoltenVK 1.4.2 (an Apple M3, not an M5 Pro): `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` where `tools/lod_bias_probe.py` measures that the sampler drops the bias (see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.3 cases | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | diff --git a/make_game.py b/make_game.py index b9ca5191f8..f3b59f5fbe 100644 --- a/make_game.py +++ b/make_game.py @@ -1893,11 +1893,17 @@ def runtime_gpu_info() -> dict: def runtime_gpu_explicit_lod_bias(): - """explicit_lod_bias as tools/vk_subgroup_info.py answers for the GPU the runtime would use: True where the driver - drops the sampler's mipLodBias (MoltenVK), None when it can't tell.""" + """tools/lod_bias_probe.py's answer for the GPU the runtime would use: True where it measures that the sampler drops + mipLodBias (MoltenVK on an Apple M3, not on an M5 Pro), False where it applies it, None when it can't tell (no + vk_sampler_test in runtime/build/linux or runtime/build yet, or no answer).""" + exe = "vk_sampler_test" + (".exe" if os.name == "nt" else "") + builds = [os.path.join(ROOT, "runtime", "build", *p) for p in (("linux",), (), ("RelWithDebInfo",), ("Release",))] + build = next((b for b in builds if os.path.isfile(os.path.join(b, exe))), None) + if build is None: + return None try: - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], - capture_output=True, text=True, timeout=60) + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "lod_bias_probe.py"), "--build", build], + capture_output=True, text=True, timeout=300) v = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") return None if v is None else bool(v) except (OSError, ValueError, IndexError, subprocess.SubprocessError): @@ -3039,7 +3045,7 @@ def main() -> int: "without VK_KHR_maintenance8") ap.add_argument("--explicit-lod-bias", action="store_true", help="apply the S# LOD bias in the shaders, for a driver whose sampler drops it; on by itself " - "when the runtime's GPU is on MoltenVK") + "where tools/lod_bias_probe.py measures that (MoltenVK on an Apple M3, not on an M5 Pro)") ap.add_argument("--f16-interp-fallback", action="store_true", help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") @@ -3140,8 +3146,8 @@ def main() -> int: if "shaders" in stages and not a.explicit_lod_bias: drops_bias = runtime_gpu_explicit_lod_bias() if drops_bias is True: - log("shaders: the GPU the runtime would use drops the sampler's LOD bias (MoltenVK): translating with " - "--explicit-lod-bias") + log("shaders: tools/lod_bias_probe.py measures that the GPU the runtime would use drops the sampler's LOD " + "bias: translating with --explicit-lod-bias") a.explicit_lod_bias = True elif drops_bias is None: a.explicit_lod_bias = keep_recorded_fallback("--explicit-lod-bias", work) diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index bedb2f0b66..efff2f7a72 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -90,19 +90,11 @@ def asm_mattr(path): def explicit_lod_bias(): - """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0). Unset, it is on where tools/vk_subgroup_info.py reports explicit_lod_bias - (MoltenVK drops the sampler's mipLodBias), the rule of scripts/run_gpu_tests.py. No answer leaves it off.""" - v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() - if v in ("1", "true", "yes", "on"): - return True - if v in ("0", "false", "no", "off"): - return False - try: - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], - capture_output=True, text=True, timeout=60) - return json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") is True - except (OSError, ValueError, IndexError, subprocess.SubprocessError): - return False + """LEONIDA_EXPLICIT_LOD_BIAS=1: translate with --explicit-lod-bias, where the sampler drops mipLodBias. build.py + doesn't measure it (it also runs inside the CMake build, before the test programs exist): scripts/run_gpu_tests.py + measures it with tools/lod_bias_probe.py, and `python -I tools/lod_bias_probe.py --build ` answers + for check.py's runs.""" + return (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() in ("1", "true", "yes", "on") def asm_fssm_fields(path): @@ -211,7 +203,7 @@ def translate_tests(work, names): cmd.append("--f16-interp-fallback") if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8 cmd.append("--texel-offset-fallback") - if explicit_lod_bias(): # the S# LOD bias in the shader, where the sampler drops it (MoltenVK) + if explicit_lod_bias(): # the S# LOD bias in the shader, where the sampler drops it (LEONIDA_EXPLICIT_LOD_BIAS) cmd.append("--explicit-lod-bias") # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index e5760f8ec0..53aa5121ba 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -388,13 +388,16 @@ def _device_barycentric_fallback(): return _BARYCENTRIC_FALLBACK[0] -def _device_explicit_lod_bias(): - """explicit_lod_bias from tools/vk_subgroup_info.py (MoltenVK), cached per suite, or None.""" +def _device_explicit_lod_bias(build: str | None): + """tools/lod_bias_probe.py's answer for the device the tests run on (cached per suite), or None: it draws ps_ssharp + translated without the flag and looks whether the sampler moved the level for LOD_BIAS +1 and -1.""" if not _EXPLICIT_LOD_BIAS: answer = None try: - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], - capture_output=True, text=True, timeout=60) + if not build: + raise OSError("no test programs") + r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "lod_bias_probe.py"), "--build", build], + capture_output=True, text=True, timeout=300) answer = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") except (OSError, ValueError, IndexError, subprocess.SubprocessError): pass @@ -402,16 +405,16 @@ def _device_explicit_lod_bias(): return _EXPLICIT_LOD_BIAS[0] -def explicit_lod_bias() -> bool: - """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0): translate with --explicit-lod-bias, so an explicit-LOD sample takes the - S# LOD_BIAS in the shader. Unset, it is on where the driver drops mipLodBias there: tools/vk_subgroup_info.py - reports explicit_lod_bias true (MoltenVK).""" +def explicit_lod_bias(build: str | None) -> bool: + """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0): translate with --explicit-lod-bias, so samples take the S# LOD_BIAS in the + shader. Unset, it is on where tools/lod_bias_probe.py measures that the sampler drops mipLodBias (MoltenVK on an + Apple M3, not on an M5 Pro: a driver ID can't tell); a probe without an answer leaves it off.""" v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() if v in ("1", "true", "yes", "on"): return True if v in ("0", "false", "no", "off"): return False - return _device_explicit_lod_bias() is True + return _device_explicit_lod_bias(build) is True def w64_emulated() -> bool: @@ -969,7 +972,7 @@ def run_suite(a, work: str) -> int: cmd.append("--f16-interp-fallback") if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 cmd.append("--texel-offset-fallback") - if explicit_lod_bias(): # the S# LOD bias added to explicit LODs, which MoltenVK's sampler drops + if explicit_lod_bias(getattr(a, "build", None)): # the S# LOD bias in the shader, where the sampler drops it (measured) cmd.append("--explicit-lod-bias") if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py cmd.append("--mesh-compute") diff --git a/tests/test_lod_bias_probe.py b/tests/test_lod_bias_probe.py new file mode 100644 index 0000000000..949289ac9c --- /dev/null +++ b/tests/test_lod_bias_probe.py @@ -0,0 +1,100 @@ +"""tools/lod_bias_probe.py: whether the sampler applies mipLodBias is measured from three vk_sampler_test draws. + +No GPU: build.py and vk_sampler_test are replaced by fakes that write the readback a driver would give. The probe +answers True only when LOD_BIAS +1 and -1 both read the no-bias levels, False when both move as check.py expects, +and None for a wrong no-bias draw, a mixed answer, a failed draw or missing test programs. +Standard library only; no game files. +""" +import os +import struct +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) +import check # noqa: E402 +import lod_bias_probe # noqa: E402 + + +def image(level_lz, level_implicit): + return b"".join(struct.pack("<4f", *check.sampler_texel(level_lz, x, y), *check.sampler_texel(level_implicit, x, y)) + for y in range(check.SAMPLER_SIZE) for x in range(check.SAMPLER_SIZE)) + + +class FakeRuns: + """subprocess.run for the probe: build.py writes the two modules, vk_sampler_test the levels `levels(bias)`.""" + + def __init__(self, levels, draw_rc=0): + self.levels, self.draw_rc = levels, draw_rc + + def __call__(self, cmd, **kw): + if cmd[-2:] == ["vs_ids", "ps_ssharp"]: + spirv = Path(cmd[-3]) / "spirv" + spirv.mkdir(parents=True, exist_ok=True) + for n in ("vs_ids", "ps_ssharp"): + (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") + return subprocess.CompletedProcess(cmd, 0, "", "") + words = [int(w, 16) for w in cmd[4:8]] # vk_sampler_test vs ps raw <4 S# words> + bias = (((words[2] & 0x3fff) ^ 0x2000) - 0x2000) / 256 + if not self.draw_rc: + Path(cmd[3]).write_bytes(image(*self.levels(bias))) + return subprocess.CompletedProcess(cmd, self.draw_rc, "", "device lost" if self.draw_rc else "") + + +def applied(bias): # check.py's expectation: LOD 0 / LOD 1 plus the bias, on two levels + return (min(max(round(0 + bias), 0), 1), min(max(round(1 + bias), 0), 1)) + + +class ProbeTest(unittest.TestCase): + def setUp(self): + self.build = tempfile.TemporaryDirectory() + self.addCleanup(self.build.cleanup) + Path(self.build.name, "vk_sampler_test" + lod_bias_probe.EXE).write_bytes(b"") + + def run_probe(self, fake): + with mock.patch.object(lod_bias_probe.subprocess, "run", fake): + return lod_bias_probe.probe(self.build.name) + + def test_a_driver_that_applies_the_bias(self): + self.assertIs(self.run_probe(FakeRuns(applied))[0], False) + + def test_a_driver_that_drops_the_bias(self): + answer, reason = self.run_probe(FakeRuns(lambda bias: (0, 1))) + self.assertIs(answer, True) + self.assertIn("drops", reason) + + def test_a_mixed_answer_is_unknown(self): + # +1 applied, -1 dropped: neither rule fits, so the flag must not be chosen from it. + self.assertIsNone(self.run_probe(FakeRuns(lambda bias: applied(bias) if bias > 0 else (0, 1)))[0]) + + def test_a_wrong_no_bias_draw_is_unknown(self): + self.assertIsNone(self.run_probe(FakeRuns(lambda bias: (1, 0)))[0]) + + def test_a_failed_draw_is_unknown(self): + self.assertIsNone(self.run_probe(FakeRuns(applied, draw_rc=1))[0]) + + def test_no_test_programs_is_unknown(self): + with tempfile.TemporaryDirectory() as empty: + answer, reason = lod_bias_probe.probe(empty) + self.assertIsNone(answer) + self.assertIn("vk_sampler_test", reason) + + def test_the_probe_translates_without_the_flag(self): + seen = {} + fake = FakeRuns(applied) + + def spy(cmd, **kw): + if cmd[-2:] == ["vs_ids", "ps_ssharp"]: + seen["env"] = kw.get("env", {}).get("LEONIDA_EXPLICIT_LOD_BIAS") + return fake(cmd, **kw) + self.run_probe(spy) + self.assertEqual(seen["env"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 07f291bd45..9f8ff15b69 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -815,7 +815,6 @@ def test_native64_conditions_and_boundaries(self): "native64": want_native64, "per_vertex_inputs": True, "barycentric_fallback": False, - "explicit_lod_bias": False, "max_push_constants_size": 256, "vendor_id": 0, "device_id": 0, @@ -847,15 +846,6 @@ def test_barycentric_fallback(self): self.assertIs(res["barycentric_fallback"], want) self.assertEqual(vk_info.VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 6) - def test_explicit_lod_bias(self): - """MoltenVK drops the sampler's mipLodBias (ps_ssharp), so the translator applies the S# bias itself there.""" - for label, driver, want in (("moltenvk", vk_info.VK_DRIVER_ID_MOLTENVK, True), ("amd", 1, False), - ("radv", 3, False), ("llvmpipe", 13, False)): - with self.subTest(case=label): - res, _vk = self._run_query(FakeDevice(driver_id=driver)) - self.assertIs(res["explicit_lod_bias"], want) - self.assertEqual(vk_info.VK_DRIVER_ID_MOLTENVK, 14) - def test_barycentric_fallback_rejects_an_intel_windows_fake(self): """Intel Windows uses its Windows driver ID, not ANV; the fake must carry Intel's vendor ID.""" res, _vk = self._run_query(FakeDevice(name="Intel Arc", vendor_id=0x8086, device_id=0xE20B, diff --git a/tools/lod_bias_probe.py b/tools/lod_bias_probe.py new file mode 100644 index 0000000000..28f9bc25d8 --- /dev/null +++ b/tools/lod_bias_probe.py @@ -0,0 +1,97 @@ +"""Measure whether the Vulkan driver applies VkSamplerCreateInfo::mipLodBias, for rdna2spirv.py --explicit-lod-bias. + + python -I tools/lod_bias_probe.py --build [--json] + +The answer is measured, not looked up: MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 (ps_ssharp fails on +main) but applies it on an Apple M5 Pro (ps_ssharp passes on main), so a driver ID can't decide. The probe +translates runtime/test/shaders/vs_ids and ps_ssharp *without* the flag into a temporary folder (build.py with +LEONIDA_EXPLICIT_LOD_BIAS=0), then draws them with vk_sampler_test three times: no bias, LOD_BIAS +1 and -1 (S# words +from check.py's ssharp_words). ps_ssharp's mrt0 is (lz.r, lz.g, implicit.r, implicit.g): the explicit sample at LOD +0 and the derivative one at LOD 1, on a two-level texture. + +* no-bias draw wrong -> None (the probe can't judge this device) +* +1 and -1 both as check.py expects -> False: the driver applies the bias, the flag would count it twice +* +1 and -1 both read the no-bias levels -> True: the driver drops it, translate with --explicit-lod-bias +* anything else -> None + +The last line printed is {"explicit_lod_bias": true|false|null, "reason": "..."}; the exit status is 0 either way +(2 on a usage error). It honours the environment the tests run under (VK_DRIVER_FILES, LEONIDA_VULKAN_LOADER, ...). +Standard library only; needs llvm-mc and the SPIR-V tools build.py needs, no game files. +""" +import argparse +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +SHADERS = os.path.join(ROOT, "runtime", "test", "shaders") +EXE = ".exe" if os.name == "nt" else "" +sys.path.insert(0, SHADERS) +import check # noqa: E402 (ssharp_words, sampler_mismatch, the SAMPLER_SIZE readback layout) + + +def probe(build: str, timeout: int = 120): + """(True | False | None, reason).""" + tool = os.path.join(build, "vk_sampler_test" + EXE) + if not os.path.isfile(tool): + return None, f"no vk_sampler_test{EXE} in {build}" + with tempfile.TemporaryDirectory(prefix="leonida-lod-bias-") as tmp: + env = dict(os.environ, LEONIDA_EXPLICIT_LOD_BIAS="0") + try: + r = subprocess.run([sys.executable, "-I", os.path.join(SHADERS, "build.py"), tmp, "vs_ids", "ps_ssharp"], + capture_output=True, text=True, env=env, timeout=timeout) + except (OSError, subprocess.SubprocessError) as e: + return None, f"build.py: {e}" + shaders = [os.path.join(tmp, "spirv", n + ".spv") for n in ("vs_ids", "ps_ssharp")] + if r.returncode or not all(os.path.isfile(s) for s in shaders): + return None, "build.py could not translate vs_ids and ps_ssharp: " + (r.stdout + r.stderr).strip()[-300:] + view = (0, 1) + + def draw(bias): + words = check.ssharp_words(1, bias=bias) + raw = Path(tmp) / f"bias{bias:+}.raw" + try: + d = subprocess.run([tool, *shaders, str(raw), *(f"{w:x}" for w in words), *(str(v) for v in view)], + capture_output=True, text=True, timeout=timeout) + except (OSError, subprocess.SubprocessError) as e: + return None, f"vk_sampler_test: {e}" + if d.returncode or not raw.is_file(): + return None, f"vk_sampler_test exited {d.returncode}: " + (d.stdout + d.stderr).strip()[-200:] + data = raw.read_bytes() + return check.sampler_mismatch(data, words, view), data + + base = draw(0) + if base[0] is None: + return None, base[1] + if base[0]: + return None, f"the no-bias draw is already wrong ({base[0]})" + results = {} + for bias in (1, -1): + problem, data = draw(bias) + if problem is None: + return None, data + results[bias] = (problem, data) + if not any(p for p, _ in results.values()): + return False, "the sampler applies LOD_BIAS +1 and -1" + if all(p and data == base[1] for p, data in results.values()): + return True, "the sampler drops LOD_BIAS: +1 and -1 read the no-bias levels" + return None, "; ".join(f"bias {b:+}: {p or 'ok'}" for b, (p, _) in results.items()) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--build", required=True, help="the folder with vk_sampler_test (the GPU test programs)") + a = ap.parse_args(argv) + answer, reason = probe(a.build) + print(json.dumps({"explicit_lod_bias": answer, "reason": reason})) + return 0 + + +if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(errors="replace") + sys.exit(main()) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index a2856c156a..e5e816dece 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -78,8 +78,9 @@ # maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original # coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). TEXEL_OFFSET_FALLBACK = False -# --explicit-lod-bias: MoltenVK 1.4.2 drops VkSamplerCreateInfo::mipLodBias (ps_ssharp: neither image_sample_lz with -# a +1 S# LOD_BIAS nor the derivative-LOD image_sample with -1 moves a level). With this flag the shader applies the +# --explicit-lod-bias: MoltenVK 1.4.2 on an Apple M3 drops VkSamplerCreateInfo::mipLodBias (ps_ssharp: neither +# image_sample_lz with a +1 S# LOD_BIAS nor the derivative-LOD image_sample with -1 moves a level); on an Apple M5 Pro +# the same MoltenVK applies it, so tools/lod_bias_probe.py measures it per device. With this flag the shader applies the # S#'s signed 5.8 LOD_BIAS (word 2 [13:0]) itself: added to the Lod of explicit-LOD samples and to the bias of # _b / _c_b, as a Bias operand on implicit samples, and as a 2^bias scale of Grad derivatives (lambda = log2 of # their length). The sampler still clamps the result to MIN_LOD..MAX_LOD. Only for a driver that drops the @@ -19567,8 +19568,8 @@ def main(): help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " "the coordinate instead of the Offset operand") ap.add_argument("--explicit-lod-bias", action="store_true", - help="add the S# LOD_BIAS to the Lod of explicit-LOD samples, for a driver that drops the sampler's " - "mipLodBias there (MoltenVK 1.4.2); elsewhere the bias would count twice") + help="apply the S# LOD_BIAS in the shader, for a driver whose sampler drops mipLodBias (measured by " + "tools/lod_bias_probe.py); elsewhere the bias would count twice") ap.add_argument("--mesh-compute", action="store_true", help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index 122dc41834..d380fd279b 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -193,13 +193,6 @@ def barycentric_fallback(vendor_id: int, device_id: int, driver_id: int) -> bool or gfx90c_amd_windows(vendor_id, device_id, driver_id)) -def explicit_lod_bias(driver_id: int) -> bool: - """Drivers that drop VkSamplerCreateInfo::mipLodBias from explicit-LOD samples: MoltenVK 1.4.2 (ps_ssharp's - "point bias +1" reads level 0 through image_sample_lz). The translator then adds the S# bias itself - (rdna2spirv.py --explicit-lod-bias).""" - return driver_id == VK_DRIVER_ID_MOLTENVK - - def physical_devices(vk, instance): # The list can grow between the count and fetch. Recount, with a bound for a changing driver. for _ in range(3): @@ -373,7 +366,6 @@ def query(*, stage_caps=False) -> dict: "native64": compute64 and mesh64, "per_vertex_inputs": per_vertex, "barycentric_fallback": barycentric_fallback(vendor, device, driver), - "explicit_lod_bias": explicit_lod_bias(driver), "max_push_constants_size": max_push_constants_size, "vendor_id": vendor, "device_id": device, From a03715c46af0f674722075d40cd9827b3d5cfc98 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:38:34 +0100 Subject: [PATCH 03/14] vk_subgroup_info --lod-bias: measure mipLodBias with one compute dispatch, no test programs needed (SHADER-EXPLICIT-LOD-BIAS-MVK) tools/vk_lod_bias.py clears a two-level R32_SFLOAT image to 0.0 / 1.0 and samples it at explicit LOD 0 through samplers with mipLodBias 0 and +1, from Python through ctypes. vk_subgroup_info.py --lod-bias reports the answer as explicit_lod_bias; lod_bias_probe.py uses it first and draws ps_ssharp only as a fallback, with the Homebrew llvm-mc hint when llvm-mc is missing (#1774 review). build.py and make_game.py can now measure too. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime.yml | 2 + docs/design.md | 2 +- docs/testing.md | 2 +- make_game.py | 22 +- runtime/cmake/translator_deps.cmake | 8 +- runtime/test/shaders/build.py | 19 +- scripts/run_gpu_tests.py | 10 +- tests/test_lod_bias_probe.py | 42 +++- tests/test_vk_lod_bias.py | 57 +++++ tests/test_vk_subgroup_info.py | 23 ++ tools/lod_bias_probe.py | 45 +++- tools/vk_lod_bias.py | 339 ++++++++++++++++++++++++++++ tools/vk_subgroup_info.py | 27 ++- 13 files changed, 553 insertions(+), 45 deletions(-) create mode 100644 tests/test_vk_lod_bias.py create mode 100644 tools/vk_lod_bias.py diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 752481f524..d0748c2043 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -59,6 +59,7 @@ on: - "tools/spirv_loop_guard.py" - "tools/spirv_opt.py" - "tools/spirv_stubs.py" + - "tools/vk_lod_bias.py" - "tools/vk_subgroup_info.py" - "tools/wave64_emulate_opt.py" - "tools/wave64_halves.py" @@ -111,6 +112,7 @@ on: - "tools/spirv_loop_guard.py" - "tools/spirv_opt.py" - "tools/spirv_stubs.py" + - "tools/vk_lod_bias.py" - "tools/vk_subgroup_info.py" - "tools/wave64_emulate_opt.py" - "tools/wave64_halves.py" diff --git a/docs/design.md b/docs/design.md index e000de3eba..85769839e2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,7 +502,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/lod_bias_probe.py` translates `vs_ids` and `ps_ssharp` without the flag, draws them with `vk_sampler_test` at LOD_BIAS 0, +1 and -1, and answers true only when +1 and -1 read the no-bias levels (false when both move as expected, null otherwise). `scripts/run_gpu_tests.py` and `make_game.py` take its answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it there, and `runtime/test/shaders/build.py` (which also runs inside the CMake build, before the test programs exist) takes only that variable. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | | `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/docs/testing.md b/docs/testing.md index d0845e739b..f3a8a76cd7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -780,7 +780,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | | `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | | `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | -| `ps_ssharp` fails on some Macs with MoltenVK 1.4.2 (an Apple M3, not an M5 Pro): `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` where `tools/lod_bias_probe.py` measures that the sampler drops the bias (see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.3 cases | +| `ps_ssharp` fails on some Macs with MoltenVK 1.4.2 (an Apple M3, not an M5 Pro): `point bias +1: (0,0): (1.0, 0.0, 0.502, 0.502) != (0.502, 0.502, 0.502, 0.502)` | MoltenVK drops the sampler's `mipLodBias`, so the S#'s `LOD_BIAS` moves neither the explicit nor the derivative LOD | Current `main` translates with `--explicit-lod-bias` where `tools/vk_subgroup_info.py --lod-bias` measures that the sampler drops the bias (see "S# LOD bias without the sampler's `mipLodBias`" in [design.md](design.md)). Forcing it on another driver (`LEONIDA_EXPLICIT_LOD_BIAS=1`) counts the bias twice and fails the +-0.3 cases | | `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | | On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | diff --git a/make_game.py b/make_game.py index f3b59f5fbe..b1603e308f 100644 --- a/make_game.py +++ b/make_game.py @@ -1893,13 +1893,15 @@ def runtime_gpu_info() -> dict: def runtime_gpu_explicit_lod_bias(): - """tools/lod_bias_probe.py's answer for the GPU the runtime would use: True where it measures that the sampler drops - mipLodBias (MoltenVK on an Apple M3, not on an M5 Pro), False where it applies it, None when it can't tell (no - vk_sampler_test in runtime/build/linux or runtime/build yet, or no answer).""" - exe = "vk_sampler_test" + (".exe" if os.name == "nt" else "") - builds = [os.path.join(ROOT, "runtime", "build", *p) for p in (("linux",), (), ("RelWithDebInfo",), ("Release",))] - build = next((b for b in builds if os.path.isfile(os.path.join(b, exe))), None) - if build is None: + """explicit_lod_bias as tools/vk_subgroup_info.py --lod-bias measures it on the GPU the runtime would use (one + compute dispatch): True where the sampler drops mipLodBias (MoltenVK on an Apple M3, not on an M5 Pro), False + where it applies it, None when it can't tell.""" + try: + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py"), "--lod-bias"], + capture_output=True, text=True, timeout=60) + v = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") + return None if v is None else bool(v) + except (OSError, ValueError, IndexError, subprocess.SubprocessError): return None try: r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "lod_bias_probe.py"), "--build", build], @@ -3045,7 +3047,7 @@ def main() -> int: "without VK_KHR_maintenance8") ap.add_argument("--explicit-lod-bias", action="store_true", help="apply the S# LOD bias in the shaders, for a driver whose sampler drops it; on by itself " - "where tools/lod_bias_probe.py measures that (MoltenVK on an Apple M3, not on an M5 Pro)") + "where tools/vk_subgroup_info.py --lod-bias measures that (MoltenVK on an Apple M3, not an M5 Pro)") ap.add_argument("--f16-interp-fallback", action="store_true", help="16-bit interpolation from decoded halves the vertex/mesh shader exports instead of " "PerVertexKHR inputs; on by itself when the runtime's GPU can't use them (MoltenVK)") @@ -3146,8 +3148,8 @@ def main() -> int: if "shaders" in stages and not a.explicit_lod_bias: drops_bias = runtime_gpu_explicit_lod_bias() if drops_bias is True: - log("shaders: tools/lod_bias_probe.py measures that the GPU the runtime would use drops the sampler's LOD " - "bias: translating with --explicit-lod-bias") + log("shaders: tools/vk_subgroup_info.py --lod-bias measures that the GPU the runtime would use drops the " + "sampler's LOD bias: translating with --explicit-lod-bias") a.explicit_lod_bias = True elif drops_bias is None: a.explicit_lod_bias = keep_recorded_fallback("--explicit-lod-bias", work) diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 0cb1ecdf86..a8a3a2acc4 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake @@ -1,6 +1,7 @@ -# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py -# and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in -# make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer. +# The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py, +# tools/vk_subgroup_info.py, whose answer picks --bary-fallback, and tools/vk_lod_bias.py, which its --lod-bias +# measurement imports for --explicit-lod-bias). Track the shader-stage dependencies in make_game.py's +# TRANSLATION_SOURCES here too, including the native PSO catalog writer. # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. @@ -32,6 +33,7 @@ set(LEONIDA_TRANSLATOR_DEPS ${_leonida_repo}/tools/spirv_loop_guard.py ${_leonida_repo}/tools/spirv_opt.py ${_leonida_repo}/tools/spirv_stubs.py + ${_leonida_repo}/tools/vk_lod_bias.py ${_leonida_repo}/tools/vk_subgroup_info.py ${_leonida_repo}/tools/wave64_emulate_opt.py ${_leonida_repo}/tools/wave64_halves.py) diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index efff2f7a72..3908e7679a 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -90,11 +90,20 @@ def asm_mattr(path): def explicit_lod_bias(): - """LEONIDA_EXPLICIT_LOD_BIAS=1: translate with --explicit-lod-bias, where the sampler drops mipLodBias. build.py - doesn't measure it (it also runs inside the CMake build, before the test programs exist): scripts/run_gpu_tests.py - measures it with tools/lod_bias_probe.py, and `python -I tools/lod_bias_probe.py --build ` answers - for check.py's runs.""" - return (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() in ("1", "true", "yes", "on") + """LEONIDA_EXPLICIT_LOD_BIAS=1 (or 0). Unset, it is on where tools/vk_subgroup_info.py --lod-bias measures that + the sampler drops mipLodBias (one compute dispatch from Python, no test programs needed), the rule of + scripts/run_gpu_tests.py. No answer leaves it off.""" + v = (os.environ.get("LEONIDA_EXPLICIT_LOD_BIAS") or "").strip().lower() + if v in ("1", "true", "yes", "on"): + return True + if v in ("0", "false", "no", "off"): + return False + try: + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py"), "--lod-bias"], + capture_output=True, text=True, timeout=60) + return json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") is True + except (OSError, ValueError, IndexError, AttributeError, subprocess.SubprocessError): + return False def asm_fssm_fields(path): diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 53aa5121ba..cb24f4eeac 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -389,15 +389,13 @@ def _device_barycentric_fallback(): def _device_explicit_lod_bias(build: str | None): - """tools/lod_bias_probe.py's answer for the device the tests run on (cached per suite), or None: it draws ps_ssharp - translated without the flag and looks whether the sampler moved the level for LOD_BIAS +1 and -1.""" + """tools/lod_bias_probe.py's answer for the device the tests run on (cached per suite), or None: vk_subgroup_info.py + --lod-bias's compute measurement, else (with the test programs) ps_ssharp drawn without the flag.""" if not _EXPLICIT_LOD_BIAS: answer = None try: - if not build: - raise OSError("no test programs") - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "lod_bias_probe.py"), "--build", build], - capture_output=True, text=True, timeout=300) + r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "lod_bias_probe.py"), + *(["--build", build] if build else [])], capture_output=True, text=True, timeout=300) answer = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") except (OSError, ValueError, IndexError, subprocess.SubprocessError): pass diff --git a/tests/test_lod_bias_probe.py b/tests/test_lod_bias_probe.py index 949289ac9c..952418485f 100644 --- a/tests/test_lod_bias_probe.py +++ b/tests/test_lod_bias_probe.py @@ -1,10 +1,12 @@ -"""tools/lod_bias_probe.py: whether the sampler applies mipLodBias is measured from three vk_sampler_test draws. +"""tools/lod_bias_probe.py: tools/vk_subgroup_info.py --lod-bias first, else three vk_sampler_test draws. -No GPU: build.py and vk_sampler_test are replaced by fakes that write the readback a driver would give. The probe -answers True only when LOD_BIAS +1 and -1 both read the no-bias levels, False when both move as check.py expects, -and None for a wrong no-bias draw, a mixed answer, a failed draw or missing test programs. +No GPU: vk_subgroup_info.py, build.py and vk_sampler_test are replaced by fakes. An answer from vk_subgroup_info.py +is used as it is, with no draw. Without one, the draw answers True only when LOD_BIAS +1 and -1 both read the +no-bias levels, False when both move as check.py expects, and None for a wrong no-bias draw, a mixed answer, a +failed draw or missing test programs. Standard library only; no game files. """ +import json import os import struct import subprocess @@ -29,10 +31,13 @@ def image(level_lz, level_implicit): class FakeRuns: """subprocess.run for the probe: build.py writes the two modules, vk_sampler_test the levels `levels(bias)`.""" - def __init__(self, levels, draw_rc=0): - self.levels, self.draw_rc = levels, draw_rc + def __init__(self, levels, draw_rc=0, info=None): + self.levels, self.draw_rc, self.info, self.draws = levels, draw_rc, info, 0 def __call__(self, cmd, **kw): + if cmd[-1] == "--lod-bias": # vk_subgroup_info.py --lod-bias + return subprocess.CompletedProcess(cmd, 0, json.dumps(self.info or {"explicit_lod_bias": None}), "") + self.draws += 1 if cmd[-2:] == ["vs_ids", "ps_ssharp"]: spirv = Path(cmd[-3]) / "spirv" spirv.mkdir(parents=True, exist_ok=True) @@ -60,6 +65,10 @@ def run_probe(self, fake): with mock.patch.object(lod_bias_probe.subprocess, "run", fake): return lod_bias_probe.probe(self.build.name) + def run_draw(self, fake): + with mock.patch.object(lod_bias_probe.subprocess, "run", fake): + return lod_bias_probe.draw_probe(self.build.name) + def test_a_driver_that_applies_the_bias(self): self.assertIs(self.run_probe(FakeRuns(applied))[0], False) @@ -80,10 +89,29 @@ def test_a_failed_draw_is_unknown(self): def test_no_test_programs_is_unknown(self): with tempfile.TemporaryDirectory() as empty: - answer, reason = lod_bias_probe.probe(empty) + answer, reason = lod_bias_probe.draw_probe(empty) self.assertIsNone(answer) self.assertIn("vk_sampler_test", reason) + def test_a_measured_answer_needs_no_draw(self): + for answer in (True, False): + with self.subTest(answer=answer): + fake = FakeRuns(lambda bias: (1, 0), info={"explicit_lod_bias": answer, "explicit_lod_bias_reason": "m"}) + self.assertEqual(self.run_probe(fake), (answer, "m")) + self.assertEqual(fake.draws, 0) + + def test_an_error_from_vk_subgroup_info_falls_back_to_the_draw(self): + fake = FakeRuns(lambda bias: (0, 1), info={"error": "RuntimeError: no Vulkan device"}) + self.assertIs(self.run_probe(fake)[0], True) + self.assertGreater(fake.draws, 0) + + def test_without_test_programs_only_the_measurement_answers(self): + fake = FakeRuns(applied) + with mock.patch.object(lod_bias_probe.subprocess, "run", fake): + answer, _ = lod_bias_probe.probe(None) + self.assertIsNone(answer) + self.assertEqual(fake.draws, 0) + def test_the_probe_translates_without_the_flag(self): seen = {} fake = FakeRuns(applied) diff --git a/tests/test_vk_lod_bias.py b/tests/test_vk_lod_bias.py new file mode 100644 index 0000000000..452f19f4ed --- /dev/null +++ b/tests/test_vk_lod_bias.py @@ -0,0 +1,57 @@ +"""tools/vk_lod_bias.py: the mipLodBias measurement tools/vk_subgroup_info.py --lod-bias runs. + +No GPU: the verdict is checked from the two texels the compute shader returns, a Vulkan library without the calls +gives "unknown", and the embedded SPIR-V is checked for its header (and with spirv-val when it is on PATH). +Standard library only; no game files. +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +import vk_lod_bias # noqa: E402 + + +class VerdictTest(unittest.TestCase): + def test_the_two_texels_decide(self): + # level 0 holds 0.0 and level 1 holds 1.0; the shader samples LOD 0 with mipLodBias 0 and +1 + self.assertIs(vk_lod_bias.verdict(0.0, 1.0)[0], False) # the sampler applies the bias + self.assertIs(vk_lod_bias.verdict(0.0, 0.0)[0], True) # the sampler drops it + for plain, biased in ((1.0, 1.0), (1.0, 0.0), (0.0, 0.5), (float("nan"), 0.0)): + with self.subTest(plain=plain, biased=biased): + answer, reason = vk_lod_bias.verdict(plain, biased) + self.assertIsNone(answer) + self.assertIn("unexpected", reason) + + +class MeasureTest(unittest.TestCase): + def test_a_library_without_the_calls_is_unknown(self): + answer, reason = vk_lod_bias.measure(object(), 0x1) + self.assertIsNone(answer) + self.assertIn("lacks a call", reason) + + +class ShaderTest(unittest.TestCase): + def test_the_words_are_a_spirv_module(self): + words = vk_lod_bias.SHADER_WORDS + self.assertEqual(words[0], 0x07230203) # SPIR-V magic + self.assertLessEqual(words[1], 0x00010000) # SPIR-V 1.0, so any Vulkan 1.0 device takes it + self.assertTrue(all(0 <= w <= 0xFFFFFFFF for w in words)) + + @unittest.skipUnless(shutil.which("spirv-val"), "spirv-val not on PATH") + def test_spirv_val_accepts_it(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "lod_bias.spv") + with open(path, "wb") as f: + f.write(struct.pack(f"<{len(vk_lod_bias.SHADER_WORDS)}I", *vk_lod_bias.SHADER_WORDS)) + r = subprocess.run(["spirv-val", "--target-env", "vulkan1.0", path], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 9f8ff15b69..3c502ee782 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -846,6 +846,29 @@ def test_barycentric_fallback(self): self.assertIs(res["barycentric_fallback"], want) self.assertEqual(vk_info.VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 6) + def test_lod_bias_is_measured_only_when_asked(self): + """--lod-bias adds tools/vk_lod_bias.py's answer for the chosen device; without it nothing runs on the GPU.""" + import vk_lod_bias + with mock.patch.object(vk_lod_bias, "measure", return_value=(True, "drops")) as measure: + res, _vk = self._run_query(FakeDevice()) + self.assertNotIn("explicit_lod_bias", res) + measure.assert_not_called() + vk = FakeVulkan(devices=(FakeDevice(),)) + with mock.patch.object(vk_info, "load_vulkan", return_value=vk): + res = vk_info.query(lod_bias=True) + self.assertIs(res["explicit_lod_bias"], True) + self.assertEqual(res["explicit_lod_bias_reason"], "drops") + self.assertEqual(measure.call_args.args[1].value, 0x20000001) # the chosen device's handle + + def test_a_lod_bias_measurement_that_fails_is_unknown(self): + import vk_lod_bias + vk = FakeVulkan(devices=(FakeDevice(),)) + with mock.patch.object(vk_lod_bias, "measure", side_effect=OSError("device lost")), \ + mock.patch.object(vk_info, "load_vulkan", return_value=vk): + res = vk_info.query(lod_bias=True) + self.assertIsNone(res["explicit_lod_bias"]) + self.assertIn("device lost", res["explicit_lod_bias_reason"]) + def test_barycentric_fallback_rejects_an_intel_windows_fake(self): """Intel Windows uses its Windows driver ID, not ANV; the fake must carry Intel's vendor ID.""" res, _vk = self._run_query(FakeDevice(name="Intel Arc", vendor_id=0x8086, device_id=0xE20B, diff --git a/tools/lod_bias_probe.py b/tools/lod_bias_probe.py index 28f9bc25d8..ac5421a2c7 100644 --- a/tools/lod_bias_probe.py +++ b/tools/lod_bias_probe.py @@ -1,10 +1,13 @@ """Measure whether the Vulkan driver applies VkSamplerCreateInfo::mipLodBias, for rdna2spirv.py --explicit-lod-bias. - python -I tools/lod_bias_probe.py --build [--json] + python -I tools/lod_bias_probe.py [--build ] The answer is measured, not looked up: MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 (ps_ssharp fails on -main) but applies it on an Apple M5 Pro (ps_ssharp passes on main), so a driver ID can't decide. The probe -translates runtime/test/shaders/vs_ids and ps_ssharp *without* the flag into a temporary folder (build.py with +main) but applies it on an Apple M5 Pro (ps_ssharp passes on main), so a driver ID can't decide. + +First it asks tools/vk_subgroup_info.py --lod-bias, which measures it with one compute dispatch from Python +(tools/vk_lod_bias.py) and needs no built test programs, llvm-mc or SPIR-V tools. Only when that has no answer and +--build names the test programs does it fall back to the draw below. The draw translates runtime/test/shaders/vs_ids and ps_ssharp *without* the flag into a temporary folder (build.py with LEONIDA_EXPLICIT_LOD_BIAS=0), then draws them with vk_sampler_test three times: no bias, LOD_BIAS +1 and -1 (S# words from check.py's ssharp_words). ps_ssharp's mrt0 is (lz.r, lz.g, implicit.r, implicit.g): the explicit sample at LOD 0 and the derivative one at LOD 1, on a two-level texture. @@ -34,8 +37,30 @@ import check # noqa: E402 (ssharp_words, sampler_mismatch, the SAMPLER_SIZE readback layout) -def probe(build: str, timeout: int = 120): - """(True | False | None, reason).""" +def subgroup_info_answer(timeout: int = 120): + """(True | False | None, reason) from tools/vk_subgroup_info.py --lod-bias.""" + try: + r = subprocess.run([sys.executable, "-I", os.path.join(HERE, "vk_subgroup_info.py"), "--lod-bias"], + capture_output=True, text=True, timeout=timeout) + answer = json.loads(r.stdout.strip().splitlines()[-1]) + except (OSError, ValueError, IndexError, subprocess.SubprocessError) as e: + return None, f"vk_subgroup_info.py --lod-bias: {e}" + if "error" in answer: + return None, f"vk_subgroup_info.py --lod-bias: {answer['error']}" + return answer.get("explicit_lod_bias"), answer.get("explicit_lod_bias_reason", "") + + +def probe(build: str | None = None, timeout: int = 120): + """(True | False | None, reason): vk_subgroup_info.py's measurement, else the vk_sampler_test draw.""" + answer, reason = subgroup_info_answer(timeout) + if answer is not None or not build: + return answer, reason + drawn, why = draw_probe(build, timeout) + return drawn, why if drawn is not None else f"{reason}; {why}" + + +def draw_probe(build: str, timeout: int = 120): + """(True | False | None, reason) from three vk_sampler_test draws of ps_ssharp.""" tool = os.path.join(build, "vk_sampler_test" + EXE) if not os.path.isfile(tool): return None, f"no vk_sampler_test{EXE} in {build}" @@ -48,7 +73,13 @@ def probe(build: str, timeout: int = 120): return None, f"build.py: {e}" shaders = [os.path.join(tmp, "spirv", n + ".spv") for n in ("vs_ids", "ps_ssharp")] if r.returncode or not all(os.path.isfile(s) for s in shaders): - return None, "build.py could not translate vs_ids and ps_ssharp: " + (r.stdout + r.stderr).strip()[-300:] + out = (r.stdout + r.stderr).strip() + if "llvm-mc" in out and "could not be started" in out: + # Homebrew's llvm is keg-only: say what to set instead of a bare "could not be started". + sys.path.insert(0, HERE) + import mc_command # noqa: E402 + return None, "the draw needs llvm-mc to translate ps_ssharp: " + mc_command.install_hint() + return None, "build.py could not translate vs_ids and ps_ssharp: " + out[-300:] view = (0, 1) def draw(bias): @@ -84,7 +115,7 @@ def draw(bias): def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--build", required=True, help="the folder with vk_sampler_test (the GPU test programs)") + ap.add_argument("--build", help="the folder with vk_sampler_test, for the draw fallback (the GPU test programs)") a = ap.parse_args(argv) answer, reason = probe(a.build) print(json.dumps({"explicit_lod_bias": answer, "reason": reason})) diff --git a/tools/vk_lod_bias.py b/tools/vk_lod_bias.py new file mode 100644 index 0000000000..1bdbcde20e --- /dev/null +++ b/tools/vk_lod_bias.py @@ -0,0 +1,339 @@ +"""Measure whether a Vulkan device applies VkSamplerCreateInfo::mipLodBias, with no built test programs. + +tools/vk_subgroup_info.py --lod-bias calls measure() for the device it picks and reports the answer as +"explicit_lod_bias". The same MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 and applies it on an Apple M5 +Pro (#1774), so the answer is measured, not looked up: a 4x4 R32_SFLOAT image gets 0.0 in level 0 and 1.0 in level 1 +(vkCmdClearColorImage), and one compute invocation samples it at explicit LOD 0 through a sampler with mipLodBias 0 +and one with +1 (nearest filters and mips, clamp to edge), writing both texels to a host-visible buffer. + +* plain 0.0, biased 1.0 -> False: the sampler applies the bias (rdna2spirv.py --explicit-lod-bias would count it twice) +* plain 0.0, biased 0.0 -> True: the sampler drops it (translate with --explicit-lod-bias) +* anything else, or any Vulkan error -> None, with the reason + +The shader is SHADER_WORDS, compiled from this GLSL with glslangValidator -V -g0 --target-env vulkan1.0: + + #version 450 + layout(local_size_x = 1) in; + layout(set = 0, binding = 0) uniform sampler2D plain; + layout(set = 0, binding = 1) uniform sampler2D biased; + layout(set = 0, binding = 2) buffer Out { float r[2]; }; + void main() { + r[0] = textureLod(plain, vec2(0.5), 0.0).r; + r[1] = textureLod(biased, vec2(0.5), 0.0).r; + } + +Standard library only (ctypes); 64-bit struct layouts, as vk_subgroup_info.py. No game files. +""" +import ctypes +import struct + +SHADER_WORDS = ( + 0x07230203, 0x00010000, 0x0008000b, 0x00000027, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, + 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0005000f, 0x00000005, + 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, 0x00000001, 0x00000001, 0x00000001, + 0x00040047, 0x00000009, 0x00000006, 0x00000004, 0x00030047, 0x0000000a, 0x00000003, 0x00050048, 0x0000000a, + 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x0000000c, 0x00000021, 0x00000002, 0x00040047, 0x0000000c, + 0x00000022, 0x00000000, 0x00040047, 0x00000012, 0x00000021, 0x00000000, 0x00040047, 0x00000012, 0x00000022, + 0x00000000, 0x00040047, 0x0000001f, 0x00000021, 0x00000001, 0x00040047, 0x0000001f, 0x00000022, 0x00000000, + 0x00040047, 0x00000026, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, + 0x00030016, 0x00000006, 0x00000020, 0x00040015, 0x00000007, 0x00000020, 0x00000000, 0x0004002b, 0x00000007, + 0x00000008, 0x00000002, 0x0004001c, 0x00000009, 0x00000006, 0x00000008, 0x0003001e, 0x0000000a, 0x00000009, + 0x00040020, 0x0000000b, 0x00000002, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000002, 0x00040015, + 0x0000000d, 0x00000020, 0x00000001, 0x0004002b, 0x0000000d, 0x0000000e, 0x00000000, 0x00090019, 0x0000000f, + 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000010, + 0x0000000f, 0x00040020, 0x00000011, 0x00000000, 0x00000010, 0x0004003b, 0x00000011, 0x00000012, 0x00000000, + 0x00040017, 0x00000014, 0x00000006, 0x00000002, 0x0004002b, 0x00000006, 0x00000015, 0x3f000000, 0x0005002c, + 0x00000014, 0x00000016, 0x00000015, 0x00000015, 0x0004002b, 0x00000006, 0x00000017, 0x00000000, 0x00040017, + 0x00000018, 0x00000006, 0x00000004, 0x0004002b, 0x00000007, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c, + 0x00000002, 0x00000006, 0x0004002b, 0x0000000d, 0x0000001e, 0x00000001, 0x0004003b, 0x00000011, 0x0000001f, + 0x00000000, 0x00040017, 0x00000024, 0x00000007, 0x00000003, 0x0004002b, 0x00000007, 0x00000025, 0x00000001, + 0x0006002c, 0x00000024, 0x00000026, 0x00000025, 0x00000025, 0x00000025, 0x00050036, 0x00000002, 0x00000004, + 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000010, 0x00000013, 0x00000012, 0x00070058, + 0x00000018, 0x00000019, 0x00000013, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x0000001b, + 0x00000019, 0x00000000, 0x00060041, 0x0000001c, 0x0000001d, 0x0000000c, 0x0000000e, 0x0000000e, 0x0003003e, + 0x0000001d, 0x0000001b, 0x0004003d, 0x00000010, 0x00000020, 0x0000001f, 0x00070058, 0x00000018, 0x00000021, + 0x00000020, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x00000022, 0x00000021, 0x00000000, + 0x00060041, 0x0000001c, 0x00000023, 0x0000000c, 0x0000000e, 0x0000001e, 0x0003003e, 0x00000023, 0x00000022, + 0x000100fd, 0x00010038 +) + +u32, u64, f32, vp = ctypes.c_uint32, ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p + + +def _s(name, fields): + return type(name, (ctypes.Structure,), {"_fields_": fields}) + + +QueueCreateInfo = _s("QueueCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueFamilyIndex", u32), + ("queueCount", u32), ("pQueuePriorities", ctypes.POINTER(f32))]) +DeviceCreateInfo = _s("DeviceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("queueCreateInfoCount", u32), + ("pQueueCreateInfos", ctypes.POINTER(QueueCreateInfo)), + ("enabledLayerCount", u32), ("ppEnabledLayerNames", vp), + ("enabledExtensionCount", u32), + ("ppEnabledExtensionNames", ctypes.POINTER(ctypes.c_char_p)), + ("pEnabledFeatures", vp)]) +QueueFamily = _s("QueueFamily", [("queueFlags", u32), ("queueCount", u32), ("timestampValidBits", u32), + ("granularity", u32 * 3)]) +Extent3D = _s("Extent3D", [("width", u32), ("height", u32), ("depth", u32)]) +ImageCreateInfo = _s("ImageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("imageType", u32), + ("format", u32), ("extent", Extent3D), ("mipLevels", u32), + ("arrayLayers", u32), ("samples", u32), ("tiling", u32), ("usage", u32), + ("sharingMode", u32), ("queueFamilyIndexCount", u32), + ("pQueueFamilyIndices", vp), ("initialLayout", u32)]) +MemoryRequirements = _s("MemoryRequirements", [("size", u64), ("alignment", u64), ("memoryTypeBits", u32)]) +MemoryType = _s("MemoryType", [("propertyFlags", u32), ("heapIndex", u32)]) +MemoryHeap = _s("MemoryHeap", [("size", u64), ("flags", u32)]) +MemoryProperties = _s("MemoryProperties", [("memoryTypeCount", u32), ("memoryTypes", MemoryType * 32), + ("memoryHeapCount", u32), ("memoryHeaps", MemoryHeap * 16)]) +MemoryAllocateInfo = _s("MemoryAllocateInfo", [("sType", u32), ("pNext", vp), ("allocationSize", u64), + ("memoryTypeIndex", u32)]) +SubresourceRange = _s("SubresourceRange", [("aspectMask", u32), ("baseMipLevel", u32), ("levelCount", u32), + ("baseArrayLayer", u32), ("layerCount", u32)]) +ImageViewCreateInfo = _s("ImageViewCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("image", u64), + ("viewType", u32), ("format", u32), ("components", u32 * 4), + ("subresourceRange", SubresourceRange)]) +SamplerCreateInfo = _s("SamplerCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("magFilter", u32), + ("minFilter", u32), ("mipmapMode", u32), ("addressModeU", u32), + ("addressModeV", u32), ("addressModeW", u32), ("mipLodBias", f32), + ("anisotropyEnable", u32), ("maxAnisotropy", f32), + ("compareEnable", u32), ("compareOp", u32), ("minLod", f32), + ("maxLod", f32), ("borderColor", u32), + ("unnormalizedCoordinates", u32)]) +BufferCreateInfo = _s("BufferCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("size", u64), + ("usage", u32), ("sharingMode", u32), ("queueFamilyIndexCount", u32), + ("pQueueFamilyIndices", vp)]) +LayoutBinding = _s("LayoutBinding", [("binding", u32), ("descriptorType", u32), ("descriptorCount", u32), + ("stageFlags", u32), ("pImmutableSamplers", vp)]) +SetLayoutCreateInfo = _s("SetLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("bindingCount", u32), + ("pBindings", ctypes.POINTER(LayoutBinding))]) +PoolSize = _s("PoolSize", [("type", u32), ("descriptorCount", u32)]) +PoolCreateInfo = _s("PoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("maxSets", u32), + ("poolSizeCount", u32), ("pPoolSizes", ctypes.POINTER(PoolSize))]) +SetAllocateInfo = _s("SetAllocateInfo", [("sType", u32), ("pNext", vp), ("descriptorPool", u64), + ("descriptorSetCount", u32), ("pSetLayouts", ctypes.POINTER(u64))]) +DescriptorImageInfo = _s("DescriptorImageInfo", [("sampler", u64), ("imageView", u64), ("imageLayout", u32)]) +DescriptorBufferInfo = _s("DescriptorBufferInfo", [("buffer", u64), ("offset", u64), ("range", u64)]) +WriteDescriptorSet = _s("WriteDescriptorSet", [("sType", u32), ("pNext", vp), ("dstSet", u64), ("dstBinding", u32), + ("dstArrayElement", u32), ("descriptorCount", u32), + ("descriptorType", u32), + ("pImageInfo", ctypes.POINTER(DescriptorImageInfo)), + ("pBufferInfo", ctypes.POINTER(DescriptorBufferInfo)), + ("pTexelBufferView", vp)]) +ShaderModuleCreateInfo = _s("ShaderModuleCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), + ("codeSize", ctypes.c_size_t), ("pCode", ctypes.POINTER(u32))]) +PipelineLayoutCreateInfo = _s("PipelineLayoutCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), + ("setLayoutCount", u32), + ("pSetLayouts", ctypes.POINTER(u64)), + ("pushConstantRangeCount", u32), + ("pPushConstantRanges", vp)]) +StageCreateInfo = _s("StageCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), ("stage", u32), + ("module", u64), ("pName", ctypes.c_char_p), ("pSpecializationInfo", vp)]) +ComputePipelineCreateInfo = _s("ComputePipelineCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), + ("stage", StageCreateInfo), ("layout", u64), + ("basePipelineHandle", u64), + ("basePipelineIndex", ctypes.c_int32)]) +CommandPoolCreateInfo = _s("CommandPoolCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32), + ("queueFamilyIndex", u32)]) +CommandBufferAllocateInfo = _s("CommandBufferAllocateInfo", [("sType", u32), ("pNext", vp), ("commandPool", u64), + ("level", u32), ("commandBufferCount", u32)]) +CommandBufferBeginInfo = _s("CommandBufferBeginInfo", [("sType", u32), ("pNext", vp), ("flags", u32), + ("pInheritanceInfo", vp)]) +ImageMemoryBarrier = _s("ImageMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32), + ("dstAccessMask", u32), ("oldLayout", u32), ("newLayout", u32), + ("srcQueueFamilyIndex", u32), ("dstQueueFamilyIndex", u32), + ("image", u64), ("subresourceRange", SubresourceRange)]) +BufferMemoryBarrier = _s("BufferMemoryBarrier", [("sType", u32), ("pNext", vp), ("srcAccessMask", u32), + ("dstAccessMask", u32), ("srcQueueFamilyIndex", u32), + ("dstQueueFamilyIndex", u32), ("buffer", u64), ("offset", u64), + ("size", u64)]) +SubmitInfo = _s("SubmitInfo", [("sType", u32), ("pNext", vp), ("waitSemaphoreCount", u32), ("pWaitSemaphores", vp), + ("pWaitDstStageMask", vp), ("commandBufferCount", u32), + ("pCommandBuffers", ctypes.POINTER(vp)), ("signalSemaphoreCount", u32), + ("pSignalSemaphores", vp)]) +FenceCreateInfo = _s("FenceCreateInfo", [("sType", u32), ("pNext", vp), ("flags", u32)]) + +R32_SFLOAT, LEVELS, SIZE = 100, 2, 4 +QUEUE_COMPUTE = 0x2 +IGNORED = 0xFFFFFFFF +WHOLE = 0xFFFFFFFFFFFFFFFF + + +class VkFailure(RuntimeError): + pass + + +def _check(name, result): + if result != 0: + raise VkFailure(f"{name} failed ({result})") + + +def _proto(vk): + """argtypes for every call measure() makes (all pointers and 64-bit handles).""" + names = { + "vkGetPhysicalDeviceQueueFamilyProperties": [vp, vp, vp], + "vkGetPhysicalDeviceMemoryProperties": [vp, vp], + "vkCreateDevice": [vp, vp, vp, vp], "vkDestroyDevice": [vp, vp], "vkGetDeviceQueue": [vp, u32, u32, vp], + "vkCreateImage": [vp, vp, vp, vp], "vkDestroyImage": [vp, u64, vp], + "vkGetImageMemoryRequirements": [vp, u64, vp], "vkGetBufferMemoryRequirements": [vp, u64, vp], + "vkAllocateMemory": [vp, vp, vp, vp], "vkFreeMemory": [vp, u64, vp], + "vkBindImageMemory": [vp, u64, u64, u64], "vkBindBufferMemory": [vp, u64, u64, u64], + "vkMapMemory": [vp, u64, u64, u64, u32, vp], "vkUnmapMemory": [vp, u64], + "vkCreateImageView": [vp, vp, vp, vp], "vkDestroyImageView": [vp, u64, vp], + "vkCreateSampler": [vp, vp, vp, vp], "vkDestroySampler": [vp, u64, vp], + "vkCreateBuffer": [vp, vp, vp, vp], "vkDestroyBuffer": [vp, u64, vp], + "vkCreateDescriptorSetLayout": [vp, vp, vp, vp], "vkDestroyDescriptorSetLayout": [vp, u64, vp], + "vkCreateDescriptorPool": [vp, vp, vp, vp], "vkDestroyDescriptorPool": [vp, u64, vp], + "vkAllocateDescriptorSets": [vp, vp, vp], "vkUpdateDescriptorSets": [vp, u32, vp, u32, vp], + "vkCreateShaderModule": [vp, vp, vp, vp], "vkDestroyShaderModule": [vp, u64, vp], + "vkCreatePipelineLayout": [vp, vp, vp, vp], "vkDestroyPipelineLayout": [vp, u64, vp], + "vkCreateComputePipelines": [vp, u64, u32, vp, vp, vp], "vkDestroyPipeline": [vp, u64, vp], + "vkCreateCommandPool": [vp, vp, vp, vp], "vkDestroyCommandPool": [vp, u64, vp], + "vkAllocateCommandBuffers": [vp, vp, vp], "vkBeginCommandBuffer": [vp, vp], "vkEndCommandBuffer": [vp], + "vkCmdPipelineBarrier": [vp, u32, u32, u32, u32, vp, u32, vp, u32, vp], + "vkCmdClearColorImage": [vp, u64, u32, vp, u32, vp], + "vkCmdBindPipeline": [vp, u32, u64], "vkCmdBindDescriptorSets": [vp, u32, u64, u32, u32, vp, u32, vp], + "vkCmdDispatch": [vp, u32, u32, u32], + "vkCreateFence": [vp, vp, vp, vp], "vkDestroyFence": [vp, u64, vp], + "vkQueueSubmit": [vp, u32, vp, u64], "vkWaitForFences": [vp, u32, vp, u32, u64], + } + for name, args in names.items(): + getattr(vk, name).argtypes = args + + +def _memory_type(props, bits, wanted): + for i in range(props.memoryTypeCount): + if bits >> i & 1 and props.memoryTypes[i].propertyFlags & wanted == wanted: + return i + raise VkFailure(f"no memory type with flags {wanted:#x}") + + +def measure(vk, physical_device, extensions=()): + """(True | False | None, reason) for one physical device; `extensions` are its extension names (bytes).""" + try: + _proto(vk) + except AttributeError as e: + return None, f"the Vulkan library lacks a call: {e}" + pd = ctypes.c_void_p(physical_device) if not isinstance(physical_device, ctypes.c_void_p) else physical_device + count = u32() + vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), None) + families = (QueueFamily * count.value)() + vk.vkGetPhysicalDeviceQueueFamilyProperties(pd, ctypes.byref(count), families) + family = next((i for i, f in enumerate(families) if f.queueFlags & QUEUE_COMPUTE), None) + if family is None: + return None, "no compute queue" + destroy = [] # (call, handle) in creation order, destroyed backwards + dev = ctypes.c_void_p() + try: + prio = f32(1.0) + qinfo = QueueCreateInfo(2, None, 0, family, 1, ctypes.pointer(prio)) + ext = [b"VK_KHR_portability_subset"] if b"VK_KHR_portability_subset" in extensions else [] + ext_arr = (ctypes.c_char_p * max(len(ext), 1))(*ext) + dinfo = DeviceCreateInfo(3, None, 0, 1, ctypes.pointer(qinfo), 0, None, len(ext), ext_arr, None) + _check("vkCreateDevice", vk.vkCreateDevice(pd, ctypes.byref(dinfo), None, ctypes.byref(dev))) + queue = ctypes.c_void_p() + vk.vkGetDeviceQueue(dev, family, 0, ctypes.byref(queue)) + mem_props = MemoryProperties() + vk.vkGetPhysicalDeviceMemoryProperties(pd, ctypes.byref(mem_props)) + + def make(call, info, kind): + handle = u64() + _check(call, getattr(vk, call)(dev, ctypes.byref(info), None, ctypes.byref(handle))) + destroy.append((kind, handle.value)) + return handle.value + + image = make("vkCreateImage", ImageCreateInfo(14, None, 0, 1, R32_SFLOAT, Extent3D(SIZE, SIZE, 1), LEVELS, 1, 1, + 0, 0x2 | 0x4, 0, 0, None, 0), "vkDestroyImage") + req = MemoryRequirements() + vk.vkGetImageMemoryRequirements(dev, image, ctypes.byref(req)) + image_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, req.size, + _memory_type(mem_props, req.memoryTypeBits, 0x1)), + "vkFreeMemory") + _check("vkBindImageMemory", vk.vkBindImageMemory(dev, image, image_mem, 0)) + whole = SubresourceRange(1, 0, LEVELS, 0, 1) + view = make("vkCreateImageView", ImageViewCreateInfo(15, None, 0, image, 1, R32_SFLOAT, (u32 * 4)(0, 0, 0, 0), + whole), "vkDestroyImageView") + samplers = [make("vkCreateSampler", SamplerCreateInfo(31, None, 0, 0, 0, 0, 2, 2, 2, bias, 0, 1.0, 0, 0, 0.0, + 1000.0, 0, 0), "vkDestroySampler") for bias in (0.0, 1.0)] + buffer = make("vkCreateBuffer", BufferCreateInfo(12, None, 0, 8, 0x20, 0, 0, None), "vkDestroyBuffer") + breq = MemoryRequirements() + vk.vkGetBufferMemoryRequirements(dev, buffer, ctypes.byref(breq)) + buffer_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, breq.size, + _memory_type(mem_props, breq.memoryTypeBits, 0x6)), + "vkFreeMemory") + _check("vkBindBufferMemory", vk.vkBindBufferMemory(dev, buffer, buffer_mem, 0)) + bindings = (LayoutBinding * 3)(LayoutBinding(0, 1, 1, 0x20, None), LayoutBinding(1, 1, 1, 0x20, None), + LayoutBinding(2, 7, 1, 0x20, None)) + set_layout = make("vkCreateDescriptorSetLayout", SetLayoutCreateInfo(32, None, 0, 3, bindings), + "vkDestroyDescriptorSetLayout") + sizes = (PoolSize * 2)(PoolSize(1, 2), PoolSize(7, 1)) + pool = make("vkCreateDescriptorPool", PoolCreateInfo(33, None, 0, 1, 2, sizes), "vkDestroyDescriptorPool") + layouts = (u64 * 1)(set_layout) + dset = u64() + _check("vkAllocateDescriptorSets", vk.vkAllocateDescriptorSets(dev, ctypes.byref( + SetAllocateInfo(34, None, pool, 1, layouts)), ctypes.byref(dset))) + images = [DescriptorImageInfo(s, view, 5) for s in samplers] + binfo = DescriptorBufferInfo(buffer, 0, WHOLE) + writes = (WriteDescriptorSet * 3)( + WriteDescriptorSet(35, None, dset.value, 0, 0, 1, 1, ctypes.pointer(images[0]), None, None), + WriteDescriptorSet(35, None, dset.value, 1, 0, 1, 1, ctypes.pointer(images[1]), None, None), + WriteDescriptorSet(35, None, dset.value, 2, 0, 1, 7, None, ctypes.pointer(binfo), None)) + vk.vkUpdateDescriptorSets(dev, 3, writes, 0, None) + code = (u32 * len(SHADER_WORDS))(*SHADER_WORDS) + module = make("vkCreateShaderModule", ShaderModuleCreateInfo(16, None, 0, 4 * len(SHADER_WORDS), code), + "vkDestroyShaderModule") + playout = make("vkCreatePipelineLayout", PipelineLayoutCreateInfo(30, None, 0, 1, layouts, 0, None), + "vkDestroyPipelineLayout") + cinfo = ComputePipelineCreateInfo(29, None, 0, StageCreateInfo(18, None, 0, 0x20, module, b"main", None), + playout, 0, -1) + pipeline = u64() + _check("vkCreateComputePipelines", vk.vkCreateComputePipelines(dev, 0, 1, ctypes.byref(cinfo), None, + ctypes.byref(pipeline))) + destroy.append(("vkDestroyPipeline", pipeline.value)) + cpool = make("vkCreateCommandPool", CommandPoolCreateInfo(39, None, 0, family), "vkDestroyCommandPool") + cmd = ctypes.c_void_p() + _check("vkAllocateCommandBuffers", vk.vkAllocateCommandBuffers(dev, ctypes.byref( + CommandBufferAllocateInfo(40, None, cpool, 0, 1)), ctypes.byref(cmd))) + _check("vkBeginCommandBuffer", vk.vkBeginCommandBuffer(cmd, ctypes.byref(CommandBufferBeginInfo(42, None, 1, + None)))) + to_dst = ImageMemoryBarrier(45, None, 0, 0x1000, 0, 7, IGNORED, IGNORED, image, whole) + vk.vkCmdPipelineBarrier(cmd, 0x1, 0x1000, 0, 0, None, 0, None, 1, ctypes.byref(to_dst)) + for level, value in ((0, 0.0), (1, 1.0)): + color = (f32 * 4)(value, value, value, value) + rng = SubresourceRange(1, level, 1, 0, 1) + vk.vkCmdClearColorImage(cmd, image, 7, ctypes.byref(color), 1, ctypes.byref(rng)) + to_read = ImageMemoryBarrier(45, None, 0x1000, 0x20, 7, 5, IGNORED, IGNORED, image, whole) + vk.vkCmdPipelineBarrier(cmd, 0x1000, 0x800, 0, 0, None, 0, None, 1, ctypes.byref(to_read)) + vk.vkCmdBindPipeline(cmd, 1, pipeline.value) + sets = (u64 * 1)(dset.value) + vk.vkCmdBindDescriptorSets(cmd, 1, playout, 0, 1, sets, 0, None) + vk.vkCmdDispatch(cmd, 1, 1, 1) + to_host = BufferMemoryBarrier(44, None, 0x40, 0x2000, IGNORED, IGNORED, buffer, 0, WHOLE) + vk.vkCmdPipelineBarrier(cmd, 0x800, 0x4000, 0, 0, None, 1, ctypes.byref(to_host), 0, None) + _check("vkEndCommandBuffer", vk.vkEndCommandBuffer(cmd)) + fence = make("vkCreateFence", FenceCreateInfo(8, None, 0), "vkDestroyFence") + cmds = (ctypes.c_void_p * 1)(cmd.value) + submit = SubmitInfo(4, None, 0, None, None, 1, cmds, 0, None) + _check("vkQueueSubmit", vk.vkQueueSubmit(queue, 1, ctypes.byref(submit), fence)) + fences = (u64 * 1)(fence) + _check("vkWaitForFences", vk.vkWaitForFences(dev, 1, fences, 1, 10_000_000_000)) + mapped = ctypes.c_void_p() + _check("vkMapMemory", vk.vkMapMemory(dev, buffer_mem, 0, 8, 0, ctypes.byref(mapped))) + plain, biased = struct.unpack("<2f", ctypes.string_at(mapped, 8)) + vk.vkUnmapMemory(dev, buffer_mem) + except VkFailure as e: + return None, str(e) + finally: + if dev.value: + for call, handle in reversed(destroy): + getattr(vk, call)(dev, handle, None) + vk.vkDestroyDevice(dev, None) + return verdict(plain, biased) + + +def verdict(plain: float, biased: float): + """The answer from the two texels: level 0 holds 0.0 and level 1 holds 1.0.""" + if plain == 0.0 and biased == 1.0: + return False, "the sampler applies mipLodBias (+1 reads level 1)" + if plain == 0.0 and biased == 0.0: + return True, "the sampler drops mipLodBias (+1 still reads level 0)" + return None, f"unexpected texels: plain {plain}, biased {biased}" diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index d380fd279b..ee0d8721c5 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -237,8 +237,10 @@ def device_rank(device_type: int, vendor_id: int) -> int: return (0 if vendor_id == MICROSOFT_VENDOR_ID else 10) + type_rank -def query(*, stage_caps=False) -> dict: - """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none.""" +def query(*, stage_caps=False, lod_bias=False) -> dict: + """The answer for the device the runtime would pick; raises RuntimeError with the reason when there is none. + lod_bias adds "explicit_lod_bias" (and its reason), which tools/vk_lod_bias.py measures on that device with one + small compute dispatch: True where the sampler drops mipLodBias, False where it applies it, None when unknown.""" if sys.maxsize <= 2**32: # the struct sizes below are the 64-bit ones, and 32-bit Windows Vulkan is stdcall, not CDLL's cdecl raise RuntimeError("needs a 64-bit Python") @@ -264,6 +266,7 @@ def query(*, stage_caps=False) -> dict: device_filter = os.environ.get("LEONIDA_VK_DEVICE", "") wanted = device_filter.lower() chosen = None + chosen_dev = None chosen_rank = -1 for d in devs: d = ctypes.c_void_p(d) @@ -327,6 +330,7 @@ def query(*, stage_caps=False) -> dict: rank = device_rank(dtype, vendor_id) if rank > chosen_rank: chosen_rank = rank + chosen_dev = d chosen = (dev_name, subgroup.subgroupSize, subgroup.supportedStages, sg.minSubgroupSize, sg.maxSubgroupSize, sg.requiredSubgroupSizeStages, sg.maxComputeWorkgroupSubgroups, @@ -378,14 +382,24 @@ def query(*, stage_caps=False) -> dict: result.update(supported_subgroup_stages=supported_stages, required_subgroup_size_stages=required_stages, max_compute_workgroup_subgroups=max_workgroup_subgroups) + if lod_bias: + try: + here = os.path.dirname(os.path.abspath(__file__)) + if here not in sys.path: # python -I leaves the script's folder off sys.path + sys.path.insert(0, here) + import vk_lod_bias # noqa: E402 + answer, reason = vk_lod_bias.measure(vk, chosen_dev, device_extensions(vk, chosen_dev)) + except Exception as e: # a measurement that can't run is "unknown", never a guess + answer, reason = None, f"{type(e).__name__}: {e}" + result.update(explicit_lod_bias=answer, explicit_lod_bias_reason=reason) return result finally: vk.vkDestroyInstance(inst, None) -def main(*, stage_caps=False) -> int: +def main(*, stage_caps=False, lod_bias=False) -> int: try: - print(json.dumps(query(stage_caps=stage_caps))) + print(json.dumps(query(stage_caps=stage_caps, lod_bias=lod_bias))) return 0 except Exception as e: # any failure means "unknown": the caller falls back to emulation print(json.dumps({"error": f"{type(e).__name__}: {e}"})) @@ -399,4 +413,7 @@ def main(*, stage_caps=False) -> int: pass parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--stage-caps", action="store_true", help="include raw subgroup stage masks and limits") - sys.exit(main(stage_caps=parser.parse_args().stage_caps)) + parser.add_argument("--lod-bias", action="store_true", + help="measure whether the sampler applies mipLodBias (one compute dispatch; explicit_lod_bias)") + args = parser.parse_args() + sys.exit(main(stage_caps=args.stage_caps, lod_bias=args.lod_bias)) From 98b22aee0bb2a1994a25dd977e949ba2305cb0db Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:58:22 +0100 Subject: [PATCH 04/14] ps_ssharp_ld, ps_ssharp_b: the S# mip fields on image_sample_l, _d and _b, judged by SAMPLER_CASES (SHADER-EXPLICIT-LOD-BIAS-MVK) GPU coverage for the --explicit-lod-bias paths ps_ssharp doesn't run: the Lod of image_sample_l, the 2^bias Grad scale of image_sample_d and the bias of image_sample_b. check.py's SAMPLER_FIXTURES runs all three with the same cases. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- runtime/test/shaders/check.py | 18 +++++++++++----- runtime/test/shaders/ps_ssharp_b.asm | 23 ++++++++++++++++++++ runtime/test/shaders/ps_ssharp_ld.asm | 30 +++++++++++++++++++++++++++ scripts/run_gpu_tests.py | 8 +++---- tests/test_shader_checks.py | 5 +++-- 6 files changed, 74 insertions(+), 12 deletions(-) create mode 100644 runtime/test/shaders/ps_ssharp_b.asm create mode 100644 runtime/test/shaders/ps_ssharp_ld.asm diff --git a/docs/design.md b/docs/design.md index 85769839e2..98694ddbd6 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,7 +502,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. Not GPU-checked: `_d`, `_c*`, cube and 3D forms, and the texel-offset gradients. | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), and `image_sample_b` (`ps_ssharp_b`); `check.py`'s `SAMPLER_FIXTURES` judges all three with the same cases. Not GPU-checked: the `_c*` forms, cube and 3D samples, and the texel-offset gradients. | | `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/check.py b/runtime/test/shaders/check.py index bb6426be2c..3aeeb7724e 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1638,10 +1638,17 @@ def sampler_mismatch(data, words, view): return "" -def sampler_test(tools, spirv): - """ps_ssharp: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by sampler_level. - A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at each pixel.""" - shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_ssharp")] +# The pixel shaders judged by sampler_test: ps_ssharp (image_sample_lz and image_sample), ps_ssharp_ld (image_sample_l +# and image_sample_d) and ps_ssharp_b (image_sample_lz and image_sample_b). Each writes an explicit-LOD-0 sample and an +# LOD-1 sample, so the same SAMPLER_CASES expectations hold for all three. +SAMPLER_FIXTURES = ("ps_ssharp", "ps_ssharp_ld", "ps_ssharp_b") + + +def sampler_test(tools, spirv, ps="ps_ssharp"): + """A SAMPLER_FIXTURES shader: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by + sampler_level. A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at + each pixel.""" + shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", ps)] for path in shaders: if not os.path.isfile(path): return f"missing {os.path.basename(path)}" @@ -2291,7 +2298,8 @@ def main(): results.append((name, texture_constant_test(tools, spirv, name))) results.append(("vs_base_ids", base_ids_test(tools, spirv))) results.append(("ps_tex", bindless_test(tools, spirv))) - results.append(("ps_ssharp", sampler_test(tools, spirv))) + for name in SAMPLER_FIXTURES: + results.append((name, sampler_test(tools, spirv, name))) results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) for name in MIP_TEST_PASSES: results.append((name, texture_mip_test(tools, spirv, name))) diff --git a/runtime/test/shaders/ps_ssharp_b.asm b/runtime/test/shaders/ps_ssharp_b.asm new file mode 100644 index 0000000000..92042abd5b --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_b.asm @@ -0,0 +1,23 @@ +; The S# mip fields on image_sample_b, the implicit form with a bias in the address, which ps_ssharp doesn't run. +; Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# +; (4 dwords) 32 bytes after it. +; Run: vk_sampler_test vs_ids.spv ps_ssharp_b.spv out.raw [ ] (check.py: +; SAMPLER_CASES, through sampler_test(..., "ps_ssharp_b")) +; image_sample_lz as in ps_ssharp, then image_sample_b with an address bias of 0 (v4): it sees LOD 1 like +; ps_ssharp's implicit sample, so check.py judges (lz.r, lz.g, b.r, b.g) exactly like ps_ssharp's, and the S#'s +; LOD_BIAS adds to the address bias. +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v10, 0 +v_mov_b32_e32 v11, v2 +v_mov_b32_e32 v12, v3 +image_sample_b v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +image_sample_lz v[4:5], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_ssharp_ld.asm b/runtime/test/shaders/ps_ssharp_ld.asm new file mode 100644 index 0000000000..9895301dca --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_ld.asm @@ -0,0 +1,30 @@ +; The S# mip fields on the two explicit forms ps_ssharp doesn't run: image_sample_l (an LOD in the address) and +; image_sample_d (gradients in the address). Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the +; console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. +; Run: vk_sampler_test vs_ids.spv ps_ssharp_ld.spv out.raw [ ] (check.py: +; SAMPLER_CASES, through sampler_test(..., "ps_ssharp_ld")) +; image_sample_l takes LOD 0 from v18. image_sample_d takes dU/dx = dV/dy = 1/64 and dU/dy = dV/dx = 0 (v8..v11, then U and V in v12, v13): +; on the 128x128 level 0 that is two texels per pixel, LOD 1, which is what ps_ssharp's implicit sample sees on the +; 64x64 target. So check.py judges (l.r, l.g, d.r, d.g) exactly like ps_ssharp's (lz.r, lz.g, implicit.r, +; implicit.g), and the S#'s LOD_BIAS, MIN_LOD, MAX_LOD and MIP_FILTER apply to both forms. +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v16, v2 +v_mov_b32_e32 v17, v3 +v_mov_b32_e32 v18, 0 +v_mov_b32_e32 v8, 0x3c800000 +v_mov_b32_e32 v9, 0 +v_mov_b32_e32 v10, 0 +v_mov_b32_e32 v11, 0x3c800000 +v_mov_b32_e32 v12, v2 +v_mov_b32_e32 v13, v3 +image_sample_l v[4:5], v[16:18], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +image_sample_d v[6:7], v[8:13], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index cb24f4eeac..925a27d771 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -28,7 +28,7 @@ from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) from compute_fixture import compute_header -from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) +from check import SAMPLER_CASES, SAMPLER_FIXTURES, sampler_test # ps_ssharp*: the S#/T# mip fields (vk_sampler_test) from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) @@ -722,7 +722,7 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_persp_bary": "vs_persp.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", "ps_table_fetch": "vs_ids.asm", "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm", - **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", + **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, **{name: "vs_ids.asm" for name in SAMPLER_FIXTURES}, "ps_imgatomic": "vs_ids.asm", **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", @@ -1473,9 +1473,9 @@ def run_suite(a, work: str) -> int: results.append((name, None, f"SKIP ({reason})")) else: results.append((name, rc == 0, verdict_line(rc, msg))) - elif name == "ps_ssharp": + elif name in SAMPLER_FIXTURES: # The S#/T# mip fields through vulkan_sampler() and the view range (check.py's SAMPLER_CASES). - problem = sampler_test(a.build, spirv_dir) + problem = sampler_test(a.build, spirv_dir, name) results.append((name, None if isinstance(problem, Skip) else not problem, problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) elif name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"): diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 3a2d86096c..dae2696f89 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -38,8 +38,9 @@ + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) - + len(check.TEXTURE_CONSTANTS) + 20) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, - # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, + + len(check.TEXTURE_CONSTANTS) + len(check.SAMPLER_FIXTURES) + + 19) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, + # vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case), cs_fmt_all, # cs_w32_shift64, cs_w32_cmp_f64, cs_w32_round_f64 and cs_w32_frexp_ldexp CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} From ff2e459123809a83c9f767e76707219d34194dee Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:21:58 +0100 Subject: [PATCH 05/14] vk_sampler_test --cube/--3d/--dref; ps_ssharp_cube, ps_ssharp_3d, ps_ssharp_c: the S# mip fields on cube, 3D and depth-compare samples (SHADER-EXPLICIT-LOD-BIAS-MVK) GPU coverage for the rest of --explicit-lod-bias's forms. vk_sampler_test gains a mode for a 6-layer cube (images_arr), a 128x128x2 volume (images_3d) and a D32 texture (0.25 / 0.75 per level) with the S#'s compare function; the 2D default is unchanged. check.py's SAMPLER_FIXTURES names each shader's mode and judges ps_ssharp_c as compare results. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- runtime/test/shaders/check.py | 36 ++++-- runtime/test/shaders/ps_ssharp_3d.asm | 21 ++++ runtime/test/shaders/ps_ssharp_c.asm | 22 ++++ runtime/test/shaders/ps_ssharp_cube.asm | 22 ++++ runtime/test/vk_sampler_test.cpp | 158 +++++++++++++++++++----- 6 files changed, 223 insertions(+), 38 deletions(-) create mode 100644 runtime/test/shaders/ps_ssharp_3d.asm create mode 100644 runtime/test/shaders/ps_ssharp_c.asm create mode 100644 runtime/test/shaders/ps_ssharp_cube.asm diff --git a/docs/design.md b/docs/design.md index 98694ddbd6..d1489dea5e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,7 +502,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), and `image_sample_b` (`ps_ssharp_b`); `check.py`'s `SAMPLER_FIXTURES` judges all three with the same cases. Not GPU-checked: the `_c*` forms, cube and 3D samples, and the texel-offset gradients. | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), and `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`). Not GPU-checked: the `--texel-offset-fallback` gradients (CPU-checked by `tests/semantic/test_explicit_lod_bias.py`'s scaling only). | | `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/check.py b/runtime/test/shaders/check.py index 3aeeb7724e..44d24f0581 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1638,16 +1638,36 @@ def sampler_mismatch(data, words, view): return "" -# The pixel shaders judged by sampler_test: ps_ssharp (image_sample_lz and image_sample), ps_ssharp_ld (image_sample_l -# and image_sample_d) and ps_ssharp_b (image_sample_lz and image_sample_b). Each writes an explicit-LOD-0 sample and an -# LOD-1 sample, so the same SAMPLER_CASES expectations hold for all three. -SAMPLER_FIXTURES = ("ps_ssharp", "ps_ssharp_ld", "ps_ssharp_b") +def sampler_compare_mismatch(data, words, view): + """ps_ssharp_c: the first pixel whose (c_lz, c_lz, c, c) is not the compare result of the level the S# and T# + select (vk_sampler_test --dref: depth 0.25 in level 0 and 0.75 in level 1, reference 0.5, LESS_EQUAL), or "".""" + if len(data) != SAMPLER_SIZE ** 2 * 16: + return f"expected {SAMPLER_SIZE ** 2} RGBA32F pixels, got {len(data)} bytes" + explicit, implicit = (float(sampler_level(words, view, lod) == 1) for lod in (0, 1)) + want = (explicit, explicit, implicit, implicit) + for i, got in enumerate(struct.iter_unpack("<4f", data)): + if any(not math.isclose(g, w, rel_tol=0, abs_tol=1e-6) for g, w in zip(got, want)): + y, x = divmod(i, SAMPLER_SIZE) + return f"({x},{y}): {tuple(round(g, 4) for g in got)} != {want}" + return "" + + +# The pixel shaders judged by sampler_test and the vk_sampler_test mode each needs. Each writes an explicit-LOD-0 sample +# and an LOD-1 sample, so the same SAMPLER_CASES expectations hold for all: ps_ssharp (image_sample_lz and +# image_sample), ps_ssharp_ld (image_sample_l and image_sample_d), ps_ssharp_b (image_sample_lz and image_sample_b), +# ps_ssharp_cube and ps_ssharp_3d (image_sample_lz and image_sample on a cube and a volume) and ps_ssharp_c +# (image_sample_c_lz and image_sample_c on a depth texture, judged as compare results). +SAMPLER_FIXTURES = {"ps_ssharp": (), "ps_ssharp_ld": (), "ps_ssharp_b": (), "ps_ssharp_cube": ("--cube",), + "ps_ssharp_3d": ("--3d",), "ps_ssharp_c": ("--dref",)} +SSHARP_LESS_EQUAL = 3 << 12 # S# word 0 DEPTH_COMPARE_FUNC [14:12] = LESS_EQUAL (Vulkan's VK_COMPARE_OP_LESS_OR_EQUAL) def sampler_test(tools, spirv, ps="ps_ssharp"): """A SAMPLER_FIXTURES shader: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by sampler_level. A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at - each pixel.""" + each pixel; ps_ssharp_c's compare reads 0 on level 0 and 1 on level 1.""" + mode = SAMPLER_FIXTURES[ps] + dref = "--dref" in mode shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", ps)] for path in shaders: if not os.path.isfile(path): @@ -1656,14 +1676,16 @@ def sampler_test(tools, spirv, ps="ps_ssharp"): for name, words, view in SAMPLER_CASES: raw = Path(tmp) / "pixels.raw" raw.unlink(missing_ok=True) - code, out = run(os.path.join(tools, "vk_sampler_test" + EXE), *shaders, raw, + if dref: + words = (words[0] | SSHARP_LESS_EQUAL, *words[1:]) + code, out = run(os.path.join(tools, "vk_sampler_test" + EXE), *mode, *shaders, raw, *(f"{w:x}" for w in words), *(str(v) for v in view)) if code == UNSUPPORTED: m = re.search(r"unsupported: .*", out) return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") if code or not raw.is_file(): return f"{name}: {failure(code, out, 3)}" - problem = sampler_mismatch(raw.read_bytes(), words, view) + problem = (sampler_compare_mismatch if dref else sampler_mismatch)(raw.read_bytes(), words, view) if problem: return f"{name}: {problem}" return "" diff --git a/runtime/test/shaders/ps_ssharp_3d.asm b/runtime/test/shaders/ps_ssharp_3d.asm new file mode 100644 index 0000000000..d1284ce9e3 --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_3d.asm @@ -0,0 +1,21 @@ +; The S# mip fields on a 3D sample, as ps_ssharp.asm does them on 2D (--explicit-lod-bias on images_3d, binding 6). +; Same descriptor path and target: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. +; Run: vk_sampler_test --3d vs_ids.spv ps_ssharp_3d.spv out.raw [ ] +; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_3d")). The volume is 128x128x2 then 64x64x1 with every +; slice the same, sampled at (u, v, 0.25): the third coordinate doesn't vary across the target, so image_sample sees +; LOD 1 and image_sample_lz LOD 0, as in ps_ssharp. -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g). +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v10, v2 +v_mov_b32_e32 v11, v3 +v_mov_b32_e32 v12, 0.25 +image_sample v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_3D +image_sample_lz v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_3D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_ssharp_c.asm b/runtime/test/shaders/ps_ssharp_c.asm new file mode 100644 index 0000000000..b8f6a61197 --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_c.asm @@ -0,0 +1,22 @@ +; The S# mip fields on depth-compare samples, image_sample_c_lz and image_sample_c (--explicit-lod-bias's _c forms). +; Same descriptor path and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) +; 32 bytes after it; the S# carries DEPTH_COMPARE_FUNC = LESS_EQUAL. +; Run: vk_sampler_test --dref vs_ids.spv ps_ssharp_c.spv out.raw [ ] +; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_c"), with the compare function added). The D32 texture +; holds 0.25 in level 0 and 0.75 in level 1, and the reference is 0.5: a compare reads 0 on level 0 and 1 on level 1. +; image_sample_c_lz is at LOD 0 and image_sample_c at LOD 1, as in ps_ssharp. -> mrt0 = (c_lz, c_lz, c, c). +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v10, 0.5 +v_mov_b32_e32 v11, v2 +v_mov_b32_e32 v12, v3 +image_sample_c v6, v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D +image_sample_c_lz v4, v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v4, v6, v6 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_ssharp_cube.asm b/runtime/test/shaders/ps_ssharp_cube.asm new file mode 100644 index 0000000000..7b97b358fb --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_cube.asm @@ -0,0 +1,22 @@ +; The S# mip fields on a cube sample, as ps_ssharp.asm does them on 2D (--explicit-lod-bias on images_arr, binding 3). +; Same descriptor path and target: s0:s1 is the console VA of a T# (8 dwords) with the S# (4 dwords) 32 bytes after it. +; Run: vk_sampler_test --cube vs_ids.spv ps_ssharp_cube.spv out.raw [ ] +; (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_cube")). The cube face coordinates are the way the +; hardware takes them, s, t = 1 + (u, v) on face 0 (ps_cube_sample.asm), so face 0 is read exactly where ps_ssharp +; reads the 2D texture: image_sample_lz at LOD 0 and image_sample at LOD 1. Every face holds the same levels. +; -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g), judged like ps_ssharp. +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_add_f32_e32 v10, 1.0, v2 +v_add_f32_e32 v11, 1.0, v3 +v_mov_b32_e32 v12, 0 +image_sample v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_CUBE +image_sample_lz v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_CUBE +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp index 98206931b1..92598bd0b7 100644 --- a/runtime/test/vk_sampler_test.cpp +++ b/runtime/test/vk_sampler_test.cpp @@ -3,7 +3,15 @@ // and sampler those keys name. Unlike vk_texture_test, which binds a fixed nearest sampler and one level, the // VkSampler here is vulkan_sampler(decode(S#)) and the view's levels come from decode(T#). // -// vk_sampler_test [ ] +// vk_sampler_test [--cube|--3d|--dref] [ ] +// +// The mode picks the texture and the binding the translator reads it from (--explicit-lod-bias's forms): +// (none) 2D RGBA8 at binding 0, as described below. +// --cube a cube-compatible 2D RGBA8 image with 6 layers, every layer the same, viewed as the 6-layer 2D array the +// translator samples a cube through (binding 3). +// --3d a 3D RGBA8 image, 128x128x2 then 64x64x1, every slice the same (binding 6). +// --dref a 2D D32_SFLOAT image whose level 0 holds 0.25 and level 1 0.75 (binding 0, depth aspect); the S# carries +// the compare function, so a reference of 0.5 with LESS_OR_EQUAL reads 0 on level 0 and 1 on level 1. // // S# words are hex. The T# is encode() of a 128x128 RGBA8 image with two levels, with BASE_LEVEL and LAST_LEVEL as // given (default 0 and 1). Level 0 has four solid quadrants: red, green, blue and yellow. Level 1 is solid grey @@ -20,6 +28,7 @@ #include "../src/descriptor_table.h" #include "../src/gfx10_descriptors.h" +#include #include #include #include @@ -52,8 +61,18 @@ std::vector read_spv(const char* path) { } // namespace int main(int argc, char** argv) { + enum class Mode { flat, cube, volume, dref } mode = Mode::flat; + if (argc > 1 && argv[1][0] == '-' && argv[1][1] == '-') { + if (!std::strcmp(argv[1], "--cube")) mode = Mode::cube; + else if (!std::strcmp(argv[1], "--3d")) mode = Mode::volume; + else if (!std::strcmp(argv[1], "--dref")) mode = Mode::dref; + else { std::fprintf(stderr, "unknown mode %s\n", argv[1]); return 2; } + --argc; + ++argv; + } if (argc != 8 && argc != 10) { - std::fprintf(stderr, "usage: vk_sampler_test [ ]\n"); + std::fprintf(stderr, "usage: vk_sampler_test [--cube|--3d|--dref] " + "[ ]\n"); return 2; } namespace gfx10 = leonida::gfx10; @@ -275,20 +294,84 @@ int main(int argc, char** argv) { CHECK(make_buffer(table_words.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &table_buffer, &table_map)); std::memcpy(table_map, table_words.data(), table_words.size() * 4); - // Textures. RGBA8 in memory order; level 1 grey has r = g = 128/255, unlike every level-0 colour. - constexpr VkFormat texture_format = VK_FORMAT_R8G8B8A8_UNORM; + // Textures. RGBA8 in memory order; level 1 grey has r = g = 128/255, unlike every level-0 colour. Every cube + // layer and 3D slice holds the same level, so a layer or slice coordinate can't change the colour. --dref: depth + // 0.25 in level 0 and 0.75 in level 1. + const bool depth_mode = mode == Mode::dref; + const VkFormat texture_format = depth_mode ? VK_FORMAT_D32_SFLOAT : VK_FORMAT_R8G8B8A8_UNORM; + const VkImageAspectFlags aspect = depth_mode ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; + const std::uint32_t layers = mode == Mode::cube ? 6 : 1; + const std::uint32_t depth0 = mode == Mode::volume ? 2 : 1; + const auto level_depth = [&](std::uint32_t level) { return std::max(depth0 >> level, 1u); }; constexpr std::uint32_t quadrant[2][2] = {{0xff0000ffu, 0xff00ff00u}, {0xffff0000u, 0xff00ffffu}}; constexpr std::uint32_t grey = 0xff808080u, magenta = 0xffff00ffu; + std::uint32_t depth_words[2]; + { + const float d[2] = {0.25f, 0.75f}; + std::memcpy(depth_words, d, sizeof d); + } std::vector texels; - for (std::uint32_t y = 0; y < TW; y++) - for (std::uint32_t x = 0; x < TW; x++) texels.push_back(quadrant[y >= TW / 2][x >= TW / 2]); - texels.resize(texels.size() + (TW / 2) * (TW / 2), grey); - VkImage fallback, texture; - VkImageView fallback_view, texture_view; - CHECK(make_image(texture_format, 1, 1, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &fallback)); - CHECK(make_view(fallback, texture_format, 0, 1, &fallback_view)); - CHECK(make_image(texture_format, TW, TW, levels, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &texture)); - CHECK(make_view(texture, gfx10::vulkan_format(view_of.format), view_of.first_mip, view_of.mip_count, &texture_view)); + for (std::uint32_t level = 0; level < levels; ++level) { + const std::uint32_t side = TW >> level; + for (std::uint32_t copy = 0; copy < layers * level_depth(level); ++copy) + for (std::uint32_t y = 0; y < side; y++) + for (std::uint32_t x = 0; x < side; x++) + texels.push_back(depth_mode ? depth_words[level] + : level ? grey : quadrant[y >= side / 2][x >= side / 2]); + } + const auto make_texture = [&](VkImageType type, VkFormat format, VkExtent3D extent, std::uint32_t mips, + std::uint32_t array_layers, VkImageCreateFlags flags, VkImage* img) { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.flags = flags; + ii.imageType = type; + ii.format = format; + ii.extent = extent; + ii.mipLevels = mips; + ii.arrayLayers = array_layers; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + VkResult r = vkCreateImage(dev, &ii, nullptr, img); + if (r) return r; + VkMemoryRequirements mr; + vkGetImageMemoryRequirements(dev, *img, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m; + r = vkAllocateMemory(dev, &ai, nullptr, &m); + return r ? r : vkBindImageMemory(dev, *img, m, 0); + }; + const auto make_texture_view = [&](VkImage img, VkImageViewType type, VkFormat format, VkImageAspectFlags view_aspect, + std::uint32_t base, std::uint32_t count, std::uint32_t array_layers, + VkImageView* view) { + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = img; + vi.viewType = type; + vi.format = format; + vi.subresourceRange = {view_aspect, base, count, 0, array_layers}; + return vkCreateImageView(dev, &vi, nullptr, view); + }; + // Index 0 of every bound array is a magenta 1x1 fallback of the array's dimension. + VkImage fallback, fallback3d = VK_NULL_HANDLE, texture; + VkImageView fallback_view, fallback_extra = VK_NULL_HANDLE, texture_view; + CHECK(make_texture(VK_IMAGE_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM, {1, 1, 1}, 1, 1, 0, &fallback)); + CHECK(make_view(fallback, VK_FORMAT_R8G8B8A8_UNORM, 0, 1, &fallback_view)); + if (mode == Mode::cube) + CHECK(make_texture_view(fallback, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, + 0, 1, 1, &fallback_extra)); + if (mode == Mode::volume) { + CHECK(make_texture(VK_IMAGE_TYPE_3D, VK_FORMAT_R8G8B8A8_UNORM, {1, 1, 1}, 1, 1, 0, &fallback3d)); + CHECK(make_texture_view(fallback3d, VK_IMAGE_VIEW_TYPE_3D, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, + 1, &fallback_extra)); + } + CHECK(make_texture(mode == Mode::volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D, texture_format, {TW, TW, depth0}, + levels, layers, mode == Mode::cube ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0u, &texture)); + const VkImageViewType view_type = mode == Mode::cube ? VK_IMAGE_VIEW_TYPE_2D_ARRAY + : mode == Mode::volume ? VK_IMAGE_VIEW_TYPE_3D : VK_IMAGE_VIEW_TYPE_2D; + CHECK(make_texture_view(texture, view_type, depth_mode ? texture_format : gfx10::vulkan_format(view_of.format), + aspect, view_of.first_mip, view_of.mip_count, layers, &texture_view)); + // The binding the translator reads this dimension from (set 0): images (0), images_arr (3) or images_3d (6). + const std::uint32_t texture_binding = mode == Mode::cube ? 3u : mode == Mode::volume ? 6u : 0u; VkBuffer upload; void* upload_map; const VkDeviceSize texture_offset = 256, texture_bytes = texels.size() * 4; @@ -346,17 +429,20 @@ int main(int argc, char** argv) { VkFramebuffer framebuffer; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); - // Set 0 as the translator expects it: binding 0 images[], 1 samplers[], 2 the descriptor hash table. - VkDescriptorSetLayoutBinding b[3]{}; + // Set 0 as the translator expects it: binding 0 images[], 1 samplers[], 2 the descriptor hash table, and for + // --cube / --3d the array the texture sits in, images_arr (3) or images_3d (6). + const bool extra = texture_binding != 0; + VkDescriptorSetLayoutBinding b[4]{}; b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; + b[3] = {texture_binding, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = 3; + dli.bindingCount = extra ? 4 : 3; dli.pBindings = b; VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); - const VkDescriptorPoolSize sizes[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, + const VkDescriptorPoolSize sizes[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; @@ -370,11 +456,15 @@ int main(int argc, char** argv) { dai.pSetLayouts = &dsl; VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); + // Image 1 is the texture in its own array; binding 0 keeps the 2D fallback there when the texture sits elsewhere. const VkDescriptorImageInfo images[2]{{VK_NULL_HANDLE, fallback_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {VK_NULL_HANDLE, texture_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; + {VK_NULL_HANDLE, extra ? fallback_view : texture_view, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; + const VkDescriptorImageInfo extra_images[2]{{VK_NULL_HANDLE, fallback_extra, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_NULL_HANDLE, texture_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; const VkDescriptorImageInfo sampler_infos[2]{{samplers[0]}, {samplers[1]}}; const VkDescriptorBufferInfo table_info{table_buffer, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet writes[3]{}; + VkWriteDescriptorSet writes[4]{}; for (auto& w : writes) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; @@ -385,7 +475,10 @@ int main(int argc, char** argv) { writes[1].pImageInfo = sampler_infos; writes[2].dstBinding = 2; writes[2].descriptorCount = 1; writes[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; writes[2].pBufferInfo = &table_info; - vkUpdateDescriptorSets(dev, 3, writes, 0, nullptr); + writes[3].dstBinding = texture_binding; writes[3].descriptorCount = 2; + writes[3].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + writes[3].pImageInfo = extra_images; + vkUpdateDescriptorSets(dev, extra ? 4 : 3, writes, 0, nullptr); // Pipeline. VkShaderModule modules[2]; @@ -479,25 +572,30 @@ int main(int argc, char** argv) { CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &begin)); - for (int t = 0; t < 2; ++t) { - const std::uint32_t mips = t ? levels : 1; + // The fallbacks take the magenta word at offset 0; the texture every level, all layers or slices at once. + struct Upload { VkImage image; std::uint32_t mips, layers; VkImageAspectFlags aspect; bool texture; }; + std::vector uploads{{fallback, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT, false}}; + if (fallback3d) uploads.push_back({fallback3d, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT, false}); + uploads.push_back({texture, levels, layers, aspect, true}); + for (const Upload& u : uploads) { VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - ib.image = t ? texture : fallback; - ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1}; + ib.image = u.image; + ib.subresourceRange = {u.aspect, 0, u.mips, 0, u.layers}; ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - VkDeviceSize offset = t ? texture_offset : 0; - for (std::uint32_t level = 0; level < mips; ++level) { - const std::uint32_t side = t ? TW >> level : 1; + VkDeviceSize offset = u.texture ? texture_offset : 0; + for (std::uint32_t level = 0; level < u.mips; ++level) { + const std::uint32_t side = u.texture ? TW >> level : 1; + const std::uint32_t slices = u.texture ? level_depth(level) : 1; VkBufferImageCopy c{}; c.bufferOffset = offset; - c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; - c.imageExtent = {side, side, 1}; + c.imageSubresource = {u.aspect, level, 0, u.layers}; + c.imageExtent = {side, side, slices}; vkCmdCopyBufferToImage(cmd, upload, ib.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - offset += VkDeviceSize(side) * side * 4; + offset += VkDeviceSize(side) * side * slices * u.layers * 4; } ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; From 631a5383207ef01d0b96fdd0010c9898222b791a Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:38:26 +0100 Subject: [PATCH 06/14] ps_ssharp_o: the S# mip fields on image_sample_lz_o / image_sample_o under the texel-offset fallback (SHADER-EXPLICIT-LOD-BIAS-MVK) The last --explicit-lod-bias path without GPU coverage: with LEONIDA_TEXOFF_FALLBACK=1 the implicit offset sample is a Grad sample whose derivatives the flag scales. A SKIP without the fallback, since vk_sampler_test enables no VK_KHR_maintenance8. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- runtime/test/shaders/check.py | 7 +++++-- runtime/test/shaders/ps_ssharp_o.asm | 24 ++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 runtime/test/shaders/ps_ssharp_o.asm diff --git a/docs/design.md b/docs/design.md index d1489dea5e..2c21e12d53 100644 --- a/docs/design.md +++ b/docs/design.md @@ -502,7 +502,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), and `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`). Not GPU-checked: the `--texel-offset-fallback` gradients (CPU-checked by `tests/semantic/test_explicit_lod_bias.py`'s scaling only). | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | | `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/check.py b/runtime/test/shaders/check.py index 44d24f0581..82392864fa 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1656,9 +1656,10 @@ def sampler_compare_mismatch(data, words, view): # and an LOD-1 sample, so the same SAMPLER_CASES expectations hold for all: ps_ssharp (image_sample_lz and # image_sample), ps_ssharp_ld (image_sample_l and image_sample_d), ps_ssharp_b (image_sample_lz and image_sample_b), # ps_ssharp_cube and ps_ssharp_3d (image_sample_lz and image_sample on a cube and a volume) and ps_ssharp_c -# (image_sample_c_lz and image_sample_c on a depth texture, judged as compare results). +# (image_sample_c_lz and image_sample_c on a depth texture, judged as compare results); ps_ssharp_o (image_sample_lz_o +# and image_sample_o) runs only under LEONIDA_TEXOFF_FALLBACK=1, its Grad derivatives being what it checks. SAMPLER_FIXTURES = {"ps_ssharp": (), "ps_ssharp_ld": (), "ps_ssharp_b": (), "ps_ssharp_cube": ("--cube",), - "ps_ssharp_3d": ("--3d",), "ps_ssharp_c": ("--dref",)} + "ps_ssharp_3d": ("--3d",), "ps_ssharp_c": ("--dref",), "ps_ssharp_o": ()} SSHARP_LESS_EQUAL = 3 << 12 # S# word 0 DEPTH_COMPARE_FUNC [14:12] = LESS_EQUAL (Vulkan's VK_COMPARE_OP_LESS_OR_EQUAL) @@ -1668,6 +1669,8 @@ def sampler_test(tools, spirv, ps="ps_ssharp"): each pixel; ps_ssharp_c's compare reads 0 on level 0 and 1 on level 1.""" mode = SAMPLER_FIXTURES[ps] dref = "--dref" in mode + if ps == "ps_ssharp_o" and os.environ.get("LEONIDA_TEXOFF_FALLBACK") != "1": + return Skip("SKIP (needs LEONIDA_TEXOFF_FALLBACK=1: vk_sampler_test enables no VK_KHR_maintenance8)") shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", ps)] for path in shaders: if not os.path.isfile(path): diff --git a/runtime/test/shaders/ps_ssharp_o.asm b/runtime/test/shaders/ps_ssharp_o.asm new file mode 100644 index 0000000000..d2f948e5b6 --- /dev/null +++ b/runtime/test/shaders/ps_ssharp_o.asm @@ -0,0 +1,24 @@ +; The S# mip fields on the texel-offset forms under --texel-offset-fallback, where the offset is folded into the +; coordinate and an implicit sample becomes a Grad sample (the derivatives --explicit-lod-bias scales). +; Same descriptor path, texture and target as ps_ssharp.asm: s0:s1 is the console VA of a T# (8 dwords) with the S# +; (4 dwords) 32 bytes after it. +; Run: vk_sampler_test vs_ids.spv ps_ssharp_o.spv out.raw [ ] with the shaders +; translated under LEONIDA_TEXOFF_FALLBACK=1 (check.py: SAMPLER_CASES through sampler_test(..., "ps_ssharp_o"); it +; is a SKIP otherwise, since vk_sampler_test doesn't enable VK_KHR_maintenance8 for a non-constant Offset). +; image_sample_lz_o and image_sample_o with an offset dword of 0 (v10), so the texels are ps_ssharp's: +; -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g), judged like ps_ssharp. +s_load_dwordx8 s[8:15], s[0:1], 0x0 +s_load_dwordx4 s[16:19], s[0:1], 0x20 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mov_b32_e32 v10, 0 +v_mov_b32_e32 v11, v2 +v_mov_b32_e32 v12, v3 +image_sample_o v[6:7], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +image_sample_lz_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm From 3fc6184290e404b08abc0c131ebcb714a654c609 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:09:20 +0100 Subject: [PATCH 07/14] make_game: drop the unreachable second try in runtime_gpu_explicit_lod_bias (#1774 review) Left over from the earlier draw-based version: it followed a try that always returns and named an undefined build. Co-Authored-By: Claude Opus 5.5 --- make_game.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/make_game.py b/make_game.py index 3a7492f2b3..9d652fe0d4 100644 --- a/make_game.py +++ b/make_game.py @@ -1975,13 +1975,6 @@ def runtime_gpu_explicit_lod_bias(): return None if v is None else bool(v) except (OSError, ValueError, IndexError, subprocess.SubprocessError): return None - try: - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "lod_bias_probe.py"), "--build", build], - capture_output=True, text=True, timeout=300) - v = json.loads(r.stdout.strip().splitlines()[-1]).get("explicit_lod_bias") - return None if v is None else bool(v) - except (OSError, ValueError, IndexError, subprocess.SubprocessError): - return None def runtime_gpu_per_vertex(): From 1787a81c74097b2558f2e1bbc8da7a90a349447c Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:08:05 +0100 Subject: [PATCH 08/14] vk_lod_bias: control read at explicit LOD 1 must return 1.0, else null (#1774 review) A level 1 that was never cleared also gives a biased 0.0, which read as a dropped bias. Co-Authored-By: Claude Opus 5.5 --- tests/test_vk_lod_bias.py | 21 ++++++++++---- tools/vk_lod_bias.py | 58 +++++++++++++++++++++++---------------- 2 files changed, 50 insertions(+), 29 deletions(-) diff --git a/tests/test_vk_lod_bias.py b/tests/test_vk_lod_bias.py index 452f19f4ed..702ee7d500 100644 --- a/tests/test_vk_lod_bias.py +++ b/tests/test_vk_lod_bias.py @@ -1,6 +1,6 @@ """tools/vk_lod_bias.py: the mipLodBias measurement tools/vk_subgroup_info.py --lod-bias runs. -No GPU: the verdict is checked from the two texels the compute shader returns, a Vulkan library without the calls +No GPU: the verdict is checked from the three texels the compute shader returns (with the LOD 1 control), a Vulkan library without the calls gives "unknown", and the embedded SPIR-V is checked for its header (and with spirv-val when it is on PATH). Standard library only; no game files. """ @@ -18,16 +18,25 @@ class VerdictTest(unittest.TestCase): - def test_the_two_texels_decide(self): - # level 0 holds 0.0 and level 1 holds 1.0; the shader samples LOD 0 with mipLodBias 0 and +1 - self.assertIs(vk_lod_bias.verdict(0.0, 1.0)[0], False) # the sampler applies the bias - self.assertIs(vk_lod_bias.verdict(0.0, 0.0)[0], True) # the sampler drops it + def test_the_texels_decide(self): + # level 0 holds 0.0 and level 1 holds 1.0; the shader samples LOD 0 with mipLodBias 0 and +1, and LOD 1 + self.assertIs(vk_lod_bias.verdict(0.0, 1.0, 1.0)[0], False) # the sampler applies the bias + self.assertIs(vk_lod_bias.verdict(0.0, 0.0, 1.0)[0], True) # the sampler drops it for plain, biased in ((1.0, 1.0), (1.0, 0.0), (0.0, 0.5), (float("nan"), 0.0)): with self.subTest(plain=plain, biased=biased): - answer, reason = vk_lod_bias.verdict(plain, biased) + answer, reason = vk_lod_bias.verdict(plain, biased, 1.0) self.assertIsNone(answer) self.assertIn("unexpected", reason) + def test_the_lod1_control_must_read_one(self): + # a level 1 that was never cleared also gives a biased 0.0: without the control it would look like a drop + for level1 in (0.0, 0.5, float("nan")): + for plain, biased in ((0.0, 0.0), (0.0, 1.0)): + with self.subTest(level1=level1, plain=plain, biased=biased): + answer, reason = vk_lod_bias.verdict(plain, biased, level1) + self.assertIsNone(answer) + self.assertIn("control read at LOD 1", reason) + class MeasureTest(unittest.TestCase): def test_a_library_without_the_calls_is_unknown(self): diff --git a/tools/vk_lod_bias.py b/tools/vk_lod_bias.py index 1bdbcde20e..642e1aadc9 100644 --- a/tools/vk_lod_bias.py +++ b/tools/vk_lod_bias.py @@ -4,11 +4,13 @@ "explicit_lod_bias". The same MoltenVK 1.4.2 drops the sampler's bias on an Apple M3 and applies it on an Apple M5 Pro (#1774), so the answer is measured, not looked up: a 4x4 R32_SFLOAT image gets 0.0 in level 0 and 1.0 in level 1 (vkCmdClearColorImage), and one compute invocation samples it at explicit LOD 0 through a sampler with mipLodBias 0 -and one with +1 (nearest filters and mips, clamp to edge), writing both texels to a host-visible buffer. +and one with +1 (nearest filters and mips, clamp to edge), plus once at explicit LOD 1 with no bias, writing the three +texels to a host-visible buffer. The LOD 1 read is the control: it must return 1.0, or level 1 was never cleared (or +mip selection is broken) and a biased 0.0 would not mean the bias was dropped. -* plain 0.0, biased 1.0 -> False: the sampler applies the bias (rdna2spirv.py --explicit-lod-bias would count it twice) -* plain 0.0, biased 0.0 -> True: the sampler drops it (translate with --explicit-lod-bias) -* anything else, or any Vulkan error -> None, with the reason +* plain 0.0, biased 1.0, level 1 1.0 -> False: the sampler applies the bias (--explicit-lod-bias would count it twice) +* plain 0.0, biased 0.0, level 1 1.0 -> True: the sampler drops it (translate with rdna2spirv.py --explicit-lod-bias) +* anything else, or any Vulkan error -> None, with the reason The shader is SHADER_WORDS, compiled from this GLSL with glslangValidator -V -g0 --target-env vulkan1.0: @@ -16,10 +18,11 @@ layout(local_size_x = 1) in; layout(set = 0, binding = 0) uniform sampler2D plain; layout(set = 0, binding = 1) uniform sampler2D biased; - layout(set = 0, binding = 2) buffer Out { float r[2]; }; + layout(set = 0, binding = 2) buffer Out { float r[3]; }; void main() { r[0] = textureLod(plain, vec2(0.5), 0.0).r; r[1] = textureLod(biased, vec2(0.5), 0.0).r; + r[2] = textureLod(plain, vec2(0.5), 1.0).r; } Standard library only (ctypes); 64-bit struct layouts, as vk_subgroup_info.py. No game files. @@ -28,16 +31,16 @@ import struct SHADER_WORDS = ( - 0x07230203, 0x00010000, 0x0008000b, 0x00000027, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, + 0x07230203, 0x00010000, 0x0008000b, 0x0000002d, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, 0x0005000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, 0x00000001, 0x00000001, 0x00000001, 0x00040047, 0x00000009, 0x00000006, 0x00000004, 0x00030047, 0x0000000a, 0x00000003, 0x00050048, 0x0000000a, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x0000000c, 0x00000021, 0x00000002, 0x00040047, 0x0000000c, 0x00000022, 0x00000000, 0x00040047, 0x00000012, 0x00000021, 0x00000000, 0x00040047, 0x00000012, 0x00000022, 0x00000000, 0x00040047, 0x0000001f, 0x00000021, 0x00000001, 0x00040047, 0x0000001f, 0x00000022, 0x00000000, - 0x00040047, 0x00000026, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, + 0x00040047, 0x0000002c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040015, 0x00000007, 0x00000020, 0x00000000, 0x0004002b, 0x00000007, - 0x00000008, 0x00000002, 0x0004001c, 0x00000009, 0x00000006, 0x00000008, 0x0003001e, 0x0000000a, 0x00000009, + 0x00000008, 0x00000003, 0x0004001c, 0x00000009, 0x00000006, 0x00000008, 0x0003001e, 0x0000000a, 0x00000009, 0x00040020, 0x0000000b, 0x00000002, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000002, 0x00040015, 0x0000000d, 0x00000020, 0x00000001, 0x0004002b, 0x0000000d, 0x0000000e, 0x00000000, 0x00090019, 0x0000000f, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000010, @@ -46,15 +49,18 @@ 0x00000014, 0x00000016, 0x00000015, 0x00000015, 0x0004002b, 0x00000006, 0x00000017, 0x00000000, 0x00040017, 0x00000018, 0x00000006, 0x00000004, 0x0004002b, 0x00000007, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c, 0x00000002, 0x00000006, 0x0004002b, 0x0000000d, 0x0000001e, 0x00000001, 0x0004003b, 0x00000011, 0x0000001f, - 0x00000000, 0x00040017, 0x00000024, 0x00000007, 0x00000003, 0x0004002b, 0x00000007, 0x00000025, 0x00000001, - 0x0006002c, 0x00000024, 0x00000026, 0x00000025, 0x00000025, 0x00000025, 0x00050036, 0x00000002, 0x00000004, - 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000010, 0x00000013, 0x00000012, 0x00070058, - 0x00000018, 0x00000019, 0x00000013, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x0000001b, - 0x00000019, 0x00000000, 0x00060041, 0x0000001c, 0x0000001d, 0x0000000c, 0x0000000e, 0x0000000e, 0x0003003e, - 0x0000001d, 0x0000001b, 0x0004003d, 0x00000010, 0x00000020, 0x0000001f, 0x00070058, 0x00000018, 0x00000021, - 0x00000020, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x00000022, 0x00000021, 0x00000000, - 0x00060041, 0x0000001c, 0x00000023, 0x0000000c, 0x0000000e, 0x0000001e, 0x0003003e, 0x00000023, 0x00000022, - 0x000100fd, 0x00010038 + 0x00000000, 0x0004002b, 0x0000000d, 0x00000024, 0x00000002, 0x0004002b, 0x00000006, 0x00000026, 0x3f800000, + 0x00040017, 0x0000002a, 0x00000007, 0x00000003, 0x0004002b, 0x00000007, 0x0000002b, 0x00000001, 0x0006002c, + 0x0000002a, 0x0000002c, 0x0000002b, 0x0000002b, 0x0000002b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, + 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000010, 0x00000013, 0x00000012, 0x00070058, 0x00000018, + 0x00000019, 0x00000013, 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x0000001b, 0x00000019, + 0x00000000, 0x00060041, 0x0000001c, 0x0000001d, 0x0000000c, 0x0000000e, 0x0000000e, 0x0003003e, 0x0000001d, + 0x0000001b, 0x0004003d, 0x00000010, 0x00000020, 0x0000001f, 0x00070058, 0x00000018, 0x00000021, 0x00000020, + 0x00000016, 0x00000002, 0x00000017, 0x00050051, 0x00000006, 0x00000022, 0x00000021, 0x00000000, 0x00060041, + 0x0000001c, 0x00000023, 0x0000000c, 0x0000000e, 0x0000001e, 0x0003003e, 0x00000023, 0x00000022, 0x0004003d, + 0x00000010, 0x00000025, 0x00000012, 0x00070058, 0x00000018, 0x00000027, 0x00000025, 0x00000016, 0x00000002, + 0x00000026, 0x00050051, 0x00000006, 0x00000028, 0x00000027, 0x00000000, 0x00060041, 0x0000001c, 0x00000029, + 0x0000000c, 0x0000000e, 0x00000024, 0x0003003e, 0x00000029, 0x00000028, 0x000100fd, 0x00010038 ) u32, u64, f32, vp = ctypes.c_uint32, ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p @@ -254,7 +260,7 @@ def make(call, info, kind): whole), "vkDestroyImageView") samplers = [make("vkCreateSampler", SamplerCreateInfo(31, None, 0, 0, 0, 0, 2, 2, 2, bias, 0, 1.0, 0, 0, 0.0, 1000.0, 0, 0), "vkDestroySampler") for bias in (0.0, 1.0)] - buffer = make("vkCreateBuffer", BufferCreateInfo(12, None, 0, 8, 0x20, 0, 0, None), "vkDestroyBuffer") + buffer = make("vkCreateBuffer", BufferCreateInfo(12, None, 0, 12, 0x20, 0, 0, None), "vkDestroyBuffer") breq = MemoryRequirements() vk.vkGetBufferMemoryRequirements(dev, buffer, ctypes.byref(breq)) buffer_mem = make("vkAllocateMemory", MemoryAllocateInfo(5, None, breq.size, @@ -317,8 +323,8 @@ def make(call, info, kind): fences = (u64 * 1)(fence) _check("vkWaitForFences", vk.vkWaitForFences(dev, 1, fences, 1, 10_000_000_000)) mapped = ctypes.c_void_p() - _check("vkMapMemory", vk.vkMapMemory(dev, buffer_mem, 0, 8, 0, ctypes.byref(mapped))) - plain, biased = struct.unpack("<2f", ctypes.string_at(mapped, 8)) + _check("vkMapMemory", vk.vkMapMemory(dev, buffer_mem, 0, 12, 0, ctypes.byref(mapped))) + plain, biased, level1 = struct.unpack("<3f", ctypes.string_at(mapped, 12)) vk.vkUnmapMemory(dev, buffer_mem) except VkFailure as e: return None, str(e) @@ -327,11 +333,17 @@ def make(call, info, kind): for call, handle in reversed(destroy): getattr(vk, call)(dev, handle, None) vk.vkDestroyDevice(dev, None) - return verdict(plain, biased) + return verdict(plain, biased, level1) -def verdict(plain: float, biased: float): - """The answer from the two texels: level 0 holds 0.0 and level 1 holds 1.0.""" +def verdict(plain: float, biased: float, level1: float): + """The answer from the three texels: level 0 holds 0.0 and level 1 holds 1.0. + + `level1` is the control read at explicit LOD 1: unless it is 1.0, a biased 0.0 could come from a level 1 that was + never cleared rather than from a dropped bias, so there is no answer. + """ + if level1 != 1.0: + return None, f"control read at LOD 1 gave {level1}, not 1.0 (level 1 not cleared or not selected)" if plain == 0.0 and biased == 1.0: return False, "the sampler applies mipLodBias (+1 reads level 1)" if plain == 0.0 and biased == 0.0: From 85eac6b54d27b9e134b118934501c24f4f0bdc65 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:09:32 +0100 Subject: [PATCH 09/14] rdna2spirv: --explicit-lod-bias clamps image_sample_cl / _c_cl outside the PS after the bias (#1774 review) Vulkan clamps the biased LOD: max(bias, minlod), as _b_cl already does, not max(0, minlod) + bias. Co-Authored-By: Claude Opus 5.5 --- tests/semantic/test_explicit_lod_bias.py | 12 ++++++++++++ tools/rdna2spirv.py | 10 ++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/semantic/test_explicit_lod_bias.py b/tests/semantic/test_explicit_lod_bias.py index 549ef93487..c9db3d3634 100644 --- a/tests/semantic/test_explicit_lod_bias.py +++ b/tests/semantic/test_explicit_lod_bias.py @@ -142,6 +142,18 @@ def test_compute_implicit_sample_adds_to_lod_zero(self): self.assertTrue(all(lod_operand(s) == "%f0" for s in off), off) self.assertRegex(defn(spv, lod_operand(on[0])), r"^OpFAdd %float %f0 %\w+$") + def test_compute_cl_clamps_after_the_bias(self): + # Vulkan clamps the biased LOD: max(0 + bias, minlod), as _b_cl's max(bias, minlod), not max(0, minlod) + bias + for op, vaddr in (("image_sample_cl", "v[2:4]"), ("image_sample_c_cl", "v[2:5]")): + with self.subTest(op=op): + line = f"{op} v[6:7], {vaddr}, s[8:15], s[16:19] dmask:0x3 {D2}" + off = translate("cs_lb_cl_off", literal_ssharp(0x100), line, False) + self.assertRegex(defn(off, lod_operand(samples(off)[0])), r"^OpExtInst %float %glsl FMax %f0 %\w+$") + spv = translate("cs_lb_cl_on", literal_ssharp(0x100), line, True) + m = re.match(r"^OpExtInst %float %glsl FMax (%\w+) %\w+$", defn(spv, lod_operand(samples(spv)[0]))) + self.assertTrue(m, samples(spv)) + self.assertRegex(defn(spv, m.group(1)), r"^OpFAdd %float %f0 %\w+$") + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index f2155415f5..abdcaf7852 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -13909,16 +13909,18 @@ def sample(image, cls, ty): # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is # max(base, clamp) and no MinLod operand. lod_zero = "%f0" + if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"): + # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias). + # The bias goes in before the _cl clamp below: Vulkan clamps the biased LOD, max(bias, minlod). + lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2) if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): + base = lod_zero lod_zero = self.tmp() - self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax %f0 {minlod}") + self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax {base} {minlod}") bias_lod = bias if kind in ("_b", "_c_b") and not implicit and minlod is not None: bias_lod = self.tmp() self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") - if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"): - # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias). - lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2) # Implicit samples without a bias of their own take the S# bias as a Bias operand. sbias = (self.ssharp_lod_bias(a[3]["r"] + 2) if EXPLICIT_LOD_BIAS and implicit and kind in ("", "_c") else None) From eb464f2fcb3c7fc58fcbd8a958059d5bd8e36932 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:09:32 +0100 Subject: [PATCH 10/14] docs/design.md: the 27.0 M3 checked the draw probe; the LOD 1 control and the clamp order (#1774 review) Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index 0894392a7f..17c4393c73 100644 --- a/docs/design.md +++ b/docs/design.md @@ -518,7 +518,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS, added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1; it answers true when +1 still reads level 0, false when it reads level 1, null otherwise, and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed on two Apple M3s (macOS 26.5.1 and 27.0) where it answers true, and on KosmicKrisp and llvmpipe where it answers false. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on an Apple M3 (macOS 26.5.1), where it answers true, and on KosmicKrisp and llvmpipe, where it answers false; on a second Apple M3 (macOS 27.0) only the earlier `ps_ssharp` draw probe was checked (true) until it is rerun. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | | `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`. | From 743eda012b13b70c0612748eb2ec2ffde6738b6f Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:32:00 +0100 Subject: [PATCH 11/14] vk_sampler_test: --cube / --3d tag the T# entry with the array the texture sits in Since #2098 (merged in from main) a tagged module reads its instruction's array only when the entry's kind names it; with the 2D bit alone, ps_ssharp_cube and ps_ssharp_3d read the magenta fallback. Co-Authored-By: Claude Opus 5.5 --- runtime/test/vk_sampler_test.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp index 84eefc0ae5..dbcfa6398f 100644 --- a/runtime/test/vk_sampler_test.cpp +++ b/runtime/test/vk_sampler_test.cpp @@ -285,9 +285,10 @@ int main(int argc, char** argv) { address_info.buffer = heap; const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The - // module is tagged (build.py), so the T# entry names the array its index is bound in: a sampled 2D image. + // module is tagged (build.py), so the T# entry names the array its index is bound in: the sampled 2D images, + // or with --cube / --3d the 2D-array or 3D images the texture sits in (dimension 1 or 2; see texture_binding). leonida::DescriptorTable table(16); - table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(0)); + table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(mode == Mode::cube ? 1u : mode == Mode::volume ? 2u : 0u)); table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); const auto table_words = table.build_gpu_buffer(true); VkBuffer table_buffer; From bcf1997366ddfa8e941e6c36d3723d2cc9323fc2 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:47:31 +0100 Subject: [PATCH 12/14] design.md: the 27.0 M3 reran the compute probe and ps_ssharp at 743eda012 Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index 9201e35665..57576518ef 100644 --- a/docs/design.md +++ b/docs/design.md @@ -519,7 +519,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on an Apple M3 (macOS 26.5.1), where it answers true, and on KosmicKrisp and llvmpipe, where it answers false; on a second Apple M3 (macOS 27.0) only the earlier `ps_ssharp` draw probe was checked (true) until it is rerun. GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on two Apple M3s, macOS 26.5.1 and 27.0 (MoltenVK 1.4.2), where it answers true, and on KosmicKrisp and llvmpipe (Mesa 26.3.1) on both, where it answers false; on the 27.0 M3 `ps_ssharp` and its five variants pass in auto mode on all three drivers (#1774). GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | | `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`. | From 5c702e2a7069bdacc0426336484478af8a69328d Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:02:25 +0100 Subject: [PATCH 13/14] design.md: the M5 (macOS 26.6.2) probe answers false and ps_ssharp passes without the flag Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index 57576518ef..f6fdcd620a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -519,7 +519,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). | -| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on two Apple M3s, macOS 26.5.1 and 27.0 (MoltenVK 1.4.2), where it answers true, and on KosmicKrisp and llvmpipe (Mesa 26.3.1) on both, where it answers false; on the 27.0 M3 `ps_ssharp` and its five variants pass in auto mode on all three drivers (#1774). GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | +| S# LOD bias without the sampler's `mipLodBias` (`--explicit-lod-bias`) | The S#'s `LOD_BIAS` (word 2 [13:0], signed 5.8) is the Vulkan sampler's `mipLodBias` (`vulkan_sampler()` in `runtime/src/gfx10_descriptors.h`), and Vulkan adds it to every sample's LOD, explicit or derivative. MoltenVK 1.4.2 on an Apple M3 drops it from both: `ps_ssharp` reads level 0 for `image_sample_lz` with a +0.6 or +1 bias and level 1 for the derivative-LOD `image_sample` with -0.6 or -1, where KosmicKrisp and llvmpipe (Mesa 26.3.1) on the same machine move both; the same MoltenVK on an Apple M5 Pro (macOS 26.7.3) applies it (#1774). With the flag the shader applies the bias itself, read from the S# SGPRs (a literal S# folds to a constant): added to the `Lod` of `_lz`, `_l`, `_c_lz`, `_c_l` and of the implicit forms outside the PS (before their `_cl` clamp: Vulkan clamps the biased LOD, `max(bias, minlod)`, as for `_b_cl`), added to the bias of `_b` / `_c_b`, a `Bias` operand on implicit samples in the PS, and a 2^bias scale of `Grad` derivatives (the typed 2D implicit read, `_d`, and the `--texel-offset-fallback` gradients). The sampler still clamps to `MIN_LOD`..`MAX_LOD`. Confirmed on the Apple M3 with MoltenVK 1.4.2: `ps_ssharp`'s ten S# cases exact, including +-0.3, which tell a bias counted once from twice. On KosmicKrisp and llvmpipe the flag makes +-0.3 fail (the bias counts twice), so it is measured per device, not looked up by driver ID: `tools/vk_subgroup_info.py --lod-bias` (`tools/vk_lod_bias.py`) clears a two-level R32_SFLOAT image to 0.0 and 1.0 and samples it in one compute dispatch at explicit LOD 0 through samplers with `mipLodBias` 0 and +1, plus a control read at explicit LOD 1 that must return 1.0 (a level 1 that was never cleared would also read 0.0); it answers true when +1 still reads level 0, false when it reads level 1, null otherwise (the control included), and needs no built test programs, llvm-mc or SPIR-V tools. `tools/lod_bias_probe.py` returns that answer, and only when there is none and `--build` names the test programs does it draw `ps_ssharp` without the flag at LOD_BIAS 0, +1 and -1 instead. `scripts/run_gpu_tests.py`, `runtime/test/shaders/build.py` and `make_game.py` take the answer; `LEONIDA_EXPLICIT_LOD_BIAS=1`/`0` forces it in the test runners. Confirmed with this compute measurement on two Apple M3s, macOS 26.5.1 and 27.0 (MoltenVK 1.4.2), where it answers true, and on KosmicKrisp and llvmpipe (Mesa 26.3.1) on both, where it answers false; on the 27.0 M3 `ps_ssharp` and its five variants pass in auto mode on all three drivers, and on an Apple M5 (macOS 26.6.2, MoltenVK) the probe answers false ("the sampler applies mipLodBias") and they pass without the flag (#1774). GPU-checked forms, each with the same `SAMPLER_CASES` through `check.py`'s `SAMPLER_FIXTURES` and `vk_sampler_test`: `image_sample_lz` and the derivative `image_sample` (`ps_ssharp`), `image_sample_l` and `image_sample_d`, whose `Grad` scale this checks (`ps_ssharp_ld`), `image_sample_b` (`ps_ssharp_b`), the same pair on a cube (`ps_ssharp_cube`, `vk_sampler_test --cube`, images_arr) and on a volume (`ps_ssharp_3d`, `--3d`, images_3d), `image_sample_c_lz` and `image_sample_c` on a D32 texture with a LESS_EQUAL S# (`ps_ssharp_c`, `--dref`), and `image_sample_lz_o` and `image_sample_o` under `LEONIDA_TEXOFF_FALLBACK=1`, whose folded `Grad` derivatives this scales (`ps_ssharp_o`, a SKIP without the fallback). | | `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`. | From 9d9d085a989b87c7dff300ccfc5cf52e98aaa977 Mon Sep 17 00:00:00 2001 From: Tauwni <102470988+Tauwni@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:52:02 +0100 Subject: [PATCH 14/14] CI macOS: ps_ssharp passes with --explicit-lod-bias, drop it from the expected failures The macOS GPU job printed 'ps_ssharp passed: drop it from the expected failures' on 27524a5e5. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index f0ac86ac7c..da4872c119 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -600,10 +600,9 @@ jobs: if: ${{ !cancelled() && steps.macos-build.outcome == 'success' }} # also after a runtime test failure shell: bash env: - # ps_ssharp: #1845 (the S#'s LOD bias, which a Metal sampler can't take). cs_fma_fused is newer than the job - # and wrong on MoltenVK: https://github.com/ItsNotRexed/Leonida/issues/3796#issuecomment-7086691314 + # cs_fma_fused is newer than the job and wrong on MoltenVK: + # https://github.com/ItsNotRexed/Leonida/issues/3796#issuecomment-7086691314 EXPECTED_FAILURES: >- - ps_ssharp cs_fma_fused run: | set +e