-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFNetworkRecLayer.py
executable file
·4384 lines (4028 loc) · 194 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
from __future__ import print_function
import tensorflow as tf
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 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`.
"""
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,
**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)
"""
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
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
self._cheating = cheating
self._unroll = unroll
# 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_guides/python/contrib.layers#Initializers
# https://www.tensorflow.org/api_docs/python/tf/orthogonal_initializer
# 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():
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) if initial_state is not None else None
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))
self.output.time_dim_axis = 0
self.output.batch_dim_axis = 1
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.params[p.name[len(scope_name_prefix):-2]] = p
def get_dep_layers(self):
l = super(RecLayer, self).get_dep_layers()
l += self._initial_state_deps
if isinstance(self.cell, _SubnetworkRecCell):
l += self.cell.get_parent_deps()
return l
@classmethod
def transform_config_dict(cls, d, network, get_layer):
"""
: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", None) # disable automatic guessing
super(RecLayer, cls).transform_config_dict(d, network=network, get_layer=get_layer)
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):
# Only used to resolve deps to base network.
if name.startswith("base:"):
return get_layer(name[len("base:"):])
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):
from tensorflow.python.util import nest
n_out = kwargs.get("n_out", None)
out_type = kwargs.get("out_type", None)
loss = kwargs.get("loss", None)
deps = list(sources) # type: list[LayerBase]
deps += [l for l in nest.flatten(initial_state) if isinstance(l, LayerBase)]
if out_type or n_out or loss:
if out_type:
assert out_type.get("time_dim_axis", 0) == 0
assert out_type.get("batch_dim_axis", 1) == 1
out = super(RecLayer, cls).get_out_data_from_opts(sources=sources, **kwargs)
else:
out = None
if isinstance(unit, dict): # subnetwork
source_data = get_concat_sources_data_template(sources) if sources else None
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 = 0
out.batch_dim_axis = 1
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):
return self.get_base_absolute_name_scope_prefix() + "rec/" # all under "rec" sub-name-scope
_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
def maybe_add(key, 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
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
@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))
losses.append(loss)
return losses
def get_constraints_value(self):
v = super(RecLayer, self).get_constraints_value()
from TFUtil import optional_add
if isinstance(self.cell, _SubnetworkRecCell):
for layer in self.cell.net.layers.values():
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)):
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):
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
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
# We must get x.shape[0] == self._max_seq_len, so pad it, or truncate.
x_shape = x.get_shape().as_list()
original_len = tf.shape(x)[0]
pad_len = tf.maximum(0, self._max_seq_len - original_len)
x = tf.pad(x, [(0, pad_len), (0, 0), (0, 0)])
x = x[:self._max_seq_len]
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.
pad_len = tf.maximum(0, original_len - self._max_seq_len)
y = tf.pad(y, [(0, pad_len), (0, 0), (0, 0)])
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
param_size = self._get_cudnn_param_size(
num_units=self.output.dim, input_size=self.input_data.dim, rnn_mode=cell._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 cell._rnn_mode == cudnn_rnn_ops.CUDNN_LSTM:
fn = cudnn_rnn_ops.CudnnLSTMSaveable
elif cell._rnn_mode == cudnn_rnn_ops.CUDNN_GRU:
fn = cudnn_rnn_ops.CudnnGRUSaveable
elif cell._rnn_mode == cudnn_rnn_ops.CUDNN_RNN_TANH:
fn = cudnn_rnn_ops.CudnnRNNTanhSaveable
elif cell._rnn_mode == cudnn_rnn_ops.CUDNN_RNN_RELU:
fn = cudnn_rnn_ops.CudnnRNNReluSaveable
else:
raise ValueError("rnn mode %r" % cell._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:
W = 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(W, to_int32_64(x))
else:
x = dot(x, W)
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(W, [[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
index = sequence_mask_time_major(seq_len, maxlen=self.input_data.time_dimension())
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)
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):
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
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
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,
parent_net=parent_net)
if source_data:
self.net.extern_data.data["source"] = \
source_data.copy_template_excluding_time_dim()
for key in parent_net.extern_data.data.keys():
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.
self.net.extern_data.data[key] = \
parent_net.extern_data.data[key].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: dict[str,_TemplateLayer]
self.prev_layers_needed = set() # type: set[str]
self._construct_template()
self._initial_outputs = None # type: dict[str,tf.Tensor]
self._initial_extra_outputs = None # type: dict[str,dict[str,tf.Tensor|tuple[tf.Tensor]]]
self.input_layers_moved_out = [] # type: list[str]
self.output_layers_moved_out = [] # type: list[str]
self.layers_in_loop = None # type: list[str]
self.input_layers_net = None # type: TFNetwork
self.output_layers_net = None # type: TFNetwork
self.final_acc_tas_dict = None # type: dict[str, tf.TensorArray]
self.get_final_rec_vars = None
self.accumulated_losses = {} # type: dict[str,TFNetwork.LossHolder]
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.
"""
def add_templated_layer(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
output = layer_class.get_out_data_from_opts(**layer_desc)
layer.init(layer_class=layer_class, output=output, **layer_desc)
return layer
class construct_ctx:
# Stack of layers:
layers = [] # type: list[_TemplateLayer]
def get_none_layer(name):
return None
def get_templated_layer(name):
"""
:param str name:
:rtype: _TemplateLayer|LayerBase
"""
if name.startswith("prev:"):
name = name[len("prev:"):]
self.prev_layers_needed.add(name)
if name in self.layer_data_templates:
layer = self.layer_data_templates[name]
if construct_ctx.layers:
construct_ctx.layers[-1].dependencies.add(layer)
return layer
if name.startswith("base:"):
layer = self.parent_net.get_layer(name[len("base:"):])
if construct_ctx.layers:
construct_ctx.layers[-1].dependencies.add(layer)
return layer
# Need to create layer instance here now to not run into recursive loops.
# We will extend it later in add_templated_layer().
layer = _TemplateLayer(name=name, network=self.net)
if construct_ctx.layers:
construct_ctx.layers[-1].dependencies.add(layer)
construct_ctx.layers.append(layer)
self.layer_data_templates[name] = layer
try:
# First, see how far we can get without recursive layer construction.
# We only want to get the data template for now.
self.net.construct_layer(
net_dict=self.net_dict, name=name, get_layer=get_none_layer, add_layer=add_templated_layer)
except Exception:
# Pretty generic exception handling but anything could happen.
# Not so nice but should work for now.
pass
# Now, do again, but with recursive layer construction, to determine the dependencies.
self.net.construct_layer(
net_dict=self.net_dict, name=name, get_layer=get_templated_layer, add_layer=add_templated_layer)
assert construct_ctx.layers[-1] is layer
construct_ctx.layers.pop(-1)
return layer
try:
assert not self.layer_data_templates, "do not call this multiple times"
get_templated_layer("output")
assert "output" in self.layer_data_templates
assert not construct_ctx.layers
if "end" in self.net_dict: # used to specify ending of a sequence
get_templated_layer("end")
for layer_name, layer in self.net_dict.items():
if self.parent_net.eval_flag and layer.get("loss"): # only collect losses if we need them
get_templated_layer(layer_name)
for layer_name, layer in self.net_dict.items():
if layer.get("is_output_layer"):
get_templated_layer(layer_name)
except Exception:
print("%r: exception constructing template network (for deps and data shapes)" % self)
print("Template network so far:")
from pprint import pprint
pprint(self.layer_data_templates)
raise
def _construct(self, prev_outputs, prev_extra, i,
data=None, classes=None,
inputs_moved_out_tas=None, needed_outputs=("output",)):
"""
This is called from within the `tf.while_loop` of the :class:`RecLayer`,
to construct the subnetwork, which is performed step by step.
:param dict[str,tf.Tensor] prev_outputs: outputs of the layers from the previous step
:param dict[str,dict[str,tf.Tensor]] prev_extra: extra output / hidden states of the previous step for layers
:param tf.Tensor i: loop counter. scalar, int32, current step (time)
:param tf.Tensor|None data: optional source data, shape e.g. (batch,dim)
:param tf.Tensor|None classes: optional target classes, shape e.g. (batch,) if it is sparse
:param dict[str,tf.TensorArray]|None inputs_moved_out_tas:
:param set[str] needed_outputs: layers where we need outputs
"""
from TFNetwork import TFNetwork
from TFNetworkLayer import InternalLayer, ExtendWithBeamLayer
from TFUtil import tile_transposed
needed_beam_size = self.layer_data_templates["output"].output.beam_size
if data is not None:
if needed_beam_size:
assert not self.parent_rec_layer.input_data.beam_size
data = tile_transposed(
data,
axis=self.net.extern_data.data["source"].batch_dim_axis,
multiples=needed_beam_size)
self.net.extern_data.data["source"].placeholder = data
if classes is not None:
if needed_beam_size:
classes = tile_transposed(
classes,
axis=self.net.extern_data.data[self.parent_rec_layer.target].batch_dim_axis,
multiples=needed_beam_size)
self.net.extern_data.data[self.parent_rec_layer.target].placeholder = classes
for data_key, data in self.net.extern_data.data.items():
if data_key not in self.net.used_data_keys:
continue
if data.placeholder is None:
raise Exception("rec layer %r subnet data key %r is not set" % (self.parent_rec_layer.name, data_key))
prev_layers = {} # type: dict[str,_TemplateLayer]
for name in set(list(prev_outputs.keys()) + list(prev_extra.keys())):
self.net.layers["prev:%s" % name] = prev_layers[name] = self.layer_data_templates[name].copy_as_prev_time_frame(
prev_output=prev_outputs.get(name, None),
rec_vars_prev_outputs=prev_extra.get(name, None))
extended_layers = {}
from copy import deepcopy
net_dict = deepcopy(self.net_dict)
for name in net_dict.keys():
if name in prev_layers:
net_dict[name]["rec_previous_layer"] = prev_layers[name]
inputs_moved_out = {} # type: dict[str,InternalLayer]
def get_input_moved_out(name):
"""
:param str name:
:rtype: InternalLayer
"""
if name in inputs_moved_out:
return inputs_moved_out[name]
if name.startswith("prev:"):
layer_name = name[len("prev:"):]
prev = True
assert layer_name not in inputs_moved_out, "currently cannot use both cur + prev frame"
else:
layer_name = name
prev = False
assert "prev:%s" % layer_name not in inputs_moved_out, "currently cannot use both cur + prev frame"
assert layer_name in self.input_layers_moved_out
assert isinstance(self.input_layers_net, TFNetwork)
layer = self.input_layers_net.layers[layer_name]
assert isinstance(layer, LayerBase)
output = layer.output.copy_template_excluding_time_dim()
with tf.name_scope("%s_moved_input" % name.replace(":", "_")):
if prev:
output.placeholder = tf.cond(
tf.equal(i, 0),
lambda: self._get_init_output(layer_name),
lambda: inputs_moved_out_tas[layer_name].read(i - 1))
else:
output.placeholder = inputs_moved_out_tas[layer_name].read(i)
output.sanity_check()
layer = self.net.add_layer(name=name, output=output, layer_class=InternalLayer)
inputs_moved_out[name] = layer
return layer
def get_layer(name):
"""
:param str name: layer name
:rtype: LayerBase
"""
if name.startswith("prev:"):
sub_name = name[len("prev:"):]
if sub_name in self.input_layers_moved_out:
return get_input_moved_out(name)
return prev_layers[sub_name]
if name.startswith("base:"):
if name in extended_layers:
return extended_layers[name]
layer = self.parent_net.get_layer(name[len("base:"):])
if self.parent_net.search_flag:
if needed_beam_size:
assert not layer.output.beam_size
if layer.output.beam_size != needed_beam_size:
layer = self.net.add_layer(
name="%s_copy_extend_with_beam_%i" % (name, needed_beam_size),
base_layer=layer,
beam_size=needed_beam_size,
layer_class=ExtendWithBeamLayer)
extended_layers[name] = layer
assert layer.output.beam_size == needed_beam_size
return layer
if name in self.input_layers_moved_out:
return get_input_moved_out(name)
if name in self.output_layers_moved_out:
# Will be constructed later.
# This should not be used recursively, because we checked that nothing depends on it,
# thus it should not be a problem to return None.
return None