1use ruxla_ir::{ConvDims, Precision};
4use ruxla_kernels::window::{ConvWindow, dilate_dim};
5
6use crate::backend::Backend;
7use crate::value::{Array, Num};
8
9#[derive(Clone, PartialEq, Eq, Debug)]
12pub enum Padding {
13 Valid,
15 Same,
18 SameLower,
21 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 #[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#[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#[derive(Clone, Debug, PartialEq)]
162pub struct ConvOptions {
163 pub lhs_dilation: Option<Vec<usize>>,
165 pub rhs_dilation: Option<Vec<usize>>,
167 pub dimension_numbers: Option<ConvDims>,
169 pub feature_group_count: usize,
171 pub batch_group_count: usize,
173 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#[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#[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#[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}