test_meta_arch_rcnn.py 7.42 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved


import copy
import os
import unittest

import torch
10
from d2go.export.exporter import convert_and_export_predictor
11
from d2go.runner import GeneralizedRCNNRunner
12
13
14
from d2go.utils.testing.data_loader_helper import (
    create_detection_data_loader_on_toy_dataset,
)
15
from d2go.utils.testing.rcnn_helper import get_quick_test_config_opts, RCNNBaseTestCases
16
from mobile_cv.common.misc.file_utils import make_temp_directory
17
from mobile_cv.common.misc.oss_utils import is_oss
18
19


20
def _maybe_skip_test(self, predictor_type):
21
    if is_oss() and "@c2_ops" in predictor_type:
22
23
24
25
26
27
        self.skipTest("Caffe2 is not available for OSS")

    if not torch.cuda.is_available() and "_gpu" in predictor_type:
        self.skipTest("GPU is not available for exporting GPU model")


28
class TestFBNetV3MaskRCNNFP32(RCNNBaseTestCases.TemplateTestCase):
29
    def setup_custom_test(self):
Yanghan Wang's avatar
Yanghan Wang committed
30
        super().setup_custom_test()
31
32
33
34
35
        self.cfg.merge_from_file("detectron2go://mask_rcnn_fbnetv3a_dsmask_C4.yaml")

    def test_inference(self):
        self._test_inference()

Yanghan Wang's avatar
Yanghan Wang committed
36
37
    @RCNNBaseTestCases.expand_parameterized_test_export(
        [
Yanghan Wang's avatar
Yanghan Wang committed
38
            ["torchscript@c2_ops", True],
39
            ["torchscript", True],
Yanghan Wang's avatar
Yanghan Wang committed
40
            ["torchscript_int8@c2_ops", False],
Yanghan Wang's avatar
Yanghan Wang committed
41
42
43
44
            ["torchscript_int8", False],
        ]
    )
    def test_export(self, predictor_type, compare_match):
45
        _maybe_skip_test(self, predictor_type)
Yanghan Wang's avatar
Yanghan Wang committed
46
        self._test_export(predictor_type, compare_match=compare_match)
47
48


49
50
51
52
53
54
55
56
57
58
class TestFBNetV3MaskRCNNFPNFP32(RCNNBaseTestCases.TemplateTestCase):
    def setup_custom_test(self):
        super().setup_custom_test()
        self.cfg.merge_from_file("detectron2go://mask_rcnn_fbnetv3g_fpn.yaml")

    def test_inference(self):
        self._test_inference()

    @RCNNBaseTestCases.expand_parameterized_test_export(
        [
59
60
61
62
63
            # FIXME: exporting c2_ops for FPN model might not pass this test for certain
            # combination of image sizes and resizing targets. data points are:
            # - passes before D35238890: image_size and resizing target are both 32x64 (backbone's divisibility).
            # - doesn't pass after D35238890: image_size are 32x64, resizing to 5x10.
            ["torchscript@c2_ops", False],
64
65
66
67
68
69
            ["torchscript", True],
            ["torchscript_int8@c2_ops", False],
            ["torchscript_int8", False],
        ]
    )
    def test_export(self, predictor_type, compare_match):
70
        _maybe_skip_test(self, predictor_type)
71
72
73
        self._test_export(predictor_type, compare_match=compare_match)


74
75
class TestFBNetV3MaskRCNNQATEager(RCNNBaseTestCases.TemplateTestCase):
    def setup_custom_test(self):
Yanghan Wang's avatar
Yanghan Wang committed
76
        super().setup_custom_test()
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        self.cfg.merge_from_file("detectron2go://mask_rcnn_fbnetv3a_dsmask_C4.yaml")
        # enable QAT
        self.cfg.merge_from_list(
            [
                "QUANTIZATION.BACKEND",
                "qnnpack",
                "QUANTIZATION.QAT.ENABLED",
                "True",
            ]
        )
        # FIXME: NaiveSyncBN is not supported
        self.cfg.merge_from_list(["MODEL.FBNET_V2.NORM", "bn"])

    def test_inference(self):
        self._test_inference()

Yanghan Wang's avatar
Yanghan Wang committed
93
94
    @RCNNBaseTestCases.expand_parameterized_test_export(
        [
Yanghan Wang's avatar
Yanghan Wang committed
95
            ["torchscript_int8@c2_ops", False],  # TODO: fix mismatch
Yanghan Wang's avatar
Yanghan Wang committed
96
97
98
99
            ["torchscript_int8", False],  # TODO: fix mismatch
        ]
    )
    def test_export(self, predictor_type, compare_match):
100
        _maybe_skip_test(self, predictor_type)
Yanghan Wang's avatar
Yanghan Wang committed
101
        self._test_export(predictor_type, compare_match=compare_match)
102
103


104
class TestFBNetV3KeypointRCNNFP32(RCNNBaseTestCases.TemplateTestCase):
105
    def setup_custom_test(self):
Yanghan Wang's avatar
Yanghan Wang committed
106
        super().setup_custom_test()
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        self.cfg.merge_from_file("detectron2go://keypoint_rcnn_fbnetv3a_dsmask_C4.yaml")

        # FIXME: have to use qnnpack due to follow error:
        # Per Channel Quantization is currently disabled for transposed conv
        self.cfg.merge_from_list(
            [
                "QUANTIZATION.BACKEND",
                "qnnpack",
            ]
        )

    def test_inference(self):
        self._test_inference()

Yanghan Wang's avatar
Yanghan Wang committed
121
122
    @RCNNBaseTestCases.expand_parameterized_test_export(
        [
Yanghan Wang's avatar
Yanghan Wang committed
123
            ["torchscript_int8@c2_ops", False],  # TODO: fix mismatch
Yanghan Wang's avatar
Yanghan Wang committed
124
125
126
127
            ["torchscript_int8", False],  # TODO: fix mismatch
        ]
    )
    def test_export(self, predictor_type, compare_match):
128
        if is_oss() and "@c2_ops" in predictor_type:
Yanghan Wang's avatar
Yanghan Wang committed
129
            self.skipTest("Caffe2 is not available for OSS")
Yanghan Wang's avatar
Yanghan Wang committed
130
        self._test_export(predictor_type, compare_match=compare_match)
131
132
133
134
135
136
137
138
139
140
141
142


class TestTorchVisionExport(unittest.TestCase):
    def test_export_torchvision_format(self):
        runner = GeneralizedRCNNRunner()
        cfg = runner.get_default_cfg()
        cfg.merge_from_file("detectron2go://mask_rcnn_fbnetv3a_dsmask_C4.yaml")
        cfg.merge_from_list(get_quick_test_config_opts())

        cfg.merge_from_list(["MODEL.DEVICE", "cpu"])
        pytorch_model = runner.build_model(cfg, eval_only=True)

143
        from typing import Dict, List
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

        class Wrapper(torch.nn.Module):
            def __init__(self, model):
                super().__init__()
                self.model = model

            def forward(self, inputs: List[torch.Tensor]):
                x = inputs[0].unsqueeze(0) * 255
                scale = 320.0 / min(x.shape[-2], x.shape[-1])
                x = torch.nn.functional.interpolate(
                    x,
                    scale_factor=scale,
                    mode="bilinear",
                    align_corners=True,
                    recompute_scale_factor=True,
                )
                out = self.model(x[0])
                res: Dict[str, torch.Tensor] = {}
                res["boxes"] = out[0] / scale
                res["labels"] = out[2]
                res["scores"] = out[1]
                return inputs, [res]

        size_divisibility = max(pytorch_model.backbone.size_divisibility, 10)
        h, w = size_divisibility, size_divisibility * 2
169
170
171
        with create_detection_data_loader_on_toy_dataset(
            cfg, h, w, is_train=False
        ) as data_loader:
172
173
174
175
            with make_temp_directory("test_export_torchvision_format") as tmp_dir:
                predictor_path = convert_and_export_predictor(
                    cfg,
                    copy.deepcopy(pytorch_model),
176
                    "torchscript",
177
178
179
180
181
182
183
184
185
186
187
188
                    tmp_dir,
                    data_loader,
                )

                orig_model = torch.jit.load(os.path.join(predictor_path, "model.jit"))
                wrapped_model = Wrapper(orig_model)
                # optionally do a forward
                wrapped_model([torch.rand(3, 600, 600)])
                scripted_model = torch.jit.script(wrapped_model)
                scripted_model.save(os.path.join(tmp_dir, "new_file.pt"))


189
190
191
192
193
194
195
196
197
198
199
200
201
202
class TestMaskRCNNExportOptions(RCNNBaseTestCases.TemplateTestCase):
    def setup_custom_test(self):
        super().setup_custom_test()
        self.cfg.merge_from_file("detectron2go://mask_rcnn_fbnetv3a_dsmask_C4.yaml")

    def _get_test_image_sizes(self, is_train):
        # postprocessing requires no resize from "data loader"
        return self._get_test_image_size_no_resize(is_train)

    def test_tracing_with_postprocess(self):
        self.cfg.merge_from_list(["RCNN_EXPORT.INCLUDE_POSTPROCESS", True])
        self._test_export("torchscript@tracing", compare_match=True)


203
204
if __name__ == "__main__":
    unittest.main()