use crate::backend_ops::BackendOps;
use coeus_core::{BackendError, Scalar};
use coeus_tensor::Tensor;
#[inline]
pub fn prod_axis<T: Scalar + coeus_core::FloatElement, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
axis: usize,
backend: &B,
) -> Result<Tensor<T, B>, B::Error> {
if axis >= a.ndim() {
return Err(B::Error::from(BackendError::AxisOutOfRange {
operation: "prod_axis",
axis,
rank: a.ndim(),
}));
}
let mut out_shape = a.shape_cloned();
out_shape[axis] = 1;
let mut out = unsafe { Tensor::alloc_on(out_shape, backend) }?;
let (out_storage, out_layout) = out.storage_mut_and_layout()?;
backend.reduce_prod(a.storage(), a.layout(), axis, out_storage, out_layout)?;
Ok(out)
}
pub fn prod_tensor<T: Scalar + coeus_core::FloatElement, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<Tensor<T, B>, B::Error> {
let mut reduced = if a.ndim() == 0 {
a.reshape([1])
} else {
a.clone()
};
for axis in 0..a.ndim() {
reduced = prod_axis(&reduced, axis, backend)?;
}
Ok(reduced.reshape([1]))
}
#[inline]
pub fn prod<T: Scalar + coeus_core::FloatElement + leto_ops::Scalar, B: BackendOps<T> + Default>(
a: &Tensor<T, B>,
backend: &B,
) -> Result<T, B::Error> {
if a.is_contiguous() && a.layout().offset() == 0 {
let crossover = backend.host_staging_crossover();
if crossover > 0 && a.numel() < crossover {
return super::staging::staged_scalar(a, backend, prod);
}
}
let reduced = prod_tensor(a, backend)?;
let mut scalar = [T::ZERO];
backend.copy_to_host(reduced.storage(), &mut scalar)?;
Ok(scalar[0])
}