forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFNetworkLayer.py
8251 lines (7571 loc) · 328 KB
/
TFNetworkLayer.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
"""
This module contains the layer base class :class:`LayerBase`,
and many canonical basic layers.
"""
from __future__ import print_function
import tensorflow as tf
import contextlib
import typing
import TFUtil
from Util import unicode, NotSpecified, CollectionReadCheckCovered
from TFUtil import Data, OutputWithActivation, CustomUpdate, dimshuffle, swapaxes
from Log import log
class LayerBase(object):
"""
This is the base class for all layers.
Every layer by default has a list of source layers `sources` and defines `self.output` which is of type :class:`Data`.
It shares some common functionality across all layers, such as explicitly defining the output format,
some parameter regularization, and more.
If you want to implement your own layer::
class YourOwnLayer(_ConcatInputLayer): # e.g. either _ConcatInputLayer or LayerBase as a base
" some docstring "
layer_class = "your_layer_name"
def __init__(self, your_kwarg1, your_opt_kwarg2=None, **kwargs):
" docstring, document the args! "
super(YourOwnLayer, self).__init__(**kwargs)
# Now we need to set self.output, which must be of type :class:`Data`.
# It is set at this point to whatever we got from `selfget_out_data_from_opts()`,
# so it is enough if we set self.output.placeholder and self.output.size_placeholder,
# but we could also reset self.output.
self.output.placeholder = self.input_data.placeholder + 42 # whatever you want to do
# If you don't modify the sizes (e.g. sequence-length), just copy the input sizes.
self.output.size_placeholder = self.input_data.size_placeholder.copy()
@classmethod
def get_out_data_from_opts(cls, **kwargs):
" This is supposed to return a :class:`Data` instance as a template, given the arguments. "
# example, just the same as the input:
return get_concat_sources_data_template(kwargs["sources"], name="%s_output" % kwargs["name"])
"""
layer_class = None # type: typing.Optional[str] # for get_layer_class()
recurrent = False # if the order in the time-dimension is relevant
allow_inf_in_output = False
# For compatibility, we have some parameter names (e.g. "L2") which do not conform to PEP8.
# noinspection PyPep8Naming
def __init__(self, name, network, output=None, n_out=NotSpecified, out_type=None, sources=(),
target=None, _target_layers=None, loss=None, size_target=None,
reuse_params=None,
param_device=None,
is_output_layer=None, only_on_eval=False, only_on_search=False,
copy_output_loss_from_source_idx=None,
batch_norm=False,
L2=None, darc1=None,
spatial_smoothing=0.0,
param_variational_noise=None,
updater_opts=None,
initial_output=None,
rec_previous_layer=None,
collocate_with=None,
trainable=True,
custom_param_importer=None,
register_as_extern_data=None):
"""
Usually the arguments, when specified in the network dict,
are going through :func:`transform_config_dict`, before they are passed to here.
See :func:`TFNetwork.construct_from_dict`.
:param str name:
:param TFNetwork.TFNetwork network:
:param Data output:
:param NotSpecified|None|int n_out: output dim
:param dict[str] out_type: kwargs for Data class. more explicit than n_out.
:param list[LayerBase] sources: via self.transform_config_dict()
:param str|list[str]|None target: if some loss is set, this is the target data-key,
i.e. network.extern_data.get_data(target). alternatively, this also can be a layer name.
:param dict[str,LayerBase]|None _target_layers: if target.startswith("layer:"), then this is target -> layer
:param str|None size_target: like target but this is only used to set our output size in case of training
:param Loss|None loss: via :func:`transform_config_dict`.
Every layer can have one loss (of type :class:`Loss`), or none loss.
In the net dict, it is specified as a string.
In :class:`TFNetwork`, all losses from all layers will be collected.
That is what :class:`TFUpdater.Updater` will use for training.
:param ReuseParams|None reuse_params: if given, will opt reuse the params. see :func:`self.var_creation_scope`
:param str|None param_device: e.g. "CPU", etc. any valid name for tf.device.
see https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/device_name_utils.h
:param float|None L2: for constraints
:param float|None darc1: for constraints. see Generalization in Deep Learning, https://arxiv.org/abs/1710.05468
:param float|None spatial_smoothing: see :func:`TFUtil.spatial_smoothing_energy`
:param float|None param_variational_noise: adds variational noise to the params during training
:param dict[str]|None updater_opts: accepts similar opts as TFUpdater, e.g. "optimizer", "learning_rate", ...
:param bool|None is_output_layer:
:param bool only_on_eval: if True, this layer will only be calculated in eval
:param bool only_on_search: if True, this layer will only be calculated when search is done
:param int|None copy_output_loss_from_source_idx: if set, will copy output_loss from this source
:param bool|dict batch_norm: see self.batch_norm()
:param str|float initial_output: used for recurrent layer, see self.get_rec_initial_output()
:param LayerBase|None rec_previous_layer: via the recurrent layer, layer (template) which represents the past of us
:param list[LayerBase]|None collocate_with: in the rec layer, collocate with the specified other layers
:param bool trainable: whether the parameters of this layer will be trained
:param str|callable|None custom_param_importer: used by :func:`set_param_values_by_dict`
:param str|None register_as_extern_data: registers output in network.extern_data
"""
self.name = name
self.network = network
self._register_layer()
self.kwargs = None # type: typing.Optional[typing.Dict[str]] # set via self.post_init
self.target = None
self.targets = None
if target:
if isinstance(target, list):
self.targets = target
self.target = target[0]
else:
assert isinstance(target, str)
self.targets = [target]
self.target = target
self._target_layers = _target_layers
self.loss = loss
if self.loss and self.loss.recurrent:
self.recurrent = True
if output:
self.output = output
if n_out is not NotSpecified:
assert self.output.dim == n_out
if isinstance(out_type, dict):
if "shape" in out_type:
assert self.output.shape == out_type["shape"]
if "dim" in out_type:
assert self.output.dim == out_type["dim"]
else:
self.output = self.get_out_data_from_opts(
out_type=out_type, n_out=n_out,
network=network, name=name, target=target, size_target=size_target,
sources=sources, loss=loss)
self.output_before_activation = None # type: typing.Optional[OutputWithActivation]
self.output_loss = None # type: typing.Optional[tf.Tensor]
if copy_output_loss_from_source_idx is not None:
self.output_loss = sources[copy_output_loss_from_source_idx].output_loss
self.rec_vars_outputs = {} # type: typing.Dict[str,tf.Tensor]
self.search_choices = None # type: typing.Optional[SearchChoices]
self._initial_output = initial_output
self._rec_previous_layer = rec_previous_layer
self.collocate_with = collocate_with or []
self.post_init_hooks = [] # list of functions
self.sources = sources
self.params = {} # type: typing.Dict[str,tf.Variable]
self.saveable_param_replace = {} # type: typing.Dict[tf.Variable,typing.Union['tensorflow.python.training.saver.BaseSaverBuilder.SaveableObject',None]] # see get_saveable_params_dict() # nopep8
self.reuse_params = reuse_params
self.param_device = param_device
self.L2 = L2
self.darc1 = darc1
self.spatial_smoothing = spatial_smoothing
self.param_variational_noise = param_variational_noise
self.updater_opts = CollectionReadCheckCovered(updater_opts or {})
self._is_output_layer = is_output_layer
self.only_on_eval = only_on_eval
self.only_on_search = only_on_search
self.use_batch_norm = batch_norm
self.trainable = trainable
self.custom_param_importer = custom_param_importer
self.register_as_extern_data = register_as_extern_data
# Stats will be collected by the engine.
self.stats = {} # type: typing.Dict[str,tf.Tensor]
def post_init(self, layer_desc):
"""
This gets called right after self.__init__().
:param dict[str] layer_desc: kwargs as they are passed to self.__init__
"""
self.kwargs = layer_desc
if self.use_batch_norm:
opts = {}
if isinstance(self.use_batch_norm, dict):
opts = self.use_batch_norm
self.output.placeholder = self.batch_norm(self.output, **opts)
if self.register_as_extern_data:
self.network.extern_data.extra_added_keys.add(self.register_as_extern_data)
self.network.extern_data.data[self.register_as_extern_data] = self.output
for func in self.post_init_hooks:
func()
def __repr__(self):
return "<%s %r out_type=%s>" % (
self.__class__.__name__, self.name, self.output.get_description(with_name=False) if self.output else None)
@classmethod
def get_out_data_from_opts(cls, **kwargs):
"""
Gets a Data template (i.e. shape etc is set but not the placeholder) for our __init__ args.
The purpose of having this as a separate classmethod is to be able to infer the shape information
without having to construct the layer.
This function should not create any nodes in the computation graph.
:param kwargs: all the same kwargs as for self.__init__()
:return: Data template (placeholder not set)
:rtype: Data
"""
return cls._base_get_out_data_from_opts(**kwargs)
@classmethod
def _base_get_out_data_from_opts(cls, network, name, out_type=None, n_out=NotSpecified,
target=None, _target_layers=None, size_target=None,
sources=(), loss=None,
**kwargs):
"""
Called via BaseLayer.get_out_data_from_opts().
:param TFNetwork.TFNetwork network:
:param str name:
:param dict[str]|None|(()->Data) out_type:
:param int|None|NotSpecified n_out:
:param str|list[str]|None target:
:param dict[str,LayerBase]|None _target_layers: if target.startswith("layer:"), then this is target -> layer
:param str|None size_target:
:param list[LayerBase] sources:
:param Loss|None loss:
:param kwargs: remaining kwargs of self.__init__(), ignored here
:return: Data template (placeholder not set)
:rtype: Data
"""
if callable(out_type):
return out_type(
network=network, name=name, n_out=n_out, target=target, size_target=size_target, sources=sources, loss=loss,
**kwargs)
if out_type is None:
out_type = {}
else:
out_type = out_type.copy()
out_type.setdefault("name", "%s_output" % name)
if "dim" not in out_type and n_out is not NotSpecified:
out_type["dim"] = n_out
if "dim" not in out_type and target:
out_type["dim"] = cls._static_get_target_value(
target=target[0] if isinstance(target, list) else target, _target_layers=_target_layers,
network=network, mark_data_key_as_used=False).dim
if n_out is not NotSpecified:
assert out_type["dim"] == n_out
sources_data = None
if sources and sources[0]:
sources_data = sources[0].output.copy_template()
if sources_data and not sources_data.sparse and not out_type.get("sparse", False):
out_type.setdefault("dtype", sources_data.dtype)
# You are supposed to set self.output.{batch_dim_axis,time_dim_axis} explicitly,
# as well as check the inputs if they are as you would suggest.
# However, a good default is often to use the same as the input.
if all([k not in out_type for k in Data.SpecialAxesNames]):
if sources_data:
out_type.setdefault("batch_dim_axis", sources_data.batch_dim_axis)
out_type.setdefault("time_dim_axis", sources_data.time_dim_axis)
if not out_type.get("sparse", False) and sources_data.feature_dim_axis_or_unspecified is not NotSpecified:
if sources_data.feature_dim_axis_or_unspecified is not None:
out_type.setdefault("feature_dim_axis", sources_data.feature_dim_axis_or_unspecified)
else: # None
if out_type.get("dim", None) is None:
out_type.setdefault("feature_dim_axis", None)
elif network.is_inside_rec_layer():
out_type.setdefault("time_dim_axis", None)
if "shape" not in out_type:
if sources_data:
if out_type.get("sparse", False):
out_type.setdefault("shape", sources_data.shape_sparse)
else: # not sparse
feature_dim_axis = out_type.get("feature_dim_axis", NotSpecified)
if feature_dim_axis is NotSpecified:
if sources_data.feature_dim_axis is not None:
feature_dim_axis = sources_data.feature_dim_axis
else:
feature_dim_axis = -1
default_shape = list(sources_data.shape_dense)
default_shape.insert(sources_data.batch_dim_axis, None)
default_shape[feature_dim_axis] = out_type["dim"]
default_shape.pop(out_type.get("batch_dim_axis"))
out_type.setdefault("shape", tuple(default_shape))
elif network.is_inside_rec_layer():
if out_type.get("sparse", False):
out_type.setdefault("shape", ())
else:
out_type.setdefault("shape", (out_type.get("dim", None),))
# Note: No special handling for feature_dim_axis here for now...
beam_size = None
for src in sources:
if src: # might be None if template construction
beam_size = beam_size or src.output.beam_size
out_type.setdefault("beam_size", beam_size)
output = Data(**out_type)
cls._post_init_output(
output=output, network=network, target=target, size_target=size_target, _target_layers=_target_layers,
sources=sources, **kwargs)
return output
# noinspection PyUnusedLocal
@classmethod
def _post_init_output(cls, output, network, target=None, size_target=None, _target_layers=None, sources=(), **kwargs):
"""
:param Data output:
:param TFNetwork.TFNetwork network:
:param str|list[str]|None target:
:param str|None size_target:
:param dict[str,LayerBase]|None _target_layers: if target.startswith("layer:"), then this is target -> layer
:param list[LayerBase] sources:
"""
# You are supposed to set self.output.placeholder to the value which you want to return by the layer.
# Normally you are also supposed to set self.output.size_placeholder explicitly, just like self.output.placeholder.
# However, in many cases, this will just be {0: time-lengths} and the same as from the input.
# We check for this case and preset it by that if possible.
# If you want to have it different in your layer, just overwrite it.
common_source = Data.get_common_data([s.output for s in sources if s])
if not output.size_placeholder:
if common_source and common_source.matches_var_dim_pattern(output):
output.size_placeholder = common_source.size_placeholder.copy()
elif target or size_target:
if network.train_flag is not False:
# TODO: In training, this is ok. Maybe as well as for eval but not clear.
# In forward, mark_data_key_as_used=False should be used and anyway that target value is not available.
output.size_placeholder = cls._static_get_target_value(
target=(target[0] if (target and isinstance(target, list)) else target) or size_target,
_target_layers=_target_layers,
network=network, mark_data_key_as_used=network.train_flag is not False).size_placeholder.copy()
if any([(src and not src.output.available_for_inference) for src in sources if src]):
output.available_for_inference = False
@classmethod
def cls_get_tf_scope_name(cls, name):
"""
:param str name: layer name
:return: valid scope name, might be just name. see tf._VALID_SCOPE_NAME_REGEX and tf._VALID_OP_NAME_REGEX
:rtype: str
"""
from TFUtil import get_valid_scope_name_from_str
return get_valid_scope_name_from_str(name)
@classmethod
def cls_layer_scope(cls, name):
"""
Setup scope for layer. This can also be used when the layer does not yet exists.
This is supposed to cover variable creations as well.
Currently vars might be created when used within the rec-layer, but they are caught
in a more generic way there, so we have not implemented yet any special logic here.
:param str name: layer name
:return: context manager object
"""
@contextlib.contextmanager
def layer_scope_ctx():
"""
:return: context manager object
"""
from TFUtil import reuse_name_scope
with reuse_name_scope(cls.cls_get_tf_scope_name(name)) as scope:
yield scope
return layer_scope_ctx()
@classmethod
def get_global_layer_list(cls):
"""
:rtype: list[LayerBase]
"""
from TFUtil import CollectionKeys
coll = tf.get_collection_ref(CollectionKeys.RETURNN_LAYERS)
assert isinstance(coll, list)
return coll
@classmethod
def get_recent_layer(cls):
"""
:rtype: LayerBase
"""
coll = cls.get_global_layer_list()
assert coll
return coll[-1]
def _register_layer(self):
self.get_global_layer_list().append(self)
@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
The name `get_layer` might be misleading, as this should return an existing layer,
or construct it if it does not exist yet.
`network.get_layer` would just return an existing layer.
Will modify `d` inplace such that it becomes the kwargs for `self.__init__()`.
Mostly leaves `d` as-is.
This is used by :func:`TFNetwork.construct_from_dict`.
It resolves certain arguments,
e.g. it resolves the `"from"` argument which is a list of strings,
to make it the `"sources"` argument in kwargs, with a list of :class:`LayerBase` instances.
Subclasses can extend/overwrite this.
Usually the only reason to overwrite this is when some argument might be a reference to a layer
which should be resolved.
"""
src_names = d.pop("from", ["data"])
if not isinstance(src_names, (list, tuple)):
src_names = [src_names]
d["sources"] = [
get_layer(src_name)
for src_name in src_names
if not src_name == "none"]
if "collocate_with" in d:
collocate_with = d["collocate_with"]
if not isinstance(collocate_with, (list, tuple)):
collocate_with = [collocate_with]
d["collocate_with"] = [get_layer(src_name) for src_name in collocate_with]
if "reuse_params" in d:
d["reuse_params"] = ReuseParams.from_config_dict(d["reuse_params"], network=network, get_layer=get_layer)
if d.get("loss", None) and "target" not in d:
target = get_loss_class(d["loss"]).get_default_target(network.extern_data)
if target:
d["target"] = target
targets = None
target_layers = {}
assert "_target_layers" not in d
if d.get("target", None):
targets = d["target"]
# we might have multiple targets, e.g. in choice layer, so convert to list
if isinstance(targets, str):
targets = [targets]
if network.eval_flag:
# _target_layers is a small workaround for further code which might not have access to the right get_layer.
d["_target_layers"] = target_layers
for target in targets:
assert isinstance(target, str)
# Not resolving this in the dict as target, but call get_layer to make it available.
if target.startswith("layer:"):
target_layers[target] = get_layer(target[len("layer:"):])
else:
# Note: This is a workaround for cases where we need to know about used data keys before the layer
# itself is constructed (e.g. in _SubnetworkRecCell.get_output).
# A nicer solution would be to not modify this here,
# but instead lazily handle it in TFNetwork.get_extern_data,
# such that we do not need to know in advance which data keys we need.
# Also, if we are inside a rec layer, and doing search, we also cannot do that.
if not network.is_inside_rec_layer() or not network.search_flag:
network.used_data_keys.add(target)
if "n_out" not in d and targets and network.eval_flag:
# Must be done here now because loss might be set to None later.
target = targets[0] # guess using first target
if target in target_layers:
d["n_out"] = target_layers[target].output.dim
else:
d["n_out"] = cls._guess_n_out_from_target_and_opt_loss(
network=network, target=target, loss_class_name=d.get("loss", None), get_layer=get_layer)
if d.pop("loss_only_on_non_search", None) and network.search_flag:
d.pop("loss", None)
d.pop("loss_scale", None)
d.pop("loss_opts", None)
if d.get("loss", None):
loss_opts = d.pop("loss_opts", None)
if not loss_opts:
loss_opts = {}
# loss_scale: scale factor for loss (1.0 by default). DEPRECATED: use loss.scale instead, via loss_opts
loss_scale = d.pop("loss_scale", 1.0)
if loss_scale != 1.0:
assert loss_opts.get("scale", 1.0) == 1.0, "do not use loss_scale and loss with 'scale' option together"
loss_opts["scale"] = loss_scale
d["loss"] = cls._make_loss(
class_name=d.pop("loss", None), opts=loss_opts, network=network, get_layer=get_layer)
else:
assert "loss_scale" not in d, "loss not defined, do not set loss_scale"
assert "loss_opts" not in d, "loss not defined, do not set loss_opts"
@classmethod
def _guess_n_out_from_target_and_opt_loss(cls, network, target, loss_class_name, get_layer):
"""
:param TFNetwork.TFNetwork network:
:param str target: e.g. "classes"
:param str|None loss_class_name: e.g. "ce" or None
:param ((str) -> LayerBase) get_layer: function to get or construct another layer
:return: n_out value
:rtype: int
"""
n_out = cls._static_get_target_value(
target=target, network=network, mark_data_key_as_used=False, get_layer=get_layer).dim
if loss_class_name:
n_out = get_loss_class(loss_class_name).get_auto_output_layer_dim(n_out)
return n_out
@classmethod
def _make_loss(cls, class_name, opts, network, get_layer):
"""
:param str|None class_name:
:param dict[str]|None opts:
:param TFNetwork.TFNetwork network:
:param ((str) -> LayerBase) get_layer: function to get or construct another layer
:rtype: Loss|None
"""
if not network.eval_flag:
# Don't resolve the loss opts on purpose.
# This might result in a smaller network because it might skip some get_layer calls.
# This is what we want, i.e. we don't want to resolve layers which are only needed for the loss.
return None
if not class_name:
return None
if not opts:
opts = {}
opts = opts.copy()
loss_class = get_loss_class(class_name)
assert issubclass(loss_class, Loss)
loss_class.transform_config_dict(opts, network=network, get_layer=get_layer)
loss = loss_class(base_network=network, **opts)
assert isinstance(loss, Loss)
return loss
@property
def tf_scope_name(self):
"""
:rtype: str
:return: normally just self.name, but make it a valid TF scope name
"""
return self.cls_get_tf_scope_name(name=self.name)
def get_base_absolute_name_scope_prefix(self):
"""
:return: e.g. "output/", always with "/" at end
:rtype: str
"""
return self.network.get_absolute_name_scope_prefix() + self.tf_scope_name + "/"
def get_absolute_name_scope_prefix(self):
"""
:return: e.g. "output/", always with "/" at end
:rtype: str
"""
return self.get_base_absolute_name_scope_prefix()
def get_absolute_name(self):
"""
:return: e.g. "output" or "subnet/output"
:rtype: str
"""
return self.network.get_absolute_name_prefix() + self.name
def is_output_layer(self):
"""
Some code differs between an output layer and other layers.
It is a bit arbitrary what we define as output layer.
This should be consistent with :func:`TFNetwork.construct_from_dict`.
:rtype: bool
"""
if self._is_output_layer is not None:
return self._is_output_layer
if self.loss:
return True
if self.name == "output":
return True
return False
def get_dep_layers(self):
"""
:return: list of layers this layer depends on.
normally this is just self.sources but e.g. the attention layer in addition has a base, etc.
:rtype: list[LayerBase]
"""
layers = list(self.sources) + list(self.collocate_with)
if self._target_layers:
layers += [layer for _, layer in sorted(self._target_layers.items())]
return layers
def get_sub_layer(self, layer_name):
"""
The default behavior for any layer is to return None.
: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
"""
return None
@classmethod
def get_sub_layer_out_data_from_opts(cls, layer_name, parent_layer_kwargs):
"""
Called by _TemplateLayer.get_sub_layer(). Gets a Data template for the sub-layer with name 'layer_name'.
Also returns the network the sub-layer is in and the class type of the sub-layer. There is no good default
behaviour here, as this heavily depends on how the current layer uses sub-layers.
:param str layer_name: name of the sub_layer (right part of '/' separated path)
:param dict[str] parent_layer_kwargs: kwargs for the parent layer (as kwargs in cls.get_out_data_from_opts())
:return: Data template, network and the class type of the sub-layer
:rtype: (Data, TFNetwork, type)|None
"""
return None
def get_search_choices(self):
"""
:rtype: SearchChoices|None
"""
if self.search_choices:
return self.search_choices
layer = self.network.get_search_choices(src=self)
if layer:
assert layer.search_choices
return layer.search_choices
return None
def get_search_beam_size(self):
"""
:return: beam size if there was a choice layer and we do search
:rtype: int|None
"""
if self.network.search_flag:
choices = self.get_search_choices()
if choices:
return choices.beam_size
return None
def get_normalized_layer(self):
"""
:return: e.g. if prev layer in :class:`RecLayer`, return current layer
:rtype: LayerBase
"""
return self
def get_batch_dim(self):
"""
The batch dim by this layer, not taken from our output but calculated.
Normally it is self.network.get_batch_dim()
but if we do search and there was a choice layer, it it multiplied by the beam size.
:return: batch dim * beam size
:rtype: tf.Tensor
"""
batch_dim = self.network.get_data_batch_dim()
beam_size = self.get_search_beam_size()
if beam_size is not None:
with tf.name_scope("batch_beam_dim"):
batch_dim *= beam_size
return batch_dim
@contextlib.contextmanager
def var_creation_scope(self, **kwargs):
"""
This takes care of setting up a scope where variables can be created.
:param kwargs: passed to variable_scope
:return: yields the variable_scope
"""
from TFUtil import get_current_var_scope_name, reuse_name_scope
self_base_scope = self.get_base_absolute_name_scope_prefix()
assert self_base_scope.endswith("/")
cur_scope = get_current_var_scope_name()
assert (cur_scope + "/").startswith(self_base_scope)
# There are cases were a dummy layer was created already to create the variables,
# e.g. see ReuseParams.LazyLayerResolver.
kwargs = kwargs.copy()
kwargs.setdefault("reuse", getattr(tf, "AUTO_REUSE", None))
param_variational_noise = self.param_variational_noise
if param_variational_noise is None:
param_variational_noise = self.network.get_config().float("param_variational_noise", 0)
if self.network.train_flag is False: # if True or tf.Tensor, it will use cond_on_train below
param_variational_noise = None
need_custom_getter = bool(param_variational_noise) # and param.dtype.is_floating
kwargs_custom_getter = kwargs.get("custom_getter", None)
def layer_custom_getter(getter, **getter_kwargs):
"""
See TF docs :func:`_VariableStore.get_variable`.
:param (...)->tf.Variable getter:
:rtype: tf.Variable|tf.Tensor
"""
if kwargs_custom_getter:
param = kwargs_custom_getter(getter, **getter_kwargs)
else:
param = getter(**getter_kwargs)
# Only apply this if we get a variable. Otherwise, maybe variational noise was already applied
# (by some parent var scope), and we don't want to apply it twice.
if param_variational_noise and param.dtype.is_floating and isinstance(param, tf.Variable):
with tf.name_scope("param_variational_noise"):
param = self.network.cond_on_train(
fn_train=lambda: param + tf.random_normal(
tf.shape(param), dtype=param.dtype.base_dtype,
stddev=param_variational_noise,
seed=self.network.random.randint(2 ** 31)),
fn_eval=lambda: param)
return param
@contextlib.contextmanager
def inner():
"""
Var creation scope + variable scope.
"""
if self.reuse_params:
var_scope = self.reuse_params.get_variable_scope(base_layer=self)
else:
var_scope = tf.get_variable_scope()
if need_custom_getter:
kwargs["custom_getter"] = layer_custom_getter
with reuse_name_scope(var_scope, **kwargs) as scope_:
yield scope_
if self.param_device:
device_name = self.param_device
if ":" not in device_name:
device_name = "%s:*" % device_name
if "/" not in device_name:
device_name = "/device:%s" % device_name
with tf.device(device_name):
with inner() as scope:
yield scope
else:
with inner() as scope:
yield scope
def add_param(self, param, custom_update=None, trainable=None, saveable=None, axes_split_info=None):
"""
:param tf.Variable|tf.Tensor param:
:param None|CustomUpdate custom_update: will be applied in training, instead of taking the gradient
:param bool|None trainable:
:param bool|None saveable:
:param list[list[int]]|None axes_split_info: e.g. [[n],[n]*4] for LSTM matrices
:return: param
:rtype tf.Variable
"""
_param = param
if isinstance(param, tf.Tensor):
# This can happen with a custom_getter in tf.get_variable(), e.g. via self.reuse_params.
# Check if we can still find the original variable.
from tensorflow.contrib import graph_editor
import re
possible_params = tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES, scope=re.escape(self.get_absolute_name_scope_prefix()))
if not possible_params:
# None found. Just return as-is.
return param
all_ops = graph_editor.get_backward_walk_ops([param.op], inclusive=False, control_inputs=False)
all_1st_tensors = [op.outputs[0] for op in all_ops if len(op.outputs) == 1]
# noinspection PyProtectedMember
possible_params = [p for p in possible_params if p._ref() in all_1st_tensors]
if not possible_params:
# Not found. Just return as-is.
return param
assert len(possible_params) == 1
param = possible_params[0]
assert isinstance(param, tf.Variable)
if not self.trainable:
trainable_collection_ref = param.graph.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES)
if param in trainable_collection_ref:
trainable_collection_ref.remove(param)
if trainable is None:
trainable = param in param.graph.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES)
if saveable is None:
saveable = True
if custom_update:
assert trainable
custom_update.set_on_var(param)
if axes_split_info:
from TFUtil import set_param_axes_split_info
set_param_axes_split_info(param, axes_split_info)
if self.reuse_params:
name_scope_prefix = self.reuse_params.get_absolute_name_scope_prefix(base_layer=self, param=param)
else:
name_scope_prefix = self.get_absolute_name_scope_prefix()
assert param.name
assert param.name[:len(name_scope_prefix)] == name_scope_prefix
assert param.name[-2:] == ":0"
param_name = param.name[len(name_scope_prefix):-2]
if param_name not in self.params:
self.params[param_name] = param
else:
assert self.params[param_name] is param
if not saveable:
self.saveable_param_replace[param] = None
if getattr(param, "RETURNN_layer", None) is None:
param.RETURNN_layer = self
if getattr(param, "RETURNN_updater_opts", None) is None and self.updater_opts.truth_value:
param.RETURNN_updater_opts = self.updater_opts
# Note that any further postprocessing on the parameter should not be done here,
# as we cannot guarantee that the result from this method is really used,
# e.g. when we use official TF code such as the official LSTM cell.
# The better way is to do it in self.var_creation_scope(), which also applies in those cases.
return _param
def set_param_values_by_dict(self, values_dict, session, ignore_wrong_shape=False, copy_param_mode=None):
"""
:param dict[str,numpy.ndarray] values_dict:
:param bool ignore_wrong_shape:
:param str|None copy_param_mode:
:param tf.Session session:
"""
if callable(self.custom_param_importer):
self.custom_param_importer(layer=self, values_dict=values_dict, session=session)
return
if self.custom_param_importer:
copy_param_mode = self.custom_param_importer
assert copy_param_mode in [None, "ifpossible", "subset"]
if copy_param_mode:
ignore_wrong_shape = True
for param_name, values in values_dict.items():
assert param_name in self.params, '%s: param %r unknown' % (self, param_name)
param = self.params[param_name]
assert isinstance(param, tf.Variable)
shape = param.get_shape()
assert isinstance(shape, tf.TensorShape)
assert shape.is_fully_defined(), '%s: shape of param %r %r not fully defined?' % (self, param_name, param)
param_shape = tuple(shape.as_list())
if not ignore_wrong_shape:
assert param_shape == values.shape, "var %r: shape %s != %s" % (param, shape.as_list(), values.shape)
if param_shape != values.shape:
if copy_param_mode == "subset":
assert len(param_shape) == len(values.shape), "param %r ndim must match" % param
new_values = session.run(param) # use currently (randomly) initialized params as base
param_axes_split_info = TFUtil.get_param_axes_split_info(param)
if param_axes_split_info:
TFUtil.check_param_axes_split_info(param.get_shape().as_list(), param_axes_split_info)
old_axes_splits = TFUtil.transform_param_axes_split_info_to_new_shape(
param_axes_split_info, values.shape)
print("Param %r: transform old values of shape parts %r into new shape parts %r." % (
param, old_axes_splits, param_axes_split_info), file=log.v3)
values = TFUtil.copy_with_new_split_axes(
old_axis_splits=old_axes_splits, new_axis_splits=param_axes_split_info,
old_values=values, new_values=new_values)
else:
print("Param %r: transform old values of shape %r into new shape %r." % (
param, values.shape, param_shape), file=log.v3)
values = TFUtil.copy_with_new_split_axes(
old_axis_splits=[[d] for d in values.shape],
new_axis_splits=[[d] for d in param_shape],
old_values=values, new_values=new_values)
else:
print(
"Will not set param %r because its shape %s != %s." % (param, shape.as_list(), values.shape), file=log.v3)
continue
self.network.get_var_assigner(param).assign(values, session=session)
def get_param_values_dict(self, session):
"""
:param tf.Session session:
:return: dict name -> values
:rtype: dict[str,numpy.ndarray]
"""
d = {}
for param_name, param in self.get_saveable_params_dict().items():
d[param_name] = param.eval(session)
return d
def get_saveable_params_dict(self):
"""
:return: params and saveable_param_replace resolved
:rtype: dict[str,tf.Variable|tensorflow.python.training.saver.BaseSaverBuilder.SaveableObject]
"""
if not self.saveable_param_replace:
return self.params.copy()
d = {}
for param_name, param in self.params.items():
if param in self.saveable_param_replace:
param = self.saveable_param_replace[param]
if param is None:
continue
d[param_name] = param
return d
@staticmethod
def _static_get_target_value(target, network, mark_data_key_as_used=True, _target_layers=None, get_layer=None):
"""
:param str target:
:param dict[str,LayerBase]|None _target_layers: if target.startswith("layer:"), then this is target -> layer
:param TFNetwork.TFNetwork network:
:param bool mark_data_key_as_used: forwarded self.network.get_extern_data()
:param None|((str) -> LayerBase) get_layer: function to get or construct another layer
:rtype: Data | None
"""
if not target or target == "none":
return None
if _target_layers and target in _target_layers:
return _target_layers[target].output
if target.startswith("layer:"):
if not get_layer:
get_layer = network.get_layer
return get_layer(target[len("layer:"):]).output
assert network.extern_data.has_data(target), "target %r unknown" % target
return network.get_extern_data(target, mark_data_key_as_used=mark_data_key_as_used)
def _get_target_value(self, mark_data_key_as_used=True):
"""
:param bool mark_data_key_as_used: forwarded self.network.get_extern_data()
:rtype: Data | None
"""
return self._static_get_target_value(
target=self.target, _target_layers=self._target_layers,
network=self.network, mark_data_key_as_used=mark_data_key_as_used)
def _cond_only_on_eval_opt(self, on_eval_func, default_value):
"""
:param ()->(tf.Tensor|None) on_eval_func:
:param float|tf.Tensor default_value:
:return: tensor (coming from tf.cond if needed) if on_eval_func returned a tensor, otherwise None
:rtype: tf.Tensor|None
"""
if not isinstance(default_value, tf.Tensor):
default_value = tf.constant(default_value, name="only_on_eval_dummy_zero")
class OnEval:
"""
Closure.
"""
have_output = True
@classmethod
def get_value(cls):
"""
:rtype: tf.Tensor
"""
res_ = on_eval_func()
if res_ is None:
cls.have_output = False
return default_value # Doesn't matter, will not be used anyway.
return res_
res = self.network.cond_on_train(lambda: default_value, OnEval.get_value)
if not OnEval.have_output:
return None
return res
@classmethod
def get_losses(cls, name, network, output, loss=None, reduce_func=None, layer=None, **kwargs):
"""
Losses will get constructed here.
This gets called inside a loss name scope of the layer.
When overriding this, make sure that it works both with `layer` set and unset.
: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 LayerBase|None layer:
The real layer instance, if it exists at the current point.
If not given, init() must be called at a later point.
:param ((tf.Tensor)->tf.Tensor)|None reduce_func: if given, will overwrite the reduce func for the loss.
By default, every loss_value and error_value is a scalar
(sum or average over the batches, and over the frames for frame-wise losses).
However, if you provide reduce_func = TFUtil.identity, you can get the unreduced tensor.
:param kwargs: all the remaining __init__ args
:return: the losses defined by this layer
:rtype: list[TFNetwork.LossHolder]
"""
if not loss:
return []
from TFNetwork import LossHolder
return [LossHolder(
name=name, network=network, loss=loss, layer_output=output, layer=layer, reduce_func=reduce_func)]
def get_losses_initialized(self, reduce_func=None):
"""
As self.get_losses, but here we return them all initialized (i.e. the layer is set).
You should not override this method but rather :func:`get_losses`.
:param ((tf.Tensor)->tf.Tensor)|None reduce_func: as in get_losses
:return: the losses defined by this layer
:rtype: list[TFNetwork.LossHolder]
"""
return self.__class__.get_losses(reduce_func=reduce_func, layer=self, **self.kwargs)
def get_params_l2_norm(self):
"""
:return: scalar
:rtype: tf.Tensor
"""
return 2 * sum([tf.nn.l2_loss(param) for (name, param) in sorted(self.params.items())])
def get_output_spatial_smoothing_energy(self):
"""
:return: scalar. see :func:`TFUtil.spatial_smoothing_energy`
:rtype: tf.Tensor
"""
from TFUtil import spatial_smoothing_energy, flatten_with_seq_len_mask
energy = spatial_smoothing_energy(self.output.placeholder, dim=self.output.dim) # (batch,time)
assert self.output.have_time_axis()
energy = flatten_with_seq_len_mask(
energy,
seq_lens=self.output.size_placeholder[self.output.time_dim_axis_excluding_batch],
time_major=self.output.is_time_major) # (time')
energy = tf.reduce_sum(energy)
return energy
def get_darc1(self):
"""
DARC1, simplified Directly Approximately Regularizing Complexity (DARC), via
Generalization in Deep Learning, https://arxiv.org/abs/1710.05468
:return: scalar
:rtype: tf.Tensor
"""
with tf.name_scope("darc1"):