shufflenetv2.py 15.9 KB
Newer Older
1
2
from functools import partial
from typing import Any, List, Optional, Union
3

4
5
import torch
import torch.nn as nn
6
from torch import Tensor
7
from torchvision.models import shufflenetv2
8

9
from ...transforms._presets import ImageClassification
10
from .._api import Weights, WeightsEnum
11
from .._meta import _IMAGENET_CATEGORIES
12
from .._utils import _ovewrite_named_param, handle_legacy_interface
13
14
15
16
17
18
from ..shufflenetv2 import (
    ShuffleNet_V2_X0_5_Weights,
    ShuffleNet_V2_X1_0_Weights,
    ShuffleNet_V2_X1_5_Weights,
    ShuffleNet_V2_X2_0_Weights,
)
19
from .utils import _fuse_modules, _replace_relu, quantize_model
20

21

22
__all__ = [
23
    "QuantizableShuffleNetV2",
24
25
    "ShuffleNet_V2_X0_5_QuantizedWeights",
    "ShuffleNet_V2_X1_0_QuantizedWeights",
26
27
    "ShuffleNet_V2_X1_5_QuantizedWeights",
    "ShuffleNet_V2_X2_0_QuantizedWeights",
28
29
    "shufflenet_v2_x0_5",
    "shufflenet_v2_x1_0",
30
31
    "shufflenet_v2_x1_5",
    "shufflenet_v2_x2_0",
32
33
34
35
]


class QuantizableInvertedResidual(shufflenetv2.InvertedResidual):
36
    def __init__(self, *args: Any, **kwargs: Any) -> None:
37
        super().__init__(*args, **kwargs)
38
39
        self.cat = nn.quantized.FloatFunctional()

40
    def forward(self, x: Tensor) -> Tensor:
41
42
        if self.stride == 1:
            x1, x2 = x.chunk(2, dim=1)
43
            out = self.cat.cat([x1, self.branch2(x2)], dim=1)
44
        else:
45
            out = self.cat.cat([self.branch1(x), self.branch2(x)], dim=1)
46
47
48
49
50
51
52

        out = shufflenetv2.channel_shuffle(out, 2)

        return out


class QuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2):
53
54
    # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
    def __init__(self, *args: Any, **kwargs: Any) -> None:
55
        super().__init__(*args, inverted_residual=QuantizableInvertedResidual, **kwargs)  # type: ignore[misc]
56
57
        self.quant = torch.ao.quantization.QuantStub()
        self.dequant = torch.ao.quantization.DeQuantStub()
58

59
    def forward(self, x: Tensor) -> Tensor:
60
        x = self.quant(x)
61
        x = self._forward_impl(x)
62
63
64
        x = self.dequant(x)
        return x

65
    def fuse_model(self, is_qat: Optional[bool] = None) -> None:
66
67
68
        r"""Fuse conv/bn/relu modules in shufflenetv2 model

        Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization.
69
70
71
72
73
        Model is modified in place.

        .. note::
            Note that this operation does not change numerics
            and the model after modification is in floating point
74
75
        """
        for name, m in self._modules.items():
76
77
            if name in ["conv1", "conv5"] and m is not None:
                _fuse_modules(m, [["0", "1", "2"]], is_qat, inplace=True)
78
        for m in self.modules():
79
            if type(m) is QuantizableInvertedResidual:
80
                if len(m.branch1._modules.items()) > 0:
81
82
                    _fuse_modules(m.branch1, [["0", "1"], ["2", "3", "4"]], is_qat, inplace=True)
                _fuse_modules(
83
84
                    m.branch2,
                    [["0", "1", "2"], ["3", "4"], ["5", "6", "7"]],
85
                    is_qat,
86
87
88
89
                    inplace=True,
                )


90
def _shufflenetv2(
91
92
93
94
    stages_repeats: List[int],
    stages_out_channels: List[int],
    *,
    weights: Optional[WeightsEnum],
95
96
97
98
    progress: bool,
    quantize: bool,
    **kwargs: Any,
) -> QuantizableShuffleNetV2:
99
100
101
102
103
    if weights is not None:
        _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
        if "backend" in weights.meta:
            _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
    backend = kwargs.pop("backend", "fbgemm")
104

105
    model = QuantizableShuffleNetV2(stages_repeats, stages_out_channels, **kwargs)
106
107
108
109
    _replace_relu(model)
    if quantize:
        quantize_model(model, backend)

110
111
    if weights is not None:
        model.load_state_dict(weights.get_state_dict(progress=progress))
112
113
114
115

    return model


116
117
118
119
120
_COMMON_META = {
    "min_size": (1, 1),
    "categories": _IMAGENET_CATEGORIES,
    "backend": "fbgemm",
    "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models",
121
122
123
124
    "_docs": """
        These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized
        weights listed below.
    """,
125
126
127
128
129
130
131
132
133
134
135
}


class ShuffleNet_V2_X0_5_QuantizedWeights(WeightsEnum):
    IMAGENET1K_FBGEMM_V1 = Weights(
        url="https://download.pytorch.org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth",
        transforms=partial(ImageClassification, crop_size=224),
        meta={
            **_COMMON_META,
            "num_params": 1366792,
            "unquantized": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1,
136
137
138
139
140
            "_metrics": {
                "ImageNet-1K": {
                    "acc@1": 57.972,
                    "acc@5": 79.780,
                }
141
            },
142
143
144
145
146
147
148
149
150
151
152
153
154
        },
    )
    DEFAULT = IMAGENET1K_FBGEMM_V1


class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum):
    IMAGENET1K_FBGEMM_V1 = Weights(
        url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-db332c57.pth",
        transforms=partial(ImageClassification, crop_size=224),
        meta={
            **_COMMON_META,
            "num_params": 2278604,
            "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,
155
156
157
158
159
            "_metrics": {
                "ImageNet-1K": {
                    "acc@1": 68.360,
                    "acc@5": 87.582,
                }
160
            },
161
162
163
164
165
        },
    )
    DEFAULT = IMAGENET1K_FBGEMM_V1


166
167
168
169
170
171
172
173
174
class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum):
    IMAGENET1K_FBGEMM_V1 = Weights(
        url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth",
        transforms=partial(ImageClassification, crop_size=224, resize_size=232),
        meta={
            **_COMMON_META,
            "recipe": "https://github.com/pytorch/vision/pull/5906",
            "num_params": 3503624,
            "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1,
175
176
177
178
179
            "_metrics": {
                "ImageNet-1K": {
                    "acc@1": 72.052,
                    "acc@5": 90.700,
                }
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
            },
        },
    )
    DEFAULT = IMAGENET1K_FBGEMM_V1


class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum):
    IMAGENET1K_FBGEMM_V1 = Weights(
        url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth",
        transforms=partial(ImageClassification, crop_size=224, resize_size=232),
        meta={
            **_COMMON_META,
            "recipe": "https://github.com/pytorch/vision/pull/5906",
            "num_params": 7393996,
            "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1,
195
196
197
198
199
            "_metrics": {
                "ImageNet-1K": {
                    "acc@1": 75.354,
                    "acc@5": 92.488,
                }
200
201
202
203
204
205
            },
        },
    )
    DEFAULT = IMAGENET1K_FBGEMM_V1


206
207
208
209
210
211
212
213
@handle_legacy_interface(
    weights=(
        "pretrained",
        lambda kwargs: ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1
        if kwargs.get("quantize", False)
        else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1,
    )
)
214
def shufflenet_v2_x0_5(
215
216
    *,
    weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None,
217
218
219
220
    progress: bool = True,
    quantize: bool = False,
    **kwargs: Any,
) -> QuantizableShuffleNetV2:
221
222
    """
    Constructs a ShuffleNetV2 with 0.5x output channels, as described in
223
224
    `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
    <https://arxiv.org/abs/1807.11164>`__.
225

226
227
228
229
230
    .. note::
        Note that ``quantize = True`` returns a quantized model with 8 bit
        weights. Quantized models only support inference and run on CPUs.
        GPU inference is not yet supported.

231
    Args:
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The
            pretrained weights for the model. See
            :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr.
            Default is True.
        quantize (bool, optional): If True, return a quantized version of the model.
            Default is False.
        **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights
        :members:

    .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights
        :members:
        :noindex:
252
    """
253
    weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights)
254
    return _shufflenetv2(
255
        [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
256
    )
257
258


259
260
261
262
263
264
265
266
@handle_legacy_interface(
    weights=(
        "pretrained",
        lambda kwargs: ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1
        if kwargs.get("quantize", False)
        else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,
    )
)
267
def shufflenet_v2_x1_0(
268
269
    *,
    weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None,
270
271
272
273
    progress: bool = True,
    quantize: bool = False,
    **kwargs: Any,
) -> QuantizableShuffleNetV2:
274
275
    """
    Constructs a ShuffleNetV2 with 1.0x output channels, as described in
276
277
    `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
    <https://arxiv.org/abs/1807.11164>`__.
278

279
280
281
282
283
    .. note::
        Note that ``quantize = True`` returns a quantized model with 8 bit
        weights. Quantized models only support inference and run on CPUs.
        GPU inference is not yet supported.

284
    Args:
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The
            pretrained weights for the model. See
            :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr.
            Default is True.
        quantize (bool, optional): If True, return a quantized version of the model.
            Default is False.
        **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights
        :members:

    .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights
        :members:
        :noindex:
305
    """
306
    weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights)
307
    return _shufflenetv2(
308
        [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
309
    )
310
311
312
313
314
315
316
317
318
319
320


def shufflenet_v2_x1_5(
    *,
    weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None,
    progress: bool = True,
    quantize: bool = False,
    **kwargs: Any,
) -> QuantizableShuffleNetV2:
    """
    Constructs a ShuffleNetV2 with 1.5x output channels, as described in
321
322
    `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
    <https://arxiv.org/abs/1807.11164>`__.
323

324
325
326
327
328
    .. note::
        Note that ``quantize = True`` returns a quantized model with 8 bit
        weights. Quantized models only support inference and run on CPUs.
        GPU inference is not yet supported.

329
    Args:
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The
            pretrained weights for the model. See
            :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr.
            Default is True.
        quantize (bool, optional): If True, return a quantized version of the model.
            Default is False.
        **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights
        :members:

    .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights
        :members:
        :noindex:
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    """
    weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights)
    return _shufflenetv2(
        [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
    )


def shufflenet_v2_x2_0(
    *,
    weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None,
    progress: bool = True,
    quantize: bool = False,
    **kwargs: Any,
) -> QuantizableShuffleNetV2:
    """
    Constructs a ShuffleNetV2 with 2.0x output channels, as described in
366
367
    `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
    <https://arxiv.org/abs/1807.11164>`__.
368

369
370
371
372
373
    .. note::
        Note that ``quantize = True`` returns a quantized model with 8 bit
        weights. Quantized models only support inference and run on CPUs.
        GPU inference is not yet supported.

374
    Args:
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
        weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The
            pretrained weights for the model. See
            :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): If True, displays a progress bar of the download to stderr.
            Default is True.
        quantize (bool, optional): If True, return a quantized version of the model.
            Default is False.
        **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights
        :members:

    .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights
        :members:
        :noindex:
395
396
397
398
399
    """
    weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights)
    return _shufflenetv2(
        [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs
    )
400
401
402
403
404
405
406
407
408
409
410
411
412


# The dictionary below is internal implementation detail and will be removed in v0.15
from .._utils import _ModelURLs
from ..shufflenetv2 import model_urls  # noqa: F401


quant_model_urls = _ModelURLs(
    {
        "shufflenetv2_x0.5_fbgemm": ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1.url,
        "shufflenetv2_x1.0_fbgemm": ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1.url,
    }
)