crates/kleene-graph/src/multistep.rs
//! Strong components on the CPU by Multistep (Slota, Rajamanickam and Madduri 2014), on
//! the device's threads (gatling's in the benchmark).
//!
//! 1. Trim: a vertex with no live in-edge or no live out-edge is a component of its own;
//! it is taken out and its neighbours lose an edge, again and again (counters per
//! vertex, the vertices that reach zero worked level by level).
//! 2. The giant: one forward search from the live vertex with the most in- times
//! out-edges, and one backward search inside what it reached, give that vertex's
//! component. Both look only at two bit sets (the dead and what each search reached),
//! not at the vertices' names. The rest is trimmed again.
//! 3. Colours: every live vertex takes the highest vertex that reaches it (propagated
//! forward to a fixpoint); a vertex that keeps its own is a root, and its component is
//! what reaches it backwards inside its colour (one search from all roots at once).
//! Those are taken out, and the colours start again on the rest.
//! 4. Once fewer than [`TARJAN_BELOW`] vertices are left, Tarjan's search on one thread
//! finishes them.
//!
//! Each component is then named by its least vertex.
//!
//! The searches go level by level; a level of fewer vertices than half the device's grain
//! runs on the calling thread. On a road grid (thousands of levels of a few thousand
//! vertices) that is as fast as anything measured: levels shared out to the threads, also
//! with each thread going on with its own next level while that was small (fusing, as in
//! [`crate::delta_stepping`]), were up to 3x slower and never steady (loki, road2048).
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize};
use kleene_sparse::{CpuDevice, Csr};
use crate::{Components, GraphError};
/// Below this many live vertices, Tarjan's search on one thread finishes the components.
///
/// Measured on loki (5 threads): after road2048's giant, 108686 vertices are left. Tarjan's
/// search took 10-11 ms for them, a colour round 12-21 ms. On the R-MAT graphs (rmat24,
/// rmat26) trimming and the giant leave none. The whole run was the same within noise from
/// 0 to 1 << 20 and with Tarjan right after the giant.
pub const TARJAN_BELOW: usize = 1 << 17;
const LIVE: u32 = u32::MAX;
/// Strongly connected components of `out` (with its transpose `inn`) by Multistep, on the
/// device's threads; each vertex is named by the least vertex of its component.
/// [`Components::rounds`] counts the colour rounds.
pub fn multistep(out: &Csr<u8>, inn: &Csr<u8>, device: &CpuDevice) -> crate::Result<Components> {
multistep_with(out, inn, TARJAN_BELOW, device)
}
/// [`multistep`] handing the rest to Tarjan's search below `tarjan_below` live vertices
/// (0: colours to the end; `usize::MAX`: Tarjan right after the giant).
pub fn multistep_with(
out: &Csr<u8>,
inn: &Csr<u8>,
tarjan_below: usize,
device: &CpuDevice,
) -> crate::Result<Components> {
let n = out.nrows();
if out.ncols() != n {
return Err(GraphError::NotSquare {
rows: n,
cols: out.ncols(),
});
}
if inn.nrows() != n || inn.ncols() != n {
return Err(GraphError::NoTranspose);
}
let g = Two {
oo: out.pattern().offsets(),
oi: out.pattern().indices(),
io: inn.pattern().offsets(),
ii: inn.pattern().indices(),
};
let mut fr = Frontier::new(device);
// the component's name so far (any of its vertices), or LIVE
let state: Vec<AtomicU32> = (0..n).map(|_| AtomicU32::new(LIVE)).collect();
let ind: Vec<AtomicU32> = (0..n).map(|_| AtomicU32::new(0)).collect();
let outd: Vec<AtomicU32> = (0..n).map(|_| AtomicU32::new(0)).collect();
// 1. trim
fr.each(n, |v| {
ind[v].store(g.in_row(v as u32).len() as u32, Relaxed);
outd[v].store(g.out_row(v as u32).len() as u32, Relaxed);
});
trim(&mut fr, &g, &state, &ind, &outd, None);
// 2. the giant
let mut live = fr.live(&state, None);
let pivot = fr.best(&live, |v| {
u64::from(ind[v as usize].load(Relaxed)) * u64::from(outd[v as usize].load(Relaxed))
});
if let Some(p) = pivot {
// seen: the dead and what the forward search reached; done: the dead and what the
// backward search took. Reached and not yet taken: seen and not done.
let words = n.div_ceil(64);
let seen: Vec<AtomicU64> = (0..words).map(|_| AtomicU64::new(0)).collect();
let done: Vec<AtomicU64> = (0..words).map(|_| AtomicU64::new(0)).collect();
fr.each(words, |k| {
let dead = (k * 64..(k * 64 + 64).min(n))
.filter(|&v| state[v].load(Relaxed) != LIVE)
.fold(0u64, |bits, v| bits | 1 << (v % 64));
seen[k].store(dead, Relaxed);
done[k].store(dead, Relaxed);
});
set(&seen, p);
fr.search(vec![vec![p]], &|v, next| {
for &w in g.out_row(v) {
if set(&seen, w) {
next.push(w);
}
}
});
set(&done, p);
state[p as usize].store(p, Relaxed);
fr.search(vec![vec![p]], &|v, next| {
for &w in g.in_row(v) {
if has(&seen, w) && set(&done, w) {
state[w as usize].store(p, Relaxed);
next.push(w);
}
}
});
drop(seen);
// the rest, trimmed again on its own edges
live = fr.live(&state, Some(&live));
fr.each_of(&live, |v| {
let alive = |w: &&u32| !has(&done, **w);
ind[v as usize].store(g.in_row(v).iter().filter(alive).count() as u32, Relaxed);
outd[v as usize].store(g.out_row(v).iter().filter(alive).count() as u32, Relaxed);
});
drop(done);
trim(&mut fr, &g, &state, &ind, &outd, Some(&live));
live = fr.live(&state, Some(&live));
}
// 3. colours (in the in-degree counters' words, which are done with)
let colour = ind;
let mut rounds = 0u32;
while !live.is_empty() && live.len() >= tarjan_below {
rounds += 1;
fr.each_of(&live, |v| colour[v as usize].store(v, Relaxed));
fr.search(vec![live.clone()], &|v, next| {
let c = colour[v as usize].load(Relaxed);
for &w in g.out_row(v) {
let at = &colour[w as usize];
if at.load(Relaxed) < c
&& state[w as usize].load(Relaxed) == LIVE
&& at.fetch_max(c, Relaxed) < c
{
next.push(w);
}
}
});
let roots: Vec<Vec<u32>> = fr.pick(&live, |v| colour[v as usize].load(Relaxed) == v);
for &r in roots.iter().flatten() {
state[r as usize].store(r, Relaxed);
}
fr.search(roots, &|v, next| {
let c = colour[v as usize].load(Relaxed);
for &w in g.in_row(v) {
if colour[w as usize].load(Relaxed) == c && claim(&state, w, c) {
next.push(w);
}
}
});
live = fr.live(&state, Some(&live));
}
// 4. Tarjan on the rest
if !live.is_empty() {
tarjan(&g, &live, &state, &colour);
}
// name each component by its least vertex (read first: most of a giant finds it set)
let least = outd;
fr.each(n, |v| least[v].store(LIVE, Relaxed));
fr.each(n, |v| {
let at = &least[state[v].load(Relaxed) as usize];
if (v as u32) < at.load(Relaxed) {
at.fetch_min(v as u32, Relaxed);
}
});
fr.each(n, |v| {
let name = least[state[v].load(Relaxed) as usize].load(Relaxed);
state[v].store(name, Relaxed);
});
let of = state.into_iter().map(AtomicU32::into_inner).collect();
Ok(Components { of, rounds })
}
/// Name `w` for component `c` when it is still live; whether this call did.
fn claim(state: &[AtomicU32], w: u32, c: u32) -> bool {
let at = &state[w as usize];
at.load(Relaxed) == LIVE && at.compare_exchange(LIVE, c, Relaxed, Relaxed).is_ok()
}
/// Set bit `w`; whether this call did.
fn set(bits: &[AtomicU64], w: u32) -> bool {
let (at, bit) = (&bits[w as usize / 64], 1u64 << (w % 64));
at.load(Relaxed) & bit == 0 && at.fetch_or(bit, Relaxed) & bit == 0
}
/// Whether bit `w` is set.
fn has(bits: &[AtomicU64], w: u32) -> bool {
bits[w as usize / 64].load(Relaxed) >> (w % 64) & 1 == 1
}
/// A graph in both edge orders.
struct Two<'a> {
oo: &'a [u64],
oi: &'a [u32],
io: &'a [u64],
ii: &'a [u32],
}
impl Two<'_> {
fn out_row(&self, v: u32) -> &[u32] {
&self.oi[self.oo[v as usize] as usize..self.oo[v as usize + 1] as usize]
}
fn in_row(&self, v: u32) -> &[u32] {
&self.ii[self.io[v as usize] as usize..self.io[v as usize + 1] as usize]
}
}
/// Take out every live vertex (of `among`, or all) with no live in- or out-edge, and so on
/// while its neighbours reach zero: each is a component of its own.
fn trim(
fr: &mut Frontier<'_>,
g: &Two<'_>,
state: &[AtomicU32],
ind: &[AtomicU32],
outd: &[AtomicU32],
among: Option<&[u32]>,
) {
let zero = |v: u32| {
(ind[v as usize].load(Relaxed) == 0 || outd[v as usize].load(Relaxed) == 0)
&& claim(state, v, v)
};
let seeds = match among {
Some(vs) => fr.pick(vs, zero),
None => fr.pick_all(state.len(), zero),
};
fr.search(seeds, &|v, next| {
for (row, deg) in [(g.out_row(v), ind), (g.in_row(v), outd)] {
for &w in row {
if state[w as usize].load(Relaxed) == LIVE
&& deg[w as usize].fetch_sub(1, Relaxed) == 1
&& claim(state, w, w)
{
next.push(w);
}
}
}
});
}
/// Tarjan's search on one thread over the live vertices `live` and the edges between
/// them; each component found is named by its root. `local` is scratch of one word per
/// vertex.
fn tarjan(g: &Two<'_>, live: &[u32], state: &[AtomicU32], local: &[AtomicU32]) {
const NONE: u32 = u32::MAX;
for (k, &v) in live.iter().enumerate() {
local[v as usize].store(k as u32, Relaxed);
}
let m = live.len();
let (mut index, mut low) = (vec![NONE; m], vec![0u32; m]);
let mut on = vec![false; m];
let mut stack: Vec<u32> = Vec::new();
let mut call: Vec<(u32, usize)> = Vec::new();
let mut next = 0u32;
let is_live = |w: u32| state[w as usize].load(Relaxed) == LIVE;
for root in 0..m as u32 {
if index[root as usize] != NONE {
continue;
}
index[root as usize] = next;
low[root as usize] = next;
next += 1;
stack.push(root);
on[root as usize] = true;
call.push((root, 0));
while let Some(&mut (x, ref mut at)) = call.last_mut() {
let row = g.out_row(live[x as usize]);
if *at < row.len() {
let w = row[*at];
*at += 1;
if !is_live(w) {
continue;
}
let y = local[w as usize].load(Relaxed);
if index[y as usize] == NONE {
index[y as usize] = next;
low[y as usize] = next;
next += 1;
stack.push(y);
on[y as usize] = true;
call.push((y, 0));
} else if on[y as usize] {
low[x as usize] = low[x as usize].min(index[y as usize]);
}
continue;
}
call.pop();
if let Some(&(p, _)) = call.last() {
low[p as usize] = low[p as usize].min(low[x as usize]);
}
if low[x as usize] == index[x as usize] {
let name = live[x as usize];
while let Some(y) = stack.pop() {
on[y as usize] = false;
// named after the whole component is off the stack: `is_live` above
// must keep seeing its members as live until then
low[y as usize] = name;
index[y as usize] = NONE - 1;
if y == x {
break;
}
}
}
}
}
for (k, &v) in live.iter().enumerate() {
state[v as usize].store(low[k], Relaxed);
}
}
/// Level-by-level searches and parallel passes over vertices on the device's threads;
/// each thread fills its own list of the next level.
struct Frontier<'d> {
device: &'d CpuDevice,
lanes: Vec<Vec<u32>>,
/// A level of fewer vertices runs on the calling thread.
small: usize,
/// Vertices per piece handed out.
piece: usize,
}
impl<'d> Frontier<'d> {
fn new(device: &'d CpuDevice) -> Self {
Frontier {
device,
lanes: (0..device.threads().max(1)).map(|_| Vec::new()).collect(),
small: (device.grain() / 2).max(1),
piece: (device.grain() / 32).clamp(1, 256),
}
}
/// From `seeds`, level by level: `step(v, next)` puts in `next` the vertices `v` claims
/// for the next level. The levels taken.
fn search(&mut self, seeds: Vec<Vec<u32>>, step: &(dyn Fn(u32, &mut Vec<u32>) + Sync)) -> u32 {
let mut front = seeds;
let mut levels = 0;
loop {
let total: usize = front.iter().map(Vec::len).sum();
if total == 0 {
return levels;
}
levels += 1;
if total < self.small || self.lanes.len() == 1 {
let next = &mut self.lanes[0];
for &v in front.iter().flatten() {
step(v, next);
}
} else {
let piece = self.piece;
let pieces: Vec<(usize, usize)> = front
.iter()
.enumerate()
.flat_map(|(b, f)| (0..f.len()).step_by(piece).map(move |lo| (b, lo)))
.collect();
let at = AtomicUsize::new(0);
let front = &front;
self.device.each_block(&mut self.lanes, |_, next| {
loop {
let p = at.fetch_add(1, Relaxed);
let Some(&(b, lo)) = pieces.get(p) else {
break;
};
let f = &front[b];
for &v in &f[lo..(lo + piece).min(f.len())] {
step(v, next);
}
}
});
}
let next: Vec<Vec<u32>> = self.lanes.iter_mut().map(std::mem::take).collect();
for (lane, mut old) in self.lanes.iter_mut().zip(front) {
old.clear();
*lane = old;
}
front = next;
}
}
/// `f(v)` for every `v` in `0..n`, in parallel.
fn each(&self, n: usize, f: impl Fn(usize) + Sync) {
self.device.split(n, |r| r.for_each(&f));
}
/// `f(v)` for every `v` of `vs`, in parallel.
fn each_of(&self, vs: &[u32], f: impl Fn(u32) + Sync) {
self.device
.split(vs.len(), |r| vs[r].iter().for_each(|&v| f(v)));
}
/// The vertices of `vs` that `keep` holds, in pieces.
fn pick(&self, vs: &[u32], keep: impl Fn(u32) -> bool + Sync) -> Vec<Vec<u32>> {
self.device.split(vs.len(), |r| {
vs[r].iter().copied().filter(|&v| keep(v)).collect()
})
}
/// The vertices of `0..n` that `keep` holds, in pieces.
fn pick_all(&self, n: usize, keep: impl Fn(u32) -> bool + Sync) -> Vec<Vec<u32>> {
self.device
.split(n, |r| r.map(|v| v as u32).filter(|&v| keep(v)).collect())
}
/// The live vertices (of `among`, or all), rising.
fn live(&self, state: &[AtomicU32], among: Option<&[u32]>) -> Vec<u32> {
let alive = |v: u32| state[v as usize].load(Relaxed) == LIVE;
let parts = match among {
Some(vs) => self.pick(vs, alive),
None => self.pick_all(state.len(), alive),
};
parts.concat()
}
/// The vertex of `vs` with the highest `score` (the least among equal ones).
fn best(&self, vs: &[u32], score: impl Fn(u32) -> u64 + Sync) -> Option<u32> {
self.device
.split(vs.len(), |r| {
vs[r]
.iter()
.map(|&v| (score(v), std::cmp::Reverse(v)))
.max()
})
.into_iter()
.flatten()
.max()
.map(|(_, std::cmp::Reverse(v))| v)
}
}