diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2eb8f8f71f..a83e810b53 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2602,9 +2602,19 @@ struct CardRange { /// Looked at by `crate::picked`, and not declared: what is found changed /// there was written through a view nobody declared. Not landed. picked: bool, + /// Picked by [`lazy`]: compared and stored (mode 2), and what is found + /// tells `lazy` which pieces were written lately. + lazy: bool, } impl CardPlan { + /// [`lazy`] is told which of its pieces the compare found written. + fn lazy_found(&self, differs: &[u32]) { + for r in self.ranges.iter().filter(|r| r.lazy && r.compared) { + lazy::found(&r.shadow, &r.span, |p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d))); + } + } + /// `crate::picked` is told where what it looked at changed, by the /// compare's results. fn picked_found(&self, differs: &[u32]) { @@ -3095,6 +3105,9 @@ struct Line { /// The title memory the flights' shaders and texture readbacks may write /// (address, end), in order and joined. written: Vec<(usize, usize)>, + /// `written`, with big card copies' parts only where written lately + /// ([`lazy::narrow`]; empty when that is off): what steps wait for. + narrow: Vec<(usize, usize)>, /// Host lists in the flights. lists: usize, /// The value signalled on the host's fence behind the last flight. @@ -3123,6 +3136,7 @@ unsafe impl Send for Line {} static LINE: Mutex = Mutex::new(Line { line: Vec::new(), written: Vec::new(), + narrow: Vec::new(), lists: 0, target: 0, settling: false, @@ -3138,6 +3152,33 @@ fn line() -> std::sync::MutexGuard<'static, Line> { LINE.lock().unwrap_or_else(|e| e.into_inner()) } +impl Line { + /// What steps of a submission wait for (or are done on the card for): + /// `written`, or with [`lazy::narrow`] its narrowed form. + fn blocking(&self) -> &Vec<(usize, usize)> { + if lazy::narrow() { &self.narrow } else { &self.written } + } + + /// A flight's declared writes and texture read-backs join `written` (and + /// `narrow`). + fn joined(&mut self, back: &[Declared], textures: &[(usize, usize)]) { + join_ranges(&mut self.written, back.iter().flat_map(|(_, r)| r.iter().copied()).chain(textures.iter().copied())); + if lazy::narrow() { + let mut more: Vec<(usize, usize)> = textures.to_vec(); + for (shadow, ranges) in back { + if lazy::on(shadow) { + for &(from, to) in ranges { + lazy::hot_within(shadow, from, to, &mut more); + } + } else { + more.extend(ranges.iter().copied()); + } + } + join_ranges(&mut self.narrow, more); + } + } +} + /// Why flights were settled ([`LATE_STATS`]' places from 2 on). pub(crate) const WHY_SYNC: usize = 2; const WHY_CARD_DONE: usize = 3; @@ -3202,10 +3243,10 @@ fn flying() -> bool { fn late_blocked(runs: &[&HostList]) -> Option { let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), card_steps::copies(&line)) + (line.blocking().clone(), card_steps::copies(&line)) }; blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) } @@ -4150,6 +4191,7 @@ pub(crate) mod awake; mod card_steps; pub(crate) mod indirects; mod font; +mod lazy; mod menu; mod panel; mod place; @@ -4857,6 +4899,12 @@ impl Host { }; // The same pieces in fewer passes (`rehash_runs`). let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; + // Pending pieces keep their hashes (`lazy`). + let runs = if lazy::on(shadow) && !whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + lazy::hold_back(shadow, runs) + } else { + runs + }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { @@ -4897,10 +4945,36 @@ impl Host { } } let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let lazy_copy = twin && lazy::on(shadow); + let start = shadow.span().0 as usize; for (from, to) in spans { let Some(span) = shadow.card_span(from, to) else { continue; }; + if lazy_copy { + // Only what `lazy` picks; the rest is left pending. + for (i0, i1) in lazy::select(shadow, &span) { + let (lo, hi) = (shadow.card_piece(&span, i0).0, shadow.card_piece(&span, i1 - 1).1); + if lo >= hi { + continue; + } + let span = shadow.card_run(lo, hi); + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + lo, start + hi), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + continue; + } let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; plan.ranges.push(CardRange { shadow: shadow.clone(), @@ -4909,12 +4983,44 @@ impl Host { at, compared, picked: false, + lazy: false, }); if compared { at += span.pieces; } } } + // `lazy`: the pieces forced by a send and the sweep's next ones, of + // the copies declared or sent up here. + if lazy::min().is_some() { + let mut copies: Vec<&Arc> = Vec::new(); + for shadow in declared.iter().map(|d| &d.0).chain(plan._synced.iter()) { + if lazy::on(shadow) + && shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()) + && !copies.iter().any(|s| Arc::ptr_eq(s, shadow)) + { + copies.push(shadow); + } + } + for shadow in copies { + let start = shadow.span().0 as usize; + for span in lazy::sweep(shadow) { + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + span.from as usize, start + span.to as usize), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + } + } for (shadow, from, len) in looked { let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); if let Some(span) = shadow.card_span(*from, from + len) @@ -4928,6 +5034,7 @@ impl Host { at, compared: true, picked: true, + lazy: false, }); at += span.pieces; } @@ -4966,7 +5073,10 @@ impl Host { list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); // (What is only looked at keeps its hashes: what // changed there is the next declared range's to land.) - card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 }); + // (`lazy`'s keep what they find: a piece left out + // keeps its old hashes, one compared takes new ones.) + let mode = if r.lazy || flown && !r.picked { 2 } else { 1 }; + card_pass(list, &r.span, size as u32, r.at, mode); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; @@ -5096,6 +5206,7 @@ impl Host { let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { plan.picked_found(differs); + plan.lazy_found(differs); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -5430,6 +5541,7 @@ impl Host { let Line { line: items, written, + narrow, lists, settling, poke, @@ -5443,16 +5555,31 @@ impl Host { landing.clear(); // What is still in the air, from the flights that are. written.clear(); + narrow.clear(); *lists = 0; let mut ranges = Vec::new(); + let mut narrowed = Vec::new(); for item in items.iter() { if let Late::Run(flight) = item { *lists += flight.order.len().max(1); ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); ranges.extend(flight.texture_back_ranges.iter().copied()); + if lazy::narrow() { + narrowed.extend(flight.texture_back_ranges.iter().copied()); + for (shadow, r) in &flight.back { + if lazy::on(shadow) { + for &(from, to) in r { + lazy::hot_within(shadow, from, to, &mut narrowed); + } + } else { + narrowed.extend(r.iter().copied()); + } + } + } } } join_ranges(written, ranges); + join_ranges(narrow, narrowed); *settling = false; // The landed lists are reset, and what queues hold looked at, // by the helper thread (they take locks a waiter may hold). @@ -5490,6 +5617,7 @@ impl Host { let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); let mut total = 0u64; plan.picked_found(differs); + plan.lazy_found(differs); for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) { for p in 0..r.span.pieces { if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { @@ -5665,14 +5793,8 @@ impl Host { let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); let most = { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5721,14 +5843,8 @@ impl Host { let number = sent.number; { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5788,6 +5904,7 @@ impl Host { } line.settling = true; line.written.clear(); + line.narrow.clear(); line.lists = 0; std::mem::take(&mut line.line) }; @@ -6000,7 +6117,7 @@ impl Host { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. relay_wait(why, |line| { - blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) + blocked_by(line.blocking(), runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) }); } else { self.settle(&mut submitted, why); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 3baf286c5a..f0f966f531 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -580,7 +580,7 @@ pub(super) fn cut_for(runs: &[&HostList]) -> Option { if first + 1 == runs.len() { return None; } - let written = line().written.clone(); + let written = line().blocking().clone(); blocked_by(&written, runs, false)?; let (does, steps) = does_of(&written, runs); let mut behind = None; @@ -769,10 +769,10 @@ impl Host { } let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), copies(&line)) + (line.blocking().clone(), copies(&line)) }; blocked_by(&written, runs, false)?; let taken = if copied_read(&copies, runs) { diff --git a/crates/victory-gpu/src/host/lazy.rs b/crates/victory-gpu/src/host/lazy.rs new file mode 100644 index 0000000000..21fc6822c4 --- /dev/null +++ b/crates/victory-gpu/src/host/lazy.rs @@ -0,0 +1,313 @@ +//! Fewer compares of big copies in the card's memory (`VICTORY_LAZY_COMPARE_MB=`, +//! off by default). +//! +//! A copy whose shader writes are declared is compared on the card after +//! every submission, every declared piece. For the constants heap +//! (174 MB) that is 2.2 GB of the card's reads a frame to find about +//! 2.6 MB that shaders wrote. With this switch, of a copy at least that +//! large, a submission compares only: +//! +//! - the pieces found written lately ("hot", for `VICTORY_LAZY_HOT` +//! compares, 64 by default, after the last time one was found written); +//! - the pieces about to be sent up that were left out of a compare since +//! their last one ("forced": they are not hashed again when sent, so the +//! compare still sees what shaders wrote there before); +//! - the next `VICTORY_LAZY_SWEEP` pieces (128 by default) of those left +//! out, in turn, so a piece written for the first time is found within a +//! sweep of the copy. +//! +//! The other declared pieces are left out and marked pending; their hashes +//! stay as they were, so what shaders wrote there is found when the sweep +//! or a send reaches them. These compares store the hashes they make +//! (mode 2), so a piece the CPU sent up and nothing wrote is not found +//! again. What is found is fetched and merged as before: a merge takes only +//! the bytes that differ from the CPU's side, so a piece found that nothing +//! wrote costs a fetch and nothing else. Left out: shader bytes in a 4 KiB +//! page that the CPU sends up before the piece's compare are lost. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use crate::shadow::{CardSpan, Shadow}; + +/// The smallest copy (bytes) taken this way, if on. +pub(super) fn min() -> Option { + static MIN: OnceLock> = OnceLock::new(); + *MIN.get_or_init(|| { + let mb = std::env::var("VICTORY_LAZY_COMPARE_MB").ok()?.trim().parse::().ok().filter(|&mb| mb > 0)?; + tracing::info!( + mb, + hot = hot_life(), + sweep = sweep_len(), + "copies in the card's memory this large are compared only where written lately, before a send, and in a sweep \ + (VICTORY_LAZY_COMPARE_MB)" + ); + Some(mb << 20) + }) +} + +fn hot_life() -> u8 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_HOT").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(64)) +} + +fn sweep_len() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_SWEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128)) +} + +/// Whether what flights may write of such a copy counts, for the steps that +/// wait for flights or are done on the card in their order, as only its +/// pieces written lately (`VICTORY_LAZY_NARROW=1`, with +/// `VICTORY_LAZY_COMPARE_MB`). The skinning passes declare the whole +/// constants heap written; every constant read of it then waited or was +/// done on the card (5.5 ms a frame of planning on the submitting thread). +/// A piece written for the first time is read as the title has it until the +/// sweep finds it, as its write-back is late until then anyway. +pub(super) fn narrow() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = min().is_some() && std::env::var_os("VICTORY_LAZY_NARROW").is_some_and(|v| v == "1"); + if on { + tracing::info!("flights' writes to big card copies count only where written lately (VICTORY_LAZY_NARROW)"); + } + on + }) +} + +/// Of the title range `[from, to)` of `shadow`: the parts in pieces written +/// lately, as title ranges. +pub(super) fn hot_within(shadow: &Shadow, from: usize, to: usize, out: &mut Vec<(usize, usize)>) { + let start = shadow.span().0 as usize; + let len = shadow.span().1 as usize; + let (lo, hi) = (from.max(start) - start, to.min(start + len).saturating_sub(start)); + if lo >= hi { + return; + } + let (first, last) = (shadow.card_piece_of(lo), shadow.card_piece_of(hi - 1)); + let states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = states.as_ref().and_then(|s| s.get(&shadow.id())) else { + return; + }; + for piece in first..=last { + if state.hot.get(piece as usize).is_some_and(|&h| h > 0) { + let (a, b) = piece_offsets(shadow, piece); + let (a, b) = (a.max(lo) + start, b.min(hi) + start); + match out.last_mut() { + // (`out` may hold other ranges already, above this one: the + // callers sort and join after.) + Some(last) if last.0 <= a && last.1 >= a => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + } +} + +/// Whether `shadow` is compared this way. +pub(super) fn on(shadow: &Shadow) -> bool { + min().is_some_and(|min| shadow.span().1 >= min) +} + +#[derive(Default)] +struct State { + /// Per piece: compares left while it counts as written lately. + hot: Vec, + /// Per piece: left out of a compare since it was last compared. + pending: Vec, + /// Per piece: pending and sent up without being hashed again. + forced: Vec, + cursor: usize, +} + +impl State { + fn sized(&mut self, pieces: usize) { + if self.hot.len() < pieces { + self.hot.resize(pieces, 0); + self.pending.resize(pieces, false); + self.forced.resize(pieces, false); + } + } +} + +static STATES: Mutex>> = Mutex::new(None); + +/// Since the last line: pieces compared (hot, forced, swept), left out, found. +static STATS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +fn with(shadow: &Shadow, f: impl FnOnce(&mut State) -> R) -> R { + let pieces = pieces_of(shadow); + let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let state = states.get_or_insert_with(HashMap::new).entry(shadow.id()).or_default(); + state.sized(pieces); + f(state) +} + +/// How many pieces the copy has (piece 0 holds offset 0). +fn pieces_of(shadow: &Shadow) -> usize { + let len = shadow.span().1 as usize; + if len == 0 { 0 } else { shadow.card_piece_of(len - 1) as usize + 1 } +} + +/// The offsets of the copy's piece `piece`. +fn piece_offsets(shadow: &Shadow, piece: u32) -> (usize, usize) { + let full = shadow.card_run(0, usize::MAX); + shadow.card_piece(&full, piece - full.first) +} + +/// Contiguous runs of the sorted, unique `pieces`, as spans of the copy. +fn runs_of(shadow: &Shadow, pieces: &[u32]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < pieces.len() { + let mut j = i + 1; + while j < pieces.len() && pieces[j] == pieces[j - 1] + 1 { + j += 1; + } + let lo = piece_offsets(shadow, pieces[i]).0; + let hi = piece_offsets(shadow, pieces[j - 1]).1; + if lo < hi { + out.push(shadow.card_run(lo, hi)); + } + i = j; + } + out +} + +/// The hash passes after a send: of `runs`, the pending pieces are left +/// out (and forced into this submission's compare). +pub(super) fn hold_back(shadow: &Shadow, runs: Vec) -> Vec { + let mut kept: Vec = with(shadow, |state| { + let mut kept = Vec::new(); + for run in &runs { + for piece in run.first..run.first + run.pieces { + let p = piece as usize; + if state.pending.get(p).copied().unwrap_or(false) { + state.forced[p] = true; + } else { + kept.push(piece); + } + } + } + kept + }); + kept.sort_unstable(); + kept.dedup(); + runs_of(shadow, &kept) +} + +/// Of a declared `span` of the copy: the runs `[i0, i1)` of its pieces (by +/// index in the span) to compare now; the others are marked pending. +pub(super) fn select(shadow: &Shadow, span: &CardSpan) -> Vec<(u32, u32)> { + with(shadow, |state| { + let mut out: Vec<(u32, u32)> = Vec::new(); + let (mut now, mut left) = (0u64, 0u64); + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(&hot) = state.hot.get(p) else { + continue; + }; + if hot > 0 || state.forced[p] { + state.pending[p] = false; + state.forced[p] = false; + now += 1; + match out.last_mut() { + Some(last) if last.1 == i => last.1 = i + 1, + _ => out.push((i, i + 1)), + } + } else { + state.pending[p] = true; + left += 1; + } + } + STATS[0].fetch_add(now, Ordering::Relaxed); + STATS[3].fetch_add(left, Ordering::Relaxed); + out + }) +} + +/// After the declared spans: the copy's forced pieces still pending, and the +/// next pending pieces of the sweep, as spans to compare now. +pub(super) fn sweep(shadow: &Shadow) -> Vec { + let pieces: Vec = with(shadow, |state| { + let n = state.pending.len(); + let mut out = Vec::new(); + for p in 0..n { + if state.forced[p] { + state.forced[p] = false; + state.pending[p] = false; + out.push(p as u32); + } + } + STATS[1].fetch_add(out.len() as u64, Ordering::Relaxed); + let (mut taken, mut looked) = (0, 0); + while taken < sweep_len() && looked < n { + let p = state.cursor % n.max(1); + state.cursor = (p + 1) % n.max(1); + looked += 1; + if state.pending[p] { + state.pending[p] = false; + out.push(p as u32); + taken += 1; + } + } + STATS[2].fetch_add(taken as u64, Ordering::Relaxed); + out + }); + let mut pieces = pieces; + pieces.sort_unstable(); + pieces.dedup(); + runs_of(shadow, &pieces) +} + +/// A compared piece of the copy was found written (`flagged`) or not. +pub(super) fn found(shadow: &Shadow, span: &CardSpan, flagged: impl Fn(u32) -> bool) { + let life = hot_life(); + let mut hits = 0; + with(shadow, |state| { + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(hot) = state.hot.get_mut(p) else { + continue; + }; + if flagged(i) { + *hot = life; + hits += 1; + } else { + *hot = hot.saturating_sub(1); + } + } + }); + STATS[4].fetch_add(hits, Ordering::Relaxed); + log(); +} + +fn log() { + static LAST: Mutex> = Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.duration_since(t).as_secs() < 5) { + return; + } + let first = last.is_none(); + *last = Some(now); + if first { + return; + } + let [hot, forced, swept, left, found] = std::array::from_fn(|i| STATS[i].swap(0, Ordering::Relaxed)); + let hot_now: usize = STATES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |s| s.values().map(|s| s.hot.iter().filter(|&&h| h > 0).count()).sum()); + tracing::info!( + hot, + forced, + swept, + left, + found, + hot_now, + "lazy compares in the last 5 s (VICTORY_LAZY_COMPARE_MB): pieces compared as written lately, before a send, in the \ + sweep; left out; found written; written lately now" + ); +}