crates/kleene-index/benches/walks.rs
//! The graph searches the rules use, one implementation against the other, on real sets:
//! reach from the entries (kleene's BFS vs gatling's mask walk, pushing only and with the
//! transpose, vs the condensed walk),
//! which of 64 sources reach each vertex (kleene's reach_sets vs the mask walk vs the
//! condensed walk), and strong components (kleene-graph's scc vs gatling's Condensed,
//! which kleene-index uses). Every pair is checked equal. `KLEENE_WALK` lists the sets:
//! `name=dir:edge:entry_table.column;...`. Times are the best of 5.
use std::hint::black_box;
use std::sync::Arc;
use std::time::Instant;
use gatling::gatling_mask_walk::{
Condensed, Csr as GCsr, MaskWalk, gatling_mask_walk, gatling_mask_walk_pull,
};
use kleene_gar::GarGraph;
use kleene_graph::{BfsOptions, Graph, bfs, reach_sets, scc};
use kleene_index::Gatling;
use kleene_sparse::{CpuBackend, CpuDevice, Csr};
fn ms<T>(mut f: impl FnMut() -> T) -> (f64, T) {
let mut best = f64::MAX;
let mut out = None;
for _ in 0..5 {
let t = Instant::now();
let v = black_box(f());
best = best.min(t.elapsed().as_secs_f64() * 1e3);
out = Some(v);
}
(best, out.expect("ran"))
}
fn same_partition(a: &[u32], b: &[u32]) -> bool {
let mut ab = std::collections::HashMap::new();
let mut ba = std::collections::HashMap::new();
a.iter()
.zip(b)
.all(|(&x, &y)| *ab.entry(x).or_insert(y) == y && *ba.entry(y).or_insert(x) == x)
}
fn one(name: &str, dir: &str, edge: &str, entry: &str) {
let g = GarGraph::open(dir).unwrap();
let t = g.edge_type(edge).unwrap().clone();
let adj = g.adjacency(&t).unwrap();
let n = adj.sources;
let (et, ec) = entry.split_once('.').unwrap();
let entries: Vec<u32> = {
let a = g.vertex_column(et, ec).unwrap();
use arrow_array::cast::AsArray;
match a.data_type() {
arrow_schema::DataType::UInt32 => a
.as_primitive::<arrow_array::types::UInt32Type>()
.values()
.to_vec(),
_ => a
.as_primitive::<arrow_array::types::Int64Type>()
.values()
.iter()
.map(|&x| x as u32)
.collect(),
}
};
let out = Csr::<u8>::new(
n,
n,
adj.out_offsets.clone(),
adj.out_neighbours.clone(),
None,
)
.unwrap();
let inn = Csr::<u8>::new(
n,
n,
adj.in_offsets.clone(),
adj.in_neighbours.clone(),
None,
)
.unwrap();
let pool = CpuDevice::default();
let gat = CpuDevice::with_executor(Arc::new(Gatling::new(0)));
let gc = GCsr::new(&adj.out_offsets, &adj.out_neighbours);
let gt = GCsr::new(&adj.in_offsets, &adj.in_neighbours);
println!(
"{name}: {n} vertices, {} edges, {} entries, {} threads",
adj.out_neighbours.len(),
entries.len(),
pool.threads()
);
// reach from the entries
let graph = Graph::<CpuBackend>::with_transpose(out.clone(), inn.clone(), &pool).unwrap();
let opts = BfsOptions::default();
let (k_pool, b) = ms(|| bfs(&graph, &entries, &opts, &pool).unwrap().reached);
let graph_g = Graph::<CpuBackend>::with_transpose(out.clone(), inn.clone(), &gat).unwrap();
let (k_gat, _) = ms(|| bfs(&graph_g, &entries, &opts, &gat).unwrap().reached);
let steps = bfs(&graph, &entries, &opts, &pool).unwrap().steps;
let steps: Vec<String> = steps
.iter()
.map(|s| format!("{:?} {}->{}", s.direction, s.frontier, s.reached))
.collect();
println!(" kleene BFS steps: {}", steps.join(", "));
let seeds: Vec<(u32, u64)> = entries.iter().map(|&e| (e, 1)).collect();
let (mw, masks) = ms(|| {
let mut m = vec![0u64; n];
gatling_mask_walk(gc, &mut m, &seeds, MaskWalk::default());
m
});
let reached = masks.iter().filter(|&&m| m != 0).count();
assert_eq!(reached, b, "{name}: mask walk reach = kleene BFS");
let (mp, pm) = ms(|| {
let mut m = vec![0u64; n];
gatling_mask_walk_pull(gc, gt, &mut m, &seeds, MaskWalk::default());
m
});
assert_eq!(pm, masks, "{name}: pulling mask walk = mask walk");
let (cnew, cond) = ms(|| Condensed::new(gc));
let wseeds: Vec<(u32, &[u64])> = entries.iter().map(|&e| (e, &[1u64][..])).collect();
let (cw, cm) = ms(|| {
let mut m = vec![0u64; n];
cond.walk(1, &mut m, &wseeds);
m
});
assert_eq!(cm, masks, "{name}: condensed walk = mask walk");
println!(
" reach from entries ({reached} reached): kleene BFS {k_pool:.3} ms (pool) / {k_gat:.3} ms (gatling) | gatling_mask_walk {mw:.3} ms / {mp:.3} ms (pull) | Condensed walk {cw:.3} ms (+ {cnew:.3} ms to condense)"
);
// 64 sources
let mut sources: Vec<u32> = entries.clone();
let mut k = 0u64;
while sources.len() < 64 {
sources.push(((k * 7919 + 13) % n as u64) as u32);
k += 1;
}
sources.truncate(64);
let (k64, sets) = ms(|| reach_sets::<CpuBackend>(&out, &sources, &pool).unwrap());
let (k64g, _) = ms(|| reach_sets::<CpuBackend>(&out, &sources, &gat).unwrap());
let seeds64: Vec<(u32, u64)> = sources
.iter()
.enumerate()
.map(|(i, &s)| (s, 1u64 << i))
.collect();
let (mw64, m64) = ms(|| {
let mut m = vec![0u64; n];
gatling_mask_walk(gc, &mut m, &seeds64, MaskWalk::default());
m
});
let (mp64, pm64) = ms(|| {
let mut m = vec![0u64; n];
gatling_mask_walk_pull(gc, gt, &mut m, &seeds64, MaskWalk::default());
m
});
assert_eq!(pm64, m64, "{name}: pulling mask walk = mask walk (64)");
let w64: Vec<[u64; 1]> = seeds64.iter().map(|&(_, b)| [b]).collect();
let wseeds64: Vec<(u32, &[u64])> = seeds64
.iter()
.zip(&w64)
.map(|(&(s, _), b)| (s, &b[..]))
.collect();
let (cw64, cm64) = ms(|| {
let mut m = vec![0u64; n];
cond.walk(1, &mut m, &wseeds64);
m
});
assert_eq!(cm64, m64, "{name}: condensed walk = mask walk (64)");
for v in (0..n as u32).step_by(97) {
let mut want: Vec<u32> = (0..64)
.filter(|&i| m64[v as usize] >> i & 1 == 1)
.map(|i| sources[i])
.collect();
let mut got = sets.sources_of(v);
want.sort_unstable();
want.dedup();
got.sort_unstable();
got.dedup();
assert_eq!(got, want, "{name}: sources of {v}");
}
println!(
" 64 sources: kleene reach_sets {k64:.3} ms (pool) / {k64g:.3} ms (gatling) | gatling_mask_walk {mw64:.3} ms / {mp64:.3} ms (pull) | Condensed walk {cw64:.3} ms"
);
// strong components
let (ks, kc) = ms(|| scc::<CpuBackend>(&out, &pool).unwrap());
let cc: Vec<u32> = (0..n as u32).map(|v| cond.component(v)).collect();
assert!(
same_partition(&kc.of, &cc),
"{name}: kleene scc = Condensed"
);
println!(
" strong components ({}): kleene-graph scc {ks:.3} ms | gatling Condensed {cnew:.3} ms",
cond.components()
);
}
fn main() {
let Ok(list) = std::env::var("KLEENE_WALK") else {
eprintln!("KLEENE_WALK is not set: nothing to bench");
return;
};
for item in list.split(';').filter(|s| !s.is_empty()) {
let (name, rest) = item.split_once('=').unwrap();
let mut p = rest.split(':');
let (dir, edge, entry) = (p.next().unwrap(), p.next().unwrap(), p.next().unwrap());
one(name, dir, edge, entry);
}
}