-
Notifications
You must be signed in to change notification settings - Fork 0
/
TFNetworkLayer.py
executable file
·6386 lines (5809 loc) · 263 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
from __future__ import print_function
import tensorflow as tf
import contextlib
import TFUtil
from Util import unicode, NotSpecified
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: str|None # for get_layer_class()
recurrent = False # if the order in the time-dimension is relevant
def __init__(self, name, network, output=None, n_out=None, out_type=None, sources=(),
target=None, loss=None, loss_scale=1.0, size_target=None,
reuse_params=None,
L2=None, darc1=None,
is_output_layer=None, only_on_eval=False, only_on_search=False,
copy_output_loss_from_source_idx=None,
batch_norm=False,
spatial_smoothing=0.0,
initial_output=None,
rec_previous_layer=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 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|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 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 float loss_scale: scale factor for loss (1.0 by default). DEPRECATED: use loss.scale instead.
:param ReuseParams|None reuse_params: if given, will opt reuse the params. see :func:`self.var_creation_scope`
:param float|None L2: for constraints
:param float|None darc1: for constraints. see Generalization in Deep Learning, https://arxiv.org/abs/1710.05468
: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 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:
"""
self.name = name
self.network = network
self._register_layer()
self.kwargs = None # type: dict[str] # set via self.post_init
self.target = target
self.loss = loss
if self.loss and self.loss.recurrent:
self.recurrent = True
if loss_scale != 1.0:
assert self.loss, "loss_scale is set, but no loss"
assert self.loss.scale == 1.0, "do not use loss_scale and loss with 'scale' option together"
self.loss.scale = loss_scale
if output:
self.output = output
if n_out:
assert self.output.dim == n_out
if out_type:
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: None|OutputWithActivation
self.output_loss = None # type: None|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: dict[str,tf.Tensor]
self.search_choices = None # type: SearchChoices
self._initial_output = initial_output
self._rec_previous_layer = rec_previous_layer
self.post_init_hooks = [] # list of functions
self.sources = sources
self.params = {} # type: dict[str,tf.Variable]
self.saveable_param_replace = {} # see get_saveable_params_dict()
" :type: dict[tf.Variable,tensorflow.python.training.saver.BaseSaverBuilder.SaveableObject|None] "
self.reuse_params = reuse_params
self.L2 = L2
self.darc1 = darc1
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.spatial_smoothing = spatial_smoothing
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: 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=None, target=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 out_type:
:param int|None n_out:
:param str|None target:
: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 loss and not target:
target = network.extern_data.default_target
if n_out is None and target:
n_out = cls._static_get_target_value(target=target, network=network, mark_data_key_as_used=False).dim
if out_type is None:
assert n_out
out_type = {"dim": n_out}
out_type = out_type.copy()
out_type.setdefault("name", "%s_output" % name)
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)
if n_out is not None:
out_type.setdefault("dim", n_out)
assert out_type["dim"] == n_out
# 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 sources_data and "shape" not in out_type:
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:
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))
# Note: No special handling for feature_dim_axis here for now...
beam_size = None
for src in sources:
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, sources=sources, **kwargs)
return output
@classmethod
def _post_init_output(cls, output, network, target=None, size_target=None, sources=(), **kwargs):
"""
:param Data output:
:param TFNetwork.TFNetwork network:
:param str|None target:
:param str|None size_target:
: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.
if sources and sources[0].output.matches_var_dim_pattern(output):
output.size_placeholder = sources[0].output.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 or size_target, network=network,
mark_data_key_as_used=network.train_flag is not False).size_placeholder.copy()
if any([(not src.output.available_for_inference) for src in sources]):
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
"""
# For the root name scope, it's even more restrictive, and we must also cover this case.
name = name.replace(":", "__")
if name[:1] in "_-\\/": # invalid first chars
name = (".%i." % ord(name[0])) + name[1:]
return 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():
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 "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:
d["target"] = network.extern_data.default_target
if d.get("target"):
if network.eval_flag:
# Not resolving this in the dict, but call get_layer to make it available.
assert isinstance(d["target"], str)
if d["target"].startswith("layer:"):
get_layer(d["target"][len("layer:"):])
if "n_out" not in d and d.get("target", None) and network.eval_flag:
# Must be done here now because loss might be set to None later.
d["n_out"] = cls._guess_n_out_from_target_and_opt_loss(
network=network, target=d["target"], loss_class_name=d.get("loss", None), get_layer=get_layer)
if d.pop("loss_only_on_non_search", None) and "loss" in d and network.search_flag:
del d["loss"]
d["loss"] = cls._make_loss(
class_name=d.pop("loss", None), opts=d.pop("loss_opts", None), network=network, get_layer=get_layer)
@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).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):
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 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.
:rtype: bool
"""
if self._is_output_layer is not None:
return self._is_output_layer
if self.target:
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]
"""
return list(self.sources)
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_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 var_creation_scope, 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))
with var_creation_scope() as dep:
if self.reuse_params:
with reuse_name_scope(self.reuse_params.get_variable_scope(base_layer=self, **kwargs)) as scope:
yield scope
else:
with reuse_name_scope(tf.get_variable_scope(), **kwargs) 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
"""
if isinstance(param, tf.Tensor):
# This can happen with a custom_getter in tf.get_variable(), e.g. via self.reuse_params.
# In that case, don't treat it like a param, i.e. don't save a reference in self.params,
# where we only want to store tf.Variable objects.
return param
assert isinstance(param, tf.Variable)
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_base_absolute_name_scope_prefix(base_layer=self, param=param)
else:
name_scope_prefix = self.get_base_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
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, get_layer=None):
"""
:param str target:
: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.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, 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:
have_output = True
@classmethod
def get_value(cls):
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.
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"):
if self.output_before_activation:
x = self.output_before_activation.x
else:
x = self.output.placeholder
mask = self.output.get_sequence_mask() # (time,batch) or (batch,time), like output
size = tf.size(mask) # time * batch
mask = tf.reshape(mask, (size,)) # (time*batch,)
x = tf.reshape(x, (size,) + self.output.shape[1:]) # (time*batch,dim)
x = tf.abs(x)
x = tf.where(mask, x, tf.zeros_like(x))
x = tf.reduce_sum(x, axis=0) # (dim,)
assert isinstance(x, tf.Tensor)
assert x.get_shape().ndims == 1
x = tf.reduce_max(x) # scalar
return x
def get_constraints_value(self):
"""
:return: None or scalar
:rtype: tf.Tensor|None
"""
c = 0
if self.L2:
c += self.L2 * self.get_params_l2_norm()
if self.spatial_smoothing:
c += self.spatial_smoothing * self.get_output_spatial_smoothing_energy()
if self.darc1:
c += self.darc1 * self.get_darc1()
if c is 0:
return None
return c
def batch_norm(self, data,
use_shift=True, use_std=True, use_sample=0.0, force_sample=False,
momentum=0.99, epsilon=1e-3,
sample_mean=None, sample_variance=None,
gamma=None, beta=None):
"""
:param Data data:
:param bool use_shift:
:param bool use_std:
:param float use_sample: defaults to 0.0 which is used in training
:param bool force_sample: even in eval, use the use_sample factor
:param float momentum: for the running average of sample_mean and sample_std
:param float epsilon:
:param tf.Tensor sample_mean:
:param tf.Tensor sample_variance:
:param tf.Tensor gamma:
:param tf.Tensor beta:
:rtype: tf.Tensor
http://arxiv.org/abs/1502.03167
Also see:
tf.nn.batch_normalization()
https://github.com/deepmind/sonnet/blob/master/sonnet/python/modules/batch_norm.py
"""
with tf.variable_scope("batch_norm"):
x = data.get_placeholder_flattened(keep_dims=True) # shape (time',...)
mean, variance = tf.nn.moments(x, axes=[0], keep_dims=True)
if sample_mean is None:
with self.var_creation_scope():
sample_mean = self.add_param(tf.Variable(
initial_value=tf.zeros(data.get_bc_spatial_batch_shape()),
name="%s_%s_mean" % (self.name, data.name),
trainable=False))
# Use exponential moving average of batch mean.
# Note: We could also use cumulative moving average. Our Theano implementation does that for inference.
sample_mean = tf.assign_add(sample_mean, (mean - sample_mean) * momentum)
if sample_variance is None:
# Note: Our Theano implementation does not use a moving average for this.
with self.var_creation_scope():
sample_variance = self.add_param(tf.Variable(
initial_value=tf.ones(data.get_bc_spatial_batch_shape()),
name="%s_%s_variance" % (self.name, data.name),
trainable=False))
sample_variance = tf.assign_add(sample_variance, (variance - sample_variance) * momentum)
# If train or if force_sample, use default use_sample=0.0, otherwise use_sample=1.0.
use_sample = 1.0 + tf.cast(tf.logical_or(self.network.train_flag, force_sample), tf.float32) * (use_sample - 1.0)
mean = (1. - use_sample) * mean + use_sample * sample_mean
variance = (1. - use_sample) * variance + use_sample * sample_variance
bn = (data.placeholder - mean) * tf.rsqrt(variance + epsilon)
if use_std:
if gamma is None:
with self.var_creation_scope():
gamma = self.add_param(tf.Variable(
initial_value=tf.ones(data.get_bc_spatial_batch_shape()),
name="%s_%s_gamma" % (self.name, data.name),
trainable=True))
bn *= gamma
if use_shift:
if beta is None:
with self.var_creation_scope():
beta = self.add_param(tf.Variable(
initial_value=tf.zeros(data.get_bc_spatial_batch_shape()),
name="%s_%s_beta" % (self.name, data.name),
trainable=True))
bn += beta
return bn
def get_hidden_state(self):
"""
If this is a recurrent layer, this would return the hidden state.
This is used e.g. for the RnnCellLayer class.
:rtype: tf.Tensor | list[tf.Tensor] | None
:return: optional tensor(s) with shape (time, batch, dim)
"""
return None
def get_last_hidden_state(self, key):
"""
If this is a recurrent layer, this would return the last hidden state.
Otherwise, we return None.
:param int|str|None key: also the special key "*"
:rtype: tf.Tensor | None
:return: optional tensor with shape (batch, dim)
"""
return None
@classmethod
def get_rec_initial_output(cls, batch_dim, name, output, rec_layer, initial_output=None, **kwargs):
"""
If this layer is used inside a recurrent layer, this function specifies the
output of frame t=-1, if it is needed.
As arguments, we get the usual layer arguments.
batch_dim is added because it might be special because of beam search.
Note: This could maybe share code with :func:`RnnCellLayer.get_rec_initial_state`.
We could also add support to make the initial output be the output of another layer.
:param tf.Tensor batch_dim: including beam size in beam search
:param str name: layer name
:param Data output: template
:param TFNetworkRecLayer.RecLayer rec_layer:
:param str|float|int|tf.Tensor|None initial_output:
:rtype: tf.Tensor
"""
import numpy
v = initial_output
data = output
if isinstance(v, tf.Tensor):
return v
if v is None and data.sparse:
raise Exception(
("You must explicitly provide an initial output value for sparse data %r." % data) +
(" E.g. '%s': {'initial_output': 'zeros'}." % name))
if v is None:
v = "zeros"
bc_shape = [(d if (d is not None) else 1) for d in data.batch_shape]
# Some other code might not support automatic broadcasting in the batch-axis. (Example: concat_in_time)
# Thus we will automatically
shape = list(bc_shape)
shape[data.batch_dim_axis] = batch_dim
if isinstance(v, (float, int)):
with tf.name_scope("init_%s_const" % name):
from TFUtil import constant_with_shape
return tf.cast(constant_with_shape(v, shape=shape), dtype=data.dtype)
assert isinstance(v, str)
if v == "zeros":
return tf.zeros(shape, dtype=data.dtype, name="init_%s_zeros" % name)
elif v == "ones":
return tf.ones(shape, dtype=data.dtype, name="init_%s_ones" % name)
elif v == "var":
assert not data.sparse
assert numpy.prod(bc_shape) == data.dim
with rec_layer.var_creation_scope():
x = tf.get_variable(
"init_%s_var" % name, shape=(data.dim,), dtype=data.dtype, initializer=tf.zeros_initializer(dtype=data.dtype))
x = tf.reshape(x, bc_shape, name="init_%s_var_bc" % name)
x = tf.tile(x, [batch_dim if (i == data.batch_dim_axis) else 1 for i in range(data.batch_ndim)],
name="init_%s_var_batch_bc" % name)
return x
elif v == "apply(0)":
# We will apply the layer for the input 0 and use this as the initial state.
# This code might be a bit unstable.
kwargs = kwargs.copy()
sources = kwargs.pop("sources")
zeroed_sources = []
for src in sources:
assert isinstance(src, LayerBase)
src_output = src.output.copy()
if src_output.placeholder is not None:
zeroed_src_shape = tf.shape(src_output.placeholder)
zeroed_src_shape = [zeroed_src_shape[i] for i in range(src_output.batch_ndim)]
else:
zeroed_src_shape = [(d if (d is not None) else 1) for d in src_output.batch_shape]
if src_output.batch_dim_axis is not None:
zeroed_src_shape[src_output.batch_dim_axis] = batch_dim
src_output.placeholder = tf.zeros(
zeroed_src_shape, dtype=src_output.dtype, name="init_%s_zeros" % src.name)
src_output.sanity_check()
zeroed_src = InternalLayer(name="%s_zeroed" % src.name, output=src_output, network=src.network)
zeroed_sources.append(zeroed_src)
layer = cls(name=name, output=output.copy(), sources=tuple(zeroed_sources), **kwargs)
out = layer.output.placeholder
out.set_shape(data.batch_shape)
return out
else:
raise Exception("invalid initial output type %r for sub-layer %r" % (v, name))
@classmethod
def get_rec_initial_extra_outputs(cls, batch_dim, rec_layer, **kwargs):
"""
:param tf.Tensor batch_dim: for this layer, might be with beam
:param TFNetworkRecLayer.RecLayer rec_layer:
:rtype: dict[str,tf.Tensor]
"""
return {}
@classmethod
def get_rec_initial_extra_outputs_shape_invariants(cls, **kwargs):
"""
:return: optional shapes for the tensors by get_rec_initial_extra_outputs
:rtype: dict[str,tf.TensorShape]
"""
return {}
class ReuseParams:
"""
This is for parameter sharing, i.e. reusing existing `tf.Variable` objects in a new layer,
instead of creating new variables.
:func:`ReuseParams.from_config_dict` will be called via :func:`LayerBase.transform_config_dict`.
"""
@classmethod
def from_config_dict(cls, opts, network, get_layer):
"""
This will be called via :func:`LayerBase.transform_config_dict` on the layer option `"reuse_params"`.
:param str|dict[str]|None opts:
If None, we will return None.
If str, it will be interpret as a layer name.