Repository navigation
GPU: transition host copies of title memory between shader writes and reads - #334
realhenners wants to merge 2 commits into
Conversation
|
Tested
The errors left in the run are the known ones: 114× Wave64 compute refused (#54), the 1,310,720 > 1,000,000 shader-visible heap (#16), and the two texture formats of #55. The world still ends in AI-assisted. |
|
Tested on a real RTX 5070 Laptop GPU with a GTA VI dump (the game run you asked for). With this PR applied (on It doesn't get the world rendering on its own — a device-removal still happens later from other causes (compute PSOs refused for Wave64 on this 32-lane card, since fixed by #189; plus remaining untranslated geometry shaders). But the buffer-state transitions this PR adds are clean on NVIDIA, so the barrier side is resolved. Thanks for the fix. |
|
Review note. I built this on One case where a write loses to a read within a single command.
So a dispatch that writes a host copy through a table UAV and also reads it through a root SRV gets a WRITE to READ barrier just before it runs, and writes the copy while it is in GENERIC_READ. The next read needs no transition either, so nothing separates those writes from a later vertex or index read of the same copy, which is the situation this PR exists to prevent. With one 174 MiB heap backing most of the title's buffers, one copy being both read and written by the same dispatch seems likely. Would letting the write state win within one command (or a combined state for copies used both ways) work here? From synthetic tests and reading only; I have no copy of the title. |
|
Tested on the #348 machine, stacked with #175 (Agility) + #346 (rectangles): the world-entry GPU hang persists here, and the dominant gap on this NVIDIA card looks like the wave64 compute refusals (#71), not buffer states. Setup: Windows 10 21H2 19044.7846, RTX 3080 10 GB (32.0.15.9649), Ryzen 9 7900X, 32 GB. This PR's head
So on this machine the state tracking alone does not prevent the hang; with #233 stacked (wave64 split) the refusals drop to 1 and the failure changes shape (a crash in Integration note: #346 also reworks AI use: Qwen Code (underlying model name not disclosed by the tool) built and ran the stack and drafted this comment at the user's request; counts are from the run log. |
|
Combination check on RTX 5080 / driver 621.24 / Windows 11 26300, local Xbox Series 1.0.2.1:
So the buffer transition work and the console-flow work together do not resolve #97 on this setup. This is a negative compatibility result, not a failure of either targeted test suite. Only aggregate counts and error classes shared. AI-assisted (Kimi Code). |
|
Tested commit
This confirms the PR's synthetic state-transition scenario on this AMD system. It does not test the GTA VI executable or the same-command case where a single host copy is referenced through both read and UAV descriptors. |
|
Tested
No game data used. AI-assisted (Claude Code, Claude Opus 5.5). |
|
A pointer for readers of the report above, since its last paragraph mentions #233: what happened with #233 stacked was narrowed down on that PR afterwards. The one compute pipeline the driver refused there ( Nothing here is about #334 itself. AI-assisted (Claude Code). |
The rewrite pass already writes records at or past the title's count as empty draws, so ExecuteIndirect does not need the count: it now runs all records from the list's own arguments buffer, with no count buffer. The rectangle path then changes the state of no title buffer: the count's host copy was moved to INDIRECT_ARGUMENT and back around the draw, which a buffer-state tracker such as Marvisak#458 or Marvisak#334 may have moved elsewhere, and which the draw's own shaders may need in another state (reported by claude-GTA6 on Marvisak#346: a device removal with Marvisak#458 stacked). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
hophaver's Marvisak#493: each root SRV becomes a one-descriptor table holding a raw view of the buffer's host copy from the root address to the copy's end, in a dynamic slot, so reads past the copy return zeros. VICTORY_ROOT_SRV_DIRECT=1 restores root descriptors. The branch carries Marvisak#336, which this tree had at 3c81420, and with it Marvisak#336's second commit e8d3b64. Conflict resolution, crates/victory-gpu/src/descriptor/host.rs: this tree's side is kept whole (the `spare` field, the capped sampler heap with its dynamic slots, `with`, `free_table`), and only c48b240's own additions are taken (raw_at, null_raw_at, is_sampler, gpu_handle). e8d3b64's sizing is not taken: it gives a heap the host caps 2^16 dynamic slots in place of 2^18 (MIN_DYNAMIC), so that more of the title's slots are mirrored. A tester measured that tradeoff in the title on an RTX 5080 (Zignixx, upstream issue Marvisak#71, comment 7123097017, one run per row): with 65,536 dynamic slots 22-30% of the requests for slots were refused and about 1,680 mesh dispatches per frame were dropped; with 262,144 none were, the peak in use was 132,014, and "title slot past the host heap" never fired in a 7-minute run. A capped view heap therefore keeps 2^18 dynamic slots, as this tree had. New test a_capped_view_heap_keeps_its_dynamic_slots (on the integration machine's RTX 5070 the heap of 1,310,720 title slots is capped: 737,856 title slots and 262,144 dynamic ones). Change beyond the PR, crates/victory-gpu/src/draw.rs, root_srv_table: the host copy is moved to its read state (list.buffer_state with BUFFER_READ), as root_view does since Marvisak#334. Marvisak#493 was written without Marvisak#334's buffer-state tracker; without this a copy a shader wrote earlier would be read through the table in its unordered-access state. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…through a twin texture) AnoHunted's Marvisak#469: a title texture that is both a depth target and unordered access gets a second host texture for its unordered access views; lists copy between the two where they track texture states. Conflict resolution, crates/victory-gpu/src/host.rs: Marvisak#334's buffer states and Marvisak#469's twins are both list state and both are kept (the `buffers` and `twins` fields, their initial values and their clearing in `reset`; `BufferStates` beside the `HostCopy` alias; `buffer_state` beside `move_to`, `sync_twin` and `copy_texture`). In `close`, the twins are copied back first, then Marvisak#334's buffers go back to common. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
RTX 4080 / Windows 10 A/B: the world hang remains; debug-layer state errors could not be measuredEnvironment
Important limitationThis Windows build reports So this run cannot confirm whether error IDs 527/538 disappeared. It can confirm whether the device removal remains. DRED was enabled; GPU timing and GPU-based validation were not. MethodTwo runs per variant, each with a new empty cache, the same profile/data directory, and the same scripted Enter schedule from 8 through 47 seconds. Run order was baseline, #334, #334, baseline. Each run stopped on process exit or at an eight-minute timeout. Results
The survival and frame-time ranges overlap. Two runs per variant are not enough to claim a performance improvement or regression. All four runs reached the world and then lost the device. None reported a page fault or a freed allocation. Commit headroom stayed above 7 GiB, so these particular failures were not commit exhaustion. The largest shader-translation gaps were the same in both variants: lane masks read as data, selects on untracked masks, addresses in non-root SGPRs, and structured buffers of unknown stride. Source-only verification
ConclusionPR #334 did not prevent the RTX 4080 world-load device removal in this test. The failure still lands in indirect execution or mesh dispatch, without a page fault. The targeted D3D12 state-error removal remains unverified here because the debug layer cannot be installed on this Windows build. A debug-layer-equipped tester is still needed to confirm the 527/538 result. No game files, paths, screenshots, shader dumps, or proprietary data are included in this report. AI-assisted testing and reporting; I ran the tests. |
…shader writes and reads) onto integ/next Conflicts: 1. crates/victory-gpu/src/draw.rs, `State::bind`: the stack (Marvisak#1439's depth sampling) resets `self.depth_sampled`, Marvisak#334 starts a buffer-state command (`list.begin_command()`). Independent; both kept, reset first. 2. crates/victory-gpu/src/host.rs tests: the stack adds `warp_device_creation_and_caps_probe`, Marvisak#334 adds `buffer_states_transition_between_writes_and_reads`, `buffer_states_keep_a_command_writing` and `debug_layer_accepts_buffers_written_then_read_as_vertices` (with its helpers) at the same place. The shared text holds the `#[test]` before and the closing brace after, so neither side's body closes inside the hunk: the stack's test is closed and Marvisak#334's follow as separate items (not nested). Non-textual fixes: - draw.rs `root_srv_table` (Marvisak#493, bounded root SRVs as one-view tables) reads a host copy without going through `root_view`, so it never asked Marvisak#334's tracker for the read state. It now calls `list.buffer_state(&s.buffer, BUFFER_READ)` after its refresh, on cache hits too, as Marvisak#334's author and Hiiva noted on Marvisak#334 (Marvisak#334 (comment), Marvisak#334 (comment)). - indirect.rs test `clamp_preserves_record_offsets_and_shared_budget` (Marvisak#1279, via Marvisak#1439) called `indirect::done`, which Marvisak#334 removes (the clamp now asks the tracker for the write state and `close` returns the copy to COMMON). The call is dropped; the next `bound` asks for the write state again, so no transition is missing.
…) onto Marvisak#334 + integ/next Taken instead of Marvisak#282 (same draws, Marvisak#255; only one can land): Marvisak#346 expands on the GPU after the clamp, so vertex data the GPU wrote earlier in the submission is seen, and its record grouping starts at each record's first vertex. It has the stronger title evidence: the loading screen renders (justlovett0, RTX 3080), the `prepare failed`/topology-17 drops go from 256 per frame to 0 with no device removal (neonbyte1, RTX 5090/Wine; Exorion1er, RX 9070 XT/Proton; iurysf, RTX 4070), and every defect reported on it was fixed by a later commit (scratch layout cee702e, record bounds 0aebe86, count buffer 7ff1184, Wine compiler c256f83). Marvisak#282 expands on the CPU (does not see GPU-written vertices, copies bound buffers whole, three times per draw after 4d3d003) and its last head was only checked in short runs. Conflicts: 1. crates/victory-gpu/src/indirect.rs, module doc: the stack's (Wine-safe clamp in structured buffers, root signature made beside it) kept, with Marvisak#346's sentence on the rectangle expansion added. 2. indirect.rs, `bound`: Marvisak#346 splits it into `clamp_uav` (clamp + UAV barrier) and `bound` (then a fixed UAV -> INDIRECT_ARGUMENT transition); Marvisak#334 (merged just before) replaced the fixed transitions with its buffer states (`bound` asks for BUFFER_WRITE, `execute` for BUFFER_READ). Kept Marvisak#346's split with Marvisak#334's tracking, the resolution justlovett0 and the author agreed on (Marvisak#346 comments 7121242441, 7121274527): `clamp_uav` takes the buffer, starts a command and asks for BUFFER_WRITE; `bound` is `clamp_uav` (the read state comes from `execute`), no fixed transition. 3. crates/victory-gpu/src/host.rs: the stack's `PooledUpload` and Marvisak#346's `RectScratch` added at the same place; both kept. Non-textual fixes: - rectangles.rs calls `clamp_uav(list, &args.buffer, ..)` (new parameter). - rectangles.rs: the rewrite and expand passes bind the count's and the vertex buffers' host copies as root UAVs. With Marvisak#334 those copies' states are tracked, so they now ask for BUFFER_WRITE in the clamp's command (otherwise a copy a draw had moved to GENERIC_READ would be bound as a UAV in a read state). The draw's own `prepare` then asks for the read state as before. The list-owned scratch keeps Marvisak#346's own barriers. - primitive.rs: Marvisak#346's half-float rounding commit (8c7ac43) is already here through Marvisak#1220 (in Marvisak#1418), so `half_midpoints_round_to_even` is not added twice: the PR adds 8 tests, 7 are new here.
…y unchanged pages current) onto Marvisak#346 + Marvisak#334 + integ/next Taken instead of Marvisak#693 (shadow buffers in DEFAULT VRAM with staging readback): both rewrite how shaders' writes reach title memory, on incompatible models (Marvisak#1024 stores from the CPU-mapped host copy; Marvisak#693 has no CPU mapping and merges from readback snapshots), so only one can land. Marvisak#693 has unfixed in-title regressions on its last head's predecessor and no title run since: about 2x slower frames and 5-7x GPU time on an RX 6700 XT (Marvisak#693 (comment)), GPU page faults inside freed `shadow readback/upload staging` on RX 6950 XT and RX 6700 XT (Marvisak#693 (comment)), and a changes-requested review (mercuryVM). Its last commit (1c94839) fixes the review's failure paths but not the performance loss, and was not run in the title. Marvisak#1024 has no negative report; its tests pass on RTX 4090/Wine, RTX 5070 Ti, RX 7700 XT, RTX 5090/Wine, and a title run with it (and Marvisak#472, Marvisak#322) had shorter frames and less copy-back time (AgneyaK). Conflicts, crates/victory-gpu/src/shadow.rs: 1. `Shadow::copy_back`: the stack (Marvisak#124, TG0000) skips pages already found unchanged against this submission's snapshot (`UnchangedPages`) and allocates the title buffer lazily, by PAGE; Marvisak#1024 writes back only the runs of bytes the GPU changed (`write_runs`) and marks a synced page current only if title memory still equals the copy after the final write-watch query. Independent: both kept. The loop keeps the stack's `unchanged.differs` guard and lazy buffer, with Marvisak#1024's run collection and `write_runs` inside; the final check takes the (by then allocated) lazy buffer for its page re-reads. 2. Tests: the stack's `mod tests` and Marvisak#1024's `mod copy_back_tests` at the same place. The shared text holds the closing `);`, `}` and `}`, so the stack's module is closed in the hunk and Marvisak#1024's module follows as its own `#[cfg(test)]` item (not nested). No other non-textual fix needed (cargo check --all-targets --all-features).
…us) onto Marvisak#1024 + Marvisak#346 + Marvisak#334 + integ/next One conflict, crates/victory-gpu/src/host.rs tests: the stack adds `adapter_filter_parses_index_and_name` and the capability tests, Marvisak#211 adds `present_compositor_builds_both_pipeline_states`, at the same place. The shared text holds the `#[test]` before and the closing brace after, so the stack's last test is closed in the hunk and Marvisak#211's follows as its own test (not nested). `Host::present` (single plane fast path, compositor for 2+) and `queue::present` merged without conflict; the stack does not change either. No non-textual fix needed (cargo check --all-targets --all-features). No negative report on Marvisak#211: the Series S menus render on RTX 2070 SUPER, RTX 4070 SUPER, RTX 3060 Laptop, RTX 4080, RX 7600 and WARP, and the device removals seen later in the world also happen in Series X mode without it.
…6B16A16_FLOAT) onto Marvisak#211 + Marvisak#1024 + Marvisak#346 + Marvisak#334 + integ/next Conflicts, both in tests: 1. crates/victory-gpu/src/descriptor/host.rs: the stack's tests (`raw_views_start_on_16_bytes` and the raw/structured view tests after it, from Marvisak#1426/Marvisak#704) and Marvisak#492's four `rgb9e5_srv_*` tests at the same place; git interleaved them over shared lines (a resource description's `SampleDesc`, a closing brace), so the two hunks are not separable texts. Resolved by keeping the stack's tests exactly as they were and adding Marvisak#492's four tests whole, as Marvisak#492 has them, before `dynamic_slots_are_held_until_released` (where Marvisak#492 put them). The resulting diff of the file against the previous head equals Marvisak#492's own (+235/-5 against main). 2. crates/victory-gpu/src/resource.rs: the stack's `get_desc_reports_the_allocated_mip_chain` and Marvisak#492's `r9g9b9e5_target_format_substitutes_rgba16f` / `r9g9b9e5_render_target_and_uav_textures_create_on_host` at the end of the module. The shared text holds the `#[test]` before and the closing braces after: the stack's test is closed in the hunk and Marvisak#492's follow as separate tests (not nested). The non-test changes (`target_format`, `fits` taking a resource description, `fits_texture_srv`, RTV and pipeline formats) merged without conflict. `fits` has no other caller in the stack. Uploads from title memory still skip render-target/UAV textures (`texture::title_written`), so no 4-byte RGB9E5 rows are detiled into a substituted 8-byte texture. Known open point from the review, not fixed by Marvisak#492: a copy between a substituted target and a sampled-only RGB9E5 texture would mismatch formats on the host; no report shows the title doing that. No non-textual fix needed (cargo check --all-targets --all-features).
…sak#98, Marvisak#334 to Marvisak#492, validation) The line rebuilt on the bundles' current heads (Marvisak#1402 119b763, Marvisak#1492 5bbc098 without Marvisak#98, Marvisak#1504 1d41891, Marvisak#1511 ca601f0) with every merge replayed, and the merges after this file's first version (Marvisak#334, Marvisak#346, Marvisak#1024, Marvisak#211, Marvisak#492): merge order, the runner's numbers on 967d3ae (RTX 571, WARP 570 + the known Marvisak#1084 failure, all features 580; Marvisak#98's one test leaves), what is not included (Marvisak#98, Marvisak#282 for Marvisak#346, Marvisak#693 for Marvisak#1024, Marvisak#306's latest commit), and the open pull requests whose head is contained here (109, from the 18:24 collection). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three review workers over ~30 PRs against the freshly merged upstream tree, plus three of our features the merge had discarded, re-applied with their tests: f32_to_half NaN/nearest-even (Marvisak#843), unique-temp atomic library writes (Marvisak#1660), VICTORY_PIPELINE_WORKERS (Marvisak#1728). Integrated: Marvisak#1146, Marvisak#1161, Marvisak#1474, Marvisak#1592, Marvisak#1058, Marvisak#1505, Marvisak#1177, Marvisak#1507, Marvisak#1236, Marvisak#1180 (with a new regression test for the cached opcode name). Duplicates confirmed against upstream's own code: Marvisak#957, Marvisak#1103, Marvisak#1057, Marvisak#299. Obsolete: Marvisak#513 (title_args no longer exists), Marvisak#1507's sibling Marvisak#334 covers it. Refused: Marvisak#1030 (zip dump of game data), Marvisak#962 (deletes .gitignore). Verified before this merge: fmt 0 differing, both Clippy gates exit 0, xtask policy 220 files ok, workspace 662 passed / 0 failed (10 GPU tests skipped that fail identically on upstream/main itself on this host).
|
Automated triage for the maintainers. Needs rebase. This PR does not merge cleanly into current The content has not been reviewed yet; it will be once the branch is rebased onto Generated by Claude Code |
The rewrite pass already writes records at or past the title's count as empty draws, so ExecuteIndirect does not need the count: it now runs all records from the list's own arguments buffer, with no count buffer. The rectangle path then changes the state of no title buffer: the count's host copy was moved to INDIRECT_ARGUMENT and back around the draw, which a buffer-state tracker such as Marvisak#458 or Marvisak#334 may have moved elsewhere, and which the draw's own shaders may need in another state (reported by
Code tree of fxceless/victory-fork 4e17478 (all rendering work by its author and the VIctory contributors) with, on top: - AMD fixes: skip of 39f0e9aeb156a61c, 32-lane programs per half wave and NaN/Inf filter, configurable texture upload queue, VIctory Marvisak#1599 - upstream VIctory Marvisak#334 (buffer-state tracking) and Marvisak#1271 (globally coherent glc UAVs) - fork PRs Marvisak#95, Marvisak#71, Marvisak#32, Marvisak#86; VIctory Marvisak#1696, Marvisak#1338, Marvisak#1291, Marvisak#1732 - DirectStorage page lists read at the title's submit (analysis by JappertjeV, klbf-lab#3) - offline pipeline pre-build that saves as it goes and skips driver-crashing pipelines - Series S plane composition, VICTORY_FFX_SIMPLE, scripted keys in release builds - docs/klbf/skip-amd.txt: AMD skip list used for our runs
|
Follow-up on the same-command limitation in RTX 5070 Ti 16 GB, NVIDIA 621.01, i7-14700, 32 GB RAM, Windows 11 Pro 26200. Native D3D12. When the command being prepared declares a UAV write to the argument or count allocation, the patch copies the bounded argument bytes and optional count on the GPU into a separate DEFAULT-heap buffer. The source transitions through the existing tracker and is restored to UAV before execution. One buffer per host list is reused between commands and grown when needed; earlier allocations remain held by the tracker. Commands without that overlap retain the direct path. This preserves the write-wins rule. Synthetic validation:
Title evidence on my combined local stack: a 366.3-second debug-layer run, manually stopped, logged 0 ID 527 and 0 ID 538, with no logged device removal/hang. The new argument-copy path activated. An earlier adaptation of #334 without this follow-up logged 1718 ID 538 indirect-argument errors in 145.0 seconds. My preceding build without #334 logged 1508 ID 527 and 1158 ID 538 vertex-buffer errors in 345.7 seconds. These are combined-stack observations, not a controlled single-variable A/B or performance benchmark. The new title run still has major visual corruption and poor frame times, 228 shader-translation refusal events, and other debug messages (four ID 645 capability probes and one ID 1419 sampler/root-signature issue). This is not a complete rendering or stability fix. The parent PR's untracked directly indexed views and same-command UAV/vertex/index sharing remain outside this patch. Integration details for newer main: keep root UAVs tracked as writes, preserve the current clamp implementation, and adapt Patch against c99e429 (synthetic fixtures only)--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -378,6 +378,204 @@
let code = code.unwrap();
std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
.to_vec()
+ }
+ }
+
+ /// Indirect arguments and their count may share the host allocation
+ /// the dispatched shader writes. GPU-generated arguments must be read
+ /// in INDIRECT_ARGUMENT while those shader writes remain legal UAVs.
+ #[test]
+ fn indirect_arguments_can_share_a_shader_written_buffer() {
+ use windows::core::s;
+ if in_child("indirect_arguments_can_share_a_shader_written_buffer") {
+ return;
+ }
+ let mut layer: Option<ID3D12Debug> = None;
+ // SAFETY: enable validation before this child creates a device.
+ if unsafe { D3D12GetDebugInterface(&mut layer) }.is_err() {
+ eprintln!("no D3D12 debug layer; skipped");
+ return;
+ }
+ // SAFETY: no device exists in this child yet.
+ unsafe { layer.unwrap().EnableDebugLayer() };
+ let Some(host) = host() else {
+ eprintln!("no host device; skipped");
+ return;
+ };
+ let messages: ID3D12InfoQueue = host.device.cast().unwrap();
+ const SOURCE: &str = r#"
+ #define RS "RootConstants(num32BitConstants=3, b0), UAV(u0), UAV(u1)"
+ cbuffer Mode : register(b0) { uint produce; uint groups; uint count; };
+ RWByteAddressBuffer args : register(u0);
+ RWByteAddressBuffer counter : register(u1);
+ [RootSignature(RS)] [numthreads(1, 1, 1)]
+ void main() {
+ if (produce != 0) {
+ args.Store3(64, uint3(groups, 1, 1));
+ args.Store3(80, uint3(5, 1, 1));
+ counter.Store(128, count);
+ } else {
+ uint ignored;
+ args.InterlockedAdd(0, 1, ignored);
+ counter.InterlockedAdd(4, 1, ignored);
+ }
+ }
+ [RootSignature(RS)] [numthreads(1, 1, 1)]
+ void count_only() {
+ uint ignored;
+ counter.InterlockedAdd(4, 1, ignored);
+ }
+ "#;
+ let code = compile(SOURCE, s!("main"), s!("cs_5_1"));
+ let counter_code = compile(SOURCE, s!("count_only"), s!("cs_5_1"));
+ // SAFETY: the shader contains its root signature; live bytecode
+ // and descriptors are read synchronously during object creation.
+ let (root, pso, counter_pso, signature): (_, _, _, ID3D12CommandSignature) = unsafe {
+ let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).unwrap();
+ let pso: ID3D12PipelineState = host
+ .device
+ .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+ pRootSignature: std::mem::transmute_copy(&root),
+ CS: D3D12_SHADER_BYTECODE {
+ pShaderBytecode: code.as_ptr().cast(),
+ BytecodeLength: code.len(),
+ },
+ ..Default::default()
+ })
+ .unwrap();
+ let counter_pso: ID3D12PipelineState = host
+ .device
+ .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
+ pRootSignature: std::mem::transmute_copy(&root),
+ CS: D3D12_SHADER_BYTECODE {
+ pShaderBytecode: counter_code.as_ptr().cast(),
+ BytecodeLength: counter_code.len(),
+ },
+ ..Default::default()
+ })
+ .unwrap();
+ let argument = D3D12_INDIRECT_ARGUMENT_DESC {
+ Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH,
+ ..Default::default()
+ };
+ let mut signature = None;
+ host.device
+ .CreateCommandSignature(
+ &D3D12_COMMAND_SIGNATURE_DESC {
+ ByteStride: 16,
+ NumArgumentDescs: 1,
+ pArgumentDescs: &argument,
+ ..Default::default()
+ },
+ None::<&ID3D12RootSignature>,
+ &mut signature,
+ )
+ .unwrap();
+ (root, pso, counter_pso, signature.unwrap())
+ };
+ // No count, an aliased count, a separate count, zero work, and a
+ // count above the maximum. Two executions also check fresh copies.
+ for (count_kind, count, expected, count_only) in [
+ (-1, 1, 17, false),
+ (0, 1, 7, false),
+ (1, 1, 7, false),
+ (1, 0, 0, false),
+ (1, 3, 17, false),
+ (1, 1, 7, true),
+ ] {
+ let (args, data) = host.shared_buffer(256).unwrap();
+ let (counter, counter_data) = if count_kind == 0 {
+ (args.clone(), data)
+ } else {
+ host.shared_buffer(256).unwrap()
+ };
+ let list = host.new_list().unwrap();
+ // SAFETY: mapped allocations, before the GPU uses them.
+ unsafe {
+ std::ptr::write_bytes(data, 0, 256);
+ std::ptr::write_bytes(counter_data, 0, 256);
+ messages.ClearStoredMessages();
+ }
+ let bind = |produce: u32, groups: u32| {
+ list.begin_command();
+ if produce != 0 || !count_only {
+ list.buffer_state(&args, BUFFER_WRITE);
+ }
+ list.buffer_state(&counter, BUFFER_WRITE);
+ let constants = [produce, groups, count];
+ // SAFETY: open list, live pipeline and buffers.
+ unsafe {
+ list.list.SetComputeRootSignature(&root);
+ list.list.SetPipelineState(if produce == 0 && count_only {
+ &counter_pso
+ } else {
+ &pso
+ });
+ list.list
+ .SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0);
+ list.list
+ .SetComputeRootUnorderedAccessView(1, args.GetGPUVirtualAddress());
+ list.list
+ .SetComputeRootUnorderedAccessView(2, counter.GetGPUVirtualAddress());
+ }
+ };
+ for groups in [3, 4] {
+ bind(1, groups);
+ // SAFETY: producer writes the argument records on the GPU.
+ unsafe { list.list.Dispatch(1, 1, 1) };
+ assert!(crate::indirect::bound(
+ &list,
+ &args,
+ // SAFETY: the argument buffer remains alive through execution.
+ unsafe { args.GetGPUVirtualAddress() } + 64,
+ (2, 16, 2),
+ ));
+ bind(0, 0);
+ crate::indirect::execute(
+ &list,
+ &signature,
+ (16, 2),
+ (&args, 64),
+ (count_kind >= 0).then_some((&counter, 128)),
+ )
+ .expect("indirect execution");
+ }
+ list.close();
+ host.execute(&[&list]);
+ let mut errors = Vec::new();
+ // SAFETY: bounded message buffers; GPU work has completed
+ // before reading either mapped result.
+ unsafe {
+ for i in 0..messages.GetNumStoredMessages() {
+ let mut size = 0;
+ messages.GetMessage(i, None, &mut size).unwrap();
+ let mut bytes = vec![0u64; size.div_ceil(8)];
+ let m = bytes.as_mut_ptr().cast::<D3D12_MESSAGE>();
+ messages.GetMessage(i, Some(m), &mut size).unwrap();
+ if (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 {
+ let text = std::slice::from_raw_parts(
+ (*m).pDescription,
+ (*m).DescriptionByteLength,
+ );
+ errors.push(format!(
+ "id {}: {}",
+ (*m).ID.0,
+ String::from_utf8_lossy(text)
+ ));
+ }
+ }
+ assert!(
+ errors.is_empty(),
+ "count kind {count_kind}, count {count}: {errors:?}"
+ );
+ assert_eq!(
+ data.cast::<u32>().read_volatile(),
+ if count_only { 0 } else { expected }
+ );
+ assert_eq!(counter_data.cast::<u32>().add(1).read_volatile(), expected);
+ assert_eq!(data.cast::<u32>().add(16).read_volatile(), 4);
+ assert_eq!(counter_data.cast::<u32>().add(32).read_volatile(), count);
+ }
}
}
@@ -593,7 +791,7 @@
let indirect = |list: &HostList| {
assert!(crate::indirect::bound(list, &buffer, gpu + 256, (0, 16, 1)));
bind(list);
- crate::indirect::execute(list, &signature, 1, (&buffer, 256), None);
+ crate::indirect::execute(list, &signature, (16, 1), (&buffer, 256), None).unwrap();
};
// A list that draws, draws indirectly, draws; then one that starts
// with an indirect draw, submitted together.
@@ -655,6 +853,9 @@
states: Mutex<States>,
/// The states of the host copies of title memory the list uses.
buffers: Mutex<BufferStates<ID3D12Resource>>,
+ /// Reused between indirect commands; the GPU copies argument bytes
+ /// here when their original allocation must remain shader-writable.
+ indirect_copy: Mutex<Option<ID3D12Resource>>,
/// The list that runs those transitions just before this one.
prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
/// The pipelines the list binds, for reports of slow submissions.
@@ -706,7 +907,9 @@
///
/// shortcut: buffers read only through directly indexed heaps are not
/// tracked, and a command that both writes a buffer and reads it as
-/// vertices, indices or arguments reads them in the write state.
+/// vertices or indices reads them in the write state. Indirect arguments
+/// and counts are copied to separate storage when their command writes
+/// the original allocation.
pub(crate) struct BufferStates<R> {
/// First state, current state, the command that last wrote it.
by_copy: std::collections::HashMap<usize, (u32, u32, Option<u64>, R)>,
@@ -923,6 +1126,7 @@
scratch: Mutex::default(),
states: Mutex::default(),
buffers: Mutex::default(),
+ indirect_copy: Mutex::default(),
prelude: (prelude_allocator, prelude),
pipelines: Mutex::default(),
budget: OnceLock::new(),
@@ -1409,6 +1613,67 @@
// SAFETY: an open list and a buffer the list holds.
unsafe { self.list.ResourceBarrier(&[barrier]) };
}
+ }
+
+ /// Whether the command being bound writes this allocation through a UAV.
+ pub(crate) fn buffer_written_by_command(&self, buffer: &ID3D12Resource) -> bool {
+ let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
+ buffers
+ .by_copy
+ .get(&(buffer.as_raw() as usize))
+ .is_some_and(|(_, _, wrote, _)| *wrote == Some(buffers.command))
+ }
+
+ /// GPU-only storage for one indirect command's arguments and count.
+ /// Commands in this list consume their copy before the next overwrites
+ /// it. The buffer tracker keeps older allocations alive if it grows.
+ pub(crate) fn indirect_copy(&self, size: u64) -> Option<ID3D12Resource> {
+ let mut copy = self.indirect_copy.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(buffer) = &*copy
+ // SAFETY: a descriptor query on an owned, live resource.
+ && unsafe { buffer.GetDesc() }.Width >= size
+ {
+ return Some(buffer.clone());
+ }
+ let desc = D3D12_RESOURCE_DESC {
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+ Width: size.max(1).checked_next_multiple_of(64 << 10)?,
+ Height: 1,
+ DepthOrArraySize: 1,
+ MipLevels: 1,
+ SampleDesc: DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+ ..Default::default()
+ };
+ let heap = D3D12_HEAP_PROPERTIES {
+ Type: D3D12_HEAP_TYPE_DEFAULT,
+ ..Default::default()
+ };
+ let mut buffer: Option<ID3D12Resource> = None;
+ // SAFETY: ordinary resource creation; descriptors and out pointer
+ // are valid through the call. Its states belong to the list tracker.
+ unsafe {
+ host()?
+ .device
+ .CreateCommittedResource(
+ &heap,
+ D3D12_HEAP_FLAG_NONE,
+ &desc,
+ D3D12_RESOURCE_STATE_COMMON,
+ None,
+ &mut buffer,
+ )
+ .ok()?;
+ }
+ let buffer = buffer?;
+ name(&buffer, || {
+ format!("indirect argument copy {:#x}", desc.Width)
+ });
+ *copy = Some(buffer.clone());
+ Some(buffer)
}
/// At submission: the list that moves each texture this list uses from
--- a/crates/victory-gpu/src/indirect.rs
+++ b/crates/victory-gpu/src/indirect.rs
@@ -176,6 +176,80 @@
true
}
+/// The actual argument bytes consumed by an execution, also used by
+/// diagnostics. A command may have written the original allocation again.
+pub(crate) struct Arguments {
+ pub(crate) args: (ID3D12Resource, u64),
+ pub(crate) counter: Option<(ID3D12Resource, u64)>,
+}
+
+/// A shader UAV and indirect arguments cannot use the same allocation in
+/// one command. Copy just the bounded argument range and optional count on
+/// the GPU, then restore the original UAVs before the command executes.
+fn arguments(
+ list: &HostList,
+ (stride, max): (u32, u32),
+ (args, offset): (&ID3D12Resource, u64),
+ counter: Option<(&ID3D12Resource, u64)>,
+) -> Option<Arguments> {
+ let write_args = list.buffer_written_by_command(args);
+ let write_count = counter.is_some_and(|(c, _)| list.buffer_written_by_command(c));
+ if !write_args && !write_count {
+ return Some(Arguments {
+ args: (args.clone(), offset),
+ counter: counter.map(|(c, at)| (c.clone(), at)),
+ });
+ }
+ let len = u64::from(stride) * u64::from(max.max(1));
+ let fits = |buffer: &ID3D12Resource, at: u64, bytes: u64| {
+ // SAFETY: a descriptor query on a resource the caller keeps alive.
+ let desc = unsafe { buffer.GetDesc() };
+ at.is_multiple_of(4) && at.checked_add(bytes).is_some_and(|end| end <= desc.Width)
+ };
+ if stride == 0
+ || !stride.is_multiple_of(4)
+ || !fits(args, offset, len)
+ || counter.is_some_and(|(c, at)| !fits(c, at, 4))
+ {
+ return None;
+ }
+ let copy = list.indirect_copy(len.checked_add(if counter.is_some() { 4 } else { 0 })?)?;
+ // This copy is a separate command from the shader use being prepared,
+ // so it can leave UAV even when that use just declared the same buffer.
+ list.begin_command();
+ list.buffer_state(args, BUFFER_READ);
+ if let Some((c, _)) = counter {
+ list.buffer_state(c, BUFFER_READ);
+ }
+ list.buffer_state(©, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32);
+ // SAFETY: checked source ranges and a separate, sufficiently large
+ // destination. Transitions order earlier shader writes before copying.
+ unsafe {
+ list.list.CopyBufferRegion(©, 0, args, offset, len);
+ if let Some((c, at)) = counter {
+ list.list.CopyBufferRegion(©, len, c, at, 4);
+ }
+ }
+ list.buffer_state(©, BUFFER_READ);
+ if write_args {
+ list.buffer_state(args, BUFFER_WRITE);
+ }
+ if write_count {
+ list.buffer_state(counter.unwrap().0, BUFFER_WRITE);
+ }
+ #[cfg(feature = "diagnostics")]
+ {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(|| {
+ tracing::info!("Indirect arguments copied away from a shader-written host buffer")
+ });
+ }
+ Some(Arguments {
+ args: (copy.clone(), 0),
+ counter: counter.map(|_| (copy, len)),
+ })
+}
+
/// Runs `max` records of `signature` from `args` (a host copy of title
/// memory) at `offset`, with their count at `counter` if there is one: both
/// read as arguments, after whatever wrote them (the clamp, or the draw's
@@ -183,10 +257,13 @@
pub(crate) fn execute(
list: &HostList,
signature: &ID3D12CommandSignature,
- max: u32,
+ (stride, max): (u32, u32),
(args, offset): (&ID3D12Resource, u64),
counter: Option<(&ID3D12Resource, u64)>,
-) {
+) -> Option<Arguments> {
+ let prepared = arguments(list, (stride, max), (args, offset), counter)?;
+ let (args, offset) = (&prepared.args.0, prepared.args.1);
+ let counter = prepared.counter.as_ref().map(|(c, at)| (c, *at));
list.buffer_state(args, BUFFER_READ);
if let Some((c, _)) = counter {
list.buffer_state(c, BUFFER_READ);
@@ -203,6 +280,7 @@
counter.map_or(0, |(_, at)| at),
)
};
+ Some(prepared)
}
fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
@@ -217,6 +295,44 @@
#[cfg(test)]
mod tests {
+ /// Invalid source ranges must not record copies or disturb the pending
+ /// shader-write declaration. Read-only arguments keep their original
+ /// resource and offset; copies are needed only for a simultaneous UAV.
+ #[test]
+ fn argument_snapshots_validate_ranges_before_recording() {
+ use super::*;
+ let Some(host) = host() else { return };
+ let (buffer, _) = host.shared_buffer(256).unwrap();
+ let list = host.new_list().unwrap();
+ list.begin_command();
+ let direct = arguments(&list, (16, 2), (&buffer, 64), None).unwrap();
+ assert_eq!(direct.args, (buffer.clone(), 64));
+ list.buffer_state(&buffer, BUFFER_WRITE);
+ for (stride, max, at, count) in [
+ (0, 1, 64, None),
+ (6, 1, 64, None),
+ (16, 2, 240, None),
+ (16, 1, u64::MAX - 3, None),
+ (16, 1, 65, None),
+ (16, 1, 64, Some(253)),
+ (16, 1, 64, Some(256)),
+ (16, u32::MAX, 64, None),
+ ] {
+ assert!(
+ arguments(
+ &list,
+ (stride, max),
+ (&buffer, at),
+ count.map(|at| (&buffer, at))
+ )
+ .is_none()
+ );
+ assert!(list.buffer_written_by_command(&buffer));
+ }
+ list.close();
+ host.execute(&[&list]);
+ }
+
/// The clamp compiles with the system's compiler and the host takes it.
#[test]
fn argument_clamp_builds() {
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -1044,13 +1044,16 @@
list.note_op(|| {
self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
});
- crate::indirect::execute(
+ if crate::indirect::execute(
list,
&signature,
- max,
+ (stride, max),
(&args.buffer, args.offset(arguments)),
counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))),
- );
+ ).is_none() {
+ why("could not copy aliased indirect arguments");
+ return false;
+ }
if kind == DISPATCH {
DISPATCHED.fetch_add(1, Ordering::Relaxed);
} else {Prepared and validated with OpenAI Codex. No game assets, captured shaders, screenshots, raw logs or private paths are included. Feel free to incorporate the fix and tests into this PR. |
… reads (upstream VIctory Marvisak#334, by hand onto this tree): each list tracks the state of every host copy it uses, its prelude moves each from common to its first state, a transition is recorded wherever the use changes (vertex and index buffers, root views, root SRV and UAV tables, buffer views in tables, the argument clamp's sources, indirect counts) and the list moves them back to common before it closes; within one command the write state wins. The scratch-argument ExecuteIndirect path and lazy prelude stay as they are. On RX 9070 XT the meshlet-cull indirect dispatches (0452fc2d2e2fc4c3, fc5e66f8f873d3bb) stopped hanging with this (fxceless/victory-fork #3)
Upstream superseded Marvisak#635 and Marvisak#568 (reverted just before this merge); Marvisak#189, Marvisak#334, Marvisak#437, Marvisak#542, Marvisak#587 and Marvisak#1529 are still open upstream and are kept. Resolutions: - emit::Options is upstream's struct with Marvisak#189's `wave64` added; TranslateOptions stays as its alias. lower::Parts carries both `options` and upstream's `view_marks`. - Shader cache: upstream's cached refusals and hit flag, keyed by Marvisak#189's Wave64 mode byte as before. - lower.rs: Marvisak#542's 2 GiB bound applies to raw and structured views; title memory (upstream's MEMORY path and root views read as memory) is not bounded again, being checked where it is looked up. Scalar loads take upstream's raw views plus Marvisak#437's UAVs. The descriptor-kind use keeps Marvisak#437's preference for image/vector uses inside upstream's fallback. image() is upstream's (its own a16 bias/compare, gather4_l and _cl grads), replacing Marvisak#437's parallel version. - Marvisak#189: AddH (upstream's f16 wave sum) in apply_wave_op; 16-bit reductions are refused in an emulated 64-lane wave. mask_dword checks Marvisak#189's deferred ballot errors before upstream's mask_number. - Marvisak#334: indirect arguments keep the per-list buffer states (no indirect::done); upstream's single-group clamp dispatch is taken, and its diagnostics readback copies from the read state without barriers. - GPU adapter: upstream still creates its device on the default adapter, so host_adapter() stays. The shader test host keeps the high-performance adapter pick and adds upstream's dedicated-memory requirement. - Marvisak#1529: gameinput.rs as the PR's own merge of main (scripted keys first, then keyboard and mouse); run.rs configures controls and FidelityFX.
|
Closing this in favour of 315cea1 on Thanks to everyone who tested it in the title. Across NVIDIA and AMD runs it took ids 527/538 to 0, which helped pin down the cause. If a driver or GPU-based validation ever objects to the promotion shortcut noted in |
Refs #199, #264 (NVIDIA: vertex buffer in
UNORDERED_ACCESSat a draw, barrier before-state mismatches, thenDXGI_ERROR_DEVICE_HUNGentering the world).Cause
Host copies of title buffers (
shadow.rs) are created inCOMMON(host.rs,shared_buffer) and never transitioned: they relied on implicit promotion. Promotion fromCOMMONlets a buffer be either written (UAV) or read in a list, not written and then read as vertices. The world's 174 MB heap (title buffer 0x19b10000+0xae00000in #199) is both.On top of that,
indirect.rsrecorded fixed barriers on the argument buffer:UNORDERED_ACCESS -> INDIRECT_ARGUMENTbefore everyExecuteIndirect, anddone()moved it back toUNORDERED_ACCESSafter. Because the arguments live in the same heap as the vertices, every indirect draw left the vertex data explicitly inUNORDERED_ACCESS. That matches both reports: the vertex buffer in UAV atDrawIndexedInstanced(#199, #264 id 538), and barriers whose before state was UAV while the buffer was inVERTEX_AND_CONSTANT_BUFFER(#264 id 527, 131 times).Change
BufferStates(host.rs): per list, the state of each host copy it uses: its first state and its current one. Reads (vertex, index, constant, shader resource, indirect arguments) useGENERIC_READ, shader writesUNORDERED_ACCESS, with a transition wherever the use changes.COMMONto its first state, andHostList::closemoves it back toCOMMON. State never leaks into the next list of the sameExecuteCommandLists.draw.rs: vertex and index buffers, root views, and buffer views in tables (readable: UAV views write, others read).indirect.rs: the clamp asks for the write state; the newindirect::executeasks for the read state and recordsExecuteIndirect. This replaces the fixedUAV <-> INDIRECT_ARGUMENTbarriers anddone().Shortcuts, also commented in the code: buffers read only through directly indexed heaps are not tracked. A single command that both writes a buffer through a UAV and reads it as vertices, indices or arguments leaves it in the read state, because D3D12 has no legal state for both.
Tests
host::tests::buffer_states_transition_between_writes_and_reads: the state logic (no GPU).host::tests::debug_layer_accepts_buffers_written_then_read_as_vertices: on the real host device with the D3D12 debug layer (run in a child process, since the layer is process-wide). Two lists submitted together use one shared buffer the way the world uses its heap: plain draw → argument clamp +ExecuteIndirect→ draw, then a list that starts with an indirect draw. It asserts the debug layer reports no errors. It skips without a debug layer or a GPU.main'sindirect.rsbarriers, the test fails with id 527 (barrier before stateUNORDERED_ACCESSvs the buffer's actualINDIRECT_ARGUMENT).COMMONdisabled, it also fails with id 527. The test therefore guards the cross-list handoff.cargo test --workspace,cargo test -p victory-gpu --features diagnostics,cargo build -p victory --features diagnosticsandcargo xtask policypass. Clippy onvictory-gpuadds no warnings.Not tested / limits
VICTORY_D3D12_DEBUG=1on their NVIDIA cards.UNORDERED_ACCESS. So the test cannot show NVIDIA RTX 4070 SUPER: D3D12 resource state validation failure when binding title buffer as vertex buffer #199's id 538 message disappearing, only the barrier consistency (527) and the state logic.DEVICE_HUNGis unproven. A transition from UAV to a read state also makes the shader writes visible to the input assembler, so stale or garbage vertex data is a plausible way to a hang, but NVIDIA RTX 4070 SUPER: D3D12 resource state validation failure when binding title buffer as vertex buffer #199's comment from an RTX 5080 run hung in a compute dispatch instead (closer to Host GPU device removed on RTX 4070 (diag build, DRED) - many shaders fail to translate #97).AI use: Claude Code (Claude Opus 5.5) found the cause, wrote the change and tests, ran them on the GPU above, and drafted this description.
🤖 Generated with Claude Code