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
//! Elementwise operations on slices.
//!
//! Each function dispatches on the operation once, outside the loop, so that
//! the operation is inlined into the loop and the loop can be vectorized.
//! The results are the same as applying [`Ops`] element by element.

use crate::dtype::Element;
use crate::ops::{BinaryOp, CompareOp, Ops, UnaryOp, compare};

/// Expands `$body` once per variant of an operation enum, with `$op` bound
/// to the variant as a constant.
macro_rules! dispatch {
    ($op:expr, $enum:ident { $($v:ident),* $(,)? }, |$c:ident| $body:expr) => {
        match $op {
            $($enum::$v => { const $c: $enum = $enum::$v; $body })*
        }
    };
}

/// `out[i] = op(x[i])`.
///
/// # Panics
///
/// Panics if the lengths differ.
pub fn unary_into<T: Ops>(op: UnaryOp, x: &[T], out: &mut [T]) {
    assert_eq!(x.len(), out.len());
    dispatch!(
        op,
        UnaryOp {
            Neg,
            Abs,
            Sign,
            Not,
            Floor,
            Ceil,
            Round,
            RoundEven,
            Exp,
            Expm1,
            Log,
            Log1p,
            Sqrt,
            Rsqrt,
            Cbrt,
            Sin,
            Cos,
            Tan,
            Tanh,
            Logistic,
            Square,
            ErfInv,
            Lgamma,
            Digamma,
            Erf,
            Erfc,
            BesselI0e,
            BesselI1e,
        },
        |OP| {
            for (o, &a) in out.iter_mut().zip(x) {
                *o = T::unary(OP, a);
            }
        }
    );
}

/// `x[i] = op(x[i])` (an elementwise operation written over its operand).
pub fn unary_assign<T: Ops>(op: UnaryOp, x: &mut [T]) {
    dispatch!(
        op,
        UnaryOp {
            Neg,
            Abs,
            Sign,
            Not,
            Floor,
            Ceil,
            Round,
            RoundEven,
            Exp,
            Expm1,
            Log,
            Log1p,
            Sqrt,
            Rsqrt,
            Cbrt,
            Sin,
            Cos,
            Tan,
            Tanh,
            Logistic,
            Square,
            ErfInv,
            Lgamma,
            Digamma,
            Erf,
            Erfc,
            BesselI0e,
            BesselI1e,
        },
        |OP| {
            for a in x.iter_mut() {
                *a = T::unary(OP, *a);
            }
        }
    );
}

/// `out[i] = op(x[i], y[i])`, where a slice of length 1 stands for every
/// element (a broadcast scalar).
///
/// # Panics
///
/// Panics if a length is neither 1 nor the length of `out`.
pub fn binary_into<T: Ops>(op: BinaryOp, x: &[T], y: &[T], out: &mut [T]) {
    let n = out.len();
    assert!((x.len() == n || x.len() == 1) && (y.len() == n || y.len() == 1));
    dispatch!(
        op,
        BinaryOp {
            Add,
            Sub,
            Mul,
            Div,
            Rem,
            Pow,
            Max,
            Min,
            Atan2,
            And,
            Or,
            Xor,
            ShiftLeft,
            ShiftRightLogical,
            ShiftRightArithmetic,
            Igamma,
            Igammac,
            IgammaGradA,
            RandomGammaGrad,
            Polygamma,
            Zeta,
        },
        |OP| {
            match (x.len() == n, y.len() == n) {
                (true, true) => {
                    for ((o, &a), &b) in out.iter_mut().zip(x).zip(y) {
                        *o = T::binary(OP, a, b);
                    }
                }
                (true, false) => {
                    let b = y[0];
                    for (o, &a) in out.iter_mut().zip(x) {
                        *o = T::binary(OP, a, b);
                    }
                }
                (false, true) => {
                    let a = x[0];
                    for (o, &b) in out.iter_mut().zip(y) {
                        *o = T::binary(OP, a, b);
                    }
                }
                (false, false) => {
                    let v = T::binary(OP, x[0], y[0]);
                    out.fill(v);
                }
            }
        }
    );
}

/// `x[i] = op(x[i], y[i])`, where `y` of length 1 stands for every element
/// (an elementwise operation written over its first operand).
///
/// # Panics
///
/// Panics if `y` has neither length 1 nor the length of `x`.
pub fn binary_assign<T: Ops>(op: BinaryOp, x: &mut [T], y: &[T]) {
    let n = x.len();
    assert!(y.len() == n || y.len() == 1);
    dispatch!(
        op,
        BinaryOp {
            Add,
            Sub,
            Mul,
            Div,
            Rem,
            Pow,
            Max,
            Min,
            Atan2,
            And,
            Or,
            Xor,
            ShiftLeft,
            ShiftRightLogical,
            ShiftRightArithmetic,
            Igamma,
            Igammac,
            IgammaGradA,
            RandomGammaGrad,
            Polygamma,
            Zeta,
        },
        |OP| {
            if y.len() == n {
                for (a, &b) in x.iter_mut().zip(y) {
                    *a = T::binary(OP, *a, b);
                }
            } else {
                let b = y[0];
                for a in x.iter_mut() {
                    *a = T::binary(OP, *a, b);
                }
            }
        }
    );
}

/// `out[i] = op(x[i], y[i])` for a comparison, where a slice of length 1
/// stands for every element.
///
/// # Panics
///
/// Panics if a length is neither 1 nor the length of `out`.
pub fn compare_into<T: Element>(op: CompareOp, x: &[T], y: &[T], out: &mut [bool]) {
    let n = out.len();
    assert!((x.len() == n || x.len() == 1) && (y.len() == n || y.len() == 1));
    dispatch!(
        op,
        CompareOp {
            Eq,
            Ne,
            Lt,
            Le,
            Gt,
            Ge
        },
        |OP| {
            match (x.len() == n, y.len() == n) {
                (true, true) => {
                    for ((o, &a), &b) in out.iter_mut().zip(x).zip(y) {
                        *o = compare(OP, a, b);
                    }
                }
                (true, false) => {
                    let b = y[0];
                    for (o, &a) in out.iter_mut().zip(x) {
                        *o = compare(OP, a, b);
                    }
                }
                (false, true) => {
                    let a = x[0];
                    for (o, &b) in out.iter_mut().zip(y) {
                        *o = compare(OP, a, b);
                    }
                }
                (false, false) => out.fill(compare(OP, x[0], y[0])),
            }
        }
    );
}

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

    /// The same value: equal bits, or both NaN (the bits of a NaN that an
    /// operation makes are not specified, and constant folding may give
    /// another sign than the hardware).
    fn same(a: f32, b: f32) -> bool {
        a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
    }

    #[test]
    fn max_and_min_order_signed_zeros_as_xla() {
        for (a, b) in [(0.0f32, -0.0f32), (-0.0, 0.0)] {
            assert!(f32::binary(BinaryOp::Max, a, b).is_sign_positive());
            assert!(f32::binary(BinaryOp::Min, a, b).is_sign_negative());
            assert!(f64::binary(BinaryOp::Max, f64::from(a), f64::from(b)).is_sign_positive());
            assert!(f64::binary(BinaryOp::Min, f64::from(a), f64::from(b)).is_sign_negative());
        }
        let mut out = [0.0f32; 2];
        binary_into(BinaryOp::Max, &[0.0, -0.0], &[-0.0, 0.0], &mut out);
        assert!(out.iter().all(|x| x.is_sign_positive()));
    }

    #[test]
    fn match_elementwise_ops() {
        let x = [1.5f32, -2.0, f32::NAN, 0.0, 7.25];
        let y = [0.5f32, 3.0, 1.0, -0.0, 7.25];
        for op in BinaryOp::ALL
            .into_iter()
            .filter(|op| op.supports(crate::DType::F32))
        {
            let mut out = [0.0f32; 5];
            binary_into(op, &x, &y, &mut out);
            for i in 0..5 {
                let e = f32::binary(op, x[i], y[i]);
                assert!(same(out[i], e), "{op:?}");
            }
            binary_into(op, &x, &y[..1], &mut out);
            for i in 0..5 {
                assert!(same(out[i], f32::binary(op, x[i], y[0])), "{op:?}");
            }
        }
        for op in UnaryOp::ALL
            .into_iter()
            .filter(|op| op.supports(crate::DType::F32))
        {
            let mut out = [0.0f32; 5];
            unary_into(op, &x, &mut out);
            for i in 0..5 {
                assert!(same(out[i], f32::unary(op, x[i])), "{op:?}");
            }
        }
        for op in CompareOp::ALL {
            let mut out = [false; 5];
            compare_into(op, &x[..1], &y, &mut out);
            for i in 0..5 {
                assert_eq!(out[i], compare(op, x[0], y[i]));
            }
        }
    }
}