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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.

import logging
import unittest
from typing import Callable, Tuple

import torch
import torch.nn as nn
from fvcore.common.benchmark import benchmark
from pytorchvideo.layers.accelerator.mobile_cpu.convolutions import (
    Conv3d3x3x3DwBnAct,
    Conv3dPwBnAct,
)
from pytorchvideo.models.accelerator.mobile_cpu.residual_blocks import (
    X3dBottleneckBlock,
)
from torch.utils.mobile_optimizer import optimize_for_mobile


TORCH_VERSION: Tuple[int, ...] = tuple(int(x) for x in torch.__version__.split(".")[:2])
if TORCH_VERSION >= (1, 11):
    from torch.ao.quantization import (
        convert,
        DeQuantStub,
        fuse_modules,
        get_default_qconfig,
        prepare,
        QuantStub,
        # quantize_fx
    )
else:
    from torch.quantization import (
        convert,
        DeQuantStub,
        fuse_modules,
        get_default_qconfig,
        prepare,
        QuantStub,
        # quantize_fx
    )


class TestBenchmarkEfficientBlocks(unittest.TestCase):
    def setUp(self):
        super().setUp()
        torch.set_rng_state(torch.manual_seed(42).get_state())

    def test_benchmark_conv3d_pw_bn_relu(self, num_iters: int = 20) -> None:
        """
        Benchmark Conv3dPwBnAct with ReLU activation.
        Note efficient block Conv3dPwBnAct is designed for mobile cpu with qnnpack
        backend, and benchmarking on server with another backend (e.g., fbgemm) may
        have different latency result compared to running on mobile cpu with qnnpack.
        Running on x86 based server cpu with qnnpack may also have different latency as
        running on mobile cpu with qnnpack, as qnnpack is optimized for
        ARM based mobile cpu.
        Args:
            num_iters (int): number of iterations to perform benchmarking.
        """

        torch.backends.quantized.engine = "qnnpack"
        kwargs_list = [
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "out_channels": 108,
                "quantize": False,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "out_channels": 108,
                "quantize": False,
            },
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "out_channels": 108,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "out_channels": 108,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "out_channels": 108,
                "quantize": True,
                "native_conv3d_op_qnnpack": True,
            },
        ]

        def _benchmark_conv3d_pw_bn_relu_forward(**kwargs) -> Callable:
            assert kwargs["mode"] in ("original", "deployable"), (
                "kwargs['mode'] must be either 'original' or 'deployable',"
                "but got {}.".format(kwargs["mode"])
            )
            input_tensor = torch.randn((kwargs["input_blob_size"]))
            conv_block = Conv3dPwBnAct(
                kwargs["in_channels"],
                kwargs["out_channels"],
                use_bn=False,  # assume BN has already been fused for forward
            )

            if kwargs["mode"] == "deployable":
                native_conv3d_op_qnnpack = kwargs.get("native_conv3d_op_qnnpack", False)
                conv_block.convert(
                    kwargs["input_blob_size"],
                    convert_for_quantize=kwargs["quantize"],
                    native_conv3d_op_qnnpack=native_conv3d_op_qnnpack,
                )
            conv_block.eval()

            def func_to_benchmark_dummy() -> None:
                return

            if kwargs["quantize"] is True:
                if kwargs["mode"] == "original":  # manually fuse conv and relu
                    conv_block.kernel = fuse_modules(
                        conv_block.kernel, ["conv", "act.act"]
                    )
                conv_block = nn.Sequential(
                    QuantStub(),
                    conv_block,
                    DeQuantStub(),
                )

                conv_block.qconfig = get_default_qconfig("qnnpack")
                conv_block = prepare(conv_block)
                try:
                    conv_block = convert(conv_block)

                except Exception as e:
                    logging.info(
                        "benchmark_conv3d_pw_bn_relu: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )

                    return func_to_benchmark_dummy
            try:
                traced_model = torch.jit.trace(conv_block, input_tensor, strict=False)
            except Exception as e:
                logging.info(
                    "benchmark_conv3d_pw_bn_relu: "
                    "catch exception '{}' with kwargs of {}".format(e, kwargs)
                )

                return func_to_benchmark_dummy

            if kwargs["quantize"] is False:
                traced_model = optimize_for_mobile(traced_model)

            logging.info(f"model arch: {traced_model}")

            def func_to_benchmark() -> None:
                try:
                    _ = traced_model(input_tensor)
                except Exception as e:
                    logging.info(
                        "benchmark_conv3d_pw_bn_relu: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )

                return

            return func_to_benchmark

        benchmark(
            _benchmark_conv3d_pw_bn_relu_forward,
            "benchmark_conv3d_pw_bn_relu",
            kwargs_list,
            num_iters=num_iters,
            warmup_iters=2,
        )

        self.assertTrue(True)

    def test_benchmark_conv3d_3x3x3_dw_bn_relu(self, num_iters: int = 20) -> None:
        """
        Benchmark Conv3d3x3x3DwBnAct with ReLU activation.
        Note efficient block Conv3d3x3x3DwBnAct is designed for mobile cpu with qnnpack
        backend, and benchmarking on server with another backend (e.g., fbgemm) may have
        different latency result compared as running on mobile cpu.
        Args:
            num_iters (int): number of iterations to perform benchmarking.
        """
        torch.backends.quantized.engine = "qnnpack"
        kwargs_list = [
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "quantize": False,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "quantize": False,
            },
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 40, 40),
                "in_channels": 48,
                "quantize": True,
                "native_conv3d_op_qnnpack": True,
            },
        ]

        def _benchmark_conv3d_3x3x3_dw_bn_relu_forward(**kwargs) -> Callable:
            assert kwargs["mode"] in ("original", "deployable"), (
                "kwargs['mode'] must be either 'original' or 'deployable',"
                "but got {}.".format(kwargs["mode"])
            )
            input_tensor = torch.randn((kwargs["input_blob_size"]))
            conv_block = Conv3d3x3x3DwBnAct(
                kwargs["in_channels"],
                use_bn=False,  # assume BN has already been fused for forward
            )

            def func_to_benchmark_dummy() -> None:
                return

            if kwargs["mode"] == "deployable":
                native_conv3d_op_qnnpack = kwargs.get("native_conv3d_op_qnnpack", False)
                conv_block.convert(
                    kwargs["input_blob_size"],
                    convert_for_quantize=kwargs["quantize"],
                    native_conv3d_op_qnnpack=native_conv3d_op_qnnpack,
                )
            conv_block.eval()
            if kwargs["quantize"] is True:
                if kwargs["mode"] == "original":  # manually fuse conv and relu
                    conv_block.kernel = fuse_modules(
                        conv_block.kernel, ["conv", "act.act"]
                    )
                conv_block = nn.Sequential(
                    QuantStub(),
                    conv_block,
                    DeQuantStub(),
                )

                conv_block.qconfig = get_default_qconfig("qnnpack")
                conv_block = prepare(conv_block)
                try:
                    conv_block = convert(conv_block)
                except Exception as e:
                    logging.info(
                        "benchmark_conv3d_3x3x3_dw_bn_relu: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )

                    return func_to_benchmark_dummy
            try:
                traced_model = torch.jit.trace(conv_block, input_tensor, strict=False)
            except Exception as e:
                logging.info(
                    "benchmark_conv3d_3x3x3_dw_bn_relu: "
                    "catch exception '{}' with kwargs of {}".format(e, kwargs)
                )

                return func_to_benchmark_dummy
            if kwargs["quantize"] is False:
                traced_model = optimize_for_mobile(traced_model)

            logging.info(f"model arch: {traced_model}")

            def func_to_benchmark() -> None:
                try:
                    _ = traced_model(input_tensor)
                except Exception as e:
                    logging.info(
                        "benchmark_conv3d_3x3x3_dw_bn_relu: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )
                return

            return func_to_benchmark

        benchmark(
            _benchmark_conv3d_3x3x3_dw_bn_relu_forward,
            "benchmark_conv3d_3x3x3_dw_bn_relu",
            kwargs_list,
            num_iters=num_iters,
            warmup_iters=2,
        )

        self.assertTrue(True)

    def test_benchmark_x3d_bottleneck_block(self, num_iters: int = 20) -> None:
        """
        Benchmark X3dBottleneckBlock.
        Note efficient block X3dBottleneckBlock is designed for mobile cpu with qnnpack
        backend, and benchmarking on server/laptop may have different latency result
        compared to running on mobile cpu.
        Args:
            num_iters (int): number of iterations to perform benchmarking.
        """
        torch.backends.quantized.engine = "qnnpack"
        kwargs_list = [
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 20, 20),
                "in_channels": 48,
                "mid_channels": 108,
                "out_channels": 48,
                "quantize": False,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 20, 20),
                "in_channels": 48,
                "mid_channels": 108,
                "out_channels": 48,
                "quantize": False,
            },
            {
                "mode": "original",
                "input_blob_size": (1, 48, 4, 20, 20),
                "in_channels": 48,
                "mid_channels": 108,
                "out_channels": 48,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 20, 20),
                "in_channels": 48,
                "mid_channels": 108,
                "out_channels": 48,
                "quantize": True,
            },
            {
                "mode": "deployable",
                "input_blob_size": (1, 48, 4, 20, 20),
                "in_channels": 48,
                "mid_channels": 108,
                "out_channels": 48,
                "quantize": True,
                "native_conv3d_op_qnnpack": True,
            },
        ]

        def _benchmark_x3d_bottleneck_forward(**kwargs) -> Callable:
            assert kwargs["mode"] in ("original", "deployable"), (
                "kwargs['mode'] must be either 'original' or 'deployable',"
                "but got {}.".format(kwargs["mode"])
            )
            input_tensor = torch.randn((kwargs["input_blob_size"]))
            conv_block = X3dBottleneckBlock(
                kwargs["in_channels"],
                kwargs["mid_channels"],
                kwargs["out_channels"],
                use_bn=(False, False, False),  # Assume BN has been fused for forward
            )

            if kwargs["mode"] == "deployable":
                native_conv3d_op_qnnpack = kwargs.get("native_conv3d_op_qnnpack", False)
                conv_block.convert(
                    kwargs["input_blob_size"],
                    convert_for_quantize=kwargs["quantize"],
                    native_conv3d_op_qnnpack=native_conv3d_op_qnnpack,
                )
            conv_block.eval()

            def func_to_benchmark_dummy() -> None:
                return

            if kwargs["quantize"] is True:
                conv_block = nn.Sequential(
                    QuantStub(),
                    conv_block,
                    DeQuantStub(),
                )

                conv_block.qconfig = get_default_qconfig("qnnpack")
                conv_block = prepare(conv_block)
                try:
                    conv_block = convert(conv_block)
                    traced_model = torch.jit.trace(
                        conv_block, input_tensor, strict=False
                    )
                except Exception as e:
                    logging.info(
                        "benchmark_x3d_bottleneck_forward: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )

                    return func_to_benchmark_dummy

            try:
                traced_model = torch.jit.trace(conv_block, input_tensor, strict=False)
            except Exception as e:
                logging.info(
                    "benchmark_x3d_bottleneck_forward: "
                    "catch exception '{}' with kwargs of {}".format(e, kwargs)
                )

                return func_to_benchmark_dummy

            if kwargs["quantize"] is False:
                traced_model = optimize_for_mobile(traced_model)

            logging.info(f"model arch: {traced_model}")

            def func_to_benchmark() -> None:
                try:
                    _ = traced_model(input_tensor)
                except Exception as e:
                    logging.info(
                        "benchmark_x3d_bottleneck_forward: "
                        "catch exception '{}' with kwargs of {}".format(e, kwargs)
                    )
                return

            return func_to_benchmark

        benchmark(
            _benchmark_x3d_bottleneck_forward,
            "benchmark_x3d_bottleneck_forward",
            kwargs_list,
            num_iters=num_iters,
            warmup_iters=2,
        )

        self.assertTrue(True)