use std::collections::HashMap;
use ruxla_ir::{
AVal, Atom, DType, Error, EvalCx, Function, HostArray, Params, Prim, Result, RoundingMethod,
SelectPrim,
};
use ruxla_kernels::array::{CumulativeOp, ReduceOp};
use ruxla_kernels::linalg::TriangularSolveOptions;
use ruxla_kernels::window::{ConvWindow, Window};
use ruxla_kernels::{BinaryOp, CompareOp, Element, TernaryOp, UnaryOp, with_dtype};
use crate::backend::{Backend, Native, NativeArray, ToReal};
#[doc(hidden)]
pub fn eval_native(f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>> {
NativeCx.eval_function(f, args)
}
struct NativeCx;
impl EvalCx for NativeCx {
fn eval_function(&self, f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>> {
if args.len() != f.invars.len() {
return Err(Error::Malformed(format!(
"{} arguments for {} inputs",
args.len(),
f.invars.len()
)));
}
let mut env: HashMap<u64, HostArray> = HashMap::new();
for (v, value) in &f.constvars {
env.insert(v.id(), value.clone());
}
for (v, a) in f.invars.iter().zip(args) {
env.insert(v.id(), a.clone());
}
let read = |env: &HashMap<u64, HostArray>, a: &Atom| match a {
Atom::Var(v) => env
.get(&v.id())
.cloned()
.ok_or_else(|| Error::Malformed(format!("undefined {v:?}"))),
Atom::Lit(l) => Ok(l.value().clone()),
};
for eqn in &f.eqns {
let inputs = eqn
.inputs
.iter()
.map(|a| read(&env, a))
.collect::<Result<Vec<_>>>()?;
let outputs = apply(self, eqn.prim, &inputs, &eqn.params)?;
for (v, x) in eqn.outputs.iter().zip(outputs) {
env.insert(v.id(), x);
}
}
f.outvars.iter().map(|a| read(&env, a)).collect()
}
}
macro_rules! with_linalg_dtype {
($prim:expr, $dtype:expr, |$t:ident| $body:expr) => {
match $dtype {
DType::F32 => {
type $t = f32;
$body
}
DType::F64 => {
type $t = f64;
$body
}
DType::C64 => {
type $t = ruxla_kernels::c64;
$body
}
DType::C128 => {
type $t = ruxla_kernels::c128;
$body
}
other => {
return Err(Error::type_error(
$prim.name(),
format!("expected f32, f64, c64, or c128 matrices, got {other}"),
));
}
}
};
}
fn arr<T: Element>(x: &HostArray) -> NativeArray<T> {
NativeArray::from_host(x)
}
fn scalar<T: Element>(x: &HostArray) -> T {
arr::<T>(x).data()[0]
}
fn host<T: Element>(v: T) -> HostArray {
NativeArray::new(vec![v], []).to_host()
}
fn index_scalars<I: Element>(xs: &[HostArray]) -> Vec<I> {
xs.iter().map(scalar::<I>).collect()
}
fn wrong(prim: Prim) -> Error {
Error::type_error(prim.name(), "unexpected parameters")
}
fn apply(cx: &NativeCx, prim: Prim, x: &[HostArray], params: &Params) -> Result<Vec<HostArray>> {
let in_avals: Vec<AVal> = x.iter().map(HostArray::aval).collect();
let out_avals = prim.abstract_eval(&in_avals, params)?;
let name = prim.name();
let rank0 = x.iter().all(|a| a.shape().rank() == 0);
if name == "round" {
let Params::Round { method } = params else {
return Err(wrong(prim));
};
let op = match method {
RoundingMethod::AwayFromZero => UnaryOp::Round,
RoundingMethod::ToNearestEven => UnaryOp::RoundEven,
};
return Ok(vec![unary(op, &x[0])]);
}
if let Some(op) = UnaryOp::ALL.into_iter().find(|op| op.name() == name) {
return Ok(vec![unary(op, &x[0])]);
}
if let Some(op) = BinaryOp::ALL.into_iter().find(|op| op.name() == name) {
let (a, b) = (&x[0], &x[1]);
return Ok(vec![with_dtype!(a.dtype(), |T| if rank0 {
host(Native::binary::<T>(op, scalar(a), scalar(b)))
} else {
Native::a_binary::<T>(op, &arr(a), &arr(b)).to_host()
})]);
}
if let Some(op) = TernaryOp::ALL.into_iter().find(|op| op.name() == name) {
return Ok(vec![with_dtype!(x[0].dtype(), |T| Native::a_ternary::<T>(
op,
&arr(&x[0]),
&arr(&x[1]),
&arr(&x[2])
)
.to_host())]);
}
if let Some(op) = CompareOp::ALL.into_iter().find(|op| op.name() == name) {
let (a, b) = (&x[0], &x[1]);
return Ok(vec![with_dtype!(a.dtype(), |T| if rank0 {
host(Native::compare::<T>(op, scalar(a), scalar(b)))
} else {
Native::a_compare::<T>(op, &arr(a), &arr(b)).to_host()
})]);
}
let out = match (name, params) {
(
"fft",
Params::Fft {
fft_type,
fft_lengths,
},
) => {
let to = out_avals[0].dtype;
with_dtype!(x[0].dtype(), |T| with_dtype!(to, |U| Native::fft::<T, U>(
&arr(&x[0]),
*fft_type,
fft_lengths
)
.to_host()))
}
("real", _) => to_real(ToReal::Real, &x[0]),
("imag", _) => to_real(ToReal::Imag, &x[0]),
("complex", _) => complex(&x[0], &x[1])?,
("conj", _) if x[0].dtype().is_complex() => {
with_dtype!(x[0].dtype(), |T| if rank0 {
host(Native::conj::<T>(scalar(&x[0])))
} else {
Native::a_conj::<T>(&arr(&x[0])).to_host()
})
}
("conj", _) => complex(&x[0], &HostArray::zeros(x[0].shape().clone(), x[0].dtype()))?,
("is_finite", _) => with_dtype!(x[0].dtype(), |T| if rank0 {
host(Native::is_finite::<T>(scalar(&x[0])))
} else {
Native::a_is_finite::<T>(&arr(&x[0])).to_host()
}),
("integer_pow", &Params::IntegerPow { y }) => with_dtype!(x[0].dtype(), |T| if rank0 {
host(Native::integer_pow::<T>(scalar(&x[0]), y))
} else {
Native::a_integer_pow::<T>(&arr(&x[0]), y).to_host()
}),
("convert_element_type", &Params::Convert { new_dtype }) => {
with_dtype!(x[0].dtype(), |T| with_dtype!(new_dtype, |U| if rank0 {
host(Native::cast::<T, U>(scalar(&x[0])))
} else {
Native::a_cast::<T, U>(&arr(&x[0])).to_host()
}))
}
("bitcast_convert_type", &Params::Convert { new_dtype }) => {
with_dtype!(x[0].dtype(), |T| with_dtype!(new_dtype, |U| if rank0 {
host(Native::bitcast::<T, U>(scalar(&x[0])))
} else {
Native::a_bitcast::<T, U>(&arr(&x[0])).to_host()
}))
}
("select_n", _) => select_n(&x[0], &x[1..]),
("clamp", _) => with_dtype!(x[1].dtype(), |T| Native::a_clamp::<T>(
&arr(&x[0]),
&arr(&x[1]),
&arr(&x[2])
)
.to_host()),
(
"broadcast_in_dim",
Params::BroadcastInDim {
shape,
broadcast_dimensions,
},
) => with_dtype!(x[0].dtype(), |T| Native::broadcast_in_dim::<T>(
&arr(&x[0]),
shape,
broadcast_dimensions
)
.to_host()),
("reshape", Params::Reshape { new_sizes }) => {
with_dtype!(x[0].dtype(), |T| Native::reshape::<T>(
&arr(&x[0]),
new_sizes
)
.to_host())
}
("transpose", Params::Transpose { permutation }) => {
with_dtype!(x[0].dtype(), |T| Native::transpose::<T>(
&arr(&x[0]),
permutation
)
.to_host())
}
(
"slice",
Params::Slice {
start_indices,
limit_indices,
strides,
},
) => with_dtype!(x[0].dtype(), |T| Native::slice::<T>(
&arr(&x[0]),
start_indices,
limit_indices,
strides
)
.to_host()),
("dynamic_slice", Params::DynamicSlice { slice_sizes }) => {
let starts = &x[1..];
let index_dtype = starts.first().map_or(DType::I32, HostArray::dtype);
with_dtype!(x[0].dtype(), |T| with_dtype!(index_dtype, |I| {
Native::dynamic_slice::<T, I>(&arr(&x[0]), &index_scalars::<I>(starts), slice_sizes)
.to_host()
}))
}
("dynamic_update_slice", _) => {
let starts = &x[2..];
let index_dtype = starts.first().map_or(DType::I32, HostArray::dtype);
with_dtype!(x[0].dtype(), |T| with_dtype!(index_dtype, |I| {
Native::dynamic_update_slice::<T, I>(
&arr(&x[0]),
&arr(&x[1]),
&index_scalars::<I>(starts),
)
.to_host()
}))
}
("concatenate", &Params::Concatenate { dimension }) => {
with_dtype!(x[0].dtype(), |T| {
let xs: Vec<NativeArray<T>> = x.iter().map(arr).collect();
Native::concatenate::<T>(&xs, dimension).to_host()
})
}
("pad", Params::Pad { padding_config }) => with_dtype!(x[0].dtype(), |T| Native::pad::<T>(
&arr(&x[0]),
scalar(&x[1]),
padding_config
)
.to_host()),
("rev", Params::Rev { dimensions }) => {
with_dtype!(x[0].dtype(), |T| Native::rev::<T>(&arr(&x[0]), dimensions)
.to_host())
}
(
"iota",
Params::Iota {
dtype,
shape,
dimension,
},
) => with_dtype!(*dtype, |T| Native::iota::<T>(shape, *dimension).to_host()),
("reduce_sum" | "reduce_max" | "reduce_min", Params::Reduce { axes }) => {
let op = match name {
"reduce_sum" => ReduceOp::Sum,
"reduce_max" => ReduceOp::Max,
_ => ReduceOp::Min,
};
with_dtype!(x[0].dtype(), |T| Native::reduce::<T>(op, &arr(&x[0]), axes)
.to_host())
}
(
"cumsum" | "cumprod" | "cummax" | "cummin" | "cumlogsumexp",
&Params::Cumulative { axis, reverse },
) => {
let op = match name {
"cumsum" => CumulativeOp::Sum,
"cumprod" => CumulativeOp::Prod,
"cummax" => CumulativeOp::Max,
"cummin" => CumulativeOp::Min,
_ => CumulativeOp::LogSumExp,
};
with_dtype!(x[0].dtype(), |T| Native::cumulative::<T>(
op,
&arr(&x[0]),
axis,
reverse
)
.to_host())
}
("top_k", &Params::TopK { k, axis, .. }) => {
return Ok(with_dtype!(x[0].dtype(), |T| {
let (v, i) = Native::top_k::<T>(&arr(&x[0]), k, axis);
vec![v.to_host(), i.to_host()]
}));
}
("cholesky", Params::None) => {
with_linalg_dtype!(prim, x[0].dtype(), |T| Native::cholesky::<T>(&arr(&x[0]))
.to_host())
}
(
"triangular_solve",
&Params::TriangularSolve {
left_side,
lower,
transpose_a,
conjugate_a,
unit_diagonal,
},
) => {
let options = TriangularSolveOptions {
left_side,
lower,
transpose_a,
conjugate_a,
unit_diagonal,
};
with_linalg_dtype!(prim, x[0].dtype(), |T| Native::triangular_solve::<T>(
&arr(&x[0]),
&arr(&x[1]),
options
)
.to_host())
}
("lu", Params::None) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (lu, pivots, perm) = Native::lu::<T>(&arr(&x[0]));
vec![lu.to_host(), pivots.to_host(), perm.to_host()]
}));
}
("lu_pivots_to_permutation", &Params::LuPivotsToPermutation { permutation_size }) => {
Native::lu_pivots_to_permutation(&arr(&x[0]), permutation_size).to_host()
}
(
"qr",
&Params::Qr {
full_matrices,
pivoting,
},
) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
if pivoting {
let (q, r, p) = Native::qr_pivoting::<T>(&arr(&x[0]), full_matrices);
vec![q.to_host(), r.to_host(), p.to_host()]
} else {
let (q, r) = Native::qr::<T>(&arr(&x[0]), full_matrices);
vec![q.to_host(), r.to_host()]
}
}));
}
(
"eigh",
&Params::Eigh {
lower,
sort_eigenvalues,
subset_by_index,
algorithm,
},
) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (v, w) = Native::eigh::<T>(
&arr(&x[0]),
lower,
sort_eigenvalues,
subset_by_index,
algorithm,
);
vec![v.to_host(), w.to_host()]
}));
}
(
"schur",
&Params::Schur {
compute_schur_vectors,
},
) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (t, z) = Native::schur::<T>(&arr(&x[0]), compute_schur_vectors);
let mut out = vec![t.to_host()];
out.extend(z.map(|z| z.to_host()));
out
}));
}
("hessenberg", Params::None) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (h, taus) = Native::hessenberg::<T>(&arr(&x[0]));
vec![h.to_host(), taus.to_host()]
}));
}
("householder_product", Params::None) => {
with_linalg_dtype!(prim, x[0].dtype(), |T| Native::householder_product::<T>(
&arr(&x[0]),
&arr(&x[1])
)
.to_host())
}
("ormqr", &Params::Ormqr { left, transpose }) => {
with_linalg_dtype!(prim, x[0].dtype(), |T| Native::ormqr::<T>(
&arr(&x[0]),
&arr(&x[1]),
&arr(&x[2]),
left,
transpose
)
.to_host())
}
("host_callback", Params::HostCallback { .. }) => return prim.eval(cx, x, params),
("cholesky_update", Params::None) => match x[0].dtype() {
DType::F32 => Native::cholesky_update::<f32>(&arr(&x[0]), &arr(&x[1])).to_host(),
DType::F64 => Native::cholesky_update::<f64>(&arr(&x[0]), &arr(&x[1])).to_host(),
other => {
return Err(Error::type_error(
prim.name(),
format!("expected f32 or f64 matrices, got {other}"),
));
}
},
("symmetric_product", &Params::SymmetricProduct { alpha, beta }) => match x[0].dtype() {
DType::F32 => {
Native::symmetric_product::<f32>(&arr(&x[0]), &arr(&x[1]), alpha, beta).to_host()
}
DType::F64 => {
Native::symmetric_product::<f64>(&arr(&x[0]), &arr(&x[1]), alpha, beta).to_host()
}
other => {
return Err(Error::type_error(
prim.name(),
format!("expected f32 or f64 matrices, got {other}"),
));
}
},
("tridiagonal", &Params::Tridiagonal { lower }) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (a, d, e, taus) = Native::tridiagonal::<T>(&arr(&x[0]), lower);
vec![a.to_host(), d.to_host(), e.to_host(), taus.to_host()]
}));
}
("tridiagonal_solve", &Params::TridiagonalSolve { perturb_singular }) => {
with_linalg_dtype!(prim, x[0].dtype(), |T| Native::tridiagonal_solve::<T>(
&arr(&x[0]),
&arr(&x[1]),
&arr(&x[2]),
&arr(&x[3]),
perturb_singular
)
.to_host())
}
(
"eig",
&Params::Eig {
compute_left_eigenvectors,
compute_right_eigenvectors,
enable_eigvec_derivs,
},
) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (w, vl, vr) = Native::eig::<T>(
&arr(&x[0]),
compute_left_eigenvectors,
compute_right_eigenvectors,
enable_eigvec_derivs,
);
let mut out = vec![w.to_host()];
out.extend(vl.map(|v| v.to_host()));
out.extend(vr.map(|v| v.to_host()));
out
}));
}
(
"svd",
&Params::Svd {
full_matrices,
compute_uv,
subset_by_index,
algorithm,
},
) => {
return Ok(with_linalg_dtype!(prim, x[0].dtype(), |T| {
let (s, uv) = Native::svd::<T>(
&arr(&x[0]),
full_matrices,
compute_uv,
subset_by_index,
algorithm,
);
let mut out = vec![s.to_host()];
if let Some((u, vt)) = uv {
out.push(u.to_host());
out.push(vt.to_host());
}
out
}));
}
("argmax" | "argmin", &Params::ArgMinMax { axis, index_dtype }) => {
let max = name == "argmax";
with_dtype!(x[0].dtype(), |T| with_dtype!(index_dtype, |I| {
Native::arg_min_max::<T, I>(&arr(&x[0]), axis, max).to_host()
}))
}
(
"dot_general",
Params::DotGeneral {
dimension_numbers,
precision,
preferred_element_type,
},
) => {
let to = preferred_element_type.unwrap_or(x[0].dtype());
with_dtype!(x[0].dtype(), |T| with_dtype!(to, |U| {
Native::dot_general::<T, U>(&arr(&x[0]), &arr(&x[1]), dimension_numbers, *precision)
.to_host()
}))
}
(
"conv_general_dilated",
Params::ConvGeneralDilated {
window_strides,
padding,
lhs_dilation,
rhs_dilation,
dimension_numbers,
feature_group_count,
batch_group_count,
precision,
preferred_element_type,
},
) => {
let to = preferred_element_type.unwrap_or(x[0].dtype());
let window = ConvWindow {
strides: window_strides,
padding,
lhs_dilation,
rhs_dilation,
};
with_dtype!(x[0].dtype(), |T| with_dtype!(to, |U| {
Native::conv_general_dilated::<T, U>(
&arr(&x[0]),
&arr(&x[1]),
&window,
dimension_numbers,
(*feature_group_count, *batch_group_count),
*precision,
)
.to_host()
}))
}
(
"reduce_window_sum" | "reduce_window_max" | "reduce_window_min",
Params::ReduceWindow {
window_dimensions,
window_strides,
padding,
base_dilation,
window_dilation,
},
) => {
let op = match name {
"reduce_window_sum" => ReduceOp::Sum,
"reduce_window_max" => ReduceOp::Max,
_ => ReduceOp::Min,
};
let window = Window {
dimensions: window_dimensions,
strides: window_strides,
padding,
base_dilation,
window_dilation,
};
with_dtype!(x[0].dtype(), |T| Native::reduce_window::<T>(
op,
&arr(&x[0]),
&window
)
.to_host())
}
(
"select_and_scatter_add",
Params::SelectAndScatterAdd {
select_prim,
window_dimensions,
window_strides,
padding,
},
) => {
let ones = vec![1; window_dimensions.len()];
let window = Window {
dimensions: window_dimensions,
strides: window_strides,
padding,
base_dilation: &ones,
window_dilation: &ones,
};
with_dtype!(x[0].dtype(), |T| Native::select_and_scatter_add::<T>(
&arr(&x[0]),
&arr(&x[1]),
*select_prim,
&window
)
.to_host())
}
(
"select_and_gather_add",
Params::SelectAndGatherAdd {
select_prim,
window_dimensions,
window_strides,
padding,
base_dilation,
window_dilation,
},
) => {
let window = Window {
dimensions: window_dimensions,
strides: window_strides,
padding,
base_dilation,
window_dilation,
};
let select_prim: SelectPrim = *select_prim;
with_dtype!(x[0].dtype(), |T| Native::select_and_gather_add::<T>(
&arr(&x[0]),
&arr(&x[1]),
select_prim,
&window
)
.to_host())
}
(
"gather",
Params::Gather {
dimension_numbers,
slice_sizes,
mode,
indices_are_sorted,
unique_indices,
},
) => with_dtype!(x[0].dtype(), |T| with_dtype!(x[1].dtype(), |I| {
Native::gather::<T, I>(
&arr(&x[0]),
&arr(&x[1]),
dimension_numbers,
slice_sizes,
*mode,
*indices_are_sorted && *unique_indices,
)
.to_host()
})),
(
"scatter" | "scatter-add" | "scatter-mul" | "scatter-min" | "scatter-max",
Params::Scatter {
dimension_numbers,
mode,
indices_are_sorted,
unique_indices,
},
) => {
let combine = match name {
"scatter" => None,
"scatter-add" => Some(BinaryOp::Add),
"scatter-mul" => Some(BinaryOp::Mul),
"scatter-min" => Some(BinaryOp::Min),
_ => Some(BinaryOp::Max),
};
with_dtype!(x[0].dtype(), |T| with_dtype!(x[1].dtype(), |I| {
Native::scatter::<T, I>(
combine,
&arr(&x[0]),
&arr(&x[1]),
&arr(&x[2]),
dimension_numbers,
*mode,
*indices_are_sorted && *unique_indices,
)
.to_host()
}))
}
("threefry2x32", Params::None) => {
let (a, b) = Native::threefry2x32(&arr(&x[0]), &arr(&x[1]), &arr(&x[2]), &arr(&x[3]));
return Ok(vec![a.to_host(), b.to_host()]);
}
("jit", Params::Jit { body, .. })
| ("checkpoint", Params::Checkpoint { body })
| ("custom_jvp_call", Params::CustomJvp { call: body, .. })
| ("custom_vjp_call", Params::CustomVjp { call: body, .. }) => {
return cx.eval_function(body, x);
}
("cond", Params::Cond { branches }) => {
let n = branches.len();
let i = usize::try_from(scalar::<i32>(&x[0]))
.ok()
.filter(|&i| i < n)
.unwrap_or(n - 1);
return cx.eval_function(&branches[i], &x[1..]);
}
(
"sort",
&Params::Sort {
dimension,
is_stable,
num_keys,
},
) => {
return Ok(Native::sort(x, dimension, is_stable, num_keys));
}
(
"while",
Params::While {
cond,
body,
cond_nconsts,
body_nconsts,
},
) => {
let (nc, nb) = (*cond_nconsts, *body_nconsts);
let (cond_consts, rest) = x.split_at(nc);
let (body_consts, init) = rest.split_at(nb);
let mut carry = init.to_vec();
loop {
let args: Vec<HostArray> = cond_consts.iter().chain(&carry).cloned().collect();
if !scalar::<bool>(&cx.eval_function(cond, &args)?[0]) {
break;
}
let args: Vec<HostArray> = body_consts.iter().chain(&carry).cloned().collect();
carry = cx.eval_function(body, &args)?;
}
return Ok(carry);
}
(
"scan",
Params::Scan {
body,
length,
reverse,
num_consts,
num_carry,
},
) => {
return scan(
cx,
body,
*length,
*reverse,
*num_consts,
*num_carry,
x,
&out_avals,
);
}
_ => {
return Err(Error::unsupported(
name,
"no native operation in the test dispatcher",
));
}
};
Ok(vec![out])
}
fn unary(op: UnaryOp, x: &HostArray) -> HostArray {
if op == UnaryOp::Abs {
return to_real(ToReal::Abs, x);
}
with_dtype!(x.dtype(), |T| if x.shape().rank() == 0 {
host(Native::unary::<T>(op, scalar(x)))
} else {
Native::a_unary::<T>(op, &arr(x)).to_host()
})
}
fn to_real(op: ToReal, x: &HostArray) -> HostArray {
with_dtype!(x.dtype(), |T| if x.shape().rank() == 0 {
host(Native::to_real::<T>(op, scalar(x)))
} else {
Native::a_to_real::<T>(op, &arr(x)).to_host()
})
}
fn complex(re: &HostArray, im: &HostArray) -> Result<HostArray> {
fn make<C: Element>(re: &HostArray, im: &HostArray) -> HostArray {
if re.shape().rank() == 0 {
host(Native::complex::<C>(scalar(re), scalar(im)))
} else {
Native::a_complex::<C>(&arr(re), &arr(im)).to_host()
}
}
match re.dtype() {
DType::F32 => Ok(make::<ruxla_kernels::c64>(re, im)),
DType::F64 => Ok(make::<ruxla_kernels::c128>(re, im)),
d => Err(Error::type_error(
"complex",
format!("unexpected {d} parts"),
)),
}
}
fn select_n(which: &HostArray, cases: &[HostArray]) -> HostArray {
with_dtype!(cases[0].dtype(), |T| {
if which.dtype() == DType::Bool {
if cases.len() == 1 {
return cases[0].clone();
}
if which.shape().rank() == 0 && cases[0].shape().rank() == 0 {
return host(Native::select::<T>(
scalar(which),
scalar(&cases[1]),
scalar(&cases[0]),
));
}
return Native::a_select::<T>(&arr(which), &arr(&cases[1]), &arr(&cases[0])).to_host();
}
let w = arr::<i32>(which);
let mut result = arr::<T>(&cases[0]);
for (k, case) in cases.iter().enumerate().skip(1) {
let k = NativeArray::new(vec![k as i32; w.data().len()], w.shape().clone());
let pred = Native::a_compare::<i32>(CompareOp::Ge, &w, &k);
result = Native::a_select::<T>(&pred, &arr(case), &result);
}
result.to_host()
})
}
#[allow(clippy::too_many_arguments)] fn scan(
cx: &NativeCx,
body: &Function,
length: usize,
reverse: bool,
num_consts: usize,
num_carry: usize,
x: &[HostArray],
out_avals: &[AVal],
) -> Result<Vec<HostArray>> {
let (consts, rest) = x.split_at(num_consts);
let (init, xs) = rest.split_at(num_carry);
let mut carry = init.to_vec();
let mut ys: Vec<Vec<HostArray>> = vec![Vec::new(); out_avals.len() - num_carry];
for step in 0..length {
let i = if reverse { length - 1 - step } else { step };
let mut args: Vec<HostArray> = consts.iter().chain(&carry).cloned().collect();
for a in xs {
args.push(with_dtype!(a.dtype(), |T| {
let dims = a.shape();
let mut start = vec![0; dims.rank()];
let mut limit = dims.to_vec();
start[0] = i;
limit[0] = i + 1;
let s = Native::slice::<T>(&arr(a), &start, &limit, &vec![1; dims.rank()]);
Native::reshape::<T>(&s, &dims[1..]).to_host()
}));
}
let outs = cx.eval_function(body, &args)?;
let (c, y) = outs.split_at(num_carry);
carry = c.to_vec();
for (stack, v) in ys.iter_mut().zip(y) {
stack.push(v.clone());
}
}
let mut result = carry;
for (stack, aval) in ys.into_iter().zip(&out_avals[num_carry..]) {
if length == 0 {
result.push(HostArray::zeros(aval.shape.clone(), aval.dtype));
continue;
}
result.push(with_dtype!(aval.dtype, |T| {
let mut items: Vec<NativeArray<T>> = stack
.iter()
.map(|v| {
let mut dims = vec![1];
dims.extend_from_slice(v.shape());
Native::reshape::<T>(&arr(v), &dims)
})
.collect();
if reverse {
items.reverse();
}
Native::concatenate::<T>(&items, 0).to_host()
}));
}
Ok(result)
}