-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
gru.py
2111 lines (1788 loc) · 125 KB
/
gru.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
# Copyright 2016 Johns Hopkins University (Dan Povey)
# 2017 Gaofeng Cheng (UCAS)
# 2017 Lu Huang (THU)
# 2018 Hang Lyu
# Apache 2.0.
""" This module has the implementations of different GRU layers.
"""
from __future__ import print_function
import math
import re
import sys
from libs.nnet3.xconfig.basic_layers import XconfigLayerBase
# This class is for lines like
# 'gru-layer name=gru1 input=[-1] delay=-3'
# It generates an GRU sub-graph without output projections.
# The output dimension of the layer may be specified via 'cell-dim=xxx', but if not specified,
# the dimension defaults to the same as the input.
# See other configuration values below.
# decay-time is deprecated under GRU or PGRU, as I found the PGRUs do not need the decay-time option to get generalized to unseen sequence length
#
# Parameters of the class, and their defaults:
# input='[-1]' [Descriptor giving the input of the layer.]
# cell-dim=-1 [Dimension of the cell]
# delay=-1 [Delay in the recurrent connections of the GRU/LSTM ]
# clipping-threshold=30 [similar to LSTMs ,nnet3 GRUs use a gradient clipping component at the recurrent connections.
# This is the threshold used to decide if clipping has to be activated ]
# zeroing-interval=20 [interval at which we (possibly) zero out the recurrent derivatives.]
# zeroing-threshold=15 [We only zero out the derivs every zeroing-interval, if derivs exceed this value.]
# self-repair-scale-nonlinearity=1e-5 [It is a constant scaling the self-repair vector computed in derived classes of NonlinearComponent]
# i.e., SigmoidComponent, TanhComponent and RectifiedLinearComponent ]
# ng-per-element-scale-options='' [Additional options used for the diagonal matrices in the GRU/LSTM ]
# ng-affine-options='' [Additional options used for the full matrices in the GRU/LSTM, can be used to do things like set biases to initialize to 1]
class XconfigGruLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names = None):
assert first_token == "gru-layer"
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input':'[-1]',
'cell-dim' : -1, # this is a compulsory argument
'clipping-threshold' : 30.0,
'delay' : -1,
'ng-per-element-scale-options' : ' max-change=0.75',
'ng-affine-options' : ' max-change=0.75 ',
'self-repair-scale-nonlinearity' : 0.00001,
'zeroing-interval' : 20,
'zeroing-threshold' : 15.0
}
def set_derived_configs(self):
if self.config['cell-dim'] <= 0:
self.config['cell-dim'] = self.descriptors['input']['dim']
def check_configs(self):
key = 'cell-dim'
if self.config['cell-dim'] <= 0:
raise RuntimeError("cell-dim has invalid value {0}.".format(self.config[key]))
if self.config['delay'] == 0:
raise RuntimeError("delay cannot be zero")
for key in ['self-repair-scale-nonlinearity']:
if self.config[key] < 0.0 or self.config[key] > 1.0:
raise RuntimeError("{0} has invalid value {1}.".format(key, self.config[key]))
def output_name(self, auxiliary_output = None):
node_name = 's_t'
return '{0}.{1}'.format(self.name, node_name)
def output_dim(self, auxiliary_output = None):
return self.config['cell-dim']
def get_full_config(self):
ans = []
config_lines = self.generate_gru_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in LSTM initialization
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
# convenience function to generate the GRU config
def generate_gru_config(self):
# assign some variables to reduce verbosity
name = self.name
# in the below code we will just call descriptor_strings as descriptors for conciseness
input_dim = self.descriptors['input']['dim']
input_descriptor = self.descriptors['input']['final-string']
cell_dim = self.config['cell-dim']
delay = self.config['delay']
bptrunc_str = ("clipping-threshold={0}"
" zeroing-threshold={1}"
" zeroing-interval={2}"
" recurrence-interval={3}"
"".format(self.config['clipping-threshold'],
self.config['zeroing-threshold'],
self.config['zeroing-interval'], abs(delay)))
repair_nonlin = self.config['self-repair-scale-nonlinearity']
repair_nonlin_str = "self-repair-scale={0:.10f}".format(repair_nonlin) if repair_nonlin is not None else ''
affine_str = self.config['ng-affine-options']
# Natural gradient per element scale parameters
# TODO: decide if we want to keep exposing these options
ng_per_element_scale_options = self.config['ng-per-element-scale-options']
if re.search('param-mean', ng_per_element_scale_options) is None and \
re.search('param-stddev', ng_per_element_scale_options) is None:
ng_per_element_scale_options += " param-mean=0.0 param-stddev=1.0 "
pes_str = ng_per_element_scale_options
# formulation like:
# z_t = \sigmoid ( x_t * U^z + h_{t-1} * W^z ) // update gate
# r_t = \sigmoid ( x_t * U^r + h_{t-1} * W^r ) // reset gate
# \tilde{h}_t = \tanh ( x_t * U^h + ( h_{t-1} \dot r_t ) * W^h )
# h_t = ( 1 - z_t ) \dot \tilde{h}_t + z_t \dot h_{t-1}
# y_t = h_t // y_t is the output
configs = []
configs.append("# Update gate control : W_z* matrics")
configs.append("component name={0}.W_z.xs_z type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + cell_dim, cell_dim, affine_str))
configs.append("# Reset gate control : W_r* matrics")
configs.append("component name={0}.W_z.xs_r type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + cell_dim, cell_dim, affine_str))
configs.append("# h related matrix : W_h* matrics")
configs.append("component name={0}.W_h.UW type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + cell_dim, cell_dim , affine_str))
configs.append("# Defining the non-linearities")
configs.append("component name={0}.z type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.r type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.h type=TanhComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("# Defining the components for other cell computations")
configs.append("component name={0}.h1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y2 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y type=NoOpComponent dim={1}".format(name, cell_dim))
recurrent_connection = '{0}.s_t'.format(name)
configs.append("# z_t")
configs.append("component-node name={0}.z_t_pre component={0}.W_z.xs_z input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.z_t component={0}.z input={0}.z_t_pre".format(name))
configs.append("# r_t")
configs.append("component-node name={0}.r_t_pre component={0}.W_z.xs_r input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.r_t component={0}.r input={0}.r_t_pre".format(name))
configs.append("# h_t")
configs.append("component-node name={0}.h1_t component={0}.h1 input=Append({0}.r_t, IfDefined(Offset({1}, {2})))".format(name, recurrent_connection, delay))
configs.append("component-node name={0}.h_t_pre component={0}.W_h.UW input=Append({1}, {0}.h1_t)".format(name, input_descriptor))
configs.append("component-node name={0}.h_t component={0}.h input={0}.h_t_pre".format(name))
configs.append("# y_t")
configs.append("# The following two lines are to implement (1 - z_t)")
configs.append("component-node name={0}.y1_t component={0}.y1 input=Append({0}.h_t, Sum(Scale(-1.0,{0}.z_t), Const(1.0, {1})))".format(name, cell_dim))
configs.append("component-node name={0}.y2_t component={0}.y2 input=Append(IfDefined(Offset({1}, {2})), {0}.z_t)".format(name, recurrent_connection, delay))
configs.append("component-node name={0}.y_t component={0}.y input=Sum({0}.y1_t, {0}.y2_t)".format(name))
configs.append("# s_t : recurrence")
configs.append("component name={0}.s_r type=BackpropTruncationComponent dim={1} {2}".format(name, cell_dim, bptrunc_str))
configs.append("# s_t will be output and recurrence")
configs.append("component-node name={0}.s_t component={0}.s_r input={0}.y_t".format(name))
return configs
# This class is for lines like
# 'pgru-layer name=pgru1 input=[-1] delay=-3'
# It generates an PGRU sub-graph with output projections. It can also generate
# outputs without projection, but you could use the XconfigGruLayer for this
# simple RNN.
# The output dimension of the layer may be specified via 'cell-dim=xxx', but if not specified,
# the dimension defaults to the same as the input.
# See other configuration values below.
#
# Parameters of the class, and their defaults:
# input='[-1]' [Descriptor giving the input of the layer.]
# cell-dim=-1 [Dimension of the cell]
# recurrent-projection-dim [Dimension of the projection used in recurrent connections, e.g. cell-dim/4]
# non-recurrent-projection-dim [Dimension of the projection in non-recurrent connections,
# in addition to recurrent-projection-dim, e.g. cell-dim/4]
# delay=-1 [Delay in the recurrent connections of the GRU ]
# clipping-threshold=30 [nnet3 GRU use a gradient clipping component at the recurrent connections.
# This is the threshold used to decide if clipping has to be activated ]
# zeroing-interval=20 [interval at which we (possibly) zero out the recurrent derivatives.]
# zeroing-threshold=15 [We only zero out the derivs every zeroing-interval, if derivs exceed this value.]
# self-repair-scale-nonlinearity=1e-5 [It is a constant scaling the self-repair vector computed in derived classes of NonlinearComponent]
# i.e., SigmoidComponent, TanhComponent and RectifiedLinearComponent ]
# ng-per-element-scale-options='' [Additional options used for the diagonal matrices in the GRU ]
# ng-affine-options='' [Additional options used for the full matrices in the GRU, can be used to do things like set biases to initialize to 1]
class XconfigPgruLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names = None):
assert first_token == "pgru-layer"
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input' : '[-1]',
'cell-dim' : -1, # this is a compulsory argument
'recurrent-projection-dim' : -1, # defaults to cell-dim / 4
'non-recurrent-projection-dim' : -1, # defaults to
# recurrent-projection-dim
'clipping-threshold' : 30.0,
'delay' : -1,
'ng-per-element-scale-options' : ' max-change=0.75 ',
'ng-affine-options' : ' max-change=0.75 ',
'self-repair-scale-nonlinearity' : 0.00001,
'zeroing-interval' : 20,
'zeroing-threshold' : 15.0
}
def set_derived_configs(self):
if self.config['recurrent-projection-dim'] <= 0:
self.config['recurrent-projection-dim'] = self.config['cell-dim'] / 4
if self.config['non-recurrent-projection-dim'] <= 0:
self.config['non-recurrent-projection-dim'] = \
self.config['recurrent-projection-dim']
def check_configs(self):
for key in ['cell-dim', 'recurrent-projection-dim',
'non-recurrent-projection-dim']:
if self.config[key] <= 0:
raise RuntimeError("{0} has invalid value {1}.".format(
key, self.config[key]))
if self.config['delay'] == 0:
raise RuntimeError("delay cannot be zero")
if (self.config['recurrent-projection-dim'] +
self.config['non-recurrent-projection-dim'] >
self.config['cell-dim']):
raise RuntimeError("recurrent+non-recurrent projection dim exceeds "
"cell dim.")
for key in ['self-repair-scale-nonlinearity']:
if self.config[key] < 0.0 or self.config[key] > 1.0:
raise RuntimeError("{0} has invalid value {2}."
.format(self.layer_type, key,
self.config[key]))
def auxiliary_outputs(self):
return ['h_t']
def output_name(self, auxiliary_output = None):
node_name = 'sn_t'
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
node_name = auxiliary_output
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return '{0}.{1}'.format(self.name, node_name)
def output_dim(self, auxiliary_output = None):
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
if node_name == 'c_t':
return self.config['cell-dim']
# add code for other auxiliary_outputs here when we decide to expose them
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return self.config['recurrent-projection-dim'] + self.config['non-recurrent-projection-dim']
def get_full_config(self):
ans = []
config_lines = self.generate_pgru_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in LSTM initialization
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
# convenience function to generate the PGRU config
def generate_pgru_config(self):
# assign some variables to reduce verbosity
name = self.name
# in the below code we will just call descriptor_strings as descriptors for conciseness
input_dim = self.descriptors['input']['dim']
input_descriptor = self.descriptors['input']['final-string']
cell_dim = self.config['cell-dim']
rec_proj_dim = self.config['recurrent-projection-dim']
nonrec_proj_dim = self.config['non-recurrent-projection-dim']
delay = self.config['delay']
repair_nonlin = self.config['self-repair-scale-nonlinearity']
repair_nonlin_str = "self-repair-scale={0:.10f}".format(repair_nonlin) if repair_nonlin is not None else ''
bptrunc_str = ("clipping-threshold={0}"
" zeroing-threshold={1}"
" zeroing-interval={2}"
" recurrence-interval={3}"
"".format(self.config['clipping-threshold'],
self.config['zeroing-threshold'],
self.config['zeroing-interval'],
abs(delay)))
affine_str = self.config['ng-affine-options']
pes_str = self.config['ng-per-element-scale-options']
# Natural gradient per element scale parameters
# TODO: decide if we want to keep exposing these options
if re.search('param-mean', pes_str) is None and \
re.search('param-stddev', pes_str) is None:
pes_str += " param-mean=0.0 param-stddev=1.0 "
# formulation like:
# z_t = \sigmoid ( x_t * U^z + s_{t-1} * W^z ) // update gate
# r_t = \sigmoid ( x_t * U^r + s_{t-1} * W^r ) // reset gate
# \tilde{h}_t = \tanh ( x_t * U^h + ( s_{t-1} \dot r_t ) * W^h )
# h_t = ( 1 - z_t ) \dot \tilde{h}_t + z_t \dot h_{t-1}
# y_t = h_t * W^y
# s_t = y_t (0:rec_proj_dim-1)
configs = []
configs.append("# Update gate control : W_z* matrics")
configs.append("component name={0}.W_z.xs_z type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str))
configs.append("# Reset gate control : W_r* matrics")
configs.append("component name={0}.W_z.xs_r type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, rec_proj_dim, affine_str))
configs.append("# h related matrix : W_h* matrics")
configs.append("component name={0}.W_h.UW type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim , affine_str))
configs.append("# Defining the non-linearities")
configs.append("component name={0}.z type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.r type=SigmoidComponent dim={1} {2}".format(name, rec_proj_dim, repair_nonlin_str))
configs.append("component name={0}.h type=TanhComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("# Defining the components for other cell computations")
configs.append("component name={0}.h1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * rec_proj_dim, rec_proj_dim))
configs.append("component name={0}.y1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y2 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y type=NoOpComponent dim={1}".format(name, cell_dim))
recurrent_connection = '{0}.s_t'.format(name)
recurrent_connection_y = '{0}.y_t'.format(name)
configs.append("# z_t")
configs.append("component-node name={0}.z_t_pre component={0}.W_z.xs_z input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.z_t component={0}.z input={0}.z_t_pre".format(name))
configs.append("# r_t")
configs.append("component-node name={0}.r_t_pre component={0}.W_z.xs_r input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.r_t component={0}.r input={0}.r_t_pre".format(name))
configs.append("# h_t")
configs.append("component-node name={0}.h1_t component={0}.h1 input=Append({0}.r_t, IfDefined(Offset({1}, {2})))".format(name, recurrent_connection, delay))
configs.append("component-node name={0}.h_t_pre component={0}.W_h.UW input=Append({1}, {0}.h1_t)".format(name, input_descriptor))
configs.append("component-node name={0}.h_t component={0}.h input={0}.h_t_pre".format(name))
configs.append("component-node name={0}.y1_t component={0}.y1 input=Append({0}.h_t, Sum(Scale(-1.0,{0}.z_t), Const(1.0, {1})))".format(name, cell_dim))
configs.append("component-node name={0}.y2_t component={0}.y2 input=Append(IfDefined(Offset({1}, {2})), {0}.z_t)".format(name, recurrent_connection_y, delay))
configs.append("component-node name={0}.y_t component={0}.y input=Sum({0}.y1_t, {0}.y2_t)".format(name))
configs.append("# s_t recurrent")
configs.append("component name={0}.W_s.ys type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, cell_dim, rec_proj_dim + nonrec_proj_dim, affine_str))
configs.append("component name={0}.s_r type=BackpropTruncationComponent dim={1} {2}".format(name, rec_proj_dim, bptrunc_str))
configs.append("# s_t and n_t : sn_t will be the output")
configs.append("component-node name={0}.sn_t component={0}.W_s.ys input={0}.y_t".format(name))
configs.append("dim-range-node name={0}.s_t_preclip input-node={0}.sn_t dim-offset=0 dim={1}".format(name, rec_proj_dim))
configs.append("component-node name={0}.s_t component={0}.s_r input={0}.s_t_preclip".format(name))
return configs
# This class is for lines like
# 'norm-pgru-layer name=norm-pgru1 input=[-1] delay=-3'
# Different from the vanilla PGRU, the NormPGRU uses batchnorm in the forward direction
# and renorm in the recurrence.
# The output dimension of the layer may be specified via 'cell-dim=xxx', but if not specified,
# the dimension defaults to the same as the input.
# See other configuration values below.
#
# Parameters of the class, and their defaults:
# input='[-1]' [Descriptor giving the input of the layer.]
# cell-dim=-1 [Dimension of the cell]
# recurrent-projection-dim [Dimension of the projection used in recurrent connections, e.g. cell-dim/4]
# non-recurrent-projection-dim [Dimension of the projection in non-recurrent connections,
# in addition to recurrent-projection-dim, e.g. cell-dim/4]
# delay=-1 [Delay in the recurrent connections of the GRU ]
# clipping-threshold=30 [nnet3 GRU use a gradient clipping component at the recurrent connections.
# This is the threshold used to decide if clipping has to be activated ]
# zeroing-interval=20 [interval at which we (possibly) zero out the recurrent derivatives.]
# zeroing-threshold=15 [We only zero out the derivs every zeroing-interval, if derivs exceed this value.]
# self-repair-scale-nonlinearity=1e-5 [It is a constant scaling the self-repair vector computed in derived classes of NonlinearComponent]
# i.e., SigmoidComponent, TanhComponent and RectifiedLinearComponent ]
# ng-per-element-scale-options='' [Additional options used for the diagonal matrices in the GRU ]
# ng-affine-options='' [Additional options used for the full matrices in the GRU, can be used to do things like set biases to initialize to 1]
class XconfigNormPgruLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names = None):
assert first_token == "norm-pgru-layer"
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input' : '[-1]',
'cell-dim' : -1, # this is a compulsory argument
'recurrent-projection-dim' : -1, # defaults to cell-dim / 4
'non-recurrent-projection-dim' : -1, # defaults to
# recurrent-projection-dim
'clipping-threshold' : 30.0,
'delay' : -1,
'ng-per-element-scale-options' : ' max-change=0.75 ',
'ng-affine-options' : ' max-change=0.75 ',
'self-repair-scale-nonlinearity' : 0.00001,
'zeroing-interval' : 20,
'zeroing-threshold' : 15.0,
'dropout-proportion' : -1.0, # If -1.0, no dropout components will be added
'dropout-per-frame' : True # If False, regular dropout, not per frame.
}
def set_derived_configs(self):
if self.config['recurrent-projection-dim'] <= 0:
self.config['recurrent-projection-dim'] = self.config['cell-dim'] / 4
if self.config['non-recurrent-projection-dim'] <= 0:
self.config['non-recurrent-projection-dim'] = \
self.config['recurrent-projection-dim']
def check_configs(self):
for key in ['cell-dim', 'recurrent-projection-dim',
'non-recurrent-projection-dim']:
if self.config[key] <= 0:
raise RuntimeError("{0} has invalid value {1}.".format(
key, self.config[key]))
if self.config['delay'] == 0:
raise RuntimeError("delay cannot be zero")
if (self.config['recurrent-projection-dim'] +
self.config['non-recurrent-projection-dim'] >
self.config['cell-dim']):
raise RuntimeError("recurrent+non-recurrent projection dim exceeds "
"cell dim.")
for key in ['self-repair-scale-nonlinearity']:
if self.config[key] < 0.0 or self.config[key] > 1.0:
raise RuntimeError("{0} has invalid value {2}."
.format(self.layer_type, key,
self.config[key]))
if ((self.config['dropout-proportion'] > 1.0 or
self.config['dropout-proportion'] < 0.0) and
self.config['dropout-proportion'] != -1.0 ):
raise RuntimeError("dropout-proportion has invalid value {0}."
.format(self.config['dropout-proportion']))
def auxiliary_outputs(self):
return ['h_t']
def output_name(self, auxiliary_output = None):
node_name = 'sn_t'
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
node_name = auxiliary_output
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return '{0}.{1}'.format(self.name, node_name)
def output_dim(self, auxiliary_output = None):
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
if node_name == 'h_t':
return self.config['cell-dim']
# add code for other auxiliary_outputs here when we decide to expose them
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return self.config['recurrent-projection-dim'] + self.config['non-recurrent-projection-dim']
def get_full_config(self):
ans = []
config_lines = self.generate_pgru_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in LSTM initialization
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
# convenience function to generate the Norm-PGRU config
def generate_pgru_config(self):
# assign some variables to reduce verbosity
name = self.name
# in the below code we will just call descriptor_strings as descriptors for conciseness
input_dim = self.descriptors['input']['dim']
input_descriptor = self.descriptors['input']['final-string']
cell_dim = self.config['cell-dim']
rec_proj_dim = self.config['recurrent-projection-dim']
nonrec_proj_dim = self.config['non-recurrent-projection-dim']
delay = self.config['delay']
repair_nonlin = self.config['self-repair-scale-nonlinearity']
repair_nonlin_str = "self-repair-scale={0:.10f}".format(repair_nonlin) if repair_nonlin is not None else ''
bptrunc_str = ("clipping-threshold={0}"
" zeroing-threshold={1}"
" zeroing-interval={2}"
" recurrence-interval={3}"
"".format(self.config['clipping-threshold'],
self.config['zeroing-threshold'],
self.config['zeroing-interval'],
abs(delay)))
affine_str = self.config['ng-affine-options']
pes_str = self.config['ng-per-element-scale-options']
dropout_proportion = self.config['dropout-proportion']
dropout_per_frame = 'true' if self.config['dropout-per-frame'] else 'false'
# Natural gradient per element scale parameters
# TODO: decide if we want to keep exposing these options
if re.search('param-mean', pes_str) is None and \
re.search('param-stddev', pes_str) is None:
pes_str += " param-mean=0.0 param-stddev=1.0 "
# formulation like:
# z_t = \sigmoid ( x_t * U^z + s_{t-1} * W^z ) // update gate
# r_t = \sigmoid ( x_t * U^r + s_{t-1} * W^r ) // reset gate
# \tilde{h}_t = \tanh ( x_t * U^h + ( s_{t-1} \dot r_t ) * W^h )
# h_t = ( 1 - z_t ) \dot \tilde{h}_t + z_t \dot h_{t-1}
# y_t_tmp = h_t * W^y
# s_t = renorm ( y_t_tmp (0:rec_proj_dim-1) )
# y_t = batchnorm ( y_t_tmp )
configs = []
configs.append("# Update gate control : W_z* matrics")
configs.append("component name={0}.W_z.xs_z type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str))
configs.append("# Reset gate control : W_r* matrics")
configs.append("component name={0}.W_z.xs_r type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, rec_proj_dim, affine_str))
configs.append("# h related matrix : W_h* matrics")
configs.append("component name={0}.W_h.UW type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim , affine_str))
if dropout_proportion != -1.0:
configs.append("component name={0}.dropout_z type=DropoutComponent dim={1} "
"dropout-proportion={2} dropout-per-frame={3}"
.format(name, cell_dim, dropout_proportion, dropout_per_frame))
configs.append("component name={0}.dropout_r type=DropoutComponent dim={1} "
"dropout-proportion={2} dropout-per-frame={3}"
.format(name, rec_proj_dim, dropout_proportion, dropout_per_frame))
configs.append("# Defining the non-linearities")
configs.append("component name={0}.z type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.r type=SigmoidComponent dim={1} {2}".format(name, rec_proj_dim, repair_nonlin_str))
configs.append("component name={0}.h type=TanhComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("# Defining the components for other cell computations")
configs.append("component name={0}.h1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * rec_proj_dim, rec_proj_dim))
configs.append("component name={0}.y1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y2 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y type=NoOpComponent dim={1}".format(name, cell_dim))
recurrent_connection = '{0}.s_t'.format(name)
recurrent_connection_y = '{0}.y_t'.format(name)
configs.append("# z_t")
configs.append("component-node name={0}.z_t_pre component={0}.W_z.xs_z input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
if dropout_proportion != -1.0:
configs.append("component-node name={0}.z_predrop_t component={0}.z input={0}.z_t_pre".format(name))
configs.append("component-node name={0}.z_t component={0}.dropout_z input={0}.z_predrop_t".format(name))
else:
configs.append("component-node name={0}.z_t component={0}.z input={0}.z_t_pre".format(name, input_descriptor, recurrent_connection, delay))
configs.append("# r_t")
configs.append("component-node name={0}.r_t_pre component={0}.W_z.xs_r input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
if dropout_proportion != -1.0:
configs.append("component-node name={0}.r_predrop_t component={0}.r input={0}.r_t_pre".format(name))
configs.append("component-node name={0}.r_t component={0}.dropout_r input={0}.r_predrop_t".format(name))
else:
configs.append("component-node name={0}.r_t component={0}.r input={0}.r_t_pre".format(name))
configs.append("# h_t")
configs.append("component-node name={0}.h1_t component={0}.h1 input=Append({0}.r_t, IfDefined(Offset({1}, {2})))".format(name, recurrent_connection, delay))
configs.append("component-node name={0}.h_t_pre component={0}.W_h.UW input=Append({1}, {0}.h1_t)".format(name, input_descriptor))
configs.append("component-node name={0}.h_t component={0}.h input={0}.h_t_pre".format(name))
configs.append("component-node name={0}.y1_t component={0}.y1 input=Append({0}.h_t, Sum(Scale(-1.0,{0}.z_t), Const(1.0, {1})))".format(name, cell_dim))
configs.append("component-node name={0}.y2_t component={0}.y2 input=Append(IfDefined(Offset({1}, {2})), {0}.z_t)".format(name, recurrent_connection_y, delay))
configs.append("component-node name={0}.y_t component={0}.y input=Sum({0}.y1_t, {0}.y2_t)".format(name))
configs.append("# s_t recurrent")
configs.append("component name={0}.W_s.ys type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, cell_dim, rec_proj_dim + nonrec_proj_dim, affine_str))
configs.append("component name={0}.s_r type=BackpropTruncationComponent dim={1} {2}".format(name, rec_proj_dim, bptrunc_str))
configs.append("component name={0}.batchnorm type=BatchNormComponent dim={1} target-rms=1.0".format(name, rec_proj_dim + nonrec_proj_dim))
configs.append("component name={0}.renorm type=NormalizeComponent dim={1} target-rms=1.0".format(name, rec_proj_dim))
configs.append("# s_t and n_t : sn_t will be the output")
configs.append("component-node name={0}.sn_nobatchnorm_t component={0}.W_s.ys input={0}.y_t".format(name))
configs.append("dim-range-node name={0}.s_t_preclip input-node={0}.sn_nobatchnorm_t dim-offset=0 dim={1}".format(name, rec_proj_dim))
configs.append("component-node name={0}.sn_t component={0}.batchnorm input={0}.sn_nobatchnorm_t".format(name))
configs.append("component-node name={0}.s_renorm_t component={0}.renorm input={0}.s_t_preclip".format(name))
configs.append("component-node name={0}.s_t component={0}.s_r input={0}.s_renorm_t".format(name))
return configs
# This class is for lines like
# 'opgru-layer name=opgru1 input=[-1] delay=-3'
# It generates an OPGRU sub-graph with output projections.
# The output dimension of the layer may be specified via 'cell-dim=xxx', but if not specified,
# the dimension defaults to the same as the input.
# See other configuration values below.
#
# Parameters of the class, and their defaults:
# input='[-1]' [Descriptor giving the input of the layer.]
# cell-dim=-1 [Dimension of the cell]
# recurrent-projection-dim [Dimension of the projection used in recurrent connections, e.g. cell-dim/4]
# non-recurrent-projection-dim [Dimension of the projection in non-recurrent connections,
# in addition to recurrent-projection-dim, e.g. cell-dim/4]
# delay=-1 [Delay in the recurrent connections of the GRU ]
# clipping-threshold=30 [nnet3 GRU use a gradient clipping component at the recurrent connections.
# This is the threshold used to decide if clipping has to be activated ]
# zeroing-interval=20 [interval at which we (possibly) zero out the recurrent derivatives.]
# zeroing-threshold=15 [We only zero out the derivs every zeroing-interval, if derivs exceed this value.]
# self-repair-scale-nonlinearity=1e-5 [It is a constant scaling the self-repair vector computed in derived classes of NonlinearComponent]
# i.e., SigmoidComponent, TanhComponent and RectifiedLinearComponent ]
# ng-per-element-scale-options='' [Additional options used for the diagonal matrices in the GRU ]
# ng-affine-options='' [Additional options used for the full matrices in the GRU, can be used to do things like set biases to initialize to 1]
class XconfigOpgruLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names = None):
assert first_token == "opgru-layer"
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input' : '[-1]',
'cell-dim' : -1, # this is a compulsory argument
'recurrent-projection-dim' : -1, # defaults to cell-dim / 4
'non-recurrent-projection-dim' : -1, # defaults to
# recurrent-projection-dim
'clipping-threshold' : 30.0,
'delay' : -1,
'ng-per-element-scale-options' : ' max-change=0.75 ',
'ng-affine-options' : ' max-change=0.75 ',
'self-repair-scale-nonlinearity' : 0.00001,
'zeroing-interval' : 20,
'zeroing-threshold' : 15.0
}
def set_derived_configs(self):
if self.config['recurrent-projection-dim'] <= 0:
self.config['recurrent-projection-dim'] = self.config['cell-dim'] / 4
if self.config['non-recurrent-projection-dim'] <= 0:
self.config['non-recurrent-projection-dim'] = \
self.config['recurrent-projection-dim']
def check_configs(self):
for key in ['cell-dim', 'recurrent-projection-dim',
'non-recurrent-projection-dim']:
if self.config[key] <= 0:
raise RuntimeError("{0} has invalid value {1}.".format(
key, self.config[key]))
if self.config['delay'] == 0:
raise RuntimeError("delay cannot be zero")
if (self.config['recurrent-projection-dim'] +
self.config['non-recurrent-projection-dim'] >
self.config['cell-dim']):
raise RuntimeError("recurrent+non-recurrent projection dim exceeds "
"cell dim.")
for key in ['self-repair-scale-nonlinearity']:
if self.config[key] < 0.0 or self.config[key] > 1.0:
raise RuntimeError("{0} has invalid value {2}."
.format(self.layer_type, key,
self.config[key]))
def auxiliary_outputs(self):
return ['h_t']
def output_name(self, auxiliary_output = None):
node_name = 'sn_t'
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
node_name = auxiliary_output
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return '{0}.{1}'.format(self.name, node_name)
def output_dim(self, auxiliary_output = None):
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
if node_name == 'c_t':
return self.config['cell-dim']
# add code for other auxiliary_outputs here when we decide to expose them
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return self.config['recurrent-projection-dim'] + self.config['non-recurrent-projection-dim']
def get_full_config(self):
ans = []
config_lines = self.generate_pgru_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in LSTM initialization
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
# convenience function to generate the OPGRU config
def generate_pgru_config(self):
# assign some variables to reduce verbosity
name = self.name
# in the below code we will just call descriptor_strings as descriptors for conciseness
input_dim = self.descriptors['input']['dim']
input_descriptor = self.descriptors['input']['final-string']
cell_dim = self.config['cell-dim']
rec_proj_dim = self.config['recurrent-projection-dim']
nonrec_proj_dim = self.config['non-recurrent-projection-dim']
delay = self.config['delay']
repair_nonlin = self.config['self-repair-scale-nonlinearity']
repair_nonlin_str = "self-repair-scale={0:.10f}".format(repair_nonlin) if repair_nonlin is not None else ''
bptrunc_str = ("clipping-threshold={0}"
" zeroing-threshold={1}"
" zeroing-interval={2}"
" recurrence-interval={3}"
"".format(self.config['clipping-threshold'],
self.config['zeroing-threshold'],
self.config['zeroing-interval'],
abs(delay)))
affine_str = self.config['ng-affine-options']
pes_str = self.config['ng-per-element-scale-options']
# Natural gradient per element scale parameters
# TODO: decide if we want to keep exposing these options
if re.search('param-mean', pes_str) is None and \
re.search('param-stddev', pes_str) is None:
pes_str += " param-mean=0.0 param-stddev=1.0 "
# formulation for OPGRU like:
# z_t = \sigmoid ( x_t * U^z + s_{t-1} * W^z ) // update gate
# o_t = \sigmoid ( x_t * U^o + s_{t-1} * W^o ) // output gate
# \tilde{h}_t = \tanh ( x_t * U^h + h_{t-1} \dot W^h ) // W^h is learnable vector
# h_t = ( 1 - z_t ) \dot \tilde{h}_t + z_t \dot h_{t-1}
# y_t = (y_t \dot o_t) * W^y
# s_t = y_t(0:rec_proj_dim-1)
configs = []
configs.append("# Update gate control : W_z* matrics")
configs.append("component name={0}.W_z.xs_z type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str))
configs.append("# Output gate control : W_r* matrics")
configs.append("component name={0}.W_z.xs_o type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str))
configs.append("# h related matrix : W_h* matrics")
configs.append("component name={0}.W_h.UW type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, input_dim , cell_dim , affine_str))
configs.append("component name={0}.W_h.UW_elementwise type=NaturalGradientPerElementScaleComponent dim={1} {2}".format(name, cell_dim , pes_str))
configs.append("# Defining the non-linearities")
configs.append("component name={0}.z type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.o type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.h type=TanhComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("# Defining the components for other cell computations")
configs.append("component name={0}.o1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y2 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y type=NoOpComponent dim={1}".format(name, cell_dim))
recurrent_connection = '{0}.s_t'.format(name)
recurrent_connection_y = '{0}.y_t'.format(name)
configs.append("# z_t")
configs.append("component-node name={0}.z_t_pre component={0}.W_z.xs_z input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.z_t component={0}.z input={0}.z_t_pre".format(name))
configs.append("# o_t")
configs.append("component-node name={0}.o_t_pre component={0}.W_z.xs_o input=Append({1}, IfDefined(Offset({2}, {3})))".format(name, input_descriptor, recurrent_connection, delay))
configs.append("component-node name={0}.o_t component={0}.o input={0}.o_t_pre".format(name))
configs.append("# h_t")
configs.append("component-node name={0}.h_t_pre component={0}.W_h.UW input={1}".format(name, input_descriptor))
configs.append("component-node name={0}.h_t_pre2 component={0}.W_h.UW_elementwise input=IfDefined(Offset({1}, {2}))".format(name, recurrent_connection_y, delay))
configs.append("component-node name={0}.h_t component={0}.h input=Sum({0}.h_t_pre, {0}.h_t_pre2)".format(name))
configs.append("component-node name={0}.y1_t component={0}.y1 input=Append({0}.h_t, Sum(Scale(-1.0,{0}.z_t), Const(1.0, {1})))".format(name, cell_dim))
configs.append("component-node name={0}.y2_t component={0}.y2 input=Append(IfDefined(Offset({1}, {2})), {0}.z_t)".format(name, recurrent_connection_y, delay))
configs.append("component-node name={0}.y_t component={0}.y input=Sum({0}.y1_t, {0}.y2_t)".format(name))
configs.append("component-node name={0}.y_o_t component={0}.o1 input=Append({0}.o_t, {0}.y_t)".format(name))
configs.append("# s_t recurrent")
configs.append("component name={0}.W_s.ys type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3}".format(name, cell_dim, rec_proj_dim + nonrec_proj_dim, affine_str))
configs.append("component name={0}.s_r type=BackpropTruncationComponent dim={1} {2}".format(name, rec_proj_dim, bptrunc_str))
configs.append("# s_t and n_t : sn_t will be the output")
configs.append("component-node name={0}.sn_t component={0}.W_s.ys input={0}.y_o_t".format(name))
configs.append("dim-range-node name={0}.s_t_preclip input-node={0}.sn_t dim-offset=0 dim={1}".format(name, rec_proj_dim))
configs.append("component-node name={0}.s_t component={0}.s_r input={0}.s_t_preclip".format(name))
return configs
# This class is for lines like
# 'norm-opgru-layer name=norm-opgru1 input=[-1] delay=-3'
# It generates a norm-OPGRU sub-graph with output projections.
# Different from the vanilla OPGRU, the NormOPGRU uses batchnorm in the forward direction
# and renorm in the recurrence.
# The output dimension of the layer may be specified via 'cell-dim=xxx', but if not specified,
# the dimension defaults to the same as the input.
# See other configuration values below.
#
# Parameters of the class, and their defaults:
# input='[-1]' [Descriptor giving the input of the layer.]
# cell-dim=-1 [Dimension of the cell]
# recurrent-projection-dim [Dimension of the projection used in recurrent connections, e.g. cell-dim/4]
# non-recurrent-projection-dim [Dimension of the projection in non-recurrent connections,
# in addition to recurrent-projection-dim, e.g. cell-dim/4]
# delay=-1 [Delay in the recurrent connections of the GRU ]
# clipping-threshold=30 [nnet3 GRU use a gradient clipping component at the recurrent connections.
# This is the threshold used to decide if clipping has to be activated ]
# zeroing-interval=20 [interval at which we (possibly) zero out the recurrent derivatives.]
# zeroing-threshold=15 [We only zero out the derivs every zeroing-interval, if derivs exceed this value.]
# self-repair-scale-nonlinearity=1e-5 [It is a constant scaling the self-repair vector computed in derived classes of NonlinearComponent]
# i.e., SigmoidComponent, TanhComponent and RectifiedLinearComponent ]
# ng-per-element-scale-options='' [Additional options used for the diagonal matrices in the GRU ]
# ng-affine-options='' [Additional options used for the full matrices in the GRU, can be used to do things like set biases to initialize to 1]
class XconfigNormOpgruLayer(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names = None):
assert first_token == "norm-opgru-layer"
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input' : '[-1]',
'cell-dim' : -1, # this is a compulsory argument
'recurrent-projection-dim' : -1, # defaults to cell-dim / 4
'non-recurrent-projection-dim' : -1, # defaults to
# recurrent-projection-dim
'clipping-threshold' : 30.0,
'delay' : -1,
'ng-per-element-scale-options' : ' max-change=0.75 ',
'ng-affine-options' : ' max-change=0.75 ',
'self-repair-scale-nonlinearity' : 0.00001,
'zeroing-interval' : 20,
'zeroing-threshold' : 15.0,
'dropout-proportion' : -1.0, # If -1.0, no dropout components will be added
'l2-regularize': 0.0,
'dropout-per-frame' : True # If false, regular dropout, not per frame.
}
def set_derived_configs(self):
if self.config['recurrent-projection-dim'] <= 0:
self.config['recurrent-projection-dim'] = self.config['cell-dim'] / 4
if self.config['non-recurrent-projection-dim'] <= 0:
self.config['non-recurrent-projection-dim'] = \
self.config['recurrent-projection-dim']
def check_configs(self):
for key in ['cell-dim', 'recurrent-projection-dim',
'non-recurrent-projection-dim']:
if self.config[key] <= 0:
raise RuntimeError("{0} has invalid value {1}.".format(
key, self.config[key]))
if self.config['delay'] == 0:
raise RuntimeError("delay cannot be zero")
if (self.config['recurrent-projection-dim'] +
self.config['non-recurrent-projection-dim'] >
self.config['cell-dim']):
raise RuntimeError("recurrent+non-recurrent projection dim exceeds "
"cell dim.")
for key in ['self-repair-scale-nonlinearity']:
if self.config[key] < 0.0 or self.config[key] > 1.0:
raise RuntimeError("{0} has invalid value {2}."
.format(self.layer_type, key,
self.config[key]))
if ((self.config['dropout-proportion'] > 1.0 or
self.config['dropout-proportion'] < 0.0) and
self.config['dropout-proportion'] != -1.0 ):
raise RuntimeError("dropout-proportion has invalid value {0}."
.format(self.config['dropout-proportion']))
def auxiliary_outputs(self):
return ['h_t']
def output_name(self, auxiliary_output = None):
node_name = 'sn_t'
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
node_name = auxiliary_output
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return '{0}.{1}'.format(self.name, node_name)
def output_dim(self, auxiliary_output = None):
if auxiliary_output is not None:
if auxiliary_output in self.auxiliary_outputs():
if node_name == 'c_t':
return self.config['cell-dim']
# add code for other auxiliary_outputs here when we decide to expose them
else:
raise Exception("In {0} of type {1}, unknown auxiliary output name {1}".format(self.layer_type, auxiliary_output))
return self.config['recurrent-projection-dim'] + self.config['non-recurrent-projection-dim']
def get_full_config(self):
ans = []
config_lines = self.generate_pgru_config()
for line in config_lines:
for config_name in ['ref', 'final']:
# we do not support user specified matrices in LSTM initialization
# so 'ref' and 'final' configs are the same.
ans.append((config_name, line))
return ans
# convenience function to generate the Norm-OPGRU config
def generate_pgru_config(self):
# assign some variables to reduce verbosity
name = self.name
# in the below code we will just call descriptor_strings as descriptors for conciseness
input_dim = self.descriptors['input']['dim']
input_descriptor = self.descriptors['input']['final-string']
cell_dim = self.config['cell-dim']
rec_proj_dim = self.config['recurrent-projection-dim']
nonrec_proj_dim = self.config['non-recurrent-projection-dim']
delay = self.config['delay']
repair_nonlin = self.config['self-repair-scale-nonlinearity']
repair_nonlin_str = "self-repair-scale={0:.10f}".format(repair_nonlin) if repair_nonlin is not None else ''
bptrunc_str = ("clipping-threshold={0}"
" zeroing-threshold={1}"
" zeroing-interval={2}"
" recurrence-interval={3}"
"".format(self.config['clipping-threshold'],
self.config['zeroing-threshold'],
self.config['zeroing-interval'],
abs(delay)))
affine_str = self.config['ng-affine-options']
pes_str = self.config['ng-per-element-scale-options']
dropout_proportion = self.config['dropout-proportion']
dropout_per_frame = 'true' if self.config['dropout-per-frame'] else 'false'
l2_regularize = self.config['l2-regularize']
l2_regularize_option = ('l2-regularize={0} '.format(l2_regularize)
if l2_regularize != 0.0 else '')
# Natural gradient per element scale parameters
# TODO: decide if we want to keep exposing these options
if re.search('param-mean', pes_str) is None and \
re.search('param-stddev', pes_str) is None:
pes_str += " param-mean=0.0 param-stddev=1.0 "
# formulation for OPGRU like:
# z_t = \sigmoid ( x_t * U^z + s_{t-1} * W^z ) // update gate
# o_t = \sigmoid ( x_t * U^o + s_{t-1} * W^o ) // output gate
# \tilde{h}_t = \tanh ( x_t * U^h + h_{t-1} \dot W^h ) // W^h is learnable vector
# h_t = ( 1 - z_t ) \dot \tilde{h}_t + z_t \dot h_{t-1}
# y_t_tmp = ( h_t \dot o_t) * W^y
# s_t = renorm ( y_t_tmp(0:rec_proj_dim-1) )
# y_t = batchnorm ( y_t_tmp )
configs = []
configs.append("# Update gate control : W_z* matrics")
configs.append("component name={0}.W_z.xs_z type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3} {4}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str, l2_regularize_option))
configs.append("# Output gate control : W_r* matrics")
configs.append("component name={0}.W_z.xs_o type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3} {4}".format(name, input_dim + rec_proj_dim, cell_dim, affine_str, l2_regularize_option))
configs.append("# h related matrix : W_h* matrics")
configs.append("component name={0}.W_h.UW type=NaturalGradientAffineComponent input-dim={1} output-dim={2} {3} {4}".format(name, input_dim , cell_dim , affine_str, l2_regularize_option))
configs.append("component name={0}.W_h.UW_elementwise type=NaturalGradientPerElementScaleComponent dim={1} {2}".format(name, cell_dim , pes_str))
configs.append("# Defining the non-linearities")
configs.append("component name={0}.z type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.o type=SigmoidComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("component name={0}.h type=TanhComponent dim={1} {2}".format(name, cell_dim, repair_nonlin_str))
configs.append("# Defining the components for other cell computations")
configs.append("component name={0}.o1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y1 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y2 type=ElementwiseProductComponent input-dim={1} output-dim={2}".format(name, 2 * cell_dim, cell_dim))
configs.append("component name={0}.y type=NoOpComponent dim={1}".format(name, cell_dim))
if dropout_proportion != -1.0:
configs.append("component name={0}.dropout type=DropoutComponent dim={1} "
"dropout-proportion={2} dropout-per-frame={3}"
.format(name, cell_dim, dropout_proportion, dropout_per_frame))
recurrent_connection = '{0}.s_t'.format(name)
recurrent_connection_y = '{0}.y_t'.format(name)