/
rnn_cell.py
1794 lines (1549 loc) · 65.7 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
import six
import numpy as np
from collections import namedtuple
import tensorflow as tf
from tensorflow.python.util import nest
from . import initializers as initz
from .layers import conv2d, dropout, softmax
from . import logger as log
from ..utils import util as helper
NamedOutputs = namedtuple('NamedOutputs', ['name', 'outputs'])
core_rnn_cell = tf.contrib.rnn
class BasicRNNCell(core_rnn_cell.RNNCell):
"""The most basic RNN cell.
Args:
num_units: int, The number of units in the LSTM cell.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
input_size: Deprecated and unused.
activation: Activation function of the states.
layer_norm: If `True`, layer normalization will be applied.
layer_norm_args: optional dict, layer_norm arguments
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
"""
def __init__(self,
num_units,
reuse,
trainable=True,
w_init=initz.he_normal(),
use_bias=False,
input_size=None,
activation=tf.tanh,
layer_norm=None,
layer_norm_args=None):
if input_size is not None:
log.warn("%s: The input_size parameter is deprecated.", self)
self._num_units = num_units
self._activation = activation
self._w_init = w_init
self._use_bias = use_bias
self.reuse = reuse
self.trainable = trainable
self.layer_norm = layer_norm
self.layer_norm_args = layer_norm_args or {}
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
def __call__(self, inputs, state, scope='basic_rnn_cell'):
"""Most basic RNN: output = new_state = act(W * input + U * state + B)."""
with tf.variable_scope(scope):
output = self._activation(
_linear([inputs, state],
self._num_units,
self.reuse,
w_init=self._w_init,
use_bias=self._use_bias,
trainable=self.trainable,
name=scope))
if self.layer_norm is not None:
output = self.layer_norm(
output, self.reuse, trainable=self.trainable, **self.layer_norm_args)
return output, output
class LSTMCell(core_rnn_cell.RNNCell):
"""LSTM unit.
This class adds layer normalization and recurrent dropout to a
basic LSTM unit. Layer normalization implementation is based on:
https://arxiv.org/abs/1607.06450.
"Layer Normalization" Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton
and is applied before the internal nonlinearities.
Recurrent dropout is base on:
https://arxiv.org/abs/1603.05118
"Recurrent Dropout without Memory Loss"
Stanislau Semeniuta, Aliaksei Severyn, Erhardt Barth.
Args:
num_units: int, The number of units in the LSTM cell.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
forget_bias: float, The bias added to forget gates (see above).
input_size: Deprecated and unused.
activation: Activation function of the states.
inner_activation: Activation function of the inner states.
layer_norm: If `True`, layer normalization will be applied.
layer_norm_args: optional dict, layer_norm arguments
cell_clip: (optional) A float value, if provided the cell state is clipped
by this value prior to the cell output activation.
keep_prob: unit Tensor or float between 0 and 1 representing the
recurrent dropout probability value. If float and 1.0, no dropout will
be applied.
dropout_seed: (optional) integer, the randomness seed.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
"""
def __init__(self,
num_units,
reuse,
trainable=True,
w_init=initz.he_normal(),
forget_bias=1.0,
use_bias=False,
input_size=None,
activation=tf.tanh,
inner_activation=tf.sigmoid,
keep_prob=1.0,
dropout_seed=None,
cell_clip=None,
layer_norm=None,
layer_norm_args=None):
if input_size is not None:
ValueError("%s: the input_size parameter is deprecated." % self)
self._num_units = num_units
self._forget_bias = forget_bias
self._use_bias = use_bias
self._w_init = w_init
self.layer_norm = layer_norm
self.layer_norm_args = layer_norm_args or {}
self._cell_clip = cell_clip
self._activation = activation
self._inner_activation = inner_activation
self._keep_prob = keep_prob
self._dropout_seed = dropout_seed
self.trainable = trainable
self.reuse = reuse
@property
def state_size(self):
return core_rnn_cell.LSTMStateTuple(self._num_units, self._num_units)
@property
def output_size(self):
return self._num_units
def __call__(self, inputs, state, scope='basiclstm'):
"""Long short-term memory cell (LSTM)."""
with tf.variable_scope(scope):
c, h = state
concat = _linear([inputs, h],
4 * self._num_units,
self.reuse,
trainable=self.trainable,
w_init=self._w_init,
use_bias=self._use_bias,
name=scope)
# i = input_gate, j = new_input, f = forget_gate, o = output_gate
i, j, f, o = tf.split(concat, 4, axis=1)
# apply batch normalization to inner state and gates
if self.layer_norm is not None:
i = self.layer_norm(i, self.reuse, trainable=self.trainable, **self.layer_norm_args)
j = self.layer_norm(j, self.reuse, trainable=self.trainable, **self.layer_norm_args)
f = self.layer_norm(f, self.reuse, trainable=self.trainable, **self.layer_norm_args)
o = self.layer_norm(o, self.reuse, trainable=self.trainable, **self.layer_norm_args)
j = self._activation(j)
if (not isinstance(self._keep_prob, float)) or self._keep_prob < 1:
j = dropout(j, self._keep_prob, seed=self._dropout_seed)
new_c = (c * self._inner_activation(f + self._forget_bias)
+ self._inner_activation(i) * self._activation(j))
if self._cell_clip is not None:
new_c = tf.clip_by_value(new_c, -self._cell_clip, self._cell_clip)
if self.layer_norm is not None:
layer_norm_new_c = self.layer_norm(
new_c, self.reuse, trainable=self.trainable, **self.layer_norm_args)
new_h = self._activation(layer_norm_new_c) * self._inner_activation(o)
else:
new_h = self._activation(new_c) * self._inner_activation(o)
new_state = core_rnn_cell.LSTMStateTuple(new_c, new_h)
return new_h, new_state
class AttentionCell(core_rnn_cell.RNNCell):
"""Basic attention cell.
Implementation based on https://arxiv.org/abs/1409.0473.
Create a cell with attention.
Args:
cell: an RNNCell, an attention is added to it.
e.g.: a LSTMCell
attn_length: integer, the size of an attention window.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
attn_size: integer, the size of an attention vector. Equal to
cell.output_size by default.
attn_vec_size: integer, the number of convolutional features calculated
on attention state and a size of the hidden layer built from
base cell state. Equal attn_size to by default.
input_size: integer, the size of a hidden linear layer,
layer_norm: If `True`, layer normalization will be applied.
layer_norm_args: optional dict, layer_norm arguments
built from inputs and attention. Derived from the input tensor by default.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
Raises:
TypeError: if cell is not an RNNCell.
ValueError: Cell state should be tuple of states
"""
def __init__(self,
cell,
attn_length,
reuse,
w_init=initz.he_normal(),
use_bias=False,
trainable=True,
attn_size=None,
attn_vec_size=None,
input_size=None,
layer_norm=None,
layer_norm_args=None):
if not isinstance(cell, core_rnn_cell.RNNCell):
raise TypeError("The parameter cell is not RNNCell.")
if not helper.is_sequence(cell.state_size):
raise ValueError("Cell state should be tuple of states")
if attn_length <= 0:
raise ValueError("attn_length should be greater than zero, got %s" % str(attn_length))
if attn_size is None:
attn_size = cell.output_size
if attn_vec_size is None:
attn_vec_size = attn_size
self._cell = cell
self._attn_vec_size = attn_vec_size
self._input_size = input_size
self._attn_size = attn_size
self._attn_length = attn_length
self._w_init = w_init
self._use_bias = use_bias
self.layer_norm = layer_norm
self.layer_norm_args = layer_norm_args or {}
self.reuse = reuse
self.trainable = trainable
@property
def state_size(self):
return (self._cell.state_size, self._attn_size, self._attn_size * self._attn_length)
@property
def output_size(self):
return self._attn_size
def __call__(self, inputs, state, scope='attention_cell'):
"""Long short-term memory cell with attention (LSTMA)."""
with tf.variable_scope(scope, reuse=self.reuse):
state, attns, attn_states = state
attn_states = tf.reshape(attn_states, [-1, self._attn_length, self._attn_size])
input_size = self._input_size
if input_size is None:
input_size = inputs.get_shape().as_list()[1]
inputs = _linear([inputs, attns],
input_size,
self.reuse,
w_init=self._w_init,
use_bias=self._use_bias,
trainable=self.trainable,
name=scope)
lstm_output, new_state = self._cell(inputs, state)
new_state_cat = tf.concat(helper.flatten_sq(new_state), 1)
new_attns, new_attn_states = _attention(
new_state_cat,
attn_states,
True,
self.reuse,
self._attn_size,
self._attn_vec_size,
self._attn_length,
trainable=self.trainable)
with tf.variable_scope("attn_output_projection"):
output = _linear([lstm_output, new_attns],
self._attn_size,
self.reuse,
w_init=self._w_init,
use_bias=self._use_bias,
trainable=self.trainable,
name=scope)
new_attn_states = tf.concat([new_attn_states, tf.expand_dims(output, 1)], 1)
new_attn_states = tf.reshape(new_attn_states, [-1, self._attn_length * self._attn_size])
new_state = (new_state, new_attns, new_attn_states)
if self.layer_norm is not None:
output = self.layer_norm(
output, self.reuse, trainable=self.trainable, **self.layer_norm_args)
new_state = self.layer_norm(
new_state, self.reuse, trainable=self.trainable, **self.layer_norm_args)
return output, new_state
class GRUCell(core_rnn_cell.RNNCell):
"""Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078)
Args:
num_units: int, The number of units in the LSTM cell.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
input_size: Deprecated and unused.
activation: Activation function of the states.
inner_activation: Activation function of the inner states.
layer_norm: If `True`, layer normalization will be applied.
layer_norm_args: optional dict, layer_norm arguments
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
"""
def __init__(self,
num_units,
reuse,
w_init=initz.he_normal(),
use_bias=False,
trainable=True,
input_size=None,
activation=tf.tanh,
inner_activation=tf.sigmoid,
b_init=1.0,
keep_prob=1.0,
layer_norm=None,
layer_norm_args=None):
if input_size is not None:
log.warn("%s: The input_size parameter is deprecated.", self)
self._num_units = num_units
self.reuse = reuse
self.trainable = trainable
self._activation = activation
self._b_init = b_init
self._w_init = w_init
self._use_bias = use_bias
self._keep_prob = keep_prob
self._inner_activation = inner_activation
self.layer_norm = layer_norm
self.layer_norm_args = layer_norm_args or {}
@property
def state_size(self):
return self._num_units
@property
def output_size(self):
return self._num_units
def __call__(self, inputs, state, scope='gru_cell'):
"""Gated recurrent unit (GRU) with nunits cells."""
with tf.variable_scope(scope):
with tf.variable_scope("gates"): # Reset gate and update gate.
# We start with bias of 1.0 to not reset and not update.
r, u = tf.split(
_linear([inputs, state],
2 * self._num_units,
self.reuse,
w_init=self._w_init,
b_init=self._b_init,
use_bias=self._use_bias,
trainable=self.trainable,
name=scope), 2, 1)
r, u = self._inner_activation(r), self._inner_activation(u)
if self.layer_norm is not None:
u = self.layer_norm(u, self.reuse, trainable=self.trainable, **self.layer_norm_args)
r = self.layer_norm(r, self.reuse, trainable=self.trainable, **self.layer_norm_args)
with tf.variable_scope("candidate"):
c = self._activation(
_linear([inputs, r * state],
self._num_units,
self.reuse,
w_init=self._w_init,
b_init=self._b_init,
use_bias=self._use_bias,
name=scope))
new_h = u * state + (1 - u) * c
if self.layer_norm is not None:
c = self.layer_norm(c, self.reuse, trainable=self.trainable, **self.layer_norm_args)
new_h = self.layer_norm(new_h, self.reuse, trainable=self.trainable)
return new_h, new_h
class MultiRNNCell(core_rnn_cell.RNNCell):
"""RNN cell composed sequentially of multiple simple cells.
Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
Raises:
ValueError: Cell state should be tuple of states
"""
def __init__(self, cells, state_is_tuple=True):
if not cells:
raise ValueError("Must specify at least one cell for MultiRNNCell.")
self._cells = cells
# if any(helper.is_sequence(c.state_size) for c in self._cells):
# raise ValueError("Cell state should be tuple of states")
@property
def state_size(self):
return tuple(cell.state_size for cell in self._cells)
@property
def output_size(self):
return self._cells[-1].output_size
def __call__(self, inputs, state, scope='multi_rnn_cell'):
"""Run this multi-layer cell on inputs, starting from state."""
with tf.variable_scope(scope):
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with tf.variable_scope("cell_%d" % i):
if not helper.is_sequence(state):
raise ValueError("Expected state to be a tuple of length %s, but received: %s" %
(self.state_size, state))
cur_state = state[i]
cur_inp, new_state = cell(cur_inp, cur_state)
new_states.append(new_state)
new_states = tuple(new_states)
return cur_inp, new_states
class ExtendedMultiRNNCell(MultiRNNCell):
"""Extends the Tensorflow MultiRNNCell with residual connections."""
def __init__(self,
cells,
residual_connections=False,
residual_combiner="add",
residual_dense=False):
"""Create a RNN cell composed sequentially of a number of RNNCells.
Args:
cells: list of RNNCells that will be composed in this order.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. If False, the states are all
concatenated along the column axis. This latter behavior will soon be
deprecated.
residual_connections: If true, add residual connections between all cells.
This requires all cells to have the same output_size. Also, iff the
input size is not equal to the cell output size, a linear transform
is added before the first layer.
residual_combiner: One of "add" or "concat". To create inputs for layer
t+1 either "add" the inputs from the prev layer or concat them.
residual_dense: Densely connect each layer to all other layers
Raises:
ValueError: if cells is empty (not allowed), or at least one of the cells
returns a state tuple but the flag `state_is_tuple` is `False`.
"""
super(ExtendedMultiRNNCell, self).__init__(cells, state_is_tuple=True)
assert residual_combiner in ["add", "concat", "mean"]
self._residual_connections = residual_connections
self._residual_combiner = residual_combiner
self._residual_dense = residual_dense
def __call__(self, inputs, state, scope=None):
"""Run this multi-layer cell on inputs, starting from state."""
if not self._residual_connections:
return super(ExtendedMultiRNNCell, self).__call__(inputs, state,
(scope or "extended_multi_rnn_cell"))
with tf.variable_scope(scope or "extended_multi_rnn_cell"):
# Adding Residual connections are only possible when input and output
# sizes are equal. Optionally transform the initial inputs to
# `cell[0].output_size`
if self._cells[0].output_size != inputs.get_shape().as_list()[1] and \
(self._residual_combiner in ["add", "mean"]):
inputs = tf.contrib.layers.fully_connected(
inputs=inputs,
num_outputs=self._cells[0].output_size,
activation_fn=None,
scope="input_transform")
# Iterate through all layers (code from MultiRNNCell)
cur_inp = inputs
prev_inputs = [cur_inp]
new_states = []
for i, cell in enumerate(self._cells):
with tf.variable_scope("cell_%d" % i):
if not helper.is_sequence(state):
raise ValueError("Expected state to be a tuple of length %d, but received: %s" % (len(
self.state_size), state))
cur_state = state[i]
next_input, new_state = cell(cur_inp, cur_state)
# Either combine all previous inputs or only the current
# input
input_to_combine = prev_inputs[-1:]
if self._residual_dense:
input_to_combine = prev_inputs
# Add Residual connection
if self._residual_combiner == "add":
next_input = next_input + sum(input_to_combine)
if self._residual_combiner == "mean":
combined_mean = tf.reduce_mean(tf.stack(input_to_combine), 0)
next_input = next_input + combined_mean
elif self._residual_combiner == "concat":
next_input = tf.concat([next_input] + input_to_combine, 1)
cur_inp = next_input
prev_inputs.append(cur_inp)
new_states.append(new_state)
new_states = tuple(new_states)
return cur_inp, new_states
class HighwayCell(core_rnn_cell.RNNCell):
"""RNNCell wrapper that adds highway connection on cell input and output.
Based on: R. K. Srivastava, K. Greff, and J. Schmidhuber, "Highway
networks", arXiv preprint arXiv:1505.00387, 2015.
https://arxiv.org/abs/1505.00387
"""
def __init__(self, cell, reuse, couple_carry_transform_gates=True, carry_bias_init=1.0):
"""Constructs a `HighwayWrapper` for `cell`.
Args:
cell: An instance of `RNNCell`.
couple_carry_transform_gates: boolean, should the Carry and Transform gate
be coupled.
carry_bias_init: float, carry gates bias initialization.
"""
self._cell = cell
self._reuse = reuse
self._couple_carry_transform_gates = couple_carry_transform_gates
self._carry_bias_init = carry_bias_init
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def zero_state(self, batch_size, dtype):
with tf.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
return self._cell.zero_state(batch_size, dtype)
def _highway(self, inp, out):
with tf.variable_scope('highway_cell', reuse=self._reuse):
input_size = inp.get_shape().with_rank(2)[1].value
carry_weight = tf.get_variable("carry_w", [input_size, input_size])
carry_bias = tf.get_variable(
"carry_b", [input_size], initializer=tf.constant_initializer(self._carry_bias_init))
carry = tf.sigmoid(tf.nn.xw_plus_b(inp, carry_weight, carry_bias))
if self._couple_carry_transform_gates:
transform = 1 - carry
else:
transform_weight = tf.get_variable("transform_w", [input_size, input_size])
transform_bias = tf.get_variable(
"transform_b", [input_size], initializer=tf.constant_initializer(-self._carry_bias_init))
transform = tf.sigmoid(tf.nn.xw_plus_b(inp, transform_weight, transform_bias))
return inp * carry + out * transform
def __call__(self, inputs, state, scope='higway_cell'):
"""Run the cell and add its inputs to its outputs.
Args:
inputs: cell inputs.
state: cell state.
scope: optional cell scope.
Returns:
Tuple of cell outputs and new state.
Raises:
TypeError: If cell inputs and outputs have different structure (type).
ValueError: If cell inputs and outputs have different structure (value).
"""
outputs, new_state = self._cell(inputs, state, scope=scope)
nest.assert_same_structure(inputs, outputs)
# Ensure shapes match
def assert_shape_match(inp, out):
inp.get_shape().assert_is_compatible_with(out.get_shape())
nest.map_structure(assert_shape_match, inputs, outputs)
res_outputs = nest.map_structure(self._highway, inputs, outputs)
return (res_outputs, new_state)
class NASCell(core_rnn_cell.RNNCell):
"""Neural Architecture Search (NAS) recurrent network cell.
This implements the recurrent cell from the paper:
https://arxiv.org/abs/1611.01578 Barret Zoph and Quoc V. Le. "Neural
Architecture Search with Reinforcement Learning" Proc. ICLR 2017. The
class uses an optional projection layer.
"""
def __init__(self, num_units, reuse, num_proj=None, use_biases=False, w_init=None, b_init=0.0):
"""Initialize the parameters for a NAS cell.
Args:
num_units: int, The number of units in the NAS cell
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
use_biases: (optional) bool, If True then use biases within the cell. This
is False by default.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
"""
super(NASCell, self).__init__(_reuse=reuse)
self._num_units = num_units
self._num_proj = num_proj
self._use_biases = use_biases
self._reuse = reuse
self._w_init = w_init
self._b_init = b_init
if num_proj is not None:
self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_proj)
self._output_size = num_proj
else:
self._state_size = core_rnn_cell.LSTMStateTuple(num_units, num_units)
self._output_size = num_units
@property
def state_size(self):
return self._state_size
@property
def output_size(self):
return self._output_size
def call(self, inputs, state, scope='NSA_Cell'):
"""Run one step of NAS Cell.
Args:
inputs: input Tensor, 2D, batch x num_units.
state: This must be a tuple of state Tensors, both `2-D`, with column
sizes `c_state` and `m_state`.
Returns:
A tuple containing:
- A `2-D, [batch x output_dim]`, Tensor representing the output of the
NAS Cell after reading `inputs` when previous state was `state`.
Here output_dim is:
num_proj if num_proj was set,
num_units otherwise.
- Tensor(s) representing the new state of NAS Cell after reading `inputs`
when the previous state was `state`. Same type and shape(s) as `state`.
Raises:
ValueError: If input size cannot be inferred from inputs via
static shape inference.
"""
sigmoid = tf.sigmoid
tanh = tf.tanh
relu = tf.nn.relu
num_proj = self._num_units if self._num_proj is None else self._num_proj
(c_prev, m_prev) = state
dtype = inputs.dtype
input_size = inputs.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError("Could not infer input size from inputs.get_shape()[-1]")
# Variables for the NAS cell. W_m is all matrices multiplying the
# hiddenstate and W_inputs is all matrices multiplying the inputs.
with tf.variable_scope(scope, reuse=self._reuse):
concat_w_m = tf.get_variable(
"recurrent_kernel", [num_proj, 8 * self._num_units], dtype, initializer=self._w_init)
concat_w_inputs = tf.get_variable(
"kernel", [input_size.value, 8 * self._num_units], dtype, initializer=self._w_init)
m_matrix = tf.matmul(m_prev, concat_w_m)
inputs_matrix = tf.matmul(inputs, concat_w_inputs)
if self._use_biases:
b = tf.get_variable(
"bias",
shape=[8 * self._num_units],
dtype=dtype,
initializer=tf.constant_initializer(self._b_init))
m_matrix = tf.nn.bias_add(m_matrix, b)
# The NAS cell branches into 8 different splits for both the hiddenstate
# and the input
m_matrix_splits = tf.split(axis=1, num_or_size_splits=8, value=m_matrix)
inputs_matrix_splits = tf.split(axis=1, num_or_size_splits=8, value=inputs_matrix)
# First layer
layer1_0 = sigmoid(inputs_matrix_splits[0] + m_matrix_splits[0])
layer1_1 = relu(inputs_matrix_splits[1] + m_matrix_splits[1])
layer1_2 = sigmoid(inputs_matrix_splits[2] + m_matrix_splits[2])
layer1_3 = relu(inputs_matrix_splits[3] * m_matrix_splits[3])
layer1_4 = tanh(inputs_matrix_splits[4] + m_matrix_splits[4])
layer1_5 = sigmoid(inputs_matrix_splits[5] + m_matrix_splits[5])
layer1_6 = tanh(inputs_matrix_splits[6] + m_matrix_splits[6])
layer1_7 = sigmoid(inputs_matrix_splits[7] + m_matrix_splits[7])
# Second layer
l2_0 = tanh(layer1_0 * layer1_1)
l2_1 = tanh(layer1_2 + layer1_3)
l2_2 = tanh(layer1_4 * layer1_5)
l2_3 = sigmoid(layer1_6 + layer1_7)
# Inject the cell
l2_0 = tanh(l2_0 + c_prev)
# Third layer
l3_0_pre = l2_0 * l2_1
new_c = l3_0_pre # create new cell
l3_0 = l3_0_pre
l3_1 = tanh(l2_2 + l2_3)
# Final layer
new_m = tanh(l3_0 * l3_1)
# Projection layer if specified
if self._num_proj is not None:
concat_w_proj = tf.get_variable(
"projection_weights", [self._num_units, self._num_proj], dtype, initializer=self._w_init)
new_m = tf.matmul(new_m, concat_w_proj)
new_state = core_rnn_cell.LSTMStateTuple(new_c, new_m)
return new_m, new_state
class ConvLSTMCell(core_rnn_cell.RNNCell):
"""Convolutional LSTM recurrent network cell.
https://arxiv.org/pdf/1506.04214v1.pdf
"""
def __init__(self,
conv_ndims,
input_shape,
output_channels,
kernel_shape,
reuse,
use_bias=True,
w_init=None,
b_init=1.0,
skip_connection=False,
forget_bias=1.0,
name="conv_lstm_cell"):
"""Construct ConvLSTMCell.
Args:
conv_ndims: Convolution dimensionality (1, 2 or 3).
input_shape: Shape of the input as int tuple, excluding the batch size.
output_channels: int, number of output channels of the conv LSTM.
kernel_shape: Shape of kernel as in tuple (of size 1,2 or 3).
use_bias: Use bias in convolutions.
reuse: None/True, whether to reuse variables
w_init: weights initializer object
b_init: a `int`, bias initializer value
skip_connection: If set to `True`, concatenate the input to the
output of the conv LSTM. Default: `False`.
forget_bias: Forget bias.
name: Name of the module.
Raises:
ValueError: If `skip_connection` is `True` and stride is different from 1
or if `input_shape` is incompatible with `conv_ndims`.
"""
super(ConvLSTMCell, self).__init__(name=name)
if conv_ndims != len(input_shape) - 1:
raise ValueError("Invalid input_shape {} for conv_ndims={}.".format(input_shape, conv_ndims))
self._conv_ndims = conv_ndims
self._input_shape = input_shape
self._output_channels = output_channels
self._kernel_shape = kernel_shape
self._reuse = reuse
self._w_init = w_init
self._b_init = b_init
self._use_bias = use_bias
self._forget_bias = forget_bias
self._skip_connection = skip_connection
self._total_output_channels = output_channels
if self._skip_connection:
self._total_output_channels += self._input_shape[-1]
state_size = tf.TensorShape(self._input_shape[:-1] + [self._output_channels])
self._state_size = core_rnn_cell.LSTMStateTuple(state_size, state_size)
self._output_size = tf.TensorShape(self._input_shape[:-1] + [self._total_output_channels])
@property
def output_size(self):
return self._output_size
@property
def state_size(self):
return self._state_size
def call(self, inputs, state, scope=None):
cell, hidden = state
new_hidden = _conv([inputs, hidden],
self._kernel_shape,
4 * self._output_channels,
self._use_bias,
self._reuse,
w_init=self._w_init,
b_init=self._b_init)
gates = tf.split(value=new_hidden, num_or_size_splits=4, axis=self._conv_ndims + 1)
input_gate, new_input, forget_gate, output_gate = gates
new_cell = tf.sigmoid(forget_gate + self._forget_bias) * cell
new_cell += tf.sigmoid(input_gate) * tf.tanh(new_input)
output = tf.tanh(new_cell) * tf.sigmoid(output_gate)
if self._skip_connection:
output = tf.concat([output, inputs], axis=-1)
new_state = core_rnn_cell.LSTMStateTuple(new_cell, output)
return output, new_state
class Conv1DLSTMCell(ConvLSTMCell):
"""1D Convolutional LSTM recurrent network cell.
https://arxiv.org/pdf/1506.04214v1.pdf
"""
def __init__(self, name="conv_1d_lstm_cell", **kwargs):
"""Construct Conv1DLSTM.
See `ConvLSTMCell` for more details.
"""
super(Conv1DLSTMCell, self).__init__(conv_ndims=1, **kwargs)
class Conv2DLSTMCell(ConvLSTMCell):
"""2D Convolutional LSTM recurrent network cell.
https://arxiv.org/pdf/1506.04214v1.pdf
"""
def __init__(self, name="conv_2d_lstm_cell", **kwargs):
"""Construct Conv2DLSTM.
See `ConvLSTMCell` for more details.
"""
super(Conv2DLSTMCell, self).__init__(conv_ndims=2, **kwargs)
class Conv3DLSTMCell(ConvLSTMCell):
"""3D Convolutional LSTM recurrent network cell.
https://arxiv.org/pdf/1506.04214v1.pdf
"""
def __init__(self, name="conv_3d_lstm_cell", **kwargs):
"""Construct Conv3DLSTM.
See `ConvLSTMCell` for more details.
"""
super(Conv3DLSTMCell, self).__init__(conv_ndims=3, **kwargs)
def _conv(args, filter_size, num_features, bias, reuse, w_init=None, b_init=0.0, scope='_conv'):
"""convolution:
Args:
args: a Tensor or a list of Tensors of dimension 3D, 4D or 5D
batch x n, Tensors.
filter_size: int tuple of filter height and width.
reuse: None/True, whether to reuse variables
w_init: weights initializer object
b_init: a `int`, bias initializer value
num_features: int, number of features.
bias_start: starting value to initialize the bias; 0 by default.
Returns:
A 3D, 4D, or 5D Tensor with shape [batch ... num_features]
Raises:
ValueError: if some of the arguments has unspecified or wrong shape.
"""
# Calculate the total size of arguments on dimension 1.
total_arg_size_depth = 0
shapes = [a.get_shape().as_list() for a in args]
shape_length = len(shapes[0])
for shape in shapes:
if len(shape) not in [3, 4, 5]:
raise ValueError("Conv Linear expects 3D, 4D or 5D arguments: %s" % str(shapes))
if len(shape) != len(shapes[0]):
raise ValueError("Conv Linear expects all args to be of same Dimensiton: %s" % str(shapes))
else:
total_arg_size_depth += shape[-1]
dtype = [a.dtype for a in args][0]
# determine correct conv operation
if shape_length == 3:
conv_op = tf.nn.conv1d
strides = 1
elif shape_length == 4:
conv_op = tf.nn.conv2d
strides = shape_length * [1]
elif shape_length == 5:
conv_op = tf.nn.conv3d
strides = shape_length * [1]
# Now the computation.
with tf.variable_scope(scope, reuse=reuse):
kernel = tf.get_variable(
"W", filter_size + [total_arg_size_depth, num_features], dtype=dtype, initializer=w_init)
if len(args) == 1:
res = conv_op(args[0], kernel, strides, padding='SAME')
else:
res = conv_op(tf.concat(axis=shape_length - 1, values=args), kernel, strides, padding='SAME')
if not bias:
return res
bias_term = tf.get_variable(
"biases", [num_features],
dtype=dtype,
initializer=tf.constant_initializer(b_init, dtype=dtype))
return res + bias_term
class GLSTMCell(core_rnn_cell.RNNCell):
"""Group LSTM cell (G-LSTM).
The implementation is based on: https://arxiv.org/abs/1703.10722 O.
Kuchaiev and B. Ginsburg "Factorization Tricks for LSTM Networks",
ICLR 2017 workshop.
"""
def __init__(self,
num_units,
reuse,
w_init=initz.he_normal(),
b_init=0.0,
use_bias=False,
initializer=None,
num_proj=None,
number_of_groups=1,
forget_bias=1.0,
activation=tf.tanh):
"""Initialize the parameters of G-LSTM cell.
Args:
num_units: int, The number of units in the G-LSTM cell
initializer: (optional) The initializer to use for the weight and
projection matrices.
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
number_of_groups: (optional) int, number of groups to use.
If `number_of_groups` is 1, then it should be equivalent to LSTM cell
forget_bias: Biases of the forget gate are initialized by default to 1
in order to reduce the scale of forgetting at the beginning of
the training.
activation: Activation function of the inner states.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already
has the given variables, an error is raised.
Raises:
ValueError: If `num_units` or `num_proj` is not divisible by
`number_of_groups`.
"""
self._num_units = num_units
self._initializer = initializer
self._num_proj = num_proj
self._forget_bias = forget_bias
self._activation = activation
self._number_of_groups = number_of_groups
self._w_init = w_init
self._b_init = b_init
self._use_bias = use_bias
self.reuse = reuse
if self._num_units % self._number_of_groups != 0:
raise ValueError("num_units must be divisible by number_of_groups")
if self._num_proj:
if self._num_proj % self._number_of_groups != 0:
raise ValueError("num_proj must be divisible by number_of_groups")
self._group_shape = [
int(self._num_proj / self._number_of_groups),
int(self._num_units / self._number_of_groups)
]
else:
self._group_shape = [
int(self._num_units / self._number_of_groups),
int(self._num_units / self._number_of_groups)