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

//! PageRank, betweenness centrality and triangle counting: each equal to a plain
//! single-threaded reference written here, whatever the number of workers.

use std::collections::VecDeque;

use kleene_graph::{PageRankOptions, Relabel, betweenness, pagerank, triangles, undirected};
use kleene_sparse::{BoolOrAnd, CpuDevice, Csr};

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

/// R-MAT-like skewed edges from a fixed seed (a hub, a long tail), self-loops and repeats in.
fn skewed(n: u32, m: usize, seed: u64) -> Vec<(u32, u32)> {
    let mut x = seed;
    let mut next = || {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        x
    };
    (0..m)
        .map(|_| {
            let a = (next() % u64::from(n)) as u32;
            let b = (next() % u64::from(n)) as u32;
            // a quarter of the edges touch the low numbers: hubs
            if next() % 4 == 0 { (a % 8, b) } else { (a, b) }
        })
        .collect()
}

fn fixtures() -> Vec<(&'static str, Csr<u8>)> {
    let mut grid = Vec::new();
    for r in 0..12u32 {
        for c in 0..12u32 {
            let v = r * 12 + c;
            if c + 1 < 12 {
                grid.extend([(v, v + 1), (v + 1, v)]);
            }
            if r + 1 < 12 && (r + c) % 3 != 0 {
                grid.push((v, v + 12));
            }
        }
    }
    vec![
        ("skewed", graph(600, &skewed(600, 5000, 7))),
        ("grid", graph(144, &grid)),
        // a sink, a self-loop, an isolated vertex, a triangle and a 4-clique
        (
            "small",
            graph(
                9,
                &[
                    (0, 1),
                    (1, 2),
                    (2, 0),
                    (3, 3),
                    (4, 5),
                    (5, 6),
                    (6, 7),
                    (7, 4),
                    (4, 6),
                    (5, 7),
                    (1, 4),
                ],
            ),
        ),
    ]
}

/// GAP's PageRank, one thread, the same order of sums.
fn plain_pagerank(out: &Csr<u8>, opts: &PageRankOptions) -> (Vec<f32>, u32) {
    let n = out.nrows();
    let inn = out.transpose();
    let base = (1.0 - opts.damping) / n as f32;
    let mut s = vec![1.0 / n as f32; n];
    let mut rounds = 0;
    while rounds < opts.max_rounds {
        let share: Vec<f32> = (0..n)
            .map(|u| {
                let d = out.row(u).len();
                if d == 0 { 0.0 } else { s[u] / d as f32 }
            })
            .collect();
        let mut err = 0f64;
        for (v, sv) in s.iter_mut().enumerate() {
            let mut sum = 0f32;
            for &u in inn.row(v) {
                sum += share[u as usize];
            }
            let new = base + opts.damping * sum;
            err += f64::from((new - *sv).abs());
            *sv = new;
        }
        rounds += 1;
        if err < opts.tolerance {
            break;
        }
    }
    (s, rounds)
}

/// Brandes with a queue and a stack (Brandes 2001), summed over the sources.
fn plain_betweenness(out: &Csr<u8>, sources: &[u32]) -> Vec<f64> {
    let n = out.nrows();
    let mut bc = vec![0f64; n];
    for &s in sources {
        let mut sigma = vec![0f64; n];
        let mut dist = vec![-1i64; n];
        let mut preds: Vec<Vec<u32>> = vec![Vec::new(); n];
        let mut stack = Vec::new();
        sigma[s as usize] = 1.0;
        dist[s as usize] = 0;
        let mut q = VecDeque::from([s]);
        while let Some(v) = q.pop_front() {
            stack.push(v);
            for &w in out.row(v as usize) {
                if dist[w as usize] < 0 {
                    dist[w as usize] = dist[v as usize] + 1;
                    q.push_back(w);
                }
                if dist[w as usize] == dist[v as usize] + 1 {
                    sigma[w as usize] += sigma[v as usize];
                    preds[w as usize].push(v);
                }
            }
        }
        let mut delta = vec![0f64; n];
        while let Some(w) = stack.pop() {
            for &v in &preds[w as usize] {
                delta[v as usize] +=
                    sigma[v as usize] / sigma[w as usize] * (1.0 + delta[w as usize]);
            }
            if w != s {
                bc[w as usize] += delta[w as usize];
            }
        }
    }
    bc
}

/// Every triple u < v < w with all three undirected edges, by brute force over edges.
fn plain_triangles(out: &Csr<u8>) -> u64 {
    let n = out.nrows();
    let mut adj = vec![std::collections::BTreeSet::new(); n];
    for v in 0..n {
        for &w in out.row(v) {
            if w as usize != v {
                adj[v].insert(w);
                adj[w as usize].insert(v as u32);
            }
        }
    }
    let mut t = 0;
    for u in 0..n as u32 {
        for &v in adj[u as usize].range(u + 1..) {
            for &w in adj[v as usize].range(v + 1..) {
                if adj[u as usize].contains(&w) {
                    t += 1;
                }
            }
        }
    }
    t
}

#[test]
fn pagerank_equals_gaps_single_thread_rounds() {
    let opts = PageRankOptions::default();
    for (name, out) in fixtures() {
        let inn = out.transpose();
        let (want, rounds) = plain_pagerank(&out, &opts);
        for threads in [1, 3, 8] {
            let cpu = CpuDevice::new(threads).with_grain(16);
            let got = pagerank(&out, &inn, &opts, &cpu).unwrap();
            assert_eq!(got.rounds, rounds, "{name} on {threads}");
            assert_eq!(got.scores, want, "{name} on {threads}");
            assert!(got.change < opts.tolerance || got.rounds == opts.max_rounds);
        }
    }
    // a round limit stops it
    let (_, out) = fixtures().remove(0);
    let few = PageRankOptions {
        max_rounds: 2,
        tolerance: 0.0,
        ..opts
    };
    let got = pagerank(&out, &out.transpose(), &few, &CpuDevice::new(2)).unwrap();
    assert_eq!(got.rounds, 2);
    assert_eq!(got.scores, plain_pagerank(&out, &few).0);
}

#[test]
fn betweenness_equals_brandes_with_a_stack() {
    for (name, out) in fixtures() {
        let inn = out.transpose();
        let n = out.nrows() as u32;
        let sources: Vec<u32> = [0, 3, n / 2, n - 1].into_iter().collect();
        let want = plain_betweenness(&out, &sources);
        for threads in [1, 4] {
            let cpu = CpuDevice::new(threads).with_grain(8);
            let got = betweenness(&out, &inn, &sources, &cpu).unwrap();
            assert_eq!(got.len(), want.len());
            for (v, (g, w)) in got.iter().zip(&want).enumerate() {
                assert!(
                    (g - w).abs() <= 1e-9 * w.abs().max(1.0),
                    "{name} on {threads}: vertex {v}: {g} against {w}"
                );
            }
        }
    }
    let (_, out) = fixtures().remove(2);
    assert!(betweenness(&out, &out.transpose(), &[9], &CpuDevice::new(1)).is_err());
}

#[test]
fn triangles_equal_a_brute_force_count() {
    for (name, out) in fixtures() {
        let und = undirected(&out, &out.transpose()).unwrap();
        for v in 0..und.nrows() {
            let row = und.row(v);
            assert!(
                row.windows(2).all(|w| w[0] < w[1]),
                "{name}: row {v} sorted, once"
            );
            assert!(!row.contains(&(v as u32)), "{name}: no self-loop at {v}");
            assert!(
                row.iter()
                    .all(|&w| und.row(w as usize).contains(&(v as u32)))
            );
        }
        let want = plain_triangles(&out);
        for threads in [1, 5] {
            let cpu = CpuDevice::new(threads).with_grain(8);
            for relabel in [Relabel::Auto, Relabel::Always, Relabel::Never] {
                let got = triangles(&und, relabel, &cpu).unwrap();
                assert_eq!(got.count, want, "{name} on {threads}, {relabel:?}");
                if relabel != Relabel::Auto {
                    assert_eq!(got.relabelled, relabel == Relabel::Always);
                }
            }
        }
    }
    let (_, small) = fixtures().remove(2);
    // the triangle 0-1-2 and the four of the 4-clique 4-5-6-7
    assert_eq!(plain_triangles(&small), 5);
}

/// Larger graphs for the parallel paths: a skewed one with hubs (renumbered gathers in
/// PageRank, pulled levels in betweenness, uneven triangle work), a deep one (more levels
/// than betweenness searches a batch of sources together) and a long one-way path.
fn larger() -> Vec<(&'static str, Csr<u8>)> {
    let mut grid = Vec::new();
    let side = 40u32;
    for r in 0..side {
        for c in 0..side {
            let v = r * side + c;
            if c + 1 < side {
                grid.extend([(v, v + 1), (v + 1, v)]);
            }
            if r + 1 < side && (r * 7 + c) % 5 != 0 {
                grid.extend([(v, v + side), (v + side, v)]);
            }
        }
    }
    let path: Vec<(u32, u32)> = (0..299u32).map(|v| (v, v + 1)).collect();
    vec![
        ("skewed-5000", graph(5000, &skewed(5000, 60000, 11))),
        ("grid-40", graph((side * side) as usize, &grid)),
        ("path-300", graph(300, &path)),
    ]
}

/// Worker counts and pieces small enough that every piece of work is split.
fn devices() -> Vec<CpuDevice> {
    vec![
        CpuDevice::new(1),
        CpuDevice::new(2).with_grain(1),
        CpuDevice::new(5).with_grain(16),
        CpuDevice::new(12).with_grain(64),
    ]
}

#[test]
fn pagerank_equals_gaps_rounds_on_larger_graphs_at_any_worker_count() {
    let opts = PageRankOptions::default();
    for (name, out) in larger() {
        let inn = out.transpose();
        let (want, rounds) = plain_pagerank(&out, &opts);
        for cpu in devices() {
            let got = pagerank(&out, &inn, &opts, &cpu).unwrap();
            assert_eq!(got.rounds, rounds, "{name} on {}", cpu.threads());
            assert_eq!(got.scores, want, "{name} on {}", cpu.threads());
        }
    }
}

#[test]
fn betweenness_equals_brandes_on_larger_graphs_for_any_number_of_sources() {
    for (name, out) in larger() {
        let inn = out.transpose();
        let n = out.nrows() as u32;
        // one, a full batch, and batches with a part left over; a source twice
        let picks: Vec<Vec<u32>> = vec![
            vec![n / 3],
            vec![0, 7, n / 2, n - 1],
            vec![5, 1, n / 4, n / 4, 2 * n / 3, n - 2, 3, n / 5, 9],
        ];
        for sources in picks {
            let want = plain_betweenness(&out, &sources);
            for cpu in devices() {
                let got = betweenness(&out, &inn, &sources, &cpu).unwrap();
                assert_eq!(got.len(), want.len());
                for (v, (g, w)) in got.iter().zip(&want).enumerate() {
                    assert!(
                        (g - w).abs() <= 1e-9 * w.abs().max(1.0),
                        "{name} from {sources:?} on {}: vertex {v}: {g} against {w}",
                        cpu.threads()
                    );
                }
            }
        }
    }
}

#[test]
fn betweenness_is_the_same_at_any_worker_count() {
    for (name, out) in larger() {
        let inn = out.transpose();
        let n = out.nrows() as u32;
        let sources = [2, n / 2, n - 3, n / 7, 11];
        let one = betweenness(&out, &inn, &sources, &CpuDevice::new(1)).unwrap();
        for cpu in devices() {
            let got = betweenness(&out, &inn, &sources, &cpu).unwrap();
            assert_eq!(got, one, "{name} on {}", cpu.threads());
        }
    }
}

#[test]
fn triangles_equal_a_brute_force_count_on_larger_graphs() {
    for (name, out) in larger() {
        let und = undirected(&out, &out.transpose()).unwrap();
        let want = plain_triangles(&out);
        for cpu in devices() {
            for relabel in [Relabel::Auto, Relabel::Always, Relabel::Never] {
                let got = triangles(&und, relabel, &cpu).unwrap();
                assert_eq!(got.count, want, "{name} on {}, {relabel:?}", cpu.threads());
            }
        }
    }
}