use smallvec::smallvec;
use crate::{Element, Recordable, Shape, Tensor};
use super::{Cotangents, Operation, Reads, binary};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Add;
impl Add {
pub(crate) fn arity(&self) -> usize {
2
}
pub(crate) fn reads(&self) -> Reads {
Reads::NOTHING
}
pub(crate) fn infer_shape(&self, operands: &[Shape]) -> Shape {
let (left, right) = binary(operands);
assert_eq!(left, right, "addition requires operands of equal shapes");
left.clone()
}
}
impl Add {
pub(crate) fn forward<E: Element>(&self, operands: &[&Tensor<E>]) -> Tensor<E> {
let (&left, &right) = binary(operands);
left.clone() + right.clone()
}
}
impl<Rule: Recordable> Operation<Rule> for Add {
fn backward(&self, _operands: &[&Rule], _output: &Rule, gradient: &Rule) -> Cotangents<Rule> {
smallvec![Some(gradient.clone()), Some(gradient.clone())]
}
}
#[cfg(test)]
#[path = "tests/add_tests.rs"]
mod tests;