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

densenet.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
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
  1. import re
  2. from collections import OrderedDict
  3. from functools import partial
  4. from typing import Any, List, Optional, Tuple
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. import torch.utils.checkpoint as cp
  9. from torch import Tensor
  10. from ..transforms._presets import ImageClassification
  11. from ..utils import _log_api_usage_once
  12. from ._api import register_model, Weights, WeightsEnum
  13. from ._meta import _IMAGENET_CATEGORIES
  14. from ._utils import _ovewrite_named_param, handle_legacy_interface
  15. __all__ = [
  16. "DenseNet",
  17. "DenseNet121_Weights",
  18. "DenseNet161_Weights",
  19. "DenseNet169_Weights",
  20. "DenseNet201_Weights",
  21. "densenet121",
  22. "densenet161",
  23. "densenet169",
  24. "densenet201",
  25. ]
  26. class _DenseLayer(nn.Module):
  27. def __init__(
  28. self, num_input_features: int, growth_rate: int, bn_size: int, drop_rate: float, memory_efficient: bool = False
  29. ) -> None:
  30. super().__init__()
  31. self.norm1 = nn.BatchNorm2d(num_input_features)
  32. self.relu1 = nn.ReLU(inplace=True)
  33. self.conv1 = nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)
  34. self.norm2 = nn.BatchNorm2d(bn_size * growth_rate)
  35. self.relu2 = nn.ReLU(inplace=True)
  36. self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)
  37. self.drop_rate = float(drop_rate)
  38. self.memory_efficient = memory_efficient
  39. def bn_function(self, inputs: List[Tensor]) -> Tensor:
  40. concated_features = torch.cat(inputs, 1)
  41. bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484
  42. return bottleneck_output
  43. # todo: rewrite when torchscript supports any
  44. def any_requires_grad(self, input: List[Tensor]) -> bool:
  45. for tensor in input:
  46. if tensor.requires_grad:
  47. return True
  48. return False
  49. @torch.jit.unused # noqa: T484
  50. def call_checkpoint_bottleneck(self, input: List[Tensor]) -> Tensor:
  51. def closure(*inputs):
  52. return self.bn_function(inputs)
  53. return cp.checkpoint(closure, *input, use_reentrant=False)
  54. @torch.jit._overload_method # noqa: F811
  55. def forward(self, input: List[Tensor]) -> Tensor: # noqa: F811
  56. pass
  57. @torch.jit._overload_method # noqa: F811
  58. def forward(self, input: Tensor) -> Tensor: # noqa: F811
  59. pass
  60. # torchscript does not yet support *args, so we overload method
  61. # allowing it to take either a List[Tensor] or single Tensor
  62. def forward(self, input: Tensor) -> Tensor: # noqa: F811
  63. if isinstance(input, Tensor):
  64. prev_features = [input]
  65. else:
  66. prev_features = input
  67. if self.memory_efficient and self.any_requires_grad(prev_features):
  68. if torch.jit.is_scripting():
  69. raise Exception("Memory Efficient not supported in JIT")
  70. bottleneck_output = self.call_checkpoint_bottleneck(prev_features)
  71. else:
  72. bottleneck_output = self.bn_function(prev_features)
  73. new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
  74. if self.drop_rate > 0:
  75. new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)
  76. return new_features
  77. class _DenseBlock(nn.ModuleDict):
  78. _version = 2
  79. def __init__(
  80. self,
  81. num_layers: int,
  82. num_input_features: int,
  83. bn_size: int,
  84. growth_rate: int,
  85. drop_rate: float,
  86. memory_efficient: bool = False,
  87. ) -> None:
  88. super().__init__()
  89. for i in range(num_layers):
  90. layer = _DenseLayer(
  91. num_input_features + i * growth_rate,
  92. growth_rate=growth_rate,
  93. bn_size=bn_size,
  94. drop_rate=drop_rate,
  95. memory_efficient=memory_efficient,
  96. )
  97. self.add_module("denselayer%d" % (i + 1), layer)
  98. def forward(self, init_features: Tensor) -> Tensor:
  99. features = [init_features]
  100. for name, layer in self.items():
  101. new_features = layer(features)
  102. features.append(new_features)
  103. return torch.cat(features, 1)
  104. class _Transition(nn.Sequential):
  105. def __init__(self, num_input_features: int, num_output_features: int) -> None:
  106. super().__init__()
  107. self.norm = nn.BatchNorm2d(num_input_features)
  108. self.relu = nn.ReLU(inplace=True)
  109. self.conv = nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)
  110. self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
  111. class DenseNet(nn.Module):
  112. r"""Densenet-BC model class, based on
  113. `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.
  114. Args:
  115. growth_rate (int) - how many filters to add each layer (`k` in paper)
  116. block_config (list of 4 ints) - how many layers in each pooling block
  117. num_init_features (int) - the number of filters to learn in the first convolution layer
  118. bn_size (int) - multiplicative factor for number of bottle neck layers
  119. (i.e. bn_size * k features in the bottleneck layer)
  120. drop_rate (float) - dropout rate after each dense layer
  121. num_classes (int) - number of classification classes
  122. memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,
  123. but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_.
  124. """
  125. def __init__(
  126. self,
  127. growth_rate: int = 32,
  128. block_config: Tuple[int, int, int, int] = (6, 12, 24, 16),
  129. num_init_features: int = 64,
  130. bn_size: int = 4,
  131. drop_rate: float = 0,
  132. num_classes: int = 1000,
  133. memory_efficient: bool = False,
  134. ) -> None:
  135. super().__init__()
  136. _log_api_usage_once(self)
  137. # First convolution
  138. self.features = nn.Sequential(
  139. OrderedDict(
  140. [
  141. ("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
  142. ("norm0", nn.BatchNorm2d(num_init_features)),
  143. ("relu0", nn.ReLU(inplace=True)),
  144. ("pool0", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
  145. ]
  146. )
  147. )
  148. # Each denseblock
  149. num_features = num_init_features
  150. for i, num_layers in enumerate(block_config):
  151. block = _DenseBlock(
  152. num_layers=num_layers,
  153. num_input_features=num_features,
  154. bn_size=bn_size,
  155. growth_rate=growth_rate,
  156. drop_rate=drop_rate,
  157. memory_efficient=memory_efficient,
  158. )
  159. self.features.add_module("denseblock%d" % (i + 1), block)
  160. num_features = num_features + num_layers * growth_rate
  161. if i != len(block_config) - 1:
  162. trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)
  163. self.features.add_module("transition%d" % (i + 1), trans)
  164. num_features = num_features // 2
  165. # Final batch norm
  166. self.features.add_module("norm5", nn.BatchNorm2d(num_features))
  167. # Linear layer
  168. self.classifier = nn.Linear(num_features, num_classes)
  169. # Official init from torch repo.
  170. for m in self.modules():
  171. if isinstance(m, nn.Conv2d):
  172. nn.init.kaiming_normal_(m.weight)
  173. elif isinstance(m, nn.BatchNorm2d):
  174. nn.init.constant_(m.weight, 1)
  175. nn.init.constant_(m.bias, 0)
  176. elif isinstance(m, nn.Linear):
  177. nn.init.constant_(m.bias, 0)
  178. def forward(self, x: Tensor) -> Tensor:
  179. features = self.features(x)
  180. out = F.relu(features, inplace=True)
  181. out = F.adaptive_avg_pool2d(out, (1, 1))
  182. out = torch.flatten(out, 1)
  183. out = self.classifier(out)
  184. return out
  185. def _load_state_dict(model: nn.Module, weights: WeightsEnum, progress: bool) -> None:
  186. # '.'s are no longer allowed in module names, but previous _DenseLayer
  187. # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
  188. # They are also in the checkpoints in model_urls. This pattern is used
  189. # to find such keys.
  190. pattern = re.compile(
  191. r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$"
  192. )
  193. state_dict = weights.get_state_dict(progress=progress, check_hash=True)
  194. for key in list(state_dict.keys()):
  195. res = pattern.match(key)
  196. if res:
  197. new_key = res.group(1) + res.group(2)
  198. state_dict[new_key] = state_dict[key]
  199. del state_dict[key]
  200. model.load_state_dict(state_dict)
  201. def _densenet(
  202. growth_rate: int,
  203. block_config: Tuple[int, int, int, int],
  204. num_init_features: int,
  205. weights: Optional[WeightsEnum],
  206. progress: bool,
  207. **kwargs: Any,
  208. ) -> DenseNet:
  209. if weights is not None:
  210. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  211. model = DenseNet(growth_rate, block_config, num_init_features, **kwargs)
  212. if weights is not None:
  213. _load_state_dict(model=model, weights=weights, progress=progress)
  214. return model
  215. _COMMON_META = {
  216. "min_size": (29, 29),
  217. "categories": _IMAGENET_CATEGORIES,
  218. "recipe": "https://github.com/pytorch/vision/pull/116",
  219. "_docs": """These weights are ported from LuaTorch.""",
  220. }
  221. class DenseNet121_Weights(WeightsEnum):
  222. IMAGENET1K_V1 = Weights(
  223. url="https://download.pytorch.org/models/densenet121-a639ec97.pth",
  224. transforms=partial(ImageClassification, crop_size=224),
  225. meta={
  226. **_COMMON_META,
  227. "num_params": 7978856,
  228. "_metrics": {
  229. "ImageNet-1K": {
  230. "acc@1": 74.434,
  231. "acc@5": 91.972,
  232. }
  233. },
  234. "_ops": 2.834,
  235. "_file_size": 30.845,
  236. },
  237. )
  238. DEFAULT = IMAGENET1K_V1
  239. class DenseNet161_Weights(WeightsEnum):
  240. IMAGENET1K_V1 = Weights(
  241. url="https://download.pytorch.org/models/densenet161-8d451a50.pth",
  242. transforms=partial(ImageClassification, crop_size=224),
  243. meta={
  244. **_COMMON_META,
  245. "num_params": 28681000,
  246. "_metrics": {
  247. "ImageNet-1K": {
  248. "acc@1": 77.138,
  249. "acc@5": 93.560,
  250. }
  251. },
  252. "_ops": 7.728,
  253. "_file_size": 110.369,
  254. },
  255. )
  256. DEFAULT = IMAGENET1K_V1
  257. class DenseNet169_Weights(WeightsEnum):
  258. IMAGENET1K_V1 = Weights(
  259. url="https://download.pytorch.org/models/densenet169-b2777c0a.pth",
  260. transforms=partial(ImageClassification, crop_size=224),
  261. meta={
  262. **_COMMON_META,
  263. "num_params": 14149480,
  264. "_metrics": {
  265. "ImageNet-1K": {
  266. "acc@1": 75.600,
  267. "acc@5": 92.806,
  268. }
  269. },
  270. "_ops": 3.36,
  271. "_file_size": 54.708,
  272. },
  273. )
  274. DEFAULT = IMAGENET1K_V1
  275. class DenseNet201_Weights(WeightsEnum):
  276. IMAGENET1K_V1 = Weights(
  277. url="https://download.pytorch.org/models/densenet201-c1103571.pth",
  278. transforms=partial(ImageClassification, crop_size=224),
  279. meta={
  280. **_COMMON_META,
  281. "num_params": 20013928,
  282. "_metrics": {
  283. "ImageNet-1K": {
  284. "acc@1": 76.896,
  285. "acc@5": 93.370,
  286. }
  287. },
  288. "_ops": 4.291,
  289. "_file_size": 77.373,
  290. },
  291. )
  292. DEFAULT = IMAGENET1K_V1
  293. @register_model()
  294. @handle_legacy_interface(weights=("pretrained", DenseNet121_Weights.IMAGENET1K_V1))
  295. def densenet121(*, weights: Optional[DenseNet121_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
  296. r"""Densenet-121 model from
  297. `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
  298. Args:
  299. weights (:class:`~torchvision.models.DenseNet121_Weights`, optional): The
  300. pretrained weights to use. See
  301. :class:`~torchvision.models.DenseNet121_Weights` below for
  302. more details, and possible values. By default, no pre-trained
  303. weights are used.
  304. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  305. **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
  306. base class. Please refer to the `source code
  307. <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
  308. for more details about this class.
  309. .. autoclass:: torchvision.models.DenseNet121_Weights
  310. :members:
  311. """
  312. weights = DenseNet121_Weights.verify(weights)
  313. return _densenet(32, (6, 12, 24, 16), 64, weights, progress, **kwargs)
  314. @register_model()
  315. @handle_legacy_interface(weights=("pretrained", DenseNet161_Weights.IMAGENET1K_V1))
  316. def densenet161(*, weights: Optional[DenseNet161_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
  317. r"""Densenet-161 model from
  318. `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
  319. Args:
  320. weights (:class:`~torchvision.models.DenseNet161_Weights`, optional): The
  321. pretrained weights to use. See
  322. :class:`~torchvision.models.DenseNet161_Weights` below for
  323. more details, and possible values. By default, no pre-trained
  324. weights are used.
  325. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  326. **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
  327. base class. Please refer to the `source code
  328. <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
  329. for more details about this class.
  330. .. autoclass:: torchvision.models.DenseNet161_Weights
  331. :members:
  332. """
  333. weights = DenseNet161_Weights.verify(weights)
  334. return _densenet(48, (6, 12, 36, 24), 96, weights, progress, **kwargs)
  335. @register_model()
  336. @handle_legacy_interface(weights=("pretrained", DenseNet169_Weights.IMAGENET1K_V1))
  337. def densenet169(*, weights: Optional[DenseNet169_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
  338. r"""Densenet-169 model from
  339. `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
  340. Args:
  341. weights (:class:`~torchvision.models.DenseNet169_Weights`, optional): The
  342. pretrained weights to use. See
  343. :class:`~torchvision.models.DenseNet169_Weights` below for
  344. more details, and possible values. By default, no pre-trained
  345. weights are used.
  346. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  347. **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
  348. base class. Please refer to the `source code
  349. <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
  350. for more details about this class.
  351. .. autoclass:: torchvision.models.DenseNet169_Weights
  352. :members:
  353. """
  354. weights = DenseNet169_Weights.verify(weights)
  355. return _densenet(32, (6, 12, 32, 32), 64, weights, progress, **kwargs)
  356. @register_model()
  357. @handle_legacy_interface(weights=("pretrained", DenseNet201_Weights.IMAGENET1K_V1))
  358. def densenet201(*, weights: Optional[DenseNet201_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
  359. r"""Densenet-201 model from
  360. `Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
  361. Args:
  362. weights (:class:`~torchvision.models.DenseNet201_Weights`, optional): The
  363. pretrained weights to use. See
  364. :class:`~torchvision.models.DenseNet201_Weights` below for
  365. more details, and possible values. By default, no pre-trained
  366. weights are used.
  367. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  368. **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
  369. base class. Please refer to the `source code
  370. <https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
  371. for more details about this class.
  372. .. autoclass:: torchvision.models.DenseNet201_Weights
  373. :members:
  374. """
  375. weights = DenseNet201_Weights.verify(weights)
  376. return _densenet(32, (6, 12, 48, 32), 64, weights, progress, **kwargs)
Tip!

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

Comments

Loading...