Skip to content

GPU: make ExecuteIndirect clamping countBuffer-aware and non-destructive - #242

Open
wbkepler wants to merge 4 commits into
Marvisak:mainfrom
wbkepler:gpu/indirect-count-buffer
Open

wbkepler wants to merge 4 commits into
Marvisak:mainfrom
wbkepler:gpu/indirect-count-buffer

Conversation

@wbkepler

Copy link
Copy Markdown
Contributor

Summary

Fixes ExecuteIndirect argument clamping to respect optional countBuffer and avoid mutating shared title Shadow buffers in-place:

  • indirect.rs clamp compute shader:
    • Reads src_args (at args_offset) and optional count_buf (has_count + count_offset) via read-only ByteAddressBuffer SRVs (rebasing >4 GiB offsets safely).
    • Returns early for threads at/past min(records, count_buf.Load(count_offset)) so uninitialized tail slots never consume the per-list budget.
    • Saturates BUDGET via CAS without 32-bit unsigned wraparound, and copies full stride bytes of active records into a dedicated RWByteAddressBuffer dst_args scratch buffer at offset 0.
  • Scratch buffer management (host.rs, indirect.rs):
    • HostList::indirect_scratch and Host::uav_buffer manage a growable, reusable per-HostList DEFAULT-heap UAV scratch buffer (keeping replaced buffers alive until reset()), bracketed by COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT -> COMMON barriers while leaving Shadow buffers in COMMON.
  • draw.rs:
    • Validates pipeline readiness/kind before clamping and executes indirect draws/dispatches against the clamped scratch buffer at offset 0 while preserving the original counter buffer and offset.
  • Adds 4 unit tests in indirect.rs including live D3D12 WARP ExecuteIndirect tests (countBuffer=3 with 4,093 garbage tail slots, back-to-back calls, non-destructive source, stride=24 preservation, and 128-record BUDGET saturation without wraparound) plus HostList scratch 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 — passed
  • cargo test --workspace — passed (46/46 default, 49/49 diagnostics in victory-gpu)
  • cargo xtask policy — passed (151 files ok)

@gw1337x

gw1337x commented Nov 24, 2026

Copy link
Copy Markdown

In-game data point on an RX 7800 XT (Windows 11 26200, 31.6 GB), diag build, VICTORY_D3D12_DRED=1, one run each:

Build Device removed at Last frame Process commit
main d2a4bae + #135 + #124 + #130 ~150–155 s 1077–1191 ~24 GB
the same + this PR + #230 ~177 s 1318 ~19 GB

Both 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 DISPATCH arm of State::execute_indirect. I kept this PR's pipeline-kind check above it and used #135's bind result: DISPATCH => self.bind(list, p, true).

AntoninMichelq pushed a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 24, 2026
…-aware and non-destructive) into the integration

All guards are kept. The clamp writes into the list's scratch buffer, the
budget saturates, and its CAS loop stays bounded to 256 tries (the
branch's hang guard). A record that cannot settle runs empty. The
branch's indirect rectangle-list expansion now reads the clamped scratch
records, not the title's buffer. The null-UAV dispatch skip and the
dispatch group-limit drop are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
@Raxstreams

Copy link
Copy Markdown

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.

@r4tedx

r4tedx commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Review note (built on main d2a4bae; 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; main and #40 write through all MaxCommandCount records 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.

@artor410 artor410 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.

Review and test of head 1f7f7d2, on top of main d2a4bae. Windows 11, hardware GPU, plus a WARP run with the D3D12 debug layer and GPU-based validation.

Tests: cargo test -p victory-gpu --lib gives 47 passed, 1 ignored. Clippy's only warning is in host.rs:267, which is already on main.

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:

  1. A buffer t goes from COMMON to UNORDERED_ACCESS. The WORKER_CS writes to it, standing in for the title's argument pass.
  2. Then it runs record_clamp(src = (t, 64), count = (t, 0)), then ExecuteIndirect(..., Some(&t), 0).

The debug layer reports three errors:

  • twice, SetComputeRootShaderResourceView: state UNORDERED_ACCESS "is invalid for use as a root shader resource" (the source and the count);
  • once, 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 main when the count sits in the same buffer as the arguments, the case Raxstreams describes. main transitions 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 main too.

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 way main's bound / done do. 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:

  • The scratch buffer is one buffer per list at offset 0. Each execution therefore waits on the previous one through the INDIRECT_ARGUMENT → COMMON → UNORDERED_ACCESS transitions. That is correct but serial. A bump allocation per execution, like #282's argument_space, would let executions overlap if it shows up in profiles.
  • Merging with #282: I'll rebase #282's rectangle pass to read from your scratch copy if this lands first.

Synthetic tests only; untested against the title.

🤖 Generated with Claude Code

@wbkepler

Copy link
Copy Markdown
Contributor Author

Thanks @r4tedx, good catch. Pushed 1711205:

  • HostList::gpu_written reports whether the list already declared shader (UAV) writes to a buffer's host copy, i.e. whether implicit promotion has left it in UNORDERED_ACCESS for the rest of the submission.
  • indirect::bound transitions 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_ARGUMENT before the clamp dispatch; indirect::done moves it back after ExecuteIndirect (which also reads the count in that state), so later UAV writers in the list still find it in UNORDERED_ACCESS. Buffers the list has not written keep relying on promotion from COMMON.
  • New WARP test: a compute pass writes the arguments (and holds the count) through a UAV in the same list before the clamp, and a second writer runs after it; the clamp sees the write and both writers run.

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 and cargo xtask policy pass; I have not run it under the debug layer.

BastienRodz added a commit to BastienRodz/VIctory that referenced this pull request Nov 24, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (Marvisak#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as Marvisak#260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on Marvisak#346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ghost ghost mentioned this pull request Nov 24, 2026
@wbkepler

Copy link
Copy Markdown
Contributor Author

Thanks @artor410 and @r4tedx for the thorough review and debug-layer probe! Pushed a follow-up commit:

  1. D3D12 Debug Layer + GPU-Based Validation (GBV) verification: WarpHarness in indirect.rs now enables ID3D12Debug + ID3D12Debug1::SetEnableGPUBasedValidation(true) (with full state tracking enabled) when VICTORY_D3D12_DEBUG=1 / VICTORY_D3D12_GBV=1 are set, requires a live ID3D12InfoQueue, and asserts zero CORRUPTION or ERROR messages after every submit_and_wait().
    • Ran 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 across warp_reads_arguments_written_earlier_in_the_list (UAV producer -> clamp + ExecuteIndirect with 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), and warp_budget_saturates_without_wraparound_and_preserves_draw_fields.
  2. Per-list scratch bump allocation: HostList::indirect_scratch now bump-allocates 16-byte-aligned slices (buffer, offset) within the list's device-local scratch buffer (resetting used = 0 on HostList::reset()), record_clamp targets dst_base + dst_offset, and draw::State::execute_indirect passes bounded.offset to ExecuteIndirect. Updated host_list_reuses_and_grows_scratch_across_submissions and warp_count_buffer_ignores_garbage_tail_and_preserves_source to 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), and cargo xtask policy (151 files ok).

BastienRodz added a commit to BastienRodz/VIctory that referenced this pull request Nov 24, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (Marvisak#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as Marvisak#260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on Marvisak#346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rouges78

Copy link
Copy Markdown
Contributor

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.

records main (plain add) this PR
1,024 1.4 ms 155 ms
4,096 1.9 ms 2.09 s
16,384 2.4 ms device removed
65,536 5.8 ms not run

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.

BastienRodz added a commit to BastienRodz/VIctory that referenced this pull request Nov 24, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (Marvisak#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as Marvisak#260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on Marvisak#346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Pin0d1

Pin0d1 commented Nov 24, 2026

Copy link
Copy Markdown

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#1, along with the ordered work-budget changes.

Download the patch · Reproduction steps, tests and logs

@FunWithFlagsDev

Copy link
Copy Markdown

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:

  • Preserves the saturation policy of GPU: make ExecuteIndirect clamping countBuffer-aware and non-destructive #242.
  • Preserves count-buffer handling and non-destructive argument storage.
  • Uses saturating arithmetic throughout the local prefix scan to prevent intermediate overflow.
  • Keeps inactive lanes participating in group synchronization without accessing inactive records.
  • Uses Shader Model 5.1-style groupshared memory and group barriers, without requiring SM 6 wave intrinsics.

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.

@rouges78

Copy link
Copy Markdown
Contributor

@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 SOURCE as 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_1 with 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 early return before 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.

records plain add in this PR's shader (wraps) this PR grouped, 64 threads (3 variants) grouped, 64 threads, back-off grouped, 1,024 threads one thread, in order (one dispatch) one group, tiles in order (one dispatch)
1,024 0.07 152 to 153 0.14 to 0.30 0.20 to 0.22 (2.4 in one session) 0.12 to 0.15 0.58 0.11
16,384 0.39 device removed (earlier run) 13.5 to 15.3 10.3 0.20 to 0.22 8.3 0.46
65,536 1.3 not run 160 to 195 51 to 57 1.5 to 1.8 31 1.8
131,072 2.6 not run 474 (one variant) 97 4.3 to 4.8 57 3.0
1,048,576 24 not run not run not run 39 to 45 not run 25

What I take from it:

  1. With 64-thread groups the contention moves from records to groups, as you expected, and by about the full factor of 64: in the same session 1,024 groups (65,536 records) took 160 to 166 ms, and 1,024 records take 152 to 153 ms in this PR. At the next size up, 2,048 groups took 474 ms and 2,048 records take 640 ms in this PR.
  2. With the plain retry loop it is still not linear. From 16,384 records up each doubling cost 2.9 to 3.7 times more (one variant, one session: 13.5, 44, 163, 474 ms). If that rate held, 262,144 records would take 1.4 to 1.8 s, close to the 2 s time-out. I did not run that size, and the last step is the lowest, so the rate may be flattening.
  3. The scan does not matter where the time is: from 4,096 records up the 7-sync version is within 7% of the 2-sync ones.
  4. Two changes remove the quadratic growth in what I measured. Both are the third variant with one change each.
    • A back-off between retries, still 64-thread groups (a random number of plain reads from a window that doubles per failure; one setting): 51 to 57 ms at 65,536 and 97 ms at 131,072.
    • Groups of 1,024 threads, the cs_5_1 maximum, with a two-level prefix, 3 syncs and the same plain retry loop. It needs the dispatch count changed to records.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.
  5. The last column has no atomics: one group walks the records in tiles of 64, all lanes load and store in parallel, and lane 0 accounts for each tile in order. That is the approach of Preserve GPU-generated ExecuteIndirect arguments and apply the work budget in order Pin0d1/VIctory#1. The column is my own shader written after it, in this PR's layout and with this PR's saturation rule, as a single dispatch. I did not run theirs, which dispatches one group per window of 4,096 records and lets a smaller record still fit after a rejected one. Mine costs between 1 and 1.6 times the plain add, and by construction admits records in record order, where a grouped scheme admits whichever groups reserve first.

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, ExecuteCommandLists and 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 by main'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 single Dispatch(1, 1, 1). So none of the three is the main or walk figure of my previous comment, which timed host.execute and 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.

@FunWithFlagsDev

Copy link
Copy Markdown

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.

Ortomanic pushed a commit to Ortomanic/VIctory that referenced this pull request Nov 24, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (Marvisak#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as Marvisak#260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on Marvisak#346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6ff6c88)
suirentakamura referenced this pull request in suirentakamura/victory-suiren Nov 24, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as #260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on #346.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
wbkepler and others added 4 commits November 24, 2026 21:34
Read indirect arguments and optional countBuffer via read-only ByteAddressBuffer SRVs and write clamped active records (0..min(max, count)) into a reusable per-HostList DEFAULT-heap scratch buffer at offset 0. Prevents inactive tail slots from exhausting the per-list budget, avoids 32-bit unsigned budget wraparound, preserves full record strides, and leaves shared Shadow buffers untouched in COMMON/GENERIC_READ.
…he clamp

The ExecuteIndirect clamp reads the title's argument and count buffers in
place (root SRVs, and the count again by ExecuteIndirect) and relied on
implicit promotion from COMMON. When a compute pass earlier in the same
list wrote them through unordered access, implicit promotion has already
left the host copy in UNORDERED_ACCESS, from which a buffer cannot be
promoted to a read state.

`HostList::gpu_written` reports whether the list declared shader writes
to a buffer's host copy; `indirect::bound` transitions each such buffer
(once, as the count may live in the argument buffer) from
UNORDERED_ACCESS to NON_PIXEL_SHADER_RESOURCE | INDIRECT_ARGUMENT before
the clamp dispatch, and `indirect::done` moves it back after
ExecuteIndirect so the list's later writers still find it in
UNORDERED_ACCESS. Buffers the list has not written keep using promotion.
`bound` now returns `Bounded { scratch, .. }`.

Adds a WARP test with a UAV producer writing the arguments (and holding
the count) in the same list before the clamp, and a second writer after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@wbkepler

Copy link
Copy Markdown
Contributor Author

@rouges78, @Pin0d1, @FunWithFlagsDev: thank you for the measurements and the sizing repro. Both are addressed in the latest push.

  • Budget contention (@rouges78, @FunWithFlagsDev): the per-record global compare-exchange retry loop is gone. The clamp now runs as one serial-per-group tile walk: a single 64-thread group reads the budget once, walks the records in tiles of 64 in record order, and one lane does the budget accounting on groupshared memory. The budget is written back once at the end, so there is no cross-thread or cross-group CAS. It is also deterministic, since budget is spent in record order.
  • Tight-stride sizing (@Pin0d1): the required span is now (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 (now 6cb8fbe). Verified with clippy (-D warnings, including the diagnostics build), cargo test -p victory-gpu and 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.

@wbkepler
wbkepler force-pushed the gpu/indirect-count-buffer branch from e5ec341 to 6cb8fbe Compare November 24, 2026 20:36
@rouges78

Copy link
Copy Markdown
Contributor

@wbkepler confirmed at 6cb8fbe on the RTX 4080 where the compare-exchange loop timed out (Windows 11):

  • No time-out any more. Clamp alone through 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).
  • At 1,048,576 records with stride 64 instead of 16: 53 ms (main 21), the copy of the whole stride shows there. All but two records rejected: 27 ms (main 122). 64 calls of 256 records in one list: 0.54 ms (main 1.25).
  • cargo test --workspace --locked passes on the card (348 passed); the indirect tests also on WARP.
  • Budget: I ran the four tests of GPU: the indirect budget is charged in record order and no longer wraps #1510 (the same one-group tile walk, in place, without the count buffer) against this head through 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.
  • One check not in the PR's tests: a slice reused after reset that 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).

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

@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 at 6cb8fbe stays 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.

PastiiJay pushed a commit to PastiiJay/klbf-lab-beta that referenced this pull request Nov 25, 2026
The rewrite pass read the title's records after the clamp and relied on
the clamp having written its bounds back in place. It now applies the
same bounds itself (2^24 vertices, 2^26 vertex instances), so a clamp
that writes elsewhere (Marvisak#242) cannot bring back unbounded counts.

f32_to_half in the expand shader or-ed the rounded mantissa into the
exponent, losing a rounding carry when the exponent is odd (1.99995
became 1.0); it now adds it, as Marvisak#260 does for primitive.rs.

The module notes also say that, with vertex inputs, the vertex id is
the expanded one, from an allocated start whose order between records
may change from run to run.

Reported by marquezinii on Marvisak#346.

Copy link
Copy Markdown
Owner

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

Airamek added a commit to Airamek/VIctory that referenced this pull request Nov 26, 2026
… chunk buffer

Port of RVZO6 Marvisak#2168 onto the hoisted bound_chunk model (our always-hoist
chunk-hoist is already landed; Marvisak#2168 targets the old per-call bound() and
does not apply). Picks the small clamp PR over Marvisak#2472 (1.1k-line prelude
batch pass, no hardware A/B available) and Marvisak#242 (conflicting branch).

- bound_chunk: leading global NULL-resource UAV flush becomes targeted
  barriers on each clamp's argument copy (deduplicated) and any distinct
  count buffer; per-request trailing global barrier becomes a barrier on
  the shared budget only. Same order, same transitions.
- Zero-record requests run no dispatch and need no barriers; their slice
  is never read. execute_indirect with max == 0 skips refresh, clamp and
  execution entirely, counting the draw/dispatch.
- HostList::budget now hands out the budget buffer with its address, for
  the targeted budget barrier.
- The chunk clamps into slices of one argument buffer at increasing
  16-byte offsets (was: every request at offset 0 of the same cached
  buffer, so every execution of a multi-request chunk read the last
  clamp's records, and transitions mismatched under the debug layer).
  run_pending executes at the request's offset; done_chunk reverts once.
- Test: chunk_scopes_uav_barriers_and_zero_records (barrier scope,
  slice offsets, transition balance via replay).
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.

10 participants