crates/kleene-graph/src/beamer.rs
//! Breadth-first search on the CPU, direction-optimizing (Beamer, Asanović and Patterson
//! 2012), on the device's threads (gatling's in the benchmark): the CPU backend's
//! [`crate::bfs`], and its hop counts in [`crate::sssp_of`].
//!
//! - Push (top-down): each thread takes pieces of the frontier, sends along their out-edges
//! and claims a vertex by clearing its bit in the open set (after a plain read: most are
//! closed already); the claimer writes the level and lists the vertex for the next level.
//! - Pull (bottom-up): the frontier is a bit set. Each thread takes whole words of the open
//! set and, for each open vertex, looks along its in-edges for a frontier vertex,
//! stopping at the first.
//! - The switch between them is Beamer's rule as [`crate::bfs_with_generic`] has it, with
//! the same options (alpha, beta), so the steps are the same as the generic search's:
//! the same directions, frontiers, vertices reached and edges looked at. The frontier's
//! out-edges, which the rule needs, are summed by the step that found the frontier.
//!
//! Every level's frontier lies in one queue of a place per vertex (each vertex is reached
//! once), one level after the other. A thread lists what it reaches in a buffer of its own
//! of [`LOCAL`] places and moves it into the queue when full, so no buffer grows with how
//! the race between the threads went: a search on kept state ([`crate::bfs_with`])
//! allocates nothing. A level of fewer vertices than half the device's grain runs on the
//! calling thread without atomic read-modify-writes on the open set. Nothing is done per
//! level over all vertices, and the levels are written in place into zeroed memory (pages
//! no level reaches are never touched; on kept state only the places the last search
//! reached are zeroed again).
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize};
use kleene_sparse::{Bitset, CpuBackend, CpuDevice, Csr, Vector, atomic_u32s, atomic_words};
use crate::{Bfs, BfsOptions, BfsState, BfsSummary, Direction, Graph, GraphError, Paths, Step};
/// Open-set words a pull hands out at a time.
const PULL_WORDS: usize = 64;
/// Levels per 4 KiB page.
const PAGE: usize = 1024;
/// Places of a thread's own buffer of reached vertices, moved into the queue when full.
const LOCAL: usize = 1024;
/// [`crate::bfs`] on the CPU by direction-optimizing search (its answer is the generic
/// search's, steps included).
pub fn beamer_bfs(
g: &Graph<CpuBackend>,
sources: &[u32],
opts: &BfsOptions,
device: &CpuDevice,
) -> crate::Result<Bfs<CpuBackend>> {
crate::bfs::check(g, sources, opts)?;
let n = g.vertices();
let mut bufs = Bufs::default();
let (reached, depth) = bufs.search(rows(g.out()), g.inn().map(rows), sources, opts, device);
let levels = if reached == 0 {
Vector::empty(n)
} else {
bufs.levels(n)
};
Ok(Bfs {
reached,
depth,
levels,
steps: bufs.steps,
})
}
/// [`crate::bfs_with`] on the CPU (its input already checked): the levels and steps go to
/// `st`, and every buffer of the last search on `st` is used again.
pub(crate) fn beamer_bfs_with(
g: &Graph<CpuBackend>,
sources: &[u32],
opts: &BfsOptions,
device: &CpuDevice,
st: &mut BfsState<CpuBackend>,
) -> BfsSummary {
let n = g.vertices();
let mut bufs = Bufs {
steps: std::mem::take(&mut st.steps),
scratch: std::mem::take(&mut st.cpu),
..Bufs::default()
};
// the last levels, dense: their values are non-zero only where they are present
let kept = match std::mem::replace(&mut st.levels, Vector::empty(0)).into_dense_parts() {
Ok((values, present)) if values.len() == n => {
bufs.values = values;
bufs.words = present.into_words();
bufs.dirty = true;
true
}
_ => false,
};
let (reached, depth) = bufs.search(rows(g.out()), g.inn().map(rows), sources, opts, device);
st.levels = if reached == 0 && !kept {
Vector::empty(n)
} else {
bufs.levels(n)
};
st.steps = bufs.steps;
st.cpu = bufs.scratch;
BfsSummary { reached, depth }
}
/// Give `st` every buffer a search over `g` on `device` takes (the pull's bit sets too, when
/// `g` has its transpose) and room for `steps` steps, so a search on it allocates nothing
/// even if it is the first or the deepest one `st` sees.
pub(crate) fn ready(
g: &Graph<CpuBackend>,
device: &CpuDevice,
steps: usize,
st: &mut BfsState<CpuBackend>,
) {
let (n, sc) = (g.vertices(), &mut st.cpu);
let (threads, words) = (device.threads().max(1), n.div_ceil(64));
if sc.lanes.len() != threads {
sc.lanes = (0..threads).map(|_| Lane::new()).collect();
}
if sc.queue.len() != n {
sc.queue = vec![0; n];
let present = Bitset::from_words(n, vec![0; words]);
st.levels = Vector::dense(vec![0; n], present).expect("a level per place");
}
if g.inn().is_some() && sc.bits.len() != words {
sc.bits = zeroed_words(words);
sc.nbits = zeroed_words(words);
}
sc.sources.reserve(1);
st.steps.reserve(steps.saturating_sub(st.steps.len()));
}
/// Hop counts from `source` (every edge one hop; the weights' values are not read) by
/// direction-optimizing search, as [`crate::sssp_of`] answers them: each vertex's parent is
/// the least vertex one hop nearer the source with an edge to it (the first in its row of
/// `transposed`, whose rows rise as kleene builds them). Pulls need `transposed`; without
/// it every level pushes, and the parents come from one pass over the out-edges.
pub fn beamer_hops(
weights: &Csr<u32>,
transposed: Option<&Csr<u32>>,
source: u32,
device: &CpuDevice,
) -> crate::Result<Paths> {
let n = weights.nrows();
if weights.ncols() != n {
return Err(GraphError::NotSquare {
rows: n,
cols: weights.ncols(),
});
}
if source as usize >= n {
return Err(GraphError::SourceOutOfRange {
source,
vertices: n,
});
}
let out = rows(weights);
let inn = transposed
.filter(|t| t.nrows() == n && t.ncols() == n)
.map(rows);
let mut found = Bufs::default();
found.search(out, inn, &[source], &BfsOptions::default(), device);
let level = &found.values;
let present = &found.words;
let reached = |v: u32| present[v as usize / 64] >> (v % 64) & 1 == 1;
// `(level << 32) | parent` per reached vertex, written in place into zeroed words
let mut packed = vec![0u64; n];
{
let words = atomic_words(&mut packed);
match inn {
Some(inn) => {
device.split(n, |r| {
for v in r {
let (v32, d) = (v as u32, level[v]);
if d == 0 || !reached(v32) {
continue;
}
// rows rise as kleene builds them: the first is the least
let p = inn
.row(v32)
.iter()
.copied()
.find(|&u| reached(u) && level[u as usize] == d - 1)
.expect("a vertex at level d has an in-edge from level d - 1");
words[v].store(u64::from(d) << 32 | u64::from(p), Relaxed);
}
});
}
None => {
// the least parent as the highest `!parent` (0: none yet)
device.split(n, |r| {
for u in r {
let u32_ = u as u32;
if !reached(u32_) {
continue;
}
let d = level[u] + 1;
let mine = u64::from(d) << 32 | u64::from(!u32_);
for &w in out.row(u32_) {
let at = &words[w as usize];
if reached(w) && level[w as usize] == d && at.load(Relaxed) < mine {
at.fetch_max(mine, Relaxed);
}
}
}
});
device.split(n, |r| {
for v in r {
let x = words[v].load(Relaxed);
if x != 0 {
words[v].store(x & !0xffff_ffff | u64::from(!(x as u32)), Relaxed);
}
}
});
}
}
words[source as usize].store(u64::from(source), Relaxed);
}
let pulls = found
.steps
.iter()
.filter(|s| s.direction == Direction::Pull)
.count() as u32;
let rounds = found.steps.len() as u32;
let present = Bitset::from_words(n, std::mem::take(&mut found.words));
let packed = Vector::dense(packed, present).expect("a word per place");
Ok(Paths::from_packed(source, packed, rounds, pulls))
}
/// A matrix's rows, without its values.
#[derive(Clone, Copy)]
struct Rows<'a> {
off: &'a [u64],
idx: &'a [u32],
}
fn rows<T: kleene_sparse::Value>(m: &Csr<T>) -> Rows<'_> {
Rows {
off: m.pattern().offsets(),
idx: m.pattern().indices(),
}
}
impl<'a> Rows<'a> {
fn vertices(&self) -> usize {
self.off.len() - 1
}
fn row(&self, v: u32) -> &'a [u32] {
&self.idx[self.off[v as usize] as usize..self.off[v as usize + 1] as usize]
}
fn degree(&self, v: u32) -> u64 {
self.off[v as usize + 1] - self.off[v as usize]
}
}
/// What the CPU search keeps in a [`BfsState`] between searches (empty on other backends):
/// the frontier queue, the threads' buffers, the frontier bit sets and the sorted sources.
#[derive(Debug, Default)]
pub(crate) struct Scratch {
/// A place per vertex: every level's frontier in turn.
queue: Vec<u32>,
lanes: Vec<Lane>,
bits: Vec<AtomicU64>,
nbits: Vec<AtomicU64>,
sources: Vec<u32>,
}
/// One thread's part of a level.
#[derive(Debug, Default)]
struct Lane {
/// What it reached and has not moved into the queue yet (at most [`LOCAL`]).
buf: Vec<u32>,
/// Edges it looked at.
examined: u64,
/// The out-edges of the vertices it reached.
edges: u64,
}
impl Lane {
fn new() -> Self {
Lane {
buf: Vec::with_capacity(LOCAL),
..Lane::default()
}
}
/// List `v` for the next level.
fn push(&mut self, v: u32, queue: &[AtomicU32], tail: &AtomicUsize) {
if self.buf.len() == LOCAL {
self.flush(queue, tail);
}
self.buf.push(v);
}
/// Move the buffer into the queue.
fn flush(&mut self, queue: &[AtomicU32], tail: &AtomicUsize) {
if self.buf.is_empty() {
return;
}
let at = tail.fetch_add(self.buf.len(), Relaxed);
for (q, &v) in queue[at..at + self.buf.len()].iter().zip(&self.buf) {
q.store(v, Relaxed);
}
self.buf.clear();
}
}
/// A search's buffers: the level per vertex (0 where not reached), the open set's words
/// (the reached set's after the search), the steps and the scratch.
#[derive(Default)]
struct Bufs {
values: Vec<u32>,
words: Vec<u64>,
/// `values` is non-zero only where `words` has a bit set (the last search's levels).
dirty: bool,
steps: Vec<Step>,
scratch: Scratch,
}
/// Clear bit `w` of `bits` if set; whether this call did.
fn take(bits: &[AtomicU64], w: u32) -> bool {
let (at, bit) = (&bits[w as usize / 64], 1u64 << (w % 64));
at.load(Relaxed) & bit != 0 && at.fetch_and(!bit, Relaxed) & bit != 0
}
/// [`take`] when no other thread writes `bits`.
fn take_alone(bits: &[AtomicU64], w: u32) -> bool {
let (at, bit) = (&bits[w as usize / 64], 1u64 << (w % 64));
let cur = at.load(Relaxed);
if cur & bit == 0 {
return false;
}
at.store(cur & !bit, Relaxed);
true
}
/// `len` atomic words, all clear.
fn zeroed_words(len: usize) -> Vec<AtomicU64> {
(0..len).map(|_| AtomicU64::new(0)).collect()
}
impl Bufs {
/// The levels as the generic search leaves them: dense, 0 where not reached.
fn levels(&mut self, n: usize) -> Vector<u32> {
let present = Bitset::from_words(n, std::mem::take(&mut self.words));
Vector::dense(std::mem::take(&mut self.values), present).expect("a level per place")
}
/// A search from `sources`: the vertices reached and the depth. The levels are left in
/// `values`, the reached set in `words` and the steps in `steps`.
fn search(
&mut self,
out: Rows<'_>,
inn: Option<Rows<'_>>,
sources: &[u32],
opts: &BfsOptions,
device: &CpuDevice,
) -> (usize, u32) {
let n = out.vertices();
let words = n.div_ceil(64);
let threads = device.threads().max(1);
let sc = &mut self.scratch;
if sc.lanes.len() != threads {
sc.lanes = (0..threads).map(|_| Lane::new()).collect();
}
if sc.queue.len() != n {
// zeroed memory: a page is touched where a level is listed
sc.queue = vec![0; n];
}
let tail = |k: usize| {
if (k + 1) * 64 > n {
u64::MAX >> ((k + 1) * 64 - n)
} else {
u64::MAX
}
};
// the places a search may enter, word by word
let allowed = |k: usize| match &opts.allowed {
Some(m) => {
let flip = if m.is_complement() { u64::MAX } else { 0 };
(m.bits().words()[k] ^ flip) & tail(k)
}
None => tail(k),
};
if self.values.len() != n || self.words.len() != words {
self.values = vec![0; n];
self.words = vec![0; words];
// touch each page once on the device's threads: a level found on one thread
// later meets no page fault
let level = atomic_u32s(&mut self.values);
device.each_mut(&mut sc.lanes, n.div_ceil(PAGE), |r, _| {
r.for_each(|p| level[p * PAGE].store(0, Relaxed))
});
} else if self.dirty {
// zero the levels the last search wrote: its reached set is in `words`
let level = atomic_u32s(&mut self.values);
let present = &self.words;
device.each_mut(&mut sc.lanes, words, |r, _| {
for k in r {
let mut w = present[k];
while w != 0 {
level[k * 64 + w.trailing_zeros() as usize].store(0, Relaxed);
w &= w - 1;
}
}
});
}
self.dirty = false;
// open: may still be reached (allowed and not yet reached)
{
let open = atomic_words(&mut self.words);
device.each_mut(&mut sc.lanes, words, |r, _| {
r.for_each(|k| open[k].store(allowed(k), Relaxed))
});
}
sc.sources.clear();
sc.sources.extend_from_slice(sources);
sc.sources.sort_unstable();
sc.sources.dedup();
self.steps.clear();
let (reached, depth) = {
let open = atomic_words(&mut self.words);
let level = atomic_u32s(&mut self.values);
levels(out, inn, n, opts, device, open, level, sc, &mut self.steps)
};
// reached: what was allowed and is closed now, and the sources
{
let present = atomic_words(&mut self.words);
device.each_mut(&mut sc.lanes, words, |r, _| {
r.for_each(|k| present[k].store(allowed(k) & !present[k].load(Relaxed), Relaxed))
});
}
for &s in &sc.sources {
self.words[s as usize / 64] |= 1 << (s % 64);
}
(reached, depth)
}
}
/// The levels of a search from `sc.sources` (rising, each once): its steps go to `steps`;
/// the vertices reached and the depth.
#[allow(clippy::too_many_arguments)]
fn levels(
out: Rows<'_>,
inn: Option<Rows<'_>>,
n: usize,
opts: &BfsOptions,
device: &CpuDevice,
open: &[AtomicU64],
level: &[AtomicU32],
sc: &mut Scratch,
steps: &mut Vec<Step>,
) -> (usize, u32) {
let words = open.len();
let threads = device.threads().max(1);
let small = (device.grain() / 2).max(1);
let piece = (device.grain() / 32).clamp(1, 256);
let auto = opts.direction == Direction::Auto && inn.is_some();
let Scratch {
queue,
lanes,
bits,
nbits,
sources,
} = sc;
let queue = atomic_u32s(queue);
// the frontier: queue[lo..hi], and (after a pull, or built for one) a bit set
for (q, &s) in queue.iter().zip(sources.iter()) {
q.store(s, Relaxed);
take_alone(open, s);
}
let (mut lo, mut hi) = (0usize, sources.len());
let front = |i: usize| queue[i].load(Relaxed);
let mut mf = if auto {
sources.iter().map(|&s| out.degree(s)).sum()
} else {
0
};
let mut bits_hold = false;
let mut nf: usize = sources.len();
let mut reached = nf;
let mut depth = 0u32;
let edges = out.idx.len() as u64;
let mut explored = 0u64;
let mut pulling = false;
let mut last_pull = 0u64;
while nf > 0 {
if opts.max_depth.is_some_and(|d| depth >= d) {
break;
}
pulling = match (opts.direction, inn) {
(Direction::Push, _) | (Direction::Auto, None) => false,
(Direction::Pull, _) => true,
(Direction::Auto, Some(_)) => {
if pulling {
(nf as u64) * opts.beta >= n as u64 && mf >= last_pull
} else {
mf * opts.alpha > edges.saturating_sub(explored)
&& (last_pull == 0 || mf > last_pull)
}
}
};
explored += mf;
let d = depth + 1;
let parallel = threads > 1 && nf >= small;
let next = AtomicUsize::new(hi);
if pulling {
let inn = inn.expect("a pull has the transpose");
if bits.len() != words {
*bits = zeroed_words(words);
*nbits = zeroed_words(words);
}
let (bits_r, nbits_r) = (&*bits, &*nbits);
if !bits_hold {
// the frontier's bit set from its part of the queue
if parallel {
device.each_mut(lanes, words, |r, _| {
r.for_each(|k| bits_r[k].store(0, Relaxed))
});
let at = AtomicUsize::new(lo);
device.each_block(lanes, |_, _| {
loop {
let a = at.fetch_add(piece, Relaxed);
if a >= hi {
break;
}
for i in a..(a + piece).min(hi) {
let v = front(i);
bits_r[v as usize / 64].fetch_or(1 << (v % 64), Relaxed);
}
}
});
} else {
bits_r.iter().for_each(|w| w.store(0, Relaxed));
for i in lo..hi {
let v = front(i);
let k = v as usize / 64;
bits_r[k].store(bits_r[k].load(Relaxed) | 1 << (v % 64), Relaxed);
}
}
}
let pull_piece = |lane: &mut Lane, klo: usize, khi: usize| {
// counted in locals and added once: a field written per edge stays in memory
let (mut examined, mut edges) = (0u64, 0u64);
for k in klo..khi {
let mut o = open[k].load(Relaxed);
let mut found = 0u64;
let mut todo = o;
while todo != 0 {
let b = todo.trailing_zeros();
todo &= todo - 1;
let v = (k * 64) as u32 + b;
for &u in inn.row(v) {
examined += 1;
if bits_r[u as usize / 64].load(Relaxed) >> (u % 64) & 1 == 1 {
level[v as usize].store(d, Relaxed);
o &= !(1 << b);
found |= 1 << b;
lane.push(v, queue, &next);
edges += out.degree(v);
break;
}
}
}
open[k].store(o, Relaxed);
nbits_r[k].store(found, Relaxed);
}
lane.examined += examined;
lane.edges += edges;
};
if threads > 1 && words >= 2 * PULL_WORDS {
let at = AtomicUsize::new(0);
device.each_block(lanes, |_, lane| {
loop {
let klo = at.fetch_add(1, Relaxed) * PULL_WORDS;
if klo >= words {
break;
}
pull_piece(lane, klo, (klo + PULL_WORDS).min(words));
}
});
} else {
pull_piece(&mut lanes[0], 0, words);
}
std::mem::swap(bits, nbits);
bits_hold = true;
} else {
let step = |lane: &mut Lane, v: u32, alone: bool| {
let row = out.row(v);
lane.examined += row.len() as u64;
for &w in row {
let won = if alone {
take_alone(open, w)
} else {
take(open, w)
};
if won {
level[w as usize].store(d, Relaxed);
lane.push(w, queue, &next);
lane.edges += out.degree(w);
}
}
};
if parallel {
let at = AtomicUsize::new(lo);
device.each_block(lanes, |_, lane| {
loop {
let a = at.fetch_add(piece, Relaxed);
if a >= hi {
break;
}
for i in a..(a + piece).min(hi) {
step(lane, front(i), false);
}
}
});
} else {
let lane = &mut lanes[0];
for i in lo..hi {
step(lane, front(i), true);
}
}
bits_hold = false;
}
let mut examined = 0u64;
let mut next_edges = 0u64;
for lane in lanes.iter_mut() {
lane.flush(queue, &next);
examined += std::mem::take(&mut lane.examined);
next_edges += std::mem::take(&mut lane.edges);
}
let end = next.load(Relaxed);
let got = end - hi;
(lo, hi) = (hi, end);
if pulling {
last_pull = examined;
}
depth = d;
steps.push(Step {
depth,
direction: if pulling {
Direction::Pull
} else {
Direction::Push
},
frontier: nf,
reached: got,
examined,
});
if got == 0 {
depth -= 1;
break;
}
reached += got;
nf = got;
mf = if auto { next_edges } else { 0 };
}
(reached, depth)
}