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

use std::fmt::Debug;

use crate::Result;
use crate::matrix::{Csr, MatrixMask};
use crate::semiring::{Semiring, Value};
use crate::vector::{Mask, Vector};

/// A place sparse objects live and the operations on them, in Burn's backend style: the
/// backend is a type with associated primitives (matrix, vector, mask, device) and every
/// operation is an associated function over them. Algorithms are written once against this
/// trait; [`crate::CpuBackend`] runs them on every core now, a CubeCL backend later.
///
/// Products take an optional mask: an entry of the result is computed only at a place the
/// mask allows (a complemented mask allows the places it does not hold).
pub trait SparseBackend: Clone + Copy + Default + Debug + Send + Sync + 'static {
    /// Where the primitives live and how work is spread (threads, a GPU queue).
    type Device: Clone + Debug + Default + Send + Sync;
    /// A matrix of `T`.
    type Matrix<T: Value>: Clone + Debug + Send + Sync;
    /// A vector of `T`.
    type Vector<T: Value>: Clone + Debug + Send + Sync;
    /// A structural vector mask.
    type Mask: Clone + Debug + Send + Sync;

    /// Buffers reused by traversal steps (frontier marks, per-thread lists), so a search
    /// allocates nothing per level.
    type Workspace: Debug + Send;

    /// The backend's name.
    fn name() -> &'static str;

    /// Move a compressed-rows matrix to the device.
    fn matrix<T: Value>(csr: Csr<T>, device: &Self::Device) -> Self::Matrix<T>;
    /// A matrix in compressed rows, on the host.
    fn matrix_to_host<T: Value>(m: &Self::Matrix<T>) -> Csr<T>;
    /// Move a vector to the device.
    fn vector<T: Value>(v: Vector<T>, device: &Self::Device) -> Self::Vector<T>;
    /// A vector on the host.
    fn vector_to_host<T: Value>(v: &Self::Vector<T>) -> Vector<T>;
    /// Move a mask to the device.
    fn mask(m: Mask, device: &Self::Device) -> Self::Mask;
    /// A mask on the host.
    fn mask_to_host(m: &Self::Mask) -> Mask;

    /// (rows, columns).
    fn shape<T: Value>(m: &Self::Matrix<T>) -> (usize, usize);
    /// The number of entries of a matrix.
    fn nnz<T: Value>(m: &Self::Matrix<T>) -> usize;
    /// The length of a vector.
    fn len<T: Value>(v: &Self::Vector<T>) -> usize;
    /// The number of entries of a vector.
    fn nvals<T: Value>(v: &Self::Vector<T>) -> usize;

    /// `y = A ⊕.⊗ x`: `y_i = ⊕_j A_ij ⊗ x_j` (pull: each allowed row reads its entries).
    fn mxv<S: Semiring>(
        a: &Self::Matrix<S::T>,
        x: &Self::Vector<S::T>,
        mask: Option<&Self::Mask>,
        s: S,
        device: &Self::Device,
    ) -> Result<Self::Vector<S::T>>;

    /// `y = x ⊕.⊗ A`: `y_j = ⊕_i x_i ⊗ A_ij` (push: each entry of `x` sends along its row).
    fn vxm<S: Semiring>(
        x: &Self::Vector<S::T>,
        a: &Self::Matrix<S::T>,
        mask: Option<&Self::Mask>,
        s: S,
        device: &Self::Device,
    ) -> Result<Self::Vector<S::T>>;

    /// `C = A ⊕.⊗ B`, computed only at the places `mask` allows.
    fn mxm<S: Semiring>(
        a: &Self::Matrix<S::T>,
        b: &Self::Matrix<S::T>,
        mask: Option<&MatrixMask>,
        s: S,
        device: &Self::Device,
    ) -> Result<Self::Matrix<S::T>>;

    /// The union of two vectors' entries, values at shared places added.
    fn ewise_add_vector<S: Semiring>(
        a: &Self::Vector<S::T>,
        b: &Self::Vector<S::T>,
        s: S,
    ) -> Result<Self::Vector<S::T>>;
    /// The intersection of two vectors' entries, values multiplied.
    fn ewise_mult_vector<S: Semiring>(
        a: &Self::Vector<S::T>,
        b: &Self::Vector<S::T>,
        s: S,
    ) -> Result<Self::Vector<S::T>>;
    /// The union of two matrices' entries, values at shared places added.
    fn ewise_add_matrix<S: Semiring>(
        a: &Self::Matrix<S::T>,
        b: &Self::Matrix<S::T>,
        s: S,
        device: &Self::Device,
    ) -> Result<Self::Matrix<S::T>>;
    /// The intersection of two matrices' entries, values multiplied.
    fn ewise_mult_matrix<S: Semiring>(
        a: &Self::Matrix<S::T>,
        b: &Self::Matrix<S::T>,
        s: S,
        device: &Self::Device,
    ) -> Result<Self::Matrix<S::T>>;

    /// `⊕` of a vector's entries (`zero` for none).
    fn reduce_vector<S: Semiring>(v: &Self::Vector<S::T>, s: S) -> S::T;
    /// `⊕` of each row's entries: an entry for each row that has any.
    fn reduce_rows<S: Semiring>(
        a: &Self::Matrix<S::T>,
        s: S,
        device: &Self::Device,
    ) -> Self::Vector<S::T>;

    /// The entries of a vector that `keep` keeps.
    fn select_vector<T: Value, F: Fn(u32, T) -> bool + Sync>(
        v: &Self::Vector<T>,
        keep: F,
    ) -> Self::Vector<T>;
    /// The entries of a matrix that `keep` keeps (row, column, value; a structural
    /// matrix's entries are the semiring's one).
    fn select_matrix<S: Semiring, F: Fn(u32, u32, S::T) -> bool + Sync>(
        a: &Self::Matrix<S::T>,
        keep: F,
        s: S,
        device: &Self::Device,
    ) -> Self::Matrix<S::T>;

    /// The transpose.
    fn transpose<T: Value>(a: &Self::Matrix<T>, device: &Self::Device) -> Self::Matrix<T>;

    /// A mask of the places where `v` has entries.
    fn mask_from_vector<T: Value>(v: &Self::Vector<T>) -> Self::Mask;
    /// Add the places where `v` has entries to the mask's bits.
    fn mask_add_vector<T: Value>(m: &mut Self::Mask, v: &Self::Vector<T>);
    /// The complemented mask.
    fn mask_complement(m: Self::Mask) -> Self::Mask;
    /// The number of places a mask allows.
    fn mask_count(m: &Self::Mask) -> usize;

    /// `w(i) = value` at each place `i` where `at` has an entry (`fill` stands at the places
    /// of `w` that had no entry when it must be stored densely).
    fn assign_scalar<T: Value, U: Value>(
        w: &mut Self::Vector<T>,
        at: &Self::Vector<U>,
        value: T,
        fill: T,
    );

    /// A workspace for traversals over `n` vertices.
    fn workspace(n: usize, device: &Self::Device) -> Self::Workspace;

    /// One structural traversal step in place, pushing: `next` becomes every place `open`
    /// allows that an entry of `frontier` has an edge to along the rows of `a`, and each of
    /// them is closed in `open`. `next` keeps its storage. Returns the edges examined.
    fn step_push(
        frontier: &Self::Vector<u8>,
        a: &Self::Matrix<u8>,
        open: &mut Self::Mask,
        next: &mut Self::Vector<u8>,
        ws: &mut Self::Workspace,
        device: &Self::Device,
    ) -> Result<u64>;

    /// One structural traversal step in place, pulling: every place `open` allows looks
    /// along its row of `at` (the transpose: its in-edges) for an entry of `frontier` and
    /// stops at the first; `next` becomes those found, each closed in `open`. Returns the
    /// edges examined.
    fn step_pull(
        frontier: &Self::Vector<u8>,
        at: &Self::Matrix<u8>,
        open: &mut Self::Mask,
        next: &mut Self::Vector<u8>,
        ws: &mut Self::Workspace,
        device: &Self::Device,
    ) -> Result<u64>;

    /// `w ⊕= u` in place: each entry of `u` is added into `w` (a place `w` lacks takes
    /// `u`'s value). Returns the entries of `w` that are new or changed, with their new
    /// values: the frontier of a propagation round.
    fn accumulate<S: Semiring>(
        w: &mut Self::Vector<S::T>,
        u: &Self::Vector<S::T>,
        s: S,
    ) -> Result<Self::Vector<S::T>>;

    /// Each entry's value replaced by `f(index, value)`.
    fn apply_indexed<T: Value, F: Fn(u32, T) -> T + Sync>(
        v: &Self::Vector<T>,
        f: F,
    ) -> Self::Vector<T>;

    /// The indices of a vector's entries, rising, on the host.
    fn indices<T: Value>(v: &Self::Vector<T>) -> Vec<u32>;

    /// `Σ` of the row lengths of `a` at the places where `v` has entries (the edges a push
    /// from `v` would touch).
    fn row_lengths_at<T: Value, U: Value>(a: &Self::Matrix<T>, v: &Self::Vector<U>) -> u64;

    /// [`SparseBackend::mxv`] into `y`, whose storage (and the workspace's) is kept between
    /// calls: a backend may then allocate nothing in steady state. The default allocates.
    fn mxv_into<S: Semiring>(
        a: &Self::Matrix<S::T>,
        x: &Self::Vector<S::T>,
        mask: Option<&Self::Mask>,
        s: S,
        y: &mut Self::Vector<S::T>,
        _ws: &mut Self::Workspace,
        device: &Self::Device,
    ) -> Result<()> {
        *y = Self::mxv(a, x, mask, s, device)?;
        Ok(())
    }

    /// [`SparseBackend::vxm`] into `y`, storage kept as for [`SparseBackend::mxv_into`].
    fn vxm_into<S: Semiring>(
        x: &Self::Vector<S::T>,
        a: &Self::Matrix<S::T>,
        mask: Option<&Self::Mask>,
        s: S,
        y: &mut Self::Vector<S::T>,
        _ws: &mut Self::Workspace,
        device: &Self::Device,
    ) -> Result<()> {
        *y = Self::vxm(x, a, mask, s, device)?;
        Ok(())
    }

    /// Remove every entry of `v`, keeping its storage where the backend can.
    fn clear_vector<T: Value>(v: &mut Self::Vector<T>, device: &Self::Device) {
        let n = Self::len(v);
        *v = Self::vector(Vector::empty(n), device);
    }

    /// `v` becomes `value` at each of `indices` (any order, repeats kept once) and nothing
    /// else, keeping its storage where the backend can.
    fn load_indices<T: Value>(
        v: &mut Self::Vector<T>,
        indices: &[u32],
        value: T,
        device: &Self::Device,
    ) -> Result<()> {
        let n = Self::len(v);
        *v = Self::vector(Vector::from_indices(n, indices, value)?, device);
        Ok(())
    }

    /// `m` becomes a copy of the host mask `host`, keeping its storage where the backend can.
    fn mask_assign(m: &mut Self::Mask, host: &Mask, device: &Self::Device) {
        *m = Self::mask(host.clone(), device);
    }
}