forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFUtil.py
6474 lines (5706 loc) · 230 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, 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
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
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 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=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,
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 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: int|None # 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: tuple[int|None] # excluding 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:
taken_axes = {self.batch_dim_axis}
if self.feature_dim_axis is not None:
taken_axes.add(self.feature_dim_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: int|None # 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: int|None
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 or all([d is not None for d in shape])):
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
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
self.sanity_check()
def sanity_check(self):
for axis_name, axis in self.get_special_axes_dict().items():
assert axis is None or 0 <= axis < self.batch_ndim, "axis %s (%i) invalid" % (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, "axis %s (%i) must be different from batch_dim_axis (%i)" % (
axis_name, axis, self.batch_dim_axis)
if self.sparse:
assert self.feature_dim_axis is None, "If sparse, there cannot be a feature dim axis."
if self.feature_dim_axis is not None:
assert self.dim == self.batch_shape[self.feature_dim_axis]
if self.placeholder is not None:
self.placeholder.set_shape(self.batch_shape)
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 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"]
return {key: getattr(self, key) for key in keys}
def get_description(self, with_name=True, with_placeholder=False):
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 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.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):
with tf.name_scope("%s_as_time_major" % (data.name,)):
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
data.sanity_check()
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
if batch_dim_axis < 0:
batch_dim_axis += self.batch_ndim
assert batch_dim_axis >= 0
data = self.copy()
if data.batch_dim_axis != batch_dim_axis:
if data.placeholder is not None:
with tf.name_scope("%s_with_batch_axis_%i" % (data.name, batch_dim_axis)):
data.placeholder = move_axis(data.placeholder, new_axis=batch_dim_axis, old_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))
data.sanity_check()
return data
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.batch_dim_axis is not None
if time_dim_axis < 0:
time_dim_axis += self.batch_ndim
assert time_dim_axis >= 0
data = self.copy()
if data.time_dim_axis != time_dim_axis:
data.time_dim_axis = time_dim_axis
assert time_dim_axis <= data.batch_ndim_dense - 2
new_axes = list(range(data.batch_ndim))
new_axes[self.time_dim_axis], new_axes[data.time_dim_axis] = \
new_axes[data.time_dim_axis], new_axes[self.time_dim_axis] # swap
if data.placeholder is not None:
with tf.name_scope("%s_with_time_axis_%i" % (data.name, time_dim_axis)):
data.placeholder = tf.transpose(data.placeholder, new_axes)
batch_shape = [data.batch_shape[i] for i in new_axes]
data.batch_dim_axis = new_axes[self.batch_dim_axis]
data.shape = tuple([d for (i, d) in enumerate(batch_shape) if i != data.batch_dim_axis])
if data.size_placeholder is not None:
data.size_placeholder = {}
for axis_wo_b, size in sorted(self.size_placeholder.items()):
axis_wb = self.get_batch_axis(axis_wo_b)
axis_wb = new_axes[axis_wb]
axis_wo_b = data.get_batch_axis_excluding_batch(axis_wb)
assert axis_wo_b is not None
data.size_placeholder[axis_wo_b] = size
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)
raise ValueError("cannot convert %r to BT|TB major" % self)
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
if feature_dim_axis < 0:
feature_dim_axis += self.batch_ndim
assert 0 <= feature_dim_axis < self.batch_ndim
data = self.copy()
if data.feature_dim_axis == feature_dim_axis:
return data
if data.placeholder is not None:
data.placeholder = move_axis(
data.placeholder, new_axis=feature_dim_axis, old_axis=data.feature_dim_axis)
new_shape = list(data.shape)
new_shape.pop(data.get_batch_axis_excluding_batch(self.feature_dim_axis))
new_shape.insert(data.get_batch_axis_excluding_batch(feature_dim_axis), data.dim)
data.shape = tuple(new_shape)
other_special_axes = data.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)
data.feature_dim_axis = feature_dim_axis
for k, a in other_special_axes.items():
setattr(data, k, a if (a < feature_dim_axis) else (a + 1))
axis_old_wo_batch = self.get_batch_axis_excluding_batch(self.feature_dim_axis)
axis_new_wo_batch = data.get_batch_axis_excluding_batch(feature_dim_axis)
if self.size_placeholder:
new_size_placeholder = {}
for i, s in self.size_placeholder.items():
if i >= axis_new_wo_batch:
if i < axis_old_wo_batch:
i += 1
else:
assert i > axis_new_wo_batch
else: # i < axis_new_wo_batch
if i > axis_old_wo_batch:
assert i > 0
i -= 1
new_size_placeholder[i] = s
data.size_placeholder = new_size_placeholder
data.sanity_check()
return data
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_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 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))
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))
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):
"""
: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).
:returns: Data, might add broadcast dimensions
:rtype: Data
"""
assert self.sparse == data.sparse
assert self.dtype == data.dtype
v = self.copy()
# Add feature dim, if needed.
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()):
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:
assert data.batch_dim_axis is not None
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 v.feature_dim_axis == data.feature_dim_axis
assert v.batch_ndim == data.batch_ndim
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:
data.size_placeholder = {
i: tile_transposed(v, axis=0, multiples=dyn_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()
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("time_dim_axis", None)
for axis_name, axis in other_special_axes.items():
kwargs[axis_name] = axis if (axis < self.time_dim_axis) else (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):
"""
Adds a time-dim-axis.
If a time-dim-axis already exists, it will anyway create this new one.
: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
kwargs = self.get_kwargs()
new_shape = list(self.shape)
new_shape.insert(time_dim_axis, None)
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("time_dim_axis", None)
for axis_name, axis in other_special_axes.items():
kwargs[axis_name] = axis if (axis < time_dim_axis) else (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]
"""
return self.get_batch_shape(batch_dim=None)
def get_batch_shape(self, batch_dim):
"""
:param int|tf.Tensor|None batch_dim:
: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] + (batch_dim,) + self.shape[self.batch_dim_axis:]
return self.shape
@property
def shape_dense(self):
"""
:return: shape with feature dim axis
:rtype: tuple[int|None]
"""
if self.sparse:
return self.shape + (self.dim,) # by default, assume at the end
return self.shape
@property
def shape_sparse(self):
"""
:return: shape without feature dim axis
:rtype: tuple[int|None]
"""
if self.sparse:
return self.shape
return self.shape[:self.feature_dim_axis] + self.shape[self.feature_dim_axis + 1:]
@property
def batch_shape_dense(self):
if self.sparse:
return self.batch_shape + (self.dim,)
return self.batch_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 batch_ndim_dense(self):
"""
:rtype: int
:return: ndim counted with batch-dim, added by 1 if we are sparse
"""
if self.sparse:
return self.batch_ndim + 1
return self.batch_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 is_batch_feature_major(self):
"""
:return: whether this is in batch-feature-major format, i.e. (batch,feature,...) (NC...)
:rtype: bool
"""
return self.batch_dim_axis == 0 and self.feature_dim_axis == 1
def _default_feature_dim_axis(self):
"""
:return: feature dim axis, counted with batch-dim
:rtype: int|None
"""
if self.sparse:
return None
if not self.shape:
return None
# Allow same as time-dim-axis...
return [i for i in range(self.batch_ndim) if i != self.batch_dim_axis][-1]
@property
def feature_dim_axis(self):
"""
:return: feature dim axis, counted with batch-dim
:rtype: int|None
"""
if self._feature_dim_axis is not NotSpecified:
return self._feature_dim_axis
return self._default_feature_dim_axis()
@feature_dim_axis.setter
def feature_dim_axis(self, value):
"""
:param int|None|NotSpecified value:
"""
assert value is NotSpecified or value is None or isinstance(value, int)
if isinstance(value, int):
assert 0 <= value < self.batch_ndim
self._feature_dim_axis = value
@property
def feature_dim_axis_or_unspecified(self):
"""
:return: feature dim axis, counted with batch-dim. could also be unspecified
:rtype: int|None|NotSpecified
"""
return self._feature_dim_axis
@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):
assert self.placeholder is not None
return self.copy_as_time_major().placeholder
def get_placeholder_as_batch_major(self):
assert self.placeholder is not None
return self.copy_as_batch_major().placeholder
def get_placeholder_with_specific_batch_dim_axis(self, batch_dim_axis):
assert self.placeholder is not None
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.placeholder is not None
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).
"""
assert self.placeholder is not None
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
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]|None axes: one axis or multiple axis, or none.
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 axes is None or axes == "":
return []
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])
spatial_axes = self.get_spatial_batch_axes()
if s < 0:
s += len(spatial_axes)
assert s < len(spatial_axes), "%s get_axes_from_description: %r invalid" % (self, axes)
axes = spatial_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"]: