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

//! The GPU backend against the CPU backend: every operation on GPU vectors and masks, and
//! every kleene-graph algorithm (through the trait and whole on the GPU), gives the same
//! answer.
//!
//! 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. The ones that open none (the
//! defaults by kind, `the_search_moves_by_frontier_and_depth`) always run.

use arrow_buffer::ScalarBuffer;
use kleene_cubecl::{CpuBelow, GpuBackend as G, GpuDevice, GpuKind, PAGERANK_L1};
use kleene_graph::{
    BfsOptions, Direction, Graph, PageRank, PageRankOptions, SsspOptions, bfs, components_of,
    components_of_generic, pagerank, pagerank_of, reach_sets, scc_of, sssp_of,
};
use kleene_sparse::{
    BitsetUnion, BoolOrAnd, CpuBackend as C, CpuDevice, Csr, Mask, MinPlus, Semiring,
    SparseBackend, Value, Vector,
};

/// A device whose algorithms all run on the GPU, whatever the graph's size, so the
/// kernels themselves are what the tests compare.
fn gpu() -> Option<GpuDevice> {
    gpu_default().inspect(|d| d.set_cpu_below(CpuBelow::NEVER))
}

/// A device with the measured small-graph thresholds. Its adapter and kind are printed;
/// a software device (Vulkan on the CPU) fails the test unless `KLEENE_GPU_SOFTWARE=1`
/// asks for it, so a run that found no GPU cannot pass as a GPU run.
fn gpu_default() -> Option<GpuDevice> {
    (std::env::var("KLEENE_GPU").as_deref() == Ok("1")).then(|| {
        let d = GpuDevice::with_cpu(CpuDevice::new(4));
        checked(&d);
        d
    })
}

fn checked(d: &GpuDevice) {
    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; set KLEENE_GPU_SOFTWARE=1 to test on it",
            d.name()
        );
    }
}

/// An integrated GPU takes every algorithm to the CPU but the source sets (from 2000000
/// edges); every other kind keeps the defaults measured on a discrete GPU.
#[test]
fn the_defaults_follow_the_kind() {
    assert_eq!(
        CpuBelow::for_kind(GpuKind::Integrated),
        CpuBelow::INTEGRATED
    );
    assert_eq!(CpuBelow::INTEGRATED.sets, 2_000_000);
    assert_eq!(CpuBelow::INTEGRATED.bfs, usize::MAX, "searches on the CPU");
    assert_eq!(CpuBelow::default().bfs, 1 << 22);
    assert_eq!(CpuBelow::default().bfs_frontier, 1 << 14);
    assert_eq!(CpuBelow::default().bfs_depth, 16);
    assert_eq!(CpuBelow::NEVER.bfs_frontier, 0, "NEVER moves no search");
    for k in [
        GpuKind::Discrete,
        GpuKind::Virtual,
        GpuKind::Other,
        GpuKind::Software,
    ] {
        assert_eq!(CpuBelow::for_kind(k), CpuBelow::default(), "{k}");
    }
    assert_eq!(CpuBelow::default().components, 1 << 17);
    assert_eq!(CpuBelow::default().pagerank, 1 << 17);
}

/// A device opened on an integrated GPU answers small and middle graphs on the CPU (no
/// kernel runs) for components, strong components, shortest paths, PageRank and the sets
/// below their threshold; a discrete one keeps the measured thresholds and runs them on
/// the GPU; `set_cpu_below` overrides either.
#[test]
fn an_integrated_gpu_leaves_the_graphs_to_the_cpu() {
    if std::env::var("KLEENE_GPU").as_deref() != Ok("1") {
        return;
    }
    if std::env::var_os("KLEENE_GPU_CPU_BELOW_EDGES").is_some() {
        return;
    }
    let cpu = CpuDevice::new(4);
    let n = 60_000usize;
    let (src, dst) = edges(n as u32, 400_000, 7);
    let out = Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let inn = out.transpose();
    let w: Vec<u32> = (0..out.nnz() as u32).map(|k| k % 17 + 1).collect();
    let wm = Csr::with_pattern(out.pattern().clone(), Some(ScalarBuffer::from(w))).unwrap();
    let srcs: Vec<u32> = (0..64).map(|k| (k * 937 % n) as u32).collect();
    let o = SsspOptions::default();
    let want_cc = components_of::<C>(&out, &inn, &cpu).unwrap().of;
    let want_scc = scc_of::<C>(&out, &inn, &cpu).unwrap().of;
    let want_pr = pagerank(&out, &inn, &PageRankOptions::default(), &cpu).unwrap();
    // (algorithm, kernels it launched, answer equal to the CPU's)
    let run = |d: &GpuDevice| {
        let mut r = Vec::new();
        let mut step = |name: &'static str, f: &dyn Fn() -> bool| {
            let before = d.launches();
            let ok = f();
            r.push((name, d.launches() - before, ok));
        };
        step("cc", &|| {
            components_of::<G>(&out, &inn, d).unwrap().of == want_cc
        });
        step("scc", &|| {
            scc_of::<G>(&out, &inn, d).unwrap().of == want_scc
        });
        step("sssp", &|| {
            let (g, c) = (
                sssp_of::<G>(&wm, None, 0, &o, d).unwrap(),
                sssp_of::<C>(&wm, None, 0, &o, &cpu).unwrap(),
            );
            (0..n as u32).all(|v| g.distance(v) == c.distance(v))
        });
        step("pagerank", &|| {
            let g = pagerank_of::<G>(&out, &inn, &PageRankOptions::default(), d).unwrap();
            g.rounds == want_pr.rounds
        });
        step("sets", &|| {
            let (g, c) = (
                reach_sets::<G>(&out, &srcs, d).unwrap(),
                reach_sets::<C>(&out, &srcs, &cpu).unwrap(),
            );
            (0..n as u32).all(|v| g.sources_of(v) == c.sources_of(v))
        });
        r
    };
    let mut seen = 0;
    if let Some(d) = GpuDevice::with_cpu_on(CpuDevice::new(4), GpuKind::Integrated) {
        seen += 1;
        assert_eq!(d.cpu_below(), CpuBelow::INTEGRATED, "{}", d.name());
        for (name, k, ok) in run(&d) {
            assert!(ok, "integrated {name}: answer");
            assert_eq!(
                k,
                0,
                "integrated {name}: {k} kernels on {} edges",
                out.nnz()
            );
        }
        d.set_cpu_below(CpuBelow::NEVER);
        for (name, k, ok) in run(&d) {
            assert!(
                ok && k > 0,
                "integrated, overridden: {name} ran {k} kernels"
            );
        }
    }
    if let Some(d) = GpuDevice::with_cpu_on(CpuDevice::new(4), GpuKind::Discrete) {
        seen += 1;
        assert_eq!(d.cpu_below(), CpuBelow::default(), "{}", d.name());
        for (name, k, ok) in run(&d) {
            assert!(ok, "discrete {name}: answer");
            // 400000 edges: over the discrete thresholds of cc (131072), sets (262144) and
            // PageRank (131072), under those of scc (1048576) and paths (2000000).
            let gpu = matches!(name, "cc" | "sets" | "pagerank");
            assert_eq!(k > 0, gpu, "discrete {name}: {k} kernels");
        }
    }
    eprintln!("kinds checked: {seen}");
}

/// Each kind of adapter the machine has opens as that kind, under its own name, and runs
/// the kernels to the CPU's answers; the default device is the most capable kind there is
/// (unless `CUBECL_WGPU_DEFAULT_DEVICE` names one).
#[test]
fn every_adapter_names_itself_and_its_kind() {
    let Some(d) = gpu_default() else { return };
    let cpu = CpuDevice::new(4);
    let (src, dst) = edges(500, 1500, 1);
    let out = Csr::<u8>::from_edges(500, 500, &src, &dst, None, BoolOrAnd).unwrap();
    let inn = out.transpose();
    let want = components_of::<C>(&out, &inn, &cpu).unwrap().of;
    let mut found = Vec::new();
    for kind in GpuKind::ALL {
        let Some(k) = GpuDevice::with_cpu_on(CpuDevice::new(4), kind) else {
            continue;
        };
        k.set_cpu_below(CpuBelow::NEVER);
        assert_eq!(k.kind(), kind, "{} opened as {kind}", k.name());
        eprintln!("  has: {}, {}", k.name(), k.kind());
        assert_eq!(
            components_of::<G>(&out, &inn, &k).unwrap().of,
            want,
            "{kind}"
        );
        assert!(k.launches() > 0, "{kind}: no kernel ran");
        found.push(kind);
    }
    if std::env::var_os("CUBECL_WGPU_DEFAULT_DEVICE").is_none() {
        assert_eq!(
            found.first(),
            Some(&d.kind()),
            "the default is the most capable kind"
        );
    } else {
        assert!(
            found.contains(&d.kind()),
            "the adapter named is one of them"
        );
    }
}

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

fn edges(n: u32, m: usize, seed: u64) -> (Vec<u32>, Vec<u32>) {
    let mut r = Lcg(seed);
    (0..m).map(|_| (r.next(n), r.next(n))).unzip()
}

fn pairs<T: Value>(v: &Vector<T>) -> Vec<(u32, T)> {
    v.iter().collect()
}

fn ops<S: Semiring>(s: S, n: usize, valued: bool, value: impl Fn(u32) -> S::T, d: &GpuDevice) {
    let cpu = CpuDevice::new(4);
    let (src, dst) = edges(n as u32, n * 6, 3);
    let w: Vec<S::T> = (0..src.len() as u32).map(&value).collect();
    let a: Csr<S::T> = Csr::from_edges(n, n, &src, &dst, valued.then_some(&w[..]), s).unwrap();
    let mut r = Lcg(9);
    let mk = |r: &mut Lcg, k: usize| {
        let p: Vec<(u32, S::T)> = (0..k)
            .map(|_| {
                let i = r.next(n as u32);
                (i, value(i))
            })
            .collect();
        Vector::from_pairs(n, p, s).unwrap()
    };
    let x = mk(&mut r, n / 3);
    let y = mk(&mut r, n / 2);
    let half: Vec<u32> = (0..n as u32).filter(|v| v % 3 != 0).collect();
    let masks = [
        None,
        Some(Mask::from_indices(n, &half)),
        Some(Mask::from_indices(n, &half).complement()),
    ];
    let ga = G::matrix(a.clone(), d);
    let gx = G::vector(x.clone(), d);
    assert_eq!(pairs(&G::vector_to_host(&gx)), pairs(&x), "upload and back");
    assert_eq!(G::nvals(&gx), x.nvals());
    assert_eq!(G::indices(&gx), x.indices());
    for m in &masks {
        let gm = m.as_ref().map(|m| G::mask(m.clone(), d));
        if let (Some(m), Some(g)) = (m, &gm) {
            assert_eq!(G::mask_count(g), C::mask_count(m));
            assert_eq!(G::mask_to_host(g).count(), m.count());
        }
        let want = C::mxv(&a, &x, m.as_ref(), s, &cpu).unwrap();
        let got = G::vector_to_host(&G::mxv(&ga, &gx, gm.as_ref(), s, d).unwrap());
        assert_eq!(pairs(&got), pairs(&want), "mxv {s:?} valued {valued}");
        let want = C::vxm(&x, &a, m.as_ref(), s, &cpu).unwrap();
        let gv = G::vxm(&gx, &ga, gm.as_ref(), s, d).unwrap();
        assert_eq!(G::nvals(&gv), want.nvals());
        assert_eq!(pairs(&G::vector_to_host(&gv)), pairs(&want), "vxm {s:?}");
        assert_eq!(G::row_lengths_at(&ga, &gv), C::row_lengths_at(&a, &want));
    }
    // Accumulate, chained on the GPU, and assignment.
    let (mut wc, mut wg) = (y.clone(), G::vector(y.clone(), d));
    let cc = C::accumulate(&mut wc, &x, s).unwrap();
    let cg = G::accumulate(&mut wg, &gx, s).unwrap();
    assert_eq!(
        pairs(&G::vector_to_host(&cg)),
        pairs(&cc),
        "accumulate {s:?}"
    );
    assert_eq!(pairs(&G::vector_to_host(&wg)), pairs(&wc));
    let mut lc = Vector::<u32>::empty(n);
    let mut lg = G::vector(Vector::<u32>::empty(n), d);
    C::assign_scalar(&mut lc, &x, 7, 0);
    G::assign_scalar(&mut lg, &gx, 7, 0);
    assert_eq!(pairs(&G::vector_to_host(&lg)), pairs(&lc));
    let mut mc = Mask::from_indices(n, &half).complement();
    let mut mg = G::mask(mc.clone(), d);
    C::mask_add_vector(&mut mc, &x);
    G::mask_add_vector(&mut mg, &gx);
    assert_eq!(G::mask_count(&mg), C::mask_count(&mc));
    assert_eq!(
        G::mask_count(&G::mask_from_vector(&gx)),
        C::mask_count(&C::mask_from_vector(&x))
    );
    // A fallback (a closure) round trip.
    let sel = G::select_vector(&gx, |i, _| i % 2 == 0);
    assert_eq!(
        pairs(&G::vector_to_host(&sel)),
        pairs(&C::select_vector(&x, |i, _| i % 2 == 0))
    );
}

#[test]
fn every_operation_agrees_with_the_cpu() {
    let Some(d) = gpu() else { return };
    eprintln!("GPU: {}", d.name());
    for n in [1usize, 37, 3000, 70_001] {
        ops(MinPlus::<u32>::new(), n, false, |i| i % 50, &d);
        ops(MinPlus::<u32>::new(), n, true, |i| i % 50 + 1, &d);
        ops(
            MinPlus::<u64>::new(),
            n,
            true,
            |i| ((i % 64 + 1) as u64) << 32 | i as u64,
            &d,
        );
        ops(BoolOrAnd, n, false, |_| 1u8, &d);
        ops(BitsetUnion, n, false, |i| 1u64 << (i % 64) | 1 << 40, &d);
    }
    assert!(d.launches() > 500, "only {} kernels ran", d.launches());
}

#[test]
fn the_graph_algorithms_agree_with_the_cpu() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    for (n, m, seed) in [(1usize, 1usize, 5u64), (500, 1500, 1), (60_000, 400_000, 2)] {
        let (src, dst) = edges(n as u32, m, seed);
        let out = Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
        let inn = out.transpose();
        for dir in [Direction::Push, Direction::Pull, Direction::Auto] {
            let opts = BfsOptions {
                direction: dir,
                ..BfsOptions::default()
            };
            let gc = Graph::<C>::with_transpose(out.clone(), inn.clone(), &cpu).unwrap();
            let gg = Graph::<G>::with_transpose(out.clone(), inn.clone(), &d).unwrap();
            let want = bfs(&gc, &[0, 7 % n as u32], &opts, &cpu).unwrap();
            let got = bfs(&gg, &[0, 7 % n as u32], &opts, &d).unwrap();
            assert_eq!(
                pairs(&C::vector_to_host(&want.levels)),
                pairs(&G::vector_to_host(&got.levels)),
                "bfs {dir:?}"
            );
            assert_eq!(want.steps, got.steps, "bfs steps {dir:?}");
        }
        let cc = components_of::<C>(&out, &inn, &cpu).unwrap().of;
        assert_eq!(cc, components_of::<G>(&out, &inn, &d).unwrap().of, "cc");
        // The algorithm written over the trait, on GPU vectors.
        assert_eq!(cc, components_of_generic::<G>(&out, &inn, &d).unwrap().of);
        assert_eq!(
            scc_of::<C>(&out, &inn, &cpu).unwrap().of,
            scc_of::<G>(&out, &inn, &d).unwrap().of,
            "scc"
        );
        let srcs: Vec<u32> = (0..100).map(|k| (k * 13 % n) as u32).collect();
        let (a, b) = (
            reach_sets::<C>(&out, &srcs, &cpu).unwrap(),
            reach_sets::<G>(&out, &srcs, &d).unwrap(),
        );
        for v in 0..n as u32 {
            assert_eq!(a.sources_of(v), b.sources_of(v), "sets");
        }
        let w: Vec<u32> = (0..out.nnz() as u32).map(|k| k % 17 + 1).collect();
        let wm = Csr::with_pattern(out.pattern().clone(), Some(ScalarBuffer::from(w))).unwrap();
        let hops: Csr<u32> = Csr::with_pattern(out.pattern().clone(), None).unwrap();
        for (m, label) in [(&wm, "weighted"), (&hops, "hops")] {
            for delta in [None, Some(1), Some(40)] {
                let o = SsspOptions {
                    delta,
                    ..SsspOptions::default()
                };
                let p = sssp_of::<C>(m, None, 0, &o, &cpu).unwrap();
                let q = sssp_of::<G>(m, None, 0, &o, &d).unwrap();
                for v in 0..n as u32 {
                    assert_eq!(
                        (p.distance(v), p.parent(v)),
                        (q.distance(v), q.parent(v)),
                        "sssp {label} delta {delta:?} at {v}"
                    );
                }
            }
        }
    }
    assert!(d.launches() > 100, "only {} kernels ran", d.launches());
}

/// A graph bigger than the cache's budget is uploaded once while something holds it: the
/// cache's budget counts only the parts nothing else holds, so a search's matrices, still
/// held by its graph, are never put out and uploaded again (on rmat26 that cost seconds a
/// call). A part nothing holds stays while it fits the budget.
#[test]
fn a_held_graph_over_the_budget_is_uploaded_once() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    let (n, m) = (60_000usize, 400_000usize);
    let (src, dst) = edges(n as u32, m, 2);
    let out = Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let inn = out.transpose();
    let w: Vec<u32> = (0..out.nnz() as u32).map(|k| k % 17 + 1).collect();
    let wm = Csr::with_pattern(out.pattern().clone(), Some(ScalarBuffer::from(w))).unwrap();
    // The narrowed weights fit the budget; with the two patterns the cache holds more.
    d.set_cache_budget(4 * out.nnz() + 1024);
    assert_eq!(d.cache_budget(), 4 * out.nnz() + 1024);
    let gg = Graph::<G>::with_transpose(out.clone(), inn.clone(), &d).unwrap();
    let o = SsspOptions::default();
    let want_bfs = bfs(
        &Graph::<C>::with_transpose(out.clone(), inn.clone(), &cpu).unwrap(),
        &[0],
        &BfsOptions::default(),
        &cpu,
    )
    .unwrap();
    let want_cc = components_of::<C>(&out, &inn, &cpu).unwrap().of;
    let want_scc = scc_of::<C>(&out, &inn, &cpu).unwrap().of;
    let p = sssp_of::<C>(&wm, None, 0, &o, &cpu).unwrap();
    let want_paths: Vec<_> = (0..n as u32)
        .map(|v| (p.distance(v), p.parent(v)))
        .collect();
    let mut first = None;
    for round in 0..3 {
        // Pushed and pulled, so the graph holds both of its matrices on the GPU.
        for direction in [Direction::Push, Direction::Pull] {
            let opts = BfsOptions {
                direction,
                ..BfsOptions::default()
            };
            let got = bfs(&gg, &[0], &opts, &d).unwrap();
            assert_eq!(
                pairs(&C::vector_to_host(&want_bfs.levels)),
                pairs(&G::vector_to_host(&got.levels)),
                "bfs {direction:?} round {round}"
            );
        }
        assert_eq!(components_of::<G>(&out, &inn, &d).unwrap().of, want_cc);
        assert_eq!(scc_of::<G>(&out, &inn, &d).unwrap().of, want_scc);
        let q = sssp_of::<G>(&wm, None, 0, &o, &d).unwrap();
        let paths: Vec<_> = (0..n as u32)
            .map(|v| (q.distance(v), q.parent(v)))
            .collect();
        assert_eq!(paths, want_paths, "sssp round {round}");
        let up = d.uploaded_bytes();
        match first {
            None => first = Some(up),
            Some(f) => assert_eq!(up, f, "round {round} uploaded again"),
        }
    }
    let f = first.unwrap() as usize;
    assert!(
        f >= 2 * 4 * (n + 1 + out.nnz()),
        "both patterns went up ({f} bytes)"
    );
    assert!(f > d.cache_budget(), "the graph is over the budget");
}

/// Every whole algorithm on a graph below its threshold runs on the CPU device: the same
/// answers as the CPU's, and not one GPU kernel. At the threshold it runs on the GPU.
#[test]
fn small_graphs_take_the_host_path() {
    let Some(d) = gpu_default() else { return };
    let cpu = CpuDevice::new(4);
    let (n, m) = (500usize, 1500usize);
    let (src, dst) = edges(n as u32, m, 1);
    let out = Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap();
    let inn = out.transpose();
    let w: Vec<u32> = (0..out.nnz() as u32).map(|k| k % 17 + 1).collect();
    let wm = Csr::with_pattern(out.pattern().clone(), Some(ScalarBuffer::from(w))).unwrap();
    let srcs: Vec<u32> = (0..70).map(|k| (k * 13 % n) as u32).collect();
    let o = SsspOptions::default();
    let all = |d: &GpuDevice| {
        let cc = components_of::<G>(&out, &inn, d).unwrap().of;
        let scc = scc_of::<G>(&out, &inn, d).unwrap().of;
        let p = sssp_of::<G>(&wm, None, 0, &o, d).unwrap();
        let paths: Vec<_> = (0..n as u32)
            .map(|v| (p.distance(v), p.parent(v)))
            .collect();
        let s = reach_sets::<G>(&out, &srcs, d).unwrap();
        let sets: Vec<_> = (0..n as u32).map(|v| s.sources_of(v)).collect();
        let pr = pagerank_of::<G>(&out, &inn, &PageRankOptions::default(), d).unwrap();
        (cc, scc, paths, sets, pr)
    };
    let want = {
        let p = sssp_of::<C>(&wm, None, 0, &o, &cpu).unwrap();
        let s = reach_sets::<C>(&out, &srcs, &cpu).unwrap();
        (
            components_of::<C>(&out, &inn, &cpu).unwrap().of,
            scc_of::<C>(&out, &inn, &cpu).unwrap().of,
            (0..n as u32)
                .map(|v| (p.distance(v), p.parent(v)))
                .collect::<Vec<_>>(),
            (0..n as u32).map(|v| s.sources_of(v)).collect::<Vec<_>>(),
            pagerank(&out, &inn, &PageRankOptions::default(), &cpu).unwrap(),
        )
    };
    let below = d.cpu_below();
    assert!(
        [
            below.components,
            below.strong,
            below.paths,
            below.sets,
            below.pagerank
        ]
        .iter()
        .all(|&e| e > out.nnz()),
        "the measured thresholds {below:?} are above {} edges",
        out.nnz()
    );
    let before = d.launches();
    assert_eq!(all(&d), want, "host path");
    assert_eq!(d.launches(), before, "no GPU kernel below the thresholds");
    d.set_cpu_below(CpuBelow::all(out.nnz()));
    assert_eq!(d.cpu_below(), CpuBelow::all(out.nnz()));
    let got = all(&d);
    assert_eq!(
        (&got.0, &got.1, &got.2, &got.3),
        (&want.0, &want.1, &want.2, &want.3),
        "GPU path"
    );
    assert_close(&got.4, &want.4, "pagerank at the threshold");
    assert!(d.launches() > before, "at the threshold the GPU runs");
}

/// The GPU's PageRank is the CPU's within [`PAGERANK_L1`], in the same rounds.
fn assert_close(got: &PageRank, want: &PageRank, what: &str) {
    assert_eq!(got.rounds, want.rounds, "{what}: rounds");
    assert_eq!(got.scores.len(), want.scores.len(), "{what}: vertices");
    let l1: f64 = got
        .scores
        .iter()
        .zip(&want.scores)
        .map(|(g, w)| f64::from((g - w).abs()))
        .sum();
    assert!(
        l1 <= PAGERANK_L1,
        "{what}: L1 distance {l1:e} > {PAGERANK_L1:e}"
    );
    assert!(
        (got.change - want.change).abs() <= PAGERANK_L1,
        "{what}: last change {} against {}",
        got.change,
        want.change
    );
}

/// GAP's rounds in `f64` on one thread, `rounds` of them: the scores both the CPU's and the
/// GPU's `f32` sums round away from.
fn pagerank_f64(out: &Csr<u8>, inn: &Csr<u8>, damping: f64, rounds: u32) -> Vec<f64> {
    let n = out.nrows();
    let deg: Vec<f64> = (0..n).map(|v| out.row(v).len() as f64).collect();
    let mut s = vec![1.0 / n as f64; n];
    for _ in 0..rounds {
        let share: Vec<f64> = (0..n)
            .map(|v| if deg[v] == 0.0 { 0.0 } else { s[v] / deg[v] })
            .collect();
        for (v, x) in s.iter_mut().enumerate() {
            let sum: f64 = inn.row(v).iter().map(|&u| share[u as usize]).sum();
            *x = (1.0 - damping) / n as f64 + damping * sum;
        }
    }
    s
}

fn l1_to(got: &[f32], exact: &[f64]) -> f64 {
    got.iter()
        .zip(exact)
        .map(|(&g, &e)| (f64::from(g) - e).abs())
        .sum()
}

/// Skewed edges: targets (and sources) drawn as a product of two draws, so a few low
/// vertices get most of the edges (R-MAT-like hubs), plus a hub every vertex points at and
/// a vertex that points at every other: rows of every length, out-degrees from 0 up.
fn skewed(n: u32, m: usize, seed: u64) -> Csr<u8> {
    let mut r = Lcg(seed);
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for _ in 0..m {
        let a = (r.next(n) as u64 * r.next(n) as u64 / n as u64) as u32;
        let b = (r.next(n) as u64 * r.next(n) as u64 / n as u64) as u32;
        src.push(r.next(n));
        dst.push(if r.next(2) == 0 { a } else { b });
    }
    for v in 0..n {
        src.push(v);
        dst.push(n - 1);
        src.push(1);
        dst.push(v);
    }
    Csr::<u8>::from_edges(n as usize, n as usize, &src, &dst, None, BoolOrAnd).unwrap()
}

/// Skewed both ways, as R-MAT is: few vertices hold most out-edges as well as most
/// in-edges, so GAP's sampled test (mean out-degree / 1.3 above the median) holds and the
/// GPU keeps its shares renumbered by falling out-degree.
fn hubs(n: u32, m: usize, seed: u64) -> Csr<u8> {
    let mut r = Lcg(seed);
    let end = |r: &mut Lcg| {
        let x = r.next(n) as u64 * r.next(n) as u64 / n as u64;
        (x * r.next(n) as u64 / n as u64) as u32
    };
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for _ in 0..m {
        src.push(end(&mut r));
        dst.push(end(&mut r));
    }
    for v in (0..n).step_by(3) {
        src.push(v);
        dst.push(0);
    }
    Csr::<u8>::from_edges(n as usize, n as usize, &src, &dst, None, BoolOrAnd).unwrap()
}

/// PageRank on the GPU against the CPU's: random and skewed graphs (skewed in-degrees, and
/// skewed both ways so the shares are kept renumbered; a row of every length,
/// vertices without out-edges, one vertex, none), GAP's settings and tight ones that run
/// to the round limit. The rounds stay on the GPU: a handful of kernels a round, and a
/// second run uploads nothing.
#[test]
fn pagerank_agrees_with_the_cpu() {
    let Some(d) = gpu() else { return };
    let cpu = CpuDevice::new(4);
    let tight = PageRankOptions {
        tolerance: 0.0,
        max_rounds: 30,
        ..PageRankOptions::default()
    };
    let mut graphs = vec![
        (
            "none",
            Csr::<u8>::from_edges(0, 0, &[], &[], None, BoolOrAnd).unwrap(),
        ),
        (
            "one",
            Csr::<u8>::from_edges(1, 1, &[], &[], None, BoolOrAnd).unwrap(),
        ),
        (
            "loop",
            Csr::<u8>::from_edges(1, 1, &[0], &[0], None, BoolOrAnd).unwrap(),
        ),
    ];
    for (n, m, seed) in [(500usize, 1500usize, 1u64), (60_000, 400_000, 2)] {
        let (src, dst) = edges(n as u32, m, seed);
        graphs.push((
            "random",
            Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap(),
        ));
    }
    graphs.push(("skewed small", skewed(3000, 20_000, 3)));
    graphs.push(("skewed", skewed(200_000, 2_000_000, 4)));
    graphs.push(("hubs small", hubs(4096, 30_000, 5)));
    graphs.push(("hubs", hubs(200_000, 2_000_000, 6)));
    for (name, out) in &graphs {
        let inn = out.transpose();
        for (oname, opts) in [("gap", PageRankOptions::default()), ("tight", tight)] {
            let want = pagerank(out, &inn, &opts, &cpu).unwrap();
            let before = d.launches();
            let got = pagerank_of::<G>(out, &inn, &opts, &d).unwrap();
            let what = format!("{name} ({} vertices) {oname}", out.nrows());
            assert_close(&got, &want, &what);
            if out.nrows() > 1 {
                let exact = pagerank_f64(out, &inn, f64::from(opts.damping), want.rounds);
                let (g, c) = (l1_to(&got.scores, &exact), l1_to(&want.scores, &exact));
                // The CPU sums a row in its order in f32, the GPU long rows as a tree: on a
                // hub of 200000 in-edges the CPU is 3e-5 off, the GPU 8e-8.
                assert!(
                    g <= 1e-6,
                    "{what}: GPU {g:e} from the f64 scores (CPU {c:e})"
                );
            }
            if out.nrows() > 1 {
                let k = d.launches() - before;
                assert!(k > 0, "{what}: no GPU kernel ran");
                assert!(
                    k <= 6 * u64::from(got.rounds) + 16,
                    "{what}: {k} kernels for {} rounds",
                    got.rounds
                );
            }
        }
        let up = d.uploaded_bytes();
        let again = pagerank_of::<G>(out, &inn, &PageRankOptions::default(), &d).unwrap();
        assert_eq!(
            d.uploaded_bytes(),
            up,
            "{name}: a second run uploaded again"
        );
        assert_close(
            &again,
            &pagerank(out, &inn, &PageRankOptions::default(), &cpu).unwrap(),
            name,
        );
    }
}

/// A `side` by `side` grid with edges both ways: a search from a corner is `2 * side - 2`
/// levels deep with frontiers of at most `side` vertices.
fn grid(side: usize) -> Csr<u8> {
    let n = side * side;
    let (mut src, mut dst) = (Vec::new(), Vec::new());
    for r in 0..side {
        for c in 0..side {
            let v = (r * side + c) as u32;
            if c + 1 < side {
                src.extend([v, v + 1]);
                dst.extend([v + 1, v]);
            }
            if r + 1 < side {
                src.extend([v, v + side as u32]);
                dst.extend([v + side as u32, v]);
            }
        }
    }
    Csr::<u8>::from_edges(n, n, &src, &dst, None, BoolOrAnd).unwrap()
}

/// The levels of a search on the GPU device `d` from `sources`, its steps and the kernels
/// it launched, against the CPU's.
fn bfs_on(
    out: &Csr<u8>,
    sources: &[u32],
    dir: Direction,
    d: &GpuDevice,
) -> (Vec<(u32, u32)>, Vec<kleene_graph::Step>, u64) {
    let cpu = CpuDevice::new(4);
    let inn = out.transpose();
    let opts = BfsOptions {
        direction: dir,
        ..BfsOptions::default()
    };
    let gc = Graph::<C>::with_transpose(out.clone(), inn.clone(), &cpu).unwrap();
    let want = bfs(&gc, sources, &opts, &cpu).unwrap();
    let gg = Graph::<G>::with_transpose(out.clone(), inn, d).unwrap();
    let before = d.launches();
    let got = bfs(&gg, sources, &opts, d).unwrap();
    let launched = d.launches() - before;
    let levels = pairs(&G::vector_to_host(&got.levels));
    assert_eq!(
        pairs(&C::vector_to_host(&want.levels)),
        levels,
        "bfs {dir:?}"
    );
    assert_eq!(want.steps, got.steps, "bfs steps {dir:?}");
    (levels, got.steps, launched)
}

/// A deep search (a 400 by 400 grid, 799 levels) moves to the host once its frontier is
/// small past the depth floor: the CPU's levels and steps, and a small part of the
/// launches the search takes when it stays on the GPU. A shallow one (R-MAT-like, a few
/// levels) never moves.
#[test]
fn deep_searches_hand_off_to_the_host() {
    let Some(d) = gpu() else { return };
    let measured = CpuBelow::default();
    assert!(
        measured.bfs_frontier > 400 && measured.bfs_depth > 0,
        "measured frontier and depth: {measured:?}"
    );
    let g = grid(400);
    for dir in [Direction::Push, Direction::Auto] {
        d.set_cpu_below(CpuBelow::NEVER);
        let (_, steps, on_gpu) = bfs_on(&g, &[0], dir, &d);
        assert_eq!(steps.len(), 799);
        d.set_cpu_below(CpuBelow { bfs: 0, ..measured });
        let (_, _, moved) = bfs_on(&g, &[0], dir, &d);
        assert!(
            moved * 10 < on_gpu,
            "{dir:?}: {moved} launches moved, {on_gpu} on the GPU"
        );
    }
    // Shallow and wide: the frontier passes the threshold before the depth floor.
    let (src, dst) = edges(60_000, 400_000, 2);
    let wide = Csr::<u8>::from_edges(60_000, 60_000, &src, &dst, None, BoolOrAnd).unwrap();
    d.set_cpu_below(CpuBelow::NEVER);
    let (_, _, on_gpu) = bfs_on(&wide, &[0], Direction::Auto, &d);
    d.set_cpu_below(CpuBelow { bfs: 0, ..measured });
    let (_, _, kept) = bfs_on(&wide, &[0], Direction::Auto, &d);
    assert_eq!(kept, on_gpu, "a shallow search stays on the GPU");
}

/// A search on a graph below [`CpuBelow::bfs`] edges runs every level on the host: the
/// CPU's answer and only the launches that set the search up.
#[test]
fn small_searches_run_on_the_host() {
    let Some(d) = gpu_default() else { return };
    let measured = d.cpu_below();
    let g = grid(60);
    assert!(g.nnz() < measured.bfs, "{} edges, {measured:?}", g.nnz());
    let (_, steps, launched) = bfs_on(&g, &[0, 1234], Direction::Auto, &d);
    assert!(steps.len() > 50);
    assert!(
        launched < 30,
        "{launched} launches for {} levels",
        steps.len()
    );
}

/// The rule, without a GPU: the host for a small graph; for a big one past the depth floor
/// while the frontier is small, and back when it grows to four times the threshold.
#[test]
fn the_search_moves_by_frontier_and_depth() {
    use kleene_graph::{GraphBackend, LevelInfo, Place};
    let d = GpuDevice::with_cpu(CpuDevice::new(1));
    let b = CpuBelow {
        bfs: 1000,
        bfs_frontier: 100,
        bfs_depth: 8,
        ..CpuBelow::NEVER
    };
    d.set_cpu_below(b);
    let at = |edges: u64, depth: u32, frontier: usize, on_host: bool| {
        G::bfs_place(
            &LevelInfo {
                depth,
                vertices: 10_000,
                edges,
                frontier: Some(frontier),
                frontier_edges: None,
                reached: 1,
                on_host,
            },
            &d,
        )
    };
    assert_eq!(at(999, 0, 5000, false), Place::Host, "small graph");
    assert_eq!(at(999, 3, 5000, true), Place::Host, "small graph stays");
    assert_eq!(at(10_000, 0, 5, false), Place::Here, "before the floor");
    assert_eq!(at(10_000, 7, 5, false), Place::Here, "before the floor");
    assert_eq!(
        at(10_000, 8, 99, false),
        Place::Host,
        "small frontier past it"
    );
    assert_eq!(
        at(10_000, 8, 100, false),
        Place::Here,
        "frontier at the threshold"
    );
    assert_eq!(
        at(10_000, 9, 399, true),
        Place::Host,
        "stays below four times"
    );
    assert_eq!(at(10_000, 9, 400, true), Place::Here, "back at four times");
    d.set_cpu_below(CpuBelow::NEVER);
    assert_eq!(at(10, 100, 1, false), Place::Here, "NEVER moves nothing");
    // A frontier the search did not read counts as large.
    let unread = LevelInfo {
        depth: 50,
        vertices: 10_000,
        edges: 10_000,
        frontier: None,
        frontier_edges: None,
        reached: 1,
        on_host: false,
    };
    d.set_cpu_below(b);
    assert_eq!(G::bfs_place(&unread, &d), Place::Here);
}