1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::{ops::{Reshape, GetShape}, tensor::{Variable, Tensor, Backward, ops::RefCellReplaceTake}, shape::{IntoShape, Shape}};
use std::{ops::Add, cell::RefCell};

#[derive(Debug, Clone)]
pub struct ReshapeBackwardV<'g, S> {
    grad: &'g RefCell<S>,
    shape: Shape,
}

impl<S, S2> Backward<S> for ReshapeBackwardV<'_, S2>
where
    S2: Default + Add<<S as Reshape>::Output, Output = S2>,
    S: Reshape,
{
    fn backward(self, res_grad: S) {
        self.grad.replace_take(|grad| grad + res_grad.reshape(self.shape));
    }
}

impl<'g, S> Reshape for &'g Variable<S>
where
    S: Clone + Reshape + GetShape,
{
    type Output = Tensor<<S as Reshape>::Output, ReshapeBackwardV<'g, S>>;
    fn reshape(self, shape: impl IntoShape) -> Self::Output {
        Tensor {
            data: (*self.data()).clone().reshape(shape),
            grad_fn: ReshapeBackwardV {
                grad: &self.grad,
                shape: self.data().shape(),
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct ReshapeBackwardT<F> {
    grad_fn: F,
    shape: Shape,
}

impl<S, F> Backward<S> for ReshapeBackwardT<F>
where
    S: Reshape,
    F: Backward<<S as Reshape>::Output>,
{
    fn backward(self, res_grad: S) {
        self.grad_fn.backward(res_grad.reshape(self.shape));
    }
}

impl<S, F> Reshape for Tensor<S, F>
where
    S: Reshape + GetShape,
{
    type Output = Tensor<<S as Reshape>::Output, ReshapeBackwardT<F>>;
    fn reshape(self, res_shape: impl IntoShape) -> Self::Output {
        let shape = self.data.shape();
        Tensor {
            data: self.data.reshape(res_shape),
            grad_fn: ReshapeBackwardT {
                grad_fn: self.grad_fn,
                shape,
            }
        }
    }
}