Skip to main content

coeus_ops/binary/
kernel.rs

1// ── Binary kernel ──
2// Generic element-wise binary kernel with broadcasting.
3
4use crate::backend_ops::{BinaryOp, ElementwiseOps};
5use coeus_core::{BackendError, Scalar};
6use coeus_tensor::broadcast::broadcast_shapes;
7use coeus_tensor::Tensor;
8
9/// Element-wise binary operation with broadcasting.
10///
11/// Uses `Tensor::alloc_on` (no zero-init) because every output element is
12/// unconditionally overwritten by the broadcast kernel.
13#[inline]
14pub fn elementwise_binary<T: Scalar, B: ElementwiseOps<T>>(
15    a: &Tensor<T, B>,
16    b: &Tensor<T, B>,
17    backend: &B,
18    op: BinaryOp,
19) -> Result<Tensor<T, B>, B::Error> {
20    let out_shape = broadcast_shapes(a.shape(), b.shape()).ok_or_else(|| {
21        B::Error::from(BackendError::IncompatibleBroadcast {
22            operation: "elementwise_binary",
23            from: a.shape().to_vec(),
24            to: b.shape().to_vec(),
25        })
26    })?;
27
28    // SAFETY: The following operation writes every output element before it is read.
29    let mut out: Tensor<T, B> = unsafe { Tensor::alloc_on(out_shape.clone(), backend) }?;
30
31    let (out_storage, out_layout) = out.storage_mut_and_layout()?;
32    backend.elementwise_binary(
33        op,
34        a.storage(),
35        a.layout(),
36        b.storage(),
37        b.layout(),
38        out_storage,
39        out_layout,
40    )?;
41
42    Ok(out)
43}
44
45/// Apply element-wise binary operation to `a` and `b`, writing result to `out`.
46#[inline]
47pub fn elementwise_binary_to<T: Scalar, B: ElementwiseOps<T>>(
48    a: &Tensor<T, B>,
49    b: &Tensor<T, B>,
50    out: &mut Tensor<T, B>,
51    backend: &B,
52    op: BinaryOp,
53) -> Result<(), B::Error> {
54    let (out_storage, out_layout) = out.storage_mut_and_layout()?;
55    backend.elementwise_binary(
56        op,
57        a.storage(),
58        a.layout(),
59        b.storage(),
60        b.layout(),
61        out_storage,
62        out_layout,
63    )
64}