fix(gpu,metal): lazily populate texture_buffer views for typed and structured buffers #278
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/278"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T07:52:44Z.
What this changes
Refs #255
Refs #258
There are two separate host causes behind indexed buffer accesses on the native Metal backend:
!typed, such asbuffer_store_dword* ... idxenon a view without static stride metadata) takeLower::view_stride(lower.rs:12595) and read root SRVt255(VIEW_STRIDES), which #264 binds.typed == true,buffer_load_format_*/buffer_store_format_*and typed-buffergetDimensions) skipview_stride(&& !typedatlower.rs:12595) and lower to DXILTypedBuffer(bufferLoad.f32,bufferStore.f32,getDimensions). Tested on a small synthetic DXIL program of our own compiled locally throughmetal-shaderconverter4.0.3 (not from the title; no listing in the repository or comments), all three operations compile to@air.read_texture_buffer_1d.v4f32,@air.write_texture_buffer_1d.v4f32, and@air.is_null_texture_buffer_1d+@air.get_width_texture_buffer_1d, loading word 1 (textureViewIDat byte+8) of the 24-byteIRDescriptorTableEntry, whereasrawBufferStore.i32(buffer_store_dwordx4) loads word 0 (gpuVAat byte+0).Metal::write_bufferpreviously wrote[gpu, 0, size as u64], leavingtextureViewID = 0(a nullMTLResourceID). On Apple Silicon,write_texture_buffer_1dto a nulltexture_bufferis a silent no-op andread_texture_buffer_1d/get_width_texture_buffer_1dreturn0.This PR:
mirror()with lazy materialization (PendingTyped+Binding::typed_buffers):NativeHost::mirrorcontinues to callwrite_buffer(0MTLTextureallocations at mirror time) and records two pending bits per entry (PendingTyped,~10 KiBfor a 40,000-entry heap;+16 KiBmeasuredphys_footprintdelta over rawmirror()).Binding::ofscans the DXIL symbol and constant tables once (dxil_uses_typed_buffers) to flag shaders that usebufferLoad,bufferStore, orTypedBuffergetDimensions(Texture2DgetDimensionsstaysfalse). At draw/dispatch submission,NativeHost::materialize_typed_buffersis a no-op unless a bound stage setstyped_buffers; when set, it promotes only pending entries inside boundRoot::Tableranges (plus explicitstride == 0typed buffer views in the bound heap if the shader also indexesResourceDescriptorHeapdirectly), leaving unbound structured buffers unmaterialized.TypeTextureBuffer(ResourceBackend::write_typed_buffer): Creates anMTLTextureType::TypeTextureBufferview overbuffer.buf(aligned tominimumTextureBufferAlignmentForPixelFormat, 16 B on Apple Silicon; warns once and falls back towrite_bufferif unaligned) and writes[gpu, tex_id, size as u64], retaining theMTLTextureinHeap::refswhile counting onlybuffer.bufinalloc_counts/MTLResidencySet.Decoded::Bufferanddescriptors::decodeunchanged, addingdescriptors::typed_bufferseparately and placingNativeHeap::typed_pendingdisjoint from #264'sstrideshunks.How it was tested
heap_tests::formatted_buffer_stores_and_loads_through_structured_and_typed_uavs(on Apple Silicon GPU): verifies!Binding::of(&cs_raw).typed_buffers,!Binding::of(&cs_img).typed_buffers(Texture2DgetDimensions),Binding::of(&cs_fmt).typed_buffers, lazy materialization (0typed_viewsaftermirror()and afterpso_raw,1afterpso_fmt, while an unbound structured UAV outside the table stays unmaterialized), and round-tripsbuffer_store_format_xyzw ... idxen,buffer_load_format_xyzw ... idxen,getDimensions, and rawbuffer_store_dwordx4across 16-byte structured,R32G32B32A32_UINT,R32G32B32A32_FLOAT,R8G8B8A8_UNORM,R16G16B16A16_FLOAT,R16G16B16A16_UINT,R32_SINT(43, negative0xDEAD_BEEF), andR16G16_SNORM(37).gfx::heap_set_tests::a_heaps_set_follows_its_entries(alignedtextureViewID != 0, unaligned+4fallbacktextureViewID == 0withgpuVAintact, and residency-setallocatedSizeinvariance).gfx::heap_set_tests::typed_buffer_view_cost_benchmarkandheap_tests::world_heap_mirror_lazy_benchmark(Apple M5 Pro, macOS 27.2.1).cargo test -p victory-hle -p victory -p victory-gpu -p victory-metal -p victory-shader -p xtaskcargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings(and--all-features)cargo xtask policyImported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T08:08:15Z.
Thank you. A second cause that the stride table does not touch is what #255 needed, and a GPU test that stores through the same entry both ways is the right test.
Before it can merge:
descriptors.rsandhost.rs; please look at #264 and rebase over it once it lands.Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by AnastasisKon on 2026-11-27T10:18:30Z.
Reviewed this against the translator side, which I've read closely this week — the diagnosis checks out from both ends: formatted accesses lower to DXIL TypedBuffer ops (bufferLoad/Store.f32, getDimensions) while buffer_store_dwordx4 lowers to rawBufferStore.i32, and the native backend decoded every buffer view to a raw range, so the textureViewID word was never written. Your AIR disassembly (word 1 vs word 0 of IRDescriptorTableEntry) explains #255's exact symptom — format stores silently no-op, dwordx4 through the same entry works — and the word-0/word-1 split confirms both can live in one entry.
Three notes, none blocking:
The structured-stride guess is sound for bit-preservation: 4/8/16 → FLOAT keeps raw 32-bit lanes intact, which is what format ops on a stride V# mean on RDNA2 (a structured V# carries no normalized format). Once this merges, a corpus sweep (#282/#286) counting how many shaders take the typed path through structured views would confirm the reach of the guess on real titles.
No interaction with the d16 path: integer_view (the d16 typed store's integer-extension choice) reads the view-stride table at root SRV t255 (#264), not the descriptor entry this PR populates — I checked; the two channels are independent, so nothing changes there.
Coverage gap, minor: the 1- and 2-channel typed formats (R32_UINT via code 43, RG32_UINT via 18, and the SNORM set) are decode-tested but not exercised on the GPU — the GPU test covers only 4-channel formats. If it's cheap, one extra case with buffer_store_format_x through an R32_UINT view would close that; fine as a follow-up too.
The heap_tests GPU test with bit patterns (0xDEADBEEF, signaling NaN) round-tripping through UNORM/FLOAT/UINT views is exactly the right kind of verification for this. Nice work.
Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T10:32:24Z.
My five questions above are still open: the count and the cost of the textures in a world run, whether the view can be made lazily, 16-byte alignment and SINT, "Refs #255" instead of "Closes #255", and the confirmation about the converter output.
Another account (AnastasisKon) wrote answers on #115 and a review here. They are not measurements and they are not yours, so I cannot count them. The branch is also behind main, and #264 and #267 move
descriptors.rsandhost.rsunder you.Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T10:48:33Z.
Rebased onto
c1b95875(38112699) and addressed all five review points (plus @AnastasisKon's 1- and 2-channel format test suggestion):Cost & Apple Silicon measurements (
#8,#79):We do not have the game installed in this environment to count world-run descriptors directly, so we added
NativeHost::typed_views()AND switchedmirror()to zero-texture lazy materialization, then measured both the eagerwrite_typed_buffercost per view and the new lazy 40,000-entrymirror()cost on an Apple M5 Pro (48 GB, macOS 27.2.1,--release,task_info(TASK_VM_INFO)phys_footprint; reproducible viacargo test --release -p victory-metal typed_buffer_view_cost_benchmark -- --ignored --nocaptureandcargo test --release -p victory-gpu world_heap_mirror_lazy_benchmark -- --ignored --nocapture):phys_footprintdeltaMTLTextures createdheap_setNativeHost::mirror(40,000 raw buffer UAVs)26.67 ms(0.67 us/entry)03.38 MiBNativeHost::mirror(40,000 structured + typed UAVs)22.25 ms(0.56 us/entry)+16.0 KiB(~10 KiBPendingTypedbitsets)03.38 MiB64write_typed_bufferentries0.17 ms(2.62 us/view)+240.0 KiB643.38 MiB512write_typed_bufferentries0.56 ms(1.09 us/view)+752.0 KiB5123.38 MiB1,000write_typed_bufferentries0.93 ms(0.93 us/view)+688.0 KiB(~0.7 KiB/view)1,0003.38 MiB10,000write_typed_bufferentries10.25 ms(1.03 us/view)+15,248.0 KiB(~1.5 KiB/view)10,0003.38 MiB40,000write_typed_bufferentries (previous commit worst case)36.77 ms(0.92 us/view)+46,320.0 KiB(+45.2 MiB,~1.2 KiB/view)40,0003.38 MiBEager creation across 40,000 entries would have cost
~45.2 MiBof kernelphys_footprint(~1.2 KiBper retainedMTLTextureTypeTextureBuffer). With lazy materialization,mirror()creates0Metal textures and adds+16 KiBtotal for a 40,000-entry heap.Lazy materialization gated on shaders that actually use
TypedBuffer:NativeHost::mirroralways callswrite_buffer([gpu, 0, size]) and sets two bits per entry inNativeHeap::typed_pending(PendingTyped:typedfor all typed and 4-, 8-, or 16-byte structured views;explicitforstride == 0typed views).Binding::of(shader)scans the module's DXILTYPE_BLOCK,CONSTANTS_BLOCK, andVALUE_SYMTAB_BLOCKonce (list::dxil_uses_typed_buffers) to check whether kept instructions calldx.op.bufferLoad.*,dx.op.bufferStore.*, ordx.op.getDimensionson aTypedBuffer(dx.types.ResourcePropertieskind10— soTexture2DgetDimensionsstaysfalse, verified inheap_tests).NativeHost::materialize_typed_buffers), draws and dispatches whose bound stages havetyped_buffers == falsereturn immediately. Whentyped_buffers == true, only pending entries inside the boundRoot::Tableranges are promoted viawrite_typed_buffer(plus explicitstride == 0typed buffer views in the bound heap whenheap_typed_buffers == true), leaving unbound structured buffers across the heap unmaterialized.Unaligned (< 16 B) buffer offsets &
SINT->UINTmapping:dev.minimumTextureBufferAlignmentForPixelFormatis16bytes across all tested formats on Apple Silicon. CallingnewTextureWithDescriptor_offset_bytesPerRowat a non-16-byte offset trips Metal validation, soMetal::write_typed_buffernow logs atracing::warn!on the first unaligned typed buffer view (debug!thereafter) and falls back towrite_buffer([gpu, 0, size]). Raw/structured accesses at word 0 (gpuVA, 4-byte aligned) continue to work; formatted accesses at word 1 read0/ no-op instead of asserting (gfx::heap_set_tests::a_heaps_set_follows_its_entriesnow tests an unaligned+4view).SINT->UINT: Yes, mapping 32-bitSINT(4,18,43) toUintwhile leaving 8- and 16-bitSINT(14,32,38,52,59,64) unmapped is intentional.victory-shaderlowers all formatted buffer loads/stores through float-typed DXIL handles (TypedBuffer<float4>,props = (10 | u, 0x409),bitcast i32 <-> float), sometal-shaderconvertertakesv4f32from the DXIL handle (@air.read/write_texture_buffer_1d.v4f32), while Apple Silicon's texture hardware unpacks/packs according to theMTLTextureview'sMTLPixelFormat(proven on GPU by0x0000_0012— subnormal float2.5e-44— packing to0x0012and reading back0x0000_0012onRGBA16Uint). For 32-bit channels there is no sub-32-bit sign extension or clamping, soUinttransfers all 32 two's-complement bits identically (now GPU-tested forR32_SINTcode43with0xDEAD_BEEF, alongsideR16G16_SNORMcode37); 8/16-bitSINTwould zero-extend underUint, so they stay excluded.Refs #255& #264 overlap:Updated both commit message and PR description to
Refs #255, and restructureddescriptors.rs,list.rs, andhost.rsagainst #264's diff (Decoded::Bufferanddecodeare now untouched vsorigin/main,typed_buffersits aftersampler, andtyped_pendingsits afterimages), eliminating line overlap with #264; happy to rebase again as soon as #264 lands.Synthetic test program confirmation:
Confirmed: the
llvm-disinspection ofmetal-shaderconverteroutput described here and in #255 was run solely on a small synthetic DXIL test program of our own, never on any game shader or title file, and no listing from it is in the repository or in the comments (cargo xtask policypasses across all 371 files).Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T11:54:28Z.
Thank you for answering all five points with numbers, and for making the mirror lazy.
I ran
bff96ea6in the game, together with #263, #253 and #264 on maince2b7860(Series S, headless). The 1280x720 G-buffer targets are 60 to 87% covered. The run made 70,492 typed views, all in the first block of world frames, and logged one "typed buffer view offset is not aligned" warning (offset 0x83aee88), which fell back to the raw entry as you intend. Views that wrap the title's pages (#267) also got their typed word. The lighting output is still noise, and the run ended in the known GPU time-out and title fault.Two questions before I merge. When a shader's DXIL scan says "no typed buffer" but it does use one, what does it read? Please add a test where the scan result is wrong on purpose, so we know the failure is a zero read and not a crash. And 70,492 is a count of promotions: can you add a count of entries that hold a typed view at one time, so we know the memory it keeps?
Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T12:16:52Z.
Rebased onto
main(92e0cd5b->16732233) and addressed both questions:What happens if
Binding's DXIL scan falsely says "no typed buffer" (typed_buffers == false):NativeHost::mirrorwrites[gpu, 0, size]viaMetal::write_buffer, leaving word 1 (textureViewID) at0(nullMTLResourceID) — and whenever an already-promoted slot is re-mirrored bymirror(),write_bufferzeroes word 1 back to0and drops the previousMTLTextureview, so there is never a stale or danglinggpuResourceID.air.read_texture_buffer_1dandair.get_width_texture_buffer_1donMTLResourceID(0)return[0, 0, 0, 0]and0, andair.write_texture_buffer_1donMTLResourceID(0)is a no-op, with no GPU fault or command-buffer error.native::tests::heap_tests::wrong_typed_buffer_scan_reads_zero_without_crashing, which compiles both a typed SRV shader (buffer_load_format_xyzw+getDimensions) and a typed UAV shader (buffer_store_format_xyzw+buffer_load_format_xyzw+getDimensions), forcesb.typed_buffers = falseandb.heap_typed_buffers = falseon purpose, and verifies on Metal both for a freshmirror()slot and for a previously promoted slot (live_typed_views == 1) that was overwritten bymirror()(live_typed_views == 0): no crash,buffer_store_format_xyzwleaves title memory untouched, andbuffer_load_format_xyzw+getDimensionswrite[0, 0, 0, 0, 0]over a0xCAFE_BABEoutput canary.Live count of entries holding a
texture_bufferview at one time (live_typed_views):Heap::typed_views(ResourceBackend::heap_typed_views, maintained inMetal::heap_entrywheneverSome(tex_view)is inserted vs overwritten/cleared) andNativeHost::live_typed_views(&self) -> usize, pluswrite_typed_buffer -> boolso unaligned fallbacks towrite_bufferare not counted as promotions.typed_views(cumulative promotions) alongsidetyped_views_live(entries currently holding aMTLTextureview across all heaps) inglue::log_draw_counts(native typed buffer views, placed below thenative draws so farline so it will not conflict with#264), and pinned both counts ina_heaps_set_follows_its_entriesandformatted_buffer_stores_and_loads_through_structured_and_typed_uavs(typed_views == 8,live_typed_views == 1).Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T12:22:43Z.
Your earlier head
bff96ea6is on main now: it went in together with #264, after my game run of the two with #253 (G-buffer 60 to 87% covered, 70,492 typed views made, one unaligned-offset fallback). Thank you for the answer about a wrong scan and the new test. Your rebased commit16732233conflicts with what is on main in four files, because I had added a similar test and counter; I am putting the two together myself, keeping yours where they do the same job, and I will merge that so this pull request closes. You do not need to rebase again.