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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
    Appellation: grad <mod>
    Contrib: FL03 <jo3mccain@icloud.com>
*/
use crate::actions::grad::GradStore;
use crate::prelude::{Scalar, TensorExpr, TensorId, TensorResult};
use crate::TensorBase;
use acme::prelude::{BinaryOp, Store, UnaryOp};

pub(crate) type Visited<K = TensorId> = std::collections::HashMap<K, bool>;

macro_rules! entry {
    ($ctx:expr, $entry:expr) => {
        entry!($ctx, $entry, $entry.zeros_like())
    };
    ($ctx:expr, $entry:expr, $default:expr) => {
        $ctx.entry($entry.id()).or_insert($default)
    };
}

impl<T> TensorBase<T>
where
    T: Scalar,
{
    /// [toposort](TensorBase::toposort) is a utilitarian functions that returns a topologically sorted list of nodes.
    fn toposort(&self, reverse: bool) -> Vec<&TensorBase<T>> {
        // Here, the sorted nodes are passed as an owned value rather than as a mutable reference to workaround some lifetime limitations.
        fn walk<'a, T>(
            scope: &'a TensorBase<T>,
            nodes: Vec<&'a TensorBase<T>>,
            visited: &mut Visited<TensorId>,
        ) -> (bool, Vec<&'a TensorBase<T>>) {
            if let Some(&tg) = visited.get(&scope.id()) {
                return (tg, nodes);
            }
            // track the gradient of the current node
            let mut track = false;
            // recursively call on the children nodes
            let mut nodes = if scope.is_variable() {
                // Do not call recursively on the "leaf" nodes.
                track = true;
                nodes
            } else if let Some(op) = scope.op().op() {
                match op {
                    TensorExpr::Binary(lhs, rhs, _kind) => {
                        let (tg, nodes) = walk(lhs, nodes, visited);
                        track |= tg;
                        let (tg, nodes) = walk(rhs, nodes, visited);
                        track |= tg;
                        nodes
                    }
                    TensorExpr::Unary(a, _kind) => {
                        let (tg, nodes) = walk(a, nodes, visited);
                        track |= tg;
                        nodes
                    }
                    _ => nodes,
                }
            } else {
                nodes
            };
            visited.insert(scope.id(), track);
            if track {
                nodes.push(scope);
            }
            (track, nodes)
        }
        // walk through the dag
        let (_tg, mut nodes) = walk(self, Vec::new(), &mut Visited::new());
        // reverse the nodes; if needed
        if reverse {
            nodes.reverse();
        }
        // return the sorted nodes
        nodes
    }

    pub fn grad(&self) -> TensorResult<GradStore<T>> {
        // get the sorted nodes
        let sorted = self.toposort(true);
        // initialize a new gradient store
        let mut store = GradStore::new();
        // insert the gradient w.r.t. the current node
        store.insert(self.id(), self.ones_like());

        for node in sorted.iter() {
            if node.is_variable() {
                continue;
            }
            // get the gradient of the node
            let grad = store.remove(&node.id()).expect("Gradient not found");
            // detach the gradient
            let grad = grad.detach();
            // handle the different types of operations
            if let Some(op) = &*node.op {
                match op {
                    TensorExpr::Binary(lhs, rhs, kind) => match kind {
                        BinaryOp::Add(_) => {
                            *entry!(store, lhs) += &grad;
                            *entry!(store, rhs) += &grad;
                        }
                        BinaryOp::Div(_) => {
                            *entry!(store, lhs) += &grad / rhs.as_ref();
                            *entry!(store, rhs) -=
                                &grad * lhs.as_ref() / (rhs.as_ref() * rhs.as_ref());
                        }
                        BinaryOp::Mul(_) => {
                            *entry!(store, lhs) += &grad * rhs.as_ref();
                            *entry!(store, rhs) += &grad * lhs.as_ref();
                        }
                        BinaryOp::Sub(_) => {
                            *entry!(store, lhs) += &grad;
                            *entry!(store, rhs) -= &grad;
                        }
                        _ => todo!(),
                    },
                    TensorExpr::BinaryScalar(lhs, rhs, kind) => match kind {
                        BinaryOp::Add(_) => {
                            *entry!(store, lhs) += &grad;
                        }
                        BinaryOp::Div(_) => {
                            *entry!(store, lhs) += &grad / *rhs;
                        }
                        BinaryOp::Mul(_) => {
                            *entry!(store, lhs) += &grad * *rhs;
                        }
                        BinaryOp::Pow => {
                            *entry!(store, lhs) += &grad * *rhs * lhs.pow(*rhs - T::one());
                        }
                        BinaryOp::Sub(_) => {
                            *entry!(store, lhs) += &grad;
                        }
                        _ => todo!(),
                    },
                    TensorExpr::Unary(val, kind) => match kind {
                        UnaryOp::Cos => {
                            *entry!(store, val) -= &grad * val.sin();
                        }
                        UnaryOp::Cosh => {
                            *entry!(store, val) += &grad * val.sinh();
                        }
                        UnaryOp::Exp => {
                            *entry!(store, val) += &grad * val.exp();
                        }
                        UnaryOp::Neg => {
                            *entry!(store, val) -= &grad;
                        }
                        UnaryOp::Sin => {
                            *entry!(store, val) += &grad * val.cos();
                        }
                        UnaryOp::Sinh => {
                            *entry!(store, val) += &grad * val.cosh();
                        }
                        UnaryOp::Sqrt => {
                            *entry!(store, val) +=
                                &grad / (val.clone().sqrt() * T::from(2).unwrap());
                        }
                        UnaryOp::Tan => {
                            *entry!(store, val) += &grad / val.clone().cos().sqr();
                        }

                        _ => todo!(),
                    },
                    _ => {}
                }
            }
        }

        Ok(store)
    }
}