1pub mod fft;
8
9use ruxla_ir::{DotDims, GatherDims, GatherScatterMode, RoundingMethod, Shape};
10use ruxla_kernels::{BinaryOp, Element, UnaryOp, bf16, f16};
11
12use crate::backend::Backend;
13
14pub mod linalg;
15use crate::lax;
16use crate::value::{
17 Array, ArrayLike, ComplexFloat, Float, Inexact, Int, Num, Numeric, Scalar, broadcast_binary,
18 broadcast_compare, broadcast_shapes,
19};
20
21#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Axes {
25 All,
27 Some(Vec<i64>),
29 Few(AxisList),
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct AxisList {
37 len: u8,
38 axes: [i64; 8],
39}
40
41impl AxisList {
42 pub fn new(axes: &[i64]) -> Option<Self> {
44 let mut out = AxisList {
45 len: axes.len() as u8,
46 axes: [0; 8],
47 };
48 out.axes.get_mut(..axes.len())?.copy_from_slice(axes);
49 Some(out)
50 }
51
52 pub fn as_slice(&self) -> &[i64] {
54 &self.axes[..usize::from(self.len)]
55 }
56}
57
58impl Axes {
59 fn of(a: &[i64]) -> Self {
60 AxisList::new(a).map_or_else(|| Axes::Some(a.to_vec()), Axes::Few)
61 }
62
63 pub fn as_slice(&self) -> Option<&[i64]> {
65 match self {
66 Axes::All => None,
67 Axes::Some(a) => Some(a),
68 Axes::Few(a) => Some(a.as_slice()),
69 }
70 }
71}
72
73pub const ALL: Axes = Axes::All;
75
76impl From<i64> for Axes {
77 fn from(a: i64) -> Self {
78 Axes::of(&[a])
79 }
80}
81
82impl From<i32> for Axes {
83 fn from(a: i32) -> Self {
84 Axes::of(&[i64::from(a)])
85 }
86}
87
88impl From<&[i64]> for Axes {
89 fn from(a: &[i64]) -> Self {
90 Axes::of(a)
91 }
92}
93
94impl<const N: usize> From<[i64; N]> for Axes {
95 fn from(a: [i64; N]) -> Self {
96 Axes::of(&a)
97 }
98}
99
100#[track_caller]
102pub(crate) fn normalize_axis(axis: i64, rank: usize) -> usize {
103 let r = rank as i64;
104 assert!(
105 (-r..r).contains(&axis),
106 "axis {axis} is out of range for rank {rank}"
107 );
108 (if axis < 0 { axis + r } else { axis }) as usize
109}
110
111impl Axes {
112 #[track_caller]
113 fn resolve(&self, rank: usize) -> Shape {
114 match self.as_slice() {
115 None => (0..rank).collect(),
116 Some(a) => {
117 let mut v: Shape = a.iter().map(|&x| normalize_axis(x, rank)).collect();
118 for i in 1..v.rank() {
120 let mut j = i;
121 while j > 0 && v[j - 1] > v[j] {
122 let (a, b) = (v[j - 1], v[j]);
123 v.set(j - 1, b);
124 v.set(j, a);
125 j -= 1;
126 }
127 }
128 v
129 }
130 }
131 }
132}
133
134pub fn full<B: Backend, T: Element>(
136 shape: impl Into<Shape>,
137 value: impl Into<Scalar<B, T>>,
138) -> Array<B, T> {
139 let shape = shape.into();
140 let value = value.into();
141 if B::FAST_PATHS
142 && let Some(x) = B::full::<T>(shape.clone(), value.0)
143 {
144 return Array(x);
145 }
146 let s = value.to_array();
147 if shape.rank() == 0 {
148 return s;
149 }
150 lax::broadcast_in_dim(&s, shape, &[])
151}
152
153pub fn zeros<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
155 full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(0)))
156}
157
158pub fn ones<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
160 full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(1)))
161}
162
163pub fn arange<B: Backend, T: Num>(n: usize) -> Array<B, T> {
165 lax::iota([n], 0)
166}
167
168pub fn astype<B: Backend, T: Element, U: Element>(x: impl ArrayLike<B, T>) -> Array<B, U> {
170 x.into_array().cast()
171}
172
173#[track_caller]
175pub fn broadcast_to<B: Backend, T: Element>(
176 x: impl ArrayLike<B, T>,
177 shape: impl Into<Shape>,
178) -> Array<B, T> {
179 x.into_array().broadcast_to(shape)
180}
181
182macro_rules! unary {
183 ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
184 $(#[$m])*
185 pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>) -> Array<B, T> {
186 x.with_array(|x| x.unary(UnaryOp::$op))
187 }
188 )*};
189}
190
191unary! { Numeric:
192 negative => Neg;
194 sign => Sign;
196 square => Square;
198}
199
200pub fn abs<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
203 x.with_array(|x| x.abs())
204}
205
206pub fn real<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
208 x.with_array(|x| x.real())
209}
210
211pub fn imag<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
213 x.with_array(|x| x.imag())
214}
215
216pub fn conj<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
218 x.with_array(|x| x.conj())
219}
220
221pub fn conjugate<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
223 conj(x)
224}
225
226pub fn angle<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
228 x.with_array(|x| x.angle())
229}
230
231unary! { Float:
232 floor => Floor;
234 ceil => Ceil;
236 round => RoundEven;
238 cbrt => Cbrt;
240}
241
242unary! { Inexact:
243 exp => Exp;
245 expm1 => Expm1;
247 log => Log;
249 log1p => Log1p;
251 sqrt => Sqrt;
253 sin => Sin;
255 cos => Cos;
257 tan => Tan;
259 tanh => Tanh;
261}
262
263pub fn logical_not<B: Backend>(x: impl ArrayLike<B, bool>) -> Array<B, bool> {
265 x.into_array().unary(UnaryOp::Not)
266}
267
268pub fn isfinite<B: Backend, T: Float>(x: impl ArrayLike<B, T>) -> Array<B, bool> {
270 lax::is_finite(&x.into_array())
271}
272
273macro_rules! binary {
274 ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
275 $(#[$m])*
276 #[track_caller]
277 pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>, y: impl ArrayLike<B, T>) -> Array<B, T> {
278 x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::$op, x, y)))
279 }
280 )*};
281}
282
283binary! { Numeric:
284 add => Add;
286 subtract => Sub;
288 multiply => Mul;
290}
291
292binary! { Num:
293 fmod => Rem;
295}
296
297binary! { Inexact:
298 divide => Div;
300 power => Pow;
302}
303
304binary! { Float:
305 arctan2 => Atan2;
307}
308
309binary! { Element:
310 maximum => Max;
312 minimum => Min;
314}
315
316#[track_caller]
318pub fn logical_and<B: Backend>(
319 x: impl ArrayLike<B, bool>,
320 y: impl ArrayLike<B, bool>,
321) -> Array<B, bool> {
322 x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::And, x, y)))
323}
324
325#[track_caller]
327pub fn logical_or<B: Backend>(
328 x: impl ArrayLike<B, bool>,
329 y: impl ArrayLike<B, bool>,
330) -> Array<B, bool> {
331 x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::Or, x, y)))
332}
333
334#[track_caller]
349pub fn floor_divide<B: Backend, T: Int>(
350 x: impl ArrayLike<B, T>,
351 y: impl ArrayLike<B, T>,
352) -> Array<B, T> {
353 let (x, y) = (x.into_array(), y.into_array());
354 let q = broadcast_binary(BinaryOp::Div, &x, &y);
355 if T::DTYPE.kind() == ruxla_kernels::DTypeKind::UnsignedInt {
356 return q;
357 }
358 let r = broadcast_binary(BinaryOp::Rem, &x, &y);
359 let zero = zeros::<B, T>(r.shape());
360 let adjust = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &zero)
362 & broadcast_compare(ruxla_kernels::CompareOp::Ne, &x.sign(), &y.sign());
363 where_(adjust, &q - Scalar::new(ruxla_kernels::cast::<u8, T>(1)), q)
364}
365
366#[track_caller]
379pub fn remainder<B: Backend, T: Num>(
380 x: impl ArrayLike<B, T>,
381 y: impl ArrayLike<B, T>,
382) -> Array<B, T> {
383 let zero = ruxla_kernels::cast::<u8, T>(0);
384 let one = ruxla_kernels::cast::<u8, T>(1);
385 let int = !T::DTYPE.is_float();
386 if B::FAST_PATHS
387 && let (Some(a), Some(b)) = (x.as_scalar(), y.as_scalar())
388 {
389 let lt = |v| B::compare::<T>(ruxla_kernels::CompareOp::Lt, v, B::lit(zero));
390 let ne = |v| B::compare::<T>(ruxla_kernels::CompareOp::Ne, v, B::lit(zero));
391 let b = if int {
392 B::select(
393 B::compare::<T>(ruxla_kernels::CompareOp::Eq, b.0, B::lit(zero)),
394 B::lit(one),
395 b.0,
396 )
397 } else {
398 b.0
399 };
400 let r = B::binary::<T>(BinaryOp::Rem, a.0, b);
401 let plus = B::binary::<bool>(
402 BinaryOp::And,
403 B::compare::<bool>(ruxla_kernels::CompareOp::Ne, lt(r), lt(b)),
404 ne(r),
405 );
406 return Scalar(B::select(plus, B::binary::<T>(BinaryOp::Add, r, b), r)).to_array();
407 }
408 let (x, y) = (x.into_array(), y.into_array());
409 let y = if int {
410 let z = zeros::<B, T>(y.shape());
411 where_(
412 broadcast_compare(ruxla_kernels::CompareOp::Eq, &y, &z),
413 Scalar::<B, T>::new(one),
414 &y,
415 )
416 } else {
417 y
418 };
419 let r = broadcast_binary(BinaryOp::Rem, &x, &y);
420 let rz = zeros::<B, T>(r.shape());
421 let not_zero = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &rz);
422 let yz = zeros::<B, T>(y.shape());
423 let plus = broadcast_compare(
424 ruxla_kernels::CompareOp::Ne,
425 &r.lt(&rz),
426 &y.lt(&yz).broadcast_to(r.shape()),
427 ) & not_zero;
428 where_(plus, broadcast_binary(BinaryOp::Add, &r, &y), r)
429}
430
431#[track_caller]
433pub fn where_<B: Backend, T: Element>(
434 cond: impl ArrayLike<B, bool>,
435 x: impl ArrayLike<B, T>,
436 y: impl ArrayLike<B, T>,
437) -> Array<B, T> {
438 let (c, x, y) = (cond.into_array(), x.into_array(), y.into_array());
439 if B::FAST_PATHS
440 && let Some(r) = B::a_select_broadcast::<T>(&c.0, &x.0, &y.0)
441 {
442 return Array(r);
443 }
444 let s = broadcast_shapes(&broadcast_shapes(&c.shape(), &x.shape()), &y.shape());
445 lax::select_array(
446 &c.broadcast_to(s.clone()),
447 &x.broadcast_to(s.clone()),
448 &y.broadcast_to(s),
449 )
450}
451
452#[track_caller]
454pub fn clip<B: Backend, T: Element>(
455 x: impl ArrayLike<B, T>,
456 lo: impl ArrayLike<B, T>,
457 hi: impl ArrayLike<B, T>,
458) -> Array<B, T> {
459 if B::FAST_PATHS
460 && let (Some(x), Some(lo), Some(hi)) = (x.as_scalar(), lo.as_scalar(), hi.as_scalar())
461 {
462 return Scalar(B::binary::<T>(
463 BinaryOp::Min,
464 B::binary::<T>(BinaryOp::Max, x.0, lo.0),
465 hi.0,
466 ))
467 .to_array();
468 }
469 minimum(maximum(x, lo), hi)
470}
471
472#[track_caller]
474pub fn equal<B: Backend, T: Element>(
475 x: impl ArrayLike<B, T>,
476 y: impl ArrayLike<B, T>,
477) -> Array<B, bool> {
478 broadcast_compare(
479 ruxla_kernels::CompareOp::Eq,
480 &x.into_array(),
481 &y.into_array(),
482 )
483}
484
485fn is_half<T: Element>() -> bool {
486 T::DTYPE == f16::DTYPE || T::DTYPE == bf16::DTYPE
487}
488
489#[track_caller]
491pub fn sum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
492 let x = x.into_array();
493 let axes = axes.into().resolve(x.ndim());
494 if is_half::<T>() {
495 return x.cast::<f32>().reduce_sum(&axes).cast::<T>();
496 }
497 x.reduce_sum(&axes)
498}
499
500#[track_caller]
502pub fn mean<B: Backend, T: Float>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
503 let x = x.into_array();
504 let shape = x.shape();
505 let axes = axes.into().resolve(shape.rank());
506 let n: usize = axes.iter().map(|&a| shape[a]).product();
507 if is_half::<T>() {
508 let total = x.cast::<f32>().reduce_sum(&axes);
509 return (total / n as f32).cast::<T>();
510 }
511 let total = x.reduce_sum(&axes);
512 total / Scalar::<B, T>::new(ruxla_kernels::cast::<u64, T>(n as u64))
513}
514
515#[track_caller]
517pub fn max<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
518 let x = x.into_array();
519 let axes = axes.into().resolve(x.ndim());
520 x.reduce_max(&axes)
521}
522
523#[track_caller]
525pub fn min<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
526 let x = x.into_array();
527 let axes = axes.into().resolve(x.ndim());
528 x.reduce_min(&axes)
529}
530
531#[track_caller]
533pub fn any<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
534 max(x, axes)
535}
536
537#[track_caller]
539pub fn all<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
540 min(x, axes)
541}
542
543#[track_caller]
545pub fn argmax<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
546 let x = x.into_array();
547 let axis = normalize_axis(axis, x.ndim());
548 lax::argmax(&x, axis)
549}
550
551#[track_caller]
553pub fn argmin<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
554 let x = x.into_array();
555 let axis = normalize_axis(axis, x.ndim());
556 lax::argmin(&x, axis)
557}
558
559#[track_caller]
562fn cumulative_operand<B: Backend, T: Element>(
563 x: impl ArrayLike<B, T>,
564 axis: Option<i64>,
565) -> (Array<B, T>, usize) {
566 let x = x.into_array();
567 if axis.is_none() || x.ndim() == 0 {
568 let n = x.size();
569 let flat = lax::reshape(&x, [n]);
570 let axis = normalize_axis(axis.unwrap_or(0), 1);
571 return (flat, axis);
572 }
573 let axis = normalize_axis(axis.unwrap_or(0), x.ndim());
574 (x, axis)
575}
576
577#[track_caller]
590pub fn cumsum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
591 let (x, axis) = cumulative_operand(x, axis);
592 lax::cumsum(&x, axis, false)
593}
594
595#[track_caller]
598pub fn cumprod<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
599 let (x, axis) = cumulative_operand(x, axis);
600 lax::cumprod(&x, axis, false)
601}
602
603#[track_caller]
605pub fn expand_dims<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, T> {
606 let x = x.into_array();
607 let shape = x.shape();
608 let axis = normalize_axis(axis, shape.rank() + 1);
609 let mut out = shape.clone();
610 out.insert(axis, 1);
611 let dims: Shape = (0..shape.rank())
612 .map(|i| if i < axis { i } else { i + 1 })
613 .collect();
614 lax::broadcast_in_dim(&x, out, &dims)
615}
616
617#[track_caller]
623#[inline]
624pub fn stack<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
625 xs: &[A],
626 axis: i64,
627) -> Array<B, T> {
628 assert!(!xs.is_empty(), "stack needs at least one array");
629 if B::FAST_PATHS && (axis == 0 || axis == -1) && xs.iter().all(|x| x.as_scalar().is_some()) {
630 let r = B::stack_scalars::<T>(xs.len(), |i| xs[i].as_scalar().expect("a scalar").0);
631 if let Some(r) = r {
632 return Array(r);
633 }
634 }
635 stack_general(xs, axis)
636}
637
638#[track_caller]
640fn stack_general<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
641 xs: &[A],
642 axis: i64,
643) -> Array<B, T> {
644 if B::FAST_PATHS && (axis == 0 || axis == -1 && xs[0].clone().into_array().ndim() == 0) {
645 let arrays: Vec<Array<B, T>> = xs.iter().map(|x| x.clone().into_array()).collect();
646 if let Some(r) = B::stack0::<T>(Array::reprs(&arrays)) {
647 return Array(r);
648 }
649 }
650 let parts: Vec<Array<B, T>> = xs.iter().map(|x| expand_dims(x.clone(), axis)).collect();
651 let axis = normalize_axis(axis, parts[0].ndim());
652 lax::concatenate(&parts, axis)
653}
654
655#[track_caller]
675pub fn take<B: Backend, T: Element, I: Int>(
676 x: &Array<B, T>,
677 indices: &Array<B, I>,
678 axis: i64,
679) -> Array<B, T> {
680 let shape = x.shape();
681 let rank = shape.rank();
682 let axis = if axis < 0 { axis + rank as i64 } else { axis };
683 assert!(
684 (0..rank as i64).contains(&axis),
685 "take: axis {axis} out of range for rank {rank}"
686 );
687 let axis = axis as usize;
688 if B::FAST_PATHS
689 && let Some(r) = B::a_take::<T, I>(&x.0, &indices.0, axis)
690 {
691 return Array(r);
692 }
693 let n = shape.dims()[axis];
694 let indices = indices.cast::<i32>();
695 let indices = where_(indices.lt(0i32), indices.clone() + n as i32, indices);
696 let index_rank = indices.ndim();
697 let mut dims_of_indices = indices.shape().dims().to_vec();
698 dims_of_indices.push(1);
699 let offset_dims = (0..axis)
700 .chain(axis + index_rank..rank - 1 + index_rank)
701 .collect();
702 let dims = GatherDims {
703 offset_dims,
704 collapsed_slice_dims: vec![axis],
705 start_index_map: vec![axis],
706 ..GatherDims::default()
707 };
708 let mut slice_sizes = shape.dims().to_vec();
709 slice_sizes[axis] = 1;
710 lax::gather(
711 x,
712 &indices.reshape(dims_of_indices),
713 &dims,
714 &slice_sizes,
715 GatherScatterMode::Clip,
716 )
717}
718
719#[track_caller]
738#[inline]
739pub fn roll<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
740 if B::FAST_PATHS
741 && let Some(dims) = B::dims(&x.0)
742 {
743 let axis = normalize_axis(axis, dims.len());
744 let n = dims[axis];
745 let i = roll_start(shift, n);
746 if i == 0 {
747 return x.clone();
748 }
749 if let Some(r) = B::a_roll::<T>(&x.0, n - i, axis) {
750 return Array(r);
751 }
752 }
753 roll_general(x, shift, axis)
754}
755
756#[inline]
759fn roll_start(shift: i64, n: usize) -> usize {
760 shift.wrapping_neg().rem_euclid(n.max(1) as i64) as usize
761}
762
763#[track_caller]
766fn roll_general<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
767 let shape = x.shape();
768 let axis = normalize_axis(axis, shape.rank());
769 let n = shape.dims()[axis];
770 let i = roll_start(shift, n);
771 if i == 0 {
772 return x.clone();
773 }
774 lax::concatenate(
775 &[
776 lax::slice_in_dim(x, i, n, 1, axis),
777 lax::slice_in_dim(x, 0, i, 1, axis),
778 ],
779 axis,
780 )
781}
782
783#[track_caller]
785pub fn concatenate<B: Backend, T: Element>(xs: &[Array<B, T>], axis: i64) -> Array<B, T> {
786 assert!(!xs.is_empty(), "concatenate needs at least one array");
787 let axis = normalize_axis(axis, xs[0].ndim());
788 lax::concatenate(xs, axis)
789}
790
791#[track_caller]
797pub fn matmul<B: Backend, T: Numeric>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
798 let (ra, rb) = (a.ndim(), b.ndim());
799 assert!(
800 (1..=2).contains(&ra) && (1..=2).contains(&rb),
801 "matmul supports ranks 1 and 2, got {ra} and {rb}"
802 );
803 let dims = DotDims {
804 lhs_contracting: vec![ra - 1],
805 rhs_contracting: vec![0],
806 ..DotDims::default()
807 };
808 lax::dot_general(a, b, &dims)
809}
810
811pub fn round_with<B: Backend, T: Float>(
813 x: impl ArrayLike<B, T>,
814 method: RoundingMethod,
815) -> Array<B, T> {
816 let op = match method {
817 RoundingMethod::AwayFromZero => UnaryOp::Round,
818 RoundingMethod::ToNearestEven => UnaryOp::RoundEven,
819 };
820 x.into_array().unary(op)
821}
822
823impl<B: Backend, T: Numeric> Array<B, T> {
824 #[track_caller]
826 pub fn dot(&self, other: &Array<B, T>) -> Array<B, T> {
827 matmul(self, other)
828 }
829
830 #[track_caller]
832 pub fn sum(&self, axes: impl Into<Axes>) -> Array<B, T> {
833 sum(self, axes)
834 }
835}