-
Notifications
You must be signed in to change notification settings - Fork 46
/
mixer.py
2257 lines (1843 loc) · 81.7 KB
/
mixer.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
'''
Mixer containing essential functions or building blocks
'''
import theano
import theano.tensor as tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import numpy
import copy
import os
import warnings
import sys
import time
from collections import OrderedDict
profile = False
# layers: 'name': ('parameter initializer', 'feedforward')
layers = {'ff': ('param_init_fflayer', 'fflayer'),
'fff': ('param_init_ffflayer', 'ffflayer'),
'gru_decoder': ('param_init_gru_decoder', 'gru_decoder'),
'gru_cond_decoder': ('param_init_gru_cond_decoder',
'gru_cond_decoder'),
'two_layer_gru_decoder': ('param_init_two_layer_gru_decoder',
'two_layer_gru_decoder'),
'two_layer_gru_decoder_both': ('param_init_two_layer_gru_decoder_both',
'two_layer_gru_decoder_both'),
'biscale_decoder': ('param_init_biscale_decoder',
'biscale_decoder'),
'biscale_decoder_both': ('param_init_biscale_decoder_both',
'biscale_decoder_both'),
'biscale_decoder_attc': ('param_init_biscale_decoder_attc',
'biscale_decoder_attc'),
'gru': ('param_init_gru', 'gru_layer')
}
# utility function to slice a tensor
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
return _x[:, n*dim:(n+1)*dim]
# push parameters to Theano shared variables
def zipp(params, tparams):
for kk, vv in params.iteritems():
tparams[kk].set_value(vv)
# pull parameters from Theano shared variables
def unzip(zipped):
new_params = OrderedDict()
for kk, vv in zipped.iteritems():
new_params[kk] = vv.get_value()
return new_params
# get the list of parameters: Note that tparams must be OrderedDict
def itemlist(tparams):
return [vv for kk, vv in tparams.iteritems()]
# dropout
def dropout_layer(state_before, use_noise, trng):
proj = tensor.switch(
use_noise,
state_before * trng.binomial(state_before.shape, p=0.5, n=1,
dtype=state_before.dtype),
state_before * 0.5)
return proj
# make prefix-appended name
def _p(pp, name):
return '%s_%s' % (pp, name)
# initialize Theano shared variables according to the initial parameters
def init_tparams(params):
tparams = OrderedDict()
for kk, pp in params.iteritems():
tparams[kk] = theano.shared(params[kk], name=kk)
return tparams
# load parameters
def load_params(path, params):
pp = numpy.load(path)
for kk, vv in params.iteritems():
if kk not in pp:
warnings.warn('%s is not in the archive' % kk)
continue
params[kk] = pp[kk]
return params
def get_layer(name):
fns = layers[name]
return (eval(fns[0]), eval(fns[1]))
# some utilities
def ortho_weight(ndim, scale=0.01):
W = scale * numpy.random.randn(ndim, ndim)
u, s, v = numpy.linalg.svd(W)
return u.astype('float32')
def norm_vector(nin, scale=0.01):
V = scale * numpy.random.randn(nin)
return V.astype('float32')
def norm_weight(nin, nout=None, scale=0.01, ortho=True):
if nout is None:
nout = nin
if nout == nin and ortho:
W = ortho_weight(nin)
else:
W = scale * numpy.random.randn(nin, nout)
return W.astype('float32')
def tanh(x):
return tensor.tanh(x)
def linear(x):
return x
def concatenate(tensor_list, axis=0):
"""
Alternative implementation of `theano.tensor.concatenate`.
This function does exactly the same thing, but contrary to Theano's own
implementation, the gradient is implemented on the GPU.
Backpropagating through `theano.tensor.concatenate` yields slowdowns
because the inverse operation (splitting) needs to be done on the CPU.
This implementation does not have that problem.
:usage:
>>> x, y = theano.tensor.matrices('x', 'y')
>>> c = concatenate([x, y], axis=1)
:parameters:
- tensor_list : list
list of Theano tensor expressions that should be concatenated.
- axis : int
the tensors will be joined along this axis.
:returns:
- out : tensor
the concatenated tensor expression.
"""
concat_size = sum(tt.shape[axis] for tt in tensor_list)
output_shape = ()
for k in range(axis):
output_shape += (tensor_list[0].shape[k],)
output_shape += (concat_size,)
for k in range(axis + 1, tensor_list[0].ndim):
output_shape += (tensor_list[0].shape[k],)
out = tensor.zeros(output_shape, dtype=tensor_list[0].dtype)
offset = 0
for tt in tensor_list:
indices = ()
for k in range(axis):
indices += (slice(None),)
indices += (slice(offset, offset + tt.shape[axis]),)
for k in range(axis + 1, tensor_list[0].ndim):
indices += (slice(None),)
out = tensor.set_subtensor(out[indices], tt)
offset += tt.shape[axis]
return out
# feedforward layer: affine transformation + point-wise nonlinearity
def param_init_fflayer(options, params, prefix='ff', nin=None, nout=None,
ortho=True, scale=0.01):
if nin is None:
nin = options['dim_proj']
if nout is None:
nout = options['dim_proj']
params[_p(prefix, 'W')] = norm_weight(nin, nout, scale=scale, ortho=ortho)
params[_p(prefix, 'b')] = numpy.zeros((nout,)).astype('float32')
return params
def fflayer(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')])
# feedforward layer short-cut: affine transformation + point-wise nonlinearity
def param_init_ffflayer(options, params, prefix='fff', nin1=None, nin2=None, nout=None,
ortho=True, scale1=0.01, scale2=0.01):
if nin1 is None:
nin1 = options['dim_proj']
if nin2 is None:
nin2 = options['dim_proj']
if nout is None:
nout = options['dim_proj']
params[_p(prefix, 'W')] = norm_weight(nin1, nout, scale=scale1, ortho=ortho)
params[_p(prefix, 'U')] = norm_weight(nin2, nout, scale=scale2, ortho=ortho)
params[_p(prefix, 'b')] = numpy.zeros((nout,)).astype('float32')
return params
def ffflayer(tparams, state_below1, state_below2, options, prefix='rconv',
activ='lambda x: tensor.tanh(x)', **kwargs):
return eval(activ)(
tensor.dot(state_below1, tparams[_p(prefix, 'W')]) +
tensor.dot(state_below2, tparams[_p(prefix, 'U')]) +
tparams[_p(prefix, 'b')])
# GRU layer
def param_init_gru(options, params, prefix='gru', nin=None, dim=None):
if nin is None:
nin = options['dim_proj']
if dim is None:
dim = options['rnn_dim']
# embedding to gates transformation weights, biases
W = numpy.concatenate([norm_weight(nin, dim),
norm_weight(nin, dim)], axis=1)
params[_p(prefix, 'W')] = W
params[_p(prefix, 'b')] = numpy.zeros((2 * dim,)).astype('float32')
# recurrent transformation weights for gates
U = numpy.concatenate([ortho_weight(dim),
ortho_weight(dim)], axis=1)
params[_p(prefix, 'U')] = U
# embedding to hidden state proposal weights, biases
Wx = norm_weight(nin, dim)
params[_p(prefix, 'Wx')] = Wx
params[_p(prefix, 'bx')] = numpy.zeros((dim,)).astype('float32')
# recurrent transformation weights for hidden state proposal
Ux = ortho_weight(dim)
params[_p(prefix, 'Ux')] = Ux
return params
def gru_layer(tparams, state_below, options, prefix='gru',
mask=None, one_step=False, init_state=None, **kwargs):
if one_step:
assert init_state, 'previous state must be provided'
n_steps = state_below.shape[0]
if state_below.ndim in [2, 3]:
n_samples = state_below.shape[1]
elif state_below.ndim == 1:
if not one_step:
raise ValueError('if state_below.ndim is 1, one_step shoud also be 1')
else:
n_samples = 1
# mask
if mask is None:
mask = tensor.alloc(1., state_below.shape[0], 1)
dim = tparams[_p(prefix, 'Ux')].shape[1]
if state_below.dtype == 'int64':
state_below_ = tparams[_p(prefix, 'W')][state_below.flatten()]
state_belowx = tparams[_p(prefix, 'Wx')][state_below.flatten()]
if state_below.ndim == 2:
state_below_ = state_below_.reshape((n_steps, n_samples, -1))
state_belowx = state_belowx.reshape((n_steps, n_samples, -1))
state_below_ += tparams[_p(prefix, 'b')]
state_belowx += tparams[_p(prefix, 'bx')]
else:
# projected x to hidden state proposal
state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \
tparams[_p(prefix, 'b')]
# projected x to gates
state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \
tparams[_p(prefix, 'bx')]
# initial/previous state
if init_state is None:
init_state = tensor.alloc(0., n_samples, dim)
# step function to be used by scan
def _step(m_, x_, xx_, h_, U, Ux):
preact = tensor.dot(h_, U)
preact += x_
preact = tensor.nnet.sigmoid(preact)
# reset and update gates
r = _slice(preact, 0, dim)
u = _slice(preact, 1, dim)
# compute the hidden state proposal
preactx = tensor.dot(h_, Ux)
preactx *= r
preactx += xx_
# hidden state proposal
h = tensor.tanh(preactx)
# leaky integrate and obtain next hidden state
h = u * h_ + (1. - u) * h
h = m_[:, None] * h + (1. - m_)[:, None] * h_
return h
# prepare scan arguments
seqs = [mask, state_below_, state_belowx]
shared_vars = [tparams[_p(prefix, 'U')],
tparams[_p(prefix, 'Ux')]]
if one_step:
rval = _step(*(seqs+[init_state]+shared_vars))
else:
rval, updates = theano.scan(_step,
sequences=seqs,
outputs_info=[init_state],
non_sequences=shared_vars,
name=_p(prefix, '_layers'),
n_steps=n_steps,
profile=profile,
strict=True)
return rval
# Conditional GRU layer without Attention
def param_init_gru_decoder(options, params, prefix='gru_decoder', nin=None,
dim=None, dimctx=None):
if nin is None:
nin = options['dim']
if dim is None:
dim = options['dim']
if dimctx is None:
dimctx = options['dim']
params = param_init_gru(options, params, prefix, nin=nin, dim=dim)
# context to GRU gates
Wc = norm_weight(dimctx, dim*2)
params[_p(prefix, 'Wc')] = Wc
# context to hidden proposal
Wcx = norm_weight(dimctx, dim)
params[_p(prefix, 'Wcx')] = Wcx
return params
def gru_decoder(tparams, state_below, options, prefix='gru_decoder',
mask=None, context=None, one_step=False,
init_state=None, **kwargs):
assert context, 'Context must be provided'
if one_step:
assert init_state, 'previous state must be provided'
n_steps = state_below.shape[0]
if state_below.ndim == 3:
n_samples = state_below.shape[1]
else:
n_samples = 1
# mask
if mask is None:
mask = tensor.alloc(1., state_below.shape[0], 1)
dim = tparams[_p(prefix, 'Ux')].shape[1]
# initial/previous state
if init_state is None:
init_state = tensor.alloc(0., n_samples, dim)
assert context.ndim == 2, 'Context must be 2-d: #sample x dim'
# projected context to GRU gates
pctx_ = tensor.dot(context, tparams[_p(prefix, 'Wc')])
# projected context to hidden state proposal
pctxx_ = tensor.dot(context, tparams[_p(prefix, 'Wcx')])
# projected x to hidden state proposal
state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \
tparams[_p(prefix, 'b')]
# projected x to gates
state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \
tparams[_p(prefix, 'bx')]
# step function to be used by scan
# arguments | sequences | outputs-info| non-seqs
def _step(m_, x_, xx_, h_, pctx_, pctxx_, U, Ux):
preact = tensor.dot(h_, U)
preact += x_
preact += pctx_
preact = tensor.nnet.sigmoid(preact)
# reset and update gates
r = _slice(preact, 0, dim)
u = _slice(preact, 1, dim)
# compute the hidden state proposal
preactx = tensor.dot(h_, Ux)
preactx *= r
preactx += xx_
preactx += pctxx_
# hidden state proposal
h = tensor.tanh(preactx)
# leaky integrate and obtain next hidden state
h = u * h_ + (1. - u) * h
h = m_[:, None] * h + (1. - m_)[:, None] * h_
return h
# prepare scan arguments
seqs = [mask, state_below_, state_belowx]
shared_vars = [tparams[_p(prefix, 'U')],
tparams[_p(prefix, 'Ux')]]
if one_step:
rval = _step(*(seqs+[init_state, pctx_, pctxx_]+shared_vars))
else:
rval, updates = theano.scan(_step,
sequences=seqs,
outputs_info=[init_state],
non_sequences=[pctx_, pctxx_]+shared_vars,
name=_p(prefix, '_layers'),
n_steps=n_steps,
profile=profile,
strict=True)
return rval
# Conditional GRU layer with Attention
def param_init_gru_cond_decoder(options, params, prefix='gru_cond_decoder',
nin=None, dim=None, dimctx=None):
if nin is None:
nin = options['dim']
if dim is None:
dim = options['dim']
if dimctx is None:
dimctx = options['dim']
params = param_init_gru(options, params, prefix, nin=nin, dim=dim)
# context to LSTM
Wc = norm_weight(dimctx, dim*2)
params[_p(prefix, 'Wc')] = Wc
Wcx = norm_weight(dimctx, dim)
params[_p(prefix, 'Wcx')] = Wcx
# attention: prev -> hidden
Wi_att = norm_weight(nin, dimctx)
params[_p(prefix, 'Wi_att')] = Wi_att
# attention: context -> hidden
Wc_att = norm_weight(dimctx)
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
return params
def gru_cond_decoder(tparams, state_below, options, prefix='gru_cond_decoder',
mask=None, context=None, one_step=False, init_state=None,
context_mask=None, **kwargs):
assert context, 'Context must be provided'
assert context.ndim == 3, \
'Context must be 3-d: #annotation x #sample x dim'
if one_step:
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 is None: # sampling or beamsearch
mask = tensor.alloc(1., state_below.shape[0], 1)
dim = tparams[_p(prefix, 'Wcx')].shape[1]
# initial/previous state
if init_state is None:
init_state = tensor.alloc(0., n_samples, dim)
# projected context
pctx_ = tensor.dot(context, tparams[_p(prefix, 'Wc_att')]) + \
tparams[_p(prefix, 'b_att')]
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
return _x[:, n*dim:(n+1)*dim]
# projected x into hidden state proposal
state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + \
tparams[_p(prefix, 'bx')]
# projected x into gru gates
state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \
tparams[_p(prefix, 'b')]
# projected x into attention module
state_belowc = tensor.dot(state_below, tparams[_p(prefix, 'Wi_att')])
# step function to be used by scan
# arguments | sequences | outputs-info | non-seqs ...
def _step_slice(m_, x_, xx_, xc_, h_, ctx_, alpha_, pctx_, cc_,
U, Wc, Wd_att, U_att, c_tt, Ux, Wcx):
# attention
# project previous hidden state
pstate_ = tensor.dot(h_, Wd_att)
# add projected context
pctx__ = pctx_ + pstate_[None, :, :]
# add projected previous output
pctx__ += xc_
pctx__ = tensor.tanh(pctx__)
# compute alignment weights
alpha = tensor.dot(pctx__, U_att)+c_tt
alpha = alpha.reshape([alpha.shape[0], alpha.shape[1]])
alpha = tensor.exp(alpha - alpha.max(0))
if context_mask:
alpha = alpha * context_mask
alpha = alpha / alpha.sum(0, keepdims=True)
# conpute the weighted averages - current context to gru
ctx_ = (cc_ * alpha[:, :, None]).sum(0)
# conditional gru layer computations
preact = tensor.dot(h_, U)
preact += x_
preact += tensor.dot(ctx_, Wc)
preact = tensor.nnet.sigmoid(preact)
# reset and update gates
r = _slice(preact, 0, dim)
u = _slice(preact, 1, dim)
preactx = tensor.dot(h_, Ux)
preactx *= r
preactx += xx_
preactx += tensor.dot(ctx_, Wcx)
# hidden state proposal, leaky integrate and obtain next hidden state
h = tensor.tanh(preactx)
h = u * h_ + (1. - u) * h
h = m_[:, None] * h + (1. - m_)[:, None] * h_
return h, ctx_, alpha.T
seqs = [mask, state_below_, state_belowx, state_belowc]
_step = _step_slice
shared_vars = [tparams[_p(prefix, 'U')],
tparams[_p(prefix, 'Wc')],
tparams[_p(prefix, 'Wd_att')],
tparams[_p(prefix, 'U_att')],
tparams[_p(prefix, 'c_tt')],
tparams[_p(prefix, 'Ux')],
tparams[_p(prefix, 'Wcx')]]
if one_step:
rval = _step(*(
seqs+[init_state, None, None, pctx_, context]+shared_vars))
else:
rval, updates = theano.scan(
_step,
sequences=seqs,
outputs_info=[init_state,
tensor.alloc(0., n_samples, context.shape[2]),
tensor.alloc(0., n_samples, context.shape[0])],
non_sequences=[pctx_,
context]+shared_vars,
name=_p(prefix, '_layers'),
n_steps=nsteps,
profile=profile,
strict=True)
return rval
def param_init_two_layer_gru_decoder(options, params,
prefix='two_layer_gru_decoder',
nin=None,
dim_char=None,
dim_word=None,
dimctx=None):
if nin is None:
nin = options['n_words']
if dim_char is None:
dim_char = options['dec_dim']
if dim_word is None:
dim_word = options['dec_dim']
if dimctx is None:
dimctx = options['enc_dim'] * 2
# embedding to gates transformation weights, biases
W_xc = numpy.concatenate([norm_weight(nin, dim_char),
norm_weight(nin, dim_char)], axis=1)
params[_p(prefix, 'W_xc')] = W_xc
params[_p(prefix, 'b_c')] = numpy.zeros((2 * dim_char,)).astype('float32')
# recurrent transformation weights for gates
U_cc = numpy.concatenate([ortho_weight(dim_char),
ortho_weight(dim_char)], axis=1)
params[_p(prefix, 'U_cc')] = U_cc
# embedding to hidden state proposal weights, biases
Wx_xc = norm_weight(nin, dim_char)
params[_p(prefix, 'Wx_xc')] = Wx_xc
params[_p(prefix, 'bx_c')] = numpy.zeros((dim_char,)).astype('float32')
# recurrent transformation weights for hidden state proposal
Ux_cc = ortho_weight(dim_char)
params[_p(prefix, 'Ux_cc')] = Ux_cc
# embedding to gates transformation weights, biases
W_cw = numpy.concatenate([norm_weight(dim_char, dim_word),
norm_weight(dim_char, dim_word)], axis=1)
params[_p(prefix, 'W_cw')] = W_cw
params[_p(prefix, 'b_w')] = numpy.zeros((2 * dim_word,)).astype('float32')
# recurrent transformation weights for gates
U_ww = numpy.concatenate([ortho_weight(dim_word),
ortho_weight(dim_word)], axis=1)
params[_p(prefix, 'U_ww')] = U_ww
# embedding to hidden state proposal weights, biases
Wx_cw = norm_weight(dim_char, dim_word)
params[_p(prefix, 'Wx_cw')] = Wx_cw
params[_p(prefix, 'bx_w')] = numpy.zeros((dim_word,)).astype('float32')
# recurrent transformation weights for hidden state proposal
Ux_ww = ortho_weight(dim_word)
params[_p(prefix, 'Ux_ww')] = Ux_ww
# context to GRU gates: char-level
W_ctxc = numpy.concatenate([norm_weight(dimctx, dim_char),
norm_weight(dimctx, dim_char)], axis=1)
params[_p(prefix, 'W_ctxc')] = W_ctxc
# context to hidden proposal: char-level
Wx_ctxc = norm_weight(dimctx, dim_char)
params[_p(prefix, 'Wx_ctxc')] = Wx_ctxc
# context to GRU gates: word-level
W_ctxw = numpy.concatenate([norm_weight(dimctx, dim_word),
norm_weight(dimctx, dim_word)], axis=1)
params[_p(prefix, 'W_ctxw')] = W_ctxw
# context to hidden proposal: word-level
Wx_ctxw = norm_weight(dimctx, dim_word)
params[_p(prefix, 'Wx_ctxw')] = Wx_ctxw
# attention: prev -> hidden
Winp_att = norm_weight(nin, dimctx)
params[_p(prefix, 'Winp_att')] = Winp_att
# attention: context -> hidden
Wctx_att = norm_weight(dimctx)
params[_p(prefix, 'Wctx_att')] = Wctx_att
# attention: decoder -> hidden
Wdec_att = norm_weight(dim_word, dimctx)
params[_p(prefix, 'Wdec_att')] = Wdec_att
# attention: hidden bias
params[_p(prefix, 'b_att')] = numpy.zeros((dimctx,)).astype('float32')
# 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_att')] = c_att
return params
def two_layer_gru_decoder(tparams, state_below, options,
prefix='two_layer_gru_decoder',
mask=None, one_step=False,
context=None, context_mask=None,
init_state_char=None, init_state_word=None,
**kwargs):
assert context, 'Context must be provided'
assert context.ndim == 3, \
'Context must be 3-D: #annotation x #sample x #dim'
if one_step:
assert init_state_char, 'previous state must be provided'
assert init_state_word, 'previous state must be provided'
n_steps = state_below.shape[0]
if state_below.ndim in [2, 3]:
n_samples = state_below.shape[1]
elif state_below.ndim == 1:
if not one_step:
raise ValueError('if state_below.ndim is 1, one_step shoud also be 1')
else:
n_samples = 1
# mask
if mask is None:
mask = tensor.alloc(1., state_below.shape[0], 1)
dim_char = tparams[_p(prefix, 'Ux_cc')].shape[1]
dim_word = tparams[_p(prefix, 'Ux_ww')].shape[1]
if state_below.dtype == 'int64':
state_below_emb = tparams[_p(prefix, 'W_xc')][state_below.flatten()] + tparams[_p(prefix, 'b_c')]
state_belowx_emb = tparams[_p(prefix, 'Wx_xc')][state_below.flatten()] + tparams[_p(prefix, 'bx_c')]
state_belowctx_emb = tparams[_p(prefix, 'Winp_att')][state_below.flatten()]
if state_below.ndim == 2:
state_below_emb = state_below_emb.reshape((n_steps, n_samples, -1))
state_belowx_emb = state_belowx_emb.reshape((n_steps, n_samples, -1))
state_belowctx_emb = state_belowctx_emb.reshape((n_steps, n_samples, -1))
else:
state_below_emb = tensor.dot(state_below, tparams[_p(prefix, 'W_xc')]) + tparams[_p(prefix, 'b_c')]
state_belowx_emb = tensor.dot(state_below, tparams[_p(prefix, 'Wx_xc')]) + tparams[_p(prefix, 'bx_c')]
state_belowctx_emb = tensor.dot(state_below, tparams[_p(prefix, 'Winp_att')])
# initial/previous state
if init_state_char is None:
init_state_char = tensor.alloc(0., n_samples, dim_char)
if init_state_word is None:
init_state_word = tensor.alloc(0., n_samples, dim_word)
# projected context
proj_ctx = tensor.dot(context, tparams[_p(prefix, 'Wctx_att')]) + tparams[_p(prefix, 'b_att')]
# step function to be used by scan
def _step(m_t,
state_below_emb_t,
state_belowx_emb_t,
state_belowctx_emb_t,
h_c_tm1, h_w_tm1,
ctx_t,
alpha_t,
proj_ctx_all,
context,
U_cc, Ux_cc,
W_cw, Wx_cw, U_ww, Ux_ww, b_w, bx_w,
W_ctxc, Wx_ctxc, W_ctxw, Wx_ctxw,
Wdec_att,
U_att, c_att):
# ~~ attention ~~ #
# project previous hidden states
proj_state = tensor.dot(h_w_tm1, Wdec_att)
# add projected context
proj_ctx = proj_ctx_all + proj_state[None, :, :] + state_belowctx_emb_t
proj_h = tensor.tanh(proj_ctx)
# compute alignment weights
alpha = tensor.dot(proj_h, U_att) + c_att
alpha = alpha.reshape([alpha.shape[0], alpha.shape[1]])
alpha = tensor.exp(alpha - alpha.max(0))
#alpha = tensor.exp(alpha)
if context_mask:
alpha = alpha * context_mask
alpha = alpha / alpha.sum(0, keepdims=True)
# compute the weighted averages - current context to GRU
ctx_t = (context * alpha[:, :, None]).sum(0)
# compute char-level
preact_c = tensor.dot(h_c_tm1, U_cc) + state_below_emb_t + tensor.dot(ctx_t, W_ctxc )
preact_c = tensor.nnet.sigmoid(preact_c)
# update gates
r_c = _slice(preact_c, 0, dim_char)
u_c = _slice(preact_c, 1, dim_char)
# compute the hidden state proposal: char-level
preactx_c = tensor.dot(h_c_tm1, Ux_cc) * r_c + state_belowx_emb_t + tensor.dot(ctx_t, Wx_ctxc)
# hidden state proposal
h_c = tensor.tanh(preactx_c)
# leaky integrate and obtain next hidden state
h_c_t = u_c * h_c_tm1 + (1. - u_c) * h_c
h_c_t = m_t[:, None] * h_c_t + (1. - m_t)[:, None] * h_c_tm1
# compute char-level
preact_w = tensor.dot(h_w_tm1, U_ww) + tensor.dot(h_c_t, W_cw) + tensor.dot(ctx_t, W_ctxw) + b_w
preact_w = tensor.nnet.sigmoid(preact_w)
# update gates
r_w = _slice(preact_w, 0, dim_char)
u_w = _slice(preact_w, 1, dim_char)
# compute the hidden state proposal: char-level
preactx_w = tensor.dot(h_w_tm1, Ux_ww) * r_w + tensor.dot(h_c_t, Wx_cw) + tensor.dot(ctx_t, Wx_ctxw) + bx_w
# hidden state proposal
h_w = tensor.tanh(preactx_w)
# leaky integrate and obtain next hidden state
h_w_t = u_w * h_w_tm1 + (1. - u_w) * h_w
h_w_t = m_t[:, None] * h_w_t + (1. - m_t)[:, None] * h_w_tm1
return h_c_t, h_w_t, ctx_t, alpha.T
# prepare scan arguments
seqs = [mask, state_below_emb, state_belowx_emb, state_belowctx_emb]
shared_vars = [
tparams[_p(prefix, 'U_cc')],
tparams[_p(prefix, 'Ux_cc')],
tparams[_p(prefix, 'W_cw')],
tparams[_p(prefix, 'Wx_cw')],
tparams[_p(prefix, 'U_ww')],
tparams[_p(prefix, 'Ux_ww')],
tparams[_p(prefix, 'b_w')],
tparams[_p(prefix, 'bx_w')],
tparams[_p(prefix, 'W_ctxc')],
tparams[_p(prefix, 'Wx_ctxc')],
tparams[_p(prefix, 'W_ctxw')],
tparams[_p(prefix, 'Wx_ctxw')],
tparams[_p(prefix, 'Wdec_att')],
tparams[_p(prefix, 'U_att')],
tparams[_p(prefix, 'c_att')],
]
if one_step:
rval = _step(*(seqs+[init_state_char, init_state_word,
None, None,
proj_ctx, context]+shared_vars))
else:
rval, updates = theano.scan(_step,
sequences=seqs,
outputs_info=[
init_state_char,
init_state_word,
tensor.alloc(0., n_samples, context.shape[2]),
tensor.alloc(0., n_samples, context.shape[0])
],
non_sequences=[proj_ctx, context]+shared_vars,
name=_p(prefix, '_layers'),
n_steps=n_steps,
profile=profile,
strict=True)
return rval
def param_init_two_layer_gru_decoder_both(options, params,
prefix='two_layer_gru_decoder_both',
nin=None,
dim_char=None,
dim_word=None,
dimctx=None):
if nin is None:
nin = options['n_words']
if dim_char is None:
dim_char = options['dec_dim']
if dim_word is None:
dim_word = options['dec_dim']
if dimctx is None:
dimctx = options['enc_dim'] * 2
# embedding to gates transformation weights, biases
W_xc = numpy.concatenate([norm_weight(nin, dim_char),
norm_weight(nin, dim_char)], axis=1)
params[_p(prefix, 'W_xc')] = W_xc
params[_p(prefix, 'b_c')] = numpy.zeros((2 * dim_char,)).astype('float32')
# recurrent transformation weights for gates
U_cc = numpy.concatenate([ortho_weight(dim_char),
ortho_weight(dim_char)], axis=1)
params[_p(prefix, 'U_cc')] = U_cc
# embedding to hidden state proposal weights, biases
Wx_xc = norm_weight(nin, dim_char)
params[_p(prefix, 'Wx_xc')] = Wx_xc
params[_p(prefix, 'bx_c')] = numpy.zeros((dim_char,)).astype('float32')
# recurrent transformation weights for hidden state proposal
Ux_cc = ortho_weight(dim_char)
params[_p(prefix, 'Ux_cc')] = Ux_cc
# embedding to gates transformation weights, biases
W_cw = numpy.concatenate([norm_weight(dim_char, dim_word),
norm_weight(dim_char, dim_word)], axis=1)
params[_p(prefix, 'W_cw')] = W_cw
params[_p(prefix, 'b_w')] = numpy.zeros((2 * dim_word,)).astype('float32')
# recurrent transformation weights for gates
U_ww = numpy.concatenate([ortho_weight(dim_word),
ortho_weight(dim_word)], axis=1)
params[_p(prefix, 'U_ww')] = U_ww
# embedding to hidden state proposal weights, biases
Wx_cw = norm_weight(dim_char, dim_word)
params[_p(prefix, 'Wx_cw')] = Wx_cw
params[_p(prefix, 'bx_w')] = numpy.zeros((dim_word,)).astype('float32')
# recurrent transformation weights for hidden state proposal
Ux_ww = ortho_weight(dim_word)
params[_p(prefix, 'Ux_ww')] = Ux_ww
# context to GRU gates: char-level
W_ctxc = numpy.concatenate([norm_weight(dimctx, dim_char),
norm_weight(dimctx, dim_char)], axis=1)
params[_p(prefix, 'W_ctxc')] = W_ctxc
# context to hidden proposal: char-level
Wx_ctxc = norm_weight(dimctx, dim_char)
params[_p(prefix, 'Wx_ctxc')] = Wx_ctxc
# context to GRU gates: word-level
W_ctxw = numpy.concatenate([norm_weight(dimctx, dim_word),
norm_weight(dimctx, dim_word)], axis=1)
params[_p(prefix, 'W_ctxw')] = W_ctxw
# context to hidden proposal: word-level
Wx_ctxw = norm_weight(dimctx, dim_word)
params[_p(prefix, 'Wx_ctxw')] = Wx_ctxw
# attention: prev -> hidden
Winp_att = norm_weight(nin, dimctx)
params[_p(prefix, 'Winp_att')] = Winp_att
# attention: context -> hidden
Wctx_att = norm_weight(dimctx)
params[_p(prefix, 'Wctx_att')] = Wctx_att
# attention: decoder -> hidden
Wdecc_att = norm_weight(dim_char, dimctx)
params[_p(prefix, 'Wdecc_att')] = Wdecc_att
Wdecw_att = norm_weight(dim_word, dimctx)
params[_p(prefix, 'Wdecw_att')] = Wdecw_att
# attention: hidden bias
params[_p(prefix, 'b_att')] = numpy.zeros((dimctx,)).astype('float32')
# 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_att')] = c_att
return params
def two_layer_gru_decoder_both(tparams, state_below, options,
prefix='two_layer_gru_decoder_both',
mask=None, one_step=False,
context=None, context_mask=None,
init_state_char=None, init_state_word=None,
**kwargs):
assert context, 'Context must be provided'
assert context.ndim == 3, \
'Context must be 3-D: #annotation x #sample x #dim'
if one_step:
assert init_state_char, 'previous state must be provided'
assert init_state_word, 'previous state must be provided'
n_steps = state_below.shape[0]
if state_below.ndim in [2, 3]: