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/centrality.rs

//! The GAP kernels kleene had not run: PageRank, betweenness centrality and triangle
//! counting, on the CPU device's workers (gatling under kleene's engine).
//!
//! Each follows the GAP Benchmark Suite's reference kernel (Beamer, Asanović, Patterson,
//! "The GAP Benchmark Suite", 2015), which is also what LAGraph's GAP programs compute:
//!
//! - [`pagerank`]: pull-based, every vertex sums the shares of its in-neighbours each round;
//!   damping 0.85, stop when the L1 change of a round is below the tolerance (1e-4) or at the
//!   round limit; a vertex without out-edges gives nothing away (GAP's and
//!   `LAGr_PageRankGAP`'s rule). Scores in `f32`, the change summed in `f64`, as GAP. On
//!   skewed degrees the shares are kept by falling out-degree, so the ones read most share
//!   cache lines.
//! - [`betweenness`]: Brandes from a few sources (GAP samples them), level by level: a
//!   forward search that counts shortest paths, then the dependencies back from the deepest
//!   level (each vertex pulls from its children). Up to four sources are searched together
//!   (as `LAGr_Betweenness` batches them), small levels pushed and large ones pulled
//!   (Beamer's rule). Scores are the plain sum over the sources (`LAGr_Betweenness`'s), in
//!   `f64`.
//! - [`triangles`]: on the undirected graph without self-loops ([`undirected`]), every
//!   vertex keeps its neighbours of a lower number, and a triangle is counted once at its
//!   highest vertex: each worker marks a vertex's lower neighbours in its own bit set and
//!   counts the marked ones in each of their lists. The vertices are first renumbered by
//!   falling degree when the degrees are skewed (GAP's `WorthRelabelling` test), so that hub
//!   lists stay short.
//!
//! Every vertex's sum runs over its row in the row's order (a path count is a whole number,
//! exact in any order), so the answers do not depend on the number of workers.

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

use kleene_sparse::{CpuDevice, Csr};

use crate::{GraphBackend, GraphError};

/// PageRank's settings.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PageRankOptions {
    /// The damping factor.
    pub damping: f32,
    /// Stop when a round changes the scores by less than this (L1).
    pub tolerance: f64,
    /// The most rounds.
    pub max_rounds: u32,
}

impl Default for PageRankOptions {
    /// GAP's: damping 0.85, tolerance 1e-4; at most 100 rounds (LAGraph's GAP program).
    fn default() -> Self {
        PageRankOptions {
            damping: 0.85,
            tolerance: 1e-4,
            max_rounds: 100,
        }
    }
}

/// PageRank's answer.
#[derive(Clone, Debug, PartialEq)]
pub struct PageRank {
    /// The score of each vertex.
    pub scores: Vec<f32>,
    /// Rounds run.
    pub rounds: u32,
    /// The L1 change of the last round.
    pub change: f64,
}

pub(crate) fn square(a: &Csr<u8>) -> crate::Result<usize> {
    if a.nrows() != a.ncols() {
        return Err(GraphError::NotSquare {
            rows: a.nrows(),
            cols: a.ncols(),
        });
    }
    Ok(a.nrows())
}

/// Rows of `off` cut in pieces of about `per` entries (a row counted as one entry more):
/// the starts, ending with the row count. Fixed by the matrix alone, not by the threads.
pub(crate) fn pieces_by_entries(off: &[u64], per: u64) -> Vec<usize> {
    let n = off.len() - 1;
    let mut cuts = vec![0usize];
    let mut at = 0usize;
    while at < n {
        // the first row whose start passes this piece's budget
        let goal = off[at] + at as u64 + per;
        let (mut lo, mut hi) = (at + 1, n);
        while lo < hi {
            let mid = (lo + hi) / 2;
            if off[mid] + mid as u64 >= goal {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        at = lo;
        cuts.push(at);
    }
    cuts
}

/// `f(p)` for every piece `p` in `0..pieces`, the pieces handed to the workers from a
/// shared counter; the results in piece order.
pub(crate) fn each_piece<R: Send>(
    cpu: &CpuDevice,
    pieces: usize,
    f: impl Fn(usize) -> R + Sync,
) -> Vec<R> {
    let next = AtomicUsize::new(0);
    let mut bufs: Vec<Vec<(usize, R)>> = (0..cpu.threads().min(pieces).max(1))
        .map(|_| Vec::new())
        .collect();
    cpu.each_block(&mut bufs, |_, mine| {
        loop {
            let p = next.fetch_add(1, Relaxed);
            if p >= pieces {
                break;
            }
            mine.push((p, f(p)));
        }
    });
    let mut all: Vec<(usize, R)> = bufs.into_iter().flatten().collect();
    all.sort_unstable_by_key(|x| x.0);
    all.into_iter().map(|x| x.1).collect()
}

/// Items per part of a [`Parts`].
const PART: usize = 1 << 16;

/// A long array kept in parts of [`PART`] items, each made and first touched by a worker,
/// so a kernel's state is set up on every thread instead of one.
pub(crate) struct Parts<T> {
    parts: Vec<Vec<T>>,
}

impl<T: Send> Parts<T> {
    /// `n` items, item `i` made by `make(i)`.
    pub(crate) fn new(n: usize, cpu: &CpuDevice, make: impl Fn(usize) -> T + Sync) -> Self {
        let parts = each_piece(cpu, n.div_ceil(PART), |p| {
            (p * PART..((p + 1) * PART).min(n)).map(&make).collect()
        });
        Parts { parts }
    }

    /// Every item, in order.
    pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
        self.parts.iter().flatten()
    }
}

impl<T> std::ops::Index<usize> for Parts<T> {
    type Output = T;

    fn index(&self, i: usize) -> &T {
        &self.parts[i / PART][i % PART]
    }
}

/// Entries (edges and rows) per piece of a pass over all rows (PageRank, a pulled level).
pub(crate) const PIECE: u64 = 1 << 16;

/// PageRank over `out` (its transpose `inn` gives each vertex its in-neighbours).
///
/// One pass a round: each vertex sums the shares of its in-neighbours (in its row's order),
/// keeps its new score and writes its share for the next round into a second array, so the
/// shares are not made in a pass of their own. The rows are cut in pieces of about equal
/// work (edges and rows), fixed by the graph, so the answer and the change do not depend on
/// the number of workers.
pub fn pagerank(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    opts: &PageRankOptions,
    cpu: &CpuDevice,
) -> crate::Result<PageRank> {
    let n = square(out)?;
    if square(inn)? != n {
        return Err(GraphError::NotSquare {
            rows: inn.nrows(),
            cols: n,
        });
    }
    if n == 0 {
        return Ok(PageRank {
            scores: Vec::new(),
            rounds: 0,
            change: 0.0,
        });
    }
    let init = 1.0f32 / n as f32;
    let base = (1.0f32 - opts.damping) / n as f32;
    let off = inn.pattern().offsets();
    let cuts = pieces_by_entries(off, PIECE);
    let pieces = cuts.len() - 1;
    let outoff = out.pattern().offsets();
    // a vertex's share of its score: score / out-degree, nothing without out-edges
    let share_of = |v: usize, s: f32| {
        let d = outoff[v + 1] - outoff[v];
        if d == 0 { 0.0 } else { s / d as f32 }
    };
    let adj = inn.pattern().indices();
    // On skewed degrees the shares are kept by falling out-degree: the shares read most
    // (of the vertices with the most out-edges) then share cache lines. Each piece's
    // in-neighbours are renumbered once for that; the rows keep their order.
    let place: Option<Vec<u32>> =
        skewed(n, |v| out.row(v).len()).then(|| falling_places(cpu, n, |v| out.row(v).len()));
    let at = |v: usize| place.as_ref().map_or(v, |p| p[v] as usize);
    let renumbered: Vec<Vec<u32>> = match &place {
        Some(p) => each_piece(cpu, pieces, |q| {
            adj[off[cuts[q]] as usize..off[cuts[q + 1]] as usize]
                .iter()
                .map(|&u| p[u as usize])
                .collect()
        }),
        None => Vec::new(),
    };
    let scores: Vec<AtomicU32> = (0..n).map(|_| AtomicU32::new(init.to_bits())).collect();
    let mut shares: [Vec<AtomicU32>; 2] = [
        (0..n).map(|_| AtomicU32::new(0)).collect(),
        (0..n).map(|_| AtomicU32::new(0)).collect(),
    ];
    let first = |vs: std::ops::Range<usize>| {
        vs.for_each(|v| shares[0][at(v)].store(share_of(v, init).to_bits(), Relaxed));
    };
    if n < PLACE_CAP {
        first(0..n);
    } else {
        cpu.split(n, first);
    }
    let (mut rounds, mut change) = (0u32, f64::INFINITY);
    while rounds < opts.max_rounds {
        let [now, next] = &shares;
        let parts = each_piece(cpu, pieces, |p| {
            let mut err = 0.0f64;
            let first = off[cuts[p]] as usize;
            let ins: &[u32] = match renumbered.get(p) {
                Some(r) => r,
                None => &adj[first..off[cuts[p + 1]] as usize],
            };
            for v in cuts[p]..cuts[p + 1] {
                let mut sum = 0.0f32;
                for &u in &ins[off[v] as usize - first..off[v + 1] as usize - first] {
                    sum += f32::from_bits(now[u as usize].load(Relaxed));
                }
                let new = base + opts.damping * sum;
                let old = f32::from_bits(scores[v].load(Relaxed));
                err += f64::from((new - old).abs());
                scores[v].store(new.to_bits(), Relaxed);
                next[at(v)].store(share_of(v, new).to_bits(), Relaxed);
            }
            err
        });
        shares.swap(0, 1);
        rounds += 1;
        change = parts.iter().sum();
        if change < opts.tolerance {
            break;
        }
    }
    Ok(PageRank {
        scores: scores
            .iter()
            .map(|x| f32::from_bits(x.load(Relaxed)))
            .collect(),
        rounds,
        change,
    })
}

/// [`pagerank`] on backend `B`: its [`GraphBackend::pagerank_of`] (the CPU backend's is
/// [`pagerank`] itself; the GPU backend keeps the rounds on the GPU).
pub fn pagerank_of<B: GraphBackend>(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    opts: &PageRankOptions,
    device: &B::Device,
) -> crate::Result<PageRank> {
    B::pagerank_of(out, inn, opts, device)
}

/// Sources betweenness searches together: one pass over a vertex's edges serves them all.
const BC_BATCH: usize = 4;

/// A vertex's path counts for each source of a batch, two vertices to a cache line; once
/// the vertex's dependency is known (and added to its score), (1 + δ) / σ in their place.
#[repr(align(32))]
struct Paths {
    sigma: [AtomicU64; BC_BATCH],
}

/// Betweenness pulls a level only when its frontier holds more than one in this many
/// vertices (Beamer's beta, GAP's 18 rounded up).
const BC_BETA: usize = 24;

/// Below this many vertices and edges a level runs on the calling thread.
const LEVEL_ALONE: usize = 1 << 14;

/// `f` over pieces of `list` (vertices whose rows in `off` are the work), the results in
/// piece order. A small list (few vertices and few edges) runs on the calling thread; a
/// larger one is cut in pieces small enough that a few hubs spread over the workers.
pub(crate) fn each_of_level<R: Send>(
    cpu: &CpuDevice,
    list: &[u32],
    off: &[u64],
    f: impl Fn(&[u32]) -> R + Sync,
) -> Vec<R> {
    let small = list.len() < LEVEL_ALONE
        && list
            .iter()
            .map(|&v| (off[v as usize + 1] - off[v as usize]) as usize)
            .sum::<usize>()
            < LEVEL_ALONE;
    if small || cpu.threads() == 1 {
        return vec![f(list)];
    }
    let per = (list.len() / (cpu.threads() * 32)).clamp(8, 1024);
    let pieces = list.len().div_ceil(per);
    each_piece(cpu, pieces, |p| {
        f(&list[p * per..((p + 1) * per).min(list.len())])
    })
}

/// A search from a batch's sources deeper than this many levels stops, and its sources
/// are searched one at a time: on a deep graph the sources' levels do not line up, and a
/// shared level list would walk every row once per source anyway, at a higher cost.
const BC_DEEP: u32 = 64;

const NONE: u32 = u32::MAX;

/// No source of a batch has reached the vertex (every byte of its depths [`packed`]).
const UNSEEN: u32 = u32::MAX;

/// A vertex's depths for the sources of a batch packed in one word, a byte a source
/// (`0xFF`: not reached), so the depths of a whole graph take four bytes a vertex. A batch
/// never passes [`BC_DEEP`] levels, so every depth fits.
mod packed {
    use super::{BC_BATCH, BC_DEEP, NONE};

    const _: () = assert!(BC_DEEP < 0xFF && BC_BATCH <= 4);

    /// Source `s`'s depth in `word` ([`NONE`] when not reached).
    pub(super) fn lane(word: u32, s: usize) -> u32 {
        match (word >> (8 * s)) & 0xFF {
            0xFF => NONE,
            b => b,
        }
    }

    /// Every source's depth in `word`.
    pub(super) fn unpack(word: u32) -> [u32; BC_BATCH] {
        std::array::from_fn(|s| lane(word, s))
    }

    /// `word` with source `s` at depth `d`.
    pub(super) fn set(word: u32, s: usize, d: u32) -> u32 {
        (word & !(0xFF << (8 * s))) | (d << (8 * s))
    }
}

/// 2^53: whole numbers below it add exactly in `f64`, in any order.
const EXACT: f64 = 9007199254740992.0;

/// `a += x` on an `f64` kept as bits.
fn add_f64(a: &AtomicU64, x: f64) {
    let mut now = a.load(Relaxed);
    loop {
        let new = (f64::from_bits(now) + x).to_bits();
        match a.compare_exchange_weak(now, new, Relaxed, Relaxed) {
            Ok(_) => return,
            Err(seen) => now = seen,
        }
    }
}

/// `f`'s new value stored in `a` unless `f` refuses (`None`): the value before, `Ok` when
/// stored, `Err` when refused (as `fetch_update`, which toolchains from 1.99 call
/// `try_update`; written out so every toolchain from the crate's 1.95 builds it alike).
fn update_u32(a: &AtomicU32, f: impl Fn(u32) -> Option<u32>) -> Result<u32, u32> {
    let mut now = a.load(Relaxed);
    loop {
        let Some(new) = f(now) else {
            return Err(now);
        };
        match a.compare_exchange_weak(now, new, Relaxed, Relaxed) {
            Ok(_) => return Ok(now),
            Err(seen) => now = seen,
        }
    }
}

fn f64_of(a: &AtomicU64) -> f64 {
    f64::from_bits(a.load(Relaxed))
}

/// Every vertex of `list` marked in `bits` (`on`), or its word of `bits` cleared.
fn mark(bits: &[AtomicU64], list: &[u32], on: bool, cpu: &CpuDevice) {
    cpu.split(list.len(), |r| {
        for &v in &list[r] {
            let w = &bits[v as usize / 64];
            if on {
                w.fetch_or(1 << (v % 64), Relaxed);
            } else {
                w.store(0, Relaxed);
            }
        }
    });
}

/// `v` is marked in `bits`.
fn marked(bits: &[AtomicU64], v: usize) -> bool {
    (bits[v / 64].load(Relaxed) >> (v % 64)) & 1 == 1
}

/// The sum of the row lengths in `off` of the vertices in `list`.
fn degree(off: &[u64], list: &[u32]) -> u64 {
    list.iter()
        .map(|&v| off[v as usize + 1] - off[v as usize])
        .sum()
}

/// The state of a batched search (see [`betweenness`]).
struct Batched {
    /// Each source's depth, a byte each ([`packed`]): a plain array, read once an edge.
    depth: Vec<AtomicU32>,
    /// The last level that listed the vertex.
    stamp: Parts<AtomicU32>,
    paths: Parts<Paths>,
    /// A bit a vertex: the vertices of one level (a pulled level's frontier, or the
    /// children's level of the backward pass), so most edges skip the depth they lead to.
    level: Vec<AtomicU64>,
    /// Every level's vertices, in the order the search found them, and where each starts.
    order: Vec<u32>,
    starts: Vec<usize>,
    /// A batch has run on this state (its path counts are not zero).
    used: bool,
}

impl Batched {
    fn new(n: usize, cpu: &CpuDevice) -> Self {
        Batched {
            depth: (0..n).map(|_| AtomicU32::new(UNSEEN)).collect(),
            stamp: Parts::new(n, cpu, |_| AtomicU32::new(NONE)),
            paths: Parts::new(n, cpu, |_| Paths {
                sigma: std::array::from_fn(|_| AtomicU64::new(0)),
            }),
            level: (0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect(),
            order: Vec::with_capacity(n),
            starts: Vec::new(),
            used: false,
        }
    }

    /// Brandes from the sources of `batch` together, their dependencies added to
    /// `scores`; false (and `scores` untouched) when the search passes [`BC_DEEP`] levels.
    fn run(
        &mut self,
        out: &Csr<u8>,
        inn: &Csr<u8>,
        in_cuts: &[usize],
        batch: &[u32],
        cpu: &CpuDevice,
        scores: &Parts<AtomicU64>,
    ) -> bool {
        let n = out.nrows();
        let lanes = batch.len();
        let Batched {
            depth,
            stamp,
            paths,
            level,
            order,
            starts,
            used,
        } = self;
        let f = f64_of;
        let depths = |v: usize| packed::unpack(depth[v].load(Relaxed));
        let (oo, io) = (out.pattern().offsets(), inn.pattern().offsets());
        // pushed path counts add up from zero (they start at zero in a new state)
        let zero = std::mem::replace(used, true);
        cpu.split(n, |r| {
            for v in r {
                depth[v].store(UNSEEN, Relaxed);
                if zero {
                    for s in 0..BC_BATCH {
                        paths[v].sigma[s].store(0, Relaxed);
                    }
                }
                stamp[v].store(NONE, Relaxed);
            }
        });
        order.clear();
        starts.clear();
        starts.push(0);
        for (s, &src) in batch.iter().enumerate() {
            let v = src as usize;
            let w = depth[v].load(Relaxed);
            depth[v].store(packed::set(w, s, 0), Relaxed);
            paths[v].sigma[s].store(1f64.to_bits(), Relaxed);
            if stamp[v].swap(0, Relaxed) != 0 {
                order.push(src);
            }
        }
        starts.push(order.len());
        // the frontier's out-edges, and the in-edges of every vertex listed so far
        // (counted once a listing, so a vertex listed for several sources at several
        // levels is counted for each)
        let mut front_out = degree(oo, order);
        let mut seen_in = degree(io, order);
        let mut d = 0u32;
        loop {
            if d >= BC_DEEP {
                return false;
            }
            let (lo, hi) = (starts[starts.len() - 2], starts[starts.len() - 1]);
            let before = order.len();
            // Beamer's rule: pull when the frontier's edges outweigh the in-edges left
            // (a vertex's listings shared between the sources) and the frontier is a
            // large part of the graph.
            let left = (inn.nnz() as u64).saturating_sub(seen_in / lanes as u64);
            if front_out > left && (hi - lo) * BC_BETA > n {
                // Pull (bottom-up): every vertex some source has not reached sums the path
                // counts of its parents on this level; that also finds it.
                mark(level, &order[lo..hi], true, cpu);
                let found = each_piece(cpu, in_cuts.len() - 1, |p| {
                    let mut mine = Vec::new();
                    for w in in_cuts[p]..in_cuts[p + 1] {
                        let dw = depths(w);
                        if !dw[..lanes].contains(&NONE) {
                            continue;
                        }
                        let mut c = [0f64; BC_BATCH];
                        let mut hit = [false; BC_BATCH];
                        for &u in inn.row(w) {
                            if !marked(level, u as usize) {
                                continue;
                            }
                            let du = depths(u as usize);
                            for s in 0..lanes {
                                if dw[s] == NONE && du[s] == d {
                                    c[s] += f(&paths[u as usize].sigma[s]);
                                    hit[s] = true;
                                }
                            }
                        }
                        if hit.contains(&true) {
                            let x = &paths[w];
                            let mut word = depth[w].load(Relaxed);
                            for s in 0..lanes {
                                if hit[s] {
                                    word = packed::set(word, s, d + 1);
                                    x.sigma[s].store(c[s].to_bits(), Relaxed);
                                }
                            }
                            depth[w].store(word, Relaxed);
                            stamp[w].store(d + 1, Relaxed);
                            mine.push(w as u32);
                        }
                    }
                    mine
                });
                mark(level, &order[lo..hi], false, cpu);
                for part in found {
                    order.extend(part);
                }
                if order.len() == before {
                    break;
                }
                d += 1;
                starts.push(order.len());
            } else {
                // Push: each newly reached (vertex, source) is claimed by one parent, and
                // every parent adds its path count to the child's. The vertex is listed
                // once for the level.
                let found: Vec<Vec<u32>> = each_of_level(cpu, &order[lo..hi], oo, |part| {
                    let mut mine = Vec::new();
                    for &u in part {
                        let du = depths(u as usize);
                        let su: [f64; BC_BATCH] = std::array::from_fn(|s| {
                            if du[s] == d {
                                f(&paths[u as usize].sigma[s])
                            } else {
                                0.0
                            }
                        });
                        for &w in out.row(u as usize) {
                            let x = &depth[w as usize];
                            let seen = x.load(Relaxed);
                            let mut claimed = false;
                            for s in 0..lanes {
                                if du[s] != d {
                                    continue;
                                }
                                let mut dw = packed::lane(seen, s);
                                if dw == NONE {
                                    dw = match update_u32(x, |now| {
                                        (packed::lane(now, s) == NONE)
                                            .then(|| packed::set(now, s, d + 1))
                                    }) {
                                        Ok(_) => {
                                            claimed = true;
                                            d + 1
                                        }
                                        Err(now) => packed::lane(now, s),
                                    };
                                }
                                if dw == d + 1 {
                                    add_f64(&paths[w as usize].sigma[s], su[s]);
                                }
                            }
                            if claimed && stamp[w as usize].swap(d + 1, Relaxed) != d + 1 {
                                mine.push(w);
                            }
                        }
                    }
                    mine
                });
                for part in found {
                    order.extend(part);
                }
                if order.len() == before {
                    break;
                }
                d += 1;
                starts.push(order.len());
                // The counts are whole numbers: below 2^53 every sum is exact in any
                // order, so the pushed counts are the pulled ones. Above it (not seen on
                // the suite's graphs) the level is pulled again in row order.
                let big = each_of_level(cpu, &order[before..], io, |part| {
                    let mut big = false;
                    for &w in part {
                        let dw = depths(w as usize);
                        let x = &paths[w as usize];
                        for (s, _) in dw[..lanes].iter().enumerate().filter(|l| *l.1 == d) {
                            big |= f(&x.sigma[s]) >= EXACT;
                        }
                    }
                    big
                });
                if big.contains(&true) {
                    each_of_level(cpu, &order[before..], io, |part| {
                        for &w in part {
                            let dw = depths(w as usize);
                            let mut c = [0f64; BC_BATCH];
                            for &u in inn.row(w as usize) {
                                let du = depths(u as usize);
                                for s in 0..lanes {
                                    if dw[s] == d && du[s] == d - 1 {
                                        c[s] += f(&paths[u as usize].sigma[s]);
                                    }
                                }
                            }
                            let x = &paths[w as usize];
                            for s in 0..lanes {
                                if dw[s] == d {
                                    x.sigma[s].store(c[s].to_bits(), Relaxed);
                                }
                            }
                        }
                    });
                }
            }
            let level = &order[before..];
            front_out = degree(oo, level);
            seen_in += degree(io, level);
        }
        // Back from the deepest level: a vertex pulls what its children give, (1 + δ) / σ
        // each (GAP's form); once its own dependency is known it adds it to its score
        // (source by source; a source gets none of its own) and keeps what it gives its
        // parents in place of its path count, which nothing reads any more.
        for k in (0..starts.len() - 1).rev() {
            let dk = k as u32;
            // level k + 1, none below the deepest
            let children: &[u32] = match starts.get(k + 2) {
                Some(&end) => &order[starts[k + 1]..end],
                None => &[],
            };
            mark(level, children, true, cpu);
            each_of_level(cpu, &order[starts[k]..starts[k + 1]], oo, |part| {
                for &v in part {
                    let dv = depths(v as usize);
                    let x = &paths[v as usize];
                    let mut acc = [0f64; BC_BATCH];
                    for &w in out.row(v as usize) {
                        if !marked(level, w as usize) {
                            continue;
                        }
                        let dw = depths(w as usize);
                        let y = &paths[w as usize];
                        for s in 0..BC_BATCH {
                            if dv[s] == dk && dw[s] == dk + 1 {
                                acc[s] += f(&y.sigma[s]);
                            }
                        }
                    }
                    let mut score = f(&scores[v as usize]);
                    for s in 0..lanes {
                        if dv[s] == dk {
                            let sigma = f(&x.sigma[s]);
                            let delta = sigma * acc[s];
                            x.sigma[s].store(((1.0 + delta) / sigma).to_bits(), Relaxed);
                            if batch[s] != v {
                                score += delta;
                            }
                        }
                    }
                    scores[v as usize].store(score.to_bits(), Relaxed);
                }
            });
            mark(level, children, false, cpu);
        }
        true
    }
}

/// The state of a search from one source (see [`betweenness`]).
struct One {
    depth: Vec<AtomicU32>,
    sigma: Vec<AtomicU64>,
    delta: Vec<AtomicU64>,
    order: Vec<u32>,
    starts: Vec<usize>,
}

impl One {
    fn new(n: usize) -> Self {
        One {
            depth: (0..n).map(|_| AtomicU32::new(NONE)).collect(),
            sigma: (0..n).map(|_| AtomicU64::new(0)).collect(),
            delta: (0..n).map(|_| AtomicU64::new(0)).collect(),
            order: Vec::with_capacity(n),
            starts: Vec::new(),
        }
    }

    /// Brandes from `src`, its dependencies added to `scores`.
    fn run(
        &mut self,
        out: &Csr<u8>,
        inn: &Csr<u8>,
        src: u32,
        cpu: &CpuDevice,
        scores: &Parts<AtomicU64>,
    ) {
        let n = out.nrows();
        let One {
            depth,
            sigma,
            delta,
            order,
            starts,
        } = self;
        let f = f64_of;
        let (oo, io) = (out.pattern().offsets(), inn.pattern().offsets());
        cpu.split(n, |r| {
            for v in r {
                depth[v].store(NONE, Relaxed);
            }
        });
        order.clear();
        starts.clear();
        order.push(src);
        starts.extend([0, 1]);
        depth[src as usize].store(0, Relaxed);
        sigma[src as usize].store(1f64.to_bits(), Relaxed);
        delta[src as usize].store(0, Relaxed);
        let mut d = 0u32;
        loop {
            let (lo, hi) = (starts[starts.len() - 2], starts[starts.len() - 1]);
            // Push: each newly reached vertex is claimed by one parent.
            let found: Vec<Vec<u32>> = each_of_level(cpu, &order[lo..hi], oo, |part| {
                let mut mine = Vec::new();
                for &u in part {
                    for &w in out.row(u as usize) {
                        let x = &depth[w as usize];
                        if x.load(Relaxed) == NONE
                            && x.compare_exchange(NONE, d + 1, Relaxed, Relaxed).is_ok()
                        {
                            mine.push(w);
                        }
                    }
                }
                mine
            });
            let before = order.len();
            for part in found {
                order.extend(part);
            }
            if order.len() == before {
                break;
            }
            d += 1;
            starts.push(order.len());
            // Pull: a vertex's path count is the sum of its parents' counts.
            each_of_level(cpu, &order[before..], io, |part| {
                for &w in part {
                    let mut c = 0f64;
                    for &u in inn.row(w as usize) {
                        if depth[u as usize].load(Relaxed) == d - 1 {
                            c += f(&sigma[u as usize]);
                        }
                    }
                    sigma[w as usize].store(c.to_bits(), Relaxed);
                    delta[w as usize].store(0, Relaxed);
                }
            });
        }
        // Back from the deepest level: a vertex pulls the dependencies of its children.
        for k in (0..starts.len() - 2).rev() {
            let dk = k as u32;
            each_of_level(cpu, &order[starts[k]..starts[k + 1]], oo, |part| {
                for &v in part {
                    let sv = f(&sigma[v as usize]);
                    let mut acc = 0f64;
                    for &w in out.row(v as usize) {
                        if depth[w as usize].load(Relaxed) == dk + 1 {
                            acc += sv / f(&sigma[w as usize]) * (1.0 + f(&delta[w as usize]));
                        }
                    }
                    delta[v as usize].store(acc.to_bits(), Relaxed);
                }
            });
        }
        let reached = &order[1..];
        each_of_level(cpu, reached, oo, |part| {
            for &v in part {
                let x = &scores[v as usize];
                x.store((f(x) + f(&delta[v as usize])).to_bits(), Relaxed);
            }
        });
    }
}

/// Betweenness centrality from `sources` (Brandes): for each vertex, the sum over the
/// sources of its dependency, the share of shortest paths from the source through it.
///
/// The sources are searched four at a time, level by level, all of a batch in the
/// same passes: a level's list holds each vertex once whichever sources reached it there,
/// and one walk over a vertex's row serves every source of the batch. A vertex's depths
/// for the batch take one word, its path counts and dependencies one cache line. A small
/// level is pushed: each parent adds its path count to its children's. A level whose
/// frontier is a large part of the graph is pulled instead (every vertex not yet reached
/// sums its parents' counts, which also finds it; Beamer's rule). On a graph deeper than
/// 64 levels the sources are searched one at a time instead.
///
/// Path counts are whole numbers, so below 2^53 they add exactly in any order (a level
/// whose counts pass it is pulled again in row order). The dependencies add in each
/// vertex's row order, and the scores add the sources' dependencies in the order given, so
/// the answer is the one source-at-a-time Brandes gives, bit for bit, at any number of
/// workers.
pub fn betweenness(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    sources: &[u32],
    cpu: &CpuDevice,
) -> crate::Result<Vec<f64>> {
    let n = square(out)?;
    if let Some(&s) = sources.iter().find(|&&s| s as usize >= n) {
        return Err(GraphError::SourceOutOfRange {
            source: s,
            vertices: n,
        });
    }
    if sources.is_empty() {
        return Ok(vec![0f64; n]);
    }
    let scores = Parts::new(n, cpu, |_| AtomicU64::new(0));
    let in_cuts = pieces_by_entries(inn.pattern().offsets(), PIECE);
    let (mut batched, mut one): (Option<Batched>, Option<One>) = (None, None);
    let mut deep = false;
    for batch in sources.chunks(BC_BATCH) {
        if batch.len() > 1 && !deep {
            let st = batched.get_or_insert_with(|| Batched::new(n, cpu));
            if st.run(out, inn, &in_cuts, batch, cpu, &scores) {
                continue;
            }
            // the graph is deep: its sources one at a time from here on
            deep = true;
            batched = None;
        }
        let st = one.get_or_insert_with(|| One::new(n));
        for &src in batch {
            st.run(out, inn, src, cpu, &scores);
        }
    }
    Ok(scores.iter().map(f64_of).collect())
}

/// The undirected graph of `out` (an edge either way, once), without self-loops, rows sorted.
pub fn undirected(out: &Csr<u8>, inn: &Csr<u8>) -> crate::Result<Csr<u8>> {
    let n = square(out)?;
    let mut off = Vec::with_capacity(n + 1);
    let mut adj = Vec::with_capacity(out.nnz() * 2);
    off.push(0u64);
    for v in 0..n {
        let (a, b) = (out.row(v), inn.row(v));
        let (mut i, mut j) = (0, 0);
        while i < a.len() || j < b.len() {
            let x = match (a.get(i), b.get(j)) {
                (Some(&x), Some(&y)) if x == y => {
                    i += 1;
                    j += 1;
                    x
                }
                (Some(&x), Some(&y)) if x < y => {
                    i += 1;
                    x
                }
                (Some(_), Some(&y)) => {
                    j += 1;
                    y
                }
                (Some(&x), None) => {
                    i += 1;
                    x
                }
                (None, Some(&y)) => {
                    j += 1;
                    y
                }
                (None, None) => unreachable!(),
            };
            if x as usize != v {
                adj.push(x);
            }
        }
        off.push(adj.len() as u64);
    }
    Ok(Csr::new(
        n,
        n,
        arrow_buffer::ScalarBuffer::from(off),
        arrow_buffer::ScalarBuffer::from(adj),
        None,
    )?)
}

/// When to renumber the vertices by falling degree before counting triangles.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Relabel {
    /// When the degrees are skewed: a sample's mean over 1.3 times its median (GAP's test,
    /// without its floor on the mean degree).
    #[default]
    Auto,
    /// Always.
    Always,
    /// Never.
    Never,
}

/// The triangle count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Triangles {
    /// Triangles, each counted once.
    pub count: u64,
    /// The vertices were renumbered by falling degree first.
    pub relabelled: bool,
}

/// GAP's sampling seed (its source picker's).
const SEED: u64 = 27491095;

/// The degrees are skewed: a sample's mean degree over 1.3 times its median (GAP's
/// `WorthRelabelling` test, without its floor on the mean), over the vertices with any.
pub(crate) fn skewed(n: usize, degree: impl Fn(usize) -> usize) -> bool {
    if !(0..n).any(|v| degree(v) > 0) {
        return false;
    }
    let samples = 1000.min(n);
    let mut x = SEED;
    let mut next = || {
        // splitmix64
        x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = x;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    };
    let mut deg = Vec::with_capacity(samples);
    while deg.len() < samples {
        let v = (next() % n as u64) as usize;
        let d = degree(v);
        if d > 0 {
            deg.push(d as u64);
        }
    }
    deg.sort_unstable();
    let mean = deg.iter().sum::<u64>() as f64 / samples as f64;
    mean / 1.3 > deg[samples / 2] as f64
}

/// The vertices by falling degree (ties by number): for each new place its vertex, and for
/// each vertex its new place; by counting the degrees.
pub(crate) fn falling_degree(n: usize, degree: impl Fn(usize) -> usize) -> (Vec<u32>, Vec<u32>) {
    let deg: Vec<usize> = (0..n).map(degree).collect();
    let top = deg.iter().copied().max().unwrap_or(0);
    let mut start = vec![0usize; top + 2];
    for &d in &deg {
        start[top - d + 1] += 1;
    }
    for i in 1..start.len() {
        start[i] += start[i - 1];
    }
    let mut old_of = vec![0u32; n];
    let mut new_of = vec![0u32; n];
    for v in 0..n {
        let slot = &mut start[top - deg[v]];
        old_of[*slot] = v as u32;
        new_of[v] = *slot as u32;
        *slot += 1;
    }
    (old_of, new_of)
}

/// Each vertex's place in an order by falling degree, equal degrees by number (the second
/// half of [`falling_degree`]), for PageRank's shares.
///
/// Counted on the workers: each piece of vertices counts its degrees, the counts give each
/// piece its first place per degree, and each piece places its own vertices. Degrees of
/// [`PLACE_CAP`] and more (few) are sorted apart and take the first places. Fewer vertices
/// than that are counted on the calling thread.
pub(crate) fn falling_places(
    cpu: &CpuDevice,
    n: usize,
    degree: impl Fn(usize) -> usize + Sync,
) -> Vec<u32> {
    if n < PLACE_CAP {
        return falling_degree(n, degree).1;
    }
    let pieces = cpu.threads().max(1);
    let per = n.div_ceil(pieces);
    // a vertex's count slot: 0 for the highest degree under the cap
    let slot = |d: usize| PLACE_CAP - 1 - d;
    let counted = each_piece(cpu, pieces, |p| {
        let mut counts = vec![0u32; PLACE_CAP];
        let mut high = Vec::new();
        for v in p * per..((p + 1) * per).min(n) {
            let d = degree(v);
            if d < PLACE_CAP {
                counts[slot(d)] += 1;
            } else {
                high.push((d, v as u32));
            }
        }
        (counts, high)
    });
    let mut high: Vec<(usize, u32)> = counted.iter().flat_map(|c| c.1.iter().copied()).collect();
    high.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
    let mut starts: Vec<Vec<u32>> = counted.into_iter().map(|c| c.0).collect();
    let mut at = high.len() as u32;
    for k in 0..PLACE_CAP {
        for s in &mut starts {
            let c = s[k];
            s[k] = at;
            at += c;
        }
    }
    let mut places = vec![0u32; n];
    for (i, &(_, v)) in high.iter().enumerate() {
        places[v as usize] = i as u32;
    }
    let mut parts: Vec<(usize, Vec<u32>, &mut [u32])> = starts
        .into_iter()
        .zip(places.chunks_mut(per))
        .enumerate()
        .map(|(p, (s, out))| (p * per, s, out))
        .collect();
    #[cfg(test)]
    if parts.len() > 1 && cpu.threads() > 1 {
        PLACED_ON_WORKERS.with(|c| c.set(c.get() + 1));
    }
    cpu.each_block(&mut parts, |_, (lo, starts, out)| {
        for (i, place) in out.iter_mut().enumerate() {
            let d = degree(*lo + i);
            if d < PLACE_CAP {
                *place = starts[slot(d)];
                starts[slot(d)] += 1;
            }
        }
    });
    drop(parts);
    places
}

/// Degrees counted one by one in [`falling_places`] (higher ones are sorted apart).
const PLACE_CAP: usize = 1 << 16;

#[cfg(test)]
thread_local! {
    /// Falling-degree orders whose places were counted on the workers (tests only).
    static PLACED_ON_WORKERS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Vertices a worker takes from the shared counter at a time when counting triangles.
const TC_CHUNK: usize = 64;

/// Every triangle once, at its highest vertex, given each vertex's lower neighbours
/// (sorted). For each `u` the worker marks the lower neighbours of `u` in its own bit set,
/// then every lower neighbour `v` of `u` counts the marked ones among its own lower
/// neighbours (all below `v`): `u`'s triangles at `v`. The work is one pass over each
/// `v`'s list per edge `u`-`v`, where a merge would also walk `u`'s list each time.
/// Workers take vertices in chunks from a shared counter, as uneven as the lists are.
fn count_lower<'a>(n: usize, lower: &(dyn Fn(usize) -> &'a [u32] + Sync), cpu: &CpuDevice) -> u64 {
    let words = n.div_ceil(64);
    let next = AtomicUsize::new(0);
    let mut bufs: Vec<(Vec<u64>, u64)> = (0..cpu.threads()).map(|_| (Vec::new(), 0)).collect();
    cpu.each_block(&mut bufs, |_, (marks, t)| {
        loop {
            let c = next.fetch_add(TC_CHUNK, Relaxed);
            if c >= n {
                break;
            }
            for u in c..(c + TC_CHUNK).min(n) {
                let lu = lower(u);
                if lu.len() < 2 {
                    continue;
                }
                if marks.is_empty() {
                    // made by the worker that uses it
                    marks.resize(words, 0);
                }
                for &w in lu {
                    marks[w as usize >> 6] |= 1 << (w & 63);
                }
                let first = lu[0];
                let mut found = 0u64;
                for &v in &lu[1..] {
                    let lv = lower(v as usize);
                    let from = lv.partition_point(|&w| w < first);
                    for &w in &lv[from..] {
                        found += (marks[w as usize >> 6] >> (w & 63)) & 1;
                    }
                }
                *t += found;
                for &w in lu {
                    marks[w as usize >> 6] = 0;
                }
            }
        }
    });
    bufs.iter().map(|b| b.1).sum()
}

/// The triangles of the undirected graph `und` (rows sorted, each edge both ways, no
/// self-loops: [`undirected`]). Each is counted once, at its highest vertex: for every
/// lower neighbour `v` of `u`, the lower neighbours `u` and `v` share.
pub fn triangles(und: &Csr<u8>, relabel: Relabel, cpu: &CpuDevice) -> crate::Result<Triangles> {
    let n = square(und)?;
    let relabelled = match relabel {
        Relabel::Always => true,
        Relabel::Never => false,
        Relabel::Auto => skewed(n, |v| und.row(v).len()),
    };
    if !relabelled {
        let lower = |u: usize| {
            let row = und.row(u);
            &row[..row.partition_point(|&w| (w as usize) < u)]
        };
        return Ok(Triangles {
            count: count_lower(n, &lower, cpu),
            relabelled,
        });
    }
    // New numbers by falling degree (ties by old number).
    let (old_of, new_of) = falling_degree(n, |v| und.row(v).len());
    // Each new vertex's lower neighbours, in new numbers, sorted.
    let rows: Vec<(usize, Vec<u32>, Vec<u64>)> = cpu.split(n, |r| {
        let mut adj = Vec::new();
        let mut off = Vec::with_capacity(r.len());
        let first = r.start;
        for u in r {
            let s = adj.len();
            adj.extend(
                und.row(old_of[u] as usize)
                    .iter()
                    .map(|&w| new_of[w as usize])
                    .filter(|&w| (w as usize) < u),
            );
            adj[s..].sort_unstable();
            off.push(adj.len() as u64);
        }
        (first, adj, off)
    });
    let mut off = Vec::with_capacity(n + 1);
    off.push(0u64);
    let mut adj = Vec::with_capacity(rows.iter().map(|r| r.1.len()).sum());
    for (_, a, o) in rows {
        let base = adj.len() as u64;
        adj.extend(a);
        off.extend(o.into_iter().map(|x| x + base));
    }
    let lower = |u: usize| &adj[off[u] as usize..off[u + 1] as usize];
    Ok(Triangles {
        count: count_lower(n, &lower, cpu),
        relabelled,
    })
}

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

    #[test]
    fn falling_degree_places_are_counted_on_the_workers_in_the_same_order() {
        // skewed degrees, many equal, a few above the counts' cap
        let n = 100_000;
        let degree = |v: usize| match v % 1000 {
            0 => (1 << 17) + v,
            k if k < 10 => 5000 + k,
            k => (k * 7919) % 97,
        };
        let want = falling_degree(n, degree).1;
        for threads in [1, 3, 8] {
            PLACED_ON_WORKERS.with(|c| c.set(0));
            let got = falling_places(&CpuDevice::new(threads), n, degree);
            assert_eq!(got, want, "{threads} threads");
            let workers = PLACED_ON_WORKERS.with(std::cell::Cell::get);
            assert_eq!(workers, usize::from(threads > 1), "{threads} threads");
        }
    }
}