Title bytes under flights' writes compared with AVX2 on threads of their own, the pairs sent up made on them; helpers that work ahead are not kept on the fast cores

VICTORY_UNDER_WIDE=0, VICTORY_UNDER_THREADS (6), VICTORY_FAST_CORES=3 (as before: all of them), VICTORY_WIDE_SPIN=<us> (0: off).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 14:23:12 -06:00
1 parent fa4f6c33e6
commit a69eb0cacb
6 files changed
+306 -82

No files matched your search

+250 -74
View File
@@ -742,7 +742,7 @@ fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
/// so a piece that held several ranges was hashed once for each.
pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> {
runs.sort_unstable_by_key(|r| r.first);
let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len());
let mut out: Vec<CardSpan> = Vec::new();
for run in runs {
match out.last_mut() {
Some(last) if run.first <= last.first + last.pieces => {
@@ -1444,6 +1444,25 @@ type Job = Box<dyn FnOnce() + Send>;
struct Workers {
jobs: Mutex<std::collections::VecDeque<Job>>,
more: std::sync::Condvar,
/// How many jobs there are, for [`spin`].
there: std::sync::atomic::AtomicUsize,
}
/// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at
/// most (0, the default: not at all): asleep, a thread is woken in 50 us and
/// more, 95 times a frame.
fn spin(there: impl Fn() -> bool) {
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0));
if most == 0 {
return;
}
let began = std::time::Instant::now();
while !there() && (began.elapsed().as_micros() as u64) < most {
for _ in 0..16 {
std::hint::spin_loop();
}
}
}
/// How many threads are kept for [`wide`].
@@ -1457,6 +1476,7 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get_or_init(|| Workers {
jobs: Mutex::new(std::collections::VecDeque::new()),
more: std::sync::Condvar::new(),
there: std::sync::atomic::AtomicUsize::new(0),
});
STARTED.call_once(|| {
for i in 0..wide_threads() {
@@ -1465,9 +1485,13 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get().expect("made above");
loop {
let job = {
// A little while awake first: the next work comes
// within microseconds more often than not.
spin(|| workers.there.load(Ordering::Acquire) > 0);
let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(job) = jobs.pop_front() {
workers.there.fetch_sub(1, Ordering::AcqRel);
break job;
}
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
@@ -1498,6 +1522,7 @@ fn wide(jobs: Vec<Job>) {
let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
for job in jobs {
let left = left.clone();
workers.there.fetch_add(1, Ordering::AcqRel);
queue.push_back(Box::new(move || {
job();
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
@@ -1512,10 +1537,14 @@ fn wide(jobs: Vec<Job>) {
loop {
let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
match job {
Some(job) => job(),
Some(job) => {
workers.there.fetch_sub(1, Ordering::AcqRel);
job()
}
None => break,
}
}
spin(|| left.0.try_lock().is_ok_and(|n| *n == 0));
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
while *n > 0 {
n = left.1.wait(n).unwrap_or_else(|e| e.into_inner());
@@ -2059,6 +2088,68 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize,
runs
}
/// [`dword_runs`] with no gap, the fast way where it can be: a frame compares
/// 12 MB this way and finds 80,000 runs.
fn word_runs(at: usize, title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
#[cfg(target_arch = "x86_64")]
if at % 4 == 0 && title.len() % 4 == 0 && title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") {
// SAFETY: the processor has AVX2, and the lengths are the same.
return unsafe { word_runs_avx2(title, held) };
}
dword_runs(at, title, held, 0)
}
/// # Safety
/// AVX2, and two slices of one length, whole words.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn word_runs_avx2(title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
use std::arch::x86_64::*;
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut push = |from: usize, len: usize| match runs.last_mut() {
Some((a, n)) if *a + *n == from => *n += len,
_ => runs.push((from, len)),
};
let n = title.len();
let mut i = 0;
while i + 256 <= n {
let mut differ = 0u64;
for k in 0..8 {
// SAFETY: inside both slices (`i + 256 <= n`).
let same = unsafe {
_mm256_cmpeq_epi32(
_mm256_loadu_si256(title.as_ptr().add(i + 32 * k).cast()),
_mm256_loadu_si256(held.as_ptr().add(i + 32 * k).cast()),
)
};
differ |= u64::from(!_mm256_movemask_ps(_mm256_castsi256_ps(same)) as u8) << (8 * k);
}
while differ != 0 {
let first = differ.trailing_zeros();
let count = (differ >> first).trailing_ones();
push(i + 4 * first as usize, 4 * count as usize);
if first + count >= 64 {
break;
}
differ &= u64::MAX << (first + count);
}
i += 256;
}
while i + 4 <= n {
if title[i..i + 4] != held[i..i + 4] {
push(i, 4);
}
i += 4;
}
runs
}
/// Whether the pages of [`Shadow::merge_under_writes`] are compared on several
/// threads (`VICTORY_UNDER_WIDE=0`: on the submitting one).
fn under_wide() -> bool {
crate::toggled!("VICTORY_UNDER_WIDE")
}
/// What shaders wrote goes into title memory from `at` on: `title` is what
/// was read there, `merged` the same with their bytes put in. Only the
/// dwords that differ are written. The whole stretch from the first changed
@@ -2140,7 +2231,7 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
#[cfg(test)]
mod merge_tests {
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed, word_runs};
/// A piece put back takes the GPU's bytes where the copy changed and
/// the title's everywhere else, reads and writes title memory only from
@@ -2311,6 +2402,31 @@ mod merge_tests {
println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
}
#[test]
fn word_runs_are_the_dword_runs() {
let mut seed = 7u32;
let mut random = move || {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
seed >> 8
};
for round in 0..200 {
let n = 4 * (random() as usize % 400);
let was: Vec<u8> = (0..n).map(|_| random() as u8).collect();
let mut now = was.clone();
for _ in 0..random() % 200 {
if n == 0 {
break;
}
let at = random() as usize % n;
let len = (random() as usize % 24).min(n - at);
for b in &mut now[at..at + len] {
*b = random() as u8;
}
}
assert_eq!(word_runs(0x1000, &now, &was), dword_runs(0x1000, &now, &was, 0), "round {round}");
}
}
#[test]
fn changed_runs_are_exactly_the_bytes_that_differ() {
let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
@@ -3377,7 +3493,6 @@ impl Shadow {
// copy in the PC's memory in the snapshot.
let busy = if crate::watch::light() { joined(busy) } else { busy };
let base = start / PAGE;
let mut title = vec![0u8; PAGE];
for (a, e) in busy {
// As the refresh itself asks (`update_free`): the journal if
// the submission's asking covered the range, else the kernel,
@@ -3393,89 +3508,150 @@ impl Shadow {
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
stale_pages_in(base, &copied, a, e, &written)
};
for page in stale {
let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
if lo >= hi {
if stale.is_empty() {
continue;
}
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let held = if self.card.is_some() {
self.data as usize
} else {
before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize)
};
if held == 0 {
note_stale(3);
return true;
}
// A page's part in the range, compared and put in: the runs it
// changed; none for a page that is not there (left as it is, and
// looked at again next time) or that had too many.
type Done = Option<Vec<(usize, usize)>>;
let left = std::sync::atomic::AtomicI64::new(*runs_left as i64);
let over = std::sync::atomic::AtomicBool::new(false);
let done: Vec<Mutex<Done>> = stale.iter().map(|_| Mutex::new(None)).collect();
let page_of = |i: usize| -> (usize, usize) { ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)) };
let one = |i: usize| {
let (lo, hi) = page_of(i);
if lo < hi && !over.load(Ordering::Relaxed) {
// SAFETY: the reference holds the copy's bytes at the
// copy's offsets, and these are in a declared range; the
// locks held above keep out what else writes them, and
// no two pages are the same.
let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) };
match runs {
Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs,
Err(()) => over.store(true, Ordering::Relaxed),
}
}
};
// (Not on the threads of `wide`: the thread that waits there
// takes whatever work comes, and a landing's takes the lock.)
if stale.len() > 2 && under_wide() {
crate::land::each_under(stale.len(), &one);
} else {
(0..stale.len()).for_each(one);
}
*runs_left = left.into_inner().max(0) as usize;
let mut taken = Vec::new();
for (i, runs) in done.into_iter().enumerate() {
let Some(runs) = runs.into_inner().unwrap_or_else(|e| e.into_inner()) else {
continue;
}
let n = hi - lo;
let title = &mut title[..n];
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
// A page that is not there is left as it is, and looked at
// again next time.
if !crate::host::read_into(lo as *const u8, title) {
continue;
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - start;
if self.card.is_some() {
// SAFETY: inside the mapping of the copy's CPU side,
// which only the submitting thread writes.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count();
if copies > *runs_left {
note_stale(2);
return true;
}
*runs_left -= copies;
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m)));
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
return true;
};
// SAFETY: the snapshot's allocation holds the copy's
// bytes at the copy's offsets (`writing`), and these
// are in a declared range.
let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) };
for (r, m) in changed_runs(title, held) {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[1].fetch_add(1, Ordering::Relaxed);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
}
drop(before);
drop(_merging);
};
let (lo, hi) = ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e));
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
MERGED[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (lo - start + r, lo - start + r + m)));
// Taken, if the range holds all of the page that is in the
// copy; else the rest of it is the refresh's, which notes
// only whole pages, and the page is looked at again.
if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e {
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e {
taken.push(stale[i]);
}
}
drop(before);
drop(merging);
{
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
for page in taken {
if let Some(at) = copied.get_mut(page - base) {
*at = now;
}
}
}
if over.into_inner() {
note_stale(2);
return true;
}
}
false
}
/// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one
/// page, compared with the reference, which begins at `held`, and put in.
/// The runs that changed, none if it cannot be read, and an error if
/// there were more to copy one by one than `left`.
///
/// # Safety
/// The reference holds the copy's length, and nothing else writes these
/// bytes of it during the call.
unsafe fn merge_page_under_writes(
&self,
lo: usize,
n: usize,
held: *mut u8,
left: &std::sync::atomic::AtomicI64,
) -> Result<Option<Vec<(usize, usize)>>, ()> {
thread_local! {
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
let title = &mut title[..n];
if !crate::host::read_into(lo as *const u8, title) {
return Ok(None);
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - self.start as usize;
// SAFETY: the caller's.
let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) };
if self.card.is_some() {
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count() as i64;
if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies {
return Err(());
}
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
return Ok(Some(runs));
}
let runs = changed_runs(title, held);
for &(r, m) in &runs {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
Ok(Some(runs))
})
}
/// At submission: copies what changed of `[address, address + len)`
/// since it was last copied (all of it if the memory is not
/// write-watched). Returns the bytes copied.