-
Notifications
You must be signed in to change notification settings - Fork 103
/
ParaSentDecoder.lua
425 lines (330 loc) · 12.2 KB
/
ParaSentDecoder.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
--[[ Unit to decode a sequence of output tokens.
. . . .
| | | |
h_1 => h_2 => h_3 => ... => h_n
| | | |
. . . .
| | | |
h_1 => h_2 => h_3 => ... => h_n
| | | |
| | | |
x_1 x_2 x_3 x_n
Inherits from [onmt.Sequencer](onmt+modules+Sequencer).
--]]
local ParaSentDecoder, parent = torch.class('onmt.ParaSentDecoder', 'onmt.Sequencer')
--[[ Construct a decoder layer.
Parameters:
* `inputNetwork` - input nn module.
* `rnn` - recurrent module, such as [onmt.LSTM](onmt+modules+LSTM).
* `generator` - optional, an output [onmt.Generator](onmt+modules+Generator).
* `inputFeed` - bool, enable input feeding.
--]]
function ParaSentDecoder:__init(inputNetwork, rnn, generator, inputFeed, h_dim)
assert(h_dim ~= nil)
self.rnn = rnn
self.inputNet = inputNetwork
self.args = {}
self.args.rnnSize = self.rnn.outputSize
self.args.numEffectiveLayers = self.rnn.numEffectiveLayers
self.q_dim = self.args.rnnSize
self.h_dim = h_dim
self.args.inputIndex = {}
self.args.outputIndex = {}
-- Input feeding means the decoder takes an extra
-- vector each time representing the attention at the
-- previous step.
self.args.inputFeed = inputFeed
parent.__init(self, self:_buildModel())
-- The generator use the output of the decoder sequencer to generate the
-- likelihoods over the target vocabulary.
self.generator = generator
self:add(self.generator)
self:resetPreallocation()
end
--[[ Return a new Decoder using the serialized data `pretrained`. ]]
function ParaSentDecoder.load(pretrained)
local self = torch.factory('onmt.ParaSentDecoder')()
self.args = pretrained.args
parent.__init(self, pretrained.modules[1])
self.generator = pretrained.modules[2]
self:add(self.generator)
self:resetPreallocation()
return self
end
--[[ Return data to serialize. ]]
function ParaSentDecoder:serialize()
return {
modules = self.modules,
args = self.args
}
end
function ParaSentDecoder:resetPreallocation()
if self.args.inputFeed then
self.inputFeedProto = torch.Tensor()
end
-- Prototype for preallocated hidden and cell states.
self.stateProto = torch.Tensor()
-- Prototype for preallocated output gradients.
self.gradOutputProto = torch.Tensor()
-- Prototype for preallocated context gradient.
self.gradContextProto = torch.Tensor()
end
--[[ Build a default one time-step of the decoder
Returns: An nn-graph mapping
$${(c^1_{t-1}, h^1_{t-1}, .., c^L_{t-1}, h^L_{t-1}, x_t, con/H, if) =>
(c^1_{t}, h^1_{t}, .., c^L_{t}, h^L_{t}, a)}$$
Where ${c^l}$ and ${h^l}$ are the hidden and cell states at each layer,
${x_t}$ is a sparse word to lookup,
${con/H}$ is the context/source hidden states for attention,
${if}$ is the input feeding, and
${a}$ is the context vector computed at this timestep.
--]]
function ParaSentDecoder:_buildModel()
local inputs = {}
local states = {}
-- Inputs are previous layers first.
for _ = 1, self.args.numEffectiveLayers do
local h0 = nn.Identity()() -- batchSize x rnnSize
table.insert(inputs, h0)
table.insert(states, h0)
end
local x = nn.Identity()() -- batchSize
table.insert(inputs, x)
self.args.inputIndex.x = #inputs
local context = nn.Identity()() -- batchSize x sourceLength x rnnSize
table.insert(inputs, context)
self.args.inputIndex.context = #inputs
local inputFeed
if self.args.inputFeed then
inputFeed = nn.Identity()() -- batchSize x rnnSize
table.insert(inputs, inputFeed)
self.args.inputIndex.inputFeed = #inputs
end
-- Compute the input network.
local input = self.inputNet(x)
-- If set, concatenate previous decoder output.
if self.args.inputFeed then
input = nn.JoinTable(2)({input, inputFeed})
end
table.insert(states, input)
-- Forward states and input into the RNN.
local outputs = self.rnn(states)
-- The output of a subgraph is a node: split it to access the last RNN output.
outputs = { outputs:split(self.args.numEffectiveLayers) }
-- Compute the attention here using h^L as query.
local attnLayer = onmt.CustomizedAttention(self.h_dim, self.q_dim)
attnLayer.name = 'decoderAttn'
local attnOutput = attnLayer({outputs[#outputs], context})
if self.rnn.dropout > 0 then
attnOutput = nn.Dropout(self.rnn.dropout)(attnOutput)
end
table.insert(outputs, attnOutput)
return nn.gModule(inputs, outputs)
end
--[[ Mask padding means that the attention-layer is constrained to
give zero-weight to padding. This is done by storing a reference
to the softmax attention-layer.
Parameters:
* See [onmt.MaskedSoftmax](onmt+modules+MaskedSoftmax).
--]]
function ParaSentDecoder:maskPadding(sourceSizes, sourceLength, beamSize)
if not self.decoderAttn then
self.network:apply(function (layer)
if layer.name == 'decoderAttn' then
self.decoderAttn = layer
end
end)
end
self.decoderAttn:replace(function(module)
if module.name == 'softmaxAttn' then
local mod
if sourceSizes ~= nil then
mod = onmt.MaskedSoftmax(sourceSizes, sourceLength, beamSize)
else
mod = nn.SoftMax()
end
mod.name = 'softmaxAttn'
mod:type(module._type)
self.softmaxAttn = mod
return mod
else
return module
end
end)
end
--[[ Run one step of the decoder.
Parameters:
* `input` - input to be passed to inputNetwork.
* `prevStates` - stack of hidden states (batch x layers*model x rnnSize)
* `context` - encoder output (batch x n x rnnSize)
* `prevOut` - previous distribution (batch x #words)
* `t` - current timestep
Returns:
1. `out` - Top-layer hidden state.
2. `states` - All states.
--]]
function ParaSentDecoder:forwardOne(input, prevStates, context, prevOut, t)
local inputs = {}
-- Create RNN input (see sequencer.lua `buildNetwork('dec')`).
onmt.utils.Table.append(inputs, prevStates)
table.insert(inputs, input)
table.insert(inputs, context)
local inputSize
if torch.type(input) == 'table' then
inputSize = input[1]:size(1)
else
inputSize = input:size(1)
end
if self.args.inputFeed then
if prevOut == nil then
table.insert(inputs, onmt.utils.Tensor.reuseTensor(self.inputFeedProto,
{ inputSize, self.args.rnnSize }))
else
table.insert(inputs, prevOut)
end
end
-- Remember inputs for the backward pass.
if self.train then
self.inputs[t] = inputs
end
local outputs = self:net(t):forward(inputs)
local out = outputs[#outputs]
local states = {}
for i = 1, #outputs - 1 do
table.insert(states, outputs[i])
end
return out, states
end
--[[Compute all forward steps.
Parameters:
* `batch` - `Batch` object
* `encoderStates` -
* `context` -
* `func` - Calls `func(out, t)` each timestep.
--]]
function ParaSentDecoder:forwardAndApply(batch, encoderStates, context, func)
-- TODO: Make this a private method.
if self.statesProto == nil then
self.statesProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
self.stateProto,
{ batch.size, self.args.rnnSize })
end
local states = onmt.utils.Tensor.copyTensorTable(self.statesProto, encoderStates)
local prevOut
for t = 1, batch.targetLength do
prevOut, states = self:forwardOne(batch:getTargetInput(t), states, context, prevOut, t)
func(prevOut, t)
end
end
--[[Compute all forward steps.
Parameters:
* `batch` - a `Batch` object.
* `encoderStates` - a batch of initial decoder states (optional) [0]
* `context` - the context to apply attention to.
Returns: Table of top hidden state for each timestep.
--]]
function ParaSentDecoder:forward(batch, encoderStates, context)
encoderStates = encoderStates
or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
onmt.utils.Cuda.convert(torch.Tensor()),
{ batch.size, self.args.rnnSize })
if self.train then
self.inputs = {}
end
local outputs = {}
self:forwardAndApply(batch, encoderStates, context, function (out)
table.insert(outputs, out)
end)
return outputs
end
--[[ Compute the backward update.
Parameters:
* `batch` - a `Batch` object
* `outputs` - expected outputs
* `criterion` - a single target criterion object
Note: This code runs both the standard backward and criterion forward/backward.
It returns both the gradInputs and the loss.
-- ]]
function ParaSentDecoder:backward(batch, outputs, criterion)
if self.gradOutputsProto == nil then
self.gradOutputsProto = onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers + 1,
self.gradOutputProto,
{ batch.size, self.args.rnnSize })
end
local gradStatesInput = onmt.utils.Tensor.reuseTensorTable(self.gradOutputsProto,
{ batch.size, self.args.rnnSize })
local gradContextInput = onmt.utils.Tensor.reuseTensor(self.gradContextProto,
{ batch.size, batch.sourceLength, self.h_dim })
local loss = 0
for t = batch.targetLength, 1, -1 do
-- Compute decoder output gradients.
-- Note: This would typically be in the forward pass.
local pred = self.generator:forward(outputs[t])
local output = batch:getTargetOutput(t)
loss = loss + criterion:forward(pred, output)
-- Compute the criterion gradient.
local genGradOut = criterion:backward(pred, output)
for j = 1, #genGradOut do
genGradOut[j]:div(batch.totalSize)
end
-- Compute the final layer gradient.
local decGradOut = self.generator:backward(outputs[t], genGradOut)
gradStatesInput[#gradStatesInput]:add(decGradOut)
-- Compute the standarad backward.
local gradInput = self:net(t):backward(self.inputs[t], gradStatesInput)
-- Accumulate encoder output gradients.
gradContextInput:add(gradInput[self.args.inputIndex.context])
gradStatesInput[#gradStatesInput]:zero()
-- Accumulate previous output gradients with input feeding gradients.
if self.args.inputFeed and t > 1 then
gradStatesInput[#gradStatesInput]:add(gradInput[self.args.inputIndex.inputFeed])
end
-- Prepare next decoder output gradients.
for i = 1, #self.statesProto do
gradStatesInput[i]:copy(gradInput[i])
end
end
return gradStatesInput, gradContextInput, loss
end
--[[ Compute the loss on a batch.
Parameters:
* `batch` - a `Batch` to score.
* `encoderStates` - initialization of decoder.
* `context` - the attention context.
* `criterion` - a pointwise criterion.
--]]
function ParaSentDecoder:computeLoss(batch, encoderStates, context, criterion)
encoderStates = encoderStates
or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
onmt.utils.Cuda.convert(torch.Tensor()),
{ batch.size, self.args.rnnSize })
local loss = 0
self:forwardAndApply(batch, encoderStates, context, function (out, t)
local pred = self.generator:forward(out)
local output = batch:getTargetOutput(t)
loss = loss + criterion:forward(pred, output)
end)
return loss
end
--[[ Compute the score of a batch.
Parameters:
* `batch` - a `Batch` to score.
* `encoderStates` - initialization of decoder.
* `context` - the attention context.
--]]
function ParaSentDecoder:computeScore(batch, encoderStates, context)
encoderStates = encoderStates
or onmt.utils.Tensor.initTensorTable(self.args.numEffectiveLayers,
onmt.utils.Cuda.convert(torch.Tensor()),
{ batch.size, self.args.rnnSize })
local score = {}
self:forwardAndApply(batch, encoderStates, context, function (out, t)
local pred = self.generator:forward(out)
for b = 1, batch.size do
if t <= batch.targetSize[b] then
score[b] = (score[b] or 0) + pred[1][b][batch.targetOutput[t][b]]
end
end
end)
return score
end