lraspp.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from collections import OrderedDict
  2. from functools import partial
  3. from typing import Any, Dict, Optional
  4. from torch import nn, Tensor
  5. from torch.nn import functional as F
  6. from ...transforms._presets import SemanticSegmentation
  7. from ...utils import _log_api_usage_once
  8. from .._api import register_model, Weights, WeightsEnum
  9. from .._meta import _VOC_CATEGORIES
  10. from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter
  11. from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3
  12. __all__ = ["LRASPP", "LRASPP_MobileNet_V3_Large_Weights", "lraspp_mobilenet_v3_large"]
  13. class LRASPP(nn.Module):
  14. """
  15. Implements a Lite R-ASPP Network for semantic segmentation from
  16. `"Searching for MobileNetV3"
  17. <https://arxiv.org/abs/1905.02244>`_.
  18. Args:
  19. backbone (nn.Module): the network used to compute the features for the model.
  20. The backbone should return an OrderedDict[Tensor], with the key being
  21. "high" for the high level feature map and "low" for the low level feature map.
  22. low_channels (int): the number of channels of the low level features.
  23. high_channels (int): the number of channels of the high level features.
  24. num_classes (int, optional): number of output classes of the model (including the background).
  25. inter_channels (int, optional): the number of channels for intermediate computations.
  26. """
  27. def __init__(
  28. self, backbone: nn.Module, low_channels: int, high_channels: int, num_classes: int, inter_channels: int = 128
  29. ) -> None:
  30. super().__init__()
  31. _log_api_usage_once(self)
  32. self.backbone = backbone
  33. self.classifier = LRASPPHead(low_channels, high_channels, num_classes, inter_channels)
  34. def forward(self, input: Tensor) -> Dict[str, Tensor]:
  35. features = self.backbone(input)
  36. out = self.classifier(features)
  37. out = F.interpolate(out, size=input.shape[-2:], mode="bilinear", align_corners=False)
  38. result = OrderedDict()
  39. result["out"] = out
  40. return result
  41. class LRASPPHead(nn.Module):
  42. def __init__(self, low_channels: int, high_channels: int, num_classes: int, inter_channels: int) -> None:
  43. super().__init__()
  44. self.cbr = nn.Sequential(
  45. nn.Conv2d(high_channels, inter_channels, 1, bias=False),
  46. nn.BatchNorm2d(inter_channels),
  47. nn.ReLU(inplace=True),
  48. )
  49. self.scale = nn.Sequential(
  50. nn.AdaptiveAvgPool2d(1),
  51. nn.Conv2d(high_channels, inter_channels, 1, bias=False),
  52. nn.Sigmoid(),
  53. )
  54. self.low_classifier = nn.Conv2d(low_channels, num_classes, 1)
  55. self.high_classifier = nn.Conv2d(inter_channels, num_classes, 1)
  56. def forward(self, input: Dict[str, Tensor]) -> Tensor:
  57. low = input["low"]
  58. high = input["high"]
  59. x = self.cbr(high)
  60. s = self.scale(high)
  61. x = x * s
  62. x = F.interpolate(x, size=low.shape[-2:], mode="bilinear", align_corners=False)
  63. return self.low_classifier(low) + self.high_classifier(x)
  64. def _lraspp_mobilenetv3(backbone: MobileNetV3, num_classes: int) -> LRASPP:
  65. backbone = backbone.features
  66. # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
  67. # The first and last blocks are always included because they are the C0 (conv1) and Cn.
  68. stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
  69. low_pos = stage_indices[-4] # use C2 here which has output_stride = 8
  70. high_pos = stage_indices[-1] # use C5 which has output_stride = 16
  71. low_channels = backbone[low_pos].out_channels
  72. high_channels = backbone[high_pos].out_channels
  73. backbone = IntermediateLayerGetter(backbone, return_layers={str(low_pos): "low", str(high_pos): "high"})
  74. return LRASPP(backbone, low_channels, high_channels, num_classes)
  75. class LRASPP_MobileNet_V3_Large_Weights(WeightsEnum):
  76. COCO_WITH_VOC_LABELS_V1 = Weights(
  77. url="https://download.pytorch.org/models/lraspp_mobilenet_v3_large-d234d4ea.pth",
  78. transforms=partial(SemanticSegmentation, resize_size=520),
  79. meta={
  80. "num_params": 3221538,
  81. "categories": _VOC_CATEGORIES,
  82. "min_size": (1, 1),
  83. "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#lraspp_mobilenet_v3_large",
  84. "_metrics": {
  85. "COCO-val2017-VOC-labels": {
  86. "miou": 57.9,
  87. "pixel_acc": 91.2,
  88. }
  89. },
  90. "_ops": 2.086,
  91. "_file_size": 12.49,
  92. "_docs": """
  93. These weights were trained on a subset of COCO, using only the 20 categories that are present in the
  94. Pascal VOC dataset.
  95. """,
  96. },
  97. )
  98. DEFAULT = COCO_WITH_VOC_LABELS_V1
  99. @register_model()
  100. @handle_legacy_interface(
  101. weights=("pretrained", LRASPP_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1),
  102. weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  103. )
  104. def lraspp_mobilenet_v3_large(
  105. *,
  106. weights: Optional[LRASPP_MobileNet_V3_Large_Weights] = None,
  107. progress: bool = True,
  108. num_classes: Optional[int] = None,
  109. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  110. **kwargs: Any,
  111. ) -> LRASPP:
  112. """Constructs a Lite R-ASPP Network model with a MobileNetV3-Large backbone from
  113. `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`_ paper.
  114. .. betastatus:: segmentation module
  115. Args:
  116. weights (:class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights`, optional): The
  117. pretrained weights to use. See
  118. :class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights` below for
  119. more details, and possible values. By default, no pre-trained
  120. weights are used.
  121. progress (bool, optional): If True, displays a progress bar of the
  122. download to stderr. Default is True.
  123. num_classes (int, optional): number of output classes of the model (including the background).
  124. aux_loss (bool, optional): If True, it uses an auxiliary loss.
  125. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained
  126. weights for the backbone.
  127. **kwargs: parameters passed to the ``torchvision.models.segmentation.LRASPP``
  128. base class. Please refer to the `source code
  129. <https://github.com/pytorch/vision/blob/main/torchvision/models/segmentation/lraspp.py>`_
  130. for more details about this class.
  131. .. autoclass:: torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights
  132. :members:
  133. """
  134. if kwargs.pop("aux_loss", False):
  135. raise NotImplementedError("This model does not use auxiliary loss")
  136. weights = LRASPP_MobileNet_V3_Large_Weights.verify(weights)
  137. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  138. if weights is not None:
  139. weights_backbone = None
  140. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  141. elif num_classes is None:
  142. num_classes = 21
  143. backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True)
  144. model = _lraspp_mobilenetv3(backbone, num_classes)
  145. if weights is not None:
  146. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  147. return model