1use std::fmt;
5use std::sync::Arc;
6
7use ruxla_ir::{
8 AVal, ConvDims, DotDims, EighImplementation, FftType, GatherDims, GatherScatterMode, HostArray,
9 Params, Precision, ScatterDims, SelectPrim, Shape, SvdAlgorithm,
10};
11use ruxla_kernels::array::{self as k, CumulativeOp, ReduceOp};
12use ruxla_kernels::elementwise as ew;
13use ruxla_kernels::linalg::{self as kl, TriangularSolveOptions};
14use ruxla_kernels::window::{self as kw, ConvWindow, Window};
15use ruxla_kernels::{BinaryOp, CompareOp, DTypeKind, Element, TernaryOp, UnaryOp, cast};
16use ruxla_prims as p;
17
18use crate::shared::Shared;
19use crate::trace::{self, TraceRef};
20use crate::tree::Tree;
21use crate::value::{Bool, I32, LinalgFloat, LinalgScalar, Scalar};
22
23mod sealed {
24 pub trait Sealed {}
25}
26
27#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub enum ToReal {
30 Abs,
32 Real,
34 Imag,
36}
37
38const SMALL: usize = 8;
40
41#[derive(Clone)]
45enum Data<T: Element> {
46 Small {
47 len: u8,
48 buf: [T; SMALL],
49 },
50 Slice(Shared<T>),
52 Vec(Arc<Vec<T>>),
54}
55
56impl<T: Element> Data<T> {
57 #[inline]
58 fn from_vec(v: Vec<T>) -> Self {
59 if v.len() <= SMALL {
60 let mut buf = [T::default(); SMALL];
61 buf[..v.len()].copy_from_slice(&v);
62 Data::Small {
63 len: v.len() as u8,
64 buf,
65 }
66 } else {
67 Data::Vec(Arc::new(v))
68 }
69 }
70
71 #[inline]
72 fn from_slice(v: &[T]) -> Self {
73 if v.len() <= SMALL {
74 Self::build(v.len(), |out| out.copy_from_slice(v))
75 } else {
76 Data::Slice(Shared::from_slice(v))
77 }
78 }
79
80 #[inline]
82 fn filled(len: usize, v: T) -> Self {
83 if len <= SMALL {
84 Self::build(len, |out| out.fill(v))
85 } else {
86 Data::Slice(Shared::filled(len, v))
87 }
88 }
89
90 #[inline]
92 fn make_mut(&mut self) -> &mut [T] {
93 let shared = match self {
94 Data::Small { .. } => false,
95 Data::Slice(a) => a.get_mut().is_none(),
96 Data::Vec(a) => Arc::get_mut(a).is_none(),
97 };
98 if shared {
99 *self = Data::from_slice(self);
100 }
101 self.unique_mut()
102 }
103
104 #[inline]
106 fn is_unique(&mut self) -> bool {
107 match self {
108 Data::Small { .. } => true,
109 Data::Slice(a) => a.get_mut().is_some(),
110 Data::Vec(a) => Arc::get_mut(a).is_some(),
111 }
112 }
113
114 #[inline]
117 fn unique_mut(&mut self) -> &mut [T] {
118 match self {
119 Data::Small { len, buf } => &mut buf[..usize::from(*len)],
120 Data::Slice(a) => a.get_mut().expect("a new buffer is not shared"),
121 Data::Vec(a) => Arc::get_mut(a).expect("a new buffer is not shared"),
122 }
123 }
124
125 #[inline(always)]
127 fn build(len: usize, f: impl FnOnce(&mut [T])) -> Self {
128 if len <= SMALL {
129 let mut buf = [T::default(); SMALL];
130 f(&mut buf[..len]);
131 Data::Small {
132 len: len as u8,
133 buf,
134 }
135 } else {
136 Self::build_shared(len, f)
137 }
138 }
139
140 #[inline(never)]
143 fn build_shared(len: usize, f: impl FnOnce(&mut [T])) -> Self {
144 Data::Slice(Shared::new(len, f))
145 }
146
147 #[inline]
150 fn build_overwrite(len: usize, f: impl FnOnce(&mut [T])) -> Self {
151 if len <= SMALL {
152 Self::build(len, f)
153 } else {
154 Self::build_overwrite_shared(len, f)
155 }
156 }
157
158 #[inline(never)]
159 fn build_overwrite_shared(len: usize, f: impl FnOnce(&mut [T])) -> Self {
160 Data::Slice(Shared::new_overwrite(len, f))
161 }
162}
163
164impl<T: Element> std::ops::Deref for Data<T> {
165 type Target = [T];
166 #[inline]
167 fn deref(&self) -> &[T] {
168 match self {
169 Data::Small { len, buf } => &buf[..usize::from(*len)],
170 Data::Slice(v) => v,
171 Data::Vec(v) => v,
172 }
173 }
174}
175
176impl<T: Element> PartialEq for Data<T> {
177 fn eq(&self, other: &Self) -> bool {
178 self[..] == other[..]
179 }
180}
181
182#[doc(hidden)]
186#[derive(Clone, Debug)]
187pub enum NativeKey {
188 Single([u32; 2]),
190 Array(Arc<NativeArray<u32>>),
192}
193
194impl NativeKey {
195 #[inline]
197 fn words(&self) -> [u32; 2] {
198 match self {
199 NativeKey::Single(w) => *w,
200 NativeKey::Array(a) => [a.data[0], a.data[1]],
201 }
202 }
203}
204
205#[derive(Clone, PartialEq)]
208pub struct NativeArray<T: Element> {
209 data: Data<T>,
210 shape: Shape,
211}
212
213impl<T: Element> NativeArray<T> {
214 #[track_caller]
220 pub fn new(data: Vec<T>, shape: impl Into<Shape>) -> Self {
221 let shape = shape.into();
222 assert_eq!(
223 data.len(),
224 shape.size(),
225 "{} elements for shape [{shape}]",
226 data.len()
227 );
228 Self {
229 data: Data::from_vec(data),
230 shape,
231 }
232 }
233
234 #[track_caller]
240 #[inline]
241 pub fn from_slice(data: &[T], shape: impl Into<Shape>) -> Self {
242 let shape = shape.into();
243 assert_eq!(
244 data.len(),
245 shape.size(),
246 "{} elements for shape [{shape}]",
247 data.len()
248 );
249 Self {
250 data: Data::from_slice(data),
251 shape,
252 }
253 }
254
255 pub fn data(&self) -> &[T] {
257 &self.data
258 }
259
260 pub fn shape(&self) -> &Shape {
262 &self.shape
263 }
264
265 pub fn to_host(&self) -> HostArray {
267 HostArray::from_vec(self.data.to_vec(), self.shape.clone())
268 }
269
270 #[track_caller]
276 pub fn from_host(h: &HostArray) -> Self {
277 let data = h.to_vec::<T>().unwrap_or_else(|e| panic!("{e}"));
278 Self::new(data, h.shape().clone())
279 }
280}
281
282impl<T: Element> fmt::Debug for NativeArray<T> {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 write!(f, "{}[{}] {:?}", T::DTYPE, self.shape, &self.data[..])
285 }
286}
287
288pub trait Backend: Copy + Default + Send + Sync + fmt::Debug + 'static + sealed::Sealed {
295 type Scalar<T: Element>: Copy + fmt::Debug;
297 type Array<T: Element>: Clone + fmt::Debug;
299 type Leaf: Clone + fmt::Debug;
301 #[doc(hidden)]
304 type KeyData: Clone + fmt::Debug;
305
306 #[doc(hidden)]
310 const FAST_PATHS: bool = false;
311
312 fn lit<T: Element>(v: T) -> Self::Scalar<T>;
314 fn unary<T: Element>(op: UnaryOp, x: Self::Scalar<T>) -> Self::Scalar<T>;
316 fn binary<T: Element>(op: BinaryOp, x: Self::Scalar<T>, y: Self::Scalar<T>) -> Self::Scalar<T>;
318 fn compare<T: Element>(
320 op: CompareOp,
321 x: Self::Scalar<T>,
322 y: Self::Scalar<T>,
323 ) -> Self::Scalar<bool>;
324 fn is_finite<T: Element>(x: Self::Scalar<T>) -> Self::Scalar<bool>;
326 fn integer_pow<T: Element>(x: Self::Scalar<T>, y: i32) -> Self::Scalar<T>;
328 fn select<T: Element>(
330 c: Self::Scalar<bool>,
331 t: Self::Scalar<T>,
332 f: Self::Scalar<T>,
333 ) -> Self::Scalar<T>;
334 fn cast<T: Element, U: Element>(x: Self::Scalar<T>) -> Self::Scalar<U>;
336 fn bitcast<T: Element, U: Element>(x: Self::Scalar<T>) -> Self::Scalar<U>;
338 fn to_real<T: Element>(op: ToReal, x: Self::Scalar<T>) -> Self::Scalar<T::Real>;
340 fn complex<C: Element>(re: Self::Scalar<C::Real>, im: Self::Scalar<C::Real>)
342 -> Self::Scalar<C>;
343 fn conj<T: Element>(x: Self::Scalar<T>) -> Self::Scalar<T>;
345
346 fn constant<T: Element>(x: &NativeArray<T>) -> Self::Array<T>;
348 #[doc(hidden)]
351 #[inline]
352 fn constant_owned<T: Element>(x: NativeArray<T>) -> Self::Array<T> {
353 Self::constant(&x)
354 }
355 fn shape<T: Element>(x: &Self::Array<T>) -> Shape;
357 fn to_array<T: Element>(x: Self::Scalar<T>) -> Self::Array<T>;
359 fn to_scalar<T: Element>(x: &Self::Array<T>) -> Self::Scalar<T>;
361 fn a_unary<T: Element>(op: UnaryOp, x: &Self::Array<T>) -> Self::Array<T>;
363 fn a_binary<T: Element>(op: BinaryOp, x: &Self::Array<T>, y: &Self::Array<T>)
365 -> Self::Array<T>;
366 fn a_ternary<T: Element>(
368 op: TernaryOp,
369 x: &Self::Array<T>,
370 y: &Self::Array<T>,
371 z: &Self::Array<T>,
372 ) -> Self::Array<T>;
373 fn a_compare<T: Element>(
375 op: CompareOp,
376 x: &Self::Array<T>,
377 y: &Self::Array<T>,
378 ) -> Self::Array<bool>;
379 fn a_is_finite<T: Element>(x: &Self::Array<T>) -> Self::Array<bool>;
381 fn a_integer_pow<T: Element>(x: &Self::Array<T>, y: i32) -> Self::Array<T>;
383 fn a_cast<T: Element, U: Element>(x: &Self::Array<T>) -> Self::Array<U>;
385 fn a_bitcast<T: Element, U: Element>(x: &Self::Array<T>) -> Self::Array<U>;
387 fn a_to_real<T: Element>(op: ToReal, x: &Self::Array<T>) -> Self::Array<T::Real>;
389 fn a_complex<C: Element>(
391 re: &Self::Array<C::Real>,
392 im: &Self::Array<C::Real>,
393 ) -> Self::Array<C>;
394 fn a_conj<T: Element>(x: &Self::Array<T>) -> Self::Array<T>;
396 fn a_select<T: Element>(
398 c: &Self::Array<bool>,
399 t: &Self::Array<T>,
400 f: &Self::Array<T>,
401 ) -> Self::Array<T>;
402 fn a_clamp<T: Element>(
404 lo: &Self::Array<T>,
405 x: &Self::Array<T>,
406 hi: &Self::Array<T>,
407 ) -> Self::Array<T>;
408 fn broadcast_in_dim<T: Element>(
410 x: &Self::Array<T>,
411 shape: &[usize],
412 dims: &[usize],
413 ) -> Self::Array<T>;
414 fn reshape<T: Element>(x: &Self::Array<T>, shape: &[usize]) -> Self::Array<T>;
416 fn transpose<T: Element>(x: &Self::Array<T>, perm: &[usize]) -> Self::Array<T>;
418 fn slice<T: Element>(
420 x: &Self::Array<T>,
421 start: &[usize],
422 limit: &[usize],
423 strides: &[usize],
424 ) -> Self::Array<T>;
425 fn dynamic_slice<T: Element, I: Element>(
427 x: &Self::Array<T>,
428 starts: &[Self::Scalar<I>],
429 sizes: &[usize],
430 ) -> Self::Array<T>;
431 fn dynamic_update_slice<T: Element, I: Element>(
433 x: &Self::Array<T>,
434 update: &Self::Array<T>,
435 starts: &[Self::Scalar<I>],
436 ) -> Self::Array<T>;
437 fn concatenate<T: Element>(xs: &[Self::Array<T>], dim: usize) -> Self::Array<T>;
439 fn pad<T: Element>(
441 x: &Self::Array<T>,
442 value: Self::Scalar<T>,
443 config: &[(i64, i64, usize)],
444 ) -> Self::Array<T>;
445 fn rev<T: Element>(x: &Self::Array<T>, dims: &[usize]) -> Self::Array<T>;
447 fn iota<T: Element>(shape: &[usize], dim: usize) -> Self::Array<T>;
449 fn reduce<T: Element>(op: ReduceOp, x: &Self::Array<T>, axes: &[usize]) -> Self::Array<T>;
451 fn arg_min_max<T: Element, I: Element>(
453 x: &Self::Array<T>,
454 axis: usize,
455 max: bool,
456 ) -> Self::Array<I>;
457 fn sort(
460 operands: &[Self::Leaf],
461 dimension: usize,
462 is_stable: bool,
463 num_keys: usize,
464 ) -> Vec<Self::Leaf>;
465 fn cumulative<T: Element>(
468 op: CumulativeOp,
469 x: &Self::Array<T>,
470 axis: usize,
471 reverse: bool,
472 ) -> Self::Array<T>;
473 fn top_k<T: Element>(
476 x: &Self::Array<T>,
477 k: usize,
478 axis: usize,
479 ) -> (Self::Array<T>, Self::Array<i32>);
480 fn cholesky<T: LinalgScalar>(x: &Self::Array<T>) -> Self::Array<T>;
482 fn triangular_solve<T: LinalgScalar>(
484 a: &Self::Array<T>,
485 b: &Self::Array<T>,
486 options: TriangularSolveOptions,
487 ) -> Self::Array<T>;
488 fn lu<T: LinalgScalar>(
491 x: &Self::Array<T>,
492 ) -> (Self::Array<T>, Self::Array<i32>, Self::Array<i32>);
493 fn lu_pivots_to_permutation(pivots: &Self::Array<i32>, size: usize) -> Self::Array<i32>;
495 fn qr<T: LinalgScalar>(
497 x: &Self::Array<T>,
498 full_matrices: bool,
499 ) -> (Self::Array<T>, Self::Array<T>);
500 fn qr_pivoting<T: LinalgScalar>(
503 x: &Self::Array<T>,
504 full_matrices: bool,
505 ) -> (Self::Array<T>, Self::Array<T>, Self::Array<i32>);
506 fn eigh<T: LinalgScalar>(
509 x: &Self::Array<T>,
510 lower: bool,
511 sort_eigenvalues: bool,
512 subset_by_index: Option<(usize, usize)>,
513 algorithm: Option<EighImplementation>,
514 ) -> (Self::Array<T>, Self::Array<T::Real>);
515 #[allow(clippy::type_complexity)] fn eig<T: LinalgScalar>(
519 x: &Self::Array<T>,
520 left: bool,
521 right: bool,
522 enable_eigvec_derivs: bool,
523 ) -> (
524 Self::Array<<T as LinalgScalar>::Complex>,
525 Option<Self::Array<<T as LinalgScalar>::Complex>>,
526 Option<Self::Array<<T as LinalgScalar>::Complex>>,
527 );
528 fn schur<T: LinalgScalar>(
531 x: &Self::Array<T>,
532 compute_schur_vectors: bool,
533 ) -> (Self::Array<T>, Option<Self::Array<T>>);
534 fn hessenberg<T: LinalgScalar>(x: &Self::Array<T>) -> (Self::Array<T>, Self::Array<T>);
537 fn householder_product<T: LinalgScalar>(
539 a: &Self::Array<T>,
540 taus: &Self::Array<T>,
541 ) -> Self::Array<T>;
542 fn ormqr<T: LinalgScalar>(
544 a: &Self::Array<T>,
545 taus: &Self::Array<T>,
546 c: &Self::Array<T>,
547 left: bool,
548 transpose: bool,
549 ) -> Self::Array<T>;
550 fn cholesky_update<T: LinalgFloat>(r: &Self::Array<T>, w: &Self::Array<T>) -> Self::Array<T>;
553 fn symmetric_product<T: LinalgFloat>(
555 a: &Self::Array<T>,
556 c: &Self::Array<T>,
557 alpha: f64,
558 beta: f64,
559 ) -> Self::Array<T>;
560 #[allow(clippy::type_complexity)] fn tridiagonal<T: LinalgScalar>(
565 x: &Self::Array<T>,
566 lower: bool,
567 ) -> (
568 Self::Array<T>,
569 Self::Array<T::Real>,
570 Self::Array<T::Real>,
571 Self::Array<T>,
572 );
573 fn tridiagonal_solve<T: LinalgScalar>(
577 dl: &Self::Array<T>,
578 d: &Self::Array<T>,
579 du: &Self::Array<T>,
580 b: &Self::Array<T>,
581 perturb_singular: bool,
582 ) -> Self::Array<T>;
583 #[allow(clippy::type_complexity)] fn svd<T: LinalgScalar>(
588 x: &Self::Array<T>,
589 full_matrices: bool,
590 compute_uv: bool,
591 subset_by_index: Option<(usize, usize)>,
592 algorithm: Option<SvdAlgorithm>,
593 ) -> (
594 Self::Array<T::Real>,
595 Option<(Self::Array<T>, Self::Array<T>)>,
596 );
597 fn fft<T: Element, U: Element>(
600 x: &Self::Array<T>,
601 fft_type: FftType,
602 fft_lengths: &[usize],
603 ) -> Self::Array<U>;
604 fn dot_general<T: Element, U: Element>(
607 l: &Self::Array<T>,
608 r: &Self::Array<T>,
609 dims: &DotDims,
610 precision: Precision,
611 ) -> Self::Array<U>;
612 fn conv_general_dilated<T: Element, U: Element>(
616 lhs: &Self::Array<T>,
617 rhs: &Self::Array<T>,
618 window: &ConvWindow<'_>,
619 dims: &ConvDims,
620 groups: (usize, usize),
621 precision: Precision,
622 ) -> Self::Array<U>;
623 fn reduce_window<T: Element>(
625 op: ReduceOp,
626 x: &Self::Array<T>,
627 window: &Window<'_>,
628 ) -> Self::Array<T>;
629 fn select_and_scatter_add<T: Element>(
631 source: &Self::Array<T>,
632 operand: &Self::Array<T>,
633 select_prim: SelectPrim,
634 window: &Window<'_>,
635 ) -> Self::Array<T>;
636 fn select_and_gather_add<T: Element>(
638 tangents: &Self::Array<T>,
639 operand: &Self::Array<T>,
640 select_prim: SelectPrim,
641 window: &Window<'_>,
642 ) -> Self::Array<T>;
643 fn gather<T: Element, I: Element>(
645 x: &Self::Array<T>,
646 indices: &Self::Array<I>,
647 dims: &GatherDims,
648 sizes: &[usize],
649 mode: GatherScatterMode,
650 sorted_unique: bool,
651 ) -> Self::Array<T>;
652 #[allow(clippy::too_many_arguments)]
654 fn scatter<T: Element, I: Element>(
655 combine: Option<BinaryOp>,
656 x: &Self::Array<T>,
657 indices: &Self::Array<I>,
658 updates: &Self::Array<T>,
659 dims: &ScatterDims,
660 mode: GatherScatterMode,
661 sorted_unique: bool,
662 ) -> Self::Array<T>;
663
664 fn cond<S: Tree<Self>, R: Tree<Self>>(
667 index: I32<Self>,
668 branches: &[&dyn Fn(S) -> R],
669 operand: S,
670 ) -> R;
671 fn while_loop<C: Tree<Self>>(
673 cond: &dyn Fn(&C) -> Bool<Self>,
674 body: &dyn Fn(C) -> C,
675 init: C,
676 ) -> C;
677 fn custom_jvp<I: Tree<Self>, O: Tree<Self>>(
680 f: &dyn Fn(I) -> O,
681 jvp: &dyn Fn(I, I) -> (O, O),
682 primals: I,
683 ) -> O {
684 let _ = jvp;
685 f(primals)
686 }
687 fn custom_vjp<I: Tree<Self>, O: Tree<Self>, R: Tree<Self>>(
690 f: &dyn Fn(I) -> O,
691 fwd: &dyn Fn(I) -> (O, R),
692 bwd: &dyn Fn(R, O) -> I,
693 primals: I,
694 ) -> O {
695 let _ = (fwd, bwd);
696 f(primals)
697 }
698 fn checkpoint<I: Tree<Self>, O: Tree<Self>>(f: &dyn Fn(I) -> O, input: I) -> O {
701 f(input)
702 }
703 fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
705 f: &dyn Fn(C, X) -> (C, Y),
706 init: C,
707 xs: X,
708 length: usize,
709 reverse: bool,
710 ) -> (C, Y);
711 #[doc(hidden)]
716 fn a_binary_broadcast<T: Element>(
717 op: BinaryOp,
718 x: &Self::Array<T>,
719 y: &Self::Array<T>,
720 ) -> Option<Self::Array<T>> {
721 let _ = (op, x, y);
722 None
723 }
724
725 #[doc(hidden)]
728 fn a_compare_broadcast<T: Element>(
729 op: CompareOp,
730 x: &Self::Array<T>,
731 y: &Self::Array<T>,
732 ) -> Option<Self::Array<bool>> {
733 let _ = (op, x, y);
734 None
735 }
736
737 #[doc(hidden)]
741 fn a_binary_assign<T: Element>(
742 op: BinaryOp,
743 x: &mut Self::Array<T>,
744 y: &Self::Array<T>,
745 ) -> bool {
746 let _ = (op, x, y);
747 false
748 }
749
750 #[doc(hidden)]
753 fn a_unary_assign<T: Element>(op: UnaryOp, x: &mut Self::Array<T>) -> bool {
754 let _ = (op, x);
755 false
756 }
757
758 #[doc(hidden)]
763 fn a_select_broadcast<T: Element>(
764 c: &Self::Array<bool>,
765 x: &Self::Array<T>,
766 y: &Self::Array<T>,
767 ) -> Option<Self::Array<T>> {
768 let _ = (c, x, y);
769 None
770 }
771
772 #[doc(hidden)]
776 fn a_take<T: Element, I: Element>(
777 x: &Self::Array<T>,
778 indices: &Self::Array<I>,
779 axis: usize,
780 ) -> Option<Self::Array<T>> {
781 let _ = (x, indices, axis);
782 None
783 }
784
785 #[doc(hidden)]
790 fn a_roll<T: Element>(x: &Self::Array<T>, shift: usize, axis: usize) -> Option<Self::Array<T>> {
791 let _ = (x, shift, axis);
792 None
793 }
794
795 #[doc(hidden)]
799 fn random_uniform<T: crate::value::Float>(
800 key: &Self::KeyData,
801 shape: &Shape,
802 minval: &Self::Array<T>,
803 maxval: &Self::Array<T>,
804 ) -> Option<Self::Array<T>> {
805 let _ = (key, shape, minval, maxval);
806 None
807 }
808
809 #[doc(hidden)]
812 fn random_uniform_scalar<T: crate::value::Float>(
813 key: &Self::KeyData,
814 lo: Self::Scalar<T>,
815 hi: Self::Scalar<T>,
816 ) -> Option<Self::Scalar<T>> {
817 let _ = (key, lo, hi);
818 None
819 }
820
821 #[doc(hidden)]
824 fn random_randint_scalar<T: crate::value::Int>(
825 key: &Self::KeyData,
826 lo: Self::Scalar<T>,
827 hi: Self::Scalar<T>,
828 ) -> Option<Self::Scalar<T>> {
829 let _ = (key, lo, hi);
830 None
831 }
832
833 #[doc(hidden)]
836 fn random_randint<T: crate::value::Int>(
837 key: &Self::KeyData,
838 shape: &Shape,
839 minval: &Self::Array<T>,
840 maxval: &Self::Array<T>,
841 ) -> Option<Self::Array<T>> {
842 let _ = (key, shape, minval, maxval);
843 None
844 }
845
846 #[doc(hidden)]
853 fn point_update_in_place<T: Element>(
854 x: &mut Self::Array<T>,
855 index: &[crate::indexing::Index<Self>],
856 value: Self::Scalar<T>,
857 combine: Option<BinaryOp>,
858 ) -> bool {
859 let _ = (x, index, value, combine);
860 false
861 }
862 #[doc(hidden)]
867 fn update_box<T: Element>(
868 x: &mut Self::Array<T>,
869 starts: &[usize],
870 sizes: &[usize],
871 values: &Self::Array<T>,
872 combine: Option<BinaryOp>,
873 ) -> bool {
874 let _ = (x, starts, sizes, values, combine);
875 false
876 }
877 #[doc(hidden)]
883 fn point_update<T: Element>(
884 x: &Self::Array<T>,
885 index: &[Self::Scalar<i32>],
886 value: &Self::Array<T>,
887 combine: Option<BinaryOp>,
888 ) -> Option<Self::Array<T>> {
889 let _ = (x, index, value, combine);
890 None
891 }
892
893 #[doc(hidden)]
897 fn index_leading<T: Element>(x: &Self::Array<T>, index: &[usize]) -> Option<Self::Array<T>> {
898 let _ = (x, index);
899 None
900 }
901
902 #[doc(hidden)]
904 fn key_from_array(data: Self::Array<u32>) -> Self::KeyData;
905 #[doc(hidden)]
907 fn key_to_array(key: &Self::KeyData) -> Self::Array<u32>;
908 #[doc(hidden)]
910 fn key_rank(key: &Self::KeyData) -> usize {
911 Self::rank::<u32>(&Self::key_to_array(key))
912 }
913
914 #[doc(hidden)]
918 fn key_split2(key: &Self::KeyData) -> Option<(Self::KeyData, Self::KeyData)> {
919 let _ = key;
920 None
921 }
922
923 #[doc(hidden)]
927 fn stack0<T: Element>(xs: &[Self::Array<T>]) -> Option<Self::Array<T>> {
928 let _ = xs;
929 None
930 }
931 #[doc(hidden)]
934 fn stack_scalars<T: Element>(
935 n: usize,
936 scalar: impl FnMut(usize) -> Self::Scalar<T>,
937 ) -> Option<Self::Array<T>> {
938 let _ = (n, scalar);
939 None
940 }
941 #[doc(hidden)]
943 #[inline]
944 fn rank<T: Element>(x: &Self::Array<T>) -> usize {
945 Self::shape(x).rank()
946 }
947 #[doc(hidden)]
950 #[inline]
951 fn dims<T: Element>(x: &Self::Array<T>) -> Option<&[usize]> {
952 let _ = x;
953 None
954 }
955 #[doc(hidden)]
960 fn sort_key_val_typed<K: Element, V: Element>(
961 keys: &Self::Array<K>,
962 values: &Self::Array<V>,
963 dimension: usize,
964 ) -> Option<(Self::Array<K>, Self::Array<V>)> {
965 let _ = (keys, values, dimension);
966 None
967 }
968 #[doc(hidden)]
972 fn slice_box<T: Element>(
973 x: &Self::Array<T>,
974 starts: &[usize],
975 sizes: &[usize],
976 out: Shape,
977 ) -> Option<Self::Array<T>> {
978 let _ = (x, starts, sizes, out);
979 None
980 }
981 #[doc(hidden)]
984 #[inline]
985 fn full<T: Element>(shape: Shape, value: Self::Scalar<T>) -> Option<Self::Array<T>> {
986 let _ = (shape, value);
987 None
988 }
989 #[doc(hidden)]
991 #[inline]
992 fn int_value(x: Self::Scalar<i32>) -> Option<i64> {
993 let _ = x;
994 None
995 }
996 #[doc(hidden)]
999 #[inline]
1000 fn branch_value(pred: Bool<Self>) -> Option<bool> {
1001 let _ = pred;
1002 None
1003 }
1004 #[doc(hidden)]
1007 #[inline]
1008 fn element<T: Element>(x: &Self::Array<T>, flat: usize) -> Option<Self::Scalar<T>> {
1009 let _ = (x, flat);
1010 None
1011 }
1012
1013 #[doc(hidden)]
1016 fn key_split(key: &Self::KeyData, num: usize) -> Self::KeyData {
1017 let a = crate::value::Array::<Self, u32>(Self::key_to_array(key));
1018 Self::key_from_array(crate::random::split_generic(&a, num).0)
1019 }
1020
1021 #[doc(hidden)]
1024 fn key_fold_in(key: &Self::KeyData, data: Self::Scalar<u32>) -> Self::KeyData {
1025 let a = crate::value::Array::<Self, u32>(Self::key_to_array(key));
1026 Self::key_from_array(crate::random::fold_in_generic(&a, Scalar(data)).0)
1027 }
1028
1029 #[doc(hidden)]
1033 fn key_bits(key: &Self::KeyData, shape: &[usize]) -> (Self::Array<u32>, Self::Array<u32>) {
1034 let k = crate::value::Array::<Self, u32>(Self::key_to_array(key));
1035 let (a, b) = crate::random::key_bits_generic(&k, shape);
1036 (a.0, b.0)
1037 }
1038
1039 #[doc(hidden)]
1044 fn threefry2x32(
1045 k1: &Self::Array<u32>,
1046 k2: &Self::Array<u32>,
1047 x1: &Self::Array<u32>,
1048 x2: &Self::Array<u32>,
1049 ) -> (Self::Array<u32>, Self::Array<u32>) {
1050 let a = |x: &Self::Array<u32>| crate::value::Array::<Self, u32>(x.clone());
1051 let (y1, y2) = crate::random::threefry2x32_generic(&a(k1), &a(k2), &a(x1), &a(x2));
1052 (y1.0, y2.0)
1053 }
1054 fn fori_loop<C: Tree<Self>>(
1056 lo: I32<Self>,
1057 hi: I32<Self>,
1058 body: &dyn Fn(I32<Self>, C) -> C,
1059 init: C,
1060 ) -> C;
1061
1062 fn scalar_leaf<T: Element>(x: Self::Scalar<T>) -> Self::Leaf;
1064 fn leaf_scalar<T: Element>(l: Self::Leaf) -> Self::Scalar<T>;
1066 fn array_leaf<T: Element>(x: &Self::Array<T>) -> Self::Leaf;
1068 fn leaf_array<T: Element>(l: Self::Leaf) -> Self::Array<T>;
1070 fn leaf_aval(l: &Self::Leaf) -> AVal;
1072 fn host_callback(
1075 callback: &ruxla_ir::callback::HostCallback,
1076 args: &[Self::Leaf],
1077 outputs: &[AVal],
1078 ) -> Vec<Self::Leaf>;
1079}
1080
1081#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
1085pub struct Native;
1086
1087#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
1090pub struct Trace;
1091
1092impl sealed::Sealed for Native {}
1093impl sealed::Sealed for Trace {}
1094
1095#[inline]
1097fn to_real_native<T: Element>(op: ToReal, x: T) -> T::Real {
1098 match op {
1099 ToReal::Abs => T::unary(UnaryOp::Abs, x).re(),
1100 ToReal::Real => x.re(),
1101 ToReal::Imag => x.im(),
1102 }
1103}
1104
1105fn starts_i64<I: Element>(s: &[I]) -> Vec<i64> {
1106 s.iter().map(|&i| cast::<I, i64>(i)).collect()
1107}
1108
1109fn copy_box<T: Element>(
1115 x: &NativeArray<T>,
1116 starts: &[usize],
1117 sizes: &[usize],
1118 out: Shape,
1119) -> Option<NativeArray<T>> {
1120 let rank = x.shape.rank();
1121 if rank > 8 || rank == 0 {
1122 return None;
1123 }
1124 let count: usize = sizes.iter().product();
1125 if count == 0 {
1126 return Some(build(out, |_| {}));
1127 }
1128 let mut stride = [0usize; 8];
1129 let mut base = 0;
1130 let mut st = 1;
1131 for d in (0..rank).rev() {
1132 stride[d] = st;
1133 base += starts[d] * st;
1134 st *= x.shape[d];
1135 }
1136 let mut dims = [(0usize, 0usize); 8];
1139 let mut nd = 0;
1140 for d in 0..rank {
1141 if sizes[d] == 1 {
1142 continue;
1143 }
1144 if nd > 0 && dims[nd - 1].1 == sizes[d] * stride[d] {
1145 dims[nd - 1] = (dims[nd - 1].0 * sizes[d], stride[d]);
1146 } else {
1147 dims[nd] = (sizes[d], stride[d]);
1148 nd += 1;
1149 }
1150 }
1151 let run = if nd > 0 && dims[nd - 1].1 == 1 {
1152 nd -= 1;
1153 dims[nd].0
1154 } else {
1155 1
1156 };
1157 let (inner, inner_stride) = if nd > 0 {
1158 nd -= 1;
1159 dims[nd]
1160 } else {
1161 (1, 0)
1162 };
1163 let src: &[T] = &x.data;
1164 let outer_extent: usize = dims[..nd].iter().map(|&(n, s)| (n - 1) * s).sum();
1165 assert!(
1166 base + outer_extent + (inner - 1) * inner_stride + run <= src.len(),
1167 "the box is inside the array"
1168 );
1169 Some(build_all(out, |o| {
1170 let mut pos = [0usize; 8];
1171 let mut w = 0;
1172 loop {
1173 let s = &src[base..base + (inner - 1) * inner_stride + run];
1174 if run == 1 {
1175 for (k, o) in o[w..w + inner].iter_mut().enumerate() {
1176 *o = s[k * inner_stride];
1177 }
1178 } else {
1179 for k in 0..inner {
1180 o[w + k * run..w + (k + 1) * run]
1181 .copy_from_slice(&s[k * inner_stride..k * inner_stride + run]);
1182 }
1183 }
1184 w += inner * run;
1185 let mut d = nd;
1186 loop {
1187 if d == 0 {
1188 return;
1189 }
1190 d -= 1;
1191 pos[d] += 1;
1192 base += dims[d].1;
1193 if pos[d] < dims[d].0 {
1194 break;
1195 }
1196 base -= dims[d].1 * dims[d].0;
1197 pos[d] = 0;
1198 }
1199 }
1200 }))
1201}
1202
1203fn native<T: Element>(data: Vec<T>, shape: impl Into<Shape>) -> NativeArray<T> {
1204 NativeArray::new(data, shape)
1205}
1206
1207#[inline]
1211fn broadcast_shape_simple<'a, T: Element, U: Element>(
1212 x: &'a NativeArray<T>,
1213 y: &'a NativeArray<U>,
1214) -> Option<&'a Shape> {
1215 if x.shape == y.shape || (y.data.len() == 1 && y.shape.rank() <= x.shape.rank()) {
1216 Some(&x.shape)
1217 } else if x.data.len() == 1 && x.shape.rank() <= y.shape.rank() {
1218 Some(&y.shape)
1219 } else {
1220 None
1221 }
1222}
1223
1224#[inline]
1232fn broadcast_rows<T: Element, U: Element, R: Element>(
1233 x: &NativeArray<T>,
1234 y: &NativeArray<U>,
1235 rows: impl Fn(&[T], &[U], &mut [R]),
1236) -> Option<NativeArray<R>> {
1237 let (xs, ys) = (x.shape.dims(), y.shape.dims());
1238 let rank = xs.len().max(ys.len());
1239 if rank == 0 || rank > 8 {
1240 return None;
1241 }
1242 let mut dims = [1usize; 8];
1244 let (mut sx, mut sy) = ([0usize; 8], [0usize; 8]);
1245 let (mut px, mut py) = (1, 1);
1246 for k in (0..rank).rev() {
1247 let a = if k + xs.len() >= rank {
1248 xs[k + xs.len() - rank]
1249 } else {
1250 1
1251 };
1252 let b = if k + ys.len() >= rank {
1253 ys[k + ys.len() - rank]
1254 } else {
1255 1
1256 };
1257 dims[k] = match (a, b) {
1258 _ if a == b => a,
1259 (1, b) => b,
1260 (a, 1) => a,
1261 _ => return None,
1262 };
1263 if a != 1 {
1264 sx[k] = px;
1265 }
1266 if b != 1 {
1267 sy[k] = py;
1268 }
1269 px *= a;
1270 py *= b;
1271 }
1272 let len = dims[rank - 1];
1273 let n: usize = dims[..rank].iter().product();
1274 if n == 0 {
1275 return None;
1276 }
1277 let (wx, wy) = (
1278 if sx[rank - 1] == 0 { 1 } else { len },
1279 if sy[rank - 1] == 0 { 1 } else { len },
1280 );
1281 let shape = Shape::from(dims[..rank].to_vec());
1282 Some(build_all(shape, |o| {
1283 let mut index = [0usize; 8];
1284 let (mut ox, mut oy) = (0, 0);
1285 for out in o.chunks_exact_mut(len) {
1286 rows(&x.data[ox..ox + wx], &y.data[oy..oy + wy], out);
1287 let mut k = rank - 1;
1289 while k > 0 {
1290 k -= 1;
1291 index[k] += 1;
1292 ox += sx[k];
1293 oy += sy[k];
1294 if index[k] < dims[k] {
1295 break;
1296 }
1297 ox -= sx[k] * dims[k];
1298 oy -= sy[k] * dims[k];
1299 index[k] = 0;
1300 }
1301 }
1302 }))
1303}
1304
1305#[inline(always)]
1307fn build<T: Element>(shape: Shape, f: impl FnOnce(&mut [T])) -> NativeArray<T> {
1308 NativeArray {
1309 data: Data::build(shape.size(), f),
1310 shape,
1311 }
1312}
1313
1314#[inline(always)]
1317fn build_all<T: Element>(shape: Shape, f: impl FnOnce(&mut [T])) -> NativeArray<T> {
1318 NativeArray {
1319 data: Data::build_overwrite(shape.size(), f),
1320 shape,
1321 }
1322}
1323
1324impl Backend for Native {
1325 type Scalar<T: Element> = T;
1326 type Array<T: Element> = NativeArray<T>;
1327 type Leaf = HostArray;
1328 type KeyData = NativeKey;
1329 const FAST_PATHS: bool = true;
1330
1331 #[inline]
1332 fn lit<T: Element>(v: T) -> T {
1333 v
1334 }
1335 #[inline]
1336 fn unary<T: Element>(op: UnaryOp, x: T) -> T {
1337 T::unary(op, x)
1338 }
1339 #[inline]
1340 fn binary<T: Element>(op: BinaryOp, x: T, y: T) -> T {
1341 T::binary(op, x, y)
1342 }
1343 #[inline]
1344 fn compare<T: Element>(op: CompareOp, x: T, y: T) -> bool {
1345 ruxla_kernels::compare(op, x, y)
1346 }
1347 #[inline]
1348 fn is_finite<T: Element>(x: T) -> bool {
1349 T::is_finite(x)
1350 }
1351 #[inline]
1352 fn integer_pow<T: Element>(x: T, y: i32) -> T {
1353 ruxla_kernels::integer_pow(x, y)
1354 }
1355 #[inline]
1356 fn select<T: Element>(c: bool, t: T, f: T) -> T {
1357 if c { t } else { f }
1358 }
1359 #[inline]
1360 fn cast<T: Element, U: Element>(x: T) -> U {
1361 cast(x)
1362 }
1363 #[inline]
1364 fn bitcast<T: Element, U: Element>(x: T) -> U {
1365 assert_eq!(
1366 T::DTYPE.size_in_bytes(),
1367 U::DTYPE.size_in_bytes(),
1368 "cannot reinterpret {} as {}",
1369 T::DTYPE,
1370 U::DTYPE
1371 );
1372 U::from_bits(x.to_bits())
1373 }
1374 #[inline]
1375 fn to_real<T: Element>(op: ToReal, x: T) -> T::Real {
1376 to_real_native(op, x)
1377 }
1378 #[inline]
1379 fn complex<C: Element>(re: C::Real, im: C::Real) -> C {
1380 C::from_parts(re, im)
1381 }
1382 #[inline]
1383 fn conj<T: Element>(x: T) -> T {
1384 T::from_parts(
1385 x.re(),
1386 <T::Real as ruxla_kernels::Ops>::unary(UnaryOp::Neg, x.im()),
1387 )
1388 }
1389
1390 fn constant<T: Element>(x: &NativeArray<T>) -> NativeArray<T> {
1391 x.clone()
1392 }
1393 #[inline]
1394 fn constant_owned<T: Element>(x: NativeArray<T>) -> NativeArray<T> {
1395 x
1396 }
1397 fn shape<T: Element>(x: &NativeArray<T>) -> Shape {
1398 x.shape.clone()
1399 }
1400 #[inline]
1401 fn to_array<T: Element>(x: T) -> NativeArray<T> {
1402 build(Shape::scalar(), |o| o[0] = x)
1403 }
1404 #[track_caller]
1405 fn to_scalar<T: Element>(x: &NativeArray<T>) -> T {
1406 assert_eq!(
1407 x.shape.rank(),
1408 0,
1409 "expected a scalar, got an array of shape [{}]",
1410 x.shape
1411 );
1412 x.data[0]
1413 }
1414 fn a_unary<T: Element>(op: UnaryOp, x: &NativeArray<T>) -> NativeArray<T> {
1415 build_all(x.shape.clone(), |o| ew::unary_into(op, &x.data, o))
1416 }
1417 #[track_caller]
1418 fn a_binary<T: Element>(
1419 op: BinaryOp,
1420 x: &NativeArray<T>,
1421 y: &NativeArray<T>,
1422 ) -> NativeArray<T> {
1423 same_shape(op.name(), &x.shape, &y.shape);
1424 build_all(x.shape.clone(), |o| {
1425 ew::binary_into(op, &x.data, &y.data, o)
1426 })
1427 }
1428 #[track_caller]
1429 fn a_ternary<T: Element>(
1430 op: TernaryOp,
1431 x: &NativeArray<T>,
1432 y: &NativeArray<T>,
1433 z: &NativeArray<T>,
1434 ) -> NativeArray<T> {
1435 same_shape(op.name(), &x.shape, &y.shape);
1436 same_shape(op.name(), &x.shape, &z.shape);
1437 build_all(x.shape.clone(), |o| {
1438 for (i, o) in o.iter_mut().enumerate() {
1439 *o = T::ternary(op, x.data[i], y.data[i], z.data[i]);
1440 }
1441 })
1442 }
1443 #[track_caller]
1444 fn a_compare<T: Element>(
1445 op: CompareOp,
1446 x: &NativeArray<T>,
1447 y: &NativeArray<T>,
1448 ) -> NativeArray<bool> {
1449 same_shape(op.name(), &x.shape, &y.shape);
1450 build_all(x.shape.clone(), |o| {
1451 ew::compare_into(op, &x.data, &y.data, o)
1452 })
1453 }
1454 fn a_is_finite<T: Element>(x: &NativeArray<T>) -> NativeArray<bool> {
1455 build_all(x.shape.clone(), |o| {
1456 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1457 *o = T::is_finite(a);
1458 }
1459 })
1460 }
1461 fn a_integer_pow<T: Element>(x: &NativeArray<T>, y: i32) -> NativeArray<T> {
1462 build_all(x.shape.clone(), |o| {
1463 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1464 *o = ruxla_kernels::integer_pow(a, y);
1465 }
1466 })
1467 }
1468 fn a_cast<T: Element, U: Element>(x: &NativeArray<T>) -> NativeArray<U> {
1469 build_all(x.shape.clone(), |o| {
1470 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1471 *o = cast(a);
1472 }
1473 })
1474 }
1475 fn a_bitcast<T: Element, U: Element>(x: &NativeArray<T>) -> NativeArray<U> {
1476 build_all(x.shape.clone(), |o| {
1477 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1478 *o = Self::bitcast::<T, U>(a);
1479 }
1480 })
1481 }
1482 fn a_to_real<T: Element>(op: ToReal, x: &NativeArray<T>) -> NativeArray<T::Real> {
1483 build_all(x.shape.clone(), |o| {
1484 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1485 *o = to_real_native(op, a);
1486 }
1487 })
1488 }
1489 #[track_caller]
1490 fn a_complex<C: Element>(
1491 re: &NativeArray<C::Real>,
1492 im: &NativeArray<C::Real>,
1493 ) -> NativeArray<C> {
1494 same_shape("complex", &re.shape, &im.shape);
1495 build_all(re.shape.clone(), |o| {
1496 for ((o, &a), &b) in o.iter_mut().zip(re.data.iter()).zip(im.data.iter()) {
1497 *o = C::from_parts(a, b);
1498 }
1499 })
1500 }
1501 fn a_conj<T: Element>(x: &NativeArray<T>) -> NativeArray<T> {
1502 build_all(x.shape.clone(), |o| {
1503 for (o, &a) in o.iter_mut().zip(x.data.iter()) {
1504 *o = Self::conj::<T>(a);
1505 }
1506 })
1507 }
1508 #[track_caller]
1509 fn a_select<T: Element>(
1510 c: &NativeArray<bool>,
1511 t: &NativeArray<T>,
1512 f: &NativeArray<T>,
1513 ) -> NativeArray<T> {
1514 same_shape("select_n", &t.shape, &f.shape);
1515 if c.shape.rank() != 0 {
1516 same_shape("select_n", &c.shape, &t.shape);
1517 }
1518 let (cd, td, fd): (&[bool], &[T], &[T]) = (&c.data, &t.data, &f.data);
1519 if cd.len() == 1 {
1520 return NativeArray {
1521 data: if cd[0] {
1522 t.data.clone()
1523 } else {
1524 f.data.clone()
1525 },
1526 shape: t.shape.clone(),
1527 };
1528 }
1529 build_all(t.shape.clone(), |o| {
1530 for (((o, &c), &a), &b) in o.iter_mut().zip(cd).zip(td).zip(fd) {
1531 *o = if c { a } else { b };
1532 }
1533 })
1534 }
1535 fn a_clamp<T: Element>(
1536 lo: &NativeArray<T>,
1537 x: &NativeArray<T>,
1538 hi: &NativeArray<T>,
1539 ) -> NativeArray<T> {
1540 native(k::clamp(&lo.data, &x.data, &hi.data), x.shape.clone())
1541 }
1542 fn broadcast_in_dim<T: Element>(
1543 x: &NativeArray<T>,
1544 shape: &[usize],
1545 dims: &[usize],
1546 ) -> NativeArray<T> {
1547 let valid = dims.len() == x.shape.rank()
1548 && dims.windows(2).all(|w| w[0] < w[1])
1549 && dims
1550 .iter()
1551 .zip(x.shape.dims())
1552 .all(|(&d, &n)| d < shape.len() && (n == 1 || n == shape[d]));
1553 if !valid {
1554 check_native(
1556 p::BROADCAST_IN_DIM,
1557 &[x.aval()],
1558 &Params::BroadcastInDim {
1559 shape: shape.into(),
1560 broadcast_dimensions: dims.to_vec(),
1561 },
1562 );
1563 }
1564 if x.shape.rank() == 0 {
1565 let shape = Shape::from(shape);
1566 return NativeArray {
1567 data: Data::filled(shape.size(), x.data[0]),
1568 shape,
1569 };
1570 }
1571 if shape.iter().product::<usize>() == x.data.len() {
1573 return NativeArray {
1574 data: x.data.clone(),
1575 shape: shape.into(),
1576 };
1577 }
1578 build_all(Shape::from(shape), |o| {
1579 k::broadcast_in_dim_into(&x.data, &x.shape, shape, dims, o)
1580 })
1581 }
1582 #[track_caller]
1583 fn reshape<T: Element>(x: &NativeArray<T>, shape: &[usize]) -> NativeArray<T> {
1584 let size = shape.iter().try_fold(1usize, |a, &d| a.checked_mul(d));
1585 assert!(
1586 size == Some(x.data.len()),
1587 "cannot reshape [{}] to {shape:?}",
1588 x.shape
1589 );
1590 NativeArray {
1591 data: x.data.clone(),
1592 shape: shape.into(),
1593 }
1594 }
1595 fn transpose<T: Element>(x: &NativeArray<T>, perm: &[usize]) -> NativeArray<T> {
1596 let rank = x.shape.rank();
1597 let valid = perm.len() == rank && rank <= 8 && (0..rank).all(|d| perm.contains(&d));
1598 if !valid {
1599 let out = check_native(
1601 p::TRANSPOSE,
1602 &[x.aval()],
1603 &Params::Transpose {
1604 permutation: perm.to_vec(),
1605 },
1606 );
1607 return native(k::transpose(&x.data, &x.shape, perm), out);
1608 }
1609 let out: Shape = perm.iter().map(|&p| x.shape[p]).collect();
1610 build_all(out, |o| k::transpose_into(&x.data, &x.shape, perm, o))
1611 }
1612 fn slice<T: Element>(
1613 x: &NativeArray<T>,
1614 start: &[usize],
1615 limit: &[usize],
1616 strides: &[usize],
1617 ) -> NativeArray<T> {
1618 let rank = x.shape.rank();
1619 let valid = start.len() == rank
1620 && limit.len() == rank
1621 && strides.len() == rank
1622 && (0..rank).all(|i| start[i] <= limit[i] && limit[i] <= x.shape[i] && strides[i] > 0);
1623 if !valid {
1624 let params = Params::Slice {
1626 start_indices: start.to_vec(),
1627 limit_indices: limit.to_vec(),
1628 strides: strides.to_vec(),
1629 };
1630 check_native(p::SLICE, &[x.aval()], ¶ms);
1631 }
1632 let out: Shape = (0..rank)
1633 .map(|i| (limit[i] - start[i]).div_ceil(strides[i]))
1634 .collect();
1635 if (1..rank).all(|i| start[i] == 0 && limit[i] == x.shape[i] && strides[i] == 1)
1637 && rank > 0
1638 && strides[0] == 1
1639 {
1640 let inner: usize = x.shape[1..].iter().product();
1641 return NativeArray {
1642 data: Data::from_slice(&x.data[start[0] * inner..limit[0] * inner]),
1643 shape: out,
1644 };
1645 }
1646 if strides.iter().all(|&st| st == 1)
1647 && let Some(r) = copy_box(x, start, out.dims(), out.clone())
1648 {
1649 return r;
1650 }
1651 native(k::slice(&x.data, &x.shape, start, limit, strides), out)
1652 }
1653 #[track_caller]
1654 fn dynamic_slice<T: Element, I: Element>(
1655 x: &NativeArray<T>,
1656 starts: &[I],
1657 sizes: &[usize],
1658 ) -> NativeArray<T> {
1659 assert!(
1660 starts.len() == x.shape.rank()
1661 && sizes.len() == x.shape.rank()
1662 && sizes.iter().zip(x.shape.dims()).all(|(s, n)| s <= n),
1663 "dynamic_slice: invalid sizes {sizes:?} for shape [{}]",
1664 x.shape
1665 );
1666 let mut at = [0usize; 8];
1668 if starts.len() <= at.len() {
1669 for ((a, &s), (&n, &k)) in at
1670 .iter_mut()
1671 .zip(starts)
1672 .zip(x.shape.dims().iter().zip(sizes))
1673 {
1674 *a = cast::<I, i64>(s).clamp(0, (n - k) as i64) as usize;
1675 }
1676 if let Some(r) = copy_box(x, &at[..starts.len()], sizes, Shape::from(sizes)) {
1677 return r;
1678 }
1679 }
1680 native(
1681 k::dynamic_slice(&x.data, &x.shape, &starts_i64(starts), sizes),
1682 sizes,
1683 )
1684 }
1685 #[track_caller]
1686 fn dynamic_update_slice<T: Element, I: Element>(
1687 x: &NativeArray<T>,
1688 update: &NativeArray<T>,
1689 starts: &[I],
1690 ) -> NativeArray<T> {
1691 assert!(
1692 starts.len() == x.shape.rank()
1693 && update.shape.rank() == x.shape.rank()
1694 && update.shape.iter().zip(x.shape.dims()).all(|(u, n)| u <= n),
1695 "dynamic_update_slice: update [{}] does not fit [{}]",
1696 update.shape,
1697 x.shape
1698 );
1699 native(
1700 k::dynamic_update_slice(
1701 &x.data,
1702 &x.shape,
1703 &update.data,
1704 &update.shape,
1705 &starts_i64(starts),
1706 ),
1707 x.shape.clone(),
1708 )
1709 }
1710 fn concatenate<T: Element>(xs: &[NativeArray<T>], dim: usize) -> NativeArray<T> {
1711 let first = &xs[0].shape;
1712 let valid = dim < first.rank()
1713 && xs.iter().all(|x| {
1714 x.shape.rank() == first.rank()
1715 && (0..first.rank()).all(|i| i == dim || x.shape[i] == first[i])
1716 });
1717 if !valid {
1718 let avals: Vec<AVal> = xs.iter().map(NativeArray::aval).collect();
1720 check_native(
1721 p::CONCATENATE,
1722 &avals,
1723 &Params::Concatenate { dimension: dim },
1724 );
1725 }
1726 let out: Shape = (0..first.rank())
1727 .map(|i| {
1728 if i == dim {
1729 xs.iter().map(|x| x.shape[i]).sum()
1730 } else {
1731 first[i]
1732 }
1733 })
1734 .collect();
1735 if first[..dim].iter().all(|&d| d == 1) {
1738 return build(out, |o| {
1739 let mut at = 0;
1740 for x in xs {
1741 o[at..at + x.data.len()].copy_from_slice(&x.data);
1742 at += x.data.len();
1743 }
1744 });
1745 }
1746 let outer: usize = first[..dim].iter().product();
1749 let inner = |x: &NativeArray<T>| x.shape.dims()[dim..].iter().product::<usize>();
1750 build(out, |o| {
1751 if xs.iter().all(|x| inner(x) == 1) {
1752 let n = xs.len();
1754 for (k, x) in xs.iter().enumerate() {
1755 for (i, &v) in x.data.iter().enumerate() {
1756 o[i * n + k] = v;
1757 }
1758 }
1759 return;
1760 }
1761 let inners: Vec<usize> = xs.iter().map(inner).collect();
1762 let mut at = 0;
1763 for i in 0..outer {
1764 for (x, &n) in xs.iter().zip(&inners) {
1765 o[at..at + n].copy_from_slice(&x.data[i * n..(i + 1) * n]);
1766 at += n;
1767 }
1768 }
1769 })
1770 }
1771 fn pad<T: Element>(
1772 x: &NativeArray<T>,
1773 value: T,
1774 config: &[(i64, i64, usize)],
1775 ) -> NativeArray<T> {
1776 let out = check_native(
1777 p::PAD,
1778 &[x.aval(), AVal::scalar(T::DTYPE)],
1779 &Params::Pad {
1780 padding_config: config.to_vec(),
1781 },
1782 );
1783 native(k::pad(&x.data, &x.shape, value, config), out)
1784 }
1785 fn rev<T: Element>(x: &NativeArray<T>, dims: &[usize]) -> NativeArray<T> {
1786 check_native(
1787 p::REV,
1788 &[x.aval()],
1789 &Params::Rev {
1790 dimensions: dims.to_vec(),
1791 },
1792 );
1793 native(k::rev(&x.data, &x.shape, dims), x.shape.clone())
1794 }
1795 fn iota<T: Element>(shape: &[usize], dim: usize) -> NativeArray<T> {
1796 build_all(Shape::from(shape), |o| k::iota_into::<T>(shape, dim, o))
1797 }
1798 fn reduce<T: Element>(op: ReduceOp, x: &NativeArray<T>, axes: &[usize]) -> NativeArray<T> {
1799 let prim = match op {
1800 ReduceOp::Sum => p::REDUCE_SUM,
1801 ReduceOp::Max => p::REDUCE_MAX,
1802 ReduceOp::Min => p::REDUCE_MIN,
1803 };
1804 let rank = x.shape.rank();
1805 let valid = axes
1806 .iter()
1807 .enumerate()
1808 .all(|(i, &a)| a < rank && !axes[..i].contains(&a))
1809 && (op != ReduceOp::Sum || T::DTYPE != ruxla_ir::DType::Bool);
1810 if !valid {
1811 check_native(
1813 prim,
1814 &[x.aval()],
1815 &Params::Reduce {
1816 axes: axes.to_vec(),
1817 },
1818 );
1819 }
1820 let out: Shape = (0..rank)
1821 .filter(|i| !axes.contains(i))
1822 .map(|i| x.shape[i])
1823 .collect();
1824 if axes.len() == rank {
1826 let acc = k::reduce_all(&x.data, op);
1827 return build(out, |o| o[0] = acc);
1828 }
1829 native(k::reduce(&x.data, &x.shape, axes, op), out)
1830 }
1831 fn arg_min_max<T: Element, I: Element>(
1832 x: &NativeArray<T>,
1833 axis: usize,
1834 max: bool,
1835 ) -> NativeArray<I> {
1836 let prim = if max { p::ARGMAX } else { p::ARGMIN };
1837 let out = check_native(
1838 prim,
1839 &[x.aval()],
1840 &Params::ArgMinMax {
1841 axis,
1842 index_dtype: I::DTYPE,
1843 },
1844 );
1845 native(
1846 k::arg_min_max(&x.data, &x.shape, axis, max)
1847 .into_iter()
1848 .map(cast)
1849 .collect(),
1850 out,
1851 )
1852 }
1853 fn sort(
1854 operands: &[HostArray],
1855 dimension: usize,
1856 is_stable: bool,
1857 num_keys: usize,
1858 ) -> Vec<HostArray> {
1859 let avals: Vec<AVal> = operands.iter().map(HostArray::aval).collect();
1860 let params = Params::Sort {
1861 dimension,
1862 is_stable,
1863 num_keys,
1864 };
1865 check_native(p::SORT, &avals, ¶ms);
1866 let shape = operands[0].shape().clone();
1867 let buffers: Vec<_> = operands.iter().map(HostArray::buffer).collect();
1868 k::sort(&buffers, &shape, dimension, num_keys)
1870 .into_iter()
1871 .map(|b| HostArray::from_buffer(b, shape.clone()))
1872 .collect()
1873 }
1874 fn cumulative<T: Element>(
1875 op: CumulativeOp,
1876 x: &NativeArray<T>,
1877 axis: usize,
1878 reverse: bool,
1879 ) -> NativeArray<T> {
1880 let out = check_native(
1881 cumulative_prim(op),
1882 &[x.aval()],
1883 &Params::Cumulative { axis, reverse },
1884 );
1885 native(k::cumulative(&x.data, &x.shape, axis, reverse, op), out)
1886 }
1887 fn top_k<T: Element>(
1888 x: &NativeArray<T>,
1889 k: usize,
1890 axis: usize,
1891 ) -> (NativeArray<T>, NativeArray<i32>) {
1892 let params = Params::TopK {
1893 k,
1894 axis,
1895 is_stable: true,
1896 };
1897 let out = check_native(p::TOP_K, &[x.aval()], ¶ms);
1898 let (values, indices) = k::top_k(&x.data, &x.shape, k, axis);
1899 (native(values, out.clone()), native(indices, out))
1900 }
1901 fn cholesky<T: LinalgScalar>(x: &NativeArray<T>) -> NativeArray<T> {
1902 let out = check_native(p::CHOLESKY, &[x.aval()], &Params::None);
1903 let (batch, n, _) = matrix_dims(&x.shape);
1904 native(kl::cholesky(&x.data, batch, n), out)
1905 }
1906 fn triangular_solve<T: LinalgScalar>(
1907 a: &NativeArray<T>,
1908 b: &NativeArray<T>,
1909 options: TriangularSolveOptions,
1910 ) -> NativeArray<T> {
1911 let params = triangular_solve_params(options);
1912 let out = check_native(p::TRIANGULAR_SOLVE, &[a.aval(), b.aval()], ¶ms);
1913 let (batch, m, n) = matrix_dims(&b.shape);
1914 native(
1915 kl::triangular_solve(&a.data, &b.data, batch, m, n, options),
1916 out,
1917 )
1918 }
1919 fn lu<T: LinalgScalar>(
1920 x: &NativeArray<T>,
1921 ) -> (NativeArray<T>, NativeArray<i32>, NativeArray<i32>) {
1922 let outs = check_native_all(p::LU, &[x.aval()], &Params::None);
1923 let (batch, m, n) = matrix_dims(&x.shape);
1924 let (lu, pivots, perm) = kl::lu(&x.data, batch, m, n);
1925 (
1926 native(lu, outs[0].clone()),
1927 native(pivots, outs[1].clone()),
1928 native(perm, outs[2].clone()),
1929 )
1930 }
1931 fn lu_pivots_to_permutation(pivots: &NativeArray<i32>, size: usize) -> NativeArray<i32> {
1932 let params = Params::LuPivotsToPermutation {
1933 permutation_size: size,
1934 };
1935 let out = check_native(p::LU_PIVOTS_TO_PERMUTATION, &[pivots.aval()], ¶ms);
1936 let dims = pivots.shape.dims();
1937 let k = dims[dims.len() - 1];
1938 let batch = dims[..dims.len() - 1].iter().product();
1939 native(
1940 kl::lu_pivots_to_permutation(&pivots.data, batch, k, size),
1941 out,
1942 )
1943 }
1944 fn qr<T: LinalgScalar>(
1945 x: &NativeArray<T>,
1946 full_matrices: bool,
1947 ) -> (NativeArray<T>, NativeArray<T>) {
1948 let params = Params::Qr {
1949 full_matrices,
1950 pivoting: false,
1951 };
1952 let outs = check_native_all(p::QR, &[x.aval()], ¶ms);
1953 let (batch, m, n) = matrix_dims(&x.shape);
1954 let (q, r) = kl::qr(&x.data, batch, m, n, full_matrices);
1955 (native(q, outs[0].clone()), native(r, outs[1].clone()))
1956 }
1957 fn qr_pivoting<T: LinalgScalar>(
1958 x: &NativeArray<T>,
1959 full_matrices: bool,
1960 ) -> (NativeArray<T>, NativeArray<T>, NativeArray<i32>) {
1961 let params = Params::Qr {
1962 full_matrices,
1963 pivoting: true,
1964 };
1965 let outs = check_native_all(p::QR, &[x.aval()], ¶ms);
1966 let (batch, m, n) = matrix_dims(&x.shape);
1967 let (q, r, perm) = kl::qr_pivoting(&x.data, batch, m, n, full_matrices);
1968 (
1969 native(q, outs[0].clone()),
1970 native(r, outs[1].clone()),
1971 native(perm, outs[2].clone()),
1972 )
1973 }
1974 fn eigh<T: LinalgScalar>(
1975 x: &NativeArray<T>,
1976 lower: bool,
1977 sort_eigenvalues: bool,
1978 subset_by_index: Option<(usize, usize)>,
1979 algorithm: Option<EighImplementation>,
1980 ) -> (NativeArray<T>, NativeArray<T::Real>) {
1981 let params = Params::Eigh {
1982 lower,
1983 sort_eigenvalues,
1984 subset_by_index,
1985 algorithm,
1986 };
1987 let outs = check_native_all(p::EIGH, &[x.aval()], ¶ms);
1988 let (batch, n, _) = matrix_dims(&x.shape);
1989 let jacobi = algorithm == Some(EighImplementation::Jacobi);
1990 let (v, w) = kl::eigh(&x.data, batch, n, lower, jacobi);
1991 let (v, w) = match subset_by_index {
1992 Some(range) => (
1993 slice_columns(&v, batch * n, n, range),
1994 slice_columns(&w, batch, n, range),
1995 ),
1996 None => (v, w),
1997 };
1998 (native(v, outs[0].clone()), native(w, outs[1].clone()))
1999 }
2000 fn schur<T: LinalgScalar>(
2001 x: &NativeArray<T>,
2002 compute_schur_vectors: bool,
2003 ) -> (NativeArray<T>, Option<NativeArray<T>>) {
2004 let params = Params::Schur {
2005 compute_schur_vectors,
2006 };
2007 let outs = check_native_all(p::SCHUR, &[x.aval()], ¶ms);
2008 let (batch, n, _) = matrix_dims(&x.shape);
2009 let (t, z) = kl::schur(&x.data, batch, n, compute_schur_vectors);
2010 let z = compute_schur_vectors.then(|| native(z, outs[1].clone()));
2011 (native(t, outs[0].clone()), z)
2012 }
2013 fn hessenberg<T: LinalgScalar>(x: &NativeArray<T>) -> (NativeArray<T>, NativeArray<T>) {
2014 let outs = check_native_all(p::HESSENBERG, &[x.aval()], &Params::None);
2015 let (batch, n, _) = matrix_dims(&x.shape);
2016 let (h, taus) = kl::hessenberg(&x.data, batch, n);
2017 (native(h, outs[0].clone()), native(taus, outs[1].clone()))
2018 }
2019 fn householder_product<T: LinalgScalar>(
2020 a: &NativeArray<T>,
2021 taus: &NativeArray<T>,
2022 ) -> NativeArray<T> {
2023 let out = check_native(
2024 p::HOUSEHOLDER_PRODUCT,
2025 &[a.aval(), taus.aval()],
2026 &Params::None,
2027 );
2028 let (batch, m, n) = matrix_dims(&a.shape);
2029 let k = *taus.shape.dims().last().unwrap_or(&0);
2030 native(
2031 kl::householder_product(&a.data, &taus.data, batch, m, n, k),
2032 out,
2033 )
2034 }
2035 fn ormqr<T: LinalgScalar>(
2036 a: &NativeArray<T>,
2037 taus: &NativeArray<T>,
2038 c: &NativeArray<T>,
2039 left: bool,
2040 transpose: bool,
2041 ) -> NativeArray<T> {
2042 let params = Params::Ormqr { left, transpose };
2043 let out = check_native(p::ORMQR, &[a.aval(), taus.aval(), c.aval()], ¶ms);
2044 let (batch, m, n) = matrix_dims(&a.shape);
2045 let k = *taus.shape.dims().last().unwrap_or(&0);
2046 let (_, rows, cols) = matrix_dims(&c.shape);
2047 native(
2048 kl::ormqr(
2049 &a.data,
2050 &taus.data,
2051 &c.data,
2052 batch,
2053 (m, n, k),
2054 (rows, cols),
2055 left,
2056 transpose,
2057 ),
2058 out,
2059 )
2060 }
2061 fn cholesky_update<T: LinalgFloat>(r: &NativeArray<T>, w: &NativeArray<T>) -> NativeArray<T> {
2062 let out = check_native(p::CHOLESKY_UPDATE, &[r.aval(), w.aval()], &Params::None);
2063 let (batch, n, _) = matrix_dims(&r.shape);
2064 native(kl::cholesky_update(&r.data, &w.data, batch, n), out)
2065 }
2066 fn symmetric_product<T: LinalgFloat>(
2067 a: &NativeArray<T>,
2068 c: &NativeArray<T>,
2069 alpha: f64,
2070 beta: f64,
2071 ) -> NativeArray<T> {
2072 let out = check_native(
2073 p::SYMMETRIC_PRODUCT,
2074 &[a.aval(), c.aval()],
2075 &Params::SymmetricProduct { alpha, beta },
2076 );
2077 let (batch, m, n) = matrix_dims(&a.shape);
2078 let (alpha, beta) = (
2079 ruxla_kernels::cast::<f64, T>(alpha),
2080 ruxla_kernels::cast::<f64, T>(beta),
2081 );
2082 native(
2083 kl::symmetric_product(&a.data, &c.data, batch, m, n, alpha, beta),
2084 out,
2085 )
2086 }
2087 fn tridiagonal<T: LinalgScalar>(
2088 x: &NativeArray<T>,
2089 lower: bool,
2090 ) -> (
2091 NativeArray<T>,
2092 NativeArray<T::Real>,
2093 NativeArray<T::Real>,
2094 NativeArray<T>,
2095 ) {
2096 let outs = check_native_all(p::TRIDIAGONAL, &[x.aval()], &Params::Tridiagonal { lower });
2097 let (batch, n, _) = matrix_dims(&x.shape);
2098 let (a, d, e, taus) = kl::tridiagonal(&x.data, batch, n, lower);
2099 (
2100 native(a, outs[0].clone()),
2101 native(d, outs[1].clone()),
2102 native(e, outs[2].clone()),
2103 native(taus, outs[3].clone()),
2104 )
2105 }
2106 fn tridiagonal_solve<T: LinalgScalar>(
2107 dl: &NativeArray<T>,
2108 d: &NativeArray<T>,
2109 du: &NativeArray<T>,
2110 b: &NativeArray<T>,
2111 perturb_singular: bool,
2112 ) -> NativeArray<T> {
2113 let out = check_native(
2114 p::TRIDIAGONAL_SOLVE,
2115 &[dl.aval(), d.aval(), du.aval(), b.aval()],
2116 &Params::TridiagonalSolve { perturb_singular },
2117 );
2118 let (batch, m, n) = matrix_dims(&b.shape);
2119 native(
2120 kl::tridiagonal_solve(
2121 &dl.data,
2122 &d.data,
2123 &du.data,
2124 &b.data,
2125 batch,
2126 m,
2127 n,
2128 perturb_singular,
2129 ),
2130 out,
2131 )
2132 }
2133 fn eig<T: LinalgScalar>(
2134 x: &NativeArray<T>,
2135 left: bool,
2136 right: bool,
2137 enable_eigvec_derivs: bool,
2138 ) -> (
2139 NativeArray<<T as LinalgScalar>::Complex>,
2140 Option<NativeArray<<T as LinalgScalar>::Complex>>,
2141 Option<NativeArray<<T as LinalgScalar>::Complex>>,
2142 ) {
2143 let params = Params::Eig {
2144 compute_left_eigenvectors: left,
2145 compute_right_eigenvectors: right,
2146 enable_eigvec_derivs,
2147 };
2148 let outs = check_native_all(p::EIG, &[x.aval()], ¶ms);
2149 let (batch, n, _) = matrix_dims(&x.shape);
2150 let (w, vl, vr) = kl::eig(&x.data, batch, n, left, right);
2151 let w = native(T::complex_vec(w), outs[0].clone());
2152 let vl = left.then(|| native(T::complex_vec(vl), outs[1].clone()));
2153 let vr = right.then(|| native(T::complex_vec(vr), outs[outs.len() - 1].clone()));
2154 (w, vl, vr)
2155 }
2156 fn svd<T: LinalgScalar>(
2157 x: &NativeArray<T>,
2158 full_matrices: bool,
2159 compute_uv: bool,
2160 subset_by_index: Option<(usize, usize)>,
2161 algorithm: Option<SvdAlgorithm>,
2162 ) -> (
2163 NativeArray<T::Real>,
2164 Option<(NativeArray<T>, NativeArray<T>)>,
2165 ) {
2166 let params = Params::Svd {
2167 full_matrices,
2168 compute_uv,
2169 subset_by_index,
2170 algorithm,
2171 };
2172 let outs = check_native_all(p::SVD, &[x.aval()], ¶ms);
2173 let (batch, m, n) = matrix_dims(&x.shape);
2174 let jacobi = algorithm == Some(SvdAlgorithm::Jacobi);
2175 let (s, u, vt) = kl::svd(&x.data, batch, m, n, full_matrices, compute_uv, jacobi);
2176 let k = m.min(n);
2177 let (s, u, vt) = match subset_by_index {
2178 Some(range) if !compute_uv => (slice_columns(&s, batch, k, range), u, vt),
2179 Some(range) => (
2180 slice_columns(&s, batch, k, range),
2181 slice_columns(&u, batch * m, k, range),
2182 slice_columns(&vt, batch, k * n, (range.0 * n, range.1 * n)),
2185 ),
2186 None => (s, u, vt),
2187 };
2188 let s = native(s, outs[0].clone());
2189 let uv = compute_uv.then(|| (native(u, outs[1].clone()), native(vt, outs[2].clone())));
2190 (s, uv)
2191 }
2192 fn fft<T: Element, U: Element>(
2193 x: &NativeArray<T>,
2194 fft_type: FftType,
2195 fft_lengths: &[usize],
2196 ) -> NativeArray<U> {
2197 let params = Params::Fft {
2198 fft_type,
2199 fft_lengths: fft_lengths.to_vec(),
2200 };
2201 let out = check_native(p::FFT, &[x.aval()], ¶ms);
2202 let b = ruxla_kernels::fft::fft(
2203 &ruxla_kernels::Buffer::from_vec(x.data.to_vec()),
2204 &x.shape,
2205 fft_type,
2206 fft_lengths,
2207 );
2208 let v = b.as_slice::<U>().expect("the result type").to_vec();
2209 native(v, out)
2210 }
2211 fn dot_general<T: Element, U: Element>(
2212 l: &NativeArray<T>,
2213 r: &NativeArray<T>,
2214 dims: &DotDims,
2215 precision: Precision,
2216 ) -> NativeArray<U> {
2217 let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
2218 let params = Params::DotGeneral {
2219 dimension_numbers: dims.clone(),
2220 precision,
2221 preferred_element_type: preferred,
2222 };
2223 let out = check_native(p::DOT_GENERAL, &[l.aval(), r.aval()], ¶ms);
2224 let (lu, ru): (Vec<U>, Vec<U>) = (
2225 l.data.iter().map(|&a| cast(a)).collect(),
2226 r.data.iter().map(|&a| cast(a)).collect(),
2227 );
2228 native(k::dot_general(&lu, &l.shape, &ru, &r.shape, dims), out)
2229 }
2230 fn conv_general_dilated<T: Element, U: Element>(
2231 lhs: &NativeArray<T>,
2232 rhs: &NativeArray<T>,
2233 window: &ConvWindow<'_>,
2234 dims: &ConvDims,
2235 groups: (usize, usize),
2236 precision: Precision,
2237 ) -> NativeArray<U> {
2238 let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
2239 let params = conv_params(window, dims, groups, precision, preferred);
2240 let out = check_native(p::CONV_GENERAL_DILATED, &[lhs.aval(), rhs.aval()], ¶ms);
2241 let (lu, ru): (Vec<U>, Vec<U>) = (
2242 lhs.data.iter().map(|&a| cast(a)).collect(),
2243 rhs.data.iter().map(|&a| cast(a)).collect(),
2244 );
2245 native(
2246 kw::conv_general_dilated(
2247 &lu, &lhs.shape, &ru, &rhs.shape, window, dims, groups.0, groups.1,
2248 ),
2249 out,
2250 )
2251 }
2252 fn reduce_window<T: Element>(
2253 op: ReduceOp,
2254 x: &NativeArray<T>,
2255 window: &Window<'_>,
2256 ) -> NativeArray<T> {
2257 let out = check_native(reduce_window_prim(op), &[x.aval()], &window_params(window));
2258 native(kw::reduce_window(&x.data, &x.shape, window, op), out)
2259 }
2260 fn select_and_scatter_add<T: Element>(
2261 source: &NativeArray<T>,
2262 operand: &NativeArray<T>,
2263 select_prim: SelectPrim,
2264 window: &Window<'_>,
2265 ) -> NativeArray<T> {
2266 let params = select_and_scatter_add_params(select_prim, window);
2267 let out = check_native(
2268 p::SELECT_AND_SCATTER_ADD,
2269 &[source.aval(), operand.aval()],
2270 ¶ms,
2271 );
2272 native(
2273 kw::select_and_scatter_add(
2274 &source.data,
2275 &operand.data,
2276 &operand.shape,
2277 window.dimensions,
2278 window.strides,
2279 window.padding,
2280 select_prim == SelectPrim::Ge,
2281 ),
2282 out,
2283 )
2284 }
2285 fn select_and_gather_add<T: Element>(
2286 tangents: &NativeArray<T>,
2287 operand: &NativeArray<T>,
2288 select_prim: SelectPrim,
2289 window: &Window<'_>,
2290 ) -> NativeArray<T> {
2291 let params = select_and_gather_add_params(select_prim, window);
2292 let out = check_native(
2293 p::SELECT_AND_GATHER_ADD,
2294 &[tangents.aval(), operand.aval()],
2295 ¶ms,
2296 );
2297 native(
2298 kw::select_and_gather_add(
2299 &tangents.data,
2300 &operand.data,
2301 &operand.shape,
2302 window,
2303 select_prim == SelectPrim::Ge,
2304 ),
2305 out,
2306 )
2307 }
2308 fn gather<T: Element, I: Element>(
2309 x: &NativeArray<T>,
2310 indices: &NativeArray<I>,
2311 dims: &GatherDims,
2312 sizes: &[usize],
2313 mode: GatherScatterMode,
2314 sorted_unique: bool,
2315 ) -> NativeArray<T> {
2316 let params = Params::Gather {
2317 dimension_numbers: dims.clone(),
2318 slice_sizes: sizes.to_vec(),
2319 mode,
2320 indices_are_sorted: sorted_unique,
2321 unique_indices: sorted_unique,
2322 };
2323 let out = check_native(p::GATHER, &[x.aval(), indices.aval()], ¶ms);
2324 native(
2325 k::gather(
2326 &x.data,
2327 &x.shape,
2328 &starts_i64(&indices.data),
2329 &indices.shape,
2330 dims,
2331 sizes,
2332 ),
2333 out,
2334 )
2335 }
2336 fn scatter<T: Element, I: Element>(
2337 combine: Option<BinaryOp>,
2338 x: &NativeArray<T>,
2339 indices: &NativeArray<I>,
2340 updates: &NativeArray<T>,
2341 dims: &ScatterDims,
2342 mode: GatherScatterMode,
2343 sorted_unique: bool,
2344 ) -> NativeArray<T> {
2345 let params = Params::Scatter {
2346 dimension_numbers: dims.clone(),
2347 mode,
2348 indices_are_sorted: sorted_unique,
2349 unique_indices: sorted_unique,
2350 };
2351 check_native(
2352 scatter_prim(combine),
2353 &[x.aval(), indices.aval(), updates.aval()],
2354 ¶ms,
2355 );
2356 let f = combine.map(|op| move |a: T, b: T| T::binary(op, a, b));
2357 let f_ref: Option<&dyn Fn(T, T) -> T> = f.as_ref().map(|f| f as &dyn Fn(T, T) -> T);
2358 native(
2359 k::scatter(
2360 &x.data,
2361 &x.shape,
2362 &starts_i64(&indices.data),
2363 &indices.shape,
2364 &updates.data,
2365 &updates.shape,
2366 dims,
2367 mode,
2368 f_ref,
2369 ),
2370 x.shape.clone(),
2371 )
2372 }
2373
2374 fn cond<S: Tree<Self>, R: Tree<Self>>(
2375 index: I32<Native>,
2376 branches: &[&dyn Fn(S) -> R],
2377 operand: S,
2378 ) -> R {
2379 let n = branches.len();
2380 let i = usize::try_from(index.value())
2381 .ok()
2382 .filter(|&i| i < n)
2383 .unwrap_or(n - 1);
2384 branches[i](operand)
2385 }
2386 fn while_loop<C: Tree<Self>>(
2387 cond: &dyn Fn(&C) -> Bool<Native>,
2388 body: &dyn Fn(C) -> C,
2389 init: C,
2390 ) -> C {
2391 let mut c = init;
2392 while cond(&c).value() {
2393 c = body(c);
2394 }
2395 c
2396 }
2397 fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
2398 f: &dyn Fn(C, X) -> (C, Y),
2399 init: C,
2400 xs: X,
2401 length: usize,
2402 reverse: bool,
2403 ) -> (C, Y) {
2404 let mut x_leaves = Vec::new();
2405 xs.flatten(&mut x_leaves);
2406 let mut carry = init;
2407 let mut ys: Vec<Y> = Vec::with_capacity(length);
2408 let order: Vec<usize> = if reverse {
2409 (0..length).rev().collect()
2410 } else {
2411 (0..length).collect()
2412 };
2413 for &i in &order {
2414 let slices: Vec<HostArray> = x_leaves.iter().map(|x| index_leading(x, i)).collect();
2415 let x = xs.unflatten_like(&mut slices.into_iter());
2416 let (c, y) = f(carry, x);
2417 carry = c;
2418 ys.push(y);
2419 }
2420 if reverse {
2421 ys.reverse();
2422 }
2423 if length == 0 {
2424 let zeros: Vec<HostArray> = x_leaves
2427 .iter()
2428 .map(|x| HostArray::zeros(x.shape().dims()[1..].to_vec(), x.dtype()))
2429 .collect();
2430 let (_, y) = f(carry.clone(), xs.unflatten_like(&mut zeros.into_iter()));
2431 let mut leaves = Vec::new();
2432 y.flatten(&mut leaves);
2433 let empty = leaves.iter().map(|l| {
2434 let mut shape = vec![0];
2435 shape.extend_from_slice(l.shape());
2436 HostArray::zeros(shape, l.dtype())
2437 });
2438 return (
2439 carry,
2440 y.unflatten_like(&mut empty.collect::<Vec<_>>().into_iter()),
2441 );
2442 }
2443 let ys = stack_trees(&ys, length);
2444 (carry, ys)
2445 }
2446 #[inline]
2447 fn a_binary_broadcast<T: Element>(
2448 op: BinaryOp,
2449 x: &NativeArray<T>,
2450 y: &NativeArray<T>,
2451 ) -> Option<NativeArray<T>> {
2452 let Some(shape) = broadcast_shape_simple(x, y) else {
2453 return broadcast_rows(x, y, |a, b, o| ew::binary_into(op, a, b, o));
2454 };
2455 Some(build_all(shape.clone(), |o| {
2456 ew::binary_into(op, &x.data, &y.data, o);
2457 }))
2458 }
2459 #[inline]
2460 fn a_compare_broadcast<T: Element>(
2461 op: CompareOp,
2462 x: &NativeArray<T>,
2463 y: &NativeArray<T>,
2464 ) -> Option<NativeArray<bool>> {
2465 let Some(shape) = broadcast_shape_simple(x, y) else {
2466 return broadcast_rows(x, y, |a, b, o| ew::compare_into(op, a, b, o));
2467 };
2468 Some(build_all(shape.clone(), |o| {
2469 ew::compare_into(op, &x.data, &y.data, o);
2470 }))
2471 }
2472 #[inline]
2473 fn a_binary_assign<T: Element>(
2474 op: BinaryOp,
2475 x: &mut NativeArray<T>,
2476 y: &NativeArray<T>,
2477 ) -> bool {
2478 let fits = y.shape == x.shape || (y.data.len() == 1 && y.shape.rank() <= x.shape.rank());
2479 if !fits || !x.data.is_unique() {
2480 return false;
2481 }
2482 ew::binary_assign(op, x.data.unique_mut(), &y.data);
2483 true
2484 }
2485 #[inline]
2486 fn a_unary_assign<T: Element>(op: UnaryOp, x: &mut NativeArray<T>) -> bool {
2487 if !x.data.is_unique() {
2488 return false;
2489 }
2490 ew::unary_assign(op, x.data.unique_mut());
2491 true
2492 }
2493 fn a_select_broadcast<T: Element>(
2494 c: &NativeArray<bool>,
2495 x: &NativeArray<T>,
2496 y: &NativeArray<T>,
2497 ) -> Option<NativeArray<T>> {
2498 let mut shape: Option<&Shape> = None;
2501 for s in [&c.shape, &x.shape, &y.shape] {
2502 if s.rank() != 0 {
2503 match shape {
2504 Some(t) if t != s => return None,
2505 _ => shape = Some(s),
2506 }
2507 }
2508 }
2509 let shape = shape?.clone();
2510 let n = shape.size();
2511 let pick = |a: &NativeArray<T>| {
2512 if a.shape.rank() == 0 {
2513 NativeArray {
2514 data: Data::filled(n, a.data[0]),
2515 shape: shape.clone(),
2516 }
2517 } else {
2518 a.clone()
2519 }
2520 };
2521 if c.shape.rank() == 0 {
2522 return Some(pick(if c.data[0] { x } else { y }));
2523 }
2524 let (cd, xd, yd): (&[bool], &[T], &[T]) = (&c.data, &x.data, &y.data);
2525 Some(build_all(shape.clone(), |o| {
2526 match (xd.len() == n, yd.len() == n) {
2527 (true, true) => {
2528 for (((o, &c), &a), &b) in o.iter_mut().zip(cd).zip(xd).zip(yd) {
2529 *o = if c { a } else { b };
2530 }
2531 }
2532 (true, false) => {
2533 for ((o, &c), &a) in o.iter_mut().zip(cd).zip(xd) {
2534 *o = if c { a } else { yd[0] };
2535 }
2536 }
2537 (false, true) => {
2538 for ((o, &c), &b) in o.iter_mut().zip(cd).zip(yd) {
2539 *o = if c { xd[0] } else { b };
2540 }
2541 }
2542 (false, false) => {
2543 for (o, &c) in o.iter_mut().zip(cd) {
2544 *o = if c { xd[0] } else { yd[0] };
2545 }
2546 }
2547 }
2548 }))
2549 }
2550 fn a_take<T: Element, I: Element>(
2551 x: &NativeArray<T>,
2552 indices: &NativeArray<I>,
2553 axis: usize,
2554 ) -> Option<NativeArray<T>> {
2555 let dims = x.shape.dims();
2556 let n = dims[axis];
2557 if n == 0 {
2558 return None;
2559 }
2560 let inner: usize = dims[axis + 1..].iter().product();
2561 let outer: usize = dims[..axis].iter().product();
2562 let mut out_dims = dims[..axis].to_vec();
2563 out_dims.extend_from_slice(indices.shape.dims());
2564 out_dims.extend_from_slice(&dims[axis + 1..]);
2565 let id: &[I] = &indices.data;
2566 let xd: &[T] = &x.data;
2567 let row = |i: I| {
2570 let i = cast::<I, i64>(i);
2571 let i = if i < 0 { i + n as i64 } else { i };
2572 i.clamp(0, n as i64 - 1) as usize
2573 };
2574 Some(build_all(Shape::from(out_dims), |o| {
2575 if inner == 1 {
2576 for (b, o) in o.chunks_exact_mut(id.len().max(1)).enumerate() {
2579 let base = &xd[b * n..(b + 1) * n];
2580 for (o, &i) in o.iter_mut().zip(id) {
2581 *o = base[row(i)];
2582 }
2583 }
2584 return;
2585 }
2586 let mut at = 0;
2587 for b in 0..outer {
2588 for &i in id {
2589 let src = (b * n + row(i)) * inner;
2590 o[at..at + inner].copy_from_slice(&xd[src..src + inner]);
2591 at += inner;
2592 }
2593 }
2594 }))
2595 }
2596 fn a_roll<T: Element>(x: &NativeArray<T>, shift: usize, axis: usize) -> Option<NativeArray<T>> {
2597 let dims = x.shape.dims();
2598 let n = dims[axis];
2599 let inner: usize = dims[axis + 1..].iter().product();
2600 let block = n * inner;
2602 let (k, xd): (usize, &[T]) = (shift * inner, &x.data);
2603 Some(build_all(x.shape.clone(), |o| {
2604 for (o, x) in o.chunks_exact_mut(block).zip(xd.chunks_exact(block)) {
2605 o[k..].copy_from_slice(&x[..block - k]);
2606 o[..k].copy_from_slice(&x[block - k..]);
2607 }
2608 }))
2609 }
2610 #[inline]
2611 fn key_from_array(data: NativeArray<u32>) -> NativeKey {
2612 if data.shape.dims() == [2] {
2613 NativeKey::Single([data.data[0], data.data[1]])
2614 } else {
2615 NativeKey::Array(Arc::new(data))
2616 }
2617 }
2618 #[inline]
2619 fn key_to_array(key: &NativeKey) -> NativeArray<u32> {
2620 match key {
2621 NativeKey::Single([a, b]) => build(Shape::from([2]), |o| {
2622 o[0] = *a;
2623 o[1] = *b;
2624 }),
2625 NativeKey::Array(a) => (**a).clone(),
2626 }
2627 }
2628 #[inline]
2629 fn key_rank(key: &NativeKey) -> usize {
2630 match key {
2631 NativeKey::Single(_) => 1,
2632 NativeKey::Array(a) => a.shape.rank(),
2633 }
2634 }
2635 fn random_uniform<T: crate::value::Float>(
2636 key: &NativeKey,
2637 shape: &Shape,
2638 minval: &NativeArray<T>,
2639 maxval: &NativeArray<T>,
2640 ) -> Option<NativeArray<T>> {
2641 if minval.data.len() != 1 || maxval.data.len() != 1 {
2642 return None;
2643 }
2644 let (lo, hi) = (minval.data[0], maxval.data[0]);
2645 let [k1, k2] = key.words();
2646 Some(uniform_native::<T>(k1, k2, shape, lo, hi))
2647 }
2648 #[inline]
2649 fn random_uniform_scalar<T: crate::value::Float>(key: &NativeKey, lo: T, hi: T) -> Option<T> {
2650 let [k1, k2] = key.words();
2651 Some(uniform_one(k1, k2, lo, hi))
2652 }
2653 #[inline]
2654 fn random_randint_scalar<T: crate::value::Int>(key: &NativeKey, lo: T, hi: T) -> Option<T> {
2655 Some(randint_one(key.words(), lo, hi))
2656 }
2657 fn random_randint<T: crate::value::Int>(
2658 key: &NativeKey,
2659 shape: &Shape,
2660 minval: &NativeArray<T>,
2661 maxval: &NativeArray<T>,
2662 ) -> Option<NativeArray<T>> {
2663 if minval.data.len() != 1 || maxval.data.len() != 1 {
2664 return None;
2665 }
2666 let (lo, hi) = (minval.data[0], maxval.data[0]);
2667 Some(randint_native::<T>(key.words(), shape, lo, hi))
2668 }
2669 fn point_update<T: Element>(
2670 x: &NativeArray<T>,
2671 index: &[i32],
2672 value: &NativeArray<T>,
2673 combine: Option<BinaryOp>,
2674 ) -> Option<NativeArray<T>> {
2675 if index.len() != x.shape.rank() || value.data.len() != 1 {
2676 return None;
2677 }
2678 let mut flat = 0usize;
2679 for (&i, &n) in index.iter().zip(x.shape.dims()) {
2680 let i = usize::try_from(i).ok().filter(|&i| i < n);
2682 let Some(i) = i else {
2683 return Some(x.clone());
2684 };
2685 flat = flat * n + i;
2686 }
2687 let v = value.data[0];
2688 let mut data = Data::from_slice(&x.data);
2689 let o = data.unique_mut();
2690 o[flat] = match combine {
2691 None => v,
2692 Some(op) => T::binary(op, o[flat], v),
2693 };
2694 Some(NativeArray {
2695 data,
2696 shape: x.shape.clone(),
2697 })
2698 }
2699 fn update_box<T: Element>(
2700 x: &mut NativeArray<T>,
2701 starts: &[usize],
2702 sizes: &[usize],
2703 values: &NativeArray<T>,
2704 combine: Option<BinaryOp>,
2705 ) -> bool {
2706 let rank = x.shape.rank();
2707 let count: usize = sizes.iter().product();
2708 if starts.len() != rank
2709 || sizes.len() != rank
2710 || (values.data.len() != count && values.data.len() != 1)
2711 {
2712 return false;
2713 }
2714 if count == 0 {
2715 return true;
2716 }
2717 if rank > 8 {
2718 return false;
2719 }
2720 let mut stride = [0usize; 8];
2723 let mut base = 0;
2724 let mut st = 1;
2725 for d in (0..rank).rev() {
2726 stride[d] = st;
2727 base += starts[d] * st;
2728 st *= x.shape[d];
2729 }
2730 let mut dims = [(0usize, 0usize); 8];
2734 let mut nd = 0;
2735 for d in 0..rank {
2736 if sizes[d] == 1 {
2737 continue;
2738 }
2739 if nd > 0 && dims[nd - 1].1 == sizes[d] * stride[d] {
2740 dims[nd - 1] = (dims[nd - 1].0 * sizes[d], stride[d]);
2741 } else {
2742 dims[nd] = (sizes[d], stride[d]);
2743 nd += 1;
2744 }
2745 }
2746 let run = if nd > 0 && dims[nd - 1].1 == 1 {
2749 nd -= 1;
2750 dims[nd].0
2751 } else {
2752 1
2753 };
2754 let (inner, inner_stride) = if nd > 0 {
2755 nd -= 1;
2756 dims[nd]
2757 } else {
2758 (1, 0)
2759 };
2760 let o = x.data.make_mut();
2761 let vals: &[T] = &values.data;
2762 let single = vals.len() == 1;
2763 let last = base + (inner - 1) * inner_stride + run;
2764 let outer_extent: usize = dims[..nd].iter().map(|&(n, s)| (n - 1) * s).sum();
2765 assert!(
2766 last + outer_extent <= o.len(),
2767 "the box is inside the array"
2768 );
2769 let mut pos = [0usize; 8];
2770 let mut src_at = 0;
2771 loop {
2772 let o = &mut o[base..base + (inner - 1) * inner_stride + run];
2773 match (run, combine) {
2774 (1, None) => {
2775 let p = o.as_mut_ptr();
2776 if single {
2777 let v = vals[0];
2778 for k in 0..inner {
2779 unsafe { *p.add(k * inner_stride) = v };
2782 }
2783 } else {
2784 for (k, &v) in vals[src_at..src_at + inner].iter().enumerate() {
2785 unsafe { *p.add(k * inner_stride) = v };
2787 }
2788 }
2789 }
2790 _ => {
2791 for k in 0..inner {
2792 let o = &mut o[k * inner_stride..k * inner_stride + run];
2793 let src = src_at + k * run;
2794 match combine {
2795 None if single => o.fill(vals[0]),
2796 None => o.copy_from_slice(&vals[src..src + run]),
2797 Some(op) => {
2798 for (j, e) in o.iter_mut().enumerate() {
2799 let v = if single { vals[0] } else { vals[src + j] };
2800 *e = T::binary(op, *e, v);
2801 }
2802 }
2803 }
2804 }
2805 }
2806 }
2807 src_at += inner * run;
2808 let mut d = nd;
2810 loop {
2811 if d == 0 {
2812 return true;
2813 }
2814 d -= 1;
2815 pos[d] += 1;
2816 base += dims[d].1;
2817 if pos[d] < dims[d].0 {
2818 break;
2819 }
2820 base -= dims[d].1 * dims[d].0;
2821 pos[d] = 0;
2822 }
2823 }
2824 }
2825 #[inline(always)]
2826 fn point_update_in_place<T: Element>(
2827 x: &mut NativeArray<T>,
2828 index: &[crate::indexing::Index<Native>],
2829 value: T,
2830 combine: Option<BinaryOp>,
2831 ) -> bool {
2832 use crate::indexing::Index;
2833 if index.len() != x.shape.rank() {
2834 return false;
2835 }
2836 let mut flat = 0usize;
2837 let mut in_bounds = true;
2838 for (component, &n) in index.iter().zip(x.shape.dims()) {
2839 let i = match *component {
2840 Index::Int(i) => i,
2841 Index::Dynamic(s) => i64::from(s.value()),
2842 _ => return false,
2843 };
2844 let i = if i < 0 { i + n as i64 } else { i };
2845 match usize::try_from(i).ok().filter(|&i| i < n) {
2847 Some(i) => flat = flat * n + i,
2848 None => in_bounds = false,
2849 }
2850 }
2851 if in_bounds {
2852 let o = x.data.make_mut();
2853 let e = unsafe { o.get_unchecked_mut(flat) };
2857 *e = match combine {
2858 None => value,
2859 Some(op) => T::binary(op, *e, value),
2860 };
2861 }
2862 true
2863 }
2864 #[inline]
2865 fn index_leading<T: Element>(x: &NativeArray<T>, index: &[usize]) -> Option<NativeArray<T>> {
2866 let dims = x.shape.dims();
2867 let (lead, rest) = dims.split_at(index.len());
2868 let mut flat = 0;
2869 for (&i, &n) in index.iter().zip(lead) {
2870 flat = flat * n + i;
2871 }
2872 let inner: usize = rest.iter().product();
2873 Some(NativeArray {
2874 data: Data::from_slice(&x.data[flat * inner..(flat + 1) * inner]),
2875 shape: Shape::from(rest),
2876 })
2877 }
2878 #[inline]
2879 fn key_split2(key: &NativeKey) -> Option<(NativeKey, NativeKey)> {
2880 let [k1, k2] = key.words();
2882 let (a, b) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
2883 Some((
2884 NativeKey::Single([a[0], b[0]]),
2885 NativeKey::Single([a[1], b[1]]),
2886 ))
2887 }
2888 #[inline]
2889 fn stack_scalars<T: Element>(
2890 n: usize,
2891 mut scalar: impl FnMut(usize) -> T,
2892 ) -> Option<NativeArray<T>> {
2893 Some(build(Shape::from([n]), |o| {
2894 for (i, o) in o.iter_mut().enumerate() {
2895 *o = scalar(i);
2896 }
2897 }))
2898 }
2899 #[inline]
2900 fn rank<T: Element>(x: &NativeArray<T>) -> usize {
2901 x.shape.rank()
2902 }
2903 #[inline]
2904 fn dims<T: Element>(x: &NativeArray<T>) -> Option<&[usize]> {
2905 Some(x.shape.dims())
2906 }
2907 fn slice_box<T: Element>(
2908 x: &NativeArray<T>,
2909 starts: &[usize],
2910 sizes: &[usize],
2911 out: Shape,
2912 ) -> Option<NativeArray<T>> {
2913 copy_box(x, starts, sizes, out)
2914 }
2915 fn sort_key_val_typed<K: Element, V: Element>(
2916 keys: &NativeArray<K>,
2917 values: &NativeArray<V>,
2918 dimension: usize,
2919 ) -> Option<(NativeArray<K>, NativeArray<V>)> {
2920 let dims = keys.shape.dims();
2921 if keys.shape != values.shape || dimension >= dims.len() {
2922 return None;
2923 }
2924 let n = dims[dimension];
2925 let inner: usize = dims[dimension + 1..].iter().product();
2926 let total = keys.data.len();
2927 let kd: &[K] = &keys.data;
2928 let mut perm = vec![0usize; total];
2930 let mut line: Vec<usize> = Vec::with_capacity(n);
2931 let outer = total.checked_div(n * inner).unwrap_or(0);
2932 for o in 0..outer {
2933 for i in 0..inner {
2934 let base = o * n * inner + i;
2935 line.clear();
2936 line.extend((0..n).map(|k| base + k * inner));
2937 line.sort_by(|&a, &b| ruxla_kernels::array::sort_order(kd[a], kd[b]));
2938 for (k, &src) in line.iter().enumerate() {
2939 perm[base + k * inner] = src;
2940 }
2941 }
2942 }
2943 let vd: &[V] = &values.data;
2944 let k = build_all(keys.shape.clone(), |out| {
2945 for (o, &p) in out.iter_mut().zip(&perm) {
2946 *o = kd[p];
2947 }
2948 });
2949 let v = build_all(values.shape.clone(), |out| {
2950 for (o, &p) in out.iter_mut().zip(&perm) {
2951 *o = vd[p];
2952 }
2953 });
2954 Some((k, v))
2955 }
2956 #[inline]
2957 fn full<T: Element>(shape: Shape, value: T) -> Option<NativeArray<T>> {
2958 Some(NativeArray {
2959 data: Data::filled(shape.size(), value),
2960 shape,
2961 })
2962 }
2963 #[inline]
2964 fn int_value(x: i32) -> Option<i64> {
2965 Some(i64::from(x))
2966 }
2967 #[inline]
2968 fn branch_value(pred: Bool<Native>) -> Option<bool> {
2969 Some(pred.value())
2970 }
2971 #[inline]
2972 fn element<T: Element>(x: &NativeArray<T>, flat: usize) -> Option<T> {
2973 Some(x.data[flat])
2974 }
2975 fn stack0<T: Element>(xs: &[NativeArray<T>]) -> Option<NativeArray<T>> {
2976 let first = xs.first()?;
2977 if xs.iter().any(|x| x.shape != first.shape) {
2978 return None;
2979 }
2980 let mut shape = first.shape.clone();
2981 shape.insert(0, xs.len());
2982 Some(build(shape, |o| {
2983 let n = first.data.len();
2984 for (chunk, x) in o.chunks_exact_mut(n.max(1)).zip(xs) {
2985 chunk.copy_from_slice(&x.data);
2986 }
2987 }))
2988 }
2989 fn key_split(key: &NativeKey, num: usize) -> NativeKey {
2990 let [k1, k2] = key.words();
2991 NativeKey::Array(Arc::new(build(Shape::from([num, 2]), |o| {
2992 hash_counters(k1, k2, num, |i, a, b| {
2993 o[2 * i] = a;
2994 o[2 * i + 1] = b;
2995 });
2996 })))
2997 }
2998 fn key_fold_in(key: &NativeKey, data: u32) -> NativeKey {
2999 let [k1, k2] = key.words();
3000 let (a, b) = threefry2x32_scalar(k1, k2, 0, data);
3001 NativeKey::Single([a, b])
3002 }
3003 fn key_bits(key: &NativeKey, shape: &[usize]) -> (NativeArray<u32>, NativeArray<u32>) {
3004 let [k1, k2] = key.words();
3005 let shape = Shape::from(shape);
3006 let n = shape.size();
3007 let mut a = build(shape.clone(), |_| {});
3008 let mut b = build(shape, |_| {});
3009 {
3010 let (oa, ob) = (a.data.unique_mut(), b.data.unique_mut());
3011 hash_counters(k1, k2, n, |i, x, y| {
3012 oa[i] = x;
3013 ob[i] = y;
3014 });
3015 }
3016 (a, b)
3017 }
3018 fn threefry2x32(
3019 k1: &NativeArray<u32>,
3020 k2: &NativeArray<u32>,
3021 x1: &NativeArray<u32>,
3022 x2: &NativeArray<u32>,
3023 ) -> (NativeArray<u32>, NativeArray<u32>) {
3024 let shape = [k1, k2, x1, x2]
3026 .iter()
3027 .map(|x| &x.shape)
3028 .find(|s| s.rank() > 0)
3029 .cloned()
3030 .unwrap_or_else(Shape::scalar);
3031 let at = |x: &NativeArray<u32>, i: usize| {
3032 if x.data.len() == 1 {
3033 x.data[0]
3034 } else {
3035 x.data[i]
3036 }
3037 };
3038 let (y1, y2): (Vec<u32>, Vec<u32>) = (0..shape.size())
3039 .map(|i| threefry2x32_scalar(at(k1, i), at(k2, i), at(x1, i), at(x2, i)))
3040 .unzip();
3041 (native(y1, shape.clone()), native(y2, shape))
3042 }
3043 fn fori_loop<C: Tree<Self>>(
3044 lo: I32<Native>,
3045 hi: I32<Native>,
3046 body: &dyn Fn(I32<Native>, C) -> C,
3047 init: C,
3048 ) -> C {
3049 let mut c = init;
3050 for i in lo.value()..hi.value() {
3051 c = body(Scalar::new(i), c);
3052 }
3053 c
3054 }
3055
3056 fn scalar_leaf<T: Element>(x: T) -> HostArray {
3057 HostArray::scalar(x)
3058 }
3059 #[track_caller]
3060 fn leaf_scalar<T: Element>(l: HostArray) -> T {
3061 assert_eq!(
3062 l.shape().rank(),
3063 0,
3064 "expected a scalar leaf, got {:?}",
3065 l.aval()
3066 );
3067 l.as_slice::<T>().unwrap_or_else(|e| panic!("{e}"))[0]
3068 }
3069 fn array_leaf<T: Element>(x: &NativeArray<T>) -> HostArray {
3070 x.to_host()
3071 }
3072 fn leaf_array<T: Element>(l: HostArray) -> NativeArray<T> {
3073 NativeArray::from_host(&l)
3074 }
3075 fn leaf_aval(l: &HostArray) -> AVal {
3076 l.aval()
3077 }
3078 #[track_caller]
3079 fn host_callback(
3080 callback: &ruxla_ir::callback::HostCallback,
3081 args: &[HostArray],
3082 outputs: &[AVal],
3083 ) -> Vec<HostArray> {
3084 let results = callback
3085 .call(args)
3086 .unwrap_or_else(|m| panic!("the host callback `{}` failed: {m}", callback.name()));
3087 let got: Vec<AVal> = results.iter().map(HostArray::aval).collect();
3088 assert_eq!(
3089 got,
3090 outputs,
3091 "the host callback `{}` returned other types than declared",
3092 callback.name()
3093 );
3094 results
3095 }
3096}
3097
3098impl<T: Element> NativeArray<T> {
3099 fn aval(&self) -> AVal {
3100 AVal::new(self.shape.clone(), T::DTYPE)
3101 }
3102}
3103
3104fn cumulative_prim(op: CumulativeOp) -> ruxla_ir::Prim {
3106 match op {
3107 CumulativeOp::Sum => p::CUMSUM,
3108 CumulativeOp::Prod => p::CUMPROD,
3109 CumulativeOp::Max => p::CUMMAX,
3110 CumulativeOp::Min => p::CUMMIN,
3111 CumulativeOp::LogSumExp => p::CUMLOGSUMEXP,
3112 }
3113}
3114
3115#[track_caller]
3119fn check_native_all(prim: ruxla_ir::Prim, inputs: &[AVal], params: &Params) -> Vec<Shape> {
3120 prim.abstract_eval(inputs, params)
3121 .unwrap_or_else(|e| panic!("{e}"))
3122 .into_iter()
3123 .map(|a| a.shape)
3124 .collect()
3125}
3126
3127fn slice_columns<E: Copy>(
3129 x: &[E],
3130 rows: usize,
3131 cols: usize,
3132 (start, end): (usize, usize),
3133) -> Vec<E> {
3134 (0..rows)
3135 .flat_map(|r| x[r * cols + start..r * cols + end].iter().copied())
3136 .collect()
3137}
3138
3139fn matrix_dims(shape: &Shape) -> (usize, usize, usize) {
3142 let d = shape.dims();
3143 let r = d.len();
3144 (d[..r - 2].iter().product(), d[r - 2], d[r - 1])
3145}
3146
3147fn triangular_solve_params(o: TriangularSolveOptions) -> Params {
3150 Params::TriangularSolve {
3151 left_side: o.left_side,
3152 lower: o.lower,
3153 transpose_a: o.transpose_a,
3154 conjugate_a: o.conjugate_a,
3155 unit_diagonal: o.unit_diagonal,
3156 }
3157}
3158
3159#[track_caller]
3160fn check_native(prim: ruxla_ir::Prim, inputs: &[AVal], params: &Params) -> Shape {
3161 prim.abstract_eval(inputs, params)
3162 .unwrap_or_else(|e| panic!("{e}"))
3163 .remove(0)
3164 .shape
3165}
3166
3167fn conv_params(
3168 window: &ConvWindow<'_>,
3169 dims: &ConvDims,
3170 groups: (usize, usize),
3171 precision: Precision,
3172 preferred_element_type: Option<ruxla_ir::DType>,
3173) -> Params {
3174 Params::ConvGeneralDilated {
3175 window_strides: window.strides.to_vec(),
3176 padding: window.padding.to_vec(),
3177 lhs_dilation: window.lhs_dilation.to_vec(),
3178 rhs_dilation: window.rhs_dilation.to_vec(),
3179 dimension_numbers: dims.clone(),
3180 feature_group_count: groups.0,
3181 batch_group_count: groups.1,
3182 precision,
3183 preferred_element_type,
3184 }
3185}
3186
3187fn reduce_window_prim(op: ReduceOp) -> ruxla_ir::Prim {
3188 match op {
3189 ReduceOp::Sum => p::REDUCE_WINDOW_SUM,
3190 ReduceOp::Max => p::REDUCE_WINDOW_MAX,
3191 ReduceOp::Min => p::REDUCE_WINDOW_MIN,
3192 }
3193}
3194
3195fn window_params(w: &Window<'_>) -> Params {
3196 Params::ReduceWindow {
3197 window_dimensions: w.dimensions.to_vec(),
3198 window_strides: w.strides.to_vec(),
3199 padding: w.padding.to_vec(),
3200 base_dilation: w.base_dilation.to_vec(),
3201 window_dilation: w.window_dilation.to_vec(),
3202 }
3203}
3204
3205#[track_caller]
3206fn select_and_scatter_add_params(select_prim: SelectPrim, w: &Window<'_>) -> Params {
3207 assert!(
3208 w.base_dilation
3209 .iter()
3210 .chain(w.window_dilation)
3211 .all(|&d| d == 1),
3212 "select_and_scatter_add has no dilation"
3213 );
3214 Params::SelectAndScatterAdd {
3215 select_prim,
3216 window_dimensions: w.dimensions.to_vec(),
3217 window_strides: w.strides.to_vec(),
3218 padding: w.padding.to_vec(),
3219 }
3220}
3221
3222fn select_and_gather_add_params(select_prim: SelectPrim, w: &Window<'_>) -> Params {
3223 Params::SelectAndGatherAdd {
3224 select_prim,
3225 window_dimensions: w.dimensions.to_vec(),
3226 window_strides: w.strides.to_vec(),
3227 padding: w.padding.to_vec(),
3228 base_dilation: w.base_dilation.to_vec(),
3229 window_dilation: w.window_dilation.to_vec(),
3230 }
3231}
3232
3233#[track_caller]
3234fn same_shape(op: &str, a: &Shape, b: &Shape) {
3235 assert!(
3236 a == b,
3237 "{op}: operands must have the same shape, got [{a}] and [{b}]"
3238 );
3239}
3240
3241fn scatter_prim(combine: Option<BinaryOp>) -> ruxla_ir::Prim {
3242 match combine {
3243 None => p::SCATTER,
3244 Some(BinaryOp::Add) => p::SCATTER_ADD,
3245 Some(BinaryOp::Mul) => p::SCATTER_MUL,
3246 Some(BinaryOp::Min) => p::SCATTER_MIN,
3247 Some(BinaryOp::Max) => p::SCATTER_MAX,
3248 Some(op) => panic!("no scatter combines with {}", op.name()),
3249 }
3250}
3251
3252fn index_leading(x: &HostArray, i: usize) -> HostArray {
3254 let inner: usize = x.shape().dims()[1..].iter().product();
3255 let b = ruxla_kernels::with_buffer!(x.buffer(), |v| ruxla_kernels::Buffer::from_vec(
3256 v[i * inner..(i + 1) * inner].to_vec()
3257 ));
3258 HostArray::from_buffer(b, x.shape().dims()[1..].to_vec())
3259}
3260
3261#[inline]
3264fn threefry2x32_scalar(k1: u32, k2: u32, x1: u32, x2: u32) -> (u32, u32) {
3265 const ROTATIONS: [[u32; 4]; 2] = [[13, 15, 26, 6], [17, 29, 16, 24]];
3266 let ks = [k1, k2, k1 ^ k2 ^ 0x1BD1_1BDA];
3267 let mut x = [x1.wrapping_add(ks[0]), x2.wrapping_add(ks[1])];
3268 for i in 0..5 {
3269 for &r in &ROTATIONS[i % 2] {
3270 x[0] = x[0].wrapping_add(x[1]);
3271 x[1] = x[1].rotate_left(r) ^ x[0];
3272 }
3273 x[0] = x[0].wrapping_add(ks[(i + 1) % 3]);
3274 x[1] = x[1]
3275 .wrapping_add(ks[(i + 2) % 3])
3276 .wrapping_add(i as u32 + 1);
3277 }
3278 (x[0], x[1])
3279}
3280
3281#[inline(always)]
3284fn threefry2x32_lanes<const N: usize>(
3285 k1: u32,
3286 k2: u32,
3287 x1: [u32; N],
3288 x2: [u32; N],
3289) -> ([u32; N], [u32; N]) {
3290 threefry2x32_lanes_keys([k1; N], [k2; N], x1, x2)
3291}
3292
3293#[inline(always)]
3297fn threefry2x32_lanes_keys<const N: usize>(
3298 k1: [u32; N],
3299 k2: [u32; N],
3300 x1: [u32; N],
3301 x2: [u32; N],
3302) -> ([u32; N], [u32; N]) {
3303 let k3: [u32; N] = std::array::from_fn(|j| k1[j] ^ k2[j] ^ 0x1BD1_1BDA);
3304 let ks = [k1, k2, k3];
3305 let mut a = x1;
3306 let mut b = x2;
3307 for j in 0..N {
3308 a[j] = a[j].wrapping_add(k1[j]);
3309 b[j] = b[j].wrapping_add(k2[j]);
3310 }
3311 macro_rules! round {
3312 ($r:expr) => {
3313 for j in 0..N {
3314 a[j] = a[j].wrapping_add(b[j]);
3315 b[j] = b[j].rotate_left($r) ^ a[j];
3316 }
3317 };
3318 }
3319 macro_rules! inject {
3320 ($i:expr) => {
3321 for j in 0..N {
3322 a[j] = a[j].wrapping_add(ks[($i + 1) % 3][j]);
3323 b[j] = b[j].wrapping_add(ks[($i + 2) % 3][j]).wrapping_add($i + 1);
3324 }
3325 };
3326 }
3327 macro_rules! even {
3328 ($i:expr) => {
3329 round!(13);
3330 round!(15);
3331 round!(26);
3332 round!(6);
3333 inject!($i);
3334 };
3335 }
3336 macro_rules! odd {
3337 ($i:expr) => {
3338 round!(17);
3339 round!(29);
3340 round!(16);
3341 round!(24);
3342 inject!($i);
3343 };
3344 }
3345 even!(0);
3346 odd!(1);
3347 even!(2);
3348 odd!(3);
3349 even!(4);
3350 (a, b)
3351}
3352
3353#[inline(always)]
3358fn hash_counters(k1: u32, k2: u32, n: usize, mut f: impl FnMut(usize, u32, u32)) {
3359 for i in 0..n {
3360 let (a, b) = threefry2x32_scalar(k1, k2, ((i as u64) >> 32) as u32, i as u32);
3361 f(i, a, b);
3362 }
3363}
3364
3365#[inline(always)]
3368fn bits_from_hash(b1: u32, b2: u32, nbits: usize) -> u64 {
3369 match nbits {
3370 64 => (u64::from(b1) << 32) | u64::from(b2),
3371 32 => u64::from(b1 ^ b2),
3372 16 => u64::from((b1 ^ b2) as u16),
3373 _ => u64::from((b1 ^ b2) as u8),
3374 }
3375}
3376
3377fn uniform_native<T: Element>(k1: u32, k2: u32, shape: &Shape, lo: T, hi: T) -> NativeArray<T> {
3380 let (nbits, nmant) = match T::DTYPE {
3381 ruxla_ir::DType::F16 => (16, 10),
3382 ruxla_ir::DType::BF16 => (16, 7),
3383 ruxla_ir::DType::F32 => (32, 23),
3384 _ => (64, 52),
3385 };
3386 let rng_bits = if nmant < 8 { 8 } else { nbits };
3387 let shift = (rng_bits - nmant) as u32;
3390 let one: T = cast::<u8, T>(1);
3391 let one_bits = one.to_bits();
3392 let span = T::binary(BinaryOp::Sub, hi, lo);
3393 build(shape.clone(), |o| {
3394 hash_counters(k1, k2, o.len(), |i, b1, b2| {
3395 let float_bits = (bits_from_hash(b1, b2, rng_bits) >> shift) | one_bits;
3396 let floats = T::binary(BinaryOp::Sub, T::from_bits(float_bits), one);
3397 let scaled = T::binary(BinaryOp::Add, T::binary(BinaryOp::Mul, floats, span), lo);
3398 o[i] = T::binary(BinaryOp::Max, lo, scaled);
3399 });
3400 })
3401}
3402
3403#[inline]
3406fn uniform_one<T: Element>(k1: u32, k2: u32, lo: T, hi: T) -> T {
3407 let (nbits, nmant) = match T::DTYPE {
3408 ruxla_ir::DType::F16 => (16, 10),
3409 ruxla_ir::DType::BF16 => (16, 7),
3410 ruxla_ir::DType::F32 => (32, 23),
3411 _ => (64, 52),
3412 };
3413 let rng_bits = if nmant < 8 { 8 } else { nbits };
3414 let one: T = cast::<u8, T>(1);
3415 let (b1, b2) = threefry2x32_scalar(k1, k2, 0, 0);
3416 let float_bits = (bits_from_hash(b1, b2, rng_bits) >> (rng_bits - nmant)) | one.to_bits();
3417 let floats = T::binary(BinaryOp::Sub, T::from_bits(float_bits), one);
3418 let span = T::binary(BinaryOp::Sub, hi, lo);
3419 let scaled = T::binary(BinaryOp::Add, T::binary(BinaryOp::Mul, floats, span), lo);
3420 T::binary(BinaryOp::Max, lo, scaled)
3421}
3422
3423#[inline]
3426fn randint_one<T: Element>(key: [u32; 2], lo: T, hi: T) -> T {
3427 let nbits = T::DTYPE.size_in_bytes() * 8;
3428 let mask = if nbits == 64 {
3429 u64::MAX
3430 } else {
3431 (1u64 << nbits) - 1
3432 };
3433 let [k1, k2] = key;
3434 let (s1, s2) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
3435 let (a, b) = threefry2x32_lanes_keys([s1[0], s1[1]], [s2[0], s2[1]], [0, 0], [0, 0]);
3436 let span = if hi <= lo {
3437 1
3438 } else {
3439 T::binary(BinaryOp::Sub, hi, lo).to_bits() & mask
3440 };
3441 let half = (1u64 << (nbits / 2)) & mask;
3442 let multiplier = half % span;
3443 let multiplier = (multiplier.wrapping_mul(multiplier) & mask) % span;
3444 let higher = bits_from_hash(a[0], b[0], nbits);
3445 let lower = bits_from_hash(a[1], b[1], nbits);
3446 let offset =
3447 ((higher % span).wrapping_mul(multiplier) & mask).wrapping_add(lower % span) & mask;
3448 T::binary(BinaryOp::Add, lo, T::from_bits(offset % span))
3449}
3450
3451fn randint_native<T: Element>(key: [u32; 2], shape: &Shape, lo: T, hi: T) -> NativeArray<T> {
3456 let nbits = T::DTYPE.size_in_bytes() * 8;
3457 let mask = if nbits == 64 {
3458 u64::MAX
3459 } else {
3460 (1u64 << nbits) - 1
3461 };
3462 let [k1, k2] = key;
3464 let (s1, s2) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
3465 let (h1, h2, l1, l2) = (s1[0], s2[0], s1[1], s2[1]);
3466 let span = if hi <= lo {
3467 1
3468 } else {
3469 T::binary(BinaryOp::Sub, hi, lo).to_bits() & mask
3470 };
3471 let half = (1u64 << (nbits / 2)) & mask;
3472 let multiplier = half % span;
3473 let multiplier = (multiplier.wrapping_mul(multiplier) & mask) % span;
3474 build(shape.clone(), |o| {
3475 for (i, o) in o.iter_mut().enumerate() {
3476 let c = [(i as u64 >> 32) as u32; 2];
3478 let (a, b) = threefry2x32_lanes_keys([h1, l1], [h2, l2], c, [i as u32; 2]);
3479 let higher = bits_from_hash(a[0], b[0], nbits);
3480 let lower = bits_from_hash(a[1], b[1], nbits);
3481 let offset =
3482 ((higher % span).wrapping_mul(multiplier) & mask).wrapping_add(lower % span) & mask;
3483 *o = T::binary(BinaryOp::Add, lo, T::from_bits(offset % span));
3484 }
3485 })
3486}
3487
3488fn stack_trees<Y: Tree<Native>>(ys: &[Y], length: usize) -> Y {
3490 let first = &ys[0];
3491 let per: Vec<Vec<HostArray>> = ys
3492 .iter()
3493 .map(|y| {
3494 let mut l = Vec::new();
3495 y.flatten(&mut l);
3496 l
3497 })
3498 .collect();
3499 let stacked: Vec<HostArray> = (0..per[0].len())
3500 .map(|j| {
3501 let parts: Vec<&HostArray> = per.iter().map(|l| &l[j]).collect();
3502 let mut shape = vec![length];
3503 shape.extend_from_slice(parts[0].shape());
3504 let b = ruxla_kernels::with_buffer!(parts[0].buffer(), |v0| {
3505 let mut all = v0.clone();
3506 for p in &parts[1..] {
3507 all.extend_from_slice(p.as_slice().expect("same types"));
3508 }
3509 ruxla_kernels::Buffer::from_vec(all)
3510 });
3511 HostArray::from_buffer(b, shape)
3512 })
3513 .collect();
3514 first.unflatten_like(&mut stacked.into_iter())
3515}
3516
3517fn bind1(prim: ruxla_ir::Prim, inputs: &[TraceRef], params: Params) -> TraceRef {
3518 trace::bind(prim, inputs, params).remove(0)
3519}
3520
3521impl Backend for Trace {
3522 type Scalar<T: Element> = TraceRef;
3523 type Array<T: Element> = TraceRef;
3524 type Leaf = TraceRef;
3525 type KeyData = TraceRef;
3526
3527 fn lit<T: Element>(v: T) -> TraceRef {
3528 trace::literal(HostArray::scalar(v))
3529 }
3530 fn unary<T: Element>(op: UnaryOp, x: TraceRef) -> TraceRef {
3531 if op == UnaryOp::Abs && T::DTYPE.kind() == DTypeKind::UnsignedInt {
3533 return x;
3534 }
3535 let (prim, params) = p::unary_prim(op);
3536 bind1(prim, &[x], params)
3537 }
3538 fn binary<T: Element>(op: BinaryOp, x: TraceRef, y: TraceRef) -> TraceRef {
3539 bind1(p::binary_prim(op), &[x, y], Params::None)
3540 }
3541 fn compare<T: Element>(op: CompareOp, x: TraceRef, y: TraceRef) -> TraceRef {
3542 bind1(p::compare_prim(op), &[x, y], Params::None)
3543 }
3544 fn is_finite<T: Element>(x: TraceRef) -> TraceRef {
3545 bind1(p::IS_FINITE, &[x], Params::None)
3546 }
3547 fn integer_pow<T: Element>(x: TraceRef, y: i32) -> TraceRef {
3548 bind1(p::INTEGER_POW, &[x], Params::IntegerPow { y })
3549 }
3550 fn select<T: Element>(c: TraceRef, t: TraceRef, f: TraceRef) -> TraceRef {
3551 bind1(p::SELECT_N, &[c, f, t], Params::None)
3552 }
3553 fn cast<T: Element, U: Element>(x: TraceRef) -> TraceRef {
3554 if T::DTYPE == U::DTYPE {
3555 return x;
3556 }
3557 if let Some(v) = trace::literal_value(x) {
3559 return trace::literal(v.convert(U::DTYPE));
3560 }
3561 bind1(
3562 p::CONVERT_ELEMENT_TYPE,
3563 &[x],
3564 Params::Convert {
3565 new_dtype: U::DTYPE,
3566 },
3567 )
3568 }
3569 fn bitcast<T: Element, U: Element>(x: TraceRef) -> TraceRef {
3570 bind1(
3571 p::BITCAST_CONVERT_TYPE,
3572 &[x],
3573 Params::Convert {
3574 new_dtype: U::DTYPE,
3575 },
3576 )
3577 }
3578
3579 fn to_real<T: Element>(op: ToReal, x: TraceRef) -> TraceRef {
3580 match op {
3581 ToReal::Abs => Self::unary::<T>(UnaryOp::Abs, x),
3582 ToReal::Real => bind1(p::REAL, &[x], Params::None),
3583 ToReal::Imag => bind1(p::IMAG, &[x], Params::None),
3584 }
3585 }
3586 fn complex<C: Element>(re: TraceRef, im: TraceRef) -> TraceRef {
3587 bind1(p::COMPLEX, &[re, im], Params::None)
3588 }
3589 fn conj<T: Element>(x: TraceRef) -> TraceRef {
3590 bind1(p::CONJ, &[x], Params::None)
3591 }
3592
3593 fn constant<T: Element>(x: &NativeArray<T>) -> TraceRef {
3594 trace::constant(x.to_host())
3595 }
3596 fn shape<T: Element>(x: &TraceRef) -> Shape {
3597 trace::aval(*x).shape
3598 }
3599 fn to_array<T: Element>(x: TraceRef) -> TraceRef {
3600 x
3601 }
3602 #[track_caller]
3603 fn to_scalar<T: Element>(x: &TraceRef) -> TraceRef {
3604 let a = trace::aval(*x);
3605 assert_eq!(a.shape.rank(), 0, "expected a scalar, got {a}");
3606 *x
3607 }
3608 fn a_unary<T: Element>(op: UnaryOp, x: &TraceRef) -> TraceRef {
3609 Self::unary::<T>(op, *x)
3610 }
3611 fn a_binary<T: Element>(op: BinaryOp, x: &TraceRef, y: &TraceRef) -> TraceRef {
3612 Self::binary::<T>(op, *x, *y)
3613 }
3614 fn a_ternary<T: Element>(op: TernaryOp, x: &TraceRef, y: &TraceRef, z: &TraceRef) -> TraceRef {
3615 bind1(p::ternary_prim(op), &[*x, *y, *z], Params::None)
3616 }
3617 fn a_compare<T: Element>(op: CompareOp, x: &TraceRef, y: &TraceRef) -> TraceRef {
3618 Self::compare::<T>(op, *x, *y)
3619 }
3620 fn a_is_finite<T: Element>(x: &TraceRef) -> TraceRef {
3621 Self::is_finite::<T>(*x)
3622 }
3623 fn a_integer_pow<T: Element>(x: &TraceRef, y: i32) -> TraceRef {
3624 Self::integer_pow::<T>(*x, y)
3625 }
3626 fn a_cast<T: Element, U: Element>(x: &TraceRef) -> TraceRef {
3627 Self::cast::<T, U>(*x)
3628 }
3629 fn a_bitcast<T: Element, U: Element>(x: &TraceRef) -> TraceRef {
3630 Self::bitcast::<T, U>(*x)
3631 }
3632 fn a_to_real<T: Element>(op: ToReal, x: &TraceRef) -> TraceRef {
3633 Self::to_real::<T>(op, *x)
3634 }
3635 fn a_complex<C: Element>(re: &TraceRef, im: &TraceRef) -> TraceRef {
3636 Self::complex::<C>(*re, *im)
3637 }
3638 fn a_conj<T: Element>(x: &TraceRef) -> TraceRef {
3639 Self::conj::<T>(*x)
3640 }
3641 fn a_select<T: Element>(c: &TraceRef, t: &TraceRef, f: &TraceRef) -> TraceRef {
3642 bind1(p::SELECT_N, &[*c, *f, *t], Params::None)
3643 }
3644 fn a_clamp<T: Element>(lo: &TraceRef, x: &TraceRef, hi: &TraceRef) -> TraceRef {
3645 bind1(p::CLAMP, &[*lo, *x, *hi], Params::None)
3646 }
3647 fn broadcast_in_dim<T: Element>(x: &TraceRef, shape: &[usize], dims: &[usize]) -> TraceRef {
3648 bind1(
3649 p::BROADCAST_IN_DIM,
3650 &[*x],
3651 Params::BroadcastInDim {
3652 shape: shape.into(),
3653 broadcast_dimensions: dims.to_vec(),
3654 },
3655 )
3656 }
3657 fn reshape<T: Element>(x: &TraceRef, shape: &[usize]) -> TraceRef {
3658 bind1(
3659 p::RESHAPE,
3660 &[*x],
3661 Params::Reshape {
3662 new_sizes: shape.into(),
3663 },
3664 )
3665 }
3666 fn transpose<T: Element>(x: &TraceRef, perm: &[usize]) -> TraceRef {
3667 bind1(
3668 p::TRANSPOSE,
3669 &[*x],
3670 Params::Transpose {
3671 permutation: perm.to_vec(),
3672 },
3673 )
3674 }
3675 fn slice<T: Element>(
3676 x: &TraceRef,
3677 start: &[usize],
3678 limit: &[usize],
3679 strides: &[usize],
3680 ) -> TraceRef {
3681 bind1(
3682 p::SLICE,
3683 &[*x],
3684 Params::Slice {
3685 start_indices: start.to_vec(),
3686 limit_indices: limit.to_vec(),
3687 strides: strides.to_vec(),
3688 },
3689 )
3690 }
3691 fn dynamic_slice<T: Element, I: Element>(
3692 x: &TraceRef,
3693 starts: &[TraceRef],
3694 sizes: &[usize],
3695 ) -> TraceRef {
3696 let mut inputs = vec![*x];
3697 inputs.extend_from_slice(starts);
3698 bind1(
3699 p::DYNAMIC_SLICE,
3700 &inputs,
3701 Params::DynamicSlice {
3702 slice_sizes: sizes.to_vec(),
3703 },
3704 )
3705 }
3706 fn dynamic_update_slice<T: Element, I: Element>(
3707 x: &TraceRef,
3708 update: &TraceRef,
3709 starts: &[TraceRef],
3710 ) -> TraceRef {
3711 let mut inputs = vec![*x, *update];
3712 inputs.extend_from_slice(starts);
3713 bind1(p::DYNAMIC_UPDATE_SLICE, &inputs, Params::None)
3714 }
3715 fn concatenate<T: Element>(xs: &[TraceRef], dim: usize) -> TraceRef {
3716 bind1(p::CONCATENATE, xs, Params::Concatenate { dimension: dim })
3717 }
3718 fn pad<T: Element>(x: &TraceRef, value: TraceRef, config: &[(i64, i64, usize)]) -> TraceRef {
3719 bind1(
3720 p::PAD,
3721 &[*x, value],
3722 Params::Pad {
3723 padding_config: config.to_vec(),
3724 },
3725 )
3726 }
3727 fn rev<T: Element>(x: &TraceRef, dims: &[usize]) -> TraceRef {
3728 bind1(
3729 p::REV,
3730 &[*x],
3731 Params::Rev {
3732 dimensions: dims.to_vec(),
3733 },
3734 )
3735 }
3736 fn iota<T: Element>(shape: &[usize], dim: usize) -> TraceRef {
3737 bind1(
3738 p::IOTA,
3739 &[],
3740 Params::Iota {
3741 dtype: T::DTYPE,
3742 shape: shape.into(),
3743 dimension: dim,
3744 },
3745 )
3746 }
3747 fn reduce<T: Element>(op: ReduceOp, x: &TraceRef, axes: &[usize]) -> TraceRef {
3748 let prim = match op {
3749 ReduceOp::Sum => p::REDUCE_SUM,
3750 ReduceOp::Max => p::REDUCE_MAX,
3751 ReduceOp::Min => p::REDUCE_MIN,
3752 };
3753 bind1(
3754 prim,
3755 &[*x],
3756 Params::Reduce {
3757 axes: axes.to_vec(),
3758 },
3759 )
3760 }
3761 fn arg_min_max<T: Element, I: Element>(x: &TraceRef, axis: usize, max: bool) -> TraceRef {
3762 let prim = if max { p::ARGMAX } else { p::ARGMIN };
3763 bind1(
3764 prim,
3765 &[*x],
3766 Params::ArgMinMax {
3767 axis,
3768 index_dtype: I::DTYPE,
3769 },
3770 )
3771 }
3772 fn sort(
3773 operands: &[TraceRef],
3774 dimension: usize,
3775 is_stable: bool,
3776 num_keys: usize,
3777 ) -> Vec<TraceRef> {
3778 trace::bind(
3779 p::SORT,
3780 operands,
3781 Params::Sort {
3782 dimension,
3783 is_stable,
3784 num_keys,
3785 },
3786 )
3787 }
3788 fn cumulative<T: Element>(
3789 op: CumulativeOp,
3790 x: &TraceRef,
3791 axis: usize,
3792 reverse: bool,
3793 ) -> TraceRef {
3794 bind1(
3795 cumulative_prim(op),
3796 &[*x],
3797 Params::Cumulative { axis, reverse },
3798 )
3799 }
3800 fn fft<T: Element, U: Element>(
3801 x: &TraceRef,
3802 fft_type: FftType,
3803 fft_lengths: &[usize],
3804 ) -> TraceRef {
3805 bind1(
3806 p::FFT,
3807 &[*x],
3808 Params::Fft {
3809 fft_type,
3810 fft_lengths: fft_lengths.to_vec(),
3811 },
3812 )
3813 }
3814 fn top_k<T: Element>(x: &TraceRef, k: usize, axis: usize) -> (TraceRef, TraceRef) {
3815 let out = trace::bind(
3816 p::TOP_K,
3817 &[*x],
3818 Params::TopK {
3819 k,
3820 axis,
3821 is_stable: true,
3822 },
3823 );
3824 (out[0], out[1])
3825 }
3826 fn cholesky<T: LinalgScalar>(x: &TraceRef) -> TraceRef {
3827 bind1(p::CHOLESKY, &[*x], Params::None)
3828 }
3829 fn triangular_solve<T: LinalgScalar>(
3830 a: &TraceRef,
3831 b: &TraceRef,
3832 options: TriangularSolveOptions,
3833 ) -> TraceRef {
3834 bind1(
3835 p::TRIANGULAR_SOLVE,
3836 &[*a, *b],
3837 triangular_solve_params(options),
3838 )
3839 }
3840 fn lu<T: LinalgScalar>(x: &TraceRef) -> (TraceRef, TraceRef, TraceRef) {
3841 let out = trace::bind(p::LU, &[*x], Params::None);
3842 (out[0], out[1], out[2])
3843 }
3844 fn lu_pivots_to_permutation(pivots: &TraceRef, size: usize) -> TraceRef {
3845 bind1(
3846 p::LU_PIVOTS_TO_PERMUTATION,
3847 &[*pivots],
3848 Params::LuPivotsToPermutation {
3849 permutation_size: size,
3850 },
3851 )
3852 }
3853 fn qr<T: LinalgScalar>(x: &TraceRef, full_matrices: bool) -> (TraceRef, TraceRef) {
3854 let out = trace::bind(
3855 p::QR,
3856 &[*x],
3857 Params::Qr {
3858 full_matrices,
3859 pivoting: false,
3860 },
3861 );
3862 (out[0], out[1])
3863 }
3864 fn qr_pivoting<T: LinalgScalar>(
3865 x: &TraceRef,
3866 full_matrices: bool,
3867 ) -> (TraceRef, TraceRef, TraceRef) {
3868 let out = trace::bind(
3869 p::QR,
3870 &[*x],
3871 Params::Qr {
3872 full_matrices,
3873 pivoting: true,
3874 },
3875 );
3876 (out[0], out[1], out[2])
3877 }
3878 fn eigh<T: LinalgScalar>(
3879 x: &TraceRef,
3880 lower: bool,
3881 sort_eigenvalues: bool,
3882 subset_by_index: Option<(usize, usize)>,
3883 algorithm: Option<EighImplementation>,
3884 ) -> (TraceRef, TraceRef) {
3885 let out = trace::bind(
3886 p::EIGH,
3887 &[*x],
3888 Params::Eigh {
3889 lower,
3890 sort_eigenvalues,
3891 subset_by_index,
3892 algorithm,
3893 },
3894 );
3895 (out[0], out[1])
3896 }
3897 fn schur<T: LinalgScalar>(
3898 x: &TraceRef,
3899 compute_schur_vectors: bool,
3900 ) -> (TraceRef, Option<TraceRef>) {
3901 let out = trace::bind(
3902 p::SCHUR,
3903 &[*x],
3904 Params::Schur {
3905 compute_schur_vectors,
3906 },
3907 );
3908 (out[0], compute_schur_vectors.then(|| out[1]))
3909 }
3910 fn hessenberg<T: LinalgScalar>(x: &TraceRef) -> (TraceRef, TraceRef) {
3911 let out = trace::bind(p::HESSENBERG, &[*x], Params::None);
3912 (out[0], out[1])
3913 }
3914 fn householder_product<T: LinalgScalar>(a: &TraceRef, taus: &TraceRef) -> TraceRef {
3915 bind1(p::HOUSEHOLDER_PRODUCT, &[*a, *taus], Params::None)
3916 }
3917 fn ormqr<T: LinalgScalar>(
3918 a: &TraceRef,
3919 taus: &TraceRef,
3920 c: &TraceRef,
3921 left: bool,
3922 transpose: bool,
3923 ) -> TraceRef {
3924 bind1(
3925 p::ORMQR,
3926 &[*a, *taus, *c],
3927 Params::Ormqr { left, transpose },
3928 )
3929 }
3930 fn cholesky_update<T: LinalgFloat>(r: &TraceRef, w: &TraceRef) -> TraceRef {
3931 bind1(p::CHOLESKY_UPDATE, &[*r, *w], Params::None)
3932 }
3933 fn symmetric_product<T: LinalgFloat>(
3934 a: &TraceRef,
3935 c: &TraceRef,
3936 alpha: f64,
3937 beta: f64,
3938 ) -> TraceRef {
3939 bind1(
3940 p::SYMMETRIC_PRODUCT,
3941 &[*a, *c],
3942 Params::SymmetricProduct { alpha, beta },
3943 )
3944 }
3945 fn tridiagonal<T: LinalgScalar>(
3946 x: &TraceRef,
3947 lower: bool,
3948 ) -> (TraceRef, TraceRef, TraceRef, TraceRef) {
3949 let out = trace::bind(p::TRIDIAGONAL, &[*x], Params::Tridiagonal { lower });
3950 (out[0], out[1], out[2], out[3])
3951 }
3952 fn tridiagonal_solve<T: LinalgScalar>(
3953 dl: &TraceRef,
3954 d: &TraceRef,
3955 du: &TraceRef,
3956 b: &TraceRef,
3957 perturb_singular: bool,
3958 ) -> TraceRef {
3959 bind1(
3960 p::TRIDIAGONAL_SOLVE,
3961 &[*dl, *d, *du, *b],
3962 Params::TridiagonalSolve { perturb_singular },
3963 )
3964 }
3965 fn eig<T: LinalgScalar>(
3966 x: &TraceRef,
3967 left: bool,
3968 right: bool,
3969 enable_eigvec_derivs: bool,
3970 ) -> (TraceRef, Option<TraceRef>, Option<TraceRef>) {
3971 let out = trace::bind(
3972 p::EIG,
3973 &[*x],
3974 Params::Eig {
3975 compute_left_eigenvectors: left,
3976 compute_right_eigenvectors: right,
3977 enable_eigvec_derivs,
3978 },
3979 );
3980 let vl = left.then(|| out[1]);
3981 let vr = right.then(|| out[out.len() - 1]);
3982 (out[0], vl, vr)
3983 }
3984 fn svd<T: LinalgScalar>(
3985 x: &TraceRef,
3986 full_matrices: bool,
3987 compute_uv: bool,
3988 subset_by_index: Option<(usize, usize)>,
3989 algorithm: Option<SvdAlgorithm>,
3990 ) -> (TraceRef, Option<(TraceRef, TraceRef)>) {
3991 let out = trace::bind(
3992 p::SVD,
3993 &[*x],
3994 Params::Svd {
3995 full_matrices,
3996 compute_uv,
3997 subset_by_index,
3998 algorithm,
3999 },
4000 );
4001 (out[0], compute_uv.then(|| (out[1], out[2])))
4002 }
4003 fn dot_general<T: Element, U: Element>(
4004 l: &TraceRef,
4005 r: &TraceRef,
4006 dims: &DotDims,
4007 precision: Precision,
4008 ) -> TraceRef {
4009 let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
4010 bind1(
4011 p::DOT_GENERAL,
4012 &[*l, *r],
4013 Params::DotGeneral {
4014 dimension_numbers: dims.clone(),
4015 precision,
4016 preferred_element_type: preferred,
4017 },
4018 )
4019 }
4020 fn conv_general_dilated<T: Element, U: Element>(
4021 lhs: &TraceRef,
4022 rhs: &TraceRef,
4023 window: &ConvWindow<'_>,
4024 dims: &ConvDims,
4025 groups: (usize, usize),
4026 precision: Precision,
4027 ) -> TraceRef {
4028 let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
4029 bind1(
4030 p::CONV_GENERAL_DILATED,
4031 &[*lhs, *rhs],
4032 conv_params(window, dims, groups, precision, preferred),
4033 )
4034 }
4035 fn reduce_window<T: Element>(op: ReduceOp, x: &TraceRef, window: &Window<'_>) -> TraceRef {
4036 bind1(reduce_window_prim(op), &[*x], window_params(window))
4037 }
4038 fn select_and_scatter_add<T: Element>(
4039 source: &TraceRef,
4040 operand: &TraceRef,
4041 select_prim: SelectPrim,
4042 window: &Window<'_>,
4043 ) -> TraceRef {
4044 bind1(
4045 p::SELECT_AND_SCATTER_ADD,
4046 &[*source, *operand],
4047 select_and_scatter_add_params(select_prim, window),
4048 )
4049 }
4050 fn select_and_gather_add<T: Element>(
4051 tangents: &TraceRef,
4052 operand: &TraceRef,
4053 select_prim: SelectPrim,
4054 window: &Window<'_>,
4055 ) -> TraceRef {
4056 bind1(
4057 p::SELECT_AND_GATHER_ADD,
4058 &[*tangents, *operand],
4059 select_and_gather_add_params(select_prim, window),
4060 )
4061 }
4062 fn gather<T: Element, I: Element>(
4063 x: &TraceRef,
4064 indices: &TraceRef,
4065 dims: &GatherDims,
4066 sizes: &[usize],
4067 mode: GatherScatterMode,
4068 sorted_unique: bool,
4069 ) -> TraceRef {
4070 let params = Params::Gather {
4071 dimension_numbers: dims.clone(),
4072 slice_sizes: sizes.to_vec(),
4073 mode,
4074 indices_are_sorted: sorted_unique,
4075 unique_indices: sorted_unique,
4076 };
4077 bind1(p::GATHER, &[*x, *indices], params)
4078 }
4079 fn scatter<T: Element, I: Element>(
4080 combine: Option<BinaryOp>,
4081 x: &TraceRef,
4082 indices: &TraceRef,
4083 updates: &TraceRef,
4084 dims: &ScatterDims,
4085 mode: GatherScatterMode,
4086 sorted_unique: bool,
4087 ) -> TraceRef {
4088 let params = Params::Scatter {
4089 dimension_numbers: dims.clone(),
4090 mode,
4091 indices_are_sorted: sorted_unique,
4092 unique_indices: sorted_unique,
4093 };
4094 bind1(scatter_prim(combine), &[*x, *indices, *updates], params)
4095 }
4096
4097 fn cond<S: Tree<Self>, R: Tree<Self>>(
4098 index: I32<Trace>,
4099 branches: &[&dyn Fn(S) -> R],
4100 operand: S,
4101 ) -> R {
4102 crate::control::trace_cond(index, branches, operand)
4103 }
4104 fn while_loop<C: Tree<Self>>(
4105 cond: &dyn Fn(&C) -> Bool<Trace>,
4106 body: &dyn Fn(C) -> C,
4107 init: C,
4108 ) -> C {
4109 crate::control::trace_while(cond, body, init)
4110 }
4111 fn custom_jvp<I: Tree<Self>, O: Tree<Self>>(
4112 f: &dyn Fn(I) -> O,
4113 jvp: &dyn Fn(I, I) -> (O, O),
4114 primals: I,
4115 ) -> O {
4116 crate::control::trace_custom_jvp(f, jvp, primals)
4117 }
4118 fn custom_vjp<I: Tree<Self>, O: Tree<Self>, R: Tree<Self>>(
4119 f: &dyn Fn(I) -> O,
4120 fwd: &dyn Fn(I) -> (O, R),
4121 bwd: &dyn Fn(R, O) -> I,
4122 primals: I,
4123 ) -> O {
4124 crate::control::trace_custom_vjp(f, fwd, bwd, primals)
4125 }
4126 fn checkpoint<I: Tree<Self>, O: Tree<Self>>(f: &dyn Fn(I) -> O, input: I) -> O {
4127 crate::control::trace_checkpoint(f, input)
4128 }
4129 fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
4130 f: &dyn Fn(C, X) -> (C, Y),
4131 init: C,
4132 xs: X,
4133 length: usize,
4134 reverse: bool,
4135 ) -> (C, Y) {
4136 crate::control::trace_scan(f, init, xs, length, reverse)
4137 }
4138 fn fori_loop<C: Tree<Self>>(
4139 lo: I32<Trace>,
4140 hi: I32<Trace>,
4141 body: &dyn Fn(I32<Trace>, C) -> C,
4142 init: C,
4143 ) -> C {
4144 crate::control::trace_fori_loop(lo, hi, body, init)
4145 }
4146 fn key_from_array(data: TraceRef) -> TraceRef {
4147 data
4148 }
4149 fn key_to_array(key: &TraceRef) -> TraceRef {
4150 *key
4151 }
4152 fn threefry2x32(
4153 k1: &TraceRef,
4154 k2: &TraceRef,
4155 x1: &TraceRef,
4156 x2: &TraceRef,
4157 ) -> (TraceRef, TraceRef) {
4158 let outs = trace::bind(p::THREEFRY2X32, &[*k1, *k2, *x1, *x2], Params::None);
4159 (outs[0], outs[1])
4160 }
4161
4162 fn scalar_leaf<T: Element>(x: TraceRef) -> TraceRef {
4163 x
4164 }
4165 fn leaf_scalar<T: Element>(l: TraceRef) -> TraceRef {
4166 l
4167 }
4168 fn array_leaf<T: Element>(x: &TraceRef) -> TraceRef {
4169 *x
4170 }
4171 fn leaf_array<T: Element>(l: TraceRef) -> TraceRef {
4172 l
4173 }
4174 fn leaf_aval(l: &TraceRef) -> AVal {
4175 trace::aval(*l)
4176 }
4177 fn host_callback(
4178 callback: &ruxla_ir::callback::HostCallback,
4179 args: &[TraceRef],
4180 outputs: &[AVal],
4181 ) -> Vec<TraceRef> {
4182 trace::bind(
4183 p::HOST_CALLBACK,
4184 args,
4185 Params::HostCallback {
4186 callback: callback.clone(),
4187 outputs: outputs.to_vec(),
4188 },
4189 )
4190 }
4191}