densenet.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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)
  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)