Skip to main content

ruxla_kernels/
elementwise.rs

1//! Elementwise operations on slices.
2//!
3//! Each function dispatches on the operation once, outside the loop, so that
4//! the operation is inlined into the loop and the loop can be vectorized.
5//! The results are the same as applying [`Ops`] element by element.
6
7use crate::dtype::Element;
8use crate::ops::{BinaryOp, CompareOp, Ops, UnaryOp, compare};
9
10/// Expands `$body` once per variant of an operation enum, with `$op` bound
11/// to the variant as a constant.
12macro_rules! dispatch {
13    ($op:expr, $enum:ident { $($v:ident),* $(,)? }, |$c:ident| $body:expr) => {
14        match $op {
15            $($enum::$v => { const $c: $enum = $enum::$v; $body })*
16        }
17    };
18}
19
20/// `out[i] = op(x[i])`.
21///
22/// # Panics
23///
24/// Panics if the lengths differ.
25pub fn unary_into<T: Ops>(op: UnaryOp, x: &[T], out: &mut [T]) {
26    assert_eq!(x.len(), out.len());
27    dispatch!(
28        op,
29        UnaryOp {
30            Neg,
31            Abs,
32            Sign,
33            Not,
34            Floor,
35            Ceil,
36            Round,
37            RoundEven,
38            Exp,
39            Expm1,
40            Log,
41            Log1p,
42            Sqrt,
43            Rsqrt,
44            Cbrt,
45            Sin,
46            Cos,
47            Tan,
48            Tanh,
49            Logistic,
50            Square,
51            ErfInv,
52            Lgamma,
53            Digamma,
54            Erf,
55            Erfc,
56            BesselI0e,
57            BesselI1e,
58        },
59        |OP| {
60            for (o, &a) in out.iter_mut().zip(x) {
61                *o = T::unary(OP, a);
62            }
63        }
64    );
65}
66
67/// `x[i] = op(x[i])` (an elementwise operation written over its operand).
68pub fn unary_assign<T: Ops>(op: UnaryOp, x: &mut [T]) {
69    dispatch!(
70        op,
71        UnaryOp {
72            Neg,
73            Abs,
74            Sign,
75            Not,
76            Floor,
77            Ceil,
78            Round,
79            RoundEven,
80            Exp,
81            Expm1,
82            Log,
83            Log1p,
84            Sqrt,
85            Rsqrt,
86            Cbrt,
87            Sin,
88            Cos,
89            Tan,
90            Tanh,
91            Logistic,
92            Square,
93            ErfInv,
94            Lgamma,
95            Digamma,
96            Erf,
97            Erfc,
98            BesselI0e,
99            BesselI1e,
100        },
101        |OP| {
102            for a in x.iter_mut() {
103                *a = T::unary(OP, *a);
104            }
105        }
106    );
107}
108
109/// `out[i] = op(x[i], y[i])`, where a slice of length 1 stands for every
110/// element (a broadcast scalar).
111///
112/// # Panics
113///
114/// Panics if a length is neither 1 nor the length of `out`.
115pub fn binary_into<T: Ops>(op: BinaryOp, x: &[T], y: &[T], out: &mut [T]) {
116    let n = out.len();
117    assert!((x.len() == n || x.len() == 1) && (y.len() == n || y.len() == 1));
118    dispatch!(
119        op,
120        BinaryOp {
121            Add,
122            Sub,
123            Mul,
124            Div,
125            Rem,
126            Pow,
127            Max,
128            Min,
129            Atan2,
130            And,
131            Or,
132            Xor,
133            ShiftLeft,
134            ShiftRightLogical,
135            ShiftRightArithmetic,
136            Igamma,
137            Igammac,
138            IgammaGradA,
139            RandomGammaGrad,
140            Polygamma,
141            Zeta,
142        },
143        |OP| {
144            match (x.len() == n, y.len() == n) {
145                (true, true) => {
146                    for ((o, &a), &b) in out.iter_mut().zip(x).zip(y) {
147                        *o = T::binary(OP, a, b);
148                    }
149                }
150                (true, false) => {
151                    let b = y[0];
152                    for (o, &a) in out.iter_mut().zip(x) {
153                        *o = T::binary(OP, a, b);
154                    }
155                }
156                (false, true) => {
157                    let a = x[0];
158                    for (o, &b) in out.iter_mut().zip(y) {
159                        *o = T::binary(OP, a, b);
160                    }
161                }
162                (false, false) => {
163                    let v = T::binary(OP, x[0], y[0]);
164                    out.fill(v);
165                }
166            }
167        }
168    );
169}
170
171/// `x[i] = op(x[i], y[i])`, where `y` of length 1 stands for every element
172/// (an elementwise operation written over its first operand).
173///
174/// # Panics
175///
176/// Panics if `y` has neither length 1 nor the length of `x`.
177pub fn binary_assign<T: Ops>(op: BinaryOp, x: &mut [T], y: &[T]) {
178    let n = x.len();
179    assert!(y.len() == n || y.len() == 1);
180    dispatch!(
181        op,
182        BinaryOp {
183            Add,
184            Sub,
185            Mul,
186            Div,
187            Rem,
188            Pow,
189            Max,
190            Min,
191            Atan2,
192            And,
193            Or,
194            Xor,
195            ShiftLeft,
196            ShiftRightLogical,
197            ShiftRightArithmetic,
198            Igamma,
199            Igammac,
200            IgammaGradA,
201            RandomGammaGrad,
202            Polygamma,
203            Zeta,
204        },
205        |OP| {
206            if y.len() == n {
207                for (a, &b) in x.iter_mut().zip(y) {
208                    *a = T::binary(OP, *a, b);
209                }
210            } else {
211                let b = y[0];
212                for a in x.iter_mut() {
213                    *a = T::binary(OP, *a, b);
214                }
215            }
216        }
217    );
218}
219
220/// `out[i] = op(x[i], y[i])` for a comparison, where a slice of length 1
221/// stands for every element.
222///
223/// # Panics
224///
225/// Panics if a length is neither 1 nor the length of `out`.
226pub fn compare_into<T: Element>(op: CompareOp, x: &[T], y: &[T], out: &mut [bool]) {
227    let n = out.len();
228    assert!((x.len() == n || x.len() == 1) && (y.len() == n || y.len() == 1));
229    dispatch!(
230        op,
231        CompareOp {
232            Eq,
233            Ne,
234            Lt,
235            Le,
236            Gt,
237            Ge
238        },
239        |OP| {
240            match (x.len() == n, y.len() == n) {
241                (true, true) => {
242                    for ((o, &a), &b) in out.iter_mut().zip(x).zip(y) {
243                        *o = compare(OP, a, b);
244                    }
245                }
246                (true, false) => {
247                    let b = y[0];
248                    for (o, &a) in out.iter_mut().zip(x) {
249                        *o = compare(OP, a, b);
250                    }
251                }
252                (false, true) => {
253                    let a = x[0];
254                    for (o, &b) in out.iter_mut().zip(y) {
255                        *o = compare(OP, a, b);
256                    }
257                }
258                (false, false) => out.fill(compare(OP, x[0], y[0])),
259            }
260        }
261    );
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    /// The same value: equal bits, or both NaN (the bits of a NaN that an
269    /// operation makes are not specified, and constant folding may give
270    /// another sign than the hardware).
271    fn same(a: f32, b: f32) -> bool {
272        a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
273    }
274
275    #[test]
276    fn max_and_min_order_signed_zeros_as_xla() {
277        for (a, b) in [(0.0f32, -0.0f32), (-0.0, 0.0)] {
278            assert!(f32::binary(BinaryOp::Max, a, b).is_sign_positive());
279            assert!(f32::binary(BinaryOp::Min, a, b).is_sign_negative());
280            assert!(f64::binary(BinaryOp::Max, f64::from(a), f64::from(b)).is_sign_positive());
281            assert!(f64::binary(BinaryOp::Min, f64::from(a), f64::from(b)).is_sign_negative());
282        }
283        let mut out = [0.0f32; 2];
284        binary_into(BinaryOp::Max, &[0.0, -0.0], &[-0.0, 0.0], &mut out);
285        assert!(out.iter().all(|x| x.is_sign_positive()));
286    }
287
288    #[test]
289    fn match_elementwise_ops() {
290        let x = [1.5f32, -2.0, f32::NAN, 0.0, 7.25];
291        let y = [0.5f32, 3.0, 1.0, -0.0, 7.25];
292        for op in BinaryOp::ALL
293            .into_iter()
294            .filter(|op| op.supports(crate::DType::F32))
295        {
296            let mut out = [0.0f32; 5];
297            binary_into(op, &x, &y, &mut out);
298            for i in 0..5 {
299                let e = f32::binary(op, x[i], y[i]);
300                assert!(same(out[i], e), "{op:?}");
301            }
302            binary_into(op, &x, &y[..1], &mut out);
303            for i in 0..5 {
304                assert!(same(out[i], f32::binary(op, x[i], y[0])), "{op:?}");
305            }
306        }
307        for op in UnaryOp::ALL
308            .into_iter()
309            .filter(|op| op.supports(crate::DType::F32))
310        {
311            let mut out = [0.0f32; 5];
312            unary_into(op, &x, &mut out);
313            for i in 0..5 {
314                assert!(same(out[i], f32::unary(op, x[i])), "{op:?}");
315            }
316        }
317        for op in CompareOp::ALL {
318            let mut out = [false; 5];
319            compare_into(op, &x[..1], &y, &mut out);
320            for i in 0..5 {
321                assert_eq!(out[i], compare(op, x[0], y[i]));
322            }
323        }
324    }
325}