forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTFUtil.py
More file actions
9640 lines (8603 loc) · 351 KB
/
TFUtil.py
File metadata and controls
9640 lines (8603 loc) · 351 KB
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,
src_data=None, src_axis=None):
"""
:param str|None kind:
:param str|None description: the description should be unique
:param int|None dimension:
:param tf.Tensor|None dyn_size: e.g. seq_len, (batch,)
:param Data|None src_data:
:param int|None src_axis:
"""
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]
if src_data:
assert isinstance(src_data, Data) and isinstance(src_axis, int)
self.src_data = src_data
self.src_axis = src_axis
if dyn_size is not None:
other = DimensionTag.get_tag_from_size_tensor(dyn_size)
if other:
self.declare_same_as(other)
else:
self.set_tag_on_size_tensor(dyn_size)
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:
"""
# It's unusual if self.dimension is not None, but let's accept that.
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: size tensor. has been set before via :func:`set_tag_on_size_tensor`
:rtype: DimensionTag|None
"""
return getattr(x, "_is_size_of_dim_tag", None)
def can_compare(self):
"""
:return: whether we can clearly identify this axis. for axes with dynamic size, we require the dyn_size.
:rtype: bool
"""
if self.same_as:
return self.same_as.can_compare()
if self.kind in [self.Types.Batch, self.Types.Feature]:
return True
assert self.kind == self.Types.Spatial
if self.dimension is not None:
return True
if self.dyn_size is None:
return False
assert self.get_tag_from_size_tensor(self.dyn_size).get_same_base() is self
return True
def is_equal(self, other, ignore_feature_dim=False, allow_same_feature_dim=False, allow_same_spatial_dim=None,
treat_feature_as_spatial=False):
"""
Compares self to other for equality.
Note that the default behavior is very restrictive.
Use functions such as :func:`get_all_dimension_tags` or :func:`get_existing_tag_from_collection`
to explicitly specify the behavior for the comparison.
:param DimensionTag other:
:param bool ignore_feature_dim:
:param bool allow_same_feature_dim:
:param bool|None allow_same_spatial_dim:
:param bool treat_feature_as_spatial:
:rtype: bool
"""
if allow_same_spatial_dim is None:
allow_same_spatial_dim = allow_same_feature_dim
self_base = self.get_same_base()
other_base = other.get_same_base()
if self_base is other_base:
return True
self_kind = self.kind
other_kind = other.kind
if self_kind == other_kind == self.Types.Feature and ignore_feature_dim:
return True
if treat_feature_as_spatial:
if self_kind == self.Types.Feature:
self_kind = self.Types.Spatial
if other_kind == self.Types.Feature:
other_kind = self.Types.Spatial
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_spatial_dim:
return True
if self.description == other.description:
return True
return False
def __eq__(self, other):
"""
:param DimensionTag other:
:rtype: bool
"""
if not isinstance(other, DimensionTag):
return False
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 or self.same_as is other.get_same_base()
self.same_as = other.get_same_base()
# If we have a defined source, and this is a dynamic spatial axis, and it was undefined before,
# maybe we can overtake the size_placeholder now.
if self.same_as.dyn_size is not None and self.src_data:
assert isinstance(self.src_axis, int)
# Maybe it changed in the meanwhile, so check.
if self.src_data.get_dim_tag(self.src_axis).description == self.description:
if self.src_data.size_placeholder is None:
self.src_data.size_placeholder = {}
self.src_data.size_placeholder[
self.src_data.get_batch_axis_excluding_batch(self.src_axis)] = self.same_as.dyn_size
# If others dyn_size is None but we have a dyn_size, maybe update others dyn_size.
if self.dyn_size is not None and self.same_as.dyn_size is not self.dyn_size:
# Could be unset if it comes from the config, or from prev graph creation.
# This is important such that self.can_compare() is sane.
if self.same_as.dyn_size is None or self.same_as.dyn_size.graph is not self.dyn_size.graph:
self.same_as.dyn_size = self.dyn_size
@classmethod
def get_existing_tag_from_collection(cls, other, tags, is_equal_opts=None):
"""
:param DimensionTag other:
:param list[DimensionTag]|tuple[DimensionTag]|set[DimensionTag] tags:
:param dict[str]|None is_equal_opts: passed to DimensionTag.is_equal
:rtype: DimensionTag|None
"""
if is_equal_opts is None:
is_equal_opts = {}
for _tag in tags:
if _tag.is_equal(other, **is_equal_opts):
return _tag
return None
@classmethod
def get_all_dimension_tags(cls, data_list, is_equal_opts=None, unique_separate_axes=True):
"""
:param list[Data] data_list:
:param dict[str]|None is_equal_opts: passed to DimensionTag.is_equal
:param bool unique_separate_axes: e.g. data_list=[Data with shape (B,5,5,10)] results in 4 dim tags, not 3.
:return: list of dimension tags, dict for data -> list of dimension tags (for each axis)
:rtype: (list[DimensionTag], dict[Data, list[DimensionTag]])
"""
tags = []
data_axes_dict = {}
for data in data_list:
data_axes_dict[data] = []
tags_for_data = []
for axis in range(data.batch_ndim):
tag = data.get_dim_tag(axis)
existing_tag = cls.get_existing_tag_from_collection(tag, tags=tags, is_equal_opts=is_equal_opts)
if not existing_tag:
if unique_separate_axes:
# Don't append it to `tags` directly now, such that e.g. for data with shape (B,5,5,10),
# we end up with two separate dim tags for the two spatial dims.
tags_for_data.append(tag)
else:
tags.append(tag)
data_axes_dict[data].append(existing_tag or tag)
tags.extend(tags_for_data)
return tags, data_axes_dict
@classmethod
def get_uniq_collection(cls, tags, is_equal_opts=None):
"""
:param list[DimensionTag]|tuple[DimensionTag]|set[DimensionTag] tags:
:param dict[str]|None is_equal_opts: passed to DimensionTag.is_equal
:rtype: list[DimensionTag]
"""
res = []
for tag in tags:
ex = cls.get_existing_tag_from_collection(tag, res, is_equal_opts=is_equal_opts)
if not ex:
res.append(tag)
return res
class SearchBeam:
"""
Represents info about the beam from some beam search (e.g. via :func:`beam_search`),
e.g. such as the beam size, but also the dependencies.
This is somewhat parallel to :class:`SearchChoices`, but simpler,
and independent from the layers/network (:class:`LayerBase`).
"""
def __init__(self, beam_size, dependency=NotSpecified, name=None, _next_frame=None):
"""
:param int beam_size:
:param SearchBeam|NotSpecified|None dependency:
:param str|None name:
:param SearchBeam|None _next_frame:
"""
if isinstance(dependency, SearchBeam):
assert name and dependency.name and name != dependency.name
if name and os.path.basename(name).startswith("prev:"):
assert _next_frame
self.beam_size = beam_size
self.dependency = dependency
self.name = name
self._next_frame = _next_frame
def copy_as_prev_frame(self):
"""
:rtype: SearchBeam
"""
if self._next_frame: # already prev frame -> return self. see logic in RecLayer maybe_transform
return self
assert self.name
name = "%s/prev:%s" % (os.path.dirname(self.name), os.path.basename(self.name))
return SearchBeam(beam_size=self.beam_size, name=name, _next_frame=self)
def __repr__(self):
keys = ["name", "beam_size"]
if self.dependency is not NotSpecified:
keys.append("dependency")
return "%s(%s)" % (
self.__class__.__name__, ", ".join(["%s=%r" % (key, getattr(self, key)) for key in keys]))
def __eq__(self, other):
"""
:param SearchBeam|object|None other:
:rtype: bool
"""
if self is other:
return True
if self is None or other is None:
return False
if not isinstance(self, SearchBeam) or not isinstance(other, SearchBeam):
return False
if self.name is None or other.name is None:
return False # cannot identify
return self.name == other.name
def __ne__(self, other):
"""
:param SearchBeam|object|None other:
:rtype: bool
"""
return not (self == other)
def __hash__(self):
return hash(self.name)
def _get_dependency_list(self):
"""
:return: list as far as it is defined
:rtype: list[SearchBeam]
"""
ls = [self]
while isinstance(ls[-1].dependency, SearchBeam):
ls.append(ls[-1].dependency)
return ls
@classmethod
def get_combined_beam(cls, beam1, beam2=None, *beams):
"""
Combines beams.
This will throw an exception if they cannot be combined.
Note that in beam search (see :class:`SearchChoices`),
the logic to combine beams from different search choices
happens in a generic way for all layers automatically
via :func:`TFNetwork._create_layer_layer_desc`,
so normally we already have the same beam.
Unless we are at template construction.
:param SearchBeam|None beam1:
:param SearchBeam|None beam2:
:param SearchBeam|None beams:
:rtype: SearchBeam|None
"""
if beams:
beam12 = cls.get_combined_beam(beam1, beam2)
return cls.get_combined_beam(beam12, beams[0], *beams[1:])
if beam2 is None:
return beam1
if beam1 is None:
return beam2
if beam1 == beam2:
if beam2.dependency is NotSpecified:
return beam1
if beam1.dependency is NotSpecified:
return beam2
return beam1
assert beam1.name and beam2.name
if beam2._next_frame and not beam1._next_frame:
return beam1
if beam1._next_frame and not beam2._next_frame:
return beam2
b1 = beam1
b2 = beam2
used_next_frame = False
if b1._next_frame and b2._next_frame:
b1 = b1._next_frame
b2 = b2._next_frame
used_next_frame = True
l1 = b1._get_dependency_list()
l2 = b2._get_dependency_list()
if b2 in l1:
return beam1
if b1 in l2:
return beam2
if used_next_frame:
# Example: beam1: prev:out, beam2: prev:t, t->prev:out (l2).
if beam1 in l2: # -> beam1 dep on beam2
return beam1
if beam2 in l1:
return beam2
raise Exception(
"\n".join([
"Cannot combine beams:",
" 1: %s (deps: %s, next %s, next deps %s)" % (
beam1, beam1._get_dependency_list(),
beam1._next_frame, beam1._next_frame._get_dependency_list() if beam1._next_frame else None),
" 2: %s (deps: %s, next %s, next deps %s)" % (
beam2, beam2._get_dependency_list(), beam2._next_frame,
beam2._next_frame._get_dependency_list() if beam2._next_frame else None)]))
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,
undefined=False,
beam=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]|None 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 bool undefined:
:param SearchBeam|None beam: 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
self.undefined = undefined
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 not None:
size_placeholder = size_placeholder.copy()
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="%s:var:extern_data:%s" % (
"time" if self.get_batch_axis(axis) == self.time_dim_axis else "spatial%i" % 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 = beam
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)
@classmethod
def create_undefined(cls, name=None):
"""
:param str name:
:return: Data with undefined=True. the shape/dtype does not really matter
:rtype: Data
"""
return Data(name="%s_undefined" % (name or "unknown"), shape=(), dim=None, undefined=True)
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
else:
if self.feature_dim_axis is None: # e.g. scalars, or [B]
assert self.dim is None, "%s: not sparse but no feature-dim-axis, so dim should be None" % 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:
# Note: We could just call self.placeholder.set_shape.
# However, we are more explicit. We assume that the placeholder has already a known shape, and error otherwise.
assert self.placeholder.shape.ndims == self.batch_ndim
for i in range(self.batch_ndim):
if self.batch_shape[i] is None:
continue # we allow anything in the placeholder
if self.placeholder.shape[i].value != self.batch_shape[i]:
print("Mismatching shape: Tensor %r vs Data %r" % (self.placeholder, self))
print_graph_output(self.placeholder, max_depth=3)
assert self.placeholder.shape[i].value == self.batch_shape[i]
self.placeholder.set_shape(self.batch_shape)
assert self.placeholder.dtype.base_dtype.name == self.dtype
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, with_size_placeholder=False):
"""
:param bool with_size_placeholder:
: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.undefined:
keys += ["undefined"]
if self.beam is not None:
keys += ["beam"]
if self.vocab:
keys += ["vocab"]
if with_size_placeholder and self.size_placeholder is not None:
keys += ["size_placeholder"]
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 or
self.batch_dim_axis is None or
self.batch_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.undefined:
keys.append("undefined")
if self.beam is not None:
keys.append("beam")
args = ["%s=%r" % (key, getattr(self, key)) for key in keys]
args += ["batch_shape_meta=[%s]" % ",".join(self.get_batch_axes_short_description())]
return "Data(%s)" % ", ".join(args)
def get_batch_axes_short_description(self):
"""
:rtype: list[str]
"""
res = []
for axis, dim_tag in enumerate(self.get_batch_shape_dim_tags()):
descriptions = []
if axis == self.batch_dim_axis:
descriptions.append("B")
if axis == self.time_dim_axis:
descriptions.append("T")
if axis == self.feature_dim_axis:
descriptions.append("F")
if self.batch_shape[axis] is None:
if axis == self.batch_dim_axis:
pass # expected
elif self.size_placeholder and self.get_batch_axis_excluding_batch(axis) in self.size_placeholder:
descriptions.append(repr(dim_tag.description))
else:
descriptions.append("?")
else:
descriptions.append(str(self.batch_shape[axis]))
if dim_tag.kind == DimensionTag.Types.Spatial and dim_tag.dyn_size is not None:
descriptions.append(repr(dim_tag.description))
res.append("|".join(descriptions))
return res
def get_compare_key(self):
"""
:return: some key which can be used for compare functions, i.e. such that
cmp(get_compare_key(self), get_compare_key(other)) == cmp(self, other),
i.e. we define some order by that.
Note that this order is not totally fixed, and might change.
:rtype: object
"""
return (
self.name, self.dtype,
self.shape,
self.batch_dim_axis, self.feature_dim_axis, self.time_dim_axis,
sorted(self.size_placeholder.keys()),
[self.get_size_dim_tag(i) for i in range(len(self.size_placeholder))],
self.beam)
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 batch_dim_axis < 0:
assert batch_dim_axis + self.batch_ndim + 1 >= 0
batch_dim_axis += self.batch_ndim + 1
assert 0 <= batch_dim_axis <= self.batch_ndim
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