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

nordisk/kleene

crates/kleene-sparse/benches/kernels.rs

//! Kernel timings on every instruction-set level the host has: the word kernels, `mxv_into`
//! and `vxm_into` in steady state, and a whole search of push or pull steps, on one thread
//! and on every core. A plain timing loop (no harness): `cargo bench -p kleene-sparse`,
//! `KLEENE_BENCH_SCALE` (default 20) sets the R-MAT-like graph's 2^scale vertices.

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

use kleene_sparse::{
    BoolOrAnd, CpuBackend, CpuDevice, Csr, KeyCol, Mask, PlusTimes, Simd, SparseBackend, Vector,
};

type B = CpuBackend;

fn median(mut f: impl FnMut(), runs: usize) -> Duration {
    f();
    let mut t: Vec<Duration> = (0..runs)
        .map(|_| {
            let t0 = Instant::now();
            f();
            t0.elapsed()
        })
        .collect();
    t.sort_unstable();
    t[t.len() / 2]
}

fn rmat(scale: u32, factor: usize) -> (usize, Vec<u32>, Vec<u32>) {
    let n = 1usize << scale;
    let mut x = 1u64;
    let mut step = || {
        x = x
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (x >> 33) as u32
    };
    let (mut src, mut dst) = (
        Vec::with_capacity(n * factor),
        Vec::with_capacity(n * factor),
    );
    for _ in 0..n * factor {
        let (mut s, mut d) = (0u32, 0u32);
        for _ in 0..scale {
            let r = step() % 100;
            s = (s << 1) | u32::from((57..76).contains(&r) || r >= 95);
            d = (d << 1) | u32::from(r >= 76);
        }
        src.push(s);
        dst.push(d);
    }
    (n, src, dst)
}

/// The buffers a search keeps.
struct Kept {
    ws: kleene_sparse::CpuWorkspace,
    f: Vector<u8>,
    nx: Vector<u8>,
    open: Mask,
}

fn search(a: &Csr<u8>, at: &Csr<u8>, pull: bool, d: &CpuDevice, k: &mut Kept) -> usize {
    let n = a.nrows();
    let Kept { ws, f, nx, open } = k;
    B::load_indices(f, &[0, 1, 2], 1, d).unwrap();
    B::mask_assign(open, &Mask::all(n), d);
    B::mask_add_vector(open, f);
    let mut reached = f.nvals();
    let mut swaps = 0;
    while f.nvals() > 0 {
        if pull {
            B::step_pull(f, at, open, nx, ws, d).unwrap();
        } else {
            B::step_push(f, a, open, nx, ws, d).unwrap();
        }
        std::mem::swap(f, nx);
        swaps += 1;
        reached += f.nvals();
    }
    if swaps % 2 == 1 {
        std::mem::swap(f, nx);
    }
    reached
}

fn main() {
    let scale: u32 = std::env::var("KLEENE_BENCH_SCALE")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(20);
    let (n, src, dst) = rmat(scale, 8);
    let a = Csr::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let at = a.transpose();
    let s = PlusTimes::<u64>::new();
    let vals: Vec<u64> = (0..a.nnz() as u64).map(|k| k % 7 + 1).collect();
    let av = Csr::with_pattern(a.pattern().clone(), Some(vals.into())).unwrap();
    let x =
        Vector::from_pairs(n, (0..n as u32).step_by(16).map(|i| (i, 1u64)).collect(), s).unwrap();
    let words: Vec<u64> = (0..n as u64 / 64)
        .map(|i| i.wrapping_mul(0x9e3779b97f4a7c15))
        .collect();
    let flat = vals_of(&av);
    // Row columns of n rows (two wide and one narrow key column) and masks of several
    // densities.
    let mut seed = 7u64;
    let mut rnd = move || {
        seed = seed
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        seed ^ (seed >> 29)
    };
    let c0: Vec<u64> = (0..n).map(|_| rnd()).collect();
    let c1: Vec<u32> = (0..n).map(|_| rnd() as u32).collect();
    let c2: Vec<u64> = (0..n).map(|_| rnd() % 1000).collect();
    let half: Vec<bool> = (0..n).map(|_| rnd() % 2 == 0).collect();
    let sixteenth: Vec<bool> = (0..n).map(|_| rnd() % 16 == 0).collect();
    let eighth: Vec<bool> = (0..n).map(|_| rnd() % 8 == 0).collect();
    let sixty_fourth: Vec<bool> = (0..n).map(|_| rnd() % 64 == 0).collect();
    let bits_of = |m: &[bool]| -> Vec<u64> {
        m.chunks(64)
            .map(|c| {
                c.iter()
                    .enumerate()
                    .fold(0u64, |w, (b, &k)| w | (k as u64) << b)
            })
            .collect()
    };
    let (half_bits, eighth_bits, sixteenth_bits, sixty_fourth_bits) = (
        bits_of(&half),
        bits_of(&eighth),
        bits_of(&sixteenth),
        bits_of(&sixty_fourth),
    );
    let threads = std::thread::available_parallelism().map_or(1, |t| t.get());
    println!(
        "R-MAT-like scale {scale}: {n} vertices, {} edges; levels {:?}; {threads} cores",
        a.nnz(),
        Simd::available()
    );
    println!(
        "{:<34} {:>8} {:>8} {:>12}",
        "kernel", "level", "threads", "median"
    );
    for level in Simd::available() {
        let simd = Simd::with_level(level).unwrap();
        let mut w2 = words.clone();
        let row = |name: &str, th: usize, d: Duration| {
            println!(
                "{name:<34} {:>8} {th:>8} {:>9.3} ms",
                format!("{level:?}"),
                d.as_secs_f64() * 1e3
            );
        };
        row(
            "popcount (n/64 words)",
            1,
            median(
                || {
                    std::hint::black_box(simd.popcount(&words));
                },
                21,
            ),
        );
        row(
            "or_assign (n/64 words)",
            1,
            median(|| simd.or_assign(&mut w2, &words), 21),
        );
        row(
            "fold min (nnz u64)",
            1,
            median(
                || {
                    std::hint::black_box(simd.fold(&flat, u64::MAX, u64::min));
                },
                11,
            ),
        );
        let cols = [KeyCol::U64(&c0), KeyCol::U32(&c1), KeyCol::U64(&c2)];
        let mut h = vec![0u64; n];
        row(
            "hash_rows (3 key columns, n)",
            1,
            median(|| simd.hash_rows(&cols, 0, &mut h), 11),
        );
        let mut g32 = vec![0u32; n];
        for (name, m) in [
            ("compact_bools (n, kept 1/2)", &half),
            ("compact_bools (n, kept 1/8)", &eighth),
            ("compact_bools (n, kept 1/16)", &sixteenth),
            ("compact_bools (n, kept 1/64)", &sixty_fourth),
        ] {
            row(
                name,
                1,
                median(
                    || {
                        std::hint::black_box(simd.compact_bools(m, 0, &mut g32));
                    },
                    11,
                ),
            );
        }
        for (name, w) in [
            ("bits_to_places (n, set 1/2)", &half_bits),
            ("bits_to_places (n, set 1/8)", &eighth_bits),
            ("bits_to_places (n, set 1/16)", &sixteenth_bits),
            ("bits_to_places (n, set 1/64)", &sixty_fourth_bits),
        ] {
            row(
                name,
                1,
                median(
                    || {
                        std::hint::black_box(simd.bits_to_places(w, 0, &mut g32));
                    },
                    11,
                ),
            );
        }
        for (name, col, lo, hi) in [
            (
                "select_range (n u64, kept 1/2)",
                KeyCol::U64(&c0),
                0,
                u64::MAX / 2,
            ),
            (
                "select_range (n u64, kept 1/16)",
                KeyCol::U64(&c0),
                0,
                u64::MAX / 16,
            ),
            (
                "select_range (n u32, kept 1/2)",
                KeyCol::U32(&c1),
                0,
                u64::from(u32::MAX / 2),
            ),
            (
                "select_range (n u32, kept 1/16)",
                KeyCol::U32(&c1),
                0,
                u64::from(u32::MAX / 16),
            ),
        ] {
            row(
                name,
                1,
                median(
                    || {
                        std::hint::black_box(simd.select_range(col, lo, hi, true, 0, &mut g32));
                    },
                    11,
                ),
            );
        }
        for th in [1, threads] {
            let d = CpuDevice::new(th).with_simd(simd);
            let mut ws = B::workspace(n, &d);
            let mut y = Vector::empty(n);
            row(
                "mxv_into plus-times (x 1/16)",
                th,
                median(
                    || B::mxv_into(&av, &x, None, s, &mut y, &mut ws, &d).unwrap(),
                    7,
                ),
            );
            row(
                "vxm_into plus-times (x 1/16)",
                th,
                median(
                    || B::vxm_into(&x, &av, None, s, &mut y, &mut ws, &d).unwrap(),
                    7,
                ),
            );
            let mut k = Kept {
                ws,
                f: Vector::empty(n),
                nx: Vector::empty(n),
                open: Mask::all(n),
            };
            for pull in [false, true] {
                let name = if pull {
                    "search, pull steps"
                } else {
                    "search, push steps"
                };
                row(
                    name,
                    th,
                    median(
                        || {
                            search(&a, &at, pull, &d, &mut k);
                        },
                        5,
                    ),
                );
            }
        }
    }
}

fn vals_of(a: &Csr<u64>) -> Vec<u64> {
    a.values().map(|v| v.to_vec()).unwrap_or_default()
}