Expand file tree
/
Copy pathModule.lua
More file actions
Latest commit
429 lines (374 loc) · 11.8 KB
/
Copy pathModule.lua
File metadata and controls
429 lines (374 loc) · 11.8 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
localModule=torch.class('nn.Module')
functionModule:__init()
self.gradInput=torch.Tensor()
self.output=torch.Tensor()
self._type=self.output:type()
end
functionModule:parameters()
ifself.weightandself.biasthen
return {self.weight, self.bias}, {self.gradWeight, self.gradBias}
elseifself.weightthen
return {self.weight}, {self.gradWeight}
elseifself.biasthen
return {self.bias}, {self.gradBias}
else
return
end
end
functionModule:updateOutput(input)
returnself.output
end
functionModule:forward(input)
returnself:updateOutput(input)
end
functionModule:backward(input, gradOutput, scale)
scale=scaleor1
self:updateGradInput(input, gradOutput)
self:accGradParameters(input, gradOutput, scale)
returnself.gradInput
end
functionModule:backwardUpdate(input, gradOutput, lr)
self:updateGradInput(input, gradOutput)
self:accUpdateGradParameters(input, gradOutput, lr)
returnself.gradInput
end
functionModule:updateGradInput(input, gradOutput)
returnself.gradInput
end
functionModule:accGradParameters(input, gradOutput, scale)
end
functionModule:accUpdateGradParameters(input, gradOutput, lr)
ifself.sharedthen
self:sharedAccUpdateGradParameters(input, gradOutput, lr)
else
self:defaultAccUpdateGradParameters(input, gradOutput, lr)
end
end
functionModule:defaultAccUpdateGradParameters(input, gradOutput, lr)
localgradWeight=self.gradWeight
localgradBias=self.gradBias
self.gradWeight=self.weight
self.gradBias=self.bias
self:accGradParameters(input, gradOutput, -lr)
self.gradWeight=gradWeight
self.gradBias=gradBias
end
functionModule:sharedAccUpdateGradParameters(input, gradOutput, lr)
ifself:parameters() then
self:zeroGradParameters()
self:accGradParameters(input, gradOutput, 1)
self:updateParameters(lr)
end
end
functionModule:zeroGradParameters()
local_,gradParams=self:parameters()
ifgradParamsthen
fori=1,#gradParamsdo
gradParams[i]:zero()
end
end
end
functionModule:updateParameters(learningRate)
localparams, gradParams=self:parameters()
ifparamsthen
fori=1,#paramsdo
params[i]:add(-learningRate, gradParams[i])
end
end
end
functionModule:training()
self.train=true
end
functionModule:evaluate()
self.train=false
end
functionModule:share(mlp, ...)
localarg= {...}
fori,vinipairs(arg) do
ifself[v] ~=nilthen
self[v]:set(mlp[v])
self.shared=true
mlp.shared=true
end
end
returnself
end
localfunctionsharedWrite(...)
localarg= {...}
localshared= {}
fori,vinipairs(arg) do
shared[v] =true
end
returnfunction(self, file)
localobject= {}
fork, vinpairs(self) do
ifshared[k] then
assert(torch.isTensor(v), 'Shared parameters have to be Tensors')
object[k] =v.new()
else
object[k] =v
end
end
file:writeObject(object)
end
end
functionModule:clone(...)
localoldWrite=nn.Module.write
nn.Module.write=sharedWrite(...)
localf=torch.MemoryFile("rw"):binary()
f:writeObject(self)
f:seek(1)
localclone=f:readObject()
f:close()
nn.Module.write=oldWrite
ifselect('#',...) >0then
clone:share(self,...)
end
returnclone
end
functionModule:type(type, tensorCache)
ifnottypethen
returnself._type
end
tensorCache=tensorCacheor {}
-- find all tensors and convert them
forkey,paraminpairs(self) do
self[key] =nn.utils.recursiveType(param, type, tensorCache)
end
self._type=type
returnself
end
functionModule:float(...)
returnself:type('torch.FloatTensor',...)
end
functionModule:double(...)
returnself:type('torch.DoubleTensor',...)
end
functionModule:cuda(...)
returnself:type('torch.CudaTensor',...)
end
functionModule:reset()
end
functionModule:write(file)
-- Write all values in the object as a table.
localobject= {}
fork, vinpairs(self) do
object[k] =v
end
file:writeObject(object)
end
functionModule:read(file)
localobject=file:readObject()
fork, vinpairs(object) do
self[k] =v
end
end
-- This function is not easy to understand. It works as follows:
--
-- - gather all parameter tensors for this module (and children);
-- count all parameter values (floats)
-- - create one ginormous memory area (Storage object) with room for all
-- parameters
-- - remap each parameter tensor to point to an area within the ginormous
-- Storage, and copy it there
--
-- It has the effect of making all parameters point to the same memory area,
-- which is then returned.
--
-- The purpose is to allow operations over all parameters (such as momentum
-- updates and serialization), but it assumes that all parameters are of
-- the same type (and, in the case of CUDA, on the same device), which
-- is not always true. Use for_each() to iterate over this module and
-- children instead.
--
-- Module._flattenTensorBuffer can be used by other packages (e.g. cunn)
-- to specify the type of temporary buffers. For example, the temporary
-- buffers for CudaTensor could be FloatTensor, to avoid GPU memory usage.
--
-- TODO: This logically belongs to torch.Tensor, not nn.
Module._flattenTensorBuffer= {}
functionModule.flatten(parameters)
-- returns true if tensor occupies a contiguous region of memory (no holes)
localfunctionisCompact(tensor)
localsortedStride, perm=torch.sort(
torch.LongTensor(tensor:nDimension()):set(tensor:stride()), 1, true)
localsortedSize=torch.LongTensor(tensor:nDimension()):set(
tensor:size()):index(1, perm)
localnRealDim=torch.clamp(sortedStride, 0, 1):sum()
sortedStride=sortedStride:narrow(1, 1, nRealDim):clone()
sortedSize=sortedSize:narrow(1, 1, nRealDim):clone()
localt=tensor.new():set(tensor:storage(), 1,
sortedSize:storage(),
sortedStride:storage())
returnt:isContiguous()
end
ifnotparametersor#parameters==0then
returntorch.Tensor()
end
localTensor=parameters[1].new
localTmpTensor=Module._flattenTensorBuffer[torch.type(parameters[1])] orTensor
-- 1. construct the set of all unique storages referenced by parameter tensors
localstorages= {}
localnParameters=0
localparameterMeta= {}
fork=1,#parametersdo
localparam=parameters[k]
localstorage=parameters[k]:storage()
localstorageKey=torch.pointer(storage)
ifnotstorages[storageKey] then
storages[storageKey] = {storage, nParameters}
nParameters=nParameters+storage:size()
end
parameterMeta[k] = {storageOffset=param:storageOffset() +
storages[storageKey][2],
size=param:size(),
stride=param:stride()}
end
-- 2. construct a single tensor that will hold all the parameters
localflatParameters=TmpTensor(nParameters):zero()
-- 3. determine if there are elements in the storage that none of the
-- parameter tensors reference ('holes')
localtensorsCompact=true
fork=1,#parametersdo
localmeta=parameterMeta[k]
localtmp=TmpTensor():set(
flatParameters:storage(), meta.storageOffset, meta.size, meta.stride)
tmp:fill(1)
tensorsCompact=tensorsCompactandisCompact(tmp)
end
localmaskParameters=flatParameters:byte():clone()
localcompactOffsets=flatParameters:long():cumsum(1)
localnUsedParameters=compactOffsets[-1]
-- 4. copy storages into the flattened parameter tensor
for_, storageAndOffsetinpairs(storages) do
localstorage, offset=table.unpack(storageAndOffset)
flatParameters[{{offset+1,offset+storage:size()}}]:copy(Tensor():set(storage))
end
-- 5. allow garbage collection
storages=nil
fork=1,#parametersdo
parameters[k]:set(Tensor())
end
-- 6. compact the flattened parameters if there were holes
ifnUsedParameters~=nParametersthen
assert(tensorsCompact,
"Cannot gather tensors that are not compact")
flatParameters=TmpTensor(nUsedParameters):copy(
flatParameters:maskedSelect(maskParameters))
fork=1,#parametersdo
parameterMeta[k].storageOffset=
compactOffsets[parameterMeta[k].storageOffset]
end
end
ifTmpTensor~=Tensorthen
flatParameters=Tensor(flatParameters:nElement()):copy(flatParameters)
end
-- 7. fix up the parameter tensors to point at the flattened parameters
fork=1,#parametersdo
parameters[k]:set(flatParameters:storage(),
parameterMeta[k].storageOffset,
parameterMeta[k].size,
parameterMeta[k].stride)
end
returnflatParameters
end
functionModule:getParameters()
-- get parameters
localparameters,gradParameters=self:parameters()
localp, g=Module.flatten(parameters), Module.flatten(gradParameters)
assert(p:nElement() ==g:nElement(),
'check that you are sharing parameters and gradParameters')
ifparametersthen
fori=1,#parametersdo
assert(parameters[i]:storageOffset() ==gradParameters[i]:storageOffset(),
'misaligned parameter at ' ..tostring(i))
end
end
returnp, g
end
functionModule:__call__(input, gradOutput)
self:forward(input)
ifgradOutputthen
self:backward(input, gradOutput)
returnself.output, self.gradInput
else
returnself.output
end
end
-- Run a callback (called with the module as an argument) in preorder over this
-- module and its children.
--
functionModule:apply(callback)
callback(self)
ifself.modulesthen
for_, moduleinipairs(self.modules) do
module:apply(callback)
end
end
end
functionModule:findModules(typename, container)
container=containerorself
localnodes= {}
localcontainers= {}
localmod_type=torch.typename(self)
ifmod_type==typenamethen
nodes[#nodes+1] =self
containers[#containers+1] =container
end
-- Recurse on nodes with 'modules'
if (self.modules~=nil) then
if (torch.type(self.modules) =='table') then
fori=1, #self.modulesdo
localchild=self.modules[i]
localcur_nodes, cur_containers=
child:findModules(typename, self)
assert(#cur_nodes==#cur_containers,
'Internal error: incorrect return length') -- This shouldn't happen
-- add the list items from our child to our list (ie return a
-- flattened table of the return nodes).
forj=1, #cur_nodesdo
nodes[#nodes+1] =cur_nodes[j]
containers[#containers+1] =cur_containers[j]
end
end
end
end
returnnodes, containers
end
-- returns a list of modules
functionModule:listModules()
localfunctiontinsert(to, from)
iftorch.type(from) =='table' then
fori=1,#fromdo
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
-- include self first
localmodules= {self}
ifself.modulesthen
fori=1,#self.modulesdo
localmodulas=self.modules[i]:listModules()
ifmodulasthen
tinsert(modules,modulas)
end
end
end
returnmodules
end
functionModule:clearState()
returnnn.utils.clear(self, 'output', 'gradInput')
end
-- similar to apply, recursively goes over network and calls
-- a callback function which returns a new module replacing the old one
functionnn.Module:replace(callback)
localout=callback(self)
ifself.modulesthen
fori, moduleinipairs(self.modules) do
self.modules[i] =module:replace(callback)
end
end
returnout
end