forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFNetworkRecLayer.py
6289 lines (5790 loc) · 279 KB
/
TFNetworkRecLayer.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
"""
Defines multiple recurrent layers, most importantly :class:`RecLayer`.
"""
from __future__ import print_function
import tensorflow as tf
import typing
from tensorflow.python.ops.nn import rnn_cell
from TFNetworkLayer import LayerBase, _ConcatInputLayer, SearchChoices, get_concat_sources_data_template, Loss
from TFUtil import Data, reuse_name_scope, get_random_seed
from Util import NotSpecified
from Log import log
class RecLayer(_ConcatInputLayer):
"""
Recurrent layer, has support for several implementations of LSTMs (via ``unit`` argument),
see :ref:`tf_lstm_benchmark` (http://returnn.readthedocs.io/en/latest/tf_lstm_benchmark.html),
and also GRU, or simple RNN.
Via `unit` parameter, you specify the operation/model performed in the recurrence.
It can be a string and specify a RNN cell, where all TF cells can be used,
and the `"Cell"` suffix can be omitted; and case is ignored.
Some possible LSTM implementations are (in all cases for both CPU and GPU):
* BasicLSTM (the cell), via official TF, pure TF implementation
* LSTMBlock (the cell), via tf.contrib.rnn.
* LSTMBlockFused, via tf.contrib.rnn. should be much faster than BasicLSTM
* CudnnLSTM, via tf.contrib.cudnn_rnn. This is experimental yet.
* NativeLSTM, our own native LSTM. should be faster than LSTMBlockFused.
* NativeLstm2, improved own native LSTM, should be the fastest and most powerful.
We default to the current tested fastest one, i.e. NativeLSTM.
Note that they are currently not compatible to each other, i.e. the way the parameters are represented.
A subnetwork can also be given which will be evaluated step-by-step,
which can use attention over some separate input,
which can be used to implement a decoder in a sequence-to-sequence scenario.
The subnetwork will get the extern data from the parent net as templates,
and if there is input to the RecLayer,
then it will be available as the "source" data key in the subnetwork.
The subnetwork is specified as a `dict` for the `unit` parameter.
In the subnetwork, you can access outputs from layers from the previous time step when they
are referred to with the "prev:" prefix.
Example::
{
"class": "rec",
"from": ["input"],
"unit": {
# Recurrent subnet here, operate on a single time-step:
"output": {
"class": "linear",
"from": ["prev:output", "data:source"],
"activation": "relu",
"n_out": n_out},
},
"n_out": n_out},
}
More examples can be seen in :mod:`test_TFNetworkRecLayer` and :mod:`test_TFEngine`.
The subnetwork can automatically optimize the inner recurrent loop
by moving layers out of the loop if possible.
It will try to do that greedily. This can be disabled via the option `optimize_move_layers_out`.
It assumes that those layers behave the same with time-dimension or without time-dimension and used per-step.
Examples for such layers are :class:`LinearLayer`, :class:`RnnCellLayer`
or :class:`SelfAttentionLayer` with option `attention_left_only`.
This layer can also be inside another RecLayer. In that case, it behaves similar to :class:`RnnCellLayer`.
(This support is somewhat incomplete yet. It should work for the native units such as NativeLstm.)
"""
layer_class = "rec"
recurrent = True
_default_lstm_unit = "nativelstm" # TFNativeOp.NativeLstmCell
def __init__(self,
unit="lstm", unit_opts=None,
direction=None, input_projection=True,
initial_state=None,
max_seq_len=None,
forward_weights_init=None, recurrent_weights_init=None, bias_init=None,
optimize_move_layers_out=None,
cheating=False,
unroll=False,
use_global_rec_step_offset=False,
**kwargs):
"""
:param str|dict[str,dict[str]] unit: the RNNCell/etc name, e.g. "nativelstm". see comment below.
alternatively a whole subnetwork, which will be executed step by step,
and which can include "prev" in addition to "from" to refer to previous steps.
:param None|dict[str] unit_opts: passed to RNNCell creation
:param int|None direction: None|1 -> forward, -1 -> backward
:param bool input_projection: True -> input is multiplied with matrix. False only works if same input dim
:param LayerBase|str|float|int|tuple|None initial_state:
:param int|tf.Tensor|None max_seq_len: if unit is a subnetwork. str will be evaluated. see code
:param str forward_weights_init: see :func:`TFUtil.get_initializer`
:param str recurrent_weights_init: see :func:`TFUtil.get_initializer`
:param str bias_init: see :func:`TFUtil.get_initializer`
:param bool|None optimize_move_layers_out: will automatically move layers out of the loop when possible
:param bool cheating: make targets available, and determine length by them
:param bool unroll: if possible, unroll the loop (implementation detail)
:param bool use_global_rec_step_offset:
"""
super(RecLayer, self).__init__(**kwargs)
import re
from TFUtil import is_gpu_available
from tensorflow.contrib import rnn as rnn_contrib
from tensorflow.python.util import nest
if is_gpu_available():
from tensorflow.contrib import cudnn_rnn
else:
cudnn_rnn = None
import TFNativeOp
if direction is not None:
assert direction in [-1, 1]
self._last_hidden_state = None # type: typing.Optional[tf.Tensor]
self._direction = direction
self._initial_state_deps = [l for l in nest.flatten(initial_state) if isinstance(l, LayerBase)]
self._input_projection = input_projection
self._max_seq_len = max_seq_len
if optimize_move_layers_out is None:
optimize_move_layers_out = self.network.get_config().bool("optimize_move_layers_out", True)
self._optimize_move_layers_out = optimize_move_layers_out
if cheating:
print("%s: cheating enabled, i.e. we know the ground truth seq length" % self, file=log.v2)
self._cheating = cheating
self._unroll = unroll
self._use_global_rec_step_offset = use_global_rec_step_offset
# On the random initialization:
# For many cells, e.g. NativeLSTM: there will be a single recurrent weight matrix, (output.dim, output.dim * 4),
# and a single input weight matrix (input_data.dim, output.dim * 4), and a single bias (output.dim * 4,).
# The bias is by default initialized with 0.
# In the Theano :class:`RecurrentUnitLayer`, create_recurrent_weights() and create_forward_weights() are used,
# where forward_weights_init = "random_uniform(p_add=%i)" % (output.dim * 4)
# and recurrent_weights_init = "random_uniform()",
# thus with in=input_data.dim, out=output.dim,
# for forward weights: uniform sqrt(6. / (in + out*8)), for rec. weights: uniform sqrt(6. / (out*5)).
# TensorFlow initializers:
# https://www.tensorflow.org/api_docs/python/tf/initializers
# https://www.tensorflow.org/api_docs/python/tf/keras/initializers/Orthogonal
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/init_ops.py
# xavier_initializer with uniform=True: uniform sqrt(6 / (fan_in + fan_out)),
# i.e. uniform sqrt(6. / (in + out*4)) for forward, sqrt(6./(out*5)) for rec.
# Ref: https://www.tensorflow.org/api_docs/python/tf/contrib/layers/xavier_initializer
# Keras uses these defaults:
# Ref: https://github.com/fchollet/keras/blob/master/keras/layers/recurrent.py
# Ref: https://keras.io/initializers/, https://github.com/fchollet/keras/blob/master/keras/engine/topology.py
# (fwd weights) kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal',
# where glorot_uniform is sqrt(6 / (fan_in + fan_out)), i.e. fwd weights: uniform sqrt(6 / (in + out*4)),
# and orthogonal creates a random orthogonal matrix (fan_in, fan_out), i.e. rec (out, out*4).
self._bias_initializer = tf.constant_initializer(0.0)
self._fwd_weights_initializer = None
self._rec_weights_initializer = None
from TFUtil import get_initializer, xavier_initializer
if forward_weights_init is not None:
self._fwd_weights_initializer = get_initializer(
forward_weights_init, seed=self.network.random.randint(2**31), eval_local_ns={"layer": self})
if recurrent_weights_init is not None:
self._rec_weights_initializer = get_initializer(
recurrent_weights_init, seed=self.network.random.randint(2**31), eval_local_ns={"layer": self})
if bias_init is not None:
self._bias_initializer = get_initializer(
bias_init, seed=self.network.random.randint(2**31), eval_local_ns={"layer": self})
if self._rec_weights_initializer:
default_var_initializer = self._rec_weights_initializer
elif self._fwd_weights_initializer:
default_var_initializer = self._fwd_weights_initializer
else:
default_var_initializer = xavier_initializer(seed=self.network.random.randint(2**31))
with reuse_name_scope("rec", initializer=default_var_initializer) as scope:
assert isinstance(scope, tf.VariableScope)
self._rec_scope = scope
scope_name_prefix = scope.name + "/" # e.g. "layer1/rec/"
with self.var_creation_scope():
self._initial_state = None
if self._rec_previous_layer: # inside another RecLayer
self._initial_state = self._rec_previous_layer.rec_vars_outputs["state"]
elif initial_state is not None:
if initial_state:
assert isinstance(unit, str), 'initial_state not supported currently for custom unit'
self._initial_state = RnnCellLayer.get_rec_initial_state(
initial_state=initial_state, n_out=self.output.dim, unit=unit, unit_opts=unit_opts,
batch_dim=self.network.get_data_batch_dim(), name=self.name,
rec_layer=self)
self.cell = self._get_cell(unit, unit_opts=unit_opts)
if isinstance(self.cell, (rnn_cell.RNNCell, rnn_contrib.FusedRNNCell, rnn_contrib.LSTMBlockWrapper)):
y = self._get_output_cell(self.cell)
elif cudnn_rnn and isinstance(self.cell, (cudnn_rnn.CudnnLSTM, cudnn_rnn.CudnnGRU)):
y = self._get_output_cudnn(self.cell)
elif isinstance(self.cell, TFNativeOp.RecSeqCellOp):
y = self._get_output_native_rec_op(self.cell)
elif isinstance(self.cell, _SubnetworkRecCell):
y = self._get_output_subnet_unit(self.cell)
else:
raise Exception("invalid type: %s" % type(self.cell))
if self._rec_previous_layer: # inside another RecLayer
self.rec_vars_outputs["state"] = self._last_hidden_state
self.output.placeholder = y
# Very generic way to collect all created params.
# Note that for the TF RNN cells, there is no other way to do this.
# Also, see the usage of :func:`LayerBase.cls_layer_scope`, e.g. for initial vars.
params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=re.escape(scope_name_prefix))
self._add_params(params=params, scope_name_prefix=scope_name_prefix)
# More specific way. Should not really add anything anymore but you never know.
# Also, this will update self.saveable_param_replace.
if isinstance(self.cell, _SubnetworkRecCell):
self._add_params(params=self.cell.net.get_params_list(), scope_name_prefix=scope_name_prefix)
self.saveable_param_replace.update(self.cell.net.get_saveable_param_replace_dict())
if self.cell.input_layers_net:
self._add_params(params=self.cell.input_layers_net.get_params_list(), scope_name_prefix=scope_name_prefix)
self.saveable_param_replace.update(self.cell.input_layers_net.get_saveable_param_replace_dict())
if self.cell.output_layers_net:
self._add_params(params=self.cell.output_layers_net.get_params_list(), scope_name_prefix=scope_name_prefix)
self.saveable_param_replace.update(self.cell.output_layers_net.get_saveable_param_replace_dict())
def _add_params(self, scope_name_prefix, params):
"""
:param str scope_name_prefix:
:param list[tf.Variable] params:
"""
for p in params:
if not p.name.startswith(scope_name_prefix):
continue
assert p.name.startswith(scope_name_prefix) and p.name.endswith(":0")
self.add_param(p)
# Sublayers do not know whether the RecLayer is trainable. If it is not, we need to mark all defined parameters
# as untrainable
if not self.trainable:
trainable_collection_ref = p.graph.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES)
if p in trainable_collection_ref:
trainable_collection_ref.remove(p)
def get_dep_layers(self):
"""
:rtype: list[LayerBase]
"""
ls = super(RecLayer, self).get_dep_layers()
ls += self._initial_state_deps
if isinstance(self.cell, _SubnetworkRecCell):
ls += self.cell.get_parent_deps()
return ls
@classmethod
def transform_config_dict(cls, d, network, get_layer):
"""
This method transforms the templates in the config dictionary into references
of the layer instances (and creates them in the process).
:param dict[str] d: will modify inplace
:param TFNetwork.TFNetwork network:
:param ((str) -> LayerBase) get_layer: function to get or construct another layer
"""
if isinstance(d.get("unit"), dict):
d["n_out"] = d.get("n_out", NotSpecified) # disable automatic guessing
super(RecLayer, cls).transform_config_dict(d, network=network, get_layer=get_layer) # everything except "unit"
if "initial_state" in d:
d["initial_state"] = RnnCellLayer.transform_initial_state(
d["initial_state"], network=network, get_layer=get_layer)
if isinstance(d.get("unit"), dict):
def sub_get_layer(name):
"""
:param str name:
:rtype: LayerBase
"""
# Only used to resolve deps to base network.
if name.startswith("base:"):
return get_layer(name[len("base:"):]) # calls get_layer of parent network
from TFNetwork import TFNetwork, ExternData
subnet = TFNetwork(parent_net=network, extern_data=network.extern_data) # dummy subnet
for sub in d["unit"].values(): # iterate over the layers of the subnet
assert isinstance(sub, dict)
if "class" in sub:
from TFNetworkLayer import get_layer_class
class_name = sub["class"]
cl = get_layer_class(class_name)
# Operate on a copy because we will transform the dict later.
# We only need this to resolve any other layer dependencies in the main network.
cl.transform_config_dict(sub.copy(), network=subnet, get_layer=sub_get_layer)
if isinstance(d.get("max_seq_len"), str):
from TFNetwork import LayerNotFound
def max_len_from(src):
"""
:param str src: layer name
:return: max seq-len of the layer output
:rtype: tf.Tensor
"""
layer = None
if src.startswith("base:"):
# For legacy reasons, this was interpret to be in the subnet, so this should access the current net.
# However, now we want that this behaves more standard, such that "base:" accesses the parent net,
# but we also want to not break old configs.
# We first check whether there is such a layer in the parent net.
try:
layer = get_layer(src)
except LayerNotFound:
src = src[len("base:"):] # This will fall-back to the old behavior.
if not layer:
layer = get_layer(src)
return tf.reduce_max(layer.output.get_sequence_lengths(), name="max_seq_len_%s" % layer.tf_scope_name)
# Note: Normally we do not expect that anything is added to the TF computation graph
# within transform_config_dict, so this is kind of bad practice.
# However, we must make sure at this point that any layers will get resolved via get_layer calls.
# Also make sure that we do not introduce any new name-scope here
# as this would confuse recursive get_layer calls.
d["max_seq_len"] = eval(d["max_seq_len"], {"max_len_from": max_len_from, "tf": tf})
@classmethod
def get_out_data_from_opts(cls, unit, sources=(), initial_state=None, **kwargs):
"""
:param str|dict[str] unit:
:param list[LayerBase] sources:
:param str|LayerBase|list[str|LayerBase] initial_state:
:rtype: Data
"""
from tensorflow.python.util import nest
source_data = get_concat_sources_data_template(sources) if sources else None
if source_data and not source_data.have_time_axis():
# We expect to be inside another RecLayer, and should do a single step (like RnnCellLayer).
out_time_dim_axis = None
out_batch_dim_axis = 0
else:
out_time_dim_axis = 0
out_batch_dim_axis = 1
n_out = kwargs.get("n_out", NotSpecified)
out_type = kwargs.get("out_type", None)
loss = kwargs.get("loss", None)
deps = list(sources) # type: typing.List[LayerBase]
deps += [l for l in nest.flatten(initial_state) if isinstance(l, LayerBase)]
if out_type or n_out is not NotSpecified or loss:
if out_type:
assert out_type.get("time_dim_axis", out_time_dim_axis) == out_time_dim_axis
assert out_type.get("batch_dim_axis", out_batch_dim_axis) == out_batch_dim_axis
out = super(RecLayer, cls).get_out_data_from_opts(sources=sources, **kwargs)
else:
out = None
if isinstance(unit, dict): # subnetwork
subnet = _SubnetworkRecCell(parent_net=kwargs["network"], net_dict=unit, source_data=source_data)
sub_out = subnet.layer_data_templates["output"].output.copy_template_adding_time_dim(
name="%s_output" % kwargs["name"], time_dim_axis=0)
if out:
assert sub_out.dim == out.dim
assert sub_out.shape == out.shape
out = sub_out
deps += subnet.get_parent_deps()
assert out
out.time_dim_axis = out_time_dim_axis
out.batch_dim_axis = out_batch_dim_axis
cls._post_init_output(output=out, sources=sources, **kwargs)
for dep in deps:
out.beam_size = out.beam_size or dep.output.beam_size
return out
def get_absolute_name_scope_prefix(self):
"""
:rtype: str
"""
return self.get_base_absolute_name_scope_prefix() + "rec/" # all under "rec" sub-name-scope
@classmethod
def get_rec_initial_extra_outputs(cls, **kwargs):
"""
:rtype: dict[str,tf.Tensor|tuple[tf.Tensor]]
"""
sources = kwargs.get("sources")
source_data = get_concat_sources_data_template(sources) if sources else None
if source_data and not source_data.have_time_axis():
# We expect to be inside another RecLayer, and should do a single step (like RnnCellLayer).
return {"state": RnnCellLayer.get_rec_initial_state(**kwargs)}
return {}
@classmethod
def get_rec_initial_output(cls, **kwargs):
"""
:rtype: tf.Tensor
"""
# This is only called if we are inside another rec layer.
return RnnCellLayer.get_rec_initial_output(**kwargs)
_rnn_cells_dict = {}
@classmethod
def _create_rnn_cells_dict(cls):
from TFUtil import is_gpu_available
from tensorflow.contrib import rnn as rnn_contrib
import TFNativeOp
allowed_types = (rnn_cell.RNNCell, rnn_contrib.FusedRNNCell, rnn_contrib.LSTMBlockWrapper, TFNativeOp.RecSeqCellOp)
if is_gpu_available():
from tensorflow.contrib import cudnn_rnn
allowed_types += (cudnn_rnn.CudnnLSTM, cudnn_rnn.CudnnGRU)
else:
cudnn_rnn = None
# noinspection PyShadowingNames
def maybe_add(key, v):
"""
:param str key:
:param type v:
"""
if isinstance(v, type) and issubclass(v, allowed_types):
name = key
if name.endswith("Cell"):
name = name[:-len("Cell")]
name = name.lower()
assert cls._rnn_cells_dict.get(name) in [v, None]
cls._rnn_cells_dict[name] = v
for key, v in globals().items():
maybe_add(key, v)
for key, v in vars(rnn_contrib).items():
maybe_add(key, v)
for key, v in vars(TFNativeOp).items():
maybe_add(key, v)
if is_gpu_available():
for key, v in vars(cudnn_rnn).items():
maybe_add(key, v)
# Alias for the standard LSTM cell, because self._get_cell(unit="lstm") will use "NativeLSTM" by default.
maybe_add("StandardLSTM", rnn_contrib.LSTMCell)
_warn_msg_once_for_cell_name = set()
@classmethod
def get_rnn_cell_class(cls, name):
"""
:param str name: cell name, minus the "Cell" at the end
:rtype: () -> rnn_cell.RNNCell|TFNativeOp.RecSeqCellOp
"""
if not cls._rnn_cells_dict:
cls._create_rnn_cells_dict()
from TFUtil import is_gpu_available
if not is_gpu_available():
m = {"cudnnlstm": "LSTMBlockFused", "cudnngru": "GRUBlock"}
if name.lower() in m:
if name.lower() not in cls._warn_msg_once_for_cell_name:
print("You have selected unit %r in a rec layer which is for GPU only, so we are using %r instead." %
(name, m[name.lower()]), file=log.v2)
cls._warn_msg_once_for_cell_name.add(name.lower())
name = m[name.lower()]
if name.lower() in ["lstmp", "lstm"]:
name = cls._default_lstm_unit
if name.lower() not in cls._rnn_cells_dict:
raise Exception("unknown cell %r. known cells: %r" % (name, sorted(cls._rnn_cells_dict.keys())))
return cls._rnn_cells_dict[name.lower()]
def _get_input(self):
"""
:return: (x, seq_len), where x is (time,batch,...,dim) and seq_len is (batch,)
:rtype: (tf.Tensor, tf.Tensor)
"""
assert self.input_data
if self.input_data.have_time_axis():
x = self.input_data.placeholder # (batch,time,dim) or (time,batch,dim)
if not self.input_data.is_time_major:
assert self.input_data.batch_dim_axis == 0
assert self.input_data.time_dim_axis == 1
x = self.input_data.get_placeholder_as_time_major() # (time,batch,[dim])
seq_len = self.input_data.get_sequence_lengths()
return x, seq_len
else: # no time-dim-axis, expect to be inside another RecLayer
# Just add a dummy time dim, and seq_len == 1 everywhere.
x = self.input_data.placeholder
x = tf.expand_dims(x, 0)
seq_len = tf.ones([self.input_data.get_batch_dim()], dtype=self.input_data.size_dtype)
return x, seq_len
@classmethod
def get_losses(cls, name, network, output, loss=None, reduce_func=None, layer=None, **kwargs):
"""
:param str name: layer name
:param TFNetwork.TFNetwork network:
:param Loss|None loss: argument just as for __init__
:param Data output: the output (template) for the layer
:param ((tf.Tensor)->tf.Tensor)|None reduce_func:
:param LayerBase|None layer:
:param kwargs: other layer kwargs
:rtype: list[TFNetwork.LossHolder]
"""
from TFNetwork import LossHolder
losses = super(RecLayer, cls).get_losses(
name=name, network=network, output=output, loss=loss, layer=layer, reduce_func=reduce_func, **kwargs)
unit = kwargs["unit"]
if isinstance(unit, dict): # subnet
if layer:
assert isinstance(layer, RecLayer)
assert isinstance(layer.cell, _SubnetworkRecCell)
subnet = layer.cell
else:
sources = kwargs["sources"]
source_data = get_concat_sources_data_template(sources) if sources else None
subnet = _SubnetworkRecCell(parent_net=network, net_dict=unit, source_data=source_data)
for layer_name, template_layer in sorted(subnet.layer_data_templates.items()):
assert isinstance(template_layer, _TemplateLayer)
assert issubclass(template_layer.layer_class_type, LayerBase)
for loss in template_layer.layer_class_type.get_losses(reduce_func=reduce_func, **template_layer.kwargs):
assert isinstance(loss, LossHolder)
if layer:
assert loss.name in subnet.accumulated_losses
loss = subnet.accumulated_losses[loss.name]
assert isinstance(loss, LossHolder)
assert loss.get_layer()
loss = loss.copy_new_base(network=network, name="%s/%s" % (name, loss.name), reduce_func=reduce_func)
losses.append(loss)
return losses
def get_constraints_value(self):
"""
:rtype: tf.Tensor
"""
v = super(RecLayer, self).get_constraints_value()
from TFUtil import optional_add
if isinstance(self.cell, _SubnetworkRecCell):
layers = list(self.cell.net.layers.values())
if self.cell.input_layers_net:
layers += list(self.cell.input_layers_net.layers.values())
if self.cell.output_layers_net:
layers += list(self.cell.output_layers_net.layers.values())
for layer in layers:
v = optional_add(v, layer.get_constraints_value())
return v
def _get_cell(self, unit, unit_opts=None):
"""
:param str|dict[str] unit:
:param None|dict[str] unit_opts:
:rtype: _SubnetworkRecCell|tensorflow.contrib.rnn.RNNCell|tensorflow.contrib.rnn.FusedRNNCell|TFNativeOp.RecSeqCellOp
"""
from TFUtil import is_gpu_available
from tensorflow.contrib import rnn as rnn_contrib
import TFNativeOp
if isinstance(unit, dict):
assert unit_opts is None
return _SubnetworkRecCell(parent_rec_layer=self, net_dict=unit)
assert isinstance(unit, str)
rnn_cell_class = self.get_rnn_cell_class(unit)
n_hidden = self.output.dim
if unit_opts is None:
unit_opts = {}
if is_gpu_available():
from tensorflow.contrib import cudnn_rnn
if issubclass(rnn_cell_class, (cudnn_rnn.CudnnLSTM, cudnn_rnn.CudnnGRU)):
# noinspection PyArgumentList
cell = rnn_cell_class(
num_layers=1, num_units=n_hidden,
input_mode='linear_input', direction='unidirectional', dropout=0.0, **unit_opts)
return cell
if issubclass(rnn_cell_class, TFNativeOp.RecSeqCellOp):
# noinspection PyArgumentList
cell = rnn_cell_class(
n_hidden=n_hidden, n_input_dim=self.input_data.dim,
input_is_sparse=self.input_data.sparse,
step=self._direction, **unit_opts)
return cell
# noinspection PyArgumentList
cell = rnn_cell_class(n_hidden, **unit_opts)
assert isinstance(
cell, (rnn_contrib.RNNCell, rnn_contrib.FusedRNNCell, rnn_contrib.LSTMBlockWrapper)) # e.g. BasicLSTMCell
return cell
def _get_output_cell(self, cell):
"""
:param tensorflow.contrib.rnn.RNNCell|tensorflow.contrib.rnn.FusedRNNCell cell:
:return: output of shape (time, batch, dim)
:rtype: tf.Tensor
"""
from tensorflow.python.ops import rnn
from tensorflow.contrib import rnn as rnn_contrib
assert self.input_data
assert not self.input_data.sparse
x, seq_len = self._get_input()
if self._direction == -1:
x = tf.reverse_sequence(x, seq_lengths=seq_len, batch_dim=1, seq_dim=0)
if isinstance(cell, BaseRNNCell):
with tf.variable_scope(tf.get_variable_scope(), initializer=self._fwd_weights_initializer):
x = cell.get_input_transformed(x)
if isinstance(cell, rnn_cell.RNNCell): # e.g. BasicLSTMCell
if self._unroll:
assert self._max_seq_len is not None, "specify max_seq_len for unroll"
# We must get x.shape[0] == self._max_seq_len, so pad it.
x_shape = x.get_shape().as_list()
original_len = tf.shape(x)[0]
# With unrolling, normally we would require max_seq_len >= original_len.
# Earlier, we just truncated it in that case and filled with zero afterwards,
# which is bad, as this silently introduces wrong behavior for this case.
with tf.control_dependencies([
tf.assert_greater_equal(self._max_seq_len, original_len,
message="required for unroll: max_seq_len >= seq_len")]):
pad_len = tf.maximum(0, self._max_seq_len - original_len) # max, in case we want to support truncate later
x = tf.pad(x, [(0, pad_len), (0, 0), (0, 0)])
x.set_shape([self._max_seq_len] + x_shape[1:])
x = tf.unstack(x, axis=0, num=self._max_seq_len)
y, final_state = rnn.static_rnn(
cell=cell, dtype=tf.float32, inputs=x, sequence_length=seq_len,
initial_state=self._initial_state)
y = tf.stack(y, axis=0)
y.set_shape([self._max_seq_len, None, self.output.dim]) # (time,batch,ydim)
# Now, recover the original len.
y = y[:original_len]
else:
# Will get (time,batch,ydim).
assert self._max_seq_len is None
y, final_state = rnn.dynamic_rnn(
cell=cell, inputs=x, time_major=True, sequence_length=seq_len, dtype=tf.float32,
initial_state=self._initial_state)
self._last_hidden_state = final_state
elif isinstance(cell, (rnn_contrib.FusedRNNCell, rnn_contrib.LSTMBlockWrapper)): # e.g. LSTMBlockFusedCell
# Will get (time,batch,ydim).
assert self._max_seq_len is None
y, final_state = cell(
inputs=x, sequence_length=seq_len, dtype=tf.float32,
initial_state=self._initial_state)
self._last_hidden_state = final_state
else:
raise Exception("invalid type: %s" % type(cell))
if self._direction == -1:
y = tf.reverse_sequence(y, seq_lengths=seq_len, batch_dim=1, seq_dim=0)
return y
@staticmethod
def _get_cudnn_param_size(num_units, input_size,
num_layers=1, rnn_mode="lstm", input_mode="linear_input", direction='unidirectional'):
"""
:param int num_layers:
:param int num_units:
:param int input_size:
:param str rnn_mode: 'lstm', 'gru', 'rnn_tanh' or 'rnn_relu'
:param str input_mode: "linear_input", "skip_input", "auto_select". note that we have a different default.
:param str direction: 'unidirectional' or 'bidirectional'
:return: size
:rtype: int
"""
# Also see test_RecLayer_get_cudnn_params_size().
dir_count = {"unidirectional": 1, "bidirectional": 2}[direction]
num_gates = {"lstm": 3, "gru": 2}.get(rnn_mode, 0)
if input_mode == "linear_input" or (input_mode == "auto_select" and num_units != input_size):
# (input + recurrent + 2 * bias) * output * (gates + cell in)
size = (input_size + num_units + 2) * num_units * (num_gates + 1) * dir_count
elif input_mode == "skip_input" or (input_mode == "auto_select" and num_units == input_size):
# (recurrent + 2 * bias) * output * (gates + cell in)
size = (num_units + 2) * num_units * (num_gates + 1) * dir_count
else:
raise Exception("invalid input_mode %r" % input_mode)
# Remaining layers:
size += (num_units * dir_count + num_units + 2) * num_units * (num_gates + 1) * dir_count * (num_layers - 1)
return size
@staticmethod
def convert_cudnn_canonical_to_lstm_block(reader, prefix, target="lstm_block_wrapper/"):
"""
This assumes CudnnLSTM currently, with num_layers=1, input_mode="linear_input", direction='unidirectional'!
:param tf.train.CheckpointReader reader:
:param str prefix: e.g. "layer2/rec/"
:param str target: e.g. "lstm_block_wrapper/" or "rnn/lstm_cell/"
:return: dict key -> value, {".../kernel": ..., ".../bias": ...} with prefix
:rtype: dict[str,numpy.ndarray]
"""
# For reference:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
# For CudnnLSTM, there are 8 tensors per weight and per bias for each
# layer: tensor 0-3 are applied to the input from the previous layer and
# tensor 4-7 to the recurrent input. Tensor 0 and 4 are for the input gate;
# tensor 1 and 5 the forget gate; tensor 2 and 6 the new memory gate;
# tensor 3 and 7 the output gate.
import numpy
num_vars = 16
values = []
for i in range(num_vars):
values.append(reader.get_tensor("%scudnn/CudnnRNNParamsToCanonical:%i" % (prefix, i)))
assert len(values[-1].shape) == 1
output_dim = values[-1].shape[0]
# For some reason, the input weight matrices are sometimes flattened.
assert numpy.prod(values[0].shape) % output_dim == 0
input_dim = numpy.prod(values[0].shape) // output_dim
weights_and_biases = [
(numpy.concatenate(
[numpy.reshape(values[i], [output_dim, input_dim]), # input weights
numpy.reshape(values[i + 4], [output_dim, output_dim])], # recurrent weights
axis=1),
values[8 + i] + # input bias
values[8 + i + 4] # recurrent bias
)
for i in range(4)]
# cuDNN weights are in ifco order, convert to icfo order.
weights_and_biases[1:3] = reversed(weights_and_biases[1:3])
weights = numpy.transpose(numpy.concatenate([wb[0] for wb in weights_and_biases], axis=0))
biases = numpy.concatenate([wb[1] for wb in weights_and_biases], axis=0)
return {prefix + target + "kernel": weights, prefix + target + "bias": biases}
def _get_output_cudnn(self, cell):
"""
:param tensorflow.contrib.cudnn_rnn.CudnnLSTM|tensorflow.contrib.cudnn_rnn.CudnnGRU cell:
:return: output of shape (time, batch, dim)
:rtype: tf.Tensor
"""
from TFUtil import get_current_var_scope_name
from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops
assert self._max_seq_len is None
assert self.input_data
assert not self.input_data.sparse
x, seq_len = self._get_input()
n_batch = tf.shape(seq_len)[0]
if self._direction == -1:
x = tf.reverse_sequence(x, seq_lengths=seq_len, batch_dim=1, seq_dim=0)
with tf.variable_scope("cudnn"):
cell.build(x.get_shape())
num_layers = 1
# noinspection PyProtectedMember
rnn_mode = cell._rnn_mode
param_size = self._get_cudnn_param_size(
num_units=self.output.dim, input_size=self.input_data.dim, rnn_mode=rnn_mode, num_layers=num_layers)
# Note: The raw params used during training for the cuDNN op is just a single variable
# with all params concatenated together.
# For the checkpoint save/restore, we will use Cudnn*Saveable, which also makes it easier in CPU mode
# to import the params for another unit like LSTMBlockCell.
# Also see:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_ops_test.py
params = cell.kernel
params.set_shape([param_size])
if rnn_mode == cudnn_rnn_ops.CUDNN_LSTM:
fn = cudnn_rnn_ops.CudnnLSTMSaveable
elif rnn_mode == cudnn_rnn_ops.CUDNN_GRU:
fn = cudnn_rnn_ops.CudnnGRUSaveable
elif rnn_mode == cudnn_rnn_ops.CUDNN_RNN_TANH:
fn = cudnn_rnn_ops.CudnnRNNTanhSaveable
elif rnn_mode == cudnn_rnn_ops.CUDNN_RNN_RELU:
fn = cudnn_rnn_ops.CudnnRNNReluSaveable
else:
raise ValueError("rnn mode %r" % rnn_mode)
params_saveable = fn(
params,
num_layers=cell.num_layers,
num_units=cell.num_units,
input_size=cell.input_size,
input_mode=cell.input_mode,
direction=cell.direction,
scope="%s/params_canonical" % get_current_var_scope_name(),
name="%s/params_canonical" % get_current_var_scope_name())
tf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, params_saveable)
self.saveable_param_replace[params] = params_saveable
# It's like a fused cell, i.e. operates on the full sequence.
input_h = tf.zeros((num_layers, n_batch, self.output.dim), dtype=tf.float32)
input_c = tf.zeros((num_layers, n_batch, self.output.dim), dtype=tf.float32)
y, _ = cell(x, initial_state=(input_h, input_c))
if self._direction == -1:
y = tf.reverse_sequence(y, seq_lengths=seq_len, batch_dim=1, seq_dim=0)
return y
def _get_output_native_rec_op(self, cell):
"""
:param TFNativeOp.RecSeqCellOp cell:
:return: output of shape (time, batch, dim)
:rtype: tf.Tensor
"""
from TFUtil import dot, sequence_mask_time_major, directed, to_int32_64, set_param_axes_split_info
assert self._max_seq_len is None
assert self.input_data
x, seq_len = self._get_input()
if self._input_projection:
if cell.does_input_projection:
# The cell get's x as-is. It will internally does the matrix mult and add the bias.
pass
else:
weights = tf.get_variable(
name="W", shape=(self.input_data.dim, cell.n_input_dim), dtype=tf.float32,
initializer=self._fwd_weights_initializer)
if self.input_data.sparse:
x = tf.nn.embedding_lookup(weights, to_int32_64(x))
else:
x = dot(x, weights)
b = tf.get_variable(name="b", shape=(cell.n_input_dim,), dtype=tf.float32, initializer=self._bias_initializer)
if len(cell.n_input_dim_parts) > 1:
set_param_axes_split_info(weights, [[self.input_data.dim], cell.n_input_dim_parts])
set_param_axes_split_info(b, [cell.n_input_dim_parts])
x += b
else:
assert not cell.does_input_projection
assert not self.input_data.sparse
assert self.input_data.dim == cell.n_input_dim
if self.input_data.have_time_axis():
index = sequence_mask_time_major(seq_len, maxlen=self.input_data.time_dimension())
else:
index = tf.ones([1, self.input_data.get_batch_dim()], dtype=tf.bool) # see _get_input
if not cell.does_direction_handling:
x = directed(x, self._direction)
index = directed(index, self._direction)
y, final_state = cell(
inputs=x, index=index,
initial_state=self._initial_state,
recurrent_weights_initializer=self._rec_weights_initializer)
self._last_hidden_state = final_state
if not cell.does_direction_handling:
y = directed(y, self._direction)
if not self.input_data.have_time_axis(): # see _get_input
y = y[0]
return y
def _get_output_subnet_unit(self, cell):
"""
:param _SubnetworkRecCell cell:
:return: output of shape (time, batch, dim)
:rtype: tf.Tensor
"""
output, search_choices = cell.get_output(rec_layer=self)
self.search_choices = search_choices
self._last_hidden_state = cell
return output
def get_last_hidden_state(self, key):
"""
:param str|int|None key:
:rtype: tf.Tensor
"""
assert self._last_hidden_state is not None, (
"last-hidden-state not implemented/supported for this layer-type. try another unit. see the code.")
return RnnCellLayer.get_state_by_key(self._last_hidden_state, key=key)
@classmethod
def is_prev_step_layer(cls, layer):
"""
:param LayerBase layer:
:rtype: bool
"""
if isinstance(layer, _TemplateLayer):
return layer.is_prev_time_frame
return False
def get_sub_layer(self, layer_name):
"""
:param str layer_name: name of the sub_layer (right part of '/' separated path)
:return: the sub_layer addressed in layer_name or None if no sub_layer exists
:rtype: LayerBase|None
"""
if isinstance(self.cell, _SubnetworkRecCell):
# try to find layer_name in cell:
return self.cell.get_layer_from_outside(layer_name)
return None
class _SubnetworkRecCell(object):
"""
This class is used by :class:`RecLayer` to implement
the generic subnetwork logic inside the recurrency.
"""
_debug_out = None # set to list to enable
def __init__(self, net_dict, parent_rec_layer=None, parent_net=None, source_data=None):
"""
:param dict[str,dict[str]] net_dict: dict for the subnetwork, layer name -> layer dict
:param RecLayer parent_rec_layer:
:param TFNetwork.TFNetwork parent_net:
:param Data|None source_data: usually concatenated input from the rec-layer
"""
from copy import deepcopy
if parent_net is None and parent_rec_layer:
parent_net = parent_rec_layer.network
if source_data is None and parent_rec_layer:
source_data = parent_rec_layer.input_data
self.parent_rec_layer = parent_rec_layer
self.parent_net = parent_net
self.net_dict = deepcopy(net_dict)
from TFNetwork import TFNetwork, ExternData, LossHolder
self.net = TFNetwork(
name="%s/%s:rec-subnet" % (parent_net.name, parent_rec_layer.name if parent_rec_layer else "?"),
extern_data=ExternData(),
train_flag=parent_net.train_flag,
search_flag=parent_net.search_flag,
parent_layer=parent_rec_layer,
is_inside_rec_layer=True,
parent_net=parent_net)
if source_data:
self.net.extern_data.data["source"] = (
source_data.copy_template_excluding_time_dim())
for key, data in parent_net.extern_data.data.items():
if key in self.net.extern_data.data:
continue # Don't overwrite existing, e.g. "source".
# These are just templates. You can use them as possible targets for dimension information,
# but not as actual sources or targets.
# Note: We maybe should check data.is_same_time_dim()...
self.net.extern_data.data[key] = data.copy_template_excluding_time_dim()
if parent_net.search_flag and parent_rec_layer and parent_rec_layer.output.beam_size:
for key, data in list(self.net.extern_data.data.items()):
self.net.extern_data.data[key] = data.copy_extend_with_beam(
beam_size=parent_rec_layer.output.beam_size)
self.layer_data_templates = {} # type: typing.Dict[str,_TemplateLayer]
self.prev_layers_needed = set() # type: typing.Set[str]
self.prev_layer_templates = {} # type: typing.Dict[str,_TemplateLayer]
self._construct_template()
self._initial_outputs = None # type: typing.Optional[typing.Dict[str,tf.Tensor]]
self._initial_extra_outputs = None # type: typing.Optional[typing.Dict[str,typing.Dict[str,typing.Union[tf.Tensor,typing.Tuple[tf.Tensor,...]]]]] # nopep8
self.input_layers_moved_out = [] # type: typing.List[str]
self.output_layers_moved_out = [] # type: typing.List[str]
self.layers_in_loop = None # type: typing.Optional[typing.List[str]]
self.input_layers_net = None # type: typing.Optional[TFNetwork]
self.output_layers_net = None # type: typing.Optional[TFNetwork]
self.final_acc_tas_dict = None # type: typing.Optional[typing.Dict[str, tf.TensorArray]]
self.get_final_rec_vars = None
self.accumulated_losses = {} # type: typing.Dict[str,LossHolder]
def __repr__(self):
return "<%s of %r>" % (self.__class__.__name__, self.parent_rec_layer)
def _construct_template(self):
"""
Without creating any computation graph, create TemplateLayer instances.
Need it for shape/meta information as well as dependency graph in advance.
It will init self.layer_data_templates and self.prev_layers_needed.
"""
from TFNetwork import NetworkConstructionDependencyLoopException
class ConstructCtx:
"""
Closure.
"""
# Stack of layers:
layers = [] # type: typing.List[_TemplateLayer]
most_recent = None
partially_finished = [] # type: typing.List[_TemplateLayer]
class GetLayer:
"""
Helper class to provide the ``get_layer`` function with specific properties.
"""
# noinspection PyMethodParameters
def __init__(lself,
safe=False, once=False, allow_uninitialized_template=False,
iterative_testing=True, reconstruct=False,
parent=None):
lself.safe = safe
lself.once = once
lself.allow_uninitialized_template = allow_uninitialized_template
lself.parent = parent
lself.iterative_testing = iterative_testing
lself.reconstruct = reconstruct
lself.count = 0
lself.returned_none_count = 0
# noinspection PyMethodParameters
def __repr__(lself):
return (
"<RecLayer construct template GetLayer>("
"safe %r, once %r, allow_uninitialized_template %r, count %r, parent %r)") % (
lself.safe, lself.once, lself.allow_uninitialized_template, lself.count, lself.parent)
# noinspection PyMethodParameters
def add_templated_layer(lself, name, layer_class, **layer_desc):
"""
This is used instead of self.net.add_layer because we don't want to add
the layers at this point, we just want to construct the template layers
and store inside self.layer_data_templates.
:param str name:
:param type[LayerBase]|LayerBase layer_class:
:param dict[str] layer_desc:
:rtype: LayerBase
"""
# _TemplateLayer already created in get_templated_layer.
layer_ = self.layer_data_templates[name]
layer_desc = layer_desc.copy()
layer_desc["name"] = name
layer_desc["network"] = self.net
layer_.kwargs = layer_desc # set it now already for better debugging
if layer_ not in ConstructCtx.partially_finished:
ConstructCtx.partially_finished.append(layer_)
output = layer_class.get_out_data_from_opts(**layer_desc)
layer_.init(layer_class=layer_class, output=output, **layer_desc)
if lself.returned_none_count == 0:
ConstructCtx.partially_finished.remove(layer_)
return layer_
# noinspection PyMethodParameters
def __call__(lself, name):
"""
This is the get_layer function implementation.
:param str name: layer name
:return: layer, or None
:rtype: LayerBase|None
"""
_name = name
is_prev = False
if name.startswith("prev:"):
name = name[len("prev:"):]
is_prev = True
self.prev_layers_needed.add(name)
if name in self.layer_data_templates:
layer_ = self.layer_data_templates[name]
if ConstructCtx.layers:
ConstructCtx.layers[-1].add_dependency(layer_, is_prev_time_frame=is_prev)
if lself.allow_uninitialized_template:
return layer_
if not lself.reconstruct and layer_.is_initialized:
return layer_
if name.startswith("base:"):