-
Notifications
You must be signed in to change notification settings - Fork 0
/
Padding.lua
47 lines (44 loc) · 1.41 KB
/
Padding.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
local Padding, parent = torch.class('nn.Padding', 'nn.Module')
-- pad can be positive (right) negative (left)
function Padding:__init(dim, pad, nInputDim, value)
self.dim = dim
self.pad = pad
self.nInputDim = nInputDim
self.value = value or 0
self.outputSize = torch.LongStorage()
parent.__init(self)
end
function Padding:updateOutput(input)
self.outputSize:resize(input:dim())
self.outputSize:copy(input:size())
local dim = self.dim
if self.nInputDim and input:dim() ~= self.nInputDim then
dim = dim + 1
end
self.outputSize[dim] = self.outputSize[dim] + math.abs(self.pad)
self.output:resize(self.outputSize)
self.output:fill(self.value)
local outputWindow
if self.pad > 0 then
outputWindow = self.output:narrow(dim, 1, input:size(dim))
else
outputWindow = self.output:narrow(dim, 1 - self.pad, input:size(dim))
end
outputWindow:copy(input)
return self.output
end
function Padding:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
local dim = self.dim
if self.nInputDim and input:dim() ~= self.nInputDim then
dim = dim + 1
end
local gradOutputWindow
if self.pad > 0 then
gradOutputWindow = gradOutput:narrow(dim, 1, input:size(dim))
else
gradOutputWindow = gradOutput:narrow(dim, 1 - self.pad, input:size(dim))
end
self.gradInput:copy(gradOutputWindow:copy(input))
return self.gradInput
end