crates/kleene-sparse/tests/no_alloc.rs
//! The hot paths allocate nothing once their buffers have grown: `mxv_into` and `vxm_into`
//! in steady state, and push and pull steps level after level, on one thread and on
//! several (the workers are made with the device, not per step). A counting allocator
//! sees every allocation of every thread of this test binary, so it holds one test.
// A counting allocator needs `unsafe impl GlobalAlloc`: allowed in this test only.
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_sparse::{
BoolOrAnd, CpuBackend, CpuDevice, Csr, Mask, MinPlus, PlusTimes, Semiring, SparseBackend,
Vector,
};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
// SAFETY: every call is passed straight to the system allocator.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
unsafe { System.dealloc(p, l) }
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn allocations_in(f: impl FnOnce()) -> usize {
let before = ALLOCS.load(Ordering::SeqCst);
f();
ALLOCS.load(Ordering::SeqCst) - before
}
type B = CpuBackend;
fn random_edges(n: usize, per_row: usize, seed: u64) -> (Vec<u32>, Vec<u32>) {
let mut x = seed;
let mut step = || {
x = x
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(x >> 33) as u32
};
let (mut src, mut dst) = (Vec::new(), Vec::new());
for i in 0..n {
for _ in 0..(step() as usize % (2 * per_row + 1)) {
src.push(i as u32);
dst.push(step() % n as u32);
}
}
(src, dst)
}
fn entries<T: kleene_sparse::Value>(v: &Vector<T>) -> Vec<(u32, T)> {
v.iter().collect()
}
fn products_allocate_nothing_in_steady_state(device: &CpuDevice) {
let n = 20_000;
let (src, dst) = random_edges(n, 6, 7);
let vals: Vec<u64> = (0..src.len() as u64).map(|k| k % 7 + 1).collect();
let s = PlusTimes::<u64>::new();
let a = Csr::from_edges(n, n, &src, &dst, Some(&vals), s).unwrap();
let x = Vector::from_pairs(
n,
(0..n as u32)
.step_by(3)
.map(|i| (i, (i % 5 + 1) as u64))
.collect(),
s,
)
.unwrap();
let mask = Mask::from_indices(n, &(0..n as u32).step_by(2).collect::<Vec<_>>()).complement();
let mut ws = B::workspace(n, device);
let mut y = Vector::empty(n);
for m in [None, Some(&mask)] {
let want_mxv = B::mxv(&a, &x, m, s, device).unwrap();
let want_vxm = B::vxm(&x, &a, m, s, device).unwrap();
// Two warm-up calls grow every buffer.
for _ in 0..2 {
B::mxv_into(&a, &x, m, s, &mut y, &mut ws, device).unwrap();
B::vxm_into(&x, &a, m, s, &mut y, &mut ws, device).unwrap();
}
let got = allocations_in(|| {
for _ in 0..5 {
B::mxv_into(&a, &x, m, s, &mut y, &mut ws, device).unwrap();
}
});
assert_eq!(entries(&y), entries(&want_mxv), "mxv_into");
assert_eq!(got, 0, "mxv_into allocated ({} threads)", device.threads());
let got = allocations_in(|| {
for _ in 0..5 {
B::vxm_into(&x, &a, m, s, &mut y, &mut ws, device).unwrap();
}
});
assert_eq!(entries(&y), entries(&want_vxm), "vxm_into");
assert_eq!(got, 0, "vxm_into allocated ({} threads)", device.threads());
}
// A full operand: the result written densely in place allocates nothing either.
let xf = Vector::dense(
(0..n as u64).map(|i| i % 5 + 1).collect(),
kleene_sparse::Bitset::full(n),
)
.unwrap();
for m in [None, Some(&mask)] {
let (mut yp, mut yq) = (Vector::empty(n), Vector::empty(n));
for _ in 0..2 {
B::mxv_into(&a, &xf, m, s, &mut yp, &mut ws, device).unwrap();
B::vxm_into(&xf, &a, m, s, &mut yq, &mut ws, device).unwrap();
}
let got = allocations_in(|| {
for _ in 0..5 {
B::mxv_into(&a, &xf, m, s, &mut yp, &mut ws, device).unwrap();
B::vxm_into(&xf, &a, m, s, &mut yq, &mut ws, device).unwrap();
}
});
assert_eq!(
entries(&yp),
entries(&B::mxv(&a, &xf, m, s, device).unwrap())
);
assert_eq!(
entries(&yq),
entries(&B::vxm(&xf, &a, m, s, device).unwrap())
);
assert_eq!(
got,
0,
"full-operand products allocated ({} threads)",
device.threads()
);
}
// Another semiring and value type shares the workspace.
let m = MinPlus::<u32>::new();
let a32 = Csr::from_edges(
n,
n,
&src,
&dst,
Some(&src.iter().map(|&v| v % 11).collect::<Vec<u32>>()),
m,
)
.unwrap();
let x32 = Vector::from_indices(n, &[1, 50, 999, 7000], 0u32).unwrap();
let mut y32 = Vector::empty(n);
for _ in 0..2 {
B::vxm_into(&x32, &a32, None, m, &mut y32, &mut ws, device).unwrap();
}
let got =
allocations_in(|| B::vxm_into(&x32, &a32, None, m, &mut y32, &mut ws, device).unwrap());
assert_eq!(got, 0, "min-plus vxm_into allocated");
assert_eq!(
entries(&y32),
entries(&B::vxm(&x32, &a32, None, m, device).unwrap())
);
}
fn steps_allocate_nothing_level_after_level(device: &CpuDevice) {
let n = 50_000;
let (src, dst) = random_edges(n, 4, 11);
let a = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
let at = a.transpose();
let sources = [4000u32, 0, 17];
let mut ws = B::workspace(n, device);
let mut frontier: Vector<u8> = Vector::empty(n);
let mut next: Vector<u8> = Vector::empty(n);
let start = Mask::all(n);
let mut open = Mask::all(n);
for pull in [false, true] {
// A first search grows every buffer; the second must not allocate.
let mut reached = [0usize; 2];
for (round, count) in reached.iter_mut().enumerate() {
let got = allocations_in(|| {
B::load_indices(&mut frontier, &sources, 1, device).unwrap();
B::mask_assign(&mut open, &start, device);
B::mask_add_vector(&mut open, &frontier);
*count = frontier.nvals();
let mut swaps = 0;
while frontier.nvals() > 0 {
if pull {
B::step_pull(&frontier, &at, &mut open, &mut next, &mut ws, device)
.unwrap();
} else {
B::step_push(&frontier, &a, &mut open, &mut next, &mut ws, device).unwrap();
}
std::mem::swap(&mut frontier, &mut next);
swaps += 1;
*count += frontier.nvals();
}
// Each vector keeps the role it had, so it meets the same sizes next time.
if swaps % 2 == 1 {
std::mem::swap(&mut frontier, &mut next);
}
});
if round == 1 {
assert_eq!(
got,
0,
"steps allocated (pull {pull}, {} threads)",
device.threads()
);
}
}
assert_eq!(reached[0], reached[1]);
assert!(reached[0] > n / 2, "the search reached {}", reached[0]);
}
}
#[test]
fn hot_paths_allocate_nothing_after_setup() {
for device in [
CpuDevice::new(1),
CpuDevice::new(4).with_grain(64),
CpuDevice::default().with_grain(256),
] {
products_allocate_nothing_in_steady_state(&device);
steps_allocate_nothing_level_after_level(&device);
}
// The semiring of a structural reach is a plain one: checked for the compiler's sake.
let _ = BoolOrAnd.one();
}