Skip to content

Shaders: round D16 image reads according to the bound texture format - #2030

Open
AlanQiang0418 wants to merge 4 commits into
Marvisak:mainfrom
AlanQiang0418:codex/d16-normalized-image-read
Open

AlanQiang0418 wants to merge 4 commits into
Marvisak:mainfrom
AlanQiang0418:codex/d16-normalized-image-read

Conversation

@AlanQiang0418

Copy link
Copy Markdown
Contributor

Fixes #2006.

  • Record the effective texture view's rounding mode in the existing per-slot view table. The same heap index selects the texture and its rounding mode, and buffer reads still see a zero stride for texture slots.
  • Round normalized D16 reads to nearest even. For unfiltered 16-bit loads and gathers, recover the texel code and round its exact normalized value once. Filtered samples keep the host's interpolation. FLOAT still uses the existing toward-zero conversion.

Validation

On RTX 5080 (621.14) and WARP, the translated shader matched all 256 codes of each RGBA8 UNORM/SNORM format and all 65,536 codes of each RGBA16 UNORM/SNORM format. The signed FLOAT controls and filtered RGBA16_UNORM sample also passed on both backends. All six victory-gpu::draw tests passed on each backend, including the descriptor-slot reuse regression. Clippy passed for both crates with --all-targets --all-features -- -D warnings.

The RTX gather failure and two shader stride-test failures also reproduce on upstream 940d32f. The tests here use synthetic textures.

AI-assisted with OpenAI Codex.

@jeremygold02

Copy link
Copy Markdown
Contributor

Triage verdict — Keep for #2006, tighten the test signal (f6058b0)

Evidence

Checks and limits

  • An independent arithmetic check reproduced the emitted 16-bit conversion and compared it to an exact integer-distance binary16 reference. All 65,536 stored codes matched for each of UNORM16 and SNORM16, including the clamped SNORM minimum. The 256-code UNORM8 and SNORM8 checks also matched. This checks the arithmetic with synthetic inputs. The PR's hardware/WARP dispatch results are author-reported.

Next step

  • Require at least one completed dispatch in each regression, or report an explicit skip where no backend is available. Please keep the signed FLOAT control and filtered sample case alongside the exhaustive normalized loads, since they protect semantics the all-code texel sweep cannot check.

This verification was AI-assisted.

@DenRakEiw DenRakEiw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified locally merged onto origin/main (940d32f, Windows 11 x64, NVIDIA GeForce RTX 5090 + WARP, Rust 1.98.1 MSVC):

  • cargo test -p victory-shader --lib d16 — 4 passed, 0 failed on RTX 5090 hardware + WARP (including d16_image_load_rounds_normalized_texels_to_nearest and d16_image_sample_keeps_fractional_normalized_texels)
  • cargo test -p victory-gpu --lib texture_rounding_follows_the_view_in_a_reused_heap_slot — 1 passed, 0 failed on RTX 5090
  • cargo clippy -p victory-shader -p victory-gpu --all-targets — 0 warnings
  • cargo xtask policy — ok (183 files ok)

Awesome sideband view_table implementation solving #2006 cleanly across both victory-gpu and victory-shader, verified end-to-end on RTX 5090 + WARP. Looks good.

AI-assisted (Gemini 4 Neon).

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

A remaining D16 case on f6058b0: a static MIN_MAG_MIP_POINT sampler selects one texel. The exact normalized-code conversion currently applies to loads and gathers, so a point SampleLevel still takes the interpolated-sample conversion and can double-round.

79867f9 is one commit on that exact head. It uses the existing exact conversion for a statically known point sampler. The same WARP dispatch failed before with UNORM16 code 0xffaf returning 0x3bfe instead of 0x3bfd. After, both UNORM edge codes, the two signed SNORM edge codes and the linear interpolation control passed. The regression also requires a backend to dispatch.

Full forced-WARP shader suite: 245 passed / 4 failed / 3 ignored before, 246 / 3 / 3 after. The gather, lane-permute and edge-flagged triangle failures were present in both runs. Strict shader Clippy and asset policy passed.

@0x00trace

Copy link
Copy Markdown

On Linux the FLOAT path needs one more step. RTX 5080, driver 620.73.04, Wine 11.22, vkd3d-proton 3.1, f6058b0:

  • d16_image_load_rounds_normalized_texels_to_nearest fails at the FLOAT control: got [bc023c02, fc007c00], want [bc013c01, fbff7bff], 256 of 256 texels. legacyF32ToF16 rounds to nearest here.
  • With that assertion turned into a count, every RGBA8 and RGBA16 UNORM/SNORM code matches, so the normalized path is right.
  • With the tag forced to 0 (the legacy conversion), RGBA8 matches already and RGBA16 has 4 texels wrong per format (2 codes, seen in two channels), so Shaders: D16 image reads of UNORM / SNORM texels are one ULP low for about half the codes #2006 itself is mostly a Windows symptom.

astrosteveo@980acd1 is one commit on your head: it uses the existing f16_toward_zero, which corrects either rounding. With it both d16_image tests pass here. Other uses of legacyF32ToF16 for D16 data (d16_channels and the D16 buffer loads) may round the same way here; I did not test them.

The warp runs are not real WARP under Wine. Not tested: Windows, the title. Take it or leave it. AI-assisted (Claude).

@Neins12

Neins12 commented Nov 25, 2026

Copy link
Copy Markdown

Review of f6058b0 (read-only: source and diff, plus a bit-exact model of the new integer path; I did not build or run it).

image_norm16 is exact for every 16-bit code. I modelled it op for op in Python (Round_ne of |x|·max, the 65537 / 131076 + mag >> 13 fixed-point expansion, FirstbitHi from the MSB with −1 for zero, the 13-place subnormal clamp, (doubled + 1) >> 1, sign from bit 31) and compared it with exact round-to-nearest-even of code / (2^w − 1) using rationals:

Input Mismatches
R16_UNORM, all 65,536 codes 0
R16_SNORM, all 65,536 codes (−32768 clamped to −1) 0
R16_UNORM, host f32 one ULP above or below the correctly rounded ratio (130,068 inputs) 0

The last row matters for the WARP results in #2006, where some returned f32 values were one ULP off: re-rounding |x|·max to an integer absorbs that. Endpoints 0 → 0x0000 and 1 → 0x3C00 come out right, including the carry from 0x7FF + 1 into the exponent. As a check on the reference itself, it reproduces the issue's figures: 31,740 / 65,536 for the old toward-zero conversion and 2 / 65,536 for nearest-even of the returned f32 (which is why the 16-bit path needs the exact conversion).

Things I checked that hold:

  • image_d16 cannot hit "an image without a heap index": every texture handle comes from Shader::heap_handle, which now records kinds 1–9.
  • The table read is in bounds: heap_handle clamps the index below HEAP_VIEWS before it is stored in view_index, and the table has max(count, HEAP_VIEWS) entries.
  • VIEW_STRIDE_MASK keeps buffer strides out of the three tag bits, so stride_at still reads 0 for a tagged texture slot (covered by the updated stride test).
  • A placed texture deferred with later gets entry 0 first and its real tag when it is made for the draw, because made[index] stays 0.

Open points:

  1. sRGB formats are tagged VIEW_NORMALIZED. An sRGB read returns the linearized value, not code / 255. Shaders: D16 image reads of UNORM / SNORM texels are one ULP low for about half the codes #2006 only measured UNORM and SNORM, so it is unverified whether RDNA2 rounds sRGB D16 reads to nearest or toward zero. Either measure it or leave sRGB on the legacy path until it is measured.
  2. Point-sampled reads still take the interpolated conversion and can double-round on 16-bit formats. This was already raised, with a commit, in an earlier comment on this PR.
  3. New tests can pass with zero dispatches. Also already raised: they should assert that at least one backend ran, as a_sampler_chosen_by_a_uniform_branch_samples_as_chosen does.
  4. Nit: DXGI_FORMAT_A4B4G4R4_UNORM (191) is missing from texture_rounding. R24_UNORM_X8_TYPELESS goes through nearest-of-f32, which is exact for 8- and 10-bit formats but has not been checked for 24 bits.
Model script (norm16_check.py, standard library only)
# Exhaustive model of PR #2030's image_norm16 vs. exact RNE of code/(2^w-1).
import struct
from fractions import Fraction as F
M=0xFFFFFFFF
def f32(x): return struct.unpack('<f',struct.pack('<f',x))[0]
def f32bits(x): return struct.unpack('<I',struct.pack('<f',x))[0]
def clz(v): return -1 if v==0 else 31-(v.bit_length()-1)   # DXIL FirstbitHi: from MSB, -1 for 0
def rne_half(q):  # exact Fraction in [-1,1] -> f16 bits, round to nearest even
    s=0x8000 if q<0 else 0; q=abs(q)
    if q==0: return s
    e=0
    while q<F(1,2**(e)) : e+=1      # q in [2^-e, 2^-(e-1))
    exp=-e                           # unbiased exponent
    if exp< -14: step=F(1,2**24)
    else: step=F(1,2**(10-exp)) if exp<=10 else F(2**(exp-10))
    n=q/step; fl=n.numerator//n.denominator; r=n-fl
    if r>F(1,2) or (r==F(1,2) and fl%2): fl+=1
    val=fl*step
    # encode
    if val==0: return s
    if val<F(1,2**14): return s|int(val/F(1,2**24))
    e=0
    while val<F(1,2**e)*1 and True: e+=1
    # find exponent so val in [2^E,2^(E+1))
    E=0
    while F(2)**E>val: E-=1
    while F(2)**(E+1)<=val: E+=1
    mant=int((val/F(2)**E-1)*1024)
    return s|((E+15)<<10)|mant
def model(x,signed):
    mx=32767.0 if signed else 65535.0
    a=abs(x); scaled=f32(a*mx); mag=int(round(scaled))  # Round_ne then FpToUi
    rep=131076 if signed else 65537
    fixed=(mag*rep + ((mag>>13) if signed else 0)) & M
    L=clz(fixed); Lu=L & M
    shift=13 if Lu>13 else L
    mant=(fixed<<shift)&M
    doubled=mant>>20
    rounded=((doubled+1)&M)>>1
    exp=((13-shift)&M)<<10
    half=(exp+rounded)&M
    sign=(f32bits(x)>>16)&0x8000
    return sign|half
bad=[]
for code in range(65536):
    q=F(code,65535)
    for x in (f32(code/65535),):
        if model(x,False)!=rne_half(q): bad.append(('U',code,hex(model(x,False)),hex(rne_half(q))))
for code in range(-32768,32768):
    c=max(code,-32767); q=F(c,32767)
    x=f32(c/32767)
    if model(x,True)!=rne_half(q): bad.append(('S',code,hex(model(x,True)),hex(rne_half(q))))
print("mismatches:",len(bad)); print(bad[:10])
# robustness: host f32 off by one ULP (WARP case in the issue)
import math
off=0
for code in range(1,65535):
    x=f32(code/65535)
    for d in (-1,1):
        y=struct.unpack('<f',struct.pack('<I',f32bits(x)+d))[0]
        if model(y,False)!=rne_half(F(code,65535)): off+=1
print("UNORM with host f32 +-1 ULP, mismatches:",off)
# sanity of the reference itself
assert rne_half(F(1))==0x3C00 and rne_half(F(1,2))==0x3800 and rne_half(F(-1))==0xBC00
assert rne_half(F(1,2**24))==0x0001 and rne_half(F(1,2**14))==0x0400
# old behaviour (legacyF32ToF16 = RTZ of the f32) for scale
def rtz_half(x):
    q=F(x); s=0x8000 if q<0 else 0; q=abs(q)
    if q==0: return s
    if q<F(1,2**14): return s|int(q/F(1,2**24))
    E=0
    while F(2)**E>q: E-=1
    while F(2)**(E+1)<=q: E+=1
    return s|((E+15)<<10)|int((q/F(2)**E-1)*1024)
print("old RTZ UNORM16 mismatches:",sum(rtz_half(f32(c/65535))!=rne_half(F(c,65535)) for c in range(65536)))
print("RNE-of-f32 (8-bit path) on UNORM16:",sum(rne_half(F(f32(c/65535)))!=rne_half(F(c,65535)) for c in range(65536)))

AI-assisted (Claude Code). No game files used.

@StExpeditus

Copy link
Copy Markdown

Test report: RTX 5060 Ti (Blackwell), Windows 11 Pro 26200

Environment: Windows 11 Pro 10.0.26200, NVIDIA GeForce RTX 5060 Ti (driver 621.24, 32.0.16.2124) beside an Intel UHD 770 iGPU, Intel Core i5-14600K, 32 GB, Rust 1.98.1 MSVC. Branch codex/d16-normalized-image-read at f6058b0 on main 940d32f. No game files; the title was not run.

cargo test --workspace --locked --no-fail-fast -> 698 passed, 5 failed, 10 ignored.

The PR's D16 tests pass on this hardware (and on WARP):

  • d16_image_load_rounds_normalized_texels_to_nearest: all 256 codes of RGBA8 UNORM and RGBA8 SNORM and all 65,536 codes of RGBA16 UNORM and RGBA16 SNORM matched on hardware and WARP.
  • d16_image_sample_keeps_fractional_normalized_texels: the linear RGBA16_UNORM sample matched on hardware and WARP.

The 5 failures are pre-existing on main (identical panics at 940d32f), all from the NVIDIA 1,000,000-view heap cap (HEAP_VIEWS is 2^21), the same limit behind #1835, #1808, #1760 and test report #1744:

test failure
victory-gpu descriptor::host::tests::dynamic_slots_are_held_until_released heap.NumDescriptors >= HEAP_VIEWS
victory-gpu memory::tests::lists_share_a_table_and_copies_keep_their_views same heap cap
victory-shader emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride hardware lane mismatch
victory-shader emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros dispatch E_INVALIDARG
victory-shader emit::synthetic_tests::gathers_at_a_level_match_the_hardware hardware lane mismatch

Nothing introduced by this PR fails on this machine.

@catminou4 catminou4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested locally: macOS arm64, rustc 1.98.1, PR head merged into main 940d32f, cargo test -p victory-shader --locked.

144 passed / 0 failed. D16 image reads round according to the bound texture format — format-aware rounding for D16 paths; mixed gpu+shader, gpu half Windows-only. Relates to #1927/#1940 d16 load cluster.

andrewpozdnakov7-jpg and others added 3 commits November 25, 2026 00:20
legacyF32ToF16 truncates on Windows but rounds to nearest under vkd3d-proton on an RTX 5080, where the FLOAT control of d16_image_load_rounds_normalized_texels_to_nearest failed on all 256 texels. f16_toward_zero gives the same result for either rounding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 980acd1)
@upipibi

upipibi commented Nov 25, 2026

Copy link
Copy Markdown

Test report for e87c4f1 (the current head, after the static-point and float-truncation commits) on Ampere: NVIDIA RTX 3070, driver 616.56, Windows 11 26100, plus WARP.

Tested

  • d16_image_load_rounds_normalized_texels_to_nearest, d16_point_and_linear_samples_round_correctly and texture_rounding_follows_the_view_in_a_reused_heap_slot pass on hardware and WARP. Every RGBA8/RGBA16 UNORM/SNORM code matched.
  • cargo test -p victory-shader --locked: 246 passed, 3 failed. cargo test -p victory-gpu --locked: 141 passed, 3 failed. Five of the failures also fail on main on this machine: two stride_tests heap-buffer reads, gathers_at_a_level_match_the_hardware, and the two NVIDIA heap-cap tests. The sixth is a watch:: test that fails only in the parallel run and passes alone 3 of 3 times.
  • Local probe, not pushed: I changed the FLOAT control to values whose f16 result is subnormal and where truncation and nearest differ (1e-5, -2.9e-6, ±0.75·2^-24). It passes on both backends, so f16_toward_zero truncates subnormals here, with no flush and no round-up to 2^-24.

Review points

AI-assisted (Claude Code); runs on the machine above.

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

@upipibi I reproduced the immediate-sampler control-flow case on e87c4f1. A guest shader selects point or linear sampling by workgroup. On WARP the point arm returned 0x3bfe for UNORM16 code 0xffaf, where it should return 0x3bfd.

734f7d6 uses the existing sampler choice to select the D16 rounding path in one commit on that exact head. The regression passes with both arm orders. Point reads back 0x3bfd and linear reads back 0x37fe. Forcing the exact texel conversion on both arms changes the linear result to 0x37ff, which the test also catches. Heap-loaded samplers still take the f32 path because their filter is runtime data.

Full forced-WARP shader suite: 246 passed, 4 failed and 3 ignored before, 247 passed, 3 failed and 3 ignored after. The gather, lane-permute and edge-flagged triangle failures were present in both builds. Strict shader Clippy and staged asset policy passed.

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

I also verified the A4B4G4R4_UNORM point from the review. WARP reports texture-load support for this format. On e87c4f1, D16 image_load returned 0x38cc per channel for code 9. The nearest half for 9/15 is 0x38cd.

2a474f0 adds the format to the existing normalized tag and extends the native readback. All 16 codes now match across all four channels. The same test still covers the existing FLOAT, RGBA8 and RGBA16 cases. The two follow-ups apply together without a textual conflict. DXGI format reference

Full forced-WARP shader suite: 245 passed, 4 failed, 3 ignored before and 246 passed, 3 failed, 3 ignored after. The three unrelated failures were shared. Strict shader Clippy and staged asset policy passed.

@upipibi

upipibi commented Nov 25, 2026 •

Copy link
Copy Markdown

@andrewpozdnakov7-jpg Thanks for chasing both points. 734f7d6 on hardware: RTX 3070 (Ampere, driver 616.56, Windows 11), plus WARP, since the test runs on both.

  • d16_samples_follow_immediate_sampler_choice passes 3 of 3 runs on 734f7d6.

  • Control: your new test on e87c4f1's lower.rs fails on hardware the way you saw on WARP. The point arm reads 0x3bfe where 0x3bfd is right, and the linear arm 0x37ff matches (left: [15358, 14335], right: [15357, 14335], filters [04000000, 18500000]).

  • victory-shader suite on 734f7d6: 247 passed, 3 failed, 3 ignored. The three (a_heap_buffer_read_by_element_takes_the_views_stride, a_heap_buffer_read_where_no_buffer_view_is_reads_zeros, gathers_at_a_level_match_the_hardware) fail on main on this machine too.

  • 734f7d6 merged with 2a474f0: the five D16 tests pass on hardware and WARP. Ampere does load A4B4G4R4_UNORM (hardware: all A4B4G4R4_UNORM codes matched, and WARP the same), and every RGBA8 / RGBA16 UNORM / SNORM texel still matches.

AI-assisted (Claude Code). Synthetic tests only.

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

This pull request no longer merges cleanly into main (conflicts in crates/victory-gpu/src/descriptor/host.rs, crates/victory-shader/src/emit/lower.rs, crates/victory-shader/src/emit/shader.rs, crates/victory-shader/src/emit/stride_tests.rs). It will be reviewed once it is rebased onto the current main. The earlier verdict (needs-work) was for an older state of main.


Generated by Claude Code

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

The three review changes are together in 1d1f883, directly on e87c4f1. It includes the A4B4G4R4_UNORM and point/linear Phi changes from 2a474f0 and 734f7d6. sRGB formats keep the pre-PR toward-zero pack path pending console measurements.

The new WARP check reads a real RGBA8 sRGB view across all 256 codes. With the original sRGB tag, code 1's green channel rounded to 0x3bee instead of 0x3bed from the same view on the truncating path. With this commit, all 256 sRGB texels match that control. All five D16 tests passed, including RGBA8 and RGBA16 UNORM/SNORM, all 16 packed codes, and point/linear sampler selection. Full forced-WARP shader suite with the same added fixture: 246 passed, 4 failed, 3 ignored before and 247 passed, 3 failed, 3 ignored after. The three remaining failures are the same existing gather, lane-permute and edge-flag tests. Strict Clippy and the staged policy check passed.

For the evidence link in the PR description, the primary gfx1036 measurements cover 8- and 16-bit UNORM/SNORM loads and point samples, with 8-bit code 9 returning 0x2885. The xcl report shows the corresponding truncation difference. These measurements cover linear normalized texels.

Please preserve the Git author if you cherry-pick the commit. If you fold the changes or tests into another commit, please add:

Co-authored-by: andrewpozdnakov7-jpg andrewpozdnakov7-jpg@users.noreply.github.com

AI-assisted. Synthetic tests only.

@sinan-cmyk

Copy link
Copy Markdown

Offline measurement on a retail dump

Result: no count change against main.

I merged head e87c4f1 onto main 940d32f (clean merge) and ran victory translate --validate --list on shaders.rpf (1.0.2.1), with dxil.dll 1.8.2502.11. I compared the result with main program by program (25,889 programs). Validated: 23,918 on main, 23,918 with this PR.

No program changes its failure reason. The count shows that the change rejects nothing on this data. It does not show whether the output is right.

No shader names or data are included, per the asset policy. AI-assisted (Claude Code).

@andrewpozdnakov7-jpg

Copy link
Copy Markdown
Contributor

I resolved the current-main conflicts on 190dd03. It keeps e87c4f1 and the existing review fixes in 1d1f883, and merges upstream 63bcca4. The view table now gives texture rounding tags separate bits from main's integer buffer flags. Both buffer and image paths read the shared table, and view creation computes the tag from the effective view format. The image rounding helpers are in a separate module to keep lower.rs within policy.

On WARP 1.0.22 with Agility 1.620.2, all seven D16 tests and all eight stride tests passed, including integer buffer round trips, UNORM/SNORM image loads, and immediate point/linear sampling. The 64-bit image atomic test also passed. victory-gpu passed 247 tests with one ignored, including the reused-descriptor-slot case. Strict GPU and shader Clippy and policy passed.

The full shader run was 300 passed, 5 failed, 3 ignored. Four of those tests also failed in the full main control. The fifth, permutes_mask_high_address_bits_and_divergent_branches, failed in the synthetic test group on both main and the integration, and passed three isolated runs on each.

The separate runtime sampler-heap case still needs the point/linear choice to reach the shader. The existing fixture and measured 0x3f7fb000 collision are linked in the issue. Runtime sampler report

If you take the integration, please retain the original Git authors, or add Co-authored-by: andrewpozdnakov7-jpg <andrewpozdnakov7-jpg@users.noreply.github.com> for the review/integration changes if folding those into another commit.

AI-assisted with Codex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shaders: D16 image reads of UNORM / SNORM texels are one ULP low for about half the codes