From 512c3794f81f6582d30afeb27bc05eaf60fe9479 Mon Sep 17 00:00:00 2001 From: Michael McCrimmons Date: Thu, 26 Nov 2026 15:02:23 -0600 Subject: [PATCH 1/2] test(gpu): measure growing write declarations on one mapped shadow --- crates/victory-gpu/src/shadow.rs | 2 + .../victory-gpu/src/shadow/snapshot_bench.rs | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 crates/victory-gpu/src/shadow/snapshot_bench.rs diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ca502923..bf9580a3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2205,6 +2205,8 @@ pub(crate) fn near(va: u64) -> String { #[cfg(test)] mod parallel_copy_tests; +#[cfg(test)] +mod snapshot_bench; #[cfg(test)] pub(crate) mod tests { diff --git a/crates/victory-gpu/src/shadow/snapshot_bench.rs b/crates/victory-gpu/src/shadow/snapshot_bench.rs new file mode 100644 index 00000000..e97abd5b --- /dev/null +++ b/crates/victory-gpu/src/shadow/snapshot_bench.rs @@ -0,0 +1,56 @@ +//! Capture time for repeated declarations on one 64 MiB shadow. Run this +//! test alone, in release, with `--ignored --nocapture --test-threads=1`. + +use super::{find, register, unregister}; +use crate::watch::{PAGE, tests}; +use std::time::Instant; + +#[test] +#[ignore = "times snapshot preparation on a mapped D3D12 buffer"] +fn growing_write_ranges() { + const MIB: usize = 1 << 20; + const SIZE: usize = 64 * MIB; + let p = tests::pool(SIZE / PAGE); + register(p, p as u64, SIZE as u64); + let copy = find(p as u64, SIZE as u64).expect("host buffer"); + assert!(!copy.aliased, "this measures snapshots, not zero-copy"); + // Gives the host mapping known bytes and pays first-touch costs before timing. + copy.update(p, SIZE); + + let growing: Vec<_> = (0..=16) + .map(|i| ((16 - i) * MIB, (32 + 2 * i) * MIB)) + .collect(); + let disjoint = [(0, 16 * MIB), (32 * MIB, 16 * MIB)]; + for (name, ranges) in [ + ("one", &[(0, SIZE)][..]), + ("growing", growing.as_slice()), + ("disjoint", &disjoint[..]), + ] { + let mut times = Vec::new(); + for round in 0..11 { + let start = Instant::now(); + for &(offset, bytes) in ranges { + copy.writing(p + offset, bytes, false); + } + let elapsed = start.elapsed(); + // Copy-back and returning buffers to the pool are outside the timer. + // A changed byte must reach title memory on each iteration. + let at = p + ranges[0].0 + 5; + let value = round + 1; + copy.write_host(at as u64, &[value]); + for &(offset, bytes) in ranges { + copy.copy_back(p + offset, bytes); + } + // SAFETY: the test owns this pool; copy-back has returned. + assert_eq!(unsafe { (at as *const u8).read_volatile() }, value); + if round >= 2 { + times.push(elapsed.as_micros()); + } + } + times.sort_unstable(); + eprintln!("{name}: median {} us (9 warm captures)", times[4]); + } + unregister(p, p as u64); + drop(copy); + tests::free(p); +} From 885d997f265ee739b915aa72632dc5b0c47f9607 Mon Sep 17 00:00:00 2001 From: Michael McCrimmons Date: Thu, 26 Nov 2026 15:07:30 -0600 Subject: [PATCH 2/2] perf(gpu): append only newly covered bytes to write snapshots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port Yumaste’s Marvisak/VIctory#3211 (d5128bce, ebd01cdd) to the Mac tree. Keep the port’s recent-buffer pool, widened views and untracked refresh path. Count moves on growth as snapshot traffic. A 64 MiB growing-range capture on M5 Pro falls from 18.686 to 1.530 ms with the same copy-back result. Co-authored-by: Yumaste --- crates/victory-gpu/src/shadow.rs | 101 ++++----- crates/victory-gpu/src/shadow/snapshot.rs | 241 ++++++++++++++++++++++ 2 files changed, 280 insertions(+), 62 deletions(-) create mode 100644 crates/victory-gpu/src/shadow/snapshot.rs diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index bf9580a3..995300e3 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -25,6 +25,9 @@ use windows::Win32::Graphics::Direct3D12::ID3D12Resource; use crate::host::{HostList, host}; use crate::watch::PAGE; +mod snapshot; +use snapshot::Snapshot; + fn merge_writeback(title: &mut [u8], host: &mut [u8], old: &[u8]) -> bool { let mut changed = 0; for ((title_byte, host_byte), old_byte) in title.iter_mut().zip(host).zip(old) { @@ -79,8 +82,7 @@ pub(crate) struct Shadow { /// title memory there is older than the copy. pending: Mutex>, /// The copy's bytes before the submission ran where its shaders write: - /// what the GPU wrote differs. Disjoint segments (offset, bytes) in - /// order, and the 64 KiB pieces (by title address) already compared. + /// what the GPU wrote differs. Overlapping declarations share their captured bytes. before: Mutex, /// Its first bit in the buffer views' written-pages bitmap, one per /// 64 KiB title page it touches (tracked memory only): writes through @@ -219,16 +221,14 @@ impl Widened { } } -/// Snapshot segments (offset, bytes) and the pieces compared. -type Snapshot = (Vec<(usize, Vec)>, std::collections::HashSet); - /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex = Mutex::new(crate::recent::Pool::new()); -/// An empty buffer with room for `n` bytes, from the pool if it has one. -fn pooled(n: usize) -> Vec { - let taken = POOL.lock().unwrap_or_else(|e| e.into_inner()).take(n); - taken.unwrap_or_else(|| Vec::with_capacity(n)) +/// Prefer a warm buffer that leaves room to grow, then any that fits. The +/// pool is already sorted by capacity, and holds only emptied snapshots. +fn pooled(required: usize, preferred: usize) -> Option> { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.take(preferred).or_else(|| pool.take(required)) } /// Returns a snapshot buffer to the pool, which keeps the largest up to @@ -609,39 +609,19 @@ impl Shadow { if from >= to { return; } - // SAFETY: inside the mapping. - let host = - |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let segments = &mut before.0; - // The segments the range overlaps or touches. - let first = segments.partition_point(|(at, bytes)| at + bytes.len() < from); - let last = first + segments[first..].iter().take_while(|(at, _)| *at <= to).count(); - if let [(at, bytes)] = &segments[first..last] - && *at <= from - && to <= at + bytes.len() - { - return; - } - let start = segments.get(first).filter(|_| first < last).map_or(from, |s| s.0.min(from)); - let end = segments[first..last].last().map_or(to, |(at, bytes)| (at + bytes.len()).max(to)); #[cfg(feature = "diagnostics")] let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::SnapshotUs); + // SAFETY: inside the mapping. + let host = unsafe { std::slice::from_raw_parts(self.data.add(from), to - from) }; + let copied = before.capture(from, host); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::SnapshotBytes, (end - start) as u64); - #[cfg(feature = "diagnostics")] - crate::copystat::snapshot(self.start, self.len, (end - start) as u64); - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - let mut at = start; - for (taken, bytes) in segments.drain(first..last) { - grown.extend_from_slice(host(at, taken)); - grown.extend_from_slice(&bytes); - at = taken + bytes.len(); - give_back(bytes); + if copied != 0 { + crate::copystat::add(crate::copystat::C::SnapshotBytes, copied as u64); + crate::copystat::snapshot(self.start, self.len, copied as u64); } - grown.extend_from_slice(host(at, end)); - segments.insert(first, (start, grown)); + #[cfg(not(feature = "diagnostics"))] + let _ = copied; } /// `[address, address + len)` expanded outward to 64 KiB page @@ -694,21 +674,17 @@ impl Shadow { } let _source = self.widened_source.lock().unwrap_or_else(|e| e.into_inner()); let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let (segments, compared) = &mut *snapshot; let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; - if let Some((taken, before)) = segments.iter().find(|(at, bytes)| *at <= from && to <= at + bytes.len()) - && back - && from < to - { - let before = &before[from - taken..to - taken]; + if back && from < to && snapshot.covers(from, to) { #[cfg(feature = "diagnostics")] let _timed = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::CompareUs); // By 64 KiB piece: the copy compared with its bytes before the // submission, title memory read only where the GPU wrote. const PIECE: usize = 64 << 10; let mut title = vec![0u8; PIECE]; + let mut scratch = Vec::new(); let mut synced = Vec::new(); let mut at = from; while at < to { @@ -716,18 +692,19 @@ impl Shadow { // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; let title = &mut title[..n]; // A whole piece is compared once per submission, whichever // declared ranges overlap it: then what the GPU wrote there // went back. - if n == PIECE && !compared.insert(start + at) { + if n == PIECE && !snapshot.compared.insert(start + at) { at += n; continue; } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::CompareBytes, n as u64); - if host != old && crate::host::read_into((start + at) as *const u8, title) { + if let Some(old) = snapshot.changed_piece(at, host, &mut scratch) + && crate::host::read_into((start + at) as *const u8, title) + { // Title memory with the GPU's bytes put in; the copy // takes the title's bytes in turn. if merge_writeback(title, host, old) { @@ -761,10 +738,7 @@ impl Shadow { let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); pending.remove(&(address, address + len)); if pending.is_empty() { - compared.clear(); - for (_, bytes) in segments.drain(..) { - give_back(bytes); - } + snapshot.clear(); if let Some(t) = &self.tracked { t.disarm(); } @@ -1045,14 +1019,9 @@ impl Shadow { fn sync_snapshot_in(&self, before: &mut Snapshot, a: usize, b: usize) { let start = self.start as usize; let (a, b) = (a - start, b - start); - for (at, bytes) in before.0.iter_mut() { - let (s, e) = ((*at).max(a), (*at + bytes.len()).min(b)); - if s < e { - // SAFETY: inside the mapping. - let host = unsafe { std::slice::from_raw_parts(self.data.add(s), e - s) }; - bytes[s - *at..e - *at].copy_from_slice(host); - } - } + // SAFETY: the caller refreshed these bytes inside the mapped shadow. + let host = unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; + before.refresh(a, host); } /// [`Shadow::update`] of untracked `[from, to)` (inside the buffer). @@ -2310,17 +2279,23 @@ pub(crate) mod tests { let title = |at: usize| (p + at) as *mut u8; let host = |at: usize| copy.read_host((p + at) as u64 & !3, 1)[0].to_le_bytes()[at % 4]; copy.update(p, len); + // The refresh below crosses an earlier snapshot fragment. Both busy + // declarations must use the refreshed bytes as their baseline. + copy.writing(p + PAGE + 18, 4, false); copy.writing(p, len, false); // SAFETY: (all title reads and writes below) bytes of our allocation. unsafe { title(PAGE + 20).write_volatile(0x55) }; assert_eq!(copy.update(p + PAGE + 16, 16), 16, "the busy range is copied"); assert_eq!(host(PAGE + 20), 0x55, "the title's constant reaches the copy"); copy.write_host((p + 10) as u64, &[0xaa]); + // SAFETY: our allocation; the CPU writes again after the refresh. + unsafe { title(PAGE + 20).write_volatile(0x66) }; assert_eq!(copy.copy_back(p, len), PAGE, "the shader's page goes back"); + assert_eq!(copy.copy_back(p + PAGE + 18, 4), 0, "no GPU write here"); // SAFETY: bytes of our allocation. unsafe { assert_eq!(title(10).read_volatile(), 0xaa, "the shader's write goes back"); - assert_eq!(title(PAGE + 20).read_volatile(), 0x55, "the constant is not undone"); + assert_eq!(title(PAGE + 20).read_volatile(), 0x66, "the later title write stays"); } drop(copy); unregister(p, p as u64); @@ -2516,20 +2491,22 @@ pub(crate) mod tests { return; // no host GPU here }; copy.update(p, len); - let bytes = |s: &Shadow| s.before.lock().unwrap().0.iter().map(|(_, b)| b.len()).sum::(); + let bytes = |s: &Shadow| s.before.lock().unwrap().len(); copy.writing(p + 16, 64, false); copy.writing(p + 3 * PAGE, 100, false); assert_eq!(bytes(©), 164, "two segments"); + copy.writing(p + PAGE + 4, 4, false); copy.writing(p + PAGE, 2 * PAGE, false); copy.writing(p + PAGE, PAGE, false); copy.writing(p + 80, 8, false); - assert_eq!(bytes(©), 72 + 2 * PAGE + 100, "merged where they overlap or touch"); + assert_eq!(bytes(©), 72 + 2 * PAGE + 100, "no bytes captured twice"); // The GPU writes inside two ranges. copy.write_host((p + 20) as u64, &[1, 2, 3]); copy.write_host((p + PAGE + 5) as u64, &[9]); assert_eq!(copy.copy_back(p + 16, 64), 64, "the range's part of the piece"); assert_eq!(copy.copy_back(p + PAGE, 2 * PAGE), PAGE, "the piece written"); assert_eq!(copy.copy_back(p + PAGE, PAGE), 0, "compared once"); + assert_eq!(copy.copy_back(p + PAGE + 4, 4), 0, "the copied bytes agree"); assert_eq!(copy.copy_back(p + 3 * PAGE, 100), 0); assert_eq!(copy.copy_back(p + 80, 8), 0); // SAFETY: our pool. @@ -2873,7 +2850,7 @@ pub(crate) mod tests { assert_eq!(copy.mark_entry(p as u64 + PAGE as u64 + 8), Some((base as u32 + 1, 8))); copy.update(p, len); copy.writing(p, len, true); - assert!(copy.before.lock().unwrap().0.is_empty(), "no snapshot"); + assert_eq!(copy.before.lock().unwrap().len(), 0, "no snapshot"); // The shaders write a byte in each page; the title writes pages 1 // and 2 meanwhile. copy.write_host((p + 10) as u64, &[0xaa]); diff --git a/crates/victory-gpu/src/shadow/snapshot.rs b/crates/victory-gpu/src/shadow/snapshot.rs new file mode 100644 index 00000000..e44a65ec --- /dev/null +++ b/crates/victory-gpu/src/shadow/snapshot.rs @@ -0,0 +1,241 @@ +//! Save only the bytes newly covered by each declared GPU write. +//! Spans keep their title-address order; the backing bytes stay in capture order. + +use super::{give_back, pooled}; + +#[derive(Default)] +pub(super) struct Snapshot { + bytes: Vec, + /// The last captured size guides the first pool checkout next submission. + last_size: usize, + /// Disjoint spans in address order, pointing into the capture buffer. + spans: Vec, + /// The 64 KiB pieces already compared, by title address. + pub(super) compared: std::collections::HashSet, +} + +struct SnapshotSpan { + start: usize, + end: usize, + offset: usize, +} + +impl Snapshot { + #[cfg(test)] + pub(super) fn len(&self) -> usize { + self.bytes.len() + } + + /// Keep newly covered bytes, without rebuilding the previously captured ranges. + /// Return the bytes copied, including moving saved bytes when the backing buffer + /// grows: the Mac snapshot diagnostics measure that traffic too. + pub(super) fn capture(&mut self, start: usize, host: &[u8]) -> usize { + let end = start + host.len(); + let before = self.bytes.len(); + let mut at = start; + let mut i = self.spans.partition_point(|span| span.end <= at); + let mut moved = 0; + if host.len() > self.bytes.capacity() - before { + let covered: usize = self.spans[i..] + .iter() + .take_while(|span| span.start < end) + .map(|span| span.end.min(end) - span.start.max(start)) + .sum(); + moved = self.reserve(before + (host.len() - covered)); + } + while at < end { + if let Some(span) = self.spans.get(i) + && span.start <= at + { + at = span.end; + i += 1; + continue; + } + let next = self.spans.get(i).map_or(end, |span| end.min(span.start)); + let offset = self.bytes.len(); + self.bytes + .extend_from_slice(&host[at - start..next - start]); + // Consecutive captures in address order can still use one span. + if let Some(previous) = i.checked_sub(1).and_then(|j| self.spans.get_mut(j)) + && previous.end == at + && previous.offset + (previous.end - previous.start) == offset + { + previous.end = next; + } else { + self.spans.insert( + i, + SnapshotSpan { + start: at, + end: next, + offset, + }, + ); + i += 1; + } + at = next; + } + self.bytes.len() - before + moved + } + + fn reserve(&mut self, required: usize) -> usize { + let capacity = self.bytes.capacity(); + if required <= capacity { + return 0; + } + // Grow by enough to amortize copying, but use a smaller warm + // buffer if it can hold the new snapshot. + let growth = required.max(capacity.saturating_mul(2)); + let preferred = if capacity == 0 { + growth.max(self.last_size) + } else { + growth + }; + let mut grown = pooled(required, preferred).unwrap_or_else(|| Vec::with_capacity(growth)); + grown.extend_from_slice(&self.bytes); + let old = std::mem::replace(&mut self.bytes, grown); + let moved = old.len(); + if capacity != 0 { + give_back(old); + } + moved + } + + pub(super) fn covers(&self, start: usize, end: usize) -> bool { + let mut at = start; + for span in &self.spans[self.spans.partition_point(|span| span.end <= start)..] { + if span.start > at { + break; + } + at = span.end; + if at >= end { + return true; + } + } + false + } + + /// The original bytes of a changed piece inside a range checked by + /// `covers`. Assemble fragmented bytes only if they differ from the host. + pub(super) fn changed_piece<'a>( + &'a self, + start: usize, + host: &[u8], + scratch: &'a mut Vec, + ) -> Option<&'a [u8]> { + let end = start + host.len(); + debug_assert!(self.covers(start, end)); + let first = self.spans.partition_point(|span| span.end <= start); + let span = &self.spans[first]; + if end <= span.end { + let offset = span.offset + (start - span.start); + let old = &self.bytes[offset..offset + host.len()]; + return (host != old).then_some(old); + } + let fragments = || { + self.spans[first..] + .iter() + .take_while(|span| span.start < end) + .map(|span| { + let from = span.start.max(start); + let to = span.end.min(end); + let offset = span.offset + (from - span.start); + ( + &self.bytes[offset..offset + to - from], + from - start..to - start, + ) + }) + }; + if fragments().all(|(old, range)| old == &host[range]) { + return None; + } + scratch.clear(); + for (old, _) in fragments() { + scratch.extend_from_slice(old); + } + Some(scratch) + } + + /// A refresh before the GPU runs changes the baseline for the captured bytes. + pub(super) fn refresh(&mut self, start: usize, host: &[u8]) { + let end = start + host.len(); + let first = self.spans.partition_point(|span| span.end <= start); + for span in self.spans[first..] + .iter() + .take_while(|span| span.start < end) + { + let from = span.start.max(start); + let to = span.end.min(end); + let offset = span.offset + (from - span.start); + self.bytes[offset..offset + to - from].copy_from_slice(&host[from - start..to - start]); + } + } + + pub(super) fn clear(&mut self) { + self.compared.clear(); + self.spans.clear(); + if !self.bytes.is_empty() { + self.last_size = self.bytes.len(); + give_back(std::mem::take(&mut self.bytes)); + } + } +} + +#[cfg(test)] +mod tests { + use super::Snapshot; + + #[test] + fn overlapping_snapshots_keep_old_bytes_until_a_refresh() { + let mut snapshot = Snapshot { + bytes: Vec::with_capacity(7), + ..Snapshot::default() + }; + let mut scratch = Vec::new(); + assert_eq!(snapshot.capture(4, &[14, 15]), 2); + let data = snapshot.bytes.as_ptr(); + assert_eq!(snapshot.capture(4, &[0, 0]), 0); + assert_eq!( + snapshot.bytes.as_ptr(), + data, + "covered bytes need no growth" + ); + assert_eq!(snapshot.capture(0, &[10, 11]), 2); + assert!(!snapshot.covers(0, 6), "there is a gap"); + assert_eq!(snapshot.capture(1, &[21, 12, 13, 24, 25, 16]), 3); + assert_eq!(snapshot.capture(0, &[0; 7]), 0); + assert!(snapshot.covers(0, 7)); + assert!(!snapshot.covers(0, 8)); + let original = [10, 11, 12, 13, 14, 15, 16]; + assert!(snapshot.changed_piece(0, &original, &mut scratch).is_none()); + assert!(scratch.is_empty()); + assert_eq!( + snapshot.changed_piece(0, &[0; 7], &mut scratch).unwrap(), + original + ); + snapshot.refresh(1, &[21, 22, 23, 24, 25]); + assert_eq!( + snapshot.changed_piece(0, &[0; 7], &mut scratch).unwrap(), + [10, 21, 22, 23, 24, 25, 16] + ); + assert_eq!(snapshot.changed_piece(5, &[0], &mut scratch).unwrap(), [25]); + snapshot.clear(); + assert!(!snapshot.covers(0, 1)); + } + + #[test] + fn snapshot_traffic_counts_moving_the_saved_bytes_only_on_growth() { + let mut snapshot = Snapshot { + bytes: Vec::with_capacity(2), + ..Snapshot::default() + }; + assert_eq!(snapshot.capture(0, &[1, 2]), 2); + assert_eq!(snapshot.capture(1, &[9, 3, 4]), 4, "two new plus two moved"); + assert_eq!(snapshot.capture(0, &[9; 4]), 0); + let mut scratch = Vec::new(); + assert!( + snapshot + .changed_piece(0, &[1, 2, 3, 4], &mut scratch) + .is_none() + ); + } +}