From 897065f05d8fb5cb098fccf2aadb8e188de5833c Mon Sep 17 00:00:00 2001 From: NickJBc Date: Tue, 24 Nov 2026 21:29:08 -0400 Subject: [PATCH] GPU: add an opt-in 256-thread card hash Port NickJBc's wide shader and host integration from fxceless/victory-fork#493, commit ccdf4c4b1e718259f7864d4a479b259e4c62bb5b. VICTORY_CARD_HASH_WIDE=1 selects one algorithm for uploads and compares for the lifetime of the device. The default remains the serial shader. The 128-bit hash is internal and differs between the two algorithms. Fall back to the serial path if creating the wide roots or PSO fails. Exercise both on D3D12 WARP with partial pieces, paired sign-bit edits, and compare-only and compare-and-store semantics across reversions. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/card_hash.rs | 298 ++++++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 114 ++++++----- crates/victory-gpu/src/indirect.rs | 51 ++++- crates/victory-gpu/src/lib.rs | 2 + 4 files changed, 413 insertions(+), 52 deletions(-) create mode 100644 crates/victory-gpu/src/card_hash.rs diff --git a/crates/victory-gpu/src/card_hash.rs b/crates/victory-gpu/src/card_hash.rs new file mode 100644 index 0000000000..5d953e5c36 --- /dev/null +++ b/crates/victory-gpu/src/card_hash.rs @@ -0,0 +1,298 @@ +//! A wider form of the hash pass over copies in the card's memory +//! (`VICTORY_CARD_HASH_WIDE=1`; off by default): the same work as +//! `crate::host::CARD_COMPARE`, with the same root signature, constants and +//! results, but a group of 256 threads per 64 KiB piece instead of one +//! thread. +//! +//! The narrow form walks a piece 16 bytes at a time, 4,096 dependent steps +//! on one thread, with neighbouring threads 64 KiB apart, so a pass over a +//! few pieces takes the time of a whole piece on one lane of the card +//! (`crate::host`'s `rehash_runs`: 514 such passes a frame in run 102). +//! Here lane `l` of a piece's group takes the piece's 16-byte blocks +//! `l, l + 256, l + 512, ...` (16 steps for a whole piece; the group's loads +//! of one step are 4 KiB side by side), and the 256 lane hashes are then +//! joined in a fixed tree. +//! +//! The hash differs from the narrow form's. Nothing outside the shader +//! computes or reads it (the `hashes` buffer holds only what the shader +//! stored), and one form is chosen for the run, so the two never meet. +//! +//! What either form guarantees: a change confined to one 16-byte block of +//! a piece always changes its hash. Here because the lane's round is a +//! bijection of its state for a given block and of the block for a given +//! state, and [`join`] is a bijection of each side for a given other side. +//! A change spread over several blocks is missed only by a collision of +//! the 128-bit value, as before. + +/// Groups per row of the dispatch: a dimension may not exceed 65,535 +/// groups, and a run can hold more pieces than that. +pub(crate) const ROW: u32 = 32768; + +/// The groups to dispatch for `pieces` pieces: the wide form takes a group +/// per piece, in rows of [`ROW`]; the narrow form a thread per piece, in +/// groups of 64. +pub(crate) fn groups(pieces: u32, wide: bool) -> (u32, u32) { + if wide { + (pieces.min(ROW), pieces.div_ceil(ROW)) + } else { + (pieces.div_ceil(64), 1) + } +} + +/// The wide form's source (FXC, `cs_5_1`). Every thread reaches every +/// barrier: a group past the last piece hashes nothing and stores nothing, +/// but does not return early. +pub(crate) const CARD_COMPARE_WIDE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +groupshared uint4 lanes[256]; + +uint4 step16(uint4 h, uint4 x) { + h = (h ^ x) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + return h.yzwx ^ (h >> 15); +} + +uint4 join(uint4 a, uint4 b) { + return (a * uint4(0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du, 0x27D4EB2Fu)) + ^ (b * uint4(0x01000193u, 0x2545F491u, 0x5851F42Du, 0x6C078965u)).wxyz; +} + +[RootSignature(RS)] +[numthreads(256, 1, 1)] +void main(uint3 group : SV_GroupID, uint lane : SV_GroupIndex) { + uint i = group.y * 32768u + group.x; + bool live = i < pieces; + uint piece = first + i; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + if (!live) hi = lo; + uint4 h = uint4(0x9E3779B9u ^ lane, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + [loop] + for (uint at = lo + lane * 16u; at < hi; at += 4096u) { + h = step16(h, now.Load4(at)); + } + lanes[lane] = h; + GroupMemoryBarrierWithGroupSync(); + [unroll] + for (uint s = 128u; s > 0u; s >>= 1u) { + if (lane < s) lanes[lane] = join(lanes[lane], lanes[lane + s]); + GroupMemoryBarrierWithGroupSync(); + } + if (live && lane == 0u) { + h = lanes[0]; + if (compare != 0u) { + differs.Store(out_at + i * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } + } +} +"#; + +/// Whether the wide form is asked for (`VICTORY_CARD_HASH_WIDE=1`). Read +/// once, when the host makes the compare. +pub(crate) fn wide() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_HASH_WIDE").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +mod tests { + //! The shader's arithmetic, step for step in Rust, to pin what it + //! computes (the shader itself runs only on a card). + use super::{ROW, groups}; + + /// Threads per piece (the shader's `numthreads`). + const LANES: u32 = 256; + + const K: [u32; 4] = [0x0100_0193, 0x9E37_79B1, 0x85EB_CA77, 0xC2B2_AE3D]; + const JA: [u32; 4] = [0x9E37_79B1, 0x85EB_CA77, 0xC2B2_AE3D, 0x27D4_EB2F]; + const JB: [u32; 4] = [0x0100_0193, 0x2545_F491, 0x5851_F42D, 0x6C07_8965]; + + fn mul(a: [u32; 4], k: [u32; 4]) -> [u32; 4] { + std::array::from_fn(|i| a[i].wrapping_mul(k[i])) + } + + fn step16(h: [u32; 4], x: [u32; 4]) -> [u32; 4] { + let h = mul(std::array::from_fn(|i| h[i] ^ x[i]), K); + // h.yzwx ^ (h >> 15) + std::array::from_fn(|i| h[(i + 1) % 4] ^ (h[i] >> 15)) + } + + fn join(a: [u32; 4], b: [u32; 4]) -> [u32; 4] { + let (a, b) = (mul(a, JA), mul(b, JB)); + // b.wxyz + std::array::from_fn(|i| a[i] ^ b[(i + 3) % 4]) + } + + fn load4(buf: &[u8], at: usize) -> [u32; 4] { + std::array::from_fn(|i| { + u32::from_le_bytes(buf[at + 4 * i..at + 4 * i + 4].try_into().unwrap()) + }) + } + + /// The bounds the shader hashes for `piece`. + fn bounds(piece: u32, skew: u32, size: u32) -> (u32, u32) { + let lo = piece * 65536; + let lo = if lo > skew { lo - skew } else { 0 }; + let hi = ((piece + 1) * 65536 - skew).min(size); + (lo & !15, (hi + 15) & !15) + } + + /// What the group of `piece` leaves in `lanes[0]`. + fn piece_hash(buf: &[u8], piece: u32, skew: u32) -> [u32; 4] { + let (lo, hi) = bounds(piece, skew, buf.len() as u32); + let mut lanes: Vec<[u32; 4]> = (0..LANES) + .map(|lane| { + let mut h = [0x9E37_79B9 ^ lane, 0x85EB_CA6B, 0xC2B2_AE35, 0x27D4_EB2F]; + let mut at = lo + lane * 16; + while at < hi { + h = step16(h, load4(buf, at as usize)); + at += 4096; + } + h + }) + .collect(); + let mut s = LANES / 2; + while s > 0 { + for lane in 0..s as usize { + lanes[lane] = join(lanes[lane], lanes[lane + s as usize]); + } + s /= 2; + } + lanes[0] + } + + fn noise(n: usize, seed: u64) -> Vec { + let mut x = seed | 1; + (0..n) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() + } + + /// Every 16-byte block of a piece is taken by exactly one lane, once. + #[test] + fn the_lanes_take_every_block_of_a_piece_once() { + for (piece, skew, size) in [ + (0u32, 0u32, 1u32 << 20), + (3, 0, 1 << 20), + (0, 0x1f00, 1 << 20), + (2, 0x1f00, 1 << 20), + (15, 0, 1 << 20), + (15, 0x8000, 1 << 20), + ] { + let (lo, hi) = bounds(piece, skew, size); + let mut seen = vec![0u8; ((hi - lo) / 16) as usize]; + for lane in 0..LANES { + let mut at = lo + lane * 16; + while at < hi { + seen[((at - lo) / 16) as usize] += 1; + at += 4096; + } + } + assert!(seen.iter().all(|&n| n == 1), "piece {piece} skew {skew:#x}"); + } + } + + /// A change of any one byte of a piece changes its hash; a change + /// outside its bounds does not. + #[test] + fn one_changed_byte_always_shows() { + let size = 4 * 65536; + let base = noise(size, 7); + for skew in [0u32, 0x1f00] { + let piece = 1; + let (lo, hi) = bounds(piece, skew, size as u32); + let before = piece_hash(&base, piece, skew); + let mut probe = noise(64, 99).into_iter(); + for at in (lo..hi) + .step_by(97) + .chain([lo, lo + 15, lo + 16, hi - 16, hi - 1]) + { + let mut buf = base.clone(); + buf[at as usize] ^= probe.next().unwrap_or(1) | 1; + assert_ne!( + piece_hash(&buf, piece, skew), + before, + "byte {at:#x} skew {skew:#x}" + ); + } + for at in [lo.wrapping_sub(1), hi] { + if (at as usize) < size { + let mut buf = base.clone(); + buf[at as usize] ^= 0x5a; + assert_eq!( + piece_hash(&buf, piece, skew), + before, + "byte {at:#x} outside" + ); + } + } + } + } + + /// Pieces that hold the same bytes at different places, or the same + /// blocks in another order, hash differently (the lane seeds and the + /// tree's order are in the hash). + #[test] + fn swapped_blocks_show() { + let size = 2 * 65536; + let base = noise(size, 3); + let before = piece_hash(&base, 0, 0); + let mut swapped = base.clone(); + let (a, b) = (16 * 5, 16 * 300); + for i in 0..16 { + swapped.swap(a + i, b + i); + } + assert_ne!(piece_hash(&swapped, 0, 0), before); + assert_eq!(piece_hash(&base, 0, 0), before); + } + + /// The groups cover pieces `0..n` with each index once and stay within + /// the 65,535-group limit per dimension. + #[test] + fn the_dispatch_covers_every_piece() { + for n in [ + 0u32, + 1, + 2, + 63, + 64, + 65, + ROW - 1, + ROW, + ROW + 1, + 3 * ROW + 5, + 262_144, + ] { + let (x, y) = groups(n, true); + assert!(x <= 65_535 && y <= 65_535); + let live = (0..y) + .flat_map(|gy| (0..x).map(move |gx| gy * ROW + gx)) + .filter(|&i| i < n) + .count(); + assert_eq!(live as u32, n, "{n} pieces"); + let (x, _) = groups(n, false); + assert!(x * 64 >= n && x * 64 < n + 64); + } + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index cb57a59f98..64d9d749f7 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1423,6 +1423,9 @@ struct CardWork { fetch: Prelude, root: ID3D12RootSignature, pso: ID3D12PipelineState, + /// Whether `pso` is the wide form of the compare + /// ([`crate::card_hash`]): a group per piece, not a thread. + wide: bool, /// One dword per piece compared, set where the piece differs: PC /// memory, mapped (buffer, mapping, bytes). differs: (ID3D12Resource, usize, u64), @@ -2905,56 +2908,75 @@ impl Host { fn make_card_work(&self) -> windows::core::Result { use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; - let mut code: Option = None; - // SAFETY: the source and names live through the call; the out - // pointer is ours. - unsafe { - D3DCompile( - CARD_COMPARE.as_ptr().cast(), - CARD_COMPARE.len(), - windows::core::s!("card compare"), - None, - None, - windows::core::s!("main"), - windows::core::s!("cs_5_1"), - 0, - 0, - &mut code, - None, - )?; + let pipeline = |source: &str| -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> { + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("card compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the shader blob holds both the bytecode and root signature. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok((root, pso)) + } + }; + // The wide form if asked for; the narrow one if it was not, or if + // the wide one does not compile here (copies in the card's memory + // hang on the compare, so it must not be lost to the switch). + let wide = crate::card_hash::wide() + .then(|| pipeline(crate::card_hash::CARD_COMPARE_WIDE)) + .and_then(|made| { + made.map_err(|e| tracing::warn!(error = %e, "wide card compare unavailable, using serial compare")) + .ok() + }); + let ((root, pso), wide) = match wide { + Some(pipeline) => (pipeline, true), + None => (pipeline(CARD_COMPARE)?, false), + }; + if wide { + tracing::info!("card compare: a group per piece (VICTORY_CARD_HASH_WIDE)"); } - let code = code.ok_or_else(windows::core::Error::empty)?; let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); // A megabyte of results: 262,144 pieces, 16 GB of declared ranges // in one submission. const RESULTS: u64 = 1 << 20; let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; name(&differs, || "card compare results".into()); - // SAFETY: the blob's own bytes; the root signature is inside the - // shader. - unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); - let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; - let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - })?; - Ok(CardWork { - sync: vec![list()?], - check: vec![list()?], - fetch: list()?, - root, - pso, - differs: (differs, data as usize, RESULTS), - fetched: None, - taken: 0, - out: 0, - }) - } + Ok(CardWork { + sync: vec![list()?], + check: vec![list()?], + fetch: list()?, + root, + pso, + wide, + differs: (differs, data as usize, RESULTS), + fetched: None, + taken: 0, + out: 0, + }) } /// Before a submission's lists run, for copies in the card's memory @@ -3077,7 +3099,8 @@ impl Host { for run in runs { let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); - list.Dispatch(run.pieces.div_ceil(64), 1, 1); + let (x, y) = crate::card_hash::groups(run.pieces, work.wide); + list.Dispatch(x, y, 1); } } list.Close()?; @@ -3162,7 +3185,8 @@ impl Host { list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + let (x, y) = crate::card_hash::groups(r.span.pieces, work.wide); + list.Dispatch(x, y, 1); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index bff1577eb5..e2b6cde5e4 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -661,13 +661,23 @@ void main() { /// compare before it, also a change back. #[test] fn warp_card_compare_stores_the_hash_it_made_when_told() { - let Some(mut warp) = WarpHarness::new() else { - return; - }; - let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + for wide in [false, true] { + let Some(warp) = WarpHarness::new() else { + eprintln!("skipping card hash test: D3D12 WARP is unavailable"); + return; + }; + check_card_compare(warp, wide); + eprintln!("WARP verified dirty-piece flags (wide={wide})"); + } + } + + fn check_card_compare(mut warp: WarpHarness, wide: bool) { + let source = if wide { crate::card_hash::CARD_COMPARE_WIDE } else { crate::host::CARD_COMPARE }; + let compare = compile_cs(&warp.device, source).expect("card compare must compile"); const PIECE: usize = 64 << 10; + const SKEW: u32 = 256; const PIECES: u32 = 3; - let size = PIECE * PIECES as usize; + let size = PIECE * 2; let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); @@ -685,12 +695,13 @@ void main() { } warp.list.SetComputeRootSignature(&compare.root); warp.list.SetPipelineState(&compare.pso); - let constants = [0u32, 0, size as u32, PIECES, 0, mode]; + let constants = [0u32, SKEW, size as u32, PIECES, 0, mode]; warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); - warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + let (x, y) = crate::card_hash::groups(PIECES, wide); + warp.list.Dispatch(x, y, 1); } warp.submit_and_wait(); // SAFETY: as above. @@ -718,6 +729,32 @@ void main() { set(content[at]); assert_eq!(run(&mut warp, 2), [0, 1, 0]); assert_eq!(run(&mut warp, 2), [0, 0, 0]); + + // Reproduce the paired sign-bit edit reported on PR #71, then also + // exercise siblings in the 256-lane tree. These are the final loads + // in the full middle piece, at their first dword's high byte. + let middle = PIECE - SKEW as usize; + for offsets in [[64_512, 65_024], [61_440, 63_488]] { + for offset in offsets { + let i = middle + offset + 3; + // SAFETY: the queue is idle and the piece is inside this mapping. + unsafe { now_ptr.add(i).write_volatile(content[i] ^ 0x80) }; + } + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + for offset in offsets { + let i = middle + offset + 3; + // SAFETY: the same two bytes after waiting for the compare. + unsafe { now_ptr.add(i).write_volatile(content[i]) }; + } + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + } + // Both partial pieces and the full middle piece change together. + for i in [0, PIECE - SKEW as usize - 1, at, at + 128 * 16, size - 1] { + // SAFETY: each offset is within the live mapping, with the queue idle. + unsafe { now_ptr.add(i).write_volatile(content[i] ^ 0x80) }; + } + assert_eq!(run(&mut warp, 2), [1, 1, 1]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); } /// The clamp compiles with the system's compiler and the host takes it. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f110b1..c2da86073c 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -17,6 +17,8 @@ #[cfg(all(windows, feature = "diagnostics"))] mod capture; +#[cfg(any(windows, test))] +mod card_hash; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat;