diff --git a/.claude/knowledge/pm-stats-probe.md b/.claude/knowledge/pm-stats-probe.md new file mode 100644 index 00000000..c8566b61 --- /dev/null +++ b/.claude/knowledge/pm-stats-probe.md @@ -0,0 +1,92 @@ +# D-PM-STATS: what P×M makes cheaper (probe, 2026-11-25) + +> **READ BY:** anyone proposing a Codec9 / Abakus operation, a P×M reduction +> or compare, or citing P×M performance. +> +> **Status:** MEASURED-LAB on one shared host, two runs per tier. Research +> only. Nothing here is a production API, a kernel, or a layout decision. + +Code: `examples/pm_stats/stats.rs` (the probes), `examples/pm_stats/main.rs` +(bench), `tests/pm_stats.rs` (oracles). Composed from existing +`ndarray::simd` words only. Base: ndarray master `a6b6c05`. + +## What carries the result + +An untouched lane has `M = 0`, so it contributes nothing to `Σx`, `Σ|x|`, +`Σx²` or `Σxy`. **Only the count `N` needs `touched`.** No sum, power sum or +product needs a validity filter; `x²` and `|x|` need no polarity at all. + +## Contracts and oracles + +| Probe | Contract | Oracle | +|---|---|---| +| Stats | `N` selected touched, `S = Σx`, `Q = Σx²`, `A = Σ|x|`; variance as the exact rational `(N·Q − S², N²)`, `None` for an empty population | exact scalar fold; boundary blocks: all untouched, only `+0`, full cancellation, nearly constant (63/4096) | +| Compare | `lt`, `le`, `eq` three-valued (`is`, `unknown`); `lt_const` for `x < c` | every 512 × 512 codeword pair; every constant −255..=255 | +| Select | `min`, `max`, untouched where either operand is | every 512 × 512 pair | +| Products | `Σxy`, as `Σ_same − Σ_opp` and as `Σ_all − 2Σ_opp` | every 512 × 512 pair, whole and per block | + +11 tests, green on AVX-512 and on the v3 (AVX2) tier. NEON and wasm were not +run. + +Disable runs, each red: `lt` ignoring polarity (2 tests), `lt` without the +known mask (1), `N` from P alone (3), arm B ignoring polarity (1), `prod_sum` +dropping its high byte (5), the dot product ignoring polarity (1), `x < 0` +without the touched check (1). + +## Measured (ns per 64 lanes, best of 7; two runs, shared host) + +The run-to-run spread is large on this host (some cells move 2–3×). Read the +ranges, not the digits. The i16 sum and stats baselines are scalar loops the +compiler did not vectorize well; the compare baseline is a real `I16x32` SIMD +loop, and the sum baseline is the library's `masked_sum_i32`. + +**Signed sum S, 64K lanes** + +| | split | `ΣM − 2ΣM⁻` | `masked_sum_i32` | +|---|---|---|---| +| AVX-512 | 2.9–3.9, flat over density and mix | 4.0 | 1.7 at ≤1% selected, 5.7 at 10%, 12 at ≥50% | +| AVX2 | 9.8–21 | 8.4–13.7 | 1.7–4 at ≤1%, 9–20 dense | + +- P×M cost is independent of selection density and polarity mix. `masked_sum_i32` walks set bits, so it wins below roughly 1–10% density and loses 3–4× when dense. +- **`ΣM − 2ΣM⁻` is slower on AVX-512 and faster on AVX2.** The better form is ISA-dependent; neither is universally cheaper. + +**All four statistics, 50% selection:** AVX-512 12–18 at every working set +(64, 64K, 16M lanes), against the scalar i16 loop at 41–51. On AVX2 there is +no win: 44–47 against 40–48. `prod_sum` (for `Q`) is the cost there; the +AVX2 `U16x32` is two halves. + +**`a < b`:** 3.5–4.5 against `I16x32` at 3.1–4.2 when L2-resident (AVX2: +4.95 against 3.08, P×M slower). At 16M lanes 5.3–17 against 12–20; the gap +there is bytes. **`x < 0`** is one `cmpeq`: 1.7–1.9. + +**Dot product:** AVX-512 16–17 against 11–15 L2-resident (no win), 20–25 +against 26–32 at 16M lanes (win, bandwidth). **AVX2: 59–61 against 11–30, a +large loss.** + +## What this establishes + +- The strongest fruit is the **statistical fold** on AVX-512: N, S, Q, A in one pass, density-independent, no decode, no validity prefilter. +- **Signed comparison is not cheaper in ALU work.** It costs about the same as an `I16x32` compare and wins only when memory-bound. **`x < 0` is genuinely cheaper.** +- **The dot product is not cheaper in ALU work**, and is much worse on AVX2. Its only win is bandwidth at large working sets on AVX-512. +- Every advantage measured here comes from **bytes (72 vs 128–256 per 64 lanes) or from density-independence**, not from fewer instructions. The exception is `x < 0`. + +## Not measured, or not established + +- Instruction sequences: the arms inlined, and no disassembly was captured. +- Hot vs cold beyond working-set size; latency vs throughput (only throughput loops). +- NEON, wasm, AVX-only and v2 tiers. +- Allocations: the arms allocate nothing per block, but this was read, not instrumented. +- Wider widths (PM17/25/33) and widened accumulators: not probed. +- Composition across sealed DR tiles: N, S, Q, A add across tiles, but no tile fold was built. + +## Reusable primitive inventory + +`U8x64::{mask_blend, cmpgt_mask, cmpeq_mask, sum_bytes_u64}`, +`U16x32::{from_u8x64_lo, from_u8x64_hi, mullo, shr, shl, Sub, +pack_saturate_u8}` (lane-order preserving), `abakus::pm::touched`, +`I16x32::cmp_gt`. `masked_group_bounded_power_sums_u8` is a scalar keyed +fold (`group_walk`, one row at a time), not a SIMD kernel. + +Missing and worth naming: a vertical byte-sum accumulator. `sum_bytes_u64` +reduces horizontally on every call; a fold that kept the `U64x8` partials +across blocks would pay one horizontal reduction per tile. diff --git a/Cargo.toml b/Cargo.toml index eb9de081..5292d2c2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,6 +85,11 @@ name = "add_pm" path = "examples/add_pm/main.rs" required-features = ["std"] +[[example]] +name = "pm_stats" +path = "examples/pm_stats/main.rs" +required-features = ["std"] + [[example]] name = "u9_abacus" path = "examples/u9_abacus/main.rs" diff --git a/examples/pm_stats/main.rs b/examples/pm_stats/main.rs new file mode 100644 index 00000000..9a254bb7 --- /dev/null +++ b/examples/pm_stats/main.rs @@ -0,0 +1,277 @@ +//! D-PM-STATS: cost of `P × M` statistical folds, signed comparison and +//! sign-partitioned products, against conventional signed lanes with an +//! equal-semantics validity plane. Correctness lives in `tests/pm_stats.rs`. +//! +//! cargo run --release --example pm_stats --features std +//! +//! Reports ns per 64 lanes (best of several timed repetitions). The tier is +//! whatever this build targets; the header prints it. +#[allow(dead_code)] +mod stats; + +use std::hint::black_box; +use std::time::Instant; + +use ndarray::hpc::abakus::pm::Pm; +use ndarray::simd::masked_sum_i32; +use stats::*; + +struct Data { + mags: Vec, + pos: Vec, + sel: Vec, + /// The same values as `i16` and `i32`, with a validity plane already + /// intersected with the selection (the baseline gets that for free). + v16: Vec, + v32: Vec, + live: Vec, +} + +fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s +} + +#[derive(Clone, Copy)] +enum Mix { + Mixed, + Positive, + Untouched, +} + +fn data(blocks: usize, density_pct: u64, mix: Mix, seed: u64) -> Data { + let mut s = seed; + let n = blocks * 64; + let (mut mags, mut v16, mut v32) = (vec![0u8; n], vec![0i16; n], vec![0i32; n]); + let (mut pos, mut sel, mut live) = (vec![0u64; blocks], vec![0u64; blocks], vec![0u64; blocks]); + for b in 0..blocks { + for j in 0..64 { + let i = b * 64 + j; + let r = xorshift(&mut s); + let (m, p) = match mix { + Mix::Mixed => ((r % 256) as u8, r >> 9 & 1 == 1), + Mix::Positive => ((r % 256) as u8, true), + Mix::Untouched => (0, false), + }; + let picked = xorshift(&mut s) % 100 < density_pct; + mags[i] = m; + pos[b] |= u64::from(p) << j; + sel[b] |= u64::from(picked) << j; + let touched = p || m != 0; + let v = if p { i16::from(m) } else { -i16::from(m) }; + v16[i] = v; + v32[i] = i32::from(v); + live[b] |= u64::from(picked && touched) << j; + } + } + Data { + mags, + pos, + sel, + v16, + v32, + live, + } +} + +/// Best ns per 64 lanes over `reps` timed passes of `f`. +fn time(blocks: usize, mut f: impl FnMut() -> R) -> f64 { + let passes = (1usize << 22).div_ceil(blocks * 64).max(1); + let mut best = f64::MAX; + for _ in 0..7 { + let t = Instant::now(); + for _ in 0..passes { + black_box(f()); + } + let ns = t.elapsed().as_nanos() as f64 / (passes * blocks) as f64; + best = best.min(ns); + } + best +} + +// ---------- the arms ---------- + +fn s_split(d: &Data) -> i64 { + let mut s = 0i64; + for (b, &m) in d.sel.iter().enumerate() { + let x = block_at(&d.mags, &d.pos, b); + s += msum(m & x.pos, x.mag) as i64 - msum(m & !x.pos, x.mag) as i64; + } + s +} + +fn s_total_minus_neg(d: &Data) -> i64 { + let mut s = 0i64; + for (b, &m) in d.sel.iter().enumerate() { + let x = block_at(&d.mags, &d.pos, b); + s += msum(m, x.mag) as i64 - 2 * msum(m & !x.pos, x.mag) as i64; + } + s +} + +fn s_i32(d: &Data) -> i64 { + masked_sum_i32(&d.v32, &d.live) +} + +fn s_i16(d: &Data) -> i64 { + let mut s = 0i64; + for (b, &m) in d.live.iter().enumerate() { + for j in 0..64 { + s += i64::from(d.v16[b * 64 + j]) * (m >> j & 1) as i64; + } + } + s +} + +fn all_i16(d: &Data) -> Stats { + let mut st = Stats::default(); + for (b, &m) in d.live.iter().enumerate() { + for j in 0..64 { + let k = (m >> j & 1) as i64; + let v = i64::from(d.v16[b * 64 + j]); + st.n += k as u64; + st.s += v * k; + st.q += (v * v * k) as u64; + st.a += (v.abs() * k) as u64; + } + } + st +} + +fn lt_pm(d: &Data, e: &Data) -> u32 { + let mut c = 0; + for b in 0..d.sel.len() { + c += lt(block_at(&d.mags, &d.pos, b), block_at(&e.mags, &e.pos, b)) + .is + .count_ones(); + } + c +} + +fn lt_zero_pm(d: &Data) -> u32 { + (0..d.sel.len()) + .map(|b| lt_const(block_at(&d.mags, &d.pos, b), 0).is.count_ones()) + .sum() +} + +fn lt_i16(d: &Data, e: &Data) -> u32 { + let mut c = 0; + for b in 0..d.live.len() { + let both = d.live[b] & e.live[b]; + let mut r = 0u64; + for j in 0..64 { + r |= u64::from(d.v16[b * 64 + j] < e.v16[b * 64 + j]) << j; + } + c += (r & both).count_ones(); + } + c +} + +/// The fair SIMD baseline: two `I16x32` compares per 64 lanes. +fn lt_i16_simd(d: &Data, e: &Data) -> u32 { + use ndarray::simd::I16x32; + let mut c = 0; + for b in 0..d.live.len() { + let at = |v: &[i16], h: usize| I16x32::from_slice(&v[b * 64 + h * 32..b * 64 + h * 32 + 32]); + let lo = at(&e.v16, 0).cmp_gt(at(&d.v16, 0)); + let hi = at(&e.v16, 1).cmp_gt(at(&d.v16, 1)); + c += ((u64::from(lo) | u64::from(hi) << 32) & d.live[b] & e.live[b]).count_ones(); + } + c +} + +fn dot_pm(d: &Data, e: &Data) -> i64 { + let mut s = 0i64; + for b in 0..d.sel.len() { + let (x, y) = (block_at(&d.mags, &d.pos, b), block_at(&e.mags, &e.pos, b)); + s += dot_total_minus_twice_opp(&[x], &[y], &[u64::MAX]); + } + s +} + +fn dot_i16(d: &Data, e: &Data) -> i64 { + let mut s = 0i64; + for i in 0..d.v16.len() { + s += i64::from(d.v16[i]) * i64::from(e.v16[i]); + } + s +} + +fn main() { + println!( + "D-PM-STATS avx512f={} avx2={} (ns per 64 lanes, best of 7)", + cfg!(target_feature = "avx512f"), + cfg!(target_feature = "avx2") + ); + // Bytes per 64 lanes each arm reads. + println!("bytes/64: P×M 72 (+8 sel) | i16 128 (+8 live) | i32 256 (+8 live)\n"); + + println!("[1] signed sum S, 1024 blocks (64K lanes), by density and polarity mix"); + println!( + "{:<10} {:>4} {:>8} {:>8} {:>8} {:>8} {:>8}", + "mix", "sel%", "split", "M-2neg", "foldS", "i32lib", "i16" + ); + for (name, mix) in [("mixed", Mix::Mixed), ("positive", Mix::Positive), ("untouched", Mix::Untouched)] { + for dens in [0, 1, 10, 50, 100] { + let d = data(1024, dens, mix, 7); + let want = s_i16(&d); + assert_eq!((s_split(&d), s_total_minus_neg(&d), s_i32(&d)), (want, want, want)); + assert_eq!(fold_soa(&d.mags, &d.pos, &d.sel, Demand::SUM).s, want); + println!( + "{:<10} {:>4} {:>8.2} {:>8.2} {:>8.2} {:>8.2} {:>8.2}", + name, + dens, + time(1024, || s_split(&d)), + time(1024, || s_total_minus_neg(&d)), + time(1024, || fold_soa(&d.mags, &d.pos, &d.sel, Demand::SUM).s), + time(1024, || s_i32(&d)), + time(1024, || s_i16(&d)), + ); + } + } + + println!("\n[1] all four statistics (N, S, Q, A), mixed, 50% selection, by working set"); + println!("{:<12} {:>10} {:>10}", "lanes", "fold", "i16"); + for blocks in [1usize, 1024, 262_144] { + let d = data(blocks, 50, Mix::Mixed, 9); + assert_eq!(fold_soa(&d.mags, &d.pos, &d.sel, Demand::ALL), all_i16(&d)); + println!( + "{:<12} {:>10.2} {:>10.2}", + blocks * 64, + time(blocks, || fold_soa(&d.mags, &d.pos, &d.sel, Demand::ALL)), + time(blocks, || all_i16(&d)), + ); + } + + println!("\n[2] a < b and x < 0, mixed, 100% selection"); + println!("{:<12} {:>10} {:>10} {:>10} {:>10}", "lanes", "lt P×M", "lt i16simd", "lt i16loop", "x<0 P×M"); + for blocks in [1024usize, 262_144] { + let (d, e) = (data(blocks, 100, Mix::Mixed, 3), data(blocks, 100, Mix::Mixed, 4)); + assert_eq!(lt_pm(&d, &e), lt_i16(&d, &e)); + assert_eq!(lt_pm(&d, &e), lt_i16_simd(&d, &e)); + println!( + "{:<12} {:>10.2} {:>10.2} {:>10.2} {:>10.2}", + blocks * 64, + time(blocks, || lt_pm(&d, &e)), + time(blocks, || lt_i16_simd(&d, &e)), + time(blocks, || lt_i16(&d, &e)), + time(blocks, || lt_zero_pm(&d)), + ); + } + + println!("\n[3] signed dot product, mixed, all lanes"); + println!("{:<12} {:>10} {:>10}", "lanes", "P×M", "i16"); + for blocks in [1024usize, 262_144] { + let (d, e) = (data(blocks, 100, Mix::Mixed, 5), data(blocks, 100, Mix::Mixed, 6)); + assert_eq!(dot_pm(&d, &e), dot_i16(&d, &e)); + println!( + "{:<12} {:>10.2} {:>10.2}", + blocks * 64, + time(blocks, || dot_pm(&d, &e)), + time(blocks, || dot_i16(&d, &e)), + ); + } + let _: Option = None; +} diff --git a/examples/pm_stats/stats.rs b/examples/pm_stats/stats.rs new file mode 100644 index 00000000..27010fea --- /dev/null +++ b/examples/pm_stats/stats.rs @@ -0,0 +1,289 @@ +//! D-PM-STATS probes over `P × M` blocks (`abakus::pm`): statistical folds, +//! signed comparison and selection, and sign-partitioned products. +//! +//! Research only. Everything is composed from existing `ndarray::simd` words; +//! no new kernel, API or layout. Correctness lives in `tests/pm_stats.rs`. +//! +//! The observation the folds rest on: an untouched lane has `M = 0`, so it +//! adds nothing to a sum of magnitudes, of signed values, of squares or of +//! products. Only the count `N` needs `touched`; nothing else needs a validity +//! filter. + +use ndarray::hpc::abakus::pm::{touched, Pm}; +use ndarray::simd::{U16x32, U8x64}; + +/// Sum of the magnitudes in `mask`'s lanes (`vpsadbw` on AVX-512). +#[inline(always)] +pub fn msum(mask: u64, m: U8x64) -> u64 { + U8x64::mask_blend(mask, U8x64::splat(0), m).sum_bytes_u64() +} + +/// `Σ (a_i · b_i)` over 64 lanes, exact: products are at most 255² and fit a +/// `u16` lane; each product is split into its two bytes so the byte sums stay +/// within `sum_bytes_u64`'s range. +#[inline(always)] +pub fn prod_sum(a: U8x64, b: U8x64) -> u64 { + let lo = U16x32::from_u8x64_lo(a).mullo(U16x32::from_u8x64_lo(b)); + let hi = U16x32::from_u8x64_hi(a).mullo(U16x32::from_u8x64_hi(b)); + let (lo_h, hi_h) = (lo.shr(8), hi.shr(8)); + let (lo_l, hi_l) = (lo - lo_h.shl(8), hi - hi_h.shl(8)); + let low = lo_l.pack_saturate_u8(hi_l).sum_bytes_u64(); + let high = lo_h.pack_saturate_u8(hi_h).sum_bytes_u64(); + low + (high << 8) +} + +// ---------- Probe 1: sufficient statistics ---------- + +/// Which statistics a caller demands. +#[derive(Clone, Copy, Debug)] +pub struct Demand { + pub n: bool, + pub s: bool, + pub q: bool, + pub a: bool, +} + +impl Demand { + pub const ALL: Demand = Demand { + n: true, + s: true, + q: true, + a: true, + }; + pub const SUM: Demand = Demand { + n: false, + s: true, + q: false, + a: false, + }; +} + +/// `N` selected touched values, `S = Σx`, `Q = Σx²`, `A = Σ|x|`. Fields not +/// demanded stay 0. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + pub n: u64, + pub s: i64, + pub q: u64, + pub a: u64, +} + +/// Arm A: positive and negative magnitudes reduced separately. +pub fn sum_split(xs: &[Pm], sel: &[u64]) -> i64 { + let mut s = 0i64; + for (x, &m) in xs.iter().zip(sel) { + s += msum(m & x.pos, x.mag) as i64 - msum(m & !x.pos, x.mag) as i64; + } + s +} + +/// Arm B: `S = Σ M − 2 Σ M_negative`. +pub fn sum_total_minus_twice_neg(xs: &[Pm], sel: &[u64]) -> i64 { + let mut s = 0i64; + for (x, &m) in xs.iter().zip(sel) { + s += msum(m, x.mag) as i64 - 2 * msum(m & !x.pos, x.mag) as i64; + } + s +} + +/// Arm C: one fold computing only the demanded statistics. `A` is shared by +/// `S` (arm B's form) when both are demanded. +pub fn fold(xs: &[Pm], sel: &[u64], d: Demand) -> Stats { + let mut st = Stats::default(); + for (x, &m) in xs.iter().zip(sel) { + fold_block(*x, m, d, &mut st); + } + st +} + +/// One block of [`fold`]. +#[inline(always)] +pub fn fold_block(x: Pm, m: u64, d: Demand, st: &mut Stats) { + if d.n { + st.n += u64::from((m & touched(x)).count_ones()); + } + if d.s || d.a { + let a = msum(m, x.mag); + if d.a { + st.a += a; + } + if d.s { + st.s += a as i64 - 2 * msum(m & !x.pos, x.mag) as i64; + } + } + if d.q { + let mb = U8x64::mask_blend(m, U8x64::splat(0), x.mag); + st.q += prod_sum(mb, mb); + } +} + +/// The register shape a source lends: a `u8` magnitude slab and its `u64` +/// polarity plane, 64 lanes per word. Reads each block in place. +#[inline(always)] +pub fn block_at(mags: &[u8], pos: &[u64], b: usize) -> Pm { + Pm { + mag: U8x64::from_slice(&mags[b * 64..b * 64 + 64]), + pos: pos[b], + } +} + +/// [`fold`] over the borrowed slab and plane. +pub fn fold_soa(mags: &[u8], pos: &[u64], sel: &[u64], d: Demand) -> Stats { + let mut st = Stats::default(); + for (b, &m) in sel.iter().enumerate() { + fold_block(block_at(mags, pos, b), m, d, &mut st); + } + st +} + +/// Population variance as an exact rational `(N·Q − S², N²)`; `None` for an +/// empty population. Exact in `i128` for any population this probe folds. +pub fn variance_parts(st: Stats) -> Option<(i128, i128)> { + if st.n == 0 { + return None; + } + let n = i128::from(st.n); + Some((n * i128::from(st.q) - i128::from(st.s) * i128::from(st.s), n * n)) +} + +// ---------- Probe 2: signed comparison and selection ---------- + +/// A three-valued comparison: lanes where it holds, and lanes it cannot +/// decide because an operand is untouched. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cmp { + pub is: u64, + pub unknown: u64, +} + +/// `a < b`: two unsigned magnitude compares, then mask logic on polarity. +#[inline(always)] +pub fn lt(a: Pm, b: Pm) -> Cmp { + let known = touched(a) & touched(b); + let gab = a.mag.cmpgt_mask(b.mag); + let gba = b.mag.cmpgt_mask(a.mag); + let r = (!a.pos & b.pos) | (a.pos & b.pos & gba) | (!a.pos & !b.pos & gab); + Cmp { + is: r & known, + unknown: !known, + } +} + +/// Numerical `a = b`. `+0` has one code, so on touched lanes this equals +/// codeword identity; two untouched lanes are unknown, not equal. +#[inline(always)] +pub fn eq(a: Pm, b: Pm) -> Cmp { + let known = touched(a) & touched(b); + let r = !(a.pos ^ b.pos) & a.mag.cmpeq_mask(b.mag); + Cmp { + is: r & known, + unknown: !known, + } +} + +#[inline(always)] +pub fn le(a: Pm, b: Pm) -> Cmp { + let (l, e) = (lt(a, b), eq(a, b)); + Cmp { + is: l.is | e.is, + unknown: l.unknown, + } +} + +/// `x < c` for a constant: one magnitude compare plus `touched`, or for +/// `c = 0` a single `cmpeq` (`x < 0` is exactly `!P ∧ M ≠ 0`). +#[inline(always)] +pub fn lt_const(x: Pm, c: i16) -> Cmp { + let t = touched(x); + let r = if c > 0 { + !x.pos | (x.pos & U8x64::splat(c as u8).cmpgt_mask(x.mag)) + } else if c == 0 { + !x.pos + } else { + !x.pos & x.mag.cmpgt_mask(U8x64::splat((-c) as u8)) + }; + Cmp { is: r & t, unknown: !t } +} + +/// The smaller of `a` and `b`, untouched where either is untouched. +#[inline(always)] +pub fn min(a: Pm, b: Pm) -> Pm { + pick(lt(a, b), a, b) +} + +/// The larger of `a` and `b`, untouched where either is untouched. +#[inline(always)] +pub fn max(a: Pm, b: Pm) -> Pm { + pick(lt(b, a), a, b) +} + +/// `a` where `c.is`, else `b`; untouched where `c.unknown`. +#[inline(always)] +fn pick(c: Cmp, a: Pm, b: Pm) -> Pm { + let mag = U8x64::mask_blend(c.is, b.mag, a.mag); + let mag = U8x64::mask_blend(c.unknown, mag, U8x64::splat(0)); + let pos = ((c.is & a.pos) | (!c.is & b.pos)) & !c.unknown; + Pm { mag, pos } +} + +// ---------- Probe 3: sign-partitioned products ---------- + +/// `Σ a·b` over the selected lanes, split by product polarity: +/// `Σ_same Ma·Mb − Σ_opposite Ma·Mb`. +pub fn dot_split(a: &[Pm], b: &[Pm], sel: &[u64]) -> i64 { + let mut d = 0i64; + for ((x, y), &m) in a.iter().zip(b).zip(sel) { + let same = m & !(x.pos ^ y.pos); + let opp = m & (x.pos ^ y.pos); + let z = U8x64::splat(0); + d += prod_sum(U8x64::mask_blend(same, z, x.mag), y.mag) as i64 + - prod_sum(U8x64::mask_blend(opp, z, x.mag), y.mag) as i64; + } + d +} + +/// The same as `Σ_all − 2 Σ_opposite`, mirroring probe 1's arm B. +pub fn dot_total_minus_twice_opp(a: &[Pm], b: &[Pm], sel: &[u64]) -> i64 { + let mut d = 0i64; + for ((x, y), &m) in a.iter().zip(b).zip(sel) { + let opp = m & (x.pos ^ y.pos); + let z = U8x64::splat(0); + d += prod_sum(U8x64::mask_blend(m, z, x.mag), y.mag) as i64 + - 2 * prod_sum(U8x64::mask_blend(opp, z, x.mag), y.mag) as i64; + } + d +} + +// ---------- shared helpers for the oracle and baselines ---------- + +/// Codeword `c` in `0..512`: magnitude `c & 255`, polarity bit 8. +pub fn value_of(c: u16) -> Option { + let (m, p) = (i32::from(c & 0xff), c >> 8 & 1 == 1); + match (p, m) { + (false, 0) => None, + (true, m) => Some(m), + (false, m) => Some(-m), + } +} + +pub fn block_of(codes: &[u16]) -> Pm { + let mut mag = [0u8; 64]; + let mut pos = 0u64; + for (i, &c) in codes.iter().enumerate() { + mag[i] = (c & 0xff) as u8; + pos |= u64::from(c >> 8 & 1) << i; + } + Pm { + mag: U8x64::from_array(mag), + pos, + } +} + +pub fn lane(x: Pm, i: usize) -> Option { + let m = i32::from(x.mag.to_array()[i]); + match (x.pos >> i & 1 == 1, m) { + (false, 0) => None, + (true, m) => Some(m), + (false, m) => Some(-m), + } +} diff --git a/tests/pm_stats.rs b/tests/pm_stats.rs new file mode 100644 index 00000000..5b6f190d --- /dev/null +++ b/tests/pm_stats.rs @@ -0,0 +1,261 @@ +#![cfg(feature = "std")] +#![allow(clippy::needless_range_loop)] +//! D-PM-STATS probes (`examples/pm_stats/stats.rs`) against independent +//! scalar oracles: every 512 × 512 codeword pair for comparison, selection and +//! products; random and boundary blocks for the statistical folds. + +#[path = "../examples/pm_stats/stats.rs"] +#[allow(dead_code)] +mod stats; + +use ndarray::hpc::abakus::pm::Pm; +use stats::*; + +/// One block of operand pairs with the codewords it was built from. +type PairBlock = (Pm, Pm, [(u16, u16); 64]); + +/// Every (a, b) codeword pair, 64 pairs to a block. +fn all_pairs() -> Vec { + let codes: Vec<(u16, u16)> = (0..512u16) + .flat_map(|a| (0..512u16).map(move |b| (a, b))) + .collect(); + codes + .chunks(64) + .map(|ch| { + let mut pairs = [(0u16, 0u16); 64]; + pairs.copy_from_slice(ch); + let a: Vec = ch.iter().map(|p| p.0).collect(); + let b: Vec = ch.iter().map(|p| p.1).collect(); + (block_of(&a), block_of(&b), pairs) + }) + .collect() +} + +fn bit(m: u64, i: usize) -> bool { + m >> i & 1 == 1 +} + +// ---------- Probe 2: comparison and selection, exhaustive ---------- + +#[test] +fn comparisons_match_the_oracle_on_every_codeword_pair() { + let mut checked = 0usize; + for (a, b, pairs) in all_pairs() { + let (l, e, q) = (lt(a, b), eq(a, b), le(a, b)); + for i in 0..64 { + let (va, vb) = (value_of(pairs[i].0), value_of(pairs[i].1)); + match (va, vb) { + (Some(x), Some(y)) => { + assert!(!bit(l.unknown, i)); + assert_eq!(bit(l.is, i), x < y, "lt {x} {y}"); + assert_eq!(bit(e.is, i), x == y, "eq {x} {y}"); + assert_eq!(bit(q.is, i), x <= y, "le {x} {y}"); + } + _ => { + assert!(bit(l.unknown, i) && bit(e.unknown, i), "{va:?} {vb:?} must be unknown"); + assert!(!bit(l.is, i) && !bit(e.is, i) && !bit(q.is, i)); + } + } + checked += 1; + } + } + assert_eq!(checked, 512 * 512); +} + +#[test] +fn min_and_max_match_the_oracle_on_every_codeword_pair() { + for (a, b, pairs) in all_pairs() { + let (lo, hi) = (min(a, b), max(a, b)); + for i in 0..64 { + let (va, vb) = (value_of(pairs[i].0), value_of(pairs[i].1)); + let want = va.zip(vb); + assert_eq!(lane(lo, i), want.map(|(x, y)| x.min(y)), "min {va:?} {vb:?}"); + assert_eq!(lane(hi, i), want.map(|(x, y)| x.max(y)), "max {va:?} {vb:?}"); + } + } +} + +/// A constant comparison takes its own path; it must agree with the general +/// two-operand one for every codeword and every constant in range. +#[test] +fn constant_comparison_agrees_with_the_oracle() { + let codes: Vec = (0..512).collect(); + for c in -255i16..=255 { + for ch in codes.chunks(64) { + let x = block_of(ch); + let r = lt_const(x, c); + for (i, &code) in ch.iter().enumerate() { + match value_of(code) { + Some(v) => { + assert!(!bit(r.unknown, i)); + assert_eq!(bit(r.is, i), v < i32::from(c), "{v} < {c}"); + } + None => assert!(bit(r.unknown, i) && !bit(r.is, i)), + } + } + } + } +} + +/// Numerical equality is not codeword identity for untouched lanes: two +/// untouched operands are unknown, never equal. +#[test] +fn two_untouched_lanes_are_unknown_not_equal() { + let u = block_of(&[0u16; 64]); + let e = eq(u, u); + assert_eq!((e.is, e.unknown), (0, u64::MAX)); + let z = block_of(&[256u16; 64]); // +0 everywhere + assert_eq!(eq(z, z).is, u64::MAX, "+0 = +0"); +} + +// ---------- Probe 3: products, exhaustive ---------- + +#[test] +fn sign_partitioned_products_match_the_oracle_on_every_codeword_pair() { + let blocks = all_pairs(); + let a: Vec = blocks.iter().map(|t| t.0).collect(); + let b: Vec = blocks.iter().map(|t| t.1).collect(); + let sel = vec![u64::MAX; a.len()]; + let want: i64 = blocks + .iter() + .flat_map(|t| t.2.iter()) + .filter_map(|&(x, y)| Some(i64::from(value_of(x)?) * i64::from(value_of(y)?))) + .sum(); + assert_eq!(dot_split(&a, &b, &sel), want); + assert_eq!(dot_total_minus_twice_opp(&a, &b, &sel), want); + // Per block too: one-sided errors could cancel in the total. + for t in &blocks { + let w: i64 = + t.2.iter() + .filter_map(|&(x, y)| Some(i64::from(value_of(x)?) * i64::from(value_of(y)?))) + .sum(); + assert_eq!(dot_split(&[t.0], &[t.1], &[u64::MAX]), w); + } +} + +#[test] +fn prod_sum_is_exact_at_the_magnitude_bound() { + use ndarray::simd::U8x64; + let m = U8x64::splat(255); + assert_eq!(prod_sum(m, m), 64 * 255 * 255); +} + +// ---------- Probe 1: statistical folds ---------- + +fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s +} + +fn random_blocks(n: usize, seed: u64) -> (Vec, Vec, Vec<[u16; 64]>) { + let mut s = seed; + let mut xs = Vec::new(); + let mut sel = Vec::new(); + let mut codes = Vec::new(); + for _ in 0..n { + let mut c = [0u16; 64]; + for v in &mut c { + *v = (xorshift(&mut s) % 512) as u16; + } + xs.push(block_of(&c)); + sel.push(xorshift(&mut s)); + codes.push(c); + } + (xs, sel, codes) +} + +fn oracle(sel: &[u64], codes: &[[u16; 64]]) -> Stats { + let mut st = Stats::default(); + for (m, c) in sel.iter().zip(codes) { + for i in 0..64 { + if bit(*m, i) { + if let Some(v) = value_of(c[i]) { + st.n += 1; + st.s += i64::from(v); + st.q += (i64::from(v) * i64::from(v)) as u64; + st.a += u64::from(v.unsigned_abs()); + } + } + } + } + st +} + +#[test] +fn statistics_match_the_oracle_on_random_blocks() { + for seed in 1..=8u64 { + let (xs, sel, codes) = random_blocks(257, seed); + let want = oracle(&sel, &codes); + assert_eq!(fold(&xs, &sel, Demand::ALL), want, "seed {seed}"); + assert_eq!(sum_split(&xs, &sel), want.s); + assert_eq!(sum_total_minus_twice_neg(&xs, &sel), want.s); + } +} + +/// The slab-and-plane form reads the same blocks as the `Pm` form. +#[test] +fn fold_over_the_lent_slab_equals_the_block_fold() { + let (xs, sel, codes) = random_blocks(65, 5); + let mut mags = Vec::new(); + let mut pos = Vec::new(); + for x in &xs { + mags.extend_from_slice(&x.mag.to_array()); + pos.push(x.pos); + } + assert_eq!(fold_soa(&mags, &pos, &sel, Demand::ALL), oracle(&sel, &codes)); +} + +#[test] +fn fold_computes_only_what_is_demanded() { + let (xs, sel, codes) = random_blocks(9, 3); + let want = oracle(&sel, &codes); + assert_eq!( + fold(&xs, &sel, Demand::SUM), + Stats { + s: want.s, + ..Stats::default() + } + ); +} + +#[test] +fn boundary_populations() { + let all = [u64::MAX]; + // Entirely untouched: no values, and variance is undefined, not zero. + let u = block_of(&[0u16; 64]); + let st = fold(&[u], &all, Demand::ALL); + assert_eq!(st, Stats::default()); + assert_eq!(variance_parts(st), None); + // Only established zeros: 64 values, sum 0, variance exactly 0. + let z = block_of(&[256u16; 64]); + let st = fold(&[z], &all, Demand::ALL); + assert_eq!( + st, + Stats { + n: 64, + ..Stats::default() + } + ); + assert_eq!(variance_parts(st), Some((0, 64 * 64))); + // Full cancellation: +255 and -255 alternating. + let codes: Vec = (0..64) + .map(|i| if i % 2 == 0 { 256 + 255 } else { 255 }) + .collect(); + let st = fold(&[block_of(&codes)], &all, Demand::ALL); + assert_eq!((st.n, st.s, st.a, st.q), (64, 0, 64 * 255, 64 * 255 * 255)); + // Nearly constant: 63 × +200 and one +201; variance is 63/4096. + let mut codes = vec![256 + 200u16; 64]; + codes[17] = 256 + 201; + let st = fold(&[block_of(&codes)], &all, Demand::ALL); + assert_eq!(variance_parts(st), Some((63, 4096))); +} + +#[test] +fn selection_density_extremes() { + let (xs, _, codes) = random_blocks(33, 11); + for sel in [vec![0u64; 33], vec![u64::MAX; 33]] { + assert_eq!(fold(&xs, &sel, Demand::ALL), oracle(&sel, &codes)); + } +}