Skip to main content

ruxla_core/lax/
window.rs

1//! Windowed reductions (`lax.reduce_window` with `add`, `max`, or `min`).
2
3use ruxla_ir::DType;
4use ruxla_kernels::Element;
5pub use ruxla_kernels::array::ReduceOp;
6use ruxla_kernels::window::{Window, dilate_dim};
7
8use super::Padding;
9use crate::backend::Backend;
10use crate::value::{Array, Num};
11
12/// `lax.reduce_window` with the monoid `op` (`add` from 0, `max` from the
13/// lowest value, or `min` from the highest), with base and window
14/// dilations (`None`: 1). String padding is resolved for the operand's
15/// shape and the dilated window, as JAX does.
16///
17/// # Panics
18///
19/// Panics if the window does not fit the operand, if the padding is
20/// negative, or if booleans are summed.
21#[track_caller]
22pub fn reduce_window<B: Backend, T: Element>(
23    x: &Array<B, T>,
24    op: ReduceOp,
25    window_dimensions: &[usize],
26    window_strides: &[usize],
27    padding: impl Into<Padding>,
28    base_dilation: Option<&[usize]>,
29    window_dilation: Option<&[usize]>,
30) -> Array<B, T> {
31    assert!(
32        op != ReduceOp::Sum || T::DTYPE != DType::Bool,
33        "reduce_window_sum does not accept booleans"
34    );
35    let rank = window_dimensions.len();
36    let ones = vec![1; rank];
37    let base_dilation = base_dilation.unwrap_or(&ones);
38    let window_dilation = window_dilation.unwrap_or(&ones);
39    let padding = padding.into();
40    let pads = match &padding {
41        Padding::Explicit(pads) => pads.clone(),
42        _ => {
43            let window: Vec<usize> = window_dimensions
44                .iter()
45                .zip(window_dilation)
46                .map(|(&d, &w)| dilate_dim(d, w))
47                .collect();
48            padding.to_pads(x.shape().dims(), &window, window_strides)
49        }
50    };
51    let window = Window {
52        dimensions: window_dimensions,
53        strides: window_strides,
54        padding: &pads,
55        base_dilation,
56        window_dilation,
57    };
58    Array(B::reduce_window(op, &x.0, &window))
59}
60
61/// Sums over windows (`lax.reduce_window(x, 0, lax.add, ...)`).
62///
63/// # Examples
64///
65/// ```
66/// use ruxla_core::{Array, Native, lax};
67///
68/// let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [4]);
69/// let y = lax::reduce_window_sum(&x, &[2], &[2], lax::Padding::Valid);
70/// assert_eq!(y.to_vec(), [3.0, 7.0]);
71/// ```
72///
73/// # Panics
74///
75/// See [`reduce_window`].
76#[track_caller]
77pub fn reduce_window_sum<B: Backend, T: Num>(
78    x: &Array<B, T>,
79    window_dimensions: &[usize],
80    window_strides: &[usize],
81    padding: impl Into<Padding>,
82) -> Array<B, T> {
83    reduce_window(
84        x,
85        ReduceOp::Sum,
86        window_dimensions,
87        window_strides,
88        padding,
89        None,
90        None,
91    )
92}
93
94/// The maximum over windows, propagating NaN (`lax.reduce_window(x, -inf,
95/// lax.max, ...)`).
96///
97/// # Examples
98///
99/// ```
100/// use ruxla_core::{Array, Native, lax};
101///
102/// let x = Array::<Native, f32>::from_vec(vec![1.0, 5.0, 3.0], [3]);
103/// let y = lax::reduce_window_max(&x, &[2], &[1], lax::Padding::Same);
104/// assert_eq!(y.to_vec(), [5.0, 5.0, 3.0]);
105/// ```
106///
107/// # Panics
108///
109/// See [`reduce_window`].
110#[track_caller]
111pub fn reduce_window_max<B: Backend, T: Element>(
112    x: &Array<B, T>,
113    window_dimensions: &[usize],
114    window_strides: &[usize],
115    padding: impl Into<Padding>,
116) -> Array<B, T> {
117    reduce_window(
118        x,
119        ReduceOp::Max,
120        window_dimensions,
121        window_strides,
122        padding,
123        None,
124        None,
125    )
126}
127
128/// The minimum over windows, propagating NaN (`lax.reduce_window(x, inf,
129/// lax.min, ...)`).
130///
131/// # Panics
132///
133/// See [`reduce_window`].
134#[track_caller]
135pub fn reduce_window_min<B: Backend, T: Element>(
136    x: &Array<B, T>,
137    window_dimensions: &[usize],
138    window_strides: &[usize],
139    padding: impl Into<Padding>,
140) -> Array<B, T> {
141    reduce_window(
142        x,
143        ReduceOp::Min,
144        window_dimensions,
145        window_strides,
146        padding,
147        None,
148        None,
149    )
150}