-
Notifications
You must be signed in to change notification settings - Fork 1
/
mobilenet.py
204 lines (167 loc) · 6.37 KB
/
mobilenet.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
"""
MobileNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
__all__ = ['MobileNet', 'mobilenet_w1', 'mobilenet_w3d4', 'mobilenet_wd2', 'mobilenet_wd4', 'get_mobilenet']
import os
import torch.nn as nn
from common import conv3x3_block, dwsconv3x3_block
class MobileNet(nn.Module):
"""
MobileNet model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
first_stage_stride : bool
Whether stride is used at the first stage.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
first_stage_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000,
dropout=0.0,
global_pool=True):
super(MobileNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
init_block_channels = channels[0][0]
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels[1:]):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and ((i != 0) or first_stage_stride) else 1
stage.add_module("unit{}".format(j + 1), dwsconv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
if global_pool:
pass
else:
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.dropout = dropout
if dropout > 0:
self.dropout_layer = nn.Dropout(p=dropout)
# self.output = nn.Linear(
# in_features=in_channels,
# out_features=num_classes)
self.classifier = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if 'dw_conv.conv' in name:
nn.init.kaiming_normal_(module.weight, mode='fan_in')
elif name == 'init_block.conv' or 'pw_conv.conv' in name:
nn.init.kaiming_normal_(module.weight, mode='fan_out')
elif 'bn' in name:
nn.init.constant_(module.weight, 1)
nn.init.constant_(module.bias, 0)
elif 'output' in name:
nn.init.kaiming_normal_(module.weight, mode='fan_out')
nn.init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
# x = self.output(x)
if self.dropout > 0:
x = self.dropout_layer(x)
x = self.classifier(x)
return x
def get_mobilenet(width_scale,
**kwargs):
"""
Create MobileNet model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers. The same as depth depth_multiplier
"""
channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 512], [1024, 1024]]
first_stage_stride = False
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
net = MobileNet(
channels=channels,
first_stage_stride=first_stage_stride,
**kwargs)
return net
def mobilenet_w1(**kwargs):
"""
1.0 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
return get_mobilenet(width_scale=1.0, **kwargs)
def mobilenet_w3d4(**kwargs):
"""
0.75 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
return get_mobilenet(width_scale=0.75, **kwargs)
def mobilenet_wd2(**kwargs):
"""
0.5 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
return get_mobilenet(width_scale=0.5, **kwargs)
def mobilenet_wd4(**kwargs):
"""
0.25 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
return get_mobilenet(width_scale=0.25, **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mobilenet_w1,
mobilenet_w3d4,
mobilenet_wd2,
mobilenet_wd4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenet_w1 or weight_count == 4231976)
assert (model != mobilenet_w3d4 or weight_count == 2585560)
assert (model != mobilenet_wd2 or weight_count == 1331592)
assert (model != mobilenet_wd4 or weight_count == 470072)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
# _test()
net = mobilenet_w1(in_size=128)
import torch
net.load_state_dict(torch.load("mobilenet_v1_128_tf2torch.pth"), strict=False)