From 4959d6b630e1769210fcf688136a840744c9856a Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:02:27 -0600 Subject: [PATCH] d3d12: hash a texture's memory with AES rounds, 2.9-5.9x faster (D3D12-GPU-TEXTURE-DIGEST-AES) texture::digest, which tells whether a guarded texture's memory changed (at every check that is not skipped, and over all of it the first time), was a fold of 64x64-bit multiplications that ran at 23.5 GB/s at every size from 16 KiB to 256 MiB: the multiplications were its limit, not the memory. With AES-NI it is now eight 128-bit lanes of `aesenc` over 128 bytes at a time, each lane through two more rounds on its own before the lanes meet: 139, 121, 108, 114 and 70 GB/s on 16 KiB, 256 KiB, 2 MiB, 32 MiB and 256 MiB (Ryzen 7 7800X3D, best of five, `digest_speeds`). The folded one stays as the fallback. The digests are only compared with each other inside one run and none is written out, so the value may change; which version is used cannot change during a run. A first version, whose lanes met by one round, had pairs of one-bit changes with the same digest (1,328 in a million with four lanes). `no_two_changes_cancel_in_the_aes_digest` tries pairs of one-bit changes over 520 bytes and 4 KiB of noise and of zeros: none for the real digest and for the folded one, 83 for the eight-lane version met by one round (its negative control). AI-assisted: Claude Sonnet 5.5 Co-authored-by: Cursor --- d3d12/crates/leonida-gpu/src/texture.rs | 320 +++++++++++++++++++++++- d3d12/docs/findings.md | 10 + 2 files changed, 325 insertions(+), 5 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index e0a15e13a4..32ce3a4911 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -1323,11 +1323,87 @@ fn once() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_ONCE").is_none_or(|v| v != "0")) } -/// A 128-bit digest of `bytes`, to tell a texture's memory changed: four -/// lanes of folded multiplications over 64 bytes at a time. (Not a +/// A 128-bit digest of `bytes`, to tell a texture's memory changed. (Not a /// cryptographic one, which took 0.27 ms a megabyte, four times the detiling -/// it was to spare; nobody makes up textures to collide.) +/// it was to spare; nobody makes up textures to collide.) With AES-NI, which +/// every processor the title runs on has, [`digest_aes`]; without, +/// [`digest_folded`]. The digests are only compared with one another inside +/// one run, none is written out, and which of the two is used cannot change +/// during it: they need not agree on a value. pub(crate) fn digest(bytes: &[u8]) -> Digest { + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("aes") { + // SAFETY: the processor has AES-NI (and SSE2, which every x86-64 one has). + return unsafe { digest_aes(bytes) }; + } + digest_folded(bytes) +} + +/// [`digest`] of eight 128-bit lanes of AES rounds over 128 bytes at a time: +/// lane `i` takes the block's `i`-th 16 bytes with `aesenc` (a round of AES +/// with those bytes as its round key). They are eight independent chains, +/// which hide the latency of the rounds. Before the lanes meet, each goes +/// through two more rounds on its own, so that a change in one of the last +/// blocks has spread over all 16 bytes of its lane: with the lanes met by +/// one round, as in `aesenc(lane0, lane1)`, two single-bit changes in two +/// lanes cancelled one time in about 2^7 (`no_two_changes_cancel_in_the_aes_digest` +/// has that version as its negative control). The length is mixed in at the +/// end. 117-143 GB/s from cache and 70 GB/s from memory on a Ryzen 7 7800X3D, +/// where [`digest_folded`] is 23.5 GB/s at every size. +/// +/// # Safety +/// The processor has AES-NI and SSE2. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "aes,sse2")] +unsafe fn digest_aes(bytes: &[u8]) -> Digest { + use std::arch::x86_64::{ + __m128i, _mm_aesenc_si128, _mm_loadu_si128, _mm_set_epi64x, _mm_storeu_si128, _mm_xor_si128, + }; + // SAFETY: the intrinsics need the features this function enables, and the loads + // and the store are of 16 bytes inside the block, the padded block and `out`. + unsafe { + // Round keys, a different one for every `i`: two multiplications of + // the splitmix constants by `i + 1`, folded. + let key = |i: u64| { + let x = (i + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15); + let lo = (x ^ x >> 29).wrapping_mul(0xbf58_476d_1ce4_e5b9); + let hi = (x ^ x >> 31).wrapping_mul(0x94d0_49bb_1331_11eb); + _mm_set_epi64x((hi ^ hi >> 32) as i64, (lo ^ lo >> 32) as i64) + }; + let mut lane: [__m128i; 8] = std::array::from_fn(|i| key(i as u64)); + let mut absorb = |block: &[u8; 128]| { + let at = block.as_ptr().cast::<__m128i>(); + for (i, one) in lane.iter_mut().enumerate() { + *one = _mm_aesenc_si128(*one, _mm_loadu_si128(at.add(i))); + } + }; + let mut blocks = bytes.chunks_exact(128); + for block in &mut blocks { + absorb(block.try_into().unwrap_or(&[0; 128])); + } + let rest = blocks.remainder(); + let mut last = [0u8; 128]; + last[..rest.len()].copy_from_slice(rest); + absorb(&last); + let mut met = _mm_set_epi64x(bytes.len() as i64, !(bytes.len() as i64)); + for (i, one) in lane.iter().enumerate() { + let own = _mm_aesenc_si128( + _mm_aesenc_si128(*one, key(8 + i as u64)), + key(16 + i as u64), + ); + met = _mm_xor_si128(met, own); + } + let met = _mm_aesenc_si128(_mm_aesenc_si128(met, key(24)), key(25)); + let mut out = [0u8; 16]; + _mm_storeu_si128(out.as_mut_ptr().cast(), met); + Digest(u128::from_le_bytes(out)) + } +} + +/// [`digest`] of four lanes of folded multiplications over 64 bytes at a +/// time: 23.5 GB/s at every size on a Ryzen 7 7800X3D, the multiplications +/// being the limit and not the memory. +fn digest_folded(bytes: &[u8]) -> Digest { const K: [u64; 8] = [ 0xa076_1d64_78bd_642f, 0xe703_7ed1_a0b4_28db, @@ -3573,10 +3649,19 @@ mod allocation_costs { } /// The digest tells every length and every changed byte apart, zeros - /// among them. + /// among them: the one `digest` takes, and each of its two versions. #[test] fn a_digest_tells_bytes_apart() { - use super::digest; + tells_bytes_apart(super::digest); + tells_bytes_apart(super::digest_folded); + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("aes") { + // SAFETY: the processor has AES-NI. + tells_bytes_apart(|bytes| unsafe { super::digest_aes(bytes) }); + } + } + + fn tells_bytes_apart(digest: impl Fn(&[u8]) -> super::Digest) { let zeros = [0u8; 400]; let mut seen: Vec = (0..400).map(|n| digest(&zeros[..n])).collect(); for at in 0..400 { @@ -3602,6 +3687,231 @@ mod allocation_costs { assert_eq!(digest(&text), digest(&text.clone())); } + /// The digests of `base` with each one bit of `bits` turned over, and each two of them: how + /// many of them are another's. + #[cfg(target_arch = "x86_64")] + fn collisions_among_flips( + digest: &dyn Fn(&[u8]) -> super::Digest, + base: &[u8], + bits: &[usize], + ) -> usize { + let mut all = vec![digest(base).0]; + for (k, &a) in bits.iter().enumerate() { + let mut once = base.to_vec(); + once[a / 8] ^= 1 << (a % 8); + all.push(digest(&once).0); + for &c in &bits[k + 1..] { + let mut twice = once.clone(); + twice[c / 8] ^= 1 << (c % 8); + all.push(digest(&twice).0); + } + } + let n = all.len(); + all.sort_unstable(); + all.dedup(); + n - all.len() + } + + /// [`super::digest_aes`] with its lanes met by one round each, as it was first written: the + /// negative control of `no_two_changes_cancel_in_the_aes_digest`. + /// + /// # Safety + /// The processor has AES-NI and SSE2. + #[cfg(target_arch = "x86_64")] + #[target_feature(enable = "aes,sse2")] + unsafe fn aes_digest_met_by_one_round(bytes: &[u8]) -> super::Digest { + use std::arch::x86_64::{ + __m128i, _mm_aesenc_si128, _mm_loadu_si128, _mm_set_epi64x, _mm_storeu_si128, + }; + // SAFETY: as in `digest_aes`. + unsafe { + let key = |i: u64| { + _mm_set_epi64x( + (i.wrapping_mul(0x2545_f491_4f6c_dd1d) ^ 0x9e37) as i64, + !i.wrapping_mul(0x9e37_79b9_7f4a_7c15) as i64, + ) + }; + let mut lane: [__m128i; 8] = std::array::from_fn(|i| key(i as u64 + 1)); + let mut absorb = |block: &[u8; 128]| { + let at = block.as_ptr().cast::<__m128i>(); + for (i, one) in lane.iter_mut().enumerate() { + *one = _mm_aesenc_si128(*one, _mm_loadu_si128(at.add(i))); + } + }; + let mut blocks = bytes.chunks_exact(128); + for block in &mut blocks { + absorb(block.try_into().unwrap_or(&[0; 128])); + } + let rest = blocks.remainder(); + let mut last = [0u8; 128]; + last[..rest.len()].copy_from_slice(rest); + absorb(&last); + let len = _mm_set_epi64x(bytes.len() as i64, !(bytes.len() as i64)); + let a = _mm_aesenc_si128(_mm_aesenc_si128(lane[0], lane[1]), key(20)); + let b = _mm_aesenc_si128(_mm_aesenc_si128(lane[2], lane[3]), len); + let c = _mm_aesenc_si128(_mm_aesenc_si128(lane[4], lane[5]), key(21)); + let d = _mm_aesenc_si128(_mm_aesenc_si128(lane[6], lane[7]), key(22)); + let e = _mm_aesenc_si128(_mm_aesenc_si128(a, b), key(23)); + let f = _mm_aesenc_si128(_mm_aesenc_si128(c, d), key(24)); + let met = _mm_aesenc_si128(_mm_aesenc_si128(e, f), key(25)); + let mut out = [0u8; 16]; + _mm_storeu_si128(out.as_mut_ptr().cast(), met); + super::Digest(u128::from_le_bytes(out)) + } + } + + /// Pairs of one-bit changes, in 520 bytes of noise and of zeros (four 128-byte blocks and a + /// tail, the places a lane's change meets another's) and in 4 KiB of both spread over its + /// blocks: no two have the same digest, as with the folded one; the version whose lanes meet + /// by one round has some (83 of them in this test; a first version with four lanes, 1,328 in a + /// million pairs). + #[cfg(target_arch = "x86_64")] + #[test] + fn no_two_changes_cancel_in_the_aes_digest() { + if !std::arch::is_x86_feature_detected!("aes") { + return; + } + let mut state = 0x1234_5678_9ABC_DEF1_u64; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state as u8 + }) + .collect() + }; + // Every seventh bit of 520 bytes and the 64 of the last eight. + let mut near: Vec = (0..520 * 8) + .filter(|b| b % 7 == 0) + .chain(4096..4160) + .collect(); + near.sort_unstable(); + near.dedup(); + // A bit in each of eleven places of each of 32 blocks, and the end of 4 KiB. + let mut spread: Vec = Vec::new(); + for block in 0..32 { + for place in [0usize, 3, 4, 15, 16, 20, 31, 64, 67, 112, 127] { + spread.push((block * 128 + place) * 8 + (block + place) % 8); + } + } + spread.extend((4096 - 70..4096).map(|b| b * 8 + 1)); + spread.sort_unstable(); + spread.dedup(); + let real = |bytes: &[u8]| { + // SAFETY: the processor has AES-NI. + unsafe { super::digest_aes(bytes) } + }; + let control = |bytes: &[u8]| { + // SAFETY: the processor has AES-NI. + unsafe { aes_digest_met_by_one_round(bytes) } + }; + let (mut thin, mut thick) = (0, 0); + for (base, bits) in [ + (noise(520), &near), + (vec![0; 520], &near), + (noise(4096), &spread), + (vec![0; 4096], &spread), + ] { + assert_eq!( + collisions_among_flips(&real, &base, bits), + 0, + "{} bytes", + base.len() + ); + thin += collisions_among_flips(&control, &base, bits); + if base.len() == 520 { + thick += collisions_among_flips(&super::digest_folded, &base, bits); + } + } + println!( + "pairs of changes with one digest: folded {thick}, met by one round {thin}, real 0" + ); + assert_eq!(thick, 0, "the folded digest"); + assert!( + thin > 20, + "the control has {thin} of them: the test could not tell it from the real one" + ); + } + + /// The two versions of the digest, in GB/s over buffers of 16 KiB to 256 MiB (best of five): + /// `cargo test --release -p leonida-gpu --lib digest_speeds -- --ignored --nocapture`. + #[cfg(target_arch = "x86_64")] + #[test] + #[ignore = "a measurement, not a check"] + fn digest_speeds() { + if !std::arch::is_x86_feature_detected!("aes") { + return; + } + let versions: [(&str, &dyn Fn(&[u8]) -> super::Digest); 2] = [ + ("folded", &super::digest_folded), + // SAFETY: the processor has AES-NI. + ("aes", &|bytes| unsafe { super::digest_aes(bytes) }), + ]; + for len in [16usize << 10, 256 << 10, 2 << 20, 32 << 20, 256 << 20] { + let bytes: Vec = (0..len) + .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8) + .collect(); + let runs = ((1usize << 30) / len).max(4); + for (name, digest) in versions { + std::hint::black_box(digest(&bytes)); + let mut best = f64::MAX; + for _ in 0..5 { + let began = std::time::Instant::now(); + for _ in 0..runs { + std::hint::black_box(digest(std::hint::black_box(&bytes))); + } + best = best.min(began.elapsed().as_secs_f64() / runs as f64); + } + println!( + "{name:>6} {:>7} KiB: {:6.1} GB/s", + len >> 10, + len as f64 / best / 1e9 + ); + } + } + } + + /// A change of one bit turns over half the 128 bits of the digest, on average, in a + /// megabyte as in a short run, whichever lane it is in. + #[cfg(target_arch = "x86_64")] + #[test] + fn a_changed_bit_turns_half_the_aes_digest_over() { + if !std::arch::is_x86_feature_detected!("aes") { + return; + } + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let real = |bytes: &[u8]| { + // SAFETY: the processor has AES-NI. + unsafe { super::digest_aes(bytes) } + }; + for len in [1usize, 15, 16, 127, 128, 129, 1000, 1 << 20] { + let bytes: Vec = (0..len).map(|_| next() as u8).collect(); + let was = real(&bytes).0; + let flips = 300.min(len * 8); + let mut turned = 0u32; + let mut least = u32::MAX; + for _ in 0..flips { + let bit = (next() as usize) % (len * 8); + let mut once = bytes.clone(); + once[bit / 8] ^= 1 << (bit % 8); + let now = (real(&once).0 ^ was).count_ones(); + turned += now; + least = least.min(now); + } + let mean = f64::from(turned) / flips as f64; + assert!((60.0..68.0).contains(&mean), "{len} bytes: {mean}"); + assert!(least > 30, "{len} bytes: a flip turned over {least} bits"); + } + } + /// The spread places lie one in each whole 64 KiB step, inside the span, /// and no more of them than asked for. #[test] diff --git a/d3d12/docs/findings.md b/d3d12/docs/findings.md index 1a7b40e55c..a40fedc7c7 100644 --- a/d3d12/docs/findings.md +++ b/d3d12/docs/findings.md @@ -1167,6 +1167,16 @@ the card's own 55 ms. and -1.00 +-0.90, the submitting thread -2.88 +-0.50 and -2.62 +-0.49, the card -0.58 and -0.27. A gain of about a millisecond a frame, three of the submitting thread; what it risks is a quiet texture's change seen up to 16 turns late, which a tour with it on is to show. + The hash itself (`texture::digest`, over a texture's memory at every check that is not skipped, and over all of it the + first time it is seen) was a fold of 64x64-bit multiplications that ran at 23.5 GB/s at every size from 16 KiB to + 256 MiB: the multiplications were its limit, not the memory. Eight lanes of AES rounds (`texture::digest_aes`, with + AES-NI, the folded one without) run at 139, 121, 108, 114 and 70 GB/s on 16 KiB, 256 KiB, 2 MiB, 32 MiB and 256 MiB + (best of five, `digest_speeds`, a Ryzen 7 7800X3D: 4.6-5.9 times from cache, 2.9 times from memory). A first version, + whose lanes met by one round, had pairs of one-bit changes with one digest (1,328 in a million with four lanes; the + test of pairs has the eight-lane form as its negative control, 83 in its pairs); with each lane through two rounds before they meet, none in 2.2 million pairs (the + test as first run, with every third bit of the 520 bytes; it keeps every seventh to take 7 s), as with the folded + one. No frame time was taken with it: the 38 to 40 MB of guarded textures the code counted for one + save a frame are 1.7 ms at 23.5 GB/s and 0.3 to 0.6 ms at the speeds above, on the submitting thread. - **Open: the copies behind aliased views could go.** The title reads R32_UINT textures its compute programs write through R9G9B9E5 views it places over them, and the host copies the texels into a texture of the view's format through a buffer (`texture::alias`; 1.0 ms of a timing run's frame for the 2560x1440 one, about 1.6 ms with the