Skip to main content

gam_math/
jet_partitions.rs

1//! Bitmask-coefficient multi-directional jets used by marginal-slope and
2//! latent-survival row kernels.
3//!
4//! The layout stores one coefficient per direction mask. The calculus itself
5//! lives in [`crate::jet_algebra`]: that module owns the layout-agnostic
6//! Leibniz / Faà di Bruno *combinatorics* once, and the scalar (`n_dirs <= 1`)
7//! path here still routes through it so a fix to the rule is a fix to both
8//! representations.
9//!
10//! ## Why this layout is special (and how the hot path exploits it)
11//!
12//! Each direction is seeded *linearly* (one first-derivative slot), so every
13//! direction variable squares to zero. The coefficients therefore form the
14//! commutative **multilinear / set-function algebra**: `coeffs[mask]` is the
15//! coefficient of `Π_{i ∈ mask} ε_i`. In that algebra two facts collapse the
16//! generic combinatorial walkers into tight branch-free arithmetic:
17//!
18//! * **`mul` is the subset (zeta-style) convolution**
19//!   `out[mask] = Σ_{sub ⊆ mask} a[sub] · b[mask \ sub]`.
20//!   The shared `leibniz_product` walker rebuilds two `SlotBuf`s and folds bit
21//!   lists back into masks (`mask_of`) *per subset*; here we enumerate the
22//!   submasks of `mask` directly — `mask \ sub == mask ^ sub` because
23//!   `sub ⊆ mask` — in the **same ascending order** the walker used, so the
24//!   floating-point accumulation is bit-for-bit identical while every
25//!   `SlotBuf`/closure/`mask_of` allocation and indirection disappears
26//!   (`3^K` pure FMAs, no heap, no `dyn`).
27//!
28//! * **`compose_unary` is the truncated Faà di Bruno composition**, computed
29//!   here from the *multilinear powers* of the non-constant part rather than a
30//!   direct set-partition sum. Let `v` be the non-constant part of `self`
31//!   (`v[0] = 0`, `v[mask] = self[mask]`) and let `v^{⊛k}` be the `k`-fold
32//!   *subset convolution* (the multilinear power). The ordered-tuple identity
33//!   `v^{⊛k}[mask] = k! · Σ_{π ⊢ mask, |π| = k} Π_{B ∈ π} v[B]` turns the
34//!   set-partition sum into a degree-4 polynomial in `v`:
35//!
36//!   ```text
37//!   f(self)[mask] = Σ_{k=0}^{4} (f^{(k)} / k!) · v^{⊛k}[mask]      (mask ≠ 0)
38//!   f(self)[0]    = f^{(0)}
39//!   ```
40//!
41//!   The powers themselves are built by the **pointed (lowest-set-bit)
42//!   recurrence**, not by full subset convolutions. Write `ℓ` for the lowest
43//!   set bit of `mask`. In any partition of `mask` exactly one block owns `ℓ`,
44//!   and the `k` blocks of an ordered `k`-tuple are interchangeable, so pinning
45//!   the outer block to the one containing `ℓ` counts each partition once
46//!   instead of `k` times:
47//!
48//!   ```text
49//!   v^{⊛k}[mask] = k · Σ_{B ⊆ mask, ℓ ∈ B} v[B] · v^{⊛(k-1)}[mask \ B]
50//!   ```
51//!
52//!   This is an exact identity (`k = 2, 3, 4` reproduce `v²`, `v³`, `v⁴` to
53//!   roundoff against a brute-force partition sum, gated in `tests`), and it is
54//!   what makes the schedule cheap at small `K`: the complements `mask \ B`
55//!   range over submasks of `mask ^ ℓ` rather than of `mask`, and the surviving
56//!   term set shrinks with `k` because `v^{⊛(k-1)}` vanishes below popcount
57//!   `k-1`. All three powers therefore share **one** descending submask walk
58//!   whose `k = 3` and `k = 4` chains are popcount-suffixes of the `k = 2`
59//!   chain — one walk, one `v[B]` load, and three independent Dot2 chains to
60//!   interleave.
61//!
62//!   Each accumulation is a compensated dot product (Ogita–Rump–Oishi Dot2,
63//!   FMA-split products + TwoSum carry) so the result is computed in ~double
64//!   the working precision and the rounding of `v²` cannot compound through
65//!   `v³`/`v⁴`; the integer multiplicity `k` is applied with its own FMA split
66//!   so it costs one rounding rather than discarding the compensated tail; the
67//!   final per-mask combine is Neumaier-compensated and `wide::f64x4`-vectorised;
68//!   and the whole call runs on reused thread-local scratch with no per-call
69//!   heap traffic.
70//!
71//! ### What this schedule costs
72//!
73//! Everything below is recomputed from the enumeration itself by
74//! `compose_unary_work_model_matches_the_closed_form`, which replays the walk and
75//! counts its steps. A counted model cannot drift the way a prose factor did:
76//! this header once claimed "~3× fewer FLOPs than the partition gather" for a
77//! schedule that in fact cost ~9× as much at the `K` production runs at.
78//!
79//! * the pointed recurrence walks `Σ_{p ≥ 2} C(K,p)·Σ_{k=2..4, k ≤ p} Σ_{j ≥ k-1}
80//!   C(p-1,j)` terms, i.e. `Θ(3^K)`, each a compensated Dot2 (10 flops), plus a
81//!   5-flop multiplicity epilogue per power per mask;
82//! * the partition gather walks `Σ_p C(K,p)·B_{≤4}(p)` terms, i.e. `Θ(5^K/4!)`,
83//!   each `|π|` plain multiplies and an add. (That count is a *lower bound* on
84//!   the gather: it omits the `2^p` per-mask index remap the gather also needs,
85//!   so every comparison below is stated against the gather at its best.)
86//!
87//! ```text
88//!   K                        2     3     4     6      8      9     10     12
89//!   pointed terms            1     7    34   534   6514  21589  69886  696810
90//!   gather terms             5    15    52   855  18002  86472 422005 10306752
91//!   pointed/gather flops  2.5x  3.5x  3.3x  2.0x  0.91x  0.59x  0.37x   0.15x
92//! ```
93//!
94//! Two facts worth carrying:
95//!
96//! * The three-full-subset-convolution schedule this replaced walked **exactly
97//!   4×** as many terms at every `K ≤ 4` (136 against 34 at `K = 4`) — one factor
98//!   of 2 from pinning the block that owns `ℓ`, one from walking submasks of
99//!   `mask ^ ℓ` instead of `mask`. Its flop crossover against the gather sat at
100//!   `K = 10`; the pointed recurrence moves it to `K = 8`.
101//! * At `K = 4` the schedule walks 34 terms against the gather's 52. It does
102//!   strictly *less* combinatorial work than the partition sum it replaced —
103//!   at every `K`, not just past a crossover — and the residual 3.3× flop ratio
104//!   at `K = 4` is entirely the Dot2 compensation: 10 flops a term against ~3.
105//!   That is the accuracy the double-double gate pins, and the only reason to
106//!   prefer this schedule; it is not free, and a reader sizing a new call site
107//!   should plan for it.
108use std::cell::RefCell;
109use std::sync::atomic::{AtomicU64, Ordering};
110use wide::f64x4;
111
112pub static COMPOSE_UNARY_CALLS: AtomicU64 = AtomicU64::new(0);
113pub static MUL_CALLS: AtomicU64 = AtomicU64::new(0);
114
115/// Length of the unary derivative stack `[f, f', f'', f''', f'''']`: composition
116/// is exact through order 4, partitions into `>= 5` blocks are truncated.
117const DERIVS: usize = 5;
118
119#[derive(Clone)]
120pub struct MultiDirJet {
121    pub coeffs: Vec<f64>,
122}
123
124impl MultiDirJet {
125    pub fn zero(n_dirs: usize) -> Self {
126        Self {
127            coeffs: vec![0.0; 1usize << n_dirs],
128        }
129    }
130
131    pub fn constant(n_dirs: usize, value: f64) -> Self {
132        let mut out = Self::zero(n_dirs);
133        out.coeffs[0] = value;
134        out
135    }
136
137    pub fn linear(n_dirs: usize, base: f64, first: &[f64]) -> Self {
138        let mut out = Self::constant(n_dirs, base);
139        for (idx, &value) in first.iter().take(n_dirs).enumerate() {
140            out.coeffs[1usize << idx] = value;
141        }
142        out
143    }
144
145    #[inline]
146    pub fn coeff(&self, mask: usize) -> f64 {
147        self.coeffs[mask]
148    }
149
150    pub fn add(&self, other: &Self) -> Self {
151        Self {
152            coeffs: self
153                .coeffs
154                .iter()
155                .zip(other.coeffs.iter())
156                .map(|(lhs, rhs)| lhs + rhs)
157                .collect(),
158        }
159    }
160
161    pub fn scale(&self, scalar: f64) -> Self {
162        Self {
163            coeffs: self.coeffs.iter().map(|value| scalar * value).collect(),
164        }
165    }
166
167    /// Subset-convolution product `out[mask] = Σ_{sub ⊆ mask} a[sub]·b[mask^sub]`.
168    ///
169    /// Bit-identical to the shared `crate::jet_algebra::leibniz_product` walker
170    /// (the submasks are enumerated in the same ascending order — the walker's
171    /// compacted subset index is a monotone bit-deposit of the submask) while
172    /// dropping its per-subset `SlotBuf`/closure/`mask_of` overhead. The scalar
173    /// `n_dirs == 0` case keeps the shared walker live as its reference.
174    pub fn mul(&self, other: &Self) -> Self {
175        MUL_CALLS.fetch_add(1, Ordering::Relaxed);
176        let count = self.coeffs.len();
177        if count <= 1 {
178            return self.mul_reference(other);
179        }
180        let a = &self.coeffs;
181        let b = &other.coeffs;
182        // Both operands carry the same direction set, so `b` is `count` long too.
183        // With that established once, every `a[sub]`/`b[mask ^ sub]` below is
184        // provably in bounds (`sub, mask ^ sub ⊆ mask < count`), so the inner
185        // submask walk can drop its per-load bounds checks.
186        assert_eq!(
187            b.len(),
188            count,
189            "MultiDirJet::mul operands must share n_dirs"
190        );
191        let mut out = vec![0.0; count];
192        for (mask, slot) in out.iter_mut().enumerate() {
193            // Walk every submask of `mask` in ascending numeric order — the same
194            // order `leibniz_product` accumulates — via the classic gap-fill
195            // increment `next = ((sub | !mask) + 1) & mask`.
196            let mut acc = 0.0;
197            let mut sub = 0usize;
198            // SAFETY: `sub ⊆ mask < count` and `mask ^ sub ⊆ mask < count`, and
199            // both `a` and `b` are `count` long (asserted above).
200            unsafe {
201                loop {
202                    acc += *a.get_unchecked(sub) * *b.get_unchecked(mask ^ sub);
203                    if sub == mask {
204                        break;
205                    }
206                    sub = (sub | !mask).wrapping_add(1) & mask;
207                }
208            }
209            *slot = acc;
210        }
211        Self { coeffs: out }
212    }
213
214    /// The pre-#perf shared-walker product, retained verbatim as the scalar-case
215    /// implementation and as the bit-exact reference for `mul`.
216    fn mul_reference(&self, other: &Self) -> Self {
217        let count = self.coeffs.len();
218        let mut out = vec![0.0; count];
219        for (mask, slot) in out.iter_mut().enumerate() {
220            let bits = bit_positions(mask);
221            *slot = crate::jet_algebra::leibniz_product(
222                bits.as_slice(),
223                |t| self.coeffs[mask_of(t)],
224                |c| other.coeffs[mask_of(c)],
225            );
226        }
227        Self { coeffs: out }
228    }
229
230    /// Exact (order-4 truncated) unary composition `f(self)` from the Taylor
231    /// stack `[f, f', f'', f''', f'''']` at `self.coeff(0)`.
232    ///
233    /// Computed by the truncated-Taylor reassociation (see the module note):
234    /// `f(self) = Σ_{k=0}^{4} (f^{(k)}/k!)·v^{⊛k}` with `v` the non-constant
235    /// part of `self`. The three subset-convolution powers `v²`, `v³`, `v⁴`
236    /// are compensated (Dot2) and the per-mask combine is Neumaier-compensated
237    /// and vectorised, so the result is *more* accurate vs. the true
238    /// real-arithmetic value than the prior naive partition sum (proven against
239    /// a double-double oracle in `tests`). The scalar `n_dirs == 0` case keeps
240    /// the shared Faà di Bruno walker live as its reference.
241    pub fn compose_unary(&self, derivs: [f64; DERIVS]) -> Self {
242        COMPOSE_UNARY_CALLS.fetch_add(1, Ordering::Relaxed);
243        let count = self.coeffs.len();
244        if count <= 1 {
245            return <Self as crate::jet_algebra::JetAlgebra<DERIVS>>::compose_unary(self, derivs);
246        }
247        let mut out = vec![0.0; count];
248        COMPOSE_SCRATCH.with(|cell| {
249            let mut buf = cell.borrow_mut();
250            buf.clear();
251            buf.resize(4 * count, 0.0);
252            compose_unary_coefficients_into(&self.coeffs, derivs, buf.as_mut_slice(), &mut out);
253        });
254        Self { coeffs: out }
255    }
256}
257
258thread_local! {
259    /// Reused composition scratch (`4·count` f64s: v, v², v³, v⁴). Sized up on
260    /// demand and never freed, so a steady-state `compose_unary` does zero heap
261    /// work beyond the owned output `Vec`.
262    static COMPOSE_SCRATCH: RefCell<Vec<f64>> = const { RefCell::new(Vec::new()) };
263}
264
265#[inline]
266fn compose_unary_coefficients_into(
267    coefficients: &[f64],
268    derivs: [f64; DERIVS],
269    scratch: &mut [f64],
270    out: &mut [f64],
271) {
272    let count = coefficients.len();
273    assert!(count > 1 && count.is_power_of_two());
274    assert!(scratch.len() == 4 * count && out.len() == count);
275    let (vbuf, tail) = scratch.split_at_mut(count);
276    let (p2, tail) = tail.split_at_mut(count);
277    let (p3, p4) = tail.split_at_mut(count);
278
279    // v is the non-constant part of the input. The k=0 Taylor term owns the
280    // constant coefficient, so the zero mask must not enter any power.
281    vbuf.copy_from_slice(coefficients);
282    vbuf[0] = 0.0;
283
284    // The three multilinear powers, by the pointed recurrence (module header).
285    multilinear_powers_into(vbuf, p2, p3, p4);
286    // `1/k!` undoes the ordered-tuple overcount of each k-fold subset power
287    // relative to the unordered set-partition sum.
288    let coefficients_by_order = [
289        derivs[1],
290        derivs[2] * 0.5,
291        derivs[3] * (1.0 / 6.0),
292        derivs[4] * (1.0 / 24.0),
293    ];
294    combine_powers(vbuf, p2, p3, p4, coefficients_by_order, out);
295    out[0] = derivs[0];
296}
297
298/// Branchless TwoSum: returns `(s, e)` with `s = fl(a+b)` and `a+b = s+e`
299/// exactly (Knuth/Møller). Used by the compensated power recurrence and combine.
300#[inline(always)]
301fn two_sum(a: f64, b: f64) -> (f64, f64) {
302    let s = a + b;
303    let bb = s - a;
304    let e = (a - (s - bb)) + (b - bb);
305    (s, e)
306}
307
308/// One step of an Ogita–Rump–Oishi Dot2: accumulate `x·y` into `(s, c)` so that
309/// `s + c` carries the running sum in ~twice the working precision. The product
310/// is split into head plus exact FMA error, and the addition's rounding error is
311/// recovered by TwoSum, so neither the product nor the sum silently drops bits.
312#[inline(always)]
313fn dot2_step(s: &mut f64, c: &mut f64, x: f64, y: f64) {
314    let prod = x * y;
315    let prod_err = x.mul_add(y, -prod); // exact: prod + prod_err == x*y
316    let (t, sum_err) = two_sum(*s, prod);
317    *s = t;
318    *c += prod_err + sum_err;
319}
320
321/// `k·(s + c)` for a small integer multiplicity `k`, with `k·s` split into head
322/// plus exact FMA error so the multiplicity costs one final rounding rather than
323/// discarding the compensated tail. For `k ∈ {2, 4}` the split is identically
324/// zero (both are exact scalings); `k = 3` is the case that needs it.
325#[inline(always)]
326fn scaled_compensated(k: f64, s: f64, c: f64) -> f64 {
327    let hi = k * s;
328    let lo = k.mul_add(s, -hi); // exact: hi + lo == k*s
329    hi + (lo + k * c)
330}
331
332/// The multilinear powers `v^{⊛2}`, `v^{⊛3}`, `v^{⊛4}` of the non-constant part
333/// `v`, by the **pointed (lowest-set-bit) recurrence** derived in the module
334/// header:
335///
336/// ```text
337/// v^{⊛k}[mask] = k · Σ_{t ⊊ mask, ℓ ∉ t} v[mask \ t] · v^{⊛(k-1)}[t]
338/// ```
339///
340/// with `ℓ` the lowest set bit of `mask`. Pinning the block that owns `ℓ` counts
341/// each partition once instead of `k` times, and the surviving `t` range over
342/// submasks of `mask ^ ℓ` rather than of `mask` — together an exactly 4× shorter
343/// walk than the three full subset convolutions this replaced, at every
344/// `K ≤ 4` (see `compose_unary_work_model_matches_the_closed_form`).
345///
346/// All three powers share **one** descending walk over the submasks of
347/// `mask ^ ℓ`, because their term sets are nested: `v^{⊛(k-1)}[t]` vanishes
348/// below `popcount(t) = k - 1`, so the `k = 3` and `k = 4` chains are the
349/// `popcount ≥ 2` and `popcount ≥ 3` suffixes of the `k = 2` chain. Sharing the
350/// walk also shares the `v[mask \ t]` load and gives three independent Dot2
351/// dependency chains to interleave, which is what the old kernel's four-way
352/// unroll was buying separately.
353///
354/// Every accumulation is a compensated Dot2, so the rounding of `v²` cannot
355/// compound through `v³`/`v⁴`. Masks below popcount `k` are left at zero: the
356/// `k`-fold multilinear power vanishes there, so the prune is exact.
357#[inline]
358fn multilinear_powers_into(v: &[f64], p2: &mut [f64], p3: &mut [f64], p4: &mut [f64]) {
359    let count = v.len();
360    // SAFETY precondition for the `get_unchecked` loads below, pinned once per
361    // call (negligible next to the walk): all four buffers are `count` long.
362    // Every index read is either `t` or `mask ^ t` for `t ⊆ mask < count`, and
363    // both are submasks of `mask`, hence `< count`. The per-load bounds checks
364    // LLVM cannot elide (the indices are data-dependent) are a real cost across
365    // the exponential walk, and eliding them measured ~20% on the kernel this
366    // replaced.
367    assert!(p2.len() == count && p3.len() == count && p4.len() == count);
368    if count > 0 {
369        p2[0] = 0.0;
370        p3[0] = 0.0;
371        p4[0] = 0.0;
372    }
373    for mask in 1..count {
374        // `v^{⊛k}` vanishes below popcount k, so a popcount-1 mask is all-zero
375        // in every power and never enters a walk.
376        let lowest = mask & mask.wrapping_neg();
377        let rest = mask ^ lowest;
378        if rest == 0 {
379            p2[mask] = 0.0;
380            p3[mask] = 0.0;
381            p4[mask] = 0.0;
382            continue;
383        }
384        let (mut s2, mut c2) = (0.0f64, 0.0f64);
385        let (mut s3, mut c3) = (0.0f64, 0.0f64);
386        let (mut s4, mut c4) = (0.0f64, 0.0f64);
387        // Descending submask walk `t = (t - 1) & rest` over the NONZERO submasks
388        // of `rest` (the classic Gosper-style enumeration). `t = 0` is skipped
389        // because it is the one term whose complement is the whole mask, and
390        // `v^{⊛(k-1)}[0] = 0` for every `k ≥ 2`.
391        let mut t = rest;
392        while t != 0 {
393            // SAFETY: `t ⊆ rest ⊂ mask < count` and `mask ^ t ⊆ mask < count`,
394            // and all four buffers are `count` long (asserted above).
395            unsafe {
396                let block = *v.get_unchecked(mask ^ t);
397                dot2_step(&mut s2, &mut c2, block, *v.get_unchecked(t));
398                let popcount = (t as u64).count_ones();
399                if popcount >= 2 {
400                    dot2_step(&mut s3, &mut c3, block, *p2.get_unchecked(t));
401                    if popcount >= 3 {
402                        dot2_step(&mut s4, &mut c4, block, *p3.get_unchecked(t));
403                    }
404                }
405            }
406            t = (t - 1) & rest;
407        }
408        // The pointed recurrence's multiplicity. `v^{⊛k}[mask]` must be written
409        // before the `k+1` chain of any LATER mask reads it, and `t < mask`
410        // strictly for every `t ⊆ mask ^ ℓ`, so writing all three here keeps the
411        // recurrence's read-before-write order across the ascending mask loop.
412        p2[mask] = scaled_compensated(2.0, s2, c2);
413        p3[mask] = scaled_compensated(3.0, s3, c3);
414        p4[mask] = scaled_compensated(4.0, s4, c4);
415    }
416}
417
418/// `out[mask] = c[0]·p1 + c[1]·p2 + c[2]·p3 + c[3]·p4` for `mask ≥ 1`, with a
419/// Neumaier-compensated four-term accumulation (the powers span growing
420/// magnitudes, so the compensation recovers the bits a naive `+=` would drop)
421/// and a `wide::f64x4` body over four masks at a time. `out[0]` is overwritten
422/// by the caller with the value channel.
423#[inline]
424fn combine_powers(p1: &[f64], p2: &[f64], p3: &[f64], p4: &[f64], c: [f64; 4], out: &mut [f64]) {
425    let n = out.len();
426    let (c1, c2, c3, c4) = (c[0], c[1], c[2], c[3]);
427    let (v1, v2, v3, v4) = (
428        f64x4::splat(c1),
429        f64x4::splat(c2),
430        f64x4::splat(c3),
431        f64x4::splat(c4),
432    );
433    let mut mask = 0usize;
434    // Vector body: four contiguous masks per step. Neumaier compensation is
435    // applied lane-wise; pick the larger magnitude to subtract first.
436    while mask + 4 <= n {
437        let load = |p: &[f64]| f64x4::new([p[mask], p[mask + 1], p[mask + 2], p[mask + 3]]);
438        let mut s = v1 * load(p1);
439        let mut comp = f64x4::splat(0.0);
440        for (cv, pv) in [(v2, p2), (v3, p3), (v4, p4)] {
441            let term = cv * load(pv);
442            let t = s + term;
443            let big_s = s.abs().simd_ge(term.abs());
444            let lost = big_s.blend((s - t) + term, (term - t) + s);
445            comp += lost;
446            s = t;
447        }
448        let res = s + comp;
449        out[mask..mask + 4].copy_from_slice(&res.to_array());
450        mask += 4;
451    }
452    // Scalar tail (and the small-K path where `n < 4`).
453    while mask < n {
454        let mut s = c1 * p1[mask];
455        let mut comp = 0.0f64;
456        for (cv, pv) in [(c2, p2), (c3, p3), (c4, p4)] {
457            let term = cv * pv[mask];
458            let (t, e) = two_sum(s, term);
459            comp += e;
460            s = t;
461        }
462        out[mask] = s + comp;
463        mask += 1;
464    }
465}
466
467impl crate::jet_algebra::JetAlgebra<DERIVS> for MultiDirJet {
468    #[inline]
469    fn derivative(&self, slots: &[usize]) -> f64 {
470        self.coeffs[mask_of(slots)]
471    }
472
473    fn map_derivatives<F>(&self, mut f: F) -> Self
474    where
475        F: FnMut(&[usize]) -> f64,
476    {
477        let mut out = vec![0.0; self.coeffs.len()];
478        for (mask, value) in out.iter_mut().enumerate() {
479            let bits = bit_positions(mask);
480            *value = f(bits.as_slice());
481        }
482        Self { coeffs: out }
483    }
484}
485
486/// The set-bit positions of `mask`, low to high — the differentiation slots of
487/// that coefficient.
488fn bit_positions(mask: usize) -> crate::jet_algebra::SlotBuf {
489    let mut out = crate::jet_algebra::SlotBuf::new();
490    let mut m = mask;
491    while m != 0 {
492        let bit = m.trailing_zeros() as usize;
493        out.push_slot(bit);
494        m &= m - 1;
495    }
496    out
497}
498
499/// Combine a slot-group (list of bit positions) back into a sub-mask.
500fn mask_of(slots: &[usize]) -> usize {
501    slots.iter().fold(0usize, |acc, &b| acc | (1usize << b))
502}
503
504// #932-2 cutover: `MultiDirJet::bilinear` (the 4-coeff `[base, d1, d2, d12]`
505// constructor) and `MultiDirJet::sub` are consumed ONLY by the now test-only hand
506// survival directional/bidirectional oracle (the production flex jet path uses the
507// `flex_jet` runtime jet algebra, not `MultiDirJet`). After the #1521 crate split
508// moved `MultiDirJet` into `gam-math`, those oracle tests live in the dependent
509// `gam` crate, where a `#[cfg(test)]` gate in *this* crate is inactive — so the
510// methods must be plain `pub` inherent methods to be reachable cross-crate. They
511// carry no dead-code cost because `pub` items are part of the crate's public API.
512// Bodies are byte-identical to their former gated form.
513impl MultiDirJet {
514
515    pub fn sub(&self, other: &Self) -> Self {
516        Self {
517            coeffs: self
518                .coeffs
519                .iter()
520                .zip(other.coeffs.iter())
521                .map(|(lhs, rhs)| lhs - rhs)
522                .collect(),
523        }
524    }
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530
531    /// A flattened set-partition table for a fixed slot count. `parts[i] = (off,
532    /// order)` describes one partition: its `order` block submasks (compacted) are
533    /// `flat[off .. off + order]`.
534    ///
535    /// This direct set-partition sum is the previous production `compose_unary`
536    /// implementation, retained as the **accuracy reference** the new
537    /// truncated-Taylor path is graded against: a double-double oracle is the
538    /// truth, and the test asserts the new path's error-vs-truth is `≤` this naive
539    /// partition sum's error-vs-truth on every randomised program.
540    struct PartTable {
541        flat: Vec<u32>,
542        parts: Vec<(usize, u8)>,
543    }
544
545    thread_local! {
546        /// Cached set-partition tables, indexed by slot count `m`. Entry `m` holds
547        /// every partition of `{0..m}` into `< DERIVS` blocks, in the shared
548        /// walker's recursion order, each block a compacted submask. Pure function
549        /// of `m`, so caching is sound and deterministic.
550        static PARTITION_TABLES: RefCell<Vec<std::rc::Rc<PartTable>>> =
551            const { RefCell::new(Vec::new()) };
552    }
553
554    /// Return cached partition tables for slot counts `0..=n_dirs`.
555    fn partition_tables(n_dirs: usize) -> Vec<std::rc::Rc<PartTable>> {
556        PARTITION_TABLES.with(|cell| {
557            let mut tables = cell.borrow_mut();
558            while tables.len() <= n_dirs {
559                let m = tables.len();
560                tables.push(std::rc::Rc::new(build_partitions(m)));
561            }
562            (0..=n_dirs)
563                .map(|m| std::rc::Rc::clone(&tables[m]))
564                .collect()
565        })
566    }
567
568    /// The previous production `compose_unary`: a direct set-partition (Faà di
569    /// Bruno) sum per output mask, retained as the accuracy reference.
570    fn compose_unary_partition_reference(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<f64> {
571        let count = coeffs.len();
572        let n_dirs = count.trailing_zeros() as usize;
573        let tables = partition_tables(n_dirs);
574        let mut out = vec![0.0; count];
575        let mut remap = vec![0usize; count];
576        let mut pos = [0usize; usize::BITS as usize];
577        for (mask, slot) in out.iter_mut().enumerate() {
578            if mask == 0 {
579                *slot = derivs[0];
580                continue;
581            }
582            let mut npos = 0usize;
583            let mut m = mask;
584            while m != 0 {
585                pos[npos] = m.trailing_zeros() as usize;
586                npos += 1;
587                m &= m - 1;
588            }
589            remap[0] = 0;
590            for cb in 1usize..(1usize << npos) {
591                let low = cb.trailing_zeros() as usize;
592                remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
593            }
594            let table = &tables[npos];
595            let flat = &table.flat;
596            let mut total = 0.0;
597            for &(off, order) in table.parts.iter() {
598                let order = order as usize;
599                let mut prod = derivs[order];
600                for &cb in &flat[off..off + order] {
601                    prod *= coeffs[remap[cb as usize]];
602                }
603                total += prod;
604            }
605            *slot = total;
606        }
607        out
608    }
609
610    /// Enumerate the set-partitions of `{0..m}` with fewer than `DERIVS` blocks, in
611    /// the exact DFS order of [`crate::jet_algebra`]'s `for_each_partition`
612    /// recursion ("place each element into an existing block, else open a new one"),
613    /// each block recorded as a compacted submask of `{0..m}`, flattened.
614    fn build_partitions(m: usize) -> PartTable {
615        fn recurse(
616            elem: usize,
617            m: usize,
618            blocks: &mut [u32; 8],
619            n_blocks: usize,
620            out: &mut PartTable,
621        ) {
622            // Partitions with `>= DERIVS` blocks are truncated (their `f^{(order)}`
623            // is beyond the stack); the block count never decreases, so the whole
624            // subtree contributes nothing and is pruned — matching the walker's
625            // per-partition `order >= derivs.len()` skip.
626            if n_blocks >= DERIVS {
627                return;
628            }
629            if elem == m {
630                let off = out.flat.len();
631                out.flat.extend_from_slice(&blocks[..n_blocks]);
632                out.parts.push((off, n_blocks as u8));
633                return;
634            }
635            for b in 0..n_blocks {
636                blocks[b] |= 1u32 << elem;
637                recurse(elem + 1, m, blocks, n_blocks, out);
638                blocks[b] &= !(1u32 << elem);
639            }
640            blocks[n_blocks] = 1u32 << elem;
641            recurse(elem + 1, m, blocks, n_blocks + 1, out);
642        }
643        let mut out = PartTable {
644            flat: Vec::new(),
645            parts: Vec::new(),
646        };
647        let mut blocks = [0u32; 8];
648        recurse(0, m, &mut blocks, 0, &mut out);
649        out
650    }
651
652    // ── constructors ─────────────────────────────────────────────────────────
653
654    #[test]
655    fn zero_has_correct_length_and_all_zero_coefficients() {
656        let j = MultiDirJet::zero(3);
657        assert_eq!(j.coeffs.len(), 8);
658        assert!(j.coeffs.iter().all(|&v| v == 0.0));
659    }
660
661    #[test]
662    fn constant_has_value_at_mask_zero_and_zeros_elsewhere() {
663        let j = MultiDirJet::constant(2, 5.0);
664        assert_eq!(j.coeffs.len(), 4);
665        assert_eq!(j.coeff(0), 5.0);
666        assert_eq!(j.coeff(1), 0.0);
667        assert_eq!(j.coeff(2), 0.0);
668        assert_eq!(j.coeff(3), 0.0);
669    }
670
671    #[test]
672    fn linear_sets_base_and_per_direction_slots() {
673        let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
674        assert_eq!(j.coeff(0), 1.0); // constant
675        assert_eq!(j.coeff(1), 2.0); // mask 0b01 — direction 0
676        assert_eq!(j.coeff(2), 3.0); // mask 0b10 — direction 1
677        assert_eq!(j.coeff(3), 0.0); // cross term is zero
678    }
679
680    // ── elementwise arithmetic ────────────────────────────────────────────────
681
682    #[test]
683    fn add_is_elementwise() {
684        let a = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
685        let b = MultiDirJet::linear(2, 4.0, &[5.0, 6.0]);
686        let c = a.add(&b);
687        assert_eq!(c.coeff(0), 5.0);
688        assert_eq!(c.coeff(1), 7.0);
689        assert_eq!(c.coeff(2), 9.0);
690        assert_eq!(c.coeff(3), 0.0);
691    }
692
693    #[test]
694    fn scale_multiplies_all_coefficients() {
695        let j = MultiDirJet::linear(2, 1.0, &[2.0, 3.0]);
696        let s = j.scale(2.0);
697        assert_eq!(s.coeff(0), 2.0);
698        assert_eq!(s.coeff(1), 4.0);
699        assert_eq!(s.coeff(2), 6.0);
700        assert_eq!(s.coeff(3), 0.0);
701    }
702
703    #[test]
704    fn sub_is_elementwise_difference() {
705        let a = MultiDirJet::constant(2, 5.0);
706        let b = MultiDirJet::constant(2, 3.0);
707        let c = a.sub(&b);
708        assert_eq!(c.coeff(0), 2.0);
709        assert_eq!(c.coeff(1), 0.0);
710        assert_eq!(c.coeff(2), 0.0);
711        assert_eq!(c.coeff(3), 0.0);
712    }
713
714    // ── mul (subset-convolution) ──────────────────────────────────────────────
715
716    #[test]
717    fn mul_of_constants_is_scalar_product() {
718        let a = MultiDirJet::constant(2, 2.0);
719        let b = MultiDirJet::constant(2, 3.0);
720        let c = a.mul(&b);
721        assert_eq!(c.coeff(0), 6.0);
722        assert_eq!(c.coeff(1), 0.0);
723        assert_eq!(c.coeff(2), 0.0);
724        assert_eq!(c.coeff(3), 0.0);
725    }
726
727    #[test]
728    fn mul_satisfies_leibniz_rule_single_direction() {
729        // (1 + ε) * (1 + ε) = 1 + 2ε
730        let x = MultiDirJet::linear(1, 1.0, &[1.0]);
731        let y = MultiDirJet::linear(1, 1.0, &[1.0]);
732        let z = x.mul(&y);
733        assert_eq!(z.coeff(0), 1.0);
734        assert_eq!(z.coeff(1), 2.0);
735    }
736
737    #[test]
738    fn mul_cross_term_two_independent_directions() {
739        // (1 + ε₁)(1 + ε₂) = 1 + ε₁ + ε₂ + ε₁ε₂
740        let x = MultiDirJet::linear(2, 1.0, &[1.0, 0.0]);
741        let y = MultiDirJet::linear(2, 1.0, &[0.0, 1.0]);
742        let z = x.mul(&y);
743        assert_eq!(z.coeff(0), 1.0);
744        assert_eq!(z.coeff(1), 1.0);
745        assert_eq!(z.coeff(2), 1.0);
746        assert_eq!(z.coeff(3), 1.0);
747    }
748
749    // ── compose_unary: truncated-Taylor reassociation ─────────────────────────
750    //
751    // The new `compose_unary` reassociates the per-mask Faà di Bruno set-partition
752    // sum into a degree-4 polynomial in the subset-convolution power of the
753    // non-constant part. These tests are the accuracy gate: a double-double
754    // oracle is the truth, and the new path's error-vs-truth must be `≤` the old
755    // naive partition sum's error-vs-truth on every randomised program.
756
757    /// Deterministic xorshift64* — no `rand` dependency in the test.
758    struct Rng(u64);
759    impl Rng {
760        fn next_u64(&mut self) -> u64 {
761            let mut x = self.0;
762            x ^= x >> 12;
763            x ^= x << 25;
764            x ^= x >> 27;
765            self.0 = x;
766            x.wrapping_mul(0x2545F4914F6CDD1D)
767        }
768        /// Uniform in `[-scale, scale]`.
769        fn signed(&mut self, scale: f64) -> f64 {
770            let u = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64; // [0,1)
771            (2.0 * u - 1.0) * scale
772        }
773    }
774
775    // ── A double-double oracle for the exact (order-4 truncated) composition ──
776
777    #[inline]
778    fn two_prod(a: f64, b: f64) -> (f64, f64) {
779        let p = a * b;
780        (p, a.mul_add(b, -p))
781    }
782    #[inline]
783    fn dd_two_sum(a: f64, b: f64) -> (f64, f64) {
784        let s = a + b;
785        let bb = s - a;
786        (s, (a - (s - bb)) + (b - bb))
787    }
788    #[derive(Clone, Copy)]
789    struct Dd {
790        hi: f64,
791        lo: f64,
792    }
793    impl Dd {
794        fn from(x: f64) -> Self {
795            Self { hi: x, lo: 0.0 }
796        }
797        fn mul_f64(self, b: f64) -> Self {
798            let (p, e) = two_prod(self.hi, b);
799            let lo = self.lo.mul_add(b, e);
800            let s = p + lo;
801            Self {
802                hi: s,
803                lo: (p - s) + lo,
804            }
805        }
806        fn add(self, o: Self) -> Self {
807            let (s, e) = dd_two_sum(self.hi, o.hi);
808            let (s2, e2) = dd_two_sum(self.lo, o.lo);
809            let lo = e + s2;
810            let h1 = s + lo;
811            let l1 = (s - h1) + lo;
812            let lo2 = l1 + e2;
813            let h = h1 + lo2;
814            Self {
815                hi: h,
816                lo: (h1 - h) + lo2,
817            }
818        }
819        /// `|self - x|` to ~double precision in the residual (Sterbenz: `x` and
820        /// `hi` agree to ~53 bits, so `x - hi` is essentially exact).
821        fn abs_err_to(self, x: f64) -> f64 {
822            ((x - self.hi) - self.lo).abs()
823        }
824    }
825
826    /// High-precision truth for `compose_unary` via the set-partition reference,
827    /// every product and sum carried in double-double.
828    fn compose_truth(coeffs: &[f64], derivs: [f64; DERIVS]) -> Vec<Dd> {
829        let count = coeffs.len();
830        let n_dirs = count.trailing_zeros() as usize;
831        let tables = partition_tables(n_dirs);
832        let mut out = vec![Dd::from(0.0); count];
833        let mut remap = vec![0usize; count];
834        let mut pos = [0usize; 64];
835        for (mask, slot) in out.iter_mut().enumerate() {
836            if mask == 0 {
837                *slot = Dd::from(derivs[0]);
838                continue;
839            }
840            let mut npos = 0usize;
841            let mut m = mask;
842            while m != 0 {
843                pos[npos] = m.trailing_zeros() as usize;
844                npos += 1;
845                m &= m - 1;
846            }
847            remap[0] = 0;
848            for cb in 1usize..(1usize << npos) {
849                let low = cb.trailing_zeros() as usize;
850                remap[cb] = remap[cb & (cb - 1)] | (1usize << pos[low]);
851            }
852            let table = &tables[npos];
853            let mut total = Dd::from(0.0);
854            for &(off, order) in table.parts.iter() {
855                let order = order as usize;
856                let mut prod = Dd::from(derivs[order]);
857                for &cb in &table.flat[off..off + order] {
858                    prod = prod.mul_f64(coeffs[remap[cb as usize]]);
859                }
860                total = total.add(prod);
861            }
862            *slot = total;
863        }
864        out
865    }
866
867    /// Build a random composite jet so the composition input is a realistic
868    /// non-trivial multilinear element (not just seeded directions).
869    fn random_inner(n_dirs: usize, rng: &mut Rng) -> MultiDirJet {
870        let base = rng.signed(0.8);
871        let first: Vec<f64> = (0..n_dirs).map(|_| rng.signed(0.6)).collect();
872        let a = MultiDirJet::linear(n_dirs, base, &first);
873        let b = MultiDirJet::linear(
874            n_dirs,
875            rng.signed(0.7),
876            &(0..n_dirs).map(|_| rng.signed(0.5)).collect::<Vec<_>>(),
877        );
878        // a*b + a populates the full cross-mask spectrum.
879        a.mul(&b).add(&a)
880    }
881
882    #[test]
883    fn compose_unary_matches_partition_reference_simple() {
884        // exp-like stack on a 2-direction cross jet: every coeff agrees with the
885        // direct set-partition reference to a tight tolerance.
886        let j = MultiDirJet::linear(2, 0.3, &[0.5, -0.4]).mul(&MultiDirJet::linear(
887            2,
888            -0.2,
889            &[0.1, 0.7],
890        ));
891        let d = [0.9_f64, 1.1, -0.7, 0.4, -0.25];
892        let got = j.compose_unary(d);
893        let want = compose_unary_partition_reference(&j.coeffs, d);
894        for (mask, (&g, &w)) in got.coeffs.iter().zip(want.iter()).enumerate() {
895            let tol = 1e-13 * w.abs().max(1.0);
896            assert!(
897                (g - w).abs() <= tol,
898                "mask {mask}: got={g:.17e} want={w:.17e}"
899            );
900        }
901    }
902
903    #[test]
904    fn compose_unary_accuracy_beats_partition_sum_vs_double_double() {
905        // The accuracy gate. Over many random programs at every K used in
906        // production, the new path's error-vs-truth is never worse than the old
907        // naive partition sum's, and is a strict improvement in aggregate.
908        let mut rng = Rng(0x1234_5678_9abc_def0);
909        let mut sum_new = 0.0f64;
910        let mut sum_old = 0.0f64;
911        for &n_dirs in &[2usize, 3, 4, 6, 8] {
912            for _ in 0..200 {
913                let inner = random_inner(n_dirs, &mut rng);
914                let d = [
915                    rng.signed(1.5),
916                    rng.signed(1.5),
917                    rng.signed(2.0),
918                    rng.signed(3.0),
919                    rng.signed(4.0),
920                ];
921                let new = inner.compose_unary(d);
922                let old = compose_unary_partition_reference(&inner.coeffs, d);
923                let truth = compose_truth(&inner.coeffs, d);
924                for mask in 0..inner.coeffs.len() {
925                    let en = truth[mask].abs_err_to(new.coeffs[mask]);
926                    let eo = truth[mask].abs_err_to(old[mask]);
927                    sum_new += en;
928                    sum_old += eo;
929                    // Per-coefficient: new is never materially worse. The 4 ULP
930                    // slack absorbs the rare tie where a differently-grouped but
931                    // equally-valid rounding lands one ULP either way.
932                    let scale = truth[mask].hi.abs().max(1.0);
933                    assert!(
934                        en <= eo + 4.0 * f64::EPSILON * scale,
935                        "K={n_dirs} mask={mask}: new_err={en:.3e} old_err={eo:.3e}"
936                    );
937                }
938            }
939        }
940        // Aggregate: the compensated reassociation is a real improvement.
941        assert!(
942            sum_new <= sum_old,
943            "aggregate error regressed: new={sum_new:.6e} old={sum_old:.6e}"
944        );
945        eprintln!(
946            "compose_unary accuracy: total |err| new={sum_new:.6e} old={sum_old:.6e} \
947             (improvement {:.2}x)",
948            sum_old / sum_new.max(f64::MIN_POSITIVE)
949        );
950    }
951
952    /// `v^{⊛k}[mask] = k! · Σ_{π ⊢ mask, |π| = k} Π_{B ∈ π} v[B]` by direct
953    /// enumeration of the set partitions of `mask` — the *definition* the pointed
954    /// recurrence claims to compute.
955    ///
956    /// Returns `[v², v³, v⁴]` and, per mask, the forward error the pair of
957    /// evaluations is jointly entitled to: this reference accumulates `n` terms
958    /// naively (Wilkinson: `n·u` times the sum of the term magnitudes) after up to
959    /// three roundings per product, and the compensated walk is good to ~`u`, so
960    /// `(n + 4)·EPSILON·Σ|term|` bounds their difference. It is derived from the
961    /// enumeration, not fitted to an observed failure.
962    fn brute_force_multilinear_powers(v: &[f64]) -> ([Vec<f64>; 3], [Vec<f64>; 3]) {
963        fn recurse(
964            elem: usize,
965            bits: &[usize],
966            blocks: &mut Vec<usize>,
967            v: &[f64],
968            acc: &mut [f64; 5],
969            acc_abs: &mut [f64; 5],
970            acc_count: &mut [u32; 5],
971        ) {
972            if blocks.len() > 4 {
973                return;
974            }
975            if elem == bits.len() {
976                let order = blocks.len();
977                if order >= 2 {
978                    let product: f64 = blocks.iter().map(|&b| v[b]).product();
979                    acc[order] += product;
980                    acc_abs[order] += product.abs();
981                    acc_count[order] += 1;
982                }
983                return;
984            }
985            let bit = 1usize << bits[elem];
986            for slot in 0..blocks.len() {
987                blocks[slot] |= bit;
988                recurse(elem + 1, bits, blocks, v, acc, acc_abs, acc_count);
989                blocks[slot] &= !bit;
990            }
991            blocks.push(bit);
992            recurse(elem + 1, bits, blocks, v, acc, acc_abs, acc_count);
993            blocks.pop();
994        }
995        let count = v.len();
996        let mut powers = [vec![0.0; count], vec![0.0; count], vec![0.0; count]];
997        let mut entitled = [vec![0.0; count], vec![0.0; count], vec![0.0; count]];
998        let factorial = [1.0, 1.0, 2.0, 6.0, 24.0];
999        for mask in 1..count {
1000            let mut bits = Vec::new();
1001            let mut rest = mask;
1002            while rest != 0 {
1003                bits.push(rest.trailing_zeros() as usize);
1004                rest &= rest - 1;
1005            }
1006            let mut acc = [0.0f64; 5];
1007            let mut acc_abs = [0.0f64; 5];
1008            let mut acc_count = [0u32; 5];
1009            recurse(
1010                0,
1011                &bits,
1012                &mut Vec::new(),
1013                v,
1014                &mut acc,
1015                &mut acc_abs,
1016                &mut acc_count,
1017            );
1018            for order in 2..=4usize {
1019                powers[order - 2][mask] = factorial[order] * acc[order];
1020                entitled[order - 2][mask] = (f64::from(acc_count[order]) + 4.0)
1021                    * f64::EPSILON
1022                    * factorial[order]
1023                    * acc_abs[order];
1024            }
1025        }
1026        (powers, entitled)
1027    }
1028
1029    /// The pointed (lowest-set-bit) recurrence is an *identity*, not an
1030    /// approximation: pinning the block that owns the lowest set bit and
1031    /// multiplying by `k` reproduces the `k`-fold multilinear power of the
1032    /// brute-force set-partition definition, to the forward error the two
1033    /// evaluations are jointly entitled to.
1034    ///
1035    /// This is the gate on the recurrence the module header derives. The header's
1036    /// cost claims are only worth anything if the cheaper walk computes the same
1037    /// quantity, and that is what this pins.
1038    #[test]
1039    fn pointed_recurrence_reproduces_the_brute_force_multilinear_powers() {
1040        let mut rng = Rng(0x0be1_1ab0_1a5e_c001);
1041        for n_dirs in 1usize..=6 {
1042            for _ in 0..24 {
1043                let count = 1usize << n_dirs;
1044                let mut v: Vec<f64> = (0..count).map(|_| rng.signed(1.0)).collect();
1045                v[0] = 0.0;
1046                let mut p2 = vec![f64::NAN; count];
1047                let mut p3 = vec![f64::NAN; count];
1048                let mut p4 = vec![f64::NAN; count];
1049                multilinear_powers_into(&v, &mut p2, &mut p3, &mut p4);
1050                let (want, entitled) = brute_force_multilinear_powers(&v);
1051                for (order, got) in [&p2, &p3, &p4].iter().enumerate() {
1052                    for mask in 0..count {
1053                        // Graded against the forward error the two evaluations are
1054                        // jointly entitled to (see the reference above), which is a
1055                        // derived bound rather than a fitted tolerance. Where the
1056                        // power vanishes identically the bound is zero and the
1057                        // agreement must be exact.
1058                        let tolerance = entitled[order][mask];
1059                        assert!(
1060                            (got[mask] - want[order][mask]).abs() <= tolerance,
1061                            "K={n_dirs} k={} mask={mask}: pointed={:.17e} partitions={:.17e} \
1062                             tol={tolerance:.3e}",
1063                            order + 2,
1064                            got[mask],
1065                            want[order][mask]
1066                        );
1067                    }
1068                }
1069            }
1070        }
1071    }
1072
1073    /// The two schedules' operation counts, recomputed from the enumeration
1074    /// itself. This is the machine-independent statement of what each schedule
1075    /// costs and where the convolution path becomes the cheaper one; the
1076    /// wall-clock test below can only corroborate it.
1077    ///
1078    /// It exists because the header once claimed the convolution schedule was
1079    /// "~3× fewer FLOPs than the per-mask partition gather" full stop, and a
1080    /// wall-clock test asserted a speedup from `K = 6`. Both were false of the
1081    /// schedule then in the file: three full subset convolutions cost ~9× the
1082    /// gather at the `K = 4` the production entry point uses, and did not come
1083    /// out ahead until `K = 10`. A counted model cannot drift the way a prose
1084    /// factor did.
1085    #[test]
1086    fn compose_unary_work_model_matches_the_closed_form() {
1087        // Dot2: mul, FMA error, TwoSum (6), two carry adds.
1088        const DOT2_FLOPS: u64 = 10;
1089        // `scaled_compensated`: k·s, its FMA error, k·c, and two adds.
1090        const MULTIPLICITY_FLOPS: u64 = 5;
1091
1092        let binom = |n: u32, r: u32| -> u64 {
1093            (0..r).fold(1u64, |acc, i| acc * u64::from(n - i) / (u64::from(i) + 1))
1094        };
1095
1096        // Replay of `multilinear_powers_into`'s enumeration — same mask loop,
1097        // same lowest-bit pin, same descending walk over the submasks of
1098        // `mask ^ lowest`, same popcount gates — counting Dot2 steps instead of
1099        // performing them. This is what makes the closed form below a claim about
1100        // the kernel rather than about itself.
1101        fn walked_terms(n_dirs: u32) -> u64 {
1102            let count = 1usize << n_dirs;
1103            let mut steps = 0u64;
1104            for mask in 1..count {
1105                let lowest = mask & mask.wrapping_neg();
1106                let rest = mask ^ lowest;
1107                if rest == 0 {
1108                    continue;
1109                }
1110                let mut t = rest;
1111                while t != 0 {
1112                    steps += 1;
1113                    let popcount = (t as u64).count_ones();
1114                    if popcount >= 2 {
1115                        steps += 1;
1116                        if popcount >= 3 {
1117                            steps += 1;
1118                        }
1119                    }
1120                    t = (t - 1) & rest;
1121                }
1122            }
1123            steps
1124        }
1125
1126        // Closed form: per mask of popcount p ≥ 2 and each power k ≤ p, the
1127        // submasks t of `mask ^ ℓ` (a (p-1)-set) with popcount(t) ≥ k-1.
1128        let pointed_terms = |n_dirs: u32| -> u64 {
1129            (2..=n_dirs)
1130                .map(|p| {
1131                    let per_mask: u64 = (2..=4u32)
1132                        .filter(|k| *k <= p)
1133                        .map(|k| (k - 1..=p - 1).map(|j| binom(p - 1, j)).sum::<u64>())
1134                        .sum();
1135                    binom(n_dirs, p) * per_mask
1136                })
1137                .sum()
1138        };
1139        let pointed_flops = |n_dirs: u32| -> u64 {
1140            (2..=n_dirs)
1141                .map(|p| {
1142                    let per_mask: u64 = (2..=4u32)
1143                        .filter(|k| *k <= p)
1144                        .map(|k| (k - 1..=p - 1).map(|j| binom(p - 1, j)).sum::<u64>())
1145                        .sum();
1146                    binom(n_dirs, p) * (per_mask * DOT2_FLOPS + 3 * MULTIPLICITY_FLOPS)
1147                })
1148                .sum()
1149        };
1150
1151        // The schedule this replaced: three full subset convolutions v², v³=v²⊛v,
1152        // v⁴=v²⊛v², each pruned at popcount < k, each surviving mask walking all
1153        // 2^popcount of its submasks.
1154        let full_convolution_terms = |n_dirs: u32| -> u64 {
1155            (2..=4u32)
1156                .map(|k| {
1157                    (k..=n_dirs)
1158                        .map(|p| binom(n_dirs, p) * (1u64 << p))
1159                        .sum::<u64>()
1160                })
1161                .sum()
1162        };
1163
1164        // Partition gather: per mask of popcount p, every set partition of a
1165        // p-set into 1..=4 blocks contributes |π| multiplies and one add. This
1166        // omits the gather's own `2^p` per-mask index remap, so it is a lower
1167        // bound on the gather and every comparison below is against its best case.
1168        fn stirling(n: u32, blocks: u32) -> u64 {
1169            let (n, blocks) = (n as usize, blocks as usize);
1170            let mut s = vec![vec![0u64; blocks + 1]; n + 1];
1171            s[0][0] = 1;
1172            for i in 1..=n {
1173                for j in 1..=blocks {
1174                    s[i][j] = (j as u64) * s[i - 1][j] + s[i - 1][j - 1];
1175                }
1176            }
1177            s[n][blocks]
1178        }
1179        let gather_terms = |n_dirs: u32| -> u64 {
1180            1 + (1..=n_dirs)
1181                .map(|p| binom(n_dirs, p) * (1..=4u32).map(|b| stirling(p, b)).sum::<u64>())
1182                .sum::<u64>()
1183        };
1184        let gather_flops = |n_dirs: u32| -> u64 {
1185            1 + (1..=n_dirs)
1186                .map(|p| {
1187                    binom(n_dirs, p)
1188                        * (1..=4u32)
1189                            .map(|b| stirling(p, b) * (u64::from(b) + 1))
1190                            .sum::<u64>()
1191                })
1192                .sum::<u64>()
1193        };
1194
1195        // (a) The closed form describes the walk the kernel actually performs.
1196        for n_dirs in 2..=12u32 {
1197            assert_eq!(
1198                walked_terms(n_dirs),
1199                pointed_terms(n_dirs),
1200                "K={n_dirs}: closed form disagrees with the replayed enumeration"
1201            );
1202        }
1203
1204        // (b) Against the three full subset convolutions this replaced: exactly
1205        // 4× fewer terms across the whole range production runs at — one factor
1206        // of 2 from pinning the block that owns the lowest set bit, one from
1207        // walking submasks of `mask ^ ℓ` rather than of `mask`.
1208        for n_dirs in 2..=4u32 {
1209            assert_eq!(
1210                full_convolution_terms(n_dirs),
1211                4 * pointed_terms(n_dirs),
1212                "K={n_dirs}: the replaced schedule should be exactly 4x this one"
1213            );
1214        }
1215        for n_dirs in 2..=14u32 {
1216            assert!(
1217                pointed_terms(n_dirs) < full_convolution_terms(n_dirs),
1218                "K={n_dirs}: the pointed recurrence must never walk more terms \
1219                 than the full convolutions it replaced ({} vs {})",
1220                pointed_terms(n_dirs),
1221                full_convolution_terms(n_dirs)
1222            );
1223        }
1224
1225        // (c) Against the partition gather: strictly fewer terms at every K,
1226        // including the production K = 4 (34 against 52). The combinatorial
1227        // deficit that made the old schedule indefensible at small K is gone.
1228        for n_dirs in 2..=14u32 {
1229            assert!(
1230                pointed_terms(n_dirs) < gather_terms(n_dirs),
1231                "K={n_dirs}: pointed schedule should walk fewer terms than the \
1232                 partition gather ({} vs {})",
1233                pointed_terms(n_dirs),
1234                gather_terms(n_dirs)
1235            );
1236        }
1237        assert_eq!((pointed_terms(4), gather_terms(4)), (34, 52));
1238
1239        // (d) What remains at the production K = 4 is the compensation premium
1240        // and nothing else: 10 flops a term against the gather's ~3, over fewer
1241        // terms, for a 3.3x flop ratio. That is the price of the ~double-precision
1242        // accumulation the accuracy gate pins — it is bought, not free.
1243        let production_ratio = pointed_flops(4) as f64 / gather_flops(4) as f64;
1244        assert!(
1245            (production_ratio - 3.34).abs() < 0.05,
1246            "at the production K=4 the pointed schedule should cost ~3.34x the \
1247             partition gather's flops, got {production_ratio:.2}x"
1248        );
1249
1250        // (e) The flop crossover, which the pointed recurrence moves from K = 10
1251        // (three full convolutions) to K = 8.
1252        for n_dirs in 2..=7u32 {
1253            assert!(
1254                pointed_flops(n_dirs) > gather_flops(n_dirs),
1255                "K={n_dirs}: below the crossover the compensated schedule is still \
1256                 the more expensive one ({} vs {})",
1257                pointed_flops(n_dirs),
1258                gather_flops(n_dirs)
1259            );
1260        }
1261        for n_dirs in 8..=14u32 {
1262            assert!(
1263                pointed_flops(n_dirs) < gather_flops(n_dirs),
1264                "K={n_dirs}: at and above the K=8 crossover the compensated \
1265                 schedule should also be the cheaper one ({} vs {})",
1266                pointed_flops(n_dirs),
1267                gather_flops(n_dirs)
1268            );
1269        }
1270    }
1271
1272
1273    /// Wall-clock corroboration of the compensated `compose_unary` schedule
1274    /// against the previous partition-sum implementation, at every `K`.
1275    ///
1276    /// This is corroboration, not the contract. The contract is
1277    /// `compose_unary_work_model_matches_the_closed_form`, which counts
1278    /// operations: a count is the same on every machine, and a wall clock is
1279    /// not. The speed cell is asserted only at `K = 12`, far past the
1280    /// crossover the counted model reports (`K = 8` for the pointed
1281    /// recurrence), where the compensated schedule does ~7x less arithmetic;
1282    /// below that the multiple is printed for the record. The gate opens only
1283    /// in the release profile (`SpeedGate::open` documents why).
1284    #[test]
1285    fn compose_unary_speedup_over_partition_sum() {
1286        use crate::paired_timing::{SpeedGate, paired_interleaved};
1287
1288        if cfg!(debug_assertions) {
1289            return;
1290        }
1291        let mut gate = SpeedGate::open("COMPOSE-UNARY-932");
1292        let mut rng = Rng(0xfeed_face_dead_beef);
1293        for &n_dirs in &[2usize, 4, 6, 8, 12] {
1294            // The per-call cost spans ~5 orders of magnitude across this K
1295            // range (both schedules are exponential in K), so the sample count
1296            // has to shrink with K or the K=12 arm alone would run for hours.
1297            let n_inputs = if n_dirs >= 12 { 4usize } else { 256 };
1298            let inputs: Vec<(MultiDirJet, [f64; DERIVS])> = (0..n_inputs)
1299                .map(|_| {
1300                    (
1301                        random_inner(n_dirs, &mut rng),
1302                        [
1303                            rng.signed(1.5),
1304                            rng.signed(1.5),
1305                            rng.signed(2.0),
1306                            rng.signed(3.0),
1307                            rng.signed(4.0),
1308                        ],
1309                    )
1310                })
1311                .collect();
1312            let iterations = if n_dirs >= 12 { 3usize } else { 200 };
1313            // One arm call composes every input once; the nudge perturbs the
1314            // outer derivative stack so no composition is loop-invariant.
1315            let timing = paired_interleaved(
1316                15,
1317                iterations,
1318                0x9320_C0DE ^ n_dirs as u64,
1319                |nudge| {
1320                    let mut sink = 0.0f64;
1321                    for (jet, derivs) in &inputs {
1322                        let mut derivs = *derivs;
1323                        derivs[0] += nudge;
1324                        sink += jet.compose_unary(derivs).coeffs.iter().sum::<f64>();
1325                    }
1326                    sink
1327                },
1328                |nudge| {
1329                    let mut sink = 0.0f64;
1330                    for (jet, derivs) in &inputs {
1331                        let mut derivs = *derivs;
1332                        derivs[0] += nudge;
1333                        sink += compose_unary_partition_reference(&jet.coeffs, derivs)
1334                            .iter()
1335                            .sum::<f64>();
1336                    }
1337                    sink
1338                },
1339            );
1340            if n_dirs >= 12 {
1341                gate.faster(
1342                    &format!("K={n_dirs}"),
1343                    &timing,
1344                    "compensated",
1345                    "partition_sum",
1346                );
1347            } else {
1348                eprintln!(
1349                    "COMPOSE-UNARY-932 K={n_dirs} {} (below the counted crossover; not gated)",
1350                    timing.summary("compensated", "partition_sum"),
1351                );
1352            }
1353        }
1354        gate.finish();
1355    }
1356}