GPU: sparse copies snapshot and copy back their tiles on several threads #18

Closed
PikPakPik wants to merge 1 commit from upstream-pr/18 into main
PikPakPik commented 2026-11-25 12:03:23 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by PikPakPik on 2026-11-25T12:03:23Z.


Each world frame snapshots about 620 MB of shader-written tiles before a submission and compares them after, all on the submitting thread. The diagnostics counters (sparse writes since) show about 160 GB of ranges declared a frame for those 620 MB of distinct tiles, of which about 65 MB differ. The sampling profile (VICTORY_PROFILE) put Shadow::writing at 20 % and Shadow::copy_back at 18 % of the submitting thread's samples, most of it memmove and one lock of the tiles' map per 64 KiB.

The change is in shadow.rs only. A range inside one already declared for the submission returns at once: its tiles' snapshots are taken, as or_insert_with left them before. The views of a range's tiles are found under one lock (tiles_of). New snapshots and the copy-back of a range's tiles run through host::in_parallel, one tile per item, so no two threads touch the same memory. What is copied back and how is unchanged (merge_gpu_writes_mut, watch::writing, write_mapped).

Measured on this machine (RX 9060 XT, Ryzen 7 9700X, Series X profile, diagnostics build, standing still in the world): copying back went from about 48 to 32 ms a frame, and Shadow::writing from 20 % to 8.5 % of the submitting thread's samples. cargo test -p victory-gpu: 109 passed, 4 ignored; none of them reaches this path (sparse returns None under cfg(test)), so it was checked in the world only.

The frame rate barely moves, from about 4.1 to 4.3 fps, and that comparison is not clean: the numbers before are from 4cbe9d7 with VICTORY_SKIP_PIPELINES, those after from 71652a2 without it, where the refresh copies grew from about 10 to 30 ms a frame. The GPU's ~95 ms a frame is untouched. in_parallel still creates its threads on each call, about 3 % of the samples; a pool would save that.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:issue:6604039549 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/18). Originally posted by [PikPakPik](https://github.com/PikPakPik) on 2026-11-25T12:03:23Z. --- **Each world frame snapshots about 620 MB of shader-written tiles before a submission and compares them after, all on the submitting thread.** The diagnostics counters (`sparse writes since`) show about 160 GB of ranges declared a frame for those 620 MB of distinct tiles, of which about 65 MB differ. The sampling profile (`VICTORY_PROFILE`) put `Shadow::writing` at 20 % and `Shadow::copy_back` at 18 % of the submitting thread's samples, most of it `memmove` and one lock of the tiles' map per 64 KiB. The change is in `shadow.rs` only. A range inside one already declared for the submission returns at once: its tiles' snapshots are taken, as `or_insert_with` left them before. The views of a range's tiles are found under one lock (`tiles_of`). New snapshots and the copy-back of a range's tiles run through `host::in_parallel`, one tile per item, so no two threads touch the same memory. What is copied back and how is unchanged (`merge_gpu_writes_mut`, `watch::writing`, `write_mapped`). Measured on this machine (RX 9060 XT, Ryzen 7 9700X, Series X profile, diagnostics build, standing still in the world): copying back went from about 48 to 32 ms a frame, and `Shadow::writing` from 20 % to 8.5 % of the submitting thread's samples. `cargo test -p victory-gpu`: 109 passed, 4 ignored; none of them reaches this path (`sparse` returns `None` under `cfg(test)`), so it was checked in the world only. **The frame rate barely moves, from about 4.1 to 4.3 fps, and that comparison is not clean:** the numbers before are from `4cbe9d7` with `VICTORY_SKIP_PIPELINES`, those after from `71652a2` without it, where the refresh copies grew from about 10 to 30 ms a frame. The GPU's ~95 ms a frame is untouched. `in_parallel` still creates its threads on each call, about 3 % of the samples; a pool would save that.
Ekabusto commented 2026-11-25 12:47:35 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by Ekabusto on 2026-11-25T12:47:35Z.


Checked locally: builds, and cargo test -p victory-gpu --lib passes (109 passed, 4 ignored). As the description says, the tests do not reach this path. No conflicts with main or the other open PRs.

What I checked in the code:

  • Each work item is one tile's part of the range, so no two threads write the same view, snapshot or title bytes. The snapshot pointers stay valid because before stays locked for the whole parallel section and nothing is inserted into it meanwhile.
  • The helpers that now run on worker threads look safe there: watch::writing takes the global GUARDS mutex, and read_into/write_mapped recover from faults through the process-wide exception handler (or fall back to Read/WriteProcessMemory).
  • The covered early return in sparse_writing skips work only when an enclosing range is still pending in the same submission, so its snapshots are already taken.

One nit: clippy reports one new undocumented_unsafe_blocks warning at shadow.rs:2038. One // SAFETY: comment covers two unsafe blocks (host and old); the second needs its own.

Reviewed on Windows 11 (build 26300), Rust 1.98.1, each PR in its own worktree; no game data, not run in the game. AI-assisted (Claude Code).

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7162863858 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/18#issuecomment-7162863858). Originally posted by [Ekabusto](https://github.com/Ekabusto) on 2026-11-25T12:47:35Z. --- Checked locally: builds, and `cargo test -p victory-gpu --lib` passes (109 passed, 4 ignored). As the description says, the tests do not reach this path. No conflicts with `main` or the other open PRs. What I checked in the code: - Each work item is one tile's part of the range, so no two threads write the same view, snapshot or title bytes. The snapshot pointers stay valid because `before` stays locked for the whole parallel section and nothing is inserted into it meanwhile. - The helpers that now run on worker threads look safe there: `watch::writing` takes the global `GUARDS` mutex, and `read_into`/`write_mapped` recover from faults through the process-wide exception handler (or fall back to `Read/WriteProcessMemory`). - The `covered` early return in `sparse_writing` skips work only when an enclosing range is still pending in the same submission, so its snapshots are already taken. One nit: clippy reports one new `undocumented_unsafe_blocks` warning at `shadow.rs:2038`. One `// SAFETY:` comment covers two `unsafe` blocks (`host` and `old`); the second needs its own. Reviewed on Windows 11 (build 26300), Rust 1.98.1, each PR in its own worktree; no game data, not run in the game. AI-assisted (Claude Code).
gut0to commented 2026-11-25 15:09:37 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-25T15:09:37Z.

Review: COMMENTED


AI-assisted review: I checked the test gating and the new parallel copy-back path.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review:6060195276 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/18#pullrequestreview-6060195276). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-25T15:09:37Z. **Review:** COMMENTED --- AI-assisted review: I checked the test gating and the new parallel copy-back path.
gut0to commented 2026-11-25 15:09:37 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-25T15:09:37Z.

Code review location: crates/victory-gpu/src/shadow.rs; line 2007

@@ -1931,74 +1935,139 @@ impl Shadow {
         None
     }
 
-    /// [`Shadow::writing`] of a sparse copy.
+    /// The CPU's views of each tile's part of `[from, to)`: its title
+    /// address, the view, its length. Tiles already mapped are found under
+    /// one lock (the world declares ~160 GB of ranges a frame: one lock per
+    /// 64 KiB tile was a tenth of the submitting thread's time).
+    fn tiles_of(&self, s: &Sparse, from: usize, to: usize) -> Vec<(usize, usize, usize)> {
+        let start = self.start as usize;
+        let mut views = Vec::with_capacity((to - from).div_ceil(PAGE) + 1);
+        let mut missing = Vec::new();
+        {
+            let mut tiles = s.tiles.lock().unwrap_or_else(|e| e.into_inner());
+            let frame = crate::queue::presented();
+            let mut at = from;
+            while at < to {
+                let n = (PAGE - at % PAGE).min(to - at);
+                match tiles.get_mut(&(((at - start) / PAGE) as u32)) {
+                    Some(t) => {
+                        t.used = frame;
+                        views.push((at, t.data + at % PAGE, n));
+                    }
+                    None => missing.push((at, n)),
+                }
+                at += n;
+            }
+        }
+        for (at, n) in missing {
+            if let Some(data) = self.tile(s, at) {
+                views.push((at, data + at % PAGE, n));
+            }
+        }
+        views
+    }
+
+    /// [`Shadow::writing`] of a sparse copy. A range inside one already
+    /// declared for this submission has its tiles' snapshots taken; new
+    /// snapshots are copied on several threads (hundreds of MB a frame).
     fn sparse_writing(&self, s: &Sparse, address: usize, len: usize) {
-        self.pending
-            .lock()
-            .unwrap_or_else(|e| e.into_inner())
-            .push((address, address + len));
+        let end = address + len;
+        let covered = {
+            let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
+            let covered = pending.iter().any(|&(a, b)| a <= address && end <= b);
+            pending.push((address, end));
+            covered
+        };
+        #[cfg(feature = "diagnostics")]
+        SPARSE_WRITES[0].fetch_add(len as u64, Ordering::Relaxed);
+        if covered {
+            return;
+        }
+        let views = self.tiles_of(s, address, end);
         let mut before = s.before.lock().unwrap_or_else(|e| e.into_inner());
         let start = self.start as usize;
+        // (tile, the start of its view) of tiles without a snapshot yet.
+        let new: Vec<(u32, usize)> = views
+            .iter()
+            .map(|&(at, data, _)| (((at - start) / PAGE) as u32, data & !(PAGE - 1)))
+            .filter(|(tile, _)| !before.contains_key(tile))
+            .collect();
+        if new.is_empty() {
+            return;
+        }
         #[cfg(feature = "diagnostics")]
-        SPARSE_WRITES[0].fetch_add(len as u64, Ordering::Relaxed);
-        self.each_tile(s, address, address + len, |at, data, _| {
-            let tile = ((at - start) / PAGE) as u32;
-            before.entry(tile).or_insert_with(|| {
-                #[cfg(feature = "diagnostics")]
-                SPARSE_WRITES[1].fetch_add(PAGE as u64, Ordering::Relaxed);
-                let whole = data as usize & !(PAGE - 1);
-                let mut buf = pooled_tile();
-                // SAFETY: the tile's mapping.
-                buf.extend_from_slice(unsafe { std::slice::from_raw_parts(whole as *const u8, PAGE) });
-                buf
-            });
+        SPARSE_WRITES[1].fetch_add((new.len() * PAGE) as u64, Ordering::Relaxed);
+        let mut bufs = pooled_tiles(new.len());
+        let copies: Vec<(usize, usize)> =
+            new.iter().zip(&mut bufs).map(|(&(_, view), buf)| (view, buf.as_mut_ptr() as usize)).collect();
+        crate::host::in_parallel(&copies, 16, |chunk| {
+            for &(view, buf) in chunk {
+                // SAFETY: the tile's mapping; a buffer with room for a tile,
+                // each written by one thread.
+                unsafe { std::ptr::copy_nonoverlapping(view as *const u8, buf as *mut u8, PAGE) };

Could this snapshot/copy-back path get a small deterministic regression test? The current test configuration never reaches sparse shadows (as the PR notes), while this change adds parallel raw tile copies and pooled-buffer length updates. A test with multiple tiles, including one unchanged tile and one GPU-modified range, could check that only the modified bytes are copied back and no tile is lost or duplicated. AI-assisted review.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review-comment:4696906547 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/18#discussion_r4696906547). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-25T15:09:37Z. **Code review location:** `crates/victory-gpu/src/shadow.rs`; line 2007 ~~~~diff @@ -1931,74 +1935,139 @@ impl Shadow { None } - /// [`Shadow::writing`] of a sparse copy. + /// The CPU's views of each tile's part of `[from, to)`: its title + /// address, the view, its length. Tiles already mapped are found under + /// one lock (the world declares ~160 GB of ranges a frame: one lock per + /// 64 KiB tile was a tenth of the submitting thread's time). + fn tiles_of(&self, s: &Sparse, from: usize, to: usize) -> Vec<(usize, usize, usize)> { + let start = self.start as usize; + let mut views = Vec::with_capacity((to - from).div_ceil(PAGE) + 1); + let mut missing = Vec::new(); + { + let mut tiles = s.tiles.lock().unwrap_or_else(|e| e.into_inner()); + let frame = crate::queue::presented(); + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + match tiles.get_mut(&(((at - start) / PAGE) as u32)) { + Some(t) => { + t.used = frame; + views.push((at, t.data + at % PAGE, n)); + } + None => missing.push((at, n)), + } + at += n; + } + } + for (at, n) in missing { + if let Some(data) = self.tile(s, at) { + views.push((at, data + at % PAGE, n)); + } + } + views + } + + /// [`Shadow::writing`] of a sparse copy. A range inside one already + /// declared for this submission has its tiles' snapshots taken; new + /// snapshots are copied on several threads (hundreds of MB a frame). fn sparse_writing(&self, s: &Sparse, address: usize, len: usize) { - self.pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push((address, address + len)); + let end = address + len; + let covered = { + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + let covered = pending.iter().any(|&(a, b)| a <= address && end <= b); + pending.push((address, end)); + covered + }; + #[cfg(feature = "diagnostics")] + SPARSE_WRITES[0].fetch_add(len as u64, Ordering::Relaxed); + if covered { + return; + } + let views = self.tiles_of(s, address, end); let mut before = s.before.lock().unwrap_or_else(|e| e.into_inner()); let start = self.start as usize; + // (tile, the start of its view) of tiles without a snapshot yet. + let new: Vec<(u32, usize)> = views + .iter() + .map(|&(at, data, _)| (((at - start) / PAGE) as u32, data & !(PAGE - 1))) + .filter(|(tile, _)| !before.contains_key(tile)) + .collect(); + if new.is_empty() { + return; + } #[cfg(feature = "diagnostics")] - SPARSE_WRITES[0].fetch_add(len as u64, Ordering::Relaxed); - self.each_tile(s, address, address + len, |at, data, _| { - let tile = ((at - start) / PAGE) as u32; - before.entry(tile).or_insert_with(|| { - #[cfg(feature = "diagnostics")] - SPARSE_WRITES[1].fetch_add(PAGE as u64, Ordering::Relaxed); - let whole = data as usize & !(PAGE - 1); - let mut buf = pooled_tile(); - // SAFETY: the tile's mapping. - buf.extend_from_slice(unsafe { std::slice::from_raw_parts(whole as *const u8, PAGE) }); - buf - }); + SPARSE_WRITES[1].fetch_add((new.len() * PAGE) as u64, Ordering::Relaxed); + let mut bufs = pooled_tiles(new.len()); + let copies: Vec<(usize, usize)> = + new.iter().zip(&mut bufs).map(|(&(_, view), buf)| (view, buf.as_mut_ptr() as usize)).collect(); + crate::host::in_parallel(&copies, 16, |chunk| { + for &(view, buf) in chunk { + // SAFETY: the tile's mapping; a buffer with room for a tile, + // each written by one thread. + unsafe { std::ptr::copy_nonoverlapping(view as *const u8, buf as *mut u8, PAGE) }; ~~~~ --- Could this snapshot/copy-back path get a small deterministic regression test? The current test configuration never reaches sparse shadows (as the PR notes), while this change adds parallel raw tile copies and pooled-buffer length updates. A test with multiple tiles, including one unchanged tile and one GPU-modified range, could check that only the modified bytes are copied back and no tile is lost or duplicated. AI-assisted review.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Belobug/VIctory-Belobug-AMD!18
No description provided.