1use crate::array::{ReduceOp, size, strides};
8use crate::dtype::{DType, Element, cast};
9use crate::ops::{BinaryOp, CompareOp, compare};
10
11#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
20pub struct ConvDims {
21 pub lhs_spec: Vec<usize>,
23 pub rhs_spec: Vec<usize>,
25 pub out_spec: Vec<usize>,
27}
28
29impl ConvDims {
30 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#[derive(Clone, Copy, Debug)]
44pub struct ConvWindow<'a> {
45 pub strides: &'a [usize],
47 pub padding: &'a [(i64, i64)],
50 pub lhs_dilation: &'a [usize],
52 pub rhs_dilation: &'a [usize],
54}
55
56pub fn dilate_dim(d: usize, dilation: usize) -> usize {
59 if d == 0 { 0 } else { 1 + dilation * (d - 1) }
60}
61
62pub 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
73pub 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
93fn 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
110fn 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#[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#[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 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 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#[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 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 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 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
421pub 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#[derive(Clone, Copy, Debug)]
485pub struct Window<'a> {
486 pub dimensions: &'a [usize],
488 pub strides: &'a [usize],
490 pub padding: &'a [(i64, i64)],
492 pub base_dilation: &'a [usize],
494 pub window_dilation: &'a [usize],
496}
497
498pub 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
510fn 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
538pub 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#[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
562pub 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
610pub 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 #[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 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 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 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 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 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 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}