Skip to content

GPU: skip unchanged texture uploads via prelude copy recording - #230

Open
wbkepler wants to merge 2 commits into
Marvisak:mainfrom
wbkepler:gpu/skip-clean-texture-uploads
Open

wbkepler wants to merge 2 commits into
Marvisak:mainfrom
wbkepler:gpu/skip-clean-texture-uploads

Conversation

@wbkepler

Copy link
Copy Markdown

Summary

  • Decouples title-written texture CopyTextureRegion recording from command-list record time onto HostList::prelude at submission time so unchanged textures are not DMA-copied every frame.
  • texture::upload now registers (Arc<Staging>, Arc<HostTexture>) with the HostList without transitioning to COPY_DEST or baking CopyTextureRegion into the main list (preserving host_written skipping, per-list first_use dedup, and resource lifetimes).
  • Staging::refresh returns dirty: bool across both MEM_WRITE_WATCH and blake3 hash paths.
  • HostList::prelude transitions to COPY_DEST, records CopyTextureRegion, and transitions into the main list's expected first state only when refresh reports dirty contents (including first upload), skipping all GPU copies and redundant barriers on clean frames.
  • Adds 3 live D3D12 WARP unit tests in texture.rs covering initial pixel readback, zero copies on clean/reused/multi-list submissions (both hash and MEM_WRITE_WATCH paths), single re-upload on CPU modification, and host_written protection.

Verification

  • cargo clippy --workspace --all-targets — passed (zero new warnings)
  • cargo clippy -p victory --features diagnostics --all-targets — passed
  • cargo test --workspace — passed (46 passed, 1 ignored in victory-gpu)
  • cargo xtask policy — passed (151 files ok)

AntoninMichelq pushed a commit to AntoninMichelq/VIctory that referenced this pull request Nov 24, 2026
…e copy recording) into the integration

create_staging keeps the branch's staging budget: it takes the kept map
(None in the PR's tests) to evict before allocating. HostTexture's
memstat bytes field is pub(crate) so the PR's tests can build one; the
PR's second tests module is renamed read_tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
AntoninMichelq pushed a commit to AntoninMichelq/VIctory that referenced this pull request Nov 24, 2026
…nto the integration

The depth-bounds feature query moves into Host::from_device (PR Marvisak#230) so
the WARP test hosts query it too. The PR's test calls execute with
&HostList (the branch's list reuse made new_list return Arc).

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

Copy link
Copy Markdown
Contributor

Thanks @wbkepler for adding upload-count checks for unchanged, CPU-written, and host-written textures.

I tested commit 6a96adbfb8fcb001686dc251a24cda3dd34ee51c with:

cargo test --locked -p victory-gpu --lib texture -- --test-threads=1

The texture-filter run completed with 6 passed, 0 failed, 1 ignored benchmark, and 40 filtered tests. The three new cases verify:

The WARP tests return early when the software adapter is unavailable, and the harness reports that return as passed; this run does not distinguish that case from executing the assertions. The tests cover the D3D12 WARP path, not a hardware adapter or a title’s texture workload.

@andrewpozdnakov7-jpg

Copy link
Copy Markdown

I checked a related ordering case on 6a96adb for #758. Recording and closing a CopyResource list marks the destination host-written immediately. If that list is discarded, an independent list still skips the CPU texture upload. A Windows D3D12 WARP regression confirmed that the upload is queued before recording the copy and suppressed afterward, even though the copy list is never submitted.

The patch keeps the write marker on the command list and applies it while preparing submitted lists in order. The unsubmitted-copy regression passes with it. A second test submits a real GPU copy followed by a reader in one batch, checks that it emitted zero staging copies, and reads back the GPU-copied pixels. With the submission-time guard disabled, that second test fails.

The diagnostic suite can still hit the existing write-watch flake documented in #185. That test failed in 2 of 5 full runs before this patch and 1 of 5 with it, and passed in isolation on both. Library Clippy with warnings denied passed. This patch covers discarded lists. The later CPU-write case in #758 is still separate.

AI-assisted. Synthetic WARP tests only.

Tested follow-up diff for 6a96adb
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index b65fab8baaf77653a823ca9cdab57bc8d05620b5..0f27f72c2153779dc490d7be7d0c561315792ccc 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -406,6 +406,8 @@ enum Step {
     Host(Box<dyn Fn() + Send>),
     /// Shaders write a range (address, bytes) of a buffer's host copy.
     GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
+    /// A submitted copy or resolve makes this host texture authoritative.
+    TextureHostWrite(std::sync::Arc<crate::resource::HostTexture>),
     /// Brings a texture's staging buffer up to date and, when dirty, copies
     /// it into the host texture on the list's prelude: once per submission,
     /// whichever lists sample it, until a `Copy` or `Run` intervenes.
@@ -1227,6 +1229,10 @@ impl HostList {
         self.deferred().copies.push(Step::Host(Box::new(work)));
     }
 
+    pub(crate) fn defer_texture_write(&self, texture: std::sync::Arc<crate::resource::HostTexture>) {
+        self.deferred().copies.push(Step::TextureHostWrite(texture));
+    }
+
     /// Brings a texture's staging buffer up to date when the list is
     /// submitted (and copies it to `texture` on the prelude only if dirty),
     /// keeping both alive until the list is reset.
@@ -1303,8 +1309,15 @@ impl HostList {
                     shadow.writing(*address, *len);
                     continue;
                 }
+                Step::TextureHostWrite(copy) => {
+                    copy.host_written.store(true, Ordering::Relaxed);
+                    continue;
+                }
                 Step::Texture(staging, copy) => {
-                    if batch.texture_due(staging) && staging.refresh() {
+                    if !copy.host_written.load(Ordering::Relaxed)
+                        && batch.texture_due(staging)
+                        && staging.refresh()
+                    {
                         uploads.push((staging.clone(), copy.clone()));
                     }
                     continue;
diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs
index 78d6d736e282363deb6c59132a2d133d000b326e..85dd4753765f54d7cdcca23c979c8d7d878734a5 100644
--- a/crates/victory-gpu/src/list.rs
+++ b/crates/victory-gpu/src/list.rs
@@ -448,7 +448,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
         ) {
             ensure_state(list, dst, COPY_DEST);
             ensure_state(list, src, COPY_SOURCE);
-            crate::texture::host_written(dst);
+            crate::texture::defer_host_write(list, dst);
             #[cfg(feature = "diagnostics")]
             list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
             // SAFETY: an open list and live textures.
@@ -539,7 +539,7 @@ extern "system" fn copy_texture_region(
             from.resource = texture.as_raw().cast_const().cast();
         }
         ensure_state(list, dst.resource, COPY_DEST);
-        crate::texture::host_written(dst.resource);
+        crate::texture::defer_host_write(list, dst.resource);
         let mut to_location = dst;
         to_location.resource = to.as_raw().cast_const().cast();
         let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
@@ -623,7 +623,7 @@ extern "system" fn resolve(
         const RESOLVE_SOURCE: u32 = 0x2000;
         ensure_state(list, dst, RESOLVE_DEST);
         ensure_state(list, src, RESOLVE_SOURCE);
-        crate::texture::host_written(dst);
+        crate::texture::defer_host_write(list, dst);
         #[cfg(feature = "diagnostics")]
         list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
         // SAFETY: an open list and live textures; the region is inside both.
diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs
index 46c5c71abfaee7f985586417519eb243e3ad35d3..9a8402a6dc169f4fe6e11a5b581968bccbd95dbc 100644
--- a/crates/victory-gpu/src/resource.rs
+++ b/crates/victory-gpu/src/resource.rs
@@ -761,6 +761,7 @@ struct Resource {
 pub(crate) struct HostTexture {
     pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
     pub(crate) state: std::sync::atomic::AtomicU32,
+    pub(crate) host_written: std::sync::atomic::AtomicBool,
 }
 
 /// Moves the host texture to `wanted` (a host texture state); the host
@@ -941,6 +942,7 @@ fn hand_out_resource(
             std::sync::Arc::new(HostTexture {
                 texture,
                 state: state.into(),
+                host_written: false.into(),
             })
         }),
     });
@@ -1409,6 +1411,57 @@ mod tests {
         heap
     }
 
+    #[cfg(all(windows, feature = "diagnostics"))]
+    #[test]
+    #[ignore = "requires D3D12"]
+    fn recording_an_unsubmitted_copy_keeps_cpu_texture_uploads() {
+        let _host = crate::host::host().expect("D3D12 host");
+        let null = std::ptr::null();
+        let allocator_iid = crate::object::guid(
+            0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
+        );
+        let list_iid = crate::object::guid(
+            0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
+        );
+        let mut allocator = null;
+        assert_eq!(crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), S_OK);
+        let command_list = || {
+            let mut list = null;
+            assert_eq!(crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), S_OK);
+            list
+        };
+        let new_texture = || {
+            let mut resource = null;
+            let desc = ResourceDesc { layout: 1, ..texture(4, 4, 28, 1) };
+            assert_eq!(
+                create_committed(null, &PROPERTIES, 0, &desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut resource),
+                S_OK,
+            );
+            resource
+        };
+        let (src, dst) = (new_texture(), new_texture());
+        let upload_is_queued = |list| {
+            let list = crate::list::host_list(list).expect("host list");
+            crate::texture::upload(list, dst, host_resource(dst).expect("host texture"));
+            list.has_deferred_work()
+        };
+        let (control, copy, sample) = (command_list(), command_list(), command_list());
+        let before = upload_is_queued(control);
+        let copy_resource = slot::<extern "system" fn(This, This, This)>(copy, 0x88);
+        copy_resource(copy, dst, src);
+        let close = slot::<extern "system" fn(This) -> HRESULT>(copy, 0x48);
+        assert_eq!(close(copy), S_OK);
+        // The control and copy lists are never submitted. This independent
+        // list must still see the guest-backed destination as uploadable.
+        let after = upload_is_queued(sample);
+
+        for object in [sample, copy, control, dst, src, allocator] {
+            slot::<Release>(object, 0x10)(object);
+        }
+        assert!(before, "the control must queue the upload");
+        assert!(after, "an unsubmitted CopyResource suppressed the upload");
+    }
+
     #[test]
     fn heaps_are_zeroed_aligned_memory() {
         let heap = heap(1 << 20);
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
index c8c13e99abb5f14c381a0871c45cccb31db66374..6d939fb8e60a5ce9c235c4ef27964d467092ce45 100644
--- a/crates/victory-gpu/src/texture.rs
+++ b/crates/victory-gpu/src/texture.rs
@@ -64,15 +64,11 @@ unsafe impl Sync for Staging {}
 
 static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
 
-/// Textures the host GPU wrote by a copy or resolve: their contents are on
-/// the host, not in title memory, which stays as it was.
-static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
-
-/// A host copy or resolve writes `resource`.
-pub(crate) fn host_written(resource: This) {
-    let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
-    set.get_or_insert_with(Default::default)
-        .insert(resource as usize);
+/// Records a copy or resolve's write alongside the list's other deferred work.
+pub(crate) fn defer_host_write(list: &HostList, resource: This) {
+    if let Some(copy) = crate::resource::host_copy(resource) {
+        list.defer_texture_write(copy);
+    }
 }
 
 /// The title released a resource.
@@ -81,10 +77,6 @@ pub(crate) fn forget(resource: usize) {
     if let Some(map) = map.as_mut() {
         map.remove(&resource);
     }
-    let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
-    if let Some(set) = set.as_mut() {
-        set.remove(&resource);
-    }
 }
 
 /// Whether `resource`'s host copy takes its contents from title memory:
@@ -100,19 +92,14 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
 /// only when its contents changed (including first upload), copied into its
 /// host texture on the list's prelude command list.
 pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
-    let host_written = HOST_WRITTEN
-        .lock()
-        .unwrap_or_else(|e| e.into_inner())
-        .as_ref()
-        .is_some_and(|set| set.contains(&(resource as usize)));
-    // shortcut: a texture the host copied into keeps the host's contents
-    // even if the title later writes its memory too.
-    if host_written || !list.first_use(resource as usize) {
-        return;
-    }
     let Some(copy) = crate::resource::host_copy(resource) else {
         return;
     };
+    if copy.host_written.load(std::sync::atomic::Ordering::Relaxed)
+        || !list.first_use(resource as usize)
+    {
+        return;
+    }
     let Some(staging) = staging(resource, texture) else {
         return;
     };
@@ -402,6 +389,7 @@ mod tests {
         let copy = Arc::new(HostTexture {
             texture: resource.unwrap(),
             state: AtomicU32::new(D3D12_RESOURCE_STATE_COMMON.0 as u32),
+            host_written: false.into(),
         });
         (copy, layout_tex)
     }
@@ -696,19 +684,52 @@ mod tests {
     }
 
     #[test]
-    fn host_written_texture_never_queues_cpu_upload() {
+    fn submitted_texture_write_prevents_a_later_staging_copy() {
         let Some(host) = Host::new_warp() else {
             return;
         };
-        let (copy, _) = make_rgba_texture(&host, 4, 4);
-        let fake_resource = 0x1234_5678usize as This;
-        host_written(fake_resource);
-        let list = host.new_list().expect("new list");
-        upload(&list, fake_resource, &copy.texture);
-        assert!(
-            !list.has_deferred_work(),
-            "host-written textures must not queue CPU-to-GPU uploads"
-        );
-        forget(fake_resource as usize);
+        let (copy, tex) = make_rgba_texture(&host, 4, 4);
+        let layout = tex.planes[0].layout.clone();
+        let mut title_mem = vec![0u8; layout.size as usize];
+        fill_linear_rgba(&layout, &mut title_mem, [0x11, 0x22, 0x33, 0xff]);
+        let staging = create_staging(
+            &host,
+            std::ptr::null(),
+            &copy.texture,
+            layout,
+            title_mem.as_ptr(),
+        )
+        .expect("create staging");
+        let (source, source_tex) = make_rgba_texture(&host, 4, 4);
+        let source_layout = source_tex.planes[0].layout.clone();
+        let mut source_mem = vec![0u8; source_layout.size as usize];
+        let gpu_pixel = [0x44, 0x55, 0x66, 0xff];
+        fill_linear_rgba(&source_layout, &mut source_mem, gpu_pixel);
+        let source_staging = create_staging(
+            &host,
+            std::ptr::null(),
+            &source.texture,
+            source_layout,
+            source_mem.as_ptr(),
+        )
+        .expect("create source staging");
+        let writer = host.new_list().expect("writer");
+        writer.defer_texture(source_staging, source.clone());
+        writer.expect_texture_state(&source, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32);
+        writer.expect_texture_state(&copy, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32);
+        writer.defer_texture_write(copy.clone());
+        // SAFETY: compatible textures, with the source and destination
+        // states established by the prelude.
+        unsafe { writer.list.CopyResource(&copy.texture, &source.texture) };
+        writer.close();
+        let reader = host.new_list().expect("reader");
+        reader.defer_texture(staging.clone(), copy.clone());
+        reader.expect_texture_state(&copy, SHADER_RESOURCE);
+        reader.close();
+
+        host.execute(&[&writer, &reader]);
+
+        assert_eq!(staging.gpu_uploads(), 0, "the host write takes precedence");
+        assert!(all_pixels_eq(&read_back_rgba(&host, &copy, 4, 4), gpu_pixel));
     }
 }

Machad3x pushed a commit to Machad3x/VIctory that referenced this pull request Nov 24, 2026
… via prelude records

Texture uploads were baked into every command list as CopyTextureRegion even
when the staging bytes had not changed; now the copy is recorded on the
list's prelude at submission, only when Staging::refresh reports dirty. The
PR claims zero GPU copies and no redundant barriers on clean frames and ships
WARP tests for pixel readback, clean/reused/multi-list submissions and
host_written. In the Marvisak#400 A/B (one run) its frame stayed within main's noise
(715 ms vs 775-845), so the gain is on the GPU timeline, not the copies line.
Clean merge; cargo test --workspace passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Machad3x pushed a commit to Machad3x/VIctory that referenced this pull request Nov 24, 2026
…cb0222): fast texture digest, remap-epoch caching

Unwatched texture refresh (~19 submissions/frame) hashed ~156 MB/frame of
unchanged tiled bytes with blake3, retried a failing GetWriteWatch under the
global journal mutex, and re-walked VirtualQuery for each texture. Marvisak#916
reports 308-416 ms/frame there with 0 MB changed. It swaps in a 128-bit
non-cryptographic digest (160 MiB: blake3 71.4 ms -> 11.6 ms, 6.1x), caches
NOT_WATCHED, and caches commit state of MEM_MAPPED ranges until
watch::title_memory_remapped bumps REMAP_EPOCH (MEM_PRIVATE still queries; every
byte is still digested each submission, so a rewrite is never missed). Conflicts
with Marvisak#124/Marvisak#230 resolved by hand: refresh_now keeps Marvisak#230's (bytes, dirty) result,
the remap hook runs both the epoch bump and the placed-texture/loose-window
release, and the two test modules are kept. cargo test --workspace passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
PastiiJay added a commit to PastiiJay/klbf-lab that referenced this pull request Nov 24, 2026
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown

The bindless refresh composition now retains pending #413 requests through discard/reorder/reset and delegates the native upload decision to your ordered prelude. All 42 ordinary/placed cases passed AMD/NVIDIA/WARP full GBV, including preservation of a #230-marked GPU producer. Production hunk eba699d is isolated for your and the #413 author's review. The validation extends only to GPU producers this composition marks through the existing copy/resolve path.

Decouple title-written texture CopyTextureRegion recording from
command-list record time so unchanged textures are no longer DMA-copied
over PCIe on every command list every frame:

- At record time (`texture::upload`), register the texture's `Staging`
  and `Arc<HostTexture>` with the `HostList` (still skipping
  `host_written` textures and deduplicating per list) without
  transitioning to `COPY_DEST` or unconditionally recording
  `CopyTextureRegion` on the main command list.
- At submission time (`Host::execute`), `Staging::refresh()` returns
  whether title memory actually changed (including first-time upload)
  via either write-watch or blake3 hashing.
- Only when `refresh()` reports dirty contents does `HostList::prelude`
  transition the host texture to `COPY_DEST`, record `CopyTextureRegion`
  for every subresource from the staging buffer, and transition it into
  the main command list's expected initial state. Clean frames record
  zero GPU texture copies and zero redundant barriers.
- Add D3D12 WARP tests in `crates/victory-gpu/src/texture.rs` verifying
  initial upload pixel readback, zero GPU copies on unchanged subsequent
  frames (both hash-checked and `MEM_WRITE_WATCH` paths, across multiple
  and reused lists), fresh single-copy re-upload on CPU modification,
  and `host_written` protection.
@wbkepler
wbkepler force-pushed the gpu/skip-clean-texture-uploads branch from 8d81f61 to 067ece6 Compare November 24, 2026 20:42
@wbkepler

Copy link
Copy Markdown
Author

Rebased onto current main (ffe310e) as 067ece6; one trivial comment-only conflict in a host.rs test, and every texture-writing copy/resolve path (CopyResource, CopyTextureRegion, Resolve) still marks the texture host-written at submission time. Gate clean.

AI-assisted (Claude Code); checked on Windows 11 / RTX 5090.

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/host.rs, crates/victory-gpu/src/resource.rs, crates/victory-gpu/src/texture.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

PastiiJay added a commit to PastiiJay/klbf-lab that referenced this pull request Nov 25, 2026
@andrewpozdnakov7-jpg

Copy link
Copy Markdown

Independent WARP confirmation for the submission-order fix, related to #1891. I recorded a CopyResource that snapshots a 4×4 RGBA8 texture and a second list that overwrites it. I tried both recording orders and both submission orders through VIctory, then read all 16 texels of the snapshot.

Upstream 42363ab and your prelude-only parent fbec4e2 both gave 16/16 when the two orders agreed and 0/16 in each reversed case. One reversed case read the old CPU color after the submitted copy. The other read zero when the snapshot was submitted first. Your 067ece6 gave 16/16 in all four cases.

The regression is one test commit directly on 067ece6. Strict GPU Clippy and asset policy passed. The full WARP run had 57 passed, 1 failed, 1 ignored. The existing write-watch test failed with the new test both enabled and filtered out, and passed on its own. The merge with current main still conflicts in host.rs, resource.rs and texture.rs.

@Calvix2k

Copy link
Copy Markdown
Contributor

Independent confirmation of the fix on a third vendor, on your exact head 067ece6 (no rebase), Windows 10 19045, RX 7800 XT (RDNA3), driver 32.0.32029.2010.

list::tests::texture_copy_reads_follow_submission_order from @andrewpozdnakov7-jpg's 52cc201, applied verbatim to this branch, cargo test -p victory-gpu --features diagnostics --lib:

  • main 940d32f: FAILED — the two opposite record/submit orders read 0/16 pixels, matching orders 16/16.
  • this branch 067ece6: 1 passed, all four orders read 16/16; the class's other 58 tests filter out normally.

So the upload-decision-at-recording-order dependency reproduces on WARP, Blackwell, Ada and RDNA3 here, and prelude recording plus the deferred host_written mark fixes it on all four.

One thing if you rebase: on main the conflicts are real, not just context — host.rs grew the prelude/barrier paths and texture.rs's upload path changed since ffe310e, so git cherry-pick leaves 14 hunks in those two files. Happy to help work through them here, or to test a rebased branch on this GPU; the regression test above is the check I would use.

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.

6 participants