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/src/algo.rs

//! The algorithms whose rounds stay on the GPU: the graph goes up once (cached), the state
//! lives in GPU buffers, each round is a kernel or two and only a count comes back; the
//! answer comes down at the end.

use std::collections::HashMap;

use cubecl::prelude::{CubeCount, CubeDim};
use cubecl::server::Handle;
use kleene_graph::{
    Components, GraphBackend, LevelInfo, PageRank, PageRankOptions, Paths, Place, SAMPLE,
    SourceSets, SsspOptions, sssp_delta,
};
use kleene_sparse::{CpuBackend, CpuDevice, Csr, Vector};

use crate::backend::GpuBackend;
use crate::dev::{DevPattern, GpuDevice, GpuMatrix, RANK_SHORT, buf, grid, lanes, skewed, words};
use crate::kernels::{self, SLOTS};

/// The most the GPU's PageRank scores may differ from the CPU's [`kleene_graph::pagerank`]
/// in L1 (the sum over the vertices of the absolute differences): GAP's stopping tolerance,
/// 1e-4. Both keep `f32` scores (as LAGraph's `LAGr_PageRankGAP` does), run the same rounds
/// and stop at the same one, but the GPU sums a long row as a tree of partial sums where
/// the CPU adds it in the row's order (and the GPU's compiler may fuse a multiply and an
/// add), so the scores differ by rounding. Measured: 3e-8 to 2e-7 on the benchmark's graphs
/// (R-MAT 12 to 26, road grids); 3e-5 on a test graph with a vertex of 200000 in-edges,
/// where the GPU is 8e-8 from scores summed in `f64` and the CPU's one long `f32` sum is
/// the one 3e-5 off. The tests and the benchmark's GPU column check every answer against
/// this bound and the same rounds.
pub const PAGERANK_L1: f64 = 1e-4;

/// Two lists of up to `n` places, swapped round by round.
struct Lists {
    a: Handle,
    b: Handle,
}

impl Lists {
    fn new(n: usize, d: &GpuDevice) -> Self {
        Lists {
            a: d.alloc(n, 4),
            b: d.alloc(n, 4),
        }
    }

    fn swap(&mut self) {
        std::mem::swap(&mut self.a, &mut self.b);
    }
}

/// `places` copied into the start of `list`.
fn load_list(d: &GpuDevice, list: &Handle, places: &[u32]) {
    let src = d.upload_u32(places);
    let (count, dim) = grid(places.len());
    kernels::copy_u32::launch(
        d.client(),
        count,
        dim,
        buf(&src, places.len()),
        buf(list, places.len()),
    );
    d.launched();
}

fn clear_listed(d: &GpuDevice, list: &Handle, count: usize, bits: &Handle, n: usize) {
    let (c, dim) = grid(count);
    kernels::clear_listed::launch(
        d.client(),
        c,
        dim,
        buf(list, count),
        count as u32,
        buf(bits, words(n)),
    );
    d.launched();
}

fn link_rows(d: &GpuDevice, p: &DevPattern, f: &Handle, from: u32, count: u32, skip: u32) {
    let n = p.rows;
    let (c, dim) = grid(n);
    kernels::link_rows::launch(
        d.client(),
        c,
        dim,
        buf(&p.offsets, n + 1),
        buf(&p.indices, p.nnz),
        buf(f, n),
        from,
        count,
        skip,
        n as u32,
    );
    d.launched();
}

fn compress(d: &GpuDevice, f: &Handle, n: usize) {
    let (c, dim) = grid(n);
    kernels::compress::launch(d.client(), c, dim, buf(f, n), n as u32);
    d.launched();
}

/// Weak components by union-find on the GPU (Afforest: Sutton et al.): link each vertex
/// with its first [`SAMPLE`] out- and in-neighbours, take the most common root (from a
/// sample of vertices) for the giant component, then link the rest of the edges of every
/// vertex outside it. A root is the least vertex of its tree, so each vertex ends holding
/// the least vertex of its component.
fn components_gpu(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    d: &GpuDevice,
) -> Option<kleene_graph::Result<Components>> {
    let n = out.nrows();
    let (po, pi) = (d.pattern(out)?, d.pattern(inn)?);
    let f = d.alloc(n, 4);
    let (c, dim) = grid(n);
    kernels::iota::launch(d.client(), c, dim, buf(&f, n));
    d.launched();
    for r in 0..SAMPLE as u32 {
        link_rows(d, &po, &f, r, 1, u32::MAX);
        link_rows(d, &pi, &f, r, 1, u32::MAX);
        compress(d, &f, n);
    }
    let picks: Vec<u32> = (0..1024u64.min(n as u64))
        .map(|i| (i * n as u64 / 1024.min(n as u64)) as u32)
        .collect();
    let at = d.upload_u32(&picks);
    let got = d.alloc(picks.len(), 4);
    let (c, dim) = grid(picks.len());
    kernels::gather::launch(
        d.client(),
        c,
        dim,
        buf(&f, n),
        buf(&at, picks.len()),
        buf(&got, picks.len()),
    );
    d.launched();
    let mut tally: HashMap<u32, usize> = HashMap::new();
    for r in d.read_u32(&got).into_iter().take(picks.len()) {
        *tally.entry(r).or_default() += 1;
    }
    let giant = tally
        .into_iter()
        .max_by_key(|&(r, k)| (k, std::cmp::Reverse(r)))
        .map_or(u32::MAX, |(r, _)| r);
    link_rows(d, &po, &f, SAMPLE as u32, u32::MAX, giant);
    link_rows(d, &pi, &f, SAMPLE as u32, u32::MAX, giant);
    compress(d, &f, n);
    let mut of = d.read_u32(&f);
    of.truncate(n);
    Some(Ok(Components {
        of,
        rounds: SAMPLE as u32 + 1,
    }))
}

/// Strong components on the GPU, as the CPU does them: trim vertices with no live in- or
/// out-neighbour, colour the live ones with the least vertex reaching them (pushed until
/// nothing falls), name each root's component by searching back from all roots at once
/// inside their colours, and repeat on what is left.
fn scc_gpu(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    d: &GpuDevice,
) -> Option<kleene_graph::Result<Components>> {
    let n = out.nrows();
    let (po, pi) = (d.pattern(out)?, d.pattern(inn)?);
    let of = d.filled_u32(n, u32::MAX);
    let colour = d.alloc(n, 4);
    let changed = d.filled_u32(words(n), 0);
    let mut lists = Lists::new(n, d);
    let trim = |d: &GpuDevice| {
        for _ in 0..64 {
            let slots = d.slots(0);
            let (c, dim) = grid(n);
            kernels::trim::launch(
                d.client(),
                c,
                dim,
                buf(&po.offsets, n + 1),
                buf(&po.indices, po.nnz),
                buf(&pi.offsets, n + 1),
                buf(&pi.indices, pi.nnz),
                buf(&of, n),
                buf(&slots, SLOTS),
                n as u32,
            );
            d.launched();
            if d.sum_slots(&slots) == 0 {
                break;
            }
        }
    };
    trim(d);
    let mut rounds = 0u32;
    loop {
        let counter = d.counter();
        let (c, dim) = grid(n);
        kernels::colour_init::launch(
            d.client(),
            c,
            dim,
            buf(&of, n),
            buf(&colour, n),
            buf(&counter, 1),
            buf(&lists.a, n),
            n as u32,
        );
        d.launched();
        let mut nf = d.read_counter(&counter);
        if nf == 0 {
            break;
        }
        rounds += 1;
        while nf > 0 {
            let counter = d.counter();
            let (c, dim) = lanes(nf);
            kernels::colour_push::launch(
                d.client(),
                c,
                dim,
                buf(&po.offsets, n + 1),
                buf(&po.indices, po.nnz),
                buf(&lists.a, nf),
                nf as u32,
                buf(&of, n),
                buf(&colour, n),
                buf(&changed, words(n)),
                buf(&counter, 1),
                buf(&lists.b, n),
            );
            d.launched();
            nf = d.read_counter(&counter);
            clear_listed(d, &lists.b, nf, &changed, n);
            lists.swap();
        }
        let counter = d.counter();
        let (c, dim) = grid(n);
        kernels::roots::launch(
            d.client(),
            c,
            dim,
            buf(&of, n),
            buf(&colour, n),
            buf(&counter, 1),
            buf(&lists.a, n),
            n as u32,
        );
        d.launched();
        nf = d.read_counter(&counter);
        while nf > 0 {
            let counter = d.counter();
            let (c, dim) = lanes(nf);
            kernels::back_push::launch(
                d.client(),
                c,
                dim,
                buf(&pi.offsets, n + 1),
                buf(&pi.indices, pi.nnz),
                buf(&lists.a, nf),
                nf as u32,
                buf(&colour, n),
                buf(&of, n),
                buf(&counter, 1),
                buf(&lists.b, n),
            );
            d.launched();
            nf = d.read_counter(&counter);
            lists.swap();
        }
        trim(d);
    }
    let mut of = d.read_u32(&of);
    of.truncate(n);
    Some(Ok(Components { of, rounds }))
}

/// Shortest paths by delta-stepping on the GPU over `(distance << 32) | parent` words: a
/// relaxation offers `((d(u) + w) << 32) | u` by atomic minimum, so the shortest distance
/// and, among equal ones, the lowest parent win, as on the CPU. The vertices of the
/// current bucket (distance under the limit) are relaxed until none changes; changed ones
/// past the limit wait in pending bits; then the limit moves past the least pending
/// distance and those under it are taken.
fn sssp_gpu(
    weights: &Csr<u32>,
    source: u32,
    opts: &SsspOptions,
    d: &GpuDevice,
) -> Option<kleene_graph::Result<Paths>> {
    let n = weights.nrows();
    let p = d.pattern(weights)?;
    let (wh, valued) = match weights.values() {
        Some(_) => (d.narrow(weights)?.values.clone(), true),
        None => (d.upload_u32(&[0]), false),
    };
    let delta = sssp_delta(weights, opts);
    let packed = d.alloc(n, 8);
    d.fill_word::<u64>(&packed, n, u64::MAX);
    kernels::set_u64::launch(
        d.client(),
        cubecl::prelude::CubeCount::Static(1, 1, 1),
        cubecl::prelude::CubeDim::new_1d(1),
        buf(&packed, n),
        source,
        source as u64,
    );
    d.launched();
    let changed = d.filled_u32(words(n), 0);
    let pending = d.filled_u32(words(n), 0);
    let lists = Lists::new(n, d);
    load_list(d, &lists.a, &[source]);
    let mut nf = 1usize;
    let mut limit = delta;
    let mut rounds = 0u32;
    loop {
        while nf > 0 {
            let counter = d.counter();
            let (c, dim) = lanes(nf);
            kernels::relax::launch(
                d.client(),
                c,
                dim,
                buf(&p.offsets, n + 1),
                buf(&p.indices, p.nnz),
                buf(&wh, if valued { p.nnz } else { 1 }),
                buf(&lists.a, nf),
                nf as u32,
                buf(&packed, n),
                buf(&changed, words(n)),
                buf(&counter, 1),
                buf(&lists.b, n),
                valued,
            );
            d.launched();
            rounds += 1;
            let nc = d.read_counter(&counter);
            if nc == 0 {
                break;
            }
            let counter = d.counter();
            let (c, dim) = grid(nc);
            kernels::split::launch(
                d.client(),
                c,
                dim,
                buf(&lists.b, nc),
                nc as u32,
                buf(&changed, words(n)),
                buf(&packed, n),
                limit,
                buf(&pending, words(n)),
                buf(&counter, 1),
                buf(&lists.a, n),
            );
            d.launched();
            nf = d.read_counter(&counter);
        }
        let slots = d.slots(u32::MAX);
        let (c, dim) = grid(words(n));
        kernels::pending_min::launch(
            d.client(),
            c,
            dim,
            buf(&pending, words(n)),
            buf(&packed, n),
            buf(&slots, SLOTS),
        );
        d.launched();
        let least = d.read_u32(&slots).into_iter().min().unwrap_or(u32::MAX);
        if least == u32::MAX {
            break;
        }
        limit = (least as u64 / delta + 1) * delta;
        let counter = d.counter();
        let (c, dim) = grid(words(n));
        kernels::extract::launch(
            d.client(),
            c,
            dim,
            buf(&pending, words(n)),
            buf(&packed, n),
            limit,
            buf(&counter, 1),
            buf(&lists.a, n),
        );
        d.launched();
        nf = d.read_counter(&counter);
    }
    let all = d.read_u64(&packed);
    let (mut idx, mut val) = (Vec::new(), Vec::new());
    for (v, &x) in all.iter().take(n).enumerate() {
        if x != u64::MAX {
            idx.push(v as u32);
            val.push(x);
        }
    }
    let packed = match Vector::sparse(n, idx, val) {
        Ok(v) => v,
        Err(e) => return Some(Err(e.into())),
    };
    Some(Ok(Paths::from_packed(source, packed, rounds, 0)))
}

/// Source sets on the GPU: per batch of 64 sources a word per vertex, each changed vertex
/// or-ing its word into its targets until none gains a source.
fn sets_gpu(
    a: &Csr<u8>,
    sources: &[u32],
    d: &GpuDevice,
) -> Option<kleene_graph::Result<SourceSets>> {
    let n = a.nrows();
    let p = d.pattern(a)?;
    let vals = d.alloc(n, 8);
    let changed = d.filled_u32(words(n), 0);
    let mut lists = Lists::new(n, d);
    let mut batches = Vec::new();
    let mut rounds = Vec::new();
    for chunk in sources.chunks(64) {
        d.fill_word::<u64>(&vals, n, 0);
        let bits: Vec<u64> = (0..chunk.len()).map(|k| 1u64 << k).collect();
        let (ih, bh) = (d.upload_u32(chunk), d.upload_u64(&bits));
        let (c, dim) = grid(chunk.len());
        kernels::seed_sets::launch(
            d.client(),
            c,
            dim,
            buf(&ih, chunk.len()),
            buf(&bh, chunk.len()),
            buf(&vals, n),
        );
        d.launched();
        let mut start: Vec<u32> = chunk.to_vec();
        start.sort_unstable();
        start.dedup();
        load_list(d, &lists.a, &start);
        let mut nf = start.len();
        let mut r = 0u32;
        while nf > 0 {
            let counter = d.counter();
            let (c, dim) = lanes(nf);
            kernels::sets_push::launch(
                d.client(),
                c,
                dim,
                buf(&p.offsets, n + 1),
                buf(&p.indices, p.nnz),
                buf(&lists.a, nf),
                nf as u32,
                buf(&vals, n),
                buf(&changed, words(n)),
                buf(&counter, 1),
                buf(&lists.b, n),
            );
            d.launched();
            nf = d.read_counter(&counter);
            clear_listed(d, &lists.b, nf, &changed, n);
            lists.swap();
            r += 1;
        }
        let all = d.read_u64(&vals);
        let (mut idx, mut val) = (Vec::new(), Vec::new());
        for (v, &x) in all.iter().take(n).enumerate() {
            if x != 0 {
                idx.push(v as u32);
                val.push(x);
            }
        }
        match Vector::sparse(n, idx, val) {
            Ok(v) => batches.push(v),
            Err(e) => return Some(Err(e.into())),
        }
        rounds.push(r);
    }
    Some(Ok(SourceSets::from_batches(
        sources.to_vec(),
        batches,
        rounds,
    )))
}

/// The cubes of a grid.
fn cubes(count: &CubeCount) -> usize {
    match count {
        CubeCount::Static(x, y, z) => (*x as usize) * (*y as usize) * (*z as usize),
        CubeCount::Dynamic(_) => unreachable!("grids are static"),
    }
}

/// The change of a round as summed on the GPU, widened.
trait Change: cubecl::prelude::Float + cubecl::CubeElement {
    fn widen(self) -> f64;
}

impl Change for f64 {
    fn widen(self) -> f64 {
        self
    }
}

impl Change for f32 {
    fn widen(self) -> f64 {
        f64::from(self)
    }
}

/// PageRank on the GPU, GAP's pull rounds as [`kleene_graph::pagerank`] runs them: the
/// in-pattern, the out-degrees and the long-row lists go up once (cached); scores and two
/// share arrays live on the GPU; a round is a kernel over the short rows (a unit a row,
/// summed in the row's order), one over the rows of up to [`crate::dev::RANK_LONG`]
/// entries (32 units a row), one over the longer ones (256 units a row) and one adding the
/// cubes' changes, then the change (one number) comes back for the stop test.
fn pagerank_gpu<F: Change>(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    opts: &PageRankOptions,
    d: &GpuDevice,
) -> Option<kleene_graph::Result<PageRank>> {
    let n = out.nrows();
    // On skewed degrees the shares are kept renumbered by falling out-degree (DevRank).
    let plain = if skewed(n, |v| out.row(v).len()) {
        None
    } else {
        Some(d.pattern(inn)?)
    };
    let rank = d.rank_parts(out, inn, plain.as_deref())?;
    let (offsets, indices, place, placed) = match (&rank.placed, &plain) {
        (Some(pl), _) => (&pl.offsets, &pl.indices, &pl.place, true),
        (None, Some(p)) => (&p.offsets, &p.indices, &rank.degree, false),
        (None, None) => unreachable!("a pattern or its renumbered copy"),
    };
    let nnz = inn.nnz();
    let init = 1.0f32 / n as f32;
    let base = (1.0f32 - opts.damping) / n as f32;
    let scores = d.alloc(n, 4);
    let mut shares = [d.alloc(n, 4), d.alloc(n, 4)];
    let (c, dim) = grid(n);
    kernels::rank_init::launch(
        d.client(),
        c,
        dim,
        buf(&rank.degree, n),
        buf(place, n),
        buf(&scores, n),
        buf(&shares[0], n),
        init,
        placed,
    );
    d.launched();
    // (rows, count, group, listed): every row of at most RANK_SHORT entries, then the lists.
    let none = d.alloc(1, 4);
    let mut passes = vec![(&none, n, 1u32, false)];
    if rank.nmid > 0 {
        passes.push((&rank.mid, rank.nmid, 32, true));
    }
    if rank.nfar > 0 {
        passes.push((&rank.far, rank.nfar, 256, true));
    }
    let grids: Vec<(CubeCount, CubeDim)> = passes
        .iter()
        .map(|&(_, count, group, _)| grid(count * group as usize))
        .collect();
    let total: usize = grids.iter().map(|(c, _)| cubes(c)).sum();
    let partial = d.alloc(total, size_of::<F>());
    let sum = d.alloc(1, size_of::<F>());
    let (mut rounds, mut change) = (0u32, f64::INFINITY);
    while rounds < opts.max_rounds {
        let [now, next] = &shares;
        let mut at = 0usize;
        for (&(rows, count, group, listed), (c, dim)) in passes.iter().zip(&grids) {
            kernels::rank_rows::launch::<F>(
                d.client(),
                c.clone(),
                *dim,
                buf(offsets, n + 1),
                buf(indices, nnz),
                buf(rows, if listed { count } else { 1 }),
                count as u32,
                buf(&rank.degree, n),
                buf(place, n),
                buf(now, n),
                buf(next, n),
                buf(&scores, n),
                base,
                opts.damping,
                RANK_SHORT,
                group / 2,
                buf(&partial, total),
                at as u32,
                group,
                listed,
                placed,
            );
            d.launched();
            at += cubes(c);
        }
        kernels::sum_partials::launch::<F>(
            d.client(),
            CubeCount::Static(1, 1, 1),
            CubeDim::new_1d(256),
            buf(&partial, total),
            total as u32,
            buf(&sum, 1),
        );
        d.launched();
        shares.swap(0, 1);
        rounds += 1;
        change = F::from_bytes(&d.client().read_one_unchecked(sum.clone()))[0].widen();
        if change < opts.tolerance {
            break;
        }
    }
    let mut scores = d.read_f32(&scores);
    scores.truncate(n);
    Some(Ok(PageRank {
        scores,
        rounds,
        change,
    }))
}

/// A round of the computed split on the GPU: the out- and in-patterns and the list of long
/// rows are the cached ones (uploaded once for every round); `part` goes up and the wanted
/// part comes back, 4 bytes a node each way. A unit a node of at most
/// [`crate::dev::SPLIT_SHORT`] edges counts its votes in a local array of `k` counters
/// (rounded up to a power of two: one compiled kernel per size); a cube of 256 units a
/// longer node counts them in shared memory. `None`: the graph does not fit 32 bits.
pub(crate) fn split_votes_gpu(
    out: &Csr<u8>,
    inn: &Csr<u8>,
    part: &[u32],
    room: &[u32],
    d: &GpuDevice,
) -> Option<Vec<u32>> {
    let n = out.nrows();
    let k = room.len();
    let (po, pi) = (d.pattern(out)?, d.pattern(inn)?);
    let long = d.split_parts(out, inn)?;
    // `create` of owned bytes: on loki's RTX 5080 it took 40 ms for 16777216 nodes against
    // 105 ms for `create_from_slice` (which copies the slice once more on the way).
    let ph = d
        .client()
        .create(cubecl::bytes::Bytes::from_elems(part.to_vec()));
    let rh = d.upload_u32(room);
    let want = d.alloc(n, 4);
    let cap = k.next_power_of_two().max(2);
    let (c, dim) = grid(n);
    kernels::split_votes_rows::launch(
        d.client(),
        c,
        dim,
        buf(&po.offsets, n + 1),
        buf(&po.indices, po.nnz),
        buf(&pi.offsets, n + 1),
        buf(&pi.indices, pi.nnz),
        buf(&ph, n),
        buf(&rh, k),
        buf(&want, n),
        n as u32,
        k as u32,
        crate::dev::SPLIT_SHORT,
        cap,
    );
    d.launched();
    if long.nlong > 0 {
        let (c, dim) = grid(long.nlong * 256);
        kernels::split_votes_long::launch(
            d.client(),
            c,
            dim,
            buf(&po.offsets, n + 1),
            buf(&po.indices, po.nnz),
            buf(&pi.offsets, n + 1),
            buf(&pi.indices, pi.nnz),
            buf(&ph, n),
            buf(&rh, k),
            buf(&long.long, long.nlong),
            long.nlong as u32,
            buf(&want, n),
            k as u32,
        );
        d.launched();
    }
    let mut want = d.read_u32(&want);
    want.truncate(n);
    Some(want)
}

/// The GPU runs each algorithm whole; a graph below the device's [`crate::CpuBelow`]
/// threshold for it, or too large for 32-bit offsets, runs on the CPU backend's own.
impl GraphBackend for GpuBackend {
    fn components_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        device: &GpuDevice,
    ) -> kleene_graph::Result<Components> {
        if inn.nrows() != out.nrows()
            || out.nrows() != out.ncols()
            || out.nnz() < device.cpu_below().components
        {
            return <CpuBackend as GraphBackend>::components_of(out, inn, device.cpu());
        }
        components_gpu(out, inn, device)
            .unwrap_or_else(|| <CpuBackend as GraphBackend>::components_of(out, inn, device.cpu()))
    }

    fn scc_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        device: &GpuDevice,
    ) -> kleene_graph::Result<Components> {
        if inn.nrows() != out.nrows()
            || out.nrows() != out.ncols()
            || out.nnz() < device.cpu_below().strong
        {
            return <CpuBackend as GraphBackend>::scc_of(out, inn, device.cpu());
        }
        scc_gpu(out, inn, device)
            .unwrap_or_else(|| <CpuBackend as GraphBackend>::scc_of(out, inn, device.cpu()))
    }

    fn sssp_of(
        weights: &Csr<u32>,
        transposed: Option<&Csr<u32>>,
        source: u32,
        opts: &SsspOptions,
        device: &GpuDevice,
    ) -> kleene_graph::Result<Paths> {
        if weights.nnz() < device.cpu_below().paths {
            return <CpuBackend as GraphBackend>::sssp_of(
                weights,
                transposed,
                source,
                opts,
                device.cpu(),
            );
        }
        sssp_gpu(weights, source, opts, device).unwrap_or_else(|| {
            <CpuBackend as GraphBackend>::sssp_of(weights, transposed, source, opts, device.cpu())
        })
    }

    fn reach_sets(
        a: &Csr<u8>,
        sources: &[u32],
        device: &GpuDevice,
    ) -> kleene_graph::Result<SourceSets> {
        if a.nnz() < device.cpu_below().sets {
            return <CpuBackend as GraphBackend>::reach_sets(a, sources, device.cpu());
        }
        sets_gpu(a, sources, device)
            .unwrap_or_else(|| <CpuBackend as GraphBackend>::reach_sets(a, sources, device.cpu()))
    }

    fn pagerank_of(
        out: &Csr<u8>,
        inn: &Csr<u8>,
        opts: &PageRankOptions,
        device: &GpuDevice,
    ) -> kleene_graph::Result<PageRank> {
        let n = out.nrows();
        if n < 2
            || inn.nrows() != n
            || out.ncols() != n
            || inn.ncols() != n
            || out.nnz() < device.cpu_below().pagerank
        {
            return kleene_graph::pagerank(out, inn, opts, device.cpu());
        }
        let got = if device.has_f64() {
            pagerank_gpu::<f64>(out, inn, opts, device)
        } else {
            pagerank_gpu::<f32>(out, inn, opts, device)
        };
        got.unwrap_or_else(|| kleene_graph::pagerank(out, inn, opts, device.cpu()))
    }

    /// A search on a graph below [`crate::CpuBelow::bfs`] edges runs on the CPU from its
    /// first level (an integrated GPU's defaults: every search). A bigger one moves there
    /// past [`crate::CpuBelow::bfs_depth`] levels while its frontier is under
    /// [`crate::CpuBelow::bfs_frontier`] vertices (a level of a deep, narrow search costs a
    /// launch or two on the GPU and microseconds on the CPU), and back when the frontier
    /// reaches four times that.
    fn bfs_place(info: &LevelInfo, device: &GpuDevice) -> Place {
        let b = device.cpu_below();
        if (info.edges as usize) < b.bfs {
            return Place::Host;
        }
        let Some(f) = info.frontier else {
            return if info.on_host {
                Place::Host
            } else {
                Place::Here
            };
        };
        let host = if info.on_host {
            f < b.bfs_frontier.saturating_mul(4)
        } else {
            info.depth >= b.bfs_depth && f < b.bfs_frontier
        };
        if host { Place::Host } else { Place::Here }
    }

    fn split_votes(
        out: &GpuMatrix<u8>,
        inn: &GpuMatrix<u8>,
        part: &[u32],
        room: &[u32],
        device: &GpuDevice,
    ) -> kleene_graph::Result<Vec<u32>> {
        let (o, i) = (&out.host, &inn.host);
        let cpu = || <CpuBackend as GraphBackend>::split_votes(o, i, part, room, device.cpu());
        let k = room.len();
        if part.len() != o.nrows()
            || part.iter().any(|&p| p as usize >= k)
            || !device.split_on_gpu(o, i, k)
        {
            return cpu();
        }
        split_votes_gpu(o, i, part, room, device).map_or_else(cpu, Ok)
    }

    fn host_pattern(m: &GpuMatrix<u8>) -> Option<&Csr<u8>> {
        Some(&m.host)
    }

    fn host_device(device: &GpuDevice) -> Option<&CpuDevice> {
        Some(device.cpu())
    }
}