Skip to main content

ruxla_core/lax/
conv.rs

1//! Convolutions (`lax.conv_general_dilated`, `lax.conv`) and padding.
2
3use ruxla_ir::{ConvDims, Precision};
4use ruxla_kernels::window::{ConvWindow, dilate_dim};
5
6use crate::backend::Backend;
7use crate::value::{Array, Num};
8
9/// Padding of a convolution or a windowed reduction, as JAX's `padding`
10/// argument: a string or explicit `(low, high)` pairs.
11#[derive(Clone, PartialEq, Eq, Debug)]
12pub enum Padding {
13    /// No padding (`'VALID'`).
14    Valid,
15    /// Padding so that the output has `ceil(in / stride)` elements, split
16    /// evenly with the extra element at the end (`'SAME'`).
17    Same,
18    /// As [`Padding::Same`], with the extra element at the start
19    /// (`'SAME_LOWER'`).
20    SameLower,
21    /// `(low, high)` padding of each dimension; negative padding removes
22    /// elements.
23    Explicit(Vec<(i64, i64)>),
24}
25
26impl From<Vec<(i64, i64)>> for Padding {
27    fn from(pads: Vec<(i64, i64)>) -> Self {
28        Padding::Explicit(pads)
29    }
30}
31
32impl From<&[(i64, i64)]> for Padding {
33    fn from(pads: &[(i64, i64)]) -> Self {
34        Padding::Explicit(pads.to_vec())
35    }
36}
37
38impl<const N: usize> From<[(i64, i64); N]> for Padding {
39    fn from(pads: [(i64, i64); N]) -> Self {
40        Padding::Explicit(pads.to_vec())
41    }
42}
43
44impl Padding {
45    /// Resolves the padding for an input of spatial shape `in_shape`, a
46    /// (dilated) window of shape `window_shape`, and `window_strides`
47    /// (`lax.padtype_to_pads` for strings).
48    ///
49    /// # Panics
50    ///
51    /// Panics if explicit padding has the wrong number of pairs.
52    #[track_caller]
53    pub fn to_pads(
54        &self,
55        in_shape: &[usize],
56        window_shape: &[usize],
57        window_strides: &[usize],
58    ) -> Vec<(i64, i64)> {
59        match self {
60            Padding::Valid => vec![(0, 0); in_shape.len()],
61            Padding::Same | Padding::SameLower => in_shape
62                .iter()
63                .zip(window_shape)
64                .zip(window_strides)
65                .map(|((&n, &w), &s)| {
66                    let out = n.div_ceil(s) as i64;
67                    let pad = ((out - 1) * s as i64 + w as i64 - n as i64).max(0);
68                    if *self == Padding::Same {
69                        (pad / 2, pad - pad / 2)
70                    } else {
71                        (pad - pad / 2, pad / 2)
72                    }
73                })
74                .collect(),
75            Padding::Explicit(pads) => {
76                assert_eq!(
77                    pads.len(),
78                    in_shape.len(),
79                    "padding needs one (low, high) pair per dimension"
80                );
81                pads.clone()
82            }
83        }
84    }
85}
86
87/// Converts string dimension numbers such as `("NHWC", "HWIO", "NHWC")` to
88/// [`ConvDims`] (`lax.conv_dimension_numbers`): `N` and `C` are the batch
89/// and feature dimensions of the input and the output, `O` and `I` the
90/// output and input feature dimensions of the kernel, and other characters
91/// name spatial dimensions, which are ordered as in the kernel's spec.
92///
93/// # Examples
94///
95/// ```
96/// use ruxla_core::lax;
97///
98/// let d = lax::conv_dimension_numbers("NHWC", "HWIO", "NHWC");
99/// assert_eq!(d.lhs_spec, [0, 3, 1, 2]);
100/// assert_eq!(d.rhs_spec, [3, 2, 0, 1]);
101/// ```
102///
103/// # Panics
104///
105/// Panics if the specs are malformed (as JAX raises).
106#[track_caller]
107pub fn conv_dimension_numbers(lhs: &str, rhs: &str, out: &str) -> ConvDims {
108    let specs = [lhs, rhs, out];
109    let pairs = [('N', 'C'), ('O', 'I'), ('N', 'C')];
110    for (spec, (a, b)) in specs.iter().zip(pairs) {
111        let count = |c| spec.chars().filter(|&x| x == c).count();
112        assert!(
113            count(a) == 1 && count(b) == 1,
114            "convolution dimension numbers {spec:?} must contain {a:?} and {b:?} exactly once"
115        );
116        let mut chars: Vec<char> = spec.chars().collect();
117        chars.sort_unstable();
118        chars.dedup();
119        assert_eq!(
120            chars.len(),
121            spec.chars().count(),
122            "convolution dimension numbers {spec:?} cannot have duplicate characters"
123        );
124        assert_eq!(
125            spec.len(),
126            lhs.len(),
127            "convolution dimension numbers must have the same length"
128        );
129    }
130    let spatial = |spec: &str, (a, b): (char, char)| -> Vec<char> {
131        spec.chars().filter(|&c| c != a && c != b).collect()
132    };
133    let rhs_spatial = spatial(rhs, pairs[1]);
134    let mut lhs_spatial = spatial(lhs, pairs[0]);
135    let mut out_spatial = spatial(out, pairs[2]);
136    lhs_spatial.sort_unstable();
137    out_spatial.sort_unstable();
138    let mut sorted_rhs = rhs_spatial.clone();
139    sorted_rhs.sort_unstable();
140    assert!(
141        lhs_spatial == sorted_rhs && out_spatial == sorted_rhs,
142        "convolution dimension numbers must have the same spatial characters"
143    );
144    let perm = |spec: &str, (a, b): (char, char)| -> Vec<usize> {
145        let index = |c: char| spec.chars().position(|x| x == c).expect("checked");
146        let mut p = vec![index(a), index(b)];
147        p.extend(rhs_spatial.iter().map(|&c| index(c)));
148        p
149    };
150    ConvDims {
151        lhs_spec: perm(lhs, pairs[0]),
152        rhs_spec: perm(rhs, pairs[1]),
153        out_spec: perm(out, pairs[2]),
154    }
155}
156
157/// The optional arguments of [`conv_general_dilated`], with JAX's
158/// defaults: no dilation, the canonical dimension numbers (`NCHW`, `OIHW`,
159/// `NCHW` for two spatial dimensions), one group, and the default
160/// precision.
161#[derive(Clone, Debug, PartialEq)]
162pub struct ConvOptions {
163    /// The dilation of each spatial dimension of the input (`None`: 1).
164    pub lhs_dilation: Option<Vec<usize>>,
165    /// The dilation of each spatial dimension of the kernel (`None`: 1).
166    pub rhs_dilation: Option<Vec<usize>>,
167    /// The layout of the operands and the result (`None`: canonical).
168    pub dimension_numbers: Option<ConvDims>,
169    /// The number of groups of features.
170    pub feature_group_count: usize,
171    /// The number of groups of the batch.
172    pub batch_group_count: usize,
173    /// The precision on accelerators.
174    pub precision: Precision,
175}
176
177impl Default for ConvOptions {
178    fn default() -> Self {
179        Self {
180            lhs_dilation: None,
181            rhs_dilation: None,
182            dimension_numbers: None,
183            feature_group_count: 1,
184            batch_group_count: 1,
185            precision: Precision::Default,
186        }
187    }
188}
189
190/// `lax.conv_general_dilated` computing in `U`: the general convolution
191/// (see [`conv_general_dilated`]).
192///
193/// # Panics
194///
195/// Panics if the shapes or the options do not fit together, or if string
196/// padding is used with input dilation (as JAX raises).
197#[track_caller]
198pub fn conv_general_dilated_with<B: Backend, T: Num, U: Num>(
199    lhs: &Array<B, T>,
200    rhs: &Array<B, T>,
201    window_strides: &[usize],
202    padding: impl Into<Padding>,
203    options: &ConvOptions,
204) -> Array<B, U> {
205    let (lshape, rshape) = (lhs.shape(), rhs.shape());
206    let rank = lshape.rank();
207    assert_eq!(
208        rank,
209        rshape.rank(),
210        "convolution requires lhs and rhs of the same rank"
211    );
212    assert!(rank >= 2, "convolution requires operands of rank 2 or more");
213    let n = rank - 2;
214    let dims = options
215        .dimension_numbers
216        .clone()
217        .unwrap_or_else(|| ConvDims::canonical(rank));
218    let ones = vec![1; n];
219    let lhs_dilation = options.lhs_dilation.clone().unwrap_or_else(|| ones.clone());
220    let rhs_dilation = options.rhs_dilation.clone().unwrap_or_else(|| ones.clone());
221    let padding = padding.into();
222    let pads = match &padding {
223        Padding::Explicit(pads) => pads.clone(),
224        _ => {
225            assert!(
226                lhs_dilation.iter().all(|&d| d == 1),
227                "string padding is not implemented for transposed convolution; \
228                 give the padding explicitly"
229            );
230            let in_shape: Vec<usize> = dims.lhs_spec[2..].iter().map(|&d| lshape[d]).collect();
231            let window: Vec<usize> = dims.rhs_spec[2..]
232                .iter()
233                .zip(&rhs_dilation)
234                .map(|(&d, &r)| dilate_dim(rshape[d], r))
235                .collect();
236            padding.to_pads(&in_shape, &window, window_strides)
237        }
238    };
239    let window = ConvWindow {
240        strides: window_strides,
241        padding: &pads,
242        lhs_dilation: &lhs_dilation,
243        rhs_dilation: &rhs_dilation,
244    };
245    Array(B::conv_general_dilated::<T, U>(
246        &lhs.0,
247        &rhs.0,
248        &window,
249        &dims,
250        (options.feature_group_count, options.batch_group_count),
251        options.precision,
252    ))
253}
254
255/// `lax.conv_general_dilated`: a convolution with strides, padding, input
256/// and kernel dilation, any layout, and feature or batch groups, with the
257/// result in the operands' type.
258///
259/// # Examples
260///
261/// ```
262/// use ruxla_core::{Array, Native, lax};
263///
264/// // NWC input and WIO kernel, as Flax lays them out.
265/// let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [1, 4, 1]);
266/// let k = Array::<Native, f32>::from_vec(vec![1.0, 10.0], [2, 1, 1]);
267/// let options = lax::ConvOptions {
268///     dimension_numbers: Some(lax::conv_dimension_numbers("NWC", "WIO", "NWC")),
269///     ..Default::default()
270/// };
271/// let y = lax::conv_general_dilated(&x, &k, &[1], lax::Padding::Same, &options);
272/// assert_eq!(y.to_vec(), [21.0, 32.0, 43.0, 4.0]);
273/// ```
274///
275/// # Panics
276///
277/// See [`conv_general_dilated_with`].
278#[track_caller]
279pub fn conv_general_dilated<B: Backend, T: Num>(
280    lhs: &Array<B, T>,
281    rhs: &Array<B, T>,
282    window_strides: &[usize],
283    padding: impl Into<Padding>,
284    options: &ConvOptions,
285) -> Array<B, T> {
286    conv_general_dilated_with::<B, T, T>(lhs, rhs, window_strides, padding, options)
287}
288
289/// `lax.conv`: a convolution of an `NCHW`-style input with an `OIHW`-style
290/// kernel.
291///
292/// # Panics
293///
294/// See [`conv_general_dilated_with`].
295#[track_caller]
296pub fn conv<B: Backend, T: Num>(
297    lhs: &Array<B, T>,
298    rhs: &Array<B, T>,
299    window_strides: &[usize],
300    padding: impl Into<Padding>,
301) -> Array<B, T> {
302    conv_general_dilated(lhs, rhs, window_strides, padding, &ConvOptions::default())
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn padding_like_jax() {
311        assert_eq!(
312            Padding::Same.to_pads(&[5, 6], &[3, 2], &[2, 1]),
313            [(1, 1), (0, 1)]
314        );
315        assert_eq!(Padding::SameLower.to_pads(&[6], &[2], &[1]), [(1, 0)]);
316        assert_eq!(Padding::Valid.to_pads(&[6], &[2], &[1]), [(0, 0)]);
317    }
318
319    #[test]
320    fn dimension_numbers_like_jax() {
321        let d = conv_dimension_numbers("NCHW", "OIHW", "NCHW");
322        assert_eq!(d, ConvDims::canonical(4));
323        let d = conv_dimension_numbers("NHWC", "HWIO", "NHWC");
324        assert_eq!(d.out_spec, [0, 3, 1, 2]);
325        let d = conv_dimension_numbers("NWHC", "HWIO", "NCWH");
326        assert_eq!(d.lhs_spec, [0, 3, 2, 1]);
327        assert_eq!(d.out_spec, [0, 1, 3, 2]);
328    }
329}