test_trt_convert_batch_norm.py 12.0 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
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
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
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.

W
Wilber 已提交
15
import unittest
16
from functools import partial
17
from typing import Any, Dict, List
18

19 20 21 22 23 24
import numpy as np
from program_config import ProgramConfig, TensorConfig
from trt_layer_auto_scan_test import SkipReasons, TrtLayerAutoScanTest

import paddle.inference as paddle_infer

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

class TrtConvertBatchNormTest(TrtLayerAutoScanTest):
    def is_program_valid(self, program_config: ProgramConfig) -> bool:
        return True

    def sample_program_configs(self):
        def generate_input1(attrs: List[Dict[str, Any]], batch):
            if self.dims == 4:
                if attrs[0]['data_layout'] == "NCHW":
                    return np.ones([batch, 3, 24, 24]).astype(np.float32)
                elif attrs[0]['data_layout'] == "NHWC":
                    return np.ones([batch, 24, 24, 3]).astype(np.float32)
            elif self.dims == 3:
                return np.ones([batch, 3, 24]).astype(np.float32)
            elif self.dims == 2:
                return np.ones([batch, 3]).astype(np.float32)

        def generate_bias(attrs: List[Dict[str, Any]], batch):
            return np.full((3), 0.9).astype("float32")

        def generate_mean(attrs: List[Dict[str, Any]], batch):
            return np.full((3), 0.9).astype("float32")

        def generate_scale(attrs: List[Dict[str, Any]], batch):
            return np.full((3), 1.1).astype("float32")

        def generate_variance(attrs: List[Dict[str, Any]], batch):
            return np.full((3), 1.2).astype("float32")

        def generate_MomentumTensor(attrs: List[Dict[str, Any]], batch):
            return np.full((3), 0.9).astype("float32")

        for dims in [2, 3, 4]:
            for num_input in [0, 1]:
59
                for batch in [1, 4]:
60 61 62 63 64
                    for epsilon in [1e-6, 1e-5, 1e-4]:
                        for data_layout in ["NCHW"]:
                            for momentum in [0.9, 0.8]:
                                self.num_input = num_input
                                self.dims = dims
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
                                dics = [
                                    {
                                        "epsilon": epsilon,
                                        "data_layout": data_layout,
                                        "momentum": momentum,
                                        "is_test": True,
                                        "trainable_statistics": False,
                                    },
                                    {},
                                ]
                                dics_intput = [
                                    {
                                        "X": ["batch_norm_input"],
                                        "Bias": ["Bias"],
                                        "Mean": ["Mean"],
                                        "Scale": ["Scale"],
                                        "Variance": ["Variance"],
                                        "MomentumTensor": ["MomentumTensor"],
                                    },
                                    {
                                        "X": ["batch_norm_input"],
                                        "Bias": ["Bias"],
                                        "Mean": ["Mean"],
                                        "Scale": ["Scale"],
                                        "Variance": ["Variance"],
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
                                ]
                                dics_intputs = [
                                    {
                                        "Bias": TensorConfig(
                                            data_gen=partial(
                                                generate_bias, dics, batch
                                            )
                                        ),
                                        "Mean": TensorConfig(
                                            data_gen=partial(
                                                generate_mean, dics, batch
                                            )
                                        ),
                                        "Scale": TensorConfig(
                                            data_gen=partial(
                                                generate_scale, dics, batch
                                            )
                                        ),
                                        "Variance": TensorConfig(
                                            data_gen=partial(
                                                generate_variance, dics, batch
                                            )
                                        ),
                                        "MomentumTensor": TensorConfig(
                                            data_gen=partial(
                                                generate_MomentumTensor,
                                                dics,
                                                batch,
                                            )
                                        ),
                                    },
                                    {
                                        "Bias": TensorConfig(
                                            data_gen=partial(
                                                generate_bias, dics, batch
                                            )
                                        ),
                                        "Mean": TensorConfig(
                                            data_gen=partial(
                                                generate_mean, dics, batch
                                            )
                                        ),
                                        "Scale": TensorConfig(
                                            data_gen=partial(
                                                generate_scale, dics, batch
                                            )
                                        ),
                                        "Variance": TensorConfig(
                                            data_gen=partial(
                                                generate_variance, dics, batch
                                            )
                                        ),
                                    },
                                ]
                                ops_config = [
                                    {
                                        "op_type": "batch_norm",
                                        "op_inputs": dics_intput[num_input],
                                        "op_outputs": {
                                            "Y": ["batch_norm_out"],
                                            "MeanOut": ["Mean"],
                                            "VarianceOut": ["Variance"],
                                            "SavedMean": ["SavedMean"],
                                            "SavedVariance": ["SavedVariance"],
                                        },
                                        "op_attrs": dics[0],
                                    }
                                ]
159 160 161 162 163
                                ops = self.generate_op_config(ops_config)
                                program_config = ProgramConfig(
                                    ops=ops,
                                    weights=dics_intputs[num_input],
                                    inputs={
164 165 166 167 168
                                        "batch_norm_input": TensorConfig(
                                            data_gen=partial(
                                                generate_input1, dics, batch
                                            )
                                        )
169
                                    },
170 171
                                    outputs=["batch_norm_out"],
                                )
172 173 174 175

                                yield program_config

    def sample_predictor_configs(
176 177
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
178 179 180 181
        def generate_dynamic_shape(attrs):
            if self.dims == 4:
                if attrs[0]['data_layout'] == "NCHW":
                    self.dynamic_shape.min_input_shape = {
182
                        "batch_norm_input": [1, 3, 12, 12]
183 184
                    }
                    self.dynamic_shape.max_input_shape = {
185
                        "batch_norm_input": [4, 3, 24, 24]
186 187
                    }
                    self.dynamic_shape.opt_input_shape = {
188
                        "batch_norm_input": [1, 3, 24, 24]
189 190 191
                    }
                elif attrs[0]['data_layout'] == "NHWC":
                    self.dynamic_shape.min_input_shape = {
192
                        "batch_norm_input": [1, 12, 12, 3]
193 194
                    }
                    self.dynamic_shape.max_input_shape = {
195
                        "batch_norm_input": [4, 24, 24, 3]
196 197
                    }
                    self.dynamic_shape.opt_input_shape = {
198
                        "batch_norm_input": [1, 24, 24, 3]
199 200 201
                    }
            elif self.dims == 3:
                self.dynamic_shape.min_input_shape = {
202
                    "batch_norm_input": [1, 3, 12]
203 204
                }
                self.dynamic_shape.max_input_shape = {
205
                    "batch_norm_input": [4, 3, 24]
206 207
                }
                self.dynamic_shape.opt_input_shape = {
208
                    "batch_norm_input": [1, 3, 24]
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
                }
            elif self.dims == 2:
                self.dynamic_shape.min_input_shape = {
                    "batch_norm_input": [1, 3]
                }
                self.dynamic_shape.max_input_shape = {
                    "batch_norm_input": [4, 3]
                }
                self.dynamic_shape.opt_input_shape = {
                    "batch_norm_input": [1, 3]
                }

        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):
            return 1, 2

        attrs = [
230
            program_config.ops[i].attrs for i in range(len(program_config.ops))
231 232 233 234 235
        ]
        # for static_shape
        clear_dynamic_shape()
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), generate_trt_nodes_num(
236 237
            attrs, False
        ), 1e-5
238 239
        self.trt_param.precision = paddle_infer.PrecisionType.Half
        yield self.create_inference_config(), generate_trt_nodes_num(
240 241
            attrs, False
        ), (1e-3, 1e-3)
242 243 244 245

        # for dynamic_shape
        generate_dynamic_shape(attrs)
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
246
        yield self.create_inference_config(), generate_trt_nodes_num(
247 248
            attrs, True
        ), 1e-5
249
        self.trt_param.precision = paddle_infer.PrecisionType.Half
250
        yield self.create_inference_config(), generate_trt_nodes_num(
251 252
            attrs, True
        ), (1e-3, 1e-3)
253 254 255 256 257 258 259

    def add_skip_trt_case(self):
        def teller1(program_config, predictor_config):
            if len(program_config.weights) == 5:
                return True
            return False

260 261 262 263 264
        self.add_skip_case(
            teller1,
            SkipReasons.TRT_NOT_SUPPORT,
            "INPUT MomentumTensor NOT SUPPORT",
        )
265 266 267 268 269 270 271 272

    def test(self):
        self.add_skip_trt_case()
        self.run_test()


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