Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathModule.lua
More file actions
Latest commit
626 lines (553 loc) · 19.1 KB
/
Copy pathModule.lua
File metadata and controls
626 lines (553 loc) · 19.1 KB
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
local_=require'moses'
localModule=nn.Module
functionModule:sparseParameters()
returnself:parameters()
end
functionModule:updateParameters(learningRate)
-- sparse params can have different learningRate scales per param
localparams, gradParams, scales=self:sparseParameters()
ifparamsthen
fori,paraminpairs(params) do-- pairs for sparse params
localscale=scalesandscales[i] or1
param:add(-learningRate*scale, gradParams[i])
end
end
end
functionModule:zeroGradParameters()
local_,gradParams=self:sparseParameters()
ifgradParamsthen
fori,gradParaminpairs(gradParams) do-- pairs for sparse params
gradParam:zero()
end
end
end
------------------------ clone and type --------------------------------
Module.dpnn_parameters= {'weight', 'bias'}
Module.dpnn_gradParameters= {'gradWeight', 'gradBias'}
-- efficient version of :
-- clone = self:clone()
-- clone:share(self, paramNames, gradParamNames)
-- Note that this method is the very bane of my existence.
-- I have worked on it too many times...
functionModule:sharedClone(shareParams, shareGradParams, stepClone)
shareParams= (shareParams==nil) andtrueorshareParams
shareGradParams= (shareGradParams==nil) andtrueorshareGradParams
ifstepCloneandself.dpnn_stepclonethen
-- this is for AbstractRecurrent modules (in rnn)
returnself
end
localpointers= {} -- to params/gradParams (dont clone params/gradParams)
localscdone= {}
-- 1. remove all params/gradParams
localfunctionrecursiveRemove(obj) -- remove modules
localmoduleTree
localisTable=type(obj) =='table'
iftorch.isTypeOf(obj, 'nn.Module') then
assert(isTable)
ifstepCloneandobj.dpnn_stepclonethen
-- this is for AbstractRecurrent modules (in rnn)
moduleTree=obj
obj=nil
isTable=false
elseifobj.dpnn_sharedClonethen
-- allow to use a custom sharedClone method on one module
moduleTree=obj
obj=nil
isTable=false
elseifscdone[torch.pointer(obj)] then
moduleTree=scdone[torch.pointer(obj)]
else
-- remove the params, gradParams. Save for later.
localparams= {}
ifshareParamsthen
fori,paramNameinipairs(obj.dpnn_parameters) do
localparam=obj[paramName]
ifparamthen
params[paramName] =param
obj[paramName] =nil
iftorch.isTensor(param) andparam.storageandparam:storage() then
pointers[torch.pointer(param:storage():data())] =true
end
end
end
end
ifshareGradParamsthen
fori,paramNameinipairs(obj.dpnn_gradParameters) do
localgradParam=obj[paramName]
ifgradParamthen
params[paramName] =gradParam
obj[paramName] =nil
iftorch.isTensor(gradParam) andgradParam.storageandgradParam:storage() then
pointers[torch.pointer(gradParam:storage():data())] =true
end
end
end
end
-- find all obj.attribute tensors that share storage with the shared params
forparamName, paraminpairs(obj) do
iftorch.isTensor(param) andparam:storage() then
ifpointers[torch.pointer(param:storage():data())] then
params[paramName] =param
obj[paramName] =nil
end
end
end
moduleTree=params
scdone[torch.pointer(obj)] =moduleTree
fork,vinpairs(obj) do
moduleTree[k], obj[k] =recursiveRemove(v)
end
end
elseifisTablethen
ifscdone[torch.pointer(obj)] then
moduleTree=scdone[torch.pointer(obj)]
else
assert(notmoduleTree)
moduleTree= {}
fork,vinpairs(obj) do
moduleTree[k], obj[k] =recursiveRemove(v)
end
scdone[torch.pointer(obj)] =moduleTree
end
end
returnmoduleTree, obj
end
localmoduleTree, original=recursiveRemove(self)
assert(original)
-- 2. clone everything but parameters, gradients and modules (removed above)
localclone=self:clone()
-- 3. add back to self/clone everything that was removed in step 1
localfunctionrecursiveSet(clone, original, moduleTree)
assert(clone)
assert(original)
ifscdone[torch.pointer(original)] then
fork,paraminpairs(moduleTree) do
iftorch.isTypeOf(param,'nn.Module') then
ifparam.dpnn_sharedClonethen
-- Call the custom sharedClone
clone[k] =param:dpnn_sharedClone()
else
-- AbstractRecurrent instances branch here with stepClone = true
clone[k] =param
end
original[k] =param
elseiftorch.isTensor(param) then
ifparam.storagethen
clone[k] =param.new():set(param)
original[k] =param
else-- for torch.MultiCudaTensor
clone[k] =param
original[k] =param
end
elseiftype(param) =='table' then
recursiveSet(clone[k], original[k], param)
end
end
scdone[torch.pointer(original)] =nil
end
end
recursiveSet(clone, self, moduleTree)
returnclone
end
-- we override this method such that hidden modules
-- will be included in the getParameters call.
-- Hidden modules are common for recurrent modules that
-- have internal references to modules that share parameters
-- with the main modules.
-- These must also be included in the getParameters() call in order
-- to maintain shared storage for tensors.
functionModule:getParameters()
localcon=nn.Container()
con:add(self)
-- recursive get all modules (modules, sharedclones, etc.)
localfunctionrecursiveGetModules(tbl)
fork,minpairs(tbl) do
iftorch.isTypeOf(m, 'nn.Module') then
ifnotm.dpnn_getParameters_foundthen
con:add(m)
m.dpnn_getParameters_found=true
recursiveGetModules(m)
end
elseiftorch.type(m) =='table' then
recursiveGetModules(m)
end
end
end
recursiveGetModules(self)
fori,minipairs(con.modules) do
m.dpnn_getParameters_found=nil
end
-- get ALL parameters
localparameters,gradParameters=con:parameters()
returnModule.flatten(parameters), Module.flatten(gradParameters)
end
----------------- serialization (see nn.Serial) -------------------
Module.dpnn_mediumEmpty= {'output', 'gradInput', 'momGradParams', 'dpnn_input'}
Module.dpnn_lightEmpty=Module.dpnn_gradParameters
-- defaults to heavy serialization
Module.dpnn_serialEmpty= {}
-- sets the serialization behavior of the entire module structure
functionModule:serialMode(empty)
assert(torch.type(empty) =='table', "Expecting table at arg 1")
self.dpnn_serialEmpty=empty
-- set the serial of all encapsulated modules
localfunctionrecursiveSerial(tbl)
fork,vinpairs(tbl) do
iftorch.isTypeOf(v, 'nn.Module') then
v:serialMode(empty)
elseiftorch.type(v) =='table' then
recursiveSerial(v)
end
end
end
recursiveSerial(self)
returnself
end
-- serialMode : serialize everything
functionModule:heavySerial()
returnself:serialMode({})
end
-- serialMode : serialize everything except dpnn_mediumEmpty attributes
functionModule:mediumSerial()
self.dpnn_serialEmpty=self.dpnn_mediumEmpty
-- set the serial of all encapsulated modules
localfunctionrecursiveSerial(tbl)
fork,vinpairs(tbl) do
iftorch.isTypeOf(v, 'nn.Module') then
v:mediumSerial()
elseiftorch.type(v) =='table' then
recursiveSerial(v)
end
end
end
recursiveSerial(self)
returnself
end
-- serialMode : serialize everything except dpnn_mediumEmpty and dpnn_lightEmpty attributes
functionModule:lightSerial()
self.dpnn_serialEmpty=_.clone(self.dpnn_mediumEmpty)
fork,vinipairs(self.dpnn_lightEmpty) do
table.insert(self.dpnn_serialEmpty, v)
end
-- set the serial of all encapsulated modules
localfunctionrecursiveSerial(tbl)
fork,vinpairs(tbl) do
iftorch.isTypeOf(v, 'nn.Module') then
v:lightSerial()
elseiftorch.type(v) =='table' then
recursiveSerial(v)
end
end
end
recursiveSerial(self)
returnself
end
functionModule:getSerialState(states)
states=statesor {}
-- dont get the serial state of the same module twice (reuse existing)
ifstates[self] then
returnstates[self]
end
-- returns the object structure as tables (i.e. without metatables)
localfunctionrecursiveState(tbl)
localstate=_.map(tbl,
function(k,v)
iftorch.isTypeOf(tbl, 'nn.Module') and_.contains(tbl.dpnn_serialEmpty, k) then
-- "empties" module attributes found in empty
iftorch.type(v) =='table' then
-- empty table
return {}
elseiftorch.isTensor(v) then
-- empty tensor
returnv.new()
else
-- not table nor tensor? then serialize as is
returnv
end
elseiftorch.isTypeOf(v, 'nn.Module') then
-- recursive, yet can be overwritten
returnv:getSerialState(states)
elseiftorch.type(v) =='table' then
-- in case it is a table of modules
ifnotstates[v] then
states[v] =recursiveState(v)
end
returnstates[v]
else
returnv
end
end
)
returnstate
end
localstate=recursiveState(self)
-- include typename so that module can be reconstructed from the state
state.dpnn_typename=torch.type(self)
states[self] =state
returnstate
end
-- decorates self with nn.Serial
functionModule:Serial(tensortype)
returnnn.Serial(self, tensortype)
end
----------------------- for training -----------------------------
-- useful to get the output size
-- I chose this method name because it is less likely to be overriden.
functionModule:outside(insize)
localinput
iftorch.type(insize) =='table' then
input=torch.randn(table.unpack(insize))
else
input=torch.randn(insize)
end
localoutput=self:updateOutput(input)
returnoutput:size()
end
-- for those interested in implementing the visitor design pattern
functionModule:accept(visitor)
visitor:visit(self)
end
-- Can be used as a regularizer instead of weight decay
-- Assumes that parameters are arranged (output dim x ... x input dim)
functionModule:maxParamNorm(maxOutNorm, maxInNorm)
-- this allows each module to set its own max[Out,In]Norm
maxOutNorm=self.maxOutNormormaxOutNorm
maxInNorm=self.maxInNormormaxInNorm
ifnot (maxOutNormormaxInNorm) then
return
end
ifself.modulesthen
fori,moduleinipairs(self.modules) do
module:maxParamNorm(maxOutNorm, maxInNorm)
end
else
localparams=self:parameters()
ifnotparamsorgradParamsthen
return
end
fork,paraminpairs(params) do-- pairs for sparse params
-- By default, only affects non-1D params.
ifparam:dim() >1then
ifmaxOutNormandmaxOutNorm>0then
-- rows feed into output neurons
param:renorm(2, 1, maxOutNorm)
end
ifmaxInNormandmaxInNorm>0then
-- cols feed out from input neurons
param:renorm(2, param:dim(), maxInNorm)
end
end
end
end
end
-- Similar to maxParamNorm, but norm is global to Module for which
-- this is called. Unless moduleLocal is true, in which case, the
-- norm constraint is applied to the norm of all parameters in each
-- component (non-container) module.
functionModule:gradParamClip(cutoffNorm, moduleLocal)
-- this allows each module to set its own cutoffNorm
cutoffNorm=self.cutoffNormorcutoffNorm
ifcutoffNorm<=0then
return
end
ifself.moduleLocal~=nilthen
moduleLocal=self.moduleLocal
end
localnorm=0
ifmoduleLocalandself.modulesthen
fori,moduleinipairs(self.modules) do
norm=norm+math.pow(module:gradParamClip(cutoffNorm, moduleLocal), 2)
end
norm=math.sqrt(norm)
else
localparams, gradParams=self:parameters()
ifnot (paramsandgradParams) then
returnnorm
end
fork,gradParaminpairs(gradParams) do-- pairs for sparse params
iftorch.type(gradParam) =='torch.CudaTensor' then
cutorch.withDevice(gradParam:getDevice(), function() -- support multi-device models
norm=norm+math.pow(gradParam:norm(),2)
end)
else
norm=norm+math.pow(gradParam:norm(),2)
end
end
norm=math.sqrt(norm)
ifnorm>cutoffNormthen
-- rescale gradParams to obtain desired cutoffNorm
fork,gradParaminpairs(gradParams) do
iftorch.type(gradParam) =='torch.CudaTensor' then
cutorch.withDevice(gradParam:getDevice(), function() -- support multi-device models
gradParam:mul(cutoffNorm/norm)
end)
else
gradParam:mul(cutoffNorm/norm)
end
end
end
end
returnnorm
end
-- Adds weight decay constraint on params with dims > 2 (default).
-- TODO : allow inplace weightDecay (before calling accUpdateGradParameters)
functionModule:weightDecay(wdFactor, wdMinDim)
-- this allows each module to set its own hyper-parameters
wdFactor=self.wdFactororwdFactor
ifwdFactor<=0then
return
end
wdMinDim=self.wdMinDimorwdMinDimor2
ifself.modulesthen
fori,moduleinipairs(self.modules) do
module:weightDecay(wdFactor, wdMinDim)
end
else
localparams, gradParams=self:parameters()
ifnot (paramsandgradParams) then
return
end
fori,paraminpairs(params) do-- pairs for sparse params
ifparam:dim() >=wdMinDimthen
gradParams[i]:add(wdFactor, param)
end
end
end
end
functionModule:momentumGradParameters()
if (notself.momGradParams) or_.isEmpty(self.momGradParams) then
localparams, gradParams=self:parameters()
ifnotgradParamsor_.isEmpty(gradParams) then
return
end
self.momGradParams= {}
fori,gradParaminpairs(gradParams) do
iftorch.type(gradParam) =='torch.CudaTensor' then
cutorch.withDevice(gradParam:getDevice(), function() -- support multi-device models
self.momGradParams[i] =gradParam.new():resizeAs(gradParam):copy(gradParam)
end)
else
self.momGradParams[i] =gradParam.new():resizeAs(gradParam):copy(gradParam)
end
end
end
returnself.momGradParams
end
-- uses momentum learning to update gradParams
functionModule:updateGradParameters(momFactor, momDamp, momNesterov)
-- this allows each module to set its own hyper-parameters
momFactor=self.momFactorormomFactor
ifmomFactor<=0then
return
end
momDamp=self.momDampormomDampormomFactor
ifself.momNesterov~=nilthen
momNesterov=self.momNesterov
end
ifself.modulesthen
fori,moduleinipairs(self.modules) do
module:updateGradParameters(momFactor, momDamp, momNesterov)
end
else
localparams, gradParams=self:parameters()
if (notparams) or_.isEmpty(params) then
return
end
localmomGradParams=self:momentumGradParameters()
fori,gradParaminpairs(gradParams) do
momGradParams[i]:mul(momFactor)
momGradParams[i]:add(1-momDamp, gradParam)
end
ifmomNesterovthen
fori,gradParaminpairs(gradParams) do
gradParam:add(momFactor, momGradParams[i])
end
else
fori,gradParaminpairs(gradParams) do
gradParam:copy(momGradParams[i])
end
end
end
end
functionModule:checkParameters()
localparams=self:parameters() or {}
fork,paraminpairs(params) do
if_.isNaN(param:sum()) then
error("NaN Error for param at index" ..k)
end
end
end
functionModule:dontBackward()
self.backward=function() end
self.updateGradInput=function() end
self.accGradParameters=function() end
self.accUpdateGradParameters=function() end
returnself
end
functionModule:contiguousInput(input, backward)
ifbackwardthen
returnself.dpnn_cinputorinput
end
ifnotinput:isContiguous() then
self.dpnn_cinput=self.dpnn_cinputorinput.new()
self.dpnn_cinput:resizeAs(input):copy(input)
input=self.dpnn_cinput
end
returninput
end
functionModule:toBatch(tensor, nDim, batchDim)
localbatchDim=batchDimor1
iftensor:dim() ==nDimthen
self.dpnn_online=true
localsize=tensor:size():totable()
table.insert(size, batchDim, 1)
tensor=tensor:view(table.unpack(size))
else
self.dpnn_online=false
end
returntensor
end
functionModule:fromBatch(tensor, batchDim)
ifself.dpnn_onlinethen
localsize=tensor:size():totable()
assert(table.remove(size, batchDim) ==1)
tensor=tensor:view(table.unpack(size))
end
returntensor
end
functionModule:extrapolateType()
localparams=module:parameters()
ifparamsthen
-- extrapolate the tensor type of the module
localtypes= {}
fori, paraminipairs(params) do
localtensorType=torch.type(param)
types[tensorType] = (types[tensorType] or0) +1
end
localmaxCount=0
localmaxType
fortensorType, countinpairs(types) do
ifcount>maxCountthen
maxtype=tensorType
maxCount=count
end
end
returnmaxType
end
returnnil--unknown otherwise
end
functionModule:profile()
ifself.modulesthen
fori, moduleinipairs(self.modules) do
module:profile()
end
end
self.dpnn_profile=true
end
functionModule:reinforce(reward)
ifself.modulesthen
fori, moduleinipairs(self.modules) do
module:reinforce(reward)
end
end
end