forked from osmr/imgclsmob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_gl2tf_conv1x1.py
165 lines (137 loc) · 4.17 KB
/
convert_gl2tf_conv1x1.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
import numpy as np
import mxnet as mx
import tensorflow as tf
class GluonModel(mx.gluon.HybridBlock):
def __init__(self,
**kwargs):
super(GluonModel, self).__init__(**kwargs)
with self.name_scope():
self.conv = mx.gluon.nn.Conv2D(
channels=64,
kernel_size=7,
strides=2,
padding=3,
use_bias=True,
in_channels=3)
def hybrid_forward(self, F, x):
x = self.conv(x)
return x
# def tensorflow_model(x):
#
# padding = 3
# x = tf.pad(x, [[0, 0], [0, 0], [padding, padding], [padding, padding]])
# x = tf.layers.conv2d(
# inputs=x,
# filters=64,
# kernel_size=7,
# strides=2,
# padding='valid',
# data_format='channels_first',
# use_bias=False,
# name='conv')
# return x
def conv2d(x,
in_channels,
out_channels,
kernel_size,
strides=1,
padding=0,
groups=1,
use_bias=True,
name="conv2d"):
"""
Convolution 2D layer wrapper.
Parameters:
----------
x : Tensor
Input tensor.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
name : str, default 'conv2d'
Layer name.
Returns
-------
Tensor
Resulted tensor.
"""
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if isinstance(strides, int):
strides = (strides, strides)
if isinstance(padding, int):
padding = (padding, padding)
if groups != 1:
raise NotImplementedError
if (padding[0] > 0) or (padding[1] > 0):
x = tf.pad(x, [[0, 0], [0, 0], list(padding), list(padding)])
x = tf.layers.conv2d(
inputs=x,
filters=out_channels,
kernel_size=kernel_size,
strides=strides,
padding='valid',
data_format='channels_first',
use_bias=use_bias,
name=name)
return x
def tensorflow_model(x):
x = conv2d(
x=x,
in_channels=3,
out_channels=64,
kernel_size=7,
strides=2,
padding=3,
use_bias=True,
name="conv")
return x
def main():
success = True
for i in range(10):
# w = np.random.randint(10, size=(64, 3, 7, 7)).astype(np.float32)
# x = np.random.randint(10, size=(1, 3, 224, 224)).astype(np.float32)
w = np.random.randn(64, 3, 7, 7).astype(np.float32)
b = np.random.randn(64, ).astype(np.float32)
x = np.random.randn(10, 3, 224, 224).astype(np.float32)
gl_model = GluonModel()
# ctx = mx.cpu()
ctx = mx.gpu(0)
gl_params = gl_model._collect_params_with_prefix()
gl_params['conv.weight']._load_init(mx.nd.array(w, ctx), ctx)
gl_params['conv.bias']._load_init(mx.nd.array(b, ctx), ctx)
gl_x = mx.nd.array(x, ctx)
gl_y = gl_model(gl_x).asnumpy()
xx = tf.placeholder(
dtype=tf.float32,
shape=(None, 3, 224, 224),
name='xx')
tf_model = tensorflow_model(xx)
tf_params = {v.name: v for v in tf.global_variables()}
with tf.Session() as sess:
tf_w = np.transpose(w, axes=(2, 3, 1, 0))
sess.run(tf_params['conv/kernel:0'].assign(tf_w))
sess.run(tf_params['conv/bias:0'].assign(b))
tf_y = sess.run(tf_model, feed_dict={xx: x})
tf.reset_default_graph()
dist = np.sum(np.abs(gl_y - tf_y))
if dist > 1e-5:
success = False
print("i={}, dist={}".format(i, dist))
# print(gl_y)
# print(tf_y)
if success:
print("All ok.")
if __name__ == '__main__':
main()