use crate::array::{ReduceOp, size, strides};
use crate::dtype::{DType, Element, cast};
use crate::ops::{BinaryOp, CompareOp, compare};
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct ConvDims {
pub lhs_spec: Vec<usize>,
pub rhs_spec: Vec<usize>,
pub out_spec: Vec<usize>,
}
impl ConvDims {
pub fn canonical(rank: usize) -> Self {
let iota: Vec<usize> = (0..rank).collect();
Self {
lhs_spec: iota.clone(),
rhs_spec: iota.clone(),
out_spec: iota,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ConvWindow<'a> {
pub strides: &'a [usize],
pub padding: &'a [(i64, i64)],
pub lhs_dilation: &'a [usize],
pub rhs_dilation: &'a [usize],
}
pub fn dilate_dim(d: usize, dilation: usize) -> usize {
if d == 0 { 0 } else { 1 + dilation * (d - 1) }
}
pub fn stride_dim(d: i64, window: usize, stride: usize) -> usize {
let window = window as i64;
if d < window {
0
} else {
((d - window) / stride as i64 + 1) as usize
}
}
pub fn conv_shape(
lhs: &[usize],
rhs: &[usize],
w: &ConvWindow<'_>,
d: &ConvDims,
batch_group_count: usize,
) -> Vec<usize> {
let mut out = vec![0; lhs.len()];
out[d.out_spec[0]] = lhs[d.lhs_spec[0]] / batch_group_count.max(1);
out[d.out_spec[1]] = rhs[d.rhs_spec[0]];
for k in 0..lhs.len().saturating_sub(2) {
let (lo, hi) = w.padding[k];
let padded = dilate_dim(lhs[d.lhs_spec[2 + k]], w.lhs_dilation[k]) as i64 + lo + hi;
let window = dilate_dim(rhs[d.rhs_spec[2 + k]], w.rhs_dilation[k]);
out[d.out_spec[2 + k]] = stride_dim(padded, window, w.strides[k]);
}
out
}
fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
let n = size(shape);
let mut index = vec![0; shape.len()];
for _ in 0..n {
f(&index);
for d in (0..shape.len()).rev() {
index[d] += 1;
if index[d] < shape[d] {
break;
}
index[d] = 0;
}
}
}
fn all_indices(shape: &[usize]) -> Vec<Vec<usize>> {
let mut out = Vec::with_capacity(size(shape));
for_each_index(shape, |i| out.push(i.to_vec()));
out
}
#[inline]
fn undilate(p: i64, lo: i64, dilation: usize, n: usize) -> Option<usize> {
let p = p - lo;
let dilation = dilation as i64;
if p < 0 || p % dilation != 0 || p / dilation >= n as i64 {
None
} else {
Some((p / dilation) as usize)
}
}
#[allow(clippy::too_many_arguments)]
pub fn conv_general_dilated<T: Element>(
lhs: &[T],
lshape: &[usize],
rhs: &[T],
rshape: &[usize],
w: &ConvWindow<'_>,
d: &ConvDims,
feature_group_count: usize,
batch_group_count: usize,
) -> Vec<T> {
if matches!(T::DTYPE, DType::F16 | DType::BF16) {
let wide = |x: &[T]| x.iter().map(|&v| cast::<T, f32>(v)).collect::<Vec<f32>>();
return conv_general_dilated(
&wide(lhs),
lshape,
&wide(rhs),
rshape,
w,
d,
feature_group_count,
batch_group_count,
)
.into_iter()
.map(cast::<f32, T>)
.collect();
}
if let Some(out) = conv_features_last(
lhs,
lshape,
rhs,
rshape,
w,
d,
feature_group_count,
batch_group_count,
) {
return out;
}
let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
let nsp = lshape.len() - 2;
let (lst, rst) = (strides(lshape), strides(rshape));
let out_features = rshape[d.rhs_spec[0]];
let in_features = rshape[d.rhs_spec[1]];
let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
let out_per_feature_group = (out_features / feature_group_count).max(1);
let out_per_batch_group = (out_features / batch_group_count).max(1);
let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
.into_iter()
.map(|kidx| {
let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
(kidx, off)
})
.collect();
let lfeat = lst[d.lhs_spec[1]];
let rfeat = rst[d.rhs_spec[1]];
let fused = T::DTYPE == DType::F64;
let mut out = Vec::with_capacity(size(&out_shape));
for_each_index(&out_shape, |o| {
let b = o[d.out_spec[0]];
let f = o[d.out_spec[1]];
let feature_group = f / out_per_feature_group;
let batch_group = f / out_per_batch_group;
let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
+ feature_group * in_features * lfeat;
let rbase = f * rst[d.rhs_spec[0]];
let mut acc = T::default();
'positions: for (kidx, roff) in &positions {
let mut loff = 0;
for k in 0..nsp {
let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
let n = lshape[d.lhs_spec[2 + k]];
match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
None => continue 'positions,
}
}
let (l0, r0) = (lbase + loff, rbase + roff);
if fused {
for i in 0..in_features {
let (a, b): (f64, f64) = (cast(lhs[l0 + i * lfeat]), cast(rhs[r0 + i * rfeat]));
acc = cast(a.mul_add(b, cast(acc)));
}
} else {
for i in 0..in_features {
let p = T::binary(BinaryOp::Mul, lhs[l0 + i * lfeat], rhs[r0 + i * rfeat]);
acc = T::binary(BinaryOp::Add, acc, p);
}
}
}
out.push(acc);
});
out
}
#[allow(clippy::too_many_arguments)]
fn conv_features_last<T: Element>(
lhs: &[T],
lshape: &[usize],
rhs: &[T],
rshape: &[usize],
w: &ConvWindow<'_>,
d: &ConvDims,
feature_group_count: usize,
batch_group_count: usize,
) -> Option<Vec<T>> {
let rank = lshape.len();
let nsp = rank.checked_sub(2)?;
if nsp == 0
|| matches!(T::DTYPE, DType::F64 | DType::F16 | DType::BF16)
|| feature_group_count != 1
|| batch_group_count != 1
|| w.lhs_dilation.iter().any(|&x| x != 1)
|| w.rhs_dilation.iter().any(|&x| x != 1)
|| d.lhs_spec[1] != rank - 1
|| d.rhs_spec[0] != rank - 1
|| d.out_spec[1] != rank - 1
{
return None;
}
let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
let (lst, rst) = (strides(lshape), strides(rshape));
let ost = strides(&out_shape);
let features = rshape[d.rhs_spec[0]];
let in_features = rshape[d.rhs_spec[1]];
let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
.into_iter()
.map(|kidx| {
let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
(kidx, off)
})
.collect();
let rfeat = rst[d.rhs_spec[1]];
let mut out = vec![T::default(); size(&out_shape)];
const BLOCK: usize = 4;
let last = out_shape[d.out_spec[1 + nsp]];
let mut row_shape = vec![out_shape[d.out_spec[0]]];
row_shape.extend((0..nsp - 1).map(|k| out_shape[d.out_spec[2 + k]]));
let mut acc = vec![T::default(); BLOCK * features];
for r in all_indices(&row_shape) {
let lbase = r[0] * lst[d.lhs_spec[0]];
let mut j0 = 0;
while j0 < last {
let nb = BLOCK.min(last - j0);
acc.fill(T::default());
for (kidx, roff) in &positions {
let mut offs = [None; BLOCK];
let mut inside = true;
for (j, off) in offs.iter_mut().enumerate().take(nb) {
let mut loff = 0;
let mut ok = true;
for k in 0..nsp {
let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
let p = (o * w.strides[k] + kidx[k]) as i64 - w.padding[k].0;
if p < 0 || p >= lshape[d.lhs_spec[2 + k]] as i64 {
ok = false;
break;
}
loff += p as usize * lst[d.lhs_spec[2 + k]];
}
*off = ok.then_some(lbase + loff);
inside &= ok;
}
if inside && nb == BLOCK {
let o: [usize; BLOCK] = std::array::from_fn(|j| offs[j].unwrap_or(0));
const CH: usize = 16;
let full = features - features % CH;
for fc in (0..full).step_by(CH) {
let mut y: [[T; CH]; BLOCK] = std::array::from_fn(|j| {
std::array::from_fn(|c| acc[j * features + fc + c])
});
for i in 0..in_features {
let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
let base = roff + i * rfeat + fc;
let row: &[T; CH] = rhs[base..base + CH].try_into().expect("a chunk");
for c in 0..CH {
let wv = row[c];
for j in 0..BLOCK {
y[j][c] = T::binary(
BinaryOp::Add,
y[j][c],
T::binary(BinaryOp::Mul, x[j], wv),
);
}
}
}
for (j, yj) in y.iter().enumerate() {
acc[j * features + fc..j * features + fc + CH].copy_from_slice(yj);
}
}
if full < features {
let (a0, rest) = acc.split_at_mut(features);
let (a1, rest) = rest.split_at_mut(features);
let (a2, a3) = rest.split_at_mut(features);
for i in 0..in_features {
let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
let row = &rhs[roff + i * rfeat + full..roff + i * rfeat + features];
let lanes = a0[full..]
.iter_mut()
.zip(a1[full..].iter_mut())
.zip(a2[full..].iter_mut())
.zip(a3[full..].iter_mut())
.zip(row);
for ((((y0, y1), y2), y3), &wv) in lanes {
*y0 = T::binary(
BinaryOp::Add,
*y0,
T::binary(BinaryOp::Mul, x[0], wv),
);
*y1 = T::binary(
BinaryOp::Add,
*y1,
T::binary(BinaryOp::Mul, x[1], wv),
);
*y2 = T::binary(
BinaryOp::Add,
*y2,
T::binary(BinaryOp::Mul, x[2], wv),
);
*y3 = T::binary(
BinaryOp::Add,
*y3,
T::binary(BinaryOp::Mul, x[3], wv),
);
}
}
}
} else {
for (j, off) in offs.iter().enumerate().take(nb) {
let Some(l0) = *off else { continue };
let aj = &mut acc[j * features..(j + 1) * features];
for i in 0..in_features {
let a = lhs[l0 + i];
let row = &rhs[roff + i * rfeat..roff + i * rfeat + features];
for (x, &b) in aj.iter_mut().zip(row) {
*x = T::binary(BinaryOp::Add, *x, T::binary(BinaryOp::Mul, a, b));
}
}
}
}
}
for j in 0..nb {
let mut obase = r[0] * ost[d.out_spec[0]];
for k in 0..nsp {
let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
obase += o * ost[d.out_spec[2 + k]];
}
out[obase..obase + features]
.copy_from_slice(&acc[j * features..(j + 1) * features]);
}
j0 += nb;
}
}
Some(out)
}
pub fn conv_terms(
lshape: &[usize],
rshape: &[usize],
w: &ConvWindow<'_>,
d: &ConvDims,
feature_group_count: usize,
batch_group_count: usize,
) -> Vec<[usize; 3]> {
let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
let nsp = lshape.len() - 2;
let (lst, rst) = (strides(lshape), strides(rshape));
let out_features = rshape[d.rhs_spec[0]];
let in_features = rshape[d.rhs_spec[1]];
let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
let out_per_feature_group = (out_features / feature_group_count).max(1);
let out_per_batch_group = (out_features / batch_group_count).max(1);
let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
.into_iter()
.map(|kidx| {
let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
(kidx, off)
})
.collect();
let lfeat = lst[d.lhs_spec[1]];
let rfeat = rst[d.rhs_spec[1]];
let mut terms = Vec::new();
let mut flat = 0;
for_each_index(&out_shape, |o| {
let b = o[d.out_spec[0]];
let f = o[d.out_spec[1]];
let feature_group = f / out_per_feature_group;
let batch_group = f / out_per_batch_group;
let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
+ feature_group * in_features * lfeat;
let rbase = f * rst[d.rhs_spec[0]];
'positions: for (kidx, roff) in &positions {
let mut loff = 0;
for k in 0..nsp {
let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
let n = lshape[d.lhs_spec[2 + k]];
match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
None => continue 'positions,
}
}
let (l0, r0) = (lbase + loff, rbase + roff);
for i in 0..in_features {
terms.push([flat, l0 + i * lfeat, r0 + i * rfeat]);
}
}
flat += 1;
});
terms
}
#[derive(Clone, Copy, Debug)]
pub struct Window<'a> {
pub dimensions: &'a [usize],
pub strides: &'a [usize],
pub padding: &'a [(i64, i64)],
pub base_dilation: &'a [usize],
pub window_dilation: &'a [usize],
}
pub fn reduce_window_shape(shape: &[usize], w: &Window<'_>) -> Vec<usize> {
(0..shape.len())
.map(|i| {
let (lo, hi) = w.padding[i];
let padded = dilate_dim(shape[i], w.base_dilation[i]) as i64 + lo + hi;
let window = dilate_dim(w.dimensions[i], w.window_dilation[i]);
stride_dim(padded, window, w.strides[i])
})
.collect()
}
fn for_each_window(shape: &[usize], w: &Window<'_>, mut f: impl FnMut(&[Option<usize>])) {
let out_shape = reduce_window_shape(shape, w);
let st = strides(shape);
let positions = all_indices(w.dimensions);
let mut covered = vec![None; positions.len()];
for_each_index(&out_shape, |o| {
for (c, widx) in covered.iter_mut().zip(&positions) {
let mut flat = Some(0);
for i in 0..shape.len() {
let p = (o[i] * w.strides[i] + widx[i] * w.window_dilation[i]) as i64;
match undilate(p, w.padding[i].0, w.base_dilation[i], shape[i]) {
Some(q) => flat = flat.map(|f| f + q * st[i]),
None => {
flat = None;
break;
}
}
}
*c = flat;
}
f(&covered);
});
}
pub fn reduce_window<T: Element>(x: &[T], shape: &[usize], w: &Window<'_>, op: ReduceOp) -> Vec<T> {
let bin = op.binary();
let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
for_each_window(shape, w, |covered| {
let mut acc = op.identity::<T>();
for &v in covered.iter().flatten() {
acc = T::binary(bin, acc, x[v]);
}
out.push(acc);
});
out
}
#[inline]
fn selects<T: Element>(ge: bool, a: T, b: T) -> bool {
compare(if ge { CompareOp::Ge } else { CompareOp::Le }, a, b)
}
pub fn select_and_scatter_add<T: Element>(
source: &[T],
operand: &[T],
shape: &[usize],
dimensions: &[usize],
window_strides: &[usize],
padding: &[(i64, i64)],
ge: bool,
) -> Vec<T> {
let ones = vec![1; shape.len()];
let w = Window {
dimensions,
strides: window_strides,
padding,
base_dilation: &ones,
window_dilation: &ones,
};
let identity = if ge { T::lowest() } else { T::highest() };
let mut out = vec![T::default(); size(shape)];
let mut s = 0;
for_each_window(shape, &w, |covered| {
let value = |c: Option<usize>| c.map_or(identity, |i| operand[i]);
let mut selected = covered[0];
let mut selected_value = value(selected);
for &c in &covered[1..] {
let v = value(c);
if !selects(ge, selected_value, v) {
selected = c;
selected_value = v;
}
}
if let Some(i) = selected {
out[i] = T::binary(BinaryOp::Add, out[i], source[s]);
}
s += 1;
});
out
}
pub fn select_and_gather_add<T: Element>(
tangents: &[T],
operand: &[T],
shape: &[usize],
w: &Window<'_>,
ge: bool,
) -> Vec<T> {
let identity = if ge { T::lowest() } else { T::highest() };
let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
for_each_window(shape, w, |covered| {
let (mut k, mut v) = (identity, T::default());
for &i in covered.iter().flatten() {
if !selects(ge, k, operand[i]) {
k = operand[i];
v = tangents[i];
}
}
out.push(v);
});
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn features_last_sums_as_the_general_loop() {
let d = ConvDims {
lhs_spec: vec![0, 3, 1, 2],
rhs_spec: vec![3, 2, 0, 1],
out_spec: vec![0, 3, 1, 2],
};
for (lshape, strides, padding) in [
([2, 5, 6, 3], [1, 2], [(1, 1), (0, 2)]),
([1, 4, 11, 2], [1, 1], [(1, 1), (1, 1)]),
([1, 3, 13, 2], [1, 1], [(0, 0), (2, -1)]),
] {
let rshape = [3, 3, lshape[3], 20];
let w = ConvWindow {
strides: &strides,
padding: &padding,
lhs_dilation: &[1, 1],
rhs_dilation: &[1, 1],
};
let n: usize = lshape.iter().product();
let m: usize = rshape.iter().product();
let lhs: Vec<f32> = (0..n)
.map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
.collect();
let rhs: Vec<f32> = (0..m)
.map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
.collect();
let fast = conv_features_last(&lhs, &lshape, &rhs, &rshape, &w, &d, 1, 1)
.expect("the fast loop applies");
let mut out = vec![0.0f32; fast.len()];
for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 1, 1) {
out[o] += lhs[l] * rhs[r];
}
assert_eq!(
fast.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
"{lshape:?} {strides:?} {padding:?}"
);
}
}
#[test]
fn conv_terms_sum_as_the_kernel() {
let lshape = [2, 4, 7, 6];
let rshape = [3, 3, 2, 4];
let d = ConvDims {
lhs_spec: vec![0, 1, 2, 3],
rhs_spec: vec![3, 2, 0, 1],
out_spec: vec![0, 1, 2, 3],
};
let w = ConvWindow {
strides: &[2, 1],
padding: &[(1, 2), (0, 1)],
lhs_dilation: &[1, 2],
rhs_dilation: &[2, 1],
};
let lhs: Vec<f32> = (0..2 * 4 * 7 * 6)
.map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
.collect();
let rhs: Vec<f32> = (0..3 * 3 * 2 * 4)
.map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
.collect();
let expected = conv_general_dilated(&lhs, &lshape, &rhs, &rshape, &w, &d, 2, 1);
let mut out = vec![0.0f32; expected.len()];
for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 2, 1) {
out[o] += lhs[l] * rhs[r];
}
assert_eq!(
out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
);
}
#[test]
fn convolution_with_padding_strides_and_dilation() {
let x = [1.0f32, 2.0, 3.0, 4.0, 5.0];
let k = [1.0f32, 10.0];
let d = ConvDims::canonical(3);
let w = ConvWindow {
strides: &[2],
padding: &[(1, 0)],
lhs_dilation: &[1],
rhs_dilation: &[1],
};
let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
assert_eq!(y, [10.0, 32.0, 54.0]);
let w = ConvWindow {
strides: &[1],
padding: &[(0, 0)],
lhs_dilation: &[2],
rhs_dilation: &[1],
};
let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
assert_eq!(y, [1.0, 20.0, 2.0, 30.0, 3.0, 40.0, 4.0, 50.0]);
}
#[test]
fn windowed_reductions() {
let x = [1.0f32, 5.0, 2.0, 4.0];
let w = Window {
dimensions: &[2],
strides: &[1],
padding: &[(1, 0)],
base_dilation: &[1],
window_dilation: &[1],
};
assert_eq!(reduce_window_shape(&[4], &w), [4]);
assert_eq!(
reduce_window(&x, &[4], &w, ReduceOp::Sum),
[1.0, 6.0, 7.0, 6.0]
);
assert_eq!(
reduce_window(&x, &[4], &w, ReduceOp::Max),
[1.0, 5.0, 5.0, 4.0]
);
let src = [1.0f32, 10.0, 100.0, 1000.0];
assert_eq!(
select_and_scatter_add(&src, &x, &[4], &[2], &[1], &[(1, 0)], true),
[1.0, 110.0, 0.0, 1000.0]
);
let t = [0.1f32, 0.5, 0.2, 0.4];
assert_eq!(
select_and_gather_add(&t, &x, &[4], &w, true),
[0.1, 0.5, 0.5, 0.4]
);
}
}