-
Notifications
You must be signed in to change notification settings - Fork 0
/
nmt.RL.py
1611 lines (1269 loc) · 68.2 KB
/
nmt.RL.py
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
from __future__ import print_function
import re
import torch
import torch.nn as nn
import torch.nn.utils
from torch.autograd import Variable
from torch import optim
from torch.nn import Parameter
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction
import time
import numpy as np
from collections import defaultdict, Counter, namedtuple
from itertools import chain, islice
import argparse, os, sys
from util import read_corpus, data_iter, batch_slice
from vocab import Vocab, VocabEntry
from process_samples import generate_hamming_distance_payoff_distribution
import math
def init_config():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', default=5783287, type=int, help='random seed')
parser.add_argument('--cuda', action='store_true', default=False, help='use gpu')
parser.add_argument('--mode', choices=['RL_train', 'train', 'raml_train', 'test', 'sample', 'prob', 'interactive'],
default='train', help='run mode')
parser.add_argument('--vocab', type=str, help='path of the serialized vocabulary')
parser.add_argument('--batch_size', default=32, type=int, help='batch size')
parser.add_argument('--beam_size', default=5, type=int, help='beam size for beam search')
parser.add_argument('--sample_size', default=10, type=int, help='sample size')
parser.add_argument('--embed_size', default=256, type=int, help='size of word embeddings')
parser.add_argument('--hidden_size', default=256, type=int, help='size of LSTM hidden states')
parser.add_argument('--dropout', default=0., type=float, help='dropout rate')
parser.add_argument('--train_src', type=str, help='path to the training source file')
parser.add_argument('--train_tgt', type=str, help='path to the training target file')
parser.add_argument('--dev_src', type=str, help='path to the dev source file')
parser.add_argument('--dev_tgt', type=str, help='path to the dev target file')
parser.add_argument('--test_src', type=str, help='path to the test source file')
parser.add_argument('--test_tgt', type=str, help='path to the test target file')
parser.add_argument('--decode_max_time_step', default=200, type=int, help='maximum number of time steps used '
'in decoding and sampling')
parser.add_argument('--valid_niter', default=500, type=int, help='every n iterations to perform validation')
parser.add_argument('--valid_metric', default='bleu', choices=['bleu', 'ppl', 'word_acc', 'sent_acc'], help='metric used for validation')
parser.add_argument('--log_every', default=50, type=int, help='every n iterations to log training statistics')
parser.add_argument('--load_model', default=None, type=str, help='load a pre-trained model')
parser.add_argument('--save_to', default='model', type=str, help='save trained model to')
parser.add_argument('--save_model_after', default=2, help='save the model only after n validation iterations')
parser.add_argument('--save_to_file', default=None, type=str, help='if provided, save decoding results to file')
parser.add_argument('--save_nbest', default=False, action='store_true', help='save nbest decoding results')
parser.add_argument('--patience', default=5, type=int, help='training patience')
parser.add_argument('--uniform_init', default=None, type=float, help='if specified, use uniform initialization for all parameters')
parser.add_argument('--clip_grad', default=5., type=float, help='clip gradients')
parser.add_argument('--max_niter', default=-1, type=int, help='maximum number of training iterations')
parser.add_argument('--lr', default=0.001, type=float, help='learning rate')
parser.add_argument('--lr_decay', default=0.5, type=float, help='decay learning rate if the validation performance drops')
# raml training
parser.add_argument('--debug', default=False, action='store_true')
parser.add_argument('--temp', default=0.85, type=float, help='temperature in reward distribution')
parser.add_argument('--raml_sample_mode', default='pre_sample',
choices=['pre_sample', 'hamming_distance', 'hamming_distance_impt_sample'],
help='sample mode when using RAML')
parser.add_argument('--raml_sample_file', type=str, help='path to the sampled targets')
parser.add_argument('--raml_bias_groundtruth', action='store_true', default=False, help='make sure ground truth y* is in samples')
parser.add_argument('--smooth_bleu', action='store_true', default=False,
help='smooth sentence level BLEU score.')
#TODO: greedy sampling is still buggy!
parser.add_argument('--sample_method', default='random', choices=['random', 'greedy'])
args = parser.parse_args()
# seed the RNG
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
np.random.seed(args.seed * 13 / 7)
return args
def input_transpose(sents, pad_token):
max_len = max(len(s) for s in sents)
batch_size = len(sents)
sents_t = []
masks = []
for i in xrange(max_len):
sents_t.append([sents[k][i] if len(sents[k]) > i else pad_token for k in xrange(batch_size)])
masks.append([1 if len(sents[k]) > i else 0 for k in xrange(batch_size)])
return sents_t, masks
def word2id(sents, vocab):
if type(sents[0]) == list:
return [[vocab[w] for w in s] for s in sents]
else:
return [vocab[w] for w in sents]
def tensor_transform(linear, X):
# X is a 3D tensor
return linear(X.contiguous().view(-1, X.size(2))).view(X.size(0), X.size(1), -1)
class NMT(nn.Module):
def __init__(self, args, vocab):
super(NMT, self).__init__()
self.args = args
self.vocab = vocab
self.src_embed = nn.Embedding(len(vocab.src), args.embed_size, padding_idx=vocab.src['<pad>'])
self.tgt_embed = nn.Embedding(len(vocab.tgt), args.embed_size, padding_idx=vocab.tgt['<pad>'])
self.encoder_lstm = nn.LSTM(args.embed_size, args.hidden_size, bidirectional=True, dropout=args.dropout)
self.decoder_lstm = nn.LSTMCell(args.embed_size + args.hidden_size, args.hidden_size)
# attention: dot product attention
# project source encoding to decoder rnn's h space
self.att_src_linear = nn.Linear(args.hidden_size * 2, args.hidden_size, bias=False)
# transformation of decoder hidden states and context vectors before reading out target words
# this produces the `attentional vector` in (Luong et al., 2015)
self.att_vec_linear = nn.Linear(args.hidden_size * 2 + args.hidden_size, args.hidden_size, bias=False)
# prediction layer of the target vocabulary
self.readout = nn.Linear(args.hidden_size, len(vocab.tgt), bias=False)
# dropout layer
self.dropout = nn.Dropout(args.dropout)
# initialize the decoder's state and cells with encoder hidden states
self.decoder_cell_init = nn.Linear(args.hidden_size * 2, args.hidden_size)
def forward(self, src_sents, src_sents_len, tgt_words):
src_encodings, init_ctx_vec = self.encode(src_sents, src_sents_len)
scores, sample_y = self.decode_sample(src_encodings, init_ctx_vec, tgt_words)
base_y = self.decode_baseline(src_encodings, init_ctx_vec, tgt_words)
#222
return scores, sample_y, base_y
def encode(self, src_sents, src_sents_len):
"""
:param src_sents: (src_sent_len, batch_size), sorted by the length of the source
:param src_sents_len: (src_sent_len)
"""
# (src_sent_len, batch_size, embed_size)
src_word_embed = self.src_embed(src_sents)
packed_src_embed = pack_padded_sequence(src_word_embed, src_sents_len)
# output: (src_sent_len, batch_size, hidden_size)
output, (last_state, last_cell) = self.encoder_lstm(packed_src_embed)
output, _ = pad_packed_sequence(output)
dec_init_cell = self.decoder_cell_init(torch.cat([last_cell[0], last_cell[1]], 1))
dec_init_state = F.tanh(dec_init_cell)
return output, (dec_init_state, dec_init_cell)
def decode_sample(self, src_encoding, dec_init_vec, tgt_sents):
"""
:param src_encoding: (src_sent_len, batch_size, hidden_size)
:param dec_init_vec: (batch_size, hidden_size)
:param tgt_sents: (tgt_sent_len, batch_size)
:return:
"""
init_state = dec_init_vec[0]
init_cell = dec_init_vec[1]
hidden = (init_state, init_cell)
new_tensor = init_cell.data.new
batch_size = src_encoding.size(1)
# (batch_size, src_sent_len, hidden_size * 2)
src_encoding = src_encoding.permute(1, 0, 2)
# (batch_size, src_sent_len, hidden_size)
src_encoding_att_linear = tensor_transform(self.att_src_linear, src_encoding)
# initialize attentional vector
att_tm1 = Variable(new_tensor(batch_size, self.args.hidden_size).zero_(), requires_grad=False)
#tgt_word_embed = self.tgt_embed(tgt_sents)
scores = []
tgt_len = tgt_sents.size(0)
sample_y = []
for i in range(tgt_len):
if i == 0:
y_tm1_embed = self.tgt_embed(tgt_sents[0].view(-1)) #tgt_word_embed.split(split_size=1)
## a y
else:
y_tm1_embed = self.tgt_embed(sample_y[-1].view(-1))
#cur_score = F.softmax(self.readout(att_tm1))
#cur_y = cur_score.multinomial(1).view(-1)
#y_tm1_embed = self.tgt_embed(cur_y)
# input feeding: concate y_tm1 and previous attentional vector
x = torch.cat([y_tm1_embed, att_tm1], 1)
#sample_y.append(cur_y.view(-1,1))
# self.decoder_lstm = nn.LSTMCell(args.embed_size + args.hidden_size, args.hidden_size)
# h_t: (batch_size, hidden_size)
h_t, cell_t = self.decoder_lstm(x, hidden)
h_t = self.dropout(h_t)
ctx_t, alpha_t = self.dot_prod_attention(h_t, src_encoding, src_encoding_att_linear)
# softmax
# this produces the `attentional vector` in (Luong et al., 2015)
# self.att_vec_linear = nn.Linear(args.hidden_size * 2 + args.hidden_size, args.hidden_size, bias=False)
# prediction layer of the target vocabulary
att_t = F.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1))) # E.q. (5)
att_t = self.dropout(att_t)
# self.readout = nn.Linear(args.hidden_size, len(vocab.tgt), bias=False)
score_t = self.readout(att_t) # E.q. (6)
scores.append(score_t)
cur_y = torch.multinomial(F.softmax(score_t), 1).view(-1)
sample_y.append(cur_y.view(-1,1))
att_tm1 = att_t
hidden = h_t, cell_t
'''
# start from `<s>`, until y_{T-1}
for y_tm1_embed in tgt_word_embed.split(split_size=1):
# input feeding: concate y_tm1 and previous attentional vector
x = torch.cat([y_tm1_embed.squeeze(0), att_tm1], 1)
# h_t: (batch_size, hidden_size)
h_t, cell_t = self.decoder_lstm(x, hidden)
h_t = self.dropout(h_t)
ctx_t, alpha_t = self.dot_prod_attention(h_t, src_encoding, src_encoding_att_linear)
att_t = F.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1))) # E.q. (5)
att_t = self.dropout(att_t)
score_t = self.readout(att_t) # E.q. (6)
scores.append(score_t)
att_tm1 = att_t
hidden = h_t, cell_t
'''
scores = torch.stack(scores)
sample_y = torch.stack(sample_y)
return scores, sample_y
def decode_baseline(self, src_encoding, dec_init_vec, tgt_sents):
"""
:param src_encoding: (src_sent_len, batch_size, hidden_size)
:param dec_init_vec: (batch_size, hidden_size)
:param tgt_sents: (tgt_sent_len, batch_size)
:return:
"""
init_state = dec_init_vec[0]
init_cell = dec_init_vec[1]
hidden = (init_state, init_cell)
new_tensor = init_cell.data.new
batch_size = src_encoding.size(1)
# (batch_size, src_sent_len, hidden_size * 2)
src_encoding = src_encoding.permute(1, 0, 2)
# (batch_size, src_sent_len, hidden_size)
src_encoding_att_linear = tensor_transform(self.att_src_linear, src_encoding)
# initialize attentional vector
att_tm1 = Variable(new_tensor(batch_size, self.args.hidden_size).zero_(), requires_grad=False)
#tgt_word_embed = self.tgt_embed(tgt_sents)
tgt_len = tgt_sents.size(0)
#sample_y = []
base_y = []
#scores = []
# start from `<s>`, until y_{T-1}
#for y_tm1_embed in tgt_word_embed.split(split_size=1):
for i in range(tgt_len):
if i == 0:
y_tm1_embed = self.tgt_embed(tgt_sents[0].view(-1))
else:
y_tm1_embed = self.tgt_embed(base_y[-1].view(-1))
# input feeding: concate y_tm1 and previous attentional vector
x = torch.cat([y_tm1_embed, att_tm1], 1)
# h_t: (batch_size, hidden_size)
h_t, cell_t = self.decoder_lstm(x, hidden)
h_t = self.dropout(h_t)
ctx_t, alpha_t = self.dot_prod_attention(h_t, src_encoding, src_encoding_att_linear)
att_t = F.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1))) # E.q. (5)
att_t = self.dropout(att_t)
score_t = self.readout(att_t) # E.q. (6)
#base_y.append(F.log_softmax(score_t).view(-1,1))
_ , cur_max_y = torch.max(score_t, 1)
base_y.append(cur_max_y.view(-1, 1))
#scores.append(score_t)
att_tm1 = att_t
hidden = h_t, cell_t
base_y = torch.stack(base_y)
return base_y
def translate(self, src_sents, beam_size=None, to_word=True):
"""
perform beam search
TODO: batched beam search
"""
if not type(src_sents[0]) == list:
src_sents = [src_sents]
if not beam_size:
beam_size = args.beam_size
src_sents_var = to_input_variable(src_sents, self.vocab.src, cuda=args.cuda, is_test=True)
src_encoding, dec_init_vec = self.encode(src_sents_var, [len(src_sents[0])])
src_encoding_att_linear = tensor_transform(self.att_src_linear, src_encoding)
init_state = dec_init_vec[0]
init_cell = dec_init_vec[1]
hidden = (init_state, init_cell)
att_tm1 = Variable(torch.zeros(1, self.args.hidden_size), volatile=True)
hyp_scores = Variable(torch.zeros(1), volatile=True)
if args.cuda:
att_tm1 = att_tm1.cuda()
hyp_scores = hyp_scores.cuda()
eos_id = self.vocab.tgt['</s>']
bos_id = self.vocab.tgt['<s>']
tgt_vocab_size = len(self.vocab.tgt)
hypotheses = [[bos_id]]
completed_hypotheses = []
completed_hypothesis_scores = []
t = 0
while len(completed_hypotheses) < beam_size and t < args.decode_max_time_step:
t += 1
hyp_num = len(hypotheses)
expanded_src_encoding = src_encoding.expand(src_encoding.size(0), hyp_num, src_encoding.size(2))
expanded_src_encoding_att_linear = src_encoding_att_linear.expand(src_encoding_att_linear.size(0), hyp_num, src_encoding_att_linear.size(2))
y_tm1 = Variable(torch.LongTensor([hyp[-1] for hyp in hypotheses]), volatile=True)
if args.cuda:
y_tm1 = y_tm1.cuda()
y_tm1_embed = self.tgt_embed(y_tm1)
x = torch.cat([y_tm1_embed, att_tm1], 1)
# h_t: (hyp_num, hidden_size)
h_t, cell_t = self.decoder_lstm(x, hidden)
h_t = self.dropout(h_t)
ctx_t, alpha_t = self.dot_prod_attention(h_t, expanded_src_encoding.permute(1, 0, 2), expanded_src_encoding_att_linear.permute(1, 0, 2))
att_t = F.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1)))
att_t = self.dropout(att_t)
score_t = self.readout(att_t)
p_t = F.log_softmax(score_t)
live_hyp_num = beam_size - len(completed_hypotheses)
new_hyp_scores = (hyp_scores.unsqueeze(1).expand_as(p_t) + p_t).view(-1)
top_new_hyp_scores, top_new_hyp_pos = torch.topk(new_hyp_scores, k=live_hyp_num)
prev_hyp_ids = top_new_hyp_pos / tgt_vocab_size
word_ids = top_new_hyp_pos % tgt_vocab_size
# new_hyp_scores = new_hyp_scores[top_new_hyp_pos.data]
new_hypotheses = []
live_hyp_ids = []
new_hyp_scores = []
for prev_hyp_id, word_id, new_hyp_score in zip(prev_hyp_ids.cpu().data, word_ids.cpu().data, top_new_hyp_scores.cpu().data):
hyp_tgt_words = hypotheses[prev_hyp_id] + [word_id]
if word_id == eos_id:
completed_hypotheses.append(hyp_tgt_words)
completed_hypothesis_scores.append(new_hyp_score)
else:
new_hypotheses.append(hyp_tgt_words)
live_hyp_ids.append(prev_hyp_id)
new_hyp_scores.append(new_hyp_score)
if len(completed_hypotheses) == beam_size:
break
live_hyp_ids = torch.LongTensor(live_hyp_ids)
if args.cuda:
live_hyp_ids = live_hyp_ids.cuda()
hidden = (h_t[live_hyp_ids], cell_t[live_hyp_ids])
att_tm1 = att_t[live_hyp_ids]
hyp_scores = Variable(torch.FloatTensor(new_hyp_scores), volatile=True) # new_hyp_scores[live_hyp_ids]
if args.cuda:
hyp_scores = hyp_scores.cuda()
hypotheses = new_hypotheses
if len(completed_hypotheses) == 0:
completed_hypotheses = [hypotheses[0]]
completed_hypothesis_scores = [0.0]
if to_word:
for i, hyp in enumerate(completed_hypotheses):
completed_hypotheses[i] = [self.vocab.tgt.id2word[w] for w in hyp]
## add length penalty
pos_scores = (np.array(completed_hypothesis_scores))
#print (pos_scores)
lengths = [ len(i) for i in completed_hypotheses ]
lengths = np.array(lengths)
lengths = (5 + lengths)/(5 + 1)
#print (lengths)
pos_scores /= lengths
#print (pos_scores)
#print ('*' * 50)
completed_hypothesis_scores = pos_scores.tolist()
ranked_hypotheses = sorted(zip(completed_hypotheses, completed_hypothesis_scores), key=lambda x: x[1], reverse=True)
return [hyp for hyp, score in ranked_hypotheses]
def sample(self, src_sents, sample_size=None, to_word=False):
if not type(src_sents[0]) == list:
src_sents = [src_sents]
if not sample_size:
sample_size = args.sample_size
src_sents_num = len(src_sents)
batch_size = src_sents_num * sample_size
src_sents_var = to_input_variable(src_sents, self.vocab.src, cuda=args.cuda, is_test=True)
src_encoding, (dec_init_state, dec_init_cell) = self.encode(src_sents_var, [len(s) for s in src_sents])
dec_init_state = dec_init_state.repeat(sample_size, 1)
dec_init_cell = dec_init_cell.repeat(sample_size, 1)
hidden = (dec_init_state, dec_init_cell)
# tile everything
# if args.sample_method == 'expand':
# # src_enc: (src_sent_len, sample_size, enc_size)
# # cat result: (src_sent_len, batch_size * sample_size, enc_size)
# src_encoding = torch.cat([src_enc.expand(src_enc.size(0), sample_size, src_enc.size(2)) for src_enc in src_encoding.split(1, dim=1)], 1)
# dec_init_state = torch.cat([x.expand(sample_size, x.size(1)) for x in dec_init_state.split(1, dim=0)], 0)
# dec_init_cell = torch.cat([x.expand(sample_size, x.size(1)) for x in dec_init_cell.split(1, dim=0)], 0)
# elif args.sample_method == 'repeat':
src_encoding = src_encoding.repeat(1, sample_size, 1)
src_encoding_att_linear = tensor_transform(self.att_src_linear, src_encoding)
src_encoding = src_encoding.permute(1, 0, 2)
src_encoding_att_linear = src_encoding_att_linear.permute(1, 0, 2)
new_tensor = dec_init_state.data.new
att_tm1 = Variable(new_tensor(batch_size, self.args.hidden_size).zero_(), volatile=True)
y_0 = Variable(torch.LongTensor([self.vocab.tgt['<s>'] for _ in xrange(batch_size)]), volatile=True)
eos = self.vocab.tgt['</s>']
# eos_batch = torch.LongTensor([eos] * batch_size)
sample_ends = torch.ByteTensor([0] * batch_size)
all_ones = torch.ByteTensor([1] * batch_size)
if args.cuda:
y_0 = y_0.cuda()
sample_ends = sample_ends.cuda()
all_ones = all_ones.cuda()
samples = [y_0]
t = 0
while t < args.decode_max_time_step:
t += 1
# (sample_size)
y_tm1 = samples[-1]
y_tm1_embed = self.tgt_embed(y_tm1)
x = torch.cat([y_tm1_embed, att_tm1], 1)
# h_t: (batch_size, hidden_size)
h_t, cell_t = self.decoder_lstm(x, hidden)
h_t = self.dropout(h_t)
ctx_t, alpha_t = self.dot_prod_attention(h_t, src_encoding, src_encoding_att_linear)
att_t = F.tanh(self.att_vec_linear(torch.cat([h_t, ctx_t], 1))) # E.q. (5)
att_t = self.dropout(att_t)
score_t = self.readout(att_t) # E.q. (6)
p_t = F.softmax(score_t)
if args.sample_method == 'random':
y_t = torch.multinomial(p_t, num_samples=1).squeeze(1)
elif args.sample_method == 'greedy':
_, y_t = torch.topk(p_t, k=1, dim=1)
y_t = y_t.squeeze(1)
samples.append(y_t)
sample_ends |= torch.eq(y_t, eos).byte().data
if torch.equal(sample_ends, all_ones):
break
# if torch.equal(y_t.data, eos_batch):
# break
att_tm1 = att_t
hidden = h_t, cell_t
# post-processing
completed_samples = [list([list() for _ in xrange(sample_size)]) for _ in xrange(src_sents_num)]
for y_t in samples:
for i, sampled_word in enumerate(y_t.cpu().data):
src_sent_id = i % src_sents_num
sample_id = i / src_sents_num
if len(completed_samples[src_sent_id][sample_id]) == 0 or completed_samples[src_sent_id][sample_id][-1] != eos:
completed_samples[src_sent_id][sample_id].append(sampled_word)
if to_word:
for i, src_sent_samples in enumerate(completed_samples):
completed_samples[i] = word2id(src_sent_samples, self.vocab.tgt.id2word)
return completed_samples
def attention(self, h_t, src_encoding, src_linear_for_att):
# (1, batch_size, attention_size) + (src_sent_len, batch_size, attention_size) =>
# (src_sent_len, batch_size, attention_size)
att_hidden = F.tanh(self.att_h_linear(h_t).unsqueeze(0).expand_as(src_linear_for_att) + src_linear_for_att)
# (batch_size, src_sent_len)
att_weights = F.softmax(tensor_transform(self.att_vec_linear, att_hidden).squeeze(2).permute(1, 0))
# (batch_size, hidden_size * 2)
ctx_vec = torch.bmm(src_encoding.permute(1, 2, 0), att_weights.unsqueeze(2)).squeeze(2)
return ctx_vec, att_weights
def dot_prod_attention(self, h_t, src_encoding, src_encoding_att_linear, mask=None):
"""
:param h_t: (batch_size, hidden_size)
:param src_encoding: (batch_size, src_sent_len, hidden_size * 2)
:param src_encoding_att_linear: (batch_size, src_sent_len, hidden_size)
:param mask: (batch_size, src_sent_len)
"""
# (batch_size, src_sent_len)
att_weight = torch.bmm(src_encoding_att_linear, h_t.unsqueeze(2)).squeeze(2)
if mask:
att_weight.data.masked_fill_(mask, -float('inf'))
att_weight = F.softmax(att_weight)
att_view = (att_weight.size(0), 1, att_weight.size(1))
# (batch_size, hidden_size)
ctx_vec = torch.bmm(att_weight.view(*att_view), src_encoding).squeeze(1)
return ctx_vec, att_weight
def save(self, path):
print('save parameters to [%s]' % path, file=sys.stderr)
params = {
'args': self.args,
'vocab': self.vocab,
'state_dict': self.state_dict()
}
torch.save(params, path)
def to_input_variable(sents, vocab, cuda=False, is_test=False):
"""
return a tensor of shape (src_sent_len, batch_size)
"""
word_ids = word2id(sents, vocab)
sents_t, masks = input_transpose(word_ids, vocab['<pad>'])
sents_var = Variable(torch.LongTensor(sents_t), volatile=is_test, requires_grad=False)
if cuda:
sents_var = sents_var.cuda()
return sents_var
def evaluate_loss(model, data, crit):
model.eval()
cum_loss = 0.
cum_tgt_words = 0.
for src_sents, tgt_sents in data_iter(data, batch_size=args.batch_size, shuffle=False):
pred_tgt_word_num = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`
src_sents_len = [len(s) for s in src_sents]
src_sents_var = to_input_variable(src_sents, model.vocab.src, cuda=args.cuda, is_test=True)
tgt_sents_var = to_input_variable(tgt_sents, model.vocab.tgt, cuda=args.cuda, is_test=True)
# (tgt_sent_len, batch_size, tgt_vocab_size)
scores = model(src_sents_var, src_sents_len, tgt_sents_var[:-1])
loss = crit(scores.view(-1, scores.size(2)), tgt_sents_var[1:].view(-1))
cum_loss += loss.data[0]
cum_tgt_words += pred_tgt_word_num
loss = cum_loss / cum_tgt_words
return loss
def init_training(args):
vocab = torch.load(args.vocab)
model = NMT(args, vocab)
model.train()
if args.uniform_init:
print('uniformly initialize parameters [-%f, +%f]' % (args.uniform_init, args.uniform_init), file=sys.stderr)
for p in model.parameters():
p.data.uniform_(-args.uniform_init, args.uniform_init)
vocab_mask = torch.ones(len(vocab.tgt))
vocab_mask[vocab.tgt['<pad>']] = 0
nll_loss = nn.NLLLoss(weight=vocab_mask, size_average=False)
cross_entropy_loss = nn.CrossEntropyLoss(weight=vocab_mask, size_average=False)
if args.cuda:
model = model.cuda()
nll_loss = nll_loss.cuda()
cross_entropy_loss = cross_entropy_loss.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
return vocab, model, optimizer, nll_loss, cross_entropy_loss
def train(args):
train_data_src = read_corpus(args.train_src, source='src')
train_data_tgt = read_corpus(args.train_tgt, source='tgt')
dev_data_src = read_corpus(args.dev_src, source='src')
dev_data_tgt = read_corpus(args.dev_tgt, source='tgt')
train_data = zip(train_data_src, train_data_tgt)
dev_data = zip(dev_data_src, dev_data_tgt)
vocab, model, optimizer, nll_loss, cross_entropy_loss = init_training(args)
train_iter = patience = cum_loss = report_loss = cum_tgt_words = report_tgt_words = 0
cum_examples = cum_batches = report_examples = epoch = valid_num = best_model_iter = 0
hist_valid_scores = []
train_time = begin_time = time.time()
print('begin Maximum Likelihood training')
while True:
epoch += 1
for src_sents, tgt_sents in data_iter(train_data, batch_size=args.batch_size):
train_iter += 1
src_sents_var = to_input_variable(src_sents, vocab.src, cuda=args.cuda)
tgt_sents_var = to_input_variable(tgt_sents, vocab.tgt, cuda=args.cuda)
batch_size = len(src_sents)
src_sents_len = [len(s) for s in src_sents]
pred_tgt_word_num = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`
optimizer.zero_grad()
# (tgt_sent_len, batch_size, tgt_vocab_size)
scores = model(src_sents_var, src_sents_len, tgt_sents_var[:-1])
word_loss = cross_entropy_loss(scores.view(-1, scores.size(2)), tgt_sents_var[1:].view(-1))
loss = word_loss / batch_size
word_loss_val = word_loss.data[0]
loss_val = loss.data[0]
loss.backward()
# clip gradient
grad_norm = torch.nn.utils.clip_grad_norm(model.parameters(), args.clip_grad)
optimizer.step()
report_loss += word_loss_val
cum_loss += word_loss_val
report_tgt_words += pred_tgt_word_num
cum_tgt_words += pred_tgt_word_num
report_examples += batch_size
cum_examples += batch_size
cum_batches += batch_size
if train_iter % args.log_every == 0:
print('epoch %d, iter %d, avg. loss %.2f, avg. ppl %.2f ' \
'cum. examples %d, speed %.2f words/sec, time elapsed %.2f sec' % (epoch, train_iter,
report_loss / report_examples,
np.exp(report_loss / report_tgt_words),
cum_examples,
report_tgt_words / (time.time() - train_time),
time.time() - begin_time), file=sys.stderr)
train_time = time.time()
report_loss = report_tgt_words = report_examples = 0.
# perform validation
if train_iter % args.valid_niter == 0:
print('epoch %d, iter %d, cum. loss %.2f, cum. ppl %.2f cum. examples %d' % (epoch, train_iter,
cum_loss / cum_batches,
np.exp(cum_loss / cum_tgt_words),
cum_examples), file=sys.stderr)
cum_loss = cum_batches = cum_tgt_words = 0.
valid_num += 1
print('begin validation ...', file=sys.stderr)
model.eval()
# compute dev. ppl and bleu
dev_loss = evaluate_loss(model, dev_data, cross_entropy_loss)
dev_ppl = np.exp(dev_loss)
if args.valid_metric in ['bleu', 'word_acc', 'sent_acc']:
dev_hyps = decode(model, dev_data)
dev_hyps = [hyps[0] for hyps in dev_hyps]
if args.valid_metric == 'bleu':
valid_metric = get_bleu([tgt for src, tgt in dev_data], dev_hyps)
else:
valid_metric = get_acc([tgt for src, tgt in dev_data], dev_hyps, acc_type=args.valid_metric)
print('validation: iter %d, dev. ppl %f, dev. %s %f' % (train_iter, dev_ppl, args.valid_metric, valid_metric),
file=sys.stderr)
else:
valid_metric = -dev_ppl
print('validation: iter %d, dev. ppl %f' % (train_iter, dev_ppl),
file=sys.stderr)
model.train()
is_better = len(hist_valid_scores) == 0 or valid_metric > max(hist_valid_scores)
is_better_than_last = len(hist_valid_scores) == 0 or valid_metric > hist_valid_scores[-1]
hist_valid_scores.append(valid_metric)
if valid_num > args.save_model_after:
model_file = args.save_to + '.iter%d.bin' % train_iter
print('save model to [%s]' % model_file, file=sys.stderr)
model.save(model_file)
if (not is_better_than_last) and args.lr_decay:
lr = optimizer.param_groups[0]['lr'] * args.lr_decay
print('decay learning rate to %f' % lr, file=sys.stderr)
optimizer.param_groups[0]['lr'] = lr
if is_better:
patience = 0
best_model_iter = train_iter
if valid_num > args.save_model_after:
print('save currently the best model ..', file=sys.stderr)
model_file_abs_path = os.path.abspath(model_file)
symlin_file_abs_path = os.path.abspath(args.save_to + '.bin')
os.system('ln -sf %s %s' % (model_file_abs_path, symlin_file_abs_path))
else:
patience += 1
print('hit patience %d' % patience, file=sys.stderr)
if patience == args.patience:
print('early stop!', file=sys.stderr)
print('the best model is from iteration [%d]' % best_model_iter, file=sys.stderr)
exit(0)
def my_lcs(string, sub):
"""
Calculates longest common subsequence for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the longest common subsequence between the two strings
Note: my_lcs only gives length of the longest common subsequence, not the actual LCS
"""
if(len(string)< len(sub)):
sub, string = string, sub
lengths = [[0 for i in range(0,len(sub)+1)] for j in range(0,len(string)+1)]
for j in range(1,len(sub)+1):
for i in range(1,len(string)+1):
if(string[i-1] == sub[j-1]):
lengths[i][j] = lengths[i-1][j-1] + 1
else:
lengths[i][j] = max(lengths[i-1][j] , lengths[i][j-1])
return lengths[len(string)][len(sub)]
def calc_Rouge_L(candidate, refs):
"""
Compute ROUGE-L score given one candidate and references for an image
:param candidate: str : candidate sentence to be evaluated
:param refs: list of str : COCO reference sentences for the particular image to be evaluated
:returns score: int (ROUGE-L score for the candidate evaluated against references)
"""
beta = 1.
assert(len(candidate)==1)
assert(len(refs)>0)
prec = []
rec = []
# split into tokens
token_c = candidate[0]#.split(" ")
for reference in refs:
# split into tokens
token_r = reference#.split(" ")
# compute the longest common subsequence
lcs = my_lcs(token_r, token_c)
prec.append(lcs/float(len(token_c)))
rec.append(lcs/float(len(token_r)))
prec_max = max(prec)
rec_max = max(rec)
if(prec_max!=0 and rec_max !=0):
score = ((1 + beta**2)*prec_max*rec_max)/float(rec_max + beta**2*prec_max)
else:
score = 0.0
return [prec_max,rec_max,score]
def RL_train(args):
#vocab = torch.load(args.vocab)
if args.load_model:
print ('load seq2seq model from %s' % args.load_model, file = sys.stderr )
params = torch.load(args.load_model, map_location = lambda storage, loc:storage)
vocab = params['vocab']
#params = torch.load(args.load_model, map_location=lambda storage, loc: storage)
nmt_args = params['args']
state_dict = params['state_dict']
model = NMT(nmt_args, vocab)
model.load_state_dict(state_dict)
vocab_mask = torch.ones(len(vocab.tgt))
vocab_mask[vocab.tgt['<pad>']] = 0
cross_entropy_loss = nn.CrossEntropyLoss(weight = vocab_mask, size_average=False, reduce = False)
if args.cuda:
model = model.cuda()
cross_entropy_loss = cross_entropy_loss.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr = args.lr)
model.train()
# read corpus
train_data_src = read_corpus(nmt_args.train_src, source = 'src')
train_data_tgt = read_corpus(nmt_args.train_tgt, source = 'tgt')
train_data = zip(train_data_src, train_data_tgt)
dev_data_src = read_corpus(nmt_args.dev_src, source = 'src')
dev_data_tgt = read_corpus(nmt_args.dev_tgt, source = 'tgt')
dev_data = zip(dev_data_src, dev_data_tgt)
train_iter = patience = cum_loss = report_loss = cum_tgt_words = report_tgt_words = 0
cum_examples = cum_batches = report_examples = epoch = valid_num = best_model_iter = 0
hist_valid_scores = []
train_time = begin_time = time.time()
report_sample_re = report_base_re = 0
print('begin RL training ...', file = sys.stderr)
while True:
epoch += 1
for src_sents, tgt_sents in data_iter(train_data, batch_size = args.batch_size):
train_iter += 1
batch_size = len(src_sents)
src_sents_var = to_input_variable(src_sents, vocab.src, cuda = args.cuda)
tgt_sents_var = to_input_variable(tgt_sents, vocab.tgt, cuda = args.cuda)
src_sents_len = [len(s) for s in src_sents]
tgt_sents_len = [len(s[1:]) for s in tgt_sents]
pred_tgt_word_num = sum(tgt_sents_len) #sum(len(s[1:]) for s in tgt_sents)
optimizer.zero_grad()
#111
# scores: len, batch, dict_size
# sample_y, base_y: len, batch
scores, sample_y, base_y = model(src_sents_var, src_sents_len, tgt_sents_var[:-1])
sample_y = torch.squeeze(sample_y, 2)
base_y = torch.squeeze(base_y, 2)
### get reward ## R_L ##
# for sample_y
#print (sample_y.size())
#print (base_y.size())
#print (scores.size())
'''
#print (lensample_y.transpose(0, 1).data.tolist(())
print (len(sample_y.transpose(0, 1).data.tolist()))
print (sample_y.transpose(0, 1).data.tolist()[0])
print ('-----')
print (len(tgt_sents_var.transpose(0, 1).data.tolist()))
print (tgt_sents_var.transpose(0, 1).data.tolist()[0])
print (len(tgt_sents_len))
print ('******')
print (zip(sample_y.transpose(0, 1).data.tolist(), tgt_sents_var.transpose(0, 1).data.tolist(), tgt_sents_len))
'''
reward_RL_sample = [ calc_Rouge_L([hyp[:rlen]], [ref[:rlen]])[2] for hyp, ref, rlen in zip(sample_y.transpose(0, 1).data.tolist(), tgt_sents_var.transpose(0, 1).data.tolist(), tgt_sents_len) ]
reward_RL_base = [ calc_Rouge_L([hyp[:rlen]], [ref[:rlen]])[2] for hyp, ref, rlen in zip(base_y.transpose(0, 1).data.tolist(), tgt_sents_var.transpose(0, 1).data.tolist(), tgt_sents_len ) ]
reward_RL_sample = Variable(torch.FloatTensor(reward_RL_sample), requires_grad = False).view(1, batch_size, 1)
reward_RL_base = Variable(torch.FloatTensor(reward_RL_base), requires_grad = False).view(1, batch_size, 1)
#print (reward_RL_sample.data)
#print (reward_RL_base.data)
#print ('----------')
if args.cuda:
reward_RL_sample = reward_RL_sample.cuda()
reward_RL_base = reward_RL_base.cuda()
word_loss = cross_entropy_loss( scores.view(-1, scores.size(2)), sample_y.view(-1) ).view(scores.size(0), scores.size(1),1)
word_loss = -word_loss * (reward_RL_base - reward_RL_sample) # + word_loss
#print (word_loss.size())
word_loss = torch.sum(word_loss)
loss = word_loss / batch_size #scores.view(-1, scores.size(2)).size(0)
word_loss_val = word_loss.data[0]
loss_val = loss.data[0]
sample_re = torch.sum(reward_RL_sample)
base_re = torch.sum(reward_RL_base)
loss.backward()
#TC_loss.backward()
# clip gradient
grad_norm = torch.nn.utils.clip_grad_norm(model.parameters(), nmt_args.clip_grad)
optimizer.step()
#optimizer_TC.step()
#TC_cum_loss += TC_loss_var
report_loss += word_loss_val
cum_loss += word_loss_val
report_sample_re += sample_re.data[0]
report_base_re += base_re.data[0]
report_tgt_words += pred_tgt_word_num
cum_tgt_words += pred_tgt_word_num
report_examples += batch_size
cum_examples += batch_size
cum_batches += batch_size
if train_iter % nmt_args.log_every == 0:
print('epoch %d, iter %d, avg. loss %.2f, avg. ppl %.2f, sample_re %.4f, base_re %.4f, ' \
'cum. examples %d, speed %.2f words/sec, time elapsed %.2f sec' % (epoch, train_iter,
report_loss / report_examples,
np.exp(
report_loss / report_tgt_words),
report_sample_re / report_examples,
report_base_re / report_examples,
cum_examples,
report_tgt_words / (
time.time() - train_time),
time.time() - begin_time),
file=sys.stderr)
train_time = time.time()
#TC_cum_loss =
report_loss = report_tgt_words = report_examples = report_sample_re = report_base_re = 0.
# perform validation
if train_iter % nmt_args.valid_niter == 0:
print('epoch %d, iter %d, cum. loss %.2f, cum. ppl %.2f cum. examples %d' % (epoch, train_iter,
cum_loss / cum_batches,
np.exp(
cum_loss / cum_tgt_words),
cum_examples),
file=sys.stderr)
cum_loss = cum_batches = cum_tgt_words = 0.
valid_num += 1
print('save current model ..', file=sys.stderr)
model_file = args.save_to + '.iter%d.bin' % train_iter
print('save RL model to [%s]' % model_file, file=sys.stderr)