crates/kleene-sparse/src/simd.rs
//! Word kernels for bitsets and reductions, and row kernels for a query engine's columns,
//! compiled for several instruction sets and chosen at run time: x86_64 AVX2 and AVX-512
//! (detected when the device is made), aarch64 NEON (always there), and plain scalar code
//! on every target. Every level runs the same code in the same order (reductions in the
//! same sixteen lanes), so every level gives the same answer bit for bit; the tests run
//! each level the host has against the scalar one.
//!
//! | Kernel | Levels with their own code |
//! |---|---|
//! | `popcount`, `or_assign`, `and_assign`, `and_not_assign`, `first_nonzero`, `fold`, `fold_gather`, `hash_rows` | one plain loop compiled per level (the compiler vectorises it with that level's instructions) |
//! | `compact_bools` (a `bool` mask to the kept row numbers) | AVX2 (also on AVX-512 hosts) |
//! | `bits_to_places` (the set bits of words to their places) | AVX2, AVX-512 |
//! | `select_range` (the rows whose value lies in a range, or outside it) | AVX2, AVX-512 |
//! | [`prefetch_read`] (a hint to start loading one entry's cache line) | x86_64 (T0); nothing elsewhere |
//!
//! Row gathers (`out[k] = col[rows[k]]`) are left to plain code: the hardware gathers
//! measured slower than plain loads on Tiger Lake, Zen 3+ and Zen 4.
// `#[target_feature]` functions may only be called where the feature is known to be
// present: `Simd` holds a level only after detecting it, and every call below goes through
// a match on it.
#![allow(unsafe_code)]
#[cfg(target_arch = "x86_64")]
mod x86;
/// An instruction set the word kernels run on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SimdLevel {
/// Plain code (whatever the target enables at compile time).
Scalar,
/// x86_64 AVX2 with POPCNT and BMI2.
Avx2,
/// x86_64 AVX-512 (F, BW, DQ, VL, VPOPCNTDQ) with POPCNT and BMI2.
Avx512,
/// aarch64 Advanced SIMD.
Neon,
}
/// Ask the CPU to start loading the cache line that holds `data[index]`, so a read of it a
/// little later finds it near instead of waiting on memory (for random reads whose index
/// is known some steps ahead). A hint only: it reads no memory, returns nothing and changes
/// no answer. An index at or past the end does nothing; it is checked before any pointer is
/// formed, so `v + D` near the end needs no check by the caller. x86_64: a T0 prefetch;
/// every other target: nothing.
#[inline(always)]
pub fn prefetch_read<T>(data: &[T], index: usize) {
if let Some(entry) = data.get(index) {
#[cfg(target_arch = "x86_64")]
x86::prefetch_t0(entry);
#[cfg(not(target_arch = "x86_64"))]
let _ = entry;
}
}
/// A level the host has, checked when made: the only way to hold one is [`Simd::detect`],
/// [`Simd::scalar`] or [`Simd::with_level`], which refuses a level the host lacks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Simd(SimdLevel);
impl Default for Simd {
fn default() -> Self {
Simd::detect()
}
}
impl Simd {
/// The best level this host has (std caches the CPU's answer: this allocates nothing
/// and costs a few loads).
pub fn detect() -> Self {
#[cfg(target_arch = "x86_64")]
{
if is_x86_feature_detected!("avx2")
&& is_x86_feature_detected!("popcnt")
&& is_x86_feature_detected!("bmi2")
{
if is_x86_feature_detected!("avx512f")
&& is_x86_feature_detected!("avx512bw")
&& is_x86_feature_detected!("avx512dq")
&& is_x86_feature_detected!("avx512vl")
&& is_x86_feature_detected!("avx512vpopcntdq")
{
return Simd(SimdLevel::Avx512);
}
return Simd(SimdLevel::Avx2);
}
}
#[cfg(target_arch = "aarch64")]
{
if std::arch::is_aarch64_feature_detected!("neon") {
return Simd(SimdLevel::Neon);
}
}
Simd(SimdLevel::Scalar)
}
/// Plain code.
pub fn scalar() -> Self {
Simd(SimdLevel::Scalar)
}
/// `level` if this host has it.
pub fn with_level(level: SimdLevel) -> Option<Self> {
Self::available().contains(&level).then_some(Simd(level))
}
/// The level.
pub fn level(self) -> SimdLevel {
self.0
}
/// Every level this host has, scalar first, best last.
pub fn available() -> Vec<SimdLevel> {
let best = Self::detect().0;
let mut out = vec![SimdLevel::Scalar];
if best == SimdLevel::Avx512 {
out.push(SimdLevel::Avx2);
}
if best != SimdLevel::Scalar {
out.push(best);
}
out
}
}
/// Instantiate a kernel body (an `#[inline(always)]` function) once per level and dispatch
/// on the level held.
macro_rules! dispatch {
($simd:expr, $k:expr) => {{
let k = $k;
match $simd.0 {
#[cfg(target_arch = "x86_64")]
SimdLevel::Avx2 => {
#[target_feature(enable = "avx2,popcnt,bmi2")]
fn avx2<A: Kernel>(a: A) -> A::Out {
a.run()
}
// SAFETY: `Simd` holds Avx2 only when the host has these features.
unsafe { avx2(k) }
}
#[cfg(target_arch = "x86_64")]
SimdLevel::Avx512 => {
#[target_feature(
enable = "avx512f,avx512bw,avx512dq,avx512vl,avx512vpopcntdq,avx2,popcnt,bmi2"
)]
fn avx512<A: Kernel>(a: A) -> A::Out {
a.run()
}
// SAFETY: `Simd` holds Avx512 only when the host has these features.
unsafe { avx512(k) }
}
#[cfg(target_arch = "aarch64")]
SimdLevel::Neon => {
#[target_feature(enable = "neon")]
fn neon<A: Kernel>(a: A) -> A::Out {
a.run()
}
// SAFETY: `Simd` holds Neon only when the host has it.
unsafe { neon(k) }
}
_ => k.run(),
}
}};
}
/// A kernel: its arguments, and a body inlined into each level's function.
trait Kernel {
type Out;
fn run(self) -> Self::Out;
}
/// Called once per block of a lane loop: the compiler then vectorises the block across its
/// lanes (contiguous loads), never the loop across blocks. Without it, the AVX-512 builds
/// (a level here, or `-C target-cpu` of an AVX-512 host for every level) turned the lane
/// loops of `popcount` and `fold` into strided hardware gathers, four times slower than
/// plain code. An empty barrier: it costs no instruction.
#[inline(always)]
fn no_outer_vectors() {
std::hint::black_box(());
}
/// Lanes a reduction keeps apart (wide enough for 16 `u32` in an AVX-512 register).
const LANES: usize = 16;
struct Popcount<'a>(&'a [u64]);
impl Kernel for Popcount<'_> {
type Out = usize;
#[inline(always)]
fn run(self) -> usize {
let mut lanes = [0u64; 8];
let (chunks, rest) = self.0.as_chunks::<8>();
for c in chunks {
no_outer_vectors();
for (l, w) in lanes.iter_mut().zip(c) {
*l += w.count_ones() as u64;
}
}
let tail: u64 = rest.iter().map(|w| w.count_ones() as u64).sum();
(lanes.iter().sum::<u64>() + tail) as usize
}
}
#[derive(Clone, Copy)]
enum Op {
Or,
And,
AndNot,
}
struct Combine<'a> {
dst: &'a mut [u64],
src: &'a [u64],
op: Op,
}
impl Kernel for Combine<'_> {
type Out = ();
#[inline(always)]
fn run(self) {
let n = self.dst.len().min(self.src.len());
let (d, s) = (&mut self.dst[..n], &self.src[..n]);
match self.op {
Op::Or => d.iter_mut().zip(s).for_each(|(a, b)| *a |= *b),
Op::And => d.iter_mut().zip(s).for_each(|(a, b)| *a &= *b),
Op::AndNot => d.iter_mut().zip(s).for_each(|(a, b)| *a &= !*b),
}
}
}
struct FirstNonZero<'a> {
words: &'a [u64],
flip: u64,
from: usize,
}
impl Kernel for FirstNonZero<'_> {
type Out = usize;
#[inline(always)]
fn run(self) -> usize {
let mut i = self.from;
let w = self.words;
// Eight words at a time: one OR-reduction and compare per block.
while i + 8 <= w.len() {
let mut any = 0u64;
for x in &w[i..i + 8] {
any |= *x ^ self.flip;
}
if any != 0 {
break;
}
i += 8;
}
while i < w.len() && w[i] ^ self.flip == 0 {
i += 1;
}
i
}
}
struct Fold<'a, T, F> {
xs: &'a [T],
init: T,
f: F,
}
impl<T: Copy, F: Fn(T, T) -> T> Kernel for Fold<'_, T, F> {
type Out = T;
#[inline(always)]
fn run(self) -> T {
let f = &self.f;
let mut lanes = [self.init; LANES];
let (chunks, rest) = self.xs.as_chunks::<LANES>();
for c in chunks {
no_outer_vectors();
for (l, &x) in lanes.iter_mut().zip(c) {
*l = f(*l, x);
}
}
for (l, &x) in lanes.iter_mut().zip(rest) {
*l = f(*l, x);
}
// A fixed tree over the lanes: the same order on every level.
let mut width = LANES;
while width > 1 {
width /= 2;
for i in 0..width {
lanes[i] = f(lanes[i], lanes[i + width]);
}
}
lanes[0]
}
}
struct Gather<'a, T, F> {
idx: &'a [u32],
vals: &'a [T],
init: T,
f: F,
}
impl<T: Copy, F: Fn(T, T) -> T> Kernel for Gather<'_, T, F> {
type Out = T;
#[inline(always)]
fn run(self) -> T {
let f = &self.f;
let mut lanes = [self.init; 4];
let (chunks, rest) = self.idx.as_chunks::<4>();
for c in chunks {
for (l, &j) in lanes.iter_mut().zip(c) {
*l = f(*l, self.vals[j as usize]);
}
}
for (l, &j) in lanes.iter_mut().zip(rest) {
*l = f(*l, self.vals[j as usize]);
}
f(f(lanes[0], lanes[2]), f(lanes[1], lanes[3]))
}
}
impl Simd {
/// The number of set bits.
pub fn popcount(self, words: &[u64]) -> usize {
dispatch!(self, Popcount(words))
}
/// `dst |= src`, word by word (over the shorter length).
pub fn or_assign(self, dst: &mut [u64], src: &[u64]) {
dispatch!(
self,
Combine {
dst,
src,
op: Op::Or
}
)
}
/// `dst &= src`, word by word.
pub fn and_assign(self, dst: &mut [u64], src: &[u64]) {
dispatch!(
self,
Combine {
dst,
src,
op: Op::And
}
)
}
/// `dst &= !src`, word by word.
pub fn and_not_assign(self, dst: &mut [u64], src: &[u64]) {
dispatch!(
self,
Combine {
dst,
src,
op: Op::AndNot
}
)
}
/// The first word at or after `from` that is not zero once XORed with `flip` (`words.len()`
/// when there is none): the next word of a mask with an allowed place.
pub fn first_nonzero(self, words: &[u64], flip: u64, from: usize) -> usize {
dispatch!(self, FirstNonZero { words, flip, from })
}
/// `f` folded over `xs` from `init`, in sixteen lanes joined by a fixed tree: `f` must
/// be associative and commutative with `init` its identity (a semiring's add and zero).
pub fn fold<T: Copy, F: Fn(T, T) -> T>(self, xs: &[T], init: T, f: F) -> T {
dispatch!(self, Fold { xs, init, f })
}
/// `f` folded over `vals[idx[k]]` for every `k` from `init` (four lanes; the same
/// rules as [`Simd::fold`]): a row of a sparse matrix against a dense vector.
pub fn fold_gather<T: Copy, F: Fn(T, T) -> T>(
self,
idx: &[u32],
vals: &[T],
init: T,
f: F,
) -> T {
dispatch!(self, Gather { idx, vals, init, f })
}
}
/// The hash of a row's key, value by value: the hash [`Simd::hash_rows`] gives every row
/// at once, and the one a caller hashing one row (a probe) must use to meet them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RowHash(u64);
impl Default for RowHash {
fn default() -> Self {
RowHash::new()
}
}
impl RowHash {
/// A hash of no values yet.
#[inline(always)]
pub const fn new() -> Self {
RowHash(0x243F_6A88_85A3_08D3)
}
/// The hash with value `x` mixed in.
#[inline(always)]
#[must_use]
pub const fn mix(self, x: u64) -> Self {
RowHash(
(self.0 ^ x)
.wrapping_mul(0x9E37_79B9_7F4A_7C15)
.rotate_left(27),
)
}
/// The finished hash.
#[inline(always)]
pub const fn finish(self) -> u64 {
let h = (self.0 ^ (self.0 >> 31)).wrapping_mul(0xD6E8_FEB8_6659_FD93);
h ^ (h >> 32)
}
}
/// One key column of the rows [`Simd::hash_rows`] hashes: `u32` or `u64` values (a `u32`
/// value hashes as the same `u64`).
#[derive(Clone, Copy, Debug)]
pub enum KeyCol<'a> {
/// Narrow values.
U32(&'a [u32]),
/// Wide values.
U64(&'a [u64]),
}
impl KeyCol<'_> {
/// The number of values.
pub fn len(&self) -> usize {
match self {
KeyCol::U32(v) => v.len(),
KeyCol::U64(v) => v.len(),
}
}
/// Whether it has no values.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Rows hashed per block: the block's hashes stay in the first-level cache while every
/// column is mixed in.
const HASH_BLOCK: usize = 256;
/// One step of a batch hash over a block: start, mix a column in, or finish.
enum HashStep<'a> {
Start,
Wide(&'a [u64]),
Narrow(&'a [u32]),
Finish,
}
struct Hash<'a> {
h: &'a mut [u64],
step: HashStep<'a>,
}
impl Kernel for Hash<'_> {
type Out = ();
#[inline(always)]
fn run(self) {
match self.step {
HashStep::Start => self.h.fill(RowHash::new().0),
HashStep::Wide(x) => {
let m = self.h.len();
for (h, &x) in self.h.iter_mut().zip(&x[..m]) {
*h = RowHash(*h).mix(x).0;
}
}
HashStep::Narrow(x) => {
let m = self.h.len();
for (h, &x) in self.h.iter_mut().zip(&x[..m]) {
*h = RowHash(*h).mix(x as u64).0;
}
}
HashStep::Finish => {
for h in self.h.iter_mut() {
*h = RowHash(*h).finish();
}
}
}
}
}
#[inline(always)]
fn compact_plain(keep: &[bool], base: u32, out: &mut [u32]) -> usize {
let mut n = 0;
for (k, &b) in keep.iter().enumerate() {
// Without a branch on `b` while a place is free: written always, counted if kept.
if let Some(o) = out.get_mut(n) {
*o = base + k as u32;
n += b as usize;
} else if b {
panic!(
"compaction: more kept rows than the output's {} places",
out.len()
);
}
}
n
}
#[inline(always)]
fn bits_plain(words: &[u64], base: u32, out: &mut [u32]) -> usize {
let room = out.len();
let mut n = 0;
for (wi, &w) in words.iter().enumerate() {
let mut w = w;
let at = base + 64 * wi as u32;
while w != 0 {
*out.get_mut(n).unwrap_or_else(|| {
panic!("compaction: more set bits than the output's {room} places")
}) = at + w.trailing_zeros();
n += 1;
w &= w - 1;
}
}
n
}
#[inline(always)]
fn select_plain<T: Copy + PartialOrd>(
col: &[T],
lo: T,
hi: T,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
let room = out.len();
let mut n = 0;
for (k, &x) in col.iter().enumerate() {
let b = (lo <= x && x <= hi) == inside;
if let Some(o) = out.get_mut(n) {
*o = base + k as u32;
n += b as usize;
} else if b {
panic!("selection: more kept rows than the output's {room} places");
}
}
n
}
fn check_places(base: u32, places: usize) {
assert!(
base as usize + places <= 1 << 32,
"compaction: places from {base} on past u32"
);
}
impl Simd {
/// The hash of rows `lo..lo + out.len()` of `cols` (every column at least that long)
/// into `out`: `out[k]` is [`RowHash`] of the row's values, column by column.
pub fn hash_rows(self, cols: &[KeyCol], lo: usize, out: &mut [u64]) {
for (b, h) in out.chunks_mut(HASH_BLOCK).enumerate() {
let at = lo + b * HASH_BLOCK;
let m = h.len();
dispatch!(
self,
Hash {
h: &mut *h,
step: HashStep::Start
}
);
for c in cols {
let step = match c {
KeyCol::U64(v) => HashStep::Wide(&v[at..at + m]),
KeyCol::U32(v) => HashStep::Narrow(&v[at..at + m]),
};
dispatch!(self, Hash { h: &mut *h, step });
}
dispatch!(
self,
Hash {
h,
step: HashStep::Finish
}
);
}
}
/// The places `base + k` of every `keep[k]` that is true, rising, written to the
/// front of `out`; returns how many. `out` needs a place per kept row (panics
/// otherwise; with `keep.len()` places it never does), and `base + keep.len()` must
/// not pass `2^32`. Places of `out` past the count may be overwritten.
pub fn compact_bools(self, keep: &[bool], base: u32, out: &mut [u32]) -> usize {
check_places(base, keep.len());
#[cfg(target_arch = "x86_64")]
match self.0 {
// SAFETY: `Simd` holds a level only when the host has its features.
SimdLevel::Avx512 | SimdLevel::Avx2 => {
return unsafe { x86::compact_bools_avx2(keep, base, out) };
}
_ => {}
}
compact_plain(keep, base, out)
}
/// The places `base + 64 w + b` of every set bit `b` of `words[w]`, rising, written to
/// the front of `out`; returns how many (as [`Simd::compact_bools`]: a place per set
/// bit needed, `base + 64 words.len()` within `2^32`).
pub fn bits_to_places(self, words: &[u64], base: u32, out: &mut [u32]) -> usize {
check_places(base, words.len() * 64);
#[cfg(target_arch = "x86_64")]
match self.0 {
// SAFETY: `Simd` holds a level only when the host has its features.
SimdLevel::Avx512 => return unsafe { x86::bits_to_places_avx512(words, base, out) },
SimdLevel::Avx2 => return unsafe { x86::bits_to_places_avx2(words, base, out) },
_ => {}
}
bits_plain(words, base, out)
}
/// The places `base + k` where `(lo <= col[k] && col[k] <= hi) == inside`, rising,
/// written to the front of `out`; returns how many (as [`Simd::compact_bools`]: a
/// place per kept row needed, `base + col.len()` within `2^32`). A `u32` column
/// compares as its `u64` values; a range past `u32::MAX` keeps what it reaches. Every
/// compare of `x` with a constant is one range: `==` (`k..=k`), `<`, `<=`, `>`, `>=`,
/// and `!=` (`k..=k` outside).
pub fn select_range(
self,
col: KeyCol,
lo: u64,
hi: u64,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
check_places(base, col.len());
match col {
KeyCol::U64(v) => {
#[cfg(target_arch = "x86_64")]
match self.0 {
// SAFETY: `Simd` holds a level only when the host has its features.
SimdLevel::Avx512 => {
return unsafe { x86::select_u64_avx512(v, lo, hi, inside, base, out) };
}
SimdLevel::Avx2 => {
return unsafe { x86::select_u64_avx2(v, lo, hi, inside, base, out) };
}
_ => {}
}
select_plain(v, lo, hi, inside, base, out)
}
KeyCol::U32(v) => {
// The range as u32 bounds: empty when it starts past u32::MAX.
if lo > u32::MAX as u64 || lo > hi {
return if inside {
0
} else {
self.select_range(col, 0, u64::MAX, true, base, out)
};
}
let (lo, hi) = (lo as u32, hi.min(u32::MAX as u64) as u32);
#[cfg(target_arch = "x86_64")]
match self.0 {
// SAFETY: `Simd` holds a level only when the host has its features.
SimdLevel::Avx512 => {
return unsafe { x86::select_u32_avx512(v, lo, hi, inside, base, out) };
}
SimdLevel::Avx2 => {
return unsafe { x86::select_u32_avx2(v, lo, hi, inside, base, out) };
}
_ => {}
}
select_plain(v, lo, hi, inside, base, out)
}
}
}
}