|
a |
|
b/util/ReverseSequence.lua |
|
|
1 |
------------------------------------------------------------------------ |
|
|
2 |
-- Adapted from github.com/jcjohnson/torch-rnn/pull/66/commits/5e30c1d54dc9ed1d152e4a55e9c438775f623ef7 |
|
|
3 |
|
|
|
4 |
--[[ ReverseSequence ]] -- |
|
|
5 |
-- Reverses a sequence on a given dimension. |
|
|
6 |
-- Example: Given a tensor of torch.Tensor({{1,2,3,4,5}, {6,7,8,9,10}) |
|
|
7 |
-- nn.ReverseSequence(1):forward(tensor) would give: torch.Tensor({{6,7,8,9,10},{1,2,3,4,5}}) |
|
|
8 |
------------------------------------------------------------------------ |
|
|
9 |
local ReverseSequence, parent = torch.class("nn.ReverseSequence", "nn.Module") |
|
|
10 |
|
|
|
11 |
function ReverseSequence:__init(dim,gpu) |
|
|
12 |
parent.__init(self) |
|
|
13 |
self.output = torch.Tensor() |
|
|
14 |
self.gradInput = torch.Tensor() |
|
|
15 |
self.outputIndices = torch.LongTensor() |
|
|
16 |
self.gradIndices = torch.LongTensor() |
|
|
17 |
self.typ = 'torch.CudaTensor' |
|
|
18 |
if gpu and (gpu < 1) then |
|
|
19 |
self.typ = 'torch.LongTensor' |
|
|
20 |
end |
|
|
21 |
end |
|
|
22 |
|
|
|
23 |
function ReverseSequence:reverseOutput(input) |
|
|
24 |
self.output:resizeAs(input) |
|
|
25 |
self.outputIndices:resize(input:size()) |
|
|
26 |
local T = input:size(1) |
|
|
27 |
for x = 1, T do |
|
|
28 |
self.outputIndices:narrow(1, x, 1):fill(T - x + 1) |
|
|
29 |
end |
|
|
30 |
self.output:gather(input, 1, self.outputIndices:type(self.typ)) |
|
|
31 |
end |
|
|
32 |
|
|
|
33 |
function ReverseSequence:updateOutput(input) |
|
|
34 |
input = input:transpose(1, 2) |
|
|
35 |
self:reverseOutput(input) |
|
|
36 |
self.output = self.output:transpose(1, 2) |
|
|
37 |
return self.output |
|
|
38 |
end |
|
|
39 |
|
|
|
40 |
function ReverseSequence:reverseGradOutput(gradOutput) |
|
|
41 |
self.gradInput:resizeAs(gradOutput) |
|
|
42 |
self.gradIndices:resize(gradOutput:size()) |
|
|
43 |
local T = gradOutput:size(1) |
|
|
44 |
for x = 1, T do |
|
|
45 |
self.gradIndices:narrow(1, x, 1):fill(T - x + 1) |
|
|
46 |
end |
|
|
47 |
self.gradInput:gather(gradOutput, 1, self.gradIndices:type(self.typ)) |
|
|
48 |
end |
|
|
49 |
|
|
|
50 |
function ReverseSequence:updateGradInput(inputTable, gradOutput) |
|
|
51 |
gradOutput = gradOutput:transpose(1, 2) |
|
|
52 |
self:reverseGradOutput(gradOutput) |
|
|
53 |
self.gradInput = self.gradInput:transpose(1, 2) |
|
|
54 |
return self.gradInput |
|
|
55 |
end |