ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Convolutions and windowed reductions on row-major buffers, with XLA's
//! semantics.
//!
//! As in [`crate::array`], shapes are assumed to have been checked (by shape
//! inference); the functions panic on inconsistent inputs.

use crate::array::{ReduceOp, size, strides};
use crate::dtype::{DType, Element, cast};
use crate::ops::{BinaryOp, CompareOp, compare};

/// The dimension numbers of a convolution, as JAX's `ConvDimensionNumbers`:
/// each spec lists dimensions of an operand or of the result.
///
/// `lhs_spec` is `(batch, feature, spatial...)` of the input, `rhs_spec`
/// is `(output feature, input feature, spatial...)` of the kernel, and
/// `out_spec` is `(batch, feature, spatial...)` of the result. Spatial
/// dimension `k` of the three correspond, and the window parameters of a
/// convolution are given in this order.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct ConvDims {
    /// The input's batch, feature, and spatial dimensions.
    pub lhs_spec: Vec<usize>,
    /// The kernel's output feature, input feature, and spatial dimensions.
    pub rhs_spec: Vec<usize>,
    /// The result's batch, feature, and spatial dimensions.
    pub out_spec: Vec<usize>,
}

impl ConvDims {
    /// The dimension numbers of operands in the canonical order
    /// `(batch, feature, spatial...)` (JAX's default for `None`).
    pub fn canonical(rank: usize) -> Self {
        let iota: Vec<usize> = (0..rank).collect();
        Self {
            lhs_spec: iota.clone(),
            rhs_spec: iota.clone(),
            out_spec: iota,
        }
    }
}

/// The window of a convolution: one entry per spatial dimension.
#[derive(Clone, Copy, Debug)]
pub struct ConvWindow<'a> {
    /// The step between windows.
    pub strides: &'a [usize],
    /// `(low, high)` padding of the (dilated) input; negative padding
    /// removes elements.
    pub padding: &'a [(i64, i64)],
    /// The dilation of the input (`d - 1` holes between elements).
    pub lhs_dilation: &'a [usize],
    /// The dilation of the kernel.
    pub rhs_dilation: &'a [usize],
}

/// The size of a dimension of size `d` after dilation:
/// `1 + dilation * (d - 1)`, or 0 for an empty dimension.
pub fn dilate_dim(d: usize, dilation: usize) -> usize {
    if d == 0 { 0 } else { 1 + dilation * (d - 1) }
}

/// The number of windows of size `window` with step `stride` in a
/// dimension of size `d`: `max(0, (d - window) / stride + 1)`.
pub fn stride_dim(d: i64, window: usize, stride: usize) -> usize {
    let window = window as i64;
    if d < window {
        0
    } else {
        ((d - window) / stride as i64 + 1) as usize
    }
}

/// The shape of the result of a convolution.
pub fn conv_shape(
    lhs: &[usize],
    rhs: &[usize],
    w: &ConvWindow<'_>,
    d: &ConvDims,
    batch_group_count: usize,
) -> Vec<usize> {
    let mut out = vec![0; lhs.len()];
    out[d.out_spec[0]] = lhs[d.lhs_spec[0]] / batch_group_count.max(1);
    out[d.out_spec[1]] = rhs[d.rhs_spec[0]];
    for k in 0..lhs.len().saturating_sub(2) {
        let (lo, hi) = w.padding[k];
        let padded = dilate_dim(lhs[d.lhs_spec[2 + k]], w.lhs_dilation[k]) as i64 + lo + hi;
        let window = dilate_dim(rhs[d.rhs_spec[2 + k]], w.rhs_dilation[k]);
        out[d.out_spec[2 + k]] = stride_dim(padded, window, w.strides[k]);
    }
    out
}

/// Calls `f` with the multi-index of each element of `shape`, in row-major
/// order.
fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
    let n = size(shape);
    let mut index = vec![0; shape.len()];
    for _ in 0..n {
        f(&index);
        for d in (0..shape.len()).rev() {
            index[d] += 1;
            if index[d] < shape[d] {
                break;
            }
            index[d] = 0;
        }
    }
}

/// The multi-indices of `shape` in row-major order.
fn all_indices(shape: &[usize]) -> Vec<Vec<usize>> {
    let mut out = Vec::with_capacity(size(shape));
    for_each_index(shape, |i| out.push(i.to_vec()));
    out
}

/// The position in an operand dimension of size `n` of the element that a
/// window position covers, given the position `p` in the padded and dilated
/// dimension: `None` for padding and for holes of the dilation.
#[inline]
fn undilate(p: i64, lo: i64, dilation: usize, n: usize) -> Option<usize> {
    let p = p - lo;
    let dilation = dilation as i64;
    if p < 0 || p % dilation != 0 || p / dilation >= n as i64 {
        None
    } else {
        Some((p / dilation) as usize)
    }
}

/// `conv_general_dilated`: XLA's convolution, with feature groups (the
/// input features and the output features are split into
/// `feature_group_count` groups, and output group `g` sees input group `g`)
/// and batch groups (the input batch is split into `batch_group_count`
/// groups, the major part of the batch dimension, and output feature group
/// `g` sees batch group `g`).
///
/// Each result is accumulated in the result type, over the kernel's spatial
/// positions in row-major order and, for each, over the input features, as
/// XLA's CPU backend does for `f64` (with fused multiply-adds, which gives
/// the same bits) and for 16-bit floats (in `f32`, rounded once). XLA sums
/// `f32` convolutions in another order (with Eigen).
/// Padding and the holes of the input dilation contribute nothing (not
/// `0 * w`, which differs for an infinite or NaN `w`).
#[allow(clippy::too_many_arguments)]
pub fn conv_general_dilated<T: Element>(
    lhs: &[T],
    lshape: &[usize],
    rhs: &[T],
    rshape: &[usize],
    w: &ConvWindow<'_>,
    d: &ConvDims,
    feature_group_count: usize,
    batch_group_count: usize,
) -> Vec<T> {
    if matches!(T::DTYPE, DType::F16 | DType::BF16) {
        let wide = |x: &[T]| x.iter().map(|&v| cast::<T, f32>(v)).collect::<Vec<f32>>();
        return conv_general_dilated(
            &wide(lhs),
            lshape,
            &wide(rhs),
            rshape,
            w,
            d,
            feature_group_count,
            batch_group_count,
        )
        .into_iter()
        .map(cast::<f32, T>)
        .collect();
    }
    if let Some(out) = conv_features_last(
        lhs,
        lshape,
        rhs,
        rshape,
        w,
        d,
        feature_group_count,
        batch_group_count,
    ) {
        return out;
    }
    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
    let nsp = lshape.len() - 2;
    let (lst, rst) = (strides(lshape), strides(rshape));
    let out_features = rshape[d.rhs_spec[0]];
    let in_features = rshape[d.rhs_spec[1]];
    let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
    let out_per_feature_group = (out_features / feature_group_count).max(1);
    let out_per_batch_group = (out_features / batch_group_count).max(1);
    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
    // The kernel's spatial positions, with their offsets in the kernel.
    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
        .into_iter()
        .map(|kidx| {
            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
            (kidx, off)
        })
        .collect();
    let lfeat = lst[d.lhs_spec[1]];
    let rfeat = rst[d.rhs_spec[1]];
    // XLA's CPU backend fuses the products and sums of `f64` convolutions.
    let fused = T::DTYPE == DType::F64;
    let mut out = Vec::with_capacity(size(&out_shape));
    for_each_index(&out_shape, |o| {
        let b = o[d.out_spec[0]];
        let f = o[d.out_spec[1]];
        let feature_group = f / out_per_feature_group;
        let batch_group = f / out_per_batch_group;
        let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
            + feature_group * in_features * lfeat;
        let rbase = f * rst[d.rhs_spec[0]];
        let mut acc = T::default();
        'positions: for (kidx, roff) in &positions {
            let mut loff = 0;
            for k in 0..nsp {
                let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
                let n = lshape[d.lhs_spec[2 + k]];
                match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
                    Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
                    None => continue 'positions,
                }
            }
            let (l0, r0) = (lbase + loff, rbase + roff);
            if fused {
                for i in 0..in_features {
                    let (a, b): (f64, f64) = (cast(lhs[l0 + i * lfeat]), cast(rhs[r0 + i * rfeat]));
                    acc = cast(a.mul_add(b, cast(acc)));
                }
            } else {
                for i in 0..in_features {
                    let p = T::binary(BinaryOp::Mul, lhs[l0 + i * lfeat], rhs[r0 + i * rfeat]);
                    acc = T::binary(BinaryOp::Add, acc, p);
                }
            }
        }
        out.push(acc);
    });
    out
}

/// [`conv_general_dilated`] for the layouts of Flax's convolutions (the
/// features innermost in the input, the kernel's output features innermost,
/// and the output's features innermost: `NHWC`, `HWIO`, `NHWC`), without
/// dilation or groups, and for the types it does not fuse or widen: for
/// each output position, the kernel positions and input features are
/// visited in the same order and each product is added to a row of all the
/// output features, so that the innermost loop reads the kernel's
/// contiguous rows. Every output element is the same sum, in the same
/// order, as in the general loop. `None` for other cases.
#[allow(clippy::too_many_arguments)]
fn conv_features_last<T: Element>(
    lhs: &[T],
    lshape: &[usize],
    rhs: &[T],
    rshape: &[usize],
    w: &ConvWindow<'_>,
    d: &ConvDims,
    feature_group_count: usize,
    batch_group_count: usize,
) -> Option<Vec<T>> {
    let rank = lshape.len();
    let nsp = rank.checked_sub(2)?;
    if nsp == 0
        || matches!(T::DTYPE, DType::F64 | DType::F16 | DType::BF16)
        || feature_group_count != 1
        || batch_group_count != 1
        || w.lhs_dilation.iter().any(|&x| x != 1)
        || w.rhs_dilation.iter().any(|&x| x != 1)
        || d.lhs_spec[1] != rank - 1
        || d.rhs_spec[0] != rank - 1
        || d.out_spec[1] != rank - 1
    {
        return None;
    }
    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
    let (lst, rst) = (strides(lshape), strides(rshape));
    let ost = strides(&out_shape);
    let features = rshape[d.rhs_spec[0]];
    let in_features = rshape[d.rhs_spec[1]];
    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
        .into_iter()
        .map(|kidx| {
            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
            (kidx, off)
        })
        .collect();
    let rfeat = rst[d.rhs_spec[1]];
    let mut out = vec![T::default(); size(&out_shape)];
    // The output positions (batch and spatial), features excluded, in rows
    // along the last spatial dimension, computed `BLOCK` at a time so that
    // each row of the kernel is read once for all of them (positions where
    // the window leaves the input contribute nothing to that output only).
    const BLOCK: usize = 4;
    let last = out_shape[d.out_spec[1 + nsp]];
    let mut row_shape = vec![out_shape[d.out_spec[0]]];
    row_shape.extend((0..nsp - 1).map(|k| out_shape[d.out_spec[2 + k]]));
    let mut acc = vec![T::default(); BLOCK * features];
    for r in all_indices(&row_shape) {
        let lbase = r[0] * lst[d.lhs_spec[0]];
        let mut j0 = 0;
        while j0 < last {
            let nb = BLOCK.min(last - j0);
            acc.fill(T::default());
            for (kidx, roff) in &positions {
                // The input offset of each output of the block, if inside.
                let mut offs = [None; BLOCK];
                let mut inside = true;
                for (j, off) in offs.iter_mut().enumerate().take(nb) {
                    let mut loff = 0;
                    let mut ok = true;
                    for k in 0..nsp {
                        let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
                        let p = (o * w.strides[k] + kidx[k]) as i64 - w.padding[k].0;
                        if p < 0 || p >= lshape[d.lhs_spec[2 + k]] as i64 {
                            ok = false;
                            break;
                        }
                        loff += p as usize * lst[d.lhs_spec[2 + k]];
                    }
                    *off = ok.then_some(lbase + loff);
                    inside &= ok;
                }
                if inside && nb == BLOCK {
                    let o: [usize; BLOCK] = std::array::from_fn(|j| offs[j].unwrap_or(0));
                    // Chunks of `CH` features held in locals over the input
                    // features (registers), the rest as rows.
                    const CH: usize = 16;
                    let full = features - features % CH;
                    for fc in (0..full).step_by(CH) {
                        let mut y: [[T; CH]; BLOCK] = std::array::from_fn(|j| {
                            std::array::from_fn(|c| acc[j * features + fc + c])
                        });
                        for i in 0..in_features {
                            let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
                            let base = roff + i * rfeat + fc;
                            let row: &[T; CH] = rhs[base..base + CH].try_into().expect("a chunk");
                            for c in 0..CH {
                                let wv = row[c];
                                for j in 0..BLOCK {
                                    y[j][c] = T::binary(
                                        BinaryOp::Add,
                                        y[j][c],
                                        T::binary(BinaryOp::Mul, x[j], wv),
                                    );
                                }
                            }
                        }
                        for (j, yj) in y.iter().enumerate() {
                            acc[j * features + fc..j * features + fc + CH].copy_from_slice(yj);
                        }
                    }
                    if full < features {
                        let (a0, rest) = acc.split_at_mut(features);
                        let (a1, rest) = rest.split_at_mut(features);
                        let (a2, a3) = rest.split_at_mut(features);
                        for i in 0..in_features {
                            let x = [lhs[o[0] + i], lhs[o[1] + i], lhs[o[2] + i], lhs[o[3] + i]];
                            let row = &rhs[roff + i * rfeat + full..roff + i * rfeat + features];
                            let lanes = a0[full..]
                                .iter_mut()
                                .zip(a1[full..].iter_mut())
                                .zip(a2[full..].iter_mut())
                                .zip(a3[full..].iter_mut())
                                .zip(row);
                            for ((((y0, y1), y2), y3), &wv) in lanes {
                                *y0 = T::binary(
                                    BinaryOp::Add,
                                    *y0,
                                    T::binary(BinaryOp::Mul, x[0], wv),
                                );
                                *y1 = T::binary(
                                    BinaryOp::Add,
                                    *y1,
                                    T::binary(BinaryOp::Mul, x[1], wv),
                                );
                                *y2 = T::binary(
                                    BinaryOp::Add,
                                    *y2,
                                    T::binary(BinaryOp::Mul, x[2], wv),
                                );
                                *y3 = T::binary(
                                    BinaryOp::Add,
                                    *y3,
                                    T::binary(BinaryOp::Mul, x[3], wv),
                                );
                            }
                        }
                    }
                } else {
                    for (j, off) in offs.iter().enumerate().take(nb) {
                        let Some(l0) = *off else { continue };
                        let aj = &mut acc[j * features..(j + 1) * features];
                        for i in 0..in_features {
                            let a = lhs[l0 + i];
                            let row = &rhs[roff + i * rfeat..roff + i * rfeat + features];
                            for (x, &b) in aj.iter_mut().zip(row) {
                                *x = T::binary(BinaryOp::Add, *x, T::binary(BinaryOp::Mul, a, b));
                            }
                        }
                    }
                }
            }
            for j in 0..nb {
                let mut obase = r[0] * ost[d.out_spec[0]];
                for k in 0..nsp {
                    let o = if k + 1 < nsp { r[1 + k] } else { j0 + j };
                    obase += o * ost[d.out_spec[2 + k]];
                }
                out[obase..obase + features]
                    .copy_from_slice(&acc[j * features..(j + 1) * features]);
            }
            j0 += nb;
        }
    }
    Some(out)
}

/// The products that [`conv_general_dilated`] sums, in its order: for each
/// element of the result (row-major), `[result, lhs, rhs]` positions of the
/// operands' elements whose products are added, from zero, in this order (to
/// compile small convolutions as a table: the same sums as the kernel, bit
/// for bit, for the types it does not fuse or widen, that is, other than
/// `f64`, `f16`, and `bf16`).
pub fn conv_terms(
    lshape: &[usize],
    rshape: &[usize],
    w: &ConvWindow<'_>,
    d: &ConvDims,
    feature_group_count: usize,
    batch_group_count: usize,
) -> Vec<[usize; 3]> {
    let out_shape = conv_shape(lshape, rshape, w, d, batch_group_count);
    let nsp = lshape.len() - 2;
    let (lst, rst) = (strides(lshape), strides(rshape));
    let out_features = rshape[d.rhs_spec[0]];
    let in_features = rshape[d.rhs_spec[1]];
    let batch_per_group = lshape[d.lhs_spec[0]] / batch_group_count;
    let out_per_feature_group = (out_features / feature_group_count).max(1);
    let out_per_batch_group = (out_features / batch_group_count).max(1);
    let kernel_sizes: Vec<usize> = (0..nsp).map(|k| rshape[d.rhs_spec[2 + k]]).collect();
    let positions: Vec<(Vec<usize>, usize)> = all_indices(&kernel_sizes)
        .into_iter()
        .map(|kidx| {
            let off = (0..nsp).map(|k| kidx[k] * rst[d.rhs_spec[2 + k]]).sum();
            (kidx, off)
        })
        .collect();
    let lfeat = lst[d.lhs_spec[1]];
    let rfeat = rst[d.rhs_spec[1]];
    let mut terms = Vec::new();
    let mut flat = 0;
    for_each_index(&out_shape, |o| {
        let b = o[d.out_spec[0]];
        let f = o[d.out_spec[1]];
        let feature_group = f / out_per_feature_group;
        let batch_group = f / out_per_batch_group;
        let lbase = (batch_group * batch_per_group + b) * lst[d.lhs_spec[0]]
            + feature_group * in_features * lfeat;
        let rbase = f * rst[d.rhs_spec[0]];
        'positions: for (kidx, roff) in &positions {
            let mut loff = 0;
            for k in 0..nsp {
                let p = (o[d.out_spec[2 + k]] * w.strides[k] + kidx[k] * w.rhs_dilation[k]) as i64;
                let n = lshape[d.lhs_spec[2 + k]];
                match undilate(p, w.padding[k].0, w.lhs_dilation[k], n) {
                    Some(q) => loff += q * lst[d.lhs_spec[2 + k]],
                    None => continue 'positions,
                }
            }
            let (l0, r0) = (lbase + loff, rbase + roff);
            for i in 0..in_features {
                terms.push([flat, l0 + i * lfeat, r0 + i * rfeat]);
            }
        }
        flat += 1;
    });
    terms
}

/// The window of a windowed reduction: one entry per operand dimension.
#[derive(Clone, Copy, Debug)]
pub struct Window<'a> {
    /// The size of the window.
    pub dimensions: &'a [usize],
    /// The step between windows.
    pub strides: &'a [usize],
    /// `(low, high)` padding of the (dilated) operand.
    pub padding: &'a [(i64, i64)],
    /// The dilation of the operand (`d - 1` holes between elements).
    pub base_dilation: &'a [usize],
    /// The dilation of the window.
    pub window_dilation: &'a [usize],
}

/// The shape of the result of a windowed reduction.
pub fn reduce_window_shape(shape: &[usize], w: &Window<'_>) -> Vec<usize> {
    (0..shape.len())
        .map(|i| {
            let (lo, hi) = w.padding[i];
            let padded = dilate_dim(shape[i], w.base_dilation[i]) as i64 + lo + hi;
            let window = dilate_dim(w.dimensions[i], w.window_dilation[i]);
            stride_dim(padded, window, w.strides[i])
        })
        .collect()
}

/// Calls `f` for each window of `w` over an operand of `shape`, in
/// row-major order of the result, with the flat indices of the operand
/// elements the window covers (`None` for padding and holes), in row-major
/// order of the window.
fn for_each_window(shape: &[usize], w: &Window<'_>, mut f: impl FnMut(&[Option<usize>])) {
    let out_shape = reduce_window_shape(shape, w);
    let st = strides(shape);
    let positions = all_indices(w.dimensions);
    let mut covered = vec![None; positions.len()];
    for_each_index(&out_shape, |o| {
        for (c, widx) in covered.iter_mut().zip(&positions) {
            let mut flat = Some(0);
            for i in 0..shape.len() {
                let p = (o[i] * w.strides[i] + widx[i] * w.window_dilation[i]) as i64;
                match undilate(p, w.padding[i].0, w.base_dilation[i], shape[i]) {
                    Some(q) => flat = flat.map(|f| f + q * st[i]),
                    None => {
                        flat = None;
                        break;
                    }
                }
            }
            *c = flat;
        }
        f(&covered);
    });
}

/// `reduce_window_sum`, `reduce_window_max`, `reduce_window_min`: combines
/// the elements of each window, from the identity, in row-major order of
/// the window (padding and holes are skipped). This is XLA's order on CPU
/// for windows without padding; with padding, XLA sums some windows in
/// another order.
pub fn reduce_window<T: Element>(x: &[T], shape: &[usize], w: &Window<'_>, op: ReduceOp) -> Vec<T> {
    let bin = op.binary();
    let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
    for_each_window(shape, w, |covered| {
        let mut acc = op.identity::<T>();
        for &v in covered.iter().flatten() {
            acc = T::binary(bin, acc, x[v]);
        }
        out.push(acc);
    });
    out
}

/// Whether `a` is selected over `b`: `a >= b` (`ge`) or `a <= b`.
#[inline]
fn selects<T: Element>(ge: bool, a: T, b: T) -> bool {
    compare(if ge { CompareOp::Ge } else { CompareOp::Le }, a, b)
}

/// `select_and_scatter_add`: for each window of `operand` (of shape
/// `shape`), selects an element (`ge`: the first maximum, otherwise the
/// first minimum, as XLA's `select_and_scatter` with the comparison as
/// `select`) and adds the window's element of `source` to it in the result
/// (zeros elsewhere). Windows are visited in row-major order.
///
/// As JAX lowers it on CPU, padding holds the identity of the selection
/// (the lowest value for `ge`, the highest otherwise) and can be selected,
/// in which case the source element is dropped.
pub fn select_and_scatter_add<T: Element>(
    source: &[T],
    operand: &[T],
    shape: &[usize],
    dimensions: &[usize],
    window_strides: &[usize],
    padding: &[(i64, i64)],
    ge: bool,
) -> Vec<T> {
    let ones = vec![1; shape.len()];
    let w = Window {
        dimensions,
        strides: window_strides,
        padding,
        base_dilation: &ones,
        window_dilation: &ones,
    };
    let identity = if ge { T::lowest() } else { T::highest() };
    let mut out = vec![T::default(); size(shape)];
    let mut s = 0;
    for_each_window(shape, &w, |covered| {
        let value = |c: Option<usize>| c.map_or(identity, |i| operand[i]);
        let mut selected = covered[0];
        let mut selected_value = value(selected);
        for &c in &covered[1..] {
            let v = value(c);
            if !selects(ge, selected_value, v) {
                selected = c;
                selected_value = v;
            }
        }
        if let Some(i) = selected {
            out[i] = T::binary(BinaryOp::Add, out[i], source[s]);
        }
        s += 1;
    });
    out
}

/// `select_and_gather_add`: for each window of `operand`, the element of
/// `tangents` at the position of the selected element of `operand` (`ge`:
/// the first maximum, otherwise the first minimum), or 0 if the window
/// covers no element.
///
/// Each window is reduced from `(identity, 0)` in row-major order, keeping
/// the accumulated pair when `select(acc, x)` holds and taking the element
/// otherwise, as JAX's lowering to a `reduce_window` of pairs does; padding
/// and holes are skipped.
pub fn select_and_gather_add<T: Element>(
    tangents: &[T],
    operand: &[T],
    shape: &[usize],
    w: &Window<'_>,
    ge: bool,
) -> Vec<T> {
    let identity = if ge { T::lowest() } else { T::highest() };
    let mut out = Vec::with_capacity(size(&reduce_window_shape(shape, w)));
    for_each_window(shape, w, |covered| {
        let (mut k, mut v) = (identity, T::default());
        for &i in covered.iter().flatten() {
            if !selects(ge, k, operand[i]) {
                k = operand[i];
                v = tangents[i];
            }
        }
        out.push(v);
    });
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The loop for Flax's layouts gives the general loop's sums, bit for
    /// bit (the general loop's order is that of `conv_terms`).
    #[test]
    fn features_last_sums_as_the_general_loop() {
        let d = ConvDims {
            lhs_spec: vec![0, 3, 1, 2],
            rhs_spec: vec![3, 2, 0, 1],
            out_spec: vec![0, 3, 1, 2],
        };
        // Blocks of four outputs inside and at the edges, and leftovers.
        for (lshape, strides, padding) in [
            ([2, 5, 6, 3], [1, 2], [(1, 1), (0, 2)]),
            ([1, 4, 11, 2], [1, 1], [(1, 1), (1, 1)]),
            ([1, 3, 13, 2], [1, 1], [(0, 0), (2, -1)]),
        ] {
            // 20 output features: a chunk of 16 and a remainder.
            let rshape = [3, 3, lshape[3], 20];
            let w = ConvWindow {
                strides: &strides,
                padding: &padding,
                lhs_dilation: &[1, 1],
                rhs_dilation: &[1, 1],
            };
            let n: usize = lshape.iter().product();
            let m: usize = rshape.iter().product();
            let lhs: Vec<f32> = (0..n)
                .map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
                .collect();
            let rhs: Vec<f32> = (0..m)
                .map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
                .collect();
            let fast = conv_features_last(&lhs, &lshape, &rhs, &rshape, &w, &d, 1, 1)
                .expect("the fast loop applies");
            let mut out = vec![0.0f32; fast.len()];
            for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 1, 1) {
                out[o] += lhs[l] * rhs[r];
            }
            assert_eq!(
                fast.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
                out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
                "{lshape:?} {strides:?} {padding:?}"
            );
        }
    }

    #[test]
    fn conv_terms_sum_as_the_kernel() {
        // A 2-D convolution with padding, strides, dilation, and feature
        // groups, in an unusual layout.
        let lshape = [2, 4, 7, 6];
        let rshape = [3, 3, 2, 4];
        let d = ConvDims {
            lhs_spec: vec![0, 1, 2, 3],
            rhs_spec: vec![3, 2, 0, 1],
            out_spec: vec![0, 1, 2, 3],
        };
        let w = ConvWindow {
            strides: &[2, 1],
            padding: &[(1, 2), (0, 1)],
            lhs_dilation: &[1, 2],
            rhs_dilation: &[2, 1],
        };
        let lhs: Vec<f32> = (0..2 * 4 * 7 * 6)
            .map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0)
            .collect();
        let rhs: Vec<f32> = (0..3 * 3 * 2 * 4)
            .map(|i| ((i * 13 % 29) as f32 - 14.0) / 3.0)
            .collect();
        let expected = conv_general_dilated(&lhs, &lshape, &rhs, &rshape, &w, &d, 2, 1);
        let mut out = vec![0.0f32; expected.len()];
        for [o, l, r] in conv_terms(&lshape, &rshape, &w, &d, 2, 1) {
            out[o] += lhs[l] * rhs[r];
        }
        assert_eq!(
            out.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
            expected.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn convolution_with_padding_strides_and_dilation() {
        // One example, one feature, width 5; a kernel of width 2.
        let x = [1.0f32, 2.0, 3.0, 4.0, 5.0];
        let k = [1.0f32, 10.0];
        let d = ConvDims::canonical(3);
        let w = ConvWindow {
            strides: &[2],
            padding: &[(1, 0)],
            lhs_dilation: &[1],
            rhs_dilation: &[1],
        };
        // Padded: [0, 1, 2, 3, 4, 5]; windows at 0, 2, 4.
        let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
        assert_eq!(y, [10.0, 32.0, 54.0]);
        let w = ConvWindow {
            strides: &[1],
            padding: &[(0, 0)],
            lhs_dilation: &[2],
            rhs_dilation: &[1],
        };
        // Dilated: [1, _, 2, _, 3, _, 4, _, 5].
        let y = conv_general_dilated(&x, &[1, 1, 5], &k, &[1, 1, 2], &w, &d, 1, 1);
        assert_eq!(y, [1.0, 20.0, 2.0, 30.0, 3.0, 40.0, 4.0, 50.0]);
    }

    #[test]
    fn windowed_reductions() {
        let x = [1.0f32, 5.0, 2.0, 4.0];
        let w = Window {
            dimensions: &[2],
            strides: &[1],
            padding: &[(1, 0)],
            base_dilation: &[1],
            window_dilation: &[1],
        };
        assert_eq!(reduce_window_shape(&[4], &w), [4]);
        assert_eq!(
            reduce_window(&x, &[4], &w, ReduceOp::Sum),
            [1.0, 6.0, 7.0, 6.0]
        );
        assert_eq!(
            reduce_window(&x, &[4], &w, ReduceOp::Max),
            [1.0, 5.0, 5.0, 4.0]
        );
        let src = [1.0f32, 10.0, 100.0, 1000.0];
        assert_eq!(
            select_and_scatter_add(&src, &x, &[4], &[2], &[1], &[(1, 0)], true),
            [1.0, 110.0, 0.0, 1000.0]
        );
        let t = [0.1f32, 0.5, 0.2, 0.4];
        assert_eq!(
            select_and_gather_add(&t, &x, &[4], &w, true),
            [0.1, 0.5, 0.5, 0.4]
        );
    }
}