pub mod fft;
use ruxla_ir::{DotDims, GatherDims, GatherScatterMode, RoundingMethod, Shape};
use ruxla_kernels::{BinaryOp, Element, UnaryOp, bf16, f16};
use crate::backend::Backend;
pub mod linalg;
use crate::lax;
use crate::value::{
Array, ArrayLike, ComplexFloat, Float, Inexact, Int, Num, Numeric, Scalar, broadcast_binary,
broadcast_compare, broadcast_shapes,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Axes {
All,
Some(Vec<i64>),
Few(AxisList),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AxisList {
len: u8,
axes: [i64; 8],
}
impl AxisList {
pub fn new(axes: &[i64]) -> Option<Self> {
let mut out = AxisList {
len: axes.len() as u8,
axes: [0; 8],
};
out.axes.get_mut(..axes.len())?.copy_from_slice(axes);
Some(out)
}
pub fn as_slice(&self) -> &[i64] {
&self.axes[..usize::from(self.len)]
}
}
impl Axes {
fn of(a: &[i64]) -> Self {
AxisList::new(a).map_or_else(|| Axes::Some(a.to_vec()), Axes::Few)
}
pub fn as_slice(&self) -> Option<&[i64]> {
match self {
Axes::All => None,
Axes::Some(a) => Some(a),
Axes::Few(a) => Some(a.as_slice()),
}
}
}
pub const ALL: Axes = Axes::All;
impl From<i64> for Axes {
fn from(a: i64) -> Self {
Axes::of(&[a])
}
}
impl From<i32> for Axes {
fn from(a: i32) -> Self {
Axes::of(&[i64::from(a)])
}
}
impl From<&[i64]> for Axes {
fn from(a: &[i64]) -> Self {
Axes::of(a)
}
}
impl<const N: usize> From<[i64; N]> for Axes {
fn from(a: [i64; N]) -> Self {
Axes::of(&a)
}
}
#[track_caller]
pub(crate) fn normalize_axis(axis: i64, rank: usize) -> usize {
let r = rank as i64;
assert!(
(-r..r).contains(&axis),
"axis {axis} is out of range for rank {rank}"
);
(if axis < 0 { axis + r } else { axis }) as usize
}
impl Axes {
#[track_caller]
fn resolve(&self, rank: usize) -> Shape {
match self.as_slice() {
None => (0..rank).collect(),
Some(a) => {
let mut v: Shape = a.iter().map(|&x| normalize_axis(x, rank)).collect();
for i in 1..v.rank() {
let mut j = i;
while j > 0 && v[j - 1] > v[j] {
let (a, b) = (v[j - 1], v[j]);
v.set(j - 1, b);
v.set(j, a);
j -= 1;
}
}
v
}
}
}
}
pub fn full<B: Backend, T: Element>(
shape: impl Into<Shape>,
value: impl Into<Scalar<B, T>>,
) -> Array<B, T> {
let shape = shape.into();
let value = value.into();
if B::FAST_PATHS
&& let Some(x) = B::full::<T>(shape.clone(), value.0)
{
return Array(x);
}
let s = value.to_array();
if shape.rank() == 0 {
return s;
}
lax::broadcast_in_dim(&s, shape, &[])
}
pub fn zeros<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(0)))
}
pub fn ones<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(1)))
}
pub fn arange<B: Backend, T: Num>(n: usize) -> Array<B, T> {
lax::iota([n], 0)
}
pub fn astype<B: Backend, T: Element, U: Element>(x: impl ArrayLike<B, T>) -> Array<B, U> {
x.into_array().cast()
}
#[track_caller]
pub fn broadcast_to<B: Backend, T: Element>(
x: impl ArrayLike<B, T>,
shape: impl Into<Shape>,
) -> Array<B, T> {
x.into_array().broadcast_to(shape)
}
macro_rules! unary {
($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
$(#[$m])*
pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>) -> Array<B, T> {
x.with_array(|x| x.unary(UnaryOp::$op))
}
)*};
}
unary! { Numeric:
negative => Neg;
sign => Sign;
square => Square;
}
pub fn abs<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
x.with_array(|x| x.abs())
}
pub fn real<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
x.with_array(|x| x.real())
}
pub fn imag<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
x.with_array(|x| x.imag())
}
pub fn conj<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
x.with_array(|x| x.conj())
}
pub fn conjugate<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
conj(x)
}
pub fn angle<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
x.with_array(|x| x.angle())
}
unary! { Float:
floor => Floor;
ceil => Ceil;
round => RoundEven;
cbrt => Cbrt;
}
unary! { Inexact:
exp => Exp;
expm1 => Expm1;
log => Log;
log1p => Log1p;
sqrt => Sqrt;
sin => Sin;
cos => Cos;
tan => Tan;
tanh => Tanh;
}
pub fn logical_not<B: Backend>(x: impl ArrayLike<B, bool>) -> Array<B, bool> {
x.into_array().unary(UnaryOp::Not)
}
pub fn isfinite<B: Backend, T: Float>(x: impl ArrayLike<B, T>) -> Array<B, bool> {
lax::is_finite(&x.into_array())
}
macro_rules! binary {
($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
$(#[$m])*
#[track_caller]
pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>, y: impl ArrayLike<B, T>) -> Array<B, T> {
x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::$op, x, y)))
}
)*};
}
binary! { Numeric:
add => Add;
subtract => Sub;
multiply => Mul;
}
binary! { Num:
fmod => Rem;
}
binary! { Inexact:
divide => Div;
power => Pow;
}
binary! { Float:
arctan2 => Atan2;
}
binary! { Element:
maximum => Max;
minimum => Min;
}
#[track_caller]
pub fn logical_and<B: Backend>(
x: impl ArrayLike<B, bool>,
y: impl ArrayLike<B, bool>,
) -> Array<B, bool> {
x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::And, x, y)))
}
#[track_caller]
pub fn logical_or<B: Backend>(
x: impl ArrayLike<B, bool>,
y: impl ArrayLike<B, bool>,
) -> Array<B, bool> {
x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::Or, x, y)))
}
#[track_caller]
pub fn floor_divide<B: Backend, T: Int>(
x: impl ArrayLike<B, T>,
y: impl ArrayLike<B, T>,
) -> Array<B, T> {
let (x, y) = (x.into_array(), y.into_array());
let q = broadcast_binary(BinaryOp::Div, &x, &y);
if T::DTYPE.kind() == ruxla_kernels::DTypeKind::UnsignedInt {
return q;
}
let r = broadcast_binary(BinaryOp::Rem, &x, &y);
let zero = zeros::<B, T>(r.shape());
let adjust = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &zero)
& broadcast_compare(ruxla_kernels::CompareOp::Ne, &x.sign(), &y.sign());
where_(adjust, &q - Scalar::new(ruxla_kernels::cast::<u8, T>(1)), q)
}
#[track_caller]
pub fn remainder<B: Backend, T: Num>(
x: impl ArrayLike<B, T>,
y: impl ArrayLike<B, T>,
) -> Array<B, T> {
let zero = ruxla_kernels::cast::<u8, T>(0);
let one = ruxla_kernels::cast::<u8, T>(1);
let int = !T::DTYPE.is_float();
if B::FAST_PATHS
&& let (Some(a), Some(b)) = (x.as_scalar(), y.as_scalar())
{
let lt = |v| B::compare::<T>(ruxla_kernels::CompareOp::Lt, v, B::lit(zero));
let ne = |v| B::compare::<T>(ruxla_kernels::CompareOp::Ne, v, B::lit(zero));
let b = if int {
B::select(
B::compare::<T>(ruxla_kernels::CompareOp::Eq, b.0, B::lit(zero)),
B::lit(one),
b.0,
)
} else {
b.0
};
let r = B::binary::<T>(BinaryOp::Rem, a.0, b);
let plus = B::binary::<bool>(
BinaryOp::And,
B::compare::<bool>(ruxla_kernels::CompareOp::Ne, lt(r), lt(b)),
ne(r),
);
return Scalar(B::select(plus, B::binary::<T>(BinaryOp::Add, r, b), r)).to_array();
}
let (x, y) = (x.into_array(), y.into_array());
let y = if int {
let z = zeros::<B, T>(y.shape());
where_(
broadcast_compare(ruxla_kernels::CompareOp::Eq, &y, &z),
Scalar::<B, T>::new(one),
&y,
)
} else {
y
};
let r = broadcast_binary(BinaryOp::Rem, &x, &y);
let rz = zeros::<B, T>(r.shape());
let not_zero = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &rz);
let yz = zeros::<B, T>(y.shape());
let plus = broadcast_compare(
ruxla_kernels::CompareOp::Ne,
&r.lt(&rz),
&y.lt(&yz).broadcast_to(r.shape()),
) & not_zero;
where_(plus, broadcast_binary(BinaryOp::Add, &r, &y), r)
}
#[track_caller]
pub fn where_<B: Backend, T: Element>(
cond: impl ArrayLike<B, bool>,
x: impl ArrayLike<B, T>,
y: impl ArrayLike<B, T>,
) -> Array<B, T> {
let (c, x, y) = (cond.into_array(), x.into_array(), y.into_array());
if B::FAST_PATHS
&& let Some(r) = B::a_select_broadcast::<T>(&c.0, &x.0, &y.0)
{
return Array(r);
}
let s = broadcast_shapes(&broadcast_shapes(&c.shape(), &x.shape()), &y.shape());
lax::select_array(
&c.broadcast_to(s.clone()),
&x.broadcast_to(s.clone()),
&y.broadcast_to(s),
)
}
#[track_caller]
pub fn clip<B: Backend, T: Element>(
x: impl ArrayLike<B, T>,
lo: impl ArrayLike<B, T>,
hi: impl ArrayLike<B, T>,
) -> Array<B, T> {
if B::FAST_PATHS
&& let (Some(x), Some(lo), Some(hi)) = (x.as_scalar(), lo.as_scalar(), hi.as_scalar())
{
return Scalar(B::binary::<T>(
BinaryOp::Min,
B::binary::<T>(BinaryOp::Max, x.0, lo.0),
hi.0,
))
.to_array();
}
minimum(maximum(x, lo), hi)
}
#[track_caller]
pub fn equal<B: Backend, T: Element>(
x: impl ArrayLike<B, T>,
y: impl ArrayLike<B, T>,
) -> Array<B, bool> {
broadcast_compare(
ruxla_kernels::CompareOp::Eq,
&x.into_array(),
&y.into_array(),
)
}
fn is_half<T: Element>() -> bool {
T::DTYPE == f16::DTYPE || T::DTYPE == bf16::DTYPE
}
#[track_caller]
pub fn sum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
let x = x.into_array();
let axes = axes.into().resolve(x.ndim());
if is_half::<T>() {
return x.cast::<f32>().reduce_sum(&axes).cast::<T>();
}
x.reduce_sum(&axes)
}
#[track_caller]
pub fn mean<B: Backend, T: Float>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
let x = x.into_array();
let shape = x.shape();
let axes = axes.into().resolve(shape.rank());
let n: usize = axes.iter().map(|&a| shape[a]).product();
if is_half::<T>() {
let total = x.cast::<f32>().reduce_sum(&axes);
return (total / n as f32).cast::<T>();
}
let total = x.reduce_sum(&axes);
total / Scalar::<B, T>::new(ruxla_kernels::cast::<u64, T>(n as u64))
}
#[track_caller]
pub fn max<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
let x = x.into_array();
let axes = axes.into().resolve(x.ndim());
x.reduce_max(&axes)
}
#[track_caller]
pub fn min<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
let x = x.into_array();
let axes = axes.into().resolve(x.ndim());
x.reduce_min(&axes)
}
#[track_caller]
pub fn any<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
max(x, axes)
}
#[track_caller]
pub fn all<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
min(x, axes)
}
#[track_caller]
pub fn argmax<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
let x = x.into_array();
let axis = normalize_axis(axis, x.ndim());
lax::argmax(&x, axis)
}
#[track_caller]
pub fn argmin<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
let x = x.into_array();
let axis = normalize_axis(axis, x.ndim());
lax::argmin(&x, axis)
}
#[track_caller]
fn cumulative_operand<B: Backend, T: Element>(
x: impl ArrayLike<B, T>,
axis: Option<i64>,
) -> (Array<B, T>, usize) {
let x = x.into_array();
if axis.is_none() || x.ndim() == 0 {
let n = x.size();
let flat = lax::reshape(&x, [n]);
let axis = normalize_axis(axis.unwrap_or(0), 1);
return (flat, axis);
}
let axis = normalize_axis(axis.unwrap_or(0), x.ndim());
(x, axis)
}
#[track_caller]
pub fn cumsum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
let (x, axis) = cumulative_operand(x, axis);
lax::cumsum(&x, axis, false)
}
#[track_caller]
pub fn cumprod<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
let (x, axis) = cumulative_operand(x, axis);
lax::cumprod(&x, axis, false)
}
#[track_caller]
pub fn expand_dims<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, T> {
let x = x.into_array();
let shape = x.shape();
let axis = normalize_axis(axis, shape.rank() + 1);
let mut out = shape.clone();
out.insert(axis, 1);
let dims: Shape = (0..shape.rank())
.map(|i| if i < axis { i } else { i + 1 })
.collect();
lax::broadcast_in_dim(&x, out, &dims)
}
#[track_caller]
#[inline]
pub fn stack<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
xs: &[A],
axis: i64,
) -> Array<B, T> {
assert!(!xs.is_empty(), "stack needs at least one array");
if B::FAST_PATHS && (axis == 0 || axis == -1) && xs.iter().all(|x| x.as_scalar().is_some()) {
let r = B::stack_scalars::<T>(xs.len(), |i| xs[i].as_scalar().expect("a scalar").0);
if let Some(r) = r {
return Array(r);
}
}
stack_general(xs, axis)
}
#[track_caller]
fn stack_general<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
xs: &[A],
axis: i64,
) -> Array<B, T> {
if B::FAST_PATHS && (axis == 0 || axis == -1 && xs[0].clone().into_array().ndim() == 0) {
let arrays: Vec<Array<B, T>> = xs.iter().map(|x| x.clone().into_array()).collect();
if let Some(r) = B::stack0::<T>(Array::reprs(&arrays)) {
return Array(r);
}
}
let parts: Vec<Array<B, T>> = xs.iter().map(|x| expand_dims(x.clone(), axis)).collect();
let axis = normalize_axis(axis, parts[0].ndim());
lax::concatenate(&parts, axis)
}
#[track_caller]
pub fn take<B: Backend, T: Element, I: Int>(
x: &Array<B, T>,
indices: &Array<B, I>,
axis: i64,
) -> Array<B, T> {
let shape = x.shape();
let rank = shape.rank();
let axis = if axis < 0 { axis + rank as i64 } else { axis };
assert!(
(0..rank as i64).contains(&axis),
"take: axis {axis} out of range for rank {rank}"
);
let axis = axis as usize;
if B::FAST_PATHS
&& let Some(r) = B::a_take::<T, I>(&x.0, &indices.0, axis)
{
return Array(r);
}
let n = shape.dims()[axis];
let indices = indices.cast::<i32>();
let indices = where_(indices.lt(0i32), indices.clone() + n as i32, indices);
let index_rank = indices.ndim();
let mut dims_of_indices = indices.shape().dims().to_vec();
dims_of_indices.push(1);
let offset_dims = (0..axis)
.chain(axis + index_rank..rank - 1 + index_rank)
.collect();
let dims = GatherDims {
offset_dims,
collapsed_slice_dims: vec![axis],
start_index_map: vec![axis],
..GatherDims::default()
};
let mut slice_sizes = shape.dims().to_vec();
slice_sizes[axis] = 1;
lax::gather(
x,
&indices.reshape(dims_of_indices),
&dims,
&slice_sizes,
GatherScatterMode::Clip,
)
}
#[track_caller]
#[inline]
pub fn roll<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
if B::FAST_PATHS
&& let Some(dims) = B::dims(&x.0)
{
let axis = normalize_axis(axis, dims.len());
let n = dims[axis];
let i = roll_start(shift, n);
if i == 0 {
return x.clone();
}
if let Some(r) = B::a_roll::<T>(&x.0, n - i, axis) {
return Array(r);
}
}
roll_general(x, shift, axis)
}
#[inline]
fn roll_start(shift: i64, n: usize) -> usize {
shift.wrapping_neg().rem_euclid(n.max(1) as i64) as usize
}
#[track_caller]
fn roll_general<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
let shape = x.shape();
let axis = normalize_axis(axis, shape.rank());
let n = shape.dims()[axis];
let i = roll_start(shift, n);
if i == 0 {
return x.clone();
}
lax::concatenate(
&[
lax::slice_in_dim(x, i, n, 1, axis),
lax::slice_in_dim(x, 0, i, 1, axis),
],
axis,
)
}
#[track_caller]
pub fn concatenate<B: Backend, T: Element>(xs: &[Array<B, T>], axis: i64) -> Array<B, T> {
assert!(!xs.is_empty(), "concatenate needs at least one array");
let axis = normalize_axis(axis, xs[0].ndim());
lax::concatenate(xs, axis)
}
#[track_caller]
pub fn matmul<B: Backend, T: Numeric>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
let (ra, rb) = (a.ndim(), b.ndim());
assert!(
(1..=2).contains(&ra) && (1..=2).contains(&rb),
"matmul supports ranks 1 and 2, got {ra} and {rb}"
);
let dims = DotDims {
lhs_contracting: vec![ra - 1],
rhs_contracting: vec![0],
..DotDims::default()
};
lax::dot_general(a, b, &dims)
}
pub fn round_with<B: Backend, T: Float>(
x: impl ArrayLike<B, T>,
method: RoundingMethod,
) -> Array<B, T> {
let op = match method {
RoundingMethod::AwayFromZero => UnaryOp::Round,
RoundingMethod::ToNearestEven => UnaryOp::RoundEven,
};
x.into_array().unary(op)
}
impl<B: Backend, T: Numeric> Array<B, T> {
#[track_caller]
pub fn dot(&self, other: &Array<B, T>) -> Array<B, T> {
matmul(self, other)
}
#[track_caller]
pub fn sum(&self, axes: impl Into<Axes>) -> Array<B, T> {
sum(self, axes)
}
}