-
Notifications
You must be signed in to change notification settings - Fork 0
/
nmt.py
executable file
·2689 lines (2245 loc) · 130 KB
/
nmt.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Build a neural machine translation model with soft attention
'''
import theano
import theano.tensor as tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import json
import numpy
import copy
import argparse
import os
import sys
import time
import logging
import itertools
from subprocess import Popen
from collections import OrderedDict
profile = False
from data_iterator import TextIterator
from training_progress import TrainingProgress
from util import *
from theano_util import *
from alignment_util import *
from raml_distributions import *
from layers import *
from initializers import *
from optimizers import *
from metrics.scorer_provider import ScorerProvider
from domain_interpolation_data_iterator import DomainInterpolatorTextIterator
from pseudo_source_data_iterator import PseudoSourceTextIterator
# batch preparation
def prepare_data(seqs_x, seqs_y, weights=None, maxlen=None, n_words_src=30000,
n_words=30000, n_factors=1):
# x: a list of sentences
lengths_x = [len(s) for s in seqs_x]
lengths_y = [len(s) for s in seqs_y]
if maxlen is not None:
new_seqs_x = []
new_seqs_y = []
new_lengths_x = []
new_lengths_y = []
new_weights = []
if weights is None:
weights = [None] * len(seqs_y) # to make the zip easier
for l_x, s_x, l_y, s_y, w in zip(lengths_x, seqs_x, lengths_y, seqs_y, weights):
if l_x < maxlen and l_y < maxlen:
new_seqs_x.append(s_x)
new_lengths_x.append(l_x)
new_seqs_y.append(s_y)
new_lengths_y.append(l_y)
new_weights.append(w)
lengths_x = new_lengths_x
seqs_x = new_seqs_x
lengths_y = new_lengths_y
seqs_y = new_seqs_y
weights = new_weights
if len(lengths_x) < 1 or len(lengths_y) < 1:
if weights is not None:
return None, None, None, None, None
else:
return None, None, None, None
n_samples = len(seqs_x)
maxlen_x = numpy.max(lengths_x) + 1
maxlen_y = numpy.max(lengths_y) + 1
x = numpy.zeros((n_factors, maxlen_x, n_samples)).astype('int64')
y = numpy.zeros((maxlen_y, n_samples)).astype('int64')
x_mask = numpy.zeros((maxlen_x, n_samples)).astype(floatX)
y_mask = numpy.zeros((maxlen_y, n_samples)).astype(floatX)
for idx, [s_x, s_y] in enumerate(zip(seqs_x, seqs_y)):
x[:, :lengths_x[idx], idx] = zip(*s_x)
x_mask[:lengths_x[idx]+1, idx] = 1.
y[:lengths_y[idx], idx] = s_y
y_mask[:lengths_y[idx]+1, idx] = 1.
if weights is not None:
return x, x_mask, y, y_mask, weights
else:
return x, x_mask, y, y_mask
# initialize all parameters
def init_params(options):
params = OrderedDict()
# embedding
params = get_layer_param('embedding')(options, params, options['n_words_src'], options['dim_per_factor'], options['factors'], suffix='')
if not options['tie_encoder_decoder_embeddings']:
params = get_layer_param('embedding')(options, params, options['n_words'], options['dim_word'], suffix='_dec')
# encoder: bidirectional RNN
params = get_layer_param(options['encoder'])(options, params,
prefix='encoder',
nin=options['dim_word'],
dim=options['dim'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'])
params = get_layer_param(options['encoder'])(options, params,
prefix='encoder_r',
nin=options['dim_word'],
dim=options['dim'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'])
if options['enc_depth'] > 1:
for level in range(2, options['enc_depth'] + 1):
prefix_f = pp('encoder', level)
prefix_r = pp('encoder_r', level)
if level <= options['enc_depth_bidirectional']:
params = get_layer_param(options['encoder'])(options, params,
prefix=prefix_f,
nin=options['dim'],
dim=options['dim'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'])
params = get_layer_param(options['encoder'])(options, params,
prefix=prefix_r,
nin=options['dim'],
dim=options['dim'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'])
else:
params = get_layer_param(options['encoder'])(options, params,
prefix=prefix_f,
nin=options['dim'] * 2,
dim=options['dim'] * 2,
recurrence_transition_depth=options['enc_recurrence_transition_depth'])
ctxdim = 2 * options['dim']
dec_state = options['dim']
if options['decoder'].startswith('lstm'):
dec_state *= 2
# init_state, init_cell
params = get_layer_param('ff')(options, params, prefix='ff_state',
nin=ctxdim, nout=dec_state)
# decoder
params = get_layer_param(options['decoder'])(options, params,
prefix='decoder',
nin=options['dim_word'],
dim=options['dim'],
dimctx=ctxdim,
recurrence_transition_depth=options['dec_base_recurrence_transition_depth'])
# deeper layers of the decoder
if options['dec_depth'] > 1:
if options['dec_deep_context']:
input_dim = options['dim'] + ctxdim
else:
input_dim = options['dim']
for level in range(2, options['dec_depth'] + 1):
params = get_layer_param(options['decoder_deep'])(options, params,
prefix=pp('decoder', level),
nin=input_dim,
dim=options['dim'],
dimctx=ctxdim,
recurrence_transition_depth=options['dec_high_recurrence_transition_depth'])
# readout
if options['deep_fusion_lm'] and options['concatenate_lm_decoder']:
params = get_layer_param('ff')(options, params, prefix='ff_logit_lstm',
nin=(options['dim']+options['lm_dim']), nout=options['dim_word'],
ortho=False)
else:
params = get_layer_param('ff')(options, params, prefix='ff_logit_lstm',
nin=options['dim'], nout=options['dim_word'],
ortho=False)
params = get_layer_param('ff')(options, params, prefix='ff_logit_prev',
nin=options['dim_word'],
nout=options['dim_word'], ortho=False)
params = get_layer_param('ff')(options, params, prefix='ff_logit_ctx',
nin=ctxdim, nout=options['dim_word'],
ortho=False)
params = get_layer_param('ff')(options, params, prefix='ff_logit',
nin=options['dim_word'],
nout=options['n_words'],
weight_matrix = not options['tie_decoder_embeddings'],
followed_by_softmax=True)
return params
# initialize LM parameters (deep fusion)
def init_params_lm(options, params):
# LM controller mechanism
prefix = 'fusion_lm'
v_g = norm_weight(options['lm_dim'], 1)
params[pp(prefix, 'v_g')] = v_g
# bias initialization
b_g = -1 * numpy.ones((1,)).astype(floatX)
#b_g = numpy.zeros((1,)).astype(floatX)
params[pp(prefix, 'b_g')] = b_g
# readout for LM
if not options['concatenate_lm_decoder']:
params = get_layer_param('ff')(options, params, prefix='ff_logit_lm',
nin=options['lm_dim'],
nout=options['dim_word'], ortho=False)
return params
def init_params_discriminator(options, params):
ctxdim = 2 * options['dim']
# discriminator: bidirectional RNN
params = get_layer_param('gru')(options, params,
prefix='discriminator',
nin=ctxdim,
dim=options['dim'])
params = get_layer_param('gru')(options, params,
prefix='discriminator_r',
nin=ctxdim,
dim=options['dim'])
params = get_layer_param('ff')(options, params, prefix='discriminator_output',
nin=ctxdim, nout=1,
ortho=False)
return params
def build_encoder(tparams, options, dropout, x_mask=None, sampling=False):
x = tensor.tensor3('x', dtype='int64')
# source text; factors 1; length 5; batch size 10
x.tag.test_value = (numpy.random.rand(1, 5, 10)*100).astype('int64')
# for the backward rnn, we just need to invert x
xr = x[:,::-1]
if x_mask is None:
xr_mask = None
else:
xr_mask = x_mask[::-1]
n_timesteps = x.shape[1]
n_samples = x.shape[2]
# word embedding for forward rnn (source)
emb = get_layer_constr('embedding')(tparams, x, suffix='', factors= options['factors'])
# word embedding for backward rnn (source)
embr = get_layer_constr('embedding')(tparams, xr, suffix='', factors= options['factors'])
if options['use_dropout']:
source_dropout = dropout((n_timesteps, n_samples, 1), options['dropout_source'])
if not sampling:
source_dropout = tensor.tile(source_dropout, (1,1,options['dim_word']))
emb *= source_dropout
if sampling:
embr *= source_dropout
else:
# we drop out the same words in both directions
embr *= source_dropout[::-1]
## level 1
proj = get_layer_constr(options['encoder'])(tparams, emb, options, dropout,
prefix='encoder',
mask=x_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, embr, options, dropout,
prefix='encoder_r',
mask=xr_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
## bidirectional levels before merge
for level in range(2, options['enc_depth_bidirectional'] + 1):
prefix_f = pp('encoder', level)
prefix_r = pp('encoder_r', level)
# run forward on previous backward and backward on previous forward
input_f = projr[0][::-1]
input_r = proj[0][::-1]
proj = get_layer_constr(options['encoder'])(tparams, input_f, options, dropout,
prefix=prefix_f,
mask=x_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, input_r, options, dropout,
prefix=prefix_r,
mask=xr_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
# residual connections
if level > 1:
proj[0] += input_f
projr[0] += input_r
# context will be the concatenation of forward and backward rnns
ctx = concatenate([proj[0], projr[0][::-1]], axis=proj[0].ndim-1)
## forward encoder layers after bidirectional layers are concatenated
for level in range(options['enc_depth_bidirectional'] + 1, options['enc_depth'] + 1):
ctx += get_layer_constr(options['encoder'])(tparams, ctx, options, dropout,
prefix=pp('encoder', level),
mask=x_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)[0]
return x, ctx
# bidirectional RNN encoder: take input x (optionally with mask), and produce sequence of context vectors (ctx)
def build_encoder_true(tparams, options, dropout, x, x_mask=None, sampling=False):
# source text; factors 1; length 5; batch size 10
#x.tag.test_value = (numpy.random.rand(1, 5, 10)*100).astype('int64')
# for the backward rnn, we just need to invert x
xr = x[:,::-1]
if x_mask is None:
xr_mask = None
else:
xr_mask = x_mask[::-1]
n_timesteps = x.shape[1]
n_samples = x.shape[2]
# word embedding for forward rnn (source)
emb = get_layer_constr('embedding')(tparams, x, suffix='', factors= options['factors'])
# word embedding for backward rnn (source)
embr = get_layer_constr('embedding')(tparams, xr, suffix='', factors= options['factors'])
if options['use_dropout']:
source_dropout = dropout((n_timesteps, n_samples, 1), options['dropout_source'])
if not sampling:
source_dropout = tensor.tile(source_dropout, (1,1,options['dim_word']))
emb *= source_dropout
if sampling:
embr *= source_dropout
else:
# we drop out the same words in both directions
embr *= source_dropout[::-1]
## level 1
proj = get_layer_constr(options['encoder'])(tparams, emb, options, dropout,
prefix='encoder',
mask=x_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, embr, options, dropout,
prefix='encoder_r',
mask=xr_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
## bidirectional levels before merge
for level in range(2, options['enc_depth_bidirectional'] + 1):
prefix_f = pp('encoder', level)
prefix_r = pp('encoder_r', level)
# run forward on previous backward and backward on previous forward
input_f = projr[0][::-1]
input_r = proj[0][::-1]
proj = get_layer_constr(options['encoder'])(tparams, input_f, options, dropout,
prefix=prefix_f,
mask=x_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, input_r, options, dropout,
prefix=prefix_r,
mask=xr_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
# residual connections
if level > 1:
proj[0] += input_f
projr[0] += input_r
# context will be the concatenation of forward and backward rnns
ctx = concatenate([proj[0], projr[0][::-1]], axis=proj[0].ndim-1)
## forward encoder layers after bidirectional layers are concatenated
for level in range(options['enc_depth_bidirectional'] + 1, options['enc_depth'] + 1):
ctx += get_layer_constr(options['encoder'])(tparams, ctx, options, dropout,
prefix=pp('encoder', level),
mask=x_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)[0]
return ctx
# bidirectional RNN encoder: take input x (optionally with mask), and produce sequence of context vectors (ctx)
def build_encoder_pseudo(tparams, options, dropout, x, x_mask=None, sampling=False):
#x = tensor.tensor3('x', dtype='int64')
# source text; factors 1; length 5; batch size 10
#x.tag.test_value = (numpy.random.rand(1, 5, 10)*100).astype('int64')
# for the backward rnn, we just need to invert x
xr = x[:,::-1]
if x_mask is None:
xr_mask = None
else:
xr_mask = x_mask[::-1]
n_timesteps = x.shape[1]
n_samples = x.shape[2]
# word embedding for forward rnn (source)
emb = get_layer_constr('embedding')(tparams, x, prefix='pseudo_', factors= options['factors'])
# word embedding for backward rnn (source)
embr = get_layer_constr('embedding')(tparams, xr, prefix='pseudo_', factors= options['factors'])
if options['use_dropout']:
source_dropout = dropout((n_timesteps, n_samples, 1), options['dropout_source'])
if not sampling:
source_dropout = tensor.tile(source_dropout, (1,1,options['dim_word']))
emb *= source_dropout
if sampling:
embr *= source_dropout
else:
# we drop out the same words in both directions
embr *= source_dropout[::-1]
## level 1
proj = get_layer_constr(options['encoder'])(tparams, emb, options, dropout,
prefix='pseudo_encoder',
mask=x_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_generator'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, embr, options, dropout,
prefix='pseudo_encoder_r',
mask=xr_mask,
dropout_probability_below=options['dropout_embedding'],
dropout_probability_rec=options['dropout_generator'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
## bidirectional levels before merge
for level in range(2, options['enc_depth_bidirectional'] + 1):
prefix_f = pp('pseudo_encoder', level)
prefix_r = pp('pseudo_encoder_r', level)
# run forward on previous backward and backward on previous forward
input_f = projr[0][::-1]
input_r = proj[0][::-1]
proj = get_layer_constr(options['encoder'])(tparams, input_f, options, dropout,
prefix=prefix_f,
mask=x_mask,
dropout_probability_below=options['dropout_generator'],
dropout_probability_rec=options['dropout_generator'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, input_r, options, dropout,
prefix=prefix_r,
mask=xr_mask,
dropout_probability_below=options['dropout_generator'],
dropout_probability_rec=options['dropout_generator'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# discard LSTM cell state
if options['encoder'].startswith('lstm'):
proj[0] = get_slice(proj[0], 0, options['dim'])
projr[0] = get_slice(projr[0], 0, options['dim'])
# residual connections
if level > 1:
proj[0] += input_f
projr[0] += input_r
# context will be the concatenation of forward and backward rnns
ctx = concatenate([proj[0], projr[0][::-1]], axis=proj[0].ndim-1)
## forward encoder layers after bidirectional layers are concatenated
for level in range(options['enc_depth_bidirectional'] + 1, options['enc_depth'] + 1):
ctx += get_layer_constr(options['encoder'])(tparams, ctx, options, dropout,
prefix=pp('pseudo_encoder', level),
mask=x_mask,
dropout_probability_below=options['dropout_generator'],
dropout_probability_rec=options['dropout_generator'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)[0]
return ctx
def build_discriminator(tparams, options, ctx_disc, x_disc_mask, begin_pseudo, trng, use_noise):
# input, mask and labels
#d_labels = tensor.vector('d_labels', dtype=floatX)
#begin_pseudo = tensor.scalar('begin_pseudo', dtype='int64')
# for the backward rnn, we just need to invert ctx
ctx_discr = ctx_disc[:,::-1]
if x_disc_mask is None:
xr_disc_mask = None
else:
xr_disc_mask = x_disc_mask[::-1]
n_timesteps = ctx_disc.shape[1]
n_samples = ctx_disc.shape[2]
#d_dropout = dropout_constr(options={'use_dropout':False}, use_noise=False, trng=None, sampling=False)
d_dropout = dropout_constr(options, use_noise, trng, sampling=False)
proj = get_layer_constr(options['encoder'])(tparams, ctx_disc, options, d_dropout,
prefix='discriminator',
mask=x_disc_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
projr = get_layer_constr(options['encoder'])(tparams, ctx_discr, options, d_dropout,
prefix='discriminator_r',
mask=xr_disc_mask,
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['enc_recurrence_transition_depth'],
truncate_gradient=options['encoder_truncate_gradient'],
profile=profile)
# context will be the concatenation of forward and backward rnns
ctx_encoded = concatenate([proj[0], projr[0][::-1]], axis=proj[0].ndim-1)
# take mean over each position in the sentence
ctx_mean = (ctx_encoded * x_disc_mask[:, :, None]).sum(0) / x_disc_mask.sum(0)[:, None]
output = get_layer_constr('ff')(tparams, ctx_mean, options, d_dropout,
prefix='discriminator_output', activ='linear')
output = tensor.clip(output, -20.0, 20.0)
d_prob = tensor.nnet.sigmoid(output)
d_labels = tensor.concatenate([tensor.ones_like(d_prob[:begin_pseudo]), tensor.zeros_like(d_prob[begin_pseudo:])])
d_cost = tensor.nnet.binary_crossentropy(d_prob, d_labels).mean()
g_prob = d_prob[begin_pseudo:]
g_labels = tensor.ones_like(g_prob)
g_cost = tensor.nnet.binary_crossentropy(g_prob, g_labels).mean()
d_acc = tensor.concatenate([d_prob[:begin_pseudo], 1. - g_prob]).mean()
g_acc = d_prob[begin_pseudo:].mean()
return d_acc, g_acc, d_cost, g_cost
# RNN decoder (including embedding and feedforward layer before output)
def build_decoder(tparams, options, y, ctx, init_state, dropout, x_mask=None, y_mask=None, sampling=False, pctx_=None, shared_vars=None, lm_init_state=None):
opt_ret = dict()
# tell RNN whether to advance just one step at a time (for sampling),
# or loop through sequence (for training)
if sampling:
one_step=True
else:
one_step=False
if options['use_dropout']:
if sampling:
target_dropout = dropout(dropout_probability=options['dropout_target'])
else:
n_timesteps_trg = y.shape[0]
n_samples = y.shape[1]
target_dropout = dropout((n_timesteps_trg, n_samples, 1), options['dropout_target'])
target_dropout = tensor.tile(target_dropout, (1, 1, options['dim_word']))
# word embedding (target), we will shift the target sequence one time step
# to the right. This is done because of the bi-gram connections in the
# readout and decoder rnn. The first target will be all zeros and we will
# not condition on the last output.
decoder_embedding_suffix = '' if options['tie_encoder_decoder_embeddings'] else '_dec'
emb = get_layer_constr('embedding')(tparams, y, suffix=decoder_embedding_suffix)
if options['use_dropout']:
emb *= target_dropout
if sampling:
emb = tensor.switch(y[:, None] < 0,
tensor.zeros((1, options['dim_word'])),
emb)
else:
emb_shifted = tensor.zeros_like(emb)
emb_shifted = tensor.set_subtensor(emb_shifted[1:], emb[:-1])
emb = emb_shifted
# decoder - pass through the decoder conditional gru with attention
proj = get_layer_constr(options['decoder'])(tparams, emb, options, dropout,
prefix='decoder',
mask=y_mask, context=ctx,
context_mask=x_mask,
pctx_=pctx_,
one_step=one_step,
init_state=init_state[0],
recurrence_transition_depth=options['dec_base_recurrence_transition_depth'],
dropout_probability_below=options['dropout_embedding'],
dropout_probability_ctx=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
truncate_gradient=options['decoder_truncate_gradient'],
profile=profile)
# hidden states of the decoder gru
next_state = proj[0]
# weighted averages of context, generated by attention module
ctxs = proj[1]
# weights (alignment matrix)
opt_ret['dec_alphas'] = proj[2]
# we return state of each layer
if sampling:
ret_state = [next_state.reshape((1, next_state.shape[0], next_state.shape[1]))]
else:
ret_state = None
if options['dec_depth'] > 1:
for level in range(2, options['dec_depth'] + 1):
# don't pass LSTM cell state to next layer
if options['decoder'].startswith('lstm'):
next_state = get_slice(next_state, 0, options['dim'])
if options['dec_deep_context']:
if sampling:
axis=1
else:
axis=2
input_ = tensor.concatenate([next_state, ctxs], axis=axis)
else:
input_ = next_state
out_state = get_layer_constr(options['decoder_deep'])(tparams, input_, options, dropout,
prefix=pp('decoder', level),
mask=y_mask,
context=ctx,
context_mask=x_mask,
pctx_=None, #TODO: we can speed up sampler by precomputing this
one_step=one_step,
init_state=init_state[level-1],
dropout_probability_below=options['dropout_hidden'],
dropout_probability_rec=options['dropout_hidden'],
recurrence_transition_depth=options['dec_high_recurrence_transition_depth'],
truncate_gradient=options['decoder_truncate_gradient'],
profile=profile)[0]
if sampling:
ret_state.append(out_state.reshape((1, proj[0].shape[0], proj[0].shape[1])))
# don't pass LSTM cell state to next layer
if options['decoder'].startswith('lstm'):
out_state = get_slice(out_state, 0, options['dim'])
# residual connection
next_state += out_state
# don't pass LSTM cell state to next layer
elif options['decoder'].startswith('lstm'):
next_state = get_slice(next_state, 0, options['dim'])
if sampling:
if options['dec_depth'] > 1:
ret_state = tensor.concatenate(ret_state, axis=0)
else:
ret_state = ret_state[0]
# language model encoder (deep fusion)
lm_ret_state = None
if options['deep_fusion_lm']:
lm_emb = get_layer_constr('embedding')(tparams, y, prefix='lm_')
if sampling:
lm_emb = tensor.switch(y[:, None] < 0,
tensor.zeros((1, options['dim_word'])),
lm_emb)
if not lm_init_state:
lm_init_state = tensor.zeros((1, options['lm_dim']))
else:
lm_emb_shifted = tensor.zeros_like(lm_emb)
lm_emb_shifted = tensor.set_subtensor(lm_emb_shifted[1:], lm_emb[:-1])
lm_emb = lm_emb_shifted
lm_dropout = dropout_constr(options={'use_dropout':False}, use_noise=False, trng=None, sampling=False)
lm_proj = get_layer_constr(options['lm_encoder'])(tparams, lm_emb, options, lm_dropout,
prefix='lm_encoder',
mask=y_mask,
one_step=one_step,
init_state=lm_init_state,
profile=profile)
lm_next_state = lm_proj[0]
lm_ret_state = lm_proj[0]
# don't pass LSTM cell state to next layer
if options['lm_encoder'].startswith('lstm'):
lm_next_state = get_slice(lm_next_state, 0, options['lm_dim'])
# controller mechanism
prefix = 'fusion_lm'
lm_gate = tensor.dot(lm_next_state, tparams[pp(prefix, 'v_g')])+tparams[pp(prefix, 'b_g')]
lm_gate = tensor.nnet.sigmoid(lm_gate)
if one_step:
lm_gate = tensor.tile(lm_gate, (1, options['lm_dim']))
else:
lm_gate = tensor.tile(lm_gate, (1, 1, options['lm_dim']))
lm_next_state = lm_next_state * lm_gate
# hidden layer taking RNN state, previous word embedding and context vector as input
# (this counts as the first layer in our deep output, which is always on)
if options['deep_fusion_lm'] and options['concatenate_lm_decoder']:
next_state = concatenate([lm_next_state, next_state], axis=next_state.ndim-1)
logit_lstm = get_layer_constr('ff')(tparams, next_state, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_logit_lstm', activ='linear')
logit_prev = get_layer_constr('ff')(tparams, emb, options, dropout,
dropout_probability=options['dropout_embedding'],
prefix='ff_logit_prev', activ='linear')
logit_ctx = get_layer_constr('ff')(tparams, ctxs, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_logit_ctx', activ='linear')
if options['deep_fusion_lm'] and not options['concatenate_lm_decoder']:
# add current lm encoder state to last layer
logit_lm = get_layer_constr('ff')(tparams, lm_next_state, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_logit_lm', activ='linear')
logit = tensor.tanh(logit_lstm+logit_prev+logit_ctx+logit_lm)
else:
logit = tensor.tanh(logit_lstm+logit_prev+logit_ctx)
# last layer
logit_W = tparams['Wemb' + decoder_embedding_suffix].T if options['tie_decoder_embeddings'] else None
logit = get_layer_constr('ff')(tparams, logit, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_logit', activ='linear', W=logit_W, followed_by_softmax=True)
return logit, opt_ret, ret_state, lm_ret_state
def build_model_single_batch(tparams, options, trng, use_noise, sampling=False):
# trng = RandomStreams(1234)
# use_noise = theano.shared(numpy_floatX(0.))
dropout = dropout_constr(options, use_noise, trng, sampling=False)
y = tensor.matrix('y', dtype='int64')
y_mask = tensor.matrix('y_mask', dtype=floatX)
x_mask = tensor.matrix('x_mask', dtype=floatX)
x, ctx = build_encoder(tparams, options, dropout, x_mask, sampling=False)
n_samples = x.shape[2]
# mean of the context (across time) will be used to initialize decoder rnn
ctx_mean = (ctx * x_mask[:, :, None]).sum(0) / x_mask.sum(0)[:, None]
# or you can use the last state of forward + backward encoder rnns
# ctx_mean = concatenate([proj[0][-1], projr[0][-1]], axis=proj[0].ndim-2)
# initial decoder state
init_state = get_layer_constr('ff')(tparams, ctx_mean, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_state', activ='tanh')
# every decoder RNN layer gets its own copy of the init state
init_state = init_state.reshape([1, init_state.shape[0], init_state.shape[1]])
if options['dec_depth'] > 1:
init_state = tensor.tile(init_state, (options['dec_depth'], 1, 1))
logit, opt_ret, _, _ = build_decoder(tparams, options, y, ctx, init_state, dropout, x_mask=x_mask, y_mask=y_mask, sampling=False)
logit_shp = logit.shape
probs = tensor.nnet.softmax(logit.reshape([logit_shp[0]*logit_shp[1],
logit_shp[2]]))
# cost
y_flat = y.flatten()
y_flat_idx = tensor.arange(y_flat.shape[0]) * options['n_words'] + y_flat
cost = -tensor.log(probs.flatten()[y_flat_idx])
cost = cost.reshape([y.shape[0], y.shape[1]])
cost = (cost * y_mask).sum(0)
return x, x_mask, y, y_mask, cost
def build_model_single_batch_pseudo(tparams, options, trng, use_noise, sampling=False):
# trng = RandomStreams(1234)
# use_noise = theano.shared(numpy_floatX(0.))
dropout = dropout_constr(options, use_noise, trng, sampling=False)
y = tensor.matrix('y', dtype='int64')
y_mask = tensor.matrix('y_mask', dtype=floatX)
x = tensor.tensor3('x', dtype='int64')
x_mask = tensor.matrix('x_mask', dtype=floatX)
ctx = build_encoder_pseudo(tparams, options, dropout, x, x_mask, sampling=False)
n_samples = x.shape[2]
# mean of the context (across time) will be used to initialize decoder rnn
ctx_mean = (ctx * x_mask[:, :, None]).sum(0) / x_mask.sum(0)[:, None]
# or you can use the last state of forward + backward encoder rnns
# ctx_mean = concatenate([proj[0][-1], projr[0][-1]], axis=proj[0].ndim-2)
# initial decoder state
init_state = get_layer_constr('ff')(tparams, ctx_mean, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_state', activ='tanh')
# every decoder RNN layer gets its own copy of the init state
init_state = init_state.reshape([1, init_state.shape[0], init_state.shape[1]])
if options['dec_depth'] > 1:
init_state = tensor.tile(init_state, (options['dec_depth'], 1, 1))
logit, opt_ret, _, _ = build_decoder(tparams, options, y, ctx, init_state, dropout, x_mask=x_mask, y_mask=y_mask, sampling=False)
logit_shp = logit.shape
probs = tensor.nnet.softmax(logit.reshape([logit_shp[0]*logit_shp[1],
logit_shp[2]]))
# cost
y_flat = y.flatten()
y_flat_idx = tensor.arange(y_flat.shape[0]) * options['n_words'] + y_flat
cost = -tensor.log(probs.flatten()[y_flat_idx])
cost = cost.reshape([y.shape[0], y.shape[1]])
cost = (cost * y_mask).sum(0)
return x, x_mask, y, y_mask, cost
# build a training model
def build_model(tparams, options):
trng = RandomStreams(1234)
use_noise = theano.shared(numpy_floatX(0.))
dropout = dropout_constr(options, use_noise, trng, sampling=False)
y = tensor.matrix('y', dtype='int64')
y_mask = tensor.matrix('y_mask', dtype=floatX)
x = tensor.tensor3('x', dtype='int64')
x_mask = tensor.matrix('x_mask', dtype=floatX)
# boundary between real and pseudo source
begin_pseudo = tensor.scalar('begin_pseudo', dtype='int64')
x_true = x[:,:,:begin_pseudo]
x_true_mask = x_mask[:,:begin_pseudo]
x_pseudo = x[:,:,begin_pseudo:]
x_pseudo_mask = x_mask[:,begin_pseudo:]
ctx_true = build_encoder_true(tparams, options, dropout, x_true, x_true_mask, sampling=False)
# build encoder for pseudo source
ctx_pseudo = build_encoder_pseudo(tparams, options, dropout, x_pseudo, x_pseudo_mask, sampling=False)
# concatenate both encodings for the decoder
ctx = tensor.concatenate([ctx_true, ctx_pseudo], axis=1)
n_samples = x.shape[2]
# mean of the context (across time) will be used to initialize decoder rnn
ctx_mean = (ctx * x_mask[:, :, None]).sum(0) / x_mask.sum(0)[:, None]
# or you can use the last state of forward + backward encoder rnns
# ctx_mean = concatenate([proj[0][-1], projr[0][-1]], axis=proj[0].ndim-2)
# initial decoder state
init_state = get_layer_constr('ff')(tparams, ctx_mean, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_state', activ='tanh')
# every decoder RNN layer gets its own copy of the init state
init_state = init_state.reshape([1, init_state.shape[0], init_state.shape[1]])
if options['dec_depth'] > 1:
init_state = tensor.tile(init_state, (options['dec_depth'], 1, 1))
logit, opt_ret, _, _ = build_decoder(tparams, options, y, ctx, init_state, dropout, x_mask=x_mask, y_mask=y_mask, sampling=False)
logit_shp = logit.shape
probs = tensor.nnet.softmax(logit.reshape([logit_shp[0]*logit_shp[1],
logit_shp[2]]))
# cost
y_flat = y.flatten()
y_flat_idx = tensor.arange(y_flat.shape[0]) * options['n_words'] + y_flat
cost = -tensor.log(probs.flatten()[y_flat_idx])
cost = cost.reshape([y.shape[0], y.shape[1]])
cost = (cost * y_mask).sum(0)
#print "Print out in build_model()"
#print opt_ret
return trng, use_noise, x, x_mask, y, y_mask, opt_ret, cost, ctx, begin_pseudo
# build a sampler
def build_sampler(tparams, options, use_noise, trng, return_alignment=False):
dropout = dropout_constr(options, use_noise, trng, sampling=True)
x, ctx = build_encoder(tparams, options, dropout, x_mask=None, sampling=True)
n_samples = x.shape[2]
# get the input for decoder rnn initializer mlp
ctx_mean = ctx.mean(0)
# ctx_mean = concatenate([proj[0][-1],projr[0][-1]], axis=proj[0].ndim-2)
init_state = get_layer_constr('ff')(tparams, ctx_mean, options, dropout,
dropout_probability=options['dropout_hidden'],
prefix='ff_state', activ='tanh')
# every decoder RNN layer gets its own copy of the init state
init_state = init_state.reshape([1, init_state.shape[0], init_state.shape[1]])
if options['dec_depth'] > 1:
init_state = tensor.tile(init_state, (options['dec_depth'], 1, 1))