forked from clementfarabet/lua---nnx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PullTable.lua
77 lines (66 loc) · 1.98 KB
/
PullTable.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
local PullTable, parent = torch.class("nn.PullTable", "nn.Module")
function PullTable:__init(push, index)
self._push = push
self._index = index
self.output = {}
self.gradInput = {}
end
function PullTable:_updateOutput(output)
self._output = output
end
function PullTable:updateOutput(inputTable)
if torch.type(inputTable) == 'table' then
for i, input in ipairs(inputTable) do
if i < self._index then
self.output[i] = input
else
self.output[i+1] = input
end
end
self.output[self._index] = self._output
else
if self._index == 1 then
self.output[2] = inputTable
self.output[1] = self._output
else
assert(self._index == 2, "table index out of range")
self.output[1] = inputTable
self.output[2] = self._output
end
end
return self.output
end
function PullTable:updateGradInput(inputTable, gradOutputTable)
self._push:_updateGradInput(gradOutputTable[self._index])
if torch.type(inputTable) == 'table' then
if torch.type(self.gradInput) ~= 'table' then
self.gradInput = {}
end
for i, gradOutput in ipairs(gradOutputTable) do
if i < self._index then
self.gradInput[i] = gradOutput
elseif i > self._index then
self.gradInput[i-1] = gradOutput
end
end
assert(#inputTable == #self.gradInput, "tables size mismatch")
else
if self._index == 1 then
self.gradInput = gradOutputTable[2]
else
self.gradInput = gradOutputTable[1]
end
end
return self.gradInput
end
function PullTable:type(type, tensorCache)
assert(type, 'PullTable: must provide a type to convert to')
tensorCache = tensorCache or {}
-- find all tensors and convert them
for key,param in pairs(self) do
if(key ~= "_push") then
self[key] = nn.utils.recursiveType(param, type, tensorCache)
end
end
return self
end