forked from harvardnlp/seq2seq-attn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallel-train.lua
1536 lines (1465 loc) · 58.6 KB
/
parallel-train.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'nn'
require 'nngraph'
require 'hdf5'
require 'data.lua'
require 'util.lua'
require 'models.lua'
require 'model_utils.lua'
cmd = torch.CmdLine()
-- data files
cmd:text("")
cmd:text("**Data options**")
cmd:text("")
cmd:option('-data_file','data/demo-train.hdf5',[[Path to the training *.hdf5 file
from preprocess.py]])
cmd:option('-val_data_file','data/demo-val.hdf5',[[Path to validation *.hdf5 file
from preprocess.py]])
cmd:option('-data_file_2','data/demo-train_2.hdf5',[[Path to the joint training *.hdf5 file
from preprocess.py]])
cmd:option('-val_data_file_2','data/demo-train_2.hdf5',[[Path to the joint validation *.hdf5 file
from preprocess.py]])
cmd:option('-savefile', 'seq2seq_lstm_attn', [[Savefile name (model will be saved as
savefile_epochX_PPL.t7 where X is the X-th epoch and PPL is
the validation perplexity]])
cmd:option('-num_shards', 0, [[If the training data has been broken up into different shards,
then training files are in this many partitions]])
cmd:option('-train_from', '', [[If training from a checkpoint then this is the path to the
pretrained model.]])
cmd:option('-Y', 0, [[If this equals 1, then use one encoder and two decoders to train the nerel network]])
-- rnn model specs
cmd:text("")
cmd:text("**Model options**")
cmd:text("")
cmd:option('-joint', 0, [[joint equals 1 means train model jointly ]])
cmd:option('-num_layers', 2, [[Number of layers in the LSTM encoder/decoder]])
cmd:option('-rnn_size', 500, [[Size of LSTM hidden states]])
cmd:option('-word_vec_size', 500, [[Word embedding sizes]])
cmd:option('-attn', 1, [[If = 1, use attention on the decoder side. If = 0, it uses the last
hidden state of the decoder as context at each time step.]])
cmd:option('-brnn', 0, [[If = 1, use a bidirectional RNN. Hidden states of the fwd/bwd
RNNs are summed.]])
cmd:option('-use_chars_enc', 0, [[If = 1, use character on the encoder
side (instead of word embeddings]])
cmd:option('-use_chars_dec', 0, [[If = 1, use character on the decoder
side (instead of word embeddings]])
cmd:option('-reverse_src', 0, [[If = 1, reverse the source sequence. The original
sequence-to-sequence paper found that this was crucial to
achieving good performance, but with attention models this
does not seem necessary. Recommend leaving it to 0]])
cmd:option('-init_dec', 1, [[Initialize the hidden/cell state of the decoder at time
0 to be the last hidden/cell state of the encoder. If 0,
the initial states of the decoder are set to zero vectors]])
cmd:option('-input_feed', 1, [[If = 1, feed the context vector at each time step as additional
input (vica concatenation with the word embeddings) to the decoder]])
cmd:option('-multi_attn', 0, [[If > 0, then use a another attention layer on this layer of
the decoder. For example, if num_layers = 3 and `multi_attn = 2`,
then the model will do an attention over the source sequence
on the second layer (and use that as input to the third layer) and
the penultimate layer]])
cmd:option('-res_net', 0, [[Use residual connections between LSTM stacks whereby the input to
the l-th LSTM layer if the hidden state of the l-1-th LSTM layer
added with the l-2th LSTM layer. We didn't find this to help in our
experiments]])
cmd:text("")
cmd:text("Below options only apply if using the character model.")
cmd:text("")
-- char-cnn model specs (if use_chars == 1)
cmd:option('-char_vec_size', 25, [[Size of the character embeddings]])
cmd:option('-kernel_width', 6, [[Size (i.e. width) of the convolutional filter]])
cmd:option('-num_kernels', 1000, [[Number of convolutional filters (feature maps). So the
representation from characters will have this many dimensions]])
cmd:option('-num_highway_layers', 2, [[Number of highway layers in the character model]])
cmd:text("")
cmd:text("**Optimization options**")
cmd:text("")
-- optimization
cmd:option('-epochs', 13, [[Number of training epochs]])
cmd:option('-start_epoch', 1, [[If loading from a checkpoint, the epoch from which to start]])
cmd:option('-param_init', 0.1, [[Parameters are initialized over uniform distribution with support
(-param_init, param_init)]])
cmd:option('-optim', 'sgd', [[Optimization method. Possible options are:
sgd (vanilla SGD), adagrad, adadelta, adam]])
cmd:option('-learning_rate', 1, [[Starting learning rate. If adagrad/adadelta/adam is used,
then this is the global learning rate. Recommended settings: sgd =1,
adagrad = 0.1, adadelta = 1, adam = 0.1]])
cmd:option('-learning_rate_2', 0.5, [[Starting learning rate. If adagrad/adadelta/adam is used,
then this is the global learning rate. Recommended settings: sgd =1,
adagrad = 0.1, adadelta = 1, adam = 0.1]])
cmd:option('-max_grad_norm', 5, [[If the norm of the gradient vector exceeds this renormalize it
to have the norm equal to max_grad_norm]])
cmd:option('-dropout', 0.3, [[Dropout probability.
Dropout is applied between vertical LSTM stacks.]])
cmd:option('-lr_decay', 0.5, [[Decay learning rate by this much if (i) perplexity does not decrease
on the validation set or (ii) epoch has gone past the start_decay_at_limit]])
cmd:option('-lr_decay_2', 0.1, [[Decay learning rate by this much if (i) perplexity does not decrease
on the validation set or (ii) epoch has gone past the start_decay_at_limit]])
cmd:option('-start_decay_at', 9, [[Start decay after this epoch]])
cmd:option('-curriculum', 0, [[For this many epochs, order the minibatches based on source
sequence length. Sometimes setting this to 1 will increase convergence speed.]])
cmd:option('-pre_word_vecs_enc', '', [[If a valid path is specified, then this will load
pretrained word embeddings (hdf5 file) on the encoder side.
See README for specific formatting instructions.]])
cmd:option('-pre_word_vecs_dec', '', [[If a valid path is specified, then this will load
pretrained word embeddings (hdf5 file) on the decoder side.
See README for specific formatting instructions.]])
cmd:option('-fix_word_vecs_enc', 0, [[If = 1, fix word embeddings on the encoder side]])
cmd:option('-fix_word_vecs_dec', 0, [[If = 1, fix word embeddings on the decoder side]])
cmd:option('-max_batch_l', '', [[If blank, then it will infer the max batch size from validation
data. You should only use this if your validation set uses a different
batch size in the preprocessing step]])
cmd:text("")
cmd:text("**Other options**")
cmd:text("")
cmd:option('-start_symbol', 0, [[Use special start-of-sentence and end-of-sentence tokens
on the source side. We've found this to make minimal difference]])
-- GPU
cmd:option('-gpuid', -1, [[Which gpu to use. -1 = use CPU]])
cmd:option('-gpuid2', -1, [[If this is >= 0, then the model will use two GPUs whereby the encoder
is on the first GPU and the decoder is on the second GPU.
This will allow you to train with bigger batches/models.]])
cmd:option('-cudnn', 0, [[Whether to use cudnn or not for convolutions (for the character model).
cudnn has much faster convolutions so this is highly recommended
if using the character model]])
-- bookkeeping
cmd:option('-save_every', 1, [[Save every this many epochs]])
cmd:option('-print_every', 50, [[Print stats after this many batches]])
cmd:option('-seed', 3435, [[Seed for random initialization]])
opt = cmd:parse(arg)
torch.manualSeed(opt.seed)
function zero_table(t)
for i = 1, #t do
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
if i == 1 or (opt.joint == 1 and i == 4) then
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(opt.gpuid2)
end
end
t[i]:zero()
end
end
function train(train_data, valid_data,train_data_2,valid_data_2)
local timer = torch.Timer()
local num_params = 0
local start_decay = 0
params, grad_params = {}, {}
opt.train_perf = {}
opt.train_perf_2 = {}
opt.val_perf = {}
opt.val_perf_2 = {}
--(self) TODO change this when need second GPU
for i = 1, #layers do
if opt.gpuid2 >= 0 then
if i == 1 or (opt.joint == 1 and i == 4)then
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(opt.gpuid2)
end
end
local p, gp = layers[i]:getParameters()
if opt.train_from:len() == 0 then
p:uniform(-opt.param_init, opt.param_init)
end
num_params = num_params + p:size(1)
params[i] = p
grad_params[i] = gp
end
if opt.pre_word_vecs_enc:len() > 0 then
local f = hdf5.open(opt.pre_word_vecs_enc)
local pre_word_vecs = f:read('word_vecs'):all()
for i = 1, pre_word_vecs:size(1) do
word_vec_layers[1].weight[i]:copy(pre_word_vecs[i])
end
end
if opt.pre_word_vecs_dec:len() > 0 then
local f = hdf5.open(opt.pre_word_vecs_dec)
local pre_word_vecs = f:read('word_vecs'):all()
for i = 1, pre_word_vecs:size(1) do
word_vec_layers[2].weight[i]:copy(pre_word_vecs[i])
end
end
if opt.brnn == 1 then --subtract shared params for brnn
num_params = num_params - word_vec_layers[1].weight:nElement()
word_vec_layers[3].weight:copy(word_vec_layers[1].weight)
if opt.use_chars_enc == 1 then
for i = 1, charcnn_offset do
num_params = num_params - charcnn_layers[i]:nElement()
charcnn_layers[i+charcnn_offset]:copy(charcnn_layers[i])
end
end
end
print("Number of parameters: " .. num_params)
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
cutorch.setDevice(opt.gpuid)
word_vec_layers[1].weight[1]:zero()
if opt.joint == 1 then
word_vec_layers[3].weight[1]:zero()
end
cutorch.setDevice(opt.gpuid2)
word_vec_layers[2].weight[1]:zero()
if opt.joint == 1 then
word_vec_layers[4].weight[1]:zero()
end
else
word_vec_layers[1].weight[1]:zero()
word_vec_layers[2].weight[1]:zero()
if opt.brnn == 1 then
word_vec_layers[3].weight[1]:zero()
end
end
-- prototypes for gradients so there is no need to clone
encoder_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
encoder_bwd_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
context_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
--(self) Joint prototypes for gradients,
if opt.joint == 1 then
encoder_2_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
encoder_2_bwd_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
context_proto3 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
end
-- need more copies of the above if using two gpus
if opt.gpuid2 >= 0 then
encoder_grad_proto2 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
context_proto2 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
encoder_bwd_grad_proto2 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
if opt.joint == 1 then
encoder_2_grad_proto2 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
context_proto4 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
encoder_2_bwd_grad_proto2 = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size)
end
end
-- clone encoder/decoder up to max source/target length decoder were copied max_sent_l times for joint model
encoder_clones = clone_many_times(encoder, opt.max_sent_l_src)
if opt.joint == 1 then
decoder_clones = clone_many_times(decoder, opt.max_sent_l)
else
decoder_clones = clone_many_times(decoder, opt.max_sent_l_targ)
end
if opt.brnn == 1 then
encoder_bwd_clones = clone_many_times(encoder_bwd, opt.max_sent_l_src)
end
--(joint) ======
if opt.joint == 1 then
encoder_2_clones = clone_many_times(encoder_2, opt.max_sent_l_src_2)
decoder_2_clones = clone_many_times(decoder_2, opt.max_sent_l)
end
--(Joint End) ===========
--(self) Reuse memory for the clones
for i = 1, opt.max_sent_l_src do
if encoder_clones[i].apply then
encoder_clones[i]:apply(function(m) m:setReuse() end)
end
if opt.brnn == 1 then
encoder_bwd_clones[i]:apply(function(m) m:setReuse() end)
end
end
if opt.joint == 1 then
for i = 1, opt.max_sent_l_src_2 do
if encoder_2_clones[i].apply then
encoder_2_clones[i]:apply(function(m) m:setReuse() end)
end
end
end
if opt.joint == 1 then
for i = 1, opt.max_sent_l do
if decoder_clones[i].apply then
decoder_clones[i]:apply(function(m) m:setReuse() end)
end
if decoder_2_clones[i].apply then
decoder_2_clones[i]:apply(function(m) m:setReuse() end)
end
end
else
for i = 1, opt.max_sent_l_targ do
if decoder_clones[i].apply then
decoder_clones[i]:apply(function(m) m:setReuse() end)
end
end
end
-- setup the initial parameters(self)
local h_init = torch.zeros(opt.max_batch_l, opt.rnn_size)
if opt.gpuid >= 0 then
h_init = h_init:cuda()
cutorch.setDevice(opt.gpuid)
if opt.gpuid2 >= 0 then
encoder_grad_proto2 = encoder_grad_proto2:cuda()
-- encoder_bwd_grad_proto2 = encoder_bwd_grad_proto2:cuda()
context_proto = context_proto:cuda()
--(JOINT) set those things on gpu1
if opt.joint == 1 then
encoder_2_grad_proto2 = encoder_2_grad_proto2:cuda()
-- encoder_2_bwd_grad_proto2 = encoder_2_bwd_grad_proto2:cuda()
context_proto3= context_proto3:cuda()
end
cutorch.setDevice(opt.gpuid2)
encoder_grad_proto = encoder_grad_proto:cuda()
-- encoder_bwd_grad_proto = encoder_bwd_grad_proto:cuda()
context_proto2 = context_proto2:cuda()
--(joint) Set those things on gpu2
if opt.joint == 1 then
encoder_2_grad_proto = encoder_2_grad_proto:cuda()
-- encoder_2_bwd_grad_proto = encoder_2_bwd_grad_proto:cuda()
context_proto4 = context_proto4:cuda()
end
cutorch.setDevice(opt.gpuid)
else
context_proto = context_proto:cuda()
encoder_grad_proto = encoder_grad_proto:cuda()
if opt.brnn == 1 then
encoder_bwd_grad_proto = encoder_bwd_grad_proto:cuda()
end
if opt.joint == 1 then
encoder_2_grad_proto = encoder_2_grad_proto:cuda()
if opt.brnn == 1 then
encoder_2_bwd_grad_proto = encoder_2_bwd_grad_proto:cuda()
end
context_proto3 = context_proto3:cuda()
end
end
end
-- these are initial states of encoder/decoder for fwd/bwd steps
init_fwd_enc = {}
init_bwd_enc = {}
init_fwd_dec = {}
init_bwd_dec = {}
for L = 1, opt.num_layers do
table.insert(init_fwd_enc, h_init:clone())
table.insert(init_fwd_enc, h_init:clone())
table.insert(init_bwd_enc, h_init:clone())
table.insert(init_bwd_enc, h_init:clone())
end
if opt.gpuid2 >= 0 then
cutorch.setDevice(opt.gpuid2)
end
if opt.input_feed == 1 then
table.insert(init_fwd_dec, h_init:clone())
end
table.insert(init_bwd_dec, h_init:clone())
for L = 1, opt.num_layers do
table.insert(init_fwd_dec, h_init:clone())
table.insert(init_fwd_dec, h_init:clone())
table.insert(init_bwd_dec, h_init:clone())
table.insert(init_bwd_dec, h_init:clone())
end
dec_offset = 3 -- offset depends on input feeding
if opt.input_feed == 1 then
dec_offset = dec_offset + 1
end
--(self) return state of this function is copied
function reset_state(state, batch_l, t)
if t == nil then
local u = {}
for i = 1, #state do
state[i]:zero()
table.insert(u, state[i][{{1, batch_l}}])
end
return u
else
local u = {[t] = {}}
for i = 1, #state do
state[i]:zero()
table.insert(u[t], state[i][{{1, batch_l}}])
end
return u
end
end
-- clean layer before saving to make the model smaller
function clean_layer(layer)
if opt.gpuid >= 0 then
layer.output = torch.CudaTensor()
layer.gradInput = torch.CudaTensor()
else
layer.output = torch.DoubleTensor()
layer.gradInput = torch.DoubleTensor()
end
if layer.modules then
for i, mod in ipairs(layer.modules) do
clean_layer(mod)
end
elseif torch.type(self) == "nn.gModule" then
layer:apply(clean_layer)
end
end
-- decay learning rate if val perf does not improve or we hit the opt.start_decay_at limit
function decay_lr(epoch)
print(opt.val_perf)
if epoch >= opt.start_decay_at then
start_decay = 1
end
if opt.val_perf[#opt.val_perf] ~= nil and opt.val_perf[#opt.val_perf-1] ~= nil then
local curr_ppl = opt.val_perf[#opt.val_perf]
local prev_ppl = opt.val_perf[#opt.val_perf-1]
if curr_ppl > prev_ppl then
start_decay = 1
end
end
if start_decay == 1 then
opt.learning_rate = opt.learning_rate * opt.lr_decay
end
end
function decay_lr_2(epoch)
opt.learning_rate_2 = opt.learning_rate_2 * opt.lr_decay_2
end
function train_batch(data, epoch, data_2)
local train_nonzeros = 0
local train_nonzeros_2 = 0
local train_nonzeros_flow = 0
local train_nonzeros_2_flow = 0
local train_loss_2 = 0
local train_loss = 0
local train_loss_flow = 0
local train_loss_2_flow = 0
local batch_order = torch.randperm(data.length) -- shuffle mini batch order
if opt.joint == 1 then
batch_order_2 = torch.randperm(data_2.length)
end
local start_time = timer:time().real
local num_words_target = 0
local num_words_source = 0
local num_words_target_2 = 0
local num_words_source_2 = 0
if opt.joint == 0 then data_2 = data end
for i = 1, math.min(data:size(),data_2:size()) do
--load data
zero_table(grad_params, 'zero')
local d
local d_2
if epoch <= opt.curriculum then
d = data[i]
else
d = data[batch_order[i]]
end
if opt.joint == 1 then
if epoch <= opt.curriculum then
d_2 = data_2[i]
else
d_2 = data_2[batch_order_2[i]]
-- d_2 = data_2[i]
end
end
local target, target_out, nonzeros, source = d[1], d[2], d[3], d[4]
local batch_l, target_l, source_l = d[5], d[6], d[7]
local target_2, target_out_2, nonzeros_2, source_2
local batch_l_2, target_l_2, source_l_2
if opt.joint == 1 then
target_2, target_out_2, nonzeros_2, source_2 = d_2[1], d_2[2], d_2[3], d_2[4]
batch_l_2, target_l_2, source_l_2 = d_2[5], d_2[6], d_2[7]
end
for joint_train = 1, 2 do
if opt.joint == 0 and joint_train == 2 then break end
local encoder_grads = encoder_grad_proto[{{1, batch_l}, {1, source_l}}]
local encoder_2_grads
if opt.joint == 1 then
encoder_2_grads = encoder_2_grad_proto[{{1, batch_l_2}, {1, source_l_2}}]
end
local encoder_bwd_grads
if opt.brnn == 1 then
encoder_bwd_grads = encoder_bwd_grad_proto[{{1, batch_l}, {1, source_l}}]
end
local dec_batch_l
local dec_2_batch_l
if joint_train == 1 then
dec_batch_l = batch_l
dec_2_batch_l = batch_l_2
else
dec_batch_l = batch_l_2
dec_2_batch_l = batch_l
end
if opt.gpuid >= 0 then
cutorch.setDevice(opt.gpuid)
end
local rnn_state_enc_2 = reset_state(init_fwd_enc, batch_l_2, 0)
local rnn_state_enc = reset_state(init_fwd_enc, batch_l, 0)
local context = context_proto[{{1, batch_l}, {1, source_l}}]
if opt.joint == 1 then
context_joint = context_proto3[{{1, batch_l_2}, {1, source_l_2}}]
end
-- forward prop encoder
for t = 1, source_l do
encoder_clones[t]:training()
local encoder_input = {source[t], table.unpack(rnn_state_enc[t-1])}
local out = encoder_clones[t]:forward(encoder_input)
rnn_state_enc[t] = out
context[{{},t}]:copy(out[#out])
end
if opt.joint == 1 then
for t = 1, source_l_2 do
encoder_2_clones[t]:training()
local encoder_input = {source_2[t], table.unpack(rnn_state_enc_2[t-1])}
local out = encoder_2_clones[t]:forward(encoder_input)
rnn_state_enc_2[t] = out-- save the encoder status for backprop(self)
context_joint[{{},t}]:copy(out[#out])
end
end
local rnn_state_enc_bwd
if opt.brnn == 1 then
rnn_state_enc_bwd = reset_state(init_fwd_enc, batch_l, source_l+1)
for t = source_l, 1, -1 do
encoder_bwd_clones[t]:training()
local encoder_input = {source[t], table.unpack(rnn_state_enc_bwd[t+1])}
local out = encoder_bwd_clones[t]:forward(encoder_input)
rnn_state_enc_bwd[t] = out
context[{{},t}]:add(out[#out])
end
end
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
cutorch.setDevice(opt.gpuid2)
local context2 = context_proto2[{{1, batch_l}, {1, source_l}}]
if opt.joint == 1 then
context2_joint = context_proto4[{{1, batch_l_2}, {1, source_l_2}}]
end
context2:copy(context)
context = context2
if opt.joint == 1 then
context2_joint:copy(context_joint)
context_joint = context2_joint
end
end
-- copy encoder last hidden state to decoder initial state
local rnn_state_dec
local rnn_state_dec_2
-- in the second train happens, decoder uses the input got from decoder
rnn_state_dec = reset_state(init_fwd_dec, dec_batch_l, 0)
rnn_state_dec_2 = reset_state(init_fwd_dec, dec_2_batch_l, 0)
if opt.init_dec == 1 then
for L = 1, opt.num_layers do
if joint_train == 1 then
rnn_state_dec[0][L*2-1+opt.input_feed]:copy(rnn_state_enc[source_l][L*2-1])
rnn_state_dec[0][L*2+opt.input_feed]:copy(rnn_state_enc[source_l][L*2])
else
rnn_state_dec_2[0][L*2-1+opt.input_feed]:copy(rnn_state_enc[source_l][L*2-1])
rnn_state_dec_2[0][L*2+opt.input_feed]:copy(rnn_state_enc[source_l][L*2])
end
end
if opt.brnn == 1 then
for L = 1, opt.num_layers do
rnn_state_dec[0][L*2-1+opt.input_feed]:add(rnn_state_enc_bwd[1][L*2-1])
rnn_state_dec[0][L*2+opt.input_feed]:add(rnn_state_enc_bwd[1][L*2])
end
end
if opt.joint == 1 then
for L = 1, opt.num_layers do
if joint_train == 1 then
rnn_state_dec_2[0][L*2-1+opt.input_feed]:copy(rnn_state_enc_2[source_l_2][L*2-1])
rnn_state_dec_2[0][L*2+opt.input_feed]:copy(rnn_state_enc_2[source_l_2][L*2])
else
rnn_state_dec[0][L*2-1+opt.input_feed]:copy(rnn_state_enc_2[source_l_2][L*2-1])
rnn_state_dec[0][L*2+opt.input_feed]:copy(rnn_state_enc_2[source_l_2][L*2])
end
end
end
end
-- forward prop decoder
local preds = {}
local preds_2 = {}
local decoder_input
local dec_iter
local dec_2_iter
local source_2_copy
local source_copy
if joint_train == 1 then
dec_iter = target_l
dec_2_iter = target_l_2
else
dec_iter = source_l_2
dec_2_iter = source_l
source_2_copy = source_2:clone()
source_copy = source:clone()
end
for t = 1, dec_iter do
decoder_clones[t]:training()
local decoder_input
if joint_train == 1 then
if opt.attn == 1 then
decoder_input = {target[t], context, table.unpack(rnn_state_dec[t-1])}
else
decoder_input = {target[t], context[{{}, source_l}], table.unpack(rnn_state_dec[t-1])}
end
else
if opt.attn == 1 then
decoder_input = {source_2_copy[t], context_joint, table.unpack(rnn_state_dec[t-1])}
else
decoder_input = {source_2_copy[t], context_joint[{{}, source_l_2}], table.unpack(rnn_state_dec[t-1])}
end
end
local out = decoder_clones[t]:forward(decoder_input)
local next_state = {}
table.insert(preds, out[#out])
if opt.input_feed == 1 then
table.insert(next_state, out[#out])
end
for j = 1, #out-1 do
table.insert(next_state, out[j])
end
rnn_state_dec[t] = next_state
end
if opt.joint == 1 then
for t = 1, dec_2_iter do
decoder_2_clones[t]:training()
local decoder_input
if joint_train == 1 then
if opt.attn == 1 then
decoder_input = {target_2[t], context_joint, table.unpack(rnn_state_dec_2[t-1])}
else
decoder_input = {target_2[t], context_joint[{{}, source_l_2}], table.unpack(rnn_state_dec_2[t-1])}
end
else
if opt.attn == 1 then
decoder_input = {source_copy[t], context, table.unpack(rnn_state_dec_2[t-1])}
else
decoder_input = {source_copy[t], context[{{}, source_l}], table.unpack(rnn_state_dec_2[t-1])}
end
end
local out = decoder_2_clones[t]:forward(decoder_input)
local next_state = {}
table.insert(preds_2, out[#out])
if opt.input_feed == 1 then
table.insert(next_state, out[#out])
end
for j = 1, #out-1 do
table.insert(next_state, out[j])
end
rnn_state_dec_2[t] = next_state
end
end
-- backward prop decoder
encoder_grads:zero()
if opt.joint == 1 then
encoder_2_grads:zero()
end
if opt.brnn == 1 then
encoder_bwd_grads:zero()
end
local drnn_state_dec = reset_state(init_bwd_dec, dec_batch_l)
local drnn_state_dec_2 = reset_state(init_bwd_dec, dec_2_batch_l)
local loss = 0
local loss_2 = 0
for t = dec_iter, 1, -1 do
local pred = generator:forward(preds[t])
local dl_dpred
if joint_train == 1 then
loss = loss + criterion:forward(pred, target_out[t])/dec_batch_l
dl_dpred = criterion:backward(pred, target_out[t])
else
loss = loss + criterion:forward(pred, source_2_copy[t])/dec_batch_l
dl_dpred = criterion:backward(pred, source_2_copy[t])
end
dl_dpred:div(dec_batch_l)
local dl_dtarget = generator:backward(preds[t], dl_dpred)
drnn_state_dec[#drnn_state_dec]:add(dl_dtarget)
local decoder_input
if joint_train == 1 then
if opt.attn == 1 then
decoder_input = {target[t], context, table.unpack(rnn_state_dec[t-1])}
else
decoder_input = {target[t], context[{{}, source_l}], table.unpack(rnn_state_dec[t-1])}
end
else
if opt.attn == 1 then
decoder_input = {source_2[t], context_joint, table.unpack(rnn_state_dec[t-1])}
else
decoder_input = {source_2[t], context_joint[{{}, source_l_2}], table.unpack(rnn_state_dec[t-1])}
end
end
local dlst = decoder_clones[t]:backward(decoder_input, drnn_state_dec)
-- accumulate encoder/decoder grads
if opt.attn == 1 then
if joint_train == 1 then
encoder_grads:add(dlst[2])
else
encoder_2_grads:add(dlst[2])
end
if opt.brnn == 1 then
encoder_bwd_grads:add(dlst[2])
end
else
if joint_train == 1 then
encoder_grads[{{}, source_l}]:add(dlst[2])
else
encoder_2_grads[{{}, source_l_2}]:add(dlst[2])
end
if opt.brnn == 1 then
encoder_bwd_grads[{{}, 1}]:add(dlst[2])
end
end
drnn_state_dec[#drnn_state_dec]:zero()
if opt.input_feed == 1 then
drnn_state_dec[#drnn_state_dec]:add(dlst[3])
end
for j = dec_offset, #dlst do
drnn_state_dec[j-dec_offset+1]:copy(dlst[j])
end
end
--(joint)
if opt.joint == 1 then
for t = dec_2_iter, 1, -1 do
local pred_2 = generator_2:forward(preds_2[t])
local dl_dpred
if joint_train == 1 then
loss_2 = loss_2 + criterion:forward(pred_2, target_out_2[t])/dec_2_batch_l
dl_dpred = criterion:backward(pred_2, target_out_2[t])
else
loss_2 = loss_2 + criterion:forward(pred_2, source_copy[t])/dec_2_batch_l
dl_dpred = criterion:backward(pred_2, source_copy[t])
end
dl_dpred:div(dec_2_batch_l)
local dl_dtarget = generator_2:backward(preds_2[t], dl_dpred)
drnn_state_dec_2[#drnn_state_dec_2]:add(dl_dtarget)
local decoder_input
if joint_train == 1 then
if opt.attn == 1 then
decoder_input = {target_2[t], context_joint, table.unpack(rnn_state_dec_2[t-1])}
else
decoder_input = {target_2[t], context_joint[{{}, source_l_2}], table.unpack(rnn_state_dec_2[t-1])}
end
else
if opt.attn == 1 then
decoder_input = {source[t], context, table.unpack(rnn_state_dec_2[t-1])}
else
decoder_input = {source[t], context[{{}, source_l}], table.unpack(rnn_state_dec_2[t-1])}
end
end
local dlst = decoder_2_clones[t]:backward(decoder_input, drnn_state_dec_2)
-- accumulate encoder/decoder grads
if opt.attn == 1 then
if joint_train == 1 then
encoder_2_grads:add(dlst[2])
else
encoder_grads:add(dlst[2])
end
if opt.brnn == 1 then
encoder_bwd_grads:add(dlst[2])
end
else
if joint_train ==1 then
encoder_2_grads[{{}, source_l_2}]:add(dlst[2])
else
encoder_grads[{{}, source_l}]:add(dlst[2])
end
if opt.brnn == 1 then
encoder_bwd_grads[{{}, 1}]:add(dlst[2])
end
end
drnn_state_dec_2[#drnn_state_dec_2]:zero()
if opt.input_feed == 1 then
drnn_state_dec_2[#drnn_state_dec_2]:add(dlst[3])
end
for j = dec_offset, #dlst do
drnn_state_dec_2[j-dec_offset+1]:copy(dlst[j])
end
end
end
word_vec_layers[2].gradWeight[1]:zero()
--(Joint)
if opt.joint == 1 then
word_vec_layers[4].gradWeight[1]:zero()
end
if opt.fix_word_vecs_dec == 1 then
word_vec_layers[2].gradWeight:zero()
if opt.joint == 1 then
word_vec_layers[4].gradWeight:zero()
end
end
local grad_norm = 0
local grad_norm_2 = 0
grad_norm = grad_norm + grad_params[2]:norm()^2 + grad_params[3]:norm()^2
--(joint) adding the grad_norm of joint model
if opt.joint == 1 then
grad_norm_2 = grad_norm_2 + grad_params[5]:norm()^2 + grad_params[6]:norm()^2
end
-- backward prop encoder
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
cutorch.setDevice(opt.gpuid)
local encoder_grads2 = encoder_grad_proto2[{{1, batch_l}, {1, source_l}}]
encoder_grads2:zero()
encoder_grads2:copy(encoder_grads)
encoder_grads = encoder_grads2 -- batch_l x source_l x rnn_size
--(joint)
if opt.joint == 1 then
encoder_2_grads2 = encoder_2_grad_proto2[{{1, batch_l_2}, {1, source_l_2}}]
encoder_2_grads2:zero()
encoder_2_grads2:copy(encoder_2_grads)
encoder_2_grads = encoder_2_grads2 -- batch_l_2 x source_l_2 x rnn_size
end
end
local drnn_state_enc = reset_state(init_bwd_enc, batch_l)
local drnn_state_enc_2 = reset_state(init_bwd_enc, batch_l_2)
if opt.init_dec == 1 then
for L = 1, opt.num_layers do
if joint_train == 1 then
drnn_state_enc[L*2-1]:copy(drnn_state_dec[L*2-1])
drnn_state_enc[L*2]:copy(drnn_state_dec[L*2])
else
drnn_state_enc[L*2-1]:copy(drnn_state_dec_2[L*2-1])
drnn_state_enc[L*2]:copy(drnn_state_dec_2[L*2])
end
end
--(joint)
if opt.joint == 1 then
for L = 1, opt.num_layers do
if joint_train == 1 then
drnn_state_enc_2[L*2-1]:copy(drnn_state_dec_2[L*2-1])
drnn_state_enc_2[L*2]:copy(drnn_state_dec_2[L*2])
else
drnn_state_enc_2[L*2-1]:copy(drnn_state_dec[L*2-1])
drnn_state_enc_2[L*2]:copy(drnn_state_dec[L*2])
end
end
end
end
for t = source_l, 1, -1 do
local encoder_input = {source[t], table.unpack(rnn_state_enc[t-1])}
if opt.attn == 1 then
drnn_state_enc[#drnn_state_enc]:add(encoder_grads[{{},t}])
else
if t == source_l then
drnn_state_enc[#drnn_state_enc]:add(encoder_grads[{{},t}])
end
end
local dlst = encoder_clones[t]:backward(encoder_input, drnn_state_enc)
for j = 1, #drnn_state_enc do
drnn_state_enc[j]:copy(dlst[j+1])
end
end
if opt.joint == 1 then
for t = source_l_2, 1, -1 do
local encoder_input = {source_2[t], table.unpack(rnn_state_enc_2[t-1])}
if opt.attn == 1 then
drnn_state_enc_2[#drnn_state_enc_2]:add(encoder_2_grads[{{},t}])
else
if t == source_l_2 then
drnn_state_enc_2[#drnn_state_enc_2]:add(encoder_2_grads[{{},t}])
end
end
local dlst = encoder_2_clones[t]:backward(encoder_input, drnn_state_enc_2)
for j = 1, #drnn_state_enc_2 do
drnn_state_enc_2[j]:copy(dlst[j+1])
end
end
end
if opt.brnn == 1 then
local drnn_state_enc = reset_state(init_bwd_enc, batch_l)
if opt.init_dec == 1 then
for L = 1, opt.num_layers do
drnn_state_enc[L*2-1]:copy(drnn_state_dec[L*2-1])
drnn_state_enc[L*2]:copy(drnn_state_dec[L*2])
end
end
for t = 1, source_l do
local encoder_input = {source[t], table.unpack(rnn_state_enc_bwd[t+1])}
if opt.attn == 1 then
drnn_state_enc[#drnn_state_enc]:add(encoder_bwd_grads[{{},t}])
else
if t == 1 then
drnn_state_enc[#drnn_state_enc]:add(encoder_bwd_grads[{{},t}])
end
end
local dlst = encoder_bwd_clones[t]:backward(encoder_input, drnn_state_enc)
for j = 1, #drnn_state_enc do
drnn_state_enc[j]:copy(dlst[j+1])
end
end
end
word_vec_layers[1].gradWeight[1]:zero()
if opt.joint == 1 then
word_vec_layers[3].gradWeight[1]:zero()
end
if opt.fix_word_vecs_enc == 1 then
word_vec_layers[1].gradWeight:zero()
if pot.joint == 1 then
word_vec_layers[3].gradWeight:zero()
end
end
grad_norm = grad_norm + grad_params[1]:norm()^2
if opt.brnn == 1 then
grad_norm = grad_norm + grad_params[4]:norm()^2
end
if opt.joint == 1 then
grad_norm_2 = grad_norm_2 + grad_params[4]:norm()^2
grad_norm_2 = grad_norm_2^0.5
end
grad_norm = grad_norm^0.5
if opt.brnn == 1 then
word_vec_layers[1].gradWeight:add(word_vec_layers[3].gradWeight)
if opt.use_chars_enc == 1 then
for j = 1, charcnn_offset do
charcnn_grad_layers[j]:add(charcnn_grad_layers[j+charcnn_offset])
end
end
end
-- Shrink norm and update params
local param_norm = 0
local param_norm_2 = 0
local shrinkage = opt.max_grad_norm / grad_norm
local shrinkage_2
if opt.joint == 1 then
shrinkage_2 = opt.max_grad_norm / grad_norm_2
end
--(joint) shrink the gradient parameter for normal model and joint model
if opt.joint == 0 then
for j = 1, #grad_params do
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
if j == 1 then
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(opt.gpuid2)
end
end
if shrinkage < 1 then
grad_params[j]:mul(shrinkage)
end
if opt.optim == 'adagrad' then
adagrad_step(params[j], grad_params[j], layer_etas[j], optStates[j])
elseif opt.optim == 'adadelta' then
adadelta_step(params[j], grad_params[j], layer_etas[j], optStates[j])
elseif opt.optim == 'adam' then
adam_step(params[j], grad_params[j], layer_etas[j], optStates[j])
else
params[j]:add(grad_params[j]:mul(-opt.learning_rate))
end
param_norm = param_norm + params[j]:norm()^2
end
else
for j = 1, 3 do
if opt.gpuid >= 0 and opt.gpuid2 >= 0 then
if j == 1 then
cutorch.setDevice(opt.gpuid)
else
cutorch.setDevice(opt.gpuid2)
end
end
if shrinkage < 1 then
grad_params[j]:mul(shrinkage)
end
if shrinkage_2 < 1 then
grad_params[j+3]:mul(shrinkage_2)
end
if opt.optim == 'adagrad' then
adagrad_step(params[j], grad_params[j], layer_etas[j], optStates[j])
adagrad_step(params[j+3], grad_params[j+3], layer_etas[j], optStates[j])
elseif opt.optim == 'adadelta' then
adadelta_step(params[j], grad_params[j], layer_etas[j], optStates[j])
adadelta_step(params[j+3], grad_params[j+3], layer_etas[j], optStates[j])
elseif opt.optim == 'adam' then
adam_step(params[j], grad_params[j], layer_etas[j], optStates[j])
adam_step(params[j+3], grad_params[j+3], layer_etas[j], optStates[j])
else
if joint_train == 1 then
params[j]:add(grad_params[j]:mul(-opt.learning_rate))
params[j+3]:add(grad_params[j+3]:mul(-opt.learning_rate))
else
params[j]:add(grad_params[j]:mul(-opt.learning_rate_2))
params[j+3]:add(grad_params[j+3]:mul(-opt.learning_rate_2))
end
end
param_norm = param_norm + params[j]:norm()^2
param_norm_2 = param_norm_2 + params[j+3]:norm()^2
end
end
param_norm = param_norm^0.5