use crate::dual::{Du, Lane, Ou, Qu};
use crate::dv::{DDotAcc, DV};
use crate::field::Fl;
use crate::ov::{ODotAcc, OV};
use crate::qv::{QDotAcc, QV};
use crate::simd::Simd;
use crate::v8::V8;
use std::sync::OnceLock;
const LN: usize = 8;
const DB: i32 = 16;
const R16: f64 = 65536.0;
const IR16: f64 = 1.0 / 65536.0;
const LMAX_LOG2: usize = 13;
const TILE: usize = 1 << (LMAX_LOG2 - 1);
const T_MAX: usize = 60;
type L8 = [f64; LN];
pub trait Expansion<S: Simd>: Copy + Send + Sync + 'static {
const NP: usize;
const PROD_S: f64;
type Acc: Copy + Send + Sync + 'static;
fn part(&self, i: usize) -> V8<S>;
fn from_parts(p: &[V8<S>]) -> Self;
fn acc_zero() -> Self::Acc;
fn acc_prod(acc: &mut Self::Acc, a: &Self, b: &Self);
fn acc_parts(acc: &mut Self::Acc, p: &[V8<S>]);
fn acc_fin(acc: &Self::Acc) -> Self;
}
impl<S: Simd> Expansion<S> for DV<S> {
const NP: usize = 2;
const PROD_S: f64 = 6e-9;
type Acc = DDotAcc<S>;
#[inline(always)]
fn part(&self, i: usize) -> V8<S> {
if i == 0 {
self.hi
} else {
self.lo
}
}
#[inline(always)]
fn from_parts(p: &[V8<S>]) -> Self {
DV { hi: p[0], lo: p[1] }
}
#[inline(always)]
fn acc_zero() -> Self::Acc {
DDotAcc::zero()
}
#[inline(always)]
fn acc_prod(acc: &mut Self::Acc, a: &Self, b: &Self) {
*acc = acc.add_prod(*a, *b);
}
#[inline(always)]
fn acc_parts(acc: &mut Self::Acc, p: &[V8<S>]) {
*acc = acc.add(DV { hi: p[0], lo: p[1] });
}
#[inline(always)]
fn acc_fin(acc: &Self::Acc) -> Self {
acc.finish()
}
}
impl<S: Simd> Expansion<S> for QV<S> {
const NP: usize = 4;
const PROD_S: f64 = 50e-9;
type Acc = QDotAcc<S>;
#[inline(always)]
fn part(&self, i: usize) -> V8<S> {
self.c[i]
}
#[inline(always)]
fn from_parts(p: &[V8<S>]) -> Self {
QV {
c: [p[0], p[1], p[2], p[3]],
}
}
#[inline(always)]
fn acc_zero() -> Self::Acc {
QDotAcc::zero()
}
#[inline(always)]
fn acc_prod(acc: &mut Self::Acc, a: &Self, b: &Self) {
acc.add_prod_mut(a, b);
}
#[inline(always)]
fn acc_parts(acc: &mut Self::Acc, p: &[V8<S>]) {
*acc = acc.add(QV {
c: [p[0], p[1], p[2], p[3]],
});
}
#[inline(always)]
fn acc_fin(acc: &Self::Acc) -> Self {
acc.finish()
}
}
impl<S: Simd> Expansion<S> for OV<S> {
const NP: usize = 8;
const PROD_S: f64 = 0.6e-6;
type Acc = ODotAcc<S>;
#[inline(always)]
fn part(&self, i: usize) -> V8<S> {
self.c[i]
}
#[inline(always)]
fn from_parts(p: &[V8<S>]) -> Self {
OV {
c: std::array::from_fn(|i| p[i]),
}
}
#[inline(always)]
fn acc_zero() -> Self::Acc {
ODotAcc::zero()
}
#[inline(always)]
fn acc_prod(acc: &mut Self::Acc, a: &Self, b: &Self) {
acc.add_prod_mut(a, b);
}
#[inline(always)]
fn acc_parts(acc: &mut Self::Acc, p: &[V8<S>]) {
*acc = acc.add(OV {
c: std::array::from_fn(|i| p[i]),
});
}
#[inline(always)]
fn acc_fin(acc: &Self::Acc) -> Self {
acc.finish()
}
}
#[derive(Clone, Copy, Debug)]
pub struct Cfg {
pub prec: i32,
pub spread: i32,
pub scale: bool,
pub blocks: bool,
pub mutate: u8,
}
pub const MUT_ZERO_LANE: u8 = 1;
pub const MUT_E2_PLAIN: u8 = 2;
pub const MUT_E2_SPLIT_ALWAYS: u8 = 4;
pub const MUT_E2_PRESCALE: u8 = 5;
pub const MUT_DROP_PAIR: u8 = 6;
pub const MUT_SLOPE: u8 = 7;
pub const MUT_CHUNK_TOP: u8 = 8;
pub const MUT_DROP_TILE: u8 = 9;
pub const MUT_NO_TILE: u8 = 10;
impl Default for Cfg {
fn default() -> Self {
Cfg {
prec: 0,
spread: 32,
scale: true,
blocks: true,
mutate: 0,
}
}
}
impl Cfg {
fn prec_of<S: Simd, E: Expansion<S>>(&self) -> Cfg {
Cfg {
prec: if self.prec > 0 { self.prec } else { 53 * E::NP as i32 },
..*self
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Stats {
pub calls: usize,
pub pairs: usize,
pub direct: usize,
pub tiles: usize,
pub fallback: usize,
pub blocks: (usize, usize),
pub max_frac: f64,
pub digits: usize,
}
impl Stats {
pub fn merge(&mut self, o: &Stats) {
self.calls += o.calls;
self.pairs += o.pairs;
self.direct += o.direct;
self.tiles += o.tiles;
self.fallback += o.fallback;
self.blocks = (self.blocks.0.max(o.blocks.0), self.blocks.1.max(o.blocks.1));
self.max_frac = self.max_frac.max(o.max_frac);
self.digits = self.digits.max(o.digits);
}
}
pub fn mullow_naive<S: Simd, E: Expansion<S>>(a: &[E], b: &[E], n: usize) -> Vec<E> {
(0..n)
.map(|k| {
let mut acc = E::acc_zero();
for i in 0..a.len().min(k + 1) {
if k - i < b.len() {
E::acc_prod(&mut acc, &a[i], &b[k - i]);
}
}
E::acc_fin(&acc)
})
.collect()
}
pub fn mullow<S: Simd, E: Expansion<S>>(a: &[E], b: &[E], n: usize, cfg: &Cfg, acc: &mut [E::Acc]) -> Stats {
mullow_pow2(a, b, n, cfg, 0, acc)
}
pub fn mullow_pow2<S: Simd, E: Expansion<S>>(
a: &[E],
b: &[E],
n: usize,
cfg: &Cfg,
e2: i32,
acc: &mut [E::Acc],
) -> Stats {
let cfg = &cfg.prec_of::<S, E>();
let (na, nb) = (a.len().min(n), b.len().min(n));
let mut st = Stats {
calls: 1,
..Stats::default()
};
if na == 0 || nb == 0 || n == 0 {
return st;
}
let finite = |v: &[E]| {
v.iter()
.all(|x| (0..E::NP).all(|p| x.part(p).to_array().iter().all(|q| q.is_finite())))
};
if !finite(&a[..na]) || !finite(&b[..nb]) {
st.max_frac = f64::INFINITY;
st.pairs = 1;
st.direct = 1;
direct(&a[..na], &b[..nb], 0, n, cfg, e2, acc);
return st;
}
let (ea, eb) = (exponents(&a[..na]), exponents(&b[..nb]));
let (fa, fb): ([f64; LN], [f64; LN]) = (
std::array::from_fn(|l| fit(&ea, l)),
std::array::from_fn(|l| fit(&eb, l)),
);
let slopes: Vec<[i32; LN]> = if cfg.scale {
vec![
std::array::from_fn(|l| (-(fa[l] + fb[l]) * 0.5).round() as i32),
std::array::from_fn(|l| (-fa[l]).round() as i32),
std::array::from_fn(|l| (-fb[l]).round() as i32),
]
} else {
vec![[0; LN]]
};
let limits: &[i32] = if cfg.blocks { &[1, 2, 4] } else { &[1] };
let mut best: Option<Choice> = None;
for sl in &slopes {
for &m in limits {
let h = cfg.spread * m;
let (ba, bb) = (blocks(&ea, sl, h, cfg), blocks(&eb, sl, h, cfg));
let c = cost::<S, E>(&ba, &bb, n, cfg);
if best.as_ref().is_none_or(|b| c < b.0) {
best = Some((c, *sl, ba, bb));
}
}
}
let (_, s, ba, bb) = best.expect("a slope and a limit");
let (ba, bb) = if cfg.blocks {
shorten::<S, E>(ba, bb, &ea, &eb, &s, n, cfg)
} else {
(ba, bb)
};
st.blocks = (ba.len(), bb.len());
thread_local! {
static WS: std::cell::RefCell<Option<Box<dyn std::any::Any>>> = const { std::cell::RefCell::new(None) };
}
WS.with(|w| {
let mut w = w.borrow_mut();
if !w.as_ref().is_some_and(|x| x.is::<Work<S>>()) {
*w = Some(Box::new(Work::<S>::new()));
}
let ws = w
.as_mut()
.and_then(|x| x.downcast_mut::<Work<S>>())
.expect("this backend's scratch");
mullow_pairs(a, b, n, cfg, e2, acc, &ba, &bb, &s, &mut st, ws);
});
st
}
type Choice = (f64, [i32; LN], Vec<Block>, Vec<Block>);
#[allow(clippy::too_many_arguments)]
fn mullow_pairs<S: Simd, E: Expansion<S>>(
a: &[E],
b: &[E],
n: usize,
cfg: &Cfg,
e2: i32,
acc: &mut [E::Acc],
ba: &[Block],
bb: &[Block],
s: &[i32; LN],
st: &mut Stats,
ws: &mut Work<S>,
) {
let mut drop = None;
if cfg.mutate == MUT_DROP_PAIR {
'find: for (ia, xa) in ba.iter().enumerate() {
for (ib, xb) in bb.iter().enumerate() {
let o = xa.start + xb.start;
if o < n {
let (la, lb) = ((xa.end - xa.start).min(n - o), (xb.end - xb.start).min(n - o));
if plan(cfg, xa.spread, xb.spread, la, lb).is_some() {
drop = Some((ia, ib));
break 'find;
}
}
}
}
}
for (ia, xa) in ba.iter().enumerate() {
for (ib, xb) in bb.iter().enumerate() {
let o = xa.start + xb.start;
if o >= n {
continue;
}
st.pairs += 1;
let (x, y) = (&a[xa.start..xa.end], &b[xb.start..xb.end]);
let (la, lb) = (x.len().min(n - o), y.len().min(n - o));
if plan(cfg, xa.spread, xb.spread, la, lb).is_none() || (cfg.mutate == MUT_NO_TILE && tiled(la, lb)) {
st.direct += 1;
direct(x, y, o, n - o, cfg, e2, acc);
continue;
}
if drop == Some((ia, ib)) {
continue;
}
if !tiled(la, lb) {
if !pair(x, y, xa, xb, s, n - o, o, cfg, e2, acc, st, ws) {
st.fallback += 1;
direct(x, y, o, n - o, cfg, e2, acc);
}
continue;
}
for (i0, j0, ta, tb) in tiles(la, lb, o, n) {
st.tiles += 1;
if cfg.mutate == MUT_DROP_TILE && st.tiles == 1 {
continue;
}
let (u, v) = (&x[i0..i0 + ta], &y[j0..j0 + tb]);
let (ua, vb) = (
Block {
start: xa.start + i0,
end: xa.start + i0 + ta,
..xa.clone()
},
Block {
start: xb.start + j0,
end: xb.start + j0 + tb,
..xb.clone()
},
);
let (ot, nt) = (o + i0 + j0, n - o - i0 - j0);
if !pair(u, v, &ua, &vb, s, nt, ot, cfg, e2, acc, st, ws) {
st.fallback += 1;
direct(u, v, ot, nt, cfg, e2, acc);
}
}
}
}
}
fn tiled(la: usize, lb: usize) -> bool {
la + lb - 1 > 1 << LMAX_LOG2
}
fn tiles(la: usize, lb: usize, o: usize, n: usize) -> impl Iterator<Item = (usize, usize, usize, usize)> {
(0..la).step_by(TILE).flat_map(move |i0| {
(0..lb).step_by(TILE).filter_map(move |j0| {
let nt = n.checked_sub(o + i0 + j0).filter(|&v| v > 0)?;
Some((i0, j0, TILE.min(la - i0).min(nt), TILE.min(lb - j0).min(nt)))
})
})
}
fn direct<S: Simd, E: Expansion<S>>(x: &[E], y: &[E], o: usize, nout: usize, cfg: &Cfg, e2: i32, acc: &mut [E::Acc]) {
let nout = nout.min(x.len() + y.len() - 1);
let prescale = (e2 != 0 && cfg.mutate == MUT_E2_PRESCALE) || (e2 == 0 && cfg.mutate == MUT_E2_SPLIT_ALWAYS);
let plain = e2 != 0 && cfg.mutate == MUT_E2_PLAIN;
if e2 != 0 && !prescale && !plain {
let ex = |v: &E| -> [i32; LN] { v.part(0).to_array().map(|p| if p == 0.0 { 0 } else { expo(p) }) };
let (xe, ye): (Vec<_>, Vec<_>) = (x.iter().map(ex).collect(), y.iter().map(ex).collect());
for k in 0..nout {
for i in k.saturating_sub(y.len() - 1)..x.len().min(k + 1) {
let al: [i32; LN] = std::array::from_fn(|l| (ye[k - i][l] - xe[i][l] + e2).div_euclid(2));
let be: [i32; LN] = std::array::from_fn(|l| e2 - al[l]);
E::acc_prod(&mut acc[o + k], &scale_lanes(&x[i], &al), &scale_lanes(&y[k - i], &be));
}
}
return;
}
let (xs, ys) = if plain {
let f = V8::splat(2f64.powi(e2));
let pl = |v: &E| -> E {
let p: Vec<V8<S>> = (0..E::NP).map(|i| v.part(i).mul(f)).collect();
E::from_parts(&p)
};
(x.iter().map(pl).collect::<Vec<_>>(), y.to_vec())
} else if prescale {
let top = |v: &[E]| -> [i32; LN] {
std::array::from_fn(|l| {
v.iter()
.map(|c| c.part(0).to_array()[l])
.filter(|&p| p != 0.0)
.map(expo)
.max()
.unwrap_or(0)
})
};
let (tx, ty) = (top(x), top(y));
let al: [i32; LN] = std::array::from_fn(|l| (ty[l] - tx[l] + e2).div_euclid(2));
let be: [i32; LN] = std::array::from_fn(|l| e2 - al[l]);
(
x.iter().map(|v| scale_lanes(v, &al)).collect(),
y.iter().map(|v| scale_lanes(v, &be)).collect(),
)
} else {
(x.to_vec(), y.to_vec())
};
for k in 0..nout {
for i in k.saturating_sub(ys.len() - 1)..xs.len().min(k + 1) {
E::acc_prod(&mut acc[o + k], &xs[i], &ys[k - i]);
}
}
}
fn exponents<S: Simd, E: Expansion<S>>(a: &[E]) -> Vec<[i32; LN]> {
a.iter()
.map(|v| v.part(0).to_array().map(|x| if x == 0.0 { i32::MIN } else { expo(x) }))
.collect()
}
#[inline]
fn expo(x: f64) -> i32 {
let b = x.to_bits();
let ex = ((b >> 52) & 0x7ff) as i32;
if ex == 0 {
-1010 - (b & ((1u64 << 52) - 1)).leading_zeros() as i32
} else {
ex - 1022
}
}
fn fit(e: &[[i32; LN]], l: usize) -> f64 {
let (mut n, mut sx, mut sy, mut sxx, mut sxy) = (0.0, 0.0, 0.0, 0.0, 0.0);
for (i, v) in e.iter().enumerate() {
if v[l] != i32::MIN {
let (x, y) = (i as f64, v[l] as f64);
n += 1.0;
sx += x;
sy += y;
sxx += x * x;
sxy += x * y;
}
}
let d = n * sxx - sx * sx;
if n < 2.0 || d <= 0.0 {
0.0
} else {
(n * sxy - sx * sy) / d
}
}
#[derive(Clone)]
struct Block {
start: usize,
end: usize,
frame: [i32; LN],
spread: i32,
}
fn blocks(e: &[[i32; LN]], s: &[i32; LN], h: i32, cfg: &Cfg) -> Vec<Block> {
let mut out = Vec::new();
let mut start = 0;
let (mut lo, mut hi) = ([i32::MAX; LN], [i32::MIN; LN]);
let close = |start: usize, end: usize, lo: &[i32; LN], hi: &[i32; LN], out: &mut Vec<Block>| {
let spread = (0..LN)
.filter(|&l| hi[l] != i32::MIN)
.map(|l| hi[l] - lo[l])
.max()
.unwrap_or(0);
let frame = std::array::from_fn(|l| if hi[l] == i32::MIN { 0 } else { hi[l] });
out.push(Block {
start,
end,
frame,
spread: if cfg.blocks { spread } else { cfg.spread },
});
};
for (i, v) in e.iter().enumerate() {
let mut split = false;
let mut nlo = lo;
let mut nhi = hi;
for l in 0..LN {
if v[l] != i32::MIN {
let x = v[l] + s[l] * i as i32;
nlo[l] = nlo[l].min(x);
nhi[l] = nhi[l].max(x);
split |= nhi[l] - nlo[l] > h;
}
}
if split && cfg.blocks && i > start {
close(start, i, &lo, &hi, &mut out);
start = i;
for l in 0..LN {
let x = v[l].saturating_add(s[l] * i as i32);
(lo[l], hi[l]) = if v[l] == i32::MIN { (i32::MAX, i32::MIN) } else { (x, x) };
}
} else {
(lo, hi) = (nlo, nhi);
}
}
close(start, e.len(), &lo, &hi, &mut out);
out
}
fn block_of(e: &[[i32; LN]], s: &[i32; LN], start: usize, end: usize, cfg: &Cfg) -> Block {
let (mut lo, mut hi) = ([i32::MAX; LN], [i32::MIN; LN]);
for (i, v) in e.iter().enumerate().take(end).skip(start) {
for l in 0..LN {
if v[l] != i32::MIN {
let x = v[l] + s[l] * i as i32;
lo[l] = lo[l].min(x);
hi[l] = hi[l].max(x);
}
}
}
let spread = (0..LN)
.filter(|&l| hi[l] != i32::MIN)
.map(|l| hi[l] - lo[l])
.max()
.unwrap_or(0);
let frame = std::array::from_fn(|l| if hi[l] == i32::MIN { 0 } else { hi[l] });
Block {
start,
end,
frame,
spread: if cfg.blocks { spread } else { cfg.spread },
}
}
#[allow(clippy::too_many_arguments)]
fn shorten<S: Simd, E: Expansion<S>>(
ba: Vec<Block>,
bb: Vec<Block>,
ea: &[[i32; LN]],
eb: &[[i32; LN]],
s: &[i32; LN],
n: usize,
cfg: &Cfg,
) -> (Vec<Block>, Vec<Block>) {
let (mut ba, mut bb) = (ba, bb);
for side in 0..2 {
let (xs, ys, ex) = if side == 0 { (&ba, &bb, ea) } else { (&bb, &ba, eb) };
let y0 = &ys[0];
let mut cut: Vec<Block> = Vec::with_capacity(xs.len() + 1);
for x in xs {
let o = x.start + y0.start;
let fits = o < n && {
let (la, lb) = ((x.end - x.start).min(n - o), (y0.end - y0.start).min(n - o));
let p = la + lb - 1;
let l = p.next_power_of_two();
let at = x.start + (l / 2 + 1).saturating_sub(lb);
if p > l / 2 && n - o <= l / 2 && at > x.start && at < x.start + la {
cut.push(block_of(ex, s, x.start, at, cfg));
cut.push(block_of(ex, s, at, x.end, cfg));
true
} else {
false
}
};
if !fits {
cut.push(x.clone());
}
}
if cut.len() > xs.len() {
let c0 = cost::<S, E>(&ba, &bb, n, cfg);
let c1 = if side == 0 {
cost::<S, E>(&cut, &bb, n, cfg)
} else {
cost::<S, E>(&ba, &cut, n, cfg)
};
if c1 < c0 {
if side == 0 {
ba = cut;
} else {
bb = cut;
}
}
}
}
(ba, bb)
}
struct Plan {
t: usize,
w: i32,
q0: usize,
nq: usize,
}
fn plan(cfg: &Cfg, ha: i32, hb: i32, la: usize, lb: usize) -> Option<Plan> {
let t = ((cfg.prec + ha.max(hb) + 7 + DB - 1) / DB) as usize;
let t = t + t % 2;
if t > T_MAX {
return None;
}
let w = DB * t as i32 - 2;
let lg = ((t * la.min(lb)) as f64).log2().ceil() as i32;
let q0 = (((2 * w - ha - hb - 2 - cfg.prec - 14 - lg) / DB).max(0) as usize).min(2 * t - 2);
let nq = (2 * t - 1 - q0).div_ceil(2) * 2;
Some(Plan { t, w, q0, nq })
}
fn cost<S: Simd, E: Expansion<S>>(ba: &[Block], bb: &[Block], n: usize, cfg: &Cfg) -> f64 {
let mut c = 0.0;
for xa in ba {
for xb in bb {
let o = xa.start + xb.start;
if o >= n {
continue;
}
let (la, lb) = ((xa.end - xa.start).min(n - o), (xb.end - xb.start).min(n - o));
if plan(cfg, xa.spread, xb.spread, la, lb).is_none() {
c += E::PROD_S * (la * lb) as f64;
} else if !tiled(la, lb) {
c += pair_cost::<S, E>(cfg, xa.spread, xb.spread, la, lb, n - o);
} else {
for (i0, j0, ta, tb) in tiles(la, lb, o, n) {
c += pair_cost::<S, E>(cfg, xa.spread, xb.spread, ta, tb, n - o - i0 - j0);
}
}
}
}
c
}
fn pair_cost<S: Simd, E: Expansion<S>>(cfg: &Cfg, ha: i32, hb: i32, la: usize, lb: usize, nout: usize) -> f64 {
let np = E::NP as f64 / 8.0;
let pl = plan(cfg, ha, hb, la, lb).expect("a pair within T_MAX digits");
let lc = (la + lb - 1).min(nout);
let l = (la + lb - 1).next_power_of_two();
let prods: usize = (pl.q0..=2 * pl.t - 2)
.map(|q| q.min(pl.t - 1) - q.saturating_sub(pl.t - 1) + 1)
.sum();
let bfly = (l / 2) as f64 * (l as f64).log2().max(1.0);
0.76e-6 * np * (la + lb) as f64
+ 6.5e-9 * (pl.t + pl.nq / 2) as f64 * bfly
+ 6.2e-9 * (l / 2 + 1) as f64 * prods as f64
+ 1.1e-6 * np * lc as f64
}
#[inline(always)]
fn pow2(e: i32) -> f64 {
f64::from_bits(((e + 1023) as u64) << 52)
}
fn scalbn(mut x: f64, mut n: i32) -> f64 {
const SUB: i32 = 1022 - 53;
if n > 1023 {
x *= pow2(1023);
n -= 1023;
if n > 1023 {
x *= pow2(1023);
n = (n - 1023).min(1023);
}
} else if n < -1022 {
x *= pow2(-SUB);
n += SUB;
if n < -1022 {
x *= pow2(-SUB);
n = (n + SUB).max(-1022);
}
}
x * pow2(n)
}
fn scale_lanes<S: Simd, E: Expansion<S>>(v: &E, e: &[i32; LN]) -> E {
let p: Vec<V8<S>> = (0..E::NP)
.map(|i| V8::from_array(std::array::from_fn(|l| scalbn(v.part(i).to_array()[l], e[l]))))
.collect();
E::from_parts(&p)
}
#[inline(always)]
fn pow2_split(e: &[i32; LN]) -> (L8, L8) {
(
std::array::from_fn(|l| pow2(e[l] / 2)),
std::array::from_fn(|l| pow2(e[l] - e[l] / 2)),
)
}
const MAGIC: f64 = 6755399441055744.0;
#[inline(always)]
fn rnd<S: Simd>(x: V8<S>) -> V8<S> {
let m = V8::splat(MAGIC);
x.add(m).sub(m)
}
#[doc(hidden)]
pub fn digits<S: Simd, E: Expansion<S>>(x: &E, k: &[i32; LN], t: usize, d: &mut [V8<S>]) {
let (f1, f2) = pow2_split(k);
let (f1, f2) = (V8::from_array(f1), V8::from_array(f2));
for dr in d.iter_mut().take(t) {
*dr = V8::zero();
}
let (one, inf) = (V8::splat(1.0), V8::splat(f64::INFINITY));
for pi in 0..E::NP {
let mut rem = x.part(pi).mul(f1).mul(f2);
let a = rem.abs();
let amax = a.hmax();
if amax < 0.5 {
continue;
}
let amin = -a.ge(one).sel(a, inf).neg().hmax();
let rhi = (((expo(amax) - 1).max(0) / DB) as usize).min(t - 1);
let rlo = if amin.is_finite() {
((expo(amin) - 54).max(0) / DB) as usize
} else {
0
};
for r in (rlo.min(rhi)..=rhi).rev() {
let q = rnd(rem.mul(V8::splat(pow2(-DB * r as i32))));
d[r] = d[r].add(q);
rem = rem.sub(q.mul(V8::splat(pow2(DB * r as i32))));
}
}
let (ir, r16) = (V8::splat(IR16), V8::splat(R16));
let mut carry = V8::zero();
for dr in d.iter_mut().take(t) {
let v = dr.add(carry);
let hi = rnd(v.mul(ir));
*dr = v.sub(hi.mul(r16));
carry = hi;
}
debug_assert!(
carry.to_array().iter().all(|&c| c == 0.0 || !c.is_finite()),
"digits: |x 2^k| too large"
);
}
fn parts_of(d: &[L8], ln: usize, e: i32, out: &mut [f64]) {
const NL: usize = T_MAX / 2 + 3;
let nl = d.len().div_ceil(4) + 1;
assert!(nl <= NL, "parts_of: {} digits", d.len());
let mut w = [0u64; NL];
let mut carry: i128 = 0;
for (li, wl) in w.iter_mut().enumerate().take(nl) {
let mut v = carry;
for j in 0..4 {
if let Some(dq) = d.get(4 * li + j) {
v += (dq[ln] as i64 as i128) << (16 * j);
}
}
*wl = v as u64;
carry = v >> 64;
}
let neg = carry < 0;
if neg {
let mut c = true;
for wl in w.iter_mut().take(nl) {
let (r, cc) = (!*wl).overflowing_add(c as u64);
*wl = r;
c = cc;
}
}
let Some(top) = (0..nl).rev().find(|&i| w[i] != 0) else {
out.fill(0.0);
return;
};
let hb = 64 * top as i64 + 63 - w[top].leading_zeros() as i64;
let bit = |b: i64| -> u64 {
if b + 53 <= 0 {
return 0;
}
let (bb, sh) = if b < 0 { (0, -b) } else { (b, 0) };
let (li, bo) = ((bb / 64) as usize, (bb % 64) as u32);
let lo = w[li] >> bo;
let hi = if bo > 0 && li + 1 < nl {
w[li + 1] << (64 - bo)
} else {
0
};
(((lo | hi) & ((1u64 << 53) - 1)) << sh) & ((1u64 << 53) - 1)
};
let sg = if neg { -1.0 } else { 1.0 };
for (j, o) in out.iter_mut().enumerate() {
let b = hb - 52 - 53 * j as i64;
let c = bit(b);
*o = if c == 0 {
0.0
} else {
let ex = (b + e as i64).clamp(-4000, 4000) as i32;
scalbn(sg * c as f64, ex)
};
}
}
struct Tables {
tw: Vec<(f64, f64)>,
rev: Vec<usize>,
}
fn tables(m: usize) -> &'static Tables {
static T: OnceLock<Vec<Tables>> = OnceLock::new();
&T.get_or_init(|| {
(0..=LMAX_LOG2)
.map(|m| {
let l = 1usize << m;
let tw = (0..l / 2)
.map(|k| {
let a = -2.0 * std::f64::consts::PI * k as f64 / l as f64;
(a.cos(), a.sin())
})
.collect();
let rev = (0..l)
.map(|i| {
if m == 0 {
0
} else {
i.reverse_bits() >> (usize::BITS as usize - m)
}
})
.collect();
Tables { tw, rev }
})
.collect()
})[m]
}
type C8<S> = [V8<S>; 2];
#[inline(always)]
fn c0<S: Simd>() -> C8<S> {
[V8::zero(), V8::zero()]
}
fn fft_dif<S: Simd>(x: &mut [C8<S>], tb: &Tables, nz: usize) {
let l = x.len();
let mut h = l / 2;
let mut first = true;
while h >= 1 {
let step = l / (2 * h);
for g in (0..l).step_by(2 * h) {
let (lo, hi) = x[g..g + 2 * h].split_at_mut(h);
for (k, (a, b)) in lo.iter_mut().zip(hi.iter_mut()).enumerate() {
let (wr, wi) = tb.tw[k * step];
let (wr, wi) = (V8::splat(wr), V8::splat(wi));
if first && g + k + h >= nz {
if g + k >= nz {
continue;
}
let (ur, ui) = (a[0], a[1]);
*b = [ur.fma(wr, ui.mul(wi).neg()), ur.fma(wi, ui.mul(wr))];
} else {
let (ur, ui, vr, vi) = (a[0], a[1], b[0], b[1]);
*a = [ur.add(vr), ui.add(vi)];
let (dr, di) = (ur.sub(vr), ui.sub(vi));
*b = [dr.fma(wr, di.mul(wi).neg()), dr.fma(wi, di.mul(wr))];
}
}
}
first = false;
h /= 2;
}
}
fn ifft_dit<S: Simd>(x: &mut [C8<S>], tb: &Tables) {
let l = x.len();
let mut h = 1;
while h < l {
let step = l / (2 * h);
for g in (0..l).step_by(2 * h) {
let (lo, hi) = x[g..g + 2 * h].split_at_mut(h);
for (k, (a, b)) in lo.iter_mut().zip(hi.iter_mut()).enumerate() {
let (wr, wi) = tb.tw[k * step];
let (wr, wi) = (V8::splat(wr), V8::splat(wi));
let (vr, vi) = (b[0], b[1]);
let tr = vr.fma(wr, vi.mul(wi));
let ti = vi.fma(wr, vr.mul(wi).neg());
let (ur, ui) = (a[0], a[1]);
*a = [ur.add(tr), ui.add(ti)];
*b = [ur.sub(tr), ui.sub(ti)];
}
}
h *= 2;
}
}
struct Work<S: Simd> {
xs: Vec<C8<S>>,
ys: Vec<C8<S>>,
vs: Vec<C8<S>>,
dig: Vec<V8<S>>,
dl: Vec<L8>,
xh: Vec<[V8<S>; 3]>,
yh: Vec<[V8<S>; 2]>,
cq: Vec<V8<S>>,
}
impl<S: Simd> Work<S> {
fn new() -> Self {
Work {
xs: Vec::new(),
ys: Vec::new(),
vs: Vec::new(),
dig: Vec::new(),
dl: Vec::new(),
xh: Vec::new(),
yh: Vec::new(),
cq: Vec::new(),
}
}
}
#[allow(clippy::too_many_arguments)]
fn load<S: Simd, E: Expansion<S>>(
a: &[E],
len: usize,
start: usize,
frame: &[i32; LN],
s: &[i32; LN],
t: usize,
l: usize,
xs: &mut Vec<C8<S>>,
dig: &mut Vec<V8<S>>,
tb: &Tables,
mutate: u8,
) {
let w = DB * t as i32 - 2;
xs.clear();
xs.resize(t / 2 * l, c0());
dig.resize(t, V8::zero());
for (i, v) in a.iter().enumerate().take(len) {
let hi = v.part(0).to_array();
let k: [i32; LN] = std::array::from_fn(|ln| {
if hi[ln] == 0.0 && mutate != MUT_ZERO_LANE {
0
} else {
s[ln] * (start + i) as i32 + w - frame[ln]
}
});
digits(v, &k, t, dig);
for u in 0..t / 2 {
xs[u * l + i] = [dig[2 * u], dig[2 * u + 1]];
}
}
for slab in xs.chunks_exact_mut(l) {
fft_dif(slab, tb, len);
}
}
#[inline(always)]
fn unpack3<S: Simd>(z: &C8<S>, w: &C8<S>) -> ([V8<S>; 3], [V8<S>; 3]) {
let (zr, zi, wr, wi) = (z[0], z[1], w[0], w[1]);
let (ei, oi) = (zi.sub(wi), wr.sub(zr));
([zr.add(wr), ei, ei.neg()], [zi.add(wi), oi, oi.neg()])
}
#[inline(always)]
fn unpack2<S: Simd>(z: &C8<S>, w: &C8<S>) -> ([V8<S>; 2], [V8<S>; 2]) {
let (zr, zi, wr, wi) = (z[0], z[1], w[0], w[1]);
([zr.add(wr), zi.sub(wi)], [zi.add(wi), wr.sub(zr)])
}
#[inline(always)]
fn cmac<S: Simd>(ar: &mut V8<S>, ai: &mut V8<S>, x: &[V8<S>; 3], y: &[V8<S>; 2]) {
*ar = x[0].fma(y[0], x[2].fma(y[1], *ar));
*ai = x[0].fma(y[1], x[1].fma(y[0], *ai));
}
#[inline(always)]
fn conv<S: Simd>(x: &[[V8<S>; 3]], y: &[[V8<S>; 2]], t: usize, q0: usize, c: &mut [V8<S>]) {
let qe = 2 * t - 2;
let mut q = q0;
while q < qe {
let (lo, hi) = (q.saturating_sub(t - 1), q.min(t - 1));
let (lo1, hi1) = ((q + 1).saturating_sub(t - 1), (q + 1).min(t - 1));
let (mut ar, mut ai, mut br, mut bi) = (V8::zero(), V8::zero(), V8::zero(), V8::zero());
if lo < lo1 {
cmac(&mut ar, &mut ai, &x[lo], &y[q - lo]);
}
let mut p = y[q + 1 - lo1];
for (xv, y0) in x[lo1..=hi].iter().zip(y[q - hi..=q - lo1].iter().rev()) {
ar = xv[0].fma(y0[0], xv[2].fma(y0[1], ar));
ai = xv[0].fma(y0[1], xv[1].fma(y0[0], ai));
br = xv[0].fma(p[0], xv[2].fma(p[1], br));
bi = xv[0].fma(p[1], xv[1].fma(p[0], bi));
p = *y0;
}
if hi1 > hi {
cmac(&mut br, &mut bi, &x[hi1], &y[q + 1 - hi1]);
}
let j = 2 * (q - q0);
c[j] = ar;
c[j + 1] = ai;
c[j + 2] = br;
c[j + 3] = bi;
q += 2;
}
if q == qe {
let (lo, hi) = (q.saturating_sub(t - 1), q.min(t - 1));
let (mut ar, mut ai) = (V8::zero(), V8::zero());
for (xv, yv) in x[lo..=hi].iter().zip(y[q - hi..=q - lo].iter().rev()) {
cmac(&mut ar, &mut ai, xv, yv);
}
let j = 2 * (q - q0);
c[j] = ar;
c[j + 1] = ai;
}
}
#[allow(clippy::too_many_arguments)]
fn pair<S: Simd, E: Expansion<S>>(
x: &[E],
y: &[E],
xa: &Block,
xb: &Block,
s: &[i32; LN],
nout: usize,
o: usize,
cfg: &Cfg,
e2: i32,
acc: &mut [E::Acc],
st: &mut Stats,
ws: &mut Work<S>,
) -> bool {
let (la, lb) = (x.len().min(nout), y.len().min(nout));
let lc = (la + lb - 1).min(nout);
let m = (la + lb - 1).next_power_of_two().trailing_zeros() as usize;
debug_assert!(m <= LMAX_LOG2, "series: block pair of {} terms", la + lb - 1);
let l = 1usize << m;
let tb = tables(m);
let Plan { t, w, q0, nq } = plan(cfg, xa.spread, xb.spread, la, lb).expect("a pair within T_MAX digits");
st.digits = st.digits.max(t);
load(
x,
la,
xa.start,
&xa.frame,
s,
t,
l,
&mut ws.xs,
&mut ws.dig,
tb,
cfg.mutate,
);
load(
y,
lb,
xb.start,
&xb.frame,
s,
t,
l,
&mut ws.ys,
&mut ws.dig,
tb,
cfg.mutate,
);
ws.vs.clear();
ws.vs.resize(nq / 2 * l, c0());
ws.xh.resize(t, [V8::zero(); 3]);
ws.yh.resize(t, [V8::zero(); 2]);
ws.cq.resize(2 * nq, V8::zero());
for c in ws.cq[2 * (2 * t - 1 - q0)..].iter_mut() {
*c = V8::zero();
}
for f in 0..=l / 2 {
let (pf, pg) = (tb.rev[f], tb.rev[(l - f) & (l - 1)]);
for u in 0..t / 2 {
(ws.xh[2 * u], ws.xh[2 * u + 1]) = unpack3(&ws.xs[u * l + pf], &ws.xs[u * l + pg]);
(ws.yh[2 * u], ws.yh[2 * u + 1]) = unpack2(&ws.ys[u * l + pf], &ws.ys[u * l + pg]);
}
conv(&ws.xh, &ws.yh, t, q0, &mut ws.cq);
for u in 0..nq / 2 {
let (er, ei, or, oi) = (ws.cq[4 * u], ws.cq[4 * u + 1], ws.cq[4 * u + 2], ws.cq[4 * u + 3]);
let (rf, rg) = (u * l + pf, u * l + pg);
if pf == pg {
ws.vs[rf] = [er, or];
} else {
ws.vs[rf] = [er.sub(oi), ei.add(or)];
ws.vs[rg] = [er.add(oi), or.sub(ei)];
}
}
}
for slab in ws.vs.chunks_exact_mut(l) {
ifft_dit(slab, tb);
}
let sc = 0.25 / l as f64;
let scv = V8::splat(sc);
let mut frac = V8::zero();
let mut bad = V8::zero().ne(V8::zero());
for mi in 0..lc {
for qi in 0..nq {
let z = ws.vs[qi / 2 * l + mi][qi % 2].mul(scv);
let e = z.sub(rnd(z)).abs();
bad = bad.or(e.ne(e));
frac = frac.max(e);
}
}
let fr = if bad.bits() != 0 { f64::INFINITY } else { frac.hmax() };
st.max_frac = st.max_frac.max(fr);
if fr.is_nan() || fr >= 0.25 {
return false;
}
let nd = 2 * t + 2 - q0;
ws.dig.resize(nd, V8::zero());
ws.dl.resize(nd, [0.0; LN]);
let (ir, r16) = (V8::splat(IR16), V8::splat(R16));
let ds = (cfg.mutate == MUT_SLOPE) as i32;
let mut pv = [[0.0f64; 8]; LN];
for mi in 0..lc {
let mut carry = V8::zero();
for qi in 0..nd {
let mut v = carry;
if qi < nq {
v = v.add(rnd(ws.vs[qi / 2 * l + mi][qi % 2].mul(scv)));
}
let hi = rnd(v.mul(ir));
ws.dig[qi] = v.sub(hi.mul(r16));
carry = hi;
}
debug_assert!(
carry.to_array().iter().all(|&c| c == 0.0),
"series: digits past the top"
);
let k = o + mi;
let e0: [i32; LN] = std::array::from_fn(|ln| {
xa.frame[ln] + xb.frame[ln] - 2 * w - (s[ln] + ds) * k as i32 + DB * q0 as i32 + e2
});
let nc = nd.div_ceil(3);
let top = e0.iter().copied().max().unwrap_or(0) + 48 * nc as i32;
if E::NP <= 4 && (top <= 960 || cfg.mutate == MUT_CHUNK_TOP) {
let (r16, r32) = (V8::splat(R16), V8::splat(R16 * R16));
for c in (0..nc).rev() {
let q = 3 * c;
let mut v = ws.dig[q];
if q + 1 < nd {
v = v.add(ws.dig[q + 1].mul(r16));
}
if q + 2 < nd {
v = v.add(ws.dig[q + 2].mul(r32));
}
if v.ne(V8::zero()).bits() == 0 {
continue;
}
let ex: [i32; LN] = std::array::from_fn(|ln| (e0[ln] + 48 * c as i32).clamp(-2044, 2044));
let (f1, f2) = pow2_split(&ex);
let mut parts = [V8::zero(); 4];
parts[0] = v.mul(V8::from_array(f1)).mul(V8::from_array(f2));
E::acc_parts(&mut acc[k], &parts[..E::NP]);
}
continue;
}
for (dl, d) in ws.dl.iter_mut().zip(&ws.dig) {
*dl = d.to_array();
}
for (ln, pl) in pv.iter_mut().enumerate() {
parts_of(&ws.dl[..nd], ln, e0[ln], &mut pl[..E::NP]);
}
let parts: [V8<S>; 8] = std::array::from_fn(|q| V8::from_array(std::array::from_fn(|ln| pv[ln][q])));
E::acc_parts(&mut acc[k], &parts[..E::NP]);
}
true
}
pub(crate) fn block_mul_expansion<S: Simd, E: Expansion<S>>(x: &[E], y: &[E], acc: &mut [E::Acc]) {
if !x.is_empty() && !y.is_empty() {
mullow(x, y, acc.len(), &Cfg::default(), acc);
}
}
pub(crate) fn block_mul_dual<S: Simd, E: Expansion<S>, L: Copy>(
x: &[L],
y: &[L],
acc: &mut [(E::Acc, E::Acc)],
vd: impl Fn(&L) -> (E, E),
) {
if x.is_empty() || y.is_empty() {
return;
}
let n = acc.len();
let cfg = Cfg::default();
let (xv, xd): (Vec<E>, Vec<E>) = x.iter().map(&vd).unzip();
let (yv, yd): (Vec<E>, Vec<E>) = y.iter().map(&vd).unzip();
let (mut av, mut ad): (Vec<E::Acc>, Vec<E::Acc>) = acc.iter().copied().unzip();
mullow(&xv, &yv, n, &cfg, &mut av);
mullow(&xv, &yd, n, &cfg, &mut ad);
mullow(&xd, &yv, n, &cfg, &mut ad);
for (a, (v, d)) in acc.iter_mut().zip(av.into_iter().zip(ad)) {
*a = (v, d);
}
}
impl<S: Simd> Du<S> {
pub(crate) fn split(&self) -> (DV<S>, DV<S>) {
(self.v, self.d)
}
}
impl<S: Simd> Qu<S> {
pub(crate) fn split(&self) -> (QV<S>, QV<S>) {
(self.v, self.d)
}
}
impl<S: Simd> Ou<S> {
pub(crate) fn split(&self) -> (OV<S>, OV<S>) {
(self.v, self.d)
}
}
pub const RELAXED_MUT_DROP: u8 = 1;
pub struct Relaxed<T: Lane, const B: usize> {
acc: Vec<Vec<T::Acc>>,
s0: usize,
next: usize,
len: usize,
pub mutate: u8,
pub squares: usize,
pub terms: u64,
}
impl<T: Lane, const B: usize> Relaxed<T, B> {
pub fn new(len: usize) -> Self {
Self::with_min(len, T::BLOCK_MIN)
}
pub fn with_min(len: usize, s0: usize) -> Self {
let s0 = if s0 == 0 { 0 } else { s0.next_power_of_two() };
let acc = if s0 == 0 {
Vec::new()
} else {
(0..B).map(|_| vec![T::acc0(); len]).collect()
};
Relaxed {
acc,
s0,
next: 0,
len,
mutate: 0,
squares: 0,
terms: 0,
}
}
pub fn direct_below(&self) -> usize {
if self.s0 == 0 {
usize::MAX
} else {
self.s0 + 1
}
}
pub fn squares_at(&self, e: usize) -> bool {
self.s0 > 0 && e > 2 * self.s0 && (e - 1).is_multiple_of(self.s0)
}
pub fn step(&mut self, x: &[Fl<T, B>], y: &[Fl<T, B>], e: usize) {
assert_eq!(e, self.next, "Relaxed::step: step {e} after {}", self.next);
self.next += 1;
if self.s0 == 0 || e < 2 || B == 0 {
return;
}
let len = self.len;
let e1 = e - 1;
let mut sq: Vec<(usize, usize, usize)> = Vec::new();
let mut s = self.s0;
while 2 * s <= e1 {
if e1.is_multiple_of(s) {
let m = e1 / s - 1;
if e + 1 < len {
sq.push((m * s + 1, s + 1, s));
if m >= 2 {
sq.push((s + 1, m * s + 1, s));
}
}
}
s *= 2;
}
if sq.is_empty() {
return;
}
assert!(
x.len() >= e && y.len() >= e,
"Relaxed::step: factors of {} and {} coefficients at step {e}",
x.len(),
y.len()
);
if self.mutate == RELAXED_MUT_DROP && self.squares == 0 {
sq.remove(0);
}
self.squares += sq.len();
self.terms += sq.iter().map(|&(_, _, s)| (s * s) as u64).sum::<u64>();
let work: usize = sq.iter().map(|&(_, _, s)| s).sum();
let form = |b: usize, acc: &mut Vec<T::Acc>| {
for &(i0, j0, s) in &sq {
let o = i0 + j0;
let n = (2 * s - 1).min(len - o);
let xs: Vec<T> = x[i0..i0 + s].iter().map(|f| f.0[b]).collect();
let ys: Vec<T> = y[j0..j0 + s].iter().map(|f| f.0[b]).collect();
T::block_mul(&xs, &ys, &mut acc[o..o + n]);
}
};
if B > 1 && work >= 64 {
use rayon::prelude::*;
self.acc.par_iter_mut().enumerate().for_each(|(b, a)| form(b, a));
} else {
for (b, a) in self.acc.iter_mut().enumerate() {
form(b, a);
}
}
}
pub fn sum(&self, x: &[Fl<T, B>], y: &[Fl<T, B>], k: usize, lo: usize, hi: usize) -> Fl<T, B> {
let mut out = Fl::<T, B>::zero();
self.sum_into(&mut out, x, y, k, lo, hi);
out
}
pub fn sum_into(&self, out: &mut Fl<T, B>, x: &[Fl<T, B>], y: &[Fl<T, B>], k: usize, lo: usize, hi: usize) {
let d = self.direct_below();
if self.s0 == 0 || k < 2 * d {
crate::field::cs_range_into(out, x, y, k, lo, hi);
return;
}
assert!(
self.next >= k,
"Relaxed::sum: order {k} before step {} is formed",
k - 1
);
assert!(
lo <= d && hi + d >= k,
"Relaxed::sum: range {lo}..={hi} at order {k} cuts the squares' terms"
);
let (a1, b0) = (hi.min(d - 1), lo.max(k + 1 - d));
for (b, o) in out.0.iter_mut().enumerate() {
let mut a = self.acc[b][k];
for i in lo..=a1 {
T::acc_mut(&mut a, &x[i].0[b], &y[k - i].0[b]);
}
for i in b0..=hi {
T::acc_mut(&mut a, &x[i].0[b], &y[k - i].0[b]);
}
*o = T::fin(a);
}
}
}
#[cfg(test)]
mod tile_tests {
use super::*;
use crate::native::OV;
use crate::simd::Native;
fn covers(la: usize, lb: usize, o: usize, n: usize, tl: &[(usize, usize, usize, usize)]) -> bool {
(0..la).all(|i| {
let mut cols: Vec<(usize, usize)> = tl
.iter()
.filter(|t| t.0 <= i && i < t.0 + t.2)
.map(|t| (t.1, t.1 + t.3))
.collect();
cols.sort_unstable();
let need = lb.min((n - o).saturating_sub(i));
let mut next = 0;
for (c0, c1) in cols {
if c0 < next || (c0 > next && next < need) {
return false;
}
next = c1;
}
next >= need
})
}
#[test]
fn tiles_cover_each_term_once() {
let lens = [4097, 6000, 8192, 8193, 9000, 12289];
let (mut checked, mut dropped) = (0, 0);
for &la in &lens {
for &lb in &lens {
if !tiled(la, lb) {
continue;
}
for o in [0, 1, 4097] {
for n in [o + 1, o + 4097, o + 8192, o + 11535, o + la + lb - 1, o + 40000] {
let tl: Vec<_> = tiles(la, lb, o, n).collect();
assert!(covers(la, lb, o, n, &tl), "{la} x {lb} at {o} to {n}");
for &(i0, j0, ta, tb) in &tl {
assert!(!tiled(ta, tb) && ta <= TILE && tb <= TILE && o + i0 + j0 < n);
}
assert!(!covers(la, lb, o, n, &tl[1..]), "{la} x {lb} at {o} to {n}: control");
dropped += 1;
checked += 1;
}
}
}
}
assert!(checked > 100 && dropped == checked);
}
#[test]
fn cost_prices_tiles_as_convolutions() {
let cfg = Cfg::default().prec_of::<Native, OV>();
let blk = |len: usize, spread: i32| Block {
start: 0,
end: len,
frame: [0; LN],
spread,
};
let (ba, bb) = ([blk(8192, 32)], [blk(8192, 32)]);
let n = 16383;
let c = cost::<Native, OV>(&ba, &bb, n, &cfg);
let sum: f64 = tiles(8192, 8192, 0, n)
.map(|(i0, j0, ta, tb)| pair_cost::<Native, OV>(&cfg, 32, 32, ta, tb, n - i0 - j0))
.sum();
assert_eq!(c, sum);
let direct = <OV as Expansion<Native>>::PROD_S * (8192.0 * 8192.0);
assert!(c < direct / 20.0, "{c} s against {direct} s term by term");
let wide = [blk(8192, 2000)];
let cw = cost::<Native, OV>(&wide, &wide, n, &cfg);
assert!(plan(&cfg, 2000, 2000, 8192, 8192).is_none());
assert_eq!(cw, direct);
}
}