crates/kleene-sparse/tests/executor.rs
//! A device runs its parallel jobs on the executor it is given, and the answers equal the
//! built-in pool's.
#![allow(unsafe_code)]
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_sparse::{CpuBackend, CpuDevice, Csr, Executor, PlusTimes, SparseBackend, Vector};
/// Runs every share in turn on the caller and counts the jobs.
struct Counting {
threads: usize,
jobs: AtomicUsize,
}
// SAFETY: `run` calls each `t` in `0..n` exactly once and returns after the last one.
unsafe impl Executor for Counting {
fn threads(&self) -> usize {
self.threads
}
fn run(&self, n: usize, job: &(dyn Fn(usize) + Sync)) {
self.jobs.fetch_add(1, Ordering::Relaxed);
for t in 0..n.min(self.threads) {
job(t);
}
}
}
fn ring(n: usize) -> Csr<u64> {
let mut src = Vec::new();
let mut dst = Vec::new();
for i in 0..n {
for d in [1, 7, 31] {
src.push(i as u32);
dst.push(((i + d) % n) as u32);
}
}
let vals: Vec<u64> = (0..src.len() as u64).map(|k| k % 7 + 1).collect();
Csr::from_edges(n, n, &src, &dst, Some(&vals), PlusTimes::<u64>::new()).expect("valid")
}
#[test]
fn a_device_runs_its_jobs_on_the_given_executor() {
let n = 1 << 16;
let a = ring(n);
let s = PlusTimes::<u64>::new();
let x = Vector::from_pairs(
n,
(0..n as u32).map(|i| (i, u64::from(i % 5 + 1))).collect(),
s,
)
.expect("valid");
let exec = Arc::new(Counting {
threads: 4,
jobs: AtomicUsize::new(0),
});
let given = CpuDevice::with_executor(exec.clone()).with_grain(256);
assert_eq!(given.threads(), 4);
let own = CpuDevice::new(4).with_grain(256);
let got = CpuBackend::mxv(&a, &x, None, s, &given).expect("mxv");
let want = CpuBackend::mxv(&a, &x, None, s, &own).expect("mxv");
assert_eq!(
got.iter().collect::<Vec<_>>(),
want.iter().collect::<Vec<_>>()
);
assert!(
exec.jobs.load(Ordering::Relaxed) > 0,
"the executor ran no job"
);
}
#[test]
fn a_large_product_joins_its_rows_on_the_workers_with_the_same_answer() {
let a = ring(1 << 19);
let s = PlusTimes::<u64>::new();
let exec = Arc::new(Counting {
threads: 4,
jobs: AtomicUsize::new(0),
});
let given = CpuDevice::with_executor(exec.clone());
let got = CpuBackend::mxm(&a, &a, None, s, &given).expect("mxm");
assert!(
got.nnz() >= 1 << 21,
"a result large enough to join on the workers"
);
// one job folds the rows, one copies the pieces into the result's arrays
assert_eq!(exec.jobs.load(Ordering::Relaxed), 2, "jobs of the product");
for threads in [1, 3, 8] {
let want = CpuBackend::mxm(&a, &a, None, s, &CpuDevice::new(threads)).expect("mxm");
assert_eq!(
got.pattern().offsets(),
want.pattern().offsets(),
"{threads} threads"
);
assert_eq!(
got.pattern().indices(),
want.pattern().indices(),
"{threads} threads"
);
assert_eq!(got.values(), want.values(), "{threads} threads");
}
}