crates/kleene-index/src/exec.rs
//! gatling (znippy-zoomies' all-core engine) as the executor of kleene's CPU device: a
//! program that already runs gatling's parked pool hands it to kleene, and every parallel
//! step runs there instead of on a second set of threads.
// The unsafe in the crate: the promise `Executor` asks for, and the atomic views of a
// transpose's columns while the pool fills them (below).
#![allow(unsafe_code)]
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, TryLockError};
use gatling::gatling_map::Pool;
use gatling::gatling_mask_walk::{
Condensed, Csr as GCsr, EdgeSets, MaskWalk, SMALL_LEVEL, gatling_mask_walk_pull,
gatling_mask_walk_sets,
};
use kleene_sparse::{CpuDevice, Executor};
/// gatling's parked pool behind kleene's [`Executor`]. One job runs at a time: a second
/// caller, or a job calling back into the device, runs its shares on its own thread.
/// Strong components come from gatling's `Condensed` (one Tarjan for kleene and the
/// rules). Source sets come from the condensed walk on graphs of up to
/// [`CONDENSED_WALK_EDGES`] edges, and above that from gatling's mask walk with pull
/// steps over a transpose built on the pool (R-MAT 22, 64 sources, oden loaded: 470-820
/// ms against 990-1750 for kleene's own search).
pub struct Gatling {
threads: usize,
/// Started at the first job that needs more than the calling thread.
pool: OnceLock<Pool>,
gate: Mutex<()>,
/// Graphs of more edges take the pulling mask walk.
condensed_walk_edges: usize,
}
/// Graphs of at most this many edges take the condensed walk (condense, then one pass in
/// component order: zox-M 2.1 ms against 10.5 for kleene's own); larger ones the pulling
/// mask walk.
pub const CONDENSED_WALK_EDGES: usize = 1 << 22;
const _: () = assert!(std::mem::align_of::<u32>() == std::mem::align_of::<AtomicU32>());
const _: () = assert!(std::mem::align_of::<u64>() == std::mem::align_of::<AtomicU64>());
/// A transpose sorts its edges in blocks of this many bits of target.
const BLOCK_BITS: usize = 14;
/// A column seen as atomics, so the shares of a job write their own places in it.
fn atomic_u64(column: &mut [u64]) -> &[AtomicU64] {
// SAFETY: `AtomicU64` has the size and (checked above) the alignment of `u64`, and the
// column is borrowed mutably for the life of the view.
unsafe { &*(column as *mut [u64] as *const [AtomicU64]) }
}
/// [`atomic_u64`] for `u32`.
fn atomic_u32(column: &mut [u32]) -> &[AtomicU32] {
// SAFETY: as in `atomic_u64`.
unsafe { &*(column as *mut [u32] as *const [AtomicU32]) }
}
impl Gatling {
/// A pool of `threads` parked workers (`0`: one per core), started at the first job
/// that needs it.
pub fn new(threads: usize) -> Self {
let threads = if threads == 0 {
gatling::gatling_forkjoin::default_workers()
} else {
threads
};
Gatling {
threads: threads.max(1),
pool: OnceLock::new(),
gate: Mutex::new(()),
condensed_walk_edges: CONDENSED_WALK_EDGES,
}
}
/// The same engine with graphs of more than `edges` edges on the pulling mask walk
/// (default [`CONDENSED_WALK_EDGES`]).
pub fn with_condensed_walk_edges(mut self, edges: usize) -> Self {
self.condensed_walk_edges = edges;
self
}
/// A CPU device on a new gatling pool of `threads` workers (`0`: one per core).
pub fn device(threads: usize) -> CpuDevice {
CpuDevice::with_executor(Arc::new(Gatling::new(threads)))
}
fn pool(&self) -> &Pool {
self.pool.get_or_init(|| Pool::new(self.threads))
}
/// The transpose of the graph `off`/`adj`, built on the pool with no shared counter
/// (a hub's in-edges would have every worker on one cache line): each share of the
/// sources counts its edges per block of targets, the edges are scattered as (target,
/// source) pairs into one region per share and block, and each block then sorts its
/// pairs by target on its own. An in-list holds its sources rising.
fn transpose(&self, off: &[u64], adj: &[u32]) -> (Vec<u64>, Vec<u32>) {
let n = off.len() - 1;
let m = adj.len();
let shares = self.threads.min(m.div_ceil(1 << 16)).max(1);
let blocks = n.div_ceil(1 << BLOCK_BITS).max(1);
// share `s` takes the sources whose edges start in its piece of `adj`
let cut = |s: usize| off.partition_point(|&o| o < (m * s / shares) as u64).min(n);
let edges = |s: usize| &adj[off[cut(s)] as usize..off[cut(s + 1)] as usize];
// pass 1: edges per share and block
let mut hist = vec![0u64; shares * blocks];
{
let h = atomic_u64(&mut hist);
self.run(shares, &|s| {
let mut row = vec![0u64; blocks];
for &v in edges(s) {
row[v as usize >> BLOCK_BITS] += 1;
}
for (x, c) in h[s * blocks..(s + 1) * blocks].iter().zip(row) {
x.store(c, Ordering::Relaxed);
}
});
}
// where each share's pairs of each block go, block after block
let mut start = vec![0u64; shares * blocks];
let mut block_start = Vec::with_capacity(blocks + 1);
let mut at = 0u64;
for b in 0..blocks {
block_start.push(at);
for s in 0..shares {
start[s * blocks + b] = at;
at += hist[s * blocks + b];
}
}
block_start.push(at);
// pass 2: the pairs, target high, source low
let mut pairs = vec![0u64; m];
{
let out = atomic_u64(&mut pairs);
self.run(shares, &|s| {
let mut cur = start[s * blocks..(s + 1) * blocks].to_vec();
for u in cut(s)..cut(s + 1) {
for &v in &adj[off[u] as usize..off[u + 1] as usize] {
let c = &mut cur[v as usize >> BLOCK_BITS];
out[*c as usize].store(u64::from(v) << 32 | u as u64, Ordering::Relaxed);
*c += 1;
}
}
});
}
// pass 3: each block by target, its sources in share and source order
let mut toff = vec![0u64; n + 1];
let mut tadj = vec![0u32; m];
{
let (to, ta) = (atomic_u64(&mut toff), atomic_u32(&mut tadj));
let next = AtomicUsize::new(0);
let pairs = &pairs;
self.run(shares, &|_| {
let mut count = vec![0u64; 1 << BLOCK_BITS];
loop {
let b = next.fetch_add(1, Ordering::Relaxed);
if b >= blocks {
break;
}
let lo = b << BLOCK_BITS;
let hi = ((b + 1) << BLOCK_BITS).min(n);
let seg = &pairs[block_start[b] as usize..block_start[b + 1] as usize];
count.fill(0);
for &p in seg {
count[(p >> 32) as usize - lo] += 1;
}
let mut at = block_start[b];
for (v, c) in (lo..hi).zip(count.iter_mut()) {
to[v].store(at, Ordering::Relaxed);
let k = *c;
*c = at;
at += k;
}
for &p in seg {
let c = &mut count[(p >> 32) as usize - lo];
ta[*c as usize].store(p as u32, Ordering::Relaxed);
*c += 1;
}
}
});
}
toff[n] = m as u64;
(toff, tadj)
}
}
impl std::fmt::Debug for Gatling {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Gatling({} workers)", self.threads)
}
}
// SAFETY: `for_some_workers(n, f)` runs `f(i, n)` once for every `i` in `0..n` (the caller
// is 0, the woken workers take the seats 1..n) and returns after all of them; `n` is at
// most `threads()`. When busy every share runs here in turn. Panics are raised after all
// shares finished, by gatling or by the loop's own unwinding.
unsafe impl Executor for Gatling {
fn threads(&self) -> usize {
self.threads
}
fn run(&self, n: usize, job: &(dyn Fn(usize) + Sync)) {
let n = n.min(self.threads());
let gate = match self.gate.try_lock() {
Ok(g) => Some(g),
Err(TryLockError::Poisoned(p)) => Some(p.into_inner()),
Err(TryLockError::WouldBlock) => None,
};
match gate {
Some(_held) if n > 1 => self.pool().for_some_workers(n, |i, _| job(i)),
_ => (0..n).for_each(job),
}
}
fn strong_components(&self, off: &[u64], adj: &[u32]) -> Option<Vec<u32>> {
let c = Condensed::new(GCsr::new(off, adj));
Some(
(0..(off.len() - 1) as u32)
.map(|v| c.component(v))
.collect(),
)
}
fn mask_walk(
&self,
off: &[u64],
adj: &[u32],
batches: &[&[(u32, u64)]],
) -> Option<Vec<Vec<u64>>> {
let n = off.len() - 1;
let g = GCsr::new(off, adj);
if adj.len() > self.condensed_walk_edges {
let (toff, tadj) = self.transpose(off, adj);
let gt = GCsr::new(&toff, &tadj);
let opts = MaskWalk {
workers: self.threads,
small_level: SMALL_LEVEL,
};
let walks = batches.iter().map(|seeds| {
let mut masks = vec![0u64; n];
gatling_mask_walk_pull(g, gt, &mut masks, seeds, opts);
masks
});
return Some(walks.collect());
}
let c = Condensed::new(g);
let walks = batches.iter().map(|seeds| {
let mut masks = vec![0u64; n];
let words: Vec<[u64; 1]> = seeds.iter().map(|&(_, m)| [m]).collect();
let s: Vec<(u32, &[u64])> = seeds
.iter()
.zip(&words)
.map(|(&(v, _), w)| (v, &w[..]))
.collect();
c.walk(1, &mut masks, &s);
masks
});
Some(walks.collect())
}
/// gatling's mask walk with edge sets (each edge passes its set's bits), all words in
/// one walk.
fn mask_walk_sets(
&self,
off: &[u64],
adj: &[u32],
slot_set: &[u32],
set_words: &[u64],
words: usize,
seeds: &[(u32, &[u64])],
) -> Option<Vec<u64>> {
let n = off.len() - 1;
let mut masks = vec![0u64; n * words];
let opts = MaskWalk {
workers: self.threads,
small_level: SMALL_LEVEL,
};
gatling_mask_walk_sets(
GCsr::new(off, adj),
EdgeSets::new(slot_set, set_words, words),
&mut masks,
seeds,
opts,
);
Some(masks)
}
}