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

use std::any::TypeId;

use cubecl::server::Handle;
use kleene_sparse::{
    BitsetUnion, BoolOrAnd, CpuBackend, Csr, Mask, MatrixMask, MinPlus, Result, Semiring,
    SparseBackend, Value, Vector,
};

use crate::dev::{
    DevValues, GpuDevice, GpuMask, GpuMatrix, GpuVector, Word, buf, grid, lanes, wide, words,
};
use crate::kernels::{self, SLOTS};

/// The CubeCL backend. Vectors and masks live on the GPU ([`GpuVector`], [`GpuMask`]),
/// matrices are uploaded once (and cached by the device). Products (`mxv`, `vxm`),
/// accumulation, the traversal steps, masks, assignment, counts and row lengths run as GPU
/// kernels for min-plus and or-and on 32- and 64-bit words, so a search's levels and a
/// propagation's rounds stay on the GPU and only counts come back. Operations given a
/// closure (`select_vector`, `apply_indexed`), matrix-matrix operations, and other
/// semirings run on the CPU backend over downloaded copies.
#[derive(Clone, Copy, Debug, Default)]
pub struct GpuBackend;

/// Nothing: the GPU kernels allocate their scratch from CubeCL's pools.
#[derive(Debug, Default)]
pub struct GpuWorkspace;

type C = CpuBackend;

/// The semiring shapes with GPU kernels: 0 min-plus, 1 or-and.
fn op<S: Semiring>() -> Option<u32> {
    let t = TypeId::of::<S>();
    if t == TypeId::of::<MinPlus<u32>>() || t == TypeId::of::<MinPlus<u64>>() {
        Some(0)
    } else if t == TypeId::of::<BoolOrAnd>() || t == TypeId::of::<BitsetUnion>() {
        Some(1)
    } else {
        None
    }
}

/// The value buffers and flags a product kernel takes for a matrix.
struct ValueArgs {
    words: Handle,
    narrow: Handle,
    valued: bool,
    is_narrow: bool,
    scale: u64,
    len: usize,
}

fn value_args<T: Value>(a: &GpuMatrix<T>) -> ValueArgs {
    let d = &a.device;
    let dummy_w = d.upload_u64(&[0]);
    let dummy_n = d.upload_u32(&[0]);
    match a.dev().and_then(|x| x.values.as_ref()) {
        None => ValueArgs {
            words: dummy_w,
            narrow: dummy_n,
            valued: false,
            is_narrow: false,
            scale: 1,
            len: 1,
        },
        Some(DevValues::Words(h)) => ValueArgs {
            words: h.clone(),
            narrow: dummy_n,
            valued: true,
            is_narrow: false,
            scale: 1,
            len: a.host.nnz(),
        },
        Some(DevValues::Narrow(nv)) => ValueArgs {
            words: dummy_w,
            narrow: nv.values.clone(),
            valued: true,
            is_narrow: true,
            scale: nv.scale,
            len: a.host.nnz(),
        },
    }
}

fn mask_args(mask: Option<&GpuMask>, d: &GpuDevice) -> (Handle, usize, u32) {
    match mask {
        Some(m) => (m.bits.clone(), words(m.n), m.comp()),
        None => (d.upload_u32(&[0]), 1, 0),
    }
}

fn pull_on<W: WordExt, T: Value>(
    a: &GpuMatrix<T>,
    x: &GpuVector<T>,
    mask: Option<&GpuMask>,
    op: u32,
    zero: T,
) -> Option<GpuVector<T>> {
    let dev = a.dev()?;
    let va = value_args(a);
    if va.valued && op != 0 {
        return None;
    }
    let d = &a.device;
    let (n, m) = (a.host.nrows(), a.host.ncols());
    let mut out = GpuVector::<T>::empty(n, d);
    let consts =
        d.client()
            .create_from_slice(W::as_bytes(&[W::of(zero), W::MAX, W::of_u64(va.scale)]));
    let (mb, ml, comp) = mask_args(mask, d);
    let (count, dim) = grid(n);
    kernels::pull::launch::<W>(
        d.client(),
        count,
        dim,
        buf(&dev.pattern.offsets, n + 1),
        buf(&dev.pattern.indices, dev.pattern.nnz),
        buf(&va.words, if va.is_narrow { 1 } else { va.len }),
        buf(&va.narrow, if va.is_narrow { va.len } else { 1 }),
        buf(&x.vals, m),
        buf(&x.bits, words(m)),
        buf(&mb, ml),
        comp,
        buf(&out.vals, n),
        buf(&out.bits, words(n)),
        buf(&consts, 3),
        n as u32,
        op,
        va.valued,
        va.is_narrow,
        mask.is_some(),
    );
    d.launched();
    out.changed();
    Some(out)
}

fn push_on<W: WordExt, T: Value>(
    x: &GpuVector<T>,
    a: &GpuMatrix<T>,
    mask: Option<&GpuMask>,
    op: u32,
    zero: T,
) -> Option<GpuVector<T>> {
    let dev = a.dev()?;
    let va = value_args(a);
    if va.valued && op != 0 {
        return None;
    }
    let d = &a.device;
    let m = a.host.ncols();
    let mut out = GpuVector::<T>::empty_at(m, zero, d);
    let (fl, nf) = x.list();
    if nf == 0 {
        return Some(out);
    }
    let consts =
        d.client()
            .create_from_slice(W::as_bytes(&[W::of(zero), W::MAX, W::of_u64(va.scale)]));
    let (mb, ml, comp) = mask_args(mask, d);
    let (count, dim) = lanes(nf);
    kernels::push::launch::<W>(
        d.client(),
        count,
        dim,
        buf(&dev.pattern.offsets, a.host.nrows() + 1),
        buf(&dev.pattern.indices, dev.pattern.nnz),
        buf(&va.words, if va.is_narrow { 1 } else { va.len }),
        buf(&va.narrow, if va.is_narrow { va.len } else { 1 }),
        buf(fl, nf),
        nf as u32,
        buf(&x.vals, x.n),
        buf(&mb, ml),
        comp,
        buf(&out.vals, m),
        buf(&out.bits, words(m)),
        buf(&consts, 3),
        op,
        va.valued,
        va.is_narrow,
        mask.is_some(),
    );
    d.launched();
    out.changed();
    Some(out)
}

trait WordExt: Word {
    fn of_u64(x: u64) -> Self;
}
impl WordExt for u32 {
    fn of_u64(x: u64) -> Self {
        x as u32
    }
}
impl WordExt for u64 {
    fn of_u64(x: u64) -> Self {
        x
    }
}

fn accumulate_on<W: Word, T: Value>(
    w: &mut GpuVector<T>,
    u: &GpuVector<T>,
    op: u32,
) -> GpuVector<T> {
    let d = w.device.clone();
    let n = w.n;
    let mut c = GpuVector::<T>::empty(n, &d);
    let nw = words(n);
    let (count, dim) = grid(nw);
    kernels::accumulate::launch::<W>(
        d.client(),
        count,
        dim,
        buf(&w.vals, n),
        buf(&w.bits, nw),
        buf(&u.vals, n),
        buf(&u.bits, nw),
        buf(&c.vals, n),
        buf(&c.bits, nw),
        op,
    );
    d.launched();
    w.changed();
    c.changed();
    c
}

fn assign_on<W: Word, T: Value, U: Value>(w: &mut GpuVector<T>, at: &GpuVector<U>, value: T) {
    let d = w.device.clone();
    let v = d.client().create_from_slice(W::as_bytes(&[W::of(value)]));
    let nw = words(w.n);
    let (count, dim) = grid(nw);
    kernels::assign_words::launch::<W>(
        d.client(),
        count,
        dim,
        buf(&at.bits, nw),
        buf(&w.bits, nw),
        buf(&w.vals, w.n),
        buf(&v, 1),
    );
    d.launched();
    w.changed();
}

fn scatter_on<W: Word, T: Value>(v: &mut GpuVector<T>, idx: &[u32], value: T) {
    let d = v.device.clone();
    let ih = d.upload_u32(idx);
    let vh = d.client().create_from_slice(W::as_bytes(&[W::of(value)]));
    let (count, dim) = grid(idx.len());
    kernels::scatter_value::launch::<W>(
        d.client(),
        count,
        dim,
        buf(&ih, idx.len()),
        buf(&v.vals, v.n),
        buf(&v.bits, words(v.n)),
        buf(&vh, 1),
    );
    d.launched();
    v.changed();
}

macro_rules! by_word {
    ($t:ty, $f:ident :: <$($g:ty),*> ($($a:expr),* $(,)?)) => {
        if wide::<$t>() {
            $f::<u64, $($g),*>($($a),*)
        } else {
            $f::<u32, $($g),*>($($a),*)
        }
    };
}

fn up<T: Value>(v: &Vector<T>, d: &GpuDevice) -> GpuVector<T> {
    GpuVector::upload(v, d)
}

impl SparseBackend for GpuBackend {
    type Device = GpuDevice;
    type Matrix<T: Value> = GpuMatrix<T>;
    type Vector<T: Value> = GpuVector<T>;
    type Mask = GpuMask;
    type Workspace = GpuWorkspace;

    fn name() -> &'static str {
        "cubecl"
    }

    fn matrix<T: Value>(csr: Csr<T>, device: &GpuDevice) -> GpuMatrix<T> {
        GpuMatrix::new(csr, device)
    }
    fn matrix_to_host<T: Value>(m: &GpuMatrix<T>) -> Csr<T> {
        m.host.clone()
    }
    fn vector<T: Value>(v: Vector<T>, device: &GpuDevice) -> GpuVector<T> {
        up(&v, device)
    }
    fn vector_to_host<T: Value>(v: &GpuVector<T>) -> Vector<T> {
        v.download()
    }
    fn mask(m: Mask, device: &GpuDevice) -> GpuMask {
        GpuMask::upload(&m, device)
    }
    fn mask_to_host(m: &GpuMask) -> Mask {
        m.download()
    }
    fn shape<T: Value>(m: &GpuMatrix<T>) -> (usize, usize) {
        (m.host.nrows(), m.host.ncols())
    }
    fn nnz<T: Value>(m: &GpuMatrix<T>) -> usize {
        m.host.nnz()
    }
    fn len<T: Value>(v: &GpuVector<T>) -> usize {
        v.n
    }
    fn nvals<T: Value>(v: &GpuVector<T>) -> usize {
        v.nvals()
    }

    fn mxv<S: Semiring>(
        a: &GpuMatrix<S::T>,
        x: &GpuVector<S::T>,
        mask: Option<&GpuMask>,
        s: S,
        device: &GpuDevice,
    ) -> Result<GpuVector<S::T>> {
        if a.host.ncols() == x.n
            && mask.is_none_or(|m| m.n == a.host.nrows())
            && let Some(op) = op::<S>()
            && let Some(y) = by_word!(S::T, pull_on::<S::T>(a, x, mask, op, s.zero()))
        {
            return Ok(y);
        }
        let m = mask.map(|m| m.download());
        Ok(up(
            &C::mxv(&a.host, &x.download(), m.as_ref(), s, device.cpu())?,
            device,
        ))
    }

    fn vxm<S: Semiring>(
        x: &GpuVector<S::T>,
        a: &GpuMatrix<S::T>,
        mask: Option<&GpuMask>,
        s: S,
        device: &GpuDevice,
    ) -> Result<GpuVector<S::T>> {
        if a.host.nrows() == x.n
            && mask.is_none_or(|m| m.n == a.host.ncols())
            && let Some(op) = op::<S>()
            && let Some(y) = by_word!(S::T, push_on::<S::T>(x, a, mask, op, s.zero()))
        {
            return Ok(y);
        }
        let m = mask.map(|m| m.download());
        Ok(up(
            &C::vxm(&x.download(), &a.host, m.as_ref(), s, device.cpu())?,
            device,
        ))
    }

    fn mxm<S: Semiring>(
        a: &GpuMatrix<S::T>,
        b: &GpuMatrix<S::T>,
        mask: Option<&MatrixMask>,
        s: S,
        device: &GpuDevice,
    ) -> Result<GpuMatrix<S::T>> {
        Ok(GpuMatrix::new(
            C::mxm(&a.host, &b.host, mask, s, device.cpu())?,
            device,
        ))
    }

    fn ewise_add_vector<S: Semiring>(
        a: &GpuVector<S::T>,
        b: &GpuVector<S::T>,
        s: S,
    ) -> Result<GpuVector<S::T>> {
        Ok(up(
            &C::ewise_add_vector(&a.download(), &b.download(), s)?,
            &a.device,
        ))
    }
    fn ewise_mult_vector<S: Semiring>(
        a: &GpuVector<S::T>,
        b: &GpuVector<S::T>,
        s: S,
    ) -> Result<GpuVector<S::T>> {
        Ok(up(
            &C::ewise_mult_vector(&a.download(), &b.download(), s)?,
            &a.device,
        ))
    }
    fn ewise_add_matrix<S: Semiring>(
        a: &GpuMatrix<S::T>,
        b: &GpuMatrix<S::T>,
        s: S,
        device: &GpuDevice,
    ) -> Result<GpuMatrix<S::T>> {
        Ok(GpuMatrix::new(
            C::ewise_add_matrix(&a.host, &b.host, s, device.cpu())?,
            device,
        ))
    }
    fn ewise_mult_matrix<S: Semiring>(
        a: &GpuMatrix<S::T>,
        b: &GpuMatrix<S::T>,
        s: S,
        device: &GpuDevice,
    ) -> Result<GpuMatrix<S::T>> {
        Ok(GpuMatrix::new(
            C::ewise_mult_matrix(&a.host, &b.host, s, device.cpu())?,
            device,
        ))
    }

    fn reduce_vector<S: Semiring>(v: &GpuVector<S::T>, s: S) -> S::T {
        C::reduce_vector(&v.download(), s)
    }
    fn reduce_rows<S: Semiring>(a: &GpuMatrix<S::T>, s: S, device: &GpuDevice) -> GpuVector<S::T> {
        up(&C::reduce_rows(&a.host, s, device.cpu()), device)
    }

    fn select_vector<T: Value, F: Fn(u32, T) -> bool + Sync>(
        v: &GpuVector<T>,
        keep: F,
    ) -> GpuVector<T> {
        up(&C::select_vector(&v.download(), keep), &v.device)
    }
    fn select_matrix<S: Semiring, F: Fn(u32, u32, S::T) -> bool + Sync>(
        a: &GpuMatrix<S::T>,
        keep: F,
        s: S,
        device: &GpuDevice,
    ) -> GpuMatrix<S::T> {
        GpuMatrix::new(C::select_matrix(&a.host, keep, s, device.cpu()), device)
    }

    fn transpose<T: Value>(a: &GpuMatrix<T>, device: &GpuDevice) -> GpuMatrix<T> {
        GpuMatrix::new(a.host.transpose(), device)
    }

    fn mask_from_vector<T: Value>(v: &GpuVector<T>) -> GpuMask {
        let d = &v.device;
        let nw = words(v.n);
        let bits = d.alloc(nw, 4);
        let (count, dim) = grid(nw);
        kernels::copy_u32::launch(d.client(), count, dim, buf(&v.bits, nw), buf(&bits, nw));
        d.launched();
        GpuMask {
            n: v.n,
            bits,
            complement: false,
            device: d.clone(),
        }
    }
    fn mask_add_vector<T: Value>(m: &mut GpuMask, v: &GpuVector<T>) {
        let d = &m.device;
        let nw = words(m.n);
        let (count, dim) = grid(nw);
        kernels::or_words::launch(d.client(), count, dim, buf(&v.bits, nw), buf(&m.bits, nw));
        d.launched();
    }
    fn mask_complement(mut m: GpuMask) -> GpuMask {
        m.complement = !m.complement;
        m
    }
    fn mask_count(m: &GpuMask) -> usize {
        let d = &m.device;
        let nw = words(m.n);
        let slots = d.slots(0);
        let (count, dim) = grid(nw);
        kernels::count_bits::launch(
            d.client(),
            count,
            dim,
            buf(&m.bits, nw),
            m.comp(),
            m.n as u32,
            buf(&slots, SLOTS),
        );
        d.launched();
        d.sum_slots(&slots) as usize
    }

    fn assign_scalar<T: Value, U: Value>(
        w: &mut GpuVector<T>,
        at: &GpuVector<U>,
        value: T,
        _fill: T,
    ) {
        by_word!(T, assign_on::<T, U>(w, at, value))
    }

    fn workspace(_n: usize, _device: &GpuDevice) -> GpuWorkspace {
        GpuWorkspace
    }

    fn step_push(
        frontier: &GpuVector<u8>,
        a: &GpuMatrix<u8>,
        open: &mut GpuMask,
        next: &mut GpuVector<u8>,
        _ws: &mut GpuWorkspace,
        device: &GpuDevice,
    ) -> Result<u64> {
        let Some(dev) = a.dev().filter(|_| a.host.values().is_none()) else {
            return host_step(frontier, a, open, next, device, false);
        };
        let d = device;
        let m = a.host.ncols();
        next.clear();
        let (fl, nf) = frontier.list();
        if nf == 0 {
            return Ok(0);
        }
        let slots = d.slots(0);
        let (count, dim) = lanes(nf);
        kernels::step_push::launch(
            d.client(),
            count,
            dim,
            buf(&dev.pattern.offsets, a.host.nrows() + 1),
            buf(&dev.pattern.indices, dev.pattern.nnz),
            buf(fl, nf),
            nf as u32,
            buf(&open.bits, words(m)),
            open.comp(),
            buf(&next.bits, words(m)),
            buf(&next.vals, m),
            buf(&slots, SLOTS),
        );
        d.launched();
        next.changed();
        Ok(d.sum_slots(&slots))
    }

    fn step_pull(
        frontier: &GpuVector<u8>,
        at: &GpuMatrix<u8>,
        open: &mut GpuMask,
        next: &mut GpuVector<u8>,
        _ws: &mut GpuWorkspace,
        device: &GpuDevice,
    ) -> Result<u64> {
        let Some(dev) = at.dev().filter(|_| at.host.values().is_none()) else {
            return host_step(frontier, at, open, next, device, true);
        };
        let d = device;
        let n = at.host.nrows();
        next.clear();
        let slots = d.slots(0);
        let (count, dim) = grid(n);
        kernels::step_pull::launch(
            d.client(),
            count,
            dim,
            buf(&dev.pattern.offsets, n + 1),
            buf(&dev.pattern.indices, dev.pattern.nnz),
            buf(&frontier.bits, words(frontier.n)),
            buf(&open.bits, words(n)),
            open.comp(),
            buf(&next.bits, words(n)),
            buf(&next.vals, n),
            buf(&slots, SLOTS),
            n as u32,
        );
        d.launched();
        next.changed();
        Ok(d.sum_slots(&slots))
    }

    fn accumulate<S: Semiring>(
        w: &mut GpuVector<S::T>,
        u: &GpuVector<S::T>,
        s: S,
    ) -> Result<GpuVector<S::T>> {
        if w.n == u.n
            && let Some(op) = op::<S>()
        {
            return Ok(by_word!(S::T, accumulate_on::<S::T>(w, u, op)));
        }
        let mut wh = w.download();
        let c = C::accumulate(&mut wh, &u.download(), s)?;
        let d = w.device.clone();
        *w = up(&wh, &d);
        Ok(up(&c, &d))
    }

    fn apply_indexed<T: Value, F: Fn(u32, T) -> T + Sync>(v: &GpuVector<T>, f: F) -> GpuVector<T> {
        up(&C::apply_indexed(&v.download(), f), &v.device)
    }

    fn indices<T: Value>(v: &GpuVector<T>) -> Vec<u32> {
        v.host_indices()
    }

    fn row_lengths_at<T: Value, U: Value>(a: &GpuMatrix<T>, v: &GpuVector<U>) -> u64 {
        let Some(dev) = a.dev() else {
            return C::row_lengths_at(&a.host, &v.download());
        };
        let d = &a.device;
        let nw = words(v.n);
        let slots = d.slots(0);
        let (count, dim) = grid(nw);
        kernels::row_lengths::launch(
            d.client(),
            count,
            dim,
            buf(&dev.pattern.offsets, a.host.nrows() + 1),
            buf(&v.bits, nw),
            v.n as u32,
            buf(&slots, SLOTS),
        );
        d.launched();
        d.sum_slots(&slots)
    }

    fn clear_vector<T: Value>(v: &mut GpuVector<T>, _device: &GpuDevice) {
        v.clear();
    }

    fn load_indices<T: Value>(
        v: &mut GpuVector<T>,
        indices: &[u32],
        value: T,
        _device: &GpuDevice,
    ) -> Result<()> {
        if let Some(&i) = indices.iter().find(|&&i| i as usize >= v.n) {
            return Err(kleene_sparse::SparseError::IndexOutOfRange {
                what: "load_indices",
                index: i as u64,
                dim: v.n as u64,
            });
        }
        v.clear();
        if !indices.is_empty() {
            by_word!(T, scatter_on::<T>(v, indices, value));
        }
        Ok(())
    }

    fn mask_assign(m: &mut GpuMask, host: &Mask, device: &GpuDevice) {
        *m = GpuMask::upload(host, device);
    }
}

/// A traversal step on the host copies (a matrix the GPU cannot hold).
fn host_step(
    frontier: &GpuVector<u8>,
    a: &GpuMatrix<u8>,
    open: &mut GpuMask,
    next: &mut GpuVector<u8>,
    device: &GpuDevice,
    pull: bool,
) -> Result<u64> {
    let f = frontier.download();
    let mut o = open.download();
    let mut nx = next.download();
    let mut ws = C::workspace(a.host.nrows().max(a.host.ncols()), device.cpu());
    let ex = if pull {
        C::step_pull(&f, &a.host, &mut o, &mut nx, &mut ws, device.cpu())?
    } else {
        C::step_push(&f, &a.host, &mut o, &mut nx, &mut ws, device.cpu())?
    };
    *open = GpuMask::upload(&o, device);
    *next = up(&nx, device);
    Ok(ex)
}