GPU: make ExecuteIndirect clamping countBuffer-aware and non-destructive #242
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/242"
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 Marvisak/VIctory. Originally posted by wbkepler on 2026-11-24T01:43:41Z.
Summary
Fixes
ExecuteIndirectargument clamping to respect optionalcountBufferand avoid mutating shared titleShadowbuffers in-place:indirect.rsclamp compute shader:src_args(atargs_offset) and optionalcount_buf(has_count+count_offset) via read-onlyByteAddressBufferSRVs (rebasing >4 GiB offsets safely).min(records, count_buf.Load(count_offset))so uninitialized tail slots never consume the per-list budget.BUDGETvia CAS without 32-bit unsigned wraparound, and copies fullstridebytes of active records into a dedicatedRWByteAddressBufferdst_argsscratch buffer at offset0.host.rs,indirect.rs):HostList::indirect_scratchandHost::uav_buffermanage a growable, reusable per-HostListDEFAULT-heap UAV scratch buffer (keeping replaced buffers alive untilreset()), bracketed byCOMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT -> COMMONbarriers while leavingShadowbuffers inCOMMON.draw.rs:0while preserving the original counter buffer and offset.indirect.rsincluding live D3D12 WARPExecuteIndirecttests (countBuffer=3with 4,093 garbage tail slots, back-to-back calls, non-destructive source,stride=24preservation, and 128-recordBUDGETsaturation without wraparound) plusHostListscratch reuse/growth/reset and layout validation tests.Verification
cargo clippy --workspace --all-targets— passed (zero new warnings)cargo clippy -p victory --features diagnostics --all-targets— passedcargo test --workspace— passed (46/46 default, 49/49 diagnostics invictory-gpu)cargo xtask policy— passed (151 files ok)Imported from Marvisak/VIctory. Originally posted by artor410 on 2026-11-24T03:38:00Z.
Review: COMMENTED
Review and test of head
1f7f7d2, on top ofmaind2a4bae. Windows 11, hardware GPU, plus a WARP run with the D3D12 debug layer and GPU-based validation.Tests:
cargo test -p victory-gpu --libgives 47 passed, 1 ignored. Clippy's only warning is inhost.rs:267, which is already onmain.The design: I agree with r4tedx. A count-aware clamp that writes into a scratch buffer and leaves the title's records alone is the right shape.
Resource states (confirms r4tedx's note): I added a local probe to this PR's tests. It is not pushed. It uses
WarpHarness, with the debug layer and GPU-based validation on:tgoes from COMMON to UNORDERED_ACCESS. TheWORKER_CSwrites to it, standing in for the title's argument pass.record_clamp(src = (t, 64), count = (t, 0)), thenExecuteIndirect(..., Some(&t), 0).The debug layer reports three errors:
SetComputeRootShaderResourceView: state UNORDERED_ACCESS "is invalid for use as a root shader resource" (the source and the count);ExecuteIndirect: state UNORDERED_ACCESS "is invalid for use as a count buffer". It expects INDIRECT_ARGUMENT.GPU-based validation also reports "Uninitialized root argument accessed" for root parameters 1 and 2 of the clamp dispatch. That is probably a follow-on of the rejected bindings. The dispatch still ran (
hits 1).The count-buffer error is a regression from
mainwhen the count sits in the same buffer as the arguments, the case Raxstreams describes.maintransitions that buffer UNORDERED_ACCESS → INDIRECT_ARGUMENT around the execution. This PR leaves the title's buffers untransitioned.A count in a separate buffer that a shader wrote is wrong on
maintoo.Suggested fix: Before the clamp, transition the source and count buffers from UNORDERED_ACCESS to NON_PIXEL_SHADER_RESOURCE | INDIRECT_ARGUMENT, and back after
ExecuteIndirect, the waymain'sbound/donedo. Alternatively, route them through whichever state tracker lands (#334 / #367). A test like the probe above, with the debug layer's info queue checked for errors, would catch it.Smaller notes:
argument_space, would let executions overlap if it shows up in profiles.Synthetic tests only; untested against the title.
🤖 Generated with Claude Code
Imported from Marvisak/VIctory. Originally posted by gw1337x on 2026-11-24T01:51:19Z.
In-game data point on an RX 7800 XT (Windows 11 26200, 31.6 GB),
diagbuild,VICTORY_D3D12_DRED=1, one run each:maind2a4bae+ #135 + #124 + #130Both runs end the same way: a page fault inside freed textures (#135's remaining case). The world stays black behind the cutscene subtitles in both, at about 1–1.6 fps. So I can only say this build got further, not that this PR alone did; #230 is in the second build too.
On top of #135 the merge had one conflict, the
DISPATCHarm ofState::execute_indirect. I kept this PR's pipeline-kind check above it and used #135'sbindresult:DISPATCH => self.bind(list, p, true).Imported from Marvisak/VIctory. Originally posted by Raxstreams on 2026-11-24T03:02:35Z.
Tested this change in a local Windows integration with the rectangle expansion and buffer-state tracking changes. All five indirect tests passed, including the WARP checks for preserving input records, ignoring the tail after the active count, and saturating the budget. Some title draws also place the count in the same shader-writable buffer as the arguments. In the integration I snapshot the bounded count into the scratch allocation and use it for ExecuteIndirect as well. I have not verified a fully presented world frame with this change.
Imported from Marvisak/VIctory. Originally posted by r4tedx on 2026-11-24T03:30:13Z.
Review note (built on
maind2a4bae; tests pass on an RTX 5070). The design here, a count-aware clamp that writes sanitized records to a scratch buffer and leaves the title's argument buffer alone, looks like the right one;mainand #40 write through allMaxCommandCountrecords of the title's own buffer, including ones the native call would skip.One gap, on resource states. The clamp binds the title's argument and count buffers as root SRVs (
SetComputeRootShaderResourceView(1, src_gpu)), and the comment says they stay as they are; only the scratch buffer is transitioned. When the same submission's compute pass wrote those arguments through a UAV (the usual case: the title's culling passes produce them), the host copy is in UNORDERED_ACCESS at that point, and a buffer can only be promoted to a read state from COMMON. That is the same class of error the debug layer reports in #199 / #264 for vertex buffers. It needs a transition of the source before the clamp reads it, or to go through whichever buffer-state tracker lands (#334 / #367).I could not check this with the debug layer (not installed here); someone who has it could run this PR's own tests with a UAV producer in the same list.
From reading and synthetic tests only; I have no copy of the title.
Imported from Marvisak/VIctory. Originally posted by wbkepler on 2026-11-24T03:42:32Z.
Thanks @r4tedx, good catch. Pushed
1711205:HostList::gpu_writtenreports whether the list already declared shader (UAV) writes to a buffer's host copy, i.e. whether implicit promotion has left it inUNORDERED_ACCESSfor the rest of the submission.indirect::boundtransitions each such buffer among the argument and count buffers (deduplicated, since the count can live in the argument buffer)UNORDERED_ACCESS -> NON_PIXEL_SHADER_RESOURCE | INDIRECT_ARGUMENTbefore the clamp dispatch;indirect::donemoves it back afterExecuteIndirect(which also reads the count in that state), so later UAV writers in the list still find it inUNORDERED_ACCESS. Buffers the list has not written keep relying on promotion fromCOMMON.This only sees writes declared through
defer_gpu_write; once #367 (buffer-state tracker) lands, this should route through its tracker instead. Workspace clippy/tests andcargo xtask policypass; I have not run it under the debug layer.Imported from Marvisak/VIctory. Originally posted by wbkepler on 2026-11-24T06:55:42Z.
Thanks @artor410 and @r4tedx for the thorough review and debug-layer probe! Pushed a follow-up commit:
WarpHarnessinindirect.rsnow enablesID3D12Debug+ID3D12Debug1::SetEnableGPUBasedValidation(true)(with full state tracking enabled) whenVICTORY_D3D12_DEBUG=1/VICTORY_D3D12_GBV=1are set, requires a liveID3D12InfoQueue, and asserts zeroCORRUPTIONorERRORmessages after everysubmit_and_wait().VICTORY_D3D12_DEBUG=1 VICTORY_D3D12_GBV=1 cargo test -p victory-gpu --lib indirect -- --test-threads=1: 6 passed, 0 failed, 0 D3D12 debug/GBV info-queue errors acrosswarp_reads_arguments_written_earlier_in_the_list(UAV producer -> clamp +ExecuteIndirectwith count in the same buffer -> later UAV writer),warp_count_buffer_ignores_garbage_tail_and_preserves_source(back-to-back calls including a non-zero bump offset), andwarp_budget_saturates_without_wraparound_and_preserves_draw_fields.HostList::indirect_scratchnow bump-allocates 16-byte-aligned slices(buffer, offset)within the list's device-local scratch buffer (resettingused = 0onHostList::reset()),record_clamptargetsdst_base + dst_offset, anddraw::State::execute_indirectpassesbounded.offsettoExecuteIndirect. Updatedhost_list_reuses_and_grows_scratch_across_submissionsandwarp_count_buffer_ignores_garbage_tail_and_preserves_sourceto verify non-zero offsets and reset behavior.Full gate:
rustfmt --edition 2024 --check crates/victory-gpu/src/indirect.rs,cargo clippy -p victory-gpu --all-targets(0 new warnings),cargo test -p victory-gpu --lib(48 passed, 0 failed, 1 ignored), andcargo xtask policy(151 files ok).Imported from Marvisak/VIctory. Originally posted by rouges78 on 2026-11-24T09:12:37Z.
Hardware data point on the budget loop, RTX 4080, Windows 11. I added one test to this branch: N draw records of one vertex instance each (kind 0, stride 16, no count buffer), which all fit the budget, clamp alone, timing
host.execute.When many records fit, each successful compare-exchange makes the other threads retry, so the work grows roughly with the square of the record count. 4,096 small records already sit at the host's 2 s time-out. Each device loss came with an nvlddmkm event 153. WARP does not show this (no time-out), and the garbage-record tests don't either, because the budget saturates after a few reservations and everything else exits early.
main does not have the problem but still wraps. A single thread walking the records with a saturating count avoids both (27 ms for 65,536 records here): https://github.com/rouges78/VIctory/tree/fix/indirect-budget-wrap, test
records_within_the_budget_all_run. It has no count-buffer awareness, which this PR has; the two could be combined.AI-assisted; the numbers are from real runs on the card.
Imported from Marvisak/VIctory. Originally posted by Pin0d1 on 2026-11-24T12:38:17Z.
I tested #242 on WARP and an RTX 2060 SUPER. It preserved the source buffer and passed all five raster cases I tested.
One edge case I found involves four 16-byte DRAW records at a 24-byte stride. The last payload fits in 88 bytes, but the buffer lookup requested 96. I included a regression test for that case in Pin0d1/VIctory#1, along with the ordered work-budget changes.
Download the patch · Reproduction steps, tests and logs
Imported from Marvisak/VIctory. Originally posted by FunWithFlagsDev on 2026-11-24T13:26:36Z.
Proposed mitigation for CAS contention: group-aggregated budget reservation
Following the hardware contention results reported by @rouges78 in #242 and #583, I investigated an alternative to both per-record atomic reservations and fully sequential processing.
The proposed approach uses a saturating parallel prefix scan within each 64-thread group, followed by a single successful global CAS reservation per admitted group.
The prototype:
For 65,536 positive-cost records that all fit within the budget, this reduces successful global reservations from 65,536 to 1,024 (98.4375%). CAS retries and synchronization overhead remain additional costs.
CPU-side validation
Both test suites passed, covering 16 automated tests and 71,536 combinatorial and randomized cases across the two models.
The grouped implementation matches the scalar saturation policy for the corresponding group-ordered linearization. It does not necessarily admit identical records under different concurrent scheduling orders.
Limitations
The HLSL prototype has not yet been compiled with Microsoft's D3DCompiler_47 or executed on a GPU.
The reduction in successful reservations is theoretical, not a measured performance improvement. Global CAS contention is reduced in scope but not necessarily eliminated.
The patch targets #242 rather than introducing another independent overflow fix.
A useful next step would be to compare this prototype against main, #242, and the sequential implementation using the existing 1,024–65,536-record synthetic workload.
This contribution was developed with AI assistance. No proprietary game assets were used.
Feedback and independent GPU validation would be appreci
victory_pr242_group_budget.zip
ated.
Imported from Marvisak/VIctory. Originally posted by rouges78 on 2026-11-24T14:17:33Z.
@FunWithFlagsDev I measured the scheme on the RTX 4080. Short version: with 64-thread groups and this PR's retry loop it is about a thousand times faster than this PR at 1,024 records, but still not linear. A back-off between retries, or 1,024-thread groups, removes the quadratic growth in what I measured, and the 1,024-thread version stays within twice a plain add up to a million records.
I did not open the zip: I don't open archives attached to comments, from anyone. Instead I had three implementations written independently from your description, all with this PR's root signature and bindings, so each replaces its
SOURCEas it is. All three use 64-thread groups: a Hillis-Steele scan with 7 group syncs, and two versions with 2 syncs where each lane sums the lanes below it. One lane per group reserves the group's total with this PR's compare-exchange loop, retried at once. So the numbers are about the scheme, not about your file. The harness takes any shader file with these bindings; I can push it to a branch if you want to time yours.All of them compile as
cs_5_1with D3DCompiler_47, pass this PR's three WARP execution tests, and pass a policy check on WARP and on the card (draw records only: exact fit, a group whose plain sum is 2^32, a count in the middle of a group, random mixes). One thing was needed for FXC: no earlyreturnbefore a group sync (error X4026), so lanes past the count are masked and still reach every sync.Clamp alone, N draw records of one vertex instance each, all fitting, in ms. Each run is the median of 3; a range covers the variants and sessions I ran for that cell.
What I take from it:
cs_5_1maximum, with a two-level prefix, 3 syncs and the same plain retry loop. It needs the dispatch count changed torecords.div_ceil(1024). From 131,072 to 1,048,576 records each doubling costs 2.0 to 2.4 times more (2.4 to 3.2 times between 16,384 and 131,072), and from 65,536 up it costs 1.2 to 1.9 times the plain add. I expected it to stay quadratic in the number of groups. My guess is that the card keeps only so many 1,024-thread groups running at once, so no more than that many compete for the budget word however long the call is. I have not checked that. A call with up to 1,024 records is then one group: no contention inside it, and the records are admitted in record order.So the 1,024-thread version of your scheme and the tile walk are both fast enough here. They differ in which records survive when the budget runs out, and in what the result rests on: the tile walk has no contention by construction, while the 1,024-thread version still runs the retry loop between groups, and its scaling is what this card did in two sessions, not something I can explain yet. Both beat the single-thread walk I suggested above (31 ms at 65,536), so I would take either over mine.
Method: a private device and queue on the hardware adapter, one submission holding only the clamp, timed around
Close,ExecuteCommandListsand the fence wait; after each run every record, the budget word and the source buffer are checked. The first column is this PR's shader with the compare-exchange loop replaced bymain's plain add, dispatched as in this PR. The last two columns are separate shaders in this PR's layout (separate source buffer, every word of the record copied), each run as a singleDispatch(1, 1, 1). So none of the three is themainor walk figure of my previous comment, which timedhost.executeand had a floor of about 1.4 ms; the two methods agree on this PR at 1,024 records (155 ms then, 152 to 153 ms now). The "earlier run" cell is from that comment. From 16,384 records up, sessions differ by 4 to 25% on the same shader, more than the three 64-thread variants differ from each other, so the ranges do not rank them.All records fitting is the worst case for a compare-exchange loop: every contender has to win once. With a spent budget or zero-cost records this PR and the grouped variants issue no exchange at all (read from the shaders, not timed).
Not measured: other vendors, dispatch and mesh records, mixed costs, and the title.
AI-assisted (Claude wrote the shaders and the harness); the numbers are from real runs on the card.
Imported from Marvisak/VIctory. Originally posted by FunWithFlagsDev on 2026-11-24T14:24:40Z.
Thank you, @rouges78. This is an excellent independent evaluation of the proposed group-aggregated reservation scheme.
Your measurements confirm both the expected reduction in contention and its remaining limitation: aggregation moves contention from individual records to groups, but does not eliminate it.
The 1,024-thread variant is particularly interesting, especially its measured performance within roughly twice the plain-add baseline at one million records.
I also agree that the ordered tile walk has an important advantage: contention is eliminated by construction, and admission order is deterministic.
Following our original group-aggregated proposal, I developed a separate hierarchical saturated-prefix-scan prototype that eliminates global CAS reservations entirely while preserving record order. It uses multiple dispatches rather than a single-dispatch retry loop. CPU-side validation passed, but its GPU performance remains unmeasured.
Thank you for the extensive hardware testing and for clearly distinguishing the independent implementations from the original attachment.
Imported from Marvisak/VIctory. Originally posted by wbkepler on 2026-11-24T20:36:06Z.
@rouges78, @Pin0d1, @FunWithFlagsDev: thank you for the measurements and the sizing repro. Both are addressed in the latest push.
(records - 1) * stride + payload(0 when records is 0). Four 16-byte DRAW records at a 24-byte stride need 88 bytes, not 96. This is a unit test, plus a WARP regression test that runs the clamp against an exact 88-byte buffer. The last record is also copied only up to its payload.The branch is rebased onto upstream
ffe310e(now6cb8fbe). Verified with clippy (-D warnings, including the diagnostics build),cargo test -p victory-gpuand the asset policy check. I have not re-measured on an RTX 4080, so the 4,096 and 16,384 record cases from @rouges78 would be welcome to confirm.AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.
Imported from Marvisak/VIctory. Originally posted by rouges78 on 2026-11-24T20:59:28Z.
@wbkepler confirmed at
6cb8fbeon the RTX 4080 where the compare-exchange loop timed out (Windows 11):host.execute, N draw records that all fit, median of 7 in two rounds, ms: 4,096: 0.26; 16,384: 0.57; 65,536: 1.8; 1,048,576: 26.6 (main: 0.42 / 1.3 / 5.7 / 72).cargo test --workspace --lockedpasses on the card (348 passed); theindirecttests also on WARP.bound, plus 600 generated cases and 14 hand-written ones (exact fits, the budget ending on a tile boundary, 70,001 records, wide strides, three calls in one list). Both admit exactly the same records, on the card and on WARP. They differ only where they should: a rejected record has all its count words zeroed here and only the first there, and with a count below the maximum this PR does not charge the inactive tail.resetthat held older arguments gets its rejected records stored as zero (200 draws, 170 fit).The test glue is local; I can push it to a branch if useful. AI-assisted (Claude wrote the harness and ran it with me; the numbers are from real runs).
Imported from Marvisak/VIctory. Originally posted by aycow on 2026-11-24T21:58:53Z.
@wbkepler I prepared a separate logical-resource-span control against
70564ae. A 64-byte native shadow covers a request the 28-byte guest argument resource must reject. The test passed on AMD and WARP and checks payload-only final records and count offsets. The candidate changes the list entry guard only and gives credit to raffclar's final-record review on #40. Your native count-resource and non-destructive clamp work at6cb8fbestays separate. The fixture does not exercise native barriers. If you see an overlap at the list boundary, I'd welcome the exact case.AI-assisted using Codex.
Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-25T00:23:36Z.
Automated triage for the maintainers.
Needs rebase. This PR does not merge cleanly into current
main(ac2525d). Conflicting files:crates/victory-gpu/src/draw.rs,crates/victory-gpu/src/host.rs.The content has not been reviewed yet; it will be once the branch is rebased onto
main.Generated by Claude Code
upstream-sync referenced this pull request2026-11-25 02:05:57 +00:00
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.