/
rnn_cell.py
2506 lines (2133 loc) · 93.3 KB
/
rnn_cell.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
# Lint as: python2, python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""RNN cells (e.g., LSTM, GRU) that the Lingvo model uses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import lingvo.compat as tf
from lingvo.core import hyperparams
from lingvo.core import py_utils
from lingvo.core import quant_utils
from lingvo.core import summary_utils
from six.moves import range
from six.moves import zip
from tensorflow.python.util import deprecation as tf_deprecation # pylint: disable=g-direct-tensorflow-import
def _HistogramSummary(p, name, v):
"""Adds a histogram summary for 'v' into the default tf graph."""
summary_utils.histogram(name, tf.cast(v, tf.float32))
RNN_CELL_WT = 'rnn_cell_weight_variable'
class RNNCell(quant_utils.QuantizableLayer):
# pylint: disable=line-too-long
"""RNN cells.
RNNCell represents recurrent state in a `.NestedMap`.
`zero_state(theta, batch_size)` returns the initial state, which is defined
by each subclass. From the state, each subclass defines `GetOutput()`
to extract the output tensor.
`RNNCell.FProp` defines the forward function::
(theta, state0, inputs) -> state1, extras
All arguments and return values are `.NestedMap`. Each subclass defines
what fields these `.NestedMap` are expected to have. `extras` is a
`.NestedMap` containing some intermediate results `FProp` computes to
facilitate the backprop.
`zero_state(theta, batch_size)`, `state0` and `state1` are all compatible
`.NestedMap` (see `.NestedMap.IsCompatible`).
I.e., they have the same keys recursively. Furthermore, the corresponding
tensors in these `.NestedMap` have the same shape and dtype.
"""
# pylint: enable=line-too-long
@classmethod
def Params(cls):
p = super(RNNCell, cls).Params()
p.Define('inputs_arity', 1,
'number of tensors expected for the inputs.act to FProp.')
p.Define('num_input_nodes', 0, 'Number of input nodes.')
p.Define(
'num_output_nodes', 0,
'Number of output nodes. If num_hidden_nodes is 0, also used as '
'cell size.')
p.Define(
'reset_cell_state', False,
('Set True to support resetting cell state in scenarios where multiple '
'inputs are packed into a single training example. The RNN layer '
'should provide reset_mask inputs in addition to act and padding if '
'this flag is set.'))
p.Define(
'zero_state_init_params', py_utils.DefaultRNNCellStateInit(),
'Parameters that define how the initial state values are set '
'for each cell. Must be one of the static functions defined in '
'py_utils.RNNCellStateInit.')
return p
def __init__(self, params):
"""Initializes RnnCell."""
super(RNNCell, self).__init__(params)
assert not self.params.vn.per_step_vn, (
'We do not support per step VN in RNN cells.')
def _VariableCollections(self):
return [RNN_CELL_WT, '%s_vars' % (self.__class__.__name__)]
def zero_state(self, theta, batch_size):
"""Returns the initial state given the batch size."""
raise NotImplementedError('Abstract method')
def GetOutput(self, state):
"""Returns the output value given the current state."""
raise NotImplementedError('Abstract method')
def batch_size(self, inputs):
"""Given the inputs, returns the batch size."""
raise NotImplementedError('Abstract method')
def FProp(self, theta, state0, inputs):
"""Forward function.
The default implementation here assumes the cell forward
function is composed of two functions::
_Gates(_Mix(theta, state0, inputs), theta, state0, inputs)
The result of `_Mix` is stashed in `extras` to facilitate backprop.
`_ResetState` is optionally applied if `reset_cell_state` is True. The RNN
layer should provide `reset_mask` inputs in addition to other inputs.
`reset_mask` inputs are expected to be 0 at timesteps where state0 should be
reset to default (zeros) before running `_Mix()` and `_Gates()`, and 1
otherwise. This is meant to support use cases like packed inputs, where
multiple samples are fed in a single input example sequence, and need to be
masked from each other. For example, if the two examples packed together
are ['good', 'day'] -> ['guten-tag'] and ['thanks'] -> ['danke']
to produce ['good', 'day', 'thanks'] -> ['guten-tag', 'danke'], the
source reset_masks would be [1, 1, 0] and target reset masks would be
[1, 0]. These ids are meant to enable masking computations for
different examples from each other.
Args:
theta: A `.NestedMap` object containing weights' values of this layer and
its children layers.
state0: The previous recurrent state. A `.NestedMap`.
inputs: The inputs to the cell. A `.NestedMap`.
Returns:
A tuple (state1, extras).
- state1: The next recurrent state. A `.NestedMap`.
- extras: Intermediate results to faciliate backprop. A `.NestedMap`.
"""
assert isinstance(inputs.act, list)
assert self.params.inputs_arity == len(inputs.act)
if self.params.reset_cell_state:
state0_modified = self._ResetState(state0.DeepCopy(), inputs)
else:
state0_modified = state0
xmw = self._Mix(theta, state0_modified, inputs)
state1 = self._Gates(xmw, theta, state0_modified, inputs)
return state1, py_utils.NestedMap()
def _ZoneOut(self,
prev_v,
cur_v,
padding_v,
zo_prob,
is_eval,
random_uniform,
qt=None,
qdomain=''):
"""Apply ZoneOut regularlization to cur_v.
Implements ZoneOut regularization as described in
https://arxiv.org/abs/1606.01305
Args:
prev_v: A tensor, values from the previous timestep.
cur_v: A tensor, values from the current timestep.
padding_v: A tensor, the paddings vector for the cur timestep.
zo_prob: A float, probability at which to apply ZoneOut regularization.
is_eval: A bool, whether or not in eval mode.
random_uniform: a tensor of random uniform numbers. This can be None if
zo_prob=0.0
qt: A string, name of the qtensor for zone out math.
qdomain: A string, name of the qdomain for quantized zone out math.
Returns:
cur_v after ZoneOut regularization has been applied.
"""
prev_v = tf.convert_to_tensor(prev_v)
cur_v = tf.convert_to_tensor(cur_v)
padding_v = tf.convert_to_tensor(padding_v)
if zo_prob == 0.0:
# Special case for when ZoneOut is not enabled.
return py_utils.ApplyPadding(padding_v, cur_v, prev_v)
if is_eval:
# We take expectation in the eval mode.
#
fns = self.fns
# This quantized mixed operation should probably occur as fused kernel to
# avoid quantized-math rounding errors. Current accuracy has not been
# verified.
prev_weight = self.QWeight(zo_prob, domain=qdomain)
new_weight = self.QWeight(1.0 - prev_weight, domain=qdomain)
if qt is None:
mix_prev = tf.multiply(tf.fill(tf.shape(prev_v), prev_weight), prev_v)
mix_curr = tf.multiply(tf.fill(tf.shape(cur_v), new_weight), cur_v)
mix = tf.add(mix_prev, mix_curr)
else:
mix_prev = fns.qmultiply(
self.QWeight(
tf.fill(tf.shape(prev_v), prev_weight), domain=qdomain),
prev_v,
qt=qt)
mix_curr = fns.qmultiply(
self.QWeight(tf.fill(tf.shape(cur_v), new_weight), domain=qdomain),
cur_v,
qt=qt)
mix = fns.qadd(mix_prev, mix_curr, qt=qt)
# If padding_v is 1, it always carries over the previous state.
return py_utils.ApplyPadding(padding_v, mix, prev_v)
else:
assert random_uniform is not None
random_uniform = py_utils.HasShape(random_uniform, tf.shape(prev_v))
zo_p = tf.cast(random_uniform < zo_prob, padding_v.dtype)
zo_p += padding_v
# If padding_v is 1, we always carry over the previous state.
zo_p = tf.minimum(zo_p, 1.0)
zo_p = tf.stop_gradient(zo_p)
return py_utils.ApplyPadding(zo_p, cur_v, prev_v)
class LSTMCellSimple(RNNCell):
"""Simple LSTM cell.
theta:
- wm: the parameter weight matrix. All gates combined.
- b: the combined bias vector.
state:
- m: the lstm output. [batch, cell_nodes]
- c: the lstm cell state. [batch, cell_nodes]
inputs:
- act: a list of input activations. [batch, input_nodes]
- padding: the padding. [batch, 1].
- reset_mask: optional 0/1 float input to support packed input training.
Shape [batch, 1]
"""
@classmethod
def Params(cls):
p = super(LSTMCellSimple, cls).Params()
p.Define(
'num_hidden_nodes', 0, 'Number of projection hidden nodes '
'(see https://arxiv.org/abs/1603.08042). '
'Set to 0 to disable projection.')
p.Define(
'cell_value_cap', 10.0, 'LSTM cell values are capped to be within '
' [-cell_value_cap, +cell_value_cap] if the value is not None. '
'It can be a scalar, a scalar tensor or None. When set to None, '
'no capping is applied.')
p.Define('forget_gate_bias', 0.0, 'Bias to apply to the forget gate.')
p.Define('output_nonlinearity', True,
'Whether or not to apply tanh non-linearity on lstm output.')
p.Define('zo_prob', 0.0,
'If > 0, applies ZoneOut regularization with the given prob.')
p.Define('enable_lstm_bias', True, 'Enable the LSTM Cell bias.')
p.Define(
'couple_input_forget_gates', False,
'Whether to couple the input and forget gates. Just like '
'tf.contrib.rnn.CoupledInputForgetGateLSTMCell')
p.Define('apply_pruning', False, 'Whether to prune the weights while '
'training')
p.Define('apply_pruning_to_projection', False,
'Whether to prune the projection matrix while '
'training')
p.Define('gradient_pruning', False, 'Whether to gradient prune the model')
p.Define('bias_init', py_utils.WeightInit.Constant(0.0),
'Initialization parameters for bias')
# Non-default quantization behaviour.
p.qdomain.Define('weight', None, 'Quantization for the weights')
p.qdomain.Define('c_state', None, 'Quantization for the c-state.')
p.qdomain.Define('m_state', None, 'Quantization for the m-state.')
p.qdomain.Define('fullyconnected', None,
'Quantization for fully connected node.')
return p
def __init__(self, params):
"""Initializes LSTMCellSimple."""
super(LSTMCellSimple, self).__init__(params)
assert isinstance(params, hyperparams.Params)
p = self.params
assert isinstance(p.cell_value_cap,
(int, float)) or p.cell_value_cap is None
assert p.cell_value_cap is None or p.qdomain.default is None
self.TrackQTensor(
'zero_m',
'm_output',
'm_output_projection',
'm_zoneout',
domain='m_state')
self.TrackQTensor(
'zero_c',
'mixed',
'c_couple_invert',
'c_input_gate',
'c_forget_gate',
'c_output_gate',
'c_zoneout',
domain='c_state')
self.TrackQTensor('add_bias', domain='fullyconnected')
with tf.variable_scope(p.name) as scope:
# Define weights.
wm_pc = py_utils.WeightParams(
shape=[
p.num_input_nodes + self.output_size,
self.num_gates * self.hidden_size
],
init=p.params_init,
dtype=p.dtype,
collections=self._VariableCollections())
self.CreateVariable('wm', wm_pc, self.AddGlobalVN)
if p.apply_pruning:
mask_pc = py_utils.WeightParams(wm_pc.shape,
py_utils.WeightInit.Constant(1.0),
p.dtype)
threshold_pc = py_utils.WeightParams([],
py_utils.WeightInit.Constant(0.0),
tf.float32)
self.CreateVariable('mask', mask_pc, theta_fn=None, trainable=False)
self.CreateVariable(
'threshold', threshold_pc, theta_fn=None, trainable=False)
# for gradient based pruning
# gradient and weight snapshots
grad_pc = py_utils.WeightParams(wm_pc.shape,
py_utils.WeightInit.Constant(0.0),
p.dtype)
if p.gradient_pruning:
self.CreateVariable(
'gradient', grad_pc, theta_fn=None, trainable=False)
self.CreateVariable(
'old_weight', grad_pc, theta_fn=None, trainable=False)
self.CreateVariable(
'old_old_weight', grad_pc, theta_fn=None, trainable=False)
py_utils.AddToPruningCollections(self.vars.wm, self.vars.mask,
self.vars.threshold,
self.vars.gradient,
self.vars.old_weight,
self.vars.old_old_weight)
else:
py_utils.AddToPruningCollections(self.vars.wm, self.vars.mask,
self.vars.threshold)
if p.num_hidden_nodes:
w_proj = py_utils.WeightParams(
shape=[self.hidden_size, self.output_size],
init=p.params_init,
dtype=p.dtype,
collections=self._VariableCollections())
self.CreateVariable('w_proj', w_proj, self.AddGlobalVN)
if p.apply_pruning_to_projection:
proj_mask_pc = py_utils.WeightParams(
w_proj.shape, py_utils.WeightInit.Constant(1.0), p.dtype)
proj_threshold_pc = py_utils.WeightParams(
[], py_utils.WeightInit.Constant(0.0), tf.float32)
self.CreateVariable(
'proj_mask', proj_mask_pc, theta_fn=None, trainable=False)
self.CreateVariable(
'proj_threshold', proj_threshold_pc, trainable=False)
# for gradient based pruning
# gradient and weight snapshots
proj_grad_pc = py_utils.WeightParams(
w_proj.shape, py_utils.WeightInit.Constant(0.0), p.dtype)
if p.gradient_pruning:
self.CreateVariable('proj_gradient', proj_grad_pc, trainable=False)
self.CreateVariable(
'proj_old_weight', proj_grad_pc, trainable=False)
self.CreateVariable(
'proj_old_old_weight', proj_grad_pc, trainable=False)
py_utils.AddToPruningCollections(self.vars.w_proj,
self.vars.proj_mask,
self.vars.proj_threshold,
self.vars.proj_gradient,
self.vars.proj_old_weight,
self.vars.proj_old_old_weight)
else:
py_utils.AddToPruningCollections(self.vars.w_proj,
self.vars.proj_mask,
self.vars.proj_threshold)
if p.enable_lstm_bias:
bias_pc = py_utils.WeightParams(
shape=[self.num_gates * self.hidden_size],
init=p.bias_init,
dtype=p.dtype,
collections=self._VariableCollections())
self.CreateVariable('b', bias_pc, self.AddGlobalVN)
# Collect some stats.
w = self.vars.wm
if p.couple_input_forget_gates:
i_i, f_g, o_g = tf.split(
value=w, num_or_size_splits=self.num_gates, axis=1)
else:
i_i, i_g, f_g, o_g = tf.split(
value=w, num_or_size_splits=self.num_gates, axis=1)
_HistogramSummary(p, scope.name + '/wm_i_g', i_g)
_HistogramSummary(p, scope.name + '/wm_i_i', i_i)
_HistogramSummary(p, scope.name + '/wm_f_g', f_g)
_HistogramSummary(p, scope.name + '/wm_o_g', o_g)
self._timestep = -1
@property
def output_size(self):
return self.params.num_output_nodes
@property
def hidden_size(self):
return self.params.num_hidden_nodes or self.params.num_output_nodes
@property
def num_gates(self):
return 3 if self.params.couple_input_forget_gates else 4
def batch_size(self, inputs):
return tf.shape(inputs.act[0])[0]
def zero_state(self, theta, batch_size):
p = self.params
zero_m = py_utils.InitRNNCellState((batch_size, self.output_size),
init=p.zero_state_init_params,
dtype=py_utils.FPropDtype(p),
is_eval=self.do_eval)
zero_c = py_utils.InitRNNCellState((batch_size, self.hidden_size),
init=p.zero_state_init_params,
dtype=py_utils.FPropDtype(p),
is_eval=self.do_eval)
if p.is_inference:
zero_m = self.QTensor('zero_m', zero_m)
zero_c = self.QTensor('zero_c', zero_c)
return py_utils.NestedMap(m=zero_m, c=zero_c)
def _ResetState(self, state, inputs):
state.m = inputs.reset_mask * state.m
state.c = inputs.reset_mask * state.c
return state
def GetOutput(self, state):
return state.m
def _GetBias(self, theta):
"""Gets the bias vector to add.
Includes adjustments like forget_gate_bias. Use this instead of the 'b'
variable directly as including adjustments in this way allows const-prop
to eliminate the adjustments at inference time.
Args:
theta: A `.NestedMap` object containing weights' values of this layer and
its children layers.
Returns:
The bias vector.
"""
p = self.params
if p.enable_lstm_bias:
b = theta.b
else:
b = tf.zeros([self.num_gates * self.hidden_size], dtype=p.dtype)
if p.forget_gate_bias != 0.0:
# Apply the forget gate bias directly to the bias vector.
if not p.couple_input_forget_gates:
# Normal 4 gate bias (i_i, i_g, f_g, o_g).
adjustment = (
tf.ones([4, self.hidden_size], dtype=p.dtype) * tf.expand_dims(
tf.constant([0., 0., p.forget_gate_bias, 0.], dtype=p.dtype),
axis=1))
else:
# 3 gates with coupled input/forget (i_i, f_g, o_g).
adjustment = (
tf.ones([3, self.hidden_size], dtype=p.dtype) * tf.expand_dims(
tf.constant([0., p.forget_gate_bias, 0.], dtype=p.dtype),
axis=1))
adjustment = tf.reshape(adjustment, [self.num_gates * self.hidden_size])
b = b + adjustment
return b
def _Mix(self, theta, state0, inputs):
assert isinstance(inputs.act, list)
if self.params.apply_pruning:
wm = self.QWeight(tf.multiply(theta.wm, theta.mask, 'masked_weights'))
else:
wm = self.QWeight(theta.wm)
concat = tf.concat(inputs.act + [state0.m], 1)
# Defer quantization until after adding in the bias to support fusing
# matmul and bias add during inference.
return tf.matmul(concat, wm)
def _Gates(self, xmw, theta, state0, inputs):
"""Compute the new state."""
i_i, i_g, f_g, o_g = self._RetrieveAndSplitGates(xmw, theta)
return self._GatesInternal(theta, state0, inputs, i_i, i_g, f_g, o_g)
def _RetrieveAndSplitGates(self, xmw, theta):
p = self.params
b = self.QWeight(tf.expand_dims(self._GetBias(theta), 0), domain='fc')
xmw = self.fns.qadd(xmw, b, qt='add_bias')
gates = tf.split(value=xmw, num_or_size_splits=self.num_gates, axis=1)
if p.couple_input_forget_gates:
gates = gates[0], None, gates[1], gates[2]
return gates
def _GatesInternal(self, theta, state0, inputs, i_i, i_g, f_g, o_g):
p = self.params
fns = self.fns
if not p.couple_input_forget_gates:
assert i_g is not None
forget_gate = fns.qmultiply(tf.sigmoid(f_g), state0.c, qt='c_input_gate')
# Sigmoid / tanh calls are not quantized under the assumption they share
# the range with c_input_gate and c_forget_gate.
input_gate = fns.qmultiply(
tf.sigmoid(i_g), tf.tanh(i_i), qt='c_forget_gate')
new_c = fns.qadd(forget_gate, input_gate, qt='c_output_gate')
else:
assert i_g is None
# Sigmoid / tanh calls are not quantized under the assumption they share
# the range with c_input_gate and c_forget_gate.
forget_gate = fns.qmultiply(tf.sigmoid(f_g), state0.c, qt='c_input_gate')
# input_gate = tanh(i_i) - tanh(i_i) * tf.sigmoid(f_g)
# equivalent to (but more stable in fixed point):
# (1.0 - sigmoid(f_g)) * tanh(i_i)
tanh_i_i = tf.tanh(i_i)
input_gate = fns.qsubtract(
tanh_i_i,
fns.qmultiply(tanh_i_i, tf.sigmoid(f_g), qt='c_couple_invert'),
qt='c_forget_gate')
new_c = fns.qadd(forget_gate, input_gate, qt='c_output_gate')
new_c = self._ProcessNewC(theta, new_c)
# Clip the cell states to reasonable value.
if p.cell_value_cap is not None:
new_c = py_utils.clip_by_value(new_c, -p.cell_value_cap, p.cell_value_cap)
if p.output_nonlinearity:
new_m = fns.qmultiply(tf.sigmoid(o_g), tf.tanh(new_c), qt='m_output')
else:
new_m = fns.qmultiply(tf.sigmoid(o_g), new_c, qt='m_output')
if p.num_hidden_nodes:
if p.apply_pruning_to_projection:
w_proj = self.QWeight(
tf.multiply(theta.w_proj, theta.proj_mask, 'masked_projection'),
domain='m_state')
else:
w_proj = self.QWeight(theta.w_proj, domain='m_state')
new_m = fns.qmatmul(new_m, w_proj, qt='m_output_projection')
# Apply Zoneout.
return self._ApplyZoneOut(state0, inputs, new_c, new_m)
def _ProcessNewC(self, theta, new_c):
return new_c
def _ApplyZoneOut(self, state0, inputs, new_c, new_m):
"""Apply Zoneout and returns the updated states."""
p = self.params
if p.zo_prob > 0.0:
assert not py_utils.use_tpu(), (
'LSTMCellSimple does not support zoneout on TPU. Switch to '
'LSTMCellSimpleDeterministic instead.')
c_random_uniform = tf.random.uniform(tf.shape(new_c), seed=p.random_seed)
m_random_uniform = tf.random.uniform(tf.shape(new_m), seed=p.random_seed)
else:
c_random_uniform = None
m_random_uniform = None
new_c = self._ZoneOut(
state0.c,
new_c,
self.QRPadding(inputs.padding),
p.zo_prob,
self.do_eval,
c_random_uniform,
qt='c_zoneout',
qdomain='c_state')
new_m = self._ZoneOut(
state0.m,
new_m,
self.QRPadding(inputs.padding),
p.zo_prob,
self.do_eval,
m_random_uniform,
qt='m_zoneout',
qdomain='m_state')
new_c.set_shape(state0.c.shape)
new_m.set_shape(state0.m.shape)
return py_utils.NestedMap(m=new_m, c=new_c)
class LSTMCellGrouped(RNNCell):
"""LSTM cell with groups.
Grouping: based on "Factorization tricks for LSTM networks".
https://arxiv.org/abs/1703.10722.
Shuffling: adapted from "ShuffleNet: An Extremely Efficient Convolutional
Neural Network for Mobile Devices". https://arxiv.org/abs/1707.01083.
theta:
- groups: a list of child LSTM cells.
state:
A `.NestedMap` containing 'groups', a list of `.NestedMap`, each with:
- m: the lstm output. [batch, cell_nodes // num_groups]
- c: the lstm cell state. [batch, cell_nodes // num_groups]
inputs:
- act: a list of input activations. [batch, input_nodes]
- padding: the padding. [batch, 1].
- reset_mask: optional 0/1 float input to support packed input training.
Shape [batch, 1]
"""
@classmethod
def Params(cls, child_cell_cls=LSTMCellSimple):
p = super(LSTMCellGrouped, cls).Params()
p.Define('child_lstm_tpl', child_cell_cls.Params(),
'Template of child LSTM cells.')
p.Define('num_hidden_nodes', 0, 'Number of hidden nodes.')
p.Define(
'split_inputs', True, 'If true, split the inputs into N groups. '
'If false, each group gets all inputs.')
p.Define('num_groups', 0, 'Number of LSTM cell groups.')
p.Define('num_shuffle_shards', 1,
'If > 1, number of shards for cross-group shuffling.')
return p
def __init__(self, params):
"""Initializes LSTMCellGrouped."""
super(LSTMCellGrouped, self).__init__(params)
assert isinstance(params, hyperparams.Params)
p = self.params
assert p.num_input_nodes > 0
assert p.num_output_nodes > 0
assert p.num_groups > 0
assert p.num_shuffle_shards > 0
assert p.num_input_nodes % p.num_groups == 0
assert p.num_output_nodes % (p.num_shuffle_shards * p.num_groups) == 0
with tf.variable_scope(p.name):
child_params = []
for i in range(p.num_groups):
child_p = self.params.child_lstm_tpl.Copy()
child_p.name = 'group_%d' % i
assert child_p.num_input_nodes == 0
assert child_p.num_output_nodes == 0
if p.split_inputs:
child_p.num_input_nodes = p.num_input_nodes // p.num_groups
else:
child_p.num_input_nodes = p.num_input_nodes
child_p.num_output_nodes = p.num_output_nodes // p.num_groups
child_p.num_hidden_nodes = p.num_hidden_nodes // p.num_groups
child_p.reset_cell_state = p.reset_cell_state
child_params.append(child_p)
self.CreateChildren('groups', child_params)
def batch_size(self, inputs):
return self.groups[0].batch_size(inputs)
def zero_state(self, theta, batch_size):
return py_utils.NestedMap(groups=[
child.zero_state(child_theta, batch_size)
for child, child_theta in zip(self.groups, theta.groups)
])
# TODO(rpang): avoid split and concat between layers with the same number of
# groups, if necessary.
def GetOutput(self, state):
p = self.params
# Assuming that GetOutput() is stateless, we can just use the first child.
outputs = [
child.GetOutput(child_state)
for child, child_state in zip(self.groups, state.groups)
]
split_output = []
# Split each output to num_shuffle_shards.
for output in outputs:
split_output.extend(
py_utils.SplitRecursively(output, p.num_shuffle_shards))
# Shuffle and concatenate shards.
return py_utils.ConcatRecursively(self._ShuffleShards(split_output))
def FProp(self, theta, state0, inputs):
"""Forward function.
Splits state0 and inputs into N groups (N=num_groups), runs child
LSTM cells on each group, and concatenates the outputs with optional
shuffling between groups.
Args:
theta: A `.NestedMap` object containing weights' values of this layer and
its children layers.
state0: The previous recurrent state. A `.NestedMap`.
inputs: The inputs to the cell. A `.NestedMap`.
Returns:
A tuple (state1, extras).
- state1: The next recurrent state. A list.
- extras: An empty `.NestedMap`.
"""
p = self.params
if p.split_inputs:
split_inputs_act = py_utils.SplitRecursively(inputs.act, p.num_groups)
else:
split_inputs_act = [inputs.act] * p.num_groups
state1 = py_utils.NestedMap(groups=[])
for child, child_theta, child_state0, child_inputs_act in zip(
self.groups, theta.groups, state0.groups, split_inputs_act):
child_inputs = inputs.copy()
child_inputs.act = child_inputs_act
child_state1, child_extras = child.FProp(child_theta, child_state0,
child_inputs)
assert not child_extras
state1.groups.append(child_state1)
return state1, py_utils.NestedMap()
def _ShuffleShards(self, shards):
"""Shuffles shards across groups.
Args:
shards: a list of length num_shuffle_shards (S) * num_groups (G). The
first S shards belong to group 0, the next S shards belong to group 1,
etc.
Returns:
A shuffled list of shards such that shards from each input group are
scattered across output groups.
For example, if we have 3 groups, each with 4 shards:
| Group 0: 0_0, 0_1, 0_2, 0_3
| Group 1: 1_0, 1_1, 1_2, 1_3
| Group 2: 2_0, 2_1, 2_2, 2_3
The shuffled output will be:
| Group 0: 0_0, 1_1, 2_2, 0_3
| Group 1: 1_0, 2_1, 0_2, 1_3
| Group 2: 2_0, 0_1, 1_2, 2_3
"""
p = self.params
assert len(shards) == (p.num_shuffle_shards * p.num_groups)
shuffled_shards = []
for group_i in range(p.num_groups):
for shuffle_i in range(p.num_shuffle_shards):
shuffled_shards.append(shards[(
(group_i + shuffle_i) % p.num_groups) * p.num_shuffle_shards +
shuffle_i])
return shuffled_shards
# TODO(yonghui): Merge this cell with the LSTMCellSimple cell.
class LSTMCellSimpleDeterministic(LSTMCellSimple):
"""Same as LSTMCellSimple, except this cell is completely deterministic."""
@classmethod
def Params(cls):
p = super(LSTMCellSimpleDeterministic, cls).Params()
return p
def __init__(self, params):
"""Initializes LSTMCell."""
super(LSTMCellSimpleDeterministic, self).__init__(params)
p = self.params
assert p.name
with tf.variable_scope(p.name):
self.CreateVariable(
name='lstm_step_counter',
var_params=py_utils.WeightParams([], py_utils.WeightInit.Constant(0),
tf.int64),
trainable=False)
vname = self.vars.lstm_step_counter.name
self._prng_seed = tf.constant(
py_utils.GenerateSeedFromName(vname), dtype=tf.int64)
if p.random_seed:
self._prng_seed += p.random_seed
def zero_state(self, theta, batch_size):
p = self.params
zero_m = tf.zeros((batch_size, self.output_size),
dtype=py_utils.FPropDtype(p))
zero_c = tf.zeros((batch_size, self.hidden_size),
dtype=py_utils.FPropDtype(p))
if p.is_inference:
zero_m = self.QTensor('zero_m', zero_m)
zero_c = self.QTensor('zero_c', zero_c)
# The first random seed changes for different layers and training steps.
random_seed1 = self._prng_seed + theta.lstm_step_counter
# The second random seed changes for different unroll time steps.
random_seed2 = tf.constant(0, dtype=tf.int64)
random_seeds = tf.stack([random_seed1, random_seed2])
return py_utils.NestedMap(m=zero_m, c=zero_c, r=random_seeds)
def _ApplyZoneOut(self, state0, inputs, new_c, new_m):
"""Apply Zoneout and returns the updated states."""
p = self.params
random_seed1 = state0.r[0]
random_seed2 = state0.r[1]
if p.zo_prob > 0.0:
# Note(yonghui): It seems that currently TF only supports int64 as the
# random seeds, however, TPU will support int32 as the seed.
# TODO(yonghui): Fix me for TPU.
c_seed = tf.stack([random_seed1, 2 * random_seed2])
m_seed = tf.stack([random_seed1, 2 * random_seed2 + 1])
if py_utils.use_tpu():
c_random_uniform = tf.random.stateless_uniform(
py_utils.GetShape(new_c, 2), tf.cast(c_seed, tf.int32))
m_random_uniform = tf.random.stateless_uniform(
py_utils.GetShape(new_m, 2), tf.cast(m_seed, tf.int32))
else:
c_random_uniform = tf.random.stateless_uniform(
py_utils.GetShape(new_c, 2), c_seed)
m_random_uniform = tf.random.stateless_uniform(
py_utils.GetShape(new_m, 2), m_seed)
else:
c_random_uniform = None
m_random_uniform = None
new_c = self._ZoneOut(
state0.c,
new_c,
inputs.padding,
p.zo_prob,
self.do_eval,
c_random_uniform,
qt='zero_c',
qdomain='c_state')
new_m = self._ZoneOut(
state0.m,
new_m,
inputs.padding,
p.zo_prob,
self.do_eval,
m_random_uniform,
qt='zero_m',
qdomain='m_state')
# TODO(yonghui): stop the proliferation of tf.stop_gradient
r = tf.stop_gradient(tf.stack([random_seed1, random_seed2 + 1]))
new_c.set_shape(state0.c.shape)
new_m.set_shape(state0.m.shape)
r.set_shape(state0.r.shape)
return py_utils.NestedMap(m=new_m, c=new_c, r=r)
def PostTrainingStepUpdate(self, global_step):
"""Update the global_step value."""
p = self.params
with tf.name_scope(p.name):
summary_utils.scalar('step_counter', self.vars.lstm_step_counter)
return self.vars.lstm_step_counter.assign(tf.cast(global_step, tf.int64))
class QuantizedLSTMCell(RNNCell):
"""Simplified LSTM cell used for quantized training.
There is no forget_gate_bias, no output_nonlinearity and no bias. Right now
only clipping is performed.
theta:
- wm: the parameter weight matrix. All gates combined.
- cap: the cell value cap.
state:
- m: the lstm output. [batch, cell_nodes]
- c: the lstm cell state. [batch, cell_nodes]
inputs:
- act: a list of input activations. [batch, input_nodes]
- padding: the padding. [batch, 1].
- reset_mask: optional 0/1 float input to support packed input training.
[batch, 1]
"""
@classmethod
def Params(cls):
p = super(QuantizedLSTMCell, cls).Params()
p.Define('cc_schedule', quant_utils.LinearClippingCapSchedule.Params(),
'Clipping cap schedule.')
return p
def __init__(self, params):
"""Initializes QuantizedLSTMCell."""
super(QuantizedLSTMCell, self).__init__(params)
assert isinstance(params, hyperparams.Params)
p = self.params
with tf.variable_scope(p.name) as scope:
# Define weights.
wm_pc = py_utils.WeightParams(
shape=[
p.num_input_nodes + p.num_output_nodes, 4 * p.num_output_nodes
],
init=p.params_init,
dtype=p.dtype,
collections=self._VariableCollections())
self.CreateVariable('wm', wm_pc, self.AddGlobalVN)
self.CreateChild('cc_schedule', p.cc_schedule)
# Collect some stats
i_i, i_g, f_g, o_g = tf.split(
value=self.vars.wm, num_or_size_splits=4, axis=1)
_HistogramSummary(p, scope.name + '/wm_i_i', i_i)
_HistogramSummary(p, scope.name + '/wm_i_g', i_g)
_HistogramSummary(p, scope.name + '/wm_f_g', f_g)
_HistogramSummary(p, scope.name + '/wm_o_g', o_g)
self._timestep = -1
def batch_size(self, inputs):
return tf.shape(inputs.act[0])[0]
def zero_state(self, theta, batch_size):
p = self.params
zero_m = py_utils.InitRNNCellState((batch_size, p.num_output_nodes),
init=p.zero_state_init_params,
dtype=py_utils.FPropDtype(p),
is_eval=self.do_eval)
zero_c = py_utils.InitRNNCellState((batch_size, p.num_output_nodes),
init=p.zero_state_init_params,
dtype=py_utils.FPropDtype(p),
is_eval=self.do_eval)
return py_utils.NestedMap(m=zero_m, c=zero_c)
def GetOutput(self, state):
return state.m
def _ResetState(self, state, inputs):
state.m = inputs.reset_mask * state.m
state.c = inputs.reset_mask * state.c
return state
def _Mix(self, theta, state0, inputs):
assert isinstance(inputs.act, list)
return py_utils.Matmul(tf.concat(inputs.act + [state0.m], 1), theta.wm)
def _Gates(self, xmw, theta, state0, inputs):
"""Compute the new state."""
i_i, i_g, f_g, o_g = tf.split(value=xmw, num_or_size_splits=4, axis=1)
new_c = tf.sigmoid(f_g) * state0.c + tf.sigmoid(i_g) * tf.tanh(i_i)
new_c = self.cc_schedule.ApplyClipping(theta.cc_schedule, new_c)
new_m = tf.sigmoid(o_g) * new_c
# Respect padding.
new_m = state0.m * inputs.padding + new_m * (1 - inputs.padding)
new_c = state0.c * inputs.padding + new_c * (1 - inputs.padding)
new_c.set_shape(state0.c.shape)
new_m.set_shape(state0.m.shape)
return py_utils.NestedMap(m=new_m, c=new_c)
class LayerNormalizedLSTMCell(RNNCell):
"""DEPRECATED: use LayerNormalizedLSTMCellSimple instead.
Simple LSTM cell with layer normalization.
Implements normalization scheme as described in
https://arxiv.org/pdf/1607.06450.pdf
theta:
- wm: the parameter weight matrix. All gates combined.
- b: the combined bias vector.
state:
- m: the lstm output. [batch, cell_nodes]
- c: the lstm cell state. [batch, cell_nodes]
inputs:
- act: a list of input activations. [batch, input_nodes]
- padding: the padding. [batch, 1].
- reset_mask: optional 0/1 float input to support packed input training.
Shape [batch, 1]
"""