use std::fmt;
use std::sync::Arc;
use ruxla_ir::{
AVal, ConvDims, DotDims, EighImplementation, FftType, GatherDims, GatherScatterMode, HostArray,
Params, Precision, ScatterDims, SelectPrim, Shape, SvdAlgorithm,
};
use ruxla_kernels::array::{self as k, CumulativeOp, ReduceOp};
use ruxla_kernels::elementwise as ew;
use ruxla_kernels::linalg::{self as kl, TriangularSolveOptions};
use ruxla_kernels::window::{self as kw, ConvWindow, Window};
use ruxla_kernels::{BinaryOp, CompareOp, DTypeKind, Element, TernaryOp, UnaryOp, cast};
use ruxla_prims as p;
use crate::shared::Shared;
use crate::trace::{self, TraceRef};
use crate::tree::Tree;
use crate::value::{Bool, I32, LinalgFloat, LinalgScalar, Scalar};
mod sealed {
pub trait Sealed {}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ToReal {
Abs,
Real,
Imag,
}
const SMALL: usize = 8;
#[derive(Clone)]
enum Data<T: Element> {
Small {
len: u8,
buf: [T; SMALL],
},
Slice(Shared<T>),
Vec(Arc<Vec<T>>),
}
impl<T: Element> Data<T> {
#[inline]
fn from_vec(v: Vec<T>) -> Self {
if v.len() <= SMALL {
let mut buf = [T::default(); SMALL];
buf[..v.len()].copy_from_slice(&v);
Data::Small {
len: v.len() as u8,
buf,
}
} else {
Data::Vec(Arc::new(v))
}
}
#[inline]
fn from_slice(v: &[T]) -> Self {
if v.len() <= SMALL {
Self::build(v.len(), |out| out.copy_from_slice(v))
} else {
Data::Slice(Shared::from_slice(v))
}
}
#[inline]
fn filled(len: usize, v: T) -> Self {
if len <= SMALL {
Self::build(len, |out| out.fill(v))
} else {
Data::Slice(Shared::filled(len, v))
}
}
#[inline]
fn make_mut(&mut self) -> &mut [T] {
let shared = match self {
Data::Small { .. } => false,
Data::Slice(a) => a.get_mut().is_none(),
Data::Vec(a) => Arc::get_mut(a).is_none(),
};
if shared {
*self = Data::from_slice(self);
}
self.unique_mut()
}
#[inline]
fn is_unique(&mut self) -> bool {
match self {
Data::Small { .. } => true,
Data::Slice(a) => a.get_mut().is_some(),
Data::Vec(a) => Arc::get_mut(a).is_some(),
}
}
#[inline]
fn unique_mut(&mut self) -> &mut [T] {
match self {
Data::Small { len, buf } => &mut buf[..usize::from(*len)],
Data::Slice(a) => a.get_mut().expect("a new buffer is not shared"),
Data::Vec(a) => Arc::get_mut(a).expect("a new buffer is not shared"),
}
}
#[inline(always)]
fn build(len: usize, f: impl FnOnce(&mut [T])) -> Self {
if len <= SMALL {
let mut buf = [T::default(); SMALL];
f(&mut buf[..len]);
Data::Small {
len: len as u8,
buf,
}
} else {
Self::build_shared(len, f)
}
}
#[inline(never)]
fn build_shared(len: usize, f: impl FnOnce(&mut [T])) -> Self {
Data::Slice(Shared::new(len, f))
}
#[inline]
fn build_overwrite(len: usize, f: impl FnOnce(&mut [T])) -> Self {
if len <= SMALL {
Self::build(len, f)
} else {
Self::build_overwrite_shared(len, f)
}
}
#[inline(never)]
fn build_overwrite_shared(len: usize, f: impl FnOnce(&mut [T])) -> Self {
Data::Slice(Shared::new_overwrite(len, f))
}
}
impl<T: Element> std::ops::Deref for Data<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
match self {
Data::Small { len, buf } => &buf[..usize::from(*len)],
Data::Slice(v) => v,
Data::Vec(v) => v,
}
}
}
impl<T: Element> PartialEq for Data<T> {
fn eq(&self, other: &Self) -> bool {
self[..] == other[..]
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub enum NativeKey {
Single([u32; 2]),
Array(Arc<NativeArray<u32>>),
}
impl NativeKey {
#[inline]
fn words(&self) -> [u32; 2] {
match self {
NativeKey::Single(w) => *w,
NativeKey::Array(a) => [a.data[0], a.data[1]],
}
}
}
#[derive(Clone, PartialEq)]
pub struct NativeArray<T: Element> {
data: Data<T>,
shape: Shape,
}
impl<T: Element> NativeArray<T> {
#[track_caller]
pub fn new(data: Vec<T>, shape: impl Into<Shape>) -> Self {
let shape = shape.into();
assert_eq!(
data.len(),
shape.size(),
"{} elements for shape [{shape}]",
data.len()
);
Self {
data: Data::from_vec(data),
shape,
}
}
#[track_caller]
#[inline]
pub fn from_slice(data: &[T], shape: impl Into<Shape>) -> Self {
let shape = shape.into();
assert_eq!(
data.len(),
shape.size(),
"{} elements for shape [{shape}]",
data.len()
);
Self {
data: Data::from_slice(data),
shape,
}
}
pub fn data(&self) -> &[T] {
&self.data
}
pub fn shape(&self) -> &Shape {
&self.shape
}
pub fn to_host(&self) -> HostArray {
HostArray::from_vec(self.data.to_vec(), self.shape.clone())
}
#[track_caller]
pub fn from_host(h: &HostArray) -> Self {
let data = h.to_vec::<T>().unwrap_or_else(|e| panic!("{e}"));
Self::new(data, h.shape().clone())
}
}
impl<T: Element> fmt::Debug for NativeArray<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}[{}] {:?}", T::DTYPE, self.shape, &self.data[..])
}
}
pub trait Backend: Copy + Default + Send + Sync + fmt::Debug + 'static + sealed::Sealed {
type Scalar<T: Element>: Copy + fmt::Debug;
type Array<T: Element>: Clone + fmt::Debug;
type Leaf: Clone + fmt::Debug;
#[doc(hidden)]
type KeyData: Clone + fmt::Debug;
#[doc(hidden)]
const FAST_PATHS: bool = false;
fn lit<T: Element>(v: T) -> Self::Scalar<T>;
fn unary<T: Element>(op: UnaryOp, x: Self::Scalar<T>) -> Self::Scalar<T>;
fn binary<T: Element>(op: BinaryOp, x: Self::Scalar<T>, y: Self::Scalar<T>) -> Self::Scalar<T>;
fn compare<T: Element>(
op: CompareOp,
x: Self::Scalar<T>,
y: Self::Scalar<T>,
) -> Self::Scalar<bool>;
fn is_finite<T: Element>(x: Self::Scalar<T>) -> Self::Scalar<bool>;
fn integer_pow<T: Element>(x: Self::Scalar<T>, y: i32) -> Self::Scalar<T>;
fn select<T: Element>(
c: Self::Scalar<bool>,
t: Self::Scalar<T>,
f: Self::Scalar<T>,
) -> Self::Scalar<T>;
fn cast<T: Element, U: Element>(x: Self::Scalar<T>) -> Self::Scalar<U>;
fn bitcast<T: Element, U: Element>(x: Self::Scalar<T>) -> Self::Scalar<U>;
fn to_real<T: Element>(op: ToReal, x: Self::Scalar<T>) -> Self::Scalar<T::Real>;
fn complex<C: Element>(re: Self::Scalar<C::Real>, im: Self::Scalar<C::Real>)
-> Self::Scalar<C>;
fn conj<T: Element>(x: Self::Scalar<T>) -> Self::Scalar<T>;
fn constant<T: Element>(x: &NativeArray<T>) -> Self::Array<T>;
#[doc(hidden)]
#[inline]
fn constant_owned<T: Element>(x: NativeArray<T>) -> Self::Array<T> {
Self::constant(&x)
}
fn shape<T: Element>(x: &Self::Array<T>) -> Shape;
fn to_array<T: Element>(x: Self::Scalar<T>) -> Self::Array<T>;
fn to_scalar<T: Element>(x: &Self::Array<T>) -> Self::Scalar<T>;
fn a_unary<T: Element>(op: UnaryOp, x: &Self::Array<T>) -> Self::Array<T>;
fn a_binary<T: Element>(op: BinaryOp, x: &Self::Array<T>, y: &Self::Array<T>)
-> Self::Array<T>;
fn a_ternary<T: Element>(
op: TernaryOp,
x: &Self::Array<T>,
y: &Self::Array<T>,
z: &Self::Array<T>,
) -> Self::Array<T>;
fn a_compare<T: Element>(
op: CompareOp,
x: &Self::Array<T>,
y: &Self::Array<T>,
) -> Self::Array<bool>;
fn a_is_finite<T: Element>(x: &Self::Array<T>) -> Self::Array<bool>;
fn a_integer_pow<T: Element>(x: &Self::Array<T>, y: i32) -> Self::Array<T>;
fn a_cast<T: Element, U: Element>(x: &Self::Array<T>) -> Self::Array<U>;
fn a_bitcast<T: Element, U: Element>(x: &Self::Array<T>) -> Self::Array<U>;
fn a_to_real<T: Element>(op: ToReal, x: &Self::Array<T>) -> Self::Array<T::Real>;
fn a_complex<C: Element>(
re: &Self::Array<C::Real>,
im: &Self::Array<C::Real>,
) -> Self::Array<C>;
fn a_conj<T: Element>(x: &Self::Array<T>) -> Self::Array<T>;
fn a_select<T: Element>(
c: &Self::Array<bool>,
t: &Self::Array<T>,
f: &Self::Array<T>,
) -> Self::Array<T>;
fn a_clamp<T: Element>(
lo: &Self::Array<T>,
x: &Self::Array<T>,
hi: &Self::Array<T>,
) -> Self::Array<T>;
fn broadcast_in_dim<T: Element>(
x: &Self::Array<T>,
shape: &[usize],
dims: &[usize],
) -> Self::Array<T>;
fn reshape<T: Element>(x: &Self::Array<T>, shape: &[usize]) -> Self::Array<T>;
fn transpose<T: Element>(x: &Self::Array<T>, perm: &[usize]) -> Self::Array<T>;
fn slice<T: Element>(
x: &Self::Array<T>,
start: &[usize],
limit: &[usize],
strides: &[usize],
) -> Self::Array<T>;
fn dynamic_slice<T: Element, I: Element>(
x: &Self::Array<T>,
starts: &[Self::Scalar<I>],
sizes: &[usize],
) -> Self::Array<T>;
fn dynamic_update_slice<T: Element, I: Element>(
x: &Self::Array<T>,
update: &Self::Array<T>,
starts: &[Self::Scalar<I>],
) -> Self::Array<T>;
fn concatenate<T: Element>(xs: &[Self::Array<T>], dim: usize) -> Self::Array<T>;
fn pad<T: Element>(
x: &Self::Array<T>,
value: Self::Scalar<T>,
config: &[(i64, i64, usize)],
) -> Self::Array<T>;
fn rev<T: Element>(x: &Self::Array<T>, dims: &[usize]) -> Self::Array<T>;
fn iota<T: Element>(shape: &[usize], dim: usize) -> Self::Array<T>;
fn reduce<T: Element>(op: ReduceOp, x: &Self::Array<T>, axes: &[usize]) -> Self::Array<T>;
fn arg_min_max<T: Element, I: Element>(
x: &Self::Array<T>,
axis: usize,
max: bool,
) -> Self::Array<I>;
fn sort(
operands: &[Self::Leaf],
dimension: usize,
is_stable: bool,
num_keys: usize,
) -> Vec<Self::Leaf>;
fn cumulative<T: Element>(
op: CumulativeOp,
x: &Self::Array<T>,
axis: usize,
reverse: bool,
) -> Self::Array<T>;
fn top_k<T: Element>(
x: &Self::Array<T>,
k: usize,
axis: usize,
) -> (Self::Array<T>, Self::Array<i32>);
fn cholesky<T: LinalgScalar>(x: &Self::Array<T>) -> Self::Array<T>;
fn triangular_solve<T: LinalgScalar>(
a: &Self::Array<T>,
b: &Self::Array<T>,
options: TriangularSolveOptions,
) -> Self::Array<T>;
fn lu<T: LinalgScalar>(
x: &Self::Array<T>,
) -> (Self::Array<T>, Self::Array<i32>, Self::Array<i32>);
fn lu_pivots_to_permutation(pivots: &Self::Array<i32>, size: usize) -> Self::Array<i32>;
fn qr<T: LinalgScalar>(
x: &Self::Array<T>,
full_matrices: bool,
) -> (Self::Array<T>, Self::Array<T>);
fn qr_pivoting<T: LinalgScalar>(
x: &Self::Array<T>,
full_matrices: bool,
) -> (Self::Array<T>, Self::Array<T>, Self::Array<i32>);
fn eigh<T: LinalgScalar>(
x: &Self::Array<T>,
lower: bool,
sort_eigenvalues: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<EighImplementation>,
) -> (Self::Array<T>, Self::Array<T::Real>);
#[allow(clippy::type_complexity)] fn eig<T: LinalgScalar>(
x: &Self::Array<T>,
left: bool,
right: bool,
enable_eigvec_derivs: bool,
) -> (
Self::Array<<T as LinalgScalar>::Complex>,
Option<Self::Array<<T as LinalgScalar>::Complex>>,
Option<Self::Array<<T as LinalgScalar>::Complex>>,
);
fn schur<T: LinalgScalar>(
x: &Self::Array<T>,
compute_schur_vectors: bool,
) -> (Self::Array<T>, Option<Self::Array<T>>);
fn hessenberg<T: LinalgScalar>(x: &Self::Array<T>) -> (Self::Array<T>, Self::Array<T>);
fn householder_product<T: LinalgScalar>(
a: &Self::Array<T>,
taus: &Self::Array<T>,
) -> Self::Array<T>;
fn ormqr<T: LinalgScalar>(
a: &Self::Array<T>,
taus: &Self::Array<T>,
c: &Self::Array<T>,
left: bool,
transpose: bool,
) -> Self::Array<T>;
fn cholesky_update<T: LinalgFloat>(r: &Self::Array<T>, w: &Self::Array<T>) -> Self::Array<T>;
fn symmetric_product<T: LinalgFloat>(
a: &Self::Array<T>,
c: &Self::Array<T>,
alpha: f64,
beta: f64,
) -> Self::Array<T>;
#[allow(clippy::type_complexity)] fn tridiagonal<T: LinalgScalar>(
x: &Self::Array<T>,
lower: bool,
) -> (
Self::Array<T>,
Self::Array<T::Real>,
Self::Array<T::Real>,
Self::Array<T>,
);
fn tridiagonal_solve<T: LinalgScalar>(
dl: &Self::Array<T>,
d: &Self::Array<T>,
du: &Self::Array<T>,
b: &Self::Array<T>,
perturb_singular: bool,
) -> Self::Array<T>;
#[allow(clippy::type_complexity)] fn svd<T: LinalgScalar>(
x: &Self::Array<T>,
full_matrices: bool,
compute_uv: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<SvdAlgorithm>,
) -> (
Self::Array<T::Real>,
Option<(Self::Array<T>, Self::Array<T>)>,
);
fn fft<T: Element, U: Element>(
x: &Self::Array<T>,
fft_type: FftType,
fft_lengths: &[usize],
) -> Self::Array<U>;
fn dot_general<T: Element, U: Element>(
l: &Self::Array<T>,
r: &Self::Array<T>,
dims: &DotDims,
precision: Precision,
) -> Self::Array<U>;
fn conv_general_dilated<T: Element, U: Element>(
lhs: &Self::Array<T>,
rhs: &Self::Array<T>,
window: &ConvWindow<'_>,
dims: &ConvDims,
groups: (usize, usize),
precision: Precision,
) -> Self::Array<U>;
fn reduce_window<T: Element>(
op: ReduceOp,
x: &Self::Array<T>,
window: &Window<'_>,
) -> Self::Array<T>;
fn select_and_scatter_add<T: Element>(
source: &Self::Array<T>,
operand: &Self::Array<T>,
select_prim: SelectPrim,
window: &Window<'_>,
) -> Self::Array<T>;
fn select_and_gather_add<T: Element>(
tangents: &Self::Array<T>,
operand: &Self::Array<T>,
select_prim: SelectPrim,
window: &Window<'_>,
) -> Self::Array<T>;
fn gather<T: Element, I: Element>(
x: &Self::Array<T>,
indices: &Self::Array<I>,
dims: &GatherDims,
sizes: &[usize],
mode: GatherScatterMode,
sorted_unique: bool,
) -> Self::Array<T>;
#[allow(clippy::too_many_arguments)]
fn scatter<T: Element, I: Element>(
combine: Option<BinaryOp>,
x: &Self::Array<T>,
indices: &Self::Array<I>,
updates: &Self::Array<T>,
dims: &ScatterDims,
mode: GatherScatterMode,
sorted_unique: bool,
) -> Self::Array<T>;
fn cond<S: Tree<Self>, R: Tree<Self>>(
index: I32<Self>,
branches: &[&dyn Fn(S) -> R],
operand: S,
) -> R;
fn while_loop<C: Tree<Self>>(
cond: &dyn Fn(&C) -> Bool<Self>,
body: &dyn Fn(C) -> C,
init: C,
) -> C;
fn custom_jvp<I: Tree<Self>, O: Tree<Self>>(
f: &dyn Fn(I) -> O,
jvp: &dyn Fn(I, I) -> (O, O),
primals: I,
) -> O {
let _ = jvp;
f(primals)
}
fn custom_vjp<I: Tree<Self>, O: Tree<Self>, R: Tree<Self>>(
f: &dyn Fn(I) -> O,
fwd: &dyn Fn(I) -> (O, R),
bwd: &dyn Fn(R, O) -> I,
primals: I,
) -> O {
let _ = (fwd, bwd);
f(primals)
}
fn checkpoint<I: Tree<Self>, O: Tree<Self>>(f: &dyn Fn(I) -> O, input: I) -> O {
f(input)
}
fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
f: &dyn Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
reverse: bool,
) -> (C, Y);
#[doc(hidden)]
fn a_binary_broadcast<T: Element>(
op: BinaryOp,
x: &Self::Array<T>,
y: &Self::Array<T>,
) -> Option<Self::Array<T>> {
let _ = (op, x, y);
None
}
#[doc(hidden)]
fn a_compare_broadcast<T: Element>(
op: CompareOp,
x: &Self::Array<T>,
y: &Self::Array<T>,
) -> Option<Self::Array<bool>> {
let _ = (op, x, y);
None
}
#[doc(hidden)]
fn a_binary_assign<T: Element>(
op: BinaryOp,
x: &mut Self::Array<T>,
y: &Self::Array<T>,
) -> bool {
let _ = (op, x, y);
false
}
#[doc(hidden)]
fn a_unary_assign<T: Element>(op: UnaryOp, x: &mut Self::Array<T>) -> bool {
let _ = (op, x);
false
}
#[doc(hidden)]
fn a_select_broadcast<T: Element>(
c: &Self::Array<bool>,
x: &Self::Array<T>,
y: &Self::Array<T>,
) -> Option<Self::Array<T>> {
let _ = (c, x, y);
None
}
#[doc(hidden)]
fn a_take<T: Element, I: Element>(
x: &Self::Array<T>,
indices: &Self::Array<I>,
axis: usize,
) -> Option<Self::Array<T>> {
let _ = (x, indices, axis);
None
}
#[doc(hidden)]
fn a_roll<T: Element>(x: &Self::Array<T>, shift: usize, axis: usize) -> Option<Self::Array<T>> {
let _ = (x, shift, axis);
None
}
#[doc(hidden)]
fn random_uniform<T: crate::value::Float>(
key: &Self::KeyData,
shape: &Shape,
minval: &Self::Array<T>,
maxval: &Self::Array<T>,
) -> Option<Self::Array<T>> {
let _ = (key, shape, minval, maxval);
None
}
#[doc(hidden)]
fn random_uniform_scalar<T: crate::value::Float>(
key: &Self::KeyData,
lo: Self::Scalar<T>,
hi: Self::Scalar<T>,
) -> Option<Self::Scalar<T>> {
let _ = (key, lo, hi);
None
}
#[doc(hidden)]
fn random_randint_scalar<T: crate::value::Int>(
key: &Self::KeyData,
lo: Self::Scalar<T>,
hi: Self::Scalar<T>,
) -> Option<Self::Scalar<T>> {
let _ = (key, lo, hi);
None
}
#[doc(hidden)]
fn random_randint<T: crate::value::Int>(
key: &Self::KeyData,
shape: &Shape,
minval: &Self::Array<T>,
maxval: &Self::Array<T>,
) -> Option<Self::Array<T>> {
let _ = (key, shape, minval, maxval);
None
}
#[doc(hidden)]
fn point_update_in_place<T: Element>(
x: &mut Self::Array<T>,
index: &[crate::indexing::Index<Self>],
value: Self::Scalar<T>,
combine: Option<BinaryOp>,
) -> bool {
let _ = (x, index, value, combine);
false
}
#[doc(hidden)]
fn update_box<T: Element>(
x: &mut Self::Array<T>,
starts: &[usize],
sizes: &[usize],
values: &Self::Array<T>,
combine: Option<BinaryOp>,
) -> bool {
let _ = (x, starts, sizes, values, combine);
false
}
#[doc(hidden)]
fn point_update<T: Element>(
x: &Self::Array<T>,
index: &[Self::Scalar<i32>],
value: &Self::Array<T>,
combine: Option<BinaryOp>,
) -> Option<Self::Array<T>> {
let _ = (x, index, value, combine);
None
}
#[doc(hidden)]
fn index_leading<T: Element>(x: &Self::Array<T>, index: &[usize]) -> Option<Self::Array<T>> {
let _ = (x, index);
None
}
#[doc(hidden)]
fn key_from_array(data: Self::Array<u32>) -> Self::KeyData;
#[doc(hidden)]
fn key_to_array(key: &Self::KeyData) -> Self::Array<u32>;
#[doc(hidden)]
fn key_rank(key: &Self::KeyData) -> usize {
Self::rank::<u32>(&Self::key_to_array(key))
}
#[doc(hidden)]
fn key_split2(key: &Self::KeyData) -> Option<(Self::KeyData, Self::KeyData)> {
let _ = key;
None
}
#[doc(hidden)]
fn stack0<T: Element>(xs: &[Self::Array<T>]) -> Option<Self::Array<T>> {
let _ = xs;
None
}
#[doc(hidden)]
fn stack_scalars<T: Element>(
n: usize,
scalar: impl FnMut(usize) -> Self::Scalar<T>,
) -> Option<Self::Array<T>> {
let _ = (n, scalar);
None
}
#[doc(hidden)]
#[inline]
fn rank<T: Element>(x: &Self::Array<T>) -> usize {
Self::shape(x).rank()
}
#[doc(hidden)]
#[inline]
fn dims<T: Element>(x: &Self::Array<T>) -> Option<&[usize]> {
let _ = x;
None
}
#[doc(hidden)]
fn sort_key_val_typed<K: Element, V: Element>(
keys: &Self::Array<K>,
values: &Self::Array<V>,
dimension: usize,
) -> Option<(Self::Array<K>, Self::Array<V>)> {
let _ = (keys, values, dimension);
None
}
#[doc(hidden)]
fn slice_box<T: Element>(
x: &Self::Array<T>,
starts: &[usize],
sizes: &[usize],
out: Shape,
) -> Option<Self::Array<T>> {
let _ = (x, starts, sizes, out);
None
}
#[doc(hidden)]
#[inline]
fn full<T: Element>(shape: Shape, value: Self::Scalar<T>) -> Option<Self::Array<T>> {
let _ = (shape, value);
None
}
#[doc(hidden)]
#[inline]
fn int_value(x: Self::Scalar<i32>) -> Option<i64> {
let _ = x;
None
}
#[doc(hidden)]
#[inline]
fn branch_value(pred: Bool<Self>) -> Option<bool> {
let _ = pred;
None
}
#[doc(hidden)]
#[inline]
fn element<T: Element>(x: &Self::Array<T>, flat: usize) -> Option<Self::Scalar<T>> {
let _ = (x, flat);
None
}
#[doc(hidden)]
fn key_split(key: &Self::KeyData, num: usize) -> Self::KeyData {
let a = crate::value::Array::<Self, u32>(Self::key_to_array(key));
Self::key_from_array(crate::random::split_generic(&a, num).0)
}
#[doc(hidden)]
fn key_fold_in(key: &Self::KeyData, data: Self::Scalar<u32>) -> Self::KeyData {
let a = crate::value::Array::<Self, u32>(Self::key_to_array(key));
Self::key_from_array(crate::random::fold_in_generic(&a, Scalar(data)).0)
}
#[doc(hidden)]
fn key_bits(key: &Self::KeyData, shape: &[usize]) -> (Self::Array<u32>, Self::Array<u32>) {
let k = crate::value::Array::<Self, u32>(Self::key_to_array(key));
let (a, b) = crate::random::key_bits_generic(&k, shape);
(a.0, b.0)
}
#[doc(hidden)]
fn threefry2x32(
k1: &Self::Array<u32>,
k2: &Self::Array<u32>,
x1: &Self::Array<u32>,
x2: &Self::Array<u32>,
) -> (Self::Array<u32>, Self::Array<u32>) {
let a = |x: &Self::Array<u32>| crate::value::Array::<Self, u32>(x.clone());
let (y1, y2) = crate::random::threefry2x32_generic(&a(k1), &a(k2), &a(x1), &a(x2));
(y1.0, y2.0)
}
fn fori_loop<C: Tree<Self>>(
lo: I32<Self>,
hi: I32<Self>,
body: &dyn Fn(I32<Self>, C) -> C,
init: C,
) -> C;
fn scalar_leaf<T: Element>(x: Self::Scalar<T>) -> Self::Leaf;
fn leaf_scalar<T: Element>(l: Self::Leaf) -> Self::Scalar<T>;
fn array_leaf<T: Element>(x: &Self::Array<T>) -> Self::Leaf;
fn leaf_array<T: Element>(l: Self::Leaf) -> Self::Array<T>;
fn leaf_aval(l: &Self::Leaf) -> AVal;
fn host_callback(
callback: &ruxla_ir::callback::HostCallback,
args: &[Self::Leaf],
outputs: &[AVal],
) -> Vec<Self::Leaf>;
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
pub struct Native;
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
pub struct Trace;
impl sealed::Sealed for Native {}
impl sealed::Sealed for Trace {}
#[inline]
fn to_real_native<T: Element>(op: ToReal, x: T) -> T::Real {
match op {
ToReal::Abs => T::unary(UnaryOp::Abs, x).re(),
ToReal::Real => x.re(),
ToReal::Imag => x.im(),
}
}
fn starts_i64<I: Element>(s: &[I]) -> Vec<i64> {
s.iter().map(|&i| cast::<I, i64>(i)).collect()
}
fn copy_box<T: Element>(
x: &NativeArray<T>,
starts: &[usize],
sizes: &[usize],
out: Shape,
) -> Option<NativeArray<T>> {
let rank = x.shape.rank();
if rank > 8 || rank == 0 {
return None;
}
let count: usize = sizes.iter().product();
if count == 0 {
return Some(build(out, |_| {}));
}
let mut stride = [0usize; 8];
let mut base = 0;
let mut st = 1;
for d in (0..rank).rev() {
stride[d] = st;
base += starts[d] * st;
st *= x.shape[d];
}
let mut dims = [(0usize, 0usize); 8];
let mut nd = 0;
for d in 0..rank {
if sizes[d] == 1 {
continue;
}
if nd > 0 && dims[nd - 1].1 == sizes[d] * stride[d] {
dims[nd - 1] = (dims[nd - 1].0 * sizes[d], stride[d]);
} else {
dims[nd] = (sizes[d], stride[d]);
nd += 1;
}
}
let run = if nd > 0 && dims[nd - 1].1 == 1 {
nd -= 1;
dims[nd].0
} else {
1
};
let (inner, inner_stride) = if nd > 0 {
nd -= 1;
dims[nd]
} else {
(1, 0)
};
let src: &[T] = &x.data;
let outer_extent: usize = dims[..nd].iter().map(|&(n, s)| (n - 1) * s).sum();
assert!(
base + outer_extent + (inner - 1) * inner_stride + run <= src.len(),
"the box is inside the array"
);
Some(build_all(out, |o| {
let mut pos = [0usize; 8];
let mut w = 0;
loop {
let s = &src[base..base + (inner - 1) * inner_stride + run];
if run == 1 {
for (k, o) in o[w..w + inner].iter_mut().enumerate() {
*o = s[k * inner_stride];
}
} else {
for k in 0..inner {
o[w + k * run..w + (k + 1) * run]
.copy_from_slice(&s[k * inner_stride..k * inner_stride + run]);
}
}
w += inner * run;
let mut d = nd;
loop {
if d == 0 {
return;
}
d -= 1;
pos[d] += 1;
base += dims[d].1;
if pos[d] < dims[d].0 {
break;
}
base -= dims[d].1 * dims[d].0;
pos[d] = 0;
}
}
}))
}
fn native<T: Element>(data: Vec<T>, shape: impl Into<Shape>) -> NativeArray<T> {
NativeArray::new(data, shape)
}
#[inline]
fn broadcast_shape_simple<'a, T: Element, U: Element>(
x: &'a NativeArray<T>,
y: &'a NativeArray<U>,
) -> Option<&'a Shape> {
if x.shape == y.shape || (y.data.len() == 1 && y.shape.rank() <= x.shape.rank()) {
Some(&x.shape)
} else if x.data.len() == 1 && x.shape.rank() <= y.shape.rank() {
Some(&y.shape)
} else {
None
}
}
#[inline]
fn broadcast_rows<T: Element, U: Element, R: Element>(
x: &NativeArray<T>,
y: &NativeArray<U>,
rows: impl Fn(&[T], &[U], &mut [R]),
) -> Option<NativeArray<R>> {
let (xs, ys) = (x.shape.dims(), y.shape.dims());
let rank = xs.len().max(ys.len());
if rank == 0 || rank > 8 {
return None;
}
let mut dims = [1usize; 8];
let (mut sx, mut sy) = ([0usize; 8], [0usize; 8]);
let (mut px, mut py) = (1, 1);
for k in (0..rank).rev() {
let a = if k + xs.len() >= rank {
xs[k + xs.len() - rank]
} else {
1
};
let b = if k + ys.len() >= rank {
ys[k + ys.len() - rank]
} else {
1
};
dims[k] = match (a, b) {
_ if a == b => a,
(1, b) => b,
(a, 1) => a,
_ => return None,
};
if a != 1 {
sx[k] = px;
}
if b != 1 {
sy[k] = py;
}
px *= a;
py *= b;
}
let len = dims[rank - 1];
let n: usize = dims[..rank].iter().product();
if n == 0 {
return None;
}
let (wx, wy) = (
if sx[rank - 1] == 0 { 1 } else { len },
if sy[rank - 1] == 0 { 1 } else { len },
);
let shape = Shape::from(dims[..rank].to_vec());
Some(build_all(shape, |o| {
let mut index = [0usize; 8];
let (mut ox, mut oy) = (0, 0);
for out in o.chunks_exact_mut(len) {
rows(&x.data[ox..ox + wx], &y.data[oy..oy + wy], out);
let mut k = rank - 1;
while k > 0 {
k -= 1;
index[k] += 1;
ox += sx[k];
oy += sy[k];
if index[k] < dims[k] {
break;
}
ox -= sx[k] * dims[k];
oy -= sy[k] * dims[k];
index[k] = 0;
}
}
}))
}
#[inline(always)]
fn build<T: Element>(shape: Shape, f: impl FnOnce(&mut [T])) -> NativeArray<T> {
NativeArray {
data: Data::build(shape.size(), f),
shape,
}
}
#[inline(always)]
fn build_all<T: Element>(shape: Shape, f: impl FnOnce(&mut [T])) -> NativeArray<T> {
NativeArray {
data: Data::build_overwrite(shape.size(), f),
shape,
}
}
impl Backend for Native {
type Scalar<T: Element> = T;
type Array<T: Element> = NativeArray<T>;
type Leaf = HostArray;
type KeyData = NativeKey;
const FAST_PATHS: bool = true;
#[inline]
fn lit<T: Element>(v: T) -> T {
v
}
#[inline]
fn unary<T: Element>(op: UnaryOp, x: T) -> T {
T::unary(op, x)
}
#[inline]
fn binary<T: Element>(op: BinaryOp, x: T, y: T) -> T {
T::binary(op, x, y)
}
#[inline]
fn compare<T: Element>(op: CompareOp, x: T, y: T) -> bool {
ruxla_kernels::compare(op, x, y)
}
#[inline]
fn is_finite<T: Element>(x: T) -> bool {
T::is_finite(x)
}
#[inline]
fn integer_pow<T: Element>(x: T, y: i32) -> T {
ruxla_kernels::integer_pow(x, y)
}
#[inline]
fn select<T: Element>(c: bool, t: T, f: T) -> T {
if c { t } else { f }
}
#[inline]
fn cast<T: Element, U: Element>(x: T) -> U {
cast(x)
}
#[inline]
fn bitcast<T: Element, U: Element>(x: T) -> U {
assert_eq!(
T::DTYPE.size_in_bytes(),
U::DTYPE.size_in_bytes(),
"cannot reinterpret {} as {}",
T::DTYPE,
U::DTYPE
);
U::from_bits(x.to_bits())
}
#[inline]
fn to_real<T: Element>(op: ToReal, x: T) -> T::Real {
to_real_native(op, x)
}
#[inline]
fn complex<C: Element>(re: C::Real, im: C::Real) -> C {
C::from_parts(re, im)
}
#[inline]
fn conj<T: Element>(x: T) -> T {
T::from_parts(
x.re(),
<T::Real as ruxla_kernels::Ops>::unary(UnaryOp::Neg, x.im()),
)
}
fn constant<T: Element>(x: &NativeArray<T>) -> NativeArray<T> {
x.clone()
}
#[inline]
fn constant_owned<T: Element>(x: NativeArray<T>) -> NativeArray<T> {
x
}
fn shape<T: Element>(x: &NativeArray<T>) -> Shape {
x.shape.clone()
}
#[inline]
fn to_array<T: Element>(x: T) -> NativeArray<T> {
build(Shape::scalar(), |o| o[0] = x)
}
#[track_caller]
fn to_scalar<T: Element>(x: &NativeArray<T>) -> T {
assert_eq!(
x.shape.rank(),
0,
"expected a scalar, got an array of shape [{}]",
x.shape
);
x.data[0]
}
fn a_unary<T: Element>(op: UnaryOp, x: &NativeArray<T>) -> NativeArray<T> {
build_all(x.shape.clone(), |o| ew::unary_into(op, &x.data, o))
}
#[track_caller]
fn a_binary<T: Element>(
op: BinaryOp,
x: &NativeArray<T>,
y: &NativeArray<T>,
) -> NativeArray<T> {
same_shape(op.name(), &x.shape, &y.shape);
build_all(x.shape.clone(), |o| {
ew::binary_into(op, &x.data, &y.data, o)
})
}
#[track_caller]
fn a_ternary<T: Element>(
op: TernaryOp,
x: &NativeArray<T>,
y: &NativeArray<T>,
z: &NativeArray<T>,
) -> NativeArray<T> {
same_shape(op.name(), &x.shape, &y.shape);
same_shape(op.name(), &x.shape, &z.shape);
build_all(x.shape.clone(), |o| {
for (i, o) in o.iter_mut().enumerate() {
*o = T::ternary(op, x.data[i], y.data[i], z.data[i]);
}
})
}
#[track_caller]
fn a_compare<T: Element>(
op: CompareOp,
x: &NativeArray<T>,
y: &NativeArray<T>,
) -> NativeArray<bool> {
same_shape(op.name(), &x.shape, &y.shape);
build_all(x.shape.clone(), |o| {
ew::compare_into(op, &x.data, &y.data, o)
})
}
fn a_is_finite<T: Element>(x: &NativeArray<T>) -> NativeArray<bool> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = T::is_finite(a);
}
})
}
fn a_integer_pow<T: Element>(x: &NativeArray<T>, y: i32) -> NativeArray<T> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = ruxla_kernels::integer_pow(a, y);
}
})
}
fn a_cast<T: Element, U: Element>(x: &NativeArray<T>) -> NativeArray<U> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = cast(a);
}
})
}
fn a_bitcast<T: Element, U: Element>(x: &NativeArray<T>) -> NativeArray<U> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = Self::bitcast::<T, U>(a);
}
})
}
fn a_to_real<T: Element>(op: ToReal, x: &NativeArray<T>) -> NativeArray<T::Real> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = to_real_native(op, a);
}
})
}
#[track_caller]
fn a_complex<C: Element>(
re: &NativeArray<C::Real>,
im: &NativeArray<C::Real>,
) -> NativeArray<C> {
same_shape("complex", &re.shape, &im.shape);
build_all(re.shape.clone(), |o| {
for ((o, &a), &b) in o.iter_mut().zip(re.data.iter()).zip(im.data.iter()) {
*o = C::from_parts(a, b);
}
})
}
fn a_conj<T: Element>(x: &NativeArray<T>) -> NativeArray<T> {
build_all(x.shape.clone(), |o| {
for (o, &a) in o.iter_mut().zip(x.data.iter()) {
*o = Self::conj::<T>(a);
}
})
}
#[track_caller]
fn a_select<T: Element>(
c: &NativeArray<bool>,
t: &NativeArray<T>,
f: &NativeArray<T>,
) -> NativeArray<T> {
same_shape("select_n", &t.shape, &f.shape);
if c.shape.rank() != 0 {
same_shape("select_n", &c.shape, &t.shape);
}
let (cd, td, fd): (&[bool], &[T], &[T]) = (&c.data, &t.data, &f.data);
if cd.len() == 1 {
return NativeArray {
data: if cd[0] {
t.data.clone()
} else {
f.data.clone()
},
shape: t.shape.clone(),
};
}
build_all(t.shape.clone(), |o| {
for (((o, &c), &a), &b) in o.iter_mut().zip(cd).zip(td).zip(fd) {
*o = if c { a } else { b };
}
})
}
fn a_clamp<T: Element>(
lo: &NativeArray<T>,
x: &NativeArray<T>,
hi: &NativeArray<T>,
) -> NativeArray<T> {
native(k::clamp(&lo.data, &x.data, &hi.data), x.shape.clone())
}
fn broadcast_in_dim<T: Element>(
x: &NativeArray<T>,
shape: &[usize],
dims: &[usize],
) -> NativeArray<T> {
let valid = dims.len() == x.shape.rank()
&& dims.windows(2).all(|w| w[0] < w[1])
&& dims
.iter()
.zip(x.shape.dims())
.all(|(&d, &n)| d < shape.len() && (n == 1 || n == shape[d]));
if !valid {
check_native(
p::BROADCAST_IN_DIM,
&[x.aval()],
&Params::BroadcastInDim {
shape: shape.into(),
broadcast_dimensions: dims.to_vec(),
},
);
}
if x.shape.rank() == 0 {
let shape = Shape::from(shape);
return NativeArray {
data: Data::filled(shape.size(), x.data[0]),
shape,
};
}
if shape.iter().product::<usize>() == x.data.len() {
return NativeArray {
data: x.data.clone(),
shape: shape.into(),
};
}
build_all(Shape::from(shape), |o| {
k::broadcast_in_dim_into(&x.data, &x.shape, shape, dims, o)
})
}
#[track_caller]
fn reshape<T: Element>(x: &NativeArray<T>, shape: &[usize]) -> NativeArray<T> {
let size = shape.iter().try_fold(1usize, |a, &d| a.checked_mul(d));
assert!(
size == Some(x.data.len()),
"cannot reshape [{}] to {shape:?}",
x.shape
);
NativeArray {
data: x.data.clone(),
shape: shape.into(),
}
}
fn transpose<T: Element>(x: &NativeArray<T>, perm: &[usize]) -> NativeArray<T> {
let rank = x.shape.rank();
let valid = perm.len() == rank && rank <= 8 && (0..rank).all(|d| perm.contains(&d));
if !valid {
let out = check_native(
p::TRANSPOSE,
&[x.aval()],
&Params::Transpose {
permutation: perm.to_vec(),
},
);
return native(k::transpose(&x.data, &x.shape, perm), out);
}
let out: Shape = perm.iter().map(|&p| x.shape[p]).collect();
build_all(out, |o| k::transpose_into(&x.data, &x.shape, perm, o))
}
fn slice<T: Element>(
x: &NativeArray<T>,
start: &[usize],
limit: &[usize],
strides: &[usize],
) -> NativeArray<T> {
let rank = x.shape.rank();
let valid = start.len() == rank
&& limit.len() == rank
&& strides.len() == rank
&& (0..rank).all(|i| start[i] <= limit[i] && limit[i] <= x.shape[i] && strides[i] > 0);
if !valid {
let params = Params::Slice {
start_indices: start.to_vec(),
limit_indices: limit.to_vec(),
strides: strides.to_vec(),
};
check_native(p::SLICE, &[x.aval()], ¶ms);
}
let out: Shape = (0..rank)
.map(|i| (limit[i] - start[i]).div_ceil(strides[i]))
.collect();
if (1..rank).all(|i| start[i] == 0 && limit[i] == x.shape[i] && strides[i] == 1)
&& rank > 0
&& strides[0] == 1
{
let inner: usize = x.shape[1..].iter().product();
return NativeArray {
data: Data::from_slice(&x.data[start[0] * inner..limit[0] * inner]),
shape: out,
};
}
if strides.iter().all(|&st| st == 1)
&& let Some(r) = copy_box(x, start, out.dims(), out.clone())
{
return r;
}
native(k::slice(&x.data, &x.shape, start, limit, strides), out)
}
#[track_caller]
fn dynamic_slice<T: Element, I: Element>(
x: &NativeArray<T>,
starts: &[I],
sizes: &[usize],
) -> NativeArray<T> {
assert!(
starts.len() == x.shape.rank()
&& sizes.len() == x.shape.rank()
&& sizes.iter().zip(x.shape.dims()).all(|(s, n)| s <= n),
"dynamic_slice: invalid sizes {sizes:?} for shape [{}]",
x.shape
);
let mut at = [0usize; 8];
if starts.len() <= at.len() {
for ((a, &s), (&n, &k)) in at
.iter_mut()
.zip(starts)
.zip(x.shape.dims().iter().zip(sizes))
{
*a = cast::<I, i64>(s).clamp(0, (n - k) as i64) as usize;
}
if let Some(r) = copy_box(x, &at[..starts.len()], sizes, Shape::from(sizes)) {
return r;
}
}
native(
k::dynamic_slice(&x.data, &x.shape, &starts_i64(starts), sizes),
sizes,
)
}
#[track_caller]
fn dynamic_update_slice<T: Element, I: Element>(
x: &NativeArray<T>,
update: &NativeArray<T>,
starts: &[I],
) -> NativeArray<T> {
assert!(
starts.len() == x.shape.rank()
&& update.shape.rank() == x.shape.rank()
&& update.shape.iter().zip(x.shape.dims()).all(|(u, n)| u <= n),
"dynamic_update_slice: update [{}] does not fit [{}]",
update.shape,
x.shape
);
native(
k::dynamic_update_slice(
&x.data,
&x.shape,
&update.data,
&update.shape,
&starts_i64(starts),
),
x.shape.clone(),
)
}
fn concatenate<T: Element>(xs: &[NativeArray<T>], dim: usize) -> NativeArray<T> {
let first = &xs[0].shape;
let valid = dim < first.rank()
&& xs.iter().all(|x| {
x.shape.rank() == first.rank()
&& (0..first.rank()).all(|i| i == dim || x.shape[i] == first[i])
});
if !valid {
let avals: Vec<AVal> = xs.iter().map(NativeArray::aval).collect();
check_native(
p::CONCATENATE,
&avals,
&Params::Concatenate { dimension: dim },
);
}
let out: Shape = (0..first.rank())
.map(|i| {
if i == dim {
xs.iter().map(|x| x.shape[i]).sum()
} else {
first[i]
}
})
.collect();
if first[..dim].iter().all(|&d| d == 1) {
return build(out, |o| {
let mut at = 0;
for x in xs {
o[at..at + x.data.len()].copy_from_slice(&x.data);
at += x.data.len();
}
});
}
let outer: usize = first[..dim].iter().product();
let inner = |x: &NativeArray<T>| x.shape.dims()[dim..].iter().product::<usize>();
build(out, |o| {
if xs.iter().all(|x| inner(x) == 1) {
let n = xs.len();
for (k, x) in xs.iter().enumerate() {
for (i, &v) in x.data.iter().enumerate() {
o[i * n + k] = v;
}
}
return;
}
let inners: Vec<usize> = xs.iter().map(inner).collect();
let mut at = 0;
for i in 0..outer {
for (x, &n) in xs.iter().zip(&inners) {
o[at..at + n].copy_from_slice(&x.data[i * n..(i + 1) * n]);
at += n;
}
}
})
}
fn pad<T: Element>(
x: &NativeArray<T>,
value: T,
config: &[(i64, i64, usize)],
) -> NativeArray<T> {
let out = check_native(
p::PAD,
&[x.aval(), AVal::scalar(T::DTYPE)],
&Params::Pad {
padding_config: config.to_vec(),
},
);
native(k::pad(&x.data, &x.shape, value, config), out)
}
fn rev<T: Element>(x: &NativeArray<T>, dims: &[usize]) -> NativeArray<T> {
check_native(
p::REV,
&[x.aval()],
&Params::Rev {
dimensions: dims.to_vec(),
},
);
native(k::rev(&x.data, &x.shape, dims), x.shape.clone())
}
fn iota<T: Element>(shape: &[usize], dim: usize) -> NativeArray<T> {
build_all(Shape::from(shape), |o| k::iota_into::<T>(shape, dim, o))
}
fn reduce<T: Element>(op: ReduceOp, x: &NativeArray<T>, axes: &[usize]) -> NativeArray<T> {
let prim = match op {
ReduceOp::Sum => p::REDUCE_SUM,
ReduceOp::Max => p::REDUCE_MAX,
ReduceOp::Min => p::REDUCE_MIN,
};
let rank = x.shape.rank();
let valid = axes
.iter()
.enumerate()
.all(|(i, &a)| a < rank && !axes[..i].contains(&a))
&& (op != ReduceOp::Sum || T::DTYPE != ruxla_ir::DType::Bool);
if !valid {
check_native(
prim,
&[x.aval()],
&Params::Reduce {
axes: axes.to_vec(),
},
);
}
let out: Shape = (0..rank)
.filter(|i| !axes.contains(i))
.map(|i| x.shape[i])
.collect();
if axes.len() == rank {
let acc = k::reduce_all(&x.data, op);
return build(out, |o| o[0] = acc);
}
native(k::reduce(&x.data, &x.shape, axes, op), out)
}
fn arg_min_max<T: Element, I: Element>(
x: &NativeArray<T>,
axis: usize,
max: bool,
) -> NativeArray<I> {
let prim = if max { p::ARGMAX } else { p::ARGMIN };
let out = check_native(
prim,
&[x.aval()],
&Params::ArgMinMax {
axis,
index_dtype: I::DTYPE,
},
);
native(
k::arg_min_max(&x.data, &x.shape, axis, max)
.into_iter()
.map(cast)
.collect(),
out,
)
}
fn sort(
operands: &[HostArray],
dimension: usize,
is_stable: bool,
num_keys: usize,
) -> Vec<HostArray> {
let avals: Vec<AVal> = operands.iter().map(HostArray::aval).collect();
let params = Params::Sort {
dimension,
is_stable,
num_keys,
};
check_native(p::SORT, &avals, ¶ms);
let shape = operands[0].shape().clone();
let buffers: Vec<_> = operands.iter().map(HostArray::buffer).collect();
k::sort(&buffers, &shape, dimension, num_keys)
.into_iter()
.map(|b| HostArray::from_buffer(b, shape.clone()))
.collect()
}
fn cumulative<T: Element>(
op: CumulativeOp,
x: &NativeArray<T>,
axis: usize,
reverse: bool,
) -> NativeArray<T> {
let out = check_native(
cumulative_prim(op),
&[x.aval()],
&Params::Cumulative { axis, reverse },
);
native(k::cumulative(&x.data, &x.shape, axis, reverse, op), out)
}
fn top_k<T: Element>(
x: &NativeArray<T>,
k: usize,
axis: usize,
) -> (NativeArray<T>, NativeArray<i32>) {
let params = Params::TopK {
k,
axis,
is_stable: true,
};
let out = check_native(p::TOP_K, &[x.aval()], ¶ms);
let (values, indices) = k::top_k(&x.data, &x.shape, k, axis);
(native(values, out.clone()), native(indices, out))
}
fn cholesky<T: LinalgScalar>(x: &NativeArray<T>) -> NativeArray<T> {
let out = check_native(p::CHOLESKY, &[x.aval()], &Params::None);
let (batch, n, _) = matrix_dims(&x.shape);
native(kl::cholesky(&x.data, batch, n), out)
}
fn triangular_solve<T: LinalgScalar>(
a: &NativeArray<T>,
b: &NativeArray<T>,
options: TriangularSolveOptions,
) -> NativeArray<T> {
let params = triangular_solve_params(options);
let out = check_native(p::TRIANGULAR_SOLVE, &[a.aval(), b.aval()], ¶ms);
let (batch, m, n) = matrix_dims(&b.shape);
native(
kl::triangular_solve(&a.data, &b.data, batch, m, n, options),
out,
)
}
fn lu<T: LinalgScalar>(
x: &NativeArray<T>,
) -> (NativeArray<T>, NativeArray<i32>, NativeArray<i32>) {
let outs = check_native_all(p::LU, &[x.aval()], &Params::None);
let (batch, m, n) = matrix_dims(&x.shape);
let (lu, pivots, perm) = kl::lu(&x.data, batch, m, n);
(
native(lu, outs[0].clone()),
native(pivots, outs[1].clone()),
native(perm, outs[2].clone()),
)
}
fn lu_pivots_to_permutation(pivots: &NativeArray<i32>, size: usize) -> NativeArray<i32> {
let params = Params::LuPivotsToPermutation {
permutation_size: size,
};
let out = check_native(p::LU_PIVOTS_TO_PERMUTATION, &[pivots.aval()], ¶ms);
let dims = pivots.shape.dims();
let k = dims[dims.len() - 1];
let batch = dims[..dims.len() - 1].iter().product();
native(
kl::lu_pivots_to_permutation(&pivots.data, batch, k, size),
out,
)
}
fn qr<T: LinalgScalar>(
x: &NativeArray<T>,
full_matrices: bool,
) -> (NativeArray<T>, NativeArray<T>) {
let params = Params::Qr {
full_matrices,
pivoting: false,
};
let outs = check_native_all(p::QR, &[x.aval()], ¶ms);
let (batch, m, n) = matrix_dims(&x.shape);
let (q, r) = kl::qr(&x.data, batch, m, n, full_matrices);
(native(q, outs[0].clone()), native(r, outs[1].clone()))
}
fn qr_pivoting<T: LinalgScalar>(
x: &NativeArray<T>,
full_matrices: bool,
) -> (NativeArray<T>, NativeArray<T>, NativeArray<i32>) {
let params = Params::Qr {
full_matrices,
pivoting: true,
};
let outs = check_native_all(p::QR, &[x.aval()], ¶ms);
let (batch, m, n) = matrix_dims(&x.shape);
let (q, r, perm) = kl::qr_pivoting(&x.data, batch, m, n, full_matrices);
(
native(q, outs[0].clone()),
native(r, outs[1].clone()),
native(perm, outs[2].clone()),
)
}
fn eigh<T: LinalgScalar>(
x: &NativeArray<T>,
lower: bool,
sort_eigenvalues: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<EighImplementation>,
) -> (NativeArray<T>, NativeArray<T::Real>) {
let params = Params::Eigh {
lower,
sort_eigenvalues,
subset_by_index,
algorithm,
};
let outs = check_native_all(p::EIGH, &[x.aval()], ¶ms);
let (batch, n, _) = matrix_dims(&x.shape);
let jacobi = algorithm == Some(EighImplementation::Jacobi);
let (v, w) = kl::eigh(&x.data, batch, n, lower, jacobi);
let (v, w) = match subset_by_index {
Some(range) => (
slice_columns(&v, batch * n, n, range),
slice_columns(&w, batch, n, range),
),
None => (v, w),
};
(native(v, outs[0].clone()), native(w, outs[1].clone()))
}
fn schur<T: LinalgScalar>(
x: &NativeArray<T>,
compute_schur_vectors: bool,
) -> (NativeArray<T>, Option<NativeArray<T>>) {
let params = Params::Schur {
compute_schur_vectors,
};
let outs = check_native_all(p::SCHUR, &[x.aval()], ¶ms);
let (batch, n, _) = matrix_dims(&x.shape);
let (t, z) = kl::schur(&x.data, batch, n, compute_schur_vectors);
let z = compute_schur_vectors.then(|| native(z, outs[1].clone()));
(native(t, outs[0].clone()), z)
}
fn hessenberg<T: LinalgScalar>(x: &NativeArray<T>) -> (NativeArray<T>, NativeArray<T>) {
let outs = check_native_all(p::HESSENBERG, &[x.aval()], &Params::None);
let (batch, n, _) = matrix_dims(&x.shape);
let (h, taus) = kl::hessenberg(&x.data, batch, n);
(native(h, outs[0].clone()), native(taus, outs[1].clone()))
}
fn householder_product<T: LinalgScalar>(
a: &NativeArray<T>,
taus: &NativeArray<T>,
) -> NativeArray<T> {
let out = check_native(
p::HOUSEHOLDER_PRODUCT,
&[a.aval(), taus.aval()],
&Params::None,
);
let (batch, m, n) = matrix_dims(&a.shape);
let k = *taus.shape.dims().last().unwrap_or(&0);
native(
kl::householder_product(&a.data, &taus.data, batch, m, n, k),
out,
)
}
fn ormqr<T: LinalgScalar>(
a: &NativeArray<T>,
taus: &NativeArray<T>,
c: &NativeArray<T>,
left: bool,
transpose: bool,
) -> NativeArray<T> {
let params = Params::Ormqr { left, transpose };
let out = check_native(p::ORMQR, &[a.aval(), taus.aval(), c.aval()], ¶ms);
let (batch, m, n) = matrix_dims(&a.shape);
let k = *taus.shape.dims().last().unwrap_or(&0);
let (_, rows, cols) = matrix_dims(&c.shape);
native(
kl::ormqr(
&a.data,
&taus.data,
&c.data,
batch,
(m, n, k),
(rows, cols),
left,
transpose,
),
out,
)
}
fn cholesky_update<T: LinalgFloat>(r: &NativeArray<T>, w: &NativeArray<T>) -> NativeArray<T> {
let out = check_native(p::CHOLESKY_UPDATE, &[r.aval(), w.aval()], &Params::None);
let (batch, n, _) = matrix_dims(&r.shape);
native(kl::cholesky_update(&r.data, &w.data, batch, n), out)
}
fn symmetric_product<T: LinalgFloat>(
a: &NativeArray<T>,
c: &NativeArray<T>,
alpha: f64,
beta: f64,
) -> NativeArray<T> {
let out = check_native(
p::SYMMETRIC_PRODUCT,
&[a.aval(), c.aval()],
&Params::SymmetricProduct { alpha, beta },
);
let (batch, m, n) = matrix_dims(&a.shape);
let (alpha, beta) = (
ruxla_kernels::cast::<f64, T>(alpha),
ruxla_kernels::cast::<f64, T>(beta),
);
native(
kl::symmetric_product(&a.data, &c.data, batch, m, n, alpha, beta),
out,
)
}
fn tridiagonal<T: LinalgScalar>(
x: &NativeArray<T>,
lower: bool,
) -> (
NativeArray<T>,
NativeArray<T::Real>,
NativeArray<T::Real>,
NativeArray<T>,
) {
let outs = check_native_all(p::TRIDIAGONAL, &[x.aval()], &Params::Tridiagonal { lower });
let (batch, n, _) = matrix_dims(&x.shape);
let (a, d, e, taus) = kl::tridiagonal(&x.data, batch, n, lower);
(
native(a, outs[0].clone()),
native(d, outs[1].clone()),
native(e, outs[2].clone()),
native(taus, outs[3].clone()),
)
}
fn tridiagonal_solve<T: LinalgScalar>(
dl: &NativeArray<T>,
d: &NativeArray<T>,
du: &NativeArray<T>,
b: &NativeArray<T>,
perturb_singular: bool,
) -> NativeArray<T> {
let out = check_native(
p::TRIDIAGONAL_SOLVE,
&[dl.aval(), d.aval(), du.aval(), b.aval()],
&Params::TridiagonalSolve { perturb_singular },
);
let (batch, m, n) = matrix_dims(&b.shape);
native(
kl::tridiagonal_solve(
&dl.data,
&d.data,
&du.data,
&b.data,
batch,
m,
n,
perturb_singular,
),
out,
)
}
fn eig<T: LinalgScalar>(
x: &NativeArray<T>,
left: bool,
right: bool,
enable_eigvec_derivs: bool,
) -> (
NativeArray<<T as LinalgScalar>::Complex>,
Option<NativeArray<<T as LinalgScalar>::Complex>>,
Option<NativeArray<<T as LinalgScalar>::Complex>>,
) {
let params = Params::Eig {
compute_left_eigenvectors: left,
compute_right_eigenvectors: right,
enable_eigvec_derivs,
};
let outs = check_native_all(p::EIG, &[x.aval()], ¶ms);
let (batch, n, _) = matrix_dims(&x.shape);
let (w, vl, vr) = kl::eig(&x.data, batch, n, left, right);
let w = native(T::complex_vec(w), outs[0].clone());
let vl = left.then(|| native(T::complex_vec(vl), outs[1].clone()));
let vr = right.then(|| native(T::complex_vec(vr), outs[outs.len() - 1].clone()));
(w, vl, vr)
}
fn svd<T: LinalgScalar>(
x: &NativeArray<T>,
full_matrices: bool,
compute_uv: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<SvdAlgorithm>,
) -> (
NativeArray<T::Real>,
Option<(NativeArray<T>, NativeArray<T>)>,
) {
let params = Params::Svd {
full_matrices,
compute_uv,
subset_by_index,
algorithm,
};
let outs = check_native_all(p::SVD, &[x.aval()], ¶ms);
let (batch, m, n) = matrix_dims(&x.shape);
let jacobi = algorithm == Some(SvdAlgorithm::Jacobi);
let (s, u, vt) = kl::svd(&x.data, batch, m, n, full_matrices, compute_uv, jacobi);
let k = m.min(n);
let (s, u, vt) = match subset_by_index {
Some(range) if !compute_uv => (slice_columns(&s, batch, k, range), u, vt),
Some(range) => (
slice_columns(&s, batch, k, range),
slice_columns(&u, batch * m, k, range),
slice_columns(&vt, batch, k * n, (range.0 * n, range.1 * n)),
),
None => (s, u, vt),
};
let s = native(s, outs[0].clone());
let uv = compute_uv.then(|| (native(u, outs[1].clone()), native(vt, outs[2].clone())));
(s, uv)
}
fn fft<T: Element, U: Element>(
x: &NativeArray<T>,
fft_type: FftType,
fft_lengths: &[usize],
) -> NativeArray<U> {
let params = Params::Fft {
fft_type,
fft_lengths: fft_lengths.to_vec(),
};
let out = check_native(p::FFT, &[x.aval()], ¶ms);
let b = ruxla_kernels::fft::fft(
&ruxla_kernels::Buffer::from_vec(x.data.to_vec()),
&x.shape,
fft_type,
fft_lengths,
);
let v = b.as_slice::<U>().expect("the result type").to_vec();
native(v, out)
}
fn dot_general<T: Element, U: Element>(
l: &NativeArray<T>,
r: &NativeArray<T>,
dims: &DotDims,
precision: Precision,
) -> NativeArray<U> {
let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
let params = Params::DotGeneral {
dimension_numbers: dims.clone(),
precision,
preferred_element_type: preferred,
};
let out = check_native(p::DOT_GENERAL, &[l.aval(), r.aval()], ¶ms);
let (lu, ru): (Vec<U>, Vec<U>) = (
l.data.iter().map(|&a| cast(a)).collect(),
r.data.iter().map(|&a| cast(a)).collect(),
);
native(k::dot_general(&lu, &l.shape, &ru, &r.shape, dims), out)
}
fn conv_general_dilated<T: Element, U: Element>(
lhs: &NativeArray<T>,
rhs: &NativeArray<T>,
window: &ConvWindow<'_>,
dims: &ConvDims,
groups: (usize, usize),
precision: Precision,
) -> NativeArray<U> {
let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
let params = conv_params(window, dims, groups, precision, preferred);
let out = check_native(p::CONV_GENERAL_DILATED, &[lhs.aval(), rhs.aval()], ¶ms);
let (lu, ru): (Vec<U>, Vec<U>) = (
lhs.data.iter().map(|&a| cast(a)).collect(),
rhs.data.iter().map(|&a| cast(a)).collect(),
);
native(
kw::conv_general_dilated(
&lu, &lhs.shape, &ru, &rhs.shape, window, dims, groups.0, groups.1,
),
out,
)
}
fn reduce_window<T: Element>(
op: ReduceOp,
x: &NativeArray<T>,
window: &Window<'_>,
) -> NativeArray<T> {
let out = check_native(reduce_window_prim(op), &[x.aval()], &window_params(window));
native(kw::reduce_window(&x.data, &x.shape, window, op), out)
}
fn select_and_scatter_add<T: Element>(
source: &NativeArray<T>,
operand: &NativeArray<T>,
select_prim: SelectPrim,
window: &Window<'_>,
) -> NativeArray<T> {
let params = select_and_scatter_add_params(select_prim, window);
let out = check_native(
p::SELECT_AND_SCATTER_ADD,
&[source.aval(), operand.aval()],
¶ms,
);
native(
kw::select_and_scatter_add(
&source.data,
&operand.data,
&operand.shape,
window.dimensions,
window.strides,
window.padding,
select_prim == SelectPrim::Ge,
),
out,
)
}
fn select_and_gather_add<T: Element>(
tangents: &NativeArray<T>,
operand: &NativeArray<T>,
select_prim: SelectPrim,
window: &Window<'_>,
) -> NativeArray<T> {
let params = select_and_gather_add_params(select_prim, window);
let out = check_native(
p::SELECT_AND_GATHER_ADD,
&[tangents.aval(), operand.aval()],
¶ms,
);
native(
kw::select_and_gather_add(
&tangents.data,
&operand.data,
&operand.shape,
window,
select_prim == SelectPrim::Ge,
),
out,
)
}
fn gather<T: Element, I: Element>(
x: &NativeArray<T>,
indices: &NativeArray<I>,
dims: &GatherDims,
sizes: &[usize],
mode: GatherScatterMode,
sorted_unique: bool,
) -> NativeArray<T> {
let params = Params::Gather {
dimension_numbers: dims.clone(),
slice_sizes: sizes.to_vec(),
mode,
indices_are_sorted: sorted_unique,
unique_indices: sorted_unique,
};
let out = check_native(p::GATHER, &[x.aval(), indices.aval()], ¶ms);
native(
k::gather(
&x.data,
&x.shape,
&starts_i64(&indices.data),
&indices.shape,
dims,
sizes,
),
out,
)
}
fn scatter<T: Element, I: Element>(
combine: Option<BinaryOp>,
x: &NativeArray<T>,
indices: &NativeArray<I>,
updates: &NativeArray<T>,
dims: &ScatterDims,
mode: GatherScatterMode,
sorted_unique: bool,
) -> NativeArray<T> {
let params = Params::Scatter {
dimension_numbers: dims.clone(),
mode,
indices_are_sorted: sorted_unique,
unique_indices: sorted_unique,
};
check_native(
scatter_prim(combine),
&[x.aval(), indices.aval(), updates.aval()],
¶ms,
);
let f = combine.map(|op| move |a: T, b: T| T::binary(op, a, b));
let f_ref: Option<&dyn Fn(T, T) -> T> = f.as_ref().map(|f| f as &dyn Fn(T, T) -> T);
native(
k::scatter(
&x.data,
&x.shape,
&starts_i64(&indices.data),
&indices.shape,
&updates.data,
&updates.shape,
dims,
mode,
f_ref,
),
x.shape.clone(),
)
}
fn cond<S: Tree<Self>, R: Tree<Self>>(
index: I32<Native>,
branches: &[&dyn Fn(S) -> R],
operand: S,
) -> R {
let n = branches.len();
let i = usize::try_from(index.value())
.ok()
.filter(|&i| i < n)
.unwrap_or(n - 1);
branches[i](operand)
}
fn while_loop<C: Tree<Self>>(
cond: &dyn Fn(&C) -> Bool<Native>,
body: &dyn Fn(C) -> C,
init: C,
) -> C {
let mut c = init;
while cond(&c).value() {
c = body(c);
}
c
}
fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
f: &dyn Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
reverse: bool,
) -> (C, Y) {
let mut x_leaves = Vec::new();
xs.flatten(&mut x_leaves);
let mut carry = init;
let mut ys: Vec<Y> = Vec::with_capacity(length);
let order: Vec<usize> = if reverse {
(0..length).rev().collect()
} else {
(0..length).collect()
};
for &i in &order {
let slices: Vec<HostArray> = x_leaves.iter().map(|x| index_leading(x, i)).collect();
let x = xs.unflatten_like(&mut slices.into_iter());
let (c, y) = f(carry, x);
carry = c;
ys.push(y);
}
if reverse {
ys.reverse();
}
if length == 0 {
let zeros: Vec<HostArray> = x_leaves
.iter()
.map(|x| HostArray::zeros(x.shape().dims()[1..].to_vec(), x.dtype()))
.collect();
let (_, y) = f(carry.clone(), xs.unflatten_like(&mut zeros.into_iter()));
let mut leaves = Vec::new();
y.flatten(&mut leaves);
let empty = leaves.iter().map(|l| {
let mut shape = vec![0];
shape.extend_from_slice(l.shape());
HostArray::zeros(shape, l.dtype())
});
return (
carry,
y.unflatten_like(&mut empty.collect::<Vec<_>>().into_iter()),
);
}
let ys = stack_trees(&ys, length);
(carry, ys)
}
#[inline]
fn a_binary_broadcast<T: Element>(
op: BinaryOp,
x: &NativeArray<T>,
y: &NativeArray<T>,
) -> Option<NativeArray<T>> {
let Some(shape) = broadcast_shape_simple(x, y) else {
return broadcast_rows(x, y, |a, b, o| ew::binary_into(op, a, b, o));
};
Some(build_all(shape.clone(), |o| {
ew::binary_into(op, &x.data, &y.data, o);
}))
}
#[inline]
fn a_compare_broadcast<T: Element>(
op: CompareOp,
x: &NativeArray<T>,
y: &NativeArray<T>,
) -> Option<NativeArray<bool>> {
let Some(shape) = broadcast_shape_simple(x, y) else {
return broadcast_rows(x, y, |a, b, o| ew::compare_into(op, a, b, o));
};
Some(build_all(shape.clone(), |o| {
ew::compare_into(op, &x.data, &y.data, o);
}))
}
#[inline]
fn a_binary_assign<T: Element>(
op: BinaryOp,
x: &mut NativeArray<T>,
y: &NativeArray<T>,
) -> bool {
let fits = y.shape == x.shape || (y.data.len() == 1 && y.shape.rank() <= x.shape.rank());
if !fits || !x.data.is_unique() {
return false;
}
ew::binary_assign(op, x.data.unique_mut(), &y.data);
true
}
#[inline]
fn a_unary_assign<T: Element>(op: UnaryOp, x: &mut NativeArray<T>) -> bool {
if !x.data.is_unique() {
return false;
}
ew::unary_assign(op, x.data.unique_mut());
true
}
fn a_select_broadcast<T: Element>(
c: &NativeArray<bool>,
x: &NativeArray<T>,
y: &NativeArray<T>,
) -> Option<NativeArray<T>> {
let mut shape: Option<&Shape> = None;
for s in [&c.shape, &x.shape, &y.shape] {
if s.rank() != 0 {
match shape {
Some(t) if t != s => return None,
_ => shape = Some(s),
}
}
}
let shape = shape?.clone();
let n = shape.size();
let pick = |a: &NativeArray<T>| {
if a.shape.rank() == 0 {
NativeArray {
data: Data::filled(n, a.data[0]),
shape: shape.clone(),
}
} else {
a.clone()
}
};
if c.shape.rank() == 0 {
return Some(pick(if c.data[0] { x } else { y }));
}
let (cd, xd, yd): (&[bool], &[T], &[T]) = (&c.data, &x.data, &y.data);
Some(build_all(shape.clone(), |o| {
match (xd.len() == n, yd.len() == n) {
(true, true) => {
for (((o, &c), &a), &b) in o.iter_mut().zip(cd).zip(xd).zip(yd) {
*o = if c { a } else { b };
}
}
(true, false) => {
for ((o, &c), &a) in o.iter_mut().zip(cd).zip(xd) {
*o = if c { a } else { yd[0] };
}
}
(false, true) => {
for ((o, &c), &b) in o.iter_mut().zip(cd).zip(yd) {
*o = if c { xd[0] } else { b };
}
}
(false, false) => {
for (o, &c) in o.iter_mut().zip(cd) {
*o = if c { xd[0] } else { yd[0] };
}
}
}
}))
}
fn a_take<T: Element, I: Element>(
x: &NativeArray<T>,
indices: &NativeArray<I>,
axis: usize,
) -> Option<NativeArray<T>> {
let dims = x.shape.dims();
let n = dims[axis];
if n == 0 {
return None;
}
let inner: usize = dims[axis + 1..].iter().product();
let outer: usize = dims[..axis].iter().product();
let mut out_dims = dims[..axis].to_vec();
out_dims.extend_from_slice(indices.shape.dims());
out_dims.extend_from_slice(&dims[axis + 1..]);
let id: &[I] = &indices.data;
let xd: &[T] = &x.data;
let row = |i: I| {
let i = cast::<I, i64>(i);
let i = if i < 0 { i + n as i64 } else { i };
i.clamp(0, n as i64 - 1) as usize
};
Some(build_all(Shape::from(out_dims), |o| {
if inner == 1 {
for (b, o) in o.chunks_exact_mut(id.len().max(1)).enumerate() {
let base = &xd[b * n..(b + 1) * n];
for (o, &i) in o.iter_mut().zip(id) {
*o = base[row(i)];
}
}
return;
}
let mut at = 0;
for b in 0..outer {
for &i in id {
let src = (b * n + row(i)) * inner;
o[at..at + inner].copy_from_slice(&xd[src..src + inner]);
at += inner;
}
}
}))
}
fn a_roll<T: Element>(x: &NativeArray<T>, shift: usize, axis: usize) -> Option<NativeArray<T>> {
let dims = x.shape.dims();
let n = dims[axis];
let inner: usize = dims[axis + 1..].iter().product();
let block = n * inner;
let (k, xd): (usize, &[T]) = (shift * inner, &x.data);
Some(build_all(x.shape.clone(), |o| {
for (o, x) in o.chunks_exact_mut(block).zip(xd.chunks_exact(block)) {
o[k..].copy_from_slice(&x[..block - k]);
o[..k].copy_from_slice(&x[block - k..]);
}
}))
}
#[inline]
fn key_from_array(data: NativeArray<u32>) -> NativeKey {
if data.shape.dims() == [2] {
NativeKey::Single([data.data[0], data.data[1]])
} else {
NativeKey::Array(Arc::new(data))
}
}
#[inline]
fn key_to_array(key: &NativeKey) -> NativeArray<u32> {
match key {
NativeKey::Single([a, b]) => build(Shape::from([2]), |o| {
o[0] = *a;
o[1] = *b;
}),
NativeKey::Array(a) => (**a).clone(),
}
}
#[inline]
fn key_rank(key: &NativeKey) -> usize {
match key {
NativeKey::Single(_) => 1,
NativeKey::Array(a) => a.shape.rank(),
}
}
fn random_uniform<T: crate::value::Float>(
key: &NativeKey,
shape: &Shape,
minval: &NativeArray<T>,
maxval: &NativeArray<T>,
) -> Option<NativeArray<T>> {
if minval.data.len() != 1 || maxval.data.len() != 1 {
return None;
}
let (lo, hi) = (minval.data[0], maxval.data[0]);
let [k1, k2] = key.words();
Some(uniform_native::<T>(k1, k2, shape, lo, hi))
}
#[inline]
fn random_uniform_scalar<T: crate::value::Float>(key: &NativeKey, lo: T, hi: T) -> Option<T> {
let [k1, k2] = key.words();
Some(uniform_one(k1, k2, lo, hi))
}
#[inline]
fn random_randint_scalar<T: crate::value::Int>(key: &NativeKey, lo: T, hi: T) -> Option<T> {
Some(randint_one(key.words(), lo, hi))
}
fn random_randint<T: crate::value::Int>(
key: &NativeKey,
shape: &Shape,
minval: &NativeArray<T>,
maxval: &NativeArray<T>,
) -> Option<NativeArray<T>> {
if minval.data.len() != 1 || maxval.data.len() != 1 {
return None;
}
let (lo, hi) = (minval.data[0], maxval.data[0]);
Some(randint_native::<T>(key.words(), shape, lo, hi))
}
fn point_update<T: Element>(
x: &NativeArray<T>,
index: &[i32],
value: &NativeArray<T>,
combine: Option<BinaryOp>,
) -> Option<NativeArray<T>> {
if index.len() != x.shape.rank() || value.data.len() != 1 {
return None;
}
let mut flat = 0usize;
for (&i, &n) in index.iter().zip(x.shape.dims()) {
let i = usize::try_from(i).ok().filter(|&i| i < n);
let Some(i) = i else {
return Some(x.clone());
};
flat = flat * n + i;
}
let v = value.data[0];
let mut data = Data::from_slice(&x.data);
let o = data.unique_mut();
o[flat] = match combine {
None => v,
Some(op) => T::binary(op, o[flat], v),
};
Some(NativeArray {
data,
shape: x.shape.clone(),
})
}
fn update_box<T: Element>(
x: &mut NativeArray<T>,
starts: &[usize],
sizes: &[usize],
values: &NativeArray<T>,
combine: Option<BinaryOp>,
) -> bool {
let rank = x.shape.rank();
let count: usize = sizes.iter().product();
if starts.len() != rank
|| sizes.len() != rank
|| (values.data.len() != count && values.data.len() != 1)
{
return false;
}
if count == 0 {
return true;
}
if rank > 8 {
return false;
}
let mut stride = [0usize; 8];
let mut base = 0;
let mut st = 1;
for d in (0..rank).rev() {
stride[d] = st;
base += starts[d] * st;
st *= x.shape[d];
}
let mut dims = [(0usize, 0usize); 8];
let mut nd = 0;
for d in 0..rank {
if sizes[d] == 1 {
continue;
}
if nd > 0 && dims[nd - 1].1 == sizes[d] * stride[d] {
dims[nd - 1] = (dims[nd - 1].0 * sizes[d], stride[d]);
} else {
dims[nd] = (sizes[d], stride[d]);
nd += 1;
}
}
let run = if nd > 0 && dims[nd - 1].1 == 1 {
nd -= 1;
dims[nd].0
} else {
1
};
let (inner, inner_stride) = if nd > 0 {
nd -= 1;
dims[nd]
} else {
(1, 0)
};
let o = x.data.make_mut();
let vals: &[T] = &values.data;
let single = vals.len() == 1;
let last = base + (inner - 1) * inner_stride + run;
let outer_extent: usize = dims[..nd].iter().map(|&(n, s)| (n - 1) * s).sum();
assert!(
last + outer_extent <= o.len(),
"the box is inside the array"
);
let mut pos = [0usize; 8];
let mut src_at = 0;
loop {
let o = &mut o[base..base + (inner - 1) * inner_stride + run];
match (run, combine) {
(1, None) => {
let p = o.as_mut_ptr();
if single {
let v = vals[0];
for k in 0..inner {
unsafe { *p.add(k * inner_stride) = v };
}
} else {
for (k, &v) in vals[src_at..src_at + inner].iter().enumerate() {
unsafe { *p.add(k * inner_stride) = v };
}
}
}
_ => {
for k in 0..inner {
let o = &mut o[k * inner_stride..k * inner_stride + run];
let src = src_at + k * run;
match combine {
None if single => o.fill(vals[0]),
None => o.copy_from_slice(&vals[src..src + run]),
Some(op) => {
for (j, e) in o.iter_mut().enumerate() {
let v = if single { vals[0] } else { vals[src + j] };
*e = T::binary(op, *e, v);
}
}
}
}
}
}
src_at += inner * run;
let mut d = nd;
loop {
if d == 0 {
return true;
}
d -= 1;
pos[d] += 1;
base += dims[d].1;
if pos[d] < dims[d].0 {
break;
}
base -= dims[d].1 * dims[d].0;
pos[d] = 0;
}
}
}
#[inline(always)]
fn point_update_in_place<T: Element>(
x: &mut NativeArray<T>,
index: &[crate::indexing::Index<Native>],
value: T,
combine: Option<BinaryOp>,
) -> bool {
use crate::indexing::Index;
if index.len() != x.shape.rank() {
return false;
}
let mut flat = 0usize;
let mut in_bounds = true;
for (component, &n) in index.iter().zip(x.shape.dims()) {
let i = match *component {
Index::Int(i) => i,
Index::Dynamic(s) => i64::from(s.value()),
_ => return false,
};
let i = if i < 0 { i + n as i64 } else { i };
match usize::try_from(i).ok().filter(|&i| i < n) {
Some(i) => flat = flat * n + i,
None => in_bounds = false,
}
}
if in_bounds {
let o = x.data.make_mut();
let e = unsafe { o.get_unchecked_mut(flat) };
*e = match combine {
None => value,
Some(op) => T::binary(op, *e, value),
};
}
true
}
#[inline]
fn index_leading<T: Element>(x: &NativeArray<T>, index: &[usize]) -> Option<NativeArray<T>> {
let dims = x.shape.dims();
let (lead, rest) = dims.split_at(index.len());
let mut flat = 0;
for (&i, &n) in index.iter().zip(lead) {
flat = flat * n + i;
}
let inner: usize = rest.iter().product();
Some(NativeArray {
data: Data::from_slice(&x.data[flat * inner..(flat + 1) * inner]),
shape: Shape::from(rest),
})
}
#[inline]
fn key_split2(key: &NativeKey) -> Option<(NativeKey, NativeKey)> {
let [k1, k2] = key.words();
let (a, b) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
Some((
NativeKey::Single([a[0], b[0]]),
NativeKey::Single([a[1], b[1]]),
))
}
#[inline]
fn stack_scalars<T: Element>(
n: usize,
mut scalar: impl FnMut(usize) -> T,
) -> Option<NativeArray<T>> {
Some(build(Shape::from([n]), |o| {
for (i, o) in o.iter_mut().enumerate() {
*o = scalar(i);
}
}))
}
#[inline]
fn rank<T: Element>(x: &NativeArray<T>) -> usize {
x.shape.rank()
}
#[inline]
fn dims<T: Element>(x: &NativeArray<T>) -> Option<&[usize]> {
Some(x.shape.dims())
}
fn slice_box<T: Element>(
x: &NativeArray<T>,
starts: &[usize],
sizes: &[usize],
out: Shape,
) -> Option<NativeArray<T>> {
copy_box(x, starts, sizes, out)
}
fn sort_key_val_typed<K: Element, V: Element>(
keys: &NativeArray<K>,
values: &NativeArray<V>,
dimension: usize,
) -> Option<(NativeArray<K>, NativeArray<V>)> {
let dims = keys.shape.dims();
if keys.shape != values.shape || dimension >= dims.len() {
return None;
}
let n = dims[dimension];
let inner: usize = dims[dimension + 1..].iter().product();
let total = keys.data.len();
let kd: &[K] = &keys.data;
let mut perm = vec![0usize; total];
let mut line: Vec<usize> = Vec::with_capacity(n);
let outer = total.checked_div(n * inner).unwrap_or(0);
for o in 0..outer {
for i in 0..inner {
let base = o * n * inner + i;
line.clear();
line.extend((0..n).map(|k| base + k * inner));
line.sort_by(|&a, &b| ruxla_kernels::array::sort_order(kd[a], kd[b]));
for (k, &src) in line.iter().enumerate() {
perm[base + k * inner] = src;
}
}
}
let vd: &[V] = &values.data;
let k = build_all(keys.shape.clone(), |out| {
for (o, &p) in out.iter_mut().zip(&perm) {
*o = kd[p];
}
});
let v = build_all(values.shape.clone(), |out| {
for (o, &p) in out.iter_mut().zip(&perm) {
*o = vd[p];
}
});
Some((k, v))
}
#[inline]
fn full<T: Element>(shape: Shape, value: T) -> Option<NativeArray<T>> {
Some(NativeArray {
data: Data::filled(shape.size(), value),
shape,
})
}
#[inline]
fn int_value(x: i32) -> Option<i64> {
Some(i64::from(x))
}
#[inline]
fn branch_value(pred: Bool<Native>) -> Option<bool> {
Some(pred.value())
}
#[inline]
fn element<T: Element>(x: &NativeArray<T>, flat: usize) -> Option<T> {
Some(x.data[flat])
}
fn stack0<T: Element>(xs: &[NativeArray<T>]) -> Option<NativeArray<T>> {
let first = xs.first()?;
if xs.iter().any(|x| x.shape != first.shape) {
return None;
}
let mut shape = first.shape.clone();
shape.insert(0, xs.len());
Some(build(shape, |o| {
let n = first.data.len();
for (chunk, x) in o.chunks_exact_mut(n.max(1)).zip(xs) {
chunk.copy_from_slice(&x.data);
}
}))
}
fn key_split(key: &NativeKey, num: usize) -> NativeKey {
let [k1, k2] = key.words();
NativeKey::Array(Arc::new(build(Shape::from([num, 2]), |o| {
hash_counters(k1, k2, num, |i, a, b| {
o[2 * i] = a;
o[2 * i + 1] = b;
});
})))
}
fn key_fold_in(key: &NativeKey, data: u32) -> NativeKey {
let [k1, k2] = key.words();
let (a, b) = threefry2x32_scalar(k1, k2, 0, data);
NativeKey::Single([a, b])
}
fn key_bits(key: &NativeKey, shape: &[usize]) -> (NativeArray<u32>, NativeArray<u32>) {
let [k1, k2] = key.words();
let shape = Shape::from(shape);
let n = shape.size();
let mut a = build(shape.clone(), |_| {});
let mut b = build(shape, |_| {});
{
let (oa, ob) = (a.data.unique_mut(), b.data.unique_mut());
hash_counters(k1, k2, n, |i, x, y| {
oa[i] = x;
ob[i] = y;
});
}
(a, b)
}
fn threefry2x32(
k1: &NativeArray<u32>,
k2: &NativeArray<u32>,
x1: &NativeArray<u32>,
x2: &NativeArray<u32>,
) -> (NativeArray<u32>, NativeArray<u32>) {
let shape = [k1, k2, x1, x2]
.iter()
.map(|x| &x.shape)
.find(|s| s.rank() > 0)
.cloned()
.unwrap_or_else(Shape::scalar);
let at = |x: &NativeArray<u32>, i: usize| {
if x.data.len() == 1 {
x.data[0]
} else {
x.data[i]
}
};
let (y1, y2): (Vec<u32>, Vec<u32>) = (0..shape.size())
.map(|i| threefry2x32_scalar(at(k1, i), at(k2, i), at(x1, i), at(x2, i)))
.unzip();
(native(y1, shape.clone()), native(y2, shape))
}
fn fori_loop<C: Tree<Self>>(
lo: I32<Native>,
hi: I32<Native>,
body: &dyn Fn(I32<Native>, C) -> C,
init: C,
) -> C {
let mut c = init;
for i in lo.value()..hi.value() {
c = body(Scalar::new(i), c);
}
c
}
fn scalar_leaf<T: Element>(x: T) -> HostArray {
HostArray::scalar(x)
}
#[track_caller]
fn leaf_scalar<T: Element>(l: HostArray) -> T {
assert_eq!(
l.shape().rank(),
0,
"expected a scalar leaf, got {:?}",
l.aval()
);
l.as_slice::<T>().unwrap_or_else(|e| panic!("{e}"))[0]
}
fn array_leaf<T: Element>(x: &NativeArray<T>) -> HostArray {
x.to_host()
}
fn leaf_array<T: Element>(l: HostArray) -> NativeArray<T> {
NativeArray::from_host(&l)
}
fn leaf_aval(l: &HostArray) -> AVal {
l.aval()
}
#[track_caller]
fn host_callback(
callback: &ruxla_ir::callback::HostCallback,
args: &[HostArray],
outputs: &[AVal],
) -> Vec<HostArray> {
let results = callback
.call(args)
.unwrap_or_else(|m| panic!("the host callback `{}` failed: {m}", callback.name()));
let got: Vec<AVal> = results.iter().map(HostArray::aval).collect();
assert_eq!(
got,
outputs,
"the host callback `{}` returned other types than declared",
callback.name()
);
results
}
}
impl<T: Element> NativeArray<T> {
fn aval(&self) -> AVal {
AVal::new(self.shape.clone(), T::DTYPE)
}
}
fn cumulative_prim(op: CumulativeOp) -> ruxla_ir::Prim {
match op {
CumulativeOp::Sum => p::CUMSUM,
CumulativeOp::Prod => p::CUMPROD,
CumulativeOp::Max => p::CUMMAX,
CumulativeOp::Min => p::CUMMIN,
CumulativeOp::LogSumExp => p::CUMLOGSUMEXP,
}
}
#[track_caller]
fn check_native_all(prim: ruxla_ir::Prim, inputs: &[AVal], params: &Params) -> Vec<Shape> {
prim.abstract_eval(inputs, params)
.unwrap_or_else(|e| panic!("{e}"))
.into_iter()
.map(|a| a.shape)
.collect()
}
fn slice_columns<E: Copy>(
x: &[E],
rows: usize,
cols: usize,
(start, end): (usize, usize),
) -> Vec<E> {
(0..rows)
.flat_map(|r| x[r * cols + start..r * cols + end].iter().copied())
.collect()
}
fn matrix_dims(shape: &Shape) -> (usize, usize, usize) {
let d = shape.dims();
let r = d.len();
(d[..r - 2].iter().product(), d[r - 2], d[r - 1])
}
fn triangular_solve_params(o: TriangularSolveOptions) -> Params {
Params::TriangularSolve {
left_side: o.left_side,
lower: o.lower,
transpose_a: o.transpose_a,
conjugate_a: o.conjugate_a,
unit_diagonal: o.unit_diagonal,
}
}
#[track_caller]
fn check_native(prim: ruxla_ir::Prim, inputs: &[AVal], params: &Params) -> Shape {
prim.abstract_eval(inputs, params)
.unwrap_or_else(|e| panic!("{e}"))
.remove(0)
.shape
}
fn conv_params(
window: &ConvWindow<'_>,
dims: &ConvDims,
groups: (usize, usize),
precision: Precision,
preferred_element_type: Option<ruxla_ir::DType>,
) -> Params {
Params::ConvGeneralDilated {
window_strides: window.strides.to_vec(),
padding: window.padding.to_vec(),
lhs_dilation: window.lhs_dilation.to_vec(),
rhs_dilation: window.rhs_dilation.to_vec(),
dimension_numbers: dims.clone(),
feature_group_count: groups.0,
batch_group_count: groups.1,
precision,
preferred_element_type,
}
}
fn reduce_window_prim(op: ReduceOp) -> ruxla_ir::Prim {
match op {
ReduceOp::Sum => p::REDUCE_WINDOW_SUM,
ReduceOp::Max => p::REDUCE_WINDOW_MAX,
ReduceOp::Min => p::REDUCE_WINDOW_MIN,
}
}
fn window_params(w: &Window<'_>) -> Params {
Params::ReduceWindow {
window_dimensions: w.dimensions.to_vec(),
window_strides: w.strides.to_vec(),
padding: w.padding.to_vec(),
base_dilation: w.base_dilation.to_vec(),
window_dilation: w.window_dilation.to_vec(),
}
}
#[track_caller]
fn select_and_scatter_add_params(select_prim: SelectPrim, w: &Window<'_>) -> Params {
assert!(
w.base_dilation
.iter()
.chain(w.window_dilation)
.all(|&d| d == 1),
"select_and_scatter_add has no dilation"
);
Params::SelectAndScatterAdd {
select_prim,
window_dimensions: w.dimensions.to_vec(),
window_strides: w.strides.to_vec(),
padding: w.padding.to_vec(),
}
}
fn select_and_gather_add_params(select_prim: SelectPrim, w: &Window<'_>) -> Params {
Params::SelectAndGatherAdd {
select_prim,
window_dimensions: w.dimensions.to_vec(),
window_strides: w.strides.to_vec(),
padding: w.padding.to_vec(),
base_dilation: w.base_dilation.to_vec(),
window_dilation: w.window_dilation.to_vec(),
}
}
#[track_caller]
fn same_shape(op: &str, a: &Shape, b: &Shape) {
assert!(
a == b,
"{op}: operands must have the same shape, got [{a}] and [{b}]"
);
}
fn scatter_prim(combine: Option<BinaryOp>) -> ruxla_ir::Prim {
match combine {
None => p::SCATTER,
Some(BinaryOp::Add) => p::SCATTER_ADD,
Some(BinaryOp::Mul) => p::SCATTER_MUL,
Some(BinaryOp::Min) => p::SCATTER_MIN,
Some(BinaryOp::Max) => p::SCATTER_MAX,
Some(op) => panic!("no scatter combines with {}", op.name()),
}
}
fn index_leading(x: &HostArray, i: usize) -> HostArray {
let inner: usize = x.shape().dims()[1..].iter().product();
let b = ruxla_kernels::with_buffer!(x.buffer(), |v| ruxla_kernels::Buffer::from_vec(
v[i * inner..(i + 1) * inner].to_vec()
));
HostArray::from_buffer(b, x.shape().dims()[1..].to_vec())
}
#[inline]
fn threefry2x32_scalar(k1: u32, k2: u32, x1: u32, x2: u32) -> (u32, u32) {
const ROTATIONS: [[u32; 4]; 2] = [[13, 15, 26, 6], [17, 29, 16, 24]];
let ks = [k1, k2, k1 ^ k2 ^ 0x1BD1_1BDA];
let mut x = [x1.wrapping_add(ks[0]), x2.wrapping_add(ks[1])];
for i in 0..5 {
for &r in &ROTATIONS[i % 2] {
x[0] = x[0].wrapping_add(x[1]);
x[1] = x[1].rotate_left(r) ^ x[0];
}
x[0] = x[0].wrapping_add(ks[(i + 1) % 3]);
x[1] = x[1]
.wrapping_add(ks[(i + 2) % 3])
.wrapping_add(i as u32 + 1);
}
(x[0], x[1])
}
#[inline(always)]
fn threefry2x32_lanes<const N: usize>(
k1: u32,
k2: u32,
x1: [u32; N],
x2: [u32; N],
) -> ([u32; N], [u32; N]) {
threefry2x32_lanes_keys([k1; N], [k2; N], x1, x2)
}
#[inline(always)]
fn threefry2x32_lanes_keys<const N: usize>(
k1: [u32; N],
k2: [u32; N],
x1: [u32; N],
x2: [u32; N],
) -> ([u32; N], [u32; N]) {
let k3: [u32; N] = std::array::from_fn(|j| k1[j] ^ k2[j] ^ 0x1BD1_1BDA);
let ks = [k1, k2, k3];
let mut a = x1;
let mut b = x2;
for j in 0..N {
a[j] = a[j].wrapping_add(k1[j]);
b[j] = b[j].wrapping_add(k2[j]);
}
macro_rules! round {
($r:expr) => {
for j in 0..N {
a[j] = a[j].wrapping_add(b[j]);
b[j] = b[j].rotate_left($r) ^ a[j];
}
};
}
macro_rules! inject {
($i:expr) => {
for j in 0..N {
a[j] = a[j].wrapping_add(ks[($i + 1) % 3][j]);
b[j] = b[j].wrapping_add(ks[($i + 2) % 3][j]).wrapping_add($i + 1);
}
};
}
macro_rules! even {
($i:expr) => {
round!(13);
round!(15);
round!(26);
round!(6);
inject!($i);
};
}
macro_rules! odd {
($i:expr) => {
round!(17);
round!(29);
round!(16);
round!(24);
inject!($i);
};
}
even!(0);
odd!(1);
even!(2);
odd!(3);
even!(4);
(a, b)
}
#[inline(always)]
fn hash_counters(k1: u32, k2: u32, n: usize, mut f: impl FnMut(usize, u32, u32)) {
for i in 0..n {
let (a, b) = threefry2x32_scalar(k1, k2, ((i as u64) >> 32) as u32, i as u32);
f(i, a, b);
}
}
#[inline(always)]
fn bits_from_hash(b1: u32, b2: u32, nbits: usize) -> u64 {
match nbits {
64 => (u64::from(b1) << 32) | u64::from(b2),
32 => u64::from(b1 ^ b2),
16 => u64::from((b1 ^ b2) as u16),
_ => u64::from((b1 ^ b2) as u8),
}
}
fn uniform_native<T: Element>(k1: u32, k2: u32, shape: &Shape, lo: T, hi: T) -> NativeArray<T> {
let (nbits, nmant) = match T::DTYPE {
ruxla_ir::DType::F16 => (16, 10),
ruxla_ir::DType::BF16 => (16, 7),
ruxla_ir::DType::F32 => (32, 23),
_ => (64, 52),
};
let rng_bits = if nmant < 8 { 8 } else { nbits };
let shift = (rng_bits - nmant) as u32;
let one: T = cast::<u8, T>(1);
let one_bits = one.to_bits();
let span = T::binary(BinaryOp::Sub, hi, lo);
build(shape.clone(), |o| {
hash_counters(k1, k2, o.len(), |i, b1, b2| {
let float_bits = (bits_from_hash(b1, b2, rng_bits) >> shift) | one_bits;
let floats = T::binary(BinaryOp::Sub, T::from_bits(float_bits), one);
let scaled = T::binary(BinaryOp::Add, T::binary(BinaryOp::Mul, floats, span), lo);
o[i] = T::binary(BinaryOp::Max, lo, scaled);
});
})
}
#[inline]
fn uniform_one<T: Element>(k1: u32, k2: u32, lo: T, hi: T) -> T {
let (nbits, nmant) = match T::DTYPE {
ruxla_ir::DType::F16 => (16, 10),
ruxla_ir::DType::BF16 => (16, 7),
ruxla_ir::DType::F32 => (32, 23),
_ => (64, 52),
};
let rng_bits = if nmant < 8 { 8 } else { nbits };
let one: T = cast::<u8, T>(1);
let (b1, b2) = threefry2x32_scalar(k1, k2, 0, 0);
let float_bits = (bits_from_hash(b1, b2, rng_bits) >> (rng_bits - nmant)) | one.to_bits();
let floats = T::binary(BinaryOp::Sub, T::from_bits(float_bits), one);
let span = T::binary(BinaryOp::Sub, hi, lo);
let scaled = T::binary(BinaryOp::Add, T::binary(BinaryOp::Mul, floats, span), lo);
T::binary(BinaryOp::Max, lo, scaled)
}
#[inline]
fn randint_one<T: Element>(key: [u32; 2], lo: T, hi: T) -> T {
let nbits = T::DTYPE.size_in_bytes() * 8;
let mask = if nbits == 64 {
u64::MAX
} else {
(1u64 << nbits) - 1
};
let [k1, k2] = key;
let (s1, s2) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
let (a, b) = threefry2x32_lanes_keys([s1[0], s1[1]], [s2[0], s2[1]], [0, 0], [0, 0]);
let span = if hi <= lo {
1
} else {
T::binary(BinaryOp::Sub, hi, lo).to_bits() & mask
};
let half = (1u64 << (nbits / 2)) & mask;
let multiplier = half % span;
let multiplier = (multiplier.wrapping_mul(multiplier) & mask) % span;
let higher = bits_from_hash(a[0], b[0], nbits);
let lower = bits_from_hash(a[1], b[1], nbits);
let offset =
((higher % span).wrapping_mul(multiplier) & mask).wrapping_add(lower % span) & mask;
T::binary(BinaryOp::Add, lo, T::from_bits(offset % span))
}
fn randint_native<T: Element>(key: [u32; 2], shape: &Shape, lo: T, hi: T) -> NativeArray<T> {
let nbits = T::DTYPE.size_in_bytes() * 8;
let mask = if nbits == 64 {
u64::MAX
} else {
(1u64 << nbits) - 1
};
let [k1, k2] = key;
let (s1, s2) = threefry2x32_lanes(k1, k2, [0, 0], [0, 1]);
let (h1, h2, l1, l2) = (s1[0], s2[0], s1[1], s2[1]);
let span = if hi <= lo {
1
} else {
T::binary(BinaryOp::Sub, hi, lo).to_bits() & mask
};
let half = (1u64 << (nbits / 2)) & mask;
let multiplier = half % span;
let multiplier = (multiplier.wrapping_mul(multiplier) & mask) % span;
build(shape.clone(), |o| {
for (i, o) in o.iter_mut().enumerate() {
let c = [(i as u64 >> 32) as u32; 2];
let (a, b) = threefry2x32_lanes_keys([h1, l1], [h2, l2], c, [i as u32; 2]);
let higher = bits_from_hash(a[0], b[0], nbits);
let lower = bits_from_hash(a[1], b[1], nbits);
let offset =
((higher % span).wrapping_mul(multiplier) & mask).wrapping_add(lower % span) & mask;
*o = T::binary(BinaryOp::Add, lo, T::from_bits(offset % span));
}
})
}
fn stack_trees<Y: Tree<Native>>(ys: &[Y], length: usize) -> Y {
let first = &ys[0];
let per: Vec<Vec<HostArray>> = ys
.iter()
.map(|y| {
let mut l = Vec::new();
y.flatten(&mut l);
l
})
.collect();
let stacked: Vec<HostArray> = (0..per[0].len())
.map(|j| {
let parts: Vec<&HostArray> = per.iter().map(|l| &l[j]).collect();
let mut shape = vec![length];
shape.extend_from_slice(parts[0].shape());
let b = ruxla_kernels::with_buffer!(parts[0].buffer(), |v0| {
let mut all = v0.clone();
for p in &parts[1..] {
all.extend_from_slice(p.as_slice().expect("same types"));
}
ruxla_kernels::Buffer::from_vec(all)
});
HostArray::from_buffer(b, shape)
})
.collect();
first.unflatten_like(&mut stacked.into_iter())
}
fn bind1(prim: ruxla_ir::Prim, inputs: &[TraceRef], params: Params) -> TraceRef {
trace::bind(prim, inputs, params).remove(0)
}
impl Backend for Trace {
type Scalar<T: Element> = TraceRef;
type Array<T: Element> = TraceRef;
type Leaf = TraceRef;
type KeyData = TraceRef;
fn lit<T: Element>(v: T) -> TraceRef {
trace::literal(HostArray::scalar(v))
}
fn unary<T: Element>(op: UnaryOp, x: TraceRef) -> TraceRef {
if op == UnaryOp::Abs && T::DTYPE.kind() == DTypeKind::UnsignedInt {
return x;
}
let (prim, params) = p::unary_prim(op);
bind1(prim, &[x], params)
}
fn binary<T: Element>(op: BinaryOp, x: TraceRef, y: TraceRef) -> TraceRef {
bind1(p::binary_prim(op), &[x, y], Params::None)
}
fn compare<T: Element>(op: CompareOp, x: TraceRef, y: TraceRef) -> TraceRef {
bind1(p::compare_prim(op), &[x, y], Params::None)
}
fn is_finite<T: Element>(x: TraceRef) -> TraceRef {
bind1(p::IS_FINITE, &[x], Params::None)
}
fn integer_pow<T: Element>(x: TraceRef, y: i32) -> TraceRef {
bind1(p::INTEGER_POW, &[x], Params::IntegerPow { y })
}
fn select<T: Element>(c: TraceRef, t: TraceRef, f: TraceRef) -> TraceRef {
bind1(p::SELECT_N, &[c, f, t], Params::None)
}
fn cast<T: Element, U: Element>(x: TraceRef) -> TraceRef {
if T::DTYPE == U::DTYPE {
return x;
}
if let Some(v) = trace::literal_value(x) {
return trace::literal(v.convert(U::DTYPE));
}
bind1(
p::CONVERT_ELEMENT_TYPE,
&[x],
Params::Convert {
new_dtype: U::DTYPE,
},
)
}
fn bitcast<T: Element, U: Element>(x: TraceRef) -> TraceRef {
bind1(
p::BITCAST_CONVERT_TYPE,
&[x],
Params::Convert {
new_dtype: U::DTYPE,
},
)
}
fn to_real<T: Element>(op: ToReal, x: TraceRef) -> TraceRef {
match op {
ToReal::Abs => Self::unary::<T>(UnaryOp::Abs, x),
ToReal::Real => bind1(p::REAL, &[x], Params::None),
ToReal::Imag => bind1(p::IMAG, &[x], Params::None),
}
}
fn complex<C: Element>(re: TraceRef, im: TraceRef) -> TraceRef {
bind1(p::COMPLEX, &[re, im], Params::None)
}
fn conj<T: Element>(x: TraceRef) -> TraceRef {
bind1(p::CONJ, &[x], Params::None)
}
fn constant<T: Element>(x: &NativeArray<T>) -> TraceRef {
trace::constant(x.to_host())
}
fn shape<T: Element>(x: &TraceRef) -> Shape {
trace::aval(*x).shape
}
fn to_array<T: Element>(x: TraceRef) -> TraceRef {
x
}
#[track_caller]
fn to_scalar<T: Element>(x: &TraceRef) -> TraceRef {
let a = trace::aval(*x);
assert_eq!(a.shape.rank(), 0, "expected a scalar, got {a}");
*x
}
fn a_unary<T: Element>(op: UnaryOp, x: &TraceRef) -> TraceRef {
Self::unary::<T>(op, *x)
}
fn a_binary<T: Element>(op: BinaryOp, x: &TraceRef, y: &TraceRef) -> TraceRef {
Self::binary::<T>(op, *x, *y)
}
fn a_ternary<T: Element>(op: TernaryOp, x: &TraceRef, y: &TraceRef, z: &TraceRef) -> TraceRef {
bind1(p::ternary_prim(op), &[*x, *y, *z], Params::None)
}
fn a_compare<T: Element>(op: CompareOp, x: &TraceRef, y: &TraceRef) -> TraceRef {
Self::compare::<T>(op, *x, *y)
}
fn a_is_finite<T: Element>(x: &TraceRef) -> TraceRef {
Self::is_finite::<T>(*x)
}
fn a_integer_pow<T: Element>(x: &TraceRef, y: i32) -> TraceRef {
Self::integer_pow::<T>(*x, y)
}
fn a_cast<T: Element, U: Element>(x: &TraceRef) -> TraceRef {
Self::cast::<T, U>(*x)
}
fn a_bitcast<T: Element, U: Element>(x: &TraceRef) -> TraceRef {
Self::bitcast::<T, U>(*x)
}
fn a_to_real<T: Element>(op: ToReal, x: &TraceRef) -> TraceRef {
Self::to_real::<T>(op, *x)
}
fn a_complex<C: Element>(re: &TraceRef, im: &TraceRef) -> TraceRef {
Self::complex::<C>(*re, *im)
}
fn a_conj<T: Element>(x: &TraceRef) -> TraceRef {
Self::conj::<T>(*x)
}
fn a_select<T: Element>(c: &TraceRef, t: &TraceRef, f: &TraceRef) -> TraceRef {
bind1(p::SELECT_N, &[*c, *f, *t], Params::None)
}
fn a_clamp<T: Element>(lo: &TraceRef, x: &TraceRef, hi: &TraceRef) -> TraceRef {
bind1(p::CLAMP, &[*lo, *x, *hi], Params::None)
}
fn broadcast_in_dim<T: Element>(x: &TraceRef, shape: &[usize], dims: &[usize]) -> TraceRef {
bind1(
p::BROADCAST_IN_DIM,
&[*x],
Params::BroadcastInDim {
shape: shape.into(),
broadcast_dimensions: dims.to_vec(),
},
)
}
fn reshape<T: Element>(x: &TraceRef, shape: &[usize]) -> TraceRef {
bind1(
p::RESHAPE,
&[*x],
Params::Reshape {
new_sizes: shape.into(),
},
)
}
fn transpose<T: Element>(x: &TraceRef, perm: &[usize]) -> TraceRef {
bind1(
p::TRANSPOSE,
&[*x],
Params::Transpose {
permutation: perm.to_vec(),
},
)
}
fn slice<T: Element>(
x: &TraceRef,
start: &[usize],
limit: &[usize],
strides: &[usize],
) -> TraceRef {
bind1(
p::SLICE,
&[*x],
Params::Slice {
start_indices: start.to_vec(),
limit_indices: limit.to_vec(),
strides: strides.to_vec(),
},
)
}
fn dynamic_slice<T: Element, I: Element>(
x: &TraceRef,
starts: &[TraceRef],
sizes: &[usize],
) -> TraceRef {
let mut inputs = vec![*x];
inputs.extend_from_slice(starts);
bind1(
p::DYNAMIC_SLICE,
&inputs,
Params::DynamicSlice {
slice_sizes: sizes.to_vec(),
},
)
}
fn dynamic_update_slice<T: Element, I: Element>(
x: &TraceRef,
update: &TraceRef,
starts: &[TraceRef],
) -> TraceRef {
let mut inputs = vec![*x, *update];
inputs.extend_from_slice(starts);
bind1(p::DYNAMIC_UPDATE_SLICE, &inputs, Params::None)
}
fn concatenate<T: Element>(xs: &[TraceRef], dim: usize) -> TraceRef {
bind1(p::CONCATENATE, xs, Params::Concatenate { dimension: dim })
}
fn pad<T: Element>(x: &TraceRef, value: TraceRef, config: &[(i64, i64, usize)]) -> TraceRef {
bind1(
p::PAD,
&[*x, value],
Params::Pad {
padding_config: config.to_vec(),
},
)
}
fn rev<T: Element>(x: &TraceRef, dims: &[usize]) -> TraceRef {
bind1(
p::REV,
&[*x],
Params::Rev {
dimensions: dims.to_vec(),
},
)
}
fn iota<T: Element>(shape: &[usize], dim: usize) -> TraceRef {
bind1(
p::IOTA,
&[],
Params::Iota {
dtype: T::DTYPE,
shape: shape.into(),
dimension: dim,
},
)
}
fn reduce<T: Element>(op: ReduceOp, x: &TraceRef, axes: &[usize]) -> TraceRef {
let prim = match op {
ReduceOp::Sum => p::REDUCE_SUM,
ReduceOp::Max => p::REDUCE_MAX,
ReduceOp::Min => p::REDUCE_MIN,
};
bind1(
prim,
&[*x],
Params::Reduce {
axes: axes.to_vec(),
},
)
}
fn arg_min_max<T: Element, I: Element>(x: &TraceRef, axis: usize, max: bool) -> TraceRef {
let prim = if max { p::ARGMAX } else { p::ARGMIN };
bind1(
prim,
&[*x],
Params::ArgMinMax {
axis,
index_dtype: I::DTYPE,
},
)
}
fn sort(
operands: &[TraceRef],
dimension: usize,
is_stable: bool,
num_keys: usize,
) -> Vec<TraceRef> {
trace::bind(
p::SORT,
operands,
Params::Sort {
dimension,
is_stable,
num_keys,
},
)
}
fn cumulative<T: Element>(
op: CumulativeOp,
x: &TraceRef,
axis: usize,
reverse: bool,
) -> TraceRef {
bind1(
cumulative_prim(op),
&[*x],
Params::Cumulative { axis, reverse },
)
}
fn fft<T: Element, U: Element>(
x: &TraceRef,
fft_type: FftType,
fft_lengths: &[usize],
) -> TraceRef {
bind1(
p::FFT,
&[*x],
Params::Fft {
fft_type,
fft_lengths: fft_lengths.to_vec(),
},
)
}
fn top_k<T: Element>(x: &TraceRef, k: usize, axis: usize) -> (TraceRef, TraceRef) {
let out = trace::bind(
p::TOP_K,
&[*x],
Params::TopK {
k,
axis,
is_stable: true,
},
);
(out[0], out[1])
}
fn cholesky<T: LinalgScalar>(x: &TraceRef) -> TraceRef {
bind1(p::CHOLESKY, &[*x], Params::None)
}
fn triangular_solve<T: LinalgScalar>(
a: &TraceRef,
b: &TraceRef,
options: TriangularSolveOptions,
) -> TraceRef {
bind1(
p::TRIANGULAR_SOLVE,
&[*a, *b],
triangular_solve_params(options),
)
}
fn lu<T: LinalgScalar>(x: &TraceRef) -> (TraceRef, TraceRef, TraceRef) {
let out = trace::bind(p::LU, &[*x], Params::None);
(out[0], out[1], out[2])
}
fn lu_pivots_to_permutation(pivots: &TraceRef, size: usize) -> TraceRef {
bind1(
p::LU_PIVOTS_TO_PERMUTATION,
&[*pivots],
Params::LuPivotsToPermutation {
permutation_size: size,
},
)
}
fn qr<T: LinalgScalar>(x: &TraceRef, full_matrices: bool) -> (TraceRef, TraceRef) {
let out = trace::bind(
p::QR,
&[*x],
Params::Qr {
full_matrices,
pivoting: false,
},
);
(out[0], out[1])
}
fn qr_pivoting<T: LinalgScalar>(
x: &TraceRef,
full_matrices: bool,
) -> (TraceRef, TraceRef, TraceRef) {
let out = trace::bind(
p::QR,
&[*x],
Params::Qr {
full_matrices,
pivoting: true,
},
);
(out[0], out[1], out[2])
}
fn eigh<T: LinalgScalar>(
x: &TraceRef,
lower: bool,
sort_eigenvalues: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<EighImplementation>,
) -> (TraceRef, TraceRef) {
let out = trace::bind(
p::EIGH,
&[*x],
Params::Eigh {
lower,
sort_eigenvalues,
subset_by_index,
algorithm,
},
);
(out[0], out[1])
}
fn schur<T: LinalgScalar>(
x: &TraceRef,
compute_schur_vectors: bool,
) -> (TraceRef, Option<TraceRef>) {
let out = trace::bind(
p::SCHUR,
&[*x],
Params::Schur {
compute_schur_vectors,
},
);
(out[0], compute_schur_vectors.then(|| out[1]))
}
fn hessenberg<T: LinalgScalar>(x: &TraceRef) -> (TraceRef, TraceRef) {
let out = trace::bind(p::HESSENBERG, &[*x], Params::None);
(out[0], out[1])
}
fn householder_product<T: LinalgScalar>(a: &TraceRef, taus: &TraceRef) -> TraceRef {
bind1(p::HOUSEHOLDER_PRODUCT, &[*a, *taus], Params::None)
}
fn ormqr<T: LinalgScalar>(
a: &TraceRef,
taus: &TraceRef,
c: &TraceRef,
left: bool,
transpose: bool,
) -> TraceRef {
bind1(
p::ORMQR,
&[*a, *taus, *c],
Params::Ormqr { left, transpose },
)
}
fn cholesky_update<T: LinalgFloat>(r: &TraceRef, w: &TraceRef) -> TraceRef {
bind1(p::CHOLESKY_UPDATE, &[*r, *w], Params::None)
}
fn symmetric_product<T: LinalgFloat>(
a: &TraceRef,
c: &TraceRef,
alpha: f64,
beta: f64,
) -> TraceRef {
bind1(
p::SYMMETRIC_PRODUCT,
&[*a, *c],
Params::SymmetricProduct { alpha, beta },
)
}
fn tridiagonal<T: LinalgScalar>(
x: &TraceRef,
lower: bool,
) -> (TraceRef, TraceRef, TraceRef, TraceRef) {
let out = trace::bind(p::TRIDIAGONAL, &[*x], Params::Tridiagonal { lower });
(out[0], out[1], out[2], out[3])
}
fn tridiagonal_solve<T: LinalgScalar>(
dl: &TraceRef,
d: &TraceRef,
du: &TraceRef,
b: &TraceRef,
perturb_singular: bool,
) -> TraceRef {
bind1(
p::TRIDIAGONAL_SOLVE,
&[*dl, *d, *du, *b],
Params::TridiagonalSolve { perturb_singular },
)
}
fn eig<T: LinalgScalar>(
x: &TraceRef,
left: bool,
right: bool,
enable_eigvec_derivs: bool,
) -> (TraceRef, Option<TraceRef>, Option<TraceRef>) {
let out = trace::bind(
p::EIG,
&[*x],
Params::Eig {
compute_left_eigenvectors: left,
compute_right_eigenvectors: right,
enable_eigvec_derivs,
},
);
let vl = left.then(|| out[1]);
let vr = right.then(|| out[out.len() - 1]);
(out[0], vl, vr)
}
fn svd<T: LinalgScalar>(
x: &TraceRef,
full_matrices: bool,
compute_uv: bool,
subset_by_index: Option<(usize, usize)>,
algorithm: Option<SvdAlgorithm>,
) -> (TraceRef, Option<(TraceRef, TraceRef)>) {
let out = trace::bind(
p::SVD,
&[*x],
Params::Svd {
full_matrices,
compute_uv,
subset_by_index,
algorithm,
},
);
(out[0], compute_uv.then(|| (out[1], out[2])))
}
fn dot_general<T: Element, U: Element>(
l: &TraceRef,
r: &TraceRef,
dims: &DotDims,
precision: Precision,
) -> TraceRef {
let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
bind1(
p::DOT_GENERAL,
&[*l, *r],
Params::DotGeneral {
dimension_numbers: dims.clone(),
precision,
preferred_element_type: preferred,
},
)
}
fn conv_general_dilated<T: Element, U: Element>(
lhs: &TraceRef,
rhs: &TraceRef,
window: &ConvWindow<'_>,
dims: &ConvDims,
groups: (usize, usize),
precision: Precision,
) -> TraceRef {
let preferred = (U::DTYPE != T::DTYPE).then_some(U::DTYPE);
bind1(
p::CONV_GENERAL_DILATED,
&[*lhs, *rhs],
conv_params(window, dims, groups, precision, preferred),
)
}
fn reduce_window<T: Element>(op: ReduceOp, x: &TraceRef, window: &Window<'_>) -> TraceRef {
bind1(reduce_window_prim(op), &[*x], window_params(window))
}
fn select_and_scatter_add<T: Element>(
source: &TraceRef,
operand: &TraceRef,
select_prim: SelectPrim,
window: &Window<'_>,
) -> TraceRef {
bind1(
p::SELECT_AND_SCATTER_ADD,
&[*source, *operand],
select_and_scatter_add_params(select_prim, window),
)
}
fn select_and_gather_add<T: Element>(
tangents: &TraceRef,
operand: &TraceRef,
select_prim: SelectPrim,
window: &Window<'_>,
) -> TraceRef {
bind1(
p::SELECT_AND_GATHER_ADD,
&[*tangents, *operand],
select_and_gather_add_params(select_prim, window),
)
}
fn gather<T: Element, I: Element>(
x: &TraceRef,
indices: &TraceRef,
dims: &GatherDims,
sizes: &[usize],
mode: GatherScatterMode,
sorted_unique: bool,
) -> TraceRef {
let params = Params::Gather {
dimension_numbers: dims.clone(),
slice_sizes: sizes.to_vec(),
mode,
indices_are_sorted: sorted_unique,
unique_indices: sorted_unique,
};
bind1(p::GATHER, &[*x, *indices], params)
}
fn scatter<T: Element, I: Element>(
combine: Option<BinaryOp>,
x: &TraceRef,
indices: &TraceRef,
updates: &TraceRef,
dims: &ScatterDims,
mode: GatherScatterMode,
sorted_unique: bool,
) -> TraceRef {
let params = Params::Scatter {
dimension_numbers: dims.clone(),
mode,
indices_are_sorted: sorted_unique,
unique_indices: sorted_unique,
};
bind1(scatter_prim(combine), &[*x, *indices, *updates], params)
}
fn cond<S: Tree<Self>, R: Tree<Self>>(
index: I32<Trace>,
branches: &[&dyn Fn(S) -> R],
operand: S,
) -> R {
crate::control::trace_cond(index, branches, operand)
}
fn while_loop<C: Tree<Self>>(
cond: &dyn Fn(&C) -> Bool<Trace>,
body: &dyn Fn(C) -> C,
init: C,
) -> C {
crate::control::trace_while(cond, body, init)
}
fn custom_jvp<I: Tree<Self>, O: Tree<Self>>(
f: &dyn Fn(I) -> O,
jvp: &dyn Fn(I, I) -> (O, O),
primals: I,
) -> O {
crate::control::trace_custom_jvp(f, jvp, primals)
}
fn custom_vjp<I: Tree<Self>, O: Tree<Self>, R: Tree<Self>>(
f: &dyn Fn(I) -> O,
fwd: &dyn Fn(I) -> (O, R),
bwd: &dyn Fn(R, O) -> I,
primals: I,
) -> O {
crate::control::trace_custom_vjp(f, fwd, bwd, primals)
}
fn checkpoint<I: Tree<Self>, O: Tree<Self>>(f: &dyn Fn(I) -> O, input: I) -> O {
crate::control::trace_checkpoint(f, input)
}
fn scan<C: Tree<Self>, X: Tree<Self>, Y: Tree<Self>>(
f: &dyn Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
reverse: bool,
) -> (C, Y) {
crate::control::trace_scan(f, init, xs, length, reverse)
}
fn fori_loop<C: Tree<Self>>(
lo: I32<Trace>,
hi: I32<Trace>,
body: &dyn Fn(I32<Trace>, C) -> C,
init: C,
) -> C {
crate::control::trace_fori_loop(lo, hi, body, init)
}
fn key_from_array(data: TraceRef) -> TraceRef {
data
}
fn key_to_array(key: &TraceRef) -> TraceRef {
*key
}
fn threefry2x32(
k1: &TraceRef,
k2: &TraceRef,
x1: &TraceRef,
x2: &TraceRef,
) -> (TraceRef, TraceRef) {
let outs = trace::bind(p::THREEFRY2X32, &[*k1, *k2, *x1, *x2], Params::None);
(outs[0], outs[1])
}
fn scalar_leaf<T: Element>(x: TraceRef) -> TraceRef {
x
}
fn leaf_scalar<T: Element>(l: TraceRef) -> TraceRef {
l
}
fn array_leaf<T: Element>(x: &TraceRef) -> TraceRef {
*x
}
fn leaf_array<T: Element>(l: TraceRef) -> TraceRef {
l
}
fn leaf_aval(l: &TraceRef) -> AVal {
trace::aval(*l)
}
fn host_callback(
callback: &ruxla_ir::callback::HostCallback,
args: &[TraceRef],
outputs: &[AVal],
) -> Vec<TraceRef> {
trace::bind(
p::HOST_CALLBACK,
args,
Params::HostCallback {
callback: callback.clone(),
outputs: outputs.to_vec(),
},
)
}
}