-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtest_layers.py
1993 lines (1558 loc) · 64.3 KB
/
test_layers.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
import _setup_test_env # noqa
import sys
import unittest
import typing
import numpy
import tensorflow as tf
from pytorch_to_returnn import torch
from pytorch_to_returnn.converter import verify_torch_and_convert_to_returnn
from pytorch_to_returnn.pprint import pformat
def test_randint():
n_batch, n_time, n_feat = 3, 5, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
out = torch.randint(low=0, high=3, size=(6, 7))
out = out + 1
return out
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feat), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_randint_dynamic():
n_batch, n_time, n_feat = 3, 5, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
bsz, tsz, fsz = inputs.shape
out = torch.randint(low=0, high=tsz, size=(bsz, 3 * tsz))
out = out + 1
return out
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feat), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_contrastive_loss():
n_batch, n_time, n_feat = 3, 14, 7 # B, T', F
n_negatives = 10 # N
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.Conv1d(in_channels=n_feat, out_channels=n_feat, kernel_size=2, stride=3)
inputs = model(inputs.transpose(1, 2)).transpose(1, 2).contiguous()
bsz, tsz, fsz = inputs.shape # (B,T,F)
tszs = torch.arange(tsz).unsqueeze(-1).expand(-1, n_negatives).flatten() # (T*N)
neg_idxs = torch.randint(low=0, high=tsz - 1, size=(bsz, n_negatives * tsz)) # (B,T*N)
neg_idxs = neg_idxs + (neg_idxs >= tszs).int() # (B,T*N)
neg_idxs = neg_idxs + (torch.arange(bsz).unsqueeze(1) * tsz) # (B,T*N)
y = inputs.view(-1, fsz) # (B,T,F) => (B*T,F)
negs = y[neg_idxs.view(-1)] # (B*T*N,F)
negs = negs.view(bsz, tsz, n_negatives, fsz).permute(2, 0, 1, 3) # to (N,B,T,F)
inputs_unsqueeze = inputs.unsqueeze(0) # (1,B,T,F)
targets = torch.cat([inputs_unsqueeze, negs], dim=0) # (N+1,B,T,F)
logits = torch.cosine_similarity(inputs.float(), targets.float(), dim=-1).type_as(inputs)
labels = logits.new_zeros(logits.size(1) * logits.size(2), dtype=torch.long)
logits = logits.transpose(0, 2)
logits = logits.reshape(-1, logits.size(-1))
output = torch.nn.functional.cross_entropy(logits, labels, reduction="sum")
return output
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feat)).astype("float32")
converter = verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feat), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
cfg = converter.get_returnn_config_serialized()
from returnn_helpers import config_net_dict_via_serialized, dummy_run_net
config, net_dict = config_net_dict_via_serialized(cfg)
dummy_run_net(config)
def test_embedding():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.Embedding(n_in, n_out)
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.randint(0, n_in, (n_time, n_batch), dtype="int64")
verify_torch_and_convert_to_returnn(
model_func,
inputs=x, inputs_data_kwargs={"shape": (None,), "sparse": True, "dim": n_in, "batch_dim_axis": 1})
def test_linear_multiple_steps():
n_steps = 3
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
ins = inputs.chunk(n_steps, dim=-1)
model = torch.nn.Linear(n_in, n_out)
outs = [model(x) for x in ins]
out = sum(outs)
return out
x = numpy.ones((n_batch, n_time, n_in * n_steps)).astype("float32")
verify_torch_and_convert_to_returnn(
model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_in * n_steps), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_load_params_in_returnn():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
class DummyModule(torch.nn.Module):
def __init__(self):
super(DummyModule, self).__init__()
self.model = torch.nn.Linear(n_in, n_out)
def forward(self, x):
return F.linear(x, self.model.weight)
mod = DummyModule()
return mod(inputs)
x = numpy.ones((n_batch, n_time, n_in)).astype("float32")
verify_torch_and_convert_to_returnn(
model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_in), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_load_params_in_returnn_with_initializer():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
class DummyModule(torch.nn.Module):
def __init__(self):
super(DummyModule, self).__init__()
self.model = torch.nn.Linear(n_in, n_out)
torch.nn.init.xavier_uniform_(self.model.weight)
def forward(self, x):
return F.linear(x, self.model.weight)
mod = DummyModule()
return mod(inputs)
x = numpy.ones((n_batch, n_time, n_in)).astype("float32")
verify_torch_and_convert_to_returnn(
model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_in), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_cat():
def model_func(wrapped_import, inputs: torch.Tensor):
if wrapped_import:
torch = wrapped_import("torch")
else:
import torch
return torch.cat((inputs, inputs), dim=-1)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (3, 3)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_cat_non_feature():
n_batch, n_time, n_feat = 3, 5, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if wrapped_import:
torch = wrapped_import("torch")
else:
import torch
x = inputs.expand(2, n_batch, n_feat, n_time)
y = inputs.expand(3, n_batch, n_feat, n_time)
return torch.cat([x, y], dim=0)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_feat, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_conv():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
# {'class': 'transposed_conv', 'from': 'layer2', 'activation': None, 'with_bias': True,
# 'n_out': 192, 'filter_size': (10,), 'strides': (5,), 'remove_padding': (3,), 'output_padding': (1,)}
model = torch.nn.Conv1d(
in_channels=n_in,
out_channels=n_out,
kernel_size=3,
stride=2)
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_conv2d():
n_in, n_out = 11, 13
n_batch, n_time1, n_time2 = 3, 17, 19
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
# {'class': 'transposed_conv', 'from': 'layer2', 'activation': None, 'with_bias': True,
# 'n_out': 192, 'filter_size': (10,), 'strides': (5,), 'remove_padding': (3,), 'output_padding': (1,)}
model = torch.nn.Conv2d(
in_channels=n_in,
out_channels=n_out,
kernel_size=(3, 5),
stride=2)
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time1, n_time2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_conv_transposed():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
# {'class': 'transposed_conv', 'from': 'layer2', 'activation': None, 'with_bias': True,
# 'n_out': 192, 'filter_size': (10,), 'strides': (5,), 'remove_padding': (3,), 'output_padding': (1,)}
model = torch.nn.ConvTranspose1d(
in_channels=n_in,
out_channels=n_out,
kernel_size=10,
stride=5,
padding=3,
output_padding=1)
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_conv_transposed_2d():
n_in, n_out = 11, 13
n_batch, n_time1, n_time2 = 3, 17, 19
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.ConvTranspose2d(
in_channels=n_in,
out_channels=n_out,
kernel_size=(10, 3),
stride=5,
padding=(2, 3),
output_padding=1)
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time1, n_time2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_conv_transposed_2d_with_unsqueeze():
n_in, n_out = 16, 16
n_batch, n_features, n_time = 4, 16, 20
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
inputs = inputs.unsqueeze(-1) # (B, F, T, 1)
model = torch.nn.ConvTranspose2d(
in_channels=n_in,
out_channels=n_out,
kernel_size=(1, 12))
return model(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_features, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_linear():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_out, n_in)).astype("float32")
bias = rnd.normal(0., 1., (n_out,)).astype("float32")
weight = torch.from_numpy(weight)
bias = torch.from_numpy(bias)
return F.linear(inputs.transpose(1, 2), weight=weight, bias=bias)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_multiplication_broadcasting():
n_batch, n_time, n_feature = 3, 7, 11
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
bsz, fsz, tsz = inputs.shape
out = inputs * inputs.expand(3, bsz, fsz, tsz)
assert out.shape == (3, bsz, fsz, tsz)
return out
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_feature, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_matmul_broadcasting():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_in, n_out)).astype("float32")
weight = torch.from_numpy(weight)
return torch.matmul(inputs.transpose(1, 2), weight)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_matmul_shared_remaining_axes():
n_1, n_2 = 2, 4
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
return torch.matmul(inputs, inputs.transpose(2, 3))
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_1, n_time, n_2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (n_1, None, n_2), "batch_dim_axis": 0, "time_dim_axis": 2, "feature_dim_axis": 3})
def test_spatial_axes_with_same_tag():
n_1, n_2 = 2, 4
n_batch, n_time = 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
x = torch.matmul(inputs, inputs.transpose(2, 3))
x = F.softmax(x, dim=-1)
return x
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_1, n_time, n_2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (n_1, None, n_2), "batch_dim_axis": 0, "time_dim_axis": 2, "feature_dim_axis": 3})
def test_bmm():
n_in, n_out = 11, 13
n_batch, n_time = 3, 5
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
inputs = inputs.transpose(0, 1)
x = inputs.new_zeros(inputs.shape[0], inputs.shape[2], n_out) + 1 # (B, F_in, F_out)
return torch.bmm(inputs, x)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_in)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_in), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_1():
"""
Regular packing and unpacking from batched, padded tensor
"""
n_batch, n_time, n_feat = 3, 5, 7
seq_lens = [5, 4, 3]
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, seq_lens)
output, _ = torch.nn.utils.rnn.pad_packed_sequence(h)
return output + 1
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, returnn_input_seq_lens={0: seq_lens}, inputs_data_kwargs={
"shape": (None, n_feat), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_2():
"""
Packing and unpacking from batched, padded tensor, where the packing is done with :func:`pack_sequence` which actually
requires a list of tensors as input.
"""
n_batch, n_time, n_feat = 3, 5, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
if not getattr(torch, "__returnn__", False):
inputs = list(inputs)
h = torch.nn.utils.rnn.pack_sequence(inputs)
output, _ = torch.nn.utils.rnn.pad_packed_sequence(h, batch_first=True)
return output + 1
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feat), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_3():
"""
Pack and return packed .data
"""
n_batch, n_time, n_feat = 3, 5, 7
seq_lens = [5, 4, 3]
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, seq_lens)
return h.data
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, returnn_input_seq_lens={0: seq_lens}, inputs_data_kwargs={
"shape": (None, n_feat), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_4():
"""
Initialize :class:`PackedSequence` directly using its init
"""
n_batch, n_time, n_feat = 3, 5, 7
seq_lens = [5, 4, 3]
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, seq_lens)
h = torch.nn.utils.rnn.PackedSequence(h.data, h.batch_sizes)
return h.data
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, returnn_input_seq_lens={0: seq_lens}, inputs_data_kwargs={
"shape": (None, n_feat), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_5():
"""
Pack and return packed .data, like :func:`test_packed_sequence_3` but with batch major input
"""
n_batch, n_time, n_feat = 3, 5, 7
seq_lens = [5, 4, 3]
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, seq_lens, batch_first=True)
return h.data
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, returnn_input_seq_lens={0: seq_lens}, inputs_data_kwargs={
"shape": (None, n_feat), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_packed_sequence_6():
"""
Pack with `batch_first=False` and unpack with `batch_first=True`
"""
n_batch, n_time, n_feat = 3, 5, 7
seq_lens = [5, 4, 3]
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, seq_lens)
output, _ = torch.nn.utils.rnn.pad_packed_sequence(h, batch_first=True)
return output + 1
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, returnn_input_seq_lens={0: seq_lens}, inputs_data_kwargs={
"shape": (None, n_feat), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_lstm_with_packed_sequence_input():
n_batch, n_time, n_feat = 3, 5, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
h = torch.nn.utils.rnn.pack_padded_sequence(inputs, [n_time] * n_batch)
output, _ = torch.nn.LSTM(n_feat, n_feat)(h)
return output.data
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_time, n_batch, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feat), "time_dim_axis": 0, "batch_dim_axis": 1, "feature_dim_axis": 2})
def test_t():
n_batch, n_feature, n_time = 3, 5, 17
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (3, 5)).astype("float32")
weight = torch.from_numpy(weight)
weight = weight.t()
return F.relu(inputs)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_feature, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_reshape_ab_c_to_a_bc():
n_batch, n_time, n_feature_1, n_feature_2 = 3, 5, 8, 6
def model_func(wrapped_import, inputs: torch.Tensor):
# test case (..., a*b, c,...) -> (..., a, b*c,...)
return inputs.view(n_batch, n_time, n_feature_1 // 2, n_feature_2 * 2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feature_1, n_feature_2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feature_1, n_feature_2), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_reshape_a_bc_to_ab_c():
n_batch, n_time, n_feature_1, n_feature_2 = 3, 5, 8, 6
def model_func(wrapped_import, inputs: torch.Tensor):
# test case (..., a, b*c,...) -> (..., a*b, c,...)
return inputs.view(n_batch, n_time, n_feature_1 * 2, n_feature_2 // 2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feature_1, n_feature_2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (None, n_feature_1, n_feature_2), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_reshape_a_b_F_to_b_aF():
n_batch, n_time, n_feature_1, n_feature_2 = 3, 5, 8, 6
def model_func(wrapped_import, inputs: torch.Tensor):
# test case (..., a, b, F,...) -> (..., b, a*F,...)
inputs = inputs.transpose(1, 2).contiguous()
return inputs.view(n_batch, n_time, n_feature_1 * n_feature_2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_feature_1, n_time, n_feature_2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"shape": (n_feature_1, None, n_feature_2), "batch_dim_axis": 0, "time_dim_axis": 2, "feature_dim_axis": 3})
def test_reshape_a_b_1_to_a_b():
n_batch, n_time, n_feature = 2, 7, 1
def model_func(wrapped_import, inputs: torch.Tensor):
# test case (a, b, 1) -> (a, b)
out = inputs.view(inputs.shape[:2]) # (B, T, F)
return out
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_time, n_feature)).astype("float32")
verify_torch_and_convert_to_returnn(
model_func, inputs=x, returnn_dummy_input_shape=x.shape,
inputs_data_kwargs={
"shape": (None, n_feature), "batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2})
def test_pad():
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch.nn.functional as F
else:
F = wrapped_import("torch.nn.functional")
inputs = F.pad(inputs, (1, 1, 2, 2))
inputs = F.pad(inputs, (1, 1))
return inputs
x = numpy.zeros((1, 1, 4, 4)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_pad_time_btf():
n_batch, n_time, n_feat = 3, 7, 5
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch.nn.functional as F
else:
F = wrapped_import("torch.nn.functional")
inputs = F.pad(inputs, (0, 0, 2, 2))
return inputs
x = numpy.ones((n_batch, n_time, n_feat)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"batch_dim_axis": 0, "time_dim_axis": 1, "feature_dim_axis": 2, "shape": (None, n_feat)})
def test_constant_pad_1d():
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
mod = torch.nn.ConstantPad1d((4, 1), 0)
return mod(inputs)
x = numpy.zeros((3, 5, 7)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_conv():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
kernel_size = 3
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_out, n_in, kernel_size)).astype("float32")
bias = rnd.normal(0., 1., (n_out,)).astype("float32")
weight = torch.from_numpy(weight)
bias = torch.from_numpy(bias)
return F.conv1d(
inputs,
weight=weight, bias=bias,
stride=2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_depthwise_conv():
n_in, n_out = 12, 12
n_batch, n_time = 3, 7
kernel_size = 3
groups = n_in
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_out, n_in // groups, kernel_size)).astype("float32")
bias = rnd.normal(0., 1., (n_out,)).astype("float32")
weight = torch.from_numpy(weight)
bias = torch.from_numpy(bias)
return F.conv1d(inputs, weight=weight, bias=bias, stride=2, groups=groups)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_conv_no_bias():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
kernel_size = 3
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_out, n_in, kernel_size)).astype("float32")
weight = torch.from_numpy(weight)
return F.conv1d(inputs, weight=weight, stride=2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_conv2d():
n_in, n_out = 11, 13
n_batch, n_time1, n_time2 = 3, 17, 19
kernel_size = (3, 5)
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_out, n_in) + kernel_size).astype("float32")
bias = rnd.normal(0., 1., (n_out,)).astype("float32")
weight = torch.from_numpy(weight)
bias = torch.from_numpy(bias)
return F.conv2d(
inputs,
weight=weight, bias=bias,
stride=2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time1, n_time2)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_functional_conv_transposed():
n_in, n_out = 11, 13
n_batch, n_time = 3, 7
kernel_size = 3
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
rnd = numpy.random.RandomState(42)
weight = rnd.normal(0., 1., (n_in, n_out, kernel_size)).astype("float32")
weight = torch.from_numpy(weight)
return F.conv_transpose1d(inputs, weight=weight, stride=2)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_batch_norm():
n_in, n_batch, n_time = 11, 3, 7
for train in [True, False]:
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.BatchNorm1d(n_in)
if not train:
model.eval()
out = model(inputs)
if train:
model.reset_running_stats() # for the test, such that we start with initial running mean/var
return out
x = numpy.ones((n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, train=train)
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, train=train)
def test_batch_norm_running_stats():
from pytorch_to_returnn.torch.nn import Module as ModuleReturnn
from pytorch_to_returnn.naming import Naming, ModuleEntry
from torch.nn import Module as ModuleTorch
n_in, n_batch, n_time = 11, 3, 7
mean_torch = None
mean_returnn = None
def model_func(wrapped_import, inputs: torch.Tensor):
nonlocal mean_torch, mean_returnn
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.BatchNorm1d(n_in)
out = model(inputs)
if isinstance(model, ModuleTorch):
mean_torch = model.running_mean.detach().cpu().numpy().copy()
elif isinstance(model, ModuleReturnn):
naming = Naming.get_instance()
if naming.import_params_from_torch_namespace: # only then we have the params
module_entry = naming.modules[model]
assert isinstance(module_entry, ModuleEntry)
assert len(module_entry.calls) == 1
call = module_entry.calls[0]
assert call.returnn_layer
mean_returnn = tf.squeeze(call.returnn_layer.params["batch_norm/v2_mean"]).eval()
model.reset_running_stats() # for the test, such that we start with initial running mean/var
return out
x = numpy.ones((n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, train=True)
assert mean_returnn is not None and mean_torch is not None
print(mean_torch)
numpy.testing.assert_allclose(mean_torch[0], 0.1, rtol=0, atol=1e-5) # default momentum 0.1
numpy.testing.assert_allclose(mean_returnn, mean_torch, rtol=0, atol=1e-5)
mean_returnn = mean_torch = None
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, train=True)
assert mean_returnn is not None and mean_torch is not None
print(mean_torch)
numpy.testing.assert_allclose(mean_returnn, mean_torch, rtol=0, atol=1e-5)
def test_fp32_layer_norm():
n_in, n_batch, n_time = 11, 3, 7
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")
# copy of Fp32LayerNorm from fairseq
class Fp32LayerNorm(torch.nn.LayerNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input):
output = F.layer_norm(
input.float(),
self.normalized_shape,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps
)
return output.type_as(input)
model = Fp32LayerNorm(n_in, elementwise_affine=True)
out = inputs.transpose(-2, -1)
out = model(out)
out = out.transpose(-2, -1)
return out
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, n_in, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x, inputs_data_kwargs={
"batch_dim_axis": 0, "time_dim_axis": 2, "feature_dim_axis": 1, "shape": (n_in, None)})
def test_group_norm():
n_batch, n_time = 4, 20
for num_groups, num_channels in [(1, 5), (5, 5)]:
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
else:
torch = wrapped_import("torch")
model = torch.nn.GroupNorm(num_groups, num_channels)
out = model(inputs)
return out
print(f"test for num_groups={num_groups}, num_channels={num_channels}")
rnd = numpy.random.RandomState(42)
x = rnd.normal(0., 1., (n_batch, num_channels, n_time)).astype("float32")
verify_torch_and_convert_to_returnn(model_func, inputs=x)
def test_fp32_group_norm():
n_batch, n_time = 3, 17
for num_groups, num_channels in [(1, 5), (5, 5)]:
def model_func(wrapped_import, inputs: torch.Tensor):
if typing.TYPE_CHECKING or not wrapped_import:
import torch
import torch.nn.functional as F
else:
torch = wrapped_import("torch")
F = wrapped_import("torch.nn.functional")