-
Notifications
You must be signed in to change notification settings - Fork 2
/
Module.lua
350 lines (304 loc) · 10 KB
/
Module.lua
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
local Module = torch.class('nn.Module')
function Module:__init()
self.gradInput = torch.Tensor()
self.output = torch.Tensor()
end
function Module:parameters()
if self.weight and self.bias then
return {self.weight, self.bias}, {self.gradWeight, self.gradBias}
elseif self.weight then
return {self.weight}, {self.gradWeight}
elseif self.bias then
return {self.bias}, {self.gradBias}
else
return
end
end
function Module:updateOutput(input)
return self.output
end
function Module:forward(input)
return self:updateOutput(input)
end
function Module:backward(input, gradOutput, scale)
scale = scale or 1
self:updateGradInput(input, gradOutput)
self:accGradParameters(input, gradOutput, scale)
return self.gradInput
end
function Module:backwardUpdate(input, gradOutput, lr)
self:updateGradInput(input, gradOutput)
self:accUpdateGradParameters(input, gradOutput, lr)
return self.gradInput
end
function Module:updateGradInput(input, gradOutput)
return self.gradInput
end
function Module:accGradParameters(input, gradOutput, scale)
end
function Module:accUpdateGradParameters(input, gradOutput, lr)
local gradWeight = self.gradWeight
local gradBias = self.gradBias
self.gradWeight = self.weight
self.gradBias = self.bias
self:accGradParameters(input, gradOutput, -lr)
self.gradWeight = gradWeight
self.gradBias = gradBias
end
function Module:sharedAccUpdateGradParameters(input, gradOutput, lr)
if self:parameters() then
self:zeroGradParameters()
self:accGradParameters(input, gradOutput, 1)
self:updateParameters(lr)
end
end
function Module:zeroGradParameters()
local _,gradParams = self:parameters()
if gradParams then
for i=1,#gradParams do
gradParams[i]:zero()
end
end
end
function Module:updateParameters(learningRate)
local params, gradParams = self:parameters()
if params then
for i=1,#params do
params[i]:add(-learningRate, gradParams[i])
end
end
end
function Module:training()
self.train = true
end
function Module:evaluate()
self.train = false
end
function Module:share(mlp, ...)
local arg = {...}
for i,v in ipairs(arg) do
if self[v] ~= nil then
self[v]:set(mlp[v])
self.accUpdateGradParameters = self.sharedAccUpdateGradParameters
mlp.accUpdateGradParameters = mlp.sharedAccUpdateGradParameters
end
end
return self
end
function Module:clone(...)
local f = torch.MemoryFile("rw"):binary()
f:writeObject(self)
f:seek(1)
local clone = f:readObject()
f:close()
if select('#',...) > 0 then
clone:share(self,...)
end
return clone
end
function Module:type(type, tensorCache)
assert(type, 'Module: must provide a type to convert to')
tensorCache = tensorCache or {}
-- find all tensors and convert them
for key,param in pairs(self) do
self[key] = nn.utils.recursiveType(param, type, tensorCache)
end
return self
end
function Module:float()
return self:type('torch.FloatTensor')
end
function Module:double()
return self:type('torch.DoubleTensor')
end
function Module:cuda()
return self:type('torch.CudaTensor')
end
function Module:reset()
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 = {}
function Module.flatten(parameters)
-- returns true if tensor occupies a contiguous region of memory (no holes)
local function isCompact(tensor)
local sortedStride, perm = torch.sort(
torch.LongTensor(tensor:nDimension()):set(tensor:stride()), 1, true)
local sortedSize = torch.LongTensor(tensor:nDimension()):set(
tensor:size()):index(1, perm)
local nRealDim = torch.clamp(sortedStride, 0, 1):sum()
sortedStride = sortedStride:narrow(1, 1, nRealDim):clone()
sortedSize = sortedSize:narrow(1, 1, nRealDim):clone()
local t = tensor.new():set(tensor:storage(), 1,
sortedSize:storage(),
sortedStride:storage())
return t:isContiguous()
end
if not parameters or #parameters == 0 then
return torch.Tensor()
end
local Tensor = parameters[1].new
local TmpTensor = Module._flattenTensorBuffer[torch.type(parameters[1])] or Tensor
-- 1. construct the set of all unique storages referenced by parameter tensors
local storages = {}
local nParameters = 0
local parameterMeta = {}
for k = 1,#parameters do
local param = parameters[k]
local storage = parameters[k]:storage()
local storageKey = torch.pointer(storage)
if not storages[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
local flatParameters = TmpTensor(nParameters):zero()
-- 3. determine if there are elements in the storage that none of the
-- parameter tensors reference ('holes')
local tensorsCompact = true
for k = 1,#parameters do
local meta = parameterMeta[k]
local tmp = TmpTensor():set(
flatParameters:storage(), meta.storageOffset, meta.size, meta.stride)
tmp:fill(1)
tensorsCompact = tensorsCompact and isCompact(tmp)
end
local maskParameters = flatParameters:byte():clone()
local compactOffsets = flatParameters:long():cumsum(1)
local nUsedParameters = compactOffsets[-1]
-- 4. copy storages into the flattened parameter tensor
for _, storageAndOffset in pairs(storages) do
local storage, offset = table.unpack(storageAndOffset)
flatParameters[{{offset+1,offset+storage:size()}}]:copy(Tensor():set(storage))
end
-- 5. allow garbage collection
storages = nil
for k = 1,#parameters do
parameters[k]:set(Tensor())
end
-- 6. compact the flattened parameters if there were holes
if nUsedParameters ~= nParameters then
assert(tensorsCompact,
"Cannot gather tensors that are not compact")
flatParameters = TmpTensor(nUsedParameters):copy(
flatParameters:maskedSelect(maskParameters))
for k = 1,#parameters do
parameterMeta[k].storageOffset =
compactOffsets[parameterMeta[k].storageOffset]
end
end
if TmpTensor ~= Tensor then
flatParameters = Tensor(flatParameters:nElement()):copy(flatParameters)
end
-- 7. fix up the parameter tensors to point at the flattened parameters
for k = 1,#parameters do
parameters[k]:set(flatParameters:storage(),
parameterMeta[k].storageOffset,
parameterMeta[k].size,
parameterMeta[k].stride)
end
return flatParameters
end
function Module:getParameters()
-- get parameters
local parameters,gradParameters = self:parameters()
return Module.flatten(parameters), Module.flatten(gradParameters)
end
function Module:__call__(input, gradOutput)
self:forward(input)
if gradOutput then
self:backward(input, gradOutput)
return self.output, self.gradInput
else
return self.output
end
end
-- Run a callback (called with the module as an argument) in preorder over this
-- module and its children.
--
function Module:apply(callback)
callback(self)
if self.modules then
for _, module in ipairs(self.modules) do
module:apply(callback)
end
end
end
function Module:findModules(typename, container)
container = container or self
local nodes = {}
local containers = {}
local mod_type = torch.typename(self)
if mod_type == typename then
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
for i = 1, #self.modules do
local child = self.modules[i]
local cur_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).
for j = 1, #cur_nodes do
nodes[#nodes+1] = cur_nodes[j]
containers[#containers+1] = cur_containers[j]
end
end
end
end
return nodes, containers
end
-- returns a list of modules
function Module:listModules()
local function tinsert(to, from)
if torch.type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
-- include self first
local modules = {self}
if self.modules then
for i=1,#self.modules do
local modulas = self.modules[i]:listModules()
if modulas then
tinsert(modules,modulas)
end
end
end
return modules
end