Skip to main content

ruxla_core/
lax.rs

1//! Operations following `jax.lax`: control flow, and primitives on arrays
2//! with strict shapes and types (operands of binary operations have the
3//! same shape).
4
5pub use ruxla_ir::FftType;
6use ruxla_ir::{DotDims, GatherDims, GatherScatterMode, Precision, ScatterDims, Shape};
7use ruxla_kernels::array::CumulativeOp;
8use ruxla_kernels::{BinaryOp, CompareOp, Element, TernaryOp, UnaryOp};
9
10use crate::backend::Backend;
11
12pub mod linalg;
13pub use crate::control::{
14    checkpoint, cond, custom_jvp, custom_vjp, fori_loop, scan, scan_reverse, select, select_with,
15    select_with_operand, switch, while_loop,
16};
17use crate::value::{Array, ComplexFloat, Float, Int, Num, Numeric, RealFloat, Scalar};
18
19mod conv;
20pub use conv::{
21    ConvOptions, Padding, conv, conv_dimension_numbers, conv_general_dilated,
22    conv_general_dilated_with,
23};
24mod window;
25pub use window::{
26    ReduceOp, reduce_window, reduce_window_max, reduce_window_min, reduce_window_sum,
27};
28
29macro_rules! unary_fns {
30    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
31        $(#[$m])*
32        pub fn $name<B: Backend, T: $bound>(x: &Array<B, T>) -> Array<B, T> {
33            x.unary(UnaryOp::$op)
34        }
35    )*};
36}
37
38unary_fns! { Num:
39    /// `-x`.
40    neg => Neg;
41    /// `|x|`.
42    abs => Abs;
43    /// The sign.
44    sign => Sign;
45    /// `x * x`.
46    square => Square;
47}
48
49unary_fns! { Float:
50    /// Round down.
51    floor => Floor;
52    /// Round up.
53    ceil => Ceil;
54    /// Round, halfway cases away from zero (`lax.round`'s default).
55    round => Round;
56    /// `e^x`.
57    exp => Exp;
58    /// `e^x - 1`.
59    expm1 => Expm1;
60    /// Natural logarithm.
61    log => Log;
62    /// `log(1 + x)`.
63    log1p => Log1p;
64    /// Square root.
65    sqrt => Sqrt;
66    /// `1 / sqrt(x)`.
67    rsqrt => Rsqrt;
68    /// Cube root.
69    cbrt => Cbrt;
70    /// Sine.
71    sin => Sin;
72    /// Cosine.
73    cos => Cos;
74    /// Tangent.
75    tan => Tan;
76    /// Hyperbolic tangent.
77    tanh => Tanh;
78    /// The logistic sigmoid.
79    logistic => Logistic;
80    /// The inverse error function.
81    erf_inv => ErfInv;
82    /// The logarithm of the absolute value of the gamma function.
83    lgamma => Lgamma;
84    /// The digamma function, the derivative of `lgamma`.
85    digamma => Digamma;
86    /// The error function.
87    erf => Erf;
88    /// The complementary error function, `1 - erf(x)`.
89    erfc => Erfc;
90    /// The exponentially scaled modified Bessel function of order 0,
91    /// `exp(-|x|) I0(x)`.
92    bessel_i0e => BesselI0e;
93    /// The exponentially scaled modified Bessel function of order 1,
94    /// `exp(-|x|) I1(x)`.
95    bessel_i1e => BesselI1e;
96}
97
98/// Logical or bitwise not.
99pub fn not<B: Backend, T: Element>(x: &Array<B, T>) -> Array<B, T> {
100    x.unary(UnaryOp::Not)
101}
102
103macro_rules! binary_fns {
104    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
105        $(#[$m])*
106        #[track_caller]
107        pub fn $name<B: Backend, T: $bound>(x: &Array<B, T>, y: &Array<B, T>) -> Array<B, T> {
108            Array(B::a_binary::<T>(BinaryOp::$op, &x.0, &y.0))
109        }
110    )*};
111}
112
113binary_fns! { Num:
114    /// `x + y`.
115    add => Add;
116    /// `x - y`.
117    sub => Sub;
118    /// `x * y`.
119    mul => Mul;
120    /// `x / y`.
121    div => Div;
122    /// Remainder of truncated division.
123    rem => Rem;
124}
125
126binary_fns! { Float:
127    /// `x^y`.
128    pow => Pow;
129    /// `atan2(x, y)`.
130    atan2 => Atan2;
131    /// The regularized lower incomplete gamma function `P(a, x)`.
132    igamma => Igamma;
133    /// The regularized upper incomplete gamma function `Q(a, x)`.
134    igammac => Igammac;
135    /// The derivative of `igamma(a, x)` with respect to `a`.
136    igamma_grad_a => IgammaGradA;
137    /// The derivative of a sample `x` of `Gamma(a, 1)` with respect to `a`.
138    random_gamma_grad => RandomGammaGrad;
139    /// The polygamma function `psi^(m)(x)` (`m` a natural number).
140    polygamma => Polygamma;
141    /// The Hurwitz zeta function `zeta(x, q)`.
142    zeta => Zeta;
143}
144
145/// The regularized incomplete beta function `I_x(a, b)`.
146#[track_caller]
147pub fn betainc<B: Backend, T: Float>(
148    a: &Array<B, T>,
149    b: &Array<B, T>,
150    x: &Array<B, T>,
151) -> Array<B, T> {
152    Array(B::a_ternary::<T>(
153        TernaryOp::RegularizedIncompleteBeta,
154        &a.0,
155        &b.0,
156        &x.0,
157    ))
158}
159
160binary_fns! { Element:
161    /// Maximum, propagating NaN.
162    max => Max;
163    /// Minimum, propagating NaN.
164    min => Min;
165    /// Logical or bitwise and.
166    and => And;
167    /// Logical or bitwise or.
168    or => Or;
169    /// Logical or bitwise exclusive or.
170    xor => Xor;
171}
172
173binary_fns! { Int:
174    /// `x << y`.
175    shift_left => ShiftLeft;
176    /// `x >> y`, filling with zeros.
177    shift_right_logical => ShiftRightLogical;
178    /// `x >> y`, filling with the sign bit.
179    shift_right_arithmetic => ShiftRightArithmetic;
180}
181
182macro_rules! compare_fns {
183    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
184        $(#[$m])*
185        #[track_caller]
186        pub fn $name<B: Backend, T: Element>(x: &Array<B, T>, y: &Array<B, T>) -> Array<B, bool> {
187            Array(B::a_compare::<T>(CompareOp::$op, &x.0, &y.0))
188        }
189    )*};
190}
191
192compare_fns! {
193    /// `x == y`.
194    eq => Eq;
195    /// `x != y`.
196    ne => Ne;
197    /// `x < y`.
198    lt => Lt;
199    /// `x <= y`.
200    le => Le;
201    /// `x > y`.
202    gt => Gt;
203    /// `x >= y`.
204    ge => Ge;
205}
206
207/// Complex numbers from their real and imaginary parts (`lax.complex`; the
208/// shapes must be equal).
209#[track_caller]
210pub fn complex<B: Backend, T: ComplexFloat>(
211    re: &Array<B, T::Real>,
212    im: &Array<B, T::Real>,
213) -> Array<B, T> {
214    Array::complex(re, im)
215}
216
217/// The real parts of complex numbers (`lax.real`).
218pub fn real<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T::Real> {
219    x.real()
220}
221
222/// The imaginary parts of complex numbers (`lax.imag`).
223pub fn imag<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T::Real> {
224    x.imag()
225}
226
227/// The complex conjugates (`lax.conj` of complex numbers).
228pub fn conj<B: Backend, T: ComplexFloat>(x: &Array<B, T>) -> Array<B, T> {
229    x.conj()
230}
231
232/// A complex-to-complex Fourier transform of the trailing axes
233/// (`lax.fft` with `FftType::Fft` or `FftType::Ifft`), of lengths
234/// `fft_lengths` (one to three, equal to the trailing dimensions). The
235/// inverse divides by the number of elements transformed.
236///
237/// # Panics
238///
239/// Panics if `fft_type` is a real transform, or the lengths do not match.
240#[track_caller]
241pub fn fft<B: Backend, C: ComplexFloat>(
242    x: &Array<B, C>,
243    fft_type: FftType,
244    fft_lengths: &[usize],
245) -> Array<B, C> {
246    assert!(
247        matches!(fft_type, FftType::Fft | FftType::Ifft),
248        "lax::fft computes complex transforms; use lax::rfft and lax::irfft"
249    );
250    Array(B::fft::<C, C>(&x.0, fft_type, fft_lengths))
251}
252
253/// The real-to-complex Fourier transform of the trailing axes (`lax.fft`
254/// with `FftType::Rfft`): the last axis has `n / 2 + 1` coefficients.
255#[track_caller]
256pub fn rfft<B: Backend, R: RealFloat>(
257    x: &Array<B, R>,
258    fft_lengths: &[usize],
259) -> Array<B, R::Complex> {
260    Array(B::fft::<R, R::Complex>(&x.0, FftType::Rfft, fft_lengths))
261}
262
263/// The complex-to-real inverse Fourier transform of the trailing axes
264/// (`lax.fft` with `FftType::Irfft`): the operand has `n / 2 + 1`
265/// coefficients along the last axis, and the result `n` real numbers.
266#[track_caller]
267pub fn irfft<B: Backend, C: ComplexFloat>(
268    x: &Array<B, C>,
269    fft_lengths: &[usize],
270) -> Array<B, C::Real> {
271    Array(B::fft::<C, C::Real>(&x.0, FftType::Irfft, fft_lengths))
272}
273
274/// Whether each element is finite.
275pub fn is_finite<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, bool> {
276    Array(B::a_is_finite::<T>(&x.0))
277}
278
279/// `x^y` for a static integer `y`.
280pub fn integer_pow<B: Backend, T: Numeric>(x: &Array<B, T>, y: i32) -> Array<B, T> {
281    Array(B::a_integer_pow::<T>(&x.0, y))
282}
283
284/// Converts to another element type.
285pub fn convert_element_type<B: Backend, T: Element, U: Element>(x: &Array<B, T>) -> Array<B, U> {
286    Array(B::a_cast::<T, U>(&x.0))
287}
288
289/// Reinterprets the bits as another element type of the same size.
290pub fn bitcast_convert_type<B: Backend, T: Element, U: Element>(x: &Array<B, T>) -> Array<B, U> {
291    Array(B::a_bitcast::<T, U>(&x.0))
292}
293
294/// `select_n(pred, on_false, on_true)` with `pred` a scalar or of the shape
295/// of the cases (`lax.select` on arrays).
296#[track_caller]
297pub fn select_array<B: Backend, T: Element>(
298    pred: &Array<B, bool>,
299    on_true: &Array<B, T>,
300    on_false: &Array<B, T>,
301) -> Array<B, T> {
302    Array(B::a_select::<T>(&pred.0, &on_true.0, &on_false.0))
303}
304
305/// `clamp(lo, x, hi)`: bounds are scalars or of the shape of `x`;
306/// propagates NaN.
307#[track_caller]
308pub fn clamp<B: Backend, T: Num>(
309    lo: &Array<B, T>,
310    x: &Array<B, T>,
311    hi: &Array<B, T>,
312) -> Array<B, T> {
313    Array(B::a_clamp::<T>(&lo.0, &x.0, &hi.0))
314}
315
316/// Broadcasts to `shape`: dimension `i` of `x` becomes dimension `dims[i]`.
317#[track_caller]
318pub fn broadcast_in_dim<B: Backend, T: Element>(
319    x: &Array<B, T>,
320    shape: impl Into<Shape>,
321    dims: &[usize],
322) -> Array<B, T> {
323    Array(B::broadcast_in_dim::<T>(&x.0, &shape.into(), dims))
324}
325
326/// Changes the shape, keeping the elements in row-major order.
327#[track_caller]
328pub fn reshape<B: Backend, T: Element>(x: &Array<B, T>, shape: impl Into<Shape>) -> Array<B, T> {
329    x.reshape(shape)
330}
331
332/// Permutes dimensions.
333#[track_caller]
334pub fn transpose<B: Backend, T: Element>(x: &Array<B, T>, perm: &[usize]) -> Array<B, T> {
335    x.transpose(perm)
336}
337
338/// A static slice. `strides` of `None` means 1.
339#[track_caller]
340pub fn slice<B: Backend, T: Element>(
341    x: &Array<B, T>,
342    start: &[usize],
343    limit: &[usize],
344    strides: Option<&[usize]>,
345) -> Array<B, T> {
346    let ones: Shape = start.iter().map(|_| 1).collect();
347    Array(B::slice::<T>(&x.0, start, limit, strides.unwrap_or(&ones)))
348}
349
350/// `x[start..limit:stride]` along one axis.
351#[track_caller]
352pub fn slice_in_dim<B: Backend, T: Element>(
353    x: &Array<B, T>,
354    start: usize,
355    limit: usize,
356    stride: usize,
357    axis: usize,
358) -> Array<B, T> {
359    let shape = x.shape();
360    let mut s: Shape = shape.iter().map(|_| 0).collect();
361    let mut l = shape.clone();
362    let mut st: Shape = shape.iter().map(|_| 1).collect();
363    s.set(axis, start);
364    l.set(axis, limit);
365    st.set(axis, stride);
366    slice(x, &s, &l, Some(&st))
367}
368
369/// Element `index` along `axis`, dropping the axis unless `keepdims`.
370#[track_caller]
371pub fn index_in_dim<B: Backend, T: Element>(
372    x: &Array<B, T>,
373    index: usize,
374    axis: usize,
375    keepdims: bool,
376) -> Array<B, T> {
377    let sliced = slice_in_dim(x, index, index + 1, 1, axis);
378    if keepdims {
379        return sliced;
380    }
381    let mut shape = x.shape();
382    shape.remove(axis);
383    sliced.reshape(shape)
384}
385
386/// Makes negative start indices count from the end, as `jax.lax` does.
387pub(crate) fn wrap_negative<B: Backend, I: Int>(index: Scalar<B, I>, size: usize) -> Scalar<B, I> {
388    if I::DTYPE.kind() != ruxla_ir::DTypeKind::SignedInt {
389        return index;
390    }
391    let zero = Scalar::new(ruxla_kernels::cast::<i64, I>(0));
392    let n = Scalar::new(ruxla_kernels::cast::<i64, I>(size as i64));
393    select(index.lt(zero), index + n, index)
394}
395
396/// A slice of `sizes` at run-time start indices. Negative indices count
397/// from the end, and indices are then clamped to keep the slice in bounds.
398#[track_caller]
399pub fn dynamic_slice<B: Backend, T: Element, I: Int>(
400    x: &Array<B, T>,
401    starts: &[Scalar<B, I>],
402    sizes: &[usize],
403) -> Array<B, T> {
404    let shape = x.shape();
405    assert_eq!(
406        starts.len(),
407        shape.rank(),
408        "dynamic_slice: one start index per dimension of [{shape}]"
409    );
410    let starts: Vec<B::Scalar<I>> = starts
411        .iter()
412        .zip(shape.dims())
413        .map(|(&s, &n)| wrap_negative(s, n).0)
414        .collect();
415    Array(B::dynamic_slice::<T, I>(&x.0, &starts, sizes))
416}
417
418/// Element `index` (a run-time index) along `axis`, dropping the axis unless
419/// `keepdims`.
420#[track_caller]
421pub fn dynamic_index_in_dim<B: Backend, T: Element, I: Int>(
422    x: &Array<B, T>,
423    index: Scalar<B, I>,
424    axis: usize,
425    keepdims: bool,
426) -> Array<B, T> {
427    let shape = x.shape();
428    assert!(
429        axis < shape.rank(),
430        "axis {axis} is out of range for shape [{shape}]"
431    );
432    let zero = Scalar::new(ruxla_kernels::cast::<i64, I>(0));
433    let starts: Vec<Scalar<B, I>> = (0..shape.rank())
434        .map(|d| if d == axis { index } else { zero })
435        .collect();
436    let mut sizes = shape.dims().to_vec();
437    sizes[axis] = 1;
438    let sliced = dynamic_slice(x, &starts, &sizes);
439    if keepdims {
440        return sliced;
441    }
442    let mut out = shape.dims().to_vec();
443    out.remove(axis);
444    sliced.reshape(out)
445}
446
447/// `x` with `update` written at run-time start indices (negative indices
448/// count from the end; indices are clamped to keep `update` in bounds).
449#[track_caller]
450pub fn dynamic_update_slice<B: Backend, T: Element, I: Int>(
451    x: &Array<B, T>,
452    update: &Array<B, T>,
453    starts: &[Scalar<B, I>],
454) -> Array<B, T> {
455    let shape = x.shape();
456    assert_eq!(
457        starts.len(),
458        shape.rank(),
459        "dynamic_update_slice: one start index per dimension of [{shape}]"
460    );
461    let starts: Vec<B::Scalar<I>> = starts
462        .iter()
463        .zip(shape.dims())
464        .map(|(&s, &n)| wrap_negative(s, n).0)
465        .collect();
466    Array(B::dynamic_update_slice::<T, I>(&x.0, &update.0, &starts))
467}
468
469/// Joins arrays along `dim`.
470#[track_caller]
471pub fn concatenate<B: Backend, T: Element>(xs: &[Array<B, T>], dim: usize) -> Array<B, T> {
472    Array(B::concatenate::<T>(Array::reprs(xs), dim))
473}
474
475/// Pads with `value`: `(low, high, interior)` per dimension.
476#[track_caller]
477pub fn pad<B: Backend, T: Element>(
478    x: &Array<B, T>,
479    value: impl Into<Scalar<B, T>>,
480    config: &[(i64, i64, usize)],
481) -> Array<B, T> {
482    Array(B::pad::<T>(&x.0, value.into().0, config))
483}
484
485/// Reverses dimensions.
486#[track_caller]
487pub fn rev<B: Backend, T: Element>(x: &Array<B, T>, dims: &[usize]) -> Array<B, T> {
488    Array(B::rev::<T>(&x.0, dims))
489}
490
491/// The indices along `dim` of each element of `shape`.
492pub fn iota<B: Backend, T: Num>(shape: impl Into<Shape>, dim: usize) -> Array<B, T> {
493    Array(B::iota::<T>(&shape.into(), dim))
494}
495
496/// Sums over `axes`.
497#[track_caller]
498pub fn reduce_sum<B: Backend, T: Numeric>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
499    x.reduce_sum(axes)
500}
501
502/// The maximum over `axes`.
503#[track_caller]
504pub fn reduce_max<B: Backend, T: Element>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
505    x.reduce_max(axes)
506}
507
508/// The minimum over `axes`.
509#[track_caller]
510pub fn reduce_min<B: Backend, T: Element>(x: &Array<B, T>, axes: &[usize]) -> Array<B, T> {
511    x.reduce_min(axes)
512}
513
514/// The index of the largest element along `axis` (NaN counts as largest;
515/// ties take the first index).
516#[track_caller]
517pub fn argmax<B: Backend, T: Element, I: Int>(x: &Array<B, T>, axis: usize) -> Array<B, I> {
518    Array(B::arg_min_max::<T, I>(&x.0, axis, true))
519}
520
521/// The index of the smallest element along `axis`.
522#[track_caller]
523pub fn argmin<B: Backend, T: Element, I: Int>(x: &Array<B, T>, axis: usize) -> Array<B, I> {
524    Array(B::arg_min_max::<T, I>(&x.0, axis, false))
525}
526
527/// Sorts along `dimension`, stably (`lax.sort` of one operand).
528///
529/// Floats are ordered as `-inf < ... < 0 < ... < inf < NaN`, with `-0.0`
530/// equal to `0.0` and all NaNs equal, as in JAX.
531///
532/// # Examples
533///
534/// ```
535/// use ruxla_core::{Array, Native, lax};
536///
537/// let x = Array::<Native, f32>::from_vec(vec![3.0, f32::NAN, -1.0, 2.0], [4]);
538/// let s = lax::sort(&x, 0).to_vec();
539/// assert_eq!(&s[..3], [-1.0, 2.0, 3.0]);
540/// assert!(s[3].is_nan());
541/// ```
542#[track_caller]
543pub fn sort<B: Backend, T: Element>(x: &Array<B, T>, dimension: usize) -> Array<B, T> {
544    if let Some((k, _)) = B::sort_key_val_typed::<T, T>(&x.0, &x.0, dimension) {
545        return Array(k);
546    }
547    let out = B::sort(&[B::array_leaf(&x.0)], dimension, true, 1);
548    Array(B::leaf_array::<T>(
549        out.into_iter().next().expect("one output"),
550    ))
551}
552
553/// Sorts `keys` along `dimension`, stably, and permutes `values` (of the
554/// same shape) in the same way (`lax.sort_key_val`).
555///
556/// # Examples
557///
558/// ```
559/// use ruxla_core::{Array, Native, lax};
560///
561/// let k = Array::<Native, u32>::from_vec(vec![3, 1, 2, 1], [4]);
562/// let v = Array::<Native, i32>::from_vec(vec![0, 1, 2, 3], [4]);
563/// let (k, v) = lax::sort_key_val(&k, &v, 0);
564/// assert_eq!(k.to_vec(), [1, 1, 2, 3]);
565/// assert_eq!(v.to_vec(), [1, 3, 2, 0]);
566/// ```
567#[track_caller]
568pub fn sort_key_val<B: Backend, K: Element, V: Element>(
569    keys: &Array<B, K>,
570    values: &Array<B, V>,
571    dimension: usize,
572) -> (Array<B, K>, Array<B, V>) {
573    if let Some((k, v)) = B::sort_key_val_typed::<K, V>(&keys.0, &values.0, dimension) {
574        return (Array(k), Array(v));
575    }
576    let mut out = B::sort(
577        &[B::array_leaf(&keys.0), B::array_leaf(&values.0)],
578        dimension,
579        true,
580        1,
581    )
582    .into_iter();
583    let k = B::leaf_array::<K>(out.next().expect("two outputs"));
584    let v = B::leaf_array::<V>(out.next().expect("two outputs"));
585    (Array(k), Array(v))
586}
587
588/// Sorts `operands` (of the same shape and element type) along
589/// `dimension`, stably and lexicographically by the first `num_keys` of
590/// them, and permutes the others in the same way (`lax.sort` with several
591/// operands and `num_keys`, as `jnp.lexsort` uses it).
592///
593/// # Examples
594///
595/// ```
596/// use ruxla_core::{Array, Native, lax};
597///
598/// let a = Array::<Native, i32>::from_vec(vec![1, 0, 1, 0], [4]);
599/// let b = Array::<Native, i32>::from_vec(vec![0, 1, 0, 0], [4]);
600/// let i = Array::<Native, i32>::from_vec(vec![0, 1, 2, 3], [4]);
601/// let out = lax::sort_multi(&[a, b, i], 0, 2);
602/// assert_eq!(out[2].to_vec(), [3, 1, 0, 2]);
603/// ```
604///
605/// # Panics
606///
607/// Panics if `num_keys` is zero or more than the number of operands.
608#[track_caller]
609pub fn sort_multi<B: Backend, T: Element>(
610    operands: &[Array<B, T>],
611    dimension: usize,
612    num_keys: usize,
613) -> Vec<Array<B, T>> {
614    assert!(
615        (1..=operands.len()).contains(&num_keys),
616        "sort_multi: num_keys {num_keys} out of range for {} operands",
617        operands.len()
618    );
619    let leaves: Vec<B::Leaf> = operands.iter().map(|x| B::array_leaf(&x.0)).collect();
620    B::sort(&leaves, dimension, true, num_keys)
621        .into_iter()
622        .map(|l| Array(B::leaf_array::<T>(l)))
623        .collect()
624}
625
626/// The cumulative sum along `axis` (`lax.cumsum`), from the end with
627/// `reverse`. Integers wrap around.
628///
629/// # Examples
630///
631/// ```
632/// use ruxla_core::{Array, Native, lax};
633///
634/// let x = Array::<Native, i32>::from_vec(vec![1, 2, 3, 4], [4]);
635/// assert_eq!(lax::cumsum(&x, 0, false).to_vec(), [1, 3, 6, 10]);
636/// assert_eq!(lax::cumsum(&x, 0, true).to_vec(), [10, 9, 7, 4]);
637/// ```
638#[track_caller]
639pub fn cumsum<B: Backend, T: Numeric>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
640    Array(B::cumulative::<T>(CumulativeOp::Sum, &x.0, axis, reverse))
641}
642
643/// The cumulative product along `axis` (`lax.cumprod`), from the end with
644/// `reverse`.
645#[track_caller]
646pub fn cumprod<B: Backend, T: Numeric>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
647    Array(B::cumulative::<T>(CumulativeOp::Prod, &x.0, axis, reverse))
648}
649
650/// The cumulative maximum along `axis` (`lax.cummax`), from the end with
651/// `reverse`. NaN propagates.
652///
653/// # Examples
654///
655/// ```
656/// use ruxla_core::{Array, Native, lax};
657///
658/// let x = Array::<Native, f32>::from_vec(vec![1.0, 3.0, 2.0, 5.0], [4]);
659/// assert_eq!(lax::cummax(&x, 0, false).to_vec(), [1.0, 3.0, 3.0, 5.0]);
660/// ```
661#[track_caller]
662pub fn cummax<B: Backend, T: Num>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
663    Array(B::cumulative::<T>(CumulativeOp::Max, &x.0, axis, reverse))
664}
665
666/// The cumulative minimum along `axis` (`lax.cummin`), from the end with
667/// `reverse`. NaN propagates.
668#[track_caller]
669pub fn cummin<B: Backend, T: Num>(x: &Array<B, T>, axis: usize, reverse: bool) -> Array<B, T> {
670    Array(B::cumulative::<T>(CumulativeOp::Min, &x.0, axis, reverse))
671}
672
673/// The cumulative `log(sum(exp(x)))` along `axis` (`lax.cumlogsumexp`),
674/// from the end with `reverse`.
675#[track_caller]
676pub fn cumlogsumexp<B: Backend, T: Float>(
677    x: &Array<B, T>,
678    axis: usize,
679    reverse: bool,
680) -> Array<B, T> {
681    Array(B::cumulative::<T>(
682        CumulativeOp::LogSumExp,
683        &x.0,
684        axis,
685        reverse,
686    ))
687}
688
689/// The `k` largest elements along the last axis in descending order, and
690/// their indices (`lax.top_k`). Equal elements keep their order; floats are
691/// ordered as `-NaN < -inf < ... < -0.0 < 0.0 < ... < inf < NaN` (by their
692/// bits, as XLA does).
693///
694/// # Panics
695///
696/// Panics if `x` is a scalar or `k` is larger than the last dimension.
697///
698/// # Examples
699///
700/// ```
701/// use ruxla_core::{Array, Native, lax};
702///
703/// let x = Array::<Native, f32>::from_vec(vec![9.0, 3.0, 6.0, 4.0, 10.0], [5]);
704/// let (values, indices) = lax::top_k(&x, 3);
705/// assert_eq!(values.to_vec(), [10.0, 9.0, 6.0]);
706/// assert_eq!(indices.to_vec(), [4, 0, 2]);
707/// ```
708#[track_caller]
709pub fn top_k<B: Backend, T: Element>(x: &Array<B, T>, k: usize) -> (Array<B, T>, Array<B, i32>) {
710    let rank = x.ndim();
711    assert!(rank > 0, "top_k needs an array with at least one dimension");
712    let (values, indices) = B::top_k::<T>(&x.0, k, rank - 1);
713    (Array(values), Array(indices))
714}
715
716/// `dot_general`, with the result in the operands' type.
717#[track_caller]
718pub fn dot_general<B: Backend, T: Numeric>(
719    lhs: &Array<B, T>,
720    rhs: &Array<B, T>,
721    dims: &DotDims,
722) -> Array<B, T> {
723    Array(B::dot_general::<T, T>(
724        &lhs.0,
725        &rhs.0,
726        dims,
727        Precision::Default,
728    ))
729}
730
731/// `dot_general` with a precision and a (wider) result type.
732#[track_caller]
733pub fn dot_general_with<B: Backend, T: Numeric, U: Numeric>(
734    lhs: &Array<B, T>,
735    rhs: &Array<B, T>,
736    dims: &DotDims,
737    precision: Precision,
738) -> Array<B, U> {
739    Array(B::dot_general::<T, U>(&lhs.0, &rhs.0, dims, precision))
740}
741
742/// `gather` (the index vector is the last dimension of `indices`).
743#[track_caller]
744pub fn gather<B: Backend, T: Element, I: Int>(
745    x: &Array<B, T>,
746    indices: &Array<B, I>,
747    dims: &GatherDims,
748    slice_sizes: &[usize],
749    mode: GatherScatterMode,
750) -> Array<B, T> {
751    Array(B::gather::<T, I>(
752        &x.0,
753        &indices.0,
754        dims,
755        slice_sizes,
756        mode,
757        false,
758    ))
759}
760
761macro_rules! scatter_fns {
762    ($($(#[$m:meta])* $name:ident => $combine:expr, $bound:ident;)*) => {$(
763        $(#[$m])*
764        #[track_caller]
765        pub fn $name<B: Backend, T: $bound, I: Int>(
766            x: &Array<B, T>,
767            indices: &Array<B, I>,
768            updates: &Array<B, T>,
769            dims: &ScatterDims,
770            mode: GatherScatterMode,
771        ) -> Array<B, T> {
772            Array(B::scatter::<T, I>($combine, &x.0, &indices.0, &updates.0, dims, mode, false))
773        }
774    )*};
775}
776
777scatter_fns! {
778    /// Writes `updates` at run-time start indices.
779    scatter => None, Element;
780    /// Adds `updates` at run-time start indices.
781    scatter_add => Some(BinaryOp::Add), Num;
782    /// Multiplies by `updates` at run-time start indices.
783    scatter_mul => Some(BinaryOp::Mul), Num;
784    /// Takes the minimum with `updates` at run-time start indices.
785    scatter_min => Some(BinaryOp::Min), Num;
786    /// Takes the maximum with `updates` at run-time start indices.
787    scatter_max => Some(BinaryOp::Max), Num;
788}