backbone_utils.py 9.82 KB
Newer Older
1
import warnings
2
from typing import Callable, Dict, List, Optional, Union
3

4
from torch import nn, Tensor
5
from torchvision.ops import misc as misc_nn_ops
6
from torchvision.ops.feature_pyramid_network import ExtraFPNBlock, FeaturePyramidNetwork, LastLevelMaxPool
7

8
from .. import mobilenet, resnet
9
10
from .._api import WeightsEnum, get_enum_from_fn
from .._utils import IntermediateLayerGetter, handle_legacy_interface
11
12


eellison's avatar
eellison committed
13
class BackboneWithFPN(nn.Module):
14
15
16
17
    """
    Adds a FPN on top of a model.
    Internally, it uses torchvision.models._utils.IntermediateLayerGetter to
    extract a submodel that returns the feature maps specified in return_layers.
18
    The same limitations of IntermediateLayerGetter apply here.
19
    Args:
20
21
22
23
24
25
26
27
28
29
30
        backbone (nn.Module)
        return_layers (Dict[name, new_name]): a dict containing the names
            of the modules for which the activations will be returned as
            the key of the dict, and the value of the dict is the name
            of the returned activation (which the user can specify).
        in_channels_list (List[int]): number of channels for each feature map
            that is returned, in the order they are present in the OrderedDict
        out_channels (int): number of channels in the FPN.
    Attributes:
        out_channels (int): the number of channels in the FPN
    """
31

32
33
34
35
36
37
38
39
    def __init__(
        self,
        backbone: nn.Module,
        return_layers: Dict[str, str],
        in_channels_list: List[int],
        out_channels: int,
        extra_blocks: Optional[ExtraFPNBlock] = None,
    ) -> None:
40
        super().__init__()
41
42
43
44

        if extra_blocks is None:
            extra_blocks = LastLevelMaxPool()

eellison's avatar
eellison committed
45
46
        self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
        self.fpn = FeaturePyramidNetwork(
47
48
            in_channels_list=in_channels_list,
            out_channels=out_channels,
49
            extra_blocks=extra_blocks,
50
51
52
        )
        self.out_channels = out_channels

53
    def forward(self, x: Tensor) -> Dict[str, Tensor]:
eellison's avatar
eellison committed
54
55
56
57
        x = self.body(x)
        x = self.fpn(x)
        return x

58

59
60
61
62
63
64
@handle_legacy_interface(
    weights=(
        "pretrained",
        lambda kwargs: get_enum_from_fn(resnet.__dict__[kwargs["backbone_name"]]).from_str("IMAGENET1K_V1"),
    ),
)
65
def resnet_fpn_backbone(
66
    *,
67
    backbone_name: str,
68
    weights: Optional[WeightsEnum],
69
70
71
72
73
    norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
    trainable_layers: int = 3,
    returned_layers: Optional[List[int]] = None,
    extra_blocks: Optional[ExtraFPNBlock] = None,
) -> BackboneWithFPN:
74
75
76
77
78
79
    """
    Constructs a specified ResNet backbone with FPN on top. Freezes the specified number of layers in the backbone.

    Examples::

        >>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
80
        >>> backbone = resnet_fpn_backbone('resnet50', weights=ResNet50_Weights.DEFAULT, trainable_layers=3)
81
82
83
84
85
86
87
88
89
90
91
92
        >>> # get some dummy image
        >>> x = torch.rand(1,3,64,64)
        >>> # compute the output
        >>> output = backbone(x)
        >>> print([(k, v.shape) for k, v in output.items()])
        >>> # returns
        >>>   [('0', torch.Size([1, 256, 16, 16])),
        >>>    ('1', torch.Size([1, 256, 8, 8])),
        >>>    ('2', torch.Size([1, 256, 4, 4])),
        >>>    ('3', torch.Size([1, 256, 2, 2])),
        >>>    ('pool', torch.Size([1, 256, 1, 1]))]

93
    Args:
94
        backbone_name (string): resnet architecture. Possible values are 'resnet18', 'resnet34', 'resnet50',
95
             'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'
96
        weights (WeightsEnum, optional): The pretrained weights for the model
97
        norm_layer (callable): it is recommended to use the default value. For details visit:
98
            (https://github.com/facebookresearch/maskrcnn-benchmark/issues/267)
99
        trainable_layers (int): number of trainable (not frozen) layers starting from final block.
100
            Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable.
101
102
103
104
105
106
107
        returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``.
            By default all layers are returned.
        extra_blocks (ExtraFPNBlock or None): if provided, extra operations will
            be performed. It is expected to take the fpn features, the original
            features and the names of the original features as input, and returns
            a new list of feature maps and their corresponding names. By
            default a ``LastLevelMaxPool`` is used.
108
    """
109
    backbone = resnet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
110
    return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks)
111

112

113
def _resnet_fpn_extractor(
114
115
    backbone: resnet.ResNet,
    trainable_layers: int,
116
117
    returned_layers: Optional[List[int]] = None,
    extra_blocks: Optional[ExtraFPNBlock] = None,
118
119
) -> BackboneWithFPN:

120
    # select layers that wont be frozen
121
122
    if trainable_layers < 0 or trainable_layers > 5:
        raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}")
123
    layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers]
124
    if trainable_layers == 5:
125
        layers_to_train.append("bn1")
126
    for name, parameter in backbone.named_parameters():
127
        if all([not name.startswith(layer) for layer in layers_to_train]):
128
129
            parameter.requires_grad_(False)

130
131
132
133
134
    if extra_blocks is None:
        extra_blocks = LastLevelMaxPool()

    if returned_layers is None:
        returned_layers = [1, 2, 3, 4]
135
136
    if min(returned_layers) <= 0 or max(returned_layers) >= 5:
        raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}")
137
    return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)}
138

139
    in_channels_stage2 = backbone.inplanes // 8
140
    in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]
141
    out_channels = 256
142
    return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
143
144


145
def _validate_trainable_layers(
146
    is_trained: bool,
147
148
149
150
151
    trainable_backbone_layers: Optional[int],
    max_value: int,
    default_value: int,
) -> int:
    # don't freeze any layers if pretrained model or backbone is not used
152
    if not is_trained:
153
154
155
156
        if trainable_backbone_layers is not None:
            warnings.warn(
                "Changing trainable_backbone_layers has not effect if "
                "neither pretrained nor pretrained_backbone have been set to True, "
157
                f"falling back to trainable_backbone_layers={max_value} so that all layers are trainable"
158
            )
159
160
161
        trainable_backbone_layers = max_value

    # by default freeze first blocks
162
    if trainable_backbone_layers is None:
163
        trainable_backbone_layers = default_value
164
165
166
167
    if trainable_backbone_layers < 0 or trainable_backbone_layers > max_value:
        raise ValueError(
            f"Trainable backbone layers should be in the range [0,{max_value}], got {trainable_backbone_layers} "
        )
168
    return trainable_backbone_layers
169
170


171
172
173
174
175
176
@handle_legacy_interface(
    weights=(
        "pretrained",
        lambda kwargs: get_enum_from_fn(mobilenet.__dict__[kwargs["backbone_name"]]).from_str("IMAGENET1K_V1"),
    ),
)
177
def mobilenet_backbone(
178
    *,
179
    backbone_name: str,
180
    weights: Optional[WeightsEnum],
181
182
183
184
185
186
    fpn: bool,
    norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
    trainable_layers: int = 2,
    returned_layers: Optional[List[int]] = None,
    extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
187
    backbone = mobilenet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
188
    return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks)
189

190

191
192
193
def _mobilenet_extractor(
    backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
    fpn: bool,
194
    trainable_layers: int,
195
196
197
198
    returned_layers: Optional[List[int]] = None,
    extra_blocks: Optional[ExtraFPNBlock] = None,
) -> nn.Module:
    backbone = backbone.features
199
    # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
200
    # The first and last blocks are always included because they are the C0 (conv1) and Cn.
201
    stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
202
203
204
    num_stages = len(stage_indices)

    # find the index of the layer from which we wont freeze
205
206
    if trainable_layers < 0 or trainable_layers > num_stages:
        raise ValueError(f"Trainable layers should be in the range [0,{num_stages}], got {trainable_layers} ")
207
    freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
208
209
210
211
212
213
214
215
216
217
218
219

    for b in backbone[:freeze_before]:
        for parameter in b.parameters():
            parameter.requires_grad_(False)

    out_channels = 256
    if fpn:
        if extra_blocks is None:
            extra_blocks = LastLevelMaxPool()

        if returned_layers is None:
            returned_layers = [num_stages - 2, num_stages - 1]
220
221
        if min(returned_layers) < 0 or max(returned_layers) >= num_stages:
            raise ValueError(f"Each returned layer should be in the range [0,{num_stages - 1}], got {returned_layers} ")
222
        return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)}
223
224
225
226
227
228
229
230
231

        in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
        return BackboneWithFPN(backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)
    else:
        m = nn.Sequential(
            backbone,
            # depthwise linear combination of channels to reduce their size
            nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
        )
232
        m.out_channels = out_channels  # type: ignore[assignment]
233
        return m