Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-cubecl/tests/split.rs

//! The computed split on the GPU against the CPU: a round's list of wanted parts
//! (`GraphBackend::split_votes`) is the CPU kernel's bit for bit, and the whole
//! `computed_split` gives the same parts, crossing edges and rounds.
//!
//! These tests open a GPU, so they run only with `KLEENE_GPU=1` (and only on a host whose
//! GPU may be used); without it each returns at once. A software device (Vulkan on the
//! CPU) fails them unless `KLEENE_GPU_SOFTWARE=1`.

mod graphs;

use kleene_cubecl::{CpuBelow, GpuBackend as G, GpuDevice};
use kleene_graph::{GraphBackend, SplitCompute, computed_split};
use kleene_sparse::{CpuBackend as C, CpuDevice, Csr, SparseBackend};

/// A device whose split rounds all run on the GPU, whatever the graph's size.
fn gpu() -> Option<GpuDevice> {
    (std::env::var("KLEENE_GPU").as_deref() == Ok("1")).then(|| {
        let d = GpuDevice::with_cpu(CpuDevice::new(4));
        let kind = d.kind();
        eprintln!("GPU: {}, {kind}", d.name());
        if kind.is_software() {
            assert!(
                std::env::var("KLEENE_GPU_SOFTWARE").as_deref() == Ok("1"),
                "SOFTWARE DEVICE: {} is Vulkan on the CPU, NOT A GPU",
                d.name()
            );
        }
        d.set_cpu_below(CpuBelow::NEVER);
        d
    })
}

/// A named graph and its transpose.
type Case = (&'static str, (Csr<u8>, Csr<u8>));

fn cases() -> Vec<Case> {
    vec![
        ("rmat16", graphs::rmat(16)),
        ("road256", graphs::road(256)),
        ("grouped", graphs::grouped()),
        ("isolated", graphs::isolated()),
    ]
}

/// The round's list on the GPU equals the CPU kernel's and the plain rule's, for K = 2, 4,
/// 7 and 64, from random parts and rooms (with zero and equal rooms: ties) and from every
/// node in part 0; and the GPU ran it (kernels were launched).
#[test]
fn a_round_on_the_gpu_is_the_cpu_round() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    for (name, (out, inn)) in cases() {
        let n = out.nrows();
        let (go, gi) = (G::matrix(out.clone(), &d), G::matrix(inn.clone(), &d));
        for k in [2u32, 4, 7, 64] {
            assert!(
                d.split_on_gpu(&out, &inn, k as usize),
                "{name} K={k} on the GPU"
            );
            for (seed, zero) in [(1u64, false), (2, false), (3, true)] {
                let part = if zero {
                    vec![0u32; n]
                } else {
                    graphs::parts(n, k, seed * 31 + k as u64)
                };
                let room = graphs::rooms(k, seed * 17 + k as u64);
                let want = <C as GraphBackend>::split_votes(&out, &inn, &part, &room, &cpu)
                    .expect("cpu round");
                assert_eq!(
                    want,
                    graphs::plain_votes(&out, &inn, &part, &room),
                    "{name} K={k} seed {seed}: the CPU kernel against the plain rule"
                );
                let before = d.launches();
                let got = <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &d)
                    .expect("gpu round");
                assert!(d.launches() > before, "{name} K={k}: the GPU ran no kernel");
                let differ = got.iter().zip(&want).filter(|(a, b)| a != b).count();
                assert_eq!(
                    differ, 0,
                    "{name} ({n} nodes) K={k} seed {seed}: {differ} nodes differ"
                );
                assert_eq!(got, want);
                let moved = want.iter().zip(&part).filter(|(a, b)| a != b).count();
                eprintln!("{name} ({n} nodes) K={k} seed {seed}: EQUAL, {moved} want to move");
            }
        }
    }
}

/// A node of many edges (past the one-unit rows) votes as the CPU says.
#[test]
fn a_hub_votes_as_on_the_cpu() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    let n = 300_000usize;
    let mut src: Vec<u32> = (1..n as u32).map(|_| 0).collect();
    let mut dst: Vec<u32> = (1..n as u32).collect();
    src.extend(1..20_000u32);
    dst.extend((1..20_000u32).map(|v| (v * 7) % n as u32));
    let (out, inn) = graphs::graph(n, &src, &dst);
    let (go, gi) = (G::matrix(out.clone(), &d), G::matrix(inn.clone(), &d));
    for k in [2u32, 4, 7, 64] {
        let part = graphs::parts(n, k, 5 + k as u64);
        let room = graphs::rooms(k, 9 + k as u64);
        let want = <C as GraphBackend>::split_votes(&out, &inn, &part, &room, &cpu).unwrap();
        let got = <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &d).unwrap();
        assert_eq!(got, want, "hub K={k}");
    }
}

/// The whole computed split on the GPU backend equals the CPU backend's: the same part per
/// node, sizes, crossing edges and rounds.
#[test]
fn the_computed_split_on_the_gpu_is_the_cpus() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    for (name, (out, inn)) in cases() {
        let (go, gi) = (G::matrix(out.clone(), &d), G::matrix(inn.clone(), &d));
        for k in [2u32, 4, 7, 64] {
            let how = SplitCompute::new(k);
            let c = computed_split::<C>(&out, &inn, &how, &cpu).expect("cpu split");
            let before = d.launches();
            let g = computed_split::<G>(&go, &gi, &how, &d).expect("gpu split");
            assert!(d.launches() > before, "{name} K={k}: the GPU ran no kernel");
            assert_eq!(g.part, c.part, "{name} K={k}: parts");
            assert_eq!(g.sizes, c.sizes, "{name} K={k}: sizes");
            assert_eq!(g.crossing_edges, c.crossing_edges, "{name} K={k}: crossing");
            assert_eq!(g.rounds, c.rounds, "{name} K={k}: rounds");
            eprintln!(
                "{name} K={k}: EQUAL, {} crossing of {} edges, {} rounds",
                c.crossing_edges,
                out.nnz(),
                c.rounds
            );
        }
    }
}

/// Below the threshold, past 64 parts, or for a list of parts out of range, the CPU
/// kernel answers (no GPU kernel runs), with the CPU's list or error.
#[test]
fn the_cpu_answers_what_the_gpu_does_not_take() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    let (out, inn) = graphs::road(64);
    let n = out.nrows();
    let (go, gi) = (G::matrix(out.clone(), &d), G::matrix(inn.clone(), &d));
    // Past 64 parts.
    let part = graphs::parts(n, 65, 1);
    let room = graphs::rooms(65, 2);
    assert!(!d.split_on_gpu(&out, &inn, 65));
    let before = d.launches();
    let got = <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &d);
    assert_eq!(d.launches(), before, "65 parts ran on the GPU");
    let want = <C as GraphBackend>::split_votes(&out, &inn, &part, &room, &cpu);
    assert!(want.is_err(), "the CPU kernel takes at most 64 parts");
    assert_eq!(format!("{got:?}"), format!("{want:?}"));
    // Below the threshold.
    d.set_cpu_below(CpuBelow::all(out.nnz() + 1));
    assert!(!d.split_on_gpu(&out, &inn, 4));
    let part = graphs::parts(n, 4, 3);
    let room = graphs::rooms(4, 4);
    let before = d.launches();
    let got = <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &d).unwrap();
    assert_eq!(d.launches(), before, "a small graph ran on the GPU");
    let want = <C as GraphBackend>::split_votes(&out, &inn, &part, &room, &cpu).unwrap();
    assert_eq!(got, want);
    d.set_cpu_below(CpuBelow::NEVER);
    // A part out of range: the CPU's answer (its error or its list).
    let mut bad = part.clone();
    bad[0] = 9;
    let before = d.launches();
    let got = <G as GraphBackend>::split_votes(&go, &gi, &bad, &room, &d);
    assert_eq!(d.launches(), before, "a bad list ran on the GPU");
    let want = <C as GraphBackend>::split_votes(&out, &inn, &bad, &room, &cpu);
    assert_eq!(format!("{got:?}"), format!("{want:?}"));
}