From 5def8df553a5c1e35b47424a773083bb6b896605 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:13:26 +0000 Subject: [PATCH 1/3] blackboard: pre-register the per-code-count power sums by neighbour addition Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XAqKMNPpoyKDKuAgEnu6HU --- .claude/blackboard.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.claude/blackboard.md b/.claude/blackboard.md index 456d789c..0a0e0cc9 100644 --- a/.claude/blackboard.md +++ b/.claude/blackboard.md @@ -1,3 +1,28 @@ +## 2026-11-14 — PRE-REGISTRATION: power sums and extrema of a `u8` lane from per-code counts by neighbour addition + +Written before any code or measurement of this slice. + +**Claim under test.** For a masked `u8` lane, `n`, `Σx`, `Σx²`, `Σx³`, `Σx⁴`, min and max can be obtained from ONE per-row step that only counts (`counts[code] += 1`) followed by a fixed chain of additions over the 256 bins, with no per-row multiplication and no `i32` lane. + +**Mechanism.** Walk the bins from 255 down to 1 with a chain of accumulators, each adding its neighbour: `t1 += c[v]; t2 += t1; t3 += t2; t4 += t3; t5 += t4`. At the end `t2..t5` are `B_k = Σ_u C(u+k−1, k)·c[u]` for `k = 1..4`. Then `S1 = B1`, `S2 = 2·B2 − S1`, `S3 = 6·B3 − 3·S2 − 2·S1`, `S4 = 24·B4 − 6·S3 − 11·S2 − 6·S1`. Min and max are the first and last non-empty bin. + +**Why it should be exact.** The map counts -> sums is linear. If the chain gives `c·u^k` for every histogram with one non-empty bin `u`, it is right for every histogram, provided nothing overflows. Accumulators are `u128`: the largest, `B_4`, is below `C(259,4)·2^64 < 2^92`. + +**Predictions (each can fail).** +- P1 exactness on a basis: for every code `u` in 0..=255 and counts 1 and 2^40, the chain returns exactly `c·u^k`, `k = 1..4`, min = max = `u`. +- P2 against rows: on random masked populations the result equals sums computed directly from the selected rows in `u128`. +- P3 against the existing fold: `n`, `Σx`, `Σx²` equal `widen_bounded_power_sums(masked_group_bounded_power_sums_u8(..))` with all keys 0, on tiles up to 65,536 rows. +- P4 additivity: counts of pieces add, and the sums from the added counts equal the sums of the whole. +- P5 cost, one group, 65,536 rows, AVX-512 host, release, µs per tile: the count step plus the chain is not slower than the existing bounded register fold on a dense mask. +- P6 the chain itself (256 bins, 5 accumulators) costs under 2 µs. + +**Kill conditions.** +- Any mismatch in P1 to P4: the routine is wrong; nothing ships. +- P5 fails: the route is reported as slower for one group and is not offered as a replacement; higher powers remain its only justification. +- P6 fails: reported with the number. + +**Known limit, stated now.** One histogram is 256 counters per GROUP. For many groups the existing 16-byte register per group is smaller. This slice claims the single-population case only; the group count at which the register wins is not predicted and will be reported if measured. + ## 2026-11-14 — coordinate folds: lane-candidate kernel replaced; the regression was loop shape, not the select - `llvm-objdump` on non-inlined probes of three kernels (merged, lane-candidate, blend+reduce). The lane-candidate and first blend+reduce versions copied each 16-lane group by value (`let lanes = if .. { *lanes } ..`): the group went through the stack (`vmovdqa64 [rsp+..]`), the candidate was compared from memory, and LLVM vectorized the four-groups-per-word bookkeeping into stack stores and reloads. The merged loop compares in place (`vpcmpgtd k0, zmm1, [rax]`). From 018c7df72ef3ec208bfa48eaba9b27d354a11370 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:19:00 +0000 Subject: [PATCH 2/3] simd: power sums and extrema of a u8 lane from per-code counts masked_code_counts_u8 counts selected rows per code. code_power_sums_u8 turns the 256 counts into n, sum x .. sum x^4, min and max with a chain of five accumulators that each add their neighbour; no value is multiplied per row and no lane wider than the u8 codes is read. masked_first_row_of_code_u8 gives the lowest selected row of a code. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XAqKMNPpoyKDKuAgEnu6HU --- crates/simd-masking-parity/src/lib.rs | 35 +++ src/simd.rs | 3 + src/simd_masking_ops.rs | 234 ++++++++++++++ tests/code_power_sums_u8.rs | 433 ++++++++++++++++++++++++++ 4 files changed, 705 insertions(+) create mode 100644 tests/code_power_sums_u8.rs diff --git a/crates/simd-masking-parity/src/lib.rs b/crates/simd-masking-parity/src/lib.rs index 184ad3db..37caac8b 100644 --- a/crates/simd-masking-parity/src/lib.rs +++ b/crates/simd-masking-parity/src/lib.rs @@ -1255,6 +1255,41 @@ fn check_masked_reductions() -> Result<(), u32> { return Err(0x8c0 | k); } } + // Per-code counts, the neighbour-addition power sums and the row of + // a code, against sums and a scan taken directly from the rows. + { + let codes: Vec = vals.iter().map(|v| v.to_le_bytes()[0]).collect(); + let mut counts = [0u64; 256]; + ndarray::simd::masked_code_counts_u8(&codes, m, &mut counts); + let rows: Vec = (0..n) + .filter(|&i| (m[i / 64] >> (i % 64)) & 1 == 1) + .collect(); + let got = ndarray::simd::code_power_sums_u8(&counts); + if rows.is_empty() != got.is_none() { + return Err(0x8d0 | k); + } + if let Some(got) = got { + let mut want = [0u128; 4]; + for &i in &rows { + let x = u128::from(codes[i]); + want[0] += x; + want[1] += x * x; + want[2] += x * x * x; + want[3] += x * x * x * x; + } + let lo = rows.iter().map(|&i| codes[i]).min(); + let hi = rows.iter().map(|&i| codes[i]).max(); + if got.n != rows.len() as u64 || got.sum != want || Some(got.min) != lo || Some(got.max) != hi { + return Err(0x8e0 | k); + } + for code in [got.min, got.max, 0u8] { + let scan = rows.iter().copied().find(|&i| codes[i] == code); + if ndarray::simd::masked_first_row_of_code_u8(&codes, m, code) != scan { + return Err(0x8f0 | k); + } + } + } + } } // The extremes must survive the masked min/max exactly, not saturate. if n > 0 { diff --git a/src/simd.rs b/src/simd.rs index 412d9b3d..b9ae6677 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -1013,6 +1013,8 @@ pub use crate::simd_masking_ops::{ masked_argmax_i32, masked_argmin_i32, masked_argminmax_i32, + masked_code_counts_u8, + masked_first_row_of_code_u8, masked_group_bounded_cross_power_sums_u8, masked_group_bounded_cross_power_sums_u8_pair, masked_group_bounded_cross_power_sums_u8_via, @@ -1082,6 +1084,7 @@ pub use crate::simd_masking_ops::{ // and `flip` laws). /// `(position, value)` of a coordinate fold such as [`masked_argmin_i32`]. pub use crate::simd_masking_ops::ArgI32; +pub use crate::simd_masking_ops::{code_power_sums_u8, CodePowerSums}; pub use crate::simd_masking_ops::{full_add_mask, half_add_mask}; #[cfg(feature = "std")] pub use crate::simd_stride::{lut9, lut_u8, FACET_BYTES}; diff --git a/src/simd_masking_ops.rs b/src/simd_masking_ops.rs index b7063496..61db2453 100644 --- a/src/simd_masking_ops.rs +++ b/src/simd_masking_ops.rs @@ -5930,6 +5930,240 @@ fn masked_fold_i32(values: &[i32], mask_words: &[u64], f: impl Fn(i32, i32) -> i acc } +// ─────────────────────────────────────────────────────────────── +// Power sums and extrema of a `u8` lane from per-code counts +// ─────────────────────────────────────────────────────────────── +// +// The per-row step only counts: `counts[code] += 1`. Everything else is a +// fixed chain of additions over the 256 bins, whatever the row count. +// +// Walk the bins from 255 down to 1 with five accumulators, each adding its +// neighbour: +// +// t1 += c[v]; t2 += t1; t3 += t2; t4 += t3; t5 += t4; +// +// At the end `t2 ..= t5` are `B_k = Σ_u C(u + k − 1, k) · c[u]` for +// `k = 1 ..= 4` (the hockey-stick identity applied `k` times), and +// +// Σx = B1 +// Σx² = 2·B2 − Σx +// Σx³ = 6·B3 − 3·Σx² − 2·Σx +// Σx⁴ = 24·B4 − 6·Σx³ − 11·Σx² − 6·Σx +// +// because `u(u+1) = u² + u`, `u(u+1)(u+2) = u³ + 3u² + 2u` and +// `u(u+1)(u+2)(u+3) = u⁴ + 6u³ + 11u² + 6u`. No value is multiplied per row +// and no lane wider than the `u8` codes is read. The minimum and maximum are +// the first and the last non-empty bin. +// +// The map from counts to sums is linear, so being exact on every histogram +// with a single non-empty bin makes it exact on all of them; the tests check +// exactly that basis. Accumulators are `u128`: the largest, `B4`, stays below +// `C(259, 4) · 2^64 < 2^92`. +// +// One histogram is 256 counters per population. For many groups the 16-byte +// register of `masked_group_bounded_power_sums_u8` is the smaller state. + +/// Add, for every row selected by `mask_words`, one to `counts[values[i]]`. +/// +/// `counts` is accumulated into, so pieces of one lane (tiles, segments) may +/// be counted by repeated calls or by adding their tables. Same bit order and +/// "bits at or past `values.len()` are ignored" contract as +/// [`masked_sum_i32`]. Allocates nothing. +/// +/// # Panics +/// +/// Panics if `mask_words.len() < values.len().div_ceil(64)`. +/// +/// # Examples +/// +/// ``` +/// use ndarray::simd::masked_code_counts_u8; +/// +/// let values = [7u8, 1, 7, 2]; +/// let mut counts = [0u64; 256]; +/// masked_code_counts_u8(&values, &[0b0111], &mut counts); // rows 0, 1, 2 +/// assert_eq!((counts[7], counts[1], counts[2]), (2, 1, 0)); +/// ``` +pub fn masked_code_counts_u8(values: &[u8], mask_words: &[u64], counts: &mut [u64; 256]) { + let words = mask_words_for(values.len()); + assert!( + mask_words.len() >= words, + "masked_code_counts_u8: mask_words.len()={} < required {words}", + mask_words.len() + ); + // Four tables, so that neighbouring rows holding the same code do not + // wait on one counter. `u32` cells are flushed before they can wrap. + let mut part = [[0u32; 256]; 4]; + let mut pending: u32 = 0; + let (blocks, tail) = values.as_chunks::<64>(); + for (w, &word) in mask_words.iter().take(words).enumerate() { + if word == 0 { + continue; + } + if let Some(block) = blocks.get(w) { + if word == u64::MAX { + for quad in block.as_chunks::<4>().0 { + part[0][usize::from(quad[0])] += 1; + part[1][usize::from(quad[1])] += 1; + part[2][usize::from(quad[2])] += 1; + part[3][usize::from(quad[3])] += 1; + } + } else { + let mut bits = word; + while bits != 0 { + let lane = bits.trailing_zeros() as usize; + bits &= bits - 1; + part[lane & 3][usize::from(block[lane])] += 1; + } + } + } else { + // The final partial block: bits past the lane are ignored. + let mut bits = word; + while bits != 0 { + let lane = bits.trailing_zeros() as usize; + bits &= bits - 1; + if let Some(&code) = tail.get(lane) { + part[lane & 3][usize::from(code)] += 1; + } + } + } + pending += 64; + if pending >= 1 << 31 { + flush_code_counts(&mut part, counts); + pending = 0; + } + } + flush_code_counts(&mut part, counts); +} + +/// Add the four partial tables into `counts` and clear them. +#[inline(always)] +fn flush_code_counts(part: &mut [[u32; 256]; 4], counts: &mut [u64; 256]) { + for (code, total) in counts.iter_mut().enumerate() { + *total += + u64::from(part[0][code]) + u64::from(part[1][code]) + u64::from(part[2][code]) + u64::from(part[3][code]); + } + *part = [[0u32; 256]; 4]; +} + +/// Count, first four power sums and extrema of a population of `u8` codes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CodePowerSums { + /// Number of values. + pub n: u64, + /// `sum[k − 1] = Σxᵏ` for `k = 1 ..= 4`, exact. + pub sum: [u128; 4], + /// The smallest code present. + pub min: u8, + /// The largest code present. + pub max: u8, +} + +impl CodePowerSums { + /// The `(n, Σx, Σx²)` record the other power-sum folds produce, or `None` + /// when `Σx` does not fit its `i64` field. + #[inline] + #[must_use] + pub fn power_sums(&self) -> Option { + Some(PowerSums { + n: self.n, + sum: i64::try_from(self.sum[0]).ok()?, + sum_sq: self.sum[1], + }) + } +} + +/// Count, `Σx ..= Σx⁴`, minimum and maximum of the population a table of +/// per-code counts describes, by neighbour additions over the 256 bins (see +/// the section note). `None` for an empty table, or when the counts add up +/// to more than `u64::MAX` rows. +/// +/// # Examples +/// +/// ``` +/// use ndarray::simd::{code_power_sums_u8, masked_code_counts_u8}; +/// +/// let values = [3u8, 2, 100, 255]; +/// let mut counts = [0u64; 256]; +/// masked_code_counts_u8(&values, &[0b1011], &mut counts); // 3, 2 and 255 +/// let s = code_power_sums_u8(&counts).unwrap(); +/// assert_eq!((s.n, s.min, s.max), (3, 2, 255)); +/// assert_eq!(s.sum[0], 3 + 2 + 255); +/// assert_eq!(s.sum[1], 9 + 4 + 65_025); +/// assert_eq!(s.sum[2], 27 + 8 + 16_581_375); +/// ``` +#[must_use] +pub fn code_power_sums_u8(counts: &[u64; 256]) -> Option { + let mut n: u64 = 0; + for &c in counts { + n = n.checked_add(c)?; + } + let min = counts.iter().position(|&c| c != 0)?; + let max = counts.iter().rposition(|&c| c != 0)?; + let (mut t1, mut t2, mut t3, mut t4, mut t5) = (0u128, 0u128, 0u128, 0u128, 0u128); + for &c in counts[1..].iter().rev() { + t1 += u128::from(c); + t2 += t1; + t3 += t2; + t4 += t3; + t5 += t4; + } + let s1 = t2; + let s2 = 2 * t3 - s1; + let s3 = 6 * t4 - 3 * s2 - 2 * s1; + let s4 = 24 * t5 - 6 * s3 - 11 * s2 - 6 * s1; + Some(CodePowerSums { + n, + sum: [s1, s2, s3, s4], + min: min as u8, + max: max as u8, + }) +} + +/// The lowest row selected by `mask_words` whose value equals `code`, or +/// `None`. With `code` the minimum or maximum from [`code_power_sums_u8`] +/// this is the row of that extreme, lowest row on ties. Stops at the first +/// block that holds one. +/// +/// # Panics +/// +/// Panics if `mask_words.len() < values.len().div_ceil(64)`. +/// +/// # Examples +/// +/// ``` +/// use ndarray::simd::masked_first_row_of_code_u8; +/// +/// let values = [7u8, 1, 7, 2]; +/// assert_eq!(masked_first_row_of_code_u8(&values, &[0b1110], 7), Some(2)); +/// assert_eq!(masked_first_row_of_code_u8(&values, &[0b1110], 9), None); +/// ``` +#[must_use] +pub fn masked_first_row_of_code_u8(values: &[u8], mask_words: &[u64], code: u8) -> Option { + let words = mask_words_for(values.len()); + assert!( + mask_words.len() >= words, + "masked_first_row_of_code_u8: mask_words.len()={} < required {words}", + mask_words.len() + ); + let needle = crate::simd::U8x64::splat(code); + let (blocks, tail) = values.as_chunks::<64>(); + for (w, &word) in mask_words.iter().take(words).enumerate() { + if word == 0 { + continue; + } + let hits = if let Some(block) = blocks.get(w) { + crate::simd::U8x64::from_array(*block).cmpeq_mask(needle) & word + } else { + crate::simd::U8x64::from_array(pad_tail(tail)).cmpeq_mask(needle) & word & live64(tail.len()) + }; + if hits != 0 { + return Some(w * 64 + hits.trailing_zeros() as usize); + } + } + None +} + // ─────────────────────────────────────────────────────────────── // Coordinate-bearing extrema: `masked_argmin_i32`, `masked_argmax_i32`, // `masked_argminmax_i32` diff --git a/tests/code_power_sums_u8.rs b/tests/code_power_sums_u8.rs new file mode 100644 index 00000000..837a75f8 --- /dev/null +++ b/tests/code_power_sums_u8.rs @@ -0,0 +1,433 @@ +#![cfg(feature = "std")] +//! Power sums and extrema of a `u8` lane from per-code counts. +//! +//! Predictions P1..P4 are pre-registered; each test names its prediction. +//! The oracle `direct` multiplies in `u128` row by row and calls nothing +//! under test. + +use ndarray::simd::{ + code_power_sums_u8, masked_code_counts_u8, masked_first_row_of_code_u8, masked_group_bounded_power_sums_u8, + widen_bounded_power_sums, CodePowerSums, PowerSums, BOUNDED_TILE_ROWS, +}; + +struct SplitMix64(u64); + +impl SplitMix64 { + fn new() -> Self { + SplitMix64(0x9E37_79B9_7F4A_7C15) + } + + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +fn selected(mask: &[u64], i: usize) -> bool { + (mask[i / 64] >> (i % 64)) & 1 == 1 +} + +/// Independent oracle: `(n, [Σx, Σx², Σx³, Σx⁴], min, max)` over selected rows. +fn direct(values: &[u8], mask: &[u64]) -> Option<(u64, [u128; 4], u8, u8)> { + let mut n = 0u64; + let mut sum = [0u128; 4]; + let mut min = 255u8; + let mut max = 0u8; + for (i, &v) in values.iter().enumerate() { + if !selected(mask, i) { + continue; + } + let x = u128::from(v); + n += 1; + sum[0] += x; + sum[1] += x * x; + sum[2] += x * x * x; + sum[3] += x * x * x * x; + if v < min { + min = v; + } + if v > max { + max = v; + } + } + if n == 0 { + None + } else { + Some((n, sum, min, max)) + } +} + +fn make_mask(rng: &mut SplitMix64, len: usize, kind: usize) -> Vec { + let words = len.div_ceil(64); + (0..words) + .map(|_| match kind { + 0 => u64::MAX, + 1 => rng.next_u64(), + _ => { + let mut w = u64::MAX; + for _ in 0..6 { + w &= rng.next_u64(); + } + w + } + }) + .collect() +} + +fn make_values(rng: &mut SplitMix64, len: usize, kind: usize) -> Vec { + (0..len) + .map(|_| match kind { + 0 => (rng.next_u64() & 0xFF) as u8, + 1 => { + if rng.next_u64() & 1 == 0 { + 0 + } else { + 255 + } + } + _ => 100 + (rng.next_u64() & 3) as u8, + }) + .collect() +} + +fn counted(values: &[u8], mask: &[u64]) -> Option { + let mut counts = [0u64; 256]; + masked_code_counts_u8(values, mask, &mut counts); + code_power_sums_u8(&counts) +} + +fn assert_matches_direct(values: &[u8], mask: &[u64], case: &str) { + let got = counted(values, mask); + let want = direct(values, mask); + match (got, want) { + (None, None) => {} + (Some(g), Some((n, sum, min, max))) => { + assert_eq!(g.n, n, "{case}: n"); + assert_eq!(g.sum, sum, "{case}: sums"); + assert_eq!(g.min, min, "{case}: min"); + assert_eq!(g.max, max, "{case}: max"); + } + (g, w) => panic!("{case}: presence differs, got {g:?} want {w:?}"), + } +} + +fn pow(u: u8, k: u32) -> u128 { + u128::from(u).pow(k) +} + +/// P1: the map from counts to sums is linear, so exactness on every +/// single-bin histogram implies exactness on every table (absent overflow). +#[test] +fn exact_on_every_single_bin_histogram() { + for u in 0..=255u8 { + for &c in &[1u64, 2, 65_536, 1u64 << 40] { + let mut counts = [0u64; 256]; + counts[usize::from(u)] = c; + let s = code_power_sums_u8(&counts).expect("non-empty single-bin table"); + assert_eq!(s.n, c, "P1 code {u} count {c}: n"); + assert_eq!(s.min, u, "P1 code {u} count {c}: min"); + assert_eq!(s.max, u, "P1 code {u} count {c}: max"); + for k in 1..=4u32 { + assert_eq!(s.sum[(k - 1) as usize], u128::from(c) * pow(u, k), "P1 code {u} count {c}: sum[{}]", k - 1); + } + } + } +} + +/// P1b: linearity on random tables, and large counts. +#[test] +fn linearity_on_random_tables() { + let mut rng = SplitMix64::new(); + for case in 0..200 { + let mut counts = [0u64; 256]; + for c in counts.iter_mut() { + if rng.next_u64() & 1 == 0 { + *c = rng.next_u64() & 0xFFFF_FFFF; + } + } + if counts.iter().all(|&c| c == 0) { + counts[(rng.next_u64() & 0xFF) as usize] = 1 + rng.below(1000); + } + let s = code_power_sums_u8(&counts).expect("non-empty table"); + let mut n = 0u64; + let mut sum = [0u128; 4]; + for (u, &c) in counts.iter().enumerate() { + n += c; + for k in 1..=4u32 { + sum[(k - 1) as usize] += u128::from(c) * pow(u as u8, k); + } + } + let first = counts.iter().position(|&c| c != 0).unwrap() as u8; + let last = counts.iter().rposition(|&c| c != 0).unwrap() as u8; + assert_eq!(s.n, n, "P1b random table {case}: n"); + assert_eq!(s.sum, sum, "P1b random table {case}: sums"); + assert_eq!(s.min, first, "P1b random table {case}: min"); + assert_eq!(s.max, last, "P1b random table {case}: max"); + } + + let big = u64::MAX / 256; + let counts = [big; 256]; + let s = code_power_sums_u8(&counts).expect("full table"); + let mut sum = [0u128; 4]; + for u in 0..=255u8 { + for k in 1..=4u32 { + sum[(k - 1) as usize] += u128::from(big) * pow(u, k); + } + } + assert_eq!(s.n, big * 256, "P1b large counts: n"); + assert_eq!(s.sum, sum, "P1b large counts: sums"); + assert_eq!((s.min, s.max), (0, 255), "P1b large counts: extrema"); +} + +/// P2: the count-table route equals the row-by-row oracle. +#[test] +fn matches_direct_sums_over_selected_rows() { + let mut rng = SplitMix64::new(); + let lens = [0usize, 1, 63, 64, 65, 127, 128, 1000, 4097, 65_536, 70_001]; + let mut non_empty = 0; + for case in 0..300 { + let len = lens[(rng.next_u64() % lens.len() as u64) as usize]; + let mk = (rng.next_u64() % 3) as usize; + let vk = (rng.next_u64() % 3) as usize; + let values = make_values(&mut rng, len, vk); + let mask = make_mask(&mut rng, len, mk); + if direct(&values, &mask).is_some() { + non_empty += 1; + } + assert_matches_direct(&values, &mask, &format!("P2 case {case} len {len} mask kind {mk} value kind {vk}")); + } + assert!(non_empty >= 200, "P2 anti-vacuity: only {non_empty} of 300 cases had a selection"); +} + +/// P2b: bits at or past the lane are ignored, and a longer mask is harmless. +#[test] +fn bits_past_the_lane_are_ignored() { + let mut rng = SplitMix64::new(); + let values = make_values(&mut rng, 70, 0); + let mask = [rng.next_u64(), u64::MAX]; + let inside: Vec = vec![mask[0], (1u64 << 6) - 1]; + let want = direct(&values, &inside).expect("rows selected"); + let got = counted(&values, &mask).expect("rows selected"); + assert_eq!(got.n, want.0, "P2b past-lane bits: n"); + assert_eq!(got.sum, want.1, "P2b past-lane bits: sums"); + assert_eq!((got.min, got.max), (want.2, want.3), "P2b past-lane bits: extrema"); + + let longer = [mask[0], mask[1], u64::MAX, u64::MAX]; + let got_long = counted(&values, &longer).expect("rows selected"); + assert_eq!(got_long, got, "P2b longer mask slice changes the result"); +} + +/// P3: agreement with the bounded 16-byte register fold. +#[test] +fn agrees_with_the_bounded_register_fold() { + let mut rng = SplitMix64::new(); + let check = |values: &[u8], mask: &[u64], case: &str| { + let keys = vec![0u32; values.len()]; + let mut regs = [[0u8; 16]; 1]; + masked_group_bounded_power_sums_u8(mask, &keys, values, &mut regs).expect("tile within bound"); + let reg = widen_bounded_power_sums(®s[0]); + match counted(values, mask) { + Some(s) => { + let ps = s.power_sums().expect("sum fits i64 on a bounded tile"); + assert_eq!(ps, reg, "{case}: record differs from the bounded fold"); + } + None => assert_eq!(reg, PowerSums::default(), "{case}: empty selection must widen to default"), + } + }; + for &len in &[1usize, 64, 4096, BOUNDED_TILE_ROWS] { + for mk in 0..3 { + let values = make_values(&mut rng, len, 0); + let mask = make_mask(&mut rng, len, mk); + check(&values, &mask, &format!("P3 len {len} mask kind {mk}")); + } + } + + let worst = vec![255u8; BOUNDED_TILE_ROWS]; + let all = vec![u64::MAX; BOUNDED_TILE_ROWS / 64]; + check(&worst, &all, "P3 worst case 65536 x 255"); + let s = counted(&worst, &all).expect("selected"); + assert_eq!(s.n, BOUNDED_TILE_ROWS as u64, "P3 worst case: n"); + + let values = make_values(&mut rng, 4096, 0); + let none = vec![0u64; 64]; + assert!(counted(&values, &none).is_none(), "P3 empty selection: code route must be None"); + check(&values, &none, "P3 empty selection"); +} + +/// P4: counts of pieces add. +#[test] +fn counts_of_pieces_add() { + let mut rng = SplitMix64::new(); + let len = 200_000usize; + let values = make_values(&mut rng, len, 0); + let mask = make_mask(&mut rng, len, 1); + let cuts = [0usize, 64_000, 128_000, len]; + + let mut whole = [0u64; 256]; + masked_code_counts_u8(&values, &mask, &mut whole); + + let mut chunked = [0u64; 256]; + let mut separate = [[0u64; 256]; 3]; + for p in 0..3 { + let (a, b) = (cuts[p], cuts[p + 1]); + let piece_mask = &mask[a / 64..b.div_ceil(64)]; + masked_code_counts_u8(&values[a..b], piece_mask, &mut chunked); + masked_code_counts_u8(&values[a..b], piece_mask, &mut separate[p]); + } + assert_eq!(chunked, whole, "P4 three calls into one table differ from one call"); + + let mut added = [0u64; 256]; + for t in &separate { + for (a, &c) in added.iter_mut().zip(t.iter()) { + *a += c; + } + } + assert_eq!(added, whole, "P4 three separate tables added bin by bin differ from one call"); + + let want = direct(&values, &mask).expect("selection"); + let s = code_power_sums_u8(&chunked).expect("selection"); + assert_eq!(s.n, want.0, "P4 n"); + assert_eq!(s.sum, want.1, "P4 sums"); + assert_eq!((s.min, s.max), (want.2, want.3), "P4 extrema"); +} + +/// P4b: counting twice doubles everything; extrema stay. +#[test] +fn counts_accumulate_not_overwrite() { + let mut rng = SplitMix64::new(); + let values = make_values(&mut rng, 5000, 0); + let mask = make_mask(&mut rng, 5000, 1); + let mut once = [0u64; 256]; + masked_code_counts_u8(&values, &mask, &mut once); + let mut twice = [0u64; 256]; + masked_code_counts_u8(&values, &mask, &mut twice); + masked_code_counts_u8(&values, &mask, &mut twice); + for u in 0..256 { + assert_eq!(twice[u], 2 * once[u], "P4b bin {u} not doubled"); + } + let a = code_power_sums_u8(&once).expect("selection"); + let b = code_power_sums_u8(&twice).expect("selection"); + assert_eq!(b.n, 2 * a.n, "P4b n"); + for k in 0..4 { + assert_eq!(b.sum[k], 2 * a.sum[k], "P4b sum[{k}]"); + } + assert_eq!((b.min, b.max), (a.min, a.max), "P4b extrema changed"); +} + +fn scan_first(values: &[u8], mask: &[u64], code: u8) -> Option { + (0..values.len()).find(|&i| selected(mask, i) && values[i] == code) +} + +#[test] +fn first_row_finds_the_lowest_selected_row_of_the_code() { + let mut rng = SplitMix64::new(); + let lens = [0usize, 1, 63, 64, 65, 200, 5000]; + for case in 0..300 { + let len = lens[(rng.next_u64() % lens.len() as u64) as usize]; + let mk = (rng.next_u64() % 3) as usize; + let vk = (rng.next_u64() % 3) as usize; + let values = make_values(&mut rng, len, vk); + let mask = make_mask(&mut rng, len, mk); + let mut codes = vec![(rng.next_u64() & 0xFF) as u8]; + if let Some((_, _, min, max)) = direct(&values, &mask) { + codes.push(min); + codes.push(max); + } + for code in codes { + assert_eq!( + masked_first_row_of_code_u8(&values, &mask, code), + scan_first(&values, &mask, code), + "first_row case {case} len {len} mask kind {mk} value kind {vk} code {code}" + ); + } + } + + // Occurs at an unselected lower row and a selected higher row. + let mut values = vec![1u8; 10]; + values[2] = 9; + values[7] = 9; + let mask = [!(1u64 << 2)]; + assert_eq!( + masked_first_row_of_code_u8(&values, &mask, 9), + Some(7), + "first_row: unselected lower row must be skipped" + ); + + // Only in the final partial block. + let mut values = vec![1u8; 100]; + values[99] = 77; + let mask = [u64::MAX, u64::MAX]; + assert_eq!( + masked_first_row_of_code_u8(&values, &mask, 77), + Some(99), + "first_row: code only in the final partial block" + ); + + // Padding bytes are zero but are not rows. + let values = vec![5u8; 70]; + let mask = [u64::MAX, u64::MAX]; + assert_eq!(masked_first_row_of_code_u8(&values, &mask, 0), None, "first_row: padding zeros must not be found"); + let mut values = vec![5u8; 70]; + values[3] = 0; + let mask = [!(1u64 << 3), u64::MAX]; + assert_eq!( + masked_first_row_of_code_u8(&values, &mask, 0), + None, + "first_row: unselected zero and padding zeros must not be found" + ); +} + +#[test] +fn extremes_and_degenerates() { + let empty = [0u64; 256]; + assert!(code_power_sums_u8(&empty).is_none(), "empty table must be None"); + let mut counts = [0u64; 256]; + masked_code_counts_u8(&[], &[], &mut counts); + assert_eq!(counts, empty, "empty lane must leave the table zero"); + assert!(code_power_sums_u8(&counts).is_none(), "empty lane must be None"); + + let values = [42u8, 7, 9]; + let mut counts = [0u64; 256]; + masked_code_counts_u8(&values, &[0b001], &mut counts); + let s = code_power_sums_u8(&counts).expect("one row"); + assert_eq!(s.n, 1, "one row: n"); + assert_eq!((s.min, s.max), (42, 42), "one row: extrema"); + assert_eq!(s.sum[0], 42, "one row: sum"); + + let rows = 65_536usize; + let all255 = vec![255u8; rows]; + let mask = vec![u64::MAX; rows / 64]; + let s = counted(&all255, &mask).expect("selected"); + assert_eq!(s.sum[3], rows as u128 * 255u128.pow(4), "all 255: fourth power sum"); + assert_eq!((s.n, s.min, s.max), (rows as u64, 255, 255), "all 255: n and extrema"); + + let zeros = vec![0u8; rows]; + let s = counted(&zeros, &mask).expect("selected"); + assert_eq!(s.sum, [0u128; 4], "all zeros: every sum zero"); + assert_eq!((s.n, s.min, s.max), (rows as u64, 0, 0), "all zeros: n and extrema"); +} + +#[test] +fn power_sums_record_matches() { + let mut counts = [0u64; 256]; + counts[3] = 10; + counts[200] = 4; + let s = code_power_sums_u8(&counts).expect("non-empty"); + let ps = s.power_sums().expect("small sums fit"); + assert_eq!(ps.n, s.n, "record n"); + assert_eq!(i128::from(ps.sum), s.sum[0] as i128, "record sum is sum[0]"); + assert_eq!(ps.sum_sq, s.sum[1], "record sum_sq is sum[1]"); + + let mut counts = [0u64; 256]; + counts[255] = u64::MAX / 2; + let s = code_power_sums_u8(&counts).expect("table is non-empty"); + assert!(s.sum[0] > i64::MAX as u128, "fixture must exceed i64::MAX"); + assert!(s.power_sums().is_none(), "sum beyond i64 must give None from power_sums"); +} From 95f6091f0f7509060d5b5ac35e5fab0a1224bf4b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:29:53 +0000 Subject: [PATCH 3/3] blackboard: results of the per-code-count power sums against the pre-registration Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XAqKMNPpoyKDKuAgEnu6HU --- .claude/blackboard.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/.claude/blackboard.md b/.claude/blackboard.md index 0a0e0cc9..a418eb7e 100644 --- a/.claude/blackboard.md +++ b/.claude/blackboard.md @@ -1,3 +1,39 @@ +## 2026-11-14 — RESULT: power sums and extrema of a `u8` lane from per-code counts (pre-registered below) + +Functions: `masked_code_counts_u8`, `code_power_sums_u8` (`CodePowerSums`), `masked_first_row_of_code_u8`. + +| prediction | result | +|---|---| +| P1 exact on every single-bin table (256 codes x counts 1, 2, 65,536, 2^40) | holds | +| P1b random tables against `Σ counts[u]·u^k` | holds, 200 tables | +| P2 against sums taken directly from the selected rows | holds, 300 populations, lengths 0 to 70,001, three mask kinds, three value kinds | +| P3 against `masked_group_bounded_power_sums_u8` + `widen_bounded_power_sums` | holds, tiles of 1, 64, 4,096 and 65,536 rows incl. all-255 | +| P4 counts of pieces add | holds, 200,000 rows in 3 pieces | +| P5 not slower than the bounded register fold, one group, dense | holds: 25 to 27 µs against 173 to 175 µs per 65,536 rows | +| P6 chain under 2 µs | holds: 376 to 382 ns | + +Timing, AVX-512 host, release, one group, 65,536 rows, minimum of 7 rounds of 200 calls, three runs, µs per tile: + +| mask | counts + chain | existing `u8` register fold | existing wide `i32` fold | +|---|---|---|---| +| dense | 25.4 to 27.1 | 173.3 to 174.8 | 72.8 to 76.7 | +| half | 31.2 to 31.6 | 82.2 to 84.9 | 43.8 to 45.6 | +| 1 in 64 | 2.35 to 2.55 | 2.48 to 2.58 | 2.80 to 2.81 | + +Chain alone: 376 to 382 ns. Row of the minimum (`masked_first_row_of_code_u8`): 15 to 25 ns dense and half, 130 to 135 ns at 1 in 64. + +Reading the numbers: +- The register fold's 174 µs is its ONE-group case: every row reads and rewrites the same three words, a store-to-load chain. Its own board entry measured 1.095 ns per row with 16 groups (about 72 µs per tile). The comparison here is the single-population case only, as pre-registered. +- The count step is the whole cost (the chain is under 2% of it). It does no multiplication and returns `Σx³`, `Σx⁴`, min and max as well. +- At 1 in 64 the three routes are equal; nothing is gained on sparse masks. +- The group count at which 256 counters per group lose to a 16-byte register was not measured. + +Tests: `tests/code_power_sums_u8.rs`, 10 tests, drafted by a Sonnet worker and run unchanged. Parity rows `0x8d0`, `0x8e0`, `0x8f0`; arms green: native (AVX-512), v3, avx-qemu, v2-qemu, neon-qemu, wasm, wasm-scalar, nightly. + +Disable runs, anchor asserted, exit 101 each (10 of 10): chain link `t3 += t1`; `Σx³` coefficient; `Σx⁴` coefficient; bin 0 included in the chain; tail bound; dense path reads the wrong byte; flush overwrites; max taken from the front; row finder without the mask; row finder without the padding clip. One patch first failed its anchor after `cargo fmt` reflowed the line; it was re-anchored and re-run. + +Not done: no grouped form; no caller in mask-risc or JC yet; `Σxy` is not covered; only the AVX-512 arm was timed. + ## 2026-11-14 — PRE-REGISTRATION: power sums and extrema of a `u8` lane from per-code counts by neighbour addition Written before any code or measurement of this slice.