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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Complex numbers: the element types [`c64`] and [`c128`].
//!
//! The arithmetic follows XLA's CPU implementation (`ElementalIrEmitter`)
//! where JAX lowers an operation to the StableHLO operation of the same
//! name, and JAX's own formulas where JAX lowers it otherwise (`abs` with
//! [`hypot`](Complex::abs), `sin`, and `cos`).

/// A complex number with real and imaginary parts of type `F`.
///
/// It orders lexicographically (by the real part, then the imaginary part),
/// as `lax.max`, `lax.min`, and `lax.sort` compare complex numbers.
#[derive(Clone, Copy, Default, PartialEq, PartialOrd, Debug)]
#[repr(C)]
pub struct Complex<F> {
    /// The real part.
    pub re: F,
    /// The imaginary part.
    pub im: F,
}

/// A complex number made of two `f32`s (`complex64`).
#[allow(non_camel_case_types)] // named like the other element types
pub type c64 = Complex<f32>;

/// A complex number made of two `f64`s (`complex128`).
#[allow(non_camel_case_types)] // named like the other element types
pub type c128 = Complex<f64>;

impl<F> Complex<F> {
    /// Creates a complex number from its real and imaginary parts.
    pub const fn new(re: F, im: F) -> Self {
        Self { re, im }
    }
}

use std::ops::{Add, Div, Neg};

macro_rules! impl_complex {
    ($f:ident, $k:expr, $e_hi:expr) => {
        impl std::ops::Add for Complex<$f> {
            type Output = Self;
            /// `x + y`.
            #[inline]
            fn add(self, o: Self) -> Self {
                Self::new(self.re + o.re, self.im + o.im)
            }
        }

        impl std::ops::Sub for Complex<$f> {
            type Output = Self;
            /// `x - y`.
            #[inline]
            fn sub(self, o: Self) -> Self {
                Self::new(self.re - o.re, self.im - o.im)
            }
        }

        impl std::ops::Mul for Complex<$f> {
            type Output = Self;
            /// `x * y`, with the multiplications and additions fused as XLA
            /// does on CPU.
            #[inline]
            fn mul(self, o: Self) -> Self {
                Self::new(
                    self.re.mul_add(o.re, -(self.im * o.im)),
                    self.im.mul_add(o.re, self.re * o.im),
                )
            }
        }

        impl std::ops::Neg for Complex<$f> {
            type Output = Self;
            /// `-x`.
            #[inline]
            fn neg(self) -> Self {
                Self::new(-self.re, -self.im)
            }
        }

        impl std::ops::Div for Complex<$f> {
            type Output = Self;
            /// `x / y` (see [`Complex::div_xla`]).
            #[inline]
            fn div(self, o: Self) -> Self {
                self.div_xla(o)
            }
        }

        impl Complex<$f> {
            /// The complex conjugate.
            #[inline]
            pub fn conj(self) -> Self {
                Self::new(self.re, -self.im)
            }

            /// `x / y` by Smith's algorithm, with XLA's handling of zero
            /// and infinite operands when the quotient would be NaN.
            pub fn div_xla(self, o: Self) -> Self {
                let (a_r, a_i, b_r, b_i) = (self.re, self.im, o.re, o.im);
                let (b_r_abs, b_i_abs) = (b_r.abs(), b_i.abs());
                let (result_r, result_i) = if b_r_abs < b_i_abs {
                    let ratio = b_r / b_i;
                    let denom = b_i + ratio * b_r;
                    ((ratio * a_r + a_i) / denom, (ratio * a_i - a_r) / denom)
                } else {
                    let ratio = b_i / b_r;
                    let denom = b_r + ratio * b_i;
                    ((ratio * a_i + a_r) / denom, (a_i - ratio * a_r) / denom)
                };
                if !(result_r.is_nan() && result_i.is_nan()) {
                    return Self::new(result_r, result_i);
                }
                let inf = $f::INFINITY;
                let (a_r_abs, a_i_abs) = (a_r.abs(), a_i.abs());
                if b_r_abs == 0.0 && b_i_abs == 0.0 && (!a_r.is_nan() || !a_i.is_nan()) {
                    // Case 1: a zero denominator.
                    let s = inf.copysign(b_r);
                    return Self::new(s * a_r, s * a_i);
                }
                let one_or_zero = |inf_: bool, sign: $f| {
                    $f::copysign(if inf_ { 1.0 } else { 0.0 }, sign)
                };
                if (a_r_abs == inf || a_i_abs == inf) && b_r_abs != inf && b_i_abs != inf {
                    // Case 2: an infinite numerator, a finite denominator.
                    let x = one_or_zero(a_r_abs == inf, a_r);
                    let y = one_or_zero(a_i_abs == inf, a_i);
                    return Self::new(inf * (x * b_r + y * b_i), inf * (y * b_r - x * b_i));
                }
                if (b_r_abs == inf || b_i_abs == inf) && a_r_abs != inf && a_i_abs != inf {
                    // Case 3: a finite numerator, an infinite denominator.
                    let x = one_or_zero(b_r_abs == inf, b_r);
                    let y = one_or_zero(b_i_abs == inf, b_i);
                    return Self::new(0.0 * (a_r * x + a_i * y), 0.0 * (a_i * x - a_r * y));
                }
                Self::new(result_r, result_i)
            }

            /// `|x|`, computed as JAX lowers it (`lax.hypot` of the real and
            /// imaginary parts, scaled by a power of two against overflow and
            /// underflow).
            pub fn abs(self) -> $f {
                let (x1, x2) = (self.re, self.im);
                let (a1, a2) = (x1.abs(), x2.abs());
                let m = max_nan(a1, a2);
                // `k` and `e_hi` as JAX computes them from `finfo`.
                let k: i32 = $k;
                let e_hi: i32 = $e_hi;
                let hi = m >= (2.0 as $f).powi(e_hi);
                let lo = m <= (2.0 as $f).powi(e_hi - k);
                let (s_down, s_up) = ((2.0 as $f).powi(-k), (2.0 as $f).powi(k));
                let scale = |x: $f| {
                    if hi {
                        x * s_down
                    } else if lo {
                        x * s_up
                    } else {
                        x
                    }
                };
                let (y1, y2) = (scale(x1), scale(x2));
                let inv_scale = if hi {
                    s_up
                } else if lo {
                    s_down
                } else {
                    1.0
                };
                let r = (y1 * y1 + y2 * y2).sqrt() * inv_scale;
                if a1 == $f::INFINITY || a2 == $f::INFINITY {
                    $f::INFINITY
                } else {
                    r
                }
            }

            /// `|x|` as XLA computes it (`max * sqrt(1 + (min / max)^2)`, with
            /// the maximum and minimum of the parts' magnitudes taken as XLA's
            /// fast min/max on CPU does), which `sign` uses.
            fn xla_abs(self) -> $f {
                let (min, max) = self.min_max_parts();
                let div = min / max;
                let r = max * (1.0 + div * div).sqrt();
                if r.is_nan() { min } else { r }
            }

            /// The minimum and maximum of the magnitudes of the parts, picked
            /// as XLA's fast min/max does (the first operand unless the second
            /// compares less or greater).
            #[inline]
            fn min_max_parts(self) -> ($f, $f) {
                let (x, y) = (self.re.abs(), self.im.abs());
                let max = if y > x { y } else { x };
                let min = if y < x { y } else { x };
                (min, max)
            }

            /// `log|x|`, computed as `log(max) + log1p((min / max)^2) / 2`
            /// without overflow.
            fn log_abs(self) -> $f {
                let (min, max) = self.min_max_parts();
                if max == 0.0 {
                    return $f::NEG_INFINITY;
                }
                if max == $f::INFINITY {
                    return max;
                }
                if self.re.is_nan() || self.im.is_nan() {
                    return $f::NAN;
                }
                let div = min / max;
                max.ln() + 0.5 * (div * div).ln_1p()
            }

            /// The argument (`atan2(im, re)`).
            #[inline]
            pub fn arg(self) -> $f {
                self.im.atan2(self.re)
            }

            /// `x / |x|`, or `x` where `x` is zero.
            pub fn sign(self) -> Self {
                if self.re.is_nan() || self.im.is_nan() {
                    return Self::new($f::NAN, $f::NAN);
                }
                let abs = self.xla_abs();
                if abs == 0.0 {
                    self
                } else {
                    Self::new(self.re / abs, self.im / abs)
                }
            }

            /// `e^x = e^a (cos b + i sin b)` (the imaginary part of a real
            /// argument is kept, as in XLA).
            pub fn exp(self) -> Self {
                let (a, b) = (self.re, self.im);
                let e = a.exp();
                let im = if b == 0.0 { b } else { e * b.sin() };
                Self::new(e * b.cos(), im)
            }

            /// `e^x - 1`.
            pub fn expm1(self) -> Self {
                // e^a cos b - 1 = expm1(a) cos b - 2 sin^2(b / 2).
                let (a, b) = (self.re, self.im);
                let h = (b * 0.5).sin();
                let im = if b == 0.0 { b } else { a.exp() * b.sin() };
                Self::new(a.exp_m1() * b.cos() - 2.0 * h * h, im)
            }

            /// `log|x| + i arg(x)`.
            pub fn log(self) -> Self {
                Self::new(self.log_abs(), self.arg())
            }

            /// `log(1 + x)`.
            pub fn log1p(self) -> Self {
                let (a, b) = (self.re, self.im);
                // log|1 + x| = log1p(a^2 + b^2 + 2a) / 2 for small |x|.
                let re = if a.abs() < 0.5 && b.abs() < 0.5 {
                    0.5 * (a * a + b * b + 2.0 * a).ln_1p()
                } else {
                    Self::new(a + 1.0, b).log_abs()
                };
                Self::new(re, b.atan2(a + 1.0))
            }

            /// The principal square root.
            pub fn sqrt(self) -> Self {
                let (a, b) = (self.re, self.im);
                if a == 0.0 && b == 0.0 {
                    return Self::new(0.0, b);
                }
                if b.is_infinite() {
                    return Self::new($f::INFINITY, b);
                }
                if a == $f::NEG_INFINITY {
                    return if b.is_nan() {
                        Self::new(b, $f::INFINITY)
                    } else {
                        Self::new(0.0, $f::INFINITY.copysign(b))
                    };
                }
                if a == $f::INFINITY {
                    return if b.is_nan() {
                        Self::new(b, b)
                    } else {
                        Self::new(a, (0.0 as $f).copysign(b))
                    };
                }
                // t = sqrt((|a| + |x|) / 2), scaled by 1/4 against overflow
                // for large arguments.
                let t = if a.abs().max(b.abs()) > $f::MAX / 8.0 {
                    let r = Self::new(a * 0.25, b * 0.25).abs();
                    (a.abs() * 0.25 + r).sqrt() * std::f64::consts::SQRT_2 as $f
                } else {
                    ((a.abs() + self.abs()) * 0.5).sqrt()
                };
                if a >= 0.0 {
                    Self::new(t, b / (2.0 * t))
                } else {
                    Self::new(b.abs() / (2.0 * t), t.copysign(b))
                }
            }

            /// `1 / sqrt(x)`.
            pub fn rsqrt(self) -> Self {
                if self.re.is_infinite() || self.im.is_infinite() {
                    return Self::new(0.0, -0.0);
                }
                Self::new(1.0, 0.0).div(self.sqrt())
            }

            /// The sine, as JAX's `_sin_complex` computes it.
            pub fn sin(self) -> Self {
                let (a, b) = (self.re, self.im);
                let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
                let snh = (e1m - e2m) / 2.0;
                let csh = (e1m + e2m + 2.0) / 2.0;
                let im = a.cos() * snh;
                if a == 0.0 {
                    Self::new(0.0, im)
                } else {
                    Self::new(a.sin() * csh, im)
                }
            }

            /// The cosine, as JAX's `_cos_complex` computes it.
            pub fn cos(self) -> Self {
                let (a, b) = (self.re, self.im);
                let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
                let snh = (e1m - e2m) / 2.0;
                let csh = (e1m + e2m + 2.0) / 2.0;
                let re = a.cos() * csh;
                if a == 0.0 {
                    Self::new(re, 0.0)
                } else {
                    Self::new(re, -a.sin() * snh)
                }
            }

            /// The tangent: `tan(x) = -i tanh(i x)`.
            pub fn tan(self) -> Self {
                let t = Self::new(-self.im, self.re).tanh();
                Self::new(t.im, -t.re)
            }

            /// The hyperbolic tangent.
            pub fn tanh(self) -> Self {
                let (a, b) = (self.re, self.im);
                if b == 0.0 {
                    return Self::new(a.tanh(), b);
                }
                // For large |a|, tanh(a) rounds to +-1 and the imaginary part
                // underflows (to 0 also where it would be NaN, as in XLA).
                if a.abs() > $f::MANTISSA_DIGITS as $f * 0.5 {
                    let e = (-2.0 * a.abs()).exp();
                    let im = 4.0 * b.sin() * b.cos() * e;
                    let im = if im.is_nan() && !b.is_nan() { 0.0 } else { im };
                    let im = if b.is_nan() { 0.0 } else { im };
                    return Self::new((1.0 as $f).copysign(a), im);
                }
                // tanh(a + bi) = (tanh a (1 + tan^2 b) + i tan b (1 - tanh^2 a))
                //              / (1 + tanh^2 a tan^2 b).
                let (th, t) = (a.tanh(), b.tan());
                let denom = 1.0 + th * th * t * t;
                Self::new(th * (1.0 + t * t) / denom, t * (1.0 - th * th) / denom)
            }

            /// `1 / (1 + e^-x)`, as XLA expands `logistic`.
            pub fn logistic(self) -> Self {
                let one = Self::new(1.0, 0.0);
                one.div(one.add(self.neg().exp()))
            }

            /// `x^y`: `e^(c log|x| - d arg x) (cos q + i sin q)` with `q = c
            /// arg x + d log|x|` for `y = c + di`, with the special cases of
            /// XLA's CPU implementation: `x^0` is 1, a positive real `x` to a
            /// real `y` is real, `1^y` is 1, and `0^y` is 0 for real `y > 0`.
            pub fn pow(self, y: Self) -> Self {
                let (a, b, c, d) = (self.re, self.im, y.re, y.im);
                if (c == 0.0 && d == 0.0) || (a == 1.0 && b == 0.0) {
                    return Self::new(1.0, 0.0);
                }
                if d == 0.0 && b == 0.0 && a > 0.0 && !c.is_nan() {
                    return Self::new(a.powf(c), 0.0);
                }
                if a == 0.0 && (b == 0.0 || b.is_nan()) && d == 0.0 && c > 0.0 {
                    return Self::new(0.0, 0.0);
                }
                // log|x| of XLA's |x|, which overflows for the largest values.
                let (lr, arg) = (self.xla_abs().ln(), b.atan2(a));
                let coeff = (c * lr).exp() * (-d * arg).exp();
                let q = c * arg + d * lr;
                Self::new(coeff * q.cos(), coeff * q.sin())
            }

            /// The maximum, comparing lexicographically as JAX lowers `max`
            /// of complex numbers (`y` unless `x` is greater).
            #[inline]
            pub fn max(self, o: Self) -> Self {
                let gt = if self.re == o.re {
                    self.im > o.im
                } else {
                    self.re > o.re
                };
                if gt { self } else { o }
            }

            /// The minimum, comparing lexicographically as JAX lowers `min`
            /// of complex numbers (`y` unless `x` is less).
            #[inline]
            pub fn min(self, o: Self) -> Self {
                let lt = if self.re == o.re {
                    self.im < o.im
                } else {
                    self.re < o.re
                };
                if lt { self } else { o }
            }

            /// Whether both parts are finite.
            #[inline]
            pub fn is_finite(self) -> bool {
                self.re.is_finite() && self.im.is_finite()
            }
        }
    };
}

/// The maximum, propagating NaN (as XLA's `EmitFloatMax`).
fn max_nan<F: num_like::Float>(a: F, b: F) -> F {
    if a.is_nan_() || b.is_nan_() {
        F::NAN_
    } else if a > b {
        a
    } else {
        b
    }
}

mod num_like {
    /// The floats that complex numbers are made of.
    pub(super) trait Float: Copy + PartialOrd {
        const NAN_: Self;
        fn is_nan_(self) -> bool;
    }
    impl Float for f32 {
        const NAN_: Self = f32::NAN;
        fn is_nan_(self) -> bool {
            self.is_nan()
        }
    }
    impl Float for f64 {
        const NAN_: Self = f64::NAN;
        fn is_nan_(self) -> bool {
            self.is_nan()
        }
    }
}

// k = (nmant - minexp + 1) / 2 and e_hi = (maxexp - 1) / 2 from `finfo`.
impl_complex!(f32, 75, 63);
impl_complex!(f64, 537, 511);

#[cfg(test)]
mod tests {
    use super::*;
    use std::ops::{Mul, Sub};

    fn close(a: c128, b: c128) -> bool {
        (a.re - b.re).abs() <= 1e-12 * (1.0 + b.re.abs())
            && (a.im - b.im).abs() <= 1e-12 * (1.0 + b.im.abs())
    }

    #[test]
    fn arithmetic() {
        let x = c128::new(1.0, 2.0);
        let y = c128::new(3.0, -1.0);
        assert_eq!(x.mul(y), c128::new(5.0, 5.0));
        assert!(close(x.div(y).mul(y), x));
        assert_eq!(c128::new(3.0, 4.0).abs(), 5.0);
        assert_eq!(c64::new(3e30, 4e30).abs(), 5e30);
        assert_eq!(c64::new(3e-30, 4e-30).abs(), 5e-30);
        assert_eq!(c128::new(f64::INFINITY, f64::NAN).abs(), f64::INFINITY);
        // Division by zero gives infinities, as in XLA.
        let q = c128::new(1.0, 1.0).div(c128::new(0.0, 0.0));
        assert_eq!((q.re, q.im), (f64::INFINITY, f64::INFINITY));
        let q = c128::new(1.0, 1.0).div(c128::new(f64::INFINITY, 0.0));
        assert_eq!((q.re, q.im), (0.0, 0.0));
    }

    #[test]
    fn functions() {
        let x = c128::new(0.5, -1.25);
        assert!(close(x.log().exp(), x));
        assert!(close(x.sqrt().mul(x.sqrt()), x));
        assert!(close(x.expm1(), x.exp().sub(c128::new(1.0, 0.0))));
        assert!(close(x.log1p(), x.add(c128::new(1.0, 0.0)).log()));
        let (s, c) = (x.sin(), x.cos());
        assert!(close(s.mul(s).add(c.mul(c)), c128::new(1.0, 0.0)));
        assert!(close(x.tan(), s.div(c)));
        let i = c128::new(0.0, 1.0);
        assert!(close(x.tanh(), x.mul(i).tan().div(i)));
        assert!(close(x.pow(c128::new(2.0, 0.0)), x.mul(x)));
        assert_eq!(
            c128::new(0.0, 0.0).pow(c128::new(0.0, 0.0)),
            c128::new(1.0, 0.0)
        );
        assert_eq!(c128::new(-4.0, 0.0).sqrt(), c128::new(0.0, 2.0));
        assert_eq!(c128::new(-4.0, -0.0).sqrt(), c128::new(0.0, -2.0));
        assert!(close(c128::new(3.0, 4.0).sign(), c128::new(0.6, 0.8)));
    }

    #[test]
    fn order() {
        let (a, b) = (c64::new(1.0, 5.0), c64::new(1.0, 7.0));
        assert!(a < b);
        assert_eq!(a.max(b), b);
        assert_eq!(a.min(b), a);
        assert_eq!(c64::new(2.0, 0.0).max(b), c64::new(2.0, 0.0));
    }
}