-
Notifications
You must be signed in to change notification settings - Fork 1
/
syntax.py
212 lines (158 loc) · 5.95 KB
/
syntax.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import numpy as np
import layers
class SyntaxOp:
def __init__(self, input=None):
self.inputs = [input]
def __add__(self, other):
return Sum(self, other)
def __neg__(self):
return Neg(self)
def __sub__(self, other):
return Sum(self, -other)
def __mul__(self, other):
return Mul(self, other)
def __div__(self, other):
raise Exception("Division not implemented")
# return Div(self, other)
def __str__(self, name=None):
if name is None:
name = self.__class__.__name__
input_str = ''
if len(self.inputs) > 0:
input_str = ', '.join([str(x) for x in self.inputs])
input_str = '(%s)' % input_str
return '%s%s' % (name, input_str)
def forward_variables(self, input_dict, depth=0, debug=False):
values = []
for input_op in self.inputs:
val = input_op.forward_variables(input_dict, depth + 1, debug)
values.append(val)
# if debug:
# print('%s%s -> %s' % ('\t' * (depth+1), input_op, val))
x = values[0] if len(values) == 1 else values
y = self.layer_forward(np.array(x))
if debug:
print('%s%s -> %s' % ('\t' * depth, self, y))
return y
def backward_variables(self, deltas, depth=0, debug=False):
if debug:
print('%s%s <- deltas %s' % ('\t' * depth, self, deltas))
deltas = self.layer_backward(deltas)
if len(self.inputs) == 1:
return self.inputs[0].backward_variables(deltas, depth + 1, debug)
else:
ret_deltas = []
for input_op, dJdy in zip(self.inputs, deltas):
delta = input_op.backward_variables(dJdy, depth + 1, debug)
if delta is not None:
ret_deltas.append(delta)
merged = self.merge_backprop_dicts(ret_deltas)
return merged
def update_weights(self, optimizer, depth=0, debug=False):
if debug:
print('%s%s' % ('\t' * depth, self))
self.layer_update_weights(optimizer)
for input in self.inputs:
input.update_weights(optimizer, depth + 1, debug)
@staticmethod
def merge_backprop_dicts(dicts):
merged = {}
for d in dicts:
for k, v in d.iteritems():
if k in merged:
merged[k] += v
else:
# very important to copy the object, not just point to it
merged[k] = np.copy(v)
return merged
def layer_forward(self, values, is_training=True):
return self.layer.forward(values, is_training)
def layer_backward(self, dJdy):
return self.layer.backward(dJdy)
def layer_update_weights(self, optimizer):
self.layer.update_weights(optimizer)
class Var(SyntaxOp):
def __init__(self, variable_name):
self.variable_name = variable_name
self.inputs = []
def forward_variables(self, input_dict, depth, debug):
val = input_dict[self.variable_name]
return val
def backward_variables(self, deltas, depth, debug):
if debug:
print('%sVar(%s) <- deltas %s' % ('\t' * depth, self.variable_name, deltas))
grad_dict = {}
grad_dict[self.variable_name] = deltas
return grad_dict
def layer_forward(self, values):
return values
# def layer_backward(self, dJdy):
# this should never be called
def layer_update_weights(self, optimizer):
return
def __str__(self):
return SyntaxOp.__str__(self, name=self.variable_name)
class Linear(SyntaxOp):
def __init__(self, in_size, out_size, initialize='random', dtype=None, input=None):
SyntaxOp.__init__(self, input)
self.layer = layers.Linear(in_size, out_size, initialize, dtype)
class WxBiasLinear(SyntaxOp):
def __init__(self, in_size, out_size, initialize_W, initialize_b, input=None):
SyntaxOp.__init__(self, input)
self.layer = layers.WxBiasLinear(in_size, out_size, initialize_W, initialize_b)
class Wx(SyntaxOp):
def __init__(self, in_size, out_size, initialize='random', input=None):
SyntaxOp.__init__(self, input)
self.layer = layers.Wx(in_size, out_size, initialize)
class PlusBias(SyntaxOp):
def __init__(self, in_size, initialize='random', input=None):
SyntaxOp.__init__(self, input)
self.layer = layers.PlusBias(in_size, initialize)
class Dropout(SyntaxOp):
def __init__(self, p, input=None):
SyntaxOp.__init__(self, input)
self.layer = layers.Dropout(p)
class Tanh(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Tanh()
self.inputs = args
class Softmax(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Softmax()
self.inputs = args
class Sigmoid(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Sigmoid()
self.inputs = args
class Sum(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Sum()
self.inputs = args
class Neg(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Neg()
self.inputs = args
class Mul(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Mul()
self.inputs = args
class Concat(SyntaxOp):
def __init__(self, *args):
self.layer = layers.Concat()
self.inputs = args
class Const(SyntaxOp):
def __init__(self, const):
SyntaxOp.__init__(self)
self.const = np.array([const])
self.inputs = []
def forward_variables(self, input_dict, depth, debug):
return self.const
def backward_variables(self, deltas, depth, debug):
pass
def update_weights(self, optimizer, depth=0, debug=False):
pass
class Store(SyntaxOp):
def __init__(self, in_size, input):
SyntaxOp.__init__(self, input)
self.layer = layers.Store(in_size)
self.read_forward = self.layer.read_forward