Skip to main content

coeus_ops/binary/
arithmetic.rs

1// ── Binary arithmetic ops ──
2
3use super::kernel::elementwise_binary;
4use crate::backend_ops::{BinaryOp, ElementwiseOps};
5use coeus_core::{BackendError, Scalar};
6use coeus_tensor::Tensor;
7
8/// Element-wise addition.
9///
10/// # Examples
11///
12/// ```
13/// use coeus_tensor::Tensor;
14/// use coeus_core::SequentialBackend;
15/// use coeus_ops::add;
16///
17/// let backend = SequentialBackend::new();
18/// let a = Tensor::<f32, SequentialBackend>::from_slice([2], &[1.0, 2.0])
19///     .expect("example tensor allocation succeeds");
20/// let b = Tensor::<f32, SequentialBackend>::from_slice([2], &[3.0, 4.0])
21///     .expect("example tensor allocation succeeds");
22/// let c = add(&a, &b, &backend).expect("example addition succeeds");
23/// assert_eq!(c.as_slice(), &[4.0, 6.0]);
24/// ```
25#[inline]
26pub fn add<T: Scalar, B: ElementwiseOps<T>>(
27    a: &Tensor<T, B>,
28    b: &Tensor<T, B>,
29    backend: &B,
30) -> Result<Tensor<T, B>, B::Error> {
31    elementwise_binary(a, b, backend, BinaryOp::Add)
32}
33
34/// Element-wise subtraction.
35///
36/// # Examples
37///
38/// ```
39/// use coeus_tensor::Tensor;
40/// use coeus_core::SequentialBackend;
41/// use coeus_ops::sub;
42///
43/// let backend = SequentialBackend::new();
44/// let a = Tensor::<f32, SequentialBackend>::from_slice([4], &[5.0, 6.0, 7.0, 8.0])
45///     .expect("example tensor allocation succeeds");
46/// let b = Tensor::<f32, SequentialBackend>::from_slice([4], &[1.0, 2.0, 3.0, 4.0])
47///     .expect("example tensor allocation succeeds");
48/// let c = sub(&a, &b, &backend).expect("example subtraction succeeds");
49/// assert_eq!(c.as_slice(), &[4.0, 4.0, 4.0, 4.0]);
50/// ```
51#[inline]
52pub fn sub<T: Scalar, B: ElementwiseOps<T>>(
53    a: &Tensor<T, B>,
54    b: &Tensor<T, B>,
55    backend: &B,
56) -> Result<Tensor<T, B>, B::Error> {
57    elementwise_binary(a, b, backend, BinaryOp::Sub)
58}
59
60/// Element-wise multiplication.
61///
62/// # Examples
63///
64/// ```
65/// use coeus_tensor::Tensor;
66/// use coeus_core::SequentialBackend;
67/// use coeus_ops::mul;
68///
69/// let backend = SequentialBackend::new();
70/// let a = Tensor::<f32, SequentialBackend>::from_slice([4], &[1.0, 2.0, 3.0, 4.0])
71///     .expect("example tensor allocation succeeds");
72/// let b = Tensor::<f32, SequentialBackend>::from_slice([4], &[5.0, 6.0, 7.0, 8.0])
73///     .expect("example tensor allocation succeeds");
74/// let c = mul(&a, &b, &backend).expect("example multiplication succeeds");
75/// assert_eq!(c.as_slice(), &[5.0, 12.0, 21.0, 32.0]);
76/// ```
77#[inline]
78pub fn mul<T: Scalar, B: ElementwiseOps<T>>(
79    a: &Tensor<T, B>,
80    b: &Tensor<T, B>,
81    backend: &B,
82) -> Result<Tensor<T, B>, B::Error> {
83    elementwise_binary(a, b, backend, BinaryOp::Mul)
84}
85
86/// Element-wise division.
87///
88/// # Examples
89///
90/// ```
91/// use coeus_tensor::Tensor;
92/// use coeus_core::SequentialBackend;
93/// use coeus_ops::div;
94///
95/// let backend = SequentialBackend::new();
96/// let a = Tensor::<f32, SequentialBackend>::from_slice([4], &[6.0, 8.0, 10.0, 12.0])
97///     .expect("example tensor allocation succeeds");
98/// let b = Tensor::<f32, SequentialBackend>::from_slice([4], &[2.0, 4.0, 5.0, 6.0])
99///     .expect("example tensor allocation succeeds");
100/// let c = div(&a, &b, &backend).expect("example division succeeds");
101/// let s = c.as_slice();
102/// assert!((s[0] - 3.0).abs() < 1e-5);
103/// assert!((s[1] - 2.0).abs() < 1e-5);
104/// assert!((s[2] - 2.0).abs() < 1e-5);
105/// assert!((s[3] - 2.0).abs() < 1e-5);
106/// ```
107#[inline]
108pub fn div<T: Scalar, B: ElementwiseOps<T>>(
109    a: &Tensor<T, B>,
110    b: &Tensor<T, B>,
111    backend: &B,
112) -> Result<Tensor<T, B>, B::Error> {
113    elementwise_binary(a, b, backend, BinaryOp::Div)
114}
115
116macro_rules! binary_assign_op {
117    ($name:ident, $op:expr, $doc:expr) => {
118        #[doc = $doc]
119        #[inline]
120        pub fn $name<T: Scalar, B: ElementwiseOps<T>>(
121            a: &mut Tensor<T, B>,
122            b: &Tensor<T, B>,
123            backend: &B,
124        ) -> Result<(), B::Error> {
125            use coeus_tensor::broadcast::broadcast_shapes;
126            if a.shape() != b.shape() {
127                let out_shape = broadcast_shapes(a.shape(), b.shape()).ok_or_else(|| {
128                    B::Error::from(BackendError::IncompatibleBroadcast {
129                        operation: "elementwise_binary_assign",
130                        from: b.shape().to_vec(),
131                        to: a.shape().to_vec(),
132                    })
133                })?;
134                if &out_shape[..] != a.shape() {
135                    return Err(B::Error::from(BackendError::IncompatibleBroadcast {
136                        operation: "elementwise_binary_assign",
137                        from: b.shape().to_vec(),
138                        to: a.shape().to_vec(),
139                    }));
140                }
141            }
142            let (a_dest, a_layout) = a.storage_and_layout_mut();
143            backend.elementwise_binary_assign($op, a_dest, a_layout, b.storage(), b.layout())?;
144            Ok(())
145        }
146    };
147}
148
149binary_assign_op!(add_assign, BinaryOp::Add, "In-place element-wise addition.");
150binary_assign_op!(
151    sub_assign,
152    BinaryOp::Sub,
153    "In-place element-wise subtraction."
154);
155binary_assign_op!(
156    mul_assign,
157    BinaryOp::Mul,
158    "In-place element-wise multiplication."
159);
160binary_assign_op!(div_assign, BinaryOp::Div, "In-place element-wise division.");
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use coeus_core::{BackendError, SequentialBackend};
166
167    #[test]
168    fn incompatible_broadcast_returns_typed_error() {
169        let backend = SequentialBackend::new();
170        let lhs = Tensor::from_slice([2], &[1.0_f32, 2.0])
171            .expect("invariant: test backend operation succeeds");
172        let rhs = Tensor::from_slice([3], &[3.0_f32, 4.0, 5.0])
173            .expect("invariant: test backend operation succeeds");
174
175        let error = match add(&lhs, &rhs, &backend) {
176            Err(error) => error,
177            Ok(_) => panic!("incompatible shapes must return a typed error"),
178        };
179        assert_eq!(
180            error,
181            BackendError::IncompatibleBroadcast {
182                operation: "elementwise_binary",
183                from: vec![2],
184                to: vec![3],
185            }
186        );
187    }
188
189    #[test]
190    fn cpu_assign_broadcasts_without_replacing_storage() {
191        let backend = SequentialBackend::new();
192        let mut lhs = Tensor::from_slice([2, 2], &[1.0_f32, 2.0, 3.0, 4.0])
193            .expect("invariant: test backend operation succeeds");
194        let rhs = Tensor::from_slice([1, 2], &[10.0_f32, 20.0])
195            .expect("invariant: test backend operation succeeds");
196        let allocation = lhs.as_slice().as_ptr();
197
198        add_assign(&mut lhs, &rhs, &backend).expect("valid row broadcast");
199
200        assert_eq!(lhs.as_slice(), &[11.0, 22.0, 13.0, 24.0]);
201        assert_eq!(lhs.as_slice().as_ptr(), allocation);
202    }
203}