fcn.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 WeightsEnum, Weights
  6. from .._meta import _VOC_CATEGORIES
  7. from .._utils import IntermediateLayerGetter, handle_legacy_interface, _ovewrite_value_param
  8. from ..resnet import ResNet, ResNet50_Weights, ResNet101_Weights, resnet50, resnet101
  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. },
  60. )
  61. DEFAULT = COCO_WITH_VOC_LABELS_V1
  62. class FCN_ResNet101_Weights(WeightsEnum):
  63. COCO_WITH_VOC_LABELS_V1 = Weights(
  64. url="https://download.pytorch.org/models/fcn_resnet101_coco-7ecb50ca.pth",
  65. transforms=partial(SemanticSegmentation, resize_size=520),
  66. meta={
  67. **_COMMON_META,
  68. "num_params": 54314346,
  69. "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet101",
  70. "_metrics": {
  71. "COCO-val2017-VOC-labels": {
  72. "miou": 63.7,
  73. "pixel_acc": 91.9,
  74. }
  75. },
  76. },
  77. )
  78. DEFAULT = COCO_WITH_VOC_LABELS_V1
  79. def _fcn_resnet(
  80. backbone: ResNet,
  81. num_classes: int,
  82. aux: Optional[bool],
  83. ) -> FCN:
  84. return_layers = {"layer4": "out"}
  85. if aux:
  86. return_layers["layer3"] = "aux"
  87. backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
  88. aux_classifier = FCNHead(1024, num_classes) if aux else None
  89. classifier = FCNHead(2048, num_classes)
  90. return FCN(backbone, classifier, aux_classifier)
  91. @handle_legacy_interface(
  92. weights=("pretrained", FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1),
  93. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  94. )
  95. def fcn_resnet50(
  96. *,
  97. weights: Optional[FCN_ResNet50_Weights] = None,
  98. progress: bool = True,
  99. num_classes: Optional[int] = None,
  100. aux_loss: Optional[bool] = None,
  101. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  102. **kwargs: Any,
  103. ) -> FCN:
  104. """Fully-Convolutional Network model with a ResNet-50 backbone from the `Fully Convolutional
  105. Networks for Semantic Segmentation <https://arxiv.org/abs/1411.4038>`_ paper.
  106. .. betastatus:: segmentation module
  107. Args:
  108. weights (:class:`~torchvision.models.segmentation.FCN_ResNet50_Weights`, optional): The
  109. pretrained weights to use. See
  110. :class:`~torchvision.models.segmentation.FCN_ResNet50_Weights` below for
  111. more details, and possible values. By default, no pre-trained
  112. weights are used.
  113. progress (bool, optional): If True, displays a progress bar of the
  114. download to stderr. Default is True.
  115. num_classes (int, optional): number of output classes of the model (including the background).
  116. aux_loss (bool, optional): If True, it uses an auxiliary loss.
  117. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained
  118. weights for the backbone.
  119. **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN``
  120. base class. Please refer to the `source code
  121. <https://github.com/pytorch/vision/blob/main/torchvision/models/segmentation/fcn.py>`_
  122. for more details about this class.
  123. .. autoclass:: torchvision.models.segmentation.FCN_ResNet50_Weights
  124. :members:
  125. """
  126. weights = FCN_ResNet50_Weights.verify(weights)
  127. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  128. if weights is not None:
  129. weights_backbone = None
  130. num_classes = _ovewrite_value_param(num_classes, len(weights.meta["categories"]))
  131. aux_loss = _ovewrite_value_param(aux_loss, True)
  132. elif num_classes is None:
  133. num_classes = 21
  134. backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True])
  135. model = _fcn_resnet(backbone, num_classes, aux_loss)
  136. if weights is not None:
  137. model.load_state_dict(weights.get_state_dict(progress=progress))
  138. return model
  139. @handle_legacy_interface(
  140. weights=("pretrained", FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1),
  141. weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1),
  142. )
  143. def fcn_resnet101(
  144. *,
  145. weights: Optional[FCN_ResNet101_Weights] = None,
  146. progress: bool = True,
  147. num_classes: Optional[int] = None,
  148. aux_loss: Optional[bool] = None,
  149. weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1,
  150. **kwargs: Any,
  151. ) -> FCN:
  152. """Fully-Convolutional Network model with a ResNet-101 backbone from the `Fully Convolutional
  153. Networks for Semantic Segmentation <https://arxiv.org/abs/1411.4038>`_ paper.
  154. .. betastatus:: segmentation module
  155. Args:
  156. weights (:class:`~torchvision.models.segmentation.FCN_ResNet101_Weights`, optional): The
  157. pretrained weights to use. See
  158. :class:`~torchvision.models.segmentation.FCN_ResNet101_Weights` below for
  159. more details, and possible values. By default, no pre-trained
  160. weights are used.
  161. progress (bool, optional): If True, displays a progress bar of the
  162. download to stderr. Default is True.
  163. num_classes (int, optional): number of output classes of the model (including the background).
  164. aux_loss (bool, optional): If True, it uses an auxiliary loss.
  165. weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained
  166. weights for the backbone.
  167. **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN``
  168. base class. Please refer to the `source code
  169. <https://github.com/pytorch/vision/blob/main/torchvision/models/segmentation/fcn.py>`_
  170. for more details about this class.
  171. .. autoclass:: torchvision.models.segmentation.FCN_ResNet101_Weights
  172. :members:
  173. """
  174. weights = FCN_ResNet101_Weights.verify(weights)
  175. weights_backbone = ResNet101_Weights.verify(weights_backbone)
  176. if weights is not None:
  177. weights_backbone = None
  178. num_classes = _ovewrite_value_param(num_classes, len(weights.meta["categories"]))
  179. aux_loss = _ovewrite_value_param(aux_loss, True)
  180. elif num_classes is None:
  181. num_classes = 21
  182. backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True])
  183. model = _fcn_resnet(backbone, num_classes, aux_loss)
  184. if weights is not None:
  185. model.load_state_dict(weights.get_state_dict(progress=progress))
  186. return model
  187. # The dictionary below is internal implementation detail and will be removed in v0.15
  188. from .._utils import _ModelURLs
  189. model_urls = _ModelURLs(
  190. {
  191. "fcn_resnet50_coco": FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1.url,
  192. "fcn_resnet101_coco": FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1.url,
  193. }
  194. )