/
impl.py
executable file
·1900 lines (1531 loc) · 70.2 KB
/
impl.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 numbers
from typing import Optional, Union, List, Tuple, Sequence, Any
from tensorflow.python.ops.image_ops_impl import ResizeMethod
from torch import Tensor
from torch.types import _int, _bool, Number, _dtype, _size
import tensorflow as tf
from tensorflow import keras
import torch
import torch.nn.functional as F
from torch import nn
import numpy as np
from nobuco.commons import ChannelOrder, ChannelOrderingStrategy
from nobuco.funcs import force_tensorflow_order, force_pytorch_order
from nobuco.converters.channel_ordering import set_channel_order, get_channel_order
from nobuco.converters.node_converter import converter
from nobuco.converters.tensor import dims_pytorch2keras, perm_keras2pytorch, \
_dim_make_positive, dim_pytorch2keras, _permute, _flatten, perm_pytorch2keras, perm_compose, \
is_identity_perm, permute_pytorch2keras, _ensure_iterable, perm_identity
from nobuco.converters.ops import hard_sigmoid_pytorch_compatible, hard_swish_pytorch_compatible, \
hard_tanh_pytorch_compatible
@converter(nn.GRU, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def gru(self: nn.GRU, input, hx=None):
assert not self.bidirectional
def reorder(param):
assert param.shape[-1] % 3 == 0
p1, p2, p3 = np.split(param, 3, axis=-1)
return np.concatenate([p2, p1, p3], axis=-1)
grus = []
for i in range(self.num_layers):
weight_ih = self.__getattr__(f'weight_ih_l{i}').detach().numpy().transpose((1, 0))
weight_hh = self.__getattr__(f'weight_hh_l{i}').detach().numpy().transpose((1, 0))
bias_ih = self.__getattr__(f'bias_ih_l{i}').detach().numpy()
bias_hh = self.__getattr__(f'bias_hh_l{i}').detach().numpy()
weight_ih = reorder(weight_ih)
weight_hh = reorder(weight_hh)
bias_ih = reorder(bias_ih)
bias_hh = reorder(bias_hh)
gru = keras.layers.GRU(
units=self.hidden_size,
activation='tanh',
recurrent_activation='sigmoid',
use_bias=self.bias,
dropout=self.dropout,
return_sequences=True,
return_state=True,
time_major=not self.batch_first,
reset_after=True,
unroll=True,
weights=[weight_ih, weight_hh, tf.stack([bias_ih, bias_hh], axis=0)],
)
grus.append(gru)
def func(input, hx=None):
x = input
hxs = []
for i in range(len(grus)):
initial_state = hx[i] if hx is not None else None
x, hxo = grus[i](x, initial_state=initial_state)
hxs.append(hxo)
hxs = tf.stack(hxs, axis=0)
return x, hxs
return func
@converter(nn.LSTM, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def lstm(self: nn.LSTM, input, hx=None):
assert not self.bidirectional
lstms = []
for i in range(self.num_layers):
weight_ih = self.__getattr__(f'weight_ih_l{i}').detach().numpy().transpose((1, 0))
weight_hh = self.__getattr__(f'weight_hh_l{i}').detach().numpy().transpose((1, 0))
bias_ih = self.__getattr__(f'bias_ih_l{i}').detach().numpy()
bias_hh = self.__getattr__(f'bias_hh_l{i}').detach().numpy()
lstm = keras.layers.LSTM(
units=self.hidden_size,
activation='tanh',
recurrent_activation='sigmoid',
use_bias=self.bias,
dropout=self.dropout,
return_sequences=True,
return_state=True,
time_major=not self.batch_first,
unroll=True,
weights=[weight_ih, weight_hh, bias_ih + bias_hh],
)
lstms.append(lstm)
def func(input, hx=None):
x = input
hxs = []
cxs = []
for i in range(len(lstms)):
initial_state = (hx[0][i], hx[1][i]) if hx is not None else None
x, hxo, cxo = lstms[i](x, initial_state=initial_state)
hxs.append(hxo)
cxs.append(cxo)
hxs = tf.stack(hxs, axis=0)
cxs = tf.stack(cxs, axis=0)
return x, (hxs, cxs)
return func
@converter(torch.cat, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def cat(tensors: Union[Tuple[Tensor, ...], List[Tensor]], dim=0, *, out: Optional[Tensor]=None):
num_dims = tensors[0].dim()
dim_keras = dim_pytorch2keras(dim, num_dims)
def func(tensors, dim=0, *, out=None):
if get_channel_order(tensors[0]) == ChannelOrder.TENSORFLOW:
return tf.concat(tensors, axis=dim_keras)
else:
return tf.concat(tensors, axis=dim)
return func
@converter(torch.stack, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def stack(tensors: Union[Tuple[Tensor, ...], List[Tensor]], dim: _int=0, *, out: Optional[Tensor]=None):
def func(tensors, dim=0, *, out=None):
return tf.stack(tensors, axis=dim)
return func
@converter(torch.Tensor.split, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def split(self, split_size, dim=0):
num_dims = self.dim()
def func(self, split_size, dim=0):
if get_channel_order(self) == ChannelOrder.TENSORFLOW:
dim = dim_pytorch2keras(dim, num_dims)
return tf.split(self, num_or_size_splits=split_size, axis=dim)
return func
@converter(torch.Tensor.repeat, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def repeat(self, *sizes):
def func(self, *sizes):
if get_channel_order(self) == ChannelOrder.TENSORFLOW:
sizes = permute_pytorch2keras(sizes)
return tf.tile(self, sizes)
return func
@converter(torch.Tensor.expand, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def expand(self, *sizes):
def get_broadcast_shape(sizes, tensor_shape):
tensor_shape = list(reversed(tensor_shape))
res = []
for i, s in enumerate(reversed(sizes)):
if s == -1:
s = tensor_shape[i]
res.append(s)
return list(reversed(res))
def func(self, *sizes):
sizes = _flatten(sizes)
broadcast_shape = get_broadcast_shape(sizes, self.shape)
return tf.broadcast_to(self, broadcast_shape)
return func
@converter(torch.Tensor.expand_as, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def expand_as(self, other):
def get_broadcast_shape(sizes, tensor_shape):
tensor_shape = list(reversed(tensor_shape))
res = []
for i, s in enumerate(reversed(sizes)):
if s == -1:
s = tensor_shape[i]
res.append(s)
return list(reversed(res))
def func(self, other):
broadcast_shape = get_broadcast_shape(other.shape, self.shape)
return tf.broadcast_to(self, broadcast_shape)
return func
@converter(torch.zeros_like, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def zeros_like(input: Tensor, *, memory_format=None, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False):
def func(input: Tensor, *, memory_format=None, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False):
tf_type = dtype_pytorch2keras(dtype)
return tf.zeros_like(input, dtype=tf_type)
return func
@converter(torch.Tensor.new_empty, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def new_empty(self, size, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False):
def func(self, size, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False):
if dtype is not None:
dtype = dtype_pytorch2keras(dtype)
else:
dtype = self.dtype
return tf.zeros(size, dtype=dtype)
return func
@converter(torch.Tensor.new_full, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def new_full(self, size, fill_value, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False):
def func(self, size, fill_value, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False):
if dtype is not None:
dtype = dtype_pytorch2keras(dtype)
else:
dtype = self.dtype
res = tf.fill(size, fill_value)
res = tf.cast(res, dtype)
return res
return func
@converter(torch.full_like, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def full_like(input: Tensor, fill_value: Number, *, memory_format=None, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False):
def func(input: Tensor, fill_value: Number, *, memory_format=None, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False):
if dtype is not None:
dtype = dtype_pytorch2keras(dtype)
else:
dtype = input.dtype
res = tf.fill(input.shape, fill_value)
res = tf.cast(res, dtype)
return res
return func
@converter(torch.roll, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def roll(input: Tensor, shifts: Union[_int, _size], dims: Union[_int, _size]=()):
assert isinstance(shifts, _int) and isinstance(dims, _int)
n_dims = input.dim()
def func(input, shifts, dims=()):
if get_channel_order(input) == ChannelOrder.TENSORFLOW:
dims = dim_pytorch2keras(dims, n_dims)
return tf.roll(input, shift=shifts, axis=dims)
return func
@converter(torch.Tensor.unbind, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def unbind(self, dim=0):
def func(self, dim=0):
return tf.unstack(self, axis=dim)
return func
# TODO: add support for 'negative' paddings
@converter(F.pad, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def pad(input: Tensor, pad: List[int], mode: str = "constant", value: float = 0.0):
n_dims = input.dim()
pad_dims = len(pad) // 2
assert len(pad) % 2 == 0
assert pad_dims <= n_dims
pad_full = []
for i in range(pad_dims):
pad_full.append(pad[2*i:2*i + 2])
for i in range(n_dims - pad_dims):
pad_full.append([0, 0])
pad_full = list(reversed(pad_full))
# pad_full_pos = [(max(s, 0), max(e, 0)) for s, e in pad_full]
# pad_full_neg = [(max(-s, 0), max(-e, 0)) for s, e in pad_full]
def func(input, pad, mode="constant", value=0.0):
pad = pad_full
if get_channel_order(input) == ChannelOrder.TENSORFLOW:
pad = permute_pytorch2keras(pad)
x = tf.pad(input, pad)
return x
return func
@converter(torch.Tensor.flatten, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def flatten(self, start_dim=0, end_dim=-1):
def func(self, start_dim=0, end_dim=-1):
start_shape = self.shape[:start_dim]
n_dims = len(self.shape)
end_dim = _dim_make_positive(end_dim, n_dims)
if end_dim < n_dims-1:
end_shape = self.shape[end_dim+1:]
else:
end_shape = []
return tf.reshape(self, (*start_shape, -1, *end_shape))
return func
@converter(torch.mean, torch.Tensor.mean, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def mean(input: Tensor, dim=None, keepdim: _bool = False, *, dtype: Optional[_dtype] = None, out: Optional[Tensor] = None):
def func(input, dim=None, keepdim=False, *, dtype=None, out=None):
if isinstance(dim, numbers.Number):
dim = [dim]
return tf.reduce_mean(input, axis=dim, keepdims=keepdim)
return func
@converter(torch.abs, torch.Tensor.abs, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def abs(input: Tensor, *, out: Optional[Tensor]=None):
def func(input, *, out=None):
return tf.abs(input)
return func
@converter(nn.Conv1d)
def conv1d(self, input: Tensor):
weight = self.weight
bias = self.bias
groups = self.groups
padding = self.padding
stride = self.stride
dilation = self.dilation
out_filters, in_filters, kw = weight.shape
weights = weight.detach().numpy()
weights = weights.transpose((2, 1, 0))
if bias is not None:
biases = bias.detach().numpy()
params = [weights, biases]
use_bias = True
else:
params = [weights]
use_bias = False
if isinstance(padding, numbers.Number):
padding = (padding,)
if padding != (0,) and padding != 'valid':
pad_layer = keras.layers.ZeroPadding1D(padding[0])
else:
pad_layer = None
if groups == out_filters and groups != 1:
conv = keras.layers.DepthwiseConv1D(kernel_size=kw,
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
elif groups == 1:
conv = keras.layers.Conv1D(filters=out_filters,
kernel_size=kw,
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
else:
def split_params(params, groups, axis):
params_split = [np.split(p, groups, axis=axis) for p in params]
return list(zip(*params_split))
params_split = split_params(params, groups, axis=-1)
def grouped_conv1d(inputs, filters, kernel_size, strides, groups, dilation=dilation):
splits = tf.split(inputs, groups, axis=-1)
convolved_splits = [
keras.layers.Conv1D(filters // groups,
kernel_size=kernel_size,
strides=strides,
padding='valid',
dilation_rate=dilation,
use_bias=use_bias,
weights=params_split[i]
)(split)
for i, split in enumerate(splits)
]
return tf.concat(convolved_splits, -1)
conv = lambda x: grouped_conv1d(x, out_filters, kernel_size=kw, strides=stride, groups=groups, dilation=dilation)
def func(input):
if pad_layer is not None:
input = pad_layer(input)
output = conv(input)
return output
return func
# @converter(F.conv1d)
# def conv1d(input: Tensor, weight: Tensor, bias: Optional[Tensor]=None, stride: Union[_int, _size]=1, padding: str="valid", dilation: Union[_int, _size]=1, groups: _int=1):
# out_filters, in_filters, kw = weight.shape
# weights = weight.detach().numpy()
# weights = weights.transpose((2, 1, 0))
#
# if bias is not None:
# biases = bias.detach().numpy()
# params = [weights, biases]
# use_bias = True
# else:
# params = [weights]
# use_bias = False
#
# if padding != 0:
# pad_layer = keras.layers.ZeroPadding1D(padding)
# else:
# pad_layer = None
#
# conv = keras.layers.Conv1D(out_filters, kernel_size=kw,
# strides=stride, padding='valid',
# # dilation_rate=dilations, groups=groups,
# use_bias=use_bias,
# weights=params
# )
#
# def func(input, *args, **kwargs):
# if pad_layer is not None:
# input = pad_layer(input)
# return conv(input)
# return func
@converter(nn.Conv2d)
def conv2d(self, input: Tensor):
weight = self.weight
bias = self.bias
groups = self.groups
padding = self.padding
stride = self.stride
dilation = self.dilation
out_filters, in_filters, kh, kw = weight.shape
weights = weight.detach().numpy()
if groups == out_filters and groups != 1:
weights = tf.transpose(weights, (2, 3, 0, 1))
elif groups == 1:
weights = tf.transpose(weights, (2, 3, 1, 0))
else:
weights = tf.transpose(weights, (2, 3, 1, 0))
if bias is not None:
biases = bias.detach().numpy()
params = [weights, biases]
use_bias = True
else:
params = [weights]
use_bias = False
if padding != 0 and padding != (0, 0) and padding != 'valid':
pad_layer = keras.layers.ZeroPadding2D(padding)
else:
pad_layer = None
if groups == out_filters and groups != 1:
conv = keras.layers.DepthwiseConv2D(kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
elif groups == 1:
conv = keras.layers.Conv2D(filters=out_filters,
kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
else:
def split_params(params, groups, axis):
params_split = [np.split(p, groups, axis=axis) for p in params]
return list(zip(*params_split))
params_split = split_params(params, groups, axis=-1)
def grouped_conv2d(inputs, filters, kernel_size, strides, groups, dilation=dilation):
splits = tf.split(inputs, groups, axis=-1)
convolved_splits = [
keras.layers.Conv2D(filters // groups,
kernel_size=kernel_size,
strides=strides,
padding='valid',
dilation_rate=dilation,
use_bias=use_bias,
weights=params_split[i]
)(split)
for i, split in enumerate(splits)
]
return tf.concat(convolved_splits, -1)
conv = lambda x: grouped_conv2d(x, out_filters, kernel_size=(kh, kw), strides=stride, groups=groups, dilation=dilation)
def func(input):
if pad_layer is not None:
input = pad_layer(input)
output = conv(input)
return output
return func
@converter(F.conv2d)
def conv2d(input: Tensor, weight: Tensor, bias: Optional[Tensor] = None, stride: Union[_int, _size] = 1,
padding: str = "valid", dilation: Union[_int, _size] = 1, groups: _int = 1):
out_filters, in_filters, kh, kw = weight.shape
weights = weight.detach().numpy()
if groups == out_filters and groups != 1:
weights = tf.transpose(weights, (2, 3, 0, 1))
elif groups == 1:
weights = tf.transpose(weights, (2, 3, 1, 0))
else:
weights = tf.transpose(weights, (2, 3, 1, 0))
if bias is not None:
biases = bias.detach().numpy()
params = [weights, biases]
use_bias = True
else:
params = [weights]
use_bias = False
if padding != 0 and padding != (0, 0) and padding != 'valid':
pad_layer = keras.layers.ZeroPadding2D(padding)
else:
pad_layer = None
if groups == out_filters and groups != 1:
conv = keras.layers.DepthwiseConv2D(kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
elif groups == 1:
conv = keras.layers.Conv2D(filters=out_filters,
kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=groups,
use_bias=use_bias,
weights=params
)
else:
def split_params(params, groups, axis):
params_split = [np.split(p, groups, axis=axis) for p in params]
return list(zip(*params_split))
params_split = split_params(params, groups, axis=-1)
def grouped_conv2d(inputs, filters, kernel_size, strides, groups, dilation=dilation):
splits = tf.split(inputs, groups, axis=-1)
convolved_splits = [
keras.layers.Conv2D(filters // groups,
kernel_size=kernel_size,
strides=strides,
padding='valid',
dilation_rate=dilation,
use_bias=use_bias,
weights=params_split[i]
)(split)
for i, split in enumerate(splits)
]
return tf.concat(convolved_splits, -1)
conv = lambda x: grouped_conv2d(x, out_filters, kernel_size=(kh, kw), strides=stride, groups=groups, dilation=dilation)
def func(input, *args, **kwargs):
if pad_layer is not None:
input = pad_layer(input)
output = conv(input)
return output
return func
@converter(nn.ConvTranspose2d)
def convTranspose2d(self, input: Tensor, output_size: Optional[List[int]] = None):
weight = self.weight
bias = self.bias
groups = self.groups
padding = self.padding
stride = self.stride
dilation = self.dilation
output_padding = self.output_padding
in_filters, out_filters, kh, kw = weight.shape
weights = weight.detach().numpy()
if groups == 1:
weights = weights.transpose((2, 3, 1, 0))
elif groups == in_filters:
weights = weights.transpose((2, 3, 0, 1))
else:
weights = weights.transpose((2, 3, 1, 0))
if bias is not None:
biases = bias.detach().numpy()
params = [weights, biases]
use_bias = True
else:
params = [weights]
use_bias = False
if isinstance(dilation, numbers.Number):
dilation = (dilation, dilation)
if isinstance(padding, numbers.Number):
padding = (padding, padding)
if isinstance(output_padding, numbers.Number):
output_padding = (output_padding, output_padding)
if padding != (0, 0):
pad = (dilation[0] * (kh - 1) - padding[0], dilation[1] * (kw - 1) - padding[1])
pad_layer = keras.layers.ZeroPadding2D(pad)
else:
pad_layer = None
pad_layer = None
if groups == 1:
conv = keras.layers.Conv2DTranspose(out_filters,
kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=1,
use_bias=use_bias,
weights=params
)
elif groups == in_filters and out_filters == 1:
weights = params[0]
weights_full = np.zeros(shape=(*weights.shape[:-1], groups))
for i in range(groups):
weights_full[..., i, i] = weights[..., i, 0]
params[0] = weights_full
conv = keras.layers.Conv2DTranspose(out_filters*groups,
kernel_size=(kh, kw),
strides=stride,
padding='valid',
dilation_rate=dilation,
groups=1,
use_bias=use_bias,
weights=params
)
else:
raise Exception('Unsupprorted # groups:', groups)
def func(input: Tensor, output_size: Optional[List[int]] = None):
assert output_size is None
if pad_layer is not None:
input = pad_layer(input)
x = conv(input)
if output_padding != (0, 0):
x = x[:, output_padding[0]:, output_padding[1]:, :]
return x
return func
# # FIXME: not thoroughly tested
# @converter(F.conv_transpose2d)
# def conv_transpose2d(input: Tensor, weight: Tensor, bias: Optional[Tensor]=None,
# stride: Union[_int, _size]=1, padding: Union[_int, _size]=0, output_padding: Union[_int, _size]=0,
# groups: _int=1, dilation: Union[_int, _size]=1):
#
# in_filters, out_filters, kh, kw = weight.shape
# weights = weight.detach().numpy()
#
# if groups == 1:
# weights = weights.transpose((2, 3, 1, 0))
# elif groups == in_filters:
# weights = weights.transpose((2, 3, 0, 1))
# else:
# weights = weights.transpose((2, 3, 1, 0))
#
# if bias is not None:
# biases = bias.detach().numpy()
# params = [weights, biases]
# use_bias = True
# else:
# params = [weights]
# use_bias = False
#
# if isinstance(dilation, numbers.Number):
# dilation = (dilation, dilation)
#
# if isinstance(padding, numbers.Number):
# padding = (padding, padding)
#
# if isinstance(output_padding, numbers.Number):
# output_padding = (output_padding, output_padding)
#
# if padding != (0, 0):
# pad = (dilation[0] * (kh - 1) - padding[0], dilation[1] * (kw - 1) - padding[1])
# pad_layer = keras.layers.ZeroPadding2D(pad)
# else:
# pad_layer = None
# pad_layer = None
#
# if groups == 1:
# conv = keras.layers.Conv2DTranspose(out_filters,
# kernel_size=(kh, kw),
# strides=stride,
# padding='valid',
# dilation_rate=dilation,
# groups=1,
# use_bias=use_bias,
# weights=params
# )
# elif groups == in_filters and out_filters == 1:
# weights = params[0]
#
# weights_full = np.zeros(shape=(*weights.shape[:-1], groups))
# for i in range(groups):
# weights_full[..., i, i] = weights[..., i, 0]
# params[0] = weights_full
#
# conv = keras.layers.Conv2DTranspose(out_filters*groups,
# kernel_size=(kh, kw),
# strides=stride,
# padding='valid',
# dilation_rate=dilation,
# groups=1,
# use_bias=use_bias,
# weights=params
# )
# else:
# raise Exception('Unsupprorted # groups:', groups)
#
# # def split_params(params, groups, axis):
# # params_split = [np.split(p, groups, axis=axis) for p in params]
# # return list(zip(*params_split))
# #
# # params_split = split_params(params, groups, axis=-2)
# #
# # def grouped_conv2d_transpose(inputs, filters, kernel_size, strides, groups, dilation=dilation):
# # splits = tf.split(inputs, groups, axis=-1)
# # convolved_splits = [
# # keras.layers.Conv2DTranspose(filters // groups,
# # kernel_size=kernel_size,
# # strides=strides,
# # padding='same',
# # dilation_rate=dilation,
# # use_bias=use_bias,
# # weights=params_split[i]
# # )(split)
# # for i, split in enumerate(splits)
# # ]
# # return tf.concat(convolved_splits, -1)
# #
# # conv = lambda x: grouped_conv2d_transpose(x, out_filters*groups, kernel_size=(kh, kw), strides=stride, groups=groups, dilation=dilation)
#
# # FIXME!
# def func(input, *args, **kwargs):
# if pad_layer is not None:
# input = pad_layer(input)
#
# x = conv(input)
#
# if output_padding != (0, 0):
# x = x[:, output_padding[0]:, output_padding[1]:, :]
# return x
# return func
@converter(nn.Linear, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def linear(self, input: Tensor):
out_filters, in_filters = self.weight.shape
weights = self.weight.detach().numpy()
weights = weights.transpose(1, 0)
biases = self.bias
if biases is not None:
biases = self.bias.detach().numpy()
params = [weights, biases]
else:
params = [weights]
return keras.layers.Dense(out_filters, weights=params)
# @converter(torch.nn.functional.linear, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
# def linear(input, weight, bias, out=None):
# out_filters, in_filters = weight.shape
# weights = weight.detach().numpy()
# weights = weights.transpose(1, 0)
#
# if bias is not None:
# biases = bias.detach().numpy()
# else:
# biases = np.zeros(shape=(out_filters,))
#
# layer = keras.layers.Dense(out_filters, weights=[weights, biases])
#
# def func(input, weight, bias, out=None):
# return layer(input)
# return func
@converter(torch.matmul, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def matmul(input: Tensor, other: Tensor, *, out: Optional[Tensor]=None):
def func(input, other, *, out=None):
return tf.linalg.matmul(input, other)
return func
@converter(torch.Tensor.matmul, torch.Tensor.__matmul__, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def matmul(self, tensor2):
def func(self, tensor2):
return tf.linalg.matmul(self, tensor2)
return func
@converter(torch.dot, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def dot(input: Tensor, tensor: Tensor, *, out: Optional[Tensor]=None):
def func(input, tensor, *, out=None):
return tf.linalg.tensordot(input, tensor, axes=1)
return func
@converter(torch.mv, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def mv(input: Tensor, vec: Tensor, *, out: Optional[Tensor]=None):
def func(input, vec, *, out=None):
return tf.linalg.tensordot(input, vec, axes=1)
return func
@converter(torch.bmm, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def bmm(input: Tensor, mat2: Tensor, *, out: Optional[Tensor]=None):
def func(input, mat2, *, out=None):
return tf.linalg.matmul(input, mat2)
return func
@converter(torch.einsum, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def einsum(*args: Any):
def func(*args: Any):
equation = args[0]
operands = args[1:]
return keras.layers.Lambda(lambda operands: tf.einsum(equation, *operands))(operands)
return func
@converter(torch.Tensor.triu, torch.Tensor.triu_, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def triu(self, diagonal=0):
def func(self, diagonal=0):
return keras.layers.Lambda(lambda x: tf.experimental.numpy.triu(x, k=diagonal))(self)
return func
# NB: tensorflow and pytorch implementations of batchnorm behave differently in train mode
@converter(nn.BatchNorm1d, nn.BatchNorm2d)
def batchNorm1d(self, input: Tensor):
momentum = self.momentum
epsilon = self.eps
weight = self.weight.detach().numpy()
bias = self.bias.detach().numpy()
running_mean = self.running_mean.detach().numpy()
running_var = self.running_var.detach().numpy()
layer = keras.layers.BatchNormalization(momentum=1 - momentum, epsilon=epsilon, weights=[weight, bias, running_mean, running_var])
return layer
# def func(input, *args, **kwargs):
# return (input - running_mean) / (tf.sqrt(running_var + epsilon)) * weight + bias
# return func
# @converter(F.batch_norm)
# def batch_norm(input: Tensor,
# running_mean: Optional[Tensor], running_var: Optional[Tensor],
# weight: Optional[Tensor] = None, bias: Optional[Tensor] = None,
# training: bool = False, momentum: float = 0.1, eps: float = 1e-5):
# weight = weight.detach().numpy()
# bias = bias.detach().numpy()
# running_mean = running_mean.detach().numpy()
# running_var = running_var.detach().numpy()
# bn = keras.layers.BatchNormalization(momentum=1 - momentum, epsilon=eps, weights=[weight, bias, running_mean, running_var])
#
# def func(input, *args, **kwargs):
# return bn(input)
# # return (input - running_mean) / (tf.sqrt(running_var + eps)) * weight + bias
# return func
@converter(F.layer_norm, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def layer_norm(input: Tensor,
normalized_shape: List[int],
weight: Optional[Tensor] = None,
bias: Optional[Tensor] = None,
eps: float = 1e-5
):
assert len(normalized_shape) == 1
weight = weight.detach().numpy()
bias = bias.detach().numpy()
layer = keras.layers.LayerNormalization(axis=-1, epsilon=eps, weights=[weight, bias])
def func(input, *args, **kwargs):
return layer(input)
return func
@converter(F.embedding, channel_ordering_strategy=ChannelOrderingStrategy.FORCE_PYTORCH_ORDER)
def embedding(input: Tensor, weight: Tensor, padding_idx: Optional[int] = None, max_norm: Optional[float] = None,
norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False):
input_dim, output_dim = weight.shape
weight = weight.detach().numpy()
layer = keras.layers.Embedding(input_dim, output_dim, weights=[weight])
def func(input, weight, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False):
return layer(input)
return func
@converter(nn.Identity, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def identity(self, input: Tensor):
def func(input):
return input
return func
@converter(torch.nn.modules.dropout.Dropout, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def dropout(self, input: Tensor):
return keras.layers.Dropout(rate=self.p)
@converter(F.dropout, channel_ordering_strategy=ChannelOrderingStrategy.MINIMUM_TRANSPOSITIONS)
def dropout(input: Tensor, p: float = 0.5, training: bool = True, inplace: bool = False):
def func(input, p=0.5, training=True, inplace=False):
return keras.layers.Dropout(rate=p)(input)
return func
# @converter(nn.MaxPool2d)
# def maxPool2D(self, input: Tensor):
# kernel_size = self.kernel_size
# stride = self.stride
# return keras.layers.MaxPool2D(pool_size=kernel_size, strides=stride)
@converter(torch.max_pool2d)
def max_pool_2d(input: Tensor, kernel_size: Union[_int, _size], stride: Union[_int, _size]=(), padding: Union[_int, _size]=0, dilation: Union[_int, _size]=1, ceil_mode: _bool=False):
if isinstance(kernel_size, numbers.Number):
kernel_size = (kernel_size, kernel_size)
if isinstance(dilation, numbers.Number):
dilation = (dilation, dilation)
if isinstance(padding, numbers.Number):
padding = (padding, padding)
if padding != (0, 0):
kh, kw = kernel_size
pad = (dilation[0] * (kh - 1) - padding[0], dilation[1] * (kw - 1) - padding[1])
pad_layer = keras.layers.ZeroPadding2D(pad)
else:
pad_layer = None
def func(input, kernel_size, stride=(), padding=0, dilation=1, ceil_mode=False):
if pad_layer is not None:
input = pad_layer(input)
return keras.layers.MaxPool2D(pool_size=kernel_size, strides=stride, padding='valid')(input)
return func
@converter(F.avg_pool2d)
def avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None):
if isinstance(kernel_size, numbers.Number):
kernel_size = (kernel_size, kernel_size)
if isinstance(padding, numbers.Number):
padding = (padding, padding)
if padding != (0, 0):
kh, kw = kernel_size
pad = ((kh - 1) - padding[0], (kw - 1) - padding[1])
pad_layer = keras.layers.ZeroPadding2D(pad)
else:
pad_layer = None
def func(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None):
if pad_layer is not None:
input = pad_layer(input)
return keras.layers.AvgPool2D(pool_size=kernel_size, strides=stride)(input)
return func