Skip to main content

ruxla_kernels/
window.rs

1//! Convolutions and windowed reductions on row-major buffers, with XLA's
2//! semantics.
3//!
4//! As in [`crate::array`], shapes are assumed to have been checked (by shape
5//! inference); the functions panic on inconsistent inputs.
6
7use crate::array::{ReduceOp, size, strides};
8use crate::dtype::{DType, Element, cast};
9use crate::ops::{BinaryOp, CompareOp, compare};
10
11/// The dimension numbers of a convolution, as JAX's `ConvDimensionNumbers`:
12/// each spec lists dimensions of an operand or of the result.
13///
14/// `lhs_spec` is `(batch, feature, spatial...)` of the input, `rhs_spec`
15/// is `(output feature, input feature, spatial...)` of the kernel, and
16/// `out_spec` is `(batch, feature, spatial...)` of the result. Spatial
17/// dimension `k` of the three correspond, and the window parameters of a
18/// convolution are given in this order.
19#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
20pub struct ConvDims {
21    /// The input's batch, feature, and spatial dimensions.
22    pub lhs_spec: Vec<usize>,
23    /// The kernel's output feature, input feature, and spatial dimensions.
24    pub rhs_spec: Vec<usize>,
25    /// The result's batch, feature, and spatial dimensions.
26    pub out_spec: Vec<usize>,
27}
28
29impl ConvDims {
30    /// The dimension numbers of operands in the canonical order
31    /// `(batch, feature, spatial...)` (JAX's default for `None`).
32    pub fn canonical(rank: usize) -> Self {
33        let iota: Vec<usize> = (0..rank).collect();
34        Self {
35            lhs_spec: iota.clone(),
36            rhs_spec: iota.clone(),
37            out_spec: iota,
38        }
39    }
40}
41
42/// The window of a convolution: one entry per spatial dimension.
43#[derive(Clone, Copy, Debug)]
44pub struct ConvWindow<'a> {
45    /// The step between windows.
46    pub strides: &'a [usize],
47    /// `(low, high)` padding of the (dilated) input; negative padding
48    /// removes elements.
49    pub padding: &'a [(i64, i64)],
50    /// The dilation of the input (`d - 1` holes between elements).
51    pub lhs_dilation: &'a [usize],
52    /// The dilation of the kernel.
53    pub rhs_dilation: &'a [usize],
54}
55
56/// The size of a dimension of size `d` after dilation:
57/// `1 + dilation * (d - 1)`, or 0 for an empty dimension.
58pub fn dilate_dim(d: usize, dilation: usize) -> usize {
59    if d == 0 { 0 } else { 1 + dilation * (d - 1) }
60}
61
62/// The number of windows of size `window` with step `stride` in a
63/// dimension of size `d`: `max(0, (d - window) / stride + 1)`.
64pub fn stride_dim(d: i64, window: usize, stride: usize) -> usize {
65    let window = window as i64;
66    if d < window {
67        0
68    } else {
69        ((d - window) / stride as i64 + 1) as usize
70    }
71}
72
73/// The shape of the result of a convolution.
74pub fn conv_shape(
75    lhs: &[usize],
76    rhs: &[usize],
77    w: &ConvWindow<'_>,
78    d: &ConvDims,
79    batch_group_count: usize,
80) -> Vec<usize> {
81    let mut out = vec![0; lhs.len()];
82    out[d.out_spec[0]] = lhs[d.lhs_spec[0]] / batch_group_count.max(1);
83    out[d.out_spec[1]] = rhs[d.rhs_spec[0]];
84    for k in 0..lhs.len().saturating_sub(2) {
85        let (lo, hi) = w.padding[k];
86        let padded = dilate_dim(lhs[d.lhs_spec[2 + k]], w.lhs_dilation[k]) as i64 + lo + hi;
87        let window = dilate_dim(rhs[d.rhs_spec[2 + k]], w.rhs_dilation[k]);
88        out[d.out_spec[2 + k]] = stride_dim(padded, window, w.strides[k]);
89    }
90    out
91}
92
93/// Calls `f` with the multi-index of each element of `shape`, in row-major
94/// order.
95fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
96    let n = size(shape);
97    let mut index = vec![0; shape.len()];
98    for _ in 0..n {
99        f(&index);
100        for d in (0..shape.len()).rev() {
101            index[d] += 1;
102            if index[d] < shape[d] {
103                break;
104            }
105            index[d] = 0;
106        }
107    }
108}
109
110/// The multi-indices of `shape` in row-major order.
111fn all_indices(shape: &[usize]) -> Vec<Vec<usize>> {
112    let mut out = Vec::with_capacity(size(shape));
113    for_each_index(shape, |i| out.push(i.to_vec()));
114    out
115}
116
117/// The position in an operand dimension of size `n` of the element that a
118/// window position covers, given the position `p` in the padded and dilated
119/// dimension: `None` for padding and for holes of the dilation.
120#[inline]
121fn undilate(p: i64, lo: i64, dilation: usize, n: usize) -> Option<usize> {
122    let p = p - lo;
123    let dilation = dilation as i64;
124    if p < 0 || p % dilation != 0 || p / dilation >= n as i64 {
125        None
126    } else {
127        Some((p / dilation) as usize)
128    }
129}
130
131/// `conv_general_dilated`: XLA's convolution, with feature groups (the
132/// input features and the output features are split into
133/// `feature_group_count` groups, and output group `g` sees input group `g`)
134/// and batch groups (the input batch is split into `batch_group_count`
135/// groups, the major part of the batch dimension, and output feature group
136/// `g` sees batch group `g`).
137///
138/// Each result is accumulated in the result type, over the kernel's spatial
139/// positions in row-major order and, for each, over the input features, as
140/// XLA's CPU backend does for `f64` (with fused multiply-adds, which gives
141/// the same bits) and for 16-bit floats (in `f32`, rounded once). XLA sums
142/// `f32` convolutions in another order (with Eigen).
143/// Padding and the holes of the input dilation contribute nothing (not
144/// `0 * w`, which differs for an infinite or NaN `w`).
145#[allow(clippy::too_many_arguments)]
146pub fn conv_general_dilated<T: Element>(
147    lhs: &[T],
148    lshape: &[usize],
149    rhs: &[T],
150    rshape: &[usize],
151    w: &ConvWindow<'_>,
152    d: &ConvDims,
153    feature_group_count: usize,
154    batch_group_count: usize,
155) -> Vec<T> {
156    if matches!(T::DTYPE, DType::F16 | DType::BF16) {
157        let wide = |x: &[T]| x.iter().map(|&v| cast::<T, f32>(v)).collect::<Vec<f32>>();
158        return conv_general_dilated(
159            &wide(lhs),
160            lshape,
161            &wide(rhs),
162            rshape,
163            w,
164            d,
165            feature_group_count,
166            batch_group_count,
167        )
168        .into_iter()
169        .map(cast::<f32, T>)
170        .collect();
171    }
172    if let Some(out) = conv_features_last(
173        lhs,
174        lshape,
175        rhs,
176        rshape,
177        w,
178        d,
179        feature_group_count,
180        batch_group_count,
181    ) {
182        return out;
183    }
184    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
185    let nsp = lshape.len() - 2;
186    let (lst, rst) = (strides(lshape), strides(rshape));
187    let out_features = rshape[d.rhs_spec[0]];
188    let in_features = rshape[d.rhs_spec[1]];
189    let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
190    let out_per_feature_group = (out_features / feature_group_count).max(1);
191    let out_per_batch_group = (out_features / batch_group_count).max(1);
192    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
193    // The kernel's spatial positions, with their offsets in the kernel.
194    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
195        .into_iter()
196        .map(|kidx| {
197            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
198            (kidx, off)
199        })
200        .collect();
201    let lfeat = lst[d.lhs_spec[1]];
202    let rfeat = rst[d.rhs_spec[1]];
203    // XLA's CPU backend fuses the products and sums of `f64` convolutions.
204    let fused = T::DTYPE == DType::F64;
205    let mut out = Vec::with_capacity(size(&out_shape));
206    for_each_index(&out_shape, |o| {
207        let b = o[d.out_spec[0]];
208        let f = o[d.out_spec[1]];
209        let feature_group = f / out_per_feature_group;
210        let batch_group = f / out_per_batch_group;
211        let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
212            + feature_group * in_features * lfeat;
213        let rbase = f * rst[d.rhs_spec[0]];
214        let mut acc = T::default();
215        'positions: for (kidx, roff) in &positions {
216            let mut loff = 0;
217            for k in 0..nsp {
218                let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
219                let n = lshape[d.lhs_spec[2 + k]];
220                match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
221                    Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
222                    None => continue 'positions,
223                }
224            }
225            let (l0, r0) = (lbase + loff, rbase + roff);
226            if fused {
227                for i in 0..in_features {
228                    let (a, b): (f64, f64) = (cast(lhs[l0 + i * lfeat]), cast(rhs[r0 + i * rfeat]));
229                    acc = cast(a.mul_add(b, cast(acc)));
230                }
231            } else {
232                for i in 0..in_features {
233                    let p = T::binary(BinaryOp::Mul, lhs[l0 + i * lfeat], rhs[r0 + i * rfeat]);
234                    acc = T::binary(BinaryOp::Add, acc, p);
235                }
236            }
237        }
238        out.push(acc);
239    });
240    out
241}
242
243/// [`conv_general_dilated`] for the layouts of Flax's convolutions (the
244/// features innermost in the input, the kernel's output features innermost,
245/// and the output's features innermost: `NHWC`, `HWIO`, `NHWC`), without
246/// dilation or groups, and for the types it does not fuse or widen: for
247/// each output position, the kernel positions and input features are
248/// visited in the same order and each product is added to a row of all the
249/// output features, so that the innermost loop reads the kernel's
250/// contiguous rows. Every output element is the same sum, in the same
251/// order, as in the general loop. `None` for other cases.
252#[allow(clippy::too_many_arguments)]
253fn conv_features_last<T: Element>(
254    lhs: &[T],
255    lshape: &[usize],
256    rhs: &[T],
257    rshape: &[usize],
258    w: &ConvWindow<'_>,
259    d: &ConvDims,
260    feature_group_count: usize,
261    batch_group_count: usize,
262) -> Option<Vec<T>> {
263    let rank = lshape.len();
264    let nsp = rank.checked_sub(2)?;
265    if nsp == 0
266        || matches!(T::DTYPE, DType::F64 | DType::F16 | DType::BF16)
267        || feature_group_count != 1
268        || batch_group_count != 1
269        || w.lhs_dilation.iter().any(|&x| x != 1)
270        || w.rhs_dilation.iter().any(|&x| x != 1)
271        || d.lhs_spec[1] != rank - 1
272        || d.rhs_spec[0] != rank - 1
273        || d.out_spec[1] != rank - 1
274    {
275        return None;
276    }
277    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
278    let (lst, rst) = (strides(lshape), strides(rshape));
279    let ost = strides(&out_shape);
280    let features = rshape[d.rhs_spec[0]];
281    let in_features = rshape[d.rhs_spec[1]];
282    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
283    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
284        .into_iter()
285        .map(|kidx| {
286            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
287            (kidx, off)
288        })
289        .collect();
290    let rfeat = rst[d.rhs_spec[1]];
291    let mut out = vec![T::default(); size(&out_shape)];
292    // The output positions (batch and spatial), features excluded, in rows
293    // along the last spatial dimension, computed `BLOCK` at a time so that
294    // each row of the kernel is read once for all of them (positions where
295    // the window leaves the input contribute nothing to that output only).
296    const BLOCK: usize = 4;
297    let last = out_shape[d.out_spec[1 + nsp]];
298    let mut row_shape = vec![out_shape[d.out_spec[0]]];
299    row_shape.extend((0..nsp - 1).map(|k| out_shape[d.out_spec[2 + k]]));
300    let mut acc = vec![T::default(); BLOCK * features];
301    for r in all_indices(&row_shape) {
302        let lbase = r[0] * lst[d.lhs_spec[0]];
303        let mut j0 = 0;
304        while j0 < last {
305            let nb = BLOCK.min(last - j0);
306            acc.fill(T::default());
307            for (kidx, roff) in &positions {
308                // The input offset of each output of the block, if inside.
309                let mut offs = [None; BLOCK];
310                let mut inside = true;
311                for (j, off) in offs.iter_mut().enumerate().take(nb) {
312                    let mut loff = 0;
313                    let mut ok = true;
314                    for k in 0..nsp {
315                        let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
316                        let p = (o * w.strides[k] + kidx[k]) as i64 - w.padding[k].0;
317                        if p < 0 || p >= lshape[d.lhs_spec[2 + k]] as i64 {
318                            ok = false;
319                            break;
320                        }
321                        loff += p as usize * lst[d.lhs_spec[2 + k]];
322                    }
323                    *off = ok.then_some(lbase + loff);
324                    inside &= ok;
325                }
326                if inside && nb == BLOCK {
327                    let o: [usize; BLOCK] = std::array::from_fn(|j| offs[j].unwrap_or(0));
328                    // Chunks of `CH` features held in locals over the input
329                    // features (registers), the rest as rows.
330                    const CH: usize = 16;
331                    let full = features - features % CH;
332                    for fc in (0..full).step_by(CH) {
333                        let mut y: [[T; CH]; BLOCK] = std::array::from_fn(|j| {
334                            std::array::from_fn(|c| acc[j * features + fc + c])
335                        });
336                        for i in 0..in_features {
337                            let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
338                            let base = roff + i * rfeat + fc;
339                            let row: &[T; CH] = rhs[base..base + CH].try_into().expect("a chunk");
340                            for c in 0..CH {
341                                let wv = row[c];
342                                for j in 0..BLOCK {
343                                    y[j][c] = T::binary(
344                                        BinaryOp::Add,
345                                        y[j][c],
346                                        T::binary(BinaryOp::Mul, x[j], wv),
347                                    );
348                                }
349                            }
350                        }
351                        for (j, yj) in y.iter().enumerate() {
352                            acc[j * features + fc..j * features + fc + CH].copy_from_slice(yj);
353                        }
354                    }
355                    if full < features {
356                        let (a0, rest) = acc.split_at_mut(features);
357                        let (a1, rest) = rest.split_at_mut(features);
358                        let (a2, a3) = rest.split_at_mut(features);
359                        for i in 0..in_features {
360                            let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
361                            let row = &rhs[roff + i * rfeat + full..roff + i * rfeat + features];
362                            let lanes = a0[full..]
363                                .iter_mut()
364                                .zip(a1[full..].iter_mut())
365                                .zip(a2[full..].iter_mut())
366                                .zip(a3[full..].iter_mut())
367                                .zip(row);
368                            for ((((y0, y1), y2), y3), &wv) in lanes {
369                                *y0 = T::binary(
370                                    BinaryOp::Add,
371                                    *y0,
372                                    T::binary(BinaryOp::Mul, x[0], wv),
373                                );
374                                *y1 = T::binary(
375                                    BinaryOp::Add,
376                                    *y1,
377                                    T::binary(BinaryOp::Mul, x[1], wv),
378                                );
379                                *y2 = T::binary(
380                                    BinaryOp::Add,
381                                    *y2,
382                                    T::binary(BinaryOp::Mul, x[2], wv),
383                                );
384                                *y3 = T::binary(
385                                    BinaryOp::Add,
386                                    *y3,
387                                    T::binary(BinaryOp::Mul, x[3], wv),
388                                );
389                            }
390                        }
391                    }
392                } else {
393                    for (j, off) in offs.iter().enumerate().take(nb) {
394                        let Some(l0) = *off else { continue };
395                        let aj = &mut acc[j * features..(j + 1) * features];
396                        for i in 0..in_features {
397                            let a = lhs[l0 + i];
398                            let row = &rhs[roff + i * rfeat..roff + i * rfeat + features];
399                            for (x, &b) in aj.iter_mut().zip(row) {
400                                *x = T::binary(BinaryOp::Add, *x, T::binary(BinaryOp::Mul, a, b));
401                            }
402                        }
403                    }
404                }
405            }
406            for j in 0..nb {
407                let mut obase = r[0] * ost[d.out_spec[0]];
408                for k in 0..nsp {
409                    let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
410                    obase += o * ost[d.out_spec[2 + k]];
411                }
412                out[obase..obase + features]
413                    .copy_from_slice(&acc[j * features..(j + 1) * features]);
414            }
415            j0 += nb;
416        }
417    }
418    Some(out)
419}
420
421/// The products that [`conv_general_dilated`] sums, in its order: for each
422/// element of the result (row-major), `[result, lhs, rhs]` positions of the
423/// operands' elements whose products are added, from zero, in this order (to
424/// compile small convolutions as a table: the same sums as the kernel, bit
425/// for bit, for the types it does not fuse or widen, that is, other than
426/// `f64`, `f16`, and `bf16`).
427pub fn conv_terms(
428    lshape: &[usize],
429    rshape: &[usize],
430    w: &ConvWindow<'_>,
431    d: &ConvDims,
432    feature_group_count: usize,
433    batch_group_count: usize,
434) -> Vec<[usize; 3]> {
435    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
436    let nsp = lshape.len() - 2;
437    let (lst, rst) = (strides(lshape), strides(rshape));
438    let out_features = rshape[d.rhs_spec[0]];
439    let in_features = rshape[d.rhs_spec[1]];
440    let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
441    let out_per_feature_group = (out_features / feature_group_count).max(1);
442    let out_per_batch_group = (out_features / batch_group_count).max(1);
443    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
444    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
445        .into_iter()
446        .map(|kidx| {
447            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
448            (kidx, off)
449        })
450        .collect();
451    let lfeat = lst[d.lhs_spec[1]];
452    let rfeat = rst[d.rhs_spec[1]];
453    let mut terms = Vec::new();
454    let mut flat = 0;
455    for_each_index(&out_shape, |o| {
456        let b = o[d.out_spec[0]];
457        let f = o[d.out_spec[1]];
458        let feature_group = f / out_per_feature_group;
459        let batch_group = f / out_per_batch_group;
460        let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
461            + feature_group * in_features * lfeat;
462        let rbase = f * rst[d.rhs_spec[0]];
463        'positions: for (kidx, roff) in &positions {
464            let mut loff = 0;
465            for k in 0..nsp {
466                let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
467                let n = lshape[d.lhs_spec[2 + k]];
468                match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
469                    Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
470                    None => continue 'positions,
471                }
472            }
473            let (l0, r0) = (lbase + loff, rbase + roff);
474            for i in 0..in_features {
475                terms.push([flat, l0 + i * lfeat, r0 + i * rfeat]);
476            }
477        }
478        flat += 1;
479    });
480    terms
481}
482
483/// The window of a windowed reduction: one entry per operand dimension.
484#[derive(Clone, Copy, Debug)]
485pub struct Window<'a> {
486    /// The size of the window.
487    pub dimensions: &'a [usize],
488    /// The step between windows.
489    pub strides: &'a [usize],
490    /// `(low, high)` padding of the (dilated) operand.
491    pub padding: &'a [(i64, i64)],
492    /// The dilation of the operand (`d - 1` holes between elements).
493    pub base_dilation: &'a [usize],
494    /// The dilation of the window.
495    pub window_dilation: &'a [usize],
496}
497
498/// The shape of the result of a windowed reduction.
499pub fn reduce_window_shape(shape: &[usize], w: &Window<'_>) -> Vec<usize> {
500    (0..shape.len())
501        .map(|i| {
502            let (lo, hi) = w.padding[i];
503            let padded = dilate_dim(shape[i], w.base_dilation[i]) as i64 + lo + hi;
504            let window = dilate_dim(w.dimensions[i], w.window_dilation[i]);
505            stride_dim(padded, window, w.strides[i])
506        })
507        .collect()
508}
509
510/// Calls `f` for each window of `w` over an operand of `shape`, in
511/// row-major order of the result, with the flat indices of the operand
512/// elements the window covers (`None` for padding and holes), in row-major
513/// order of the window.
514fn for_each_window(shape: &[usize], w: &Window<'_>, mut f: impl FnMut(&[Option<usize>])) {
515    let out_shape = reduce_window_shape(shape, w);
516    let st = strides(shape);
517    let positions = all_indices(w.dimensions);
518    let mut covered = vec![None; positions.len()];
519    for_each_index(&out_shape, |o| {
520        for (c, widx) in covered.iter_mut().zip(&positions) {
521            let mut flat = Some(0);
522            for i in 0..shape.len() {
523                let p = (o[i] * w.strides[i] + widx[i] * w.window_dilation[i]) as i64;
524                match undilate(p, w.padding[i].0, w.base_dilation[i], shape[i]) {
525                    Some(q) => flat = flat.map(|f| f + q * st[i]),
526                    None => {
527                        flat = None;
528                        break;
529                    }
530                }
531            }
532            *c = flat;
533        }
534        f(&covered);
535    });
536}
537
538/// `reduce_window_sum`, `reduce_window_max`, `reduce_window_min`: combines
539/// the elements of each window, from the identity, in row-major order of
540/// the window (padding and holes are skipped). This is XLA's order on CPU
541/// for windows without padding; with padding, XLA sums some windows in
542/// another order.
543pub fn reduce_window<T: Element>(x: &[T], shape: &[usize], w: &Window<'_>, op: ReduceOp) -> Vec<T> {
544    let bin = op.binary();
545    let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
546    for_each_window(shape, w, |covered| {
547        let mut acc = op.identity::<T>();
548        for &v in covered.iter().flatten() {
549            acc = T::binary(bin, acc, x[v]);
550        }
551        out.push(acc);
552    });
553    out
554}
555
556/// Whether `a` is selected over `b`: `a >= b` (`ge`) or `a <= b`.
557#[inline]
558fn selects<T: Element>(ge: bool, a: T, b: T) -> bool {
559    compare(if ge { CompareOp::Ge } else { CompareOp::Le }, a, b)
560}
561
562/// `select_and_scatter_add`: for each window of `operand` (of shape
563/// `shape`), selects an element (`ge`: the first maximum, otherwise the
564/// first minimum, as XLA's `select_and_scatter` with the comparison as
565/// `select`) and adds the window's element of `source` to it in the result
566/// (zeros elsewhere). Windows are visited in row-major order.
567///
568/// As JAX lowers it on CPU, padding holds the identity of the selection
569/// (the lowest value for `ge`, the highest otherwise) and can be selected,
570/// in which case the source element is dropped.
571pub fn select_and_scatter_add<T: Element>(
572    source: &[T],
573    operand: &[T],
574    shape: &[usize],
575    dimensions: &[usize],
576    window_strides: &[usize],
577    padding: &[(i64, i64)],
578    ge: bool,
579) -> Vec<T> {
580    let ones = vec![1; shape.len()];
581    let w = Window {
582        dimensions,
583        strides: window_strides,
584        padding,
585        base_dilation: &ones,
586        window_dilation: &ones,
587    };
588    let identity = if ge { T::lowest() } else { T::highest() };
589    let mut out = vec![T::default(); size(shape)];
590    let mut s = 0;
591    for_each_window(shape, &w, |covered| {
592        let value = |c: Option<usize>| c.map_or(identity, |i| operand[i]);
593        let mut selected = covered[0];
594        let mut selected_value = value(selected);
595        for &c in &covered[1..] {
596            let v = value(c);
597            if !selects(ge, selected_value, v) {
598                selected = c;
599                selected_value = v;
600            }
601        }
602        if let Some(i) = selected {
603            out[i] = T::binary(BinaryOp::Add, out[i], source[s]);
604        }
605        s += 1;
606    });
607    out
608}
609
610/// `select_and_gather_add`: for each window of `operand`, the element of
611/// `tangents` at the position of the selected element of `operand` (`ge`:
612/// the first maximum, otherwise the first minimum), or 0 if the window
613/// covers no element.
614///
615/// Each window is reduced from `(identity, 0)` in row-major order, keeping
616/// the accumulated pair when `select(acc, x)` holds and taking the element
617/// otherwise, as JAX's lowering to a `reduce_window` of pairs does; padding
618/// and holes are skipped.
619pub fn select_and_gather_add<T: Element>(
620    tangents: &[T],
621    operand: &[T],
622    shape: &[usize],
623    w: &Window<'_>,
624    ge: bool,
625) -> Vec<T> {
626    let identity = if ge { T::lowest() } else { T::highest() };
627    let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
628    for_each_window(shape, w, |covered| {
629        let (mut k, mut v) = (identity, T::default());
630        for &i in covered.iter().flatten() {
631            if !selects(ge, k, operand[i]) {
632                k = operand[i];
633                v = tangents[i];
634            }
635        }
636        out.push(v);
637    });
638    out
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644
645    /// The loop for Flax's layouts gives the general loop's sums, bit for
646    /// bit (the general loop's order is that of `conv_terms`).
647    #[test]
648    fn features_last_sums_as_the_general_loop() {
649        let d = ConvDims {
650            lhs_spec: vec![0, 3, 1, 2],
651            rhs_spec: vec![3, 2, 0, 1],
652            out_spec: vec![0, 3, 1, 2],
653        };
654        // Blocks of four outputs inside and at the edges, and leftovers.
655        for (lshape, strides, padding) in [
656            ([2, 5, 6, 3], [1, 2], [(1, 1), (0, 2)]),
657            ([1, 4, 11, 2], [1, 1], [(1, 1), (1, 1)]),
658            ([1, 3, 13, 2], [1, 1], [(0, 0), (2, -1)]),
659        ] {
660            // 20 output features: a chunk of 16 and a remainder.
661            let rshape = [3, 3, lshape[3], 20];
662            let w = ConvWindow {
663                strides: &strides,
664                padding: &padding,
665                lhs_dilation: &[1, 1],
666                rhs_dilation: &[1, 1],
667            };
668            let n: usize = lshape.iter().product();
669            let m: usize = rshape.iter().product();
670            let lhs: Vec<f32> = (0..n)
671                .map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
672                .collect();
673            let rhs: Vec<f32> = (0..m)
674                .map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
675                .collect();
676            let fast = conv_features_last(&lhs, &lshape, &rhs, &rshape, &w, &d, 1, 1)
677                .expect("the fast loop applies");
678            let mut out = vec![0.0f32; fast.len()];
679            for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 1, 1) {
680                out[o] += lhs[l] * rhs[r];
681            }
682            assert_eq!(
683                fast.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
684                out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
685                "{lshape:?} {strides:?} {padding:?}"
686            );
687        }
688    }
689
690    #[test]
691    fn conv_terms_sum_as_the_kernel() {
692        // A 2-D convolution with padding, strides, dilation, and feature
693        // groups, in an unusual layout.
694        let lshape = [2, 4, 7, 6];
695        let rshape = [3, 3, 2, 4];
696        let d = ConvDims {
697            lhs_spec: vec![0, 1, 2, 3],
698            rhs_spec: vec![3, 2, 0, 1],
699            out_spec: vec![0, 1, 2, 3],
700        };
701        let w = ConvWindow {
702            strides: &[2, 1],
703            padding: &[(1, 2), (0, 1)],
704            lhs_dilation: &[1, 2],
705            rhs_dilation: &[2, 1],
706        };
707        let lhs: Vec<f32> = (0..2 * 4 * 7 * 6)
708            .map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
709            .collect();
710        let rhs: Vec<f32> = (0..3 * 3 * 2 * 4)
711            .map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
712            .collect();
713        let expected = conv_general_dilated(&lhs, &lshape, &rhs, &rshape, &w, &d, 2, 1);
714        let mut out = vec![0.0f32; expected.len()];
715        for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 2, 1) {
716            out[o] += lhs[l] * rhs[r];
717        }
718        assert_eq!(
719            out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
720            expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
721        );
722    }
723
724    #[test]
725    fn convolution_with_padding_strides_and_dilation() {
726        // One example, one feature, width 5; a kernel of width 2.
727        let x = [1.0f32, 2.0, 3.0, 4.0, 5.0];
728        let k = [1.0f32, 10.0];
729        let d = ConvDims::canonical(3);
730        let w = ConvWindow {
731            strides: &[2],
732            padding: &[(1, 0)],
733            lhs_dilation: &[1],
734            rhs_dilation: &[1],
735        };
736        // Padded: [0, 1, 2, 3, 4, 5]; windows at 0, 2, 4.
737        let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
738        assert_eq!(y, [10.0, 32.0, 54.0]);
739        let w = ConvWindow {
740            strides: &[1],
741            padding: &[(0, 0)],
742            lhs_dilation: &[2],
743            rhs_dilation: &[1],
744        };
745        // Dilated: [1, _, 2, _, 3, _, 4, _, 5].
746        let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
747        assert_eq!(y, [1.0, 20.0, 2.0, 30.0, 3.0, 40.0, 4.0, 50.0]);
748    }
749
750    #[test]
751    fn windowed_reductions() {
752        let x = [1.0f32, 5.0, 2.0, 4.0];
753        let w = Window {
754            dimensions: &[2],
755            strides: &[1],
756            padding: &[(1, 0)],
757            base_dilation: &[1],
758            window_dilation: &[1],
759        };
760        assert_eq!(reduce_window_shape(&[4], &w), [4]);
761        assert_eq!(
762            reduce_window(&x, &[4], &w, ReduceOp::Sum),
763            [1.0, 6.0, 7.0, 6.0]
764        );
765        assert_eq!(
766            reduce_window(&x, &[4], &w, ReduceOp::Max),
767            [1.0, 5.0, 5.0, 4.0]
768        );
769        let src = [1.0f32, 10.0, 100.0, 1000.0];
770        assert_eq!(
771            select_and_scatter_add(&src, &x, &[4], &[2], &[1], &[(1, 0)], true),
772            [1.0, 110.0, 0.0, 1000.0]
773        );
774        let t = [0.1f32, 0.5, 0.2, 0.4];
775        assert_eq!(
776            select_and_gather_add(&t, &x, &[4], &w, true),
777            [0.1, 0.5, 0.5, 0.4]
778        );
779    }
780}