use ruxla_ir::{ConvDims, Precision};
use ruxla_kernels::window::{ConvWindow, dilate_dim};
use crate::backend::Backend;
use crate::value::{Array, Num};
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Padding {
Valid,
Same,
SameLower,
Explicit(Vec<(i64, i64)>),
}
impl From<Vec<(i64, i64)>> for Padding {
fn from(pads: Vec<(i64, i64)>) -> Self {
Padding::Explicit(pads)
}
}
impl From<&[(i64, i64)]> for Padding {
fn from(pads: &[(i64, i64)]) -> Self {
Padding::Explicit(pads.to_vec())
}
}
impl<const N: usize> From<[(i64, i64); N]> for Padding {
fn from(pads: [(i64, i64); N]) -> Self {
Padding::Explicit(pads.to_vec())
}
}
impl Padding {
#[track_caller]
pub fn to_pads(
&self,
in_shape: &[usize],
window_shape: &[usize],
window_strides: &[usize],
) -> Vec<(i64, i64)> {
match self {
Padding::Valid => vec![(0, 0); in_shape.len()],
Padding::Same | Padding::SameLower => in_shape
.iter()
.zip(window_shape)
.zip(window_strides)
.map(|((&n, &w), &s)| {
let out = n.div_ceil(s) as i64;
let pad = ((out - 1) * s as i64 + w as i64 - n as i64).max(0);
if *self == Padding::Same {
(pad / 2, pad - pad / 2)
} else {
(pad - pad / 2, pad / 2)
}
})
.collect(),
Padding::Explicit(pads) => {
assert_eq!(
pads.len(),
in_shape.len(),
"padding needs one (low, high) pair per dimension"
);
pads.clone()
}
}
}
}
#[track_caller]
pub fn conv_dimension_numbers(lhs: &str, rhs: &str, out: &str) -> ConvDims {
let specs = [lhs, rhs, out];
let pairs = [('N', 'C'), ('O', 'I'), ('N', 'C')];
for (spec, (a, b)) in specs.iter().zip(pairs) {
let count = |c| spec.chars().filter(|&x| x == c).count();
assert!(
count(a) == 1 && count(b) == 1,
"convolution dimension numbers {spec:?} must contain {a:?} and {b:?} exactly once"
);
let mut chars: Vec<char> = spec.chars().collect();
chars.sort_unstable();
chars.dedup();
assert_eq!(
chars.len(),
spec.chars().count(),
"convolution dimension numbers {spec:?} cannot have duplicate characters"
);
assert_eq!(
spec.len(),
lhs.len(),
"convolution dimension numbers must have the same length"
);
}
let spatial = |spec: &str, (a, b): (char, char)| -> Vec<char> {
spec.chars().filter(|&c| c != a && c != b).collect()
};
let rhs_spatial = spatial(rhs, pairs[1]);
let mut lhs_spatial = spatial(lhs, pairs[0]);
let mut out_spatial = spatial(out, pairs[2]);
lhs_spatial.sort_unstable();
out_spatial.sort_unstable();
let mut sorted_rhs = rhs_spatial.clone();
sorted_rhs.sort_unstable();
assert!(
lhs_spatial == sorted_rhs && out_spatial == sorted_rhs,
"convolution dimension numbers must have the same spatial characters"
);
let perm = |spec: &str, (a, b): (char, char)| -> Vec<usize> {
let index = |c: char| spec.chars().position(|x| x == c).expect("checked");
let mut p = vec![index(a), index(b)];
p.extend(rhs_spatial.iter().map(|&c| index(c)));
p
};
ConvDims {
lhs_spec: perm(lhs, pairs[0]),
rhs_spec: perm(rhs, pairs[1]),
out_spec: perm(out, pairs[2]),
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ConvOptions {
pub lhs_dilation: Option<Vec<usize>>,
pub rhs_dilation: Option<Vec<usize>>,
pub dimension_numbers: Option<ConvDims>,
pub feature_group_count: usize,
pub batch_group_count: usize,
pub precision: Precision,
}
impl Default for ConvOptions {
fn default() -> Self {
Self {
lhs_dilation: None,
rhs_dilation: None,
dimension_numbers: None,
feature_group_count: 1,
batch_group_count: 1,
precision: Precision::Default,
}
}
}
#[track_caller]
pub fn conv_general_dilated_with<B: Backend, T: Num, U: Num>(
lhs: &Array<B, T>,
rhs: &Array<B, T>,
window_strides: &[usize],
padding: impl Into<Padding>,
options: &ConvOptions,
) -> Array<B, U> {
let (lshape, rshape) = (lhs.shape(), rhs.shape());
let rank = lshape.rank();
assert_eq!(
rank,
rshape.rank(),
"convolution requires lhs and rhs of the same rank"
);
assert!(rank >= 2, "convolution requires operands of rank 2 or more");
let n = rank - 2;
let dims = options
.dimension_numbers
.clone()
.unwrap_or_else(|| ConvDims::canonical(rank));
let ones = vec![1; n];
let lhs_dilation = options.lhs_dilation.clone().unwrap_or_else(|| ones.clone());
let rhs_dilation = options.rhs_dilation.clone().unwrap_or_else(|| ones.clone());
let padding = padding.into();
let pads = match &padding {
Padding::Explicit(pads) => pads.clone(),
_ => {
assert!(
lhs_dilation.iter().all(|&d| d == 1),
"string padding is not implemented for transposed convolution; \
give the padding explicitly"
);
let in_shape: Vec<usize> = dims.lhs_spec[2..].iter().map(|&d| lshape[d]).collect();
let window: Vec<usize> = dims.rhs_spec[2..]
.iter()
.zip(&rhs_dilation)
.map(|(&d, &r)| dilate_dim(rshape[d], r))
.collect();
padding.to_pads(&in_shape, &window, window_strides)
}
};
let window = ConvWindow {
strides: window_strides,
padding: &pads,
lhs_dilation: &lhs_dilation,
rhs_dilation: &rhs_dilation,
};
Array(B::conv_general_dilated::<T, U>(
&lhs.0,
&rhs.0,
&window,
&dims,
(options.feature_group_count, options.batch_group_count),
options.precision,
))
}
#[track_caller]
pub fn conv_general_dilated<B: Backend, T: Num>(
lhs: &Array<B, T>,
rhs: &Array<B, T>,
window_strides: &[usize],
padding: impl Into<Padding>,
options: &ConvOptions,
) -> Array<B, T> {
conv_general_dilated_with::<B, T, T>(lhs, rhs, window_strides, padding, options)
}
#[track_caller]
pub fn conv<B: Backend, T: Num>(
lhs: &Array<B, T>,
rhs: &Array<B, T>,
window_strides: &[usize],
padding: impl Into<Padding>,
) -> Array<B, T> {
conv_general_dilated(lhs, rhs, window_strides, padding, &ConvOptions::default())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn padding_like_jax() {
assert_eq!(
Padding::Same.to_pads(&[5, 6], &[3, 2], &[2, 1]),
[(1, 1), (0, 1)]
);
assert_eq!(Padding::SameLower.to_pads(&[6], &[2], &[1]), [(1, 0)]);
assert_eq!(Padding::Valid.to_pads(&[6], &[2], &[1]), [(0, 0)]);
}
#[test]
fn dimension_numbers_like_jax() {
let d = conv_dimension_numbers("NCHW", "OIHW", "NCHW");
assert_eq!(d, ConvDims::canonical(4));
let d = conv_dimension_numbers("NHWC", "HWIO", "NHWC");
assert_eq!(d.out_spec, [0, 3, 1, 2]);
let d = conv_dimension_numbers("NWHC", "HWIO", "NCWH");
assert_eq!(d.lhs_spec, [0, 3, 2, 1]);
assert_eq!(d.out_spec, [0, 1, 3, 2]);
}
}