use super::kernel::elementwise_binary;
use crate::backend_ops::{BackendOps, BinaryOp};
use coeus_core::{BackendError, Scalar};
use coeus_tensor::Tensor;
#[inline]
pub fn add<T: Scalar, B: BackendOps<T>>(
a: &Tensor<T, B>,
b: &Tensor<T, B>,
backend: &B,
) -> Tensor<T, B> {
elementwise_binary(a, b, backend, BinaryOp::Add).expect("add: incompatible shapes")
}
#[inline]
pub fn sub<T: Scalar, B: BackendOps<T>>(
a: &Tensor<T, B>,
b: &Tensor<T, B>,
backend: &B,
) -> Tensor<T, B> {
elementwise_binary(a, b, backend, BinaryOp::Sub).expect("sub: incompatible shapes")
}
#[inline]
pub fn mul<T: Scalar, B: BackendOps<T>>(
a: &Tensor<T, B>,
b: &Tensor<T, B>,
backend: &B,
) -> Tensor<T, B> {
elementwise_binary(a, b, backend, BinaryOp::Mul).expect("mul: incompatible shapes")
}
#[inline]
pub fn div<T: Scalar, B: BackendOps<T>>(
a: &Tensor<T, B>,
b: &Tensor<T, B>,
backend: &B,
) -> Tensor<T, B> {
elementwise_binary(a, b, backend, BinaryOp::Div).expect("div: incompatible shapes")
}
macro_rules! binary_assign_op {
($name:ident, $op:expr, $doc:expr) => {
#[doc = $doc]
#[inline]
pub fn $name<T: Scalar, B: BackendOps<T>>(
a: &mut Tensor<T, B>,
b: &Tensor<T, B>,
backend: &B,
) -> Result<(), B::Error> {
use coeus_tensor::broadcast::broadcast_shapes;
if a.shape() != b.shape() {
let out_shape = broadcast_shapes(a.shape(), b.shape()).ok_or_else(|| {
B::Error::from(BackendError::IncompatibleBroadcast {
operation: "elementwise_binary_assign",
from: b.shape().to_vec(),
to: a.shape().to_vec(),
})
})?;
if &out_shape[..] != a.shape() {
return Err(B::Error::from(BackendError::IncompatibleBroadcast {
operation: "elementwise_binary_assign",
from: b.shape().to_vec(),
to: a.shape().to_vec(),
}));
}
}
let (a_dest, a_layout) = a.storage_mut_and_layout();
let a_src: &B::DeviceBuffer<T> = unsafe { &*(a_dest as *const B::DeviceBuffer<T>) };
backend.elementwise_binary(
$op,
a_src,
a_layout,
b.storage(),
b.layout(),
a_dest,
a_layout,
)?;
Ok(())
}
};
}
binary_assign_op!(add_assign, BinaryOp::Add, "In-place element-wise addition.");
binary_assign_op!(
sub_assign,
BinaryOp::Sub,
"In-place element-wise subtraction."
);
binary_assign_op!(
mul_assign,
BinaryOp::Mul,
"In-place element-wise multiplication."
);
binary_assign_op!(div_assign, BinaryOp::Div, "In-place element-wise division.");
#[cfg(test)]
mod tests {
use super::*;
use coeus_core::SequentialBackend;
#[test]
fn incompatible_broadcast_panics() {
let backend = SequentialBackend::new();
let lhs = Tensor::from_slice([2], &[1.0_f32, 2.0]);
let rhs = Tensor::from_slice([3], &[3.0_f32, 4.0, 5.0]);
let result = std::panic::catch_unwind(|| add(&lhs, &rhs, &backend));
assert!(result.is_err(), "incompatible shapes must panic");
}
}