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/tests/split_compute.rs

//! The computed split (balanced label spreading): every node in one part within its limit;
//! the CPU result equals a plain one-thread reference written straight from the rule for
//! several graphs, part counts and thread counts; K dense groups joined by a few edges are
//! cut at exactly those edges; the result never crosses more edges than its start; and a
//! split made from it gives the unsplit graph's answers through the rounds.

// The reference is written by node number, as the rule reads.
#![allow(clippy::needless_range_loop)]

use std::collections::{BTreeSet, VecDeque};

use kleene_graph::{
    BfsState, ComputedSplit, Graph, GraphBackend, Split, SplitCompute, SplitKey, components_rounds,
    computed_split, crossing_edges, khop_rounds, parts_of_key, reach_rounds,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

type B = CpuBackend;

/// A graph as its distinct edges.
struct G {
    n: usize,
    edges: Vec<(u32, u32)>,
}

impl G {
    fn new(n: usize, raw: impl IntoIterator<Item = (u32, u32)>) -> G {
        let set: BTreeSet<(u32, u32)> = raw.into_iter().collect();
        G {
            n,
            edges: set.into_iter().collect(),
        }
    }

    fn out(&self) -> Csr<u8> {
        let (s, d): (Vec<u32>, Vec<u32>) = self.edges.iter().copied().unzip();
        Csr::from_edges(self.n, self.n, &s, &d, None, BoolOrAnd).unwrap()
    }
}

struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u32 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (self.0 >> 33) as u32
    }
}

fn random(n: u32, m: usize, seed: u64) -> G {
    let mut r = Lcg(seed);
    G::new(n as usize, (0..m).map(|_| (r.next() % n, r.next() % n)))
}

/// An R-MAT graph (a 0.57, b 0.19, c 0.19, d 0.05) of 2^scale nodes.
fn rmat(scale: u32, m: usize, seed: u64) -> G {
    let mut r = Lcg(seed);
    let mut raw = Vec::with_capacity(m);
    for _ in 0..m {
        let (mut u, mut v) = (0u32, 0u32);
        for _ in 0..scale {
            let x = r.next() % 100;
            let (a, b) = match x {
                0..57 => (0, 0),
                57..76 => (0, 1),
                76..95 => (1, 0),
                _ => (1, 1),
            };
            u = (u << 1) | a;
            v = (v << 1) | b;
        }
        raw.push((u, v));
    }
    G::new(1 << scale, raw)
}

/// A `w` by `h` grid, edges both ways, ids shuffled when `shuffle`.
fn grid(w: u32, h: u32, shuffle: bool) -> G {
    let n = w * h;
    let mut id: Vec<u32> = (0..n).collect();
    if shuffle {
        let mut r = Lcg(99);
        for i in (1..n as usize).rev() {
            id.swap(i, r.next() as usize % (i + 1));
        }
    }
    let mut raw = Vec::new();
    for y in 0..h {
        for x in 0..w {
            let v = id[(y * w + x) as usize];
            if x + 1 < w {
                let u = id[(y * w + x + 1) as usize];
                raw.extend([(v, u), (u, v)]);
            }
            if y + 1 < h {
                let u = id[((y + 1) * w + x) as usize];
                raw.extend([(v, u), (u, v)]);
            }
        }
    }
    G::new(n as usize, raw)
}

/// `k` groups of `size` nodes, each node with `deg` random edges inside its group, ids
/// shuffled, the groups joined in a ring by one edge each: gives the graph, each node's
/// group and the joining edges.
fn grouped(k: u32, size: u32, deg: u32, seed: u64) -> (G, Vec<u32>, BTreeSet<(u32, u32)>) {
    let n = k * size;
    let mut r = Lcg(seed);
    let mut id: Vec<u32> = (0..n).collect();
    for i in (1..n as usize).rev() {
        id.swap(i, r.next() as usize % (i + 1));
    }
    let mut group = vec![0u32; n as usize];
    let mut raw = Vec::new();
    for g in 0..k {
        for a in 0..size {
            let v = id[(g * size + a) as usize];
            group[v as usize] = g;
            // a ring inside the group keeps it connected, then random chords
            raw.push((v, id[(g * size + (a + 1) % size) as usize]));
            for _ in 0..deg {
                let b = r.next() % size;
                if b != a {
                    raw.push((v, id[(g * size + b) as usize]));
                }
            }
        }
    }
    let mut join = BTreeSet::new();
    for g in 0..k {
        let a = id[(g * size) as usize];
        let b = id[(((g + 1) % k) * size + 1) as usize];
        join.insert((a, b));
        raw.push((a, b));
    }
    (G::new(n as usize, raw), group, join)
}

// ---- The plain one-thread reference, straight from the rule ----

fn mix(mut z: u64) -> u64 {
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

fn hash(seed: u64, salt: u64, v: u32, round: u32) -> u64 {
    mix(mix(seed ^ salt).wrapping_add(((round as u64) << 32) | v as u64))
}

fn limits(n: usize, how: &SplitCompute) -> Vec<u64> {
    match &how.capacity {
        Some(c) => c.clone(),
        None => {
            let share = (n as u64).div_ceil(how.parts as u64);
            let up = (share * how.slack_permille as u64).div_ceil(1000);
            vec![share + up; how.parts as usize]
        }
    }
}

fn reference_start(n: usize, how: &SplitCompute) -> Vec<u32> {
    let limit = limits(n, how);
    let total: u128 = limit.iter().map(|&c| c as u128).sum();
    let mut part = vec![0u32; n];
    let mut size = vec![0u64; limit.len()];
    let mut over = Vec::new();
    for v in 0..n {
        let x = (hash(how.seed, 1, v as u32, 0) as u128 * total) >> 64;
        let mut run = 0u128;
        let mut p = 0;
        loop {
            run += limit[p] as u128;
            if run > x {
                break;
            }
            p += 1;
        }
        if size[p] < limit[p] {
            part[v] = p as u32;
            size[p] += 1;
        } else {
            over.push(v);
        }
    }
    for v in over {
        let p = (0..limit.len()).find(|&p| size[p] < limit[p]).unwrap();
        part[v] = p as u32;
        size[p] += 1;
    }
    part
}

fn plain_crossing(g: &G, part: &[u32]) -> u64 {
    g.edges
        .iter()
        .filter(|&&(u, v)| part[u as usize] != part[v as usize])
        .count() as u64
}

fn reference(g: &G, how: &SplitCompute) -> ComputedSplit {
    let n = g.n;
    let k = how.parts as usize;
    let limit = limits(n, how);
    let mut part = reference_start(n, how);
    let sizes = |part: &[u32]| {
        let mut s = vec![0u64; k];
        for &p in part {
            s[p as usize] += 1;
        }
        s
    };
    let c0 = plain_crossing(g, &part);
    let mut best = (c0, part.clone());
    let mut history = vec![c0];
    let mut rounds = 0u32;
    while c0 > 0 && rounds < how.max_rounds {
        rounds += 1;
        let size = sizes(&part);
        let room: Vec<u64> = (0..k)
            .map(|p| {
                if limit[p] == 0 {
                    0
                } else {
                    65535 * (2 * limit[p] - size[p]) / (2 * limit[p])
                }
            })
            .collect();
        let mut votes = vec![vec![0u64; k]; n];
        for &(u, v) in &g.edges {
            if u != v {
                votes[u as usize][part[v as usize] as usize] += 1;
                votes[v as usize][part[u as usize] as usize] += 1;
            }
        }
        let mut wanting: Vec<Vec<(u64, u32)>> = vec![Vec::new(); k];
        for v in 0..n {
            let own = part[v] as usize;
            let mut best_p = own;
            let mut top = votes[v][own] * room[own];
            for p in 0..k {
                if votes[v][p] * room[p] > top {
                    best_p = p;
                    top = votes[v][p] * room[p];
                }
            }
            if best_p != own && hash(how.seed, 2, v as u32, rounds).is_multiple_of(2) {
                wanting[best_p].push((hash(how.seed, 3, v as u32, rounds), v as u32));
            }
        }
        for (q, mut list) in wanting.into_iter().enumerate() {
            list.sort();
            for &(_, v) in list.iter().take((limit[q] - size[q]) as usize) {
                part[v as usize] = q as u32;
            }
        }
        let c = plain_crossing(g, &part);
        if c < best.0 {
            best = (c, part.clone());
        }
        history.push(c);
        if c == 0 {
            break;
        }
        if rounds >= 3 {
            let before = history[rounds as usize - 3];
            if before.saturating_sub(c) * 1000 < before {
                break;
            }
        }
    }
    ComputedSplit {
        sizes: sizes(&best.1),
        part: best.1,
        crossing_edges: best.0,
        rounds,
    }
}

fn run(g: &G, how: &SplitCompute, device: &CpuDevice) -> ComputedSplit {
    let out = g.out();
    computed_split::<B>(&out, &out.transpose(), how, device).unwrap()
}

fn graphs() -> Vec<(&'static str, G)> {
    vec![
        ("random 2000", random(2000, 9000, 1)),
        ("random sparse 1500", random(1500, 1600, 2)),
        ("rmat 11", rmat(11, 16000, 3)),
        ("grid 40x50", grid(40, 50, false)),
        ("grid shuffled 45x45", grid(45, 45, true)),
        ("grouped 7x300", grouped(7, 300, 6, 4).0),
    ]
}

fn how(parts: u32, seed: u64) -> SplitCompute {
    SplitCompute {
        seed,
        ..SplitCompute::new(parts)
    }
}

#[test]
fn every_node_has_one_part_and_sizes_stay_within_the_limits() {
    let device = CpuDevice::new(4).with_grain(64);
    for (name, g) in graphs() {
        let out = g.out();
        for h in [
            how(2, 0),
            how(4, 1),
            how(7, 2),
            how(64, 3),
            SplitCompute {
                capacity: Some(vec![g.n as u64 / 10, g.n as u64 / 2, 0, g.n as u64 / 2]),
                ..how(4, 5)
            },
            SplitCompute {
                capacity: Some(vec![g.n as u64; 3]),
                ..how(3, 6)
            },
            SplitCompute {
                slack_permille: 0,
                ..how(5, 7)
            },
        ] {
            let r = run(&g, &h, &device);
            let limit = limits(g.n, &h);
            assert_eq!(r.part.len(), g.n, "{name}");
            assert_eq!(r.sizes.len(), h.parts as usize, "{name}");
            let mut size = vec![0u64; h.parts as usize];
            for &p in &r.part {
                assert!(p < h.parts, "{name}: part {p} of {}", h.parts);
                size[p as usize] += 1;
            }
            assert_eq!(size, r.sizes, "{name}");
            for p in 0..h.parts as usize {
                assert!(size[p] <= limit[p], "{name} {h:?}: part {p} {size:?}");
            }
            assert_eq!(r.crossing_edges, crossing_edges(&out, &r.part), "{name}");
            assert_eq!(r.crossing_edges, plain_crossing(&g, &r.part), "{name}");
            assert!(r.rounds <= h.max_rounds);
        }
    }
}

#[test]
fn the_cpu_result_equals_the_plain_reference_on_every_thread_count() {
    for (name, g) in graphs() {
        for (k, seed) in [(2, 0), (4, 11), (7, 12), (64, 13)] {
            let h = how(k, seed);
            let want = reference(&g, &h);
            for threads in [1, 2, 5, 8] {
                let device = CpuDevice::new(threads).with_grain(16);
                let got = run(&g, &h, &device);
                assert_eq!(got, want, "{name}, K {k}, {threads} threads");
            }
        }
        // unequal capacities, no slack, few rounds
        for h in [
            SplitCompute {
                capacity: Some(vec![g.n as u64 / 2, g.n as u64 / 4, g.n as u64 / 3]),
                ..how(3, 21)
            },
            SplitCompute {
                slack_permille: 0,
                max_rounds: 4,
                ..how(6, 22)
            },
            // capacities that sum to the nodes: many start nodes past a limit, placed
            // across pieces
            SplitCompute {
                capacity: Some(vec![
                    g.n as u64 / 2,
                    g.n as u64 / 8,
                    g.n as u64 - g.n as u64 / 2 - g.n as u64 / 8,
                ]),
                ..how(3, 23)
            },
            SplitCompute {
                slack_permille: 0,
                ..how(64, 24)
            },
        ] {
            let want = reference(&g, &h);
            for threads in [3, 8] {
                let got = run(&g, &h, &CpuDevice::new(threads).with_grain(16));
                assert_eq!(got, want, "{name}, {threads} threads, {h:?}");
            }
        }
    }
}

#[test]
fn the_cpu_votes_equal_the_default_on_one_thread() {
    // The trait's default (any backend keeping the host pattern) and the CPU backend's
    // kernel on many workers give the same list.
    let g = rmat(11, 16000, 8);
    let out = g.out();
    let inn = out.transpose();
    let part: Vec<u32> = (0..g.n as u32).map(|v| (v * 7 + v / 3) % 5).collect();
    let room = vec![65535, 40000, 32767, 0, 50000];
    let one = B::split_votes(&out, &inn, &part, &room, &CpuDevice::new(1)).unwrap();
    for threads in [2, 7, 16] {
        let many = B::split_votes(
            &out,
            &inn,
            &part,
            &room,
            &CpuDevice::new(threads).with_grain(8),
        )
        .unwrap();
        assert_eq!(one, many, "{threads} threads");
    }
    // nobody wants the part without room, and a node alone keeps its part
    assert!(one.iter().zip(&part).all(|(&w, &p)| w != 3 || p == 3));
}

#[test]
fn groups_joined_by_a_few_edges_are_cut_at_exactly_those_edges() {
    let device = CpuDevice::new(4).with_grain(64);
    for (k, size, seed) in [(2, 200, 1), (4, 150, 2), (7, 120, 3)] {
        let (g, group, join) = grouped(k, size, 8, seed);
        let r = run(
            &g,
            &SplitCompute {
                max_rounds: 100,
                ..how(k, seed)
            },
            &device,
        );
        assert_eq!(r.crossing_edges, join.len() as u64, "K {k}: {r:?}");
        let cut: BTreeSet<(u32, u32)> = g
            .edges
            .iter()
            .copied()
            .filter(|&(u, v)| r.part[u as usize] != r.part[v as usize])
            .collect();
        assert_eq!(cut, join, "K {k}");
        // one part per group, each group whole in its part
        let mut of = vec![u32::MAX; k as usize];
        for v in 0..g.n {
            let gr = group[v] as usize;
            if of[gr] == u32::MAX {
                of[gr] = r.part[v];
            }
            assert_eq!(of[gr], r.part[v], "K {k}: group {gr}");
        }
        let distinct: BTreeSet<u32> = of.iter().copied().collect();
        assert_eq!(distinct.len(), k as usize, "K {k}");
    }
}

#[test]
fn the_default_rounds_cut_eight_groups_exactly() {
    // 8 groups of 2000 need about 47 rounds; the default allows 100 (the 0.1 % rule stops
    // graphs without groups long before).
    assert_eq!(SplitCompute::new(8).max_rounds, 100);
    let (g, _, join) = grouped(8, 2000, 10, 1);
    let r = run(&g, &SplitCompute::new(8), &CpuDevice::new(4));
    assert_eq!(r.crossing_edges, join.len() as u64, "{} rounds", r.rounds);
}

#[test]
fn the_result_never_crosses_more_edges_than_its_start() {
    let device = CpuDevice::new(3).with_grain(64);
    let mut gs = graphs();
    gs.push(("rmat 13", rmat(13, 90000, 9)));
    gs.push(("random dense 600", random(600, 20000, 10)));
    for (name, g) in gs {
        for k in [2, 3, 8, 16] {
            for seed in [0, 1] {
                let h = how(k, seed);
                let r = run(&g, &h, &device);
                let start = plain_crossing(&g, &reference_start(g.n, &h));
                assert!(
                    r.crossing_edges <= start,
                    "{name}, K {k}: {} > {start}",
                    r.crossing_edges
                );
            }
        }
    }
}

#[test]
fn bad_asks_are_refused() {
    let g = random(100, 300, 1);
    let out = g.out();
    let inn = out.transpose();
    let d = CpuDevice::new(2);
    let try_ = |h: SplitCompute| computed_split::<B>(&out, &inn, &h, &d);
    assert!(try_(how(0, 0)).is_err());
    assert!(try_(how(65, 0)).is_err());
    assert!(try_(how(64, 0)).is_ok());
    assert!(
        try_(SplitCompute {
            capacity: Some(vec![40, 40]),
            ..how(2, 0)
        })
        .is_err()
    );
    assert!(
        try_(SplitCompute {
            capacity: Some(vec![100]),
            ..how(2, 0)
        })
        .is_err()
    );
    assert!(computed_split::<B>(&out, &random(99, 10, 1).out(), &how(2, 0), &d).is_err());
    // one part: nothing crosses, no round
    let r = try_(how(1, 0)).unwrap();
    assert_eq!((r.crossing_edges, r.rounds, r.sizes), (0, 0, vec![100]));
}

#[test]
fn parts_of_key_number_parts_as_the_split_does() {
    let n = 50;
    for key in [
        SplitKey::Hash(4),
        SplitKey::Blocks(vec![0, 10, 10, 30]),
        SplitKey::Property((0..n as u32).map(|v| (v % 3) * 10).collect()),
    ] {
        let part = parts_of_key(n, &key).unwrap();
        let split = Split::<u8>::new(n, &[], &[], None, &key, BoolOrAnd).unwrap();
        for v in 0..n as u32 {
            let id = split.ids().from_original(v).unwrap();
            assert_eq!(
                Some(part[v as usize]),
                split.ids().part_of(id),
                "{key:?} {v}"
            );
        }
    }
    assert!(parts_of_key(n, &SplitKey::Hash(0)).is_err());
}

fn plain_reach(g: &G, from: &[u32]) -> BTreeSet<u32> {
    let mut seen: BTreeSet<u32> = from.iter().copied().collect();
    let mut q: VecDeque<u32> = from.iter().copied().collect();
    let out = g.out();
    while let Some(v) = q.pop_front() {
        for &u in out.row(v as usize) {
            if seen.insert(u) {
                q.push_back(u);
            }
        }
    }
    seen
}

fn plain_khop(g: &G, s: u32, k: u32) -> Vec<u32> {
    let out = g.out();
    let mut d = vec![u32::MAX; g.n];
    d[s as usize] = 0;
    let mut q = VecDeque::from([s]);
    while let Some(v) = q.pop_front() {
        for &u in out.row(v as usize) {
            if d[u as usize] == u32::MAX {
                d[u as usize] = d[v as usize] + 1;
                q.push_back(u);
            }
        }
    }
    (0..g.n as u32)
        .filter(|&v| v != s && d[v as usize] <= k)
        .collect()
}

fn plain_components(g: &G) -> Vec<u32> {
    let mut of: Vec<u32> = (0..g.n as u32).collect();
    loop {
        let mut changed = false;
        for &(a, b) in &g.edges {
            let m = of[a as usize].min(of[b as usize]);
            if of[a as usize] != m || of[b as usize] != m {
                of[a as usize] = m;
                of[b as usize] = m;
                changed = true;
            }
        }
        if !changed {
            return of;
        }
    }
}

#[test]
fn a_split_made_from_the_result_gives_the_unsplit_answers_through_the_rounds() {
    let device = CpuDevice::new(4);
    for (name, g) in [
        ("random 800", random(800, 1500, 31)),
        ("rmat 10", rmat(10, 3000, 32)),
        ("grouped 4x100", grouped(4, 100, 4, 33).0),
    ] {
        let out = g.out();
        let inn = out.transpose();
        for k in [2, 4, 7] {
            let r = computed_split::<B>(&out, &inn, &how(k, 40), &device).unwrap();
            let key = r.key();
            let split = Split::from_csr(&out, &key, BoolOrAnd).unwrap();
            let tsplit = Split::from_csr(&inn, &key, BoolOrAnd).unwrap();
            let ids = split.ids();
            let parts = |s: &Split<u8>| -> Vec<Graph<B>> {
                s.parts()
                    .iter()
                    .map(|p| Graph::new(p.inner().clone(), &device).unwrap())
                    .collect()
            };
            // reachability
            let from = [0u32, 5, (g.n - 1) as u32];
            let mut gs = parts(&split);
            let mut st: Vec<BfsState<B>> = gs
                .iter()
                .map(|x| BfsState::new(x.vertices(), &device))
                .collect();
            let s: Vec<u64> = from
                .iter()
                .map(|&v| ids.from_original(v).unwrap())
                .collect();
            let got: BTreeSet<u32> = reach_rounds(&split, &mut gs, &s, &mut st, &device)
                .unwrap()
                .ids(ids)
                .iter()
                .map(|&i| ids.original(i).unwrap())
                .collect();
            assert_eq!(got, plain_reach(&g, &from), "{name} K {k}: reach");
            // k hops
            for (source, hops) in [(0u32, 1u32), (3, 2), (17, 4)] {
                let mut gs = parts(&split);
                let src = ids.from_original(source).unwrap();
                let mut got: Vec<u32> = khop_rounds(&split, &mut gs, src, hops, &device)
                    .unwrap()
                    .ids(ids)
                    .into_iter()
                    .map(|i| ids.original(i).unwrap())
                    .filter(|&v| v != source)
                    .collect();
                got.sort_unstable();
                assert_eq!(got, plain_khop(&g, source, hops), "{name} K {k}: k hops");
            }
            // weak components
            let c = components_rounds::<B>(&split, &tsplit, &device).unwrap();
            let got: Vec<u32> = (0..g.n as u32)
                .map(|v| c.of[ids.from_original(v).unwrap() as usize])
                .collect();
            assert_eq!(got, plain_components(&g), "{name} K {k}: components");
        }
    }
}

/// The numbers for the notes: crossing edges in % at the start and after, and the rounds.
/// `cargo test --release -p kleene-graph --test split_compute -- --ignored --nocapture`
#[test]
#[ignore]
fn report_crossing_edges() {
    let device = CpuDevice::default();
    let cases: Vec<(&str, G)> = vec![
        ("grouped 8x2000", grouped(8, 2000, 10, 1).0),
        ("grid shuffled 300x300", grid(300, 300, true)),
        ("rmat 18", rmat(18, 4_000_000, 2)),
    ];
    for (name, g) in cases {
        let out = g.out();
        let inn = out.transpose();
        let e = out.nnz() as f64;
        for k in [4, 8, 16] {
            let h = how(k, 0);
            let t = std::time::Instant::now();
            let r = computed_split::<B>(&out, &inn, &h, &device).unwrap();
            let secs = t.elapsed().as_secs_f64();
            let start = crossing_edges(&out, &reference_start(g.n, &h));
            let hash = crossing_edges(&out, &parts_of_key(g.n, &SplitKey::Hash(k)).unwrap());
            println!(
                "{name} K {k}: hash {:.2} %, start {:.2} %, computed {:.2} %, {} rounds, {secs:.2} s",
                100.0 * hash as f64 / e,
                100.0 * start as f64 / e,
                100.0 * r.crossing_edges as f64 / e,
                r.rounds
            );
        }
    }
}