crates/kleene-graph/src/split_compute.rs
//! A split computed from the graph itself: balanced label spreading (the published Spinner
//! rule, Martella et al. 2017), all in integers so every device gives the same list.
//!
//! The rule lives here once; the one pass over the edges of a round is the backend's
//! ([`GraphBackend::split_votes`]): the CPU backend runs it on the device's parked workers,
//! a GPU backend on the card, and every backend must give the same list. Everything else of
//! a round is per node or per part and runs here on the host.
//!
//! 1. **Start.** Each part `p` gets a limit: `capacity[p]` when capacities are given (what
//! the part may hold, taken as it is), else the equal share `ceil(n / K)` raised by
//! `slack_permille` (rounded up). Node `v` goes to the part its hash `h(seed, START, v,
//! 0)` picks with weights the limits (`x = h * W >> 64`, `W` the limits' sum, the first
//! part whose running sum of limits passes `x`). A part past its limit keeps its first
//! nodes in rising id; the rest go, in rising id, to the lowest parts with room.
//! 2. **A round** `r = 1, 2, ...`: each part's room is `65535 * (2 limit - size) / (2
//! limit)` (65535 empty, 32767 full, 0 for a part of limit 0), so a part's pull falls by at
//! most half as it fills and a full part's own nodes still stay at home when most of
//! their neighbours are there; `want = split_votes(out, inn, part, room)`. A node that
//! wants another part is a candidate when its hash `h(seed, MOVE, v, r)` is even (the
//! damping, below). Each part `q` lets in at most its free room at the round's start
//! (`limit - size`, leavers not counted, so no part ever passes its limit); with more
//! candidates than that, those of the least `(h(seed, PICK, v, r), v)` are let in. Then
//! the crossing edges are counted.
//! 3. **Stop and keep.** The split of the fewest crossing edges seen (the start included,
//! the earliest on a tie) is the result, so it never crosses more edges than its start.
//! The rounds stop at `max_rounds`, when nothing crosses, or when the crossing edges of
//! round `r` are not 0.1 % below those of round `r - 3`.
//!
//! **Damping.** If every node moves at once, two neighbours in two parts can swap and swap
//! back for ever (each sees the other's old part). Only the nodes whose hash of (node,
//! round) is even may move in a round: a hash, not a fixed half, so a pair that swapped once
//! moves together again in a later round only by a chance of one in four, and every node
//! gets its turn about every other round; deterministic, so every device and every thread
//! count gives the same list.
//!
//! `h(seed, salt, v, r) = mix(mix(seed ^ salt) + (r << 32 | v))`, `mix` SplitMix64's
//! finalizer, salts START = 1, MOVE = 2, PICK = 3.
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering::Relaxed};
use kleene_sparse::{CpuDevice, Csr};
use crate::split::{assign, block_parts};
use crate::{GraphBackend, GraphError, SplitKey};
/// The most parts [`computed_split`] makes (version 1: a kernel keeps a counter per part
/// for each node in hand).
pub const MAX_COMPUTED_PARTS: u32 = 64;
/// How [`computed_split`] cuts a graph.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SplitCompute {
/// The parts, K: 1 to [`MAX_COMPUTED_PARTS`].
pub parts: u32,
/// The nodes each part may hold (K entries, summing to at least the nodes); `None`:
/// equal shares raised by `slack_permille`.
pub capacity: Option<Vec<u64>>,
/// The most rounds (default 100; the 0.1 % rule stops most graphs well before).
pub max_rounds: u32,
/// The room above an equal share, in thousandths (default 50, 5 %); not used with
/// `capacity`.
pub slack_permille: u32,
/// The seed of every hash of the rule.
pub seed: u64,
}
impl SplitCompute {
/// `parts` parts of equal shares, 100 rounds at most, 5 % slack, seed 0.
pub fn new(parts: u32) -> Self {
SplitCompute {
parts,
capacity: None,
max_rounds: 100,
slack_permille: 50,
seed: 0,
}
}
}
/// What [`computed_split`] found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComputedSplit {
/// Per node its part, below K; goes into a split as [`SplitKey::Property`] (which
/// numbers only the parts that hold a node: see [`ComputedSplit::key`]).
pub part: Vec<u32>,
/// The nodes per part (K entries).
pub sizes: Vec<u64>,
/// The edges whose two ends are in different parts.
pub crossing_edges: u64,
/// The rounds run (0 when the start already crossed nothing).
pub rounds: u32,
}
impl ComputedSplit {
/// The key of this split. A part that holds no node makes no part of the split, so the
/// split's part numbers are then the non-empty parts in rising number.
pub fn key(&self) -> SplitKey {
SplitKey::Property(self.part.clone())
}
}
const START: u64 = 1;
const MOVE: u64 = 2;
const PICK: u64 = 3;
/// SplitMix64's finalizer.
fn mix(mut z: u64) -> u64 {
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// The rule's hash of node `v` in round `round`.
fn hash(seed: u64, salt: u64, v: u32, round: u32) -> u64 {
mix(mix(seed ^ salt).wrapping_add(((round as u64) << 32) | v as u64))
}
/// Per part the nodes it may hold.
fn limits(n: usize, how: &SplitCompute) -> crate::Result<Vec<u64>> {
let k = how.parts;
if k == 0 {
return Err(GraphError::Split(
"a computed split into 0 parts".to_string(),
));
}
if k > MAX_COMPUTED_PARTS {
return Err(GraphError::Split(format!(
"a computed split into {k} parts, more than the {MAX_COMPUTED_PARTS} it makes"
)));
}
let limit = match &how.capacity {
Some(c) => {
if c.len() != k as usize {
return Err(GraphError::Split(format!(
"{} capacities for {k} parts",
c.len()
)));
}
c.clone()
}
None => {
let share = (n as u64).div_ceil(k as u64);
let up = (share as u128 * how.slack_permille as u128).div_ceil(1000);
let up = u64::try_from(up).unwrap_or(u64::MAX);
vec![share.saturating_add(up); k as usize]
}
};
let total: u128 = limit.iter().map(|&c| c as u128).sum();
if total < n as u128 {
return Err(GraphError::Split(format!(
"parts that hold {total} nodes for a graph of {n}"
)));
}
Ok(limit)
}
/// Run `f(piece)` for every piece `0..pieces`, handed out from a shared counter to the
/// device's parked workers (one seat a thread, no thread started).
fn each_piece(cpu: &CpuDevice, pieces: usize, f: impl Fn(usize) + Sync) {
let next = AtomicUsize::new(0);
let mut seats = vec![(); cpu.threads().max(1).min(pieces)];
cpu.each_block(&mut seats, |_, ()| {
loop {
let p = next.fetch_add(1, Relaxed);
if p >= pieces {
break;
}
f(p);
}
});
}
/// The start: a hash split weighted by the limits, within them. Both passes run on the
/// workers: the picks and each piece's count per part, then (from the counts of the pieces
/// before it) each piece knows which of its nodes its parts still hold and where its first
/// node past a limit stands among all such nodes, so it places them as one pass in rising
/// id would.
fn start(n: usize, limit: &[u64], seed: u64, cpu: &CpuDevice) -> Vec<u32> {
let k = limit.len();
let mut run = Vec::with_capacity(k);
let mut sum = 0u128;
for &c in limit {
sum += c as u128;
run.push(sum);
}
let pick = |v: usize| {
let x = (hash(seed, START, v as u32, 0) as u128 * sum) >> 64;
run.partition_point(|&s| s <= x) as u32
};
let pieces: Vec<(Vec<u32>, Vec<u64>)> = cpu.split(n, |r| {
let picks: Vec<u32> = r.map(pick).collect();
let mut count = vec![0u64; k];
for &p in &picks {
count[p as usize] += 1;
}
(picks, count)
});
// per piece: the picks of each part before it, and the nodes past a limit before it
let mut before = vec![0u64; k];
let mut over = 0u64;
let mut plans = Vec::with_capacity(pieces.len());
for (_, count) in &pieces {
plans.push((before.clone(), over));
for p in 0..k {
let kept = count[p].min(limit[p].saturating_sub(before[p]));
over += count[p] - kept;
before[p] += count[p];
}
}
// the free room left after the kept nodes, as a running sum over the parts: the j-th
// node past a limit goes to the first part whose running sum passes j
let mut free_run = Vec::with_capacity(k);
let mut acc = 0u64;
for p in 0..k {
acc += limit[p] - before[p].min(limit[p]);
free_run.push(acc);
}
let slots: Vec<Mutex<Vec<u32>>> = pieces.into_iter().map(|(v, _)| Mutex::new(v)).collect();
each_piece(cpu, slots.len(), |i| {
let mut picks = slots[i].lock().unwrap_or_else(|e| e.into_inner());
let (mut seen, mut j) = (plans[i].0.clone(), plans[i].1);
for x in picks.iter_mut() {
let p = *x as usize;
if seen[p] >= limit[p] {
*x = free_run.partition_point(|&f| f <= j) as u32;
j += 1;
}
seen[p] += 1;
}
});
let mut part = Vec::with_capacity(n);
for m in slots {
part.extend(m.into_inner().unwrap_or_else(|e| e.into_inner()));
}
part
}
/// Per part its room, 0..=65535 (see the module's rule).
fn rooms(limit: &[u64], size: &[u64]) -> Vec<u32> {
limit
.iter()
.zip(size)
.map(|(&l, &s)| {
if l == 0 {
0
} else {
let l = l as u128;
(65535 * (2 * l - s as u128) / (2 * l)) as u32
}
})
.collect()
}
/// [`crossing_edges`] on the device's workers.
fn crossing_on(out: &Csr<u8>, part: &[u32], cpu: &CpuDevice) -> u64 {
cpu.split(out.nrows(), |r| crossing_rows(out, part, r))
.into_iter()
.sum()
}
fn crossing_rows(out: &Csr<u8>, part: &[u32], rows: std::ops::Range<usize>) -> u64 {
let mut c = 0u64;
for v in rows {
let p = part[v];
c += out
.row(v)
.iter()
.filter(|&&u| part[u as usize] != p)
.count() as u64;
}
c
}
/// The edges of `out` whose two ends are in different parts of `part` (one entry per
/// node): a plain count on the calling thread, for any part-per-node list (hash, id blocks
/// and computed splits are measured with it alike).
pub fn crossing_edges(out: &Csr<u8>, part: &[u32]) -> u64 {
crossing_rows(out, part, 0..out.nrows())
}
/// The part of every node under `key` for a graph of `nodes` nodes, numbered as
/// [`crate::Split::new`] numbers them, so hash, id blocks and computed splits can be
/// compared the same way.
pub fn parts_of_key(nodes: usize, key: &SplitKey) -> crate::Result<Vec<u32>> {
let (ids, part) = assign(nodes, key)?;
Ok(part.unwrap_or_else(|| block_parts(&ids)))
}
/// The CPU device for the host's work.
fn host_cpu<B: GraphBackend>(device: &B::Device) -> Option<&CpuDevice> {
B::cpu(device).or_else(|| B::host_device(device))
}
/// Cut the graph `out` (with its transpose `inn`) into `how.parts` parts so that few edges
/// cross, by balanced label spreading (the module's rule), each round's pass over the edges
/// on the backend ([`GraphBackend::split_votes`]). Every device and thread count gives the
/// same list. The backend must keep the host pattern ([`GraphBackend::host_pattern`]): the
/// crossing edges are counted there.
pub fn computed_split<B: GraphBackend>(
out: &B::Matrix<u8>,
inn: &B::Matrix<u8>,
how: &SplitCompute,
device: &B::Device,
) -> crate::Result<ComputedSplit> {
let (Some(o), Some(i)) = (B::host_pattern(out), B::host_pattern(inn)) else {
return Err(GraphError::Split(
"a computed split needs the graph's host pattern".to_string(),
));
};
let n = check(o, i)?;
let limit = limits(n, how)?;
let one;
let cpu = match host_cpu::<B>(device) {
Some(c) => c,
None => {
one = CpuDevice::new(1);
&one
}
};
let k = limit.len();
let mut part = start(n, &limit, how.seed, cpu);
let mut size = vec![0u64; k];
for &p in &part {
size[p as usize] += 1;
}
let c0 = crossing_on(o, &part, cpu);
let mut best = (c0, part.clone(), size.clone());
let mut history = vec![c0];
let mut rounds = 0u32;
let mut wanting: Vec<Vec<(u64, u32)>> = vec![Vec::new(); k];
// per worker, per part its candidates (kept between the rounds)
let mut found: Vec<Vec<Vec<(u64, u32)>>> = vec![vec![Vec::new(); k]; cpu.threads().max(1)];
while c0 > 0 && rounds < how.max_rounds {
rounds += 1;
let r = rounds;
let room = rooms(&limit, &size);
let want = B::split_votes(out, inn, &part, &room, device)?;
if want.len() != n {
return Err(GraphError::Split(format!(
"split votes for {} nodes, the graph has {n}",
want.len()
)));
}
candidates(&want, &part, how.seed, r, cpu, &mut found)?;
// per part: every worker's candidates, then the least (hash, node) up to its room
{
let slots: Vec<PartSlot<'_>> = wanting
.iter_mut()
.enumerate()
.map(|(q, w)| Mutex::new((q, w)))
.collect();
let (found, size, limit) = (&found, &size, &limit);
each_piece(cpu, k, |i| {
let mut slot = slots[i].lock().unwrap_or_else(|e| e.into_inner());
let (q, list) = &mut *slot;
let q = *q;
list.clear();
for f in found {
list.extend_from_slice(&f[q]);
}
let free = (limit[q] - size[q]).min(list.len() as u64) as usize;
if free < list.len() {
if free == 0 {
list.clear();
} else {
list.select_nth_unstable(free - 1);
list.truncate(free);
}
}
});
}
for (q, list) in wanting.iter().enumerate() {
for &(_, v) in list {
size[part[v as usize] as usize] -= 1;
size[q] += 1;
part[v as usize] = q as u32;
}
}
let c = crossing_on(o, &part, cpu);
if c < best.0 {
best = (c, part.clone(), size.clone());
}
history.push(c);
if c == 0 {
break;
}
if rounds >= 3 {
let before = history[rounds as usize - 3];
if before.saturating_sub(c).saturating_mul(1000) < before {
break;
}
}
}
let (crossing_edges, part, sizes) = best;
Ok(ComputedSplit {
part,
sizes,
crossing_edges,
rounds,
})
}
/// A part's number and its candidates, handed to one worker at a time.
type PartSlot<'a> = Mutex<(usize, &'a mut Vec<(u64, u32)>)>;
/// The round's candidates on the workers: each node that wants another part (checked below
/// K) and whose hash of (node, round) is even, with its admission hash, in its worker's list
/// for that part (`found[t][q]`). Which worker holds a candidate does not matter: a part
/// takes the least (hash, node) of all of them.
fn candidates(
want: &[u32],
part: &[u32],
seed: u64,
round: u32,
cpu: &CpuDevice,
found: &mut [Vec<Vec<(u64, u32)>>],
) -> crate::Result<()> {
let n = part.len();
let k = found.first().map_or(0, Vec::len);
let pieces = if cpu.threads() <= 1 || n < 2 * cpu.grain() {
1
} else {
(cpu.threads() * 8).min(n)
};
let size = n.div_ceil(pieces.max(1)).max(1);
let next = AtomicUsize::new(0);
let wrong = AtomicU32::new(u32::MAX);
let seats = found.len().min(pieces).max(1);
cpu.each_block(&mut found[..seats], |_, lists| {
for l in lists.iter_mut() {
l.clear();
}
loop {
let p = next.fetch_add(1, Relaxed);
if p * size >= n {
break;
}
for v in p * size..((p + 1) * size).min(n) {
let q = want[v];
if q == part[v] {
continue;
}
if q as usize >= k {
wrong.store(q, Relaxed);
continue;
}
let v = v as u32;
if hash(seed, MOVE, v, round) & 1 == 0 {
lists[q as usize].push((hash(seed, PICK, v, round), v));
}
}
}
});
for l in found[seats..].iter_mut().flatten() {
l.clear();
}
match wrong.into_inner() {
u32::MAX => Ok(()),
q => Err(GraphError::Split(format!(
"split votes want part {q} of {k}"
))),
}
}
/// The node count of a square `out` whose transpose `inn` has its shape.
fn check(out: &Csr<u8>, inn: &Csr<u8>) -> crate::Result<usize> {
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);
}
if n > u32::MAX as usize {
return Err(GraphError::TooManyVertices {
vertices: n,
limit: u32::MAX as usize,
});
}
Ok(n)
}
/// The inputs of a pass of split votes, checked: the node count.
fn check_votes(out: &Csr<u8>, inn: &Csr<u8>, part: &[u32], room: &[u32]) -> crate::Result<usize> {
let n = check(out, inn)?;
let k = room.len();
if k == 0 || k > MAX_COMPUTED_PARTS as usize {
return Err(GraphError::Split(format!(
"split votes over {k} parts (1 to {MAX_COMPUTED_PARTS})"
)));
}
if part.len() != n {
return Err(GraphError::Split(format!(
"a part for {} nodes, the graph has {n}",
part.len()
)));
}
if let Some(&p) = part.iter().find(|&&p| p as usize >= k) {
return Err(GraphError::Split(format!("a node in part {p} of {k}")));
}
Ok(n)
}
/// The CPU kernel of [`GraphBackend::split_votes`]: one pass over each node's out- and
/// in-edges with K counters in hand, the nodes cut into pieces of about equal edges handed
/// out from a shared counter to the device's parked workers (no thread started).
pub(crate) fn split_votes_cpu(
out: &Csr<u8>,
inn: &Csr<u8>,
part: &[u32],
room: &[u32],
cpu: &CpuDevice,
) -> crate::Result<Vec<u32>> {
let n = check_votes(out, inn, part, room)?;
let mut want = vec![0u32; n];
let (oo, io) = (out.pattern().offsets(), inn.pattern().offsets());
let edges = |v: usize| oo[v] + io[v];
let total = edges(n);
let threads = cpu.threads().max(1);
let pieces = if threads == 1 || total < 2 * cpu.grain() as u64 {
1
} else {
(threads * 16).min(n.max(1))
};
// cuts at about equal edges (both directions)
let mut cuts = vec![0usize];
for j in 1..pieces {
let at = total * j as u64 / pieces as u64;
// the first node whose edges before it reach `at`
let (mut lo, mut hi) = (0, n);
while lo < hi {
let mid = lo + (hi - lo) / 2;
if edges(mid) < at {
lo = mid + 1;
} else {
hi = mid;
}
}
let c = lo;
if c > *cuts.last().expect("a first cut") {
cuts.push(c);
}
}
cuts.push(n);
let mut slots: Vec<Mutex<(usize, &mut [u32])>> = Vec::with_capacity(cuts.len());
let mut rest: &mut [u32] = &mut want;
for w in cuts.windows(2) {
let (now, later) = rest.split_at_mut(w[1] - w[0]);
slots.push(Mutex::new((w[0], now)));
rest = later;
}
let next = AtomicUsize::new(0);
let mut seats = vec![(); threads.min(slots.len())];
cpu.each_block(&mut seats, |_, ()| {
let mut count = [0u32; MAX_COMPUTED_PARTS as usize];
loop {
let p = next.fetch_add(1, Relaxed);
if p >= slots.len() {
break;
}
let mut slot = slots[p].lock().unwrap_or_else(|e| e.into_inner());
let (first, wants) = &mut *slot;
for (k, w) in wants.iter_mut().enumerate() {
*w = vote(out, inn, part, room, *first + k, &mut count);
}
}
});
drop(slots);
Ok(want)
}
/// The part node `v` wants (the rule of [`GraphBackend::split_votes`]); `count` comes and
/// goes back all zero.
fn vote(
out: &Csr<u8>,
inn: &Csr<u8>,
part: &[u32],
room: &[u32],
v: usize,
count: &mut [u32; MAX_COMPUTED_PARTS as usize],
) -> u32 {
let mut seen = 0u64;
for &u in out.row(v).iter().chain(inn.row(v)) {
if u as usize == v {
continue;
}
let p = part[u as usize];
count[p as usize] += 1;
seen |= 1 << p;
}
let own = part[v];
let mut best = own;
let mut top = count[own as usize] as u64 * room[own as usize] as u64;
while seen != 0 {
let p = seen.trailing_zeros();
seen &= seen - 1;
let s = count[p as usize] as u64 * room[p as usize] as u64;
if s > top {
best = p;
top = s;
}
count[p as usize] = 0;
}
best
}