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

//! The two LDBC Graphalytics kernels beside the GAP ones, on the CPU device's workers:
//! community detection by label propagation ([`cdlp`]) and the local clustering
//! coefficient ([`lcc`]), as the Graphalytics specification defines them for directed
//! graphs (and as `LAGraph_cdlp` and `LAGraph_lcc` compute them).
//!
//! - [`cdlp`]: every vertex starts with its own number as its label. Each round every vertex
//!   takes the label most frequent among its neighbours, the smallest of those when several
//!   are as frequent, all at once from the last round's labels. A neighbour counts once for
//!   an out-edge and once for an in-edge (twice when the edge goes both ways); a self-loop
//!   counts for nothing, and a vertex without neighbours keeps its label. It stops after the
//!   round limit, or after a round that changed no label (later rounds would not either).
//! - [`lcc`]: a vertex's neighbours are those it has an edge to or from (itself left out);
//!   with `d` of them, its coefficient is the number of edges between two of its neighbours
//!   (an edge each way counts twice) over `d (d - 1)`, and 0 when `d < 2`. Each triangle of
//!   the undirected graph is found once, at its highest vertex after renumbering by falling
//!   degree when the degrees are skewed (as [`crate::triangles`] counts them), and gives each
//!   of its three vertices the edges between the other two.

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

use kleene_sparse::{CpuDevice, Csr};

use crate::GraphError;
use crate::centrality::{
    PIECE, Parts, each_piece, falling_degree, pieces_by_entries, skewed, square,
};

/// Community detection by label propagation: the labels and the rounds run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cdlp {
    /// Each vertex's label (the number of a vertex of its community).
    pub labels: Vec<u32>,
    /// Rounds run (the last one changed no label when it is below the limit).
    pub rounds: u32,
}

/// Both rows of every vertex: `out`'s offsets plus `inn`'s, so pieces cut on them hold
/// about equal work.
fn both_offsets(out: &Csr<u8>, inn: &Csr<u8>) -> Vec<u64> {
    let (a, b) = (out.pattern().offsets(), inn.pattern().offsets());
    a.iter().zip(b.iter()).map(|(x, y)| x + y).collect()
}

/// The smallest of the most frequent values of `labels` (sorted here).
fn min_mode(labels: &mut [u32]) -> u32 {
    labels.sort_unstable();
    let (mut best, mut best_n) = (labels[0], 0usize);
    let mut i = 0;
    while i < labels.len() {
        let x = labels[i];
        let mut j = i + 1;
        while j < labels.len() && labels[j] == x {
            j += 1;
        }
        // rising order: a later value wins only when more frequent
        if j - i > best_n {
            (best, best_n) = (x, j - i);
        }
        i = j;
    }
    best
}

/// Community detection by label propagation (Graphalytics' CDLP) over `out` and its
/// transpose `inn`, for at most `max_rounds` rounds. The neighbours of every vertex (both
/// rows, self-loops left out) are laid out once in one flat list, renumbered by falling
/// degree when the degrees are skewed so the labels read most sit together (the labels
/// themselves stay vertex numbers, so the answer is the same). Each round every worker
/// takes pieces of about equal edges from a shared counter and finds each vertex's label by
/// sorting its neighbours' labels; the answer does not depend on the number of workers.
pub fn cdlp(out: &Csr<u8>, inn: &Csr<u8>, max_rounds: u32, cpu: &CpuDevice) -> crate::Result<Cdlp> {
    let n = square(out)?;
    if square(inn)? != n {
        return Err(GraphError::NotSquare {
            rows: inn.nrows(),
            cols: n,
        });
    }
    let both = both_offsets(out, inn);
    let degree = |v: usize| (both[v + 1] - both[v]) as usize;
    let order = skewed(n, degree).then(|| falling_degree(n, degree));
    let old = |x: usize| order.as_ref().map_or(x, |(o, _)| o[x] as usize);
    let new = |v: u32| order.as_ref().map_or(v, |(_, w)| w[v as usize]);
    let both_cuts = pieces_by_entries(&both, PIECE);
    // (pieces cut on the old rows: about even enough for counting)
    let lens: Vec<u64> = each_piece(cpu, both_cuts.len() - 1, |p| {
        (both_cuts[p]..both_cuts[p + 1])
            .map(|x| {
                let v = old(x);
                let me = v as u32;
                let selfs = out.row(v).binary_search(&me).is_ok() as u64
                    + inn.row(v).binary_search(&me).is_ok() as u64;
                degree(v) as u64 - selfs
            })
            .collect::<Vec<u64>>()
    })
    .concat();
    let nb = Lists::build(&lens, cpu, |x, row| {
        let v = old(x);
        let mut k = 0;
        for &u in out.row(v).iter().chain(inn.row(v)) {
            if u as usize != v {
                row[k] = new(u);
                k += 1;
            }
        }
    });
    let cuts = pieces_by_entries(&nb.off, PIECE);
    // labels by position (new numbers), each the old number of a vertex
    let mut labels: [Vec<AtomicU32>; 2] = [
        (0..n).map(|x| AtomicU32::new(old(x) as u32)).collect(),
        (0..n).map(|_| AtomicU32::new(0)).collect(),
    ];
    let pieces = cuts.len() - 1;
    // each worker's buffer of a vertex's neighbour labels
    let mut bufs: Vec<Vec<u32>> = (0..cpu.threads().max(1)).map(|_| Vec::new()).collect();
    let mut rounds = 0;
    while rounds < max_rounds {
        let [now, next] = &labels;
        let changed = AtomicBool::new(false);
        let at = AtomicUsize::new(0);
        cpu.each_block(&mut bufs, |_, buf| {
            let mut moved = false;
            loop {
                let p = at.fetch_add(1, Relaxed);
                if p >= pieces {
                    break;
                }
                for x in cuts[p]..cuts[p + 1] {
                    let row = nb.row(x);
                    let was = now[x].load(Relaxed);
                    let is = match row {
                        [] => was,
                        [a] => now[*a as usize].load(Relaxed),
                        // a tie of two: the smaller
                        [a, b] => now[*a as usize]
                            .load(Relaxed)
                            .min(now[*b as usize].load(Relaxed)),
                        _ => {
                            buf.clear();
                            buf.extend(row.iter().map(|&w| now[w as usize].load(Relaxed)));
                            min_mode(buf)
                        }
                    };
                    moved |= is != was;
                    next[x].store(is, Relaxed);
                }
            }
            if moved {
                changed.store(true, Relaxed);
            }
        });
        labels.swap(0, 1);
        rounds += 1;
        if !changed.load(Relaxed) {
            break;
        }
    }
    let at = &labels[0];
    let labels = match &order {
        None => at.iter().map(|x| x.load(Relaxed)).collect(),
        Some((_, new_of)) => new_of
            .iter()
            .map(|&x| at[x as usize].load(Relaxed))
            .collect(),
    };
    Ok(Cdlp { labels, rounds })
}

/// A neighbour as the clustering lists keep it: its number shifted up one, and the low bit
/// set when the edge goes both ways.
fn entry(w: u32, both: bool) -> u32 {
    (w << 1) | u32::from(both)
}

/// `f(p, slice)` for each slice `p` of `piece` items of `items`, on the workers.
fn each_slice<T: Send>(
    items: &mut [T],
    piece: usize,
    cpu: &CpuDevice,
    f: impl Fn(usize, &mut [T]) + Sync,
) {
    let slots: Vec<Mutex<&mut [T]>> = items.chunks_mut(piece).map(Mutex::new).collect();
    each_piece(cpu, slots.len(), |p| {
        let mut mine = slots[p].lock().unwrap_or_else(|e| e.into_inner());
        f(p, &mut mine);
    });
}

/// Rows of entries ([`entry`]) laid out flat: the offsets and the entries.
struct Lists {
    off: Vec<u64>,
    adj: Vec<u32>,
}

impl Lists {
    fn row(&self, v: usize) -> &[u32] {
        &self.adj[self.off[v] as usize..self.off[v + 1] as usize]
    }

    /// Rows of the lengths `lens`, each filled by `fill(v, row)` on the workers (pieces
    /// cut on the lengths).
    fn build(lens: &[u64], cpu: &CpuDevice, fill: impl Fn(usize, &mut [u32]) + Sync) -> Lists {
        let n = lens.len();
        let piece = PIECE as usize;
        // the offsets on the workers: each piece's total, then each piece's run from its start
        let sums = each_piece(cpu, n.div_ceil(piece), |p| {
            lens[p * piece..((p + 1) * piece).min(n)]
                .iter()
                .sum::<u64>()
        });
        let mut starts = Vec::with_capacity(sums.len());
        let mut at = 0u64;
        for s in sums {
            starts.push(at);
            at += s;
        }
        let mut off = vec![0u64; n + 1];
        off[n] = at;
        each_slice(&mut off[..n], piece, cpu, |p, o| {
            let mut a = starts[p];
            for (k, x) in o.iter_mut().enumerate() {
                *x = a;
                a += lens[p * piece + k];
            }
        });
        let mut adj = vec![0u32; at as usize];
        let cuts = pieces_by_entries(&off, PIECE);
        // each piece's rows as one slice of its own
        let mut slots = Vec::with_capacity(cuts.len() - 1);
        let mut rest = adj.as_mut_slice();
        for p in 0..cuts.len() - 1 {
            let len = (off[cuts[p + 1]] - off[cuts[p]]) as usize;
            let (mine, more) = rest.split_at_mut(len);
            slots.push(Mutex::new(mine));
            rest = more;
        }
        each_piece(cpu, slots.len(), |p| {
            let mut mine = slots[p].lock().unwrap_or_else(|e| e.into_inner());
            let base = off[cuts[p]];
            for v in cuts[p]..cuts[p + 1] {
                let (lo, hi) = ((off[v] - base) as usize, (off[v + 1] - base) as usize);
                fill(v, &mut mine[lo..hi]);
            }
        });
        drop(slots);
        Lists { off, adj }
    }
}

/// The neighbours of `v` below `below` (to or from it, itself left out) in rising order:
/// `put(w, both)` for each, `both` when the edge goes both ways. The merge stops at the
/// first neighbour not below `below`.
#[inline]
fn merge_rows(out: &Csr<u8>, inn: &Csr<u8>, v: usize, below: u32, mut put: impl FnMut(u32, bool)) {
    let (a, b) = (out.row(v), inn.row(v));
    let (mut i, mut j) = (0, 0);
    loop {
        let (x, both) = match (a.get(i), b.get(j)) {
            (Some(&x), Some(&y)) if x == y => {
                i += 1;
                j += 1;
                (x, true)
            }
            (Some(&x), Some(&y)) if x < y => {
                i += 1;
                (x, false)
            }
            (Some(_), Some(&y)) => {
                j += 1;
                (y, false)
            }
            (Some(&x), None) => {
                i += 1;
                (x, false)
            }
            (None, Some(&y)) => {
                j += 1;
                (y, false)
            }
            (None, None) => return,
        };
        if x >= below {
            return;
        }
        if x as usize != v {
            put(x, both);
        }
    }
}

/// Each vertex's neighbours to or from it, itself left out, sorted, as entries; `lens`
/// holds their numbers.
fn neighbours(out: &Csr<u8>, inn: &Csr<u8>, lens: &[u64], cpu: &CpuDevice) -> Lists {
    Lists::build(lens, cpu, |v, row| {
        let mut k = 0;
        merge_rows(out, inn, v, u32::MAX, |x, both| {
            row[k] = entry(x, both);
            k += 1;
        });
    })
}

/// The most vertices [`lcc`] takes: its lists keep a neighbour's number in 31 bits.
pub const LCC_MAX: usize = 1 << 31;

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

/// Vertices whose counts a worker keeps in its own array (the highest degrees after
/// renumbering); the others are added to shared counters.
const LCC_OWN: usize = 1 << 17;

/// The local clustering coefficient of every vertex (Graphalytics' LCC) of `out` and its
/// transpose `inn`.
pub fn lcc(out: &Csr<u8>, inn: &Csr<u8>, cpu: &CpuDevice) -> crate::Result<Vec<f64>> {
    let n = square(out)?;
    if square(inn)? != n {
        return Err(GraphError::NotSquare {
            rows: inn.nrows(),
            cols: n,
        });
    }
    if n > LCC_MAX {
        return Err(GraphError::TooManyVertices {
            vertices: n,
            limit: LCC_MAX,
        });
    }
    // every vertex's degree and its neighbours below it, in one merge of its rows
    let piece = PIECE as usize;
    let mut deg = vec![0u64; n];
    let mut low = vec![0u64; n];
    {
        let slots: Vec<Mutex<(&mut [u64], &mut [u64])>> = deg
            .chunks_mut(piece)
            .zip(low.chunks_mut(piece))
            .map(Mutex::new)
            .collect();
        each_piece(cpu, slots.len(), |p| {
            let mut mine = slots[p].lock().unwrap_or_else(|e| e.into_inner());
            let (d, l) = &mut *mine;
            for k in 0..d.len() {
                let v = p * piece + k;
                let (mut dv, mut lv) = (0u64, 0u64);
                merge_rows(out, inn, v, u32::MAX, |x, _| {
                    dv += 1;
                    lv += u64::from((x as usize) < v);
                });
                (d[k], l[k]) = (dv, lv);
            }
        });
    }
    let degree = |v: usize| deg[v] as usize;
    // each vertex's neighbours below it, in the numbering the triangles are found in
    let (old_of, lower) = if skewed(n, degree) {
        let nb = neighbours(out, inn, &deg, cpu);
        let nb_cuts = pieces_by_entries(&nb.off, PIECE);
        let lens_of = |len: &(dyn Fn(usize) -> u64 + Sync)| -> Vec<u64> {
            each_piece(cpu, nb_cuts.len() - 1, |p| {
                (nb_cuts[p]..nb_cuts[p + 1]).map(len).collect::<Vec<u64>>()
            })
            .concat()
        };
        let (old_of, new_of) = falling_degree(n, degree);
        // (pieces cut on the old rows: about even enough for counting)
        let lens = lens_of(&|u| {
            nb.row(old_of[u] as usize)
                .iter()
                .filter(|&&e| (new_of[(e >> 1) as usize] as usize) < u)
                .count() as u64
        });
        let lower = Lists::build(&lens, cpu, |u, row| {
            let mut k = 0;
            for &e in nb.row(old_of[u] as usize) {
                let w = new_of[(e >> 1) as usize];
                if (w as usize) < u {
                    row[k] = entry(w, e & 1 == 1);
                    k += 1;
                }
            }
            row.sort_unstable();
        });
        (Some(old_of), lower)
    } else {
        // straight from the rows: the merge stops at the vertex itself
        let lower = Lists::build(&low, cpu, |u, row| {
            let mut k = 0;
            merge_rows(out, inn, u, u as u32, |x, both| {
                row[k] = entry(x, both);
                k += 1;
            });
        });
        (None, lower)
    };
    let own = LCC_OWN.min(n);
    let shared = Parts::new(n, cpu, |_| AtomicU64::new(0));
    let next = AtomicUsize::new(0);
    let words = n.div_ceil(64);
    struct Worker {
        seen: Vec<u64>,
        both: Vec<u64>,
        mine: Vec<u64>,
    }
    let mut workers: Vec<Worker> = (0..cpu.threads().max(1))
        .map(|_| Worker {
            seen: Vec::new(),
            both: Vec::new(),
            mine: Vec::new(),
        })
        .collect();
    cpu.each_block(&mut workers, |_, me| {
        let add = |x: u32, c: u64, me: &mut Vec<u64>| {
            if (x as usize) < own {
                me[x as usize] += c;
            } else {
                shared[x as usize].fetch_add(c, Relaxed);
            }
        };
        loop {
            let c = next.fetch_add(LCC_CHUNK, Relaxed);
            if c >= n {
                break;
            }
            for u in c..(c + LCC_CHUNK).min(n) {
                let lu = lower.row(u);
                if lu.len() < 2 {
                    continue;
                }
                if me.seen.is_empty() {
                    // made by the worker that uses them
                    me.seen.resize(words, 0);
                    me.both.resize(words, 0);
                    me.mine.resize(own, 0);
                }
                for &e in lu {
                    let w = (e >> 1) as usize;
                    me.seen[w >> 6] |= 1 << (w & 63);
                    me.both[w >> 6] |= u64::from(e & 1) << (w & 63);
                }
                let first = lu[0] >> 1;
                let mut at_u = 0u64;
                for &ev in &lu[1..] {
                    let v = ev >> 1;
                    let uv = 1 + u64::from(ev & 1);
                    let lv = lower.row(v as usize);
                    let from = lv.partition_point(|&e| (e >> 1) < first);
                    let mut at_v = 0u64;
                    for &ew in &lv[from..] {
                        let w = (ew >> 1) as usize;
                        if (me.seen[w >> 6] >> (w & 63)) & 1 == 1 {
                            // the triangle u > v > w
                            at_u += 1 + u64::from(ew & 1);
                            at_v += 1 + ((me.both[w >> 6] >> (w & 63)) & 1);
                            add(w as u32, uv, &mut me.mine);
                        }
                    }
                    if at_v > 0 {
                        add(v, at_v, &mut me.mine);
                    }
                }
                if at_u > 0 {
                    add(u as u32, at_u, &mut me.mine);
                }
                for &e in lu {
                    let w = (e >> 1) as usize;
                    me.seen[w >> 6] = 0;
                    me.both[w >> 6] = 0;
                }
            }
        }
    });
    // the coefficients in the numbering the triangles were found in
    let mut by_x = vec![0f64; n];
    each_slice(&mut by_x, piece, cpu, |p, c| {
        for (k, slot) in c.iter_mut().enumerate() {
            let x = p * piece + k;
            let mut t = shared[x].load(Relaxed);
            if x < own {
                t += workers
                    .iter()
                    .map(|w| w.mine.get(x).copied().unwrap_or(0))
                    .sum::<u64>();
            }
            if t > 0 {
                let d = degree(old_of.as_ref().map_or(x, |o| o[x] as usize)) as f64;
                *slot = t as f64 / (d * (d - 1.0));
            }
        }
    });
    Ok(match old_of {
        None => by_x,
        Some(old_of) => {
            let mut coef = vec![0f64; n];
            for (x, c) in by_x.into_iter().enumerate() {
                coef[old_of[x] as usize] = c;
            }
            coef
        }
    })
}