Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

mobilenetv3.py 16 KB

You have to be logged in to leave a comment. Sign In
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
  1. from functools import partial
  2. from typing import Any, Callable, List, Optional, Sequence
  3. import torch
  4. from torch import nn, Tensor
  5. from ..ops.misc import Conv2dNormActivation, SqueezeExcitation as SElayer
  6. from ..transforms._presets import ImageClassification
  7. from ..utils import _log_api_usage_once
  8. from ._api import register_model, Weights, WeightsEnum
  9. from ._meta import _IMAGENET_CATEGORIES
  10. from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface
  11. __all__ = [
  12. "MobileNetV3",
  13. "MobileNet_V3_Large_Weights",
  14. "MobileNet_V3_Small_Weights",
  15. "mobilenet_v3_large",
  16. "mobilenet_v3_small",
  17. ]
  18. class InvertedResidualConfig:
  19. # Stores information listed at Tables 1 and 2 of the MobileNetV3 paper
  20. def __init__(
  21. self,
  22. input_channels: int,
  23. kernel: int,
  24. expanded_channels: int,
  25. out_channels: int,
  26. use_se: bool,
  27. activation: str,
  28. stride: int,
  29. dilation: int,
  30. width_mult: float,
  31. ):
  32. self.input_channels = self.adjust_channels(input_channels, width_mult)
  33. self.kernel = kernel
  34. self.expanded_channels = self.adjust_channels(expanded_channels, width_mult)
  35. self.out_channels = self.adjust_channels(out_channels, width_mult)
  36. self.use_se = use_se
  37. self.use_hs = activation == "HS"
  38. self.stride = stride
  39. self.dilation = dilation
  40. @staticmethod
  41. def adjust_channels(channels: int, width_mult: float):
  42. return _make_divisible(channels * width_mult, 8)
  43. class InvertedResidual(nn.Module):
  44. # Implemented as described at section 5 of MobileNetV3 paper
  45. def __init__(
  46. self,
  47. cnf: InvertedResidualConfig,
  48. norm_layer: Callable[..., nn.Module],
  49. se_layer: Callable[..., nn.Module] = partial(SElayer, scale_activation=nn.Hardsigmoid),
  50. ):
  51. super().__init__()
  52. if not (1 <= cnf.stride <= 2):
  53. raise ValueError("illegal stride value")
  54. self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels
  55. layers: List[nn.Module] = []
  56. activation_layer = nn.Hardswish if cnf.use_hs else nn.ReLU
  57. # expand
  58. if cnf.expanded_channels != cnf.input_channels:
  59. layers.append(
  60. Conv2dNormActivation(
  61. cnf.input_channels,
  62. cnf.expanded_channels,
  63. kernel_size=1,
  64. norm_layer=norm_layer,
  65. activation_layer=activation_layer,
  66. )
  67. )
  68. # depthwise
  69. stride = 1 if cnf.dilation > 1 else cnf.stride
  70. layers.append(
  71. Conv2dNormActivation(
  72. cnf.expanded_channels,
  73. cnf.expanded_channels,
  74. kernel_size=cnf.kernel,
  75. stride=stride,
  76. dilation=cnf.dilation,
  77. groups=cnf.expanded_channels,
  78. norm_layer=norm_layer,
  79. activation_layer=activation_layer,
  80. )
  81. )
  82. if cnf.use_se:
  83. squeeze_channels = _make_divisible(cnf.expanded_channels // 4, 8)
  84. layers.append(se_layer(cnf.expanded_channels, squeeze_channels))
  85. # project
  86. layers.append(
  87. Conv2dNormActivation(
  88. cnf.expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None
  89. )
  90. )
  91. self.block = nn.Sequential(*layers)
  92. self.out_channels = cnf.out_channels
  93. self._is_cn = cnf.stride > 1
  94. def forward(self, input: Tensor) -> Tensor:
  95. result = self.block(input)
  96. if self.use_res_connect:
  97. result += input
  98. return result
  99. class MobileNetV3(nn.Module):
  100. def __init__(
  101. self,
  102. inverted_residual_setting: List[InvertedResidualConfig],
  103. last_channel: int,
  104. num_classes: int = 1000,
  105. block: Optional[Callable[..., nn.Module]] = None,
  106. norm_layer: Optional[Callable[..., nn.Module]] = None,
  107. dropout: float = 0.2,
  108. **kwargs: Any,
  109. ) -> None:
  110. """
  111. MobileNet V3 main class
  112. Args:
  113. inverted_residual_setting (List[InvertedResidualConfig]): Network structure
  114. last_channel (int): The number of channels on the penultimate layer
  115. num_classes (int): Number of classes
  116. block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet
  117. norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use
  118. dropout (float): The droupout probability
  119. """
  120. super().__init__()
  121. _log_api_usage_once(self)
  122. if not inverted_residual_setting:
  123. raise ValueError("The inverted_residual_setting should not be empty")
  124. elif not (
  125. isinstance(inverted_residual_setting, Sequence)
  126. and all([isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting])
  127. ):
  128. raise TypeError("The inverted_residual_setting should be List[InvertedResidualConfig]")
  129. if block is None:
  130. block = InvertedResidual
  131. if norm_layer is None:
  132. norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01)
  133. layers: List[nn.Module] = []
  134. # building first layer
  135. firstconv_output_channels = inverted_residual_setting[0].input_channels
  136. layers.append(
  137. Conv2dNormActivation(
  138. 3,
  139. firstconv_output_channels,
  140. kernel_size=3,
  141. stride=2,
  142. norm_layer=norm_layer,
  143. activation_layer=nn.Hardswish,
  144. )
  145. )
  146. # building inverted residual blocks
  147. for cnf in inverted_residual_setting:
  148. layers.append(block(cnf, norm_layer))
  149. # building last several layers
  150. lastconv_input_channels = inverted_residual_setting[-1].out_channels
  151. lastconv_output_channels = 6 * lastconv_input_channels
  152. layers.append(
  153. Conv2dNormActivation(
  154. lastconv_input_channels,
  155. lastconv_output_channels,
  156. kernel_size=1,
  157. norm_layer=norm_layer,
  158. activation_layer=nn.Hardswish,
  159. )
  160. )
  161. self.features = nn.Sequential(*layers)
  162. self.avgpool = nn.AdaptiveAvgPool2d(1)
  163. self.classifier = nn.Sequential(
  164. nn.Linear(lastconv_output_channels, last_channel),
  165. nn.Hardswish(inplace=True),
  166. nn.Dropout(p=dropout, inplace=True),
  167. nn.Linear(last_channel, num_classes),
  168. )
  169. for m in self.modules():
  170. if isinstance(m, nn.Conv2d):
  171. nn.init.kaiming_normal_(m.weight, mode="fan_out")
  172. if m.bias is not None:
  173. nn.init.zeros_(m.bias)
  174. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  175. nn.init.ones_(m.weight)
  176. nn.init.zeros_(m.bias)
  177. elif isinstance(m, nn.Linear):
  178. nn.init.normal_(m.weight, 0, 0.01)
  179. nn.init.zeros_(m.bias)
  180. def _forward_impl(self, x: Tensor) -> Tensor:
  181. x = self.features(x)
  182. x = self.avgpool(x)
  183. x = torch.flatten(x, 1)
  184. x = self.classifier(x)
  185. return x
  186. def forward(self, x: Tensor) -> Tensor:
  187. return self._forward_impl(x)
  188. def _mobilenet_v3_conf(
  189. arch: str, width_mult: float = 1.0, reduced_tail: bool = False, dilated: bool = False, **kwargs: Any
  190. ):
  191. reduce_divider = 2 if reduced_tail else 1
  192. dilation = 2 if dilated else 1
  193. bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult)
  194. adjust_channels = partial(InvertedResidualConfig.adjust_channels, width_mult=width_mult)
  195. if arch == "mobilenet_v3_large":
  196. inverted_residual_setting = [
  197. bneck_conf(16, 3, 16, 16, False, "RE", 1, 1),
  198. bneck_conf(16, 3, 64, 24, False, "RE", 2, 1), # C1
  199. bneck_conf(24, 3, 72, 24, False, "RE", 1, 1),
  200. bneck_conf(24, 5, 72, 40, True, "RE", 2, 1), # C2
  201. bneck_conf(40, 5, 120, 40, True, "RE", 1, 1),
  202. bneck_conf(40, 5, 120, 40, True, "RE", 1, 1),
  203. bneck_conf(40, 3, 240, 80, False, "HS", 2, 1), # C3
  204. bneck_conf(80, 3, 200, 80, False, "HS", 1, 1),
  205. bneck_conf(80, 3, 184, 80, False, "HS", 1, 1),
  206. bneck_conf(80, 3, 184, 80, False, "HS", 1, 1),
  207. bneck_conf(80, 3, 480, 112, True, "HS", 1, 1),
  208. bneck_conf(112, 3, 672, 112, True, "HS", 1, 1),
  209. bneck_conf(112, 5, 672, 160 // reduce_divider, True, "HS", 2, dilation), # C4
  210. bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation),
  211. bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation),
  212. ]
  213. last_channel = adjust_channels(1280 // reduce_divider) # C5
  214. elif arch == "mobilenet_v3_small":
  215. inverted_residual_setting = [
  216. bneck_conf(16, 3, 16, 16, True, "RE", 2, 1), # C1
  217. bneck_conf(16, 3, 72, 24, False, "RE", 2, 1), # C2
  218. bneck_conf(24, 3, 88, 24, False, "RE", 1, 1),
  219. bneck_conf(24, 5, 96, 40, True, "HS", 2, 1), # C3
  220. bneck_conf(40, 5, 240, 40, True, "HS", 1, 1),
  221. bneck_conf(40, 5, 240, 40, True, "HS", 1, 1),
  222. bneck_conf(40, 5, 120, 48, True, "HS", 1, 1),
  223. bneck_conf(48, 5, 144, 48, True, "HS", 1, 1),
  224. bneck_conf(48, 5, 288, 96 // reduce_divider, True, "HS", 2, dilation), # C4
  225. bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation),
  226. bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation),
  227. ]
  228. last_channel = adjust_channels(1024 // reduce_divider) # C5
  229. else:
  230. raise ValueError(f"Unsupported model type {arch}")
  231. return inverted_residual_setting, last_channel
  232. def _mobilenet_v3(
  233. inverted_residual_setting: List[InvertedResidualConfig],
  234. last_channel: int,
  235. weights: Optional[WeightsEnum],
  236. progress: bool,
  237. **kwargs: Any,
  238. ) -> MobileNetV3:
  239. if weights is not None:
  240. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  241. model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs)
  242. if weights is not None:
  243. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  244. return model
  245. _COMMON_META = {
  246. "min_size": (1, 1),
  247. "categories": _IMAGENET_CATEGORIES,
  248. }
  249. class MobileNet_V3_Large_Weights(WeightsEnum):
  250. IMAGENET1K_V1 = Weights(
  251. url="https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth",
  252. transforms=partial(ImageClassification, crop_size=224),
  253. meta={
  254. **_COMMON_META,
  255. "num_params": 5483032,
  256. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
  257. "_metrics": {
  258. "ImageNet-1K": {
  259. "acc@1": 74.042,
  260. "acc@5": 91.340,
  261. }
  262. },
  263. "_ops": 0.217,
  264. "_file_size": 21.114,
  265. "_docs": """These weights were trained from scratch by using a simple training recipe.""",
  266. },
  267. )
  268. IMAGENET1K_V2 = Weights(
  269. url="https://download.pytorch.org/models/mobilenet_v3_large-5c1a4163.pth",
  270. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  271. meta={
  272. **_COMMON_META,
  273. "num_params": 5483032,
  274. "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning",
  275. "_metrics": {
  276. "ImageNet-1K": {
  277. "acc@1": 75.274,
  278. "acc@5": 92.566,
  279. }
  280. },
  281. "_ops": 0.217,
  282. "_file_size": 21.107,
  283. "_docs": """
  284. These weights improve marginally upon the results of the original paper by using a modified version of
  285. TorchVision's `new training recipe
  286. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  287. """,
  288. },
  289. )
  290. DEFAULT = IMAGENET1K_V2
  291. class MobileNet_V3_Small_Weights(WeightsEnum):
  292. IMAGENET1K_V1 = Weights(
  293. url="https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth",
  294. transforms=partial(ImageClassification, crop_size=224),
  295. meta={
  296. **_COMMON_META,
  297. "num_params": 2542856,
  298. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
  299. "_metrics": {
  300. "ImageNet-1K": {
  301. "acc@1": 67.668,
  302. "acc@5": 87.402,
  303. }
  304. },
  305. "_ops": 0.057,
  306. "_file_size": 9.829,
  307. "_docs": """
  308. These weights improve upon the results of the original paper by using a simple training recipe.
  309. """,
  310. },
  311. )
  312. DEFAULT = IMAGENET1K_V1
  313. @register_model()
  314. @handle_legacy_interface(weights=("pretrained", MobileNet_V3_Large_Weights.IMAGENET1K_V1))
  315. def mobilenet_v3_large(
  316. *, weights: Optional[MobileNet_V3_Large_Weights] = None, progress: bool = True, **kwargs: Any
  317. ) -> MobileNetV3:
  318. """
  319. Constructs a large MobileNetV3 architecture from
  320. `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.
  321. Args:
  322. weights (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  323. pretrained weights to use. See
  324. :class:`~torchvision.models.MobileNet_V3_Large_Weights` below for
  325. more details, and possible values. By default, no pre-trained
  326. weights are used.
  327. progress (bool, optional): If True, displays a progress bar of the
  328. download to stderr. Default is True.
  329. **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3``
  330. base class. Please refer to the `source code
  331. <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
  332. for more details about this class.
  333. .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights
  334. :members:
  335. """
  336. weights = MobileNet_V3_Large_Weights.verify(weights)
  337. inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs)
  338. return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)
  339. @register_model()
  340. @handle_legacy_interface(weights=("pretrained", MobileNet_V3_Small_Weights.IMAGENET1K_V1))
  341. def mobilenet_v3_small(
  342. *, weights: Optional[MobileNet_V3_Small_Weights] = None, progress: bool = True, **kwargs: Any
  343. ) -> MobileNetV3:
  344. """
  345. Constructs a small MobileNetV3 architecture from
  346. `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.
  347. Args:
  348. weights (:class:`~torchvision.models.MobileNet_V3_Small_Weights`, optional): The
  349. pretrained weights to use. See
  350. :class:`~torchvision.models.MobileNet_V3_Small_Weights` below for
  351. more details, and possible values. By default, no pre-trained
  352. weights are used.
  353. progress (bool, optional): If True, displays a progress bar of the
  354. download to stderr. Default is True.
  355. **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3``
  356. base class. Please refer to the `source code
  357. <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
  358. for more details about this class.
  359. .. autoclass:: torchvision.models.MobileNet_V3_Small_Weights
  360. :members:
  361. """
  362. weights = MobileNet_V3_Small_Weights.verify(weights)
  363. inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_small", **kwargs)
  364. return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...