Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-sparse/tests/cpu_backend.rs

//! The CPU backend against dense reference results, on every semiring and thread count.

use kleene_sparse::{
    Bitset, BitsetUnion, BoolOrAnd, CpuBackend, CpuDevice, Csr, Mask, MatrixMask, MinPlus,
    PlusTimes, Semiring, SparseBackend, TransposePlan, Vector,
};

type B = CpuBackend;

/// Dense reference product over a semiring.
fn dense<S: Semiring>(a: &Csr<S::T>, s: S) -> Vec<Vec<Option<S::T>>> {
    let mut d = vec![vec![None; a.ncols()]; a.nrows()];
    for (i, j, v) in a.triples(s) {
        d[i as usize][j as usize] = Some(v);
    }
    d
}

fn dense_mxm<S: Semiring>(a: &Csr<S::T>, b: &Csr<S::T>, s: S) -> Vec<Vec<Option<S::T>>> {
    let (da, db) = (dense(a, s), dense(b, s));
    let mut c = vec![vec![None; b.ncols()]; a.nrows()];
    for i in 0..a.nrows() {
        for j in 0..b.ncols() {
            for k in 0..a.ncols() {
                if let (Some(x), Some(y)) = (da[i][k], db[k][j]) {
                    let p = s.mul(x, y);
                    c[i][j] = Some(c[i][j].map_or(p, |t| s.add(t, p)));
                }
            }
        }
    }
    c
}

/// A small pseudo-random matrix (a fixed linear congruential stream: same every run).
fn random(n: usize, m: usize, per_row: usize, seed: u64) -> Csr<u64> {
    let mut x = seed;
    let mut step = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32
    };
    let (mut src, mut dst, mut val) = (Vec::new(), Vec::new(), Vec::new());
    for i in 0..n {
        for _ in 0..per_row {
            src.push(i as u32);
            dst.push(step() % m as u32);
            val.push((step() % 9 + 1) as u64);
        }
    }
    Csr::from_edges(n, m, &src, &dst, Some(&val), MinPlus::<u64>::new()).unwrap()
}

fn devices() -> [CpuDevice; 2] {
    [CpuDevice::new(1), CpuDevice::new(4).with_grain(3)]
}

#[test]
fn mxm_matches_the_dense_product_on_every_semiring_and_thread_count() {
    let a = random(40, 30, 3, 1);
    let b = random(30, 50, 4, 2);
    for d in devices() {
        let s = MinPlus::<u64>::new();
        assert_eq!(
            dense(&B::mxm(&a, &b, None, s, &d).unwrap(), s),
            dense_mxm(&a, &b, s)
        );
        let s = PlusTimes::<u64>::new();
        assert_eq!(
            dense(&B::mxm(&a, &b, None, s, &d).unwrap(), s),
            dense_mxm(&a, &b, s)
        );
    }
}

#[test]
fn mxm_with_a_mask_and_its_complement_splits_the_product() {
    let s = PlusTimes::<u64>::new();
    let a = random(25, 25, 3, 3);
    let b = random(25, 25, 3, 4);
    let mask = MatrixMask::from(&random(25, 25, 5, 5));
    for d in devices() {
        let full = B::mxm(&a, &b, None, s, &d).unwrap();
        let inside = B::mxm(&a, &b, Some(&mask), s, &d).unwrap();
        let outside = B::mxm(&a, &b, Some(&mask.clone().complement()), s, &d).unwrap();
        assert_eq!(inside.nnz() + outside.nnz(), full.nnz());
        for (i, j, v) in inside.triples(s) {
            assert!(mask.pattern.row(i as usize).contains(&j));
            assert_eq!(full.get(i as usize, j, s), Some(v));
        }
        let back = B::ewise_add_matrix(&inside, &outside, s, &d).unwrap();
        assert_eq!(back.triples(s), full.triples(s));
    }
}

#[test]
fn mxv_and_vxm_agree_with_the_transpose() {
    let s = PlusTimes::<u64>::new();
    let a = random(60, 45, 4, 6);
    let x = Vector::from_pairs(45, vec![(3, 2), (10, 1), (44, 5), (20, 7)], s).unwrap();
    let y = Vector::from_pairs(60, vec![(0, 1), (59, 3), (31, 2)], s).unwrap();
    for d in devices() {
        let at = B::transpose(&a, &d);
        let ax = B::mxv(&a, &x, None, s, &d).unwrap();
        let xat = B::vxm(&x, &at, None, s, &d).unwrap();
        assert_eq!(
            ax.iter().collect::<Vec<_>>(),
            xat.iter().collect::<Vec<_>>()
        );
        let ya = B::vxm(&y, &a, None, s, &d).unwrap();
        let aty = B::mxv(&at, &y, None, s, &d).unwrap();
        assert_eq!(
            ya.iter().collect::<Vec<_>>(),
            aty.iter().collect::<Vec<_>>()
        );
    }
}

#[test]
fn complement_masks_on_products_drop_the_masked_places() {
    let s = BoolOrAnd;
    let a: Csr<u8> = Csr::from_edges(4, 4, &[0, 0, 1, 2], &[1, 2, 3, 3], None, s).unwrap();
    let x = Vector::from_indices(4, &[0, 1], 1u8).unwrap();
    let visited = Mask::from_indices(4, &[0, 1, 2]).complement();
    let d = CpuDevice::new(1);
    let push = B::vxm(&x, &a, Some(&visited), s, &d).unwrap();
    assert_eq!(push.indices(), vec![3]);
    let pull = B::mxv(&a.transpose(), &x, Some(&visited), s, &d).unwrap();
    assert_eq!(pull.indices(), vec![3]);
}

#[test]
fn bitset_union_carries_many_sources_at_once() {
    let s = BitsetUnion;
    let a: Csr<u64> = Csr::from_edges(3, 3, &[0, 1], &[2, 2], None, s).unwrap();
    let x = Vector::sparse(3, vec![0, 1], vec![0b01, 0b10]).unwrap();
    let y = B::vxm(&x, &a, None, s, &CpuDevice::new(1)).unwrap();
    assert_eq!(y.get(2), Some(0b11));
}

#[test]
fn ewise_reduce_select_and_assign() {
    let s = PlusTimes::<u32>::new();
    let a = Vector::from_pairs(6, vec![(1, 2), (3, 4)], s).unwrap();
    let b = Vector::from_pairs(6, vec![(3, 10), (5, 1)], s).unwrap();
    let add = B::ewise_add_vector(&a, &b, s).unwrap();
    assert_eq!(
        add.iter().collect::<Vec<_>>(),
        vec![(1, 2), (3, 14), (5, 1)]
    );
    let mul = B::ewise_mult_vector(&a, &b, s).unwrap();
    assert_eq!(mul.iter().collect::<Vec<_>>(), vec![(3, 40)]);
    assert_eq!(B::reduce_vector(&add, s), 17);
    let big = B::select_vector(&add, |_, v| v > 1);
    assert_eq!(big.indices(), vec![1, 3]);
    let mut w = Vector::<u32>::empty(6);
    B::assign_scalar(&mut w, &big, 9, 0);
    assert_eq!(w.iter().collect::<Vec<_>>(), vec![(1, 9), (3, 9)]);
    let m = Csr::from_edges(3, 3, &[0, 0, 2], &[0, 1, 2], Some(&[1u32, 2, 3]), s).unwrap();
    let d = CpuDevice::new(1);
    assert_eq!(
        B::reduce_rows(&m, s, &d).iter().collect::<Vec<_>>(),
        vec![(0, 3), (2, 3)]
    );
    let upper = B::select_matrix(&m, |i, j, _| j > i, s, &d);
    assert_eq!(upper.triples(s), vec![(0, 1, 2)]);
    assert_eq!(
        B::row_lengths_at(&m, &Vector::from_indices(3, &[0, 2], 1u8).unwrap()),
        3
    );
}

#[test]
fn shapes_that_do_not_fit_are_refused() {
    let s = PlusTimes::<u64>::new();
    let d = CpuDevice::new(1);
    let a = random(3, 4, 1, 7);
    assert!(B::mxm(&a, &a, None, s, &d).is_err());
    assert!(B::mxv(&a, &Vector::empty(3), None, s, &d).is_err());
    assert!(B::vxm(&Vector::empty(4), &a, None, s, &d).is_err());
    assert!(B::mxv(&a, &Vector::empty(4), Some(&Mask::all(9)), s, &d).is_err());
}

#[test]
fn split_returns_pieces_in_order_and_covers_everything() {
    let d = CpuDevice::new(4).with_grain(10);
    let pieces = d.split(1000, |r| r);
    assert!(pieces.len() > 1);
    assert_eq!(pieces.first().unwrap().start, 0);
    assert_eq!(pieces.last().unwrap().end, 1000);
    assert!(pieces.windows(2).all(|w| w[0].end == w[1].start));
}

#[test]
fn traversal_steps_match_masked_products_and_close_the_mask() {
    let s = BoolOrAnd;
    let n = 500;
    let mut x = 7u64;
    let mut step = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32 % n as u32
    };
    let (src, dst): (Vec<u32>, Vec<u32>) = (0..3000).map(|_| (step(), step())).unzip();
    let a: Csr<u8> = Csr::from_edges(n, n, &src, &dst, None, s).unwrap();
    let at = a.transpose();
    let frontier_idx: Vec<u32> = (0..40).map(|_| step()).collect();
    let visited_idx: Vec<u32> = (0..150).map(|_| step()).collect();
    for d in [CpuDevice::new(1), CpuDevice::new(4).with_grain(1)] {
        let frontier = Vector::from_indices(n, &frontier_idx, 1u8).unwrap();
        let open = Mask::from_indices(n, &visited_idx).complement();
        let want_push = B::vxm(&frontier, &a, Some(&open), s, &d).unwrap().indices();
        let want_pull = B::mxv(&at, &frontier, Some(&open), s, &d)
            .unwrap()
            .indices();
        assert_eq!(want_push, want_pull);
        let mut ws = B::workspace(n, &d);
        let mut next = Vector::from_indices(n, &[1, 2, 3], 1u8).unwrap();
        let mut o = open.clone();
        let pushed = B::step_push(&frontier, &a, &mut o, &mut next, &mut ws, &d).unwrap();
        assert_eq!(next.indices(), want_push);
        assert_eq!(pushed, B::row_lengths_at(&a, &frontier));
        for &i in &want_push {
            assert!(!o.allows(i as usize));
        }
        assert_eq!(o.count(), open.count() - want_push.len());
        let mut o = open.clone();
        let pulled = B::step_pull(&frontier, &at, &mut o, &mut next, &mut ws, &d).unwrap();
        assert_eq!(next.indices(), want_pull);
        assert!(pulled <= at.nnz() as u64);
        assert_eq!(o.count(), open.count() - want_pull.len());
        // The workspace comes back clean: a second pull from the same state agrees.
        let mut o2 = open.clone();
        B::step_pull(&frontier, &at, &mut o2, &mut next, &mut ws, &d).unwrap();
        assert_eq!(next.indices(), want_pull);
    }
}

#[test]
fn traversal_steps_refuse_shapes_that_do_not_fit() {
    let d = CpuDevice::new(1);
    let a: Csr<u8> = Csr::from_edges(3, 3, &[0], &[1], None, BoolOrAnd).unwrap();
    let mut ws = B::workspace(3, &d);
    let mut next = Vector::empty(3);
    let mut open = Mask::all(4);
    let f = Vector::from_indices(3, &[0], 1u8).unwrap();
    assert!(B::step_push(&f, &a, &mut open, &mut next, &mut ws, &d).is_err());
    assert!(B::step_pull(&f, &a, &mut open, &mut next, &mut ws, &d).is_err());
}

#[test]
fn trusted_patterns_check_lengths_only() {
    use arrow_buffer::ScalarBuffer;
    use kleene_sparse::Pattern;
    let ok = Pattern::trusted(
        2,
        3,
        ScalarBuffer::from(vec![0u64, 1, 2]),
        ScalarBuffer::from(vec![2u32, 0]),
        "t",
    )
    .unwrap();
    assert_eq!(ok.row(0), &[2]);
    assert!(
        Pattern::trusted(
            2,
            3,
            ScalarBuffer::from(vec![0u64, 1]),
            ScalarBuffer::from(vec![0u32]),
            "t"
        )
        .is_err()
    );
    assert!(
        Pattern::trusted(
            2,
            3,
            ScalarBuffer::from(vec![0u64, 1, 3]),
            ScalarBuffer::from(vec![0u32, 1]),
            "t"
        )
        .is_err()
    );
}

#[test]
fn accumulate_returns_what_changed_and_apply_sees_the_index() {
    let s = MinPlus::<u32>::new();
    let mut w = Vector::from_pairs(6, vec![(1, 5u32), (3, 2)], s).unwrap();
    let u = Vector::from_pairs(6, vec![(1, 7), (3, 1), (4, 9)], s).unwrap();
    let changed = B::accumulate(&mut w, &u, s).unwrap();
    assert_eq!(changed.iter().collect::<Vec<_>>(), vec![(3, 1), (4, 9)]);
    assert_eq!(w.iter().collect::<Vec<_>>(), vec![(1, 5), (3, 1), (4, 9)]);
    let again = B::accumulate(&mut w, &u, s).unwrap();
    assert_eq!(again.nvals(), 0);
    let tagged = B::apply_indexed(&changed, |i, x| x * 10 + i);
    assert_eq!(tagged.iter().collect::<Vec<_>>(), vec![(3, 13), (4, 94)]);
    assert!(B::accumulate(&mut w, &Vector::empty(3), s).is_err());
}

#[test]
fn select_keeps_a_structural_matrix_structural() {
    let a: Csr<u32> =
        Csr::from_edges(3, 3, &[0, 1, 2], &[1, 2, 0], None, MinPlus::<u32>::new()).unwrap();
    let kept = B::select_matrix(
        &a,
        |i, _, _| i != 1,
        MinPlus::<u32>::new(),
        &CpuDevice::new(1),
    );
    assert!(kept.values().is_none());
    assert_eq!(kept.nnz(), 2);
}

/// Few rows with many multiply-adds (hub rows): the product's pieces follow the work, not
/// the row count, on the default grain too; the answers stay those of one thread.
#[test]
fn mxm_on_few_heavy_rows_matches_one_thread() {
    let n = 300;
    let mut x = 7u64;
    let mut step = || {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x
    };
    let (mut src, mut dst, mut val) = (Vec::new(), Vec::new(), Vec::new());
    for _ in 0..6000 {
        let a = (step() % n) as u32;
        let a = if step() % 2 == 0 { a % 5 } else { a };
        src.push(a);
        dst.push((step() % n) as u32);
        val.push(step() % 9 + 1);
    }
    let a = Csr::from_edges(
        n as usize,
        n as usize,
        &src,
        &dst,
        Some(&val),
        PlusTimes::<u64>::new(),
    )
    .unwrap();
    let mask = MatrixMask::from(&random(n as usize, n as usize, 20, 9));
    let one = CpuDevice::new(1);
    for d in [CpuDevice::new(4), CpuDevice::new(12)] {
        for s in [PlusTimes::<u64>::new()] {
            let want = B::mxm(&a, &a, None, s, &one).unwrap();
            assert_eq!(
                B::mxm(&a, &a, None, s, &d).unwrap().triples(s),
                want.triples(s)
            );
            for m in [mask.clone(), mask.clone().complement()] {
                let want = B::mxm(&a, &a, Some(&m), s, &one).unwrap();
                let got = B::mxm(&a, &a, Some(&m), s, &d).unwrap();
                assert_eq!(got.triples(s), want.triples(s));
            }
        }
        let s = MinPlus::<u64>::new();
        assert_eq!(
            dense(&B::mxm(&a, &a, None, s, &d).unwrap(), s),
            dense_mxm(&a, &a, s)
        );
    }
}

/// A full operand (every place present) and the or-and fold that stops at its first true:
/// the same answers as the dense reference, with and without a mask.
#[test]
fn mxv_with_a_full_operand_matches_the_dense_reference() {
    let w = random(500, 400, 6, 11);
    let pattern = w.pattern().clone();
    let a: Csr<u8> = Csr::with_pattern(pattern.clone(), None).unwrap();
    let mask = Mask::new(Bitset::from_indices(
        500,
        (0..500u32).filter(|i| i % 3 != 0),
    ));
    for d in devices()
        .into_iter()
        .chain([CpuDevice::new(8).with_grain(16)])
    {
        let s = BoolOrAnd;
        let x =
            Vector::dense((0..400).map(|i| (i % 2) as u8).collect(), Bitset::full(400)).unwrap();
        let y = B::mxv(&a, &x, None, s, &d).unwrap();
        let da = dense(&a, s);
        for (i, row) in da.iter().enumerate() {
            let mut want: Option<u8> = None;
            for (j, v) in row.iter().enumerate() {
                if v.is_some() {
                    let p = s.mul(1, x.get(j).unwrap());
                    want = Some(want.map_or(p, |t| s.add(t, p)));
                }
            }
            assert_eq!(y.get(i), want, "row {i}");
        }
        let ym = B::mxv(&a, &x, Some(&mask), s, &d).unwrap();
        for i in 0..500 {
            assert_eq!(ym.get(i), if mask.allows(i) { y.get(i) } else { None });
        }
        let s = MinPlus::<u64>::new();
        let x = Vector::dense(
            (0..400).map(|i| (i % 5) as u64).collect(),
            Bitset::full(400),
        )
        .unwrap();
        let y = B::mxv(&w, &x, None, s, &d).unwrap();
        let dw = dense(&w, s);
        for (i, row) in dw.iter().enumerate() {
            let want = row
                .iter()
                .enumerate()
                .filter_map(|(j, v)| v.map(|v| s.mul(v, j as u64 % 5)))
                .reduce(|t, p| s.add(t, p));
            assert_eq!(y.get(i), want, "row {i}");
        }
    }
}

/// A product estimated below the work bound runs on the calling thread with one
/// accumulator and one piece; a larger one wakes the workers with pieces in row order; one
/// thread never splits. The answers stay those of one thread.
#[test]
fn mxm_stays_on_the_calling_thread_below_its_work_bound() {
    let tiny = random(64, 64, 2, 21);
    let big = random(2048, 2048, 4, 22);
    let twelve = CpuDevice::new(12);
    let p = B::mxm_plan(&tiny, &tiny, &twelve);
    assert!(p.flops < CpuBackend::MXM_SERIAL_BELOW, "{p:?}");
    assert_eq!((p.workers, p.cuts.clone()), (1, vec![0, 64]));
    let p = B::mxm_plan(&big, &big, &twelve);
    assert!(p.flops >= CpuBackend::MXM_SERIAL_BELOW);
    assert_eq!(p.workers, 12);
    assert_eq!((p.cuts[0], *p.cuts.last().unwrap()), (0, 2048));
    assert!(p.cuts.windows(2).all(|w| w[0] < w[1]));
    assert!(p.cuts.len() - 1 <= 12 * 8);
    let p = B::mxm_plan(&big, &big, &CpuDevice::new(1));
    assert_eq!((p.workers, p.cuts), (1, vec![0, 2048]));
    let s = PlusTimes::<u64>::new();
    for m in [&tiny, &big] {
        let one = B::mxm(m, m, None, s, &CpuDevice::new(1)).unwrap();
        assert_eq!(
            B::mxm(m, m, None, s, &twelve).unwrap().triples(s),
            one.triples(s)
        );
    }
}

/// A full operand writes the result densely, in place: `mxv_into` and `vxm_into` leave a
/// dense vector holding the entries of the same product with the operand given sparse (rows
/// and columns with no entry absent), warm calls on a vector that held another answer
/// included, with and without a mask, on one thread and on blocks.
#[test]
fn mxv_and_vxm_with_a_full_operand_write_a_dense_result_in_place() {
    let s = MinPlus::<u64>::new();
    let n = 3000;
    let w = random(n, n, 30, 5);
    let a = B::select_matrix(
        &w,
        |i, j, _| i % 7 != 0 && j % 5 != 0,
        s,
        &CpuDevice::new(1),
    );
    let x = Vector::dense((0..n as u64).map(|i| i % 9).collect(), Bitset::full(n)).unwrap();
    let xs = Vector::sparse(
        n,
        (0..n as u32).collect(),
        (0..n as u64).map(|i| i % 9).collect(),
    )
    .unwrap();
    let mask = Mask::new(Bitset::from_indices(
        n,
        (0..n as u32).filter(|i| i % 3 != 0),
    ));
    let entries = |v: &Vector<u64>| v.iter().collect::<Vec<_>>();
    for d in [
        CpuDevice::new(1),
        CpuDevice::new(12),
        CpuDevice::new(4).with_grain(64),
    ] {
        let mut ws = B::workspace(n, &d);
        for m in [None, Some(&mask)] {
            let want = B::mxv(&a, &xs, m, s, &d).unwrap();
            let mut y = Vector::from_indices(n, &[1, 2, 3], 7u64).unwrap();
            for _ in 0..2 {
                B::mxv_into(&a, &x, m, s, &mut y, &mut ws, &d).unwrap();
                assert!(
                    y.is_dense(),
                    "mxv_into: a dense result ({} threads)",
                    d.threads()
                );
                assert_eq!(
                    entries(&y),
                    entries(&want),
                    "mxv_into ({} threads)",
                    d.threads()
                );
            }
            let want = B::vxm(&xs, &a, m, s, &d).unwrap();
            let mut y = Vector::from_indices(n, &[1, 2, 3], 7u64).unwrap();
            for _ in 0..2 {
                B::vxm_into(&x, &a, m, s, &mut y, &mut ws, &d).unwrap();
                assert!(
                    y.is_dense(),
                    "vxm_into: a dense result ({} threads)",
                    d.threads()
                );
                assert_eq!(
                    entries(&y),
                    entries(&want),
                    "vxm_into ({} threads)",
                    d.threads()
                );
            }
        }
    }
}

/// `vxm_into` with a full operand keeps the matrix's transpose from its second call on the
/// same matrix and pulls over it: the answers stay the push's (the operand given sparse), a
/// matrix read once makes no transpose, a sparse operand none either, and another matrix
/// of the same shape is never read through the first one's transpose.
#[test]
fn vxm_with_a_full_operand_pulls_over_a_kept_transpose() {
    let s = MinPlus::<u64>::new();
    let n = 2000;
    let a = random(n, n, 20, 8);
    let b = random(n, n, 20, 9);
    let x = Vector::dense((0..n as u64).map(|i| i % 7).collect(), Bitset::full(n)).unwrap();
    let xs = Vector::sparse(
        n,
        (0..n as u32).collect(),
        (0..n as u64).map(|i| i % 7).collect(),
    )
    .unwrap();
    let mask = Mask::new(Bitset::from_indices(
        n,
        (0..n as u32).filter(|i| i % 4 != 1),
    ));
    let entries = |v: &Vector<u64>| v.iter().collect::<Vec<_>>();
    for d in [CpuDevice::new(1), CpuDevice::new(12)] {
        let mut ws = B::workspace(n, &d);
        let mut y = Vector::empty(n);
        B::vxm_into(&xs, &a, None, s, &mut y, &mut ws, &d).unwrap();
        B::vxm_into(&xs, &a, None, s, &mut y, &mut ws, &d).unwrap();
        assert_eq!(ws.kept_transposes(), 0, "a sparse operand keeps none");
        for m in [None, Some(&mask)] {
            let want = B::vxm(&xs, &a, m, s, &d).unwrap();
            for _ in 0..3 {
                B::vxm_into(&x, &a, m, s, &mut y, &mut ws, &d).unwrap();
                assert_eq!(entries(&y), entries(&want), "{} threads", d.threads());
            }
        }
        assert_eq!(
            ws.kept_transposes(),
            1,
            "kept for a ({} threads)",
            d.threads()
        );
        // another matrix of the same shape: its own answers, and its own transpose in time
        let want = B::vxm(&xs, &b, None, s, &d).unwrap();
        B::vxm_into(&x, &b, None, s, &mut y, &mut ws, &d).unwrap();
        assert_eq!(entries(&y), entries(&want));
        assert_eq!(ws.kept_transposes(), 0, "a's let go, b read once");
        B::vxm_into(&x, &b, None, s, &mut y, &mut ws, &d).unwrap();
        assert_eq!(entries(&y), entries(&want));
        assert_eq!(ws.kept_transposes(), 1);
    }
}

/// A masked product computes the mask's places by dot products when that is the cheaper
/// side (a mask far sparser than the product's multiply-adds) and by Gustavson's rows
/// otherwise (a light product under its own pattern, any complemented mask); the answers
/// are the dense reference's at the mask's places either way.
#[test]
fn masked_mxm_takes_dot_products_when_the_mask_is_the_cheaper_side() {
    let s = PlusTimes::<u64>::new();
    let heavy = random(300, 300, 40, 3);
    let sparse_mask = MatrixMask::from(&random(300, 300, 1, 4));
    let light = random(300, 300, 2, 5);
    let own = MatrixMask::from(&light);
    assert!(B::mxm_by_dots(
        &heavy,
        &heavy,
        &sparse_mask,
        &CpuDevice::new(4)
    ));
    assert!(!B::mxm_by_dots(&light, &light, &own, &CpuDevice::new(4)));
    let mut complement = MatrixMask::from(&random(300, 300, 1, 4));
    complement.complement = true;
    assert!(!B::mxm_by_dots(
        &heavy,
        &heavy,
        &complement,
        &CpuDevice::new(4)
    ));
    let (full_heavy, full_light) = (dense_mxm(&heavy, &heavy, s), dense_mxm(&light, &light, s));
    for d in devices().into_iter().chain([CpuDevice::new(12)]) {
        for (a, m, full) in [
            (&heavy, &sparse_mask, &full_heavy),
            (&light, &own, &full_light),
            (&heavy, &complement, &full_heavy),
        ] {
            let got = B::mxm(a, a, Some(m), s, &d).unwrap();
            let held =
                |i: usize, j: u32| m.pattern.row(i).binary_search(&j).is_ok() != m.complement;
            let want: Vec<(u32, u32, u64)> = full
                .iter()
                .enumerate()
                .flat_map(|(i, row)| {
                    row.iter().enumerate().filter_map(move |(j, v)| {
                        v.filter(|_| held(i, j as u32))
                            .map(|v| (i as u32, j as u32, v))
                    })
                })
                .collect();
            assert_eq!(got.triples(s), want, "{} threads", d.threads());
        }
    }
}

/// A transpose above its bound splits over the workers (rows of about equal entries into
/// buckets of `width` columns, then whole blocks sorted by column) and gives the one-thread
/// transpose: square and not, with values and structural, rows with no entry and columns
/// with none; below the bound and on one thread it stays on the calling thread.
#[test]
fn transpose_splits_over_the_workers_above_its_bound() {
    let twelve = CpuDevice::new(12);
    let tiny = random(200, 200, 3, 31);
    assert_eq!(
        B::transpose_plan(&tiny, &twelve),
        TransposePlan {
            workers: 1,
            width: 200,
            rows: vec![0, 200]
        }
    );
    // rows i % 5 == 0 empty, columns above 4500 never named
    let mut x = 7u64;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for i in 0..3000u32 {
        if i % 5 == 0 {
            continue;
        }
        for _ in 0..40 {
            x = x.wrapping_mul(6364136223846793005).wrapping_add(1);
            src.push(i);
            dst.push(((x >> 33) % 4500) as u32);
        }
    }
    let vals: Vec<u64> = (0..src.len() as u64).map(|k| k % 11 + 1).collect();
    let wide =
        Csr::from_edges(3000, 5000, &src, &dst, Some(&vals), PlusTimes::<u64>::new()).unwrap();
    let structural = Csr::<u64>::new(
        wide.nrows(),
        wide.ncols(),
        wide.pattern().offsets().clone(),
        wide.pattern().indices().clone(),
        None,
    )
    .unwrap();
    let big = random(4000, 4000, 30, 32);
    assert!(big.nnz() >= CpuBackend::TRANSPOSE_SERIAL_BELOW);
    let p = B::transpose_plan(&big, &twelve);
    assert_eq!(p.workers, 12);
    assert!(p.width.is_power_of_two() && p.width >= 64);
    assert_eq!((p.rows[0], *p.rows.last().unwrap()), (0, 4000));
    assert!(p.rows.windows(2).all(|w| w[0] < w[1]));
    let per = (big.nnz() + 4000) / 12;
    let off = big.pattern().offsets();
    for w in p.rows.windows(2) {
        let e = (off[w[1]] - off[w[0]]) as usize + w[1] - w[0];
        assert!(e <= per + 64, "{e} entries against {per}");
    }
    assert_eq!(B::transpose_plan(&big, &CpuDevice::new(1)).workers, 1);
    let s = PlusTimes::<u64>::new();
    for m in [&big, &wide, &structural] {
        let want = m.transpose();
        for d in [CpuDevice::new(1), CpuDevice::new(3), CpuDevice::new(12)] {
            let got = B::transpose(m, &d);
            assert_eq!((got.nrows(), got.ncols()), (m.ncols(), m.nrows()));
            assert_eq!(got.pattern().offsets(), want.pattern().offsets());
            assert_eq!(got.pattern().indices(), want.pattern().indices());
            assert_eq!(got.triples(s), want.triples(s), "{} threads", d.threads());
            assert_eq!(got.values().is_some(), want.values().is_some());
        }
    }
}

/// The dots of a masked product are cut by merge steps, not by rows: rows of many long
/// merges get pieces of their own, every piece holds about its share of the steps, and
/// the answers stay the dense reference's.
#[test]
fn masked_dots_cut_rows_by_merge_steps() {
    let n = 4000u32;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for i in 0..n {
        let per = if i < 40 { 600 } else { 4 };
        for k in 0..per {
            src.push(i);
            dst.push((i * 7 + k * 13) % n);
        }
    }
    let vals: Vec<u64> = (0..src.len() as u64).map(|k| k % 5 + 1).collect();
    let s = PlusTimes::<u64>::new();
    let a = Csr::from_edges(n as usize, n as usize, &src, &dst, Some(&vals), s).unwrap();
    let mask = MatrixMask::from(&a);
    let twelve = CpuDevice::new(12);
    let at = B::transpose(&a, &twelve);
    let p = B::mxm_dots_plan(&a, &at, &mask, &twelve);
    let (ao, bo) = (a.pattern().offsets(), at.pattern().offsets());
    let cost = |i: usize| -> u64 {
        let la = ao[i + 1] - ao[i];
        mask.pattern
            .row(i)
            .iter()
            .map(|&j| pair_steps(la, bo[j as usize + 1] - bo[j as usize]))
            .sum::<u64>()
            + 1
    };
    let total: u64 = (0..n as usize).map(cost).sum();
    assert_eq!(p.flops, total - n as u64);
    assert_eq!(p.workers, 12);
    let pieces = (p.cuts.len() - 1) as u64;
    let heaviest = (0..n as usize).map(cost).max().unwrap();
    for w in p.cuts.windows(2) {
        let c: u64 = (w[0]..w[1]).map(cost).sum();
        assert!(
            c <= total / pieces + heaviest,
            "rows {w:?}: {c} steps against {} a piece",
            total / pieces
        );
    }
    assert!(p.cuts.windows(2).all(|w| w[0] < w[1]));
    assert_eq!(
        B::mxm_dots_plan(&a, &at, &mask, &CpuDevice::new(1)).workers,
        1
    );
    let one = B::mxm(&a, &a, Some(&mask), s, &CpuDevice::new(1)).unwrap();
    assert_eq!(
        B::mxm(&a, &a, Some(&mask), s, &twelve).unwrap().triples(s),
        one.triples(s)
    );
}

/// A structural matrix times a full operand of one value whose product folds to itself
/// (or-and's true, min-plus at one value) needs only the rows' offsets: `iso_product`
/// names that product, and `mxv_into` gives the answers of the operand given sparse, a
/// mask and rows with no entry included; an operand of two values, or a semiring whose
/// sum grows (plus-times), takes the fold.
#[test]
fn mxv_with_a_structural_matrix_and_a_one_valued_operand_reads_only_the_offsets() {
    let n = 5000;
    let w = random(n, n, 12, 41);
    let pat = Csr::<u8>::new(
        n,
        n,
        w.pattern().offsets().clone(),
        w.pattern().indices().clone(),
        None,
    )
    .unwrap();
    // rows i % 9 == 0 left empty
    let pat = B::select_matrix(&pat, |i, _, _| i % 9 != 0, BoolOrAnd, &CpuDevice::new(1));
    let ones = vec![1u8; n];
    assert_eq!(B::iso_product(&ones, BoolOrAnd), Some(1));
    let mut two = ones.clone();
    two[n - 1] = 0;
    assert_eq!(B::iso_product(&two, BoolOrAnd), None);
    assert_eq!(B::iso_product(&[3u64; 8], MinPlus::<u64>::new()), Some(3));
    assert_eq!(B::iso_product(&[3u64; 8], PlusTimes::<u64>::new()), None);
    assert_eq!(B::iso_product::<BoolOrAnd>(&[], BoolOrAnd), None);
    let x = Vector::dense(ones.clone(), Bitset::full(n)).unwrap();
    let xs = Vector::sparse(n, (0..n as u32).collect(), ones.clone()).unwrap();
    let mask = Mask::new(Bitset::from_indices(
        n,
        (0..n as u32).filter(|i| i % 4 != 2),
    ));
    let entries = |v: &Vector<u8>| v.iter().collect::<Vec<_>>();
    for d in [
        CpuDevice::new(1),
        CpuDevice::new(12),
        CpuDevice::new(4).with_grain(64),
    ] {
        let mut ws = B::workspace(n, &d);
        for m in [None, Some(&mask)] {
            let want = B::mxv(&pat, &xs, m, BoolOrAnd, &d).unwrap();
            let mut y = Vector::from_indices(n, &[1, 2, 3], 1u8).unwrap();
            for _ in 0..2 {
                B::mxv_into(&pat, &x, m, BoolOrAnd, &mut y, &mut ws, &d).unwrap();
                assert_eq!(entries(&y), entries(&want), "{} threads", d.threads());
            }
        }
    }
}

/// The steps of one dot product of two rising lists of lengths `x` and `y`: a merge
/// (`x + y`), or, when one is at least eight times longer, the short one's entries found
/// in the long one by galloping (`short * (1 + 2 log2(long / short))`).
fn pair_steps(x: u64, y: u64) -> u64 {
    let (s, l) = (x.min(y), x.max(y));
    if s == 0 {
        0
    } else if l >= 8 * s {
        s * (1 + 2 * u64::from((l / s).ilog2()))
    } else {
        s + l
    }
}

/// A skewed graph: every vertex a few out-edges and an edge to and from one of twenty
/// hubs, so the hubs' rows and columns are long and the rest short.
fn skewed(n: u32) -> Csr<u64> {
    let mut x = 11u64;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for i in 0..n {
        for _ in 0..3 {
            x = x.wrapping_mul(6364136223846793005).wrapping_add(1);
            src.push(i);
            dst.push(((x >> 33) % u64::from(n)) as u32);
        }
        let hub = (i * 7919) % 20;
        src.extend([i, hub]);
        dst.extend([hub, i]);
    }
    let vals: Vec<u64> = (0..src.len() as u64).map(|k| k % 7 + 1).collect();
    Csr::from_edges(
        n as usize,
        n as usize,
        &src,
        &dst,
        Some(&vals),
        PlusTimes::<u64>::new(),
    )
    .unwrap()
}

/// `A A` at the places of `A`, each by a plain one-thread intersection of row `i` of `A`
/// with column `j` of `A`.
fn masked_square_by_intersections(a: &Csr<u64>) -> Vec<(u32, u32, u64)> {
    let s = PlusTimes::<u64>::new();
    let at = a.transpose();
    let row = |m: &Csr<u64>, i: usize| -> Vec<(u32, u64)> {
        m.pattern()
            .range(i)
            .map(|k| (m.pattern().indices()[k], m.value_at(k, s)))
            .collect()
    };
    let mut out = Vec::new();
    for i in 0..a.nrows() {
        let ri = row(a, i);
        for &j in a.pattern().row(i) {
            let cj = row(&at, j as usize);
            let mut acc: Option<u64> = None;
            for &(k, x) in &ri {
                if let Ok(p) = cj.binary_search_by_key(&k, |e| e.0) {
                    let v = x * cj[p].1;
                    acc = Some(acc.map_or(v, |t| t + v));
                }
            }
            if let Some(v) = acc {
                out.push((i as u32, j, v));
            }
        }
    }
    out
}

/// On a skewed graph a masked `A A` under `A` merges each short row against a hub's long
/// column: a merge walks the long one, galloping finds the short one's entries in it.
/// The dots plan reports those steps, the dots are taken against Gustavson's true
/// multiply-adds (the hubs' many), and the answers are the plain intersections' at one
/// and eight threads.
#[test]
fn masked_mxm_on_a_skewed_graph_gallops_and_reports_its_steps() {
    let s = PlusTimes::<u64>::new();
    let a = skewed(6000);
    let mask = MatrixMask::from(&a);
    let want = masked_square_by_intersections(&a);
    for d in [CpuDevice::new(1), CpuDevice::new(8)] {
        assert!(B::mxm_by_dots(&a, &a, &mask, &d), "{} threads", d.threads());
        let at = B::transpose(&a, &d);
        let p = B::mxm_dots_plan(&a, &at, &mask, &d);
        let (ao, bo) = (a.pattern().offsets(), at.pattern().offsets());
        let steps: u64 = (0..a.nrows())
            .flat_map(|i| mask.pattern.row(i).iter().map(move |&j| (i, j as usize)))
            .map(|(i, j)| pair_steps(ao[i + 1] - ao[i], bo[j + 1] - bo[j]))
            .sum();
        assert_eq!(p.flops, steps, "{} threads", d.threads());
        let got = B::mxm(&a, &a, Some(&mask), s, &d).unwrap();
        assert_eq!(got.triples(s), want, "{} threads", d.threads());
    }
}

/// A full operand of four mebibytes or more (read ahead, across rows, while the rows fold): the
/// same answers, bit for bit, as a plain fold of each row in order, on every fold of a full
/// row (values with no terminal: min-plus `u32` and plus-times `f64` with fractions, whose
/// sums change with the order; values with a terminal: a union of bitsets; no values: plus-times
/// `u64`), rows of every length from none to 40, on one thread and on blocks.
#[test]
fn mxv_with_a_large_full_operand_folds_each_row_in_order() {
    let n = 1usize << 20;
    let mut z = 99u64;
    let mut step = move || {
        z = z
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (z >> 33) as u32
    };
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for i in 0..n as u32 {
        let len = if i % 97 == 0 { 40 } else { step() % 3 };
        for _ in 0..len {
            src.push(i);
            dst.push(step() % n as u32);
        }
    }
    let a = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let nnz = a.nnz();
    let pattern = a.pattern().clone();
    fn check<S: Semiring>(a: &Csr<S::T>, x: Vec<S::T>, s: S) {
        let n = a.nrows();
        let mut want = Vec::new();
        for i in 0..n {
            let mut t: Option<S::T> = None;
            for (k, &j) in a.pattern().indices()[a.pattern().range(i)]
                .iter()
                .enumerate()
            {
                let w = a
                    .values()
                    .map_or(s.one(), |v| v[a.pattern().range(i).start + k]);
                let p = s.mul(w, x[j as usize]);
                t = Some(t.map_or(p, |t| s.add(t, p)));
            }
            if let Some(t) = t {
                want.push((i as u32, t));
            }
        }
        let x = Vector::dense(x, Bitset::full(n)).unwrap();
        for d in [
            CpuDevice::new(1),
            CpuDevice::new(12),
            CpuDevice::new(4).with_grain(64),
        ] {
            let mut ws = B::workspace(n, &d);
            let mut y = Vector::empty(n);
            B::mxv_into(a, &x, None, s, &mut y, &mut ws, &d).unwrap();
            assert!(
                y.iter().eq(want.iter().copied()),
                "{s:?}, {} threads",
                d.threads()
            );
        }
    }
    let w32: Vec<u32> = (0..nnz as u32).map(|k| k % 255 + 1).collect();
    let a32 = Csr::with_pattern(pattern.clone(), Some(w32.into())).unwrap();
    check(
        &a32,
        (0..n as u32).map(|i| i % 7 + 1).collect(),
        MinPlus::<u32>::new(),
    );
    let wf: Vec<f64> = (0..nnz).map(|k| (k % 13) as f64 * 0.37 + 0.1).collect();
    let af = Csr::with_pattern(pattern.clone(), Some(wf.into())).unwrap();
    let xf = (0..n).map(|i| (i % 7) as f64 * 0.1 + 0.3).collect();
    check(&af, xf, PlusTimes::<f64>::new());
    let wb: Vec<u64> = (0..nnz as u64).map(|k| !(1u64 << (k % 64))).collect();
    let ab = Csr::with_pattern(pattern.clone(), Some(wb.into())).unwrap();
    let xb = (0..n as u64)
        .map(|i| 1u64 << (i % 64) | 1 << (i * 7 % 64))
        .collect();
    check(&ab, xb, BitsetUnion);
    let au: Csr<u64> = Csr::with_pattern(pattern, None).unwrap();
    check(
        &au,
        (0..n as u64).map(|i| i % 9).collect(),
        PlusTimes::<u64>::new(),
    );
}