-
Notifications
You must be signed in to change notification settings - Fork 4
/
model_lstmdd.py
1761 lines (1539 loc) · 70.2 KB
/
model_lstmdd.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
'''
Build a soft-attention-based video caption generator
'''
import theano
import theano.tensor as tensor
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from timeit import default_timer as timer
import cPickle as pkl
import numpy
import copy
import os, sys, socket, shutil
import time
import warnings
from collections import OrderedDict
from sklearn.cross_validation import KFold
from scipy import optimize, stats
import data_engine
import metrics
import common
from common import *
from numpy import linalg as LA
base_path = None
hostname = socket.gethostname()
lscratch_dir = None
# make prefix-appended name
def _p(pp, name):
return '%s_%s'%(pp, name)
def validate_options(options):
if options['ctx2out']:
warnings.warn('Feeding context to output directly seems to hurt.')
if options['dim_word'] > options['dim']:
warnings.warn('dim_word should only be as large as dim.')
return options
class Attention(object):
def __init__(self, channel=None):
# layers: 'name': ('parameter initializer', 'feedforward')
self.layers = {
'ff': ('self.param_init_fflayer', 'self.fflayer'),
'lstm': ('self.param_init_lstm', 'self.lstm_layer'),
'lstm_cond': ('self.param_init_lstm_cond', 'self.lstm_cond_layer'),
}
self.channel = channel
def get_layer(self, name):
"""
Part of the reason the init is very slow is because,
the layer's constructor is called even when it isn't needed
"""
fns = self.layers[name]
return (eval(fns[0]), eval(fns[1]))
def load_params(self, path, params):
# load params from disk
pp = numpy.load(path)
for kk, vv in params.iteritems():
if kk not in pp:
raise Warning('%s is not in the archive'%kk)
params[kk] = pp[kk]
return params
def init_tparams(self, params, force_cpu=False):
# initialize Theano shared variables according to the initial parameters
tparams = OrderedDict()
for kk, pp in params.iteritems():
if force_cpu:
tparams[kk] = theano.tensor._shared(params[kk], name=kk)
else:
tparams[kk] = theano.shared(params[kk], name=kk)
return tparams
def param_init_fflayer(self, options, params, prefix='ff', nin=None, nout=None):
if nin == None:
nin = options['dim_proj']
if nout == None:
nout = options['dim_proj']
params[_p(prefix,'W')] = norm_weight(nin, nout, scale=0.01)
params[_p(prefix,'b')] = numpy.zeros((nout,)).astype('float32')
return params
def fflayer(self, tparams, state_below, options,
prefix='rconv', activ='lambda x: tensor.tanh(x)', **kwargs):
return eval(activ)(tensor.dot(state_below, tparams[_p(prefix,'W')])+tparams[
_p(prefix,'b')])
# LSTM layer
def param_init_lstm(self, options, params, prefix=None, nin=None, dim=None):
assert prefix is not None
if nin == None:
nin = options['dim_proj']
if dim == None:
dim = options['dim_proj']
# Stack the weight matricies for faster dot prods
W = numpy.concatenate([norm_weight(nin,dim),
norm_weight(nin,dim),
norm_weight(nin,dim),
norm_weight(nin,dim)], axis=1)
params[_p(prefix,'W')] = W
U = numpy.concatenate([ortho_weight(dim),
ortho_weight(dim),
ortho_weight(dim),
ortho_weight(dim)], axis=1)
params[_p(prefix,'U')] = U
params[_p(prefix,'b')] = numpy.zeros((4 * dim,)).astype('float32')
return params
# This function implements the lstm fprop
def lstm_layer(self, tparams, state_below, options, prefix='lstm', mask=None,
forget=False, use_noise=None, trng=None, **kwargs):
nsteps = state_below.shape[0]
dim = tparams[_p(prefix,'U')].shape[0]
if state_below.ndim == 3:
n_samples = state_below.shape[1]
init_state = tensor.alloc(0., n_samples, dim)
init_memory = tensor.alloc(0., n_samples, dim)
else:
n_samples = 1
init_state = tensor.alloc(0., dim)
init_memory = tensor.alloc(0., dim)
if mask == None:
mask = tensor.alloc(1., state_below.shape[0], 1)
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
elif _x.ndim == 2:
return _x[:, n*dim:(n+1)*dim]
return _x[n*dim:(n+1)*dim]
def _step(m_, x_, h_, c_, U, b):
preact = tensor.dot(h_, U)
preact += x_
preact += b
i = tensor.nnet.sigmoid(_slice(preact, 0, dim))
f = tensor.nnet.sigmoid(_slice(preact, 1, dim))
o = tensor.nnet.sigmoid(_slice(preact, 2, dim))
c = tensor.tanh(_slice(preact, 3, dim))
if forget:
f = T.zeros_like(f)
# c = f * c_ + (1-f) * c
c = f * c_ + i * c
h = o * tensor.tanh(c)
if m_.ndim == 0:
# when using this for minibatchsize=1
h = m_ * h + (1. - m_) * h_
c = m_ * c + (1. - m_) * c_
else:
h = m_[:,None] * h + (1. - m_)[:,None] * h_
c = m_[:,None] * c + (1. - m_)[:,None] * c_
return h, c, i, f, o, preact
state_below = tensor.dot(
state_below, tparams[_p(prefix, 'W')]) + tparams[_p(prefix, 'b')]
U = tparams[_p(prefix, 'U')]
b = tparams[_p(prefix, 'b')]
rval, updates = theano.scan(
_step,
sequences=[mask, state_below],
non_sequences=[U,b],
outputs_info = [init_state, init_memory, None, None, None, None],
name=_p(prefix, '_layers'),
n_steps=nsteps,
strict=True,
profile=False)
return rval
# Conditional LSTM layer with Attention
def param_init_lstm_cond(self, options, params,
prefix='lstm_cond', nin=None, dim=None, dimctx=None):
if nin == None:
nin = options['dim']
if dim == None:
dim = options['dim']
if dimctx == None:
dimctx = options['dim']
# input to LSTM
W = numpy.concatenate([norm_weight(nin,dim),
norm_weight(nin,dim),
norm_weight(nin,dim),
norm_weight(nin,dim)], axis=1)
params[_p(prefix,'W')] = W
# LSTM to LSTM
U = numpy.concatenate([ortho_weight(dim),
ortho_weight(dim),
ortho_weight(dim),
ortho_weight(dim)], axis=1)
params[_p(prefix,'U')] = U
# bias to LSTM
params[_p(prefix,'b')] = numpy.zeros((4 * dim,)).astype('float32')
# context to LSTM
Wc = norm_weight(dimctx,dim*4)
params[_p(prefix,'Wc')] = Wc
# attention: context -> hidden
Wc_att = norm_weight(dimctx, ortho=False)
params[_p(prefix,'Wc_att')] = Wc_att
# attention: LSTM -> hidden
Wd_att = norm_weight(dim,dimctx)
params[_p(prefix,'Wd_att')] = Wd_att
# attention: hidden bias
b_att = numpy.zeros((dimctx,)).astype('float32')
params[_p(prefix,'b_att')] = b_att
# attention:
U_att = norm_weight(dimctx,1)
params[_p(prefix,'U_att')] = U_att
c_att = numpy.zeros((1,)).astype('float32')
params[_p(prefix, 'c_tt')] = c_att
if options['selector']:
# attention: selector
W_sel = norm_weight(dim, 1)
params[_p(prefix, 'W_sel')] = W_sel
b_sel = numpy.float32(0.)
params[_p(prefix, 'b_sel')] = b_sel
return params
def lstm_cond_layer(self, tparams, state_below, options, prefix='lstm',
mask=None, context=None, one_step=False,
init_memory=None, init_state=None,
trng=None, use_noise=None,mode=None,
**kwargs):
# state_below (t, m, dim_word), or (m, dim_word) in sampling
# mask (t, m)
# context (m, f, dim_ctx), or (f, dim_word) in sampling
# init_memory, init_state (m, dim)
assert context, 'Context must be provided'
if one_step:
assert init_memory, 'previous memory must be provided'
assert init_state, 'previous state must be provided'
nsteps = state_below.shape[0]
if state_below.ndim == 3:
n_samples = state_below.shape[1]
else:
n_samples = 1
# mask
if mask == None:
mask = tensor.alloc(1., state_below.shape[0], 1)
dim = tparams[_p(prefix, 'U')].shape[0]
# initial/previous state
if init_state == None:
init_state = tensor.alloc(0., n_samples, dim)
# initial/previous memory
if init_memory == None:
init_memory = tensor.alloc(0., n_samples, dim)
# projected context
pctx_ = tensor.dot(context, tparams[_p(prefix,'Wc_att')]) + tparams[
_p(prefix, 'b_att')]
if one_step:
# tensor.dot will remove broadcasting dim
pctx_ = T.addbroadcast(pctx_,0)
# projected x
state_below = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + tparams[
_p(prefix, 'b')]
Wd_att = tparams[_p(prefix,'Wd_att')]
U_att = tparams[_p(prefix,'U_att')]
c_att = tparams[_p(prefix, 'c_tt')]
if options['selector']:
W_sel = tparams[_p(prefix, 'W_sel')]
b_sel = tparams[_p(prefix,'b_sel')]
else:
W_sel = T.alloc(0., 1)
b_sel = T.alloc(0., 1)
U = tparams[_p(prefix, 'U')]
Wc = tparams[_p(prefix, 'Wc')]
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
return _x[:, n*dim:(n+1)*dim]
def _step(m_, x_, # sequences
h_, c_, a_, ct_, # outputs_info
pctx_, ctx_, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc, # non_sequences
dp_=None, dp_att_=None):
# attention
pstate_ = tensor.dot(h_, Wd_att)
pctx_ = pctx_ + pstate_[:,None,:]
pctx_list = []
pctx_list.append(pctx_)
pctx_ = tanh(pctx_)
alpha = tensor.dot(pctx_, U_att)+c_att
alpha_pre = alpha
alpha_shp = alpha.shape
alpha = tensor.nnet.softmax(alpha.reshape([alpha_shp[0],alpha_shp[1]])) # softmax
ctx_ = (context * alpha[:,:,None]).sum(1) # (m,ctx_dim)
if options['selector']:
sel_ = tensor.nnet.sigmoid(tensor.dot(h_, W_sel) + b_sel)
sel_ = sel_.reshape([sel_.shape[0]])
ctx_ = sel_[:,None] * ctx_
preact = tensor.dot(h_, U)
preact += x_
preact += tensor.dot(ctx_, Wc)
i = _slice(preact, 0, dim)
f = _slice(preact, 1, dim)
o = _slice(preact, 2, dim)
if options['use_dropout']:
i = i * _slice(dp_, 0, dim)
f = f * _slice(dp_, 1, dim)
o = o * _slice(dp_, 2, dim)
i = tensor.nnet.sigmoid(i)
f = tensor.nnet.sigmoid(f)
o = tensor.nnet.sigmoid(o)
c = tensor.tanh(_slice(preact, 3, dim))
# c = f * c_ + (1-f) * c
c = f * c_ + i * c
c = m_[:,None] * c + (1. - m_)[:,None] * c_
h = o * tensor.tanh(c)
h = m_[:,None] * h + (1. - m_)[:,None] * h_
rval = [h, c, alpha, ctx_, pstate_, pctx_, i, f, o, preact, alpha_pre]+pctx_list
return rval
if options['use_dropout']:
_step0 = lambda m_, x_, dp_, h_, c_, \
a_, ct_, \
pctx_, context, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc: _step(
m_, x_, h_, c_,
a_, ct_,
pctx_, context, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc, dp_)
dp_shape = state_below.shape
if one_step:
dp_mask = tensor.switch(use_noise,
trng.binomial((dp_shape[0], 3*dim),
p=0.5, n=1, dtype=state_below.dtype),
tensor.alloc(0.5, dp_shape[0], 3 * dim))
else:
dp_mask = tensor.switch(use_noise,
trng.binomial((dp_shape[0], dp_shape[1], 3*dim),
p=0.5, n=1, dtype=state_below.dtype),
tensor.alloc(0.5, dp_shape[0], dp_shape[1], 3*dim))
else:
_step0 = lambda m_, x_, h_, c_, \
a_, ct_, pctx_, context, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc: _step(
m_, x_, h_, c_, a_, ct_, pctx_, context,
Wd_att, U_att, c_att, W_sel, b_sel, U, Wc)
if one_step:
if options['use_dropout']:
rval = _step0(
mask, state_below, dp_mask, init_state, init_memory, None, None,
pctx_, context, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc)
else:
rval = _step0(mask, state_below, init_state, init_memory, None, None,
pctx_, context, Wd_att, U_att, c_att, W_sel, b_sel, U, Wc)
else:
seqs = [mask, state_below]
if options['use_dropout']:
seqs += [dp_mask]
rval, updates = theano.scan(
_step0,
sequences=seqs,
outputs_info = [init_state,
init_memory,
tensor.alloc(0., n_samples, pctx_.shape[1]),
tensor.alloc(0., n_samples, context.shape[2]),
None, None, None, None, None, None, None, None],
non_sequences=[pctx_, context,
Wd_att, U_att, c_att, W_sel, b_sel, U, Wc],
name=_p(prefix, '_layers'),
n_steps=nsteps, profile=False, mode=mode, strict=True)
return rval
"""---------------------------------------------------------------------------------"""
"""---------------------------------------------------------------------------------"""
"""---------------------------------------------------------------------------------"""
def init_params(self, options):
# all parameters
params = OrderedDict()
# embedding
params['Wemb'] = norm_weight(options['n_words'], options['dim_word'])
if options['encoder'] == 'lstm_bi':
print 'bi-directional lstm encoder on ctx'
params = self.get_layer('lstm')[0](options, params, prefix='encoder',
nin=options['ctx_dim'], dim=options['encoder_dim'])
params = self.get_layer('lstm')[0](options, params, prefix='encoder_rev',
nin=options['ctx_dim'], dim=options['encoder_dim'])
ctx_dim = options['encoder_dim'] * 2 + options['ctx_dim']
elif options['encoder'] == 'lstm_uni':
print 'uni-directional lstm encoder on ctx'
params = self.get_layer('lstm')[0](options, params, prefix='encoder',
nin=options['ctx_dim'], dim=options['dim'])
ctx_dim = options['dim']
else:
print 'no lstm on ctx'
ctx_dim = options['ctx_dim']
# init_state, init_cell
for lidx in xrange(options['n_layers_init']):
params = self.get_layer('ff')[0](
options, params, prefix='ff_init_%d'%lidx, nin=ctx_dim, nout=ctx_dim)
params = self.get_layer('ff')[0](
options, params, prefix='ff_state', nin=ctx_dim, nout=options['dim'])
params = self.get_layer('ff')[0](
options, params, prefix='ff_memory', nin=ctx_dim, nout=options['dim'])
# decoder: LSTM
params = self.get_layer('lstm_cond')[0](options, params, prefix='decoder',
nin=options['dim_word'], dim=options['dim'],
dimctx=ctx_dim)
# second decoder: LSTM
params = self.get_layer('lstm_cond')[0](options, params, prefix='decoder_f',
nin=options['dim_word'], dim=options['dim'],
dimctx=ctx_dim)
# readout
params = self.get_layer('ff')[0](
options, params, prefix='ff_logit_lstm',
nin=options['dim'], nout=options['dim_word'])
if options['ctx2out']:
params = self.get_layer('ff')[0](
options, params, prefix='ff_logit_ctx',
nin=ctx_dim, nout=options['dim_word'])
if options['n_layers_out'] > 1:
for lidx in xrange(1, options['n_layers_out']):
params = self.get_layer('ff')[0](
options, params, prefix='ff_logit_h%d'%lidx,
nin=options['dim_word'], nout=options['dim_word'])
params = self.get_layer('ff')[0](
options, params, prefix='ff_logit',
nin=options['dim_word'], nout=options['n_words'])
return params
def build_model(self, tparams, options):
trng = RandomStreams(1234)
use_noise = theano.shared(numpy.float32(0.))
# description string: #words x #samples
x = tensor.matrix('x', dtype='int64')
x.tag.test_value = self.x_tv
x_mask = tensor.matrix('mask', dtype='float32')
x_mask.tag.test_value = self.mask_tv
y = tensor.matrix('y', dtype='int64')
y.tag.test_value = self.y_tv
y_mask = tensor.matrix('y_mask', dtype='float32')
y_mask.tag.test_value = self.y_mask_tv
# z = tensor.matrix('z', dtype='int64')
# z_mask = tensor.matrix('z_mask', dtype='float32')
# context: #samples x #annotations x dim
ctx = tensor.tensor3('ctx', dtype='float32')
ctx.tag.test_value = self.ctx_tv
mask_ctx = tensor.matrix('mask_ctx', dtype='float32')
mask_ctx.tag.test_value = self.ctx_mask_tv
n_timesteps = x.shape[0]
n_timesteps_f = y.shape[0]
# n_timesteps_b = z.shape[0]
n_samples = x.shape[1]
# index into the word embedding matrix, shift it forward in time
emb = tparams['Wemb'][x.flatten()].reshape([n_timesteps, n_samples, options['dim_word']])
emb_shifted = tensor.zeros_like(emb)
emb_shifted = tensor.set_subtensor(emb_shifted[1:], emb[:-1])
emb = emb_shifted
#other sample
embf = tparams['Wemb'][y.flatten()].reshape([n_timesteps_f, n_samples, options['dim_word']])
embf_shifted = tensor.zeros_like(embf)
embf_shifted = tensor.set_subtensor(embf_shifted[1:], embf[:-1])
embf = embf_shifted
counts = mask_ctx.sum(-1).dimshuffle(0,'x')
ctx_ = ctx
if options['encoder'] == 'lstm_bi':
# encoder
ctx_fwd = self.get_layer('lstm')[1](tparams, ctx_.dimshuffle(1,0,2),
options, mask=mask_ctx.dimshuffle(1,0),
prefix='encoder')[0]
ctx_rev = self.get_layer('lstm')[1](tparams, ctx_.dimshuffle(1,0,2)[::-1],
options, mask=mask_ctx.dimshuffle(1,0)[::-1],
prefix='encoder_rev')[0]
ctx0 = concatenate((ctx_fwd, ctx_rev[::-1]), axis=2)
ctx0 = ctx0.dimshuffle(1,0,2)
ctx0 = concatenate((ctx_, ctx0), axis=2)
ctx_mean = ctx0.sum(1)/counts
elif options['encoder'] == 'lstm_uni':
ctx0 = self.get_layer('lstm')[1](tparams, ctx_.dimshuffle(1,0,2),
options,
mask=mask_ctx.dimshuffle(1,0),
prefix='encoder')[0]
ctx0 = ctx0.dimshuffle(1,0,2)
ctx_mean = ctx0.sum(1)/counts
else:
ctx0 = ctx_
ctx_mean = ctx0.sum(1)/counts
# initial state/cell
for lidx in xrange(options['n_layers_init']):
ctx_mean = self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_init_%d'%lidx, activ='rectifier')
if options['use_dropout']:
ctx_mean = dropout_layer(ctx_mean, use_noise, trng)
init_state = self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_state', activ='tanh')
init_memory = self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_memory', activ='tanh')
# decoder
proj = self.get_layer('lstm_cond')[1](tparams, emb, options,
prefix='decoder',
mask=x_mask, context=ctx0,
one_step=False,
init_state=init_state,
init_memory=init_memory,
trng=trng,
use_noise=use_noise)
# decoder (ahead)
projf = self.get_layer('lstm_cond')[1](tparams, embf, options,
prefix='decoder_f',
mask=y_mask,context=ctx0,
one_step=False,
init_state=init_state,
init_memory=init_memory,
trng=trng,
use_noise=use_noise)
proj_h = proj[0]
alphas = proj[2]
ctxs = proj[3]
if options['use_dropout']:
proj_h = dropout_layer(proj_h, use_noise, trng)
# compute word probabilities
logit = self.get_layer('ff')[1](
tparams, proj_h, options, prefix='ff_logit_lstm', activ='linear')
if options['prev2out']:
logit += emb
if options['ctx2out']:
logit += self.get_layer('ff')[1](
tparams, ctxs, options, prefix='ff_logit_ctx', activ='linear')
logit = tanh(logit)
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
if options['n_layers_out'] > 1:
for lidx in xrange(1, options['n_layers_out']):
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit_h%d'%lidx, activ='rectifier')
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
# (t,m,n_words)
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit', activ='linear')
logit_shp = logit.shape
# (t*m, n_words)
probs = tensor.nnet.softmax(
logit.reshape([logit_shp[0]*logit_shp[1], logit_shp[2]]))
# cost
x_flat = x.flatten() # (t*m,)
cost = -tensor.log(probs[T.arange(x_flat.shape[0]), x_flat] + 1e-8)
cost = cost.reshape([x.shape[0], x.shape[1]])
cost_x = (cost * x_mask).sum(0)
# compute word probabilities other sample
y_proj_h = projf[0]
y_alphas = projf[2]
y_ctxs = projf[3]
if options['use_dropout']:
y_proj_h = dropout_layer(y_proj_h, use_noise, trng)
# compute word probabilities
logit = self.get_layer('ff')[1](
tparams, y_proj_h, options, prefix='ff_logit_lstm', activ='linear')
if options['prev2out']:
logit += emb
if options['ctx2out']:
logit += self.get_layer('ff')[1](
tparams, y_ctxs, options, prefix='ff_logit_ctx', activ='linear')
logit = tanh(logit)
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
if options['n_layers_out'] > 1:
for lidx in xrange(1, options['n_layers_out']):
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit_h%d'%lidx, activ='rectifier')
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
# (t,m,n_words)
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit', activ='linear')
logit_shp = logit.shape
# (t*m, n_words)
probs_y = tensor.nnet.softmax(
logit.reshape([logit_shp[0]*logit_shp[1], logit_shp[2]]))
# cost
y_flat = y.flatten() # (t*m,)
cost = -tensor.log(probs_y[T.arange(y_flat.shape[0]), y_flat] + 1e-8)
cost = cost.reshape([y.shape[0], y.shape[1]])
cost_y = (cost * y_mask).sum(0)
p_x = probs[T.arange(x_flat.shape[0]), x_flat] + 1e-8
p_y = probs_y[T.arange(y_flat.shape[0]), y_flat] + 1e-8
p_centroid = (p_x + p_y)/2
if options['cost_type'] == 'v2':# it is crashing with Nan values
print options['cost_type']
cost_xy = LA.norm(p_x - p_y)
# cost_xy = T.sum(cost_xy)
cost = cost_x + cost_y + cost_xy
elif options['cost_type'] == 'v3':
print options['cost_type']
# total cost v3
cost_xy = abs(p_x - p_y)
cost_xy = T.sum(cost_xy)
cost = cost_x + cost_y + cost_xy
# total cost v4
elif options['cost_type'] == 'v4': #winner of msvd
print options['cost_type']
cost_xy = p_x - p_y
cost_xy = cost_xy.norm(2)
cost = cost_x + cost_y + cost_xy
elif options['cost_type'] == 'v5':
print options['cost_type']
cost_xy = p_x - p_y
cost_xy = cost_xy.norm(2)
x_flat = x.flatten()
cost = -tensor.log(p_centroid)
cost = cost.reshape([x.shape[0], x.shape[1]])
cost_x = (cost * x_mask).sum(0)
y_flat = y.flatten()
cost = -tensor.log(p_centroid)
cost = cost.reshape([y.shape[0], y.shape[1]])
cost_y = (cost * y_mask).sum(0)
# c1_x = abs(p_x - p_centroid)
# c2_y = abs(p_y - p_centroid)
# cost = c1_x + c2_y + cost_xy
# cost = c1_x + c2_y
cost = cost_x + cost_y + cost_xy
# c1_x = abs(p_x - p_centroid)
# c2_y = abs(p_y - p_centroid)
# cost = c1_x + c2_y + cost_xy
elif options['cost_type'] == 'v6': #lsmdc winner
print options['cost_type']
x_flat = x.flatten()
cost = -tensor.log(p_centroid)
cost = cost.reshape([x.shape[0], x.shape[1]])
cost_x = (cost * x_mask).sum(0)
y_flat = y.flatten()
cost = -tensor.log(p_centroid)
cost = cost.reshape([y.shape[0], y.shape[1]])
cost_y = (cost * y_mask).sum(0)
cost = cost_x + cost_y
else:
# total cost v1
print options['cost_type']
cost = cost_x + cost_y
# this is a constraint to improve similarity of decoders. Needs work
# # total cost
# W = tparams[_p('decoder','W')]
# Wf = tparams[_p('decoder_f','W')]
#
# costw = abs(W - Wf)
# costw = T.sum(costw)
#
# cost = cost_x + cost_y +costw
extra = [probs, alphas]
return trng, use_noise, x, x_mask, ctx, mask_ctx, alphas, cost, extra,y,y_mask
def build_sampler(self, tparams, options, use_noise, trng, mode=None):
# context: #annotations x dim
ctx0 = tensor.matrix('ctx_sampler', dtype='float32')
#ctx0.tag.test_value = numpy.random.uniform(size=(50,1024)).astype('float32')
ctx_mask = tensor.vector('ctx_mask', dtype='float32')
#ctx_mask.tag.test_value = numpy.random.binomial(n=1,p=0.5,size=(50,)).astype('float32')
ctx_ = ctx0
counts = ctx_mask.sum(-1)
if options['encoder'] == 'lstm_bi':
# encoder
ctx_fwd = self.get_layer('lstm')[1](tparams, ctx_,
options, mask=ctx_mask,
prefix='encoder',forget=False)[0]
ctx_rev = self.get_layer('lstm')[1](tparams, ctx_[::-1],
options, mask=ctx_mask[::-1],
forget=False,
prefix='encoder_rev')[0]
ctx = concatenate((ctx_fwd, ctx_rev[::-1]), axis=1)
ctx = concatenate((ctx_, ctx),axis=1)
ctx_mean = ctx.sum(0)/counts
ctx = ctx.dimshuffle('x',0,1)
elif options['encoder'] == 'lstm_uni':
ctx = self.get_layer('lstm')[1](tparams, ctx_,
options,
mask=ctx_mask,
prefix='encoder')[0]
ctx_mean = ctx.sum(0)/counts
ctx = ctx.dimshuffle('x',0,1)
else:
# do not use RNN encoder
ctx = ctx_
ctx_mean = ctx.sum(0)/counts
#ctx_mean = ctx.mean(0)
ctx = ctx.dimshuffle('x',0,1)
# initial state/cell
for lidx in xrange(options['n_layers_init']):
ctx_mean = self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_init_%d'%lidx, activ='rectifier')
if options['use_dropout']:
ctx_mean = dropout_layer(ctx_mean, use_noise, trng)
init_state = [self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_state', activ='tanh')]
init_memory = [self.get_layer('ff')[1](
tparams, ctx_mean, options, prefix='ff_memory', activ='tanh')]
print 'Building f_init...',
f_init = theano.function(
[ctx0, ctx_mask],
[ctx0]+init_state+init_memory, name='f_init',
on_unused_input='ignore',
profile=False, mode=mode)
print 'Done'
x = tensor.vector('x_sampler', dtype='int64')
init_state = [tensor.matrix('init_state', dtype='float32')]
init_memory = [tensor.matrix('init_memory', dtype='float32')]
# if it's the first word, emb should be all zero
emb = tensor.switch(x[:,None] < 0, tensor.alloc(0., 1, tparams['Wemb'].shape[1]),
tparams['Wemb'][x])
proj = self.get_layer('lstm_cond')[1](tparams, emb, options,
prefix='decoder',
mask=None, context=ctx,
one_step=True,
init_state=init_state[0],
init_memory=init_memory[0],
trng=trng,
use_noise=use_noise,
mode=mode)
next_state, next_memory, ctxs = [proj[0]], [proj[1]], [proj[3]]
if options['use_dropout']:
proj_h = dropout_layer(proj[0], use_noise, trng)
else:
proj_h = proj[0]
logit = self.get_layer('ff')[1](
tparams, proj_h, options, prefix='ff_logit_lstm', activ='linear')
if options['prev2out']:
logit += emb
if options['ctx2out']:
logit += self.get_layer('ff')[1](
tparams, ctxs[-1], options, prefix='ff_logit_ctx', activ='linear')
logit = tanh(logit)
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
if options['n_layers_out'] > 1:
for lidx in xrange(1, options['n_layers_out']):
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit_h%d'%lidx, activ='rectifier')
if options['use_dropout']:
logit = dropout_layer(logit, use_noise, trng)
logit = self.get_layer('ff')[1](
tparams, logit, options, prefix='ff_logit', activ='linear')
logit_shp = logit.shape
next_probs = tensor.nnet.softmax(logit)
next_sample = trng.multinomial(pvals=next_probs).argmax(1)
# next word probability
print 'building f_next...'
f_next = theano.function(
[x, ctx0, ctx_mask]+init_state+init_memory,
[next_probs, next_sample]+next_state+next_memory,
name='f_next', profile=False, mode=mode, on_unused_input='ignore')
print 'Done'
return f_init, f_next
def gen_sample(self, tparams, f_init, f_next, ctx0, ctx_mask, options,
trng=None, k=1, maxlen=30, stochastic=False,
restrict_voc=False):
'''
ctx0: (26,1024)
ctx_mask: (26,)
restrict_voc: set the probability of outofvoc words with 0, renormalize
'''
if k > 1:
assert not stochastic, 'Beam search does not support stochastic sampling'
sample = []
sample_score = []
if stochastic:
sample_score = 0
live_k = 1
dead_k = 0
hyp_samples = [[]] * live_k
hyp_scores = numpy.zeros(live_k).astype('float32')
hyp_states = []
hyp_memories = []
# [(26,1024),(512,),(512,)]
rval = f_init(ctx0, ctx_mask)
ctx0 = rval[0]
next_state = []
next_memory = []
n_layers_lstm = 1
for lidx in xrange(n_layers_lstm):
next_state.append(rval[1+lidx])
next_state[-1] = next_state[-1].reshape([live_k, next_state[-1].shape[0]])
for lidx in xrange(n_layers_lstm):
next_memory.append(rval[1+n_layers_lstm+lidx])
next_memory[-1] = next_memory[-1].reshape([live_k, next_memory[-1].shape[0]])
next_w = -1 * numpy.ones((1,)).astype('int64')
# next_state: [(1,512)]
# next_memory: [(1,512)]
for ii in xrange(maxlen):
# return [(1, 50000), (1,), (1, 512), (1, 512)]
# next_w: vector
# ctx: matrix
# ctx_mask: vector
# next_state: [matrix]
# next_memory: [matrix]
rval = f_next(*([next_w, ctx0, ctx_mask]+next_state+next_memory))
next_p = rval[0]
if restrict_voc:
raise NotImplementedError()
next_w = rval[1] # already argmax sorted
next_state = []
for lidx in xrange(n_layers_lstm):
next_state.append(rval[2+lidx])
next_memory = []
for lidx in xrange(n_layers_lstm):
next_memory.append(rval[2+n_layers_lstm+lidx])
if stochastic:
sample.append(next_w[0]) # take the most likely one
sample_score += next_p[0,next_w[0]]
if next_w[0] == 0:
break
else:
# the first run is (1,50000)
cand_scores = hyp_scores[:,None] - numpy.log(next_p)
cand_flat = cand_scores.flatten()
ranks_flat = cand_flat.argsort()[:(k-dead_k)]
voc_size = next_p.shape[1]
trans_indices = ranks_flat / voc_size # index of row
word_indices = ranks_flat % voc_size # index of col
costs = cand_flat[ranks_flat]
new_hyp_samples = []
new_hyp_scores = numpy.zeros(k-dead_k).astype('float32')
new_hyp_states = []
for lidx in xrange(n_layers_lstm):
new_hyp_states.append([])
new_hyp_memories = []
for lidx in xrange(n_layers_lstm):
new_hyp_memories.append([])
for idx, [ti, wi] in enumerate(zip(trans_indices, word_indices)):
new_hyp_samples.append(hyp_samples[ti]+[wi])
new_hyp_scores[idx] = copy.copy(costs[idx])
for lidx in xrange(n_layers_lstm):
new_hyp_states[lidx].append(copy.copy(next_state[lidx][ti]))
for lidx in xrange(n_layers_lstm):
new_hyp_memories[lidx].append(copy.copy(next_memory[lidx][ti]))
# check the finished samples
new_live_k = 0
hyp_samples = []
hyp_scores = []
hyp_states = []
for lidx in xrange(n_layers_lstm):
hyp_states.append([])
hyp_memories = []
for lidx in xrange(n_layers_lstm):
hyp_memories.append([])
for idx in xrange(len(new_hyp_samples)):
if new_hyp_samples[idx][-1] == 0:
sample.append(new_hyp_samples[idx])
sample_score.append(new_hyp_scores[idx])
dead_k += 1
else:
new_live_k += 1
hyp_samples.append(new_hyp_samples[idx])
hyp_scores.append(new_hyp_scores[idx])
for lidx in xrange(n_layers_lstm):
hyp_states[lidx].append(new_hyp_states[lidx][idx])
for lidx in xrange(n_layers_lstm):
hyp_memories[lidx].append(new_hyp_memories[lidx][idx])
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
next_state = []
for lidx in xrange(n_layers_lstm):
next_state.append(numpy.array(hyp_states[lidx]))
next_memory = []
for lidx in xrange(n_layers_lstm):
next_memory.append(numpy.array(hyp_memories[lidx]))
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score, next_state, next_memory
def pred_probs(self, whichset, f_log_probs, verbose=True):
probs = []
n_done = 0
NLL = []
L = []
if whichset == 'train':
tags = self.engine.train
iterator = self.engine.kf_train
elif whichset == 'valid':
tags = self.engine.valid
iterator = self.engine.kf_valid
elif whichset == 'test':
tags = self.engine.test
iterator = self.engine.kf_test
else:
raise NotImplementedError()
n_samples = numpy.sum([len(index) for index in iterator])
for index in iterator:
tag = [tags[i] for i in index]
x, mask, ctx, ctx_mask,y,y_mask = data_engine.prepare_data(
self.engine, tag)
pred_probs = f_log_probs(x, mask, ctx, ctx_mask,y,y_mask)
L.append(mask.sum(0).tolist())