test_trt_convert_deformable_conv.py 9.3 KB
Newer Older
W
wangxinxin08 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
W
wangxinxin08 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
6
#
W
wangxinxin08 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
W
wangxinxin08 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import unittest
W
wangxinxin08 已提交
16
from functools import partial
17
from typing import Any, Dict, List
18 19 20 21 22 23

import numpy as np
from program_config import ProgramConfig, TensorConfig
from trt_layer_auto_scan_test import TrtLayerAutoScanTest

import paddle.inference as paddle_infer
W
wangxinxin08 已提交
24 25 26 27 28 29 30


class TrtConvertDeformableConvTest(TrtLayerAutoScanTest):
    def is_program_valid(self, program_config: ProgramConfig) -> bool:
        inputs = program_config.inputs
        weights = program_config.weights
        attrs = [
31
            program_config.ops[i].attrs for i in range(len(program_config.ops))
W
wangxinxin08 已提交
32 33
        ]

34 35 36 37
        if (
            inputs['input_data'].shape[1]
            != weights['filter_data'].shape[1] * attrs[0]['groups']
        ):
W
wangxinxin08 已提交
38 39 40 41 42
            return False

        return True

    def sample_program_configs(self):
43 44 45 46 47
        def compute_output_size(
            input_size: List[int],
            kernel_sizes: List[int],
            attrs: List[Dict[str, Any]],
        ):
W
wangxinxin08 已提交
48 49 50 51
            strides = attrs[0]['strides']
            paddings = attrs[0]['paddings']
            dilations = attrs[0]['dilations']
            output_size = []
52 53 54
            for i, k, s, p, d in zip(
                input_size, kernel_sizes, strides, paddings, dilations
            ):
W
wangxinxin08 已提交
55 56 57 58
                k = d * (k - 1) + 1
                output_size.append((i + 2 * p - k) // s + 1)
            return output_size

59 60 61 62 63 64
        def generate_input1(
            batch: int,
            input_size: List[int],
            kernel_sizes: List[int],
            attrs: List[Dict[str, Any]],
        ):
W
wangxinxin08 已提交
65 66
            return np.random.random([batch, 3] + input_size).astype(np.float32)

67 68 69 70 71 72
        def generate_offset1(
            batch: int,
            input_size: List[int],
            kernel_sizes: List[int],
            attrs: List[Dict[str, Any]],
        ):
W
wangxinxin08 已提交
73
            output_size = compute_output_size(input_size, kernel_sizes, attrs)
74 75 76 77 78 79 80 81 82 83
            return np.random.random(
                [batch, 2 * np.prod(kernel_sizes)] + output_size
            ).astype(np.float32)

        def generate_mask1(
            batch: int,
            input_size: List[int],
            kernel_sizes: List[int],
            attrs: List[Dict[str, Any]],
        ):
W
wangxinxin08 已提交
84
            output_size = compute_output_size(input_size, kernel_sizes, attrs)
85 86 87 88 89 90 91 92 93 94
            return np.random.random(
                [batch, np.prod(kernel_sizes)] + output_size
            ).astype(np.float32)

        def generate_filter1(
            batch: int,
            input_size: List[int],
            kernel_sizes: List[int],
            attrs: List[Dict[str, Any]],
        ):
W
wangxinxin08 已提交
95 96
            return np.random.random([6, 3] + kernel_sizes).astype(np.float32)

97
        for batch in [
98
            1,
99
        ]:
W
wangxinxin08 已提交
100 101 102 103
            for input_size in [[32, 32]]:
                for kernel_sizes in [[3, 3]]:
                    for strides in [[1, 1], [2, 2]]:
                        for paddings in [[1, 1], [0, 2]]:
104
                            for groups in [
105
                                1,
106
                            ]:
W
wangxinxin08 已提交
107
                                for dilations in [[1, 1], [2, 2]]:
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
                                    dics = [
                                        {
                                            "strides": strides,
                                            "paddings": paddings,
                                            "groups": groups,
                                            "dilations": dilations,
                                            "deformable_groups": 1,
                                            "im2col_step": 1,
                                        }
                                    ]

                                ops_config = [
                                    {
                                        "op_type": "deformable_conv",
                                        "op_inputs": {
                                            "Input": ["input_data"],
                                            "Offset": ["offset_data"],
                                            "Mask": ["mask_data"],
                                            "Filter": ["filter_data"],
                                        },
                                        "op_outputs": {
                                            "Output": ["output_data"]
                                        },
                                        "op_attrs": dics[0],
                                    }
                                ]
W
wangxinxin08 已提交
134 135 136 137 138
                                ops = self.generate_op_config(ops_config)

                                program_config = ProgramConfig(
                                    ops=ops,
                                    weights={
139 140 141 142 143 144 145 146 147
                                        "filter_data": TensorConfig(
                                            data_gen=partial(
                                                generate_filter1,
                                                batch,
                                                input_size,
                                                kernel_sizes,
                                                dics,
                                            )
                                        )
W
wangxinxin08 已提交
148 149
                                    },
                                    inputs={
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
                                        "input_data": TensorConfig(
                                            data_gen=partial(
                                                generate_input1,
                                                batch,
                                                input_size,
                                                kernel_sizes,
                                                dics,
                                            )
                                        ),
                                        "offset_data": TensorConfig(
                                            data_gen=partial(
                                                generate_offset1,
                                                batch,
                                                input_size,
                                                kernel_sizes,
                                                dics,
                                            )
                                        ),
                                        "mask_data": TensorConfig(
                                            data_gen=partial(
                                                generate_mask1,
                                                batch,
                                                input_size,
                                                kernel_sizes,
                                                dics,
                                            )
                                        ),
W
wangxinxin08 已提交
177
                                    },
178 179
                                    outputs=["output_data"],
                                )
W
wangxinxin08 已提交
180 181 182 183

                                yield program_config

    def sample_predictor_configs(
184 185
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        def generate_dynamic_shape(attrs):
            self.dynamic_shape.min_input_shape = {
                "input_data": [1, 3, 32, 32],
                "offset_data": [1, 18, 14, 14],
                "mask_data": [1, 9, 14, 14],
            }
            self.dynamic_shape.max_input_shape = {
                "input_data": [1, 3, 32, 32],
                "offset_data": [1, 18, 32, 32],
                "mask_data": [1, 9, 32, 32],
            }
            self.dynamic_shape.opt_input_shape = {
                "input_data": [1, 3, 32, 32],
                "offset_data": [1, 18, 14, 16],
                "mask_data": [1, 9, 14, 16],
            }

W
wangxinxin08 已提交
203 204 205 206 207 208 209 210 211 212
        def clear_dynamic_shape():
            self.dynamic_shape.min_input_shape = {}
            self.dynamic_shape.max_input_shape = {}
            self.dynamic_shape.opt_input_shape = {}

        def generate_trt_nodes_num(attrs, dynamic_shape):
            # TODO: This is just the example, need to be fixed.
            if len(attrs[0]['paddings']) == 4:
                return 1, 2
            else:
213
                return 1, 4
W
wangxinxin08 已提交
214 215

        attrs = [
216
            program_config.ops[i].attrs for i in range(len(program_config.ops))
W
wangxinxin08 已提交
217 218 219 220 221 222
        ]

        # for static_shape
        clear_dynamic_shape()
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), generate_trt_nodes_num(
223 224
            attrs, False
        ), 1e-5
225 226 227 228 229
        generate_dynamic_shape(attrs)
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), generate_trt_nodes_num(
            attrs, True
        ), (1e-5, 1e-5)
W
wangxinxin08 已提交
230 231 232 233 234 235 236 237

    def test(self):
        self.trt_param.workspace_size = 1 << 28
        self.run_test()


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