/
basic.py
7297 lines (6429 loc) · 264 KB
/
basic.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
"""
Lots of random utility functions for TensorFlow.
"""
from __future__ import print_function, division
import tensorflow as tf
from tensorflow.python.client import device_lib
from tensorflow.python.ops import init_ops
import contextlib
import os
import sys
import threading
import typing
from returnn.util.basic import NotSpecified, NativeCodeCompiler
import returnn.tf.compat as tf_compat
# noinspection PyUnresolvedReferences
from .data import Data, SearchBeam, Dim, DimensionTag
try:
from tensorflow.python.ops.control_flow_v2_func_graphs import ControlFlowFuncGraph
except ImportError:
ControlFlowFuncGraph = None
class CollectionKeys:
"""
Extension of :class:`tf.compat.v1.GraphKeys`
"""
RETURNN_LAYERS = "_RETURNN_layers" # LayerBase instances
RETURNN_NET_STACK = "_RETURNN_network_stack" # TFNetwork instance stack
STATE_VARS = "_RETURNN_state_vars" # tf.Variable, like e.g. tf.compat.v1.GraphKeys.LOCAL_VARIABLES
def tf_version_tuple():
"""
:return: version tuple, e.g. (1, 1, 0), parsed from tf.__version__
:rtype: tuple[int]
"""
import re
# noinspection PyUnresolvedReferences
return tuple([int(s) for s in re.sub('-rc[0-9]|-dev[0-9]*', '', tf.__version__).split(".")])
def assert_min_tf_version(version, reason):
"""
:param tuple[int] version: e.g. (1,2,0) or (1,2)
:param str reason:
"""
tf_version = tf_version_tuple()
assert len(version) <= len(tf_version)
assert tf_version >= version, "Your TF version %r is too old (older than %r). %s" % (tf_version, version, reason)
def have_min_tf_version(version):
"""
:param tuple[int] version: e.g. (1,2,0) or (1,2)
:return: True if we have at least that version, or newer
:rtype: bool
"""
tf_version = tf_version_tuple()
assert len(version) <= len(tf_version)
return tf_version >= version
class CustomUpdate(object):
"""
Custom updates will be handled by :class:`TFUpdater`.
"""
def set_on_var(self, var):
"""
:param tf.Variable var: variable to update. this will be recognized by :class:`TFUpdater.Updater`
"""
# A bit ugly, but simple.
setattr(var, "returnn_custom_update", self)
def update_var(self, var):
"""
:param tf.Variable var: variable to update
:return: operation which updates the variable, e.g. tf.compat.v1.assign_add(var, something)
:rtype: tf.Operation
"""
raise NotImplementedError
class CustomUpdateExpAverage(CustomUpdate):
"""
exponential moving average
"""
def __init__(self, average, alpha):
"""
:param tf.Tensor average:
:param float alpha:
"""
self.average = average
self.alpha = alpha
def update_var(self, var):
"""
:param tf.Variable var:
:rtype: tf.Tensor
"""
return tf_compat.v1.assign_add(var, self.alpha * (self.average - var)) # ((alpha - 1) * old + alpha * new)
def set_param_axes_split_info(param, axes_split_info):
"""
:param tf.Variable|tf.Tensor param:
:param list[list[int]|None] axes_split_info: e.g. [[n],[n]*4] for LSTM matrices
"""
check_param_axes_split_info(param.get_shape().as_list(), axes_split_info)
setattr(param, "returnn_axes_split_info", axes_split_info)
def check_param_axes_split_info(param_shape, axes_split_info):
"""
:param list[int|None]|tuple[int|None] param_shape:
:param list[list[int]|None] axes_split_info: e.g. [[n],[n]*4] for LSTM matrices
"""
assert len(axes_split_info) == len(param_shape)
for i, parts in enumerate(axes_split_info):
if parts is not None:
assert param_shape[i] == sum(parts)
def get_param_axes_split_info(param):
"""
See :func:`set_param_axes_split_info`.
:param tf.Variable|tf.Tensor param:
:rtype: list[list[int]|None]|None
"""
return getattr(param, "returnn_axes_split_info", None)
def transform_param_axes_split_info_to_new_shape(axes_split_info, new_shape, debug_name="<unknown>"):
"""
new_shape can be bigger or smaller than the old shape.
In some simple cases, it is obvious how that should be done, e.g. [[a],[b]*4], [a*2,b*8] -> [[a*2],[b*2]*4]
In some, it is not so. E.g. [[a+b],[b]*4], [a+b*2,b*8] -> [[a+b*2],[b*2]*4].
We should try to always return something, though.
If some case is not covered yet, extend this.
See test cases as well, :func:`test_transform_param_axes_split_info_to_new_shape`.
No TF involved here, however, fits better to the functions above.
:param list[list[int]] axes_split_info:
:param list[int]|tuple[int] new_shape:
:param str debug_name:
:return: new axes-split-info for the new shape
:rtype: list[list[int]]
"""
new_axes_split_info = []
assert len(axes_split_info) == len(new_shape)
dim_diff = {} # old-dim -> new-dim
for new_dim, parts in zip(new_shape, axes_split_info):
if len(parts) == 1:
dim_diff[parts[0]] = new_dim
elif len(set(parts)) == 1: # all the same
if new_dim % len(parts) == 0:
dim_diff[parts[0]] = new_dim // len(parts) # just a heuristic
for i, (new_dim, parts) in enumerate(zip(new_shape, axes_split_info)):
assert len(parts) >= 1, "%s transform %r %r diff %r" % (debug_name, axes_split_info, new_shape, dim_diff)
if len(parts) == 1: # simple case
new_axes_split_info.append([new_dim])
continue
new_parts = [dim_diff.get(d) for d in parts]
if any([d is None for d in new_parts]):
while sum([d is None for d in new_parts]) > 1:
# More than one entry is ambiguous. Assume the next one stayed the same.
j = [d is None for d in new_parts].index(True)
new_parts[j] = parts[j]
j = [d is None for d in new_parts].index(True)
new_parts[j] = new_dim - sum([d for d in new_parts if d is not None])
assert new_parts[j] > 0, debug_name
elif sum(new_parts) != new_dim:
# another heuristic. assume that the first is wrong.
new_parts[0] = new_dim - sum(new_parts[1:])
assert new_parts[0] > 0, debug_name
assert sum(new_parts) == new_dim, debug_name
new_axes_split_info.append(new_parts)
return new_axes_split_info
def copy_with_new_split_axes(old_axis_splits, new_axis_splits, old_values, new_values=None):
"""
On Numpy arrays only, however, fits better to the functions above.
:param list[list[int]] old_axis_splits:
:param list[list[int]] new_axis_splits:
:param numpy.ndarray old_values:
:param numpy.ndarray new_values:
:return: new values
:rtype: numpy.ndarray
"""
import numpy
assert len(old_axis_splits) == len(new_axis_splits)
assert all([len(old_parts) == len(new_parts) for (old_parts, new_parts) in zip(old_axis_splits, new_axis_splits)])
old_shape = [sum(parts) for parts in old_axis_splits]
assert tuple(old_shape) == old_values.shape
new_shape = [sum(parts) for parts in new_axis_splits]
if new_values is None:
new_values = numpy.zeros(new_shape, dtype=old_values.dtype)
for idxs in numpy.ndindex(tuple([len(parts) for parts in old_axis_splits])):
assert len(idxs) == len(old_axis_splits) == len(new_axis_splits)
old_offsets = [sum(parts[:i]) for i, parts in zip(idxs, old_axis_splits)]
new_offsets = [sum(parts[:i]) for i, parts in zip(idxs, new_axis_splits)]
dims = [min(old_parts[i], new_parts[i]) for i, old_parts, new_parts in zip(idxs, old_axis_splits, new_axis_splits)]
old_slices = tuple([slice(offset, offset + dim) for offset, dim in zip(old_offsets, dims)])
new_slices = tuple([slice(offset, offset + dim) for offset, dim in zip(new_offsets, dims)])
new_values[new_slices] = old_values[old_slices]
return new_values
def get_padding_info_dict_ref(x):
"""
:param tf.Tensor x:
:rtype: dict[Dim,float|int]
"""
_attr = "RETURNN_attr_padding_value_info"
if hasattr(x, _attr):
d = getattr(x, _attr)
assert isinstance(d, dict)
return d
d = {}
setattr(x, _attr, d)
return d
def set_padding_info(x, dim, pad_value):
"""
Stores the information what kind of padding value to expect after masking in the given dynamic dim.
:param tf.Tensor x:
:param returnn.tf.util.data.Dim dim: dynamic seq len axis
:param float|int pad_value:
"""
d = get_padding_info_dict_ref(x)
# If there is some earlier padding info, only keep it when it is the same value.
# Otherwise it becomes invalid.
for k, v in list(d.items()):
if v != pad_value:
del d[k]
d[dim] = pad_value
def mask_dyn_seq_len_nd(x, pad_value, axes):
"""
:param Data x:
:param float|int|tf.Tensor pad_value:
:param list[int]|tuple[int] axes:
:return: masked x
:rtype: tf.Tensor
"""
# Filter out some axes which should not be used for masking.
axes_ = []
for axis in axes:
tag = x.dim_tags[axis]
assert tag.dyn_size_ext
# It only makes sense to apply for this axis if the dyn size dims are all existing in x itself.
# E.g. if the dyn_size_ext shape is [B] but the shape of x is just [T] (without B),
# then we do not need masking.
if set(tag.dyn_size_ext.dim_tags).issubset(x.dim_tags):
axes_.append(axis)
axes = axes_
x_ = x.placeholder
if not axes:
return x_
pad_value_is_const = isinstance(pad_value, (int, float))
if pad_value_is_const:
d = get_padding_info_dict_ref(x_)
existing_pad_values = [d.get(x.dim_tags[axis]) for axis in axes]
if set(existing_pad_values) == {pad_value}:
return x_ # nothing to do
mask = None
for axis in axes:
mask_ = x.get_sequence_mask_broadcast(axis=axis)
mask = tf.logical_and(mask, mask_) if mask is not None else mask_
assert isinstance(mask, tf.Tensor)
x_ = where_bc(mask, x_, tf.cast(tf.convert_to_tensor(pad_value, name="pad_value"), dtype=x_.dtype))
if pad_value_is_const:
d = get_padding_info_dict_ref(x_)
d.clear()
d.update({x.dim_tags[axis]: pad_value for axis in axes})
return x_
def copy_compatible_reduce(source, target, reduce_type):
"""
Extension of Data.copy_compatible_to which also reduces additional dims.
:param Data source:
:param Data target:
:param str reduce_type: eg "max"
:return: source with broadcast-compatible shape to target
:rtype: Data
"""
common = Data.get_common_data([target, source])
extra_dims = list(common.dim_tags)
for d in target.dim_tags:
extra_dims.remove(d)
if not extra_dims:
return source.copy_compatible_to(target, check_sparse=False, check_dtype=False)
# extra_dims now contains dims only in source but not in target
for d in extra_dims:
assert not d.is_dynamic(), (
"%r, %r, cannot reduce dynamic dim %r (just not implemented here...)" % (source, target, d))
assert reduce_type == "max", "only max implemented currently"
axis = source.get_axis_from_description(d)
x = tf.reduce_max(source.placeholder, axis=axis)
dim_tags = source.dim_tags[:axis] + source.dim_tags[axis + 1:]
source = Data(source.name, dim_tags=dim_tags, dtype=source.dtype, placeholder=x)
# Now this should work.
return source.copy_compatible_to(target, check_sparse=False, check_dtype=False)
class OutputWithActivation(object):
"""
Stores some tensor before and after some activation function,
and also the activation function itself.
(Maybe obsolete when you directly access the TF computation graph; but simpler.)
"""
def __init__(self, x, act_func=None, act_func_opts=None):
"""
:param tf.Tensor x:
:param None|(tf.Tensor)->tf.Tensor act_func:
:param None|dict[str] act_func_opts:
"""
self.x = x
self.act_func = act_func
if act_func_opts is None:
act_func_opts = {}
self.act_func_opts = act_func_opts
if act_func:
with tf.name_scope("activation"):
# noinspection PyArgumentList
self.y = act_func(x, **act_func_opts)
else:
self.y = x
def is_softmax_act_func(self):
"""
:rtype: bool
"""
return self.act_func is tf.nn.softmax
def get_logits(self):
"""
:rtype: tf.Tensor
:return: logits. logits are (not necessarily normalized) log probabilities, i.e. the input of softmax.
This call assumes that self.y is in probability space.
"""
if self.is_softmax_act_func():
return self.x
if self.act_func is tf.exp:
return self.x
return safe_log(self.y)
def get_log_output(self):
"""
:rtype: tf.Tensor
:return: tf.math.log(output)
"""
if self.is_softmax_act_func():
return tf.nn.log_softmax(self.x)
if self.act_func is tf.exp:
return self.x
if self.act_func is tf.sigmoid:
return tf_compat.v1.log_sigmoid(self.x)
return safe_log(self.y)
def variable_scalar_summaries_dict(x, name=None):
"""
Collects all interesting information about `x`, such as min/max/mean, etc. (all scalars).
This is used by :func:`variable_summaries`.
:param tf.Tensor|tf.Variable x:
:param str name:
:return: dicth with key -> scalar info, e.g. with "%s_mean" % name -> tf.reduce_mean(x)
:rtype: dict[str,tf.Tensor]
"""
if x.dtype == tf.string:
return {}
if not name:
name = get_base_name(x)
if x.dtype.is_integer:
x_float = tf.cast(x, tf.float32)
else:
x_float = x
mean = tf.reduce_mean(x_float)
stddev = tf.sqrt(tf.reduce_mean(tf.square(x_float - mean)))
return {
'%s_mean' % name: mean,
'%s_stddev' % name: stddev,
'%s_rms' % name: tf.sqrt(tf.reduce_mean(tf.square(x_float))),
'%s_l2' % name: tf.sqrt(tf.nn.l2_loss(x_float) * 0.5),
'%s_max' % name: tf.reduce_max(x),
'%s_min' % name: tf.reduce_min(x)}
def variable_summaries(var, name=None, with_histogram=False):
"""
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
Also see :func:`variable_scalar_summaries_dict`.
:param tf.Tensor|tf.Variable var:
:param str name:
:param bool with_histogram: adds histogram. note that this can add noticeable overhead
:return: nothing, use :func:`tf.compat.v1.summary.merge_all()` to collect the summaries
"""
if var.dtype == tf.string:
return
if not name:
name = get_base_name(var)
with tf.name_scope('summaries_%s' % name):
for k, v in variable_scalar_summaries_dict(var, name=name).items():
tf_compat.v1.summary.scalar(k, v)
if with_histogram:
tf_compat.v1.summary.histogram('%s_histogram' % name, var)
def get_valid_scope_name_from_str(s):
"""
:param str s: some name
:return: valid scope name, might be just s. 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.
# NOTE: Be careful changing this logic. Try to never change the behavior for existing cases,
# because this name is used e.g. for layers, and you might introduce incompatibility by changes here.
import re
s = re.sub("[:(){}&+\\-*'\" ,]", "__", s)
if s[:1] in "_-\\/": # invalid first chars
s = (".%i." % ord(s[0])) + s[1:]
return s
def get_current_var_scope_name():
"""
:return: current absolute variable scope name, via tf.compat.v1.variable_scope
:rtype: str
"""
v = tf_compat.v1.get_variable_scope()
return v.name
def get_current_name_scope():
"""
:return: current absolute name scope, via tf.name_scope
:rtype: str
https://stackoverflow.com/questions/40907769/how-to-get-current-tensorflow-name-scope
Note that this is a private member and might break at some point.
Note also that this does not need to be the same as get_current_var_scope_name().
"""
if tf_compat.executing_eagerly():
# tf.get_current_name_scope() is not available in earlier TF versions, even with eager mode.
from tensorflow.python.eager import context
ctx = context.context()
return ctx.scope_name.rstrip("/")
# noinspection PyProtectedMember
return tf_compat.v1.get_default_graph()._name_stack or ""
@contextlib.contextmanager
def reuse_name_scope(name, absolute=None, **kwargs):
"""
Context manager to reuse an already created scope.
We try to both set the variable scope and the name scope.
:param str|tf.compat.v1.VariableScope name: relative or absolute name scope
(absolute if absolute=True or if tf.compat.v1.VariableScope).
Must not end with "/".
:param bool|None absolute: if True it will be absolute
:param kwargs: passed on to `tf.compat.v1.variable_scope`
:return: yields the variable_scope
"""
kwargs = kwargs.copy()
parent_var_scope = None # type: typing.Optional[tf_compat.v1.VariableScope]
if not absolute:
parent_var_scope = tf_compat.v1.get_variable_scope()
if isinstance(name, tf_compat.v1.VariableScope):
parent_var_scope = name
name = name.name
if absolute is not None:
assert absolute is True
absolute = True
if parent_var_scope:
for attr in [
"reuse", "initializer", "regularizer", "caching_device", "partitioner",
"dtype", "custom_getter", "use_resource", "constraint"
]:
if not hasattr(parent_var_scope, attr):
continue # e.g. "constraint" not available in older TF
kwargs.setdefault(attr, getattr(parent_var_scope, attr))
assert isinstance(name, str)
if not absolute:
assert name
# First figure out the absolute name scope which we want to reuse/set.
# The current name scope is more reliable because tf.compat.v1.variable_scope
# will always also set the name scope.
current_name_scope = get_current_name_scope()
if current_name_scope:
name = current_name_scope + "/" + name
else:
current_name_scope = None # not needed
assert name[:1] != "/" and name[-1:] != "/"
abs_name = name + "/" if name else ""
# tf.name_scope with a scope-name ending with "/" will interpret is as absolute name,
# and use it as-is.
# In all other cases, it would create a new name-scope with a new unique name,
# which is not what we want.
with tf.name_scope(abs_name):
# tf.name_scope will not set the variable scope.
# tf.compat.v1.variable_scope will also set the name scope, but the logic is broken
# for absolute name scopes, thus we had to do the tf.name_scope manually above.
# We create the dummy_var_scope to force it to reuse that name,
# and the trailing "/" will work-around the broken tf.compat.v1.variable_scope() usage of tf.name_scope().
# Afterwards we fix that name again.
# Note that the reuse-argument might be miss-leading in this context:
# It means that tf.compat.v1.get_variable() will search for existing variables and errors otherwise.
var_scope = tf_compat.v1.VariableScope(name=abs_name, reuse=kwargs.get("reuse", None))
with tf_compat.v1.variable_scope(var_scope, **kwargs) as scope:
assert isinstance(scope, tf_compat.v1.VariableScope)
# remove "/" from the end of the var-scope.
# This is a work-around to fix up the variable scope behavior for nested variable scopes.
# Warning: This might break at some future point.
# noinspection PyProtectedMember
assert scope.name is scope._name
assert scope.name[-1:] == "/" or scope.name == ""
# noinspection PyProtectedMember
scope._name = scope._name[:-1]
assert name == scope.name, "%r" % current_name_scope
yield scope
@contextlib.contextmanager
def opt_reuse_name_scope(name):
"""
:param str|tf.compat.v1.VariableScope name:
:return: yields the variable_scope
"""
if name:
with reuse_name_scope(name) as scope:
yield scope
else:
yield tf_compat.v1.get_variable_scope()
def get_name_scope_of_tensor(x):
"""
:param tf.Tensor x: has name e.g. "layer0/rec/W:0"
:return: the name scope of x, e.g. "layer0/rec"
:rtype: str
"""
parts = str(x.name).split("/")
return "/".join(parts[:-1])
def get_base_name(x):
"""
:param tf.Tensor|tf.Variable x: has name e.g. "layer0/rec/W:0"
:return: return the base name, e.g. "W", without the output index
"""
parts = str(x.name).split("/")
return parts[-1].split(":")[0]
@contextlib.contextmanager
def reuse_name_scope_of_tensor(x, prefix="", postfix="", add_tensor_name=False):
"""
:param tf.Tensor|tf.Variable x: has name e.g. "layer0/rec/W:0"
:param str prefix:
:param str postfix:
:param bool add_tensor_name:
:return: reuse the name scope of x, e.g. "layer0/rec", yields scope
"""
if tf_compat.executing_eagerly():
yield tf_compat.v1.get_variable_scope()
return
name_scope = get_name_scope_of_tensor(x)
if add_tensor_name:
from returnn.util.basic import unicode_to_str
tensor_name = unicode_to_str(os.path.basename(x.name).split(":")[0])
if name_scope:
name_scope += '/' + tensor_name
else:
name_scope = tensor_name
if not prefix and not name_scope and postfix.startswith("/"):
postfix = postfix[1:]
with reuse_name_scope(prefix + name_scope + postfix, absolute=True) as scope:
yield scope
@contextlib.contextmanager
def default_control_flow_ctx():
"""
This was earlier called ``var_creation_scope``.
If you create a variable inside of a while-loop, you might get the following error:
InvalidArgumentError: The node 'while/w/Assign' has inputs from different frames.
The input 'while/j' is in frame 'while/while/'. The input 'while/w' is in frame ''.
This happens when you directly call ``tf.Variable``, because the initial_value might be a tensor
which depends on the current control flow context.
See tests/test_TFUtil.py:test_loop_var_creation() for an example.
Related TF bugs:
https://github.com/tensorflow/tensorflow/issues/3114
https://github.com/tensorflow/tensorflow/issues/4478
https://github.com/tensorflow/tensorflow/issues/8604
One solution is to reset the current control flow context.
See also :func:`same_control_flow_ctx`.
However, with respect to variables, you should instead use
``tf.get_variable``, which does not have this problem.
"""
if tf_compat.v2:
root_graph = get_root_graph()
with root_graph.as_default(), tf.control_dependencies(None) as dep:
yield dep
return
# Resetting all control dependencies has the effect of also resetting the current control flow context.
with tf.control_dependencies(None) as dep:
yield dep
def get_root_graph(graph=None):
"""
:param tf.Graph|None graph:
:return: root graph. with control flow v2, the current graph might not be the root graph
:rtype: tf.Graph
"""
if graph is None:
graph = tf_compat.v1.get_default_graph()
if not tf_compat.v2:
return graph
from tensorflow.python.framework.func_graph import FuncGraph
while graph.building_function:
assert isinstance(graph, FuncGraph)
graph = graph.outer_graph
return graph
class _ScaledGradientBuilder(object):
"""
Use the ``scaled_gradient`` instance.
tf.identity in forward pass, but scales the gradient in backprop.
Can be used as gradient reversal layer (with negative scale)
("flip gradients").
Discussion:
https://github.com/fchollet/keras/issues/3119
https://github.com/tensorflow/tensorflow/issues/4342
Code from here:
https://github.com/pumpikano/tf-dann/blob/master/flip_gradient.py
Also see :class:`CustomGradient` which is more generic.
"""
# Needs unique grad_name (op name) per each call, thus just use a counter.
num_calls = 0
def __call__(self, x, scale=1.0, shift=0.0, scale_shift_by_sum_over_axis=None, clip_max_axis=None):
"""
:param tf.Tensor x:
:param float|tf.Tensor scale:
:param float|tf.Tensor|None shift:
:param int|None scale_shift_by_sum_over_axis: if given, calculates the sum over this axis (absolute values)
and multiplies the shift value by this sum.
:param int|None clip_max_axis: if given, clips the gradient to the abs max value in this axis
before the transformation, for all values in the axis
:rtype: tf.Tensor
"""
grad_name = "RETURNN_ScaledGradient%d" % _ScaledGradientBuilder.num_calls
from tensorflow.python.framework import ops
# noinspection PyUnusedLocal
@ops.RegisterGradient(grad_name)
def _scale_gradients(op, grad):
grad_out = grad
if isinstance(scale, tf.Tensor) or scale != 1.0:
grad_out = grad_out * scale
if isinstance(shift, tf.Tensor) or shift:
if scale_shift_by_sum_over_axis is not None:
m = tf.reduce_sum(tf.abs(grad), axis=scale_shift_by_sum_over_axis, keepdims=True)
grad_out = grad_out + shift * m
else:
grad_out = grad_out + shift
if clip_max_axis is not None:
m = tf.reduce_max(tf.abs(grad), axis=clip_max_axis, keepdims=True)
grad_out = tf.clip_by_value(grad_out, -m, m)
return [grad_out]
g = tf_compat.v1.get_default_graph()
with g.gradient_override_map({"Identity": grad_name}):
y = tf.identity(x, name="scaled_gradient_identity")
assert y.op.type == "Identity"
_ScaledGradientBuilder.num_calls += 1
return y
scaled_gradient = _ScaledGradientBuilder()
def flip_gradient(x, scale=1.0):
"""
:param tf.Tensor x:
:param float scale:
:return: identity(x) but with flipped gradient (optionally scaled)
:rtype: tf.Tensor
"""
return scaled_gradient(x, scale=-scale)
def lookup_grad_func_by_name(op_type):
"""
:param str op_type:
:return: function grad_func(op, grad), or raises LookupError
"""
from tensorflow.python.framework import ops
# Also see ops.RegisterGradient and ops.get_gradient_function.
# noinspection PyProtectedMember
return ops._gradient_registry.lookup(op_type)
def opt_register_grad_func(op_type, grad_func, assert_is_same=True):
"""
:param str op_type:
:param grad_func: function grad_func(op, grad)
:param bool assert_is_same:
"""
try:
f = lookup_grad_func_by_name(op_type)
except LookupError:
f = None
if f is not None:
if assert_is_same:
assert f is grad_func, "already registered grad for %r, and not the same func: %r != %r" % (op_type, f, grad_func)
else:
from tensorflow.python.framework import ops
ops.RegisterGradient(op_type)(grad_func)
def identity_with_check_numerics(x, with_grad=True, name="identity_with_check_numerics"):
"""
Returns identity(x), but with additional check_numerics control dependency,
and optionally the same for its gradient.
See also :func:`TFUpdater.add_check_numerics_ops`, which will add checks for the whole graph.
:param tf.Tensor x:
:param bool with_grad: whether the check will also be added for the gradient
:param str name:
:rtype: tf.Tensor
"""
with tf.name_scope(name):
with tf.control_dependencies([
tf_compat.v1.check_numerics(x, message="%s check_numerics for tensor %s" % (name, x.name))]):
if with_grad:
# An alternative to gradient_override_map would be :class:`CustomGradient` which is more generic.
# noinspection PyUnusedLocal
def _identity_with_check_numerics_grad(op, grad):
return identity_with_check_numerics(grad, with_grad=True, name="%s_grad" % name)
grad_name = "%s_with_grad" % name
opt_register_grad_func(
op_type=grad_name,
grad_func=_identity_with_check_numerics_grad,
assert_is_same=False)
g = tf_compat.v1.get_default_graph()
with g.gradient_override_map({"Identity": grad_name}):
y = tf.identity(x)
else:
y = tf.identity(x)
return y
def check_input_ndim(x, ndim):
"""
:param tf.Tensor x:
:param int ndim:
:return: x with check added
:rtype: tf.Tensor
"""
dyn_shape = x.get_shape()
if dyn_shape.ndims is not None:
assert dyn_shape.ndims == ndim
return x
# Need to fall-back to runtime check.
with tf.name_scope("check_input_ndim"):
with tf.control_dependencies(
[tf_compat.v1.assert_equal(tf.rank(x), ndim, data=["ndim not %i" % ndim, tf.shape(x)])]):
return tf.identity(x, "identity_with_ndim_check")
def check_input_ndim_equal_offset(x, y, y_ndim_offset=0):
"""
:param tf.Tensor x:
:param tf.Tensor y:
:param int y_ndim_offset:
:return: x with check added such that ndim(x) == ndim(y) + y_ndim_offset
:rtype: tf.Tensor
"""
x_dyn_shape = x.get_shape()
y_dyn_shape = y.get_shape()
if x_dyn_shape.ndims is not None and y_dyn_shape.ndims is not None:
assert x_dyn_shape.ndims == y_dyn_shape.ndims + y_ndim_offset
return x
# Need to fall-back to runtime check.
with tf.name_scope("check_input_ndim_equal_offset"):
with tf.control_dependencies(
[tf_compat.v1.assert_equal(
tf.rank(x), tf.rank(y) + y_ndim_offset,
data=["ndim not equal with offset %i" % y_ndim_offset, tf.shape(x), tf.shape(y)])]):
return tf.identity(x, "identity_with_ndim_equal_check")
def check_input_dim(x, axis, dim):
"""
:param tf.Tensor x:
:param int axis: which axis to check
:param int|tf.Tensor dim:
:return: x with check added
:rtype: tf.Tensor
"""
dyn_shape = x.get_shape()
if dyn_shape.ndims is not None and isinstance(dim, int):
if dyn_shape.dims[axis].value is not None:
assert dyn_shape.dims[axis].value == dim
return x
# Need to fall-back to runtime check.
with tf.name_scope("check_input_dim"):
with tf.control_dependencies([
tf_compat.v1.assert_equal(
tf.shape(x)[axis], dim, data=["shape[%i]:" % (axis,), tf.shape(x), "!=", "dim:", dim])]):
return tf.identity(x, "identity_with_dim_check")
def check_dim_equal(x, x_axis, y, y_axis, extra_msg=()):
"""
:param tf.Tensor x:
:param int x_axis: which axis to check
:param tf.Tensor y:
:param int y_axis: which axis to check
:param list[str]|tuple[str] extra_msg: will be printed additionally if it fails
:return: x with check added that shape(x)[x_axis] == shape(y)[y_axis]
:rtype: tf.Tensor
"""
x_dyn_shape = x.get_shape()
y_dyn_shape = y.get_shape()
if x_dyn_shape.ndims is not None and y_dyn_shape.ndims is not None:
if x_dyn_shape.dims[x_axis].value is not None and y_dyn_shape.dims[y_axis].value is not None:
assert x_dyn_shape.dims[x_axis].value == y_dyn_shape.dims[y_axis].value, extra_msg
return x
# Need to fall-back to runtime check.
with tf.name_scope("check_dim_equal"):
shape_x = tf.shape(x)
shape_y = tf.shape(y)
with tf.control_dependencies(
[tf_compat.v1.assert_equal(
shape_x[x_axis], shape_y[y_axis],
data=["x.shape[%i] != y.shape[%i]" % (x_axis, y_axis), shape_x, shape_y] + list(extra_msg))]):
return tf.identity(x, "identity_with_dim_equal_check")
def check_shape_equal(x, y):
"""
:param tf.Tensor x:
:param tf.Tensor y:
:return: x with check added that shape(x) == shape(y)
:rtype: tf.Tensor
"""
x_dyn_shape = x.get_shape()
y_dyn_shape = y.get_shape()
if x_dyn_shape.ndims is not None and y_dyn_shape.ndims is not None:
assert x_dyn_shape.ndims == y_dyn_shape.ndims
have_unknown = False
for axis in range(x_dyn_shape.ndims):
if x_dyn_shape.dims[axis].value is not None and y_dyn_shape.dims[axis].value is not None:
assert x_dyn_shape.dims[axis].value == y_dyn_shape.dims[axis].value
else:
have_unknown = True
if not have_unknown:
return x # all dims are checked, we can return
# We need to fall-back to runtime check.
with tf.name_scope("check_shape_equal"):
with tf.control_dependencies(
[tf_compat.v1.assert_equal(
tf.shape(x), tf.shape(y),
data=["x.shape not y.shape",
tf.shape(x), tf.shape(y)])]):
return tf.identity(x, "identity_with_shape_equal_check")
def get_shape_dim(x, axis, name="shape_dim"):
"""
:param tf.Tensor x:
:param int axis: which axis
:param str name:
:return: x.shape[axis] either as a static int or otherwise as an expression
:rtype: int|tf.Tensor
"""
dyn_shape = x.get_shape()
if dyn_shape.ndims is not None:
if dyn_shape.dims[axis].value is not None:
return dyn_shape.dims[axis].value
# Need to fall-back to runtime.
with tf.name_scope(name):
return tf.shape(x)[axis]
def get_shape(x):
"""
:param tf.Tensor|tf.Variable x:
:return: list of scalars, which are either int if known statically, or otherwise expressions
:rtype: list[int|tf.Tensor]
"""
with tf.name_scope("get_shape"):
static_shape = x.get_shape()
dyn_shape = None if static_shape.is_fully_defined() else tf.shape(x)
assert static_shape.ndims is not None
return [static_shape.dims[i].value
if static_shape.dims[i].value is not None
else dyn_shape[i]
for i in range(static_shape.ndims)]
def get_ndim(x):
"""
:param tf.Tensor x:
:return: x.ndim either as a static int or otherwise as an expression
:rtype: int|tf.Tensor
"""
dyn_shape = x.get_shape()
if dyn_shape.ndims is not None:
return dyn_shape.ndims
# Need to fall-back to runtime.
return tf.rank(x)
def get_range(start, stop=NotSpecified):
"""
:param int|tf.Tensor|None start:
:param int|tf.Tensor|None stop:
:return: either tuple(range(start, stop)) or the same as a symbolic expression
:rtype: tuple[int]|tf.Tensor
"""
if stop is NotSpecified:
stop = start
start = 0
if isinstance(start, tf.Tensor) or isinstance(stop, tf.Tensor):
return tf.range(start, stop)
return tuple(range(start, stop))
def identity_with_ops(x, ops):
"""
:param tf.Tensor x:
:param () -> list[tf.Operation|tf.Tensor] ops:
:return: x with all ops executed
:rtype: tf.Tensor
"""
with tf.name_scope("identity_with_ops"):
with tf.control_dependencies(ops()):
return tf.identity(x, name="identity_with_ops")
_setup_tf_thread_pools_called_once = False
def setup_tf_thread_pools(num_threads=None, log_file=None, tf_session_opts=None):
"""
See here for documentation of intra_op_parallelism_threads and inter_op_parallelism_threads:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto
intra_op_parallelism_threads is used for the LocalDevice::EigenThreadPoolInfo, which is always global.
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/common_runtime/local_device.cc
inter_op_parallelism_threads is used for the (global if not use_per_session_threads) session thread pool.
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/common_runtime/direct_session.cc
TF will setup the thread pools on first usage. That can happen quite early, esp for intra_op_parallelism_threads.