Skip to main content

ruxla_kernels/
ops.rs

1//! Elementwise operations, with XLA's semantics.
2
3use half::{bf16, f16};
4
5use crate::dtype::{DType, DTypeKind, Element};
6
7/// An elementwise operation with one operand and a result of the same type.
8#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
9pub enum UnaryOp {
10    /// `-x` (integers wrap around).
11    Neg,
12    /// `|x|` (integers wrap around).
13    Abs,
14    /// -1, 0, or 1 (NaN for NaN, and the sign of zero is kept).
15    Sign,
16    /// Logical or bitwise not.
17    Not,
18    /// Round toward negative infinity.
19    Floor,
20    /// Round toward positive infinity.
21    Ceil,
22    /// Round to the nearest integer, halfway cases away from zero.
23    Round,
24    /// Round to the nearest integer, halfway cases to even.
25    RoundEven,
26    /// `e^x`.
27    Exp,
28    /// `e^x - 1`.
29    Expm1,
30    /// Natural logarithm.
31    Log,
32    /// `log(1 + x)`.
33    Log1p,
34    /// Square root.
35    Sqrt,
36    /// `1 / sqrt(x)`.
37    Rsqrt,
38    /// Cube root.
39    Cbrt,
40    /// Sine.
41    Sin,
42    /// Cosine.
43    Cos,
44    /// Tangent.
45    Tan,
46    /// Hyperbolic tangent.
47    Tanh,
48    /// `1 / (1 + e^-x)`.
49    Logistic,
50    /// `x * x` (integers wrap around).
51    Square,
52    /// The inverse of the error function.
53    ErfInv,
54    /// The logarithm of the absolute value of the gamma function.
55    Lgamma,
56    /// The digamma function, the derivative of `lgamma`.
57    Digamma,
58    /// The error function.
59    Erf,
60    /// The complementary error function, `1 - erf(x)`.
61    Erfc,
62    /// The exponentially scaled modified Bessel function of order 0,
63    /// `exp(-|x|) I0(x)`.
64    BesselI0e,
65    /// The exponentially scaled modified Bessel function of order 1,
66    /// `exp(-|x|) I1(x)`.
67    BesselI1e,
68}
69
70/// An elementwise operation with two operands of the same type and a result
71/// of that type.
72#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
73pub enum BinaryOp {
74    /// `x + y` (integers wrap around).
75    Add,
76    /// `x - y` (integers wrap around).
77    Sub,
78    /// `x * y` (integers wrap around).
79    Mul,
80    /// `x / y`. Integer division rounds toward zero; division by zero gives
81    /// -1 (signed) or the maximum (unsigned), and `MIN / -1` gives `MIN`.
82    Div,
83    /// The remainder of truncated division, with the sign of `x`.
84    /// `x % 0` is `x` for integers.
85    Rem,
86    /// `x^y` (floats).
87    Pow,
88    /// The maximum, propagating NaN.
89    Max,
90    /// The minimum, propagating NaN.
91    Min,
92    /// `atan2(x, y)`.
93    Atan2,
94    /// Logical or bitwise and.
95    And,
96    /// Logical or bitwise or.
97    Or,
98    /// Logical or bitwise exclusive or.
99    Xor,
100    /// `x << y`; shifts by the bit width or more give 0.
101    ShiftLeft,
102    /// `x >> y` filling with zeros; shifts by the bit width or more give 0.
103    ShiftRightLogical,
104    /// `x >> y` filling with the sign bit; shifts by the bit width or more
105    /// give 0 or -1.
106    ShiftRightArithmetic,
107    /// The regularized lower incomplete gamma function `P(x, y)`.
108    Igamma,
109    /// The regularized upper incomplete gamma function `Q(x, y)`.
110    Igammac,
111    /// The derivative of `igamma(x, y)` with respect to `x`.
112    IgammaGradA,
113    /// The derivative of a sample `y` of `Gamma(x, 1)` with respect to `x`.
114    RandomGammaGrad,
115    /// The polygamma function `psi^(x)(y)` (`x` a natural number).
116    Polygamma,
117    /// The Hurwitz zeta function `zeta(x, y)`.
118    Zeta,
119}
120
121/// An elementwise operation with three operands of the same type and a
122/// result of that type.
123#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
124pub enum TernaryOp {
125    /// The regularized incomplete beta function `I_z(x, y)` of `(x, y, z)`.
126    RegularizedIncompleteBeta,
127}
128
129/// A comparison.
130#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
131pub enum CompareOp {
132    /// `x == y`.
133    Eq,
134    /// `x != y` (true if either is NaN).
135    Ne,
136    /// `x < y`.
137    Lt,
138    /// `x <= y`.
139    Le,
140    /// `x > y`.
141    Gt,
142    /// `x >= y`.
143    Ge,
144}
145
146impl UnaryOp {
147    /// Every unary operation.
148    pub const ALL: [UnaryOp; 28] = [
149        UnaryOp::Neg,
150        UnaryOp::Abs,
151        UnaryOp::Sign,
152        UnaryOp::Not,
153        UnaryOp::Floor,
154        UnaryOp::Ceil,
155        UnaryOp::Round,
156        UnaryOp::RoundEven,
157        UnaryOp::Exp,
158        UnaryOp::Expm1,
159        UnaryOp::Log,
160        UnaryOp::Log1p,
161        UnaryOp::Sqrt,
162        UnaryOp::Rsqrt,
163        UnaryOp::Cbrt,
164        UnaryOp::Sin,
165        UnaryOp::Cos,
166        UnaryOp::Tan,
167        UnaryOp::Tanh,
168        UnaryOp::Logistic,
169        UnaryOp::Square,
170        UnaryOp::ErfInv,
171        UnaryOp::Lgamma,
172        UnaryOp::Digamma,
173        UnaryOp::Erf,
174        UnaryOp::Erfc,
175        UnaryOp::BesselI0e,
176        UnaryOp::BesselI1e,
177    ];
178
179    /// The name of the primitive, as in JAX.
180    pub fn name(self) -> &'static str {
181        match self {
182            UnaryOp::Neg => "neg",
183            UnaryOp::Abs => "abs",
184            UnaryOp::Sign => "sign",
185            UnaryOp::Not => "not",
186            UnaryOp::Floor => "floor",
187            UnaryOp::Ceil => "ceil",
188            UnaryOp::Round => "round",
189            UnaryOp::RoundEven => "round_even",
190            UnaryOp::Exp => "exp",
191            UnaryOp::Expm1 => "expm1",
192            UnaryOp::Log => "log",
193            UnaryOp::Log1p => "log1p",
194            UnaryOp::Sqrt => "sqrt",
195            UnaryOp::Rsqrt => "rsqrt",
196            UnaryOp::Cbrt => "cbrt",
197            UnaryOp::Sin => "sin",
198            UnaryOp::Cos => "cos",
199            UnaryOp::Tan => "tan",
200            UnaryOp::Tanh => "tanh",
201            UnaryOp::Logistic => "logistic",
202            UnaryOp::Square => "square",
203            UnaryOp::ErfInv => "erf_inv",
204            UnaryOp::Lgamma => "lgamma",
205            UnaryOp::Digamma => "digamma",
206            UnaryOp::Erf => "erf",
207            UnaryOp::Erfc => "erfc",
208            UnaryOp::BesselI0e => "bessel_i0e",
209            UnaryOp::BesselI1e => "bessel_i1e",
210        }
211    }
212
213    /// Returns whether the operation accepts `dtype`.
214    pub fn supports(self, dtype: DType) -> bool {
215        use DTypeKind::*;
216        let kind = dtype.kind();
217        match self {
218            UnaryOp::Not => matches!(kind, Bool | SignedInt | UnsignedInt),
219            // As in `lax.abs`, unsigned integers are rejected (`jnp.abs`
220            // returns them unchanged). The `abs` of a complex number is real.
221            UnaryOp::Abs => matches!(kind, SignedInt | Float | Complex),
222            UnaryOp::Neg | UnaryOp::Sign | UnaryOp::Square => kind != Bool,
223            UnaryOp::Exp
224            | UnaryOp::Expm1
225            | UnaryOp::Log
226            | UnaryOp::Log1p
227            | UnaryOp::Sqrt
228            | UnaryOp::Rsqrt
229            | UnaryOp::Sin
230            | UnaryOp::Cos
231            | UnaryOp::Tan
232            | UnaryOp::Tanh
233            | UnaryOp::Logistic => matches!(kind, Float | Complex),
234            _ => kind == Float,
235        }
236    }
237}
238
239impl BinaryOp {
240    /// Whether `op(a, b)` is `op(b, a)` bit for bit for every element type
241    /// (addition and multiplication, also of floats, and the bitwise
242    /// operations; not `max` and `min`, whose NaN handling may depend on
243    /// the order).
244    pub fn is_commutative(self) -> bool {
245        matches!(
246            self,
247            BinaryOp::Add | BinaryOp::Mul | BinaryOp::And | BinaryOp::Or | BinaryOp::Xor
248        )
249    }
250
251    /// Every binary operation.
252    pub const ALL: [BinaryOp; 21] = [
253        BinaryOp::Add,
254        BinaryOp::Sub,
255        BinaryOp::Mul,
256        BinaryOp::Div,
257        BinaryOp::Rem,
258        BinaryOp::Pow,
259        BinaryOp::Max,
260        BinaryOp::Min,
261        BinaryOp::Atan2,
262        BinaryOp::And,
263        BinaryOp::Or,
264        BinaryOp::Xor,
265        BinaryOp::ShiftLeft,
266        BinaryOp::ShiftRightLogical,
267        BinaryOp::ShiftRightArithmetic,
268        BinaryOp::Igamma,
269        BinaryOp::Igammac,
270        BinaryOp::IgammaGradA,
271        BinaryOp::RandomGammaGrad,
272        BinaryOp::Polygamma,
273        BinaryOp::Zeta,
274    ];
275
276    /// The name of the primitive, as in JAX.
277    pub fn name(self) -> &'static str {
278        match self {
279            BinaryOp::Add => "add",
280            BinaryOp::Sub => "sub",
281            BinaryOp::Mul => "mul",
282            BinaryOp::Div => "div",
283            BinaryOp::Rem => "rem",
284            BinaryOp::Pow => "pow",
285            BinaryOp::Max => "max",
286            BinaryOp::Min => "min",
287            BinaryOp::Atan2 => "atan2",
288            BinaryOp::And => "and",
289            BinaryOp::Or => "or",
290            BinaryOp::Xor => "xor",
291            BinaryOp::ShiftLeft => "shift_left",
292            BinaryOp::ShiftRightLogical => "shift_right_logical",
293            BinaryOp::ShiftRightArithmetic => "shift_right_arithmetic",
294            BinaryOp::Igamma => "igamma",
295            BinaryOp::Igammac => "igammac",
296            BinaryOp::IgammaGradA => "igamma_grad_a",
297            BinaryOp::RandomGammaGrad => "random_gamma_grad",
298            BinaryOp::Polygamma => "polygamma",
299            BinaryOp::Zeta => "zeta",
300        }
301    }
302
303    /// Returns whether the operation accepts `dtype`.
304    pub fn supports(self, dtype: DType) -> bool {
305        use DTypeKind::*;
306        let kind = dtype.kind();
307        match self {
308            BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div => kind != Bool,
309            BinaryOp::Rem => !matches!(kind, Bool | Complex),
310            BinaryOp::Max | BinaryOp::Min => true,
311            BinaryOp::Pow => matches!(kind, Float | Complex),
312            BinaryOp::Atan2
313            | BinaryOp::Igamma
314            | BinaryOp::Igammac
315            | BinaryOp::IgammaGradA
316            | BinaryOp::RandomGammaGrad
317            | BinaryOp::Polygamma
318            | BinaryOp::Zeta => kind == Float,
319            BinaryOp::And | BinaryOp::Or | BinaryOp::Xor => {
320                matches!(kind, Bool | SignedInt | UnsignedInt)
321            }
322            BinaryOp::ShiftLeft | BinaryOp::ShiftRightLogical | BinaryOp::ShiftRightArithmetic => {
323                matches!(kind, SignedInt | UnsignedInt)
324            }
325        }
326    }
327}
328
329impl TernaryOp {
330    /// Every ternary operation.
331    pub const ALL: [TernaryOp; 1] = [TernaryOp::RegularizedIncompleteBeta];
332
333    /// The name of the primitive, as in JAX.
334    pub fn name(self) -> &'static str {
335        match self {
336            TernaryOp::RegularizedIncompleteBeta => "regularized_incomplete_beta",
337        }
338    }
339
340    /// Returns whether the operation accepts `dtype`.
341    pub fn supports(self, dtype: DType) -> bool {
342        dtype.kind() == DTypeKind::Float
343    }
344}
345
346impl CompareOp {
347    /// Every comparison.
348    pub const ALL: [CompareOp; 6] = [
349        CompareOp::Eq,
350        CompareOp::Ne,
351        CompareOp::Lt,
352        CompareOp::Le,
353        CompareOp::Gt,
354        CompareOp::Ge,
355    ];
356
357    /// The name of the primitive, as in JAX.
358    pub fn name(self) -> &'static str {
359        match self {
360            CompareOp::Eq => "eq",
361            CompareOp::Ne => "ne",
362            CompareOp::Lt => "lt",
363            CompareOp::Le => "le",
364            CompareOp::Gt => "gt",
365            CompareOp::Ge => "ge",
366        }
367    }
368
369    /// Returns whether the comparison accepts `dtype`: complex numbers
370    /// have only `eq` and `ne`, as in JAX.
371    pub fn supports(self, dtype: DType) -> bool {
372        !dtype.is_complex() || matches!(self, CompareOp::Eq | CompareOp::Ne)
373    }
374}
375
376/// Elementwise operations on one element type. Calling an operation that
377/// the type does not support (see [`UnaryOp::supports`]) panics; callers
378/// check the types first.
379pub trait Ops: Copy {
380    /// Applies a unary operation.
381    fn unary(op: UnaryOp, x: Self) -> Self;
382    /// Applies a binary operation.
383    fn binary(op: BinaryOp, x: Self, y: Self) -> Self;
384    /// Applies a ternary operation (only floats support them).
385    fn ternary(op: TernaryOp, x: Self, y: Self, z: Self) -> Self {
386        let _ = (x, y, z);
387        panic!("{} accepts only floats", op.name())
388    }
389    /// Returns whether the value is neither infinite nor NaN (always true
390    /// for integers and booleans).
391    fn is_finite(x: Self) -> bool;
392    /// The smallest value (negative infinity for floats): the identity of
393    /// `max`.
394    fn lowest() -> Self;
395    /// The largest value (positive infinity for floats): the identity of
396    /// `min`.
397    fn highest() -> Self;
398}
399
400/// Compares two values (floats follow IEEE 754: comparisons with NaN are
401/// false, except `Ne`).
402#[inline]
403pub fn compare<T: Element>(op: CompareOp, x: T, y: T) -> bool {
404    match op {
405        CompareOp::Eq => x == y,
406        CompareOp::Ne => x != y,
407        CompareOp::Lt => x < y,
408        CompareOp::Le => x <= y,
409        CompareOp::Gt => x > y,
410        CompareOp::Ge => x >= y,
411    }
412}
413
414/// `x^y` for an integer exponent, by repeated squaring in the same order as
415/// JAX's lowering of `integer_pow` (which fixes the rounding of floats).
416/// Negative exponents take the reciprocal at the end.
417#[inline]
418pub fn integer_pow<T: Element>(x: T, y: i32) -> T {
419    let one: T = crate::dtype::cast(1u8);
420    if y == 0 {
421        return one;
422    }
423    let mut n = y.unsigned_abs();
424    let mut base = x;
425    let mut acc: Option<T> = None;
426    while n > 0 {
427        if n & 1 == 1 {
428            acc = Some(match acc {
429                None => base,
430                Some(a) => T::binary(BinaryOp::Mul, a, base),
431            });
432        }
433        n >>= 1;
434        if n > 0 {
435            base = T::binary(BinaryOp::Mul, base, base);
436        }
437    }
438    let acc = acc.expect("the exponent is not zero");
439    if y < 0 {
440        T::binary(BinaryOp::Div, one, acc)
441    } else {
442        acc
443    }
444}
445
446fn unsupported(op: &str, dtype: DType) -> ! {
447    panic!("{op} does not accept {dtype} operands")
448}
449
450macro_rules! impl_signed {
451    ($($t:ty, $u:ty;)*) => {$(
452        impl Ops for $t {
453            #[inline]
454            fn unary(op: UnaryOp, x: Self) -> Self {
455                match op {
456                    UnaryOp::Neg => x.wrapping_neg(),
457                    UnaryOp::Abs => x.wrapping_abs(),
458                    UnaryOp::Sign => x.signum(),
459                    UnaryOp::Not => !x,
460                    UnaryOp::Square => x.wrapping_mul(x),
461                    _ => unsupported(op.name(), Self::DTYPE),
462                }
463            }
464            #[inline]
465            fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
466                const BITS: $t = <$t>::BITS as $t;
467                match op {
468                    BinaryOp::Add => x.wrapping_add(y),
469                    BinaryOp::Sub => x.wrapping_sub(y),
470                    BinaryOp::Mul => x.wrapping_mul(y),
471                    BinaryOp::Div => {
472                        if y == 0 {
473                            -1
474                        } else {
475                            x.wrapping_div(y)
476                        }
477                    }
478                    BinaryOp::Rem => {
479                        if y == 0 {
480                            x
481                        } else {
482                            x.wrapping_rem(y)
483                        }
484                    }
485                    BinaryOp::Max => x.max(y),
486                    BinaryOp::Min => x.min(y),
487                    BinaryOp::And => x & y,
488                    BinaryOp::Or => x | y,
489                    BinaryOp::Xor => x ^ y,
490                    BinaryOp::ShiftLeft => {
491                        if (0..BITS).contains(&y) { x << y } else { 0 }
492                    }
493                    BinaryOp::ShiftRightLogical => {
494                        if (0..BITS).contains(&y) { ((x as $u) >> y) as $t } else { 0 }
495                    }
496                    BinaryOp::ShiftRightArithmetic => {
497                        if (0..BITS).contains(&y) {
498                            x >> y
499                        } else if x < 0 {
500                            -1
501                        } else {
502                            0
503                        }
504                    }
505                    _ => unsupported(op.name(), Self::DTYPE),
506                }
507            }
508            #[inline]
509            fn is_finite(_: Self) -> bool {
510                true
511            }
512            fn lowest() -> Self {
513                <$t>::MIN
514            }
515            fn highest() -> Self {
516                <$t>::MAX
517            }
518        }
519    )*};
520}
521
522impl_signed! {
523    i8, u8;
524    i16, u16;
525    i32, u32;
526    i64, u64;
527}
528
529macro_rules! impl_unsigned {
530    ($($t:ty, $s:ty;)*) => {$(
531        impl Ops for $t {
532            #[inline]
533            fn unary(op: UnaryOp, x: Self) -> Self {
534                match op {
535                    UnaryOp::Neg => x.wrapping_neg(),
536                    UnaryOp::Abs => x,
537                    UnaryOp::Sign => <$t>::from(x != 0),
538                    UnaryOp::Not => !x,
539                    UnaryOp::Square => x.wrapping_mul(x),
540                    _ => unsupported(op.name(), Self::DTYPE),
541                }
542            }
543            #[inline]
544            fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
545                const BITS: $t = <$t>::BITS as $t;
546                match op {
547                    BinaryOp::Add => x.wrapping_add(y),
548                    BinaryOp::Sub => x.wrapping_sub(y),
549                    BinaryOp::Mul => x.wrapping_mul(y),
550                    BinaryOp::Div => x.checked_div(y).unwrap_or(<$t>::MAX),
551                    BinaryOp::Rem => x.checked_rem(y).unwrap_or(x),
552                    BinaryOp::Max => x.max(y),
553                    BinaryOp::Min => x.min(y),
554                    BinaryOp::And => x & y,
555                    BinaryOp::Or => x | y,
556                    BinaryOp::Xor => x ^ y,
557                    BinaryOp::ShiftLeft => if y < BITS { x << y } else { 0 },
558                    BinaryOp::ShiftRightLogical => if y < BITS { x >> y } else { 0 },
559                    // XLA shifts the bits as a signed integer of the same
560                    // size, filling with the top bit.
561                    BinaryOp::ShiftRightArithmetic => {
562                        ((x as $s) >> y.min(BITS - 1)) as $t
563                    }
564                    _ => unsupported(op.name(), Self::DTYPE),
565                }
566            }
567            #[inline]
568            fn is_finite(_: Self) -> bool {
569                true
570            }
571            fn lowest() -> Self {
572                0
573            }
574            fn highest() -> Self {
575                <$t>::MAX
576            }
577        }
578    )*};
579}
580
581impl_unsigned! {
582    u8, i8;
583    u16, i16;
584    u32, i32;
585    u64, i64;
586}
587
588impl Ops for bool {
589    #[inline]
590    fn unary(op: UnaryOp, x: Self) -> Self {
591        match op {
592            UnaryOp::Not => !x,
593            _ => unsupported(op.name(), DType::Bool),
594        }
595    }
596    #[inline]
597    fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
598        match op {
599            BinaryOp::And | BinaryOp::Min => x & y,
600            BinaryOp::Or | BinaryOp::Max => x | y,
601            BinaryOp::Xor => x ^ y,
602            _ => unsupported(op.name(), DType::Bool),
603        }
604    }
605    #[inline]
606    fn is_finite(_: Self) -> bool {
607        true
608    }
609    fn lowest() -> Self {
610        false
611    }
612    fn highest() -> Self {
613        true
614    }
615}
616
617/// The argument of a function of the C math library, hidden from the
618/// optimizer on Apple targets. There LLVM replaces such calls with other
619/// implementations depending on the surrounding code: it merges a `sin` and
620/// a `cos` of the same value into one call of the system's `sincos`, and it
621/// vectorizes calls in loops with the vector functions of `libsystem_m`.
622/// Their results can differ in the last bit from the scalar functions, so
623/// the native backend, the interpreter and code compiled ahead of time would
624/// round differently. Hiding the argument keeps every call a plain scalar
625/// call. Elsewhere nothing changes (glibc's `sincos` matches its `sin` and
626/// `cos`, and Rust does not vectorize math calls there).
627#[inline(always)]
628fn libm_arg<T>(x: T) -> T {
629    #[cfg(target_vendor = "apple")]
630    {
631        std::hint::black_box(x)
632    }
633    #[cfg(not(target_vendor = "apple"))]
634    {
635        x
636    }
637}
638
639macro_rules! impl_float {
640    ($($t:ty;)*) => {$(
641        impl Ops for $t {
642            #[inline]
643            fn unary(op: UnaryOp, x: Self) -> Self {
644                match op {
645                    UnaryOp::Neg => -x,
646                    UnaryOp::Abs => x.abs(),
647                    UnaryOp::Sign => {
648                        if x.is_nan() || x == 0.0 { x } else { x.signum() }
649                    }
650                    UnaryOp::Floor => x.floor(),
651                    UnaryOp::Ceil => x.ceil(),
652                    UnaryOp::Round => x.round(),
653                    UnaryOp::RoundEven => x.round_ties_even(),
654                    UnaryOp::Exp => libm_arg(x).exp(),
655                    UnaryOp::Expm1 => libm_arg(x).exp_m1(),
656                    UnaryOp::Log => libm_arg(x).ln(),
657                    UnaryOp::Log1p => libm_arg(x).ln_1p(),
658                    UnaryOp::Sqrt => x.sqrt(),
659                    UnaryOp::Rsqrt => 1.0 / x.sqrt(),
660                    UnaryOp::Cbrt => libm_arg(x).cbrt(),
661                    UnaryOp::Sin => libm_arg(x).sin(),
662                    UnaryOp::Cos => libm_arg(x).cos(),
663                    UnaryOp::Tan => libm_arg(x).tan(),
664                    UnaryOp::Tanh => libm_arg(x).tanh(),
665                    UnaryOp::Logistic => 1.0 / (1.0 + libm_arg(-x).exp()),
666                    UnaryOp::Square => x * x,
667                    UnaryOp::ErfInv
668                    | UnaryOp::Lgamma
669                    | UnaryOp::Digamma
670                    | UnaryOp::Erf
671                    | UnaryOp::Erfc
672                    | UnaryOp::BesselI0e
673                    | UnaryOp::BesselI1e => crate::special::unary(op, x),
674                    UnaryOp::Not => unsupported(op.name(), Self::DTYPE),
675                }
676            }
677            #[inline]
678            fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
679                match op {
680                    BinaryOp::Add => x + y,
681                    BinaryOp::Sub => x - y,
682                    BinaryOp::Mul => x * y,
683                    BinaryOp::Div => x / y,
684                    BinaryOp::Rem => libm_arg(x) % y,
685                    BinaryOp::Pow => libm_arg(x).powf(y),
686                    // As XLA: NaN if either is NaN, and -0 below +0 (equal
687                    // values have the same bits but for the sign of zero,
688                    // which `&` and `|` of the bits pick). `f32::max` leaves
689                    // the zero it returns unspecified.
690                    BinaryOp::Max => if x.is_nan() || y.is_nan() {
691                        <$t>::NAN
692                    } else if x == y {
693                        <$t>::from_bits(x.to_bits() & y.to_bits())
694                    } else if x > y { x } else { y },
695                    BinaryOp::Min => if x.is_nan() || y.is_nan() {
696                        <$t>::NAN
697                    } else if x == y {
698                        <$t>::from_bits(x.to_bits() | y.to_bits())
699                    } else if x < y { x } else { y },
700                    BinaryOp::Atan2 => libm_arg(x).atan2(y),
701                    BinaryOp::Igamma
702                    | BinaryOp::Igammac
703                    | BinaryOp::IgammaGradA
704                    | BinaryOp::RandomGammaGrad
705                    | BinaryOp::Polygamma
706                    | BinaryOp::Zeta => crate::special::binary(op, x, y),
707                    _ => unsupported(op.name(), Self::DTYPE),
708                }
709            }
710            #[inline]
711            fn ternary(op: TernaryOp, x: Self, y: Self, z: Self) -> Self {
712                match op {
713                    TernaryOp::RegularizedIncompleteBeta => crate::special::betainc(x, y, z),
714                }
715            }
716            #[inline]
717            fn is_finite(x: Self) -> bool {
718                x.is_finite()
719            }
720            fn lowest() -> Self {
721                <$t>::NEG_INFINITY
722            }
723            fn highest() -> Self {
724                <$t>::INFINITY
725            }
726        }
727    )*};
728}
729
730impl_float! {
731    f32;
732    f64;
733}
734
735macro_rules! impl_half {
736    ($($t:ty;)*) => {$(
737        impl Ops for $t {
738            // 16-bit floats are computed in f32 and rounded back, as XLA does.
739            #[inline]
740            fn unary(op: UnaryOp, x: Self) -> Self {
741                <$t>::from_f32(f32::unary(op, x.to_f32()))
742            }
743            #[inline]
744            fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
745                <$t>::from_f32(f32::binary(op, x.to_f32(), y.to_f32()))
746            }
747            #[inline]
748            fn ternary(op: TernaryOp, x: Self, y: Self, z: Self) -> Self {
749                <$t>::from_f32(f32::ternary(op, x.to_f32(), y.to_f32(), z.to_f32()))
750            }
751            #[inline]
752            fn is_finite(x: Self) -> bool {
753                x.is_finite()
754            }
755            fn lowest() -> Self {
756                <$t>::NEG_INFINITY
757            }
758            fn highest() -> Self {
759                <$t>::INFINITY
760            }
761        }
762    )*};
763}
764
765impl_half! {
766    f16;
767    bf16;
768}
769
770macro_rules! impl_complex {
771    ($($t:ty, $f:ty;)*) => {$(
772        impl Ops for $t {
773            #[inline]
774            fn unary(op: UnaryOp, x: Self) -> Self {
775                match op {
776                    UnaryOp::Neg => -x,
777                    // The magnitude, as a complex number with a zero
778                    // imaginary part (the primitive returns the real part).
779                    UnaryOp::Abs => Self::new(x.abs(), 0.0),
780                    UnaryOp::Sign => x.sign(),
781                    UnaryOp::Exp => x.exp(),
782                    UnaryOp::Expm1 => x.expm1(),
783                    UnaryOp::Log => x.log(),
784                    UnaryOp::Log1p => x.log1p(),
785                    UnaryOp::Sqrt => x.sqrt(),
786                    UnaryOp::Rsqrt => x.rsqrt(),
787                    UnaryOp::Sin => x.sin(),
788                    UnaryOp::Cos => x.cos(),
789                    UnaryOp::Tan => x.tan(),
790                    UnaryOp::Tanh => x.tanh(),
791                    UnaryOp::Logistic => x.logistic(),
792                    UnaryOp::Square => x * x,
793                    _ => unsupported(op.name(), Self::DTYPE),
794                }
795            }
796            #[inline]
797            fn binary(op: BinaryOp, x: Self, y: Self) -> Self {
798                match op {
799                    BinaryOp::Add => x + y,
800                    BinaryOp::Sub => x - y,
801                    BinaryOp::Mul => x * y,
802                    BinaryOp::Div => x / y,
803                    BinaryOp::Pow => x.pow(y),
804                    BinaryOp::Max => x.max(y),
805                    BinaryOp::Min => x.min(y),
806                    _ => unsupported(op.name(), Self::DTYPE),
807                }
808            }
809            #[inline]
810            fn is_finite(x: Self) -> bool {
811                x.is_finite()
812            }
813            fn lowest() -> Self {
814                Self::new(<$f>::NEG_INFINITY, <$f>::NEG_INFINITY)
815            }
816            fn highest() -> Self {
817                Self::new(<$f>::INFINITY, <$f>::INFINITY)
818            }
819        }
820    )*};
821}
822
823impl_complex! {
824    crate::c64, f32;
825    crate::c128, f64;
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831
832    #[test]
833    fn integer_edge_cases_follow_xla() {
834        assert_eq!(i32::binary(BinaryOp::Div, 7, 0), -1);
835        assert_eq!(i32::binary(BinaryOp::Div, i32::MIN, -1), i32::MIN);
836        assert_eq!(i32::binary(BinaryOp::Rem, 7, 0), 7);
837        assert_eq!(i32::binary(BinaryOp::Rem, i32::MIN, -1), 0);
838        assert_eq!(u8::binary(BinaryOp::Div, 7, 0), u8::MAX);
839        assert_eq!(i32::binary(BinaryOp::Add, i32::MAX, 1), i32::MIN);
840        assert_eq!(i32::binary(BinaryOp::ShiftLeft, 1, 32), 0);
841        assert_eq!(i32::binary(BinaryOp::ShiftLeft, 1, -1), 0);
842        assert_eq!(i32::binary(BinaryOp::ShiftRightArithmetic, -8, 40), -1);
843        assert_eq!(i32::binary(BinaryOp::ShiftRightLogical, -1, 28), 15);
844        assert_eq!(u32::binary(BinaryOp::ShiftRightLogical, 8, 32), 0);
845        // Arithmetic shifts of unsigned integers fill with the top bit, as
846        // in XLA.
847        assert_eq!(u8::binary(BinaryOp::ShiftRightArithmetic, 0x80, 7), 0xFF);
848        assert_eq!(u8::binary(BinaryOp::ShiftRightArithmetic, 0x40, 200), 0);
849        assert_eq!(
850            u32::binary(BinaryOp::ShiftRightArithmetic, u32::MAX, 1),
851            u32::MAX
852        );
853        assert!(!UnaryOp::Abs.supports(DType::U8));
854        assert_eq!(i32::unary(UnaryOp::Abs, i32::MIN), i32::MIN);
855    }
856
857    #[test]
858    fn float_edge_cases_follow_xla() {
859        assert!(f32::binary(BinaryOp::Max, 1.0, f32::NAN).is_nan());
860        assert!(f32::binary(BinaryOp::Min, f32::NAN, 1.0).is_nan());
861        assert_eq!(f32::binary(BinaryOp::Rem, -7.0, 3.0), -1.0);
862        assert_eq!(
863            f32::unary(UnaryOp::Sign, -0.0).to_bits(),
864            (-0.0f32).to_bits()
865        );
866        assert!(f32::unary(UnaryOp::Sign, f32::NAN).is_nan());
867        assert_eq!(f32::unary(UnaryOp::Round, 2.5), 3.0);
868        assert_eq!(f32::unary(UnaryOp::RoundEven, 2.5), 2.0);
869        assert_eq!(f64::unary(UnaryOp::ErfInv, 0.0), 0.0);
870        assert!((f64::unary(UnaryOp::ErfInv, 0.5) - 0.476_936_276_204_47).abs() < 1e-12);
871        assert!(!compare(CompareOp::Eq, f32::NAN, f32::NAN));
872        assert!(compare(CompareOp::Ne, f32::NAN, f32::NAN));
873        assert_eq!(
874            bf16::binary(BinaryOp::Add, bf16::ONE, bf16::ONE),
875            bf16::from_f32(2.0)
876        );
877    }
878
879    #[test]
880    fn support_tables() {
881        assert!(UnaryOp::Not.supports(DType::Bool));
882        assert!(!UnaryOp::Sin.supports(DType::I32));
883        assert!(BinaryOp::Max.supports(DType::Bool));
884        assert!(!BinaryOp::Add.supports(DType::Bool));
885        assert!(!BinaryOp::ShiftLeft.supports(DType::F32));
886    }
887
888    #[test]
889    fn integer_powers() {
890        assert_eq!(integer_pow(3i32, 5), 243);
891        assert_eq!(integer_pow(2.0f32, -2), 0.25);
892        assert_eq!(integer_pow(7u8, 0), 1);
893    }
894}