Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/src/afforest.rs

//! Weak components on the CPU by Afforest (Sutton, Ben-Nun and Barak 2018), on the
//! device's threads (gatling's in the benchmark).
//!
//! 1. Every vertex is its own parent. In each of [`NEIGHBOUR_ROUNDS`] rounds every vertex
//!    links to its next out-neighbour, and the parents are compressed.
//! 2. The most common root among [`SAMPLES`] vertices is taken for the giant component.
//! 3. Every vertex outside the giant links to the rest of its out-neighbours and to all of
//!    its in-neighbours. A vertex of the giant is skipped: an edge from it to a vertex
//!    outside is linked from the other end, which has it in its in-row or its out-row. On
//!    skewed graphs most edges are in the giant and are never looked at. The parents are
//!    compressed once more.
//!
//! Linking is lock-free union-find: of two roots the higher is hooked onto the lower by a
//! compare-and-swap on its parent, so a root is always the least vertex of its tree and
//! the answer is named as [`crate::GraphBackend`] asks with no renaming pass.
//!
//! The parent reads are random, about one cache miss per vertex per pass, so the link passes
//! and the first two compress passes ask for the parent entry they will read
//! [`FETCH_AHEAD`] vertices (or edges) ahead (`kleene_sparse::prefetch_read`), and the
//! misses overlap. The last compress, on short chains, does not: there the extra read costs
//! more than it saves.

use std::ops::Range;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU32, AtomicUsize};

use kleene_sparse::{CpuDevice, Csr, atomic_u32s, prefetch_read};

use crate::{Components, GraphError};

/// The out-neighbours every vertex links to before the giant component is sampled.
pub const NEIGHBOUR_ROUNDS: usize = 2;

/// The vertices whose roots are counted to find the giant component.
pub const SAMPLES: usize = 1024;

/// How far ahead (in vertices, or edges in the final link) a pass asks for the parent
/// entry it will read: 16 to 32 measured best at rmat-like scales 24 and 26, 8 too short.
pub const FETCH_AHEAD: usize = 32;

/// Parent entries asked for ahead (read by the tests).
#[cfg(test)]
static FETCHES: AtomicUsize = AtomicUsize::new(0);

/// Ask for `comp[i]`'s cache line (nothing past the end).
#[inline(always)]
fn fetch(comp: &[AtomicU32], i: usize) {
    prefetch_read(comp, i);
    #[cfg(test)]
    FETCHES.fetch_add(1, Relaxed);
}

/// Weakly connected components of the graph `out` (with its transpose `inn`) by Afforest,
/// on the device's threads; each vertex is named by the least vertex of its component.
/// [`Components::rounds`] is the neighbour rounds and the final pass.
pub fn afforest(out: &Csr<u8>, inn: &Csr<u8>, device: &CpuDevice) -> crate::Result<Components> {
    let mut st = AfforestState::new();
    let rounds = afforest_with(out, inn, device, &mut st)?;
    Ok(Components {
        of: st.into_labels(),
        rounds,
    })
}

/// [`afforest`]'s buffers, kept between runs: a warm run on a graph of the same size
/// allocates nothing, and every pass over the vertices runs on the device's threads.
#[derive(Debug, Default)]
pub struct AfforestState {
    /// Zeroed memory when made (no pass writes it before the workers touch it), read and
    /// written as atomics during a run.
    parents: Vec<u32>,
    seen: Vec<u32>,
}

impl AfforestState {
    /// No buffers yet (the first run makes them).
    pub fn new() -> Self {
        Self::default()
    }

    /// The component of vertex `v` after the last run (its least vertex).
    pub fn label(&self, v: usize) -> u32 {
        self.parents[v]
    }

    /// The vertices of the last run.
    pub fn len(&self) -> usize {
        self.parents.len()
    }

    /// Whether the last run had no vertex.
    pub fn is_empty(&self) -> bool {
        self.parents.is_empty()
    }

    /// The number of components of the last run (the vertices that name their own), counted
    /// on the device's threads.
    pub fn count(&self, device: &CpuDevice) -> usize {
        let comp = &self.parents[..];
        let total = AtomicUsize::new(0);
        each(device, comp.len(), |vs| {
            let mine = vs.filter(|&v| comp[v] == v as u32).count();
            total.fetch_add(mine, Relaxed);
        });
        total.into_inner()
    }

    /// The labels of the last run, the buffer moved out.
    pub fn into_labels(self) -> Vec<u32> {
        self.parents
    }
}

/// [`afforest`] into `st`'s kept buffers ([`AfforestState::label`],
/// [`AfforestState::count`]); returns the rounds (the neighbour rounds and the final pass).
pub fn afforest_with(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    device: &CpuDevice,
    st: &mut AfforestState,
) -> crate::Result<u32> {
    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 (oo, oi) = (out.pattern().offsets(), out.pattern().indices());
    let (io, ii) = (inn.pattern().offsets(), inn.pattern().indices());
    // Only a graph of another size changes the buffer; every vertex is set on the workers.
    if st.parents.len() != n {
        // zeroed memory: the first touch of each page is the workers' setting below
        st.parents = vec![0; n];
    }
    let comp = atomic_u32s(&mut st.parents);
    let ahead = FETCH_AHEAD;
    each(device, n, |vs| {
        for v in vs {
            comp[v].store(v as u32, Relaxed);
        }
    });
    // 1. a few neighbours of every vertex
    for r in 0..NEIGHBOUR_ROUNDS {
        each(device, n, |vs| {
            for v in vs {
                // the neighbour vertex v + ahead links, its parent asked for now
                let w = v + ahead;
                if ahead > 0 && w < n {
                    let (lo, hi) = (oo[w] as usize, oo[w + 1] as usize);
                    if lo + r < hi {
                        fetch(comp, oi[lo + r] as usize);
                    }
                }
                let (lo, hi) = (oo[v] as usize, oo[v + 1] as usize);
                if lo + r < hi {
                    link(v as u32, oi[lo + r], comp);
                }
            }
        });
        each(device, n, |vs| compress(comp, vs, ahead));
    }
    // 2. the giant
    let giant = most_common_root(comp, &mut st.seen);
    // 3. the rest of the edges of the vertices outside it
    each(device, n, |vs| {
        for v in vs {
            if comp[v].load(Relaxed) == giant {
                continue;
            }
            let (lo, hi) = (oo[v] as usize, oo[v + 1] as usize);
            // the edge `ahead` places on (in the neighbour lists as stored), its parent asked
            // for now
            for j in (lo + NEIGHBOUR_ROUNDS).min(hi)..hi {
                if ahead > 0
                    && let Some(&u) = oi.get(j + ahead)
                {
                    fetch(comp, u as usize);
                }
                link(v as u32, oi[j], comp);
            }
            for j in io[v] as usize..io[v + 1] as usize {
                if ahead > 0
                    && let Some(&u) = ii.get(j + ahead)
                {
                    fetch(comp, u as usize);
                }
                link(v as u32, ii[j], comp);
            }
        }
    });
    // short chains now: no fetch ahead
    each(device, n, |vs| compress(comp, vs, 0));
    Ok(NEIGHBOUR_ROUNDS as u32 + 1)
}

/// Join the trees of `u` and `v`: walk both up to their roots and hook the higher root
/// onto the lower; a hook that loses its race walks on from what the winner wrote.
fn link(u: u32, v: u32, comp: &[AtomicU32]) {
    let parent = |x: u32| comp[x as usize].load(Relaxed);
    let (mut p1, mut p2) = (parent(u), parent(v));
    while p1 != p2 {
        let (high, low) = if p1 > p2 { (p1, p2) } else { (p2, p1) };
        let up = parent(high);
        // already hooked there, or hooked there now
        if up == low
            || (up == high
                && comp[high as usize]
                    .compare_exchange(high, low, Relaxed, Relaxed)
                    .is_ok())
        {
            return;
        }
        p1 = parent(parent(high));
        p2 = parent(low);
    }
}

/// Point every vertex of `vs` at its root. No link runs at the same time, so the roots
/// stay put and each vertex is written by its own share only (and only when it moves).
/// With `ahead` > 0 the grandparent of vertex v + `ahead` is asked for first.
fn compress(comp: &[AtomicU32], vs: Range<usize>, ahead: usize) {
    for v in vs {
        if ahead > 0
            && let Some(p) = comp.get(v + ahead)
        {
            fetch(comp, p.load(Relaxed) as usize);
        }
        let first = comp[v].load(Relaxed);
        let mut p = first;
        loop {
            let up = comp[p as usize].load(Relaxed);
            if up == p {
                break;
            }
            p = up;
        }
        if p != first {
            comp[v].store(p, Relaxed);
        }
    }
}

/// The root seen most often at [`SAMPLES`] vertices drawn by a fixed stream (the parents
/// are compressed, so a parent is a root); ties go to the least.
fn most_common_root(comp: &[AtomicU32], seen: &mut Vec<u32>) -> u32 {
    let n = comp.len() as u64;
    if n == 0 {
        return 0;
    }
    let mut state = 0x2545_F491_4F6C_DD1Du64;
    seen.clear();
    seen.extend((0..SAMPLES).map(|_| {
        // splitmix64
        state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = state;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^= z >> 31;
        let v = ((z as u128 * n as u128) >> 64) as usize;
        comp[v].load(Relaxed)
    }));
    seen.sort_unstable();
    let (mut best, mut best_run) = (seen[0], 0usize);
    for run in seen.chunk_by(|a, b| a == b) {
        if run.len() > best_run {
            (best, best_run) = (run[0], run.len());
        }
    }
    best
}

/// Run `f` over `0..n` in pieces of four grains of the device, handed out from a shared
/// counter to the device's threads (uneven rows balance); one piece runs on the caller.
fn each(device: &CpuDevice, n: usize, f: impl Fn(Range<usize>) + Sync) {
    let size = device.grain().saturating_mul(4).max(1);
    let pieces = n.div_ceil(size);
    if pieces <= 1 || device.threads() <= 1 {
        f(0..n);
        return;
    }
    let next = AtomicUsize::new(0);
    let mut seats = vec![(); device.threads().min(pieces)];
    device.each_block(&mut seats, |_, ()| {
        loop {
            let p = next.fetch_add(1, Relaxed);
            if p >= pieces {
                break;
            }
            f(p * size..((p + 1) * size).min(n));
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use kleene_sparse::BoolOrAnd;

    /// The least vertex of each vertex's weak component, by plain union-find.
    fn reference(n: usize, src: &[u32], dst: &[u32]) -> Vec<u32> {
        let mut up: Vec<u32> = (0..n as u32).collect();
        fn root(up: &mut [u32], mut x: u32) -> u32 {
            while up[x as usize] != x {
                up[x as usize] = up[up[x as usize] as usize];
                x = up[x as usize];
            }
            x
        }
        for (&a, &b) in src.iter().zip(dst) {
            let (ra, rb) = (root(&mut up, a), root(&mut up, b));
            let (lo, hi) = if ra < rb { (ra, rb) } else { (rb, ra) };
            up[hi as usize] = lo;
        }
        (0..n as u32).map(|v| root(&mut up, v)).collect()
    }

    #[test]
    fn the_link_and_compress_passes_ask_for_parents_ahead_and_name_the_same_components() {
        let n = 1usize << 12;
        let mut x = 0x2545_F491_4F6C_DD1Du64;
        let mut next = || {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            // skewed: low vertices more often
            let a = (x % n as u64) as u32;
            let b = ((x >> 20) % n as u64) as u32;
            a.min(b)
        };
        let (mut src, mut dst) = (Vec::new(), Vec::new());
        for _ in 0..n {
            src.push(next());
            dst.push(next());
        }
        let out = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
        let inn = out.transpose();
        let want = reference(n, &src, &dst);
        for device in [
            CpuDevice::new(1),
            CpuDevice::new(4).with_grain(64),
            CpuDevice::new(7).with_grain(16),
        ] {
            let before = FETCHES.load(Relaxed);
            let c = afforest(&out, &inn, &device).unwrap();
            let asked = FETCHES.load(Relaxed) - before;
            // at least the two compress passes after the neighbour rounds, every vertex
            // with one `FETCH_AHEAD` after it
            assert!(
                asked >= 2 * (n - FETCH_AHEAD),
                "{asked} fetches, {} threads",
                device.threads()
            );
            assert_eq!(c.of, want, "{} threads", device.threads());
        }
    }
}