crates/kleene-sparse/src/cpu.rs
use std::any::{Any, TypeId};
use std::ops::Range;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use arrow_buffer::ScalarBuffer;
use crate::backend::SparseBackend;
use crate::bitset::Bitset;
use crate::matrix::{Csr, MatrixMask, Pattern};
use crate::pool::{Executor, Pool, atomic_words, run_each, run_each_chunk};
use crate::semiring::{Semiring, Value};
use crate::simd::Simd;
use crate::simd::prefetch_read;
use crate::vector::{Mask, Vector};
use crate::{Result, SparseError};
/// The host: how many threads an operation may spread over (worker threads made once, at
/// the device's first parallel job, and parked between jobs) and the instruction set its
/// word kernels use. Clones share the workers. The threads are the built-in pool's unless
/// the device is made on another engine ([`CpuDevice::with_executor`]).
#[derive(Clone)]
pub struct CpuDevice {
threads: usize,
grain: usize,
exec: Arc<OnceLock<Arc<dyn Executor>>>,
simd: Simd,
}
impl std::fmt::Debug for CpuDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CpuDevice")
.field("threads", &self.threads)
.field("grain", &self.grain)
.field("simd", &self.simd)
.finish_non_exhaustive()
}
}
impl Default for CpuDevice {
/// Every core the process may use.
fn default() -> Self {
CpuDevice::new(
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1),
)
}
}
impl CpuDevice {
/// At most `threads` threads (at least one); `threads - 1` workers are started at the
/// first job that needs them (work that stays on the calling thread starts none).
pub fn new(threads: usize) -> Self {
CpuDevice {
threads: threads.max(1),
grain: 4096,
exec: Arc::new(OnceLock::new()),
simd: Simd::detect(),
}
}
/// A device whose parallel jobs run on `exec` (an engine the program already has),
/// with as many threads as it offers.
pub fn with_executor(exec: Arc<dyn Executor>) -> Self {
let threads = exec.threads().max(1);
let cell = OnceLock::new();
let _ = cell.set(exec);
CpuDevice {
threads,
grain: 4096,
exec: Arc::new(cell),
simd: Simd::detect(),
}
}
/// The strong components by the engine the device was made on, when it has a search
/// of its own (see [`Executor::strong_components`]); the built-in pool has none.
pub fn engine_strong_components(&self, off: &[u64], adj: &[u32]) -> Option<Vec<u32>> {
self.exec.get()?.strong_components(off, adj)
}
/// The mask walk by the engine the device was made on, when it has one (see
/// [`Executor::mask_walk`]); the built-in pool has none.
pub fn engine_mask_walk(
&self,
off: &[u64],
adj: &[u32],
batches: &[&[(u32, u64)]],
) -> Option<Vec<Vec<u64>>> {
self.exec.get()?.mask_walk(off, adj, batches)
}
/// The mask walk with edge sets by the engine the device was made on, when it has one
/// (see [`Executor::mask_walk_sets`]); the built-in pool has none.
pub fn engine_mask_walk_sets(
&self,
off: &[u64],
adj: &[u32],
slot_set: &[u32],
set_words: &[u64],
words: usize,
seeds: &[(u32, &[u64])],
) -> Option<Vec<u64>> {
self.exec
.get()?
.mask_walk_sets(off, adj, slot_set, set_words, words, seeds)
}
/// Where the device's parallel jobs run: its parked workers (started at the first
/// call), or the engine it was made on. A job run here spawns no thread once the
/// workers are up.
pub fn executor(&self) -> &dyn Executor {
self.pool()
}
fn pool(&self) -> &dyn Executor {
&**self
.exec
.get_or_init(|| Arc::new(Pool::new(self.threads)) as Arc<dyn Executor>)
}
/// The same device with work split in pieces of at least `grain` items (rows, entries);
/// smaller work runs on the calling thread.
pub fn with_grain(mut self, grain: usize) -> Self {
self.grain = grain.max(1);
self
}
/// The same device with its word kernels on `simd` (a level the host has).
pub fn with_simd(mut self, simd: Simd) -> Self {
self.simd = simd;
self
}
/// The number of threads.
pub fn threads(&self) -> usize {
self.threads
}
/// The least piece of work (rows, entries) split off to another thread.
pub fn grain(&self) -> usize {
self.grain
}
/// The instruction set of the word kernels.
pub fn simd(&self) -> Simd {
self.simd
}
/// Pieces of `0..n` for a split: (count, size), or none when the work stays on the
/// calling thread.
fn pieces(&self, n: usize) -> Option<(usize, usize)> {
if self.threads <= 1 || n < 2 * self.grain {
return None;
}
let pieces = (n / self.grain).min(self.threads * 8).max(2);
let size = n.div_ceil(pieces);
// Rounding the size up can leave fewer non-empty pieces than asked for.
Some((n.div_ceil(size), size))
}
/// Run `f` over pieces of `0..n` on up to `threads` threads (pieces are handed out from
/// a shared counter, so uneven rows balance) and return the results in piece order.
pub fn split<R: Send>(&self, n: usize, f: impl Fn(Range<usize>) -> R + Sync) -> Vec<R> {
let Some((pieces, size)) = self.pieces(n) else {
return vec![f(0..n)];
};
let out: Vec<Mutex<Option<R>>> = (0..pieces).map(|_| Mutex::new(None)).collect();
let next = AtomicUsize::new(0);
self.pool().run(self.threads.min(pieces), &|_| {
loop {
let p = next.fetch_add(1, Ordering::Relaxed);
if p >= pieces {
break;
}
let r = f(p * size..((p + 1) * size).min(n));
*out[p].lock().unwrap_or_else(|e| e.into_inner()) = Some(r);
}
});
out.into_iter()
.map(|m| {
m.into_inner()
.unwrap_or_else(|e| e.into_inner())
.expect("every piece ran")
})
.collect()
}
/// Run `f` over the pieces `cuts[p]..cuts[p + 1]` on up to `workers` threads (handed
/// out from a shared counter) and return the results in piece order; one worker runs
/// them on the calling thread.
pub(crate) fn split_cuts<R: Send>(
&self,
cuts: &[usize],
workers: usize,
f: impl Fn(Range<usize>) -> R + Sync,
) -> Vec<R> {
let pieces = cuts.len().saturating_sub(1);
if self.threads <= 1 || workers <= 1 || pieces <= 1 {
return cuts.windows(2).map(|w| f(w[0]..w[1])).collect();
}
let out: Vec<Mutex<Option<R>>> = (0..pieces).map(|_| Mutex::new(None)).collect();
let next = AtomicUsize::new(0);
self.pool()
.run(workers.min(self.threads).min(pieces), &|_| {
loop {
let p = next.fetch_add(1, Ordering::Relaxed);
if p >= pieces {
break;
}
let r = f(cuts[p]..cuts[p + 1]);
*out[p].lock().unwrap_or_else(|e| e.into_inner()) = Some(r);
}
});
out.into_iter()
.map(|m| {
m.into_inner()
.unwrap_or_else(|e| e.into_inner())
.expect("every piece ran")
})
.collect()
}
/// Run `f` over pieces of `0..n` handed out from a shared counter; each thread owns one
/// of `bufs` (reused between calls) and appends to it. Work below twice the grain runs on
/// the calling thread into `bufs[0]`. Nothing is spawned or allocated here.
pub fn each_mut<T: Send>(
&self,
bufs: &mut [T],
n: usize,
f: impl Fn(Range<usize>, &mut T) + Sync,
) {
if bufs.is_empty() {
return;
}
let Some((pieces, size)) = self.pieces(n).filter(|_| bufs.len() > 1) else {
f(0..n, &mut bufs[0]);
return;
};
let next = AtomicUsize::new(0);
let workers = bufs.len().min(self.threads).min(pieces);
run_each(self.pool(), &mut bufs[..workers], &|_, buf| {
loop {
let p = next.fetch_add(1, Ordering::Relaxed);
if p >= pieces {
break;
}
f(p * size..((p + 1) * size).min(n), buf);
}
});
}
/// Run `f(t, &mut bufs[t])` for every buffer, one thread each (the calling thread
/// alone when there is one buffer or one thread).
pub fn each_block<T: Send>(&self, bufs: &mut [T], f: impl Fn(usize, &mut T) + Sync) {
if self.threads <= 1 || bufs.len() <= 1 {
for (t, b) in bufs.iter_mut().enumerate() {
f(t, b);
}
return;
}
let n = bufs.len().min(self.threads);
let (now, rest) = bufs.split_at_mut(n);
run_each(self.pool(), now, &f);
for (t, b) in rest.iter_mut().enumerate() {
f(n + t, b);
}
}
}
impl CpuDevice {
/// Run `f(t, &mut bufs[t], piece_t)` for every buffer, one thread each, where `piece_t`
/// is `data[t * per..(t + 1) * per]`: threads own disjoint pieces of `data`.
fn each_block_chunk<T: Send, U: Send>(
&self,
bufs: &mut [T],
data: &mut [U],
per: usize,
f: impl Fn(usize, &mut T, &mut [U]) + Sync,
) {
if self.threads <= 1 || bufs.len() <= 1 {
let len = data.len();
for (t, b) in bufs.iter_mut().enumerate() {
let lo = (t * per).min(len);
let hi = ((t + 1) * per).min(len);
f(t, b, &mut data[lo..hi]);
}
return;
}
run_each_chunk(self.pool(), bufs, data, per, &f);
}
}
/// Per-thread lists of a value type, kept in a workspace between calls.
#[derive(Debug)]
struct Lists<T: Value> {
per_thread: Vec<(Vec<u32>, Vec<T>)>,
/// A dense accumulator and the places it holds.
dense: Vec<T>,
present: Bitset,
/// A sparse operand spread densely for lookups, and its places.
xdense: Vec<T>,
xpresent: Bitset,
/// The matrix the last `vxm_into` with a full operand read, and its transpose once a
/// second such call read the same matrix.
kept: Option<Kept<T>>,
}
/// A matrix (its buffers held, so their addresses name it) and its transpose, once made.
#[derive(Debug)]
struct Kept<T: Value> {
of: Csr<T>,
t: Option<Csr<T>>,
}
/// Whether `a` and `b` are the same matrix: the same shared buffers (a [`Kept`] holds its
/// matrix's, so no other matrix can sit at their addresses while it is kept).
fn same_buffers<T: Value>(a: &Csr<T>, b: &Csr<T>) -> bool {
let (pa, pb) = (a.pattern(), b.pattern());
pa.major() == pb.major()
&& pa.minor() == pb.minor()
&& std::ptr::eq(pa.offsets().as_ptr(), pb.offsets().as_ptr())
&& std::ptr::eq(pa.indices().as_ptr(), pb.indices().as_ptr())
&& pa.indices().len() == pb.indices().len()
&& match (a.values(), b.values()) {
(None, None) => true,
(Some(x), Some(y)) => std::ptr::eq(x.as_ptr(), y.as_ptr()) && x.len() == y.len(),
_ => false,
}
}
/// Buffers a traversal or a product reuses call after call: frontier marks, per-thread
/// lists, and per value type the lists and dense scratch of `mxv` and `vxm`.
#[derive(Debug)]
pub struct CpuWorkspace {
marks: Bitset,
lists: Vec<(Vec<u32>, u64)>,
flist: Vec<u32>,
typed: Vec<(TypeId, Box<dyn Any + Send>)>,
/// The transposes the typed scratch keeps ([`CpuWorkspace::kept_transposes`]).
transposes: usize,
}
impl<T: Value> Default for Lists<T> {
fn default() -> Self {
Lists {
per_thread: Vec::new(),
dense: Vec::new(),
present: Bitset::new(0),
xdense: Vec::new(),
xpresent: Bitset::new(0),
kept: None,
}
}
}
impl CpuWorkspace {
/// The transposes this workspace keeps for `vxm_into` with a full operand (one per
/// value type at most): a second such call on the same matrix makes its transpose, and
/// later ones pull over it.
pub fn kept_transposes(&self) -> usize {
self.transposes
}
/// The scratch of value type `T` (made the first time it is asked for).
fn typed<T: Value>(&mut self, threads: usize) -> &mut Lists<T> {
typed_slot(&mut self.typed, threads)
}
}
/// The scratch of value type `T` in `typed`, with at least `threads` per-thread lists.
fn typed_slot<T: Value>(
typed: &mut Vec<(TypeId, Box<dyn Any + Send>)>,
threads: usize,
) -> &mut Lists<T> {
let id = TypeId::of::<T>();
let at = match typed.iter().position(|(t, _)| *t == id) {
Some(i) => i,
None => {
typed.push((id, Box::new(Lists::<T>::default())));
typed.len() - 1
}
};
let l = typed[at]
.1
.downcast_mut::<Lists<T>>()
.expect("stored under its own type id");
if l.per_thread.len() < threads {
l.per_thread.resize_with(threads, Default::default);
}
l
}
/// Push the rows of `frontier` on one thread: every place an edge reaches that the mask
/// words allow (a clear bit when `COMPLEMENT`, a set bit otherwise) is closed and appended to
/// `out`. Returns the edges examined. The words and the list are plain slices here, so the
/// loop keeps them in registers.
#[inline]
fn push_rows<const COMPLEMENT: bool>(
frontier: &[u32],
off: &[u64],
idx: &[u32],
words: &mut [u64],
out: &mut Vec<u32>,
) -> u64 {
let mut work = 0u64;
for &v in frontier {
let row = &idx[off[v as usize] as usize..off[v as usize + 1] as usize];
work += row.len() as u64;
for &w in row {
let (wi, m) = ((w >> 6) as usize, 1u64 << (w & 63));
let cur = words[wi];
if (cur & m == 0) == COMPLEMENT {
words[wi] = cur ^ m;
out.push(w);
}
}
}
work
}
/// Append the set places of `marks` to `out`, rising, and clear them: counted, written by
/// the compaction kernel into the grown list, then the words zeroed.
fn take_marks(simd: Simd, marks: &mut Bitset, out: &mut Vec<u32>) {
let words = marks.words_mut();
let at = out.len();
out.resize(at + simd.popcount(words), 0);
simd.bits_to_places(words, 0, &mut out[at..]);
words.fill(0);
}
/// Call `f` on every place of `lo..hi` that `open` allows (64 places per word read; runs of
/// closed words are skipped eight at a time by the word kernel).
#[inline]
fn allowed_in(open: &Mask, simd: Simd, lo: usize, hi: usize, mut f: impl FnMut(usize)) {
let words = open.bits().words();
let flip = if open.is_complement() { u64::MAX } else { 0 };
let end = hi.div_ceil(64).min(words.len());
let mut wi = lo / 64;
while wi < end {
wi = simd.first_nonzero(&words[..end], flip, wi);
if wi >= end {
break;
}
let mut w = words[wi] ^ flip;
let base = wi * 64;
if base < lo {
w &= u64::MAX << (lo - base);
}
if base + 64 > hi {
w &= (1u64 << (hi - base)) - 1;
}
while w != 0 {
let t = w.trailing_zeros() as usize;
w &= w - 1;
f(base + t);
}
wi += 1;
}
}
/// The CPU backend: compressed rows on the host, products spread over every core with
/// scoped threads.
#[derive(Clone, Copy, Debug, Default)]
pub struct CpuBackend;
fn shape_err(op: &'static str, detail: String) -> SparseError {
SparseError::Shape { op, detail }
}
/// Rows `0..n` of a compressed matrix as pieces (offsets from 0, indices, values).
struct Rows<T> {
counts: Vec<u64>,
indices: Vec<u32>,
values: Vec<T>,
}
/// How a sparse product is split ([`CpuBackend::mxm_plan`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MxmPlan {
/// Its multiply-adds (with one a row; 0 when one thread was asked for).
pub flops: u64,
/// The workers it wakes (1: the calling thread alone).
pub workers: usize,
/// The rows' cuts: piece `p` is rows `cuts[p]..cuts[p + 1]`.
pub cuts: Vec<usize>,
}
/// One worker's scratch for a sparse product: the dense accumulator, its stamps, the
/// mask's stamps, the columns a row touched, and the pieces it made.
struct MxmScratch<T> {
acc: Vec<T>,
seen: Vec<u32>,
allowed: Vec<u32>,
touched: Vec<u32>,
done: Vec<(usize, Rows<T>)>,
}
impl<T> Default for MxmScratch<T> {
fn default() -> Self {
MxmScratch {
acc: Vec::new(),
seen: Vec::new(),
allowed: Vec::new(),
touched: Vec::new(),
done: Vec::new(),
}
}
}
fn join_rows<T: Value>(
nrows: usize,
ncols: usize,
pieces: Vec<Rows<T>>,
device: &CpuDevice,
) -> Result<Csr<T>> {
join_rows_as(nrows, ncols, pieces, true, device)
}
/// Below this many entries a result's rows are joined on the calling thread: rmat12's
/// 1131361 entries copy in 0.4 ms there, about what waking the workers costs (loki).
const JOIN_ALONE: usize = 1 << 21;
/// A piece's rows and the parts of the result's arrays its entries are copied into.
type JoinPart<'a, T> = (Rows<T>, &'a mut [u32], &'a mut [T]);
/// Rows joined into one matrix, with their values or (`valued` false) structural. The
/// offsets are written on the calling thread; a large result's entries are copied on the
/// workers, into its arrays cut at the pieces' bounds (their pages first touched there).
fn join_rows_as<T: Value>(
nrows: usize,
ncols: usize,
pieces: Vec<Rows<T>>,
valued: bool,
device: &CpuDevice,
) -> Result<Csr<T>> {
let nnz: usize = pieces.iter().map(|p| p.indices.len()).sum();
let mut offsets = Vec::with_capacity(nrows + 1);
offsets.push(0u64);
let mut base = 0u64;
for p in &pieces {
offsets.extend(p.counts.iter().map(|c| base + c));
base += p.indices.len() as u64;
}
let workers = device.threads().min(pieces.len());
let (indices, values) = if nnz < JOIN_ALONE || workers <= 1 {
let mut indices = Vec::with_capacity(nnz);
let mut values = Vec::with_capacity(if valued { nnz } else { 0 });
for p in pieces {
indices.extend_from_slice(&p.indices);
if valued {
values.extend_from_slice(&p.values);
}
}
(indices, values)
} else {
let mut indices = vec![0u32; nnz];
let mut values = vec![T::default(); if valued { nnz } else { 0 }];
let mut parts: Vec<Vec<JoinPart<'_, T>>> = (0..workers).map(|_| Vec::new()).collect();
let (mut idx, mut val) = (&mut indices[..], &mut values[..]);
for (k, p) in pieces.into_iter().enumerate() {
let len = p.indices.len();
let (i, i_rest) = std::mem::take(&mut idx).split_at_mut(len);
let (v, v_rest) = std::mem::take(&mut val).split_at_mut(if valued { len } else { 0 });
(idx, val) = (i_rest, v_rest);
parts[k % workers].push((p, i, v));
}
device.each_block(&mut parts, |_, mine| {
for (p, i, v) in mine.iter_mut() {
i.copy_from_slice(&p.indices);
v.copy_from_slice(&p.values[..v.len()]);
}
});
drop(parts);
(indices, values)
};
Csr::new(
nrows,
ncols,
ScalarBuffer::from(offsets),
ScalarBuffer::from(indices),
valued.then(|| ScalarBuffer::from(values)),
)
}
/// The most blocks a dense result is cut into (their pieces sit in an array on the stack).
const DENSE_BLOCKS: usize = 64;
impl CpuBackend {
/// Below this many rows and entries a full-operand `mxv` runs on one thread. A row is a
/// branch the predictor misses, about 4 ns: zox-M (29772 rows, 59105 entries) takes
/// 0.42 ms on one thread and 0.05 on 12, while rmat12 (4096 rows, 28760 entries) is
/// faster on one (0.047 ms against 0.068 on 12, dwarf).
pub const FULL_MXV_SERIAL_BELOW: usize = 1 << 16;
/// The blocks of a full-operand `mxv` over `work` rows and entries.
fn full_blocks(work: usize, device: &CpuDevice) -> usize {
if device.threads <= 1 || work < Self::FULL_MXV_SERIAL_BELOW {
1
} else {
device.threads
}
}
}
impl CpuBackend {
/// How far ahead a full-operand `mxv` reads its operand: while an entry is folded, the
/// operand's place of the entry this many entries on (across rows) is asked for
/// ([`prefetch_read`]). The operand's reads are random and do not depend on each
/// other, but without the hint the core keeps only as many of them in flight as its
/// window holds entries, so a semiring with more instructions per entry (min-plus's
/// saturating add and min) waited longer. On an R-MAT graph of 2^22 vertices (65 M
/// entries, a 16 MB operand) min-plus `u32` took about 600 ms on one thread, and 250 ms
/// with the hint (oden, Zen 2; 32 to 128 entries ahead gave about the same, 8 and 16
/// less).
const FULL_MXV_FETCH_AHEAD: usize = 64;
/// An operand of at least this many bytes is read ahead ([`Self::FULL_MXV_FETCH_AHEAD`]);
/// a smaller one is read from a near cache, where the hint is only extra work (oden:
/// 2 MB of `f64` 25 % slower with it on one thread, 4 MB of `u32` 10-30 % faster).
const FULL_MXV_FETCH_FROM: usize = 1 << 22;
/// A row of `A` (its columns `cols`, its values `vals` or structural) folded against a
/// full operand `xv`; the terminal's test only where the semiring has one. With
/// `FETCH`, `ahead` holds the columns [`Self::FULL_MXV_FETCH_AHEAD`] entries after the
/// row's own (as many as there are), whose operand places are asked for on the way;
/// the fold itself is the same either way.
#[inline]
#[allow(clippy::too_many_arguments)]
fn full_row<S: Semiring, const FETCH: bool>(
cols: &[u32],
vals: Option<&[S::T]>,
xv: &[S::T],
s: S,
one: S::T,
terminal: Option<S::T>,
ahead: &[u32],
) -> Option<S::T> {
let fetch = |k: usize| {
if FETCH && let Some(&j) = ahead.get(k) {
prefetch_read(xv, j as usize);
}
};
let (&j0, rest) = cols.split_first()?;
let w = |k: usize| vals.map_or(one, |v| v[k]);
fetch(0);
let mut t = s.mul(w(0), xv[j0 as usize]);
match (terminal, vals) {
(Some(term), _) => {
for (k, &j) in rest.iter().enumerate() {
if t == term {
break;
}
fetch(k + 1);
t = s.add(t, s.mul(w(k + 1), xv[j as usize]));
}
}
(None, Some(v)) => {
for (k, (&j, &a)) in rest.iter().zip(&v[1..]).enumerate() {
fetch(k + 1);
t = s.add(t, s.mul(a, xv[j as usize]));
}
}
(None, None) => {
for (k, &j) in rest.iter().enumerate() {
fetch(k + 1);
t = s.add(t, s.mul(one, xv[j as usize]));
}
}
}
Some(t)
}
}
impl CpuBackend {
/// The product of a structural entry and every value of a full operand, when the
/// operand holds one value `c` and `p = one * c` folds to itself (`p + p = p`, so a row
/// of any length folds to `p`); `None` otherwise. Reads the operand until a second
/// value shows (at once for most operands).
pub fn iso_product<S: Semiring>(x: &[S::T], s: S) -> Option<S::T> {
let &c = x.first()?;
if !x.iter().all(|&v| v == c) {
return None;
}
let p = s.mul(s.one(), c);
(s.add(p, p) == p).then_some(p)
}
}
impl CpuBackend {
/// Write `y` densely in place: row `i` (each row the mask allows) gets `fold(i)`, its
/// place set when that is an entry. `blocks` blocks of about equal entries (`off`, the
/// rows' offsets, `nnz` entries; `off` empty: of about equal rows) on 64-row boundaries,
/// each block its own values and its own words of places, one worker each; nothing
/// allocated once `y` is dense.
#[allow(clippy::too_many_arguments)]
fn dense_rows<T: Value, F: Fn(usize) -> Option<T> + Sync>(
n: usize,
nnz: u64,
off: &[u64],
blocks: usize,
mask: Option<&Mask>,
y: &mut Vector<T>,
zero: T,
device: &CpuDevice,
fold: &F,
) {
let simd = device.simd;
let (yv, yp) = y.dense_parts_mut(zero);
let words = yp.words_mut();
let one = |lo: usize, vals: &mut [T], w: &mut [u64]| {
w.fill(0);
let hi = lo + vals.len();
let mut put = |i: usize| {
if let Some(t) = fold(i) {
vals[i - lo] = t;
w[(i - lo) / 64] |= 1u64 << ((i - lo) % 64);
}
};
match mask {
Some(m) => allowed_in(m, simd, lo, hi, &mut put),
None => {
// a word of places built in a register, 64 rows at a time
for (c, (word, vals)) in w.iter_mut().zip(vals.chunks_mut(64)).enumerate() {
let base = lo + c * 64;
let mut bits = 0u64;
for (k, v) in vals.iter_mut().enumerate() {
if let Some(t) = fold(base + k) {
*v = t;
bits |= 1u64 << k;
}
}
*word = bits;
}
}
}
};
let blocks = blocks.clamp(1, DENSE_BLOCKS);
if blocks == 1 {
one(0, yv, words);
return;
}
let cut = |t: usize| -> usize {
if t == 0 {
return 0;
}
if t >= blocks {
return n;
}
let r = if off.is_empty() {
n * t / blocks
} else {
let want = nnz * t as u64 / blocks as u64;
off.partition_point(|&o| o < want).min(n)
};
(r / 64 * 64).min(n)
};
let mut parts: [(usize, &mut [T], &mut [u64]); DENSE_BLOCKS] =
std::array::from_fn(|_| (0, Default::default(), Default::default()));
let (mut rv, mut rw) = (yv, words);
for (t, part) in parts.iter_mut().enumerate().take(blocks) {
let (lo, hi) = (cut(t), cut(t + 1));
let (v, rest) = std::mem::take(&mut rv).split_at_mut(hi - lo);
rv = rest;
let (w, rest) = std::mem::take(&mut rw).split_at_mut(hi.div_ceil(64) - lo.div_ceil(64));
rw = rest;
*part = (lo, v, w);
}
device.each_block(&mut parts[..blocks], |_, (lo, v, w)| one(*lo, v, w));
}
}
/// How [`SparseBackend::transpose`] splits a transpose on the workers
/// ([`CpuBackend::transpose_plan`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransposePlan {
/// The workers it wakes (1: the calling thread alone).
pub workers: usize,
/// The columns of a block (a power of two; the matrix's columns when one thread runs).
pub width: usize,
/// The rows of the matrix each worker reads in the first pass: worker `t` reads rows
/// `rows[t]..rows[t + 1]`, cut to about equal entries.
pub rows: Vec<usize>,
}
/// One worker's part of the first pass of a transpose: its rows, its count per block,
/// and (once counted) its run in each block's bucket.
struct BucketPart<'a, T> {
rows: Range<usize>,
counts: Vec<u64>,
runs: Vec<(&'a mut [u32], &'a mut [u32], &'a mut [T])>,
}
/// One worker's part of the second pass: its blocks, their buckets (read), its run of
/// the result and its columns' offsets.
struct BlockPart<'a, T> {
blocks: Range<usize>,
first: u64,
idx: &'a mut [u32],
val: &'a mut [T],
offsets: &'a mut [u64],
}
impl CpuBackend {
/// Below this many entries a transpose stays on the calling thread (one counting sort).
pub const TRANSPOSE_SERIAL_BELOW: usize = 1 << 16;
/// How [`SparseBackend::transpose`] splits `a`'s transpose on `device`, in two passes
/// of a bucket sort. First each worker reads its rows (pieces of about equal entries)
/// and moves each entry, with its row, into the bucket of its block of `width`
/// columns, at a run of its own in that bucket. Then each worker takes whole blocks
/// (about equal entries) and sorts each block's entries by column in a counting sort
/// over `width` columns, small enough to stay in cache. The buckets hold the rows in
/// rising order, so each row of the result rises.
pub fn transpose_plan<T: Value>(a: &Csr<T>, device: &CpuDevice) -> TransposePlan {
let (nr, nc) = (a.nrows(), a.ncols());
if device.threads <= 1 || a.nnz() < Self::TRANSPOSE_SERIAL_BELOW || nr < 2 || nc < 2 {
return TransposePlan {
workers: 1,
width: nc.max(1),
rows: vec![0, nr],
};
}
let width = nc.div_ceil(device.threads * 64).max(64).next_power_of_two();
let off = a.pattern().offsets();
let want = device.threads.min(nr);
let total = a.nnz() as u64 + nr as u64;
let mut rows = vec![0usize];
for t in 1..want {
let goal = total * t as u64 / want as u64;
let (mut lo, mut hi) = (0usize, nr);
while lo < hi {
let mid = (lo + hi) / 2;
if off[mid] + mid as u64 <= goal {
lo = mid + 1;
} else {
hi = mid;
}
}
if lo > *rows.last().unwrap_or(&0) && lo < nr {
rows.push(lo);
}
}
rows.push(nr);
TransposePlan {
workers: rows.len() - 1,
width,
rows,
}
}
/// The transpose of `a` on `device` by [`CpuBackend::transpose_plan`]; the rows of the
/// result rise, as [`Csr::transpose`]'s.
fn transpose_on<T: Value>(a: &Csr<T>, device: &CpuDevice) -> Csr<T> {
let plan = Self::transpose_plan(a, device);
if plan.workers <= 1 {
return a.transpose();
}
let (nr, nc, nnz) = (a.nrows(), a.ncols(), a.nnz());
let (off, idx) = (a.pattern().offsets(), a.pattern().indices());
let vals = a.values();
let shift = plan.width.trailing_zeros();
let nb = nc.div_ceil(plan.width);
let workers = plan.workers;
// Pass one, counting: entries per worker per block.
let mut parts: Vec<BucketPart<'_, T>> = plan
.rows
.windows(2)
.map(|w| BucketPart {
rows: w[0]..w[1],
counts: vec![0; nb],
runs: Vec::new(),
})
.collect();
device.each_block(&mut parts, |_, p| {
let (lo, hi) = (off[p.rows.start] as usize, off[p.rows.end] as usize);
for &j in &idx[lo..hi] {
p.counts[(j >> shift) as usize] += 1;
}
});
// The buckets block by block, each block's runs worker by worker.
let mut tr = vec![0u32; nnz];
let mut tc = vec![0u32; nnz];
let mut tv: Vec<T> = if vals.is_some() {
vec![T::default(); nnz]
} else {
Vec::new()
};
let mut block_start = Vec::with_capacity(nb + 1);
{
let (mut rr, mut rc, mut rv) = (&mut tr[..], &mut tc[..], &mut tv[..]);
let mut at = 0u64;
for b in 0..nb {
block_start.push(at);
for p in parts.iter_mut() {
let len = p.counts[b] as usize;
at += len as u64;
let (r, rest) = std::mem::take(&mut rr).split_at_mut(len);
rr = rest;
let (c, rest) = std::mem::take(&mut rc).split_at_mut(len);
rc = rest;
let vl = if vals.is_some() { len } else { 0 };
let (v, rest) = std::mem::take(&mut rv).split_at_mut(vl);
rv = rest;
p.runs.push((r, c, v));
}
}
block_start.push(at);
// Pass one, moving: each worker its rows into its runs.
device.each_block(&mut parts, |_, p| {
let mut cur = vec![0usize; nb];
for i in p.rows.clone() {
for k in off[i] as usize..off[i + 1] as usize {
let j = idx[k];
let b = (j >> shift) as usize;
let at = cur[b];
let run = &mut p.runs[b];
run.0[at] = i as u32;
run.1[at] = j;
if let Some(v) = vals {
run.2[at] = v[k];
}
cur[b] = at + 1;
}
}
});
}
drop(parts);
// Pass two: whole blocks a worker, about equal entries, each sorted by column.
let mut out_idx = vec![0u32; nnz];
let mut out_val: Vec<T> = if vals.is_some() {
vec![T::default(); nnz]
} else {
Vec::new()
};
let mut offsets = vec![0u64; nc + 1];
let mut cuts = vec![0usize];
for t in 1..workers {
let goal = nnz as u64 * t as u64 / workers as u64;
let b = block_start.partition_point(|&s| s < goal).min(nb);
if b > *cuts.last().unwrap_or(&0) && b < nb {
cuts.push(b);
}
}
cuts.push(nb);
let mut blocks: Vec<BlockPart<'_, T>> = Vec::with_capacity(cuts.len() - 1);
{
let (mut ri, mut rv, mut ro) = (&mut out_idx[..], &mut out_val[..], &mut offsets[1..]);
for w in cuts.windows(2) {
let len = (block_start[w[1]] - block_start[w[0]]) as usize;
let (i, rest) = std::mem::take(&mut ri).split_at_mut(len);
ri = rest;
let vl = if vals.is_some() { len } else { 0 };
let (v, rest) = std::mem::take(&mut rv).split_at_mut(vl);
rv = rest;
let cols = (w[1] * plan.width).min(nc) - w[0] * plan.width;
let (o, rest) = std::mem::take(&mut ro).split_at_mut(cols);
ro = rest;
blocks.push(BlockPart {
blocks: w[0]..w[1],
first: block_start[w[0]],
idx: i,
val: v,
offsets: o,
});
}
}
let (tr, tc, tv) = (&tr, &tc, &tv);
let block_start = &block_start;
let width = plan.width;
device.each_block(&mut blocks, |_, p| {
let mut next = vec![0u64; width];
for b in p.blocks.clone() {
let (lo, hi) = (block_start[b] as usize, block_start[b + 1] as usize);
let c0 = b * width;
let cols = ((b + 1) * width).min(nc) - c0;
next[..cols].fill(0);
for &j in &tc[lo..hi] {
next[j as usize - c0] += 1;
}
// the entries before each column, and each column's end as its offset
let mut at = lo as u64;
for (c, n) in next[..cols].iter_mut().enumerate() {
let here = *n;
*n = at;
at += here;
p.offsets[c0 + c - p.blocks.start * width] = at;
}
for q in lo..hi {
let c = tc[q] as usize - c0;
let to = (next[c] - p.first) as usize;
p.idx[to] = tr[q];
if vals.is_some() {
p.val[to] = tv[q];
}
next[c] += 1;
}
}
});
drop(blocks);
let pattern = Pattern::trusted(
nc,
nr,
ScalarBuffer::from(offsets),
ScalarBuffer::from(out_idx),
"transpose",
)
.expect("the offsets end at the entries");
Csr::with_pattern(pattern, vals.map(|_| ScalarBuffer::from(out_val)))
.expect("a value an entry")
}
}
/// `f(x, y)` for each index both rising lists hold, at its places `x` in `a` and `y` in
/// `b`, rising: a merge of the two, or, when one is at least
/// [`CpuBackend::MXM_GALLOP_RATIO`] times longer, each entry of the short one found in the
/// long one by galloping (doubling steps from the last place found, then a binary search).
#[inline]
fn each_common(a: &[u32], b: &[u32], mut f: impl FnMut(usize, usize)) {
let ratio = CpuBackend::MXM_GALLOP_RATIO as usize;
if a.is_empty() || b.is_empty() {
return;
}
if b.len() >= ratio * a.len() {
let mut from = 0;
for (x, &k) in a.iter().enumerate() {
from = gallop(b, from, k);
if from == b.len() {
return;
}
if b[from] == k {
f(x, from);
from += 1;
}
}
return;
}
if a.len() >= ratio * b.len() {
let mut from = 0;
for (y, &k) in b.iter().enumerate() {
from = gallop(a, from, k);
if from == a.len() {
return;
}
if a[from] == k {
f(from, y);
from += 1;
}
}
return;
}
let (mut x, mut y) = (0, 0);
while x < a.len() && y < b.len() {
let (cx, cy) = (a[x], b[y]);
if cx == cy {
f(x, y);
x += 1;
y += 1;
} else if cx < cy {
x += 1;
} else {
y += 1;
}
}
}
/// The first place at or after `from` in the rising list `long` whose index is not below
/// `k` (`long.len()` for none): steps of 1, 2, 4, .. past `from`, then a binary search in
/// the last step.
#[inline]
fn gallop(long: &[u32], from: usize, k: u32) -> usize {
let (mut lo, mut hi, mut step) = (from, from, 1);
while hi < long.len() && long[hi] < k {
lo = hi + 1;
hi += step;
step *= 2;
}
let hi = hi.min(long.len());
lo + long[lo..hi].partition_point(|&y| y < k)
}
impl CpuBackend {
/// How [`SparseBackend::mxm`] splits `a` x `b` on `device`: its estimated multiply-adds,
/// the workers it wakes and the rows' cuts. A product estimated below
/// [`CpuBackend::MXM_SERIAL_BELOW`] stays on the calling thread: one accumulator, one
/// piece.
pub fn mxm_plan<T: Value>(a: &Csr<T>, b: &Csr<T>, device: &CpuDevice) -> MxmPlan {
let n = a.nrows();
let flops = Self::mxm_work(a, b);
let serial = MxmPlan {
flops,
workers: 1,
cuts: vec![0, n],
};
if device.threads <= 1 || flops < Self::MXM_SERIAL_BELOW || n < 2 {
return serial;
}
// Eight pieces a worker, of about equal entries of `a` (one more a row), taken from a
// shared counter: rows heavy with products balance by the count.
let want = (device.threads * 8).min(n);
let off = a.pattern().offsets();
let total = a.nnz() as u64 + n as u64;
let mut cuts = vec![0usize];
for t in 1..want {
let goal = total * t as u64 / want as u64;
// the first row whose start (entries before it, one a row) passes the goal
let (mut lo, mut hi) = (0usize, n);
while lo < hi {
let mid = (lo + hi) / 2;
if off[mid] + mid as u64 <= goal {
lo = mid + 1;
} else {
hi = mid;
}
}
let at = lo;
if at > *cuts.last().unwrap_or(&0) && at < n {
cuts.push(at);
}
}
cuts.push(n);
let workers = device.threads.min(cuts.len() - 1);
MxmPlan {
flops,
workers,
cuts,
}
}
/// Whether [`SparseBackend::mxm`] computes `a` x `b` under `mask` by dot products: each
/// place the mask allows, a row of `a` intersected with a column of `b` (a transpose of
/// `b` made for it), when that is the cheaper side against Gustavson's multiply-adds.
/// The dots' side: the transpose ([`CpuBackend::MXM_TRANSPOSE_STEP`] an entry) and each
/// place of the mask in row `i` at [`CpuBackend::dot_steps`] of the row's length and a
/// column of `b` at its mean length ([`CpuBackend::MXM_DOT_STEP`] a step). Gustavson's
/// side: first its bound (`a`'s entries times `b`'s longest row) and, only when the dots
/// beat that, its multiply-adds counted exactly ([`CpuBackend::mxm_flops`]); the counts
/// run on `device`'s workers. After the transpose `mxm` counts the columns' own lengths
/// and still takes Gustavson's rows when a long column turns the sum. A complemented
/// mask allows nearly every place: never.
pub fn mxm_by_dots<T: Value>(
a: &Csr<T>,
b: &Csr<T>,
mask: &MatrixMask,
device: &CpuDevice,
) -> bool {
Self::dots_against(a, b, mask, device).is_some()
}
/// See [`CpuBackend::mxm_by_dots`]: Gustavson's multiply-adds when the dots are taken.
fn dots_against<T: Value>(
a: &Csr<T>,
b: &Csr<T>,
mask: &MatrixMask,
device: &CpuDevice,
) -> Option<u64> {
if mask.complement || a.nrows() == 0 || b.ncols() == 0 {
return None;
}
let bo = b.pattern().offsets();
let longest = Self::on_rows(b.nrows(), b.nnz(), device, |rows| {
rows.map(|k| bo[k + 1] - bo[k]).max().unwrap_or(0)
})
.into_iter()
.max()
.unwrap_or(0);
let bound = (a.nnz() as u64).saturating_mul(longest) + a.nrows() as u64;
let transpose = b.nnz() as f64 * Self::MXM_TRANSPOSE_STEP;
if transpose >= bound as f64 {
return None;
}
let col_b = (b.nnz() as u64).div_ceil(b.ncols() as u64);
let (ao, mo) = (a.pattern().offsets(), mask.pattern.offsets());
let steps: u64 = Self::on_rows(a.nrows(), a.nnz(), device, |rows| {
rows.map(|i| (mo[i + 1] - mo[i]) * Self::dot_steps(ao[i + 1] - ao[i], col_b))
.sum::<u64>()
})
.into_iter()
.sum();
let dots = transpose + steps as f64 * Self::MXM_DOT_STEP;
if dots >= bound as f64 {
return None;
}
let work = Self::mxm_flops(a, b, device);
(dots < work as f64).then_some(work)
}
/// `f` over rows `0..n` (`entries` in them): on the calling thread when small or on one
/// thread, else in pieces on `device`'s workers.
fn on_rows<R: Send>(
n: usize,
entries: usize,
device: &CpuDevice,
f: impl Fn(Range<usize>) -> R + Sync,
) -> Vec<R> {
if device.threads <= 1 || ((n + entries) as u64) < Self::MXM_SERIAL_BELOW {
vec![f(0..n)]
} else {
device.split(n, f)
}
}
/// The multiply-adds of Gustavson's `a` x `b`: for each entry `(i, k)` of `a` the length
/// of row `k` of `b`, one more a row of `a`; counted in pieces of rows on `device`.
pub fn mxm_flops<T: Value>(a: &Csr<T>, b: &Csr<T>, device: &CpuDevice) -> u64 {
let (ai, bo) = (a.pattern().indices(), b.pattern().offsets());
let ao = a.pattern().offsets();
let n = a.nrows();
Self::on_rows(n, a.nnz(), device, |rows| {
let (lo, hi) = (ao[rows.start] as usize, ao[rows.end] as usize);
ai[lo..hi]
.iter()
.map(|&k| bo[k as usize + 1] - bo[k as usize])
.sum::<u64>()
+ rows.len() as u64
})
.into_iter()
.sum()
}
/// The steps of one dot product of two rising lists of lengths `x` and `y`: a merge
/// walks both (`x + y`); when one is at least [`CpuBackend::MXM_GALLOP_RATIO`] times
/// longer, each entry of the short one is found in the long one by galloping, about
/// `short * (1 + 2 log2(long / short))`. An empty list costs nothing.
pub fn dot_steps(x: u64, y: u64) -> u64 {
let (s, l) = (x.min(y), x.max(y));
if s == 0 {
0
} else if l >= Self::MXM_GALLOP_RATIO * s {
s * (1 + 2 * u64::from((l / s).ilog2()))
} else {
s + l
}
}
/// See [`CpuBackend::dot_steps`]: a list this many times longer than the other is
/// searched by galloping, not merged.
pub const MXM_GALLOP_RATIO: u64 = 8;
/// How the dots of `a` x `b` under `mask` split on `device` (`bt`, the transpose of
/// `b`): `flops` the steps of the dots, each place `(i, j)` of the mask
/// [`CpuBackend::dot_steps`] of row `i` of `a` and row `j` of `bt` (a merge, or galloping
/// when one is far longer), and rows cut to pieces of about
/// equal steps (one more a row), eight a worker, taken from a shared counter. A row with
/// many long merges no longer holds a piece of equal rows back.
pub fn mxm_dots_plan<T: Value>(
a: &Csr<T>,
bt: &Csr<T>,
mask: &MatrixMask,
device: &CpuDevice,
) -> MxmPlan {
let n = a.nrows();
let (ao, mo) = (a.pattern().offsets(), mask.pattern.offsets());
let bo = bt.pattern().offsets();
let mi = mask.pattern.indices();
// each row's steps, one more a row, counted on the workers (the columns' lengths
// are reads all over the transpose's offsets), then the steps before each row
let steps = device.split(n, |rows| {
rows.map(|i| {
let (lo, hi) = (mo[i] as usize, mo[i + 1] as usize);
let la = ao[i + 1] - ao[i];
mi[lo..hi]
.iter()
.map(|&j| Self::dot_steps(la, bo[j as usize + 1] - bo[j as usize]))
.sum::<u64>()
+ 1
})
.collect::<Vec<u64>>()
});
let mut before = Vec::with_capacity(n + 1);
let mut total = 0u64;
before.push(0u64);
for piece in steps {
for c in piece {
total += c;
before.push(total);
}
}
let flops = total - n as u64;
if device.threads <= 1 || flops < Self::MXM_SERIAL_BELOW || n < 2 {
return MxmPlan {
flops,
workers: 1,
cuts: vec![0, n],
};
}
let want = (device.threads * 8).min(n);
let mut cuts = vec![0usize];
for t in 1..want {
let goal = total * t as u64 / want as u64;
let at = before
.partition_point(|&x| x <= goal)
.saturating_sub(1)
.min(n);
if at > *cuts.last().unwrap_or(&0) && at < n {
cuts.push(at);
}
}
cuts.push(n);
MxmPlan {
flops,
workers: device.threads.min(cuts.len() - 1),
cuts,
}
}
/// A merge step of a dot product against a multiply-add of Gustavson (see
/// [`CpuBackend::mxm_by_dots`]). Measured on dwarf (12 threads, the dots cut by merge
/// steps), masked `A A` under `A` against the estimate: rmat12 0.09, zox-M 0.13,
/// road2048 0.47; the largest taken.
pub const MXM_DOT_STEP: f64 = 0.5;
/// An entry of the transpose (on the workers) against a multiply-add of Gustavson:
/// measured as above rmat12 0.6, zox-M 2.8, road2048 3.0 (97 ms for 10.1 million
/// entries); a little over the largest.
pub const MXM_TRANSPOSE_STEP: f64 = 3.5;
/// `a` x `b` at the places `mask` holds, each by a dot product: row `i` of `a`
/// intersected with row `j` of the transpose of `b` ([`CpuBackend::dot_steps`]: merged,
/// or the short one galloped through the long one; the common indices rising either
/// way, so the sums are the same in the same order); a place with no common index is
/// no entry. Rows in pieces over the workers.
fn mxm_dots<S: Semiring>(
a: &Csr<S::T>,
bt: &Csr<S::T>,
mask: &MatrixMask,
plan: &MxmPlan,
s: S,
device: &CpuDevice,
) -> Result<Csr<S::T>> {
let (ao, ai) = (a.pattern().offsets(), a.pattern().indices());
let (bo, bi) = (bt.pattern().offsets(), bt.pattern().indices());
let pieces = device.split_cuts(&plan.cuts, plan.workers, |rows| {
let mut out = Rows {
counts: Vec::with_capacity(rows.len()),
indices: Vec::new(),
values: Vec::new(),
};
for i in rows {
let (alo, ahi) = (ao[i] as usize, ao[i + 1] as usize);
for &j in mask.pattern.row(i) {
let (blo, bhi) = (bo[j as usize] as usize, bo[j as usize + 1] as usize);
let mut acc: Option<S::T> = None;
each_common(&ai[alo..ahi], &bi[blo..bhi], |x, y| {
let p = s.mul(a.value_at(alo + x, s), bt.value_at(blo + y, s));
acc = Some(acc.map_or(p, |t| s.add(t, p)));
});
if let Some(t) = acc {
out.indices.push(j);
out.values.push(t);
}
}
out.counts.push(out.indices.len() as u64);
}
out
});
join_rows(a.nrows(), bt.nrows(), pieces, device)
}
/// The multiply-adds of `a` x `b` estimated with no pass over the rows: `a`'s entries
/// times the mean row of `b`, one more a row of `a`.
fn mxm_work<T: Value>(a: &Csr<T>, b: &Csr<T>) -> u64 {
let mean = (b.nnz() as u64).div_ceil(b.nrows().max(1) as u64);
(a.nnz() as u64).saturating_mul(mean.max(1)) + a.nrows() as u64
}
/// See [`CpuBackend::mxm_plan`]: below this estimate of multiply-adds `mxm` stays on the
/// calling thread. Measured on dwarf (12 threads): waking the workers costs about 30 us,
/// a multiply-add on one thread 10-20 ns; at 1278 the calling thread alone took 13 us
/// against 47 us on twelve, at 8688 166 us against 77 us.
pub const MXM_SERIAL_BELOW: u64 = 4096;
fn check_mask(op: &'static str, mask: Option<&Mask>, len: usize) -> Result<()> {
match mask {
Some(m) if m.len() != len => Err(shape_err(
op,
format!("mask of {} for a result of {len}", m.len()),
)),
_ => Ok(()),
}
}
/// Merge two rising entry lists with `both` for shared places; `keep_a`/`keep_b` say
/// whether places in one list only stay.
fn merge<T: Value>(
a: impl Iterator<Item = (u32, T)>,
b: impl Iterator<Item = (u32, T)>,
both: impl Fn(T, T) -> T,
union: bool,
out_i: &mut Vec<u32>,
out_v: &mut Vec<T>,
) {
let mut a = a.peekable();
let mut b = b.peekable();
loop {
match (a.peek().copied(), b.peek().copied()) {
(Some((i, x)), Some((j, y))) => {
if i == j {
out_i.push(i);
out_v.push(both(x, y));
a.next();
b.next();
} else if i < j {
if union {
out_i.push(i);
out_v.push(x);
}
a.next();
} else {
if union {
out_i.push(j);
out_v.push(y);
}
b.next();
}
}
(Some((i, x)), None) => {
if !union {
break;
}
out_i.push(i);
out_v.push(x);
a.next();
}
(None, Some((j, y))) => {
if !union {
break;
}
out_i.push(j);
out_v.push(y);
b.next();
}
(None, None) => break,
}
}
}
fn row_entries<'a, S: Semiring>(
a: &'a Csr<S::T>,
i: usize,
s: S,
) -> impl Iterator<Item = (u32, S::T)> + 'a {
let r = a.pattern().range(i);
r.map(move |k| (a.pattern().indices()[k], a.value_at(k, s)))
}
fn ewise_matrix<S: Semiring>(
op: &'static str,
a: &Csr<S::T>,
b: &Csr<S::T>,
s: S,
union: bool,
device: &CpuDevice,
) -> Result<Csr<S::T>> {
if (a.nrows(), a.ncols()) != (b.nrows(), b.ncols()) {
return Err(shape_err(
op,
format!(
"{}x{} and {}x{}",
a.nrows(),
a.ncols(),
b.nrows(),
b.ncols()
),
));
}
let pieces = device.split(a.nrows(), |rows| {
let mut out = Rows {
counts: Vec::with_capacity(rows.len()),
indices: Vec::new(),
values: Vec::new(),
};
for i in rows {
let both = |x, y| if union { s.add(x, y) } else { s.mul(x, y) };
Self::merge(
Self::row_entries(a, i, s),
Self::row_entries(b, i, s),
both,
union,
&mut out.indices,
&mut out.values,
);
out.counts.push(out.indices.len() as u64);
}
out
});
join_rows(a.nrows(), a.ncols(), pieces, device)
}
}
impl SparseBackend for CpuBackend {
type Device = CpuDevice;
type Matrix<T: Value> = Csr<T>;
type Vector<T: Value> = Vector<T>;
type Mask = Mask;
type Workspace = CpuWorkspace;
fn name() -> &'static str {
"cpu"
}
fn matrix<T: Value>(csr: Csr<T>, _device: &CpuDevice) -> Csr<T> {
csr
}
fn matrix_to_host<T: Value>(m: &Csr<T>) -> Csr<T> {
m.clone()
}
fn vector<T: Value>(v: Vector<T>, _device: &CpuDevice) -> Vector<T> {
v
}
fn vector_to_host<T: Value>(v: &Vector<T>) -> Vector<T> {
v.clone()
}
fn mask(m: Mask, _device: &CpuDevice) -> Mask {
m
}
fn mask_to_host(m: &Mask) -> Mask {
m.clone()
}
fn shape<T: Value>(m: &Csr<T>) -> (usize, usize) {
(m.nrows(), m.ncols())
}
fn nnz<T: Value>(m: &Csr<T>) -> usize {
m.nnz()
}
fn len<T: Value>(v: &Vector<T>) -> usize {
v.len()
}
fn nvals<T: Value>(v: &Vector<T>) -> usize {
v.nvals()
}
fn mxv<S: Semiring>(
a: &Csr<S::T>,
x: &Vector<S::T>,
mask: Option<&Mask>,
s: S,
device: &CpuDevice,
) -> Result<Vector<S::T>> {
if a.ncols() != x.len() {
return Err(shape_err(
"mxv",
format!("{}x{} by {}", a.nrows(), a.ncols(), x.len()),
));
}
Self::check_mask("mxv", mask, a.nrows())?;
let xv = x.lookup(s.zero());
let pieces = device.split(a.nrows(), |rows| {
let mut idx = Vec::new();
let mut val = Vec::new();
for i in rows {
if let Some(m) = mask
&& !m.allows(i)
{
continue;
}
let mut acc: Option<S::T> = None;
for k in a.pattern().range(i) {
let j = a.pattern().indices()[k] as usize;
if let Some(xj) = xv.get(j) {
let p = s.mul(a.value_at(k, s), xj);
acc = Some(match acc {
Some(t) => s.add(t, p),
None => p,
});
}
}
if let Some(t) = acc {
idx.push(i as u32);
val.push(t);
}
}
(idx, val)
});
let (mut idx, mut val) = (Vec::new(), Vec::new());
for (i, v) in pieces {
idx.extend(i);
val.extend(v);
}
Vector::sparse(a.nrows(), idx, val)
}
fn vxm<S: Semiring>(
x: &Vector<S::T>,
a: &Csr<S::T>,
mask: Option<&Mask>,
s: S,
device: &CpuDevice,
) -> Result<Vector<S::T>> {
if a.nrows() != x.len() {
return Err(shape_err(
"vxm",
format!("{} by {}x{}", x.len(), a.nrows(), a.ncols()),
));
}
Self::check_mask("vxm", mask, a.ncols())?;
let n = a.ncols();
let off = a.pattern().offsets();
let work = Self::row_lengths_at(a, x);
if work < (n / 16) as u64 && work < (device.grain * 16) as u64 {
// A small product: the pushed entries sorted and folded.
let mut all: Vec<(u32, S::T)> = Vec::with_capacity(work as usize);
let mut push = |i: u32, xi: S::T| {
for k in off[i as usize] as usize..off[i as usize + 1] as usize {
let j = a.pattern().indices()[k];
if mask.is_none_or(|m| m.allows(j as usize)) {
all.push((j, s.mul(xi, a.value_at(k, s))));
}
}
};
match x.sparse_parts() {
Some((xi, xv)) => xi.iter().zip(xv).for_each(|(&i, &v)| push(i, v)),
None => x.iter().for_each(|(i, v)| push(i, v)),
}
return Vector::from_pairs(n, all, s);
}
// A large one: a dense accumulator, threads on fixed pieces of `x`, the result read
// rising off the accumulator (`vxm_into` with a workspace of its own; keep one
// and call `vxm_into` to allocate nothing per call).
let mut ws = Self::workspace(n, device);
let mut y = Vector::empty(n);
Self::vxm_into(x, a, mask, s, &mut y, &mut ws, device)?;
Ok(y)
}
fn mxm<S: Semiring>(
a: &Csr<S::T>,
b: &Csr<S::T>,
mask: Option<&MatrixMask>,
s: S,
device: &CpuDevice,
) -> Result<Csr<S::T>> {
if a.ncols() != b.nrows() {
return Err(shape_err(
"mxm",
format!("{}x{} by {}x{}", a.nrows(), a.ncols(), b.nrows(), b.ncols()),
));
}
let (n, m) = (a.nrows(), b.ncols());
if let Some(mk) = mask
&& (mk.pattern.major() != n || mk.pattern.minor() != m)
{
return Err(shape_err(
"mxm",
format!(
"mask {}x{} for a result of {n}x{m}",
mk.pattern.major(),
mk.pattern.minor()
),
));
}
if let Some(mk) = mask
&& let Some(work) = Self::dots_against(a, b, mk, device)
{
let bt = Self::transpose_on(b, device);
let plan = Self::mxm_dots_plan(a, &bt, mk, device);
if (plan.flops as f64) * Self::MXM_DOT_STEP < work as f64 {
return Self::mxm_dots(a, &bt, mk, &plan, s, device);
}
}
// Gustavson: each row of the result folds rows of B into a dense accumulator; a
// stamp per column says which row last wrote it (and, with a mask, which row the
// mask allows it for). Pieces of rows of about equal multiply-adds go to the
// workers from a shared counter; each worker keeps one accumulator for all its
// pieces.
let rows_of = |rows: Range<usize>, sc: &mut MxmScratch<S::T>| {
if sc.seen.len() != m {
sc.acc = vec![s.zero(); m];
sc.seen = vec![u32::MAX; m];
sc.allowed = vec![u32::MAX; if mask.is_some() { m } else { 0 }];
}
let MxmScratch {
acc,
seen,
allowed,
touched,
..
} = sc;
let mut out = Rows {
counts: Vec::with_capacity(rows.len()),
indices: Vec::new(),
values: Vec::new(),
};
for i in rows {
let stamp = i as u32;
if let Some(mk) = mask {
for &j in mk.pattern.row(i) {
allowed[j as usize] = stamp;
}
}
let ok = |j: usize, allowed: &[u32]| match mask {
None => true,
Some(mk) => (allowed[j] == stamp) != mk.complement,
};
touched.clear();
for ka in a.pattern().range(i) {
let k = a.pattern().indices()[ka] as usize;
let aik = a.value_at(ka, s);
for kb in b.pattern().range(k) {
let j = b.pattern().indices()[kb] as usize;
if !ok(j, allowed) {
continue;
}
let p = s.mul(aik, b.value_at(kb, s));
if seen[j] == stamp {
acc[j] = s.add(acc[j], p);
} else {
seen[j] = stamp;
acc[j] = p;
touched.push(j as u32);
}
}
}
touched.sort_unstable();
for &j in touched.iter() {
out.indices.push(j);
out.values.push(acc[j as usize]);
}
out.counts.push(out.indices.len() as u64);
}
out
};
let plan = Self::mxm_plan(a, b, device);
if plan.workers <= 1 {
let mut sc = MxmScratch::default();
return join_rows(n, m, vec![rows_of(0..n, &mut sc)], device);
}
let cuts = &plan.cuts;
let pieces = cuts.len() - 1;
let workers = plan.workers.min(pieces);
let mut scratch: Vec<MxmScratch<S::T>> =
(0..workers).map(|_| MxmScratch::default()).collect();
let next = AtomicUsize::new(0);
run_each(device.pool(), &mut scratch, &|_, sc| {
loop {
let p = next.fetch_add(1, Ordering::Relaxed);
if p >= pieces {
break;
}
let r = rows_of(cuts[p]..cuts[p + 1], sc);
sc.done.push((p, r));
}
});
let mut slots: Vec<Option<Rows<S::T>>> = (0..pieces).map(|_| None).collect();
for sc in scratch {
for (p, r) in sc.done {
slots[p] = Some(r);
}
}
let pieces: Vec<Rows<S::T>> = slots
.into_iter()
.map(|r| r.expect("every piece ran"))
.collect();
join_rows(n, m, pieces, device)
}
fn ewise_add_vector<S: Semiring>(
a: &Vector<S::T>,
b: &Vector<S::T>,
s: S,
) -> Result<Vector<S::T>> {
if a.len() != b.len() {
return Err(shape_err(
"ewise_add",
format!("{} and {}", a.len(), b.len()),
));
}
let (mut i, mut v) = (Vec::new(), Vec::new());
Self::merge(a.iter(), b.iter(), |x, y| s.add(x, y), true, &mut i, &mut v);
Vector::sparse(a.len(), i, v)
}
fn ewise_mult_vector<S: Semiring>(
a: &Vector<S::T>,
b: &Vector<S::T>,
s: S,
) -> Result<Vector<S::T>> {
if a.len() != b.len() {
return Err(shape_err(
"ewise_mult",
format!("{} and {}", a.len(), b.len()),
));
}
let (mut i, mut v) = (Vec::new(), Vec::new());
Self::merge(
a.iter(),
b.iter(),
|x, y| s.mul(x, y),
false,
&mut i,
&mut v,
);
Vector::sparse(a.len(), i, v)
}
fn ewise_add_matrix<S: Semiring>(
a: &Csr<S::T>,
b: &Csr<S::T>,
s: S,
device: &CpuDevice,
) -> Result<Csr<S::T>> {
Self::ewise_matrix("ewise_add", a, b, s, true, device)
}
fn ewise_mult_matrix<S: Semiring>(
a: &Csr<S::T>,
b: &Csr<S::T>,
s: S,
device: &CpuDevice,
) -> Result<Csr<S::T>> {
Self::ewise_matrix("ewise_mult", a, b, s, false, device)
}
fn reduce_vector<S: Semiring>(v: &Vector<S::T>, s: S) -> S::T {
match v.sparse_parts() {
Some((_, vals)) => Simd::detect().fold(vals, s.zero(), |a, b| s.add(a, b)),
None => v.iter().fold(s.zero(), |t, (_, x)| s.add(t, x)),
}
}
fn reduce_rows<S: Semiring>(a: &Csr<S::T>, s: S, device: &CpuDevice) -> Vector<S::T> {
let pieces = device.split(a.nrows(), |rows| {
let mut out = Vec::new();
for i in rows {
let r = a.pattern().range(i);
if !r.is_empty() {
let t = match a.values() {
// Long rows in the word kernel's lanes, short ones in order: the
// choice hangs on the row only, so every level folds alike.
Some(v) if r.len() >= 64 => {
device.simd.fold(&v[r], s.zero(), |x, y| s.add(x, y))
}
_ => r.fold(s.zero(), |t, k| s.add(t, a.value_at(k, s))),
};
out.push((i as u32, t));
}
}
out
});
let (idx, val): (Vec<u32>, Vec<S::T>) = pieces.into_iter().flatten().unzip();
Vector::sparse(a.nrows(), idx, val).expect("rows are visited rising")
}
fn select_vector<T: Value, F: Fn(u32, T) -> bool + Sync>(v: &Vector<T>, keep: F) -> Vector<T> {
let (idx, val): (Vec<u32>, Vec<T>) = v.iter().filter(|&(i, x)| keep(i, x)).unzip();
Vector::sparse(v.len(), idx, val).expect("a subset of rising entries rises")
}
fn select_matrix<S: Semiring, F: Fn(u32, u32, S::T) -> bool + Sync>(
a: &Csr<S::T>,
keep: F,
s: S,
device: &CpuDevice,
) -> Csr<S::T> {
let structural = a.values().is_none();
let pieces = device.split(a.nrows(), |rows| {
let mut out = Rows {
counts: Vec::with_capacity(rows.len()),
indices: Vec::new(),
values: Vec::new(),
};
for i in rows {
for k in a.pattern().range(i) {
let j = a.pattern().indices()[k];
let x = a.value_at(k, s);
if keep(i as u32, j, x) {
out.indices.push(j);
if !structural {
out.values.push(x);
}
}
}
out.counts.push(out.indices.len() as u64);
}
out
});
join_rows_as(a.nrows(), a.ncols(), pieces, !structural, device)
.expect("a subset of valid rows")
}
fn transpose<T: Value>(a: &Csr<T>, device: &CpuDevice) -> Csr<T> {
Self::transpose_on(a, device)
}
fn mask_from_vector<T: Value>(v: &Vector<T>) -> Mask {
Mask::from_vector(v)
}
fn mask_add_vector<T: Value>(m: &mut Mask, v: &Vector<T>) {
let bits = m.bits_mut();
match v.dense_parts() {
Some((_, present)) => bits.union_with(present),
None => {
for i in v.sparse_parts().map(|p| p.0).unwrap_or(&[]) {
bits.set(*i as usize);
}
}
}
}
fn mask_complement(m: Mask) -> Mask {
m.complement()
}
fn mask_count(m: &Mask) -> usize {
m.count()
}
fn assign_scalar<T: Value, U: Value>(w: &mut Vector<T>, at: &Vector<U>, value: T, fill: T) {
if at.nvals() == 0 {
return;
}
let (values, present) = w.dense_parts_mut(fill);
match at.sparse_parts() {
Some((idx, _)) => {
for &i in idx {
values[i as usize] = value;
present.set(i as usize);
}
}
None => {
for (i, _) in at.iter() {
values[i as usize] = value;
present.set(i as usize);
}
}
}
}
fn workspace(n: usize, device: &CpuDevice) -> CpuWorkspace {
CpuWorkspace {
marks: Bitset::new(n),
lists: vec![(Vec::new(), 0); device.threads],
flist: Vec::new(),
typed: Vec::new(),
transposes: 0,
}
}
fn step_push(
frontier: &Vector<u8>,
a: &Csr<u8>,
open: &mut Mask,
next: &mut Vector<u8>,
ws: &mut CpuWorkspace,
device: &CpuDevice,
) -> Result<u64> {
if frontier.len() != a.nrows() || open.len() != a.ncols() || next.len() != a.ncols() {
return Err(shape_err(
"step_push",
format!(
"frontier {}, matrix {}x{}, mask {}, next {}",
frontier.len(),
a.nrows(),
a.ncols(),
open.len(),
next.len()
),
));
}
let fidx: &[u32] = match frontier.sparse_parts() {
Some((i, _)) => i,
None => {
ws.flist.clear();
ws.flist.extend(frontier.iter().map(|(i, _)| i));
&ws.flist
}
};
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let (ni, nv) = next.refill();
// The frontier is split by vertices (as `each_mut` splits it): a frontier too short
// to split stays on this thread, on the plain path.
let parallel = ws.lists.len() > 1 && device.pieces(fidx.len()).is_some();
let mut work = 0u64;
let n = a.ncols();
if ws.marks.len() != n {
ws.marks = Bitset::new(n);
}
if !parallel {
let complement = open.is_complement();
let words = open.bits_mut().words_mut();
work = if complement {
push_rows::<true>(fidx, &off[..], &idx[..], words, ni)
} else {
push_rows::<false>(fidx, &off[..], &idx[..], words, ni)
};
if ni.len() * 512 < n {
// Few: sort the list (cheaper than reading every word of the marks).
ni.sort_unstable();
} else {
for &w in ni.iter() {
ws.marks.set(w as usize);
}
ni.clear();
take_marks(device.simd, &mut ws.marks, ni);
}
} else {
let complement = open.is_complement();
let bits = atomic_words(open.bits_mut().words_mut());
let marks = atomic_words(ws.marks.words_mut());
// Every thread claims the places it reaches with one atomic read-modify-write
// on the mask (after a plain read: most places are closed already); a place is
// claimed by exactly one thread, which marks it. The level is then read rising
// off the marks: no list grows with how the race went.
device.each_mut(&mut ws.lists, fidx.len(), |r, (_, ex)| {
for &v in &fidx[r] {
let row = &idx[off[v as usize] as usize..off[v as usize + 1] as usize];
*ex += row.len() as u64;
for &w in row {
let (wi, m) = ((w >> 6) as usize, 1u64 << (w & 63));
let cur = bits[wi].load(Ordering::Relaxed);
if (cur & m == 0) != complement {
continue;
}
let won = if complement {
bits[wi].fetch_or(m, Ordering::Relaxed) & m == 0
} else {
bits[wi].fetch_and(!m, Ordering::Relaxed) & m != 0
};
if won {
marks[wi].fetch_or(m, Ordering::Relaxed);
}
}
}
});
for (_, ex) in &mut ws.lists {
work += std::mem::take(ex);
}
take_marks(device.simd, &mut ws.marks, ni);
}
nv.resize(ni.len(), 1);
Ok(work)
}
fn step_pull(
frontier: &Vector<u8>,
at: &Csr<u8>,
open: &mut Mask,
next: &mut Vector<u8>,
ws: &mut CpuWorkspace,
device: &CpuDevice,
) -> Result<u64> {
let n = at.nrows();
if frontier.len() != at.ncols() || open.len() != n || next.len() != n {
return Err(shape_err(
"step_pull",
format!(
"frontier {}, matrix {}x{}, mask {}, next {}",
frontier.len(),
at.nrows(),
at.ncols(),
open.len(),
next.len()
),
));
}
if ws.marks.len() != at.ncols() {
ws.marks = Bitset::new(at.ncols());
}
// The frontier as marks: from its list (set by every thread when it is long), or
// (dense) its own bitset.
let threads = device.threads.min(ws.lists.len()).max(1);
let large = match (frontier.sparse_parts(), frontier.dense_parts()) {
(Some((fidx, _)), _) => {
if threads > 1 && fidx.len() >= device.grain * 16 {
let marks = atomic_words(ws.marks.words_mut());
device.each_mut(&mut ws.lists[..threads], fidx.len(), |r, _| {
for &u in &fidx[r] {
marks[(u >> 6) as usize].fetch_or(1 << (u & 63), Ordering::Relaxed);
}
});
} else {
for &u in fidx {
ws.marks.set(u as usize);
}
}
fidx.len() * 64 >= at.ncols()
}
(_, Some((_, present))) => {
ws.marks.words_mut().copy_from_slice(present.words());
true
}
_ => unreachable!("a vector is sparse or dense"),
};
let off = at.pattern().offsets();
let idx = at.pattern().indices();
let marks = &ws.marks;
let simd = device.simd;
let complement = open.is_complement();
let flip = if complement { u64::MAX } else { 0 };
// Each block owns whole words of the mask: it scans its open places and closes
// what it finds in place (a place found now is not on this level's frontier, which
// is the marks, so closing it at once changes nothing else this level reads).
let blocks = if device.threads <= 1 || n < device.grain * 16 {
1
} else {
threads
};
let words = n.div_ceil(64);
let per = words.div_ceil(blocks);
device.each_block_chunk(
&mut ws.lists[..blocks],
open.bits_mut().words_mut(),
per,
|t, (list, ex), mine| {
let base_word = t * per;
let mut examined = 0u64;
let mut wi = 0;
while wi < mine.len() {
wi = simd.first_nonzero(mine, flip, wi);
if wi >= mine.len() {
break;
}
let gw = base_word + wi;
let mut w = mine[wi] ^ flip;
if (gw + 1) * 64 > n {
w &= u64::MAX >> ((gw + 1) * 64 - n);
}
while w != 0 {
let b = w.trailing_zeros();
w &= w - 1;
let i = gw * 64 + b as usize;
for &u in &idx[off[i] as usize..off[i + 1] as usize] {
examined += 1;
if marks.get(u as usize) {
list.push(i as u32);
// Close it: set the bit of a complemented mask, clear it
// otherwise.
mine[wi] ^= 1u64 << b;
break;
}
}
}
wi += 1;
}
*ex = examined;
},
);
let (ni, nv) = next.refill();
let mut examined = 0;
for (list, ex) in &mut ws.lists[..blocks] {
ni.extend_from_slice(list);
examined += *ex;
list.clear();
*ex = 0;
}
nv.resize(ni.len(), 1);
if large {
ws.marks.words_mut().fill(0);
} else if let Some((fidx, _)) = frontier.sparse_parts() {
for &u in fidx {
ws.marks.unset(u as usize);
}
}
Ok(examined)
}
fn mxv_into<S: Semiring>(
a: &Csr<S::T>,
x: &Vector<S::T>,
mask: Option<&Mask>,
s: S,
y: &mut Vector<S::T>,
ws: &mut CpuWorkspace,
device: &CpuDevice,
) -> Result<()> {
if a.ncols() != x.len() || y.len() != a.nrows() {
return Err(shape_err(
"mxv_into",
format!(
"{}x{} by {} into {}",
a.nrows(),
a.ncols(),
x.len(),
y.len()
),
));
}
Self::check_mask("mxv_into", mask, a.nrows())?;
let blocks = if device.threads <= 1 || a.nnz() < device.grain * 16 {
1
} else {
device.threads
};
let l = ws.typed::<S::T>(blocks);
// The operand densely: its own storage, or spread into the workspace.
let spread = x.sparse_parts();
if let Some((idx, val)) = spread {
if l.xdense.len() != x.len() {
l.xdense = vec![s.zero(); x.len()];
l.xpresent = Bitset::new(x.len());
}
for (&i, &v) in idx.iter().zip(val) {
l.xdense[i as usize] = v;
l.xpresent.set(i as usize);
}
}
let (xv, xp): (&[S::T], &Bitset) = match x.dense_parts() {
Some(p) => p,
None => (&l.xdense, &l.xpresent),
};
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let simd = device.simd;
// A full operand needs no test of its places; a fold that reaches the semiring's
// terminal stops (or-and: the first true).
let full = spread.is_none() && xp.count() == x.len();
let terminal = s.terminal();
let n = a.nrows();
if full
&& a.values().is_none()
&& let Some(p) = Self::iso_product(xv, s)
{
// A structural matrix times a full operand of one value whose product `p`
// folds to itself (or-and's true, min-plus): every row with an entry is `p`,
// so only the offsets are read, never a column or the operand at one.
let fold = |i: usize| (off[i + 1] > off[i]).then_some(p);
let blocks = Self::full_blocks(n + a.nnz(), device);
Self::dense_rows(n, n as u64, &[], blocks, mask, y, s.zero(), device, &fold);
return Ok(());
}
if full {
// A full operand gives (nearly) every row an entry: the result is written in
// place, densely, each block its own rows' values and words of places.
// The row's columns and values as slices (no test per entry of which storage
// the values have), and the terminal's test only where the semiring has one.
let (ix, av) = (&idx[..], a.values().map(|v| &v[..]));
let one = s.one();
let blocks = Self::full_blocks(n + a.nnz(), device);
// A large operand is read ahead, across rows; a small one is not (the choice
// made once, outside the rows: a small operand folds as it did before).
let ahead =
|i: usize| &ix[(off[i] as usize + Self::FULL_MXV_FETCH_AHEAD).min(ix.len())..];
let rows = |i: usize| {
let r = off[i] as usize..off[i + 1] as usize;
(&ix[r.clone()], av.map(|v| &v[r]))
};
let fetched = |i: usize| -> Option<S::T> {
let (cols, vals) = rows(i);
Self::full_row::<S, true>(cols, vals, xv, s, one, terminal, ahead(i))
};
let plain = |i: usize| -> Option<S::T> {
let (cols, vals) = rows(i);
Self::full_row::<S, false>(cols, vals, xv, s, one, terminal, &[])
};
let nnz = a.nnz() as u64;
let z = s.zero();
if std::mem::size_of_val(xv) >= Self::FULL_MXV_FETCH_FROM {
Self::dense_rows(n, nnz, off, blocks, mask, y, z, device, &fetched);
} else {
Self::dense_rows(n, nnz, off, blocks, mask, y, z, device, &plain);
}
return Ok(());
}
let row = |i: usize, oi: &mut Vec<u32>, ov: &mut Vec<S::T>| {
let r = off[i] as usize..off[i + 1] as usize;
let mut acc: Option<S::T> = None;
for k in r {
let j = idx[k] as usize;
if xp.get(j) {
let p = s.mul(a.value_at(k, s), xv[j]);
let t = match acc {
Some(t) => s.add(t, p),
None => p,
};
acc = Some(t);
if terminal == Some(t) {
break;
}
}
}
if let Some(t) = acc {
oi.push(i as u32);
ov.push(t);
}
};
let rows = |lo: usize, hi: usize, oi: &mut Vec<u32>, ov: &mut Vec<S::T>| match mask {
Some(m) => allowed_in(m, simd, lo, hi, |i| row(i, oi, ov)),
None => (lo..hi).for_each(|i| row(i, oi, ov)),
};
let (yi, yv) = y.refill();
if blocks == 1 {
rows(0, n, yi, yv);
} else {
// Blocks of about equal entries, on 64-row boundaries so a mask's words split
// cleanly; each block's rows rise, and the blocks are joined in order.
let nnz = a.nnz() as u64;
let cut = |t: usize| -> usize {
if t == 0 {
return 0;
}
if t >= blocks {
return n;
}
let want = nnz * t as u64 / blocks as u64;
let r = off.partition_point(|&o| o < want).min(n);
(r / 64 * 64).min(n)
};
let per = &mut l.per_thread[..blocks];
device.each_block(per, |t, (oi, ov)| {
oi.clear();
ov.clear();
rows(cut(t), cut(t + 1), oi, ov);
});
for (oi, ov) in per.iter_mut() {
yi.extend_from_slice(oi);
yv.extend_from_slice(ov);
oi.clear();
ov.clear();
}
}
if let Some((idx, _)) = spread {
for &i in idx {
l.xpresent.unset(i as usize);
}
}
Ok(())
}
fn vxm_into<S: Semiring>(
x: &Vector<S::T>,
a: &Csr<S::T>,
mask: Option<&Mask>,
s: S,
y: &mut Vector<S::T>,
ws: &mut CpuWorkspace,
device: &CpuDevice,
) -> Result<()> {
if a.nrows() != x.len() || y.len() != a.ncols() {
return Err(shape_err(
"vxm_into",
format!(
"{} by {}x{} into {}",
x.len(),
a.nrows(),
a.ncols(),
y.len()
),
));
}
Self::check_mask("vxm_into", mask, a.ncols())?;
let n = a.ncols();
let threads = device.threads.min(ws.lists.len()).max(1);
let xfull = x.dense_parts().is_some_and(|(_, p)| p.count() == x.len());
let CpuWorkspace {
lists,
typed,
transposes,
..
} = ws;
// Producer p's lists for consumer b sit at p * threads + b.
let l = typed_slot::<S::T>(typed, threads * threads);
if xfull {
// A full operand on a matrix read before: pull over its transpose, kept (made
// on the second such call; a matrix read once pays no transpose).
match &mut l.kept {
Some(k) if same_buffers(&k.of, a) => {
if k.t.is_none() {
k.t = Some(Self::transpose_on(a, device));
*transposes += 1;
}
let t = k.t.as_ref().expect("made above");
let (xv, _) = x.dense_parts().expect("a full operand is dense");
let (off, idx) = (t.pattern().offsets(), t.pattern().indices());
let terminal = s.terminal();
let fold = |j: usize| -> Option<S::T> {
let r = off[j] as usize..off[j + 1] as usize;
if r.is_empty() {
return None;
}
let mut acc = s.mul(xv[idx[r.start] as usize], t.value_at(r.start, s));
for k in r.start + 1..r.end {
if terminal == Some(acc) {
break;
}
acc = s.add(acc, s.mul(xv[idx[k] as usize], t.value_at(k, s)));
}
Some(acc)
};
let blocks = if device.threads <= 1 || t.nnz() < device.grain * 16 {
1
} else {
device.threads
};
Self::dense_rows(
n,
t.nnz() as u64,
off,
blocks,
mask,
y,
s.zero(),
device,
&fold,
);
return Ok(());
}
kept => {
if kept.as_ref().is_some_and(|k| k.t.is_some()) {
*transposes -= 1;
}
*kept = Some(Kept {
of: a.clone(),
t: None,
});
}
}
}
if l.dense.len() != n {
l.dense = vec![s.zero(); n];
l.present = Bitset::new(n);
}
// A full operand reaches (nearly) every column: the result's own dense storage is
// the accumulator (swapped in here, swapped back after), so nothing is copied out.
if xfull {
let (yv, yp) = y.dense_vecs_mut(s.zero());
std::mem::swap(yv, &mut l.dense);
std::mem::swap(yp, &mut l.present);
l.present.words_mut().fill(0);
}
let off = a.pattern().offsets();
let idx = a.pattern().indices();
let work: u64 = match x.sparse_parts() {
Some((xi, _)) => xi
.iter()
.map(|&i| off[i as usize + 1] - off[i as usize])
.sum(),
None => a.nnz() as u64,
};
// Push each entry of `x` along its row: into the dense accumulator directly on one
// thread, or into per-thread lists folded in after.
let send = |i: u32, xi: S::T, out: &mut dyn FnMut(u32, S::T)| {
for k in off[i as usize] as usize..off[i as usize + 1] as usize {
let j = idx[k];
if mask.is_some_and(|m| !m.allows(j as usize)) {
continue;
}
out(j, s.mul(xi, a.value_at(k, s)));
}
};
let Lists {
per_thread,
dense,
present,
..
} = l;
let mut fold = |j: u32, v: S::T| {
let j = j as usize;
if present.set(j) {
dense[j] = v;
} else {
dense[j] = s.add(dense[j], v);
}
};
let parallel = threads > 1 && work >= (device.grain * 16) as u64;
match (x.sparse_parts(), parallel) {
(Some((xi, xv)), false) => {
for (&i, &v) in xi.iter().zip(xv) {
send(i, v, &mut fold);
}
}
(None, false) => {
// dense: its places straight off the words (no boxed iterator)
let (xv, xp) = x.dense_parts().expect("not sparse, so dense");
for i in xp.iter() {
send(i, xv[i as usize], &mut fold);
}
}
(sp, true) => {
let len = sp.map_or(x.len(), |p| p.0.len());
// Columns per consumer, whole words of the accumulator's places each.
let width = n.div_ceil(threads).div_ceil(64) * 64;
// Produce: fixed, equal pieces of `x` per thread (the same input fills the
// same lists the same way every time, so they stop growing), each entry
// into the list of the consumer that owns its column.
device.each_block_chunk(
&mut lists[..threads],
&mut per_thread[..threads * threads],
threads,
|t, _, mine| {
for (oi, ov) in mine.iter_mut() {
oi.clear();
ov.clear();
}
let r = t * len / threads..(t + 1) * len / threads;
let mut out = |j: u32, v: S::T| {
let (oi, ov) = &mut mine[j as usize / width];
oi.push(j);
ov.push(v);
};
match sp {
Some((xi, xv)) => {
for k in r {
send(xi[k], xv[k], &mut out);
}
}
None => {
for i in r {
if let Some(v) = x.get(i) {
send(i as u32, v, &mut out);
}
}
}
}
},
);
// Consume: every thread folds the lists for its own columns, producers in
// order (a fixed order: the same answer every run).
let lists_in: &[(Vec<u32>, Vec<S::T>)] = per_thread;
let words = atomic_words(present.words_mut());
device.each_block_chunk(
&mut lists[..threads],
&mut dense[..],
width,
|t, _, acc| {
let lo = t * width;
for p in 0..threads {
let (oi, ov) = &lists_in[p * threads + t];
for (&j, &v) in oi.iter().zip(ov) {
let (wi, m) = ((j >> 6) as usize, 1u64 << (j & 63));
let old = words[wi].load(Ordering::Relaxed);
let at = j as usize - lo;
if old & m == 0 {
words[wi].store(old | m, Ordering::Relaxed);
acc[at] = v;
} else {
acc[at] = s.add(acc[at], v);
}
}
}
},
);
for (oi, ov) in per_thread[..threads * threads].iter_mut() {
oi.clear();
ov.clear();
}
}
}
if xfull {
// the result in place; the workspace gets back storage whose places are clear
let (yv, yp) = y.dense_vecs_mut(s.zero());
std::mem::swap(yv, dense);
std::mem::swap(yp, present);
return Ok(());
}
// The result rising off the accumulator's places, clearing them as they are read.
let (yi, yv) = y.refill();
for (wi, word) in present.words_mut().iter_mut().enumerate() {
let mut w = std::mem::take(word);
while w != 0 {
let j = wi * 64 + w.trailing_zeros() as usize;
yi.push(j as u32);
yv.push(dense[j]);
w &= w - 1;
}
}
Ok(())
}
fn clear_vector<T: Value>(v: &mut Vector<T>, _device: &CpuDevice) {
v.clear();
}
fn load_indices<T: Value>(
v: &mut Vector<T>,
indices: &[u32],
value: T,
_device: &CpuDevice,
) -> Result<()> {
v.load_indices(indices, value)
}
fn mask_assign(m: &mut Mask, host: &Mask, _device: &CpuDevice) {
m.assign(host);
}
fn accumulate<S: Semiring>(
w: &mut Vector<S::T>,
u: &Vector<S::T>,
s: S,
) -> Result<Vector<S::T>> {
if w.len() != u.len() {
return Err(shape_err(
"accumulate",
format!("{} and {}", w.len(), u.len()),
));
}
let (mut ci, mut cv) = (Vec::new(), Vec::new());
let (values, present) = w.dense_parts_mut(s.zero());
for (i, x) in u.iter() {
let k = i as usize;
let new = if present.set(k) {
x
} else {
let y = s.add(values[k], x);
if y == values[k] {
continue;
}
y
};
values[k] = new;
ci.push(i);
cv.push(new);
}
Vector::sparse(u.len(), ci, cv)
}
fn apply_indexed<T: Value, F: Fn(u32, T) -> T + Sync>(v: &Vector<T>, f: F) -> Vector<T> {
let (idx, val): (Vec<u32>, Vec<T>) = v.iter().map(|(i, x)| (i, f(i, x))).unzip();
Vector::sparse(v.len(), idx, val).expect("the same rising indices")
}
fn indices<T: Value>(v: &Vector<T>) -> Vec<u32> {
v.indices()
}
fn row_lengths_at<T: Value, U: Value>(a: &Csr<T>, v: &Vector<U>) -> u64 {
let off = a.pattern().offsets();
match v.sparse_parts() {
Some((idx, _)) => idx
.iter()
.map(|&i| off[i as usize + 1] - off[i as usize])
.sum(),
None => v
.iter()
.map(|(i, _)| off[i as usize + 1] - off[i as usize])
.sum(),
}
}
}
/// The pattern of a matrix, kept so a mask can be built from a result.
impl<T: Value> From<&Csr<T>> for MatrixMask {
fn from(a: &Csr<T>) -> Self {
MatrixMask::new(a.pattern().clone())
}
}
impl Pattern {
/// The pattern as a structural matrix (no copy: the buffers are shared).
pub fn to_structural<T: Value>(&self) -> Csr<T> {
Csr::with_pattern(self.clone(), None).expect("a pattern with no values")
}
}