Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions .claude/blackboard.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,64 @@
## 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.

**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]`).
Expand Down
35 changes: 35 additions & 0 deletions crates/simd-masking-parity/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> = 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<usize> = (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 {
Expand Down
3 changes: 3 additions & 0 deletions src/simd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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};
Expand Down
234 changes: 234 additions & 0 deletions src/simd_masking_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PowerSums> {
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<CodePowerSums> {
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<usize> {
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`
Expand Down
Loading
Loading