ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! Windowed reductions (`lax.reduce_window` with `add`, `max`, or `min`).

use ruxla_ir::DType;
use ruxla_kernels::Element;
pub use ruxla_kernels::array::ReduceOp;
use ruxla_kernels::window::{Window, dilate_dim};

use super::Padding;
use crate::backend::Backend;
use crate::value::{Array, Num};

/// `lax.reduce_window` with the monoid `op` (`add` from 0, `max` from the
/// lowest value, or `min` from the highest), with base and window
/// dilations (`None`: 1). String padding is resolved for the operand's
/// shape and the dilated window, as JAX does.
///
/// # Panics
///
/// Panics if the window does not fit the operand, if the padding is
/// negative, or if booleans are summed.
#[track_caller]
pub fn reduce_window<B: Backend, T: Element>(
    x: &Array<B, T>,
    op: ReduceOp,
    window_dimensions: &[usize],
    window_strides: &[usize],
    padding: impl Into<Padding>,
    base_dilation: Option<&[usize]>,
    window_dilation: Option<&[usize]>,
) -> Array<B, T> {
    assert!(
        op != ReduceOp::Sum || T::DTYPE != DType::Bool,
        "reduce_window_sum does not accept booleans"
    );
    let rank = window_dimensions.len();
    let ones = vec![1; rank];
    let base_dilation = base_dilation.unwrap_or(&ones);
    let window_dilation = window_dilation.unwrap_or(&ones);
    let padding = padding.into();
    let pads = match &padding {
        Padding::Explicit(pads) => pads.clone(),
        _ => {
            let window: Vec<usize> = window_dimensions
                .iter()
                .zip(window_dilation)
                .map(|(&d, &w)| dilate_dim(d, w))
                .collect();
            padding.to_pads(x.shape().dims(), &window, window_strides)
        }
    };
    let window = Window {
        dimensions: window_dimensions,
        strides: window_strides,
        padding: &pads,
        base_dilation,
        window_dilation,
    };
    Array(B::reduce_window(op, &x.0, &window))
}

/// Sums over windows (`lax.reduce_window(x, 0, lax.add, ...)`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [4]);
/// let y = lax::reduce_window_sum(&x, &[2], &[2], lax::Padding::Valid);
/// assert_eq!(y.to_vec(), [3.0, 7.0]);
/// ```
///
/// # Panics
///
/// See [`reduce_window`].
#[track_caller]
pub fn reduce_window_sum<B: Backend, T: Num>(
    x: &Array<B, T>,
    window_dimensions: &[usize],
    window_strides: &[usize],
    padding: impl Into<Padding>,
) -> Array<B, T> {
    reduce_window(
        x,
        ReduceOp::Sum,
        window_dimensions,
        window_strides,
        padding,
        None,
        None,
    )
}

/// The maximum over windows, propagating NaN (`lax.reduce_window(x, -inf,
/// lax.max, ...)`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, f32>::from_vec(vec![1.0, 5.0, 3.0], [3]);
/// let y = lax::reduce_window_max(&x, &[2], &[1], lax::Padding::Same);
/// assert_eq!(y.to_vec(), [5.0, 5.0, 3.0]);
/// ```
///
/// # Panics
///
/// See [`reduce_window`].
#[track_caller]
pub fn reduce_window_max<B: Backend, T: Element>(
    x: &Array<B, T>,
    window_dimensions: &[usize],
    window_strides: &[usize],
    padding: impl Into<Padding>,
) -> Array<B, T> {
    reduce_window(
        x,
        ReduceOp::Max,
        window_dimensions,
        window_strides,
        padding,
        None,
        None,
    )
}

/// The minimum over windows, propagating NaN (`lax.reduce_window(x, inf,
/// lax.min, ...)`).
///
/// # Panics
///
/// See [`reduce_window`].
#[track_caller]
pub fn reduce_window_min<B: Backend, T: Element>(
    x: &Array<B, T>,
    window_dimensions: &[usize],
    window_strides: &[usize],
    padding: impl Into<Padding>,
) -> Array<B, T> {
    reduce_window(
        x,
        ReduceOp::Min,
        window_dimensions,
        window_strides,
        padding,
        None,
        None,
    )
}