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

//! Which backend runs a whole algorithm.

use std::collections::HashMap;

use kleene_sparse::{CpuBackend, CpuDevice, Csr, SparseBackend, Vector};

use crate::bfs::{BfsOptions, BfsState, BfsSummary, LevelInfo, Place, bfs_with_generic};
use crate::centrality::{PageRank, PageRankOptions};
use crate::components::{Components, components_of_generic, scc_of_generic};
use crate::graph::Graph;
use crate::labels::{EdgeSets, label_reach_generic};
use crate::paths::{Paths, SourceSets, SsspOptions, reach_sets_generic, sssp_of_generic};
use crate::split_compute::split_votes_cpu;

/// A sparse backend that runs this crate's algorithms. Each method defaults to the
/// algorithm written over [`SparseBackend`]'s operations, which runs on any backend; a
/// backend whose data lives elsewhere (a GPU) overrides one with a search of its own that
/// keeps every round there. An override must give the same answer as the default: the
/// same components named by their least vertex, the same distances and parents (the
/// lowest parent among equal paths), the same source sets. Its round counts may differ.
///
/// The free functions ([`crate::components_of`], [`crate::sssp_of`], ...) check their
/// input and then call these.
pub trait GraphBackend: SparseBackend {
    /// The CPU device behind `device`, for the kernels that run on the CPU only
    /// ([`crate::betweenness`], [`crate::triangles`]) and [`GraphBackend::pagerank_of`]'s
    /// default; `None` on other backends.
    fn cpu(device: &Self::Device) -> Option<&CpuDevice> {
        let _ = device;
        None
    }

    /// [`crate::components_of`].
    fn components_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        device: &Self::Device,
    ) -> crate::Result<Components> {
        components_of_generic::<Self>(out, inn, device)
    }

    /// [`crate::scc_of`].
    fn scc_of(out: &Csr<u8>, inn: &Csr<u8>, device: &Self::Device) -> crate::Result<Components> {
        scc_of_generic::<Self>(out, inn, device)
    }

    /// [`crate::pagerank_of`]. The default runs [`crate::pagerank`] on the backend's CPU
    /// device ([`GraphBackend::cpu`], else [`GraphBackend::host_device`], else one thread).
    /// An override (a GPU's) may sum in another order: its scores then differ from the
    /// CPU's by rounding, and it must say by how much it may.
    fn pagerank_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        opts: &PageRankOptions,
        device: &Self::Device,
    ) -> crate::Result<PageRank> {
        match Self::cpu(device).or_else(|| Self::host_device(device)) {
            Some(cpu) => crate::pagerank(out, inn, opts, cpu),
            None => crate::pagerank(out, inn, opts, &CpuDevice::new(1)),
        }
    }

    /// [`crate::sssp_of`] (its input already checked).
    fn sssp_of(
        weights: &Csr<u32>,
        transposed: Option<&Csr<u32>>,
        source: u32,
        opts: &SsspOptions,
        device: &Self::Device,
    ) -> crate::Result<Paths> {
        sssp_of_generic::<Self>(weights, transposed, source, opts, device)
    }

    /// [`crate::reach_sets`] (its input already checked).
    fn reach_sets(
        a: &Csr<u8>,
        sources: &[u32],
        device: &Self::Device,
    ) -> crate::Result<SourceSets> {
        reach_sets_generic::<Self>(a, sources, device)
    }

    /// [`crate::label_reach`] (its input already checked).
    fn label_reach(
        a: &Csr<u8>,
        sets: EdgeSets<'_>,
        seeds: &[(u32, u32)],
        sources: usize,
        device: &Self::Device,
    ) -> crate::Result<SourceSets> {
        label_reach_generic::<Self>(a, sets, seeds, sources, device)
    }

    /// [`crate::bfs_with`] (its input already checked, `st` sized for `g`).
    fn bfs_of(
        g: &Graph<Self>,
        sources: &[u32],
        opts: &BfsOptions,
        device: &Self::Device,
        st: &mut BfsState<Self>,
    ) -> crate::Result<BfsSummary>
    where
        Self: Sized,
    {
        bfs_with_generic::<Self>(g, sources, opts, device, st)
    }

    /// Before each level of [`bfs_with_generic`]: where the level runs. It must not read
    /// anything back from the device on its own. The default keeps every level here.
    fn bfs_place(info: &LevelInfo, device: &Self::Device) -> Place {
        let _ = (info, device);
        Place::Here
    }

    /// The host CSR a matrix keeps (no copy), for levels moved to the host; `None`: the
    /// search cannot move.
    fn host_pattern(m: &Self::Matrix<u8>) -> Option<&Csr<u8>> {
        let _ = m;
        None
    }

    /// The CPU device levels moved to the host run on; `None`: the search cannot move.
    fn host_device(device: &Self::Device) -> Option<&CpuDevice> {
        let _ = device;
        None
    }

    /// The pass over the edges of a round of [`crate::computed_split`]: per node `v` the
    /// part it wants, the part `p` of the largest `votes(v, p) * room[p]` (in `u64`), where
    /// `votes(v, p)` counts the entries of `v`'s rows in `out` and in `inn` whose node is in
    /// part `p` (a self-loop not counted; an edge both ways counted twice) and `room[p]` is
    /// 0..=65535. A tie goes to `v`'s own part first, then to the lowest part number; a node
    /// with no neighbour, or whose best score is not above its own part's, wants its own
    /// part. `part` has one entry per node, each below `room.len()` (1 to
    /// [`crate::MAX_COMPUTED_PARTS`] parts). An override must give this same list.
    ///
    /// The default runs the CPU kernel on the host pattern ([`GraphBackend::host_pattern`])
    /// on [`GraphBackend::cpu`]'s or [`GraphBackend::host_device`]'s workers (else one
    /// thread).
    fn split_votes(
        out: &Self::Matrix<u8>,
        inn: &Self::Matrix<u8>,
        part: &[u32],
        room: &[u32],
        device: &Self::Device,
    ) -> crate::Result<Vec<u32>> {
        let (Some(o), Some(i)) = (Self::host_pattern(out), Self::host_pattern(inn)) else {
            return Err(crate::GraphError::Split(
                "split votes need the graph's host pattern".to_string(),
            ));
        };
        match Self::cpu(device).or_else(|| Self::host_device(device)) {
            Some(cpu) => split_votes_cpu(o, i, part, room, cpu),
            None => split_votes_cpu(o, i, part, room, &CpuDevice::new(1)),
        }
    }
}

/// On the CPU, weak components are Afforest's on the device's threads ([`crate::afforest`]),
/// shortest paths delta-stepping's with bucket fusion ([`crate::delta_stepping`], at the
/// options' width or [`crate::delta_for`]'s; the transpose is not needed; hop counts, on a
/// matrix without values, [`crate::beamer_hops`]'s), strong components Multistep's
/// ([`crate::multistep`]) and breadth-first search direction-optimizing
/// ([`crate::beamer_bfs`]). An engine the device was made on
/// (`CpuDevice::with_executor`) may answer source sets with searches of its own; the
/// answer is put in this trait's terms. Without one, the defaults run.
impl GraphBackend for CpuBackend {
    fn cpu(device: &CpuDevice) -> Option<&CpuDevice> {
        Some(device)
    }

    fn components_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        device: &CpuDevice,
    ) -> crate::Result<Components> {
        crate::afforest(out, inn, device)
    }

    fn sssp_of(
        weights: &Csr<u32>,
        transposed: Option<&Csr<u32>>,
        source: u32,
        opts: &SsspOptions,
        device: &CpuDevice,
    ) -> crate::Result<Paths> {
        if weights.values().is_none() {
            // every edge one hop: the levels of a breadth-first search
            return crate::beamer_hops(weights, transposed, source, device);
        }
        let delta = opts.delta.unwrap_or_else(|| crate::delta_for(weights));
        crate::delta_stepping(weights, source, delta, device)
    }

    fn scc_of(out: &Csr<u8>, inn: &Csr<u8>, device: &CpuDevice) -> crate::Result<Components> {
        crate::multistep(out, inn, device)
    }

    fn bfs_of(
        g: &Graph<Self>,
        sources: &[u32],
        opts: &BfsOptions,
        device: &CpuDevice,
        st: &mut BfsState<Self>,
    ) -> crate::Result<BfsSummary> {
        Ok(crate::beamer::beamer_bfs_with(g, sources, opts, device, st))
    }

    fn host_pattern(m: &Csr<u8>) -> Option<&Csr<u8>> {
        Some(m)
    }

    fn host_device(device: &CpuDevice) -> Option<&CpuDevice> {
        Some(device)
    }

    /// The CPU kernel on the device's parked workers: one pass over each node's out- and
    /// in-edges with a counter per part in hand, pieces of about equal edges.
    fn split_votes(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        part: &[u32],
        room: &[u32],
        device: &CpuDevice,
    ) -> crate::Result<Vec<u32>> {
        split_votes_cpu(out, inn, part, room, device)
    }

    fn reach_sets(a: &Csr<u8>, sources: &[u32], device: &CpuDevice) -> crate::Result<SourceSets> {
        let n = a.nrows();
        let (off, adj) = (a.pattern().offsets(), a.pattern().indices());
        let seeds: Vec<Vec<(u32, u64)>> = sources
            .chunks(64)
            .map(|chunk| {
                chunk
                    .iter()
                    .enumerate()
                    .map(|(k, &s)| (s, 1u64 << k))
                    .collect()
            })
            .collect();
        let seeds: Vec<&[(u32, u64)]> = seeds.iter().map(Vec::as_slice).collect();
        let Some(walks) = device.engine_mask_walk(off, adj, &seeds) else {
            return reach_sets_generic::<Self>(a, sources, device);
        };
        if walks.len() != seeds.len() || walks.iter().any(|m| m.len() != n) {
            return reach_sets_generic::<Self>(a, sources, device);
        }
        let mut batches = Vec::new();
        for masks in walks {
            let (idx, vals): (Vec<u32>, Vec<u64>) = masks
                .iter()
                .enumerate()
                .filter(|&(_, &m)| m != 0)
                .map(|(v, &m)| (v as u32, m))
                .unzip();
            batches.push(Vector::sparse(n, idx, vals)?);
        }
        let rounds = vec![0; batches.len()];
        Ok(SourceSets::from_batches(sources.to_vec(), batches, rounds))
    }

    fn label_reach(
        a: &Csr<u8>,
        sets: EdgeSets<'_>,
        seeds: &[(u32, u32)],
        sources: usize,
        device: &CpuDevice,
    ) -> crate::Result<SourceSets> {
        let n = a.nrows();
        let w = sets.words();
        // one seed mask per vertex
        let mut by: HashMap<u32, Vec<u64>> = HashMap::new();
        for &(v, k) in seeds {
            by.entry(v).or_insert_with(|| vec![0; w])[k as usize / 64] |= 1 << (k % 64);
        }
        let mut starts: Vec<(u32, Vec<u64>)> = by.into_iter().collect();
        starts.sort_unstable_by_key(|s| s.0);
        let refs: Vec<(u32, &[u64])> = starts.iter().map(|(v, m)| (*v, &m[..])).collect();
        let (off, adj) = (a.pattern().offsets(), a.pattern().indices());
        let masks = match device.engine_mask_walk_sets(
            off,
            adj,
            sets.slot_set(),
            sets.set_words(),
            w,
            &refs,
        ) {
            Some(m) if m.len() == n * w => m,
            _ => return label_reach_generic::<Self>(a, sets, seeds, sources, device),
        };
        let mut batches = Vec::with_capacity(sources.div_ceil(64));
        for b in 0..sources.div_ceil(64) {
            let (idx, vals): (Vec<u32>, Vec<u64>) = (0..n)
                .map(|v| (v as u32, masks[v * w + b]))
                .filter(|&(_, m)| m != 0)
                .unzip();
            batches.push(Vector::sparse(n, idx, vals)?);
        }
        let rounds = vec![0; batches.len()];
        Ok(SourceSets::from_batches(
            (0..sources as u32).collect(),
            batches,
            rounds,
        ))
    }
}