fcn.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from functools import partial
  2. from typing import Any, Optional
  3. from torch import nn
  4. from ...transforms._presets import SemanticSegmentation
  5. from .._api import register_model, Weights, WeightsEnum
  6. from .._meta import _VOC_CATEGORIES
  7. from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter
  8. from ..resnet import ResNet, resnet101, ResNet101_Weights, resnet50, ResNet50_Weights
  9. from ._utils import _SimpleSegmentationModel
  10. __all__ = ["FCN", "FCN_ResNet50_Weights", "FCN_ResNet101_Weights", "fcn_resnet50", "fcn_resnet101"]
  11. class FCN(_SimpleSegmentationModel):
  12. """
  13. Implements FCN model from
  14. `"Fully Convolutional Networks for Semantic Segmentation"
  15. <https://arxiv.org/abs/1411.4038>`_.
  16. Args:
  17. backbone (nn.Module): the network used to compute the features for the model.
  18. The backbone should return an OrderedDict[Tensor], with the key being
  19. "out" for the last feature map used, and "aux" if an auxiliary classifier
  20. is used.
  21. classifier (nn.Module): module that takes the "out" element returned from
  22. the backbone and returns a dense prediction.
  23. aux_classifier (nn.Module, optional): auxiliary classifier used during training
  24. """
  25. pass
  26. class FCNHead(nn.Sequential):
  27. def __init__(self, in_channels: int, channels: int) -> None:
  28. inter_channels = in_channels // 4
  29. layers = [
  30. nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
  31. nn.BatchNorm2d(inter_channels),
  32. nn.ReLU(),
  33. nn.Dropout(0.1),
  34. nn.Conv2d(inter_channels, channels, 1),
  35. ]
  36. super().__init__(*layers)
  37. _COMMON_META = {
  38. "categories": _VOC_CATEGORIES,
  39. "min_size": (1, 1),
  40. "_docs": """
  41. These weights were trained on a subset of COCO, using only the 20 categories that are present in the Pascal VOC
  42. dataset.
  43. """,
  44. }
  45. class FCN_ResNet50_Weights(WeightsEnum):
  46. COCO_WITH_VOC_LABELS_V1 = Weights(
  47. url="https://download.pytorch.org/models/fcn_resnet50_coco-1167a1af.pth",
  48. transforms=partial(SemanticSegmentation, resize_size=520),
  49. meta={
  50. **_COMMON_META,
  51. "num_params": 35322218,
  52. "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#fcn_resnet50",
  53. "_metrics": {
  54. "COCO-val2017-VOC-labels": {
  55. "miou": 60.5,
  56. "pixel_acc": 91.4,
  57. }
  58. },
  59. "_ops": 152.717,
  60. "_file_size": 135.009,
  61. },
  62. )
  63. DEFAULT = COCO_WITH_VOC_LABELS_V1
  64. class FCN_ResNet101_Weights(WeightsEnum):
  65. COCO_WITH_VOC_LABELS_V1 = Weights(
  66. url="https://download.pytorch.org/models/fcn_resnet101_coco-7ecb50ca.pth",
  67. transforms=partial(SemanticSegmentation, resize_size=520),
  68. meta={
  69. **_COMMON_META,
  70. "num_params": 54314346,
  71. "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet101",
  72. "_metrics": {
  73. "COCO-val2017-VOC-labels": {
  74. "miou": 63.7,
  75. "pixel_acc": 91.9,
  76. }
  77. },
  78. "_ops": 232.738,
  79. "_file_size": 207.711,
  80. },
  81. )
  82. DEFAULT = COCO_WITH_VOC_LABELS_V1
  83. def _fcn_resnet(
  84. backbone: ResNet,
  85. num_classes: int,
  86. aux: Optional[bool],
  87. ) -> FCN:
  88. return_layers = {"layer4": "out"}
  89. if aux:
  90. return_layers["layer3"] = "aux"
  91. backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
  92. aux_classifier = FCNHead(1024, num_classes) if aux else None
  93. classifier = FCNHead(2048, num_classes)
  94. return FCN(backbone, classifier, aux_classifier)
  95. @register_model()
  96. @handle_legacy_interface(
  97. weights=("pretrained", FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1),
  98. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  99. )
  100. def fcn_resnet50(
  101. *,
  102. weights: Optional[FCN_ResNet50_Weights] = None,
  103. progress: bool = True,
  104. num_classes: Optional[int] = None,
  105. aux_loss: Optional[bool] = None,
  106. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  107. **kwargs: Any,
  108. ) -> FCN:
  109. """Fully-Convolutional Network model with a ResNet-50 backbone from the `Fully Convolutional
  110. Networks for Semantic Segmentation <https://arxiv.org/abs/1411.4038>`_ paper.
  111. .. betastatus:: segmentation module
  112. Args:
  113. weights (:class:`~torchvision.models.segmentation.FCN_ResNet50_Weights`, optional): The
  114. pretrained weights to use. See
  115. :class:`~torchvision.models.segmentation.FCN_ResNet50_Weights` below for
  116. more details, and possible values. By default, no pre-trained
  117. weights are used.
  118. progress (bool, optional): If True, displays a progress bar of the
  119. download to stderr. Default is True.
  120. num_classes (int, optional): number of output classes of the model (including the background).
  121. aux_loss (bool, optional): If True, it uses an auxiliary loss.
  122. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained
  123. weights for the backbone.
  124. **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN``
  125. base class. Please refer to the `source code
  126. <https://github.com/pytorch/vision/blob/main/torchvision/models/segmentation/fcn.py>`_
  127. for more details about this class.
  128. .. autoclass:: torchvision.models.segmentation.FCN_ResNet50_Weights
  129. :members:
  130. """
  131. weights = FCN_ResNet50_Weights.verify(weights)
  132. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  133. if weights is not None:
  134. weights_backbone = None
  135. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  136. aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True)
  137. elif num_classes is None:
  138. num_classes = 21
  139. backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True])
  140. model = _fcn_resnet(backbone, num_classes, aux_loss)
  141. if weights is not None:
  142. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  143. return model
  144. @register_model()
  145. @handle_legacy_interface(
  146. weights=("pretrained", FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1),
  147. weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1),
  148. )
  149. def fcn_resnet101(
  150. *,
  151. weights: Optional[FCN_ResNet101_Weights] = None,
  152. progress: bool = True,
  153. num_classes: Optional[int] = None,
  154. aux_loss: Optional[bool] = None,
  155. weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1,
  156. **kwargs: Any,
  157. ) -> FCN:
  158. """Fully-Convolutional Network model with a ResNet-101 backbone from the `Fully Convolutional
  159. Networks for Semantic Segmentation <https://arxiv.org/abs/1411.4038>`_ paper.
  160. .. betastatus:: segmentation module
  161. Args:
  162. weights (:class:`~torchvision.models.segmentation.FCN_ResNet101_Weights`, optional): The
  163. pretrained weights to use. See
  164. :class:`~torchvision.models.segmentation.FCN_ResNet101_Weights` below for
  165. more details, and possible values. By default, no pre-trained
  166. weights are used.
  167. progress (bool, optional): If True, displays a progress bar of the
  168. download to stderr. Default is True.
  169. num_classes (int, optional): number of output classes of the model (including the background).
  170. aux_loss (bool, optional): If True, it uses an auxiliary loss.
  171. weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained
  172. weights for the backbone.
  173. **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN``
  174. base class. Please refer to the `source code
  175. <https://github.com/pytorch/vision/blob/main/torchvision/models/segmentation/fcn.py>`_
  176. for more details about this class.
  177. .. autoclass:: torchvision.models.segmentation.FCN_ResNet101_Weights
  178. :members:
  179. """
  180. weights = FCN_ResNet101_Weights.verify(weights)
  181. weights_backbone = ResNet101_Weights.verify(weights_backbone)
  182. if weights is not None:
  183. weights_backbone = None
  184. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  185. aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True)
  186. elif num_classes is None:
  187. num_classes = 21
  188. backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True])
  189. model = _fcn_resnet(backbone, num_classes, aux_loss)
  190. if weights is not None:
  191. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  192. return model