-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautograd.h
111 lines (80 loc) · 2.26 KB
/
autograd.h
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
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cassert>
#include <vector>
#ifndef NEURON
#define NEURON
namespace nn {
class graph;
class var;
struct op {
virtual std::vector <double> operator () (const std::vector <std::vector <double>>&) = 0;
virtual std::vector <std::vector <double>> grad (const std::vector <double>&) = 0;
};
class var {
public:
friend class graph;
class iterator;
private:
std::vector <double> v;
op *operation;
std::vector <var*> inputs;
std::vector <std::vector <double>> dereference_reference_vec (const std::vector <var*> &);
template <typename T>
var (const std::vector <var::iterator> &incoming, T *t_operation) {
std::vector <var*> raw_in;
for (auto i : incoming)
raw_in.push_back (i.reference);
operation = t_operation;
inputs = raw_in;
v = t_operation -> operator () (dereference_reference_vec (raw_in));
}
public:
class iterator {
friend class std::hash <nn::var::iterator>;
friend class graph;
friend class var;
var *reference;
public:
iterator ();
iterator (var *);
iterator operator = (var *);
bool operator == (var *);
bool operator == (const iterator &);
bool operator != (var *);
bool operator != (const iterator &);
var& operator * ();
var* operator -> () const;
};
var (const std::vector <double> &);
std::vector <double> get_value ();
};
class graph {
std::vector <var*> var_list;
std::vector <op*> op_list;
std::unordered_map <var*, int> find_outdegrees (var *);
void add_to_vector (std::vector <double> &, const std::vector <double> &);
public:
void clear ();
template <typename T>
var::iterator operator () (const std::vector <var::iterator> &inputs, const T &t) {
op_list.push_back (new T (t));
var_list.push_back (new var (inputs, *op_list.rbegin ()));
return var::iterator (*var_list.rbegin());
}
std::vector <std::vector <double>> compute_gradients (var::iterator tar, const std::vector <var::iterator> &var_list);
~graph ();
};
}
namespace std {
template <>
struct hash <nn::var::iterator> {
hash <nn::var*> reference_hash;
std::size_t operator () (const nn::var::iterator &it) const {
return reference_hash (it.reference);
}
};
}
#endif