ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! Convolutions (`lax.conv_general_dilated`, `lax.conv`) and padding.

use ruxla_ir::{ConvDims, Precision};
use ruxla_kernels::window::{ConvWindow, dilate_dim};

use crate::backend::Backend;
use crate::value::{Array, Num};

/// Padding of a convolution or a windowed reduction, as JAX's `padding`
/// argument: a string or explicit `(low, high)` pairs.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Padding {
    /// No padding (`'VALID'`).
    Valid,
    /// Padding so that the output has `ceil(in / stride)` elements, split
    /// evenly with the extra element at the end (`'SAME'`).
    Same,
    /// As [`Padding::Same`], with the extra element at the start
    /// (`'SAME_LOWER'`).
    SameLower,
    /// `(low, high)` padding of each dimension; negative padding removes
    /// elements.
    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 {
    /// Resolves the padding for an input of spatial shape `in_shape`, a
    /// (dilated) window of shape `window_shape`, and `window_strides`
    /// (`lax.padtype_to_pads` for strings).
    ///
    /// # Panics
    ///
    /// Panics if explicit padding has the wrong number of pairs.
    #[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()
            }
        }
    }
}

/// Converts string dimension numbers such as `("NHWC", "HWIO", "NHWC")` to
/// [`ConvDims`] (`lax.conv_dimension_numbers`): `N` and `C` are the batch
/// and feature dimensions of the input and the output, `O` and `I` the
/// output and input feature dimensions of the kernel, and other characters
/// name spatial dimensions, which are ordered as in the kernel's spec.
///
/// # Examples
///
/// ```
/// use ruxla_core::lax;
///
/// let d = lax::conv_dimension_numbers("NHWC", "HWIO", "NHWC");
/// assert_eq!(d.lhs_spec, [0, 3, 1, 2]);
/// assert_eq!(d.rhs_spec, [3, 2, 0, 1]);
/// ```
///
/// # Panics
///
/// Panics if the specs are malformed (as JAX raises).
#[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]),
    }
}

/// The optional arguments of [`conv_general_dilated`], with JAX's
/// defaults: no dilation, the canonical dimension numbers (`NCHW`, `OIHW`,
/// `NCHW` for two spatial dimensions), one group, and the default
/// precision.
#[derive(Clone, Debug, PartialEq)]
pub struct ConvOptions {
    /// The dilation of each spatial dimension of the input (`None`: 1).
    pub lhs_dilation: Option<Vec<usize>>,
    /// The dilation of each spatial dimension of the kernel (`None`: 1).
    pub rhs_dilation: Option<Vec<usize>>,
    /// The layout of the operands and the result (`None`: canonical).
    pub dimension_numbers: Option<ConvDims>,
    /// The number of groups of features.
    pub feature_group_count: usize,
    /// The number of groups of the batch.
    pub batch_group_count: usize,
    /// The precision on accelerators.
    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,
        }
    }
}

/// `lax.conv_general_dilated` computing in `U`: the general convolution
/// (see [`conv_general_dilated`]).
///
/// # Panics
///
/// Panics if the shapes or the options do not fit together, or if string
/// padding is used with input dilation (as JAX raises).
#[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,
    ))
}

/// `lax.conv_general_dilated`: a convolution with strides, padding, input
/// and kernel dilation, any layout, and feature or batch groups, with the
/// result in the operands' type.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// // NWC input and WIO kernel, as Flax lays them out.
/// let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [1, 4, 1]);
/// let k = Array::<Native, f32>::from_vec(vec![1.0, 10.0], [2, 1, 1]);
/// let options = lax::ConvOptions {
///     dimension_numbers: Some(lax::conv_dimension_numbers("NWC", "WIO", "NWC")),
///     ..Default::default()
/// };
/// let y = lax::conv_general_dilated(&x, &k, &[1], lax::Padding::Same, &options);
/// assert_eq!(y.to_vec(), [21.0, 32.0, 43.0, 4.0]);
/// ```
///
/// # Panics
///
/// See [`conv_general_dilated_with`].
#[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)
}

/// `lax.conv`: a convolution of an `NCHW`-style input with an `OIHW`-style
/// kernel.
///
/// # Panics
///
/// See [`conv_general_dilated_with`].
#[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]);
    }
}