-
Notifications
You must be signed in to change notification settings - Fork 1
/
nn.py
218 lines (164 loc) · 5.74 KB
/
nn.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
213
214
215
216
217
218
from microjax import grad, exp, sin, value_and_grad
import numbers
import random
import math
class Module:
"""
i am sure there better ways to do this,
but its 4am, coffine in my system stating to loose its effect,
i can write todo: but i am not gonna do it later, so.. it is what it
"""
def state_dict(self):
def _state_dict(root, state):
state = {}
for k, v in root.__dict__.items():
if isinstance(v, numbers.Number):
state[k] = v
elif isinstance(v, ModuleList):
sub_state = [
(m.state_dict() if isinstance(m, Module) else m) for m in v
]
for i, item in enumerate(sub_state):
if isinstance(item, dict):
for sub_k, sub_v in item.items():
state[f"{k}.{i}.{sub_k}"] = sub_v
else:
state[f"{k}.{i}"] = item
elif isinstance(v, Module):
sub_state = v.state_dict()
for sub_k, sub_v in sub_state.items():
state[f"{k}.{sub_k}"] = sub_v
return state
return _state_dict(self, {})
def load_state_dict(self, state):
sub_state = {}
for key, value in state.items():
if "." in key:
attrs_name = key.split(".")
attr = self
for name in attrs_name[:-1]:
if isinstance(attr, ModuleList):
attr = attr[int(name)]
else:
attr = getattr(attr, name)
if isinstance(attr, ModuleList):
attr[int(attrs_name[-1])] = value
else:
setattr(attr, attrs_name[-1], value)
else:
setattr(self, key, value)
class ModuleList(Module, list):
def __init__(self, args):
super().__init__(args)
class Neuron(Module):
def __init__(self, n_inputs):
self.weights = ModuleList(
[(random.randint(-100, 100) / 100) for _ in range(n_inputs)]
)
self.bias = 0.0
def __call__(self, inputs):
output = 0
for w, x in zip(self.weights, inputs):
output = output + w * x
return output + self.bias
class Layer(Module):
def __init__(self, n_inputs, n_outputs):
self.layers = ModuleList([Neuron(n_inputs) for _ in range(n_outputs)])
def __call__(self, inputs):
# print(f"self.layers: {self.layers}")
return [layer(inputs) for layer in self.layers]
# ===========
def sigmoid(x):
return 1 / (1 + exp(-x))
def tanh(x):
return 2 * sigmoid(2 * x) - 1
class Sigmoid(Module):
def __call__(self, inputs):
return [sigmoid(x) for x in inputs]
class Tanh(Module):
def __call__(self, inputs):
return [tanh(x) for x in inputs]
# ===========
# when you do gfunc = grad(func) it makes closure over func
# all args to gfunc(args) are boxed to calculate gradients
# that why we can pass model model directly
# with this func_with_model_state model_forward will take state as input
# but will act as if it recived model
def func_with_model_state(func, model):
def model_forward(state, *args):
model.load_state_dict(state)
return func(model, *args)
return model_forward
# ============
class MLP(Module):
def __init__(self):
self.l1 = Layer(2, 4)
self.l2 = Layer(4, 1)
self.tanh = Tanh()
self.sigmoid = Sigmoid()
def __call__(self, x):
x = self.l1(x)
x = self.tanh(x)
x = self.l2(x)
x = self.sigmoid(x)
return x
def train_step(model, inputs, targets):
loss = 0
for x, y in zip(inputs, targets):
preds = 0
preds = model(x)
local_loss = 0
# <mse_loss>
for p, t in zip(preds, y):
diff = p - t
local_loss += diff * diff
loss += local_loss / len(preds)
# </mse_loss>
return loss / len(inputs)
class AdamOptimizer:
def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999, epsilon=1e-8):
self.learning_rate = learning_rate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.t = 0
self.m = {}
self.v = {}
def step(self, weights: dict, gradients: dict):
for key in gradients:
if key not in self.m:
self.m[key] = 0
self.v[key] = 0
self.t += 1
for key, grad in gradients.items():
self.m[key] = self.beta1 * self.m[key] + (1 - self.beta1) * grad
self.v[key] = self.beta2 * self.v[key] + (1 - self.beta2) * (grad**2)
m_hat = self.m[key] / (1 - self.beta1**self.t)
v_hat = self.v[key] / (1 - self.beta2**self.t)
weights[key] -= self.learning_rate * m_hat / (v_hat**0.5 + self.epsilon)
return weights
# Example usage:
adam = AdamOptimizer(learning_rate=0.069)
model = MLP()
out_func = func_with_model_state(train_step, model)
# xor data
data = [[0, 0], [0, 1], [1, 0], [1, 1]]
targets = [[0], [1], [1], [0]]
# print(train_step(model,data,targets))
state = model.state_dict()
grad_func = value_and_grad(out_func)
iters = 500
# print(grad_func(state, data, targets))
model.load_state_dict(state)
for x, y in zip(data, targets):
print(f"{y[0]} => {model(x)[0]:.2f}")
print("--")
for idx in range(iters):
loss, grads = grad_func(state, data, targets)
if idx % 50 == 0:
print(f"loss: {loss}")
state = adam.step(state, grads)
print("--")
model.load_state_dict(state)
for x, y in zip(data, targets):
print(f"{y[0]} => {model(x)[0]:.2f}")