-
Notifications
You must be signed in to change notification settings - Fork 130
/
test_TFNetworkLayer.py
10910 lines (10125 loc) · 438 KB
/
test_TFNetworkLayer.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
# start: nosetests $this_file --nologcapture
from __future__ import division
import _setup_test_env # noqa
import tensorflow as tf
from nose.tools import assert_equal, assert_not_equal, assert_is_instance
import unittest
import numpy.testing
from pprint import pprint
from returnn.util import better_exchook
from returnn.config import Config
from returnn.tf.network import *
from returnn.tf.layers.basic import *
import returnn.tf.compat as tf_compat
import returnn.tf.util.basic as tf_util
from returnn.tf.util.data import Dim, SpatialDim, FeatureDim, BatchInfo
print("TF version:", tf.__version__)
print("Numpy version:", numpy.__version__)
@contextlib.contextmanager
def make_scope():
"""
:rtype: tf.compat.v1.Session
"""
with tf.Graph().as_default() as graph:
with tf_compat.v1.Session(graph=graph) as session:
yield session
def make_feed_dict(data_list, same_time=False, n_batch=3, n_time=7):
"""
:param list[returnn.tf.util.data.Data]|ExternData data_list:
:param bool same_time:
:param int n_batch:
:param int n_time:
:rtype: dict[tf.Tensor,numpy.ndarray]
"""
if isinstance(data_list, ExternData):
data_list = [value for (key, value) in sorted(data_list.data.items())]
assert n_time > 0 and n_batch > 0
rnd = numpy.random.RandomState(42)
existing_sizes = {} # type: typing.Dict[tf.Tensor,int]
d = {}
batch_info = None
for data in data_list:
if data.batch and not batch_info:
batch_info = data.batch
shape = list(data.batch_shape)
if data.batch_dim_axis is not None:
shape[data.batch_dim_axis] = n_batch
for axis, dim in enumerate(shape):
if dim is None:
axis_wo_b = data.get_batch_axis_excluding_batch(axis)
assert axis_wo_b in data.size_placeholder
dyn_size = data.size_placeholder[axis_wo_b]
if dyn_size in existing_sizes:
shape[axis] = existing_sizes[dyn_size]
continue
existing_sizes[dyn_size] = n_time
shape[axis] = n_time
dyn_size_v = numpy.array([n_time, max(n_time - 2, 1), max(n_time - 3, 1)])
if dyn_size_v.shape[0] > n_batch:
dyn_size_v = dyn_size_v[:n_batch]
elif dyn_size_v.shape[0] < n_batch:
dyn_size_v = numpy.concatenate(
[dyn_size_v, rnd.randint(1, n_time + 1, size=(n_batch - dyn_size_v.shape[0],))], axis=0)
d[dyn_size] = dyn_size_v
if not same_time:
n_time += 1
print("%r %r: shape %r" % (data, data.placeholder, shape))
if data.sparse:
d[data.placeholder] = rnd.randint(0, data.dim or 13, size=shape, dtype=data.dtype)
else:
d[data.placeholder] = rnd.normal(size=shape).astype(data.dtype)
if batch_info:
batch_dim = batch_info.dim
if isinstance(batch_dim, int):
assert batch_dim == n_batch, "invalid batch info %r" % batch_info
else:
assert isinstance(batch_dim, tf.Tensor)
d[batch_dim] = n_batch
return d
def test_ExternData_init_from_config():
config = Config({
"extern_data": {"data": {"dim": 42}},
})
extern_data = ExternData()
with make_scope() as session:
extern_data.init_from_config(config)
data = extern_data.data["data"]
assert data.batch_shape == (None, None, 42)
assert (data.batch_dim_axis, data.time_dim_axis, data.feature_dim_axis) == (0, 1, 2)
def test_ExternData_init_from_config_dim_none():
config = Config({
"extern_data": {"data": {"dim": None}},
})
extern_data = ExternData()
with make_scope() as session:
extern_data.init_from_config(config)
data = extern_data.data["data"]
assert data.batch_shape == (None, None, None)
assert (data.batch_dim_axis, data.time_dim_axis, data.feature_dim_axis) == (0, 1, 2)
def test_ExternData_init_twice_existing_dim_tags():
from returnn.tf.util.data import batch_dim
time_dim = SpatialDim("time")
feat_dim = FeatureDim("feature", dimension=10)
config = Config({
"extern_data": {
"data": {"dim_tags": [batch_dim, time_dim, feat_dim]} # [B,T,D]
}
})
for _ in range(2):
with make_scope() as session:
net = TFNetwork(config=config)
net.construct_from_dict({"output": {"class": "softmax_over_spatial", "from": "data"}})
session.run(net.get_default_output_layer().output.placeholder, feed_dict=make_feed_dict(net.extern_data))
def test_LinearLayer():
from returnn.tf.util.data import batch_dim
time_dim = SpatialDim("time")
feat_dim = FeatureDim("feature", dimension=5)
config = Config({
"extern_data": {
"data": {"dim_tags": [batch_dim, time_dim, feat_dim]} # [B,T,D]
}
})
for _ in range(2):
with make_scope() as session:
net = TFNetwork(config=config)
net.construct_from_dict({"output": {"class": "linear", "from": "data", "n_out": 3}})
session.run(tf_compat.v1.global_variables_initializer())
session.run(net.get_default_output_layer().output.placeholder, feed_dict=make_feed_dict(net.extern_data))
def test_LinearLayer_in_dim_spatial():
from returnn.tf.util.data import batch_dim
time_dim = SpatialDim("time")
static_spatial_dim = FeatureDim("static-spatial", dimension=3)
feat_dim = FeatureDim("in-feature", dimension=5)
out_dim = FeatureDim("out-feature", dimension=7)
config = Config({
"extern_data": {
"data": {"dim_tags": [batch_dim, time_dim, static_spatial_dim, feat_dim]} # [B,T,D1,D2]
}
})
for _ in range(2):
with make_scope() as session:
net = TFNetwork(config=config)
net.construct_from_dict({
"output": {"class": "linear", "from": "data", "in_dim": static_spatial_dim, "out_dim": out_dim}})
layer = net.get_default_output_layer()
print("Output:", layer.output)
assert layer.output.dim_tags_set_implicit == {batch_dim, time_dim, out_dim, feat_dim}
param = layer.params["W"]
assert isinstance(param, tf.Variable)
assert param.shape.as_list() == [static_spatial_dim.dimension, out_dim.dimension]
session.run(tf_compat.v1.global_variables_initializer())
session.run(layer.output.placeholder, feed_dict=make_feed_dict(net.extern_data))
def test_LinearLayer_two_time_dims_allow_broadcast_all_sources():
from returnn.tf.util.data import batch_dim
with make_scope() as session:
time1_dim = SpatialDim("time1")
time2_dim = SpatialDim("time2")
feat_dim = FeatureDim("feature", dimension=5)
out_dim = FeatureDim("feature", dimension=3)
config = Config({
"extern_data": {
"in1": {"dim_tags": [batch_dim, time1_dim, feat_dim]},
"in2": {"dim_tags": [batch_dim, time2_dim, feat_dim]},
},
})
network = TFNetwork(config=config)
try:
network.construct_from_dict({
"output": {"class": "linear", "from": ["data:in1", "data:in2"], "n_out": 3}})
except Exception as exc:
# https://github.com/rwth-i6/returnn/issues/691
print("Expected exception:", exc)
assert "require broadcasting" in str(exc)
else:
raise Exception(
"Expect allow_broadcast_all_sources exception, but layer constructed: %s" % network.get_default_output_layer())
network.construct_from_dict({
"output": {
"class": "linear", "from": ["data:in1", "data:in2"], "out_dim": out_dim,
"out_shape": {batch_dim, time1_dim, time2_dim, out_dim}}})
output = network.get_default_output_layer().output
assert output.shape == (None, None, 3)
session.run(tf_compat.v1.global_variables_initializer())
session.run(fetches=output.placeholder, feed_dict=make_feed_dict(network.extern_data))
def test_LinearLayer_generic_dim_tags():
from returnn.tf.util.data import batch_dim, any_feature_dim, any_spatial_dim
with make_scope() as session:
time1_dim = SpatialDim("time1")
time2_dim = SpatialDim("time2", dimension=7)
feat_dim = FeatureDim("feature", dimension=5)
out_dim = FeatureDim("feature", dimension=3)
config = Config({
"extern_data": {
"in1": {"dim_tags": [batch_dim, time1_dim, time2_dim, feat_dim]},
"in2": {"dim_tags": [batch_dim, time2_dim, feat_dim]},
},
})
network = TFNetwork(config=config)
network.construct_from_dict({
"output1": {
"class": "linear", "from": "data:in1", "in_dim": any_feature_dim, "out_dim": out_dim,
"out_shape": {batch_dim, time1_dim, time2_dim, out_dim},
"is_output_layer": True}})
network.construct_from_dict({
"output2": {
"class": "linear", "from": "data:in1", "in_dim": time2_dim, "out_dim": out_dim,
"out_shape": {batch_dim, time1_dim, out_dim, feat_dim},
"is_output_layer": True}})
try:
network.construct_from_dict({
"output3": {
"class": "linear", "from": "output2", "in_dim": any_feature_dim, "out_dim": out_dim,
"is_output_layer": True}})
except Exception as exc:
print("Expected exception:", exc)
assert "not found or unique in input" in str(exc)
else:
raise Exception("No exception")
network.construct_from_dict({
"output4": {
"class": "linear", "from": "data:in2", "in_dim": any_spatial_dim, "out_dim": out_dim,
"out_shape": {batch_dim, out_dim, feat_dim},
"is_output_layer": True}})
session.run(tf_compat.v1.global_variables_initializer())
session.run(
fetches=[layer.output.placeholder for layer in network.get_output_layers()],
feed_dict=make_feed_dict(network.extern_data))
def test_LinearLayer_reuse_params_layer_output():
from returnn.tf.util.data import batch_dim
with make_scope() as session:
time_dim = SpatialDim("time")
data_feat_dim = FeatureDim("feature", dimension=5)
out_feat_dim = FeatureDim("feature", dimension=7)
config = Config({
"extern_data": {
"data": {"dim_tags": [batch_dim, time_dim, data_feat_dim]},
},
})
network = TFNetwork(config=config)
network.construct_from_dict({
"weights": {"class": "variable", "shape": [data_feat_dim, out_feat_dim]},
"bias": {"class": "variable", "shape": [out_feat_dim]},
"out1": {
"class": "linear", "from": "data", "out_dim": out_feat_dim,
"is_output_layer": True,
"reuse_params": {
"map": {
"W": {"layer_output": "weights"},
"b": {"layer_output": "bias"}}}},
"out2_": {
"class": "dot", "from": ["data", "weights"],
"red1": data_feat_dim, "red2": data_feat_dim,
"var1": [batch_dim, time_dim], "var2": out_feat_dim},
"out2": {
"class": "combine", "kind": "add", "from": ["out2_", "bias"],
"is_output_layer": True}
})
out1 = network.get_layer("out1").output
out2 = network.get_layer("out2").output
params = network.get_params_list()
assert len(params) == 2 # weights and bias
session.run(tf_compat.v1.global_variables_initializer())
out1_np, out2_np = session.run(
fetches=(out1.placeholder, out2.placeholder), feed_dict=make_feed_dict(network.extern_data))
numpy.testing.assert_array_equal(out1_np, out2_np)
def test_PadLayer_time():
n_batch, n_time, n_in = 7, 3, 20
config = Config({
"extern_data": {"data": {"dim": n_in}},
"debug_print_layer_output_template": True,
})
with make_scope() as session:
padding = (2, 3)
net = TFNetwork(config=config)
net.construct_from_dict({
"output": {"class": "pad", "axes": "T", "padding": padding, "mode": "replication", "from": "data:data"}
})
out_t = net.get_default_output_layer().output.placeholder
assert out_t.shape.as_list() == [None, None, n_in]
in_v = numpy.arange(0, n_batch * n_time * n_in).astype("float32").reshape((n_batch, n_time, n_in))
out_v = session.run(out_t, feed_dict={net.extern_data.data["data"].placeholder: in_v})
assert isinstance(out_v, numpy.ndarray)
assert out_v.shape == (n_batch, n_time + sum(padding), n_in)
assert (out_v[:, 0, :] == out_v[:, padding[0], :]).all()
assert (out_v[:, -1, :] == out_v[:, -1 - padding[1], :]).all()
numpy.testing.assert_array_equal(in_v, out_v[:, padding[0]:(-padding[1] or None), :])
# check padding on left
if padding[0] > 0:
padded_left_ref = numpy.resize(in_v[:, 0, :], (padding[0], n_batch, n_in)).transpose(1, 0, 2)
numpy.testing.assert_array_equal(padded_left_ref, out_v[:, :padding[0], :])
# check padding on right
if padding[1] > 0:
padded_right_ref = numpy.resize(in_v[:, -1, :], (padding[1], n_batch, n_in)).transpose(1, 0, 2)
numpy.testing.assert_array_equal(padded_right_ref, out_v[:, -padding[1]:, :])
def test_PadLayer_feature():
n_batch, n_time, n_in = 7, 3, 20
config = Config({
"extern_data": {"data": {"dim": None}},
"debug_print_layer_output_template": True,
})
with make_scope() as session:
padding = (2, 3)
net = TFNetwork(config=config)
net.construct_from_dict({
"output": {"class": "pad", "axes": "F", "padding": padding, "mode": "replication", "from": "data:data"}
})
out_t = net.get_default_output_layer().output.placeholder
assert out_t.shape.as_list() == [None, None, None]
in_v = numpy.arange(0, n_batch * n_time * n_in).astype("float32").reshape((n_batch, n_time, n_in))
out_v = session.run(out_t, feed_dict={net.extern_data.data["data"].placeholder: in_v})
assert isinstance(out_v, numpy.ndarray)
assert out_v.shape == (n_batch, n_time, n_in + sum(padding))
assert (out_v[:, :, 0] == out_v[:, :, padding[0]]).all()
assert (out_v[:, :, -1] == out_v[:, :, -1 - padding[1]]).all()
numpy.testing.assert_array_equal(in_v, out_v[:, :, padding[0]:(-padding[1] or None)])
# check padding on left
if padding[0] > 0:
padded_left_ref = numpy.resize(in_v[:, :, 0], (n_batch, n_time, 1))
numpy.testing.assert_array_equal(padded_left_ref - out_v[:, :, :padding[0]], 0)
# check padding on right
if padding[1] > 0:
padded_left_ref = numpy.resize(in_v[:, :, -1], (n_batch, n_time, 1))
numpy.testing.assert_array_equal(padded_left_ref - out_v[:, :, -padding[1]:], 0)
def test_PadLayer_no_op():
# https://github.com/rwth-i6/returnn/issues/687
n_batch, n_time, n_in = 7, 3, 5
config = Config({
"extern_data": {"data": {"shape": (n_in, None)}}, # [B,D,T]
"debug_print_layer_output_template": True,
})
with make_scope() as session:
net = TFNetwork(config=config)
net.construct_from_dict({
"output": {'class': 'pad', 'mode': 'constant', 'axes': 'spatial', 'padding': [(0, 0)], 'from': 'data', 'value': 0}
})
out = net.get_default_output_layer().output
out_t = out.placeholder
assert out_t.shape.as_list() == [None, n_in, None]
in_v = numpy.arange(0, n_batch * n_time * n_in).astype("float32").reshape((n_batch, n_in, n_time))
out_v = session.run(out_t, feed_dict={net.extern_data.data["data"].placeholder: in_v})
assert isinstance(out_v, numpy.ndarray)
assert out_v.shape == (n_batch, n_in, n_time)
numpy.testing.assert_array_equal(in_v, out_v)
def test_PadLayer_window():
# https://github.com/rwth-i6/returnn/issues/1224
from returnn.config import Config
from returnn.tf.engine import Engine
from returnn.datasets import init_dataset
from returnn.tf.util.data import batch_dim, SpatialDim, FeatureDim
time_dim = SpatialDim('time')
in_dim = FeatureDim('in', 3)
out_dim = FeatureDim('out', 4)
def _config_get_network(epoch, **_kwargs):
window_dim = SpatialDim('window', 3)
time_dim_ = (window_dim // 2) + time_dim + window_dim.ceildiv_right(2) + (-1)
flat_dim = window_dim * time_dim_
flat_dim_ = flat_dim + window_dim
time_window_dim = time_dim + window_dim
# This is what PadLayer.get_out_data_from_opts() does.
# In returnn-common, we would execute that.
# This should be fine. But this triggers the bug.
time_dim__ = 1 + time_dim + 1
time_dim__.declare_same_as(time_dim_)
flat_dim__ = 0 + flat_dim + 3
flat_dim__.declare_same_as(flat_dim_)
net_dict = {
"#epoch": epoch, # trigger reinit
'window': {
'class': 'subnetwork',
'from': [],
'subnetwork': {
'pad': {
'class': 'pad',
'from': 'base:data:data',
'axes': time_dim,
'padding': (1, 1),
'out_dims': time_dim_,
'out_shape': {batch_dim, in_dim, time_dim_}
},
'expand_dim': {
'class': 'expand_dims',
'from': 'pad',
'axis': 'spatial',
'dim': window_dim,
'out_shape': {batch_dim, in_dim, window_dim, time_dim_}
},
'merge_dims': {
'class': 'merge_dims',
'from': 'expand_dim',
'axes': (
window_dim,
time_dim_
),
'out_dim': flat_dim,
'out_shape': {batch_dim, in_dim, flat_dim}
},
'pad_0': {
'class': 'pad',
'from': 'merge_dims',
'axes': flat_dim,
'padding': (0, 3),
'out_dims': flat_dim_,
'out_shape': {batch_dim, in_dim, flat_dim_}
},
'reshape': {
'class': 'reshape',
'from': 'pad_0',
'in_dims': [
flat_dim_
],
'out_dims': [
window_dim,
time_window_dim
],
'extra_deps': ['base:data:data'],
'out_shape': {batch_dim, in_dim, window_dim, time_window_dim}
},
'slice_nd': {
'class': 'slice_nd',
'from': 'reshape',
'size': time_dim,
'axis': time_window_dim,
'out_spatial_dim': time_dim,
'out_shape': {batch_dim, time_dim, in_dim, window_dim}
},
'output': {
'class': 'copy',
'from': 'slice_nd',
'out_shape': {batch_dim, time_dim, in_dim, window_dim}
}
}
},
'reduce': {
'class': 'reduce',
'from': 'window',
'mode': 'mean',
'axis': (window_dim, in_dim),
'out_shape': {batch_dim, time_dim}
},
'add': {
'class': 'combine',
'from': ['dot', 'reduce'],
'kind': 'add',
'is_output_layer': True,
'out_shape': {batch_dim, time_dim, out_dim}
},
'reduce_0': {
'class': 'reduce',
'from': 'add',
'mode': 'mean',
'axis': out_dim,
'out_shape': {batch_dim, time_dim}
},
'dummy': {
'class': 'copy',
'from': 'reduce_0',
'loss': 'as_is',
'out_shape': {batch_dim, time_dim}
},
'weight': {
'class': 'variable',
'shape': [
in_dim,
out_dim
],
'param_name': 'param',
},
'dot': {
'class': 'dot',
'from': ['data:data', 'weight'],
'reduce': in_dim,
'out_shape': {batch_dim, time_dim, out_dim}
},
}
return net_dict
config = Config({
"task": "train", "num_epochs": 2, "start_epoch": 1,
"get_network": _config_get_network,
"extern_data": {"data": {"dim_tags": (batch_dim, time_dim, in_dim)}},
})
train_dataset = init_dataset(
{"class": "DummyDataset", "input_dim": in_dim.dimension, "output_dim": 5, "num_seqs": 3})
engine = Engine(config)
engine.init_train_from_config(config, train_data=train_dataset)
engine.train()
def test_concat_sources():
with make_scope() as session:
network = TFNetwork(train_flag=True, extern_data=ExternData())
n_batch = 5
n_time = 3
size_placeholder = {0: tf.constant(n_time, dtype=tf.int32, shape=(n_batch,))}
src1 = InternalLayer(
name="src1", network=network,
output=Data(
name="src1_output", shape=(None, 11), placeholder=tf.zeros((n_batch, n_time, 11)),
size_placeholder=size_placeholder))
print("src1 output:", src1.output)
src2 = InternalLayer(
name="src2", network=network,
output=Data(
name="src2_output", shape=(None, 13), placeholder=tf.zeros((n_batch, n_time, 13)),
size_placeholder=size_placeholder))
print("src2 output:", src2.output)
out_kwargs = dict(name="out", sources=[src1, src2], network=network)
out_output = CopyLayer.get_out_data_from_opts(**out_kwargs)
print("out output:", out_output)
assert out_output.dim == 11 + 13
out = CopyLayer(output=out_output, **out_kwargs)
session.run(out.output.placeholder)
def test_concat_sources_batch_dim():
with make_scope() as session:
network = TFNetwork(train_flag=True, extern_data=ExternData())
n_batch = 5
n_time = 3
size_placeholder = {0: tf.constant(n_time, dtype=tf.int32, shape=(n_batch,))}
src1 = InternalLayer(
name="src1", network=network,
output=Data(
name="src1_output", shape=(None, 11), placeholder=tf.zeros((n_batch, n_time, 11)),
size_placeholder=size_placeholder))
print("src1 output:", src1.output)
src2 = InternalLayer(
name="src2", network=network,
output=Data(
name="src2_output", shape=(None, 13), time_dim_axis=0, batch_dim_axis=1,
placeholder=tf.zeros((n_time, n_batch, 13)),
size_placeholder=size_placeholder))
print("src2 output:", src2.output)
out_kwargs = dict(name="out", sources=[src1, src2], network=network)
out_output = CopyLayer.get_out_data_from_opts(**out_kwargs)
print("out output:", out_output)
assert out_output.dim == 11 + 13
assert out_output.batch_dim_axis == 0 and out_output.time_dim_axis == 1
out = CopyLayer(output=out_output, **out_kwargs)
session.run(out.output.placeholder)
def test_concat_sources_missing_dim():
with make_scope() as session:
network = TFNetwork(train_flag=True, extern_data=ExternData())
n_batch = 5
n_time = 3
size_placeholder = {0: tf.constant(n_time, dtype=tf.int32, shape=(n_batch,))}
src1 = InternalLayer(
name="src1", network=network,
output=Data(
name="src1_output", shape=(None, 11), placeholder=tf.zeros((n_batch, n_time, 11)),
size_placeholder=size_placeholder))
print("src1 output:", src1.output)
src2 = InternalLayer(
name="src2", network=network,
output=Data(
name="src2_output", shape=(13,), time_dim_axis=None, batch_dim_axis=0,
placeholder=tf.zeros((n_batch, 13)),
size_placeholder={}))
print("src2 output:", src2.output)
out_kwargs = dict(name="out", sources=[src1, src2], network=network)
out_output = CopyLayer.get_out_data_from_opts(**out_kwargs)
print("out output:", out_output)
assert out_output.dim == 11 + 13
assert out_output.batch_dim_axis == 0 and out_output.time_dim_axis == 1
out = CopyLayer(output=out_output, **out_kwargs)
session.run(out.output.placeholder)
def test_concat_sources_dim1():
with make_scope() as session:
net_dict = {
"lin1": {"class": "linear", "activation": "sigmoid", "n_out": 5, "from": "data:data"},
"lin2": {"class": "linear", "activation": "sigmoid", "n_out": 1, "from": "data:data"},
"concat": {"class": "copy", "from": ["lin1", "lin2"]},
"output": {"class": "softmax", "loss": "ce", "from": "concat"}
}
config = Config({"debug_print_layer_output_template": True})
config.update(dict(num_inputs=4, num_outputs=9))
network = TFNetwork(config=config, train_flag=True)
network.construct_from_dict(net_dict)
assert_equal(network.get_layer("concat").output.shape, (None, 6))
out = network.get_default_output_layer()
assert out.output.shape == (None, 9)
feed_dict = make_feed_dict(network.extern_data.data.values(), same_time=True)
session.run(tf_compat.v1.global_variables_initializer())
session.run(out.output.placeholder, feed_dict=feed_dict)
def test_concat_new_dim_tag():
from returnn.tf.util.data import Dim
with make_scope():
n_out = 5
time_tag = Dim(Dim.Types.Spatial, "time")
new_time_tag = Dim(Dim.Types.Spatial, "new-time")
config = Config({
"debug_print_layer_output_template": True,
"extern_data": {
"data": {"dim": n_out, "same_dim_tags_as": {"t": time_tag}},
"classes": {"dim": n_out, "sparse": True, "same_dim_tags_as": {"t": time_tag}}
}})
net = TFNetwork(config=config, search_flag=True)
net.construct_from_dict({
"data_new": {
"class": "reinterpret_data", "from": "data",
"set_dim_tags": {"t": new_time_tag}},
"output": {"class": "rec", "from": "data", "unit": {
"prev_out0": {
"class": "reinterpret_data", "from": "prev:output", "set_sparse": False},
"prev_out1": {"class": "cast", "from": "prev_out0", "dtype": "float32"},
"prev_out": {"class": "expand_dims", "from": "prev_out1", "axis": "f"},
"data_concat": {
"class": "copy", "from": ["base:data_new", "prev_out"]
},
"data_red": {"class": "reduce", "from": "data_concat", "axis": "stag:new-time", "mode": "max"},
"output_prob": {"class": "softmax", "from": "data_red", "target": "classes", "loss": "ce"},
"output": {
"class": "choice", "from": "output_prob", "beam_size": 3, "target": "classes",
"input_type": "prob", "initial_output": 0}
}}
})
def test_ConcatLayer():
with make_scope() as session:
net_dict = {
"lin1": {"class": "linear", "activation": "sigmoid", "n_out": 5, "from": "data:data"},
"lin2": {"class": "linear", "activation": "sigmoid", "n_out": 3, "from": "data:data"},
"output": {"class": "concat", "from": [("lin1", "F"), ("lin2", "F"), ("data", "F")]},
}
config = Config({"extern_data": {"data": {"dim": 2}}})
network = TFNetwork(config=config)
network.construct_from_dict(net_dict)
out = network.get_default_output_layer()
assert_equal(out.output.shape, (None, 10))
feed_dict = make_feed_dict(network.extern_data, same_time=True)
session.run(tf_compat.v1.global_variables_initializer())
session.run(out.output.placeholder, feed_dict=feed_dict)
def test_ConcatLayer_range_dyn():
with make_scope() as session:
net_dict = {
"range": {"class": "range_in_axis", "from": "data:data", "axis": "T"},
"output": {"class": "concat", "from": [("range", "T"), ("range", "T")]},
}
config = Config({"extern_data": {"data": {"dim": 2}}})
network = TFNetwork(config=config)
network.construct_from_dict(net_dict)
out = network.get_default_output_layer().output
assert_equal(out.batch_shape, (None,))
feed_dict = make_feed_dict(network.extern_data, n_time=7)
session.run(out.placeholder, feed_dict=feed_dict)
assert_equal(session.run(out.dim_tags[0].get_dim_value(), feed_dict=feed_dict), 14)
def test_LinearLayer_batch_feature_major():
with make_scope() as session:
network = TFNetwork(config=Config(), extern_data=ExternData(), train_flag=True)
n_in = 3
n_out = 7
source = InternalLayer(
name="source", network=network, output=Data(
name="source", shape=(n_in, None), time_dim_axis=2, auto_create_placeholders=True))
assert source.output.feature_dim_axis == 1
assert source.output.is_batch_feature_major
out_template = LinearLayer.get_out_data_from_opts(
name="lin", network=network, n_out=n_out, activation=None, sources=[source])
out_template.sanity_check()
assert out_template.shape == (n_out, None) and (out_template.feature_dim_axis, out_template.time_dim_axis) == (1, 2)
assert out_template.is_batch_feature_major
with tf_compat.v1.variable_scope("lin"):
layer = LinearLayer(
name="lin", network=network, n_out=n_out, activation=None, sources=[source], output=out_template)
layer.output.sanity_check()
n_batch = 5
n_times = [13, 13, 11, 7, 5]
assert len(n_times) == n_batch
n_time = max(n_times)
feed_dict = {
source.output.placeholder: numpy.random.normal(size=(n_batch, n_in, n_time)).astype("float32"),
source.output.size_placeholder[1]: numpy.array(n_times, dtype="int32")}
session.run(tf_compat.v1.global_variables_initializer())
session.run(layer.output.placeholder, feed_dict=feed_dict)
def test_batch_norm_vars():
with make_scope() as session:
n_in, n_out = 2, 3
config = Config()
layer_name = "layer1"
config.update({
"num_outputs": n_out,
"num_inputs": n_in,
"network": {
layer_name: {
"class": "linear", "activation": "relu", "batch_norm": {"masked_time": True},
"n_out": n_out, "is_output_layer": True,
"from": "data:data"}
}})
network = TFNetwork(config=config, train_flag=True)
network.construct_from_dict(config.typed_value("network"))
layer = network.layers[layer_name]
print("layer:", layer)
print("layer vars:")
pprint(layer.params)
assert layer.use_batch_norm
bn_prefix = "batch_norm/v2_"
assert_equal(set(layer.params.keys()), {
"W", "b", bn_prefix + "beta", bn_prefix + "mean", bn_prefix + "gamma", bn_prefix + "variance"})
assert_equal(layer.params["W"].get_shape().as_list(), [n_in, n_out])
assert_equal(layer.params["b"].get_shape().as_list(), [n_out])
assert_equal(layer.params[bn_prefix + "beta"].get_shape().as_list(), [n_out])
assert_equal(layer.params[bn_prefix + "gamma"].get_shape().as_list(), [n_out])
assert_equal(layer.params[bn_prefix + "mean"].get_shape().as_list(), [n_out])
assert_equal(layer.params[bn_prefix + "variance"].get_shape().as_list(), [n_out])
def _test_batch_norm_param_old_to_new_import(old_version, new_version):
import tempfile
model_tmp_dir = tempfile.mkdtemp("tmp-checkpoint")
model_filename = model_tmp_dir + "/model"
layer_name = "layer1"
n_in = 3
def _make_net_dict(param_version):
return {
layer_name: {
"class": "batch_norm", "from": "data:data", "is_output_layer": True,
"param_version": param_version, "masked_time": True}
}
with make_scope() as session:
config = Config({"extern_data": {"data": {"dim": n_in}}})
network = TFNetwork(config=config, train_flag=True)
network.construct_from_dict(_make_net_dict(param_version=old_version))
network.initialize_params(session)
network.save_params_to_file(filename=model_filename, session=session)
out_ref = session.run(
network.get_default_output_layer().output.placeholder, feed_dict=make_feed_dict(network.extern_data))
assert isinstance(out_ref, numpy.ndarray)
assert not numpy.allclose(out_ref, 0.0)
with make_scope() as session:
config = Config({"extern_data": {"data": {"dim": n_in}}})
network = TFNetwork(config=config, train_flag=True)
network.construct_from_dict(_make_net_dict(param_version=new_version))
network.load_params_from_file(filename=model_filename, session=session)
out_new = session.run(
network.get_default_output_layer().output.placeholder, feed_dict=make_feed_dict(network.extern_data))
assert isinstance(out_new, numpy.ndarray)
assert not numpy.allclose(out_new, 0.0)
numpy.testing.assert_allclose(out_ref, out_new)
def test_batch_norm_param_v0_to_v1_import():
_test_batch_norm_param_old_to_new_import(old_version=0, new_version=1)
def test_batch_norm_param_v0_to_v2_import():
_test_batch_norm_param_old_to_new_import(old_version=0, new_version=2)
def test_batch_norm_param_v1_to_v2_import():
_test_batch_norm_param_old_to_new_import(old_version=1, new_version=2)
def test_batch_norm_fused():
n_in = 3
net_dict = {
"output": {
"class": "batch_norm", "from": "data:data",
"masked_time": False,
"param_version": 2,
}
}
def _find_fused_bn_op(session_):
for op in session_.graph.get_operations():
assert isinstance(op, tf.Operation)
if "FusedBatchNorm" in op.type:
return op
with make_scope() as session:
config = Config({"extern_data": {"data": {"dim": n_in}}})
network = TFNetwork(config=config, train_flag=True)
network.construct_from_dict(net_dict)
out = network.get_default_output_layer().output.placeholder
assert _find_fused_bn_op(session)
network.initialize_params(session)
out_np = session.run(out, feed_dict=make_feed_dict(network.extern_data))
assert isinstance(out_np, numpy.ndarray)
assert not numpy.allclose(out_np, 0.0)
with make_scope() as session:
config = Config({"extern_data": {"data": {"dim": n_in}}})
network = TFNetwork(config=config, train_flag=False)
network.construct_from_dict(net_dict)
out = network.get_default_output_layer().output.placeholder
assert _find_fused_bn_op(session)
network.initialize_params(session)
out_np = session.run(out, feed_dict=make_feed_dict(network.extern_data))
assert isinstance(out_np, numpy.ndarray)
assert not numpy.allclose(out_np, 0.0)
def test_batch_norm():
with make_scope() as session:
net = TFNetwork(extern_data=ExternData(), train_flag=True)
with tf_compat.v1.variable_scope("src_nchw"):
src_nhwc = InternalLayer(
name="src_nchw", network=net,
output=Data(**{
"name": "src_nchw_output",
"dim": 16,
"shape": (None, 16, 16),
"batch_dim_axis": 0,
"time_dim_axis": 1,
"feature_dim_axis": 3,
"sparse": False}))
src_nhwc.output.placeholder = tf_compat.v1.placeholder(shape=(None, None, 16, 16), dtype=tf.float32)
src_nhwc.output.size_placeholder = {0: tf_compat.v1.placeholder(shape=(None,), dtype=tf.int32)}
rnd = numpy.random.RandomState(42)
input_data = rnd.rand(10, 11, 16, 16)
seq_lens = numpy.array([11] * 10)
with tf_compat.v1.variable_scope("batch_norm_masked_nchw"):
batch_norm_1 = BatchNormLayer(
name="batch_norm_masked_nchw", network=net, masked_time=True,
sources=[src_nhwc],
output=BatchNormLayer.get_out_data_from_opts(
name="batch_norm_masked_nchw",
sources=[src_nhwc],
network=net))
batch_norm_1.post_init(layer_desc={"output": batch_norm_1.output})
with tf_compat.v1.variable_scope("batch_norm_nonmasked_nchw"):
batch_norm_2 = BatchNormLayer(
name="batch_norm_nonmasked_nchw", network=net, masked_time=False,
sources=[src_nhwc],
output=BatchNormLayer.get_out_data_from_opts(
name="batch_norm_nonmasked_nchw",
sources=[src_nhwc],
network=net))
batch_norm_2.post_init(layer_desc={"output": batch_norm_2.output})
tf_compat.v1.global_variables_initializer().run(session=session)
out_1, seq_lens_1 = session.run(
[batch_norm_1.output.placeholder, batch_norm_1.output.size_placeholder[0]],
feed_dict={
src_nhwc.output.placeholder: input_data,
src_nhwc.output.size_placeholder[0]: seq_lens})
out_2, seq_lens_2 = session.run(
[batch_norm_2.output.placeholder, batch_norm_2.output.size_placeholder[0]],
feed_dict={
src_nhwc.output.placeholder: input_data,
src_nhwc.output.size_placeholder[0]: seq_lens})
numpy.testing.assert_array_almost_equal(out_1, out_2)
print(numpy.sum(out_1 - out_2))
def test_batch_norm_unequal_seq_len():
with make_scope() as session:
net = TFNetwork(extern_data=ExternData(), train_flag=True)
with tf_compat.v1.variable_scope("src_nhwc"):
src_nhwc = InternalLayer(
name="src_nhwc", network=net,
output=Data(**{
"name": "src_nhwc_output",
"dim": 16,
"shape": (None, 16, 16),
"batch_dim_axis": 0,
"time_dim_axis": 1,
"feature_dim_axis": 3,
"sparse": False}))
src_nhwc.output.placeholder = tf_compat.v1.placeholder(shape=(None, None, 16, 16), dtype=tf.float32)
src_nhwc.output.size_placeholder = {0: tf_compat.v1.placeholder(shape=(None,), dtype=tf.int32)}
rnd = numpy.random.RandomState(42)
input_data = rnd.rand(10, 11, 16, 16).astype('f')
input_data[2, 5:, :, :] = 0
input_data_masked = numpy.copy(input_data)
seq_lens = numpy.array([11, 11, 5, 11, 11, 11, 11, 11, 11, 11], dtype=numpy.float32)
n1 = 9 * 11 * 16 + 5 * 16
n2 = 10 * 11 * 16
with tf_compat.v1.variable_scope("batch_norm_masked_nchw"):
batch_norm_1 = BatchNormLayer(
name="batch_norm_masked_nchw", network=net, masked_time=True,
use_shift=False, use_std=False, epsilon=0.0,
sources=[src_nhwc],
output=BatchNormLayer.get_out_data_from_opts(
name="batch_norm_masked_nchw",
sources=[src_nhwc],
network=net))
batch_norm_1.post_init(layer_desc={"output": batch_norm_1.output})
with tf_compat.v1.variable_scope("batch_norm_nonmasked_nchw"):
batch_norm_2 = BatchNormLayer(
name="batch_norm_nonmasked_nchw", network=net, masked_time=False,
use_shift=False, use_std=False, epsilon=0,
sources=[src_nhwc],
output=BatchNormLayer.get_out_data_from_opts(
name="batch_norm_nonmasked_nchw",
sources=[src_nhwc],
network=net))
batch_norm_2.post_init(layer_desc={"output": batch_norm_2.output})
tf_compat.v1.global_variables_initializer().run(session=session)
out_1, seq_lens_1 = session.run(
[batch_norm_1.output.placeholder, batch_norm_1.output.size_placeholder[0]],
feed_dict={
src_nhwc.output.placeholder: input_data,
src_nhwc.output.size_placeholder[0]: seq_lens})
out_2, seq_lens_2 = session.run(
[batch_norm_2.output.placeholder, batch_norm_2.output.size_placeholder[0]],
feed_dict={
src_nhwc.output.placeholder: input_data_masked,
src_nhwc.output.size_placeholder[0]: seq_lens})
# Manually calculating batch_norm and compare to the tf output
data_mean = numpy.mean(input_data, axis=(0, 1, 2), keepdims=True, dtype=numpy.float32)
data_var = numpy.var(input_data, axis=(0, 1, 2), keepdims=True, dtype=numpy.float32)
np_bn2 = (input_data - data_mean) * (1.0 / numpy.sqrt(data_var))
numpy.testing.assert_array_almost_equal(np_bn2, out_2, decimal=5)
# Manually calculating batch_norm with different seq_lens, having:
# Mean_1 = n2 / n1 * Mean_2
# Var_1 = n2 / n1 * (Var_2 + Mean_2 ^ 2 (1 - n2 / n1))
# bn_1 = (x - Mean_1) * 1 / sqrt(Var_1)
# Substituting Mean_1 and Var_1:
np_bn1 = (
(input_data - n2 / n1 * data_mean) *
(1.0 / numpy.sqrt(n2 / n1 * (data_var + data_mean ** 2 * (1 - n2 / n1)))))
# Check with tf output.
numpy.testing.assert_array_almost_equal(np_bn1, out_1, decimal=5)
def test_BatchNormLayer_CondLayer():
from returnn.tf.util.data import batch_dim, SpatialDim, FeatureDim
time_dim = SpatialDim('time')
in_dim = FeatureDim('in', 12)
config = Config(dict(extern_data={
'data': {
'dim_tags': (batch_dim, time_dim, in_dim),
}
}))
net_dict = {
'length': {
'class': 'length',
'from': ['data:data'],
'axis': batch_dim,
'out_shape': {}
},
'mod': {
'class': 'eval',
'from': 'length',
'eval': 'source(0) % 2',
'out_shape': {}
},
'compare': {
'class': 'compare',
'from': 'mod',
'kind': 'equal',
'value': 0,
'out_shape': {}