forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFUtil.py
8159 lines (7233 loc) · 289 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
"""
Lots of random utility functions for TensorFlow.
Also provides :class:`Data`.
"""
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 Util import NotSpecified, NativeCodeCompiler
class CollectionKeys:
"""
Extension of :class:`tf.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.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 DimensionTag(object):
"""
This identifies one axis/dimension, like a time-dimension, etc.
This can be used by :class:`Data`. See :func:`Data.get_dim_tag`.
It is not to specify the specific axis in a specific Data/tensor,
but to specify the content and dimension.
I.e. if we have the same DimensionTag for two Data instances,
the dimensions should match. I.e.:
data1.get_dim_tag(i) == data2.get_dim_tag(j)
=> tf.shape(data1.placeholder)[i] == tf.shape(data2.placeholder)[j]
"""
class Types:
"""
Defines possible values for ``kind``.
"""
Unspecified = None
Batch = "batch"
Spatial = "spatial" # also time
Time = "spatial" # we don't treat this as different
Feature = "feature"
def __init__(self, kind=Types.Unspecified, description=None, dimension=None, dyn_size=None):
"""
:param str|None kind:
:param str|None description:
:param int|None dimension:
:param tf.Tensor|None dyn_size: e.g. seq_len, (batch,)
"""
self.id = id(self) # This is just used for __repr__ to distinguish different instances.
self.kind = kind
self.description = description
self.dimension = dimension
self.dyn_size = dyn_size
self.same_as = None # type: typing.Optional[DimensionTag]
def __repr__(self):
attribs = ["kind"]
for attr in ["description", "dimension"]:
if getattr(self, attr) is not None:
attribs.append(attr)
attribs.append("id")
if self.same_as:
attribs.append("same_base_id")
return "DimensionTag(%s)" % ", ".join(["%s=%r" % (attr, getattr(self, attr)) for attr in attribs])
def set_tag_on_size_tensor(self, x):
"""
:param tf.Tensor x:
"""
assert self.dimension is None
if hasattr(x, "_is_size_of_dim_tag"):
# noinspection PyProtectedMember
assert x._is_size_of_dim_tag in (None, self)
if getattr(x, "_is_size_of_dim_tag", None) is None:
setattr(x, "_is_size_of_dim_tag", self)
if self.dyn_size is None:
self.dyn_size = x
@classmethod
def get_tag_from_size_tensor(cls, x):
"""
:param tf.Tensor x:
:rtype: DimensionTag|None
"""
return getattr(x, "_is_size_of_dim_tag", None)
def is_equal(self, other, allow_same_feature_dim=False):
"""
:param DimensionTag other:
:param bool allow_same_feature_dim:
:rtype: bool
"""
self_base = self.get_same_base()
other_base = other.get_same_base()
if self_base is other_base:
return True
if self.dimension != other.dimension:
return False
if self.kind != other.kind:
return False
if self.kind == other.kind == self.Types.Batch:
# Note: This might be incorrect in some cases,
# e.g. for beam search when we have the beam hidden in the batch dim,
# or when we used MergeDimsLayer on the batch axis, or so.
# We might need to extend the logic here later.
return True
if self.kind == other.kind == self.Types.Feature:
if allow_same_feature_dim:
return True
if self.kind == other.kind == self.Types.Spatial:
if self.dimension is not None and allow_same_feature_dim:
return True
if self.description == other.description:
return True
return False
def __eq__(self, other):
"""
:param DimensionTag other:
:rtype: bool
"""
return self.is_equal(other)
def __ne__(self, other):
"""
:param DimensionTag other:
:rtype: bool
"""
return not (self == other)
def get_same_base(self):
"""
:rtype: DimensionTag
"""
if self.same_as:
return self.same_as.get_same_base()
return self
@property
def same_base_id(self):
"""
:rtype: int
"""
return self.get_same_base().id
def declare_same_as(self, other):
"""
:param DimensionTag other:
"""
assert not self.same_as
self.same_as = other.get_same_base()
@classmethod
def get_all_dimension_tags(cls, data_list, allow_same_feature_dim):
"""
:param list[Data] data_list:
:param bool allow_same_feature_dim:
:return: list of dimension tags, dict for data -> list of dimension tags (for each axis)
:rtype: (list[DimensionTag], dict[Data, list[DimensionTag]])
"""
tags = []
def get_existing_tag(other):
"""
:param DimensionTag other:
:rtype: DimensionTag|None
"""
for _tag in tags:
if _tag.is_equal(other, allow_same_feature_dim=allow_same_feature_dim):
return _tag
return None
data_axes_dict = {}
for data in data_list:
data_axes_dict[data] = []
for axis in range(data.batch_ndim):
tag = data.get_dim_tag(axis)
existing_tag = get_existing_tag(tag)
if not existing_tag:
tags.append(tag)
data_axes_dict[data].append(existing_tag or tag)
return tags, data_axes_dict
class Data(object):
"""
This class is to describe a tensor,
i.e. its shape and properties like
whether we should consider it sparse data (i.e. it represents indices).
This is used in TFNetwork to describe the dataset external data
as well as in every layer's output.
"""
size_dtype = "int32"
def __init__(self, name,
shape=None, dtype=None,
placeholder=None,
sparse=None,
dim=NotSpecified,
size_placeholder=None,
batch_dim_axis=0,
time_dim_axis=NotSpecified,
feature_dim_axis=NotSpecified,
available_for_inference=True,
auto_create_placeholders=False,
vocab=None,
same_dim_tags_as=None,
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 int|None|NotSpecified feature_dim_axis: feature dim axis. by default it's the last one
: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 str|dict[str]|GeneratingDataset.Vocabulary|None vocab:
:param dict[int|str,DimensionTag]|None same_dim_tags_as: will mark our dimension tags to be the same
: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].
"""
assert isinstance(name, str)
assert dtype is None or isinstance(dtype, str)
self.name = name
if sparse is None:
sparse = False
self.sparse = sparse
if dtype is None:
if sparse:
dtype = "int32"
else:
dtype = "float32"
self.dtype = dtype # type: str
assert batch_dim_axis is None or isinstance(batch_dim_axis, int)
self.batch_dim_axis = batch_dim_axis # type: typing.Optional[int] # None -> no batch dim axis
if shape is None:
if time_dim_axis is NotSpecified: # need to determine this now
if self.batch_dim_axis is None:
time_dim_axis = None
else:
# By default if not specified, we have a time dim.
taken_axes = {self.batch_dim_axis}
if isinstance(feature_dim_axis, int):
taken_axes.add(feature_dim_axis)
time_dim_axis = [i for i in range(max(taken_axes) + 2) if i not in taken_axes][0]
if time_dim_axis is not None:
assert time_dim_axis != self.batch_dim_axis
shape = (None,) * (self.get_batch_axis_excluding_batch(time_dim_axis) + 1)
else: # no time-dim-axis
shape = ()
if not sparse and feature_dim_axis is not None:
assert dim is not NotSpecified, "no shape specified, not sparse, feature_dim_axis existing -> need dim"
if feature_dim_axis is NotSpecified or feature_dim_axis == -1:
shape = shape + (dim,)
else:
assert 0 <= feature_dim_axis != self.batch_dim_axis
feature_dim_axis_wo_batch = self.get_batch_axis_excluding_batch(feature_dim_axis)
if feature_dim_axis_wo_batch < len(shape):
shape = shape[:-feature_dim_axis_wo_batch] + (dim,) + shape[feature_dim_axis_wo_batch + 1:]
else:
shape = shape + (None,) * (feature_dim_axis_wo_batch - len(shape)) + (dim,)
assert len(shape) == feature_dim_axis_wo_batch + 1
self.shape = tuple(shape) # type: typing.Tuple[typing.Optional[int], ...] # excl. batch-dim. see self.batch_shape
if feature_dim_axis is not NotSpecified:
if isinstance(feature_dim_axis, int):
assert not self.sparse, "cannot have feature_dim_axis when sparse"
if feature_dim_axis < 0:
feature_dim_axis += self.batch_ndim
assert 0 <= feature_dim_axis < self.batch_ndim
self._feature_dim_axis = feature_dim_axis
if time_dim_axis is NotSpecified:
if self.batch_dim_axis is None:
time_dim_axis = None
else:
# Do not select the batch dim axis, or any axis with None dim.
# Note that we currently allow to select the same as the feature dim axis,
# in case the feature dim is None.
taken_axes = {self.batch_dim_axis}
for axis, _dim in enumerate(self.batch_shape):
if _dim is not None:
taken_axes.add(axis)
available_axes = [i for i in range(self.batch_ndim) if i not in taken_axes]
if available_axes:
time_dim_axis = available_axes[0]
else:
time_dim_axis = None
if time_dim_axis is not None:
assert 0 <= time_dim_axis < self.batch_ndim
self.time_dim_axis = time_dim_axis # type: typing.Optional[int] # counted with batch-dim
if dim is NotSpecified:
assert not sparse, "need dim (num classes) if sparse"
if self.feature_dim_axis is None:
dim = None
else:
dim = self.batch_shape[self.feature_dim_axis]
self.dim = dim # type: typing.Optional[int]
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: typing.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))
tag = DimensionTag(
description="spatial:%i:extern_data/placeholders/%s" % (axis, self.name), kind=DimensionTag.Types.Spatial)
tag.set_tag_on_size_tensor(size_placeholder[axis])
if not size_placeholder and (self.ndim_dense <= 1 or all([d is not None for d in shape])):
size_placeholder = {}
self.size_placeholder = size_placeholder # type: typing.Dict[int,tf.Tensor] # axis w.o. batch -> size (batch,)
self.available_for_inference = available_for_inference
self.beam_size = beam_size
if vocab is not None:
from GeneratingDataset import Vocabulary
if isinstance(vocab, str):
vocab = Vocabulary(vocab)
elif isinstance(vocab, dict):
vocab = Vocabulary.create_vocab(**vocab)
assert isinstance(vocab, Vocabulary)
assert self.sparse, "%s should represent indices of %s" % (self, vocab)
assert self.dim == vocab.num_labels, "%s dims do not match with vocab %s" % (self, vocab)
self.vocab = vocab
if same_dim_tags_as:
# Note that this currently does not work as intended at template construction time...
for _axis, _dim_tag in sorted(same_dim_tags_as.items()):
_axis = self.get_axis_from_description(_axis)
self.get_dim_tag(_axis).declare_same_as(_dim_tag)
self.sanity_check()
@classmethod
def from_tensor(cls, x):
"""
:param tf.Tensor x:
:rtype: Data
"""
assert x.get_shape().ndims == 0, "currently only scalars supported"
return Data(name=str(x.op.name), shape=(), batch_dim_axis=None, dtype=x.dtype.name, placeholder=x)
def sanity_check(self, ignore_placeholder=False):
"""
Performs some sanity checks on self, and raises exceptions if something is not sane.
:param bool ignore_placeholder:
"""
for axis_name, axis in self.get_special_axes_dict(include_batch_dim_axis=True).items():
assert axis is None or 0 <= axis < self.batch_ndim, "%s: axis %s (%i) invalid" % (self, axis_name, axis)
if self.batch_dim_axis is not None:
for axis_name, axis in self.get_special_axes_dict(include_batch_dim_axis=False).items():
assert axis != self.batch_dim_axis, "%s: axis %s (%i) must be different from batch_dim_axis (%i)" % (
self, axis_name, axis, self.batch_dim_axis)
if self.sparse:
assert self.feature_dim_axis is None, "%s: If sparse, there cannot be a feature dim axis." % self
if self.feature_dim_axis is not None:
assert self.dim == self.batch_shape[self.feature_dim_axis], (
"%s: inconsistent dim. feature axis or unspecified: %r." % (self, self.feature_dim_axis_or_unspecified))
if not ignore_placeholder and self.placeholder is not None:
self.placeholder.set_shape(self.batch_shape)
def get_placeholder_kwargs(self, with_batch=True):
"""
:param bool with_batch:
:return: kwargs for tf.placeholder
:rtype: dict[str]
"""
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):
"""
:param int axis:
:param bool with_batch:
:return: kwargs for tf.placeholder
:rtype: dict[str]
"""
# 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):
"""
:return: relevant attrib items for copying
:rtype: dict[str]
"""
keys = ["name", "shape", "dtype", "sparse", "dim", "batch_dim_axis", "time_dim_axis"]
if self._feature_dim_axis is not NotSpecified:
keys += ["feature_dim_axis"]
if not self.available_for_inference:
keys += ["available_for_inference"]
if self.beam_size is not None:
keys += ["beam_size"]
if self.vocab:
keys += ["vocab"]
return {key: getattr(self, key) for key in keys}
def get_description(self, with_name=True, with_placeholder=False):
"""
:param bool with_name:
:param bool with_placeholder:
:return: description of self. also used for __repr__
:rtype: str
"""
keys = ["shape"]
if self.sparse:
keys.append("dtype")
keys.append("sparse")
keys.append("dim")
else:
if self.dtype != "float32":
keys.append("dtype")
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 self._feature_dim_axis is not NotSpecified:
keys.append("feature_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 __hash__(self):
return id(self)
def copy(self, name=None):
"""
:param str name: if given, will overwrite this name
: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()
if name:
data.name = name
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.time_dim_axis is not None
return self.copy_with_time_dim_axis(0)
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
return self.copy_move_axis(self.batch_dim_axis, batch_dim_axis)
def copy_with_time_dim_axis(self, time_dim_axis):
"""
:param int time_dim_axis:
:return: copy of myself with specific time_dim_axis
:rtype: Data
"""
assert self.time_dim_axis is not None
return self.copy_move_axis(self.time_dim_axis, time_dim_axis)
def copy_move_axis(self, old_axis, new_axis):
"""
:param int old_axis: counted with batch-dim
:param int new_axis: counted with batch-dim
:return: copy of myself with moved axis (see :func:`move_axis`)
:rtype: Data
"""
if old_axis < 0:
old_axis += self.batch_ndim
assert old_axis >= 0
assert 0 <= old_axis < self.batch_ndim
if new_axis < 0:
new_axis += self.batch_ndim
assert new_axis >= 0
assert 0 <= new_axis < self.batch_ndim
if old_axis == new_axis:
return self.copy()
def translate_axis(axis):
"""
:param int|None axis:
:return: axis after move_axis
:rtype: int|None
"""
if axis is None:
return None
if old_axis == new_axis:
return axis
if axis < min(old_axis, new_axis) or axis > max(old_axis, new_axis):
return axis
if axis == old_axis:
return new_axis
if old_axis < new_axis:
assert old_axis < axis <= new_axis
return axis - 1
assert new_axis <= axis < old_axis
return axis + 1
data = self.copy()
if data.placeholder is not None:
data.placeholder = move_axis(data.placeholder, old_axis, new_axis)
data.batch_dim_axis = translate_axis(self.batch_dim_axis)
new_feature_dim_axis = translate_axis(self.feature_dim_axis)
if new_feature_dim_axis != data.feature_dim_axis:
# Only assign in this case. Otherwise, e.g. if it is NotSpecified, leave it like that.
data.feature_dim_axis = new_feature_dim_axis
data.time_dim_axis = translate_axis(self.time_dim_axis)
if data.size_placeholder:
data.size_placeholder = {
data.get_batch_axis_excluding_batch(translate_axis(self.get_batch_axis(i))): size
for (i, size) in data.size_placeholder.items()}
assert None not in data.size_placeholder
new_shape = [None] * data.ndim
for i, dim in enumerate(self.shape):
new_shape[data.get_batch_axis_excluding_batch(translate_axis(self.get_batch_axis(i)))] = dim
data.shape = tuple(new_shape)
data.sanity_check()
return data
def copy_as_bt_or_tb_major(self):
"""
:rtype: Data
:return: copy of myself in batch-time-major or time-batch-major
"""
assert self.have_batch_axis() and self.have_time_axis()
if self.batch_dim_axis == 0:
return self.copy_with_time_dim_axis(1)
if self.time_dim_axis == 0:
return self.copy_with_batch_dim_axis(1)
if self.batch_dim_axis > self.time_dim_axis:
return self.copy_as_time_major().copy_as_bt_or_tb_major()
return self.copy_as_batch_major().copy_as_bt_or_tb_major()
def copy_with_feature_dim_axis(self, feature_dim_axis):
"""
:param int feature_dim_axis: can also be negative
:return: copy of myself with specific feature dim axis
:rtype: Data
"""
assert self.feature_dim_axis is not None
return self.copy_move_axis(self.feature_dim_axis, feature_dim_axis)
def copy_as_batch_feature_major(self):
"""
:return: copy of self with batch_dim_axis == 0 and feature_dim_axis == 1
:rtype: Data
"""
assert self.batch_dim_axis is not None
assert self.feature_dim_axis is not None
data = self.copy_as_batch_major()
data = data.copy_with_feature_dim_axis(1)
return data
def copy_as_batch_spatial_major(self):
"""
:return: copy with batch_dim_axis == 0, then all dynamic axes, then any other spatial axes, last feature axis
:rtype: Data
"""
data = self.copy_as_batch_major()
if data.feature_dim_axis is not None:
data = data.copy_with_feature_last()
if data.size_placeholder:
for i, (j, size) in enumerate(sorted(data.size_placeholder.items())):
data = data.copy_move_axis(data.get_batch_axis(j), i + 1)
if data.feature_dim_axis is not None:
assert data.feature_dim_axis == data.batch_ndim - 1
# Maybe reset feature_dim_axis to unspecified.
if data.feature_dim_axis_or_unspecified is not NotSpecified:
if data._default_feature_dim_axis() == data.feature_dim_axis:
data.feature_dim_axis = NotSpecified
return data
def copy_with_feature_last(self):
"""
:return: copy of self with feature_dim_axis being the very last axis
:rtype: Data
"""
assert self.feature_dim_axis is not None
return self.copy_with_feature_dim_axis(-1)
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 self.feature_dim_axis is not None:
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))
data.sanity_check()
return data
def copy_add_spatial_dim(self, spatial_dim_axis=None, dim=1):
"""
:param int|None spatial_dim_axis: counted with batch-dim. if there is no time-dim, this will be it.
:param int|None dim:
:return: copy of myself with added spatial-dim
:rtype: Data
"""
data = self.copy()
if spatial_dim_axis is None:
if self.time_dim_axis is not None:
spatial_dim_axis = self.time_dim_axis + 1 # after the existing spatial dim
elif self.feature_dim_axis is not None:
spatial_dim_axis = self.feature_dim_axis # add it before the feature dim
else:
spatial_dim_axis = self.batch_ndim # add it at the end
if data.placeholder is not None:
assert dim == 1
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] + (dim,) + 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))
if data.feature_dim_axis is not None:
# feature dim axis might have changed if unspecified, so just update dim
data.dim = data.batch_shape[data.feature_dim_axis]
data.sanity_check()
return data
def copy_add_feature_dim(self):
"""
:return: self with a new feature dim axis with dim 1.
If there is an existing feature dim, the new feature dim will be added right after.
:rtype: Data
"""
v = self.copy()
assert not v.sparse
if v.feature_dim_axis is not None:
new_feature_dim_axis = v.feature_dim_axis + 1
else:
new_feature_dim_axis = v.batch_ndim
other_special_axes = self.get_special_axes_dict(
counted_with_batch_dim=True, only_available=True, include_batch_dim_axis=True)
other_special_axes.pop("feature_dim_axis", None)
new_feature_dim_axis_wo_batch = self.get_batch_axis_excluding_batch(new_feature_dim_axis)
v.shape = v.shape[:new_feature_dim_axis_wo_batch] + (1,) + v.shape[new_feature_dim_axis_wo_batch:]
v.dim = 1
for k, a in other_special_axes.items():
setattr(v, k, a if (a < new_feature_dim_axis) else (a + 1))
v.feature_dim_axis = new_feature_dim_axis
if v.placeholder is not None:
v.placeholder = tf.expand_dims(v.placeholder, new_feature_dim_axis, name="copy_add_feature_dim")
v.sanity_check()
return v
def copy_split_feature_dim(self, new_feature_dim):
"""
:param int new_feature_dim: will be the new dim
:rtype: Data
"""
assert not self.sparse
assert self.feature_dim_axis is not None
assert self.dim is not None
assert self.dim % new_feature_dim == 0, "must be a multiple of the input feature dim"
old_feature_dim = self.dim // new_feature_dim
new_feature_dim_axis = self.feature_dim_axis + 1
v = self.copy()
other_special_axes = self.get_special_axes_dict(
counted_with_batch_dim=True, only_available=True, include_batch_dim_axis=True)
other_special_axes.pop("feature_dim_axis", None)
old_feature_dim_axis_wo_batch = self.get_batch_axis_excluding_batch(self.feature_dim_axis)
v.shape = (v.shape[:old_feature_dim_axis_wo_batch] +
(old_feature_dim, new_feature_dim) +
v.shape[old_feature_dim_axis_wo_batch + 1:])
v.dim = new_feature_dim
for k, a in other_special_axes.items():
setattr(v, k, a if (a < new_feature_dim_axis) else (a + 1))
v.feature_dim_axis = new_feature_dim_axis
if v.placeholder is not None:
v.placeholder.set_shape(self.batch_shape)
old_shape = get_shape(v.placeholder)
new_shape = (old_shape[:self.feature_dim_axis] +
[old_feature_dim, new_feature_dim] +
old_shape[new_feature_dim_axis + 1:])
v.placeholder = tf.reshape(v.placeholder, new_shape, name="copy_split_feature_dim")
v.sanity_check()
return v
def copy_compatible_to(self, data, unbroadcast=False, data_dyn_shape=None, check_sparse=True, check_dtype=True):
"""
:param Data data: other data which the returned tensor should be compatible to
It would add any missing axes with a dim 1 axis for automatic broadcasting.
It currently does not check whether existing dims match.
:param bool unbroadcast: if True, all broadcast axes (axes with dim 1) will be tiled such that they match
:param tf.Tensor|list[tf.Tensor|int]|tuple[tf.Tensor|int]|None data_dyn_shape:
For unbroadcast, if we do not want to rely on tf.shape(data.placeholder).
:param bool check_sparse:
:param bool check_dtype:
:returns: Data, might add broadcast dimensions
:rtype: Data
"""
assert not check_sparse or self.sparse == data.sparse
assert not check_dtype or self.dtype == data.dtype
_, dim_tags = DimensionTag.get_all_dimension_tags([self, data], allow_same_feature_dim=True)
v = self.copy()
v.sparse = data.sparse # we will later reset it. this is to better count the axes (feature and spatial)
if data.batch_dim_axis is not None and v.batch_dim_axis is None:
v = v.copy_add_batch_dim(0) # later we might move the axis
# Add feature dim, if needed.
if data.feature_dim_axis_or_unspecified is NotSpecified:
v.feature_dim_axis = NotSpecified
if data.feature_dim_axis is not None and v.feature_dim_axis is None:
v = v.copy_add_feature_dim()
# 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()):
if dim_tags[data][axis] in dim_tags[self]:
continue # This one seems to exist already, add the next one.
axis_wo_batch = data.get_batch_axis_excluding_batch(axis)
v = v.copy_add_spatial_dim(v.get_batch_axis(axis_wo_batch))
# Now we assume that we have all missing axes added,
# but they might still be in a wrong order.
assert len(data.get_spatial_batch_axes()) == len(v.get_spatial_batch_axes())
assert v.batch_ndim == data.batch_ndim
# Now maybe move batch/feature axis.
# We might do multiple iterations here, depending on which axis comes first.
# This is a bit ugly, but the code is simpler.
num_iterations = 0
while True:
num_iterations += 1
assert num_iterations <= 4
if v.batch_dim_axis != data.batch_dim_axis:
assert data.batch_dim_axis is not None and v.batch_dim_axis is not None
v = v.copy_with_batch_dim_axis(data.batch_dim_axis)
assert v.batch_dim_axis == data.batch_dim_axis
continue
if v.feature_dim_axis != data.feature_dim_axis:
assert data.feature_dim_axis is not None and v.feature_dim_axis is not None
v = v.copy_with_feature_dim_axis(data.feature_dim_axis)
assert v.feature_dim_axis == data.feature_dim_axis
if data.feature_dim_axis_or_unspecified is NotSpecified:
v.feature_dim_axis = NotSpecified
assert v.feature_dim_axis == data.feature_dim_axis
continue
# Now we have both equal.
break
assert data.get_spatial_batch_axes() == v.get_spatial_batch_axes()
if self.sparse and v.feature_dim_axis is not None: # we probably added it now
v.feature_dim_axis = NotSpecified
v.sparse = self.sparse # reset
if unbroadcast and any([d1 != 1 and d2 == 1 for (d1, d2) in zip(data.batch_shape, v.batch_shape)]):
v.size_placeholder.update(data.size_placeholder or {})
if v.placeholder is not None:
with tf.name_scope("copy_compatible_to_unbroadcast"):
tiles = [1] * v.batch_ndim
for axis in range(v.batch_ndim):
if v.batch_shape[axis] != 1:
continue
if data.batch_shape[axis] is not None:
tiles[axis] = data.batch_shape[axis]
elif data_dyn_shape is not None:
tiles[axis] = data_dyn_shape[axis]
else:
assert data.placeholder, "need data.placeholder for unbroadcast (target data: %r)" % v
tiles[axis] = tf.shape(data.placeholder)[axis]
v.placeholder = tf.tile(v.placeholder, tiles)
new_shape = list(v.batch_shape)
for axis in range(v.batch_ndim):
if data.batch_shape[axis] != 1 and new_shape[axis] == 1:
new_shape[axis] = data.batch_shape[axis]
if v.feature_dim_axis is not None:
v.dim = new_shape[v.feature_dim_axis]
if v.batch_dim_axis is not None:
del new_shape[v.batch_dim_axis]
v.shape = tuple(new_shape)
if v.placeholder is not None:
v.placeholder.set_shape(v.batch_shape)
v.sanity_check()
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
data.sanity_check()
return data
def copy_extend_with_beam(self, beam_size, dyn_beam_size=None):
"""
:param int beam_size:
:param tf.Tensor|None dyn_beam_size: if the beam size is dynamic
:return: copy of myself where the batch-dim is extended/multiplied by beam_size, using tile_transposed
:rtype: Data
"""
if dyn_beam_size is None:
dyn_beam_size = beam_size
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)
if data.placeholder is not None:
data.placeholder = tile_transposed(data.placeholder, axis=data.batch_dim_axis, multiples=dyn_beam_size)
if data.size_placeholder is not None:
for i, v in sorted(data.size_placeholder.items()):
tag = DimensionTag.get_tag_from_size_tensor(v)
data.size_placeholder[i] = tile_transposed(v, axis=0, multiples=dyn_beam_size)
if tag is not None:
tag.set_tag_on_size_tensor(data.size_placeholder[i])
data.beam_size = beam_size * (data.beam_size or 1)
return data
def copy_squeeze_axes(self, axes):
"""
:param list[int] axes: counted with batch dim
:return: copy of myself, with squeezed axes
:rtype: Data
"""
assert isinstance(axes, (list, tuple))
assert all([self.batch_shape[axis] == 1 for axis in axes])
if not axes:
return self.copy()
data = self.copy()
if data.placeholder is not None:
data.placeholder = tf.squeeze(
data.placeholder, axes,
name="%s_squeeze_axes" % get_valid_scope_name_from_str(data.name))
assert data.batch_dim_axis not in axes
data.shape = tuple([data.shape[i] for i in range(data.ndim) if data.get_batch_axis(i) not in axes])
if self.time_dim_axis is not None:
if self.time_dim_axis in axes:
data.time_dim_axis = None
else:
data.time_dim_axis = self.time_dim_axis - len([axis for axis in axes if axis < self.time_dim_axis])
if not self.sparse:
if self.feature_dim_axis is not None and self.feature_dim_axis_or_unspecified is not NotSpecified:
if self.feature_dim_axis in axes:
data.feature_dim_axis = None
else:
data.feature_dim_axis = self.feature_dim_axis - len([axis for axis in axes if axis < self.feature_dim_axis])
# Always reset dim. We might have a different feature axis now (if it was and is unspecified, i.e. automatic).
if data.feature_dim_axis is not None:
data.dim = data.batch_shape[data.feature_dim_axis]
else:
data.dim = None
if self.size_placeholder:
data.size_placeholder = {
i - len([axis for axis in axes if self.get_batch_axis_excluding_batch(axis) < i]): size
for (i, size) in self.size_placeholder.items()}
data.sanity_check()
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_spatial_dim(self, spatial_axis_num, name=None):
"""
:param int spatial_axis_num: index in self.get_spatial_batch_axes()
:param str|None name: if set, this will be the new name
:return: copy of myself excluding the time-dimension without placeholder
:rtype: Data
"""
spatial_axes = self.get_spatial_batch_axes()
if spatial_axis_num < 0:
spatial_axis_num += len(spatial_axes)
assert spatial_axis_num >= 0
assert 0 <= spatial_axis_num < len(spatial_axes)
axis_to_exclude = spatial_axes[spatial_axis_num]
axis_to_exclude_wo_b = self.get_batch_axis_excluding_batch(axis_to_exclude)
size_placeholder = None
if self.size_placeholder is not None:
size_placeholder = {}
for i, size in self.size_placeholder.items():
if i == axis_to_exclude_wo_b:
continue
if i > axis_to_exclude_wo_b:
i -= 1
size_placeholder[i] = size
new_shape = list(self.shape)
del new_shape[axis_to_exclude_wo_b]
kwargs = self.get_kwargs()
other_special_axes = self.get_special_axes_dict(
counted_with_batch_dim=True, only_available=True, include_batch_dim_axis=True)
for special_axis_name, special_axis in other_special_axes.items():
if special_axis == axis_to_exclude:
kwargs.pop(special_axis_name, None)
continue
kwargs[special_axis_name] = special_axis if (special_axis < axis_to_exclude) else (special_axis - 1)
kwargs["shape"] = new_shape
kwargs["size_placeholder"] = size_placeholder
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