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
//! Operations following `jax.lax`: control flow, and primitives on arrays
//! with strict shapes and types (operands of binary operations have the
//! same shape).

pub use ruxla_ir::FftType;
use ruxla_ir::{DotDims, GatherDims, GatherScatterMode, Precision, ScatterDims, Shape};
use ruxla_kernels::array::CumulativeOp;
use ruxla_kernels::{BinaryOp, CompareOp, Element, TernaryOp, UnaryOp};

use crate::backend::Backend;

pub mod linalg;
pub use crate::control::{
    checkpoint, cond, custom_jvp, custom_vjp, fori_loop, scan, scan_reverse, select, select_with,
    select_with_operand, switch, while_loop,
};
use crate::value::{Array, ComplexFloat, Float, Int, Num, Numeric, RealFloat, Scalar};

mod conv;
pub use conv::{
    ConvOptions, Padding, conv, conv_dimension_numbers, conv_general_dilated,
    conv_general_dilated_with,
};
mod window;
pub use window::{
    ReduceOp, reduce_window, reduce_window_max, reduce_window_min, reduce_window_sum,
};

macro_rules! unary_fns {
    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
        $(#[$m])*
        pub fn $name<B: Backend, T: $bound>(x: &Array<B, T>) -> Array<B, T> {
            x.unary(UnaryOp::$op)
        }
    )*};
}

unary_fns! { Num:
    /// `-x`.
    neg => Neg;
    /// `|x|`.
    abs => Abs;
    /// The sign.
    sign => Sign;
    /// `x * x`.
    square => Square;
}

unary_fns! { Float:
    /// Round down.
    floor => Floor;
    /// Round up.
    ceil => Ceil;
    /// Round, halfway cases away from zero (`lax.round`'s default).
    round => Round;
    /// `e^x`.
    exp => Exp;
    /// `e^x - 1`.
    expm1 => Expm1;
    /// Natural logarithm.
    log => Log;
    /// `log(1 + x)`.
    log1p => Log1p;
    /// Square root.
    sqrt => Sqrt;
    /// `1 / sqrt(x)`.
    rsqrt => Rsqrt;
    /// Cube root.
    cbrt => Cbrt;
    /// Sine.
    sin => Sin;
    /// Cosine.
    cos => Cos;
    /// Tangent.
    tan => Tan;
    /// Hyperbolic tangent.
    tanh => Tanh;
    /// The logistic sigmoid.
    logistic => Logistic;
    /// The inverse error function.
    erf_inv => ErfInv;
    /// The logarithm of the absolute value of the gamma function.
    lgamma => Lgamma;
    /// The digamma function, the derivative of `lgamma`.
    digamma => Digamma;
    /// The error function.
    erf => Erf;
    /// The complementary error function, `1 - erf(x)`.
    erfc => Erfc;
    /// The exponentially scaled modified Bessel function of order 0,
    /// `exp(-|x|) I0(x)`.
    bessel_i0e => BesselI0e;
    /// The exponentially scaled modified Bessel function of order 1,
    /// `exp(-|x|) I1(x)`.
    bessel_i1e => BesselI1e;
}

/// Logical or bitwise not.
pub fn not<B: Backend, T: Element>(x: &Array<B, T>) -> Array<B, T> {
    x.unary(UnaryOp::Not)
}

macro_rules! binary_fns {
    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
        $(#[$m])*
        #[track_caller]
        pub fn $name<B: Backend, T: $bound>(x: &Array<B, T>, y: &Array<B, T>) -> Array<B, T> {
            Array(B::a_binary::<T>(BinaryOp::$op, &x.0, &y.0))
        }
    )*};
}

binary_fns! { Num:
    /// `x + y`.
    add => Add;
    /// `x - y`.
    sub => Sub;
    /// `x * y`.
    mul => Mul;
    /// `x / y`.
    div => Div;
    /// Remainder of truncated division.
    rem => Rem;
}

binary_fns! { Float:
    /// `x^y`.
    pow => Pow;
    /// `atan2(x, y)`.
    atan2 => Atan2;
    /// The regularized lower incomplete gamma function `P(a, x)`.
    igamma => Igamma;
    /// The regularized upper incomplete gamma function `Q(a, x)`.
    igammac => Igammac;
    /// The derivative of `igamma(a, x)` with respect to `a`.
    igamma_grad_a => IgammaGradA;
    /// The derivative of a sample `x` of `Gamma(a, 1)` with respect to `a`.
    random_gamma_grad => RandomGammaGrad;
    /// The polygamma function `psi^(m)(x)` (`m` a natural number).
    polygamma => Polygamma;
    /// The Hurwitz zeta function `zeta(x, q)`.
    zeta => Zeta;
}

/// The regularized incomplete beta function `I_x(a, b)`.
#[track_caller]
pub fn betainc<B: Backend, T: Float>(
    a: &Array<B, T>,
    b: &Array<B, T>,
    x: &Array<B, T>,
) -> Array<B, T> {
    Array(B::a_ternary::<T>(
        TernaryOp::RegularizedIncompleteBeta,
        &a.0,
        &b.0,
        &x.0,
    ))
}

binary_fns! { Element:
    /// Maximum, propagating NaN.
    max => Max;
    /// Minimum, propagating NaN.
    min => Min;
    /// Logical or bitwise and.
    and => And;
    /// Logical or bitwise or.
    or => Or;
    /// Logical or bitwise exclusive or.
    xor => Xor;
}

binary_fns! { Int:
    /// `x << y`.
    shift_left => ShiftLeft;
    /// `x >> y`, filling with zeros.
    shift_right_logical => ShiftRightLogical;
    /// `x >> y`, filling with the sign bit.
    shift_right_arithmetic => ShiftRightArithmetic;
}

macro_rules! compare_fns {
    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
        $(#[$m])*
        #[track_caller]
        pub fn $name<B: Backend, T: Element>(x: &Array<B, T>, y: &Array<B, T>) -> Array<B, bool> {
            Array(B::a_compare::<T>(CompareOp::$op, &x.0, &y.0))
        }
    )*};
}

compare_fns! {
    /// `x == y`.
    eq => Eq;
    /// `x != y`.
    ne => Ne;
    /// `x < y`.
    lt => Lt;
    /// `x <= y`.
    le => Le;
    /// `x > y`.
    gt => Gt;
    /// `x >= y`.
    ge => Ge;
}

/// Complex numbers from their real and imaginary parts (`lax.complex`; the
/// shapes must be equal).
#[track_caller]
pub fn complex<B: Backend, T: ComplexFloat>(
    re: &Array<B, T::Real>,
    im: &Array<B, T::Real>,
) -> Array<B, T> {
    Array::complex(re, im)
}

/// The real parts of complex numbers (`lax.real`).
pub fn real<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T::Real> {
    x.real()
}

/// The imaginary parts of complex numbers (`lax.imag`).
pub fn imag<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T::Real> {
    x.imag()
}

/// The complex conjugates (`lax.conj` of complex numbers).
pub fn conj<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T> {
    x.conj()
}

/// A complex-to-complex Fourier transform of the trailing axes
/// (`lax.fft` with `FftType::Fft` or `FftType::Ifft`), of lengths
/// `fft_lengths` (one to three, equal to the trailing dimensions). The
/// inverse divides by the number of elements transformed.
///
/// # Panics
///
/// Panics if `fft_type` is a real transform, or the lengths do not match.
#[track_caller]
pub fn fft<B: Backend, C: ComplexFloat>(
    x: &Array<B, C>,
    fft_type: FftType,
    fft_lengths: &[usize],
) -> Array<B, C> {
    assert!(
        matches!(fft_type, FftType::Fft | FftType::Ifft),
        "lax::fft computes complex transforms; use lax::rfft and lax::irfft"
    );
    Array(B::fft::<C, C>(&x.0, fft_type, fft_lengths))
}

/// The real-to-complex Fourier transform of the trailing axes (`lax.fft`
/// with `FftType::Rfft`): the last axis has `n / 2 + 1` coefficients.
#[track_caller]
pub fn rfft<B: Backend, R: RealFloat>(
    x: &Array<B, R>,
    fft_lengths: &[usize],
) -> Array<B, R::Complex> {
    Array(B::fft::<R, R::Complex>(&x.0, FftType::Rfft, fft_lengths))
}

/// The complex-to-real inverse Fourier transform of the trailing axes
/// (`lax.fft` with `FftType::Irfft`): the operand has `n / 2 + 1`
/// coefficients along the last axis, and the result `n` real numbers.
#[track_caller]
pub fn irfft<B: Backend, C: ComplexFloat>(
    x: &Array<B, C>,
    fft_lengths: &[usize],
) -> Array<B, C::Real> {
    Array(B::fft::<C, C::Real>(&x.0, FftType::Irfft, fft_lengths))
}

/// Whether each element is finite.
pub fn is_finite<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
    Array(B::a_is_finite::<T>(&x.0))
}

/// `x^y` for a static integer `y`.
pub fn integer_pow<B: Backend, T: Numeric>(x: &Array<B, T>, y: i32) -> Array<B, T> {
    Array(B::a_integer_pow::<T>(&x.0, y))
}

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

/// Reinterprets the bits as another element type of the same size.
pub fn bitcast_convert_type<B: Backend, T: Element, U: Element>(x: &Array<B, T>) -> Array<B, U> {
    Array(B::a_bitcast::<T, U>(&x.0))
}

/// `select_n(pred, on_false, on_true)` with `pred` a scalar or of the shape
/// of the cases (`lax.select` on arrays).
#[track_caller]
pub fn select_array<B: Backend, T: Element>(
    pred: &Array<B, bool>,
    on_true: &Array<B, T>,
    on_false: &Array<B, T>,
) -> Array<B, T> {
    Array(B::a_select::<T>(&pred.0, &on_true.0, &on_false.0))
}

/// `clamp(lo, x, hi)`: bounds are scalars or of the shape of `x`;
/// propagates NaN.
#[track_caller]
pub fn clamp<B: Backend, T: Num>(
    lo: &Array<B, T>,
    x: &Array<B, T>,
    hi: &Array<B, T>,
) -> Array<B, T> {
    Array(B::a_clamp::<T>(&lo.0, &x.0, &hi.0))
}

/// Broadcasts to `shape`: dimension `i` of `x` becomes dimension `dims[i]`.
#[track_caller]
pub fn broadcast_in_dim<B: Backend, T: Element>(
    x: &Array<B, T>,
    shape: impl Into<Shape>,
    dims: &[usize],
) -> Array<B, T> {
    Array(B::broadcast_in_dim::<T>(&x.0, &shape.into(), dims))
}

/// Changes the shape, keeping the elements in row-major order.
#[track_caller]
pub fn reshape<B: Backend, T: Element>(x: &Array<B, T>, shape: impl Into<Shape>) -> Array<B, T> {
    x.reshape(shape)
}

/// Permutes dimensions.
#[track_caller]
pub fn transpose<B: Backend, T: Element>(x: &Array<B, T>, perm: &[usize]) -> Array<B, T> {
    x.transpose(perm)
}

/// A static slice. `strides` of `None` means 1.
#[track_caller]
pub fn slice<B: Backend, T: Element>(
    x: &Array<B, T>,
    start: &[usize],
    limit: &[usize],
    strides: Option<&[usize]>,
) -> Array<B, T> {
    let ones: Shape = start.iter().map(|_| 1).collect();
    Array(B::slice::<T>(&x.0, start, limit, strides.unwrap_or(&ones)))
}

/// `x[start..limit:stride]` along one axis.
#[track_caller]
pub fn slice_in_dim<B: Backend, T: Element>(
    x: &Array<B, T>,
    start: usize,
    limit: usize,
    stride: usize,
    axis: usize,
) -> Array<B, T> {
    let shape = x.shape();
    let mut s: Shape = shape.iter().map(|_| 0).collect();
    let mut l = shape.clone();
    let mut st: Shape = shape.iter().map(|_| 1).collect();
    s.set(axis, start);
    l.set(axis, limit);
    st.set(axis, stride);
    slice(x, &s, &l, Some(&st))
}

/// Element `index` along `axis`, dropping the axis unless `keepdims`.
#[track_caller]
pub fn index_in_dim<B: Backend, T: Element>(
    x: &Array<B, T>,
    index: usize,
    axis: usize,
    keepdims: bool,
) -> Array<B, T> {
    let sliced = slice_in_dim(x, index, index + 1, 1, axis);
    if keepdims {
        return sliced;
    }
    let mut shape = x.shape();
    shape.remove(axis);
    sliced.reshape(shape)
}

/// Makes negative start indices count from the end, as `jax.lax` does.
pub(crate) fn wrap_negative<B: Backend, I: Int>(index: Scalar<B, I>, size: usize) -> Scalar<B, I> {
    if I::DTYPE.kind() != ruxla_ir::DTypeKind::SignedInt {
        return index;
    }
    let zero = Scalar::new(ruxla_kernels::cast::<i64, I>(0));
    let n = Scalar::new(ruxla_kernels::cast::<i64, I>(size as i64));
    select(index.lt(zero), index + n, index)
}

/// A slice of `sizes` at run-time start indices. Negative indices count
/// from the end, and indices are then clamped to keep the slice in bounds.
#[track_caller]
pub fn dynamic_slice<B: Backend, T: Element, I: Int>(
    x: &Array<B, T>,
    starts: &[Scalar<B, I>],
    sizes: &[usize],
) -> Array<B, T> {
    let shape = x.shape();
    assert_eq!(
        starts.len(),
        shape.rank(),
        "dynamic_slice: one start index per dimension of [{shape}]"
    );
    let starts: Vec<B::Scalar<I>> = starts
        .iter()
        .zip(shape.dims())
        .map(|(&s, &n)| wrap_negative(s, n).0)
        .collect();
    Array(B::dynamic_slice::<T, I>(&x.0, &starts, sizes))
}

/// Element `index` (a run-time index) along `axis`, dropping the axis unless
/// `keepdims`.
#[track_caller]
pub fn dynamic_index_in_dim<B: Backend, T: Element, I: Int>(
    x: &Array<B, T>,
    index: Scalar<B, I>,
    axis: usize,
    keepdims: bool,
) -> Array<B, T> {
    let shape = x.shape();
    assert!(
        axis < shape.rank(),
        "axis {axis} is out of range for shape [{shape}]"
    );
    let zero = Scalar::new(ruxla_kernels::cast::<i64, I>(0));
    let starts: Vec<Scalar<B, I>> = (0..shape.rank())
        .map(|d| if d == axis { index } else { zero })
        .collect();
    let mut sizes = shape.dims().to_vec();
    sizes[axis] = 1;
    let sliced = dynamic_slice(x, &starts, &sizes);
    if keepdims {
        return sliced;
    }
    let mut out = shape.dims().to_vec();
    out.remove(axis);
    sliced.reshape(out)
}

/// `x` with `update` written at run-time start indices (negative indices
/// count from the end; indices are clamped to keep `update` in bounds).
#[track_caller]
pub fn dynamic_update_slice<B: Backend, T: Element, I: Int>(
    x: &Array<B, T>,
    update: &Array<B, T>,
    starts: &[Scalar<B, I>],
) -> Array<B, T> {
    let shape = x.shape();
    assert_eq!(
        starts.len(),
        shape.rank(),
        "dynamic_update_slice: one start index per dimension of [{shape}]"
    );
    let starts: Vec<B::Scalar<I>> = starts
        .iter()
        .zip(shape.dims())
        .map(|(&s, &n)| wrap_negative(s, n).0)
        .collect();
    Array(B::dynamic_update_slice::<T, I>(&x.0, &update.0, &starts))
}

/// Joins arrays along `dim`.
#[track_caller]
pub fn concatenate<B: Backend, T: Element>(xs: &[Array<B, T>], dim: usize) -> Array<B, T> {
    Array(B::concatenate::<T>(Array::reprs(xs), dim))
}

/// Pads with `value`: `(low, high, interior)` per dimension.
#[track_caller]
pub fn pad<B: Backend, T: Element>(
    x: &Array<B, T>,
    value: impl Into<Scalar<B, T>>,
    config: &[(i64, i64, usize)],
) -> Array<B, T> {
    Array(B::pad::<T>(&x.0, value.into().0, config))
}

/// Reverses dimensions.
#[track_caller]
pub fn rev<B: Backend, T: Element>(x: &Array<B, T>, dims: &[usize]) -> Array<B, T> {
    Array(B::rev::<T>(&x.0, dims))
}

/// The indices along `dim` of each element of `shape`.
pub fn iota<B: Backend, T: Num>(shape: impl Into<Shape>, dim: usize) -> Array<B, T> {
    Array(B::iota::<T>(&shape.into(), dim))
}

/// Sums over `axes`.
#[track_caller]
pub fn reduce_sum<B: Backend, T: Numeric>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
    x.reduce_sum(axes)
}

/// The maximum over `axes`.
#[track_caller]
pub fn reduce_max<B: Backend, T: Element>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
    x.reduce_max(axes)
}

/// The minimum over `axes`.
#[track_caller]
pub fn reduce_min<B: Backend, T: Element>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
    x.reduce_min(axes)
}

/// The index of the largest element along `axis` (NaN counts as largest;
/// ties take the first index).
#[track_caller]
pub fn argmax<B: Backend, T: Element, I: Int>(x: &Array<B, T>, axis: usize) -> Array<B, I> {
    Array(B::arg_min_max::<T, I>(&x.0, axis, true))
}

/// The index of the smallest element along `axis`.
#[track_caller]
pub fn argmin<B: Backend, T: Element, I: Int>(x: &Array<B, T>, axis: usize) -> Array<B, I> {
    Array(B::arg_min_max::<T, I>(&x.0, axis, false))
}

/// Sorts along `dimension`, stably (`lax.sort` of one operand).
///
/// Floats are ordered as `-inf < ... < 0 < ... < inf < NaN`, with `-0.0`
/// equal to `0.0` and all NaNs equal, as in JAX.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, f32>::from_vec(vec![3.0, f32::NAN, -1.0, 2.0], [4]);
/// let s = lax::sort(&x, 0).to_vec();
/// assert_eq!(&s[..3], [-1.0, 2.0, 3.0]);
/// assert!(s[3].is_nan());
/// ```
#[track_caller]
pub fn sort<B: Backend, T: Element>(x: &Array<B, T>, dimension: usize) -> Array<B, T> {
    if let Some((k, _)) = B::sort_key_val_typed::<T, T>(&x.0, &x.0, dimension) {
        return Array(k);
    }
    let out = B::sort(&[B::array_leaf(&x.0)], dimension, true, 1);
    Array(B::leaf_array::<T>(
        out.into_iter().next().expect("one output"),
    ))
}

/// Sorts `keys` along `dimension`, stably, and permutes `values` (of the
/// same shape) in the same way (`lax.sort_key_val`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let k = Array::<Native, u32>::from_vec(vec![3, 1, 2, 1], [4]);
/// let v = Array::<Native, i32>::from_vec(vec![0, 1, 2, 3], [4]);
/// let (k, v) = lax::sort_key_val(&k, &v, 0);
/// assert_eq!(k.to_vec(), [1, 1, 2, 3]);
/// assert_eq!(v.to_vec(), [1, 3, 2, 0]);
/// ```
#[track_caller]
pub fn sort_key_val<B: Backend, K: Element, V: Element>(
    keys: &Array<B, K>,
    values: &Array<B, V>,
    dimension: usize,
) -> (Array<B, K>, Array<B, V>) {
    if let Some((k, v)) = B::sort_key_val_typed::<K, V>(&keys.0, &values.0, dimension) {
        return (Array(k), Array(v));
    }
    let mut out = B::sort(
        &[B::array_leaf(&keys.0), B::array_leaf(&values.0)],
        dimension,
        true,
        1,
    )
    .into_iter();
    let k = B::leaf_array::<K>(out.next().expect("two outputs"));
    let v = B::leaf_array::<V>(out.next().expect("two outputs"));
    (Array(k), Array(v))
}

/// Sorts `operands` (of the same shape and element type) along
/// `dimension`, stably and lexicographically by the first `num_keys` of
/// them, and permutes the others in the same way (`lax.sort` with several
/// operands and `num_keys`, as `jnp.lexsort` uses it).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let a = Array::<Native, i32>::from_vec(vec![1, 0, 1, 0], [4]);
/// let b = Array::<Native, i32>::from_vec(vec![0, 1, 0, 0], [4]);
/// let i = Array::<Native, i32>::from_vec(vec![0, 1, 2, 3], [4]);
/// let out = lax::sort_multi(&[a, b, i], 0, 2);
/// assert_eq!(out[2].to_vec(), [3, 1, 0, 2]);
/// ```
///
/// # Panics
///
/// Panics if `num_keys` is zero or more than the number of operands.
#[track_caller]
pub fn sort_multi<B: Backend, T: Element>(
    operands: &[Array<B, T>],
    dimension: usize,
    num_keys: usize,
) -> Vec<Array<B, T>> {
    assert!(
        (1..=operands.len()).contains(&num_keys),
        "sort_multi: num_keys {num_keys} out of range for {} operands",
        operands.len()
    );
    let leaves: Vec<B::Leaf> = operands.iter().map(|x| B::array_leaf(&x.0)).collect();
    B::sort(&leaves, dimension, true, num_keys)
        .into_iter()
        .map(|l| Array(B::leaf_array::<T>(l)))
        .collect()
}

/// The cumulative sum along `axis` (`lax.cumsum`), from the end with
/// `reverse`. Integers wrap around.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, i32>::from_vec(vec![1, 2, 3, 4], [4]);
/// assert_eq!(lax::cumsum(&x, 0, false).to_vec(), [1, 3, 6, 10]);
/// assert_eq!(lax::cumsum(&x, 0, true).to_vec(), [10, 9, 7, 4]);
/// ```
#[track_caller]
pub fn cumsum<B: Backend, T: Numeric>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
    Array(B::cumulative::<T>(CumulativeOp::Sum, &x.0, axis, reverse))
}

/// The cumulative product along `axis` (`lax.cumprod`), from the end with
/// `reverse`.
#[track_caller]
pub fn cumprod<B: Backend, T: Numeric>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
    Array(B::cumulative::<T>(CumulativeOp::Prod, &x.0, axis, reverse))
}

/// The cumulative maximum along `axis` (`lax.cummax`), from the end with
/// `reverse`. NaN propagates.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, f32>::from_vec(vec![1.0, 3.0, 2.0, 5.0], [4]);
/// assert_eq!(lax::cummax(&x, 0, false).to_vec(), [1.0, 3.0, 3.0, 5.0]);
/// ```
#[track_caller]
pub fn cummax<B: Backend, T: Num>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
    Array(B::cumulative::<T>(CumulativeOp::Max, &x.0, axis, reverse))
}

/// The cumulative minimum along `axis` (`lax.cummin`), from the end with
/// `reverse`. NaN propagates.
#[track_caller]
pub fn cummin<B: Backend, T: Num>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
    Array(B::cumulative::<T>(CumulativeOp::Min, &x.0, axis, reverse))
}

/// The cumulative `log(sum(exp(x)))` along `axis` (`lax.cumlogsumexp`),
/// from the end with `reverse`.
#[track_caller]
pub fn cumlogsumexp<B: Backend, T: Float>(
    x: &Array<B, T>,
    axis: usize,
    reverse: bool,
) -> Array<B, T> {
    Array(B::cumulative::<T>(
        CumulativeOp::LogSumExp,
        &x.0,
        axis,
        reverse,
    ))
}

/// The `k` largest elements along the last axis in descending order, and
/// their indices (`lax.top_k`). Equal elements keep their order; floats are
/// ordered as `-NaN < -inf < ... < -0.0 < 0.0 < ... < inf < NaN` (by their
/// bits, as XLA does).
///
/// # Panics
///
/// Panics if `x` is a scalar or `k` is larger than the last dimension.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Native, lax};
///
/// let x = Array::<Native, f32>::from_vec(vec![9.0, 3.0, 6.0, 4.0, 10.0], [5]);
/// let (values, indices) = lax::top_k(&x, 3);
/// assert_eq!(values.to_vec(), [10.0, 9.0, 6.0]);
/// assert_eq!(indices.to_vec(), [4, 0, 2]);
/// ```
#[track_caller]
pub fn top_k<B: Backend, T: Element>(x: &Array<B, T>, k: usize) -> (Array<B, T>, Array<B, i32>) {
    let rank = x.ndim();
    assert!(rank > 0, "top_k needs an array with at least one dimension");
    let (values, indices) = B::top_k::<T>(&x.0, k, rank - 1);
    (Array(values), Array(indices))
}

/// `dot_general`, with the result in the operands' type.
#[track_caller]
pub fn dot_general<B: Backend, T: Numeric>(
    lhs: &Array<B, T>,
    rhs: &Array<B, T>,
    dims: &DotDims,
) -> Array<B, T> {
    Array(B::dot_general::<T, T>(
        &lhs.0,
        &rhs.0,
        dims,
        Precision::Default,
    ))
}

/// `dot_general` with a precision and a (wider) result type.
#[track_caller]
pub fn dot_general_with<B: Backend, T: Numeric, U: Numeric>(
    lhs: &Array<B, T>,
    rhs: &Array<B, T>,
    dims: &DotDims,
    precision: Precision,
) -> Array<B, U> {
    Array(B::dot_general::<T, U>(&lhs.0, &rhs.0, dims, precision))
}

/// `gather` (the index vector is the last dimension of `indices`).
#[track_caller]
pub fn gather<B: Backend, T: Element, I: Int>(
    x: &Array<B, T>,
    indices: &Array<B, I>,
    dims: &GatherDims,
    slice_sizes: &[usize],
    mode: GatherScatterMode,
) -> Array<B, T> {
    Array(B::gather::<T, I>(
        &x.0,
        &indices.0,
        dims,
        slice_sizes,
        mode,
        false,
    ))
}

macro_rules! scatter_fns {
    ($($(#[$m:meta])* $name:ident => $combine:expr, $bound:ident;)*) => {$(
        $(#[$m])*
        #[track_caller]
        pub fn $name<B: Backend, T: $bound, I: Int>(
            x: &Array<B, T>,
            indices: &Array<B, I>,
            updates: &Array<B, T>,
            dims: &ScatterDims,
            mode: GatherScatterMode,
        ) -> Array<B, T> {
            Array(B::scatter::<T, I>($combine, &x.0, &indices.0, &updates.0, dims, mode, false))
        }
    )*};
}

scatter_fns! {
    /// Writes `updates` at run-time start indices.
    scatter => None, Element;
    /// Adds `updates` at run-time start indices.
    scatter_add => Some(BinaryOp::Add), Num;
    /// Multiplies by `updates` at run-time start indices.
    scatter_mul => Some(BinaryOp::Mul), Num;
    /// Takes the minimum with `updates` at run-time start indices.
    scatter_min => Some(BinaryOp::Min), Num;
    /// Takes the maximum with `updates` at run-time start indices.
    scatter_max => Some(BinaryOp::Max), Num;
}