-
Notifications
You must be signed in to change notification settings - Fork 197
/
unet.py
283 lines (224 loc) · 9.89 KB
/
unet.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
import time
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, use_res_connect, expand_ratio=6):
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
self.use_res_connect = use_res_connect
self.conv = nn.Sequential(
nn.Conv2d(inp, inp * expand_ratio, 1, 1, 0, bias=False),
nn.BatchNorm2d(inp * expand_ratio),
nn.ReLU(inplace=True),
nn.Conv2d(inp * expand_ratio,
inp * expand_ratio,
3,
stride,
1,
groups=inp * expand_ratio,
bias=False),
nn.BatchNorm2d(inp * expand_ratio),
nn.ReLU(inplace=True),
nn.Conv2d(inp * expand_ratio, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
)
def forward(self, x):
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x)
class DoubleConvDW(nn.Module):
def __init__(self, in_channels, out_channels, stride=2):
super(DoubleConvDW, self).__init__()
self.double_conv = nn.Sequential(
InvertedResidual(in_channels, out_channels, stride=stride, use_res_connect=False, expand_ratio=2),
InvertedResidual(out_channels, out_channels, stride=1, use_res_connect=True, expand_ratio=2)
)
def forward(self, x):
return self.double_conv(x)
class InConvDw(nn.Module):
def __init__(self, in_channels, out_channels):
super(InConvDw, self).__init__()
self.inconv = nn.Sequential(
InvertedResidual(in_channels, out_channels, stride=1, use_res_connect=False, expand_ratio=2)
)
def forward(self, x):
return self.inconv(x)
class Down(nn.Module):
def __init__(self, in_channels, out_channels):
super(Down, self).__init__()
self.maxpool_conv = nn.Sequential(
DoubleConvDW(in_channels, out_channels, stride=2)
)
def forward(self, x):
return self.maxpool_conv(x)
class Up(nn.Module):
def __init__(self, in_channels, out_channels):
super(Up, self).__init__()
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv = DoubleConvDW(in_channels, out_channels, stride=1)
def forward(self, x1, x2):
x1 = self.up(x1)
diffY = x2.shape[2] - x1.shape[2]
diffX = x2.shape[3] - x1.shape[3]
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2])
x = torch.cat([x1, x2], axis=1)
return self.conv(x)
class OutConv(nn.Module):
def __init__(self, in_channels, out_channels):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
def forward(self, x):
return self.conv(x)
class AudioConvWenet(nn.Module):
def __init__(self):
super(AudioConvWenet, self).__init__()
# ch = [16, 32, 64, 128, 256] # if you want to run this model on a mobile device, use this.
ch = [32, 64, 128, 256, 512]
self.conv1 = InvertedResidual(ch[3], ch[3], stride=1, use_res_connect=True, expand_ratio=2)
self.conv2 = InvertedResidual(ch[3], ch[3], stride=1, use_res_connect=True, expand_ratio=2)
self.conv3 = nn.Conv2d(ch[3], ch[3], kernel_size=3, padding=1, stride=(1,2))
self.bn3 = nn.BatchNorm2d(ch[3])
self.conv4 = InvertedResidual(ch[3], ch[3], stride=1, use_res_connect=True, expand_ratio=2)
self.conv5 = nn.Conv2d(ch[3], ch[4], kernel_size=3, padding=3, stride=2)
self.bn5 = nn.BatchNorm2d(ch[4])
self.relu = nn.ReLU()
self.conv6 = InvertedResidual(ch[4], ch[4], stride=1, use_res_connect=True, expand_ratio=2)
self.conv7 = InvertedResidual(ch[4], ch[4], stride=1, use_res_connect=True, expand_ratio=2)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.relu(self.bn3(self.conv3(x)))
x = self.conv4(x)
x = self.relu(self.bn5(self.conv5(x)))
x = self.conv6(x)
x = self.conv7(x)
return x
class AudioConvHubert(nn.Module):
def __init__(self):
super(AudioConvHubert, self).__init__()
# ch = [16, 32, 64, 128, 256] # if you want to run this model on a mobile device, use this.
ch = [32, 64, 128, 256, 512]
self.conv1 = InvertedResidual(32, ch[1], stride=1, use_res_connect=False, expand_ratio=2)
self.conv2 = InvertedResidual(ch[1], ch[2], stride=1, use_res_connect=False, expand_ratio=2)
self.conv3 = nn.Conv2d(ch[2], ch[3], kernel_size=3, padding=1, stride=(2,2))
self.bn3 = nn.BatchNorm2d(ch[3])
self.conv4 = InvertedResidual(ch[3], ch[3], stride=1, use_res_connect=True, expand_ratio=2)
self.conv5 = nn.Conv2d(ch[3], ch[4], kernel_size=3, padding=3, stride=2)
self.bn5 = nn.BatchNorm2d(ch[4])
self.relu = nn.ReLU()
self.conv6 = InvertedResidual(ch[4], ch[4], stride=1, use_res_connect=True, expand_ratio=2)
self.conv7 = InvertedResidual(ch[4], ch[4], stride=1, use_res_connect=True, expand_ratio=2)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.relu(self.bn3(self.conv3(x)))
x = self.conv4(x)
x = self.relu(self.bn5(self.conv5(x)))
x = self.conv6(x)
x = self.conv7(x)
return x
class Model(nn.Module):
def __init__(self,n_channels=6, mode='hubert'):
super(Model, self).__init__()
self.n_channels = n_channels #BGR
# ch = [16, 32, 64, 128, 256] # if you want to run this model on a mobile device, use this.
ch = [32, 64, 128, 256, 512]
if mode=='hubert':
self.audio_model = AudioConvHubert()
if mode=='wenet':
self.audio_model = AudioConvWenet()
self.fuse_conv = nn.Sequential(
DoubleConvDW(ch[4]*2, ch[4], stride=1),
DoubleConvDW(ch[4], ch[3], stride=1)
)
self.inc = InConvDw(n_channels, ch[0])
self.down1 = Down(ch[0], ch[1])
self.down2 = Down(ch[1], ch[2])
self.down3 = Down(ch[2], ch[3])
self.down4 = Down(ch[3], ch[4])
self.up1 = Up(ch[4], ch[3]//2)
self.up2 = Up(ch[3], ch[2]//2)
self.up3 = Up(ch[2], ch[1]//2)
self.up4 = Up(ch[1], ch[0])
self.outc = OutConv(ch[0], 3)
def forward(self, x, audio_feat):
x1 = self.inc(x)
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
audio_feat = self.audio_model(audio_feat)
x5 = torch.cat([x5, audio_feat], axis=1)
x5 = self.fuse_conv(x5)
x = self.up1(x5, x4)
x = self.up2(x, x3)
x = self.up3(x, x2)
x = self.up4(x, x1)
out = self.outc(x)
out = F.sigmoid(out)
return out
if __name__ == '__main__':
import time
import copy
import onnx
import numpy as np
onnx_path = "./unet.onnx"
from thop import profile, clever_format
def reparameterize_model(model: torch.nn.Module) -> torch.nn.Module:
""" Method returns a model where a multi-branched structure
used in training is re-parameterized into a single branch
for inference.
:param model: MobileOne model in train mode.
:return: MobileOne model in inference mode.
"""
# Avoid editing original graph
model = copy.deepcopy(model)
for module in model.modules():
if hasattr(module, 'reparameterize'):
module.reparameterize()
return model
device = torch.device("cuda")
def check_onnx(torch_out, torch_in, audio):
onnx_model = onnx.load(onnx_path)
onnx.checker.check_model(onnx_model)
import onnxruntime
providers = ["CUDAExecutionProvider"]
ort_session = onnxruntime.InferenceSession(onnx_path, providers=providers)
print(ort_session.get_providers())
ort_inputs = {ort_session.get_inputs()[0].name: torch_in.cpu().numpy(), ort_session.get_inputs()[1].name: audio.cpu().numpy()}
ort_outs = ort_session.run(None, ort_inputs)
np.testing.assert_allclose(torch_out[0].cpu().numpy(), ort_outs[0][0], rtol=1e-03, atol=1e-05)
print("Exported model has been tested with ONNXRuntime, and the result looks good!")
net = Model(6).eval().to(device)
img = torch.zeros([1, 6, 160, 160]).to(device)
audio = torch.zeros([1, 16, 32, 32]).to(device)
# net = reparameterize_model(net)
flops, params = profile(net, (img,audio))
macs, params = clever_format([flops, params], "%3f")
print(macs, params)
# dynamic_axes= {'input':[2, 3], 'output':[2, 3]}
input_dict = {"input": img, "audio": audio}
with torch.no_grad():
torch_out = net(img, audio)
print(torch_out.shape)
torch.onnx.export(net, (img, audio), onnx_path, input_names=['input', "audio"],
output_names=['output'],
# dynamic_axes=dynamic_axes,
# example_outputs=torch_out,
opset_version=11,
export_params=True)
check_onnx(torch_out, img, audio)
# img = torch.zeros([1, 6, 160, 160]).to(device)
# audio = torch.zeros([1, 16, 32, 32]).to(device)
# with torch.no_grad():
# for i in range(100000):
# t1 = time.time()
# out = net(img, audio)
# t2 = time.time()
# # print(out.shape)
# print('time cost::', t2-t1)
# torch.save(net.state_dict(), '1.pth')