forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TFUtil.py
4080 lines (3587 loc) · 142 KB
/
TFUtil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.client import device_lib
import contextlib
import os
import sys
from Util import NotSpecified
def tf_version_tuple():
"""
:return: version tuple, e.g. (1, 1, 0), parsed from tf.__version__
:rtype: tuple[int]
"""
import re
return tuple([int(s) for s in re.sub('-rc[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)
class Data(object):
"""
This class is to describe a tensor,
i.e. it's shape and properties like
whether we should consider it as sparse data (i.e. it represents indices).
This is used in TFNetwork to describe the dataset external data
as well as for every layer output.
"""
size_dtype = "int32"
def __init__(self, name,
shape=None, dtype=None,
placeholder=None,
sparse=None,
dim=None,
size_placeholder=None,
batch_dim_axis=0,
time_dim_axis=NotSpecified,
available_for_inference=True,
auto_create_placeholders=False,
beam_size=None):
"""
:param str name:
:param tuple[int|None]|list[int|None] shape: including time-dim (can be None). excluding batch-dim.
e.g. (time,feat)=(None,128)
:param str dtype: e.g. "float32" or "int64"
:param tf.Tensor|None placeholder: with added batch-dim
:param bool sparse: whether to treat the value as an index. do not confuse with tf.SparseTensor
:param None|int dim: feature dimension, shape[-1] if not sparse, otherwise like num_classes
:param int|None batch_dim_axis: where we add the batch-dim.
e.g. shape=(time,...), 0 -> (batch,time,...), 1 -> (time,batch,...).
This is normally always set, and a lot of code expects this. However, you can set it to None
if this Data does not have a batch-dim.
:param int|None time_dim_axis: where we have the time dim axis, after we added the batch-dim.
this is often 1. however, can be None if there is no time-dim.
:param dict[int,tf.Tensor] tf.Tensor size_placeholder: for every None in shape, this will describe the size.
The size is always a tensor of shape (batch,), i.e. the size can be different for each sequence in a batch.
:param bool available_for_inference: e.g. the extern data "classes" is usually not available for inference
:param int|None beam_size: the batch-dim could be extended by a beam-size,
such that it represents the merged dims [batch, beam_size].
"""
self.name = name
if sparse is None:
if dtype and (dtype.startswith("int") or dtype.startswith("uint")):
sparse = True
else:
sparse = False
self.sparse = sparse
if shape is None:
assert dim, "no shape specified, need dim"
if sparse:
shape = (None,) # assume common (time,)
else:
shape = (None, dim) # assume common (time,feat)
self.shape = tuple(shape) # type: tuple[int|None] # excluding batch-dim. see self.batch_shape
if dtype is None:
if sparse:
dtype = "int32"
else:
dtype = "float32"
if dim is None and len(shape):
assert not sparse, "need dim"
dim = shape[-1]
self.dim = dim # type: int
self.batch_dim_axis = batch_dim_axis # type: int|None # usually not None
if time_dim_axis is NotSpecified:
if batch_dim_axis is None:
time_dim_axis = None
elif (sparse and len(shape) >= 1) or ((not sparse) and len(shape) >= 2):
if batch_dim_axis >= 1:
time_dim_axis = 0
else:
time_dim_axis = 1
else:
time_dim_axis = None
self.time_dim_axis = time_dim_axis # type: int|None # counted with batch-dim
self.dtype = dtype # type: str
if placeholder is None and auto_create_placeholders:
with tf.name_scope("extern_data/placeholders/%s/" % name):
placeholder = tf.placeholder(**self.get_placeholder_kwargs(with_batch=True))
self.placeholder = placeholder # type: tf.Tensor # this will hold the data value itself
# The size_placeholder is for each variable length dimension in shape, i.e. excluding the batch-dim.
if size_placeholder is None and auto_create_placeholders:
size_placeholder = {} # type: dict[int,tf.Tensor]
with tf.name_scope("extern_data/placeholders/%s/" % name):
for axis in self.get_axes_with_size():
size_placeholder[axis] = tf.placeholder(**self.get_size_placeholder_kwargs(axis))
if not size_placeholder and self.ndim_dense <= 1:
size_placeholder = {}
self.size_placeholder = size_placeholder # type: dict[int,tf.Tensor] # axis w.o. batch -> size of shape (batch,)
self.available_for_inference = available_for_inference
self.beam_size = beam_size
def get_placeholder_kwargs(self, with_batch=True):
return dict(name=self.name, dtype=self.dtype, shape=self.batch_shape if with_batch else self.shape)
def get_axes_with_size(self):
"""
:return: list of axes which can vary in size for each entry of the batch-dim, e.g. the time-dim-axis.
The axis index is counted without the batch-dim.
:rtype: list[int]
"""
return [i for (i, dim) in enumerate(self.shape) if dim is None]
def get_size_placeholder_kwargs(self, axis, with_batch=True):
# For each batch a separate size.
return dict(name="%s_dim%i_size" % (self.name, axis), dtype=self.size_dtype,
shape=(None,) if with_batch else ())
def get_kwargs(self):
keys = ["name", "shape", "dtype", "sparse", "dim", "batch_dim_axis", "time_dim_axis"]
if not self.available_for_inference:
keys += ["available_for_inference"]
if self.beam_size is not None:
keys += ["beam_size"]
return {key: getattr(self, key) for key in keys}
def get_description(self, with_name=True, with_placeholder=False):
keys = ["shape", "dtype"]
if self.sparse:
keys.append("sparse")
keys.append("dim")
if self.batch_dim_axis != 0:
keys.append("batch_dim_axis")
if self.time_dim_axis is None or self.time_dim_axis >= 2:
keys.append("time_dim_axis")
if with_name:
keys.insert(0, "name")
if with_placeholder:
keys.append("placeholder")
if not self.available_for_inference:
keys.append("available_for_inference")
if self.beam_size is not None:
keys.append("beam_size")
return "Data(%s)" % ", ".join(["%s=%r" % (key, getattr(self, key)) for key in keys])
def __repr__(self):
return self.get_description()
def copy(self):
"""
:return: copy of myself, using self.get_kwargs(), and with placeholder and size_placeholder
:rtype: Data
"""
data = Data(**self.get_kwargs())
data.placeholder = self.placeholder
if self.size_placeholder is not None:
data.size_placeholder = self.size_placeholder.copy()
return data
def copy_as_batch_major(self):
"""
:return: copy of myself with batch_dim_axis == 0
:rtype: Data
"""
return self.copy_with_batch_dim_axis(0)
def copy_as_time_major(self):
"""
:return: copy of myself with time_dim_axis == 0
:rtype: Data
"""
assert self.batch_dim_axis is not None
assert self.time_dim_axis is not None
data = self.copy()
if data.time_dim_axis != 0:
if data.placeholder is not None:
with reuse_name_scope_of_tensor(data.placeholder):
data.placeholder = swapaxes(data.placeholder, 0, data.time_dim_axis)
if data.batch_dim_axis <= data.time_dim_axis:
data.batch_dim_axis += 1
data.time_dim_axis = 0
return data
def copy_with_batch_dim_axis(self, batch_dim_axis):
"""
:param int batch_dim_axis:
:return: copy of myself with specific batch_dim_axis
:rtype: Data
"""
assert self.batch_dim_axis is not None
data = self.copy()
if data.batch_dim_axis != batch_dim_axis:
if data.placeholder is not None:
data.placeholder = swapaxes(data.placeholder, batch_dim_axis, data.batch_dim_axis)
other_special_axes = data.get_special_axes_dict(counted_with_batch_dim=False, only_available=True)
data.batch_dim_axis = batch_dim_axis
for k, a in other_special_axes.items():
setattr(data, k, data.get_batch_axis(a))
return data
def copy_add_batch_dim(self, batch_dim_axis):
"""
:param int batch_dim_axis:
:return: copy of myself with added batch-dim
:rtype: Data
"""
assert self.batch_dim_axis is None
if not self.sparse:
assert batch_dim_axis <= self.feature_dim_axis, "does not work yet otherwise, feature-dim-axis must be last"
data = self.copy()
if data.placeholder is not None:
data.placeholder = tf.expand_dims(data.placeholder, batch_dim_axis, name="%s_add_batch_dim" % self.name)
data.batch_dim_axis = batch_dim_axis
other_special_axes = self.get_special_axes_dict(counted_with_batch_dim=True, only_available=True)
for k, a in other_special_axes.items():
setattr(data, k, a if (a < batch_dim_axis) else (a + 1))
return data
def copy_add_spatial_dim(self, spatial_dim_axis):
"""
:param int spatial_dim_axis: counted with batch-dim. if there is no time-dim, this will be it
:return: copy of myself with added spatial-dim
:rtype: Data
"""
data = self.copy()
if data.placeholder is not None:
data.placeholder = tf.expand_dims(data.placeholder, spatial_dim_axis, name="%s_add_spatial_dim" % self.name)
axis_wo_batch = spatial_dim_axis if (spatial_dim_axis <= (self.batch_dim_axis or 0)) else (spatial_dim_axis - 1)
data.shape = data.shape[:axis_wo_batch] + (1,) + data.shape[axis_wo_batch:]
if data.time_dim_axis is None:
data.time_dim_axis = spatial_dim_axis
other_special_axes = self.get_special_axes_dict(
counted_with_batch_dim=True, only_available=True, include_batch_dim_axis=True)
for k, a in other_special_axes.items():
setattr(data, k, a if (a < spatial_dim_axis) else (a + 1))
return data
def copy_compatible_to(self, data):
"""
:param Data data: other data which the returned tensor should be compatible to
:returns: Data, might add broadcast dimensions
:rtype: Data
"""
assert self.sparse == data.sparse
assert self.dtype == data.dtype
v = self.copy()
# First add spatial dims, in case we miss any.
for axis in data.get_spatial_batch_axes():
if len(data.get_spatial_batch_axes()) > len(v.get_spatial_batch_axes()):
axis_wo_batch = data.get_batch_axis_excluding_batch(axis)
v = v.copy_add_spatial_dim(v.get_batch_axis(axis_wo_batch))
assert data.get_spatial_axes() == v.get_spatial_axes()
if v.batch_dim_axis != data.batch_dim_axis:
if v.batch_dim_axis is not None:
v = v.copy_with_batch_dim_axis(data.batch_dim_axis)
else:
# Note that it might be important here that we added any missing spatial dims before.
v = v.copy_add_batch_dim(data.batch_dim_axis)
assert v.batch_dim_axis == data.batch_dim_axis
assert data.feature_dim_axis == v.feature_dim_axis
return v
def copy_time_flattened(self):
"""
:return: copy of myself where the time-axis is flattened away into the batch-dim-axis.
See :func:`get_placeholder_time_flattened` and :func:`flatten_with_seq_len_mask for more details.
:rtype: Data
"""
assert self.batch_dim_axis is not None
assert self.time_dim_axis is not None
data = self.copy()
if data.placeholder is not None:
data.placeholder = data.get_placeholder_time_flattened()
data.shape = tuple([
data.batch_shape[i] for i in range(data.batch_ndim)
if i not in (data.batch_dim_axis, data.time_dim_axis)])
if data.size_placeholder is not None:
if data.time_dim_axis_excluding_batch in data.size_placeholder:
del data.size_placeholder[data.time_dim_axis_excluding_batch]
data.time_dim_axis = None
return data
def copy_extend_with_beam(self, beam_size):
"""
:param int beam_size:
:return: copy of myself where the batch-dim is extended/multiplied by beam_size, using tile_transposed
:rtype: Data
"""
with tf.name_scope("data_extend_with_beam"):
data = self.copy()
if data.beam_size and data.beam_size == beam_size:
return data
assert data.beam_size is None, "incompatible beam sizes (%r vs %r)" % (data.beam_size, beam_size)
data.placeholder = tile_transposed(data.placeholder, axis=data.batch_dim_axis, multiples=beam_size)
data.size_placeholder = {
i: tile_transposed(v, axis=0, multiples=beam_size) for (i, v) in data.size_placeholder.items()}
data.beam_size = beam_size * (data.beam_size or 1)
return data
def copy_template(self, name=None):
"""
:return: copy of myself, using self.get_kwargs(), without placeholder
:rtype: Data
"""
kwargs = self.get_kwargs()
if name:
kwargs["name"] = name
return Data(**kwargs)
def copy_template_excluding_time_dim(self, name=None):
"""
:param str|None name: if set, this will be the new name
:return: copy of myself excluding the time-dimension without placeholder
:rtype: Data
"""
assert self.batch_dim_axis is not None
assert self.time_dim_axis is not None
new_shape = list(self.shape)
del new_shape[self.time_dim_axis_excluding_batch]
kwargs = self.get_kwargs()
kwargs["batch_dim_axis"] = (
self.batch_dim_axis
if (self.batch_dim_axis < self.time_dim_axis)
else (self.batch_dim_axis - 1))
kwargs["time_dim_axis"] = None
kwargs["shape"] = new_shape
if name:
kwargs["name"] = name
return Data(**kwargs)
def copy_template_adding_time_dim(self, name=None, time_dim_axis=0):
"""
:param str|None name: if set, this will be the new name
:param int time_dim_axis: the new time-dim-axis index
:return: copy of myself adding the time-dimension without placeholder
:rtype: Data
"""
assert self.batch_dim_axis is not None
assert self.time_dim_axis is None
new_shape = list(self.shape)
new_shape.insert(time_dim_axis, None)
kwargs = self.get_kwargs()
kwargs["batch_dim_axis"] = (
self.batch_dim_axis
if (self.batch_dim_axis < time_dim_axis)
else (self.batch_dim_axis + 1))
kwargs["time_dim_axis"] = time_dim_axis
kwargs["shape"] = new_shape
if name:
kwargs["name"] = name
return Data(**kwargs)
def _get_variable_dim_pattern(self):
"""
:return: tuple with bools specifying which dims of the shape (excluding batch-dim) are of variable length.
e.g. (time,feature), shape=(None,128), this returns (True, False)
:rtype: tuple[bool]
"""
return tuple([dim is None for dim in self.shape])
def _get_var_len_axes(self):
return sorted([i for (i, d) in enumerate(self._get_variable_dim_pattern()) if d])
def matches_var_dim_pattern(self, other):
"""
:param Data other:
:return: whether the variable-dims pattern matches,
i.e. same variable dims (get_variable_dim_pattern), same time dim, excluding batch-dim.
i.e. the size_placeholder should be compatible.
:rtype: bool
"""
if self.time_dim_axis_excluding_batch != other.time_dim_axis_excluding_batch:
return False
return self._get_var_len_axes() == other._get_var_len_axes()
@property
def batch_shape(self):
"""
:return: shape with added batch-dim. e.g. (batch,time,feat) = (None,None,128)
:rtype: tuple[int|None]
"""
if self.batch_dim_axis is not None:
return self.shape[:self.batch_dim_axis] + (None,) + self.shape[self.batch_dim_axis:]
return self.shape
@property
def shape_dense(self):
if self.sparse:
return self.shape + (self.dim,)
return self.shape
@property
def ndim(self):
"""
:rtype: int
:return: ndim counted without batch-dim
"""
return len(self.shape)
@property
def ndim_dense(self):
"""
:rtype: int
:return: ndim counted without batch-dim, added by 1 if we are sparse
"""
if self.sparse:
return self.ndim + 1
return self.ndim
@property
def batch_ndim(self):
"""
:rtype: int
:return: ndim counted with batch-dim
"""
if self.batch_dim_axis is not None:
return self.ndim + 1
return self.ndim
@property
def is_time_major(self):
"""
:return: whether this is in time-major format, i.e. (time,batch,...)
:rtype: bool
"""
return self.time_dim_axis == 0
@property
def is_batch_major(self):
"""
:return: whether this is in batch-major format, i.e. (batch,...)
:rtype: bool
"""
return self.batch_dim_axis == 0
@property
def time_dim_axis_excluding_batch(self):
if self.time_dim_axis is None:
return None
return self.get_batch_axis_excluding_batch(self.time_dim_axis)
def time_dimension(self):
"""
:return: shape(placeholder)[time_dim_axis], int scalar
:rtype: tf.Tensor
"""
assert self.time_dim_axis is not None
with reuse_name_scope_of_tensor(self.placeholder):
with tf.name_scope("time_dim"):
return tf.shape(self.placeholder)[self.time_dim_axis]
def get_placeholder_as_time_major(self):
if self.is_time_major:
assert self.batch_dim_axis == 1
return self.placeholder
assert self.batch_dim_axis == 0
assert self.time_dim_axis == 1
with reuse_name_scope_of_tensor(self.placeholder):
return swapaxes(self.placeholder, 0, 1) # (time,batch,dim)
def get_placeholder_as_batch_major(self):
if self.batch_dim_axis == 0:
return self.placeholder
return swapaxes(self.placeholder, 0, self.batch_dim_axis) # (time,batch,dim)
def get_placeholder_with_specific_batch_dim_axis(self, batch_dim_axis):
if self.batch_dim_axis == batch_dim_axis:
return self.placeholder
return swapaxes(self.placeholder, batch_dim_axis, self.batch_dim_axis)
def get_placeholder_time_flattened(self):
assert self.have_time_axis()
# flatten_with_seq_len_mask only works for these two cases at the moment:
assert (self.time_dim_axis, self.batch_dim_axis) == (0, 1) or (self.time_dim_axis, self.batch_dim_axis) == (1, 0)
seq_lens = self.size_placeholder[self.time_dim_axis_excluding_batch]
return flatten_with_seq_len_mask(self.placeholder, seq_lens, time_major=self.is_time_major)
def get_placeholder_flattened(self, keep_dims=False):
"""
:param bool keep_dims: if set, it will add broadcast dimensions after the flattening behind the first axis
:rtype: tf.Tensor
:return: placeholder where all dynamic axes are flattened into a single axis.
e.g. for the usual case (batch, time, dim), it becomes (batch'|time', dim),
or (batch, time, height, dim) will also become (batch'|time', dim).
with keep_dims, (batch, time, height, dim) will become (batch'|time', 1, 1, dim).
"""
x = self.placeholder
dyn_axes = self.get_spatial_batch_axes() + [self.batch_dim_axis]
if dyn_axes == [self.batch_dim_axis]:
return x
assert 0 in dyn_axes, "would need some transpose, not supported at the moment"
assert len(dyn_axes) > 1
orig_num_dyn_axes = len(dyn_axes)
ndim = len(self.batch_shape)
if self.have_time_axis():
x = self.get_placeholder_time_flattened()
removed_axis = max(self.time_dim_axis, self.batch_dim_axis)
dyn_axes.remove(removed_axis)
dyn_axes = [(i if (i < removed_axis) else (i - 1))
for i in dyn_axes]
ndim -= 1
if len(dyn_axes) > 1:
assert 0 in dyn_axes, "would need some transpose, not supported at the moment"
for i in dyn_axes:
if i > 0:
assert i - 1 in dyn_axes, "would need some transpose, not supported at the moment"
shape = tf.shape(x)
x = tf.reshape(
x,
[tf.reduce_prod([shape[i] for i in dyn_axes])] +
[shape[i] for i in range(ndim) if i not in dyn_axes])
dyn_axes = [0]
assert dyn_axes == [0]
if keep_dims and orig_num_dyn_axes >= 2:
for i in range(orig_num_dyn_axes - 1):
x = tf.expand_dims(x, axis=1)
return x
@property
def feature_dim_axis(self):
if self.sparse:
return None
return self.batch_ndim - 1
@feature_dim_axis.setter
def feature_dim_axis(self, value):
assert value == self.feature_dim_axis, "feature_dim_axis cannot be set at the moment"
def get_axes(self, exclude_time=False, exclude_batch=False):
"""
:param bool exclude_time: will filter out the time-axis
:param bool exclude_batch: will filter out the batch-axis
:return: list of axes, like `range(len(self.shape))`, calculated with batch dim.
:rtype: list[int]
"""
axes = list(range(len(self.batch_shape)))
if exclude_time and self.time_dim_axis is not None:
axes.pop(axes.index(self.time_dim_axis))
if exclude_batch and self.batch_dim_axis is not None:
axes.pop(axes.index(self.batch_dim_axis))
return axes
def get_axes_from_description(self, axes):
"""
:param int|list[int]|str|list[str] axes: one axis or multiple axis.
This is counted with batch-dim, which by default is axis 0 (see enforce_batch_dim_axis).
It also accepts the special tokens "B"|"batch", "spatial", "spatial_except_time", or "F"|"feature",
and more (see the code).
:return: list of axes, counted with batch-dim
:rtype: list[int]
"""
if isinstance(axes, str):
import re
axes = axes.lower()
if axes in ["b", "batch"]:
assert self.batch_dim_axis is not None
axes = self.batch_dim_axis
elif axes == "spatial":
axes = self.get_spatial_batch_axes()
elif re.match("(s|spatial):-?\\d+$", axes):
s = int(axes.split(":")[1])
axes = self.get_spatial_batch_axes()
assert s < len(axes)
axes = axes[s]
elif axes == "spatial_except_time":
axes = self.get_spatial_batch_axes()
assert self.time_dim_axis is not None
axes.remove(self.time_dim_axis)
elif axes in ["t", "time"]:
assert self.time_dim_axis is not None
axes = self.time_dim_axis
elif axes == "except_time":
axes = list(range(self.batch_ndim))
axes.remove(self.batch_dim_axis)
assert self.time_dim_axis is not None
axes.remove(self.time_dim_axis)
elif axes in ["f", "feature", "non_spatial"]:
axes = self.get_feature_batch_axes()
elif all([a in "btf" for a in axes]):
return self.get_axes_from_description(list(axes))
else:
raise Exception("invalid axis mode %r" % axes)
if isinstance(axes, int):
axes = [axes]
assert isinstance(axes, (tuple, list)), "invalid axis %r" % axes
flat_axes = []
for i in axes:
if isinstance(i, int):
flat_axes += [i]
else:
assert isinstance(i, (str, tuple, list))
flat_axes += self.get_axes_from_description(i)
flat_axes = [i % self.batch_ndim for i in flat_axes]
res = []
for i in flat_axes:
if i not in res:
res.append(i)
return res
def get_axis_from_description(self, axis):
"""
:param int|str axis:
:return: axis, counted with batch-dim
:rtype: int
"""
axes = self.get_axes_from_description(axis)
assert len(axes) == 1, "%r is not a unique axis but %r" % (axis, axes)
return axes[0]
def get_batch_axis_excluding_batch(self, axis):
"""
:param int axis: counted with batch-dim
:return: axis counted without batch-dim
:rtype: int
"""
if self.batch_dim_axis is None:
return axis
if axis == self.batch_dim_axis:
return None
if axis < self.batch_dim_axis:
return axis
return axis - 1
def get_batch_axis(self, axis):
"""
:param int axis: counted without batch-dim
:return: axis counted with batch-dim
:rtype: int
"""
if self.batch_dim_axis is None:
return axis
if axis >= self.batch_dim_axis:
return axis + 1
return axis
def have_batch_axis(self):
return self.batch_dim_axis is not None
def have_time_axis(self):
return self.time_dim_axis is not None
def get_sequence_lengths(self):
"""
:return: seq lens tensor of shape (batch,) of dtype int32
:rtype: tf.Tensor
"""
assert self.time_dim_axis is not None
return self.size_placeholder[self.time_dim_axis_excluding_batch]
def get_sequence_mask(self):
"""
:return: seq mask of shape (batch,time) if we are batch-major, else (time,batch) if we are time-major
:rtype: tf.Tensor
"""
assert self.time_dim_axis is not None
assert self.batch_dim_axis is not None
if self.is_time_major:
assert self.batch_dim_axis == 1
return sequence_mask_time_major(self.get_sequence_lengths())
else:
assert self.batch_dim_axis == 0
assert self.time_dim_axis == 1
return sequence_mask(self.get_sequence_lengths())
def get_sequence_mask_broadcast(self):
"""
:return: seq mask of shape ((batch,time) or (time,batch)) + (1,)s for remaining dims
:rtype: tf.Tensor
"""
seq_mask = self.get_sequence_mask()
assert seq_mask.get_shape().ndims == 2 # batch and time
seq_mask = expand_multiple_dims(
seq_mask, [i for i in range(self.batch_ndim) if i not in (self.batch_dim_axis, self.time_dim_axis)])
assert seq_mask.get_shape().ndims == self.batch_ndim
return seq_mask
def get_spatial_batch_axes(self):
"""
:rtype: list[int]
:return: list of axes which are not feature and batch axes, counted with batch-dim.
"""
return [axis
for axis in range(self.batch_ndim)
if (axis not in [self.batch_dim_axis, self.feature_dim_axis])]
def get_spatial_axes(self):
"""
:rtype: list[int]
:return: list of axes which are not feature and batch axes, counted without batch-dim.
"""
return [self.get_batch_axis_excluding_batch(axis) for axis in self.get_spatial_batch_axes()]
def get_feature_batch_axes(self):
"""
:rtype: list[int]
:return: list of axes which are feature axes, counted with batch-dim. currently there is only one or zero such axis.
"""
if self.feature_dim_axis is not None:
return [self.feature_dim_axis]
return []
def get_feature_axes(self):
"""
:rtype: list[int]
:return: list of axes which are feature axes, counted without batch-dim.
"""
return [self.get_batch_axis_excluding_batch(axis) for axis in self.get_feature_batch_axes()]
SpecialAxesNames = ("batch_dim_axis", "time_dim_axis", "feature_dim_axis")
def get_special_axes_dict(self, counted_with_batch_dim=True, include_batch_dim_axis=False, only_available=False):
"""
:param bool counted_with_batch_dim:
:param bool include_batch_dim_axis:
:param bool only_available:
:return: dict axis-name -> axis
:rtype: dict[str,int]
"""
axes = list(self.SpecialAxesNames)
if include_batch_dim_axis:
assert counted_with_batch_dim
else:
axes.remove("batch_dim_axis")
d = {k: getattr(self, k) for k in axes}
if not counted_with_batch_dim:
d = {k: self.get_batch_axis_excluding_batch(v) if (v is not None) else None
for (k, v) in d.items()}
if only_available:
d = {k: v for (k, v) in d.items() if v is not None}
return d
def get_bc_spatial_batch_shape(self):
"""
:return: shape which will broadcast along all spatial dimensions and time/batch dim
:rtype: tuple[int]
"""
dyn_axes = self.get_spatial_batch_axes()
if self.batch_dim_axis is not None:
dyn_axes += [self.batch_dim_axis]
return [1 if (axis in dyn_axes) else dim
for axis, dim in enumerate(self.batch_shape)]
class CustomUpdate(object):
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, "custom_update", self)
def update_var(self, var):
"""
:param tf.Variable var: variable to update
:return: operation which updates the variable, e.g. tf.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):
return tf.assign_add(var, self.alpha * (self.average - var)) # ((alpha - 1) * old + alpha * new)
class OutputWithActivation(object):
def __init__(self, x, act_func=None):
"""
:param tf.Tensor x:
:param None|(tf.Tensor)->tf.Tensor act_func:
"""
self.x = x
self.act_func = act_func
if act_func:
with tf.name_scope("activation"):
self.y = act_func(x)
else:
self.y = x
def is_softmax_act_func(self):
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
return tf.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)
mean = tf.reduce_mean(x)
stddev = tf.sqrt(tf.reduce_mean(tf.square(x - mean)))
return {
'%s_mean' % name: mean,
'%s_stddev' % name: stddev,
'%s_rms' % name: tf.sqrt(tf.reduce_mean(tf.square(x))),
'%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.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.summary.scalar(k, v)
if with_histogram:
tf.summary.histogram('%s_histogram' % name, var)
def get_current_var_scope_name():
"""
:return: current absolute variable scope name, via tf.variable_scope
:rtype: str
"""
v = tf.get_variable_scope()
return v.name
def get_current_name_scope():
"""
:return: current absolute name scope, via tf.name_scope
:rtype: str
http://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().
"""
return tf.get_default_graph()._name_stack or ""
@contextlib.contextmanager
def reuse_name_scope(name, absolute=None, reuse_vars=None):
"""
Context manager to reuse an already created scope.
We try to both set the variable scope and the name scope.
:param str|tf.VariableScope name: relative or absolute name scope (absolute if absolute=True or if tf.VariableScope).
must not end with "/".
:param bool absolute: if True it will be absolute
:param bool reuse_vars: passed on as `reuse` arg for `tf.variable_scope`
:return: yields the variable_scope
"""
if isinstance(name, tf.VariableScope):
name = name.name
if absolute is not None:
assert absolute is True
absolute = True
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.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:] != "/"
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.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.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.get_variable() will search for existing variables and errors otherwise.
var_scope = tf.VariableScope(reuse=reuse_vars, name=abs_name)
with tf.variable_scope(var_scope) as scope:
assert isinstance(scope, tf.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.
assert scope.name is scope._name
assert scope.name[-1:] == "/" or scope.name == ""
scope._name = scope._name[:-1]
assert name == scope.name, "%r" % current_name_scope
yield 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 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=""):
"""
:param tf.Tensor x: has name e.g. "layer0/rec/W:0"
:param str prefix:
:param str postfix:
:return: reuse the name scope of x, e.g. "layer0/rec", yields scope
"""
with reuse_name_scope(prefix + get_name_scope_of_tensor(x) + postfix, absolute=True) as scope:
yield scope
@contextlib.contextmanager
def 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 ''.
Also see tests/test_TFUtil.py:test_loop_var_creation().
Related TF bugs:
https://github.com/tensorflow/tensorflow/issues/3114
https://github.com/tensorflow/tensorflow/issues/4478
https://github.com/tensorflow/tensorflow/issues/8604
The solution is to reset the current frame.
Resetting all control dependencies has this effect.
"""
with tf.control_dependencies(None) as dep:
yield dep
class FlipGradientBuilder(object):