-
Notifications
You must be signed in to change notification settings - Fork 958
/
Copy pathUnsqueeze.lua
52 lines (43 loc) · 1.68 KB
/
Unsqueeze.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
local Unsqueeze, parent = torch.class('nn.Unsqueeze', 'nn.Module')
local function _assertTensor(t)
assert(torch.isTensor(t), "This module only works on tensor")
end
function Unsqueeze:__init(pos, numInputDims)
parent.__init(self)
self.pos = pos or error('the position to insert singleton dim not specified')
self:setNumInputDims(numInputDims)
end
function Unsqueeze:setNumInputDims(numInputDims)
self.numInputDims = numInputDims
return self
end
function Unsqueeze:updateOutput(input)
_assertTensor(input)
local actualPos = self:_getActualPosition(input)
nn.utils.addSingletonDimension(self.output, input, actualPos)
return self.output
end
function Unsqueeze:updateGradInput(input, gradOutput)
_assertTensor(input)
_assertTensor(gradOutput)
assert(input:nElement() == gradOutput:nElement())
self.gradInput:view(gradOutput, input:size())
return self.gradInput
end
function Unsqueeze:__tostring__()
return torch.type(self)..'(dim ' .. self.pos .. ')'
end
function Unsqueeze:_getActualPosition(input)
-- get valid dimesion offset for batchMode (if any)
local inputDim = input:dim() -- data batch dim
self.numInputDims = self.numInputDims or inputDim -- feature map dim
local offsetDim = inputDim - self.numInputDims
assert(offsetDim >= 0, "input feature map dim (numInputDims) must be <= input:dim()")
-- the actual position; clearer error message for batchMode (if any)
local actualPos = self.pos + offsetDim
assert(actualPos >= 1 and actualPos <= (inputDim + 1),
("Invalid position: %d. input:dim() is %d, input feature map dim (numInputDims) is %d.")
:format(self.pos, inputDim, self.numInputDims)
)
return actualPos
end