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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! The value types: [`Scalar`] and [`Array`].

use std::fmt;
use std::ops;

use ruxla_ir::Shape;
use ruxla_kernels::array::ReduceOp;
use ruxla_kernels::{BinaryOp, CompareOp, Element, UnaryOp, bf16, c64, c128, f16};

use crate::backend::{Backend, Native, NativeArray, ToReal};

/// Element types that are floating point numbers.
pub trait Float: Num + Inexact {}
impl Float for f16 {}
impl Float for bf16 {}
impl Float for f32 {}
impl Float for f64 {}

/// The real element types of linear algebra (`lax::linalg`,
/// `jnp::linalg`): `f32` and `f64`.
pub trait LinalgFloat: Float + LinalgScalar + ruxla_kernels::linalg::LinalgFloat {}
impl LinalgFloat for f32 {}
impl LinalgFloat for f64 {}

/// The element types of the linear algebra primitives (`lax::linalg`):
/// `f32`, `f64`, `c64`, and `c128`. The eigenvalues of `eigh` and the
/// singular values of `svd` have the real type `Real`.
pub trait LinalgScalar:
    Inexact
    + ruxla_kernels::linalg::LinalgScalar<LinalgReal: Float + ruxla_kernels::linalg::LinalgFloat>
{
    /// The complex type of the results of `eig` (`c64` for `f32` and
    /// `c64`, `c128` for `f64` and `c128`).
    type Complex: ComplexFloat;
    /// The values of the kernel's complex type as `Complex` (the same type).
    #[doc(hidden)]
    fn complex_vec(v: Vec<ruxla_kernels::linalg::Cx<Self>>) -> Vec<Self::Complex>;
}
macro_rules! impl_linalg_scalar {
    ($($t:ty => $c:ty),*) => {$(
        impl LinalgScalar for $t {
            type Complex = $c;
            fn complex_vec(v: Vec<ruxla_kernels::linalg::Cx<Self>>) -> Vec<$c> {
                v
            }
        }
    )*};
}
impl_linalg_scalar!(f32 => c64, f64 => c128, c64 => c64, c128 => c128);
/// Element types that are numbers: integers, floats, and complex numbers
/// (NumPy's `number`). They have arithmetic.
pub trait Numeric: Element {}
macro_rules! numeric {
    ($($t:ty)*) => {$(impl Numeric for $t {})*};
}
numeric!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);

/// Element types that are floats or complex numbers (NumPy's `inexact`).
/// They have the transcendental functions that complex numbers share with
/// floats (`exp`, `ln`, `sqrt`, `sin`, ...), and derivatives.
pub trait Inexact: Numeric {}
impl Inexact for f16 {}
impl Inexact for bf16 {}
impl Inexact for f32 {}
impl Inexact for f64 {}
impl Inexact for c64 {}
impl Inexact for c128 {}

/// Element types that are complex numbers, whose parts are [`Float`]s.
pub trait ComplexFloat: Inexact + Element<Real: Float> {}
impl ComplexFloat for c64 {}
impl ComplexFloat for c128 {}

/// The floats that complex numbers are made of (`f32` and `f64`), with
/// their complex type (the result of `rfft`).
pub trait RealFloat: Float {
    /// The complex type with parts of this type.
    type Complex: ComplexFloat + Element<Real = Self>;
}
impl RealFloat for f32 {
    type Complex = c64;
}
impl RealFloat for f64 {
    type Complex = c128;
}

/// Element types that are integers.
pub trait Int: Num {}
impl Int for i8 {}
impl Int for i16 {}
impl Int for i32 {}
impl Int for i64 {}
impl Int for u8 {}
impl Int for u16 {}
impl Int for u32 {}
impl Int for u64 {}

/// Element types that are real numbers (integers and floats; not `bool`
/// or complex numbers).
pub trait Num: Numeric + Element<Real = Self> {}
macro_rules! num {
    ($($t:ty)*) => {$(impl Num for $t {})*};
}
num!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64);

/// A scalar of element type `T` on backend `B`.
///
/// On `Native` it is a `T`; on `Trace` it is a traced value. It is `Copy`
/// on both backends.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Backend, F32, Native};
///
/// fn hypot<B: Backend>(x: F32<B>, y: F32<B>) -> F32<B> {
///     (x * x + y * y).sqrt()
/// }
/// assert_eq!(hypot::<Native>(F32::new(3.0), F32::new(4.0)).value(), 5.0);
/// ```
#[repr(transparent)]
pub struct Scalar<B: Backend, T: Element>(pub(crate) B::Scalar<T>);

/// A `bool` scalar.
pub type Bool<B> = Scalar<B, bool>;
/// An `i32` scalar.
pub type I32<B> = Scalar<B, i32>;
/// An `i64` scalar.
pub type I64<B> = Scalar<B, i64>;
/// A `u32` scalar.
pub type U32<B> = Scalar<B, u32>;
/// A `u8` scalar.
pub type U8<B> = Scalar<B, u8>;
/// An `f32` scalar.
pub type F32<B> = Scalar<B, f32>;
/// An `f64` scalar.
pub type F64<B> = Scalar<B, f64>;
/// A `c64` (`complex64`) scalar.
pub type C64<B> = Scalar<B, c64>;
/// A `c128` (`complex128`) scalar.
pub type C128<B> = Scalar<B, c128>;

impl<B: Backend, T: Element> Clone for Scalar<B, T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<B: Backend, T: Element> Copy for Scalar<B, T> {}

impl<B: Backend, T: Element> fmt::Debug for Scalar<B, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Scalar<{}>({:?})", T::DTYPE, self.0)
    }
}

impl<B: Backend, T: Element> From<T> for Scalar<B, T> {
    fn from(v: T) -> Self {
        Self::new(v)
    }
}

impl<B: Backend, T: Element> Scalar<B, T> {
    /// A constant.
    pub fn new(v: T) -> Self {
        Scalar(B::lit(v))
    }

    /// Wraps a backend value.
    pub fn from_repr(r: B::Scalar<T>) -> Self {
        Scalar(r)
    }

    /// Returns the backend value.
    pub fn repr(self) -> B::Scalar<T> {
        self.0
    }

    fn unary(self, op: UnaryOp) -> Self {
        Scalar(B::unary::<T>(op, self.0))
    }

    fn binary(self, op: BinaryOp, other: impl Into<Self>) -> Self {
        Scalar(B::binary::<T>(op, self.0, other.into().0))
    }

    fn compare(self, op: CompareOp, other: impl Into<Self>) -> Bool<B> {
        Scalar(B::compare::<T>(op, self.0, other.into().0))
    }

    /// `self == other`.
    pub fn eq(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Eq, other)
    }
    /// `self != other`.
    pub fn ne(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Ne, other)
    }
    /// `self < other`.
    pub fn lt(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Lt, other)
    }
    /// `self <= other`.
    pub fn le(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Le, other)
    }
    /// `self > other`.
    pub fn gt(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Gt, other)
    }
    /// `self >= other`.
    pub fn ge(self, other: impl Into<Self>) -> Bool<B> {
        self.compare(CompareOp::Ge, other)
    }

    /// The maximum, propagating NaN (logical or for booleans).
    pub fn max(self, other: impl Into<Self>) -> Self {
        self.binary(BinaryOp::Max, other)
    }
    /// The minimum, propagating NaN (logical and for booleans).
    pub fn min(self, other: impl Into<Self>) -> Self {
        self.binary(BinaryOp::Min, other)
    }

    /// Converts to another element type, as `lax.convert_element_type`.
    pub fn cast<U: Element>(self) -> Scalar<B, U> {
        Scalar(B::cast::<T, U>(self.0))
    }

    /// Reinterprets the bits as another type of the same size.
    pub fn bitcast<U: Element>(self) -> Scalar<B, U> {
        Scalar(B::bitcast::<T, U>(self.0))
    }

    /// The value as an array of rank 0.
    pub fn to_array(self) -> Array<B, T> {
        Array(B::to_array::<T>(self.0))
    }
}

impl<T: Element> Scalar<Native, T> {
    /// Returns the value.
    pub fn value(self) -> T {
        self.0
    }
}

impl<B: Backend, T: Numeric> Scalar<B, T> {
    /// `|x|` (signed integers wrap around; unsigned integers are returned
    /// unchanged; the magnitude of a complex number is real).
    pub fn abs(self) -> Scalar<B, T::Real> {
        Scalar(B::to_real::<T>(ToReal::Abs, self.0))
    }
    /// -1, 0, or 1 (`x / |x|` for complex numbers).
    pub fn sign(self) -> Self {
        self.unary(UnaryOp::Sign)
    }
    /// `x * x`.
    pub fn square(self) -> Self {
        self.unary(UnaryOp::Square)
    }
    /// `x^y` for a static integer `y` (`lax.integer_pow`).
    pub fn integer_pow(self, y: i32) -> Self {
        Scalar(B::integer_pow::<T>(self.0, y))
    }
}

impl<B: Backend, T: Num> Scalar<B, T> {
    /// Clamps to `[lo, hi]`, propagating NaN.
    pub fn clamp(self, lo: impl Into<Self>, hi: impl Into<Self>) -> Self {
        self.max(lo).min(hi)
    }
}

impl<B: Backend, T: ComplexFloat> Scalar<B, T> {
    /// A complex number from its real and imaginary parts (`lax.complex`).
    pub fn complex(re: impl Into<Scalar<B, T::Real>>, im: impl Into<Scalar<B, T::Real>>) -> Self {
        Scalar(B::complex::<T>(re.into().0, im.into().0))
    }
    /// The real part.
    pub fn real(self) -> Scalar<B, T::Real> {
        Scalar(B::to_real::<T>(ToReal::Real, self.0))
    }
    /// The imaginary part.
    pub fn imag(self) -> Scalar<B, T::Real> {
        Scalar(B::to_real::<T>(ToReal::Imag, self.0))
    }
    /// The complex conjugate.
    pub fn conj(self) -> Self {
        Scalar(B::conj::<T>(self.0))
    }
    /// The argument (`atan2(imag, real)`, as `jnp.angle`).
    pub fn angle(self) -> Scalar<B, T::Real> {
        self.imag().atan2(self.real())
    }
}

impl<B: Backend, T: ComplexFloat> Array<B, T> {
    /// Complex numbers from their real and imaginary parts (`lax.complex`;
    /// the shapes must be equal).
    #[track_caller]
    pub fn complex(re: &Array<B, T::Real>, im: &Array<B, T::Real>) -> Self {
        Array(B::a_complex::<T>(&re.0, &im.0))
    }
    /// The real parts.
    pub fn real(&self) -> Array<B, T::Real> {
        Array(B::a_to_real::<T>(ToReal::Real, &self.0))
    }
    /// The imaginary parts.
    pub fn imag(&self) -> Array<B, T::Real> {
        Array(B::a_to_real::<T>(ToReal::Imag, &self.0))
    }
    /// The complex conjugates.
    pub fn conj(&self) -> Self {
        Array(B::a_conj::<T>(&self.0))
    }
    /// The arguments (`atan2(imag, real)`, as `jnp.angle`).
    pub fn angle(&self) -> Array<B, T::Real> {
        crate::jnp::arctan2(self.imag(), self.real())
    }
}

impl<B: Backend, T: Numeric> Array<B, T> {
    /// `|x|` (signed integers wrap around; unsigned integers are returned
    /// unchanged; the magnitude of a complex number is real).
    pub fn abs(&self) -> Array<B, T::Real> {
        Array(B::a_to_real::<T>(ToReal::Abs, &self.0))
    }
    /// -1, 0, or 1 (`x / |x|` for complex numbers).
    pub fn sign(&self) -> Self {
        self.unary(UnaryOp::Sign)
    }
    /// `x * x`.
    pub fn square(&self) -> Self {
        self.unary(UnaryOp::Square)
    }
    /// `x^y` for a static integer `y` (`lax.integer_pow`).
    pub fn integer_pow(&self, y: i32) -> Self {
        Array(B::a_integer_pow::<T>(&self.0, y))
    }
}

macro_rules! inexact_methods {
    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {
        impl<B: Backend, T: Inexact> Scalar<B, T> {
            $($(#[$m])* pub fn $name(self) -> Self { self.unary(UnaryOp::$op) })*

            /// `self^y`.
            pub fn pow(self, y: impl Into<Self>) -> Self {
                self.binary(BinaryOp::Pow, y)
            }
        }

        impl<B: Backend, T: Inexact> Array<B, T> {
            $($(#[$m])* pub fn $name(&self) -> Self { self.unary(UnaryOp::$op) })*
        }
    };
}

inexact_methods! {
    /// `e^x`.
    exp => Exp;
    /// `e^x - 1`.
    expm1 => Expm1;
    /// Natural logarithm (the principal value for complex numbers).
    ln => Log;
    /// `log(1 + x)`.
    ln_1p => Log1p;
    /// Square root (the principal value for complex numbers).
    sqrt => Sqrt;
    /// `1 / sqrt(x)`.
    rsqrt => Rsqrt;
    /// Sine.
    sin => Sin;
    /// Cosine.
    cos => Cos;
    /// Tangent.
    tan => Tan;
    /// Hyperbolic tangent.
    tanh => Tanh;
    /// The logistic sigmoid.
    logistic => Logistic;
}

macro_rules! float_methods {
    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {
        impl<B: Backend, T: Float> Scalar<B, T> {
            $($(#[$m])* pub fn $name(self) -> Self { self.unary(UnaryOp::$op) })*

            /// `atan2(self, x)`.
            pub fn atan2(self, x: impl Into<Self>) -> Self {
                self.binary(BinaryOp::Atan2, x)
            }
            /// Whether the value is neither infinite nor NaN.
            pub fn is_finite(self) -> Bool<B> {
                Scalar(B::is_finite::<T>(self.0))
            }
        }

        impl<B: Backend, T: Float> Array<B, T> {
            $($(#[$m])* pub fn $name(&self) -> Self { self.unary(UnaryOp::$op) })*

            /// Whether each element is neither infinite nor NaN.
            pub fn is_finite(&self) -> Array<B, bool> {
                Array(B::a_is_finite::<T>(&self.0))
            }
        }
    };
}

float_methods! {
    /// Round toward negative infinity.
    floor => Floor;
    /// Round toward positive infinity.
    ceil => Ceil;
    /// Round to the nearest integer, halfway cases away from zero.
    round => Round;
    /// Round to the nearest integer, halfway cases to even.
    round_even => RoundEven;
    /// Cube root.
    cbrt => Cbrt;
    /// The inverse error function.
    erf_inv => ErfInv;
    /// The logarithm of the absolute value of the gamma function.
    lgamma => Lgamma;
    /// The digamma function.
    digamma => Digamma;
    /// The error function.
    erf => Erf;
    /// The complementary error function.
    erfc => Erfc;
}

macro_rules! scalar_binop {
    ($($tr:ident $f:ident $op:ident $bound:ident;)*) => {$(
        impl<B: Backend, T: $bound> ops::$tr for Scalar<B, T> {
            type Output = Self;
            fn $f(self, rhs: Self) -> Self {
                self.binary(BinaryOp::$op, rhs)
            }
        }
        impl<B: Backend, T: $bound> ops::$tr<T> for Scalar<B, T> {
            type Output = Self;
            fn $f(self, rhs: T) -> Self {
                self.binary(BinaryOp::$op, rhs)
            }
        }
    )*};
}

scalar_binop! {
    Add add Add Numeric;
    Sub sub Sub Numeric;
    Mul mul Mul Numeric;
    Div div Div Numeric;
    Rem rem Rem Num;
    BitAnd bitand And Element;
    BitOr bitor Or Element;
    BitXor bitxor Xor Element;
}

macro_rules! scalar_lhs_literal {
    ($($t:ty)*) => {$(
        impl<B: Backend> ops::Add<Scalar<B, $t>> for $t {
            type Output = Scalar<B, $t>;
            fn add(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) + rhs }
        }
        impl<B: Backend> ops::Sub<Scalar<B, $t>> for $t {
            type Output = Scalar<B, $t>;
            fn sub(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) - rhs }
        }
        impl<B: Backend> ops::Mul<Scalar<B, $t>> for $t {
            type Output = Scalar<B, $t>;
            fn mul(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) * rhs }
        }
        impl<B: Backend> ops::Div<Scalar<B, $t>> for $t {
            type Output = Scalar<B, $t>;
            fn div(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) / rhs }
        }
    )*};
}

scalar_lhs_literal!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);

impl<B: Backend, T: Numeric> ops::Neg for Scalar<B, T> {
    type Output = Self;
    fn neg(self) -> Self {
        self.unary(UnaryOp::Neg)
    }
}

impl<B: Backend, T: Element> ops::Not for Scalar<B, T> {
    type Output = Self;
    fn not(self) -> Self {
        self.unary(UnaryOp::Not)
    }
}

impl<B: Backend, T: Int> ops::Shl for Scalar<B, T> {
    type Output = Self;
    fn shl(self, rhs: Self) -> Self {
        self.binary(BinaryOp::ShiftLeft, rhs)
    }
}

impl<B: Backend, T: Int> ops::Shr for Scalar<B, T> {
    type Output = Self;
    /// A logical shift for unsigned types and an arithmetic shift for signed
    /// types, as Rust's `>>`.
    fn shr(self, rhs: Self) -> Self {
        let op = if T::DTYPE.kind() == ruxla_ir::DTypeKind::UnsignedInt {
            BinaryOp::ShiftRightLogical
        } else {
            BinaryOp::ShiftRightArithmetic
        };
        self.binary(op, rhs)
    }
}

impl<B: Backend, T: Int> ops::Shl<T> for Scalar<B, T> {
    type Output = Self;
    fn shl(self, rhs: T) -> Self {
        self << Scalar::new(rhs)
    }
}

impl<B: Backend, T: Int> ops::Shr<T> for Scalar<B, T> {
    type Output = Self;
    fn shr(self, rhs: T) -> Self {
        self >> Scalar::new(rhs)
    }
}

/// An array of element type `T` on backend `B`, with a shape known at run
/// time (and fixed within a traced program).
///
/// On `Native` it holds shared elements, so `clone` is cheap; on `Trace` it
/// is a traced value.
#[repr(transparent)]
pub struct Array<B: Backend, T: Element>(pub(crate) B::Array<T>);

impl<B: Backend, T: Element> Clone for Array<B, T> {
    #[inline]
    fn clone(&self) -> Self {
        Array(self.0.clone())
    }
}

impl<B: Backend, T: Element> fmt::Debug for Array<B, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Array<{}>({:?})", T::DTYPE, self.0)
    }
}

impl<B: Backend, T: Element> Array<B, T> {
    /// A constant array from its elements in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if the number of elements does not match the shape.
    #[track_caller]
    pub fn from_vec(data: Vec<T>, shape: impl Into<Shape>) -> Self {
        Array(B::constant_owned(NativeArray::new(data, shape)))
    }

    /// A constant array from a copy of its elements in row-major order
    /// (like [`Array::from_vec`], without a `Vec`).
    ///
    /// # Examples
    ///
    /// ```
    /// use ruxla_core::{Array, I32, Native};
    ///
    /// let table = Array::<Native, i32>::from_slice(&[1, 0, 3, 2], [4]);
    /// assert_eq!(table.get(I32::new(2)).value(), 3);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the number of elements does not match the shape.
    #[track_caller]
    #[inline]
    pub fn from_slice(data: &[T], shape: impl Into<Shape>) -> Self {
        Array(B::constant_owned(NativeArray::from_slice(data, shape)))
    }

    /// A constant array.
    pub fn constant(x: &NativeArray<T>) -> Self {
        Array(B::constant(x))
    }

    /// Wraps a backend value.
    pub fn from_repr(r: B::Array<T>) -> Self {
        Array(r)
    }

    /// Returns the backend value.
    pub fn repr(&self) -> &B::Array<T> {
        &self.0
    }

    /// Views arrays as their backend representations.
    pub(crate) fn reprs(xs: &[Self]) -> &[B::Array<T>] {
        // SAFETY: `Array` is `#[repr(transparent)]` over `B::Array<T>`, so a
        // slice of one has the layout of a slice of the other.
        unsafe { std::slice::from_raw_parts(xs.as_ptr().cast::<B::Array<T>>(), xs.len()) }
    }

    /// Returns the shape.
    pub fn shape(&self) -> Shape {
        B::shape::<T>(&self.0)
    }

    /// Returns the number of dimensions.
    #[inline]
    pub fn ndim(&self) -> usize {
        B::rank::<T>(&self.0)
    }

    /// Returns the number of elements.
    #[inline]
    pub fn size(&self) -> usize {
        match B::dims(&self.0) {
            Some(dims) => dims.iter().product(),
            None => self.shape().size(),
        }
    }

    /// The only element of an array of rank 0.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not 0.
    #[track_caller]
    pub fn to_scalar(&self) -> Scalar<B, T> {
        Scalar(B::to_scalar::<T>(&self.0))
    }

    /// Converts to another element type.
    pub fn cast<U: Element>(&self) -> Array<B, U> {
        Array(B::a_cast::<T, U>(&self.0))
    }

    /// Changes the shape, keeping the elements in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if the sizes differ.
    #[track_caller]
    pub fn reshape(&self, shape: impl Into<Shape>) -> Self {
        Array(B::reshape::<T>(&self.0, &shape.into()))
    }

    /// Permutes the dimensions: dimension `i` of the result is dimension
    /// `perm[i]` of `self`.
    #[track_caller]
    pub fn transpose(&self, perm: &[usize]) -> Self {
        Array(B::transpose::<T>(&self.0, perm))
    }

    /// Broadcasts to `shape` with NumPy's rules.
    ///
    /// # Panics
    ///
    /// Panics if the shapes are not compatible.
    #[track_caller]
    pub fn broadcast_to(&self, shape: impl Into<Shape>) -> Self {
        let shape = shape.into();
        let s = self.shape();
        if s == shape {
            return self.clone();
        }
        assert!(
            s.rank() <= shape.rank(),
            "cannot broadcast [{s}] to [{shape}]"
        );
        let offset = shape.rank() - s.rank();
        let dims: Vec<usize> = (0..s.rank()).map(|i| i + offset).collect();
        for (i, &d) in dims.iter().enumerate() {
            assert!(
                s[i] == 1 || s[i] == shape[d],
                "cannot broadcast [{s}] to [{shape}]"
            );
        }
        Array(B::broadcast_in_dim::<T>(&self.0, &shape, &dims))
    }

    pub(crate) fn unary(&self, op: UnaryOp) -> Self {
        Array(B::a_unary::<T>(op, &self.0))
    }

    /// [`Self::unary`] of an owned array: written over its elements where
    /// they are not shared.
    pub(crate) fn into_unary(mut self, op: UnaryOp) -> Self {
        if B::FAST_PATHS && B::a_unary_assign::<T>(op, &mut self.0) {
            return self;
        }
        self.unary(op)
    }

    /// Sums over `axes` (`lax.reduce_sum`; integers wrap around).
    #[track_caller]
    pub fn reduce_sum(&self, axes: &[usize]) -> Self {
        Array(B::reduce::<T>(ReduceOp::Sum, &self.0, axes))
    }

    /// The maximum over `axes`, propagating NaN (`lax.reduce_max`).
    #[track_caller]
    pub fn reduce_max(&self, axes: &[usize]) -> Self {
        Array(B::reduce::<T>(ReduceOp::Max, &self.0, axes))
    }

    /// The minimum over `axes`, propagating NaN (`lax.reduce_min`).
    #[track_caller]
    pub fn reduce_min(&self, axes: &[usize]) -> Self {
        Array(B::reduce::<T>(ReduceOp::Min, &self.0, axes))
    }
}

impl<T: Element> Array<Native, T> {
    /// Returns the elements in row-major order.
    pub fn to_vec(&self) -> Vec<T> {
        self.0.data().to_vec()
    }

    /// Returns the native array.
    pub fn native(&self) -> &NativeArray<T> {
        &self.0
    }
}

/// Returns the shape that two shapes broadcast to, with NumPy's rules.
#[track_caller]
pub(crate) fn broadcast_shapes(a: &Shape, b: &Shape) -> Shape {
    let r = a.rank().max(b.rank());
    let dim = |s: &Shape, i: usize| {
        if i + s.rank() < r {
            1
        } else {
            s[i + s.rank() - r]
        }
    };
    if a == b {
        return a.clone();
    }
    (0..r)
        .map(|i| {
            let (x, y) = (dim(a, i), dim(b, i));
            assert!(
                x == y || x == 1 || y == 1,
                "shapes [{a}] and [{b}] do not broadcast"
            );
            x.max(y)
        })
        .collect()
}

/// Applies a binary operation with NumPy's broadcasting.
#[track_caller]
pub(crate) fn broadcast_binary<B: Backend, T: Element>(
    op: BinaryOp,
    a: &Array<B, T>,
    b: &Array<B, T>,
) -> Array<B, T> {
    if let Some(r) = B::a_binary_broadcast::<T>(op, &a.0, &b.0) {
        return Array(r);
    }
    let s = broadcast_shapes(&a.shape(), &b.shape());
    Array(B::a_binary::<T>(
        op,
        &a.broadcast_to(s.clone()).0,
        &b.broadcast_to(s).0,
    ))
}

/// Applies a comparison with NumPy's broadcasting.
#[track_caller]
pub(crate) fn broadcast_compare<B: Backend, T: Element>(
    op: CompareOp,
    a: &Array<B, T>,
    b: &Array<B, T>,
) -> Array<B, bool> {
    if let Some(r) = B::a_compare_broadcast::<T>(op, &a.0, &b.0) {
        return Array(r);
    }
    let s = broadcast_shapes(&a.shape(), &b.shape());
    Array(B::a_compare::<T>(
        op,
        &a.broadcast_to(s.clone()).0,
        &b.broadcast_to(s).0,
    ))
}

/// Something that can be an operand of an array operation: an array, a
/// scalar, or a Rust value.
pub trait ArrayLike<B: Backend, T: Element>: Sized {
    /// Converts to an array.
    fn into_array(self) -> Array<B, T>;

    /// Calls `f` with the array, without copying a borrowed array.
    #[inline]
    fn with_array<R>(self, f: impl FnOnce(&Array<B, T>) -> R) -> R {
        f(&self.into_array())
    }

    /// The value as a scalar, if it is one (for fast paths).
    #[doc(hidden)]
    #[inline]
    fn as_scalar(&self) -> Option<Scalar<B, T>> {
        None
    }

    /// Whether this is a borrowed array (whose elements must not be
    /// written over).
    #[doc(hidden)]
    #[inline]
    fn is_borrowed(&self) -> bool {
        false
    }
}

impl<B: Backend, T: Element> ArrayLike<B, T> for Array<B, T> {
    fn into_array(self) -> Array<B, T> {
        self
    }
}
impl<B: Backend, T: Element> ArrayLike<B, T> for &Array<B, T> {
    fn into_array(self) -> Array<B, T> {
        self.clone()
    }
    #[inline]
    fn with_array<R>(self, f: impl FnOnce(&Array<B, T>) -> R) -> R {
        f(self)
    }
    #[inline]
    fn is_borrowed(&self) -> bool {
        true
    }
}
impl<B: Backend, T: Element> ArrayLike<B, T> for Scalar<B, T> {
    #[inline]
    fn into_array(self) -> Array<B, T> {
        self.to_array()
    }
    #[inline]
    fn as_scalar(&self) -> Option<Scalar<B, T>> {
        Some(*self)
    }
}
impl<B: Backend, T: Element> ArrayLike<B, T> for T {
    #[inline]
    fn into_array(self) -> Array<B, T> {
        Scalar::<B, T>::new(self).to_array()
    }
    #[inline]
    fn as_scalar(&self) -> Option<Scalar<B, T>> {
        Some(Scalar::new(*self))
    }
}

macro_rules! array_binop {
    ($($tr:ident $f:ident $op:ident $bound:ident;)*) => {$(
        impl<B: Backend, T: $bound, R: ArrayLike<B, T>> ops::$tr<R> for Array<B, T> {
            type Output = Array<B, T>;
            #[track_caller]
            fn $f(mut self, rhs: R) -> Array<B, T> {
                rhs.with_array(|r| {
                    // An array that is not shared is written over.
                    if B::FAST_PATHS && B::a_binary_assign::<T>(BinaryOp::$op, &mut self.0, &r.0) {
                        return self;
                    }
                    broadcast_binary(BinaryOp::$op, &self, r)
                })
            }
        }
        impl<B: Backend, T: $bound, R: ArrayLike<B, T>> ops::$tr<R> for &Array<B, T> {
            type Output = Array<B, T>;
            #[track_caller]
            fn $f(self, rhs: R) -> Array<B, T> {
                if B::FAST_PATHS && BinaryOp::$op.is_commutative() && !rhs.is_borrowed() {
                    // A commutative operation writes over a new right
                    // operand that is not shared.
                    let mut r = rhs.into_array();
                    if B::a_binary_assign::<T>(BinaryOp::$op, &mut r.0, &self.0) {
                        return r;
                    }
                    return broadcast_binary(BinaryOp::$op, self, &r);
                }
                rhs.with_array(|r| broadcast_binary(BinaryOp::$op, self, r))
            }
        }
        impl<B: Backend, T: $bound> ops::$tr<Array<B, T>> for Scalar<B, T> {
            type Output = Array<B, T>;
            #[track_caller]
            fn $f(self, rhs: Array<B, T>) -> Array<B, T> {
                broadcast_binary(BinaryOp::$op, &self.to_array(), &rhs)
            }
        }
        impl<B: Backend, T: $bound> ops::$tr<&Array<B, T>> for Scalar<B, T> {
            type Output = Array<B, T>;
            #[track_caller]
            fn $f(self, rhs: &Array<B, T>) -> Array<B, T> {
                broadcast_binary(BinaryOp::$op, &self.to_array(), rhs)
            }
        }
    )*};
}

array_binop! {
    Add add Add Numeric;
    Sub sub Sub Numeric;
    Mul mul Mul Numeric;
    Div div Div Numeric;
    Rem rem Rem Num;
    BitAnd bitand And Element;
    BitOr bitor Or Element;
    BitXor bitxor Xor Element;
}

macro_rules! array_lhs_literal {
    ($($t:ty)*) => {$(
        impl<B: Backend> ops::Add<Array<B, $t>> for $t {
            type Output = Array<B, $t>;
            fn add(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Add, &self.into_array(), &rhs) }
        }
        impl<B: Backend> ops::Sub<Array<B, $t>> for $t {
            type Output = Array<B, $t>;
            fn sub(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Sub, &self.into_array(), &rhs) }
        }
        impl<B: Backend> ops::Mul<Array<B, $t>> for $t {
            type Output = Array<B, $t>;
            fn mul(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Mul, &self.into_array(), &rhs) }
        }
        impl<B: Backend> ops::Div<Array<B, $t>> for $t {
            type Output = Array<B, $t>;
            fn div(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Div, &self.into_array(), &rhs) }
        }
    )*};
}

array_lhs_literal!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);

impl<B: Backend, T: Numeric> ops::Neg for Array<B, T> {
    type Output = Self;
    fn neg(self) -> Self {
        self.into_unary(UnaryOp::Neg)
    }
}

impl<B: Backend, T: Numeric> ops::Neg for &Array<B, T> {
    type Output = Array<B, T>;
    fn neg(self) -> Array<B, T> {
        self.unary(UnaryOp::Neg)
    }
}

impl<B: Backend, T: Element> ops::Not for Array<B, T> {
    type Output = Self;
    fn not(self) -> Self {
        self.into_unary(UnaryOp::Not)
    }
}

impl<B: Backend, T: Element> ops::Not for &Array<B, T> {
    type Output = Array<B, T>;
    fn not(self) -> Array<B, T> {
        self.unary(UnaryOp::Not)
    }
}

impl<B: Backend, T: Element> Array<B, T> {
    /// `self == other`, elementwise with broadcasting.
    #[track_caller]
    pub fn eq(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Eq, self, &other.into_array())
    }
    /// `self != other`.
    #[track_caller]
    pub fn ne(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Ne, self, &other.into_array())
    }
    /// `self < other`.
    #[track_caller]
    pub fn lt(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Lt, self, &other.into_array())
    }
    /// `self <= other`.
    #[track_caller]
    pub fn le(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Le, self, &other.into_array())
    }
    /// `self > other`.
    #[track_caller]
    pub fn gt(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Gt, self, &other.into_array())
    }
    /// `self >= other`.
    #[track_caller]
    pub fn ge(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
        broadcast_compare(CompareOp::Ge, self, &other.into_array())
    }
}