use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::broadcast_shape;
use crate::runtime::Runtime;
use crate::tensor::Tensor;
#[inline]
pub fn normalize_dim(dim: isize, ndim: usize) -> Result<usize> {
let dim_idx = if dim < 0 {
let adjusted = ndim as isize + dim;
if adjusted < 0 {
return Err(Error::InvalidDimension { dim, ndim });
}
adjusted as usize
} else {
dim as usize
};
if dim_idx >= ndim {
return Err(Error::InvalidDimension { dim, ndim });
}
Ok(dim_idx)
}
#[inline]
pub fn validate_arange(start: f64, stop: f64, step: f64) -> Result<usize> {
if step == 0.0 {
return Err(Error::InvalidArgument {
arg: "step",
reason: "step cannot be zero".to_string(),
});
}
if (stop > start && step < 0.0) || (stop < start && step > 0.0) {
return Err(Error::InvalidArgument {
arg: "step",
reason: "step sign must match direction from start to stop".to_string(),
});
}
let numel = if start == stop {
0
} else {
((stop - start) / step).ceil() as usize
};
Ok(numel)
}
#[inline]
pub fn validate_eye(n: usize, m: Option<usize>) -> (usize, usize) {
let cols = m.unwrap_or(n);
(n, cols)
}
#[inline]
pub fn row_layout(shape: &[usize], total: usize) -> (usize, usize) {
let row_len = *shape.last().unwrap_or(&total);
let rows = total.checked_div(row_len).unwrap_or(0);
(rows, row_len)
}
#[inline]
pub fn ensure_contiguous<R: Runtime<DType = DType>>(
tensor: &Tensor<R>,
) -> crate::error::Result<Tensor<R>> {
if tensor.is_contiguous() {
Ok(tensor.clone())
} else {
tensor.contiguous()
}
}
#[inline]
pub fn validate_binary_dtypes<R: Runtime<DType = DType>>(
a: &Tensor<R>,
b: &Tensor<R>,
) -> Result<DType> {
if a.dtype() != b.dtype() {
return Err(Error::DTypeMismatch {
lhs: a.dtype(),
rhs: b.dtype(),
});
}
Ok(a.dtype())
}
#[inline]
pub fn pow_scalar_output_dtype(dtype: DType, scalar: f64) -> DType {
let integral_result = scalar >= 0.0 && scalar.fract() == 0.0;
if dtype.is_int() && !integral_result {
DType::F64
} else {
dtype
}
}
#[inline]
pub fn cap_ipow_exponent(scalar: f64) -> f64 {
if scalar > 1024.0 {
1024.0 + f64::from(scalar % 2.0 != 0.0)
} else {
scalar
}
}
#[inline]
pub fn compute_broadcast_shape<R: Runtime<DType = DType>>(
a: &Tensor<R>,
b: &Tensor<R>,
) -> Result<Vec<usize>> {
broadcast_shape(a.shape(), b.shape()).ok_or_else(|| Error::BroadcastError {
lhs: a.shape().to_vec(),
rhs: b.shape().to_vec(),
})
}
#[inline]
pub fn validate_copy_into<R: Runtime<DType = DType>>(
out: &Tensor<R>,
src: &Tensor<R>,
op_name: &'static str,
) -> Result<()> {
if out.dtype() != src.dtype() {
return Err(Error::DTypeMismatch {
lhs: src.dtype(),
rhs: out.dtype(),
});
}
if out.shape() != src.shape() {
return Err(Error::ShapeMismatch {
expected: src.shape().to_vec(),
got: out.shape().to_vec(),
});
}
if !out.is_contiguous() {
return Err(Error::Backend(format!(
"{op_name}: destination tensor must be contiguous"
)));
}
Ok(())
}
#[inline]
pub fn validate_host_write<R: Runtime<DType = DType>>(
out: &Tensor<R>,
src_dtype: DType,
src_len: usize,
op_name: &'static str,
) -> Result<()> {
if out.dtype() != src_dtype {
return Err(Error::DTypeMismatch {
lhs: src_dtype,
rhs: out.dtype(),
});
}
if out.numel() != src_len {
return Err(Error::ShapeMismatch {
expected: vec![out.numel()],
got: vec![src_len],
});
}
if !out.is_contiguous() {
return Err(Error::Backend(format!(
"{op_name}: destination tensor of shape {:?} with strides {:?} is not contiguous; \
pass the owning tensor instead of a strided view",
out.shape(),
out.strides()
)));
}
Ok(())
}
#[inline]
pub fn validate_rand_into<R: Runtime<DType = DType>>(
out: &Tensor<R>,
op_name: &'static str,
) -> Result<bool> {
if !out.dtype().is_float() {
return Err(Error::UnsupportedDType {
dtype: out.dtype(),
op: op_name,
});
}
if !out.is_contiguous() {
return Err(Error::Backend(format!(
"{op_name}: destination tensor must be contiguous"
)));
}
Ok(out.numel() == 0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pow_scalar_output_dtype_promotes_only_non_integral_exponents() {
for scalar in [0.0, 1.0, 2.0, 63.0, 1e30] {
assert_eq!(pow_scalar_output_dtype(DType::I64, scalar), DType::I64);
assert_eq!(pow_scalar_output_dtype(DType::U32, scalar), DType::U32);
}
for scalar in [0.5, -1.0, -0.5, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] {
assert_eq!(pow_scalar_output_dtype(DType::I64, scalar), DType::F64);
assert_eq!(pow_scalar_output_dtype(DType::I32, scalar), DType::F64);
}
for scalar in [0.5, -1.0, 2.0, f64::NAN] {
assert_eq!(pow_scalar_output_dtype(DType::F32, scalar), DType::F32);
assert_eq!(pow_scalar_output_dtype(DType::F64, scalar), DType::F64);
}
}
#[test]
fn test_normalize_dim_positive() {
assert_eq!(normalize_dim(0, 3).unwrap(), 0);
assert_eq!(normalize_dim(2, 3).unwrap(), 2);
}
#[test]
fn test_normalize_dim_negative() {
assert_eq!(normalize_dim(-1, 3).unwrap(), 2);
assert_eq!(normalize_dim(-3, 3).unwrap(), 0);
}
#[test]
fn test_normalize_dim_out_of_bounds() {
assert!(normalize_dim(3, 3).is_err());
assert!(normalize_dim(-4, 3).is_err());
}
#[test]
fn test_ensure_contiguous() {
use crate::runtime::cpu::{CpuDevice, CpuRuntime};
use crate::tensor::Tensor;
let device = CpuDevice::new();
let a =
Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], &device).unwrap();
assert!(a.is_contiguous());
let c = ensure_contiguous(&a).unwrap();
assert!(c.is_contiguous());
}
}