crates/kleene-graph/src/many.rs
//! Many searches at once on the CPU: the device's threads are shared out among searchers,
//! each with a state and a device of its own, and every searcher takes the next source from
//! a shared counter until none is left. A small search (a few hops) stays on one thread, so
//! one search at a time on all threads leaves most of them waiting; side by side they keep
//! every thread busy. Each search's answer is the one a search alone gives.
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use kleene_sparse::{CpuBackend, CpuDevice, atomic_words};
use crate::{BfsOptions, BfsState, Graph, GraphError, bfs_with};
/// The bytes a search state takes per vertex (levels, queue and bit sets), for the budget.
pub const MANY_BYTES_PER_VERTEX: usize = 10;
/// The default bytes all searchers' states may take together: 8 GiB.
pub const MANY_BUDGET: usize = 8 << 30;
/// One searcher: a device with its share of the threads and a state of its own.
#[derive(Debug)]
struct Searcher {
device: CpuDevice,
state: BfsState<CpuBackend>,
error: Option<GraphError>,
}
/// Kept searchers for many searches from one source each ([`BfsMany::run`]); the states and
/// the searchers' devices are kept between calls, and every state holds what any of the
/// searches took, so a warm call allocates nothing whichever searcher takes which source.
#[derive(Debug)]
pub struct BfsMany {
searchers: Vec<Searcher>,
alone: Option<BfsState<CpuBackend>>,
budget: usize,
}
impl Default for BfsMany {
fn default() -> Self {
Self::new()
}
}
impl BfsMany {
/// No searchers yet; their states may take [`MANY_BUDGET`] bytes together.
pub fn new() -> Self {
BfsMany {
searchers: Vec::new(),
alone: None,
budget: MANY_BUDGET,
}
}
/// The same, with the searchers' states held to `bytes` together.
pub fn with_budget(mut self, bytes: usize) -> Self {
self.budget = bytes;
self
}
/// How many searchers run side by side for `sources` searches over `n` vertices on
/// `device`: one per thread, at most one per source and as many as the budget holds;
/// one means the searches run one at a time on all the device's threads.
pub fn searchers(&self, n: usize, sources: usize, device: &CpuDevice) -> usize {
let fit = self.budget / (n.max(1) * MANY_BYTES_PER_VERTEX);
device.threads().min(sources).min(fit).max(1)
}
/// One search from each of `sources` with `opts`; `reached[i]` becomes the number of
/// vertices the search from `sources[i]` reached (the source included).
pub fn run(
&mut self,
g: &Graph<CpuBackend>,
sources: &[u32],
opts: &BfsOptions,
device: &CpuDevice,
reached: &mut [u64],
) -> crate::Result<()> {
if reached.len() != sources.len() {
return Err(GraphError::Slices(format!(
"many searches: {} answer places for {} sources",
reached.len(),
sources.len()
)));
}
let n = g.vertices();
let p = self.searchers(n, sources.len(), device);
if p <= 1 {
let st = self.alone.get_or_insert_with(|| BfsState::new(n, device));
for (s, r) in sources.iter().zip(reached.iter_mut()) {
*r = bfs_with(g, &[*s], opts, device, st)?.reached as u64;
}
return Ok(());
}
let threads = (device.threads() / p).max(1);
let fits = |s: &Searcher| s.device.threads() == threads && s.device.simd() == device.simd();
if self.searchers.len() != p || !self.searchers.iter().all(fits) {
self.searchers = (0..p)
.map(|_| {
let d = CpuDevice::new(threads)
.with_grain(device.grain())
.with_simd(device.simd());
let mut state = BfsState::new(n, &d);
crate::beamer::ready(g, &d, 0, &mut state);
Searcher {
state,
device: d,
error: None,
}
})
.collect();
}
let next = AtomicUsize::new(0);
let out = atomic_words(reached);
device.each_block(&mut self.searchers, |_, s| {
s.error = None;
loop {
let i = next.fetch_add(1, Relaxed);
if i >= sources.len() {
break;
}
match bfs_with(g, &sources[i..=i], opts, &s.device, &mut s.state) {
Ok(f) => out[i].store(f.reached as u64, Relaxed),
Err(e) => {
// The others stop at their next source.
next.store(sources.len(), Relaxed);
s.error = Some(e);
break;
}
}
}
});
// Room for the deepest search any searcher made: the next call may give it to another.
let most = self
.searchers
.iter()
.map(|s| s.state.steps.capacity())
.max();
for s in &mut self.searchers {
crate::beamer::ready(g, &s.device, most.unwrap_or(0), &mut s.state);
}
match self.searchers.iter_mut().find_map(|s| s.error.take()) {
Some(e) => Err(e),
None => Ok(()),
}
}
}