use std::cmp::Ordering;
use crate::buffer::Buffer;
use crate::dtype::{DType, Element, Value, cast};
use crate::ops::{BinaryOp, UnaryOp};
pub fn strides(shape: &[usize]) -> Vec<usize> {
let mut s = vec![1; shape.len()];
for i in (0..shape.len().saturating_sub(1)).rev() {
s[i] = s[i + 1] * shape[i + 1];
}
s
}
fn small_strides(shape: &[usize]) -> [usize; 8] {
let mut s = [1usize; 8];
for i in (0..shape.len().saturating_sub(1)).rev() {
s[i] = s[i + 1] * shape[i + 1];
}
s
}
pub fn size(shape: &[usize]) -> usize {
shape.iter().product()
}
pub fn unravel(mut flat: usize, shape: &[usize]) -> Vec<usize> {
let mut index = vec![0; shape.len()];
for (i, &d) in shape.iter().enumerate().rev() {
if d > 0 {
index[i] = flat % d;
flat /= d;
}
}
index
}
pub fn ravel(index: &[usize], strides: &[usize]) -> usize {
index.iter().zip(strides).map(|(i, s)| i * s).sum()
}
fn map_indices<T>(shape: &[usize], mut f: impl FnMut(&[usize]) -> T) -> Vec<T> {
let n = size(shape);
let mut out = Vec::with_capacity(n);
let mut index = vec![0; shape.len()];
for _ in 0..n {
out.push(f(&index));
for d in (0..shape.len()).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
out
}
pub fn broadcast_in_dim<T: Copy>(
x: &[T],
shape: &[usize],
out_shape: &[usize],
dims: &[usize],
) -> Vec<T> {
let n = size(out_shape);
if n == 0 {
return Vec::new();
}
let st = strides(shape);
let mut src = vec![0usize; out_shape.len()];
for (i, &d) in dims.iter().enumerate() {
if shape[i] != 1 {
src[d] = st[i];
}
}
strided_gather(x, out_shape, &src)
}
pub fn broadcast_in_dim_into<T: Copy>(
x: &[T],
shape: &[usize],
out_shape: &[usize],
dims: &[usize],
out: &mut [T],
) {
if out_shape.len() > 8 {
out.copy_from_slice(&broadcast_in_dim(x, shape, out_shape, dims));
return;
}
let st = small_strides(shape);
let mut src = [0usize; 8];
for (i, &d) in dims.iter().enumerate() {
if shape[i] != 1 {
src[d] = st[i];
}
}
strided_gather_into(x, out_shape, &src[..out_shape.len()], out);
}
pub fn strided_gather<T: Copy>(x: &[T], out_shape: &[usize], src_strides: &[usize]) -> Vec<T> {
let n = size(out_shape);
if n == 0 {
return Vec::new();
}
let mut out = vec![x[0]; n];
strided_gather_into(x, out_shape, src_strides, &mut out);
out
}
pub fn strided_gather_into<T: Copy>(
x: &[T],
out_shape: &[usize],
src_strides: &[usize],
out: &mut [T],
) {
if out.is_empty() {
return;
}
let mut stack = [(0usize, 0usize); 8];
let mut heap = Vec::new();
let mut nd = 0;
for (&d, &st) in out_shape.iter().zip(src_strides) {
if d == 1 {
continue;
}
let dims: &mut [(usize, usize)] = if out_shape.len() <= 8 {
&mut stack
} else {
if heap.is_empty() {
heap = vec![(0usize, 0usize); out_shape.len()];
}
&mut heap
};
if nd > 0 && dims[nd - 1].1 == d * st {
dims[nd - 1] = (dims[nd - 1].0 * d, st);
} else {
dims[nd] = (d, st);
nd += 1;
}
}
let dims: &[(usize, usize)] = if out_shape.len() <= 8 {
&stack[..nd]
} else {
&heap[..nd]
};
if dims.is_empty() {
out.fill(x[0]);
return;
}
let (inner, inner_st) = dims[dims.len() - 1];
let (mid, mid_st) = if dims.len() >= 2 {
dims[dims.len() - 2]
} else {
(1, 0)
};
let rest = &dims[..dims.len().saturating_sub(2)];
let block = inner * mid;
let mut index = [0usize; 8];
let mut index_heap = if rest.len() > 8 {
vec![0usize; rest.len()]
} else {
Vec::new()
};
let index: &mut [usize] = if rest.len() <= 8 {
&mut index[..rest.len()]
} else {
&mut index_heap
};
let mut base = 0usize;
for chunk in out.chunks_exact_mut(block) {
for (m, row) in chunk.chunks_exact_mut(inner).enumerate() {
let b = base + m * mid_st;
match inner_st {
0 => row.fill(x[b]),
1 => row.copy_from_slice(&x[b..b + inner]),
s => {
for (j, o) in row.iter_mut().enumerate() {
*o = x[b + j * s];
}
}
}
}
for d in (0..rest.len()).rev() {
index[d] += 1;
base += rest[d].1;
if index[d] < rest[d].0 {
break;
}
base -= rest[d].1 * rest[d].0;
index[d] = 0;
}
}
}
pub fn transpose<T: Copy>(x: &[T], shape: &[usize], perm: &[usize]) -> Vec<T> {
let st = strides(shape);
let out_shape: Vec<usize> = perm.iter().map(|&p| shape[p]).collect();
let src: Vec<usize> = perm.iter().map(|&p| st[p]).collect();
strided_gather(x, &out_shape, &src)
}
pub fn transpose_into<T: Copy>(x: &[T], shape: &[usize], perm: &[usize], out: &mut [T]) {
if perm.len() > 8 {
out.copy_from_slice(&transpose(x, shape, perm));
return;
}
let st = small_strides(shape);
let (mut out_shape, mut src) = ([0usize; 8], [0usize; 8]);
for (i, &p) in perm.iter().enumerate() {
out_shape[i] = shape[p];
src[i] = st[p];
}
let r = perm.len();
strided_gather_into(x, &out_shape[..r], &src[..r], out);
}
pub fn slice<T: Copy>(
x: &[T],
shape: &[usize],
start: &[usize],
limit: &[usize],
step: &[usize],
) -> Vec<T> {
let st = strides(shape);
let out_shape: Vec<usize> = (0..shape.len())
.map(|i| (limit[i].saturating_sub(start[i])).div_ceil(step[i]))
.collect();
map_indices(&out_shape, |out| {
let flat: usize = (0..shape.len())
.map(|i| (start[i] + out[i] * step[i]) * st[i])
.sum();
x[flat]
})
}
pub fn clamp_starts(starts: &[i64], shape: &[usize], sizes: &[usize]) -> Vec<usize> {
starts
.iter()
.zip(shape.iter().zip(sizes))
.map(|(&s, (&n, &k))| s.clamp(0, (n - k) as i64) as usize)
.collect()
}
pub fn dynamic_slice<T: Copy>(x: &[T], shape: &[usize], starts: &[i64], sizes: &[usize]) -> Vec<T> {
let start = clamp_starts(starts, shape, sizes);
let ones = vec![1; shape.len()];
let limit: Vec<usize> = start.iter().zip(sizes).map(|(s, k)| s + k).collect();
slice(x, shape, &start, &limit, &ones)
}
pub fn dynamic_update_slice<T: Copy>(
x: &[T],
shape: &[usize],
update: &[T],
update_shape: &[usize],
starts: &[i64],
) -> Vec<T> {
let start = clamp_starts(starts, shape, update_shape);
let st = strides(shape);
let mut out = x.to_vec();
let mut i = 0;
map_indices(update_shape, |u| {
let flat: usize = (0..shape.len()).map(|d| (start[d] + u[d]) * st[d]).sum();
out[flat] = update[i];
i += 1;
});
out
}
pub fn concatenate<T: Copy>(parts: &[(&[T], &[usize])], dim: usize) -> Vec<T> {
let shape0 = parts[0].1;
let outer: usize = shape0[..dim].iter().product();
let mut out = Vec::new();
for o in 0..outer {
for (x, shape) in parts {
let inner: usize = shape[dim..].iter().product();
out.extend_from_slice(&x[o * inner..(o + 1) * inner]);
}
}
out
}
pub fn pad<T: Copy>(x: &[T], shape: &[usize], value: T, config: &[(i64, i64, usize)]) -> Vec<T> {
let out_shape: Vec<usize> = shape
.iter()
.zip(config)
.map(|(&n, &(lo, hi, int))| {
let inner = if n == 0 { 0 } else { n + (n - 1) * int } as i64;
(lo + hi + inner).max(0) as usize
})
.collect();
let st = strides(shape);
map_indices(&out_shape, |out| {
let mut flat = 0;
for d in 0..shape.len() {
let (lo, _, int) = config[d];
let pos = out[d] as i64 - lo;
let step = int as i64 + 1;
if pos < 0 || pos % step != 0 || pos / step >= shape[d] as i64 {
return value;
}
flat += (pos / step) as usize * st[d];
}
x[flat]
})
}
pub fn rev<T: Copy>(x: &[T], shape: &[usize], dims: &[usize]) -> Vec<T> {
let n = size(shape);
if n == 0 {
return Vec::new();
}
let mut k = shape.len();
let mut block = 1;
while k > 0 && !dims.contains(&(k - 1)) {
k -= 1;
block *= shape[k];
}
if k == 0 {
return x.to_vec();
}
let outer = &shape[..k - 1];
let last = shape[k - 1];
let mut st = vec![0usize; k];
let mut s = 1;
for d in (0..k).rev() {
st[d] = s;
s *= shape[d];
}
let mut out = Vec::with_capacity(n);
let mut index = vec![0usize; outer.len()];
loop {
let base: usize = index
.iter()
.enumerate()
.map(|(d, &i)| {
let i = if dims.contains(&d) {
shape[d] - 1 - i
} else {
i
};
i * st[d]
})
.sum();
for j in (0..last).rev() {
let src = (base + j) * block;
out.extend_from_slice(&x[src..src + block]);
}
let mut d = outer.len();
loop {
if d == 0 {
return out;
}
d -= 1;
index[d] += 1;
if index[d] < outer[d] {
break;
}
index[d] = 0;
}
}
}
pub fn sort_order<T: Element>(a: T, b: T) -> Ordering {
if let (Value::Complex(ar, ai), Value::Complex(br, bi)) = (a.to_value(), b.to_value()) {
return sort_order(ar, br).then_with(|| sort_order(ai, bi));
}
#[allow(clippy::eq_op)]
let (a_nan, b_nan) = (a != a, b != b);
match (a_nan, b_nan) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
}
}
pub fn sort_permutation(
shape: &[usize],
dim: usize,
cmp: impl Fn(usize, usize) -> Ordering,
) -> Vec<usize> {
let n = shape[dim];
let inner: usize = shape[dim + 1..].iter().product();
let outer: usize = shape[..dim].iter().product();
let mut perm = vec![0; size(shape)];
let mut line: Vec<usize> = Vec::with_capacity(n);
for o in 0..outer {
for i in 0..inner {
let base = o * n * inner + i;
line.clear();
line.extend((0..n).map(|k| base + k * inner));
line.sort_by(|&a, &b| cmp(a, b));
for (k, &src) in line.iter().enumerate() {
perm[base + k * inner] = src;
}
}
}
perm
}
pub fn sort(operands: &[&Buffer], shape: &[usize], dim: usize, num_keys: usize) -> Vec<Buffer> {
type Cmp<'a> = Box<dyn Fn(usize, usize) -> Ordering + 'a>;
let keys: Vec<Cmp<'_>> = operands[..num_keys]
.iter()
.map(|b| crate::with_buffer!(b, |v| Box::new(|i, j| sort_order(v[i], v[j])) as Cmp<'_>))
.collect();
let perm = sort_permutation(shape, dim, |i, j| {
keys.iter()
.map(|cmp| cmp(i, j))
.find(|&o| o != Ordering::Equal)
.unwrap_or(Ordering::Equal)
});
operands
.iter()
.map(|b| {
crate::with_buffer!(b, |v| Buffer::from_vec(
perm.iter().map(|&p| v[p]).collect()
))
})
.collect()
}
pub fn iota<T: Element>(shape: &[usize], dim: usize) -> Vec<T> {
let mut out = vec![T::default(); size(shape)];
iota_into(shape, dim, &mut out);
out
}
pub fn iota_into<T: Element>(shape: &[usize], dim: usize, out: &mut [T]) {
let n = shape[dim];
let inner: usize = shape[dim + 1..].iter().product();
if n == 0 || inner == 0 {
return;
}
for block in out.chunks_exact_mut(n * inner) {
for (k, run) in block.chunks_exact_mut(inner).enumerate() {
run.fill(cast::<u64, T>(k as u64));
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ReduceOp {
Sum,
Max,
Min,
}
impl ReduceOp {
pub fn binary(self) -> BinaryOp {
match self {
ReduceOp::Sum => BinaryOp::Add,
ReduceOp::Max => BinaryOp::Max,
ReduceOp::Min => BinaryOp::Min,
}
}
pub fn identity<T: Element>(self) -> T {
match self {
ReduceOp::Sum => T::default(),
ReduceOp::Max => T::lowest(),
ReduceOp::Min => T::highest(),
}
}
}
pub fn reduced_shape(shape: &[usize], axes: &[usize]) -> Vec<usize> {
shape
.iter()
.enumerate()
.filter(|(i, _)| !axes.contains(i))
.map(|(_, &d)| d)
.collect()
}
pub fn reduce<T: Element>(x: &[T], shape: &[usize], axes: &[usize], op: ReduceOp) -> Vec<T> {
let mut sorted = axes.to_vec();
sorted.sort_unstable();
if sorted.windows(2).all(|w| w[1] == w[0] + 1)
&& sorted.last().is_some_and(|&a| a < shape.len())
{
let (a, b) = (sorted[0], sorted[sorted.len() - 1] + 1);
let pre = size(&shape[..a]);
let n = size(&shape[a..b]);
let post = size(&shape[b..]);
let mut out = vec![op.identity::<T>(); pre * post];
match op {
ReduceOp::Sum => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
T::binary(BinaryOp::Add, a, b)
}),
ReduceOp::Max => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
T::binary(BinaryOp::Max, a, b)
}),
ReduceOp::Min => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
T::binary(BinaryOp::Min, a, b)
}),
}
return out;
}
let out_shape = reduced_shape(shape, axes);
let out_st = strides(&out_shape);
let mut out = vec![op.identity::<T>(); size(&out_shape)];
let mut kept = out_st.iter();
let st: Vec<usize> = (0..shape.len())
.map(|d| {
if axes.contains(&d) {
0
} else {
*kept.next().expect("one stride per kept dimension")
}
})
.collect();
match op {
ReduceOp::Sum => reduce_strided(x, &mut out, shape, &st, |a, b| {
T::binary(BinaryOp::Add, a, b)
}),
ReduceOp::Max => reduce_strided(x, &mut out, shape, &st, |a, b| {
T::binary(BinaryOp::Max, a, b)
}),
ReduceOp::Min => reduce_strided(x, &mut out, shape, &st, |a, b| {
T::binary(BinaryOp::Min, a, b)
}),
}
out
}
#[inline(always)]
fn reduce_strided<T: Element>(
x: &[T],
out: &mut [T],
shape: &[usize],
st: &[usize],
f: impl Fn(T, T) -> T,
) {
let Some((&inner, outer_shape)) = shape.split_last() else {
if let (Some(o), Some(&v)) = (out.first_mut(), x.first()) {
*o = f(*o, v);
}
return;
};
if inner == 0 {
return;
}
let s_in = st[shape.len() - 1];
let mut index = vec![0usize; outer_shape.len()];
let mut base = 0usize;
for row in x.chunks_exact(inner) {
if s_in == 0 {
let mut acc = out[base];
for &v in row {
acc = f(acc, v);
}
out[base] = acc;
} else {
for (j, &v) in row.iter().enumerate() {
let o = base + j * s_in;
out[o] = f(out[o], v);
}
}
for d in (0..outer_shape.len()).rev() {
index[d] += 1;
base += st[d];
if index[d] < outer_shape[d] {
break;
}
base -= st[d] * outer_shape[d];
index[d] = 0;
}
}
}
#[inline(always)]
fn reduce_middle<T: Element>(
x: &[T],
out: &mut [T],
[pre, n, post]: [usize; 3],
f: impl Fn(T, T) -> T,
) {
if post == 1 {
for (o, row) in out.iter_mut().zip(x.chunks_exact(n.max(1))) {
for &v in row {
*o = f(*o, v);
}
}
return;
}
for p in 0..pre {
let o = &mut out[p * post..(p + 1) * post];
for k in 0..n {
let row = &x[(p * n + k) * post..(p * n + k + 1) * post];
for (o, &v) in o.iter_mut().zip(row) {
*o = f(*o, v);
}
}
}
}
pub fn reduce_all<T: Element>(x: &[T], op: ReduceOp) -> T {
let id = op.identity::<T>();
let associative = !matches!(
T::DTYPE.kind(),
crate::DTypeKind::Float | crate::DTypeKind::Complex
);
match op {
ReduceOp::Sum => fold(x, id, associative, |a, b| T::binary(BinaryOp::Add, a, b)),
ReduceOp::Max => fold(x, id, associative, |a, b| T::binary(BinaryOp::Max, a, b)),
ReduceOp::Min => fold(x, id, associative, |a, b| T::binary(BinaryOp::Min, a, b)),
}
}
#[inline(always)]
fn fold<T: Element>(x: &[T], id: T, associative: bool, f: impl Fn(T, T) -> T) -> T {
if associative && x.len() >= 16 {
let mut lanes = [id; 8];
let (chunks, rest) = x.as_chunks::<8>();
for c in chunks {
for (l, &v) in lanes.iter_mut().zip(c) {
*l = f(*l, v);
}
}
let acc = lanes.into_iter().fold(id, &f);
return rest.iter().fold(acc, |a, &v| f(a, v));
}
x.iter().fold(id, |a, &v| f(a, v))
}
pub fn arg_min_max<T: Element>(x: &[T], shape: &[usize], axis: usize, max: bool) -> Vec<u64> {
let n = shape[axis];
let post: usize = shape[axis + 1..].iter().product();
let pre: usize = shape[..axis].iter().product();
let mut out = Vec::with_capacity(pre * post);
for p in 0..pre {
for q in 0..post {
let mut best = 0usize;
let mut best_v: Option<T> = None;
for k in 0..n {
let v = x[(p * n + k) * post + q];
let better = match best_v {
None => true,
Some(b) => {
#[allow(clippy::eq_op)]
let (v_nan, b_nan) = (v != v, b != b);
if b_nan {
false
} else if v_nan {
true
} else if max {
v > b
} else {
v < b
}
}
};
if better {
best = k;
best_v = Some(v);
}
}
out.push(best as u64);
}
}
out
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum CumulativeOp {
Sum,
Prod,
Max,
Min,
LogSumExp,
}
impl CumulativeOp {
pub fn identity<T: Element>(self) -> T {
match self {
CumulativeOp::Sum => T::default(),
CumulativeOp::Prod => cast::<u64, T>(1),
CumulativeOp::Max | CumulativeOp::LogSumExp => T::lowest(),
CumulativeOp::Min => T::highest(),
}
}
#[inline]
pub fn combine<T: Element>(self, a: T, b: T) -> T {
match self {
CumulativeOp::Sum => T::binary(BinaryOp::Add, a, b),
CumulativeOp::Prod => T::binary(BinaryOp::Mul, a, b),
CumulativeOp::Max => T::binary(BinaryOp::Max, a, b),
CumulativeOp::Min => T::binary(BinaryOp::Min, a, b),
CumulativeOp::LogSumExp => {
let delta = T::binary(BinaryOp::Sub, a, b);
#[allow(clippy::eq_op)] if delta != delta {
T::binary(BinaryOp::Add, a, b)
} else {
let amax = T::binary(BinaryOp::Max, a, b);
let e = T::unary(UnaryOp::Neg, T::unary(UnaryOp::Abs, delta));
let l = T::unary(UnaryOp::Log1p, T::unary(UnaryOp::Exp, e));
T::binary(BinaryOp::Add, amax, l)
}
}
}
}
}
const SCAN_BLOCK: usize = 16;
fn scan_windows_into<T: Element>(
x: &[T],
out: &mut [T],
reverse: bool,
exclusive: bool,
op: CumulativeOp,
) {
let init = op.identity::<T>();
if !reverse {
let mut acc = init;
for (o, &v) in out.iter_mut().zip(x) {
let before = acc;
acc = op.combine(acc, v);
*o = if exclusive { before } else { acc };
}
} else {
for (i, o) in out.iter_mut().enumerate() {
let start = if exclusive { i + 1 } else { i };
*o = x[start..].iter().fold(init, |acc, &v| op.combine(acc, v));
}
}
}
fn scan_line_into<T: Element>(x: &[T], out: &mut [T], reverse: bool, op: CumulativeOp) {
let n = x.len();
if n <= SCAN_BLOCK {
scan_windows_into(x, out, reverse, false, op);
return;
}
let init = op.identity::<T>();
let blocks = n.div_ceil(SCAN_BLOCK);
let mut totals = vec![init; blocks];
let (mut block, mut scanned) = ([init; SCAN_BLOCK], [init; SCAN_BLOCK]);
for (b, total) in totals.iter_mut().enumerate() {
let (lo, hi) = (b * SCAN_BLOCK, ((b + 1) * SCAN_BLOCK).min(n));
block[..hi - lo].copy_from_slice(&x[lo..hi]);
block[hi - lo..].fill(init);
scan_windows_into(&block, &mut scanned, reverse, false, op);
out[lo..hi].copy_from_slice(&scanned[..hi - lo]);
*total = if reverse {
scanned[0]
} else {
scanned[SCAN_BLOCK - 1]
};
}
let mut outer = vec![init; blocks];
if blocks <= SCAN_BLOCK {
scan_windows_into(&totals, &mut outer, reverse, true, op);
} else {
let mut inclusive = vec![init; blocks];
scan_line_into(&totals, &mut inclusive, reverse, op);
if reverse {
outer[..blocks - 1].copy_from_slice(&inclusive[1..]);
} else {
outer[1..].copy_from_slice(&inclusive[..blocks - 1]);
}
}
for (i, o) in out.iter_mut().enumerate() {
*o = op.combine(*o, outer[i / SCAN_BLOCK]);
}
}
pub fn cumulative<T: Element>(
x: &[T],
shape: &[usize],
axis: usize,
reverse: bool,
op: CumulativeOp,
) -> Vec<T> {
let mut out = vec![T::default(); x.len()];
cumulative_into(x, shape, axis, reverse, op, &mut out);
out
}
pub fn cumulative_into<T: Element>(
x: &[T],
shape: &[usize],
axis: usize,
reverse: bool,
op: CumulativeOp,
out: &mut [T],
) {
let n = shape[axis];
let inner: usize = shape[axis + 1..].iter().product();
let outer: usize = shape[..axis].iter().product();
if inner == 1 {
for o in 0..outer {
let base = o * n;
scan_line_into(&x[base..base + n], &mut out[base..base + n], reverse, op);
}
return;
}
let (mut line, mut scanned) = (vec![T::default(); n], vec![T::default(); n]);
for o in 0..outer {
for i in 0..inner {
let base = o * n * inner + i;
for (k, l) in line.iter_mut().enumerate() {
*l = x[base + k * inner];
}
scan_line_into(&line, &mut scanned, reverse, op);
for (k, &v) in scanned.iter().enumerate() {
out[base + k * inner] = v;
}
}
}
}
fn top_k_key<T: Element>(v: T) -> i128 {
let dtype = T::DTYPE;
if dtype.is_float() {
let bits = 8 * dtype.size_in_bytes() as u32;
let shift = 64 - bits;
let s = ((v.to_bits() << shift) as i64) >> shift;
let s = if s < 0 {
s ^ (u64::MAX >> (65 - bits)) as i64
} else {
s
};
i128::from(s)
} else {
match v.to_value() {
Value::Int(i) => i128::from(i),
Value::UInt(u) => i128::from(u),
_ => i128::from(v.to_bits()),
}
}
}
pub fn top_k<T: Element>(x: &[T], shape: &[usize], k: usize, axis: usize) -> (Vec<T>, Vec<i32>) {
let rank = shape.len();
if axis + 1 == rank {
return top_k_last(x, shape, k);
}
let mut perm: Vec<usize> = (0..rank).collect();
perm.swap(axis, rank - 1);
let moved: Vec<usize> = perm.iter().map(|&d| shape[d]).collect();
let (values, indices) = top_k_last(&transpose(x, shape, &perm), &moved, k);
let mut out = moved;
out[rank - 1] = k;
(
transpose(&values, &out, &perm),
transpose(&indices, &out, &perm),
)
}
fn top_k_last<T: Element>(x: &[T], shape: &[usize], k: usize) -> (Vec<T>, Vec<i32>) {
let n = *shape.last().expect("top_k needs at least one dimension");
let lines = size(&shape[..shape.len() - 1]);
let mut values = Vec::with_capacity(lines * k);
let mut indices = Vec::with_capacity(lines * k);
let mut order: Vec<usize> = Vec::with_capacity(n);
for l in 0..lines {
let line = &x[l * n..(l + 1) * n];
order.clear();
order.extend(0..n);
order.sort_by(|&a, &b| top_k_key(line[b]).cmp(&top_k_key(line[a])));
for &i in &order[..k] {
values.push(line[i]);
indices.push(i as i32);
}
}
(values, indices)
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct DotDims {
pub lhs_contracting: Vec<usize>,
pub rhs_contracting: Vec<usize>,
pub lhs_batch: Vec<usize>,
pub rhs_batch: Vec<usize>,
}
pub fn free_dims(rank: usize, contracting: &[usize], batch: &[usize]) -> Vec<usize> {
(0..rank)
.filter(|d| !contracting.contains(d) && !batch.contains(d))
.collect()
}
pub fn dot_shape(lhs: &[usize], rhs: &[usize], d: &DotDims) -> Vec<usize> {
let mut out: Vec<usize> = d.lhs_batch.iter().map(|&i| lhs[i]).collect();
out.extend(
free_dims(lhs.len(), &d.lhs_contracting, &d.lhs_batch)
.iter()
.map(|&i| lhs[i]),
);
out.extend(
free_dims(rhs.len(), &d.rhs_contracting, &d.rhs_batch)
.iter()
.map(|&i| rhs[i]),
);
out
}
pub fn dot_general<T: Element>(
lhs: &[T],
lshape: &[usize],
rhs: &[T],
rshape: &[usize],
d: &DotDims,
) -> Vec<T> {
if matches!(T::DTYPE, DType::F16 | DType::BF16) {
let wide = |x: &[T]| {
x.iter()
.map(|&v| crate::cast::<T, f32>(v))
.collect::<Vec<f32>>()
};
return dot_general(&wide(lhs), lshape, &wide(rhs), rshape, d)
.into_iter()
.map(crate::cast::<f32, T>)
.collect();
}
let lfree = free_dims(lshape.len(), &d.lhs_contracting, &d.lhs_batch);
let rfree = free_dims(rshape.len(), &d.rhs_contracting, &d.rhs_batch);
let lperm: Vec<usize> = d
.lhs_batch
.iter()
.chain(&lfree)
.chain(&d.lhs_contracting)
.copied()
.collect();
let rperm: Vec<usize> = d
.rhs_batch
.iter()
.chain(&d.rhs_contracting)
.chain(&rfree)
.copied()
.collect();
let lt = permuted(lhs, lshape, &lperm);
let rt = permuted(rhs, rshape, &rperm);
let batch: usize = d.lhs_batch.iter().map(|&i| lshape[i]).product();
let m: usize = lfree.iter().map(|&i| lshape[i]).product();
let kk: usize = d.lhs_contracting.iter().map(|&i| lshape[i]).product();
let n: usize = rfree.iter().map(|&i| rshape[i]).product();
let mut out = vec![T::default(); batch * m * n];
if m * n == 0 || kk == 0 {
return out;
}
for ((o, l), r) in out
.chunks_exact_mut(m * n)
.zip(lt.chunks_exact(m * kk))
.zip(rt.chunks_exact(kk * n))
{
matmul_rows(o, l, r, kk, n);
}
out
}
fn permuted<'a, T: Copy>(x: &'a [T], shape: &[usize], perm: &[usize]) -> std::borrow::Cow<'a, [T]> {
if perm.iter().enumerate().all(|(i, &p)| i == p) {
std::borrow::Cow::Borrowed(x)
} else {
std::borrow::Cow::Owned(transpose(x, shape, perm))
}
}
fn matmul_rows<T: Element>(out: &mut [T], l: &[T], r: &[T], kk: usize, n: usize) {
let fma = |o: T, a: T, b: T| T::binary(BinaryOp::Add, o, T::binary(BinaryOp::Mul, a, b));
let m = out.len() / n;
let full_cols = n - n % TILE_COLS;
let mut i = 0;
while i + 4 <= m {
let mut j = 0;
while j < full_cols {
let mut acc = [[T::default(); TILE_COLS]; 4];
for k in 0..kk {
let rrow: &[T; TILE_COLS] = r[k * n + j..k * n + j + TILE_COLS]
.try_into()
.expect("tile");
for (t, accrow) in acc.iter_mut().enumerate() {
let a = l[(i + t) * kk + k];
for (x, &b) in accrow.iter_mut().zip(rrow) {
*x = fma(*x, a, b);
}
}
}
for (t, accrow) in acc.iter().enumerate() {
out[(i + t) * n + j..(i + t) * n + j + TILE_COLS].copy_from_slice(accrow);
}
j += TILE_COLS;
}
i += 4;
}
for row in 0..m {
let cols = if row < i { full_cols..n } else { 0..n };
if cols.is_empty() {
continue;
}
let lrow = &l[row * kk..(row + 1) * kk];
let orow = &mut out[row * n + cols.start..row * n + cols.end];
for (k, &a) in lrow.iter().enumerate() {
let rrow = &r[k * n + cols.start..k * n + cols.end];
for (o, &b) in orow.iter_mut().zip(rrow) {
*o = fma(*o, a, b);
}
}
}
}
const TILE_COLS: usize = 16;
pub fn select_n<T: Copy>(which: &[usize], cases: &[&[T]]) -> Vec<T> {
let n = cases[0].len();
(0..n)
.map(|i| {
let w = if which.len() == 1 { which[0] } else { which[i] };
cases[w.min(cases.len() - 1)][i]
})
.collect()
}
pub fn clamp<T: Element>(lo: &[T], x: &[T], hi: &[T]) -> Vec<T> {
let at = |a: &[T], i: usize| if a.len() == 1 { a[0] } else { a[i] };
(0..x.len())
.map(|i| {
let v = T::binary(BinaryOp::Max, x[i], at(lo, i));
T::binary(BinaryOp::Min, v, at(hi, i))
})
.collect()
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub enum GatherScatterMode {
#[default]
Clip,
FillOrDrop,
PromiseInBounds,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct GatherDims {
pub offset_dims: Vec<usize>,
pub collapsed_slice_dims: Vec<usize>,
pub start_index_map: Vec<usize>,
pub operand_batching_dims: Vec<usize>,
pub start_indices_batching_dims: Vec<usize>,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct ScatterDims {
pub update_window_dims: Vec<usize>,
pub inserted_window_dims: Vec<usize>,
pub scatter_dims_to_operand_dims: Vec<usize>,
pub operand_batching_dims: Vec<usize>,
pub scatter_indices_batching_dims: Vec<usize>,
}
pub fn gather_shape(indices: &[usize], d: &GatherDims, slice_sizes: &[usize]) -> Vec<usize> {
let q = indices.len();
let out_rank = d.offset_dims.len() + q - 1;
let mut offsets = (0..slice_sizes.len())
.filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
.map(|i| slice_sizes[i]);
let mut batch = indices[..q - 1].iter().copied();
(0..out_rank)
.map(|i| {
if d.offset_dims.contains(&i) {
offsets.next().expect("offset dimension")
} else {
batch.next().expect("batch dimension")
}
})
.collect()
}
pub fn gather<T: Copy>(
x: &[T],
shape: &[usize],
indices: &[i64],
indices_shape: &[usize],
d: &GatherDims,
slice_sizes: &[usize],
) -> Vec<T> {
let out_shape = gather_shape(indices_shape, d, slice_sizes);
let st = strides(shape);
let out_st = strides(&out_shape);
let q = indices_shape.len();
let vec_len = indices_shape[q - 1];
let batch_dims: Vec<usize> = (0..out_shape.len())
.filter(|i| !d.offset_dims.contains(i))
.collect();
let offset_operand: Vec<usize> = (0..shape.len())
.filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
.collect();
let slice_shape: Vec<usize> = offset_operand.iter().map(|&od| slice_sizes[od]).collect();
let mut slice_x = Vec::with_capacity(slice_shape.iter().product());
let mut slice_out = Vec::with_capacity(slice_x.capacity());
for_each_index(&slice_shape, |o| {
let mut ox = 0;
let mut oo = 0;
for (k, &v) in o.iter().enumerate() {
ox += v * st[offset_operand[k]];
oo += v * out_st[d.offset_dims[k]];
}
slice_x.push(ox);
slice_out.push(oo);
});
let batch_shape = &indices_shape[..q - 1];
let size: usize = out_shape.iter().product();
if size == 0 {
return Vec::new();
}
let mut out = vec![x[0]; size];
let mut b = 0;
for_each_index(batch_shape, |batch| {
let start = &indices[b * vec_len..(b + 1) * vec_len];
let mut base = 0;
for (&i, &od) in start.iter().zip(&d.start_index_map) {
let hi = (shape[od] - slice_sizes[od]) as i64;
base += i.clamp(0, hi) as usize * st[od];
}
for (&ob, &ib) in d
.operand_batching_dims
.iter()
.zip(&d.start_indices_batching_dims)
{
base += batch[ib] * st[ob];
}
let out_base: usize = batch
.iter()
.zip(&batch_dims)
.map(|(&v, &od)| v * out_st[od])
.sum();
for (&sx, &so) in slice_x.iter().zip(&slice_out) {
out[out_base + so] = x[base + sx];
}
b += 1;
});
out
}
fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
if shape.contains(&0) {
return;
}
let mut index = vec![0usize; shape.len()];
loop {
f(&index);
let mut k = shape.len();
loop {
if k == 0 {
return;
}
k -= 1;
index[k] += 1;
if index[k] < shape[k] {
break;
}
index[k] = 0;
}
}
}
pub fn scatter_window(rank: usize, updates_shape: &[usize], d: &ScatterDims) -> Vec<usize> {
let mut window = d.update_window_dims.iter();
(0..rank)
.map(|i| {
if d.inserted_window_dims.contains(&i) || d.operand_batching_dims.contains(&i) {
1
} else {
updates_shape[*window.next().expect("window dimension")]
}
})
.collect()
}
#[allow(clippy::too_many_arguments)]
pub fn scatter<T: Copy>(
x: &[T],
shape: &[usize],
indices: &[i64],
indices_shape: &[usize],
updates: &[T],
updates_shape: &[usize],
d: &ScatterDims,
mode: GatherScatterMode,
combine: Option<&dyn Fn(T, T) -> T>,
) -> Vec<T> {
let window = scatter_window(shape.len(), updates_shape, d);
let st = strides(shape);
let ist = strides(indices_shape);
let ust = strides(updates_shape);
let q = indices_shape.len();
let scatter_dims: Vec<usize> = (0..updates_shape.len())
.filter(|i| !d.update_window_dims.contains(i))
.collect();
let window_operand: Vec<usize> = (0..shape.len())
.filter(|i| !d.inserted_window_dims.contains(i) && !d.operand_batching_dims.contains(i))
.collect();
let mut out = x.to_vec();
let ru = updates_shape.len();
let nw = d.update_window_dims.len();
if d.operand_batching_dims.is_empty()
&& d.update_window_dims.iter().copied().eq(ru - nw..ru)
&& q >= 1
{
let window_size: usize = updates_shape[ru - nw..].iter().product();
let mut offsets = vec![0usize; window_size];
for (w, o) in offsets.iter_mut().enumerate() {
let mut rem = w;
for (k, &od) in window_operand.iter().enumerate().rev() {
let n = updates_shape[ru - nw + k];
*o += (rem % n) * st[od];
rem /= n;
}
}
let vector = indices_shape[q - 1];
let blocks = updates.len().checked_div(window_size).unwrap_or(0);
'blocks: for b in 0..blocks {
let mut base = 0;
for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
let hi = (shape[od] - window[od]) as i64;
let start = indices[b * vector + k];
let start = if mode == GatherScatterMode::Clip {
start.clamp(0, hi)
} else if (0..=hi).contains(&start) {
start
} else {
continue 'blocks;
};
base += start as usize * st[od];
}
let ub = &updates[b * window_size..(b + 1) * window_size];
match combine {
Some(f) => {
for (&o, &u) in offsets.iter().zip(ub) {
out[base + o] = f(out[base + o], u);
}
}
None => {
for (&o, &u) in offsets.iter().zip(ub) {
out[base + o] = u;
}
}
}
}
return out;
}
let mut up = vec![0usize; updates_shape.len()];
let mut full = vec![0i64; shape.len()];
for (flat, &u) in updates.iter().enumerate() {
for (k, (&s, &n)) in ust.iter().zip(updates_shape).enumerate() {
up[k] = (flat / s) % n;
}
let at0: usize = scatter_dims
.iter()
.zip(&ist[..q - 1])
.map(|(&sd, &s)| up[sd] * s)
.sum();
full.iter_mut().for_each(|f| *f = 0);
let mut dropped = false;
for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
let hi = (shape[od] - window[od]) as i64;
let start = indices[at0 + k * ist[q - 1]];
if mode == GatherScatterMode::Clip {
full[od] = start.clamp(0, hi);
} else if (0..=hi).contains(&start) {
full[od] = start;
} else {
dropped = true;
break;
}
}
if dropped {
continue;
}
for (&ob, &ib) in d
.operand_batching_dims
.iter()
.zip(&d.scatter_indices_batching_dims)
{
full[ob] += up[scatter_dims[ib]] as i64;
}
for (&od, &ud) in window_operand.iter().zip(&d.update_window_dims) {
full[od] += up[ud] as i64;
}
let o: usize = full.iter().zip(&st).map(|(&v, &s)| v as usize * s).sum();
out[o] = match combine {
Some(f) => f(out[o], u),
None => u,
};
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reduce_over_axes_apart() {
let shape = [2, 3, 2, 3, 2];
let x: Vec<f32> = (0..72).map(|i| (i as f32 * 0.37).sin()).collect();
for axes in [vec![1, 3], vec![0, 2, 4], vec![0, 4], vec![1, 3, 4]] {
let out_shape = reduced_shape(&shape, &axes);
let mut expected = vec![0.0f32; size(&out_shape)];
let mut index = [0usize; 5];
for &v in &x {
let mut o = 0;
for d in 0..5 {
if !axes.contains(&d) {
o = o * shape[d] + index[d];
}
}
expected[o] += v;
for d in (0..5).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
let got = reduce(&x, &shape, &axes, ReduceOp::Sum);
let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::<Vec<_>>();
assert_eq!(bits(&got), bits(&expected), "axes {axes:?}");
let max = reduce(&x, &shape, &axes, ReduceOp::Max);
assert_eq!(max.len(), expected.len());
}
}
#[test]
fn shape_operations() {
let x: Vec<i32> = (0..6).collect();
assert_eq!(transpose(&x, &[2, 3], &[1, 0]), [0, 3, 1, 4, 2, 5]);
assert_eq!(broadcast_in_dim(&[1, 2], &[2], &[2, 2], &[0]), [1, 1, 2, 2]);
assert_eq!(slice(&x, &[2, 3], &[0, 1], &[2, 3], &[1, 2]), [1, 4]);
assert_eq!(dynamic_slice(&x, &[2, 3], &[5, -1], &[1, 2]), [3, 4]);
assert_eq!(
dynamic_update_slice(&x, &[2, 3], &[9], &[1, 1], &[1, 9]),
[0, 1, 2, 3, 4, 9]
);
assert_eq!(concatenate(&[(&[1, 2], &[2]), (&[3], &[1])], 0), [1, 2, 3]);
assert_eq!(pad(&[1, 2], &[2], 0, &[(1, -1, 1)]), [0, 1, 0]);
assert_eq!(rev(&x, &[2, 3], &[1]), [2, 1, 0, 5, 4, 3]);
assert_eq!(iota::<f32>(&[2, 2], 1), [0.0, 1.0, 0.0, 1.0]);
}
#[test]
fn cumulative_reductions() {
let x = [1, 2, 3, 4, 5, 6];
let c = |axis, reverse, op| cumulative(&x, &[2, 3], axis, reverse, op);
assert_eq!(c(1, false, CumulativeOp::Sum), [1, 3, 6, 4, 9, 15]);
assert_eq!(c(1, true, CumulativeOp::Sum), [6, 5, 3, 15, 11, 6]);
assert_eq!(c(0, false, CumulativeOp::Prod), [1, 2, 3, 4, 10, 18]);
assert_eq!(c(0, true, CumulativeOp::Min), [1, 2, 3, 4, 5, 6]);
for n in [17, 40, 300] {
let x: Vec<i32> = (0..n).map(|i| (i * 7) % 11 - 5).collect();
let fwd = cumulative(&x, &[n as usize], 0, false, CumulativeOp::Sum);
let rev = cumulative(&x, &[n as usize], 0, true, CumulativeOp::Sum);
let mut acc = 0;
for i in 0..x.len() {
acc += x[i];
assert_eq!(fwd[i], acc);
assert_eq!(rev[i], x[i..].iter().sum::<i32>());
}
}
let x = [1.0f32, f32::NAN, 0.5];
let m = cumulative(&x, &[3], 0, false, CumulativeOp::Max);
assert!(m[0] == 1.0 && m[1].is_nan() && m[2].is_nan());
let l = cumulative(&[0.0f64, 0.0], &[2], 0, false, CumulativeOp::LogSumExp);
assert_eq!(l, [0.0, 2f64.ln()]);
}
#[test]
fn top_k_orders_by_bits() {
let nan = f32::NAN;
let x = [1.0, -nan, -0.0, 0.0, nan, f32::NEG_INFINITY, 1.0];
let (v, i) = top_k(&x, &[7], 7, 0);
assert_eq!(i, [4, 0, 6, 3, 2, 5, 1]);
assert!(v[0].is_nan() && v[6].is_nan());
assert_eq!(v[3].to_bits(), 0.0f32.to_bits());
assert_eq!(v[4].to_bits(), (-0.0f32).to_bits());
let (v, i) = top_k(&[1, 5, 3, 2, 3, 9], &[3, 2], 2, 0);
assert_eq!(v, [3, 9, 3, 5]);
assert_eq!(i, [1, 2, 2, 0]);
}
#[test]
fn sorting() {
let nan = f32::NAN;
let x = [1.0f32, -nan, 0.0, -0.0, f32::NEG_INFINITY, nan, -1.0];
let v: Vec<i32> = (0..7).collect();
let out = sort(
&[&Buffer::from_vec(x.to_vec()), &Buffer::from_vec(v)],
&[7],
0,
1,
);
assert_eq!(out[1].as_slice::<i32>().unwrap(), [4, 6, 2, 3, 0, 1, 5]);
let k1 = Buffer::from_vec(vec![1u8, 0, 1, 0, 2, 2]);
let k2 = Buffer::from_vec(vec![true, true, false, false, true, false]);
let out = sort(&[&k1, &k2], &[2, 3], 1, 2);
assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 1, 1, 0, 2, 2]);
assert_eq!(
out[1].as_slice::<bool>().unwrap(),
[true, false, true, false, false, true]
);
let out = sort(&[&k1], &[2, 3], 0, 1);
assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 0, 1, 1, 2, 2]);
}
#[test]
fn reductions() {
let x = [1.0f32, 5.0, 3.0, 7.0, 2.0, 7.0];
assert_eq!(reduce(&x, &[2, 3], &[1], ReduceOp::Sum), [9.0, 16.0]);
assert_eq!(reduce(&x, &[2, 3], &[0, 1], ReduceOp::Max), [7.0]);
assert_eq!(arg_min_max(&x, &[2, 3], 1, true), [1, 0]);
assert_eq!(arg_min_max(&[1.0f32, f32::NAN, 3.0], &[3], 0, true), [1]);
assert_eq!(reduce::<bool>(&[], &[0], &[0], ReduceOp::Max), [false]);
}
#[test]
fn dot() {
let a = [1, 2, 3, 4];
let b = [5, 6, 7, 8];
let d = DotDims {
lhs_contracting: vec![1],
rhs_contracting: vec![0],
..DotDims::default()
};
assert_eq!(dot_general(&a, &[2, 2], &b, &[2, 2], &d), [19, 22, 43, 50]);
}
#[test]
fn gather_and_scatter() {
let x: Vec<i32> = (0..15).collect();
let rows = GatherDims {
offset_dims: vec![1],
collapsed_slice_dims: vec![0],
start_index_map: vec![0],
..GatherDims::default()
};
assert_eq!(
gather(&x, &[5, 3], &[3, 9], &[2, 1], &rows, &[1, 3]),
[9, 10, 11, 12, 13, 14]
);
let d = ScatterDims {
update_window_dims: vec![1],
inserted_window_dims: vec![0],
scatter_dims_to_operand_dims: vec![0],
..ScatterDims::default()
};
let set = scatter(
&x,
&[5, 3],
&[1, 7],
&[2, 1],
&[-1, -1, -1, -2, -2, -2],
&[2, 3],
&d,
GatherScatterMode::FillOrDrop,
None,
);
assert_eq!(&set[..6], [0, 1, 2, -1, -1, -1]);
assert_eq!(&set[12..], [12, 13, 14]);
let add = |a: i32, b: i32| a + b;
let summed = scatter(
&x,
&[5, 3],
&[2, 2],
&[2, 1],
&[1; 6],
&[2, 3],
&d,
GatherScatterMode::Clip,
Some(&add),
);
assert_eq!(&summed[6..9], [8, 9, 10]);
}
}
#[cfg(test)]
mod dot_tests {
use super::*;
#[test]
fn matrix_products_match_the_general_path() {
let l: Vec<f32> = (0..3 * 5).map(|i| (i as f32 * 0.37).sin()).collect();
let r: Vec<f32> = (0..5 * 4).map(|i| (i as f32 * 0.71).cos()).collect();
let fast = dot_general(
&l,
&[3, 5],
&r,
&[5, 4],
&DotDims {
lhs_contracting: vec![1],
rhs_contracting: vec![0],
..DotDims::default()
},
);
let lt: Vec<f32> = (0..15).map(|i| l[(i % 3) * 5 + i / 3]).collect();
let general = dot_general(
<,
&[5, 3],
&r,
&[5, 4],
&DotDims {
lhs_contracting: vec![0],
rhs_contracting: vec![0],
..DotDims::default()
},
);
assert_eq!(fast, general);
let v = dot_general(
&l,
&[3, 5],
&r[..5],
&[5],
&DotDims {
lhs_contracting: vec![1],
rhs_contracting: vec![0],
..DotDims::default()
},
);
let expected: Vec<f32> = (0..3)
.map(|m| (0..5).fold(0.0f32, |acc, k| acc + l[m * 5 + k] * r[k]))
.collect();
assert_eq!(v, expected);
}
}