-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules.py
608 lines (458 loc) · 18.8 KB
/
modules.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import numpy as np
import math
class Module(object):
"""
Basically, you can think of a module as of a something (black box)
which can process `input` data and produce `ouput` data.
This is like applying a function which is called `forward`:
output = module.forward(input)
The module should be able to perform a backward pass: to differentiate the `forward` function.
More, it should be able to differentiate it if is a part of chain (chain rule).
The latter implies there is a gradient from previous step of a chain rule.
gradInput = module.backward(input, gradOutput)
"""
def __init__ (self):
self.output = None
self.gradInput = None
self.training = True
def forward(self, input):
"""
Takes an input object, and computes the corresponding output of the module.
"""
return self.updateOutput(input)
def backward(self,input, gradOutput):
"""
Performs a backpropagation step through the module, with respect to the given input.
This includes
- computing a gradient w.r.t. `input` (is needed for further backprop),
- computing a gradient w.r.t. parameters (to update parameters while optimizing).
"""
self.updateGradInput(input, gradOutput)
self.accGradParameters(input, gradOutput)
return self.gradInput
def updateOutput(self, input):
"""
Computes the output using the current parameter set of the class and input.
This function returns the result which is stored in the `output` field.
Make sure to both store the data in `output` field and return it.
"""
# The easiest case:
# self.output = input
# return self.output
pass
def updateGradInput(self, input, gradOutput):
"""
Computing the gradient of the module with respect to its own input.
This is returned in `gradInput`. Also, the `gradInput` state variable is updated accordingly.
The shape of `gradInput` is always the same as the shape of `input`.
Make sure to both store the gradients in `gradInput` field and return it.
"""
# The easiest case:
# self.gradInput = gradOutput
# return self.gradInput
pass
def accGradParameters(self, input, gradOutput):
"""
Computing the gradient of the module with respect to its own parameters.
No need to override if module has no parameters (e.g. ReLU).
"""
pass
def zeroGradParameters(self):
"""
Zeroes `gradParams` variable if the module has params.
"""
pass
def getParameters(self):
"""
Returns a list with its parameters.
If the module does not have parameters return empty list.
"""
return []
def getGradParameters(self):
"""
Returns a list with gradients with respect to its parameters.
If the module does not have parameters return empty list.
"""
return []
def train(self):
"""
Sets training mode for the module.
Training and testing behaviour differs for Dropout, BatchNorm.
"""
self.training = True
def evaluate(self):
"""
Sets evaluation mode for the module.
Training and testing behaviour differs for Dropout, BatchNorm.
"""
self.training = False
def __repr__(self):
"""
Pretty printing. Should be overrided in every module if you want
to have readable description.
"""
return "Module"
class Sequential(Module):
"""
This class implements a container, which processes `input` data sequentially.
`input` is processed by each module (layer) in self.modules consecutively.
The resulting array is called `output`.
"""
def __init__ (self):
super(Sequential, self).__init__()
self.modules = []
self.y = []
def add(self, module):
"""
Adds a module to the container.
"""
self.modules.append(module)
def updateOutput(self, input):
"""
Basic workflow of FORWARD PASS:
y_0 = module[0].forward(input)
y_1 = module[1].forward(y_0)
...
output = module[n-1].forward(y_{n-2})
Just write a little loop.
"""
old_val = input
self.y.append(old_val)
for module in self.modules:
old_val = module.forward(old_val)
self.y.append(old_val)
self.output = old_val
return self.output
def backward(self, input, gradOutput):
"""
Workflow of BACKWARD PASS:
g_{n-1} = module[n-1].backward(y_{n-2}, gradOutput)
g_{n-2} = module[n-2].backward(y_{n-3}, g_{n-1})
...
g_1 = module[1].backward(y_0, g_2)
gradInput = module[0].backward(input, g_1)
!!!
To ech module you need to provide the input, module saw while forward pass,
it is used while computing gradients.
Make sure that the input for `i-th` layer the output of `module[i]` (just the same input as in forward pass)
and NOT `input` to this Sequential module.
!!!
"""
g_val = gradOutput
n = self.modules.count
for i in range(n):
g_val = module[n - i - 1].backward(self.modules[n - i - 1], g_val)
self.gradInput = g_val
# Your code goes here. ################################################
return self.gradInput
def zeroGradParameters(self):
for module in self.modules:
module.zeroGradParameters()
def getParameters(self):
"""
Should gather all parameters in a list.
"""
return [x.getParameters() for x in self.modules]
def getGradParameters(self):
"""
Should gather all gradients w.r.t parameters in a list.
"""
return [x.getGradParameters() for x in self.modules]
def __repr__(self):
string = "".join([str(x) + '\n' for x in self.modules])
return string
def __getitem__(self,x):
return self.modules.__getitem__(x)
def train(self):
"""
Propagates training parameter through all modules
"""
self.training = True
for module in self.modules:
module.train()
def evaluate(self):
"""
Propagates training parameter through all modules
"""
self.training = False
for module in self.modules:
module.evaluate()
class Linear(Module):
"""
A module which applies a linear transformation
A common name is fully-connected layer, InnerProductLayer in caffe.
The module should work with 2D input of shape (n_samples, n_feature).
"""
def __init__(self, n_in, n_out):
super(Linear, self).__init__()
# This is a nice initialization
stdv = 1./np.sqrt(n_in)
self.W = np.random.uniform(-stdv, stdv, size = (n_out, n_in))
self.b = np.random.uniform(-stdv, stdv, size = n_out)
self.gradW = np.zeros_like(self.W)
self.gradb = np.zeros_like(self.b)
def updateOutput(self, input):
# Your code goes here. ################################################
self.output = np.Add(np.dot(input, self.W.T), self.b)
return self.output
def updateGradInput(self, input, gradOutput):
# Your code goes here. ################################################
self.gradInput = np.dot(gradOutput, input)
return self.gradInput
def accGradParameters(self, input, gradOutput):
# Your code goes here. ################################################
self.gradW = np.dot(input.T, gradOutput).T
self.gradb = np.sum(gradOutput, axis=0)
pass
def zeroGradParameters(self):
self.gradW.fill(0)
self.gradb.fill(0)
def getParameters(self):
return [self.W, self.b]
def getGradParameters(self):
return [self.gradW, self.gradb]
def __repr__(self):
s = self.W.shape
q = 'Linear %d -> %d' %(s[1],s[0])
return q
class SoftMax(Module):
def __init__(self):
super(SoftMax, self).__init__()
def updateOutput(self, input):
# start with normalization for numerical stability
self.output = np.subtract(input, input.max(axis=1, keepdims=True))
self.output = np.divide(np.exp(self.output), np.sum(np.exp(self.output), axis=1, keepdims=True))
return self.output
def updateGradInput(self, input, gradOutput):
#self.data * (1. - self.data) Where self.data is the softmax of the input, previously computed from the forward pass.
self.gradInput = gradOutput * (1. - gradOutput)
return self.gradInput
def __repr__(self):
return "SoftMax"
class LogSoftMax(Module):
def __init__(self):
super(LogSoftMax, self).__init__()
def updateOutput(self, input):
# start with normalization for numerical stability
self.output = np.subtract(input, input.max(axis=1, keepdims=True))
self.output = np.subtract(self.output, np.log(np.sum(np.exp(self.output), axis=1, keepdims=True)))
return self.output
def updateGradInput(self, input, gradOutput):
dyi_dxi = 1 - math.exp(input) / math.fsum(math.exp(input))
return self.gradInput
def __repr__(self):
return "LogSoftMax"
class BatchNormalization(Module):
EPS = 1e-3
def __init__(self, alpha = 0.):
super(BatchNormalization, self).__init__()
self.alpha = alpha
self.moving_mean = None
self.moving_variance = None
def updateOutput(self, input):
# Your code goes here. ################################################
# use self.EPS please
# self.moving_mean = self.moving_mean * alpha + np.mean(input) * (1 - alpha)
# self.moving_variance = self.moving_variance * alpha + np.var(input) * (1 - alpha)
# self.output = (input - np.mean(input)) / (np.sqrt(np.var(input) + EPS))
return self.output
def updateGradInput(self, input, gradOutput):
# Your code goes here. ################################################
#self.gradInput =
return self.gradInput
def __repr__(self):
return "BatchNormalization"
class ChannelwiseScaling(Module):
"""
Implements linear transform of input y = \gamma * x + \beta
where \gamma, \beta - learnable vectors of length x.shape[-1]
"""
def __init__(self, n_out):
super(ChannelwiseScaling, self).__init__()
stdv = 1./np.sqrt(n_out)
self.gamma = np.random.uniform(-stdv, stdv, size=n_out)
self.beta = np.random.uniform(-stdv, stdv, size=n_out)
self.gradGamma = np.zeros_like(self.gamma)
self.gradBeta = np.zeros_like(self.beta)
def updateOutput(self, input):
self.output = input * self.gamma + self.beta
return self.output
def updateGradInput(self, input, gradOutput):
self.gradInput = gradOutput * self.gamma
return self.gradInput
def accGradParameters(self, input, gradOutput):
self.gradBeta = np.sum(gradOutput, axis=0)
self.gradGamma = np.sum(gradOutput*input, axis=0)
def zeroGradParameters(self):
self.gradGamma.fill(0)
self.gradBeta.fill(0)
def getParameters(self):
return [self.gamma, self.beta]
def getGradParameters(self):
return [self.gradGamma, self.gradBeta]
def __repr__(self):
return "ChannelwiseScaling"
class Dropout(Module):
def __init__(self, p=0.5):
super(Dropout, self).__init__()
self.p = p
self.mask = None
def updateOutput(self, input):
self.output = input
if self.training = True:
self.mask = np.random.uniform(0, 1, size=input.shape[0]) > self.p
self.output = np.multiply(input, self.mask)
# Your code goes here. ################################################
return self.output
def updateGradInput(self, input, gradOutput):
# Your code goes here. ################################################
self.gradInput = gradOutput
if self.training == True:
self.gradInput = np.multiply(self.mask, gradOutput)
return self.gradInput
def __repr__(self):
return "Dropout"
class ReLU(Module):
def __init__(self):
super(ReLU, self).__init__()
def updateOutput(self, input):
self.output = np.maximum(input, 0)
return self.output
def updateGradInput(self, input, gradOutput):
self.gradInput = np.multiply(gradOutput , input > 0)
return self.gradInput
def __repr__(self):
return "ReLU"
class LeakyReLU(Module):
def __init__(self, slope = 0.03):
super(LeakyReLU, self).__init__()
self.slope = slope
def updateOutput(self, input):
self.output = np.multiply(input, (input < 0) * (self.slope - 1) + 1)
return self.output
def updateGradInput(self, input, gradOutput):
dInput = np.ones_like(input)
dInput[Input < 0] = slope
self.gradInput = np.multiply(gradOutput , dInput)
return self.gradInput
def __repr__(self):
return "LeakyReLU"
class ELU(Module):
def __init__(self, alpha = 1.0):
super(ELU, self).__init__()
self.alpha = alpha
def updateOutput(self, input):
# Your code goes here. ################################################
self.output = np.add(np.multiply(input > 0, input),
np.multipy(input <= 0, self.alpha * np.exp(input) - self.alpha))
return self.output
def updateGradInput(self, input, gradOutput):
# Your code goes here. ################################################
self.gradInput = np.add(np.multiply(gradOutput, input > 0),
np.multiply(gradOutput, np.multiply(input <= 0, np.exp(input)) * self.alpha))
return self.gradInput
def __repr__(self):
return "ELU"
class SoftPlus(Module):
def __init__(self):
super(SoftPlus, self).__init__()
def updateOutput(self, input):
limit = 30
self.output = np.add(np.multiply(input > limit, input),
np.multiply(input <= limit, np.log(1.0 + np.exp(input))))
return self.output
def updateGradInput(self, input, gradOutput):
self.gradInput = np.multiply(gradOutput , np.divide(1.0, 1 + np.exp(-input)))
return self.gradInput
def __repr__(self):
return "SoftPlus"
# My code goes here. ################################################
class LogSigmoid(Module):
def __init__(self):
super(LogSigmoid, self).__init__()
def updateOutput(self, input):
self.output = np.divide(1, 1 + np.exp(-input))
return self.output
def updateGradInput(self, input, gradOutput):
self.gradInput = np.multiply(gradOutput, np.subtract(self.output, np.multiply(self.output, self.output)))
return self.gradInput
def __repr__(self):
return "LogSigmoid"
class Criterion(object):
def __init__ (self):
self.output = None
self.gradInput = None
def forward(self, input, target):
"""
Given an input and a target, compute the loss function
associated to the criterion and return the result.
For consistency this function should not be overrided,
all the code goes in `updateOutput`.
"""
return self.updateOutput(input, target)
def backward(self, input, target):
"""
Given an input and a target, compute the gradients of the loss function
associated to the criterion and return the result.
For consistency this function should not be overrided,
all the code goes in `updateGradInput`.
"""
return self.updateGradInput(input, target)
def updateOutput(self, input, target):
"""
Function to override.
"""
return self.output
def updateGradInput(self, input, target):
"""
Function to override.
"""
return self.gradInput
def __repr__(self):
"""
Pretty printing. Should be overrided in every module if you want
to have readable description.
"""
return "Criterion"
class MSECriterion(Criterion):
def __init__(self):
super(MSECriterion, self).__init__()
def updateOutput(self, input, target):
self.output = np.sum(np.power(input - target,2)) / input.shape[0]
return self.output
def updateGradInput(self, input, target):
self.gradInput = (input - target) * 2 / input.shape[0]
return self.gradInput
def __repr__(self):
return "MSECriterion"
class ClassNLLCriterionUnstable(Criterion):
EPS = 1e-15
def __init__(self):
a = super(ClassNLLCriterionUnstable, self)
super(ClassNLLCriterionUnstable, self).__init__()
def updateOutput(self, input, target):
# Use this trick to avoid numerical errors
input_clamp = np.clip(input, self.EPS, 1 - self.EPS)
# Your code goes here. ################################################
self.output = -np.sum(np.multiply(target, np.log(input_clamp))) / input.shape[0]
return self.output
def updateGradInput(self, input, target):
# Use this trick to avoid numerical errors
input_clamp = np.clip(input, self.EPS, 1 - self.EPS)
# Your code goes here. ################################################
self.gradInput = -np.divide(target, input_clamp) / input.shape[0]
return self.gradInput
def __repr__(self):
return "ClassNLLCriterionUnstable"
class ClassNLLCriterion(Criterion):
def __init__(self):
a = super(ClassNLLCriterion, self)
super(ClassNLLCriterion, self).__init__()
def updateOutput(self, input, target):
# Your code goes here. ################################################
return self.output
def updateGradInput(self, input, target):
# Your code goes here. ################################################
return self.gradInput
def __repr__(self):
return "ClassNLLCriterion"