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

//! Shortest paths on the CPU by delta-stepping (Meyer and Sanders 2003) with bucket fusion
//! (Zhang et al., GraphIt 2020), on the device's threads (gatling's in the benchmark).
//!
//! Vertices wait in buckets of width `delta` by distance, and the buckets are taken in
//! order. An edge lighter than `delta` is light: it may lead back into the bucket being
//! worked, so the light edges of a bucket's vertices are relaxed until the bucket stays
//! empty; they are gathered once into lists, so a vertex worked again reads only those. A
//! heavy edge can only lead to a later bucket, so it is relaxed once per vertex, after its
//! bucket is done and its distance is final. A vertex put in a bucket twice before it is
//! worked is worked once. Each thread keeps its own buckets
//! (a ring of [`WINDOW`] buckets ahead of the current one, and a list for the rest); a
//! round hands the current bucket's vertices of every thread out in pieces. Bucket fusion:
//! a thread that refills the current bucket with fewer than [`FUSE`] vertices works them
//! at once in the same round, with no wait for the others; a round of fewer vertices than
//! half the device's grain is worked on the calling thread alone.
//!
//! Each vertex holds `(distance << 32) | parent` and an edge offers `(distance of u + w)
//! << 32 | u` by an atomic minimum, so among equal paths the lowest parent stays, as the
//! generic algorithm answers: every vertex on a shortest path into `v` offers its final
//! distance once at least. Only a shorter distance puts `v` in a bucket again.

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

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

use crate::Paths;

/// The bucket width the CPU backend's delta-stepping takes when the options give none:
/// the mean weight over the mean out-degree (Meyer and Sanders' width of about the
/// largest weight over the degree), at least 1, so a vertex has about one light edge.
/// The mean weight is taken from 2^16 evenly spread edges. Unweighted (every
/// edge 1) it is 1: the buckets are the levels of a breadth-first search.
///
/// Measured on loki (5 threads, the benchmark's weights 1..255, widths 2 to 512 tried):
/// rmat24 (degree 7.9) is fastest at 8 to 16 (1.23 s) and 1.1-1.5x slower at 32 to 512;
/// road2048 (degree 2.4) moves within 15 % between 4 and 255 (0.37-0.48 s; the host's
/// load moves it about as much). This gives 16 and 53.
pub fn delta_for(weights: &Csr<u32>) -> u64 {
    let Some(w) = weights.values().filter(|w| !w.is_empty()) else {
        return 1;
    };
    let step = w.len().div_ceil(WEIGHT_SAMPLE).max(1);
    let (sum, k) = w
        .iter()
        .step_by(step)
        .fold((0u64, 0u64), |(s, k), &x| (s + u64::from(x), k + 1));
    // mean weight / (edges / vertices)
    let rows = weights.nrows().max(1) as u128;
    let delta = u128::from(sum) * rows / (u128::from(k) * w.len() as u128);
    (delta as u64).max(1)
}

/// Edges whose weights [`delta_for`] averages.
pub const WEIGHT_SAMPLE: usize = 1 << 16;

/// Buckets ahead of the current one that each thread keeps in a ring; vertices farther
/// ahead wait in a list until the ring reaches them.
pub const WINDOW: u64 = 1 << 10;

/// A thread works a refill of the current bucket of fewer vertices than this at once.
pub const FUSE: usize = 1000;

/// The buckets and the finished vertices of one thread.
struct Lane {
    /// Bucket `b` (current `<= b < current + WINDOW`) at `ring[b % WINDOW]`.
    ring: Vec<Vec<u32>>,
    /// Vertices in the ring.
    in_ring: usize,
    /// Vertices whose bucket was past the ring when they were put.
    far: Vec<u32>,
    /// The least bucket put in `far` (a lower one is harmless: it only moves them early).
    far_min: u64,
    /// Vertices this thread took from the current bucket for the first time: their heavy
    /// edges are relaxed once the bucket is done.
    done: Vec<u32>,
}

impl Lane {
    fn new() -> Self {
        Lane {
            ring: (0..WINDOW).map(|_| Vec::new()).collect(),
            in_ring: 0,
            far: Vec::new(),
            far_min: u64::MAX,
            done: Vec::new(),
        }
    }

    fn put(&mut self, v: u32, bucket: u64, current: u64) {
        if bucket - current < WINDOW {
            self.ring[(bucket % WINDOW) as usize].push(v);
            self.in_ring += 1;
        } else {
            self.far.push(v);
            self.far_min = self.far_min.min(bucket);
        }
    }

    /// The vertices of bucket `b`, taken out of the ring.
    fn take(&mut self, b: u64) -> Vec<u32> {
        let bin = std::mem::take(&mut self.ring[(b % WINDOW) as usize]);
        self.in_ring -= bin.len();
        bin
    }

    /// The least bucket after `current` this thread holds a vertex for (`u64::MAX`: none).
    fn next_after(&self, current: u64) -> u64 {
        let mut next = self.far_min;
        if self.in_ring > 0 {
            for b in current + 1..current + WINDOW {
                if !self.ring[(b % WINDOW) as usize].is_empty() {
                    next = next.min(b);
                    break;
                }
            }
        }
        next
    }
}

/// Vertices per piece of the light edges.
const LIGHT_BITS: u32 = 14;

/// The light edges of the vertices of one piece.
struct LightPiece {
    off: Vec<u32>,
    to: Vec<u32>,
    w: Vec<u32>,
}

/// The edges lighter than the bucket width: the light passes, which may work a vertex
/// more than once, read only these. Gathered once, in parallel pieces of `1 <<
/// LIGHT_BITS` vertices.
enum Light {
    /// Every edge weighs 1 and the buckets are 1 wide: none is light.
    None,
    /// Every edge weighs 1 and the buckets are wider: every edge is light.
    All,
    /// The light edges of each piece.
    Lists(Vec<LightPiece>),
}

impl Light {
    fn gather(
        device: &CpuDevice,
        off: &[u64],
        adj: &[u32],
        weights: Option<&[u32]>,
        delta: u64,
    ) -> Self {
        let Some(w) = weights else {
            return if delta > 1 { Light::All } else { Light::None };
        };
        let n = off.len() - 1;
        let np = n.div_ceil(1 << LIGHT_BITS);
        let build = |p: usize| {
            let lo = p << LIGHT_BITS;
            let hi = ((p + 1) << LIGHT_BITS).min(n);
            let mut piece = LightPiece {
                off: Vec::with_capacity(hi - lo + 1),
                to: Vec::new(),
                w: Vec::new(),
            };
            piece.off.push(0);
            for v in lo..hi {
                for k in off[v] as usize..off[v + 1] as usize {
                    if u64::from(w[k]) < delta {
                        piece.to.push(adj[k]);
                        piece.w.push(w[k]);
                    }
                }
                piece.off.push(piece.to.len() as u32);
            }
            piece
        };
        let slots: Vec<std::sync::OnceLock<LightPiece>> =
            (0..np).map(|_| std::sync::OnceLock::new()).collect();
        let next = AtomicUsize::new(0);
        let mut seats = vec![(); device.threads().min(np).max(1)];
        device.each_block(&mut seats, |_, ()| {
            loop {
                let p = next.fetch_add(1, Relaxed);
                if p >= np {
                    break;
                }
                let _ = slots[p].set(build(p));
            }
        });
        Light::Lists(
            slots
                .into_iter()
                .map(|s| s.into_inner().expect("every piece is built"))
                .collect(),
        )
    }
}

/// What every share reads: the graph, the words, and the bucket width.
struct Work<'a> {
    off: &'a [u64],
    adj: &'a [u32],
    weights: Option<&'a [u32]>,
    light: Light,
    words: &'a [AtomicU64],
    /// One bit per vertex: taken from its bucket (set once, as its bucket is its last).
    taken: &'a [AtomicU64],
    /// The distance each vertex last relaxed its light edges at: a vertex put in a bucket
    /// twice before it was worked is worked once.
    last: &'a [AtomicU32],
    delta: u64,
}

impl Work<'_> {
    fn weight(&self, k: usize) -> u64 {
        self.weights.map_or(1, |w| u64::from(w[k]))
    }

    /// Offer `v` the path through `u` at `du + w`; a shorter distance puts it in a bucket.
    fn relax(&self, u: u32, du: u64, v: u32, w: u64, lane: &mut Lane, current: u64) {
        let d = du + w;
        if d >> 32 != 0 {
            return;
        }
        let offer = d << 32 | u64::from(u);
        let at = &self.words[v as usize];
        let mut old = at.load(Relaxed);
        loop {
            if offer >= old {
                return;
            }
            match at.compare_exchange_weak(old, offer, Relaxed, Relaxed) {
                Ok(_) => break,
                Err(now) => old = now,
            }
        }
        if old == u64::MAX || d < old >> 32 {
            lane.put(v, d / self.delta, current);
        }
    }

    /// Work `u` in bucket `b`: skipped when it has moved to an earlier bucket since it was
    /// put; else noted as taken (once) and its light edges relaxed.
    fn light(&self, u: u32, b: u64, lane: &mut Lane) {
        let du = self.words[u as usize].load(Relaxed) >> 32;
        if du / self.delta != b {
            return;
        }
        let at = &self.last[u as usize];
        if du != u64::from(u32::MAX) && at.load(Relaxed) == du as u32 {
            return;
        }
        at.store(du as u32, Relaxed);
        let (word, bit) = (u as usize / 64, 1u64 << (u % 64));
        if self.taken[word].load(Relaxed) & bit == 0
            && self.taken[word].fetch_or(bit, Relaxed) & bit == 0
        {
            lane.done.push(u);
        }
        match &self.light {
            Light::None => {}
            Light::All => {
                for k in self.off[u as usize] as usize..self.off[u as usize + 1] as usize {
                    self.relax(u, du, self.adj[k], 1, lane, b);
                }
            }
            Light::Lists(pieces) => {
                let piece = &pieces[(u >> LIGHT_BITS) as usize];
                let i = (u & ((1 << LIGHT_BITS) - 1)) as usize;
                for j in piece.off[i] as usize..piece.off[i + 1] as usize {
                    self.relax(u, du, piece.to[j], u64::from(piece.w[j]), lane, b);
                }
            }
        }
    }

    /// Relax the heavy edges of `u`, whose distance is final.
    fn heavy(&self, u: u32, b: u64, lane: &mut Lane) {
        let du = self.words[u as usize].load(Relaxed) >> 32;
        for k in self.off[u as usize] as usize..self.off[u as usize + 1] as usize {
            let w = self.weight(k);
            if w >= self.delta {
                self.relax(u, du, self.adj[k], w, lane, b);
            }
        }
    }
}

/// Shortest paths from `source` along `weights` (a structural matrix weighs every edge 1)
/// by delta-stepping with buckets of width `delta`, on the device's threads; the answer
/// [`crate::sssp_of_generic`] gives (distances, and among equal paths the lowest parent).
/// [`Paths::rounds`] counts the rounds of all buckets and their heavy passes; nothing is
/// pulled. The caller checks the input (as [`crate::sssp_of`] does).
pub fn delta_stepping(
    weights: &Csr<u32>,
    source: u32,
    delta: u64,
    device: &CpuDevice,
) -> crate::Result<Paths> {
    let n = weights.nrows();
    let delta = delta.max(1);
    let words: Vec<AtomicU64> = (0..n).map(|_| AtomicU64::new(u64::MAX)).collect();
    let taken: Vec<AtomicU64> = (0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect();
    let last: Vec<AtomicU32> = (0..n).map(|_| AtomicU32::new(u32::MAX)).collect();
    words[source as usize].store(u64::from(source), Relaxed);
    let (off, adj) = (weights.pattern().offsets(), weights.pattern().indices());
    let values = weights.values().map(|v| &v[..]);
    let work = Work {
        off,
        adj,
        weights: values,
        light: Light::gather(device, off, adj, values, delta),
        words: &words,
        taken: &taken,
        last: &last,
        delta,
    };
    let threads = device.threads().max(1);
    // a round of fewer vertices runs here; pieces of a round handed out
    let small = (device.grain() / 2).max(1);
    let piece = (device.grain() / 32).clamp(1, 128);
    let mut lanes: Vec<Lane> = (0..threads).map(|_| Lane::new()).collect();
    lanes[0].put(source, 0, 0);
    let mut rounds = 0u32;
    let mut current = 0u64;
    loop {
        // the light edges, round after round until the bucket stays empty
        loop {
            let bins: Vec<Vec<u32>> = lanes.iter_mut().map(|l| l.take(current)).collect();
            let total: usize = bins.iter().map(Vec::len).sum();
            if total == 0 {
                break;
            }
            rounds += 1;
            if total < small || threads == 1 {
                for &u in bins.iter().flatten() {
                    work.light(u, current, &mut lanes[0]);
                }
            } else {
                round(device, &mut lanes, &bins, piece, |u, lane| {
                    work.light(u, current, lane);
                    // bucket fusion: a small refill of the current bucket is worked here
                    while lane.ring[(current % WINDOW) as usize].len() < FUSE {
                        let refill = lane.take(current);
                        if refill.is_empty() {
                            break;
                        }
                        for &x in &refill {
                            work.light(x, current, lane);
                        }
                    }
                });
            }
        }
        // the heavy edges of the bucket's vertices, now final
        let done: Vec<Vec<u32>> = lanes
            .iter_mut()
            .map(|l| std::mem::take(&mut l.done))
            .collect();
        let total: usize = done.iter().map(Vec::len).sum();
        if total > 0 {
            rounds += 1;
            if total < small || threads == 1 {
                for &u in done.iter().flatten() {
                    work.heavy(u, current, &mut lanes[0]);
                }
            } else {
                round(device, &mut lanes, &done, piece, |u, lane| {
                    work.heavy(u, current, lane)
                });
            }
        }
        // the next bucket any thread holds
        let next = lanes
            .iter()
            .map(|l| l.next_after(current))
            .min()
            .unwrap_or(u64::MAX);
        if next == u64::MAX {
            break;
        }
        current = next;
        // vertices that waited past the ring and are now inside it
        for lane in &mut lanes {
            if lane.far_min < current + WINDOW {
                let far = std::mem::take(&mut lane.far);
                lane.far_min = u64::MAX;
                for v in far {
                    let b = (words[v as usize].load(Relaxed) >> 32) / delta;
                    if b >= current {
                        lane.put(v, b, current);
                    }
                }
            }
        }
    }
    let (idx, val): (Vec<u32>, Vec<u64>) = words
        .into_iter()
        .map(AtomicU64::into_inner)
        .enumerate()
        .filter(|&(_, x)| x != u64::MAX)
        .map(|(v, x)| (v as u32, x))
        .unzip();
    Ok(Paths::from_packed(
        source,
        Vector::sparse(n, idx, val)?,
        rounds,
        0,
    ))
}

/// One round: the vertices of `bins` handed out in pieces of `piece` to the device's
/// threads, each working them with `f` into its own lane.
fn round(
    device: &CpuDevice,
    lanes: &mut [Lane],
    bins: &[Vec<u32>],
    piece: usize,
    f: impl Fn(u32, &mut Lane) + Sync,
) {
    let pieces: Vec<(usize, usize)> = bins
        .iter()
        .enumerate()
        .flat_map(|(b, bin)| (0..bin.len()).step_by(piece).map(move |lo| (b, lo)))
        .collect();
    let next = AtomicUsize::new(0);
    device.each_block(lanes, |_, lane| {
        loop {
            let p = next.fetch_add(1, Relaxed);
            let Some(&(b, lo)) = pieces.get(p) else {
                break;
            };
            let bin = &bins[b];
            for &u in &bin[lo..(lo + piece).min(bin.len())] {
                f(u, lane);
            }
        }
    });
}