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/examples/split_time.rs

//! Times of the computed split: one round's kernel (`GraphBackend::split_votes`) and the
//! whole `computed_split`, on the CPU backend (the device's threads) against the GPU
//! backend, on the benchmark's R-MAT graphs; every GPU answer is checked equal to the CPU's.
//!
//! `cargo run --release -p kleene-cubecl --example split_time -- <scale> [cores] [K...]`
//! (`cores` one count or a list as `6,12`; defaults: 12, K = 4 and 8). Five warm runs of a
//! round, the median; the whole split once per device after a warm-up. The graph is `kleene::synth::rmat(scale, 8, 1)`,
//! the benchmark's. A round's transfer alone (part up, wanted part down) is timed on a
//! cycle of as many nodes, whose kernel has next to nothing to count.

#[path = "../tests/graphs/mod.rs"]
mod graphs;

use std::time::{Duration, Instant};

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

fn load() -> String {
    std::fs::read_to_string("/proc/loadavg")
        .map(|s| s.split_whitespace().take(3).collect::<Vec<_>>().join(" "))
        .unwrap_or_else(|_| "-".into())
}

fn median(mut t: Vec<Duration>) -> f64 {
    t.sort();
    t[t.len() / 2].as_secs_f64() * 1e3
}

fn times<T>(runs: usize, mut f: impl FnMut() -> T) -> (f64, T) {
    let mut ts = Vec::new();
    let mut last = None;
    for _ in 0..runs {
        let t0 = Instant::now();
        last = Some(f());
        ts.push(t0.elapsed());
    }
    (median(ts), last.expect("a run"))
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let scale: u32 = args.first().map_or(16, |s| s.parse().expect("scale"));
    let cores: Vec<usize> = args.get(1).map_or(vec![12], |s| {
        s.split(',').map(|c| c.parse().expect("cores")).collect()
    });
    let threads = *cores.iter().max().expect("a core count");
    let ks: Vec<u32> = if args.len() > 2 {
        args[2..].iter().map(|s| s.parse().expect("K")).collect()
    } else {
        vec![4, 8]
    };
    let t0 = Instant::now();
    let (s, d) = graphs::rmat_edges(scale, 8, 1);
    let n = 1usize << scale;
    let (out, inn) = graphs::graph(n, &s, &d);
    drop((s, d));
    eprintln!("rmat{scale} built in {:.1} s", t0.elapsed().as_secs_f64());
    let cpus: Vec<CpuDevice> = cores.iter().map(|&c| CpuDevice::new(c)).collect();
    let dev = GpuDevice::with_cpu(CpuDevice::new(threads));
    println!(
        "rmat{scale}: {n} nodes, {} edges; CPU {cores:?} cores; GPU {}, {}; load {}",
        out.nnz(),
        dev.name(),
        dev.kind(),
        load()
    );
    println!(
        "  GPU bytes of a round (patterns + part + want): {} MB; on the GPU: {}",
        GpuDevice::split_bytes(n, out.nnz() + inn.nnz()) >> 20,
        dev.split_on_gpu(&out, &inn, 4)
    );
    let (go, gi) = (G::matrix(out.clone(), &dev), G::matrix(inn.clone(), &dev));
    for &k in &ks {
        let part = graphs::parts(n, k, 11);
        let room = vec![65535u32; k as usize];
        let t = Instant::now();
        let first = <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &dev).unwrap();
        let first_ms = t.elapsed().as_secs_f64() * 1e3;
        let (g_ms, got) = times(5, || {
            <G as GraphBackend>::split_votes(&go, &gi, &part, &room, &dev).unwrap()
        });
        println!(
            "  K={k} round: GPU {g_ms:.1} ms (first call with upload and compile {first_ms:.0} ms); load {}",
            load()
        );
        for cpu in &cpus {
            let _ = <C as GraphBackend>::split_votes(&out, &inn, &part, &room, cpu).unwrap();
            let (c_ms, want) = times(5, || {
                <C as GraphBackend>::split_votes(&out, &inn, &part, &room, cpu).unwrap()
            });
            let eq = got == want && first == want;
            println!(
                "  K={k} round: CPU {} cores {c_ms:.1} ms ({:.2}x the GPU); {}; load {}",
                cpu.threads(),
                c_ms / g_ms,
                if eq { "EQUAL" } else { "DIFFERENT" },
                load()
            );
            assert!(eq, "rmat{scale} K={k}: the GPU's round differs");
        }
    }
    for &k in &ks {
        let how = SplitCompute::new(k);
        let (g_ms, g) = times(1, || computed_split::<G>(&go, &gi, &how, &dev).unwrap());
        println!(
            "  K={k} computed_split: GPU {g_ms:.0} ms; {} rounds, {} of {} edges cross ({:.1} %); load {}",
            g.rounds,
            g.crossing_edges,
            out.nnz(),
            100.0 * g.crossing_edges as f64 / out.nnz() as f64,
            load()
        );
        for cpu in &cpus {
            let (c_ms, c) = times(1, || computed_split::<C>(&out, &inn, &how, cpu).unwrap());
            let eq = g.part == c.part
                && g.sizes == c.sizes
                && g.crossing_edges == c.crossing_edges
                && g.rounds == c.rounds;
            let diff = g.part.iter().zip(&c.part).filter(|(a, b)| a != b).count();
            println!(
                "  K={k} computed_split: CPU {} cores {c_ms:.0} ms ({:.2}x the GPU); {} (parts differ at {diff} nodes); load {}",
                cpu.threads(),
                c_ms / g_ms,
                if eq { "EQUAL" } else { "DIFFERENT" },
                load()
            );
            assert!(eq, "rmat{scale} K={k}: the GPU's split differs");
        }
    }
    drop((go, gi));
    // The transfer alone: a cycle of n nodes (2 edges a node), K = 4.
    let src: Vec<u32> = (0..n as u32).collect();
    let dst: Vec<u32> = (0..n as u32).map(|v| (v + 1) % n as u32).collect();
    let (co, ci): (Csr<u8>, Csr<u8>) = graphs::graph(n, &src, &dst);
    let (co, ci) = (G::matrix(co, &dev), G::matrix(ci, &dev));
    let part = graphs::parts(n, 4, 12);
    let room = vec![65535u32; 4];
    let _ = <G as GraphBackend>::split_votes(&co, &ci, &part, &room, &dev).unwrap();
    let (t_ms, _) = times(5, || {
        <G as GraphBackend>::split_votes(&co, &ci, &part, &room, &dev).unwrap()
    });
    println!(
        "  a round on a cycle of {n} nodes (the {} MB up and down, next to no counting): {t_ms:.1} ms; load {}",
        (8 * n) >> 20,
        load()
    );
}