test_trt_convert_reshape.py 18.8 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.

15
import unittest
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
24 25 26 27 28


class TrtConvertReshapeTest(TrtLayerAutoScanTest):
    def is_program_valid(self, program_config: ProgramConfig) -> bool:
        attrs = [
29
            program_config.ops[i].attrs for i in range(len(program_config.ops))
30 31 32 33 34
        ]
        if self.dims == 1:
            if len(attrs[0]['shape']) != 1:
                return False

35
        # To test if the shape contains 0
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        if len(attrs[0]['shape']) == 3:
            if attrs[0]['shape'][1] == 0:
                if self.dims != 3:
                    return False

        if len(attrs[0]['shape']) == 4:
            if attrs[0]['shape'][2] == 0:
                if self.dims != 4:
                    return False

        return True

    def sample_program_configs(self):
        def generate_input1(attrs: List[Dict[str, Any]]):
            if self.dims == 4:
51
                self.input_shape = [1, 2, 4, 6]
52 53
                return np.ones([1, 2, 4, 6]).astype(np.float32)
            elif self.dims == 3:
54
                self.input_shape = [1, 8, 6]
55 56
                return np.ones([1, 8, 6]).astype(np.float32)
            elif self.dims == 2:
57
                self.input_shape = [1, 48]
58 59
                return np.ones([1, 48]).astype(np.float32)
            elif self.dims == 1:
60
                self.input_shape = [48]
61 62 63 64 65 66 67 68 69 70 71 72
                return np.ones([48]).astype(np.float32)

        def generate_weight1(attrs: List[Dict[str, Any]]):
            return np.array([1, 48]).astype(np.int32)

        def generate_shapeT1_data(attrs: List[Dict[str, Any]]):
            return np.array([2]).astype(np.int32)

        def generate_shapeT2_data(attrs: List[Dict[str, Any]]):
            return np.array([24]).astype(np.int32)

        for dims in [4, 3, 2, 1]:
73 74 75 76 77 78 79 80 81 82 83 84
            for shape in [
                [1, 6, 8],
                [1, 2, 4, 6],
                [1, 1, 0, 12],
                [1, 0, 6],
                [1, -1, 12],
                [2, -1],
                [3, 16],
                [3, 4, 4],
                [48],
                [-1, 48],
            ]:
85 86
                dics = [
                    {
87
                        "shape": shape,
88 89 90 91 92
                    },
                ]
                self.dims = dims
                dics_intput = [{"X": ["reshape_input"]}]

93 94 95 96 97 98 99 100
                ops_config = [
                    {
                        "op_type": "reshape",
                        "op_inputs": dics_intput[0],
                        "op_outputs": {"Out": ["reshape_out"]},
                        "op_attrs": dics[0],
                    }
                ]
101 102 103 104 105
                ops = self.generate_op_config(ops_config)
                program_config = ProgramConfig(
                    ops=ops,
                    weights={},
                    inputs={
106 107 108
                        "reshape_input": TensorConfig(
                            data_gen=partial(generate_input1, dics)
                        )
109
                    },
110 111
                    outputs=["reshape_out"],
                )
112

113
                yield program_config
114 115

    def sample_predictor_configs(
116 117
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
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
        def generate_dynamic_shape(attrs):
            if self.dims == 4:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 2, 4, 6]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 2, 4, 6]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 2, 4, 6]
                }
            elif self.dims == 3:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 8, 6]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 8, 6]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 8, 6]
                }
            elif self.dims == 2:
                self.dynamic_shape.min_input_shape = {"reshape_input": [1, 48]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [4, 48]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [1, 48]}
            elif self.dims == 1:
                self.dynamic_shape.min_input_shape = {"reshape_input": [48]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [48]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [48]}

        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):
154
            # in static shape mode, here is consistent with op_teller.cc
155 156
            if not dynamic_shape:
                if attrs[0]['shape'][0] == 0:
157
                    return 1, 2
158
                elif len(attrs[0]['shape']) == 1:
159
                    return 0, 3
160 161 162
                elif np.prod(attrs[0]['shape'][1:]) == np.prod(
                    self.input_shape[1:]
                ):
163 164 165
                    return 1, 2
                else:
                    return 0, 3
166 167 168
            return 1, 2

        attrs = [
169
            program_config.ops[i].attrs for i in range(len(program_config.ops))
170
        ]
171 172 173 174 175

        # for static_shape
        clear_dynamic_shape()
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), generate_trt_nodes_num(
176 177
            attrs, False
        ), 1e-5
178 179
        self.trt_param.precision = paddle_infer.PrecisionType.Half
        yield self.create_inference_config(), generate_trt_nodes_num(
180 181
            attrs, False
        ), 1e-3
182 183 184 185

        # for dynamic_shape
        generate_dynamic_shape(attrs)
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
186
        yield self.create_inference_config(), generate_trt_nodes_num(
187 188
            attrs, True
        ), 1e-5
189
        self.trt_param.precision = paddle_infer.PrecisionType.Half
190
        yield self.create_inference_config(), generate_trt_nodes_num(
191 192
            attrs, True
        ), 1e-3
193 194

    def add_skip_trt_case(self):
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        pass

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


# reshape having three inputs.
class TrtConvertReshapeTest2(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]]):
            if self.dims == 4:
                return np.random.random([1, 2, 4, 6]).astype(np.float32)
            elif self.dims == 3:
                return np.random.random([1, 8, 6]).astype(np.float32)
            elif self.dims == 2:
                return np.random.random([1, 48]).astype(np.float32)
            elif self.dims == 1:
                return np.random.random([48]).astype(np.float32)
217

218 219
        for dims in [4, 3, 2, 1]:
            for shape in [[-1, 48]]:
220 221 222 223 224 225
                dics = [
                    {
                        "shape": shape,
                    },
                    {},
                ]
226 227 228 229 230 231 232 233 234 235 236
                self.dims = dims
                dics_intput = [
                    {
                        "X": ["reshape_input"],
                        "ShapeTensor": ["shapeT1_data", "shapeT2_data"],
                    },
                ]
                ops_config = [
                    {
                        "op_type": "fill_constant",
                        "op_inputs": {},
237
                        "op_outputs": {"Out": ["shapeT1_data"]},
238 239 240 241 242 243 244 245 246
                        "op_attrs": {
                            "dtype": 2,
                            "str_value": "2",
                            "shape": [1],
                        },
                    },
                    {
                        "op_type": "fill_constant",
                        "op_inputs": {},
247
                        "op_outputs": {"Out": ["shapeT2_data"]},
248 249 250 251 252 253 254 255 256
                        "op_attrs": {
                            "dtype": 2,
                            "str_value": "24",
                            "shape": [1],
                        },
                    },
                    {
                        "op_type": "reshape",
                        "op_inputs": dics_intput[0],
257 258
                        "op_outputs": {"Out": ["reshape_out"]},
                        "op_attrs": dics[0],
259 260 261 262 263 264 265
                    },
                ]
                ops = self.generate_op_config(ops_config)
                program_config = ProgramConfig(
                    ops=ops,
                    weights={},
                    inputs={
266 267 268
                        "reshape_input": TensorConfig(
                            data_gen=partial(generate_input1, dics)
                        )
269
                    },
270 271
                    outputs=["reshape_out"],
                )
272 273 274 275

                yield program_config

    def sample_predictor_configs(
276 277
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
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
        def generate_dynamic_shape():
            if self.dims == 4:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 2, 4, 6]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 2, 4, 6]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 2, 4, 6]
                }
            elif self.dims == 3:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 8, 6]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 8, 6]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 8, 6]
                }
            elif self.dims == 2:
                self.dynamic_shape.min_input_shape = {"reshape_input": [1, 48]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [4, 48]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [1, 48]}
            elif self.dims == 1:
                self.dynamic_shape.min_input_shape = {"reshape_input": [48]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [48]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [48]}

        # for dynamic_shape
        generate_dynamic_shape()
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), (1, 2), 1e-5
        self.trt_param.precision = paddle_infer.PrecisionType.Half
313
        yield self.create_inference_config(), (1, 2), 1e-3
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

    def add_skip_trt_case(self):
        pass

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


# reshape having 2 inputs.
class TrtConvertReshapeTest3(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]]):
            if self.dims == 4:
                return np.random.random([1, 2, 12, 6]).astype(np.float32)
            elif self.dims == 3:
                return np.random.random([1, 8, 18]).astype(np.float32)
            elif self.dims == 2:
                return np.random.random([1, 144]).astype(np.float32)
            elif self.dims == 1:
                return np.random.random([144]).astype(np.float32)

        for dims in [4, 3, 2, 1]:
            for shape in [[-1, 144]]:
341 342 343 344 345 346
                dics = [
                    {
                        "shape": shape,
                    },
                    {},
                ]
347 348 349 350 351 352 353 354 355 356 357
                self.dims = dims
                dics_intput = [
                    {
                        "X": ["reshape_input"],
                        "shape_data": ["shape_data"],
                    },
                ]
                ops_config = [
                    {
                        "op_type": "fill_constant",
                        "op_inputs": {},
358
                        "op_outputs": {"Out": ["shape_data"]},
359 360 361 362 363 364 365 366 367
                        "op_attrs": {
                            "dtype": 2,
                            "str_value": "12",
                            "shape": [2],
                        },
                    },
                    {
                        "op_type": "reshape",
                        "op_inputs": dics_intput[0],
368 369
                        "op_outputs": {"Out": ["reshape_out"]},
                        "op_attrs": dics[0],
370 371 372 373 374 375 376
                    },
                ]
                ops = self.generate_op_config(ops_config)
                program_config = ProgramConfig(
                    ops=ops,
                    weights={},
                    inputs={
377 378 379
                        "reshape_input": TensorConfig(
                            data_gen=partial(generate_input1, dics)
                        )
380
                    },
381 382
                    outputs=["reshape_out"],
                )
383 384 385 386

                yield program_config

    def sample_predictor_configs(
387 388
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
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
        def generate_dynamic_shape():
            if self.dims == 4:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 2, 12, 6]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 2, 12, 6]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 2, 12, 6]
                }
            elif self.dims == 3:
                self.dynamic_shape.min_input_shape = {
                    "reshape_input": [1, 8, 18]
                }
                self.dynamic_shape.max_input_shape = {
                    "reshape_input": [4, 8, 18]
                }
                self.dynamic_shape.opt_input_shape = {
                    "reshape_input": [1, 8, 18]
                }
            elif self.dims == 2:
                self.dynamic_shape.min_input_shape = {"reshape_input": [1, 144]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [4, 144]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [1, 144]}
            elif self.dims == 1:
                self.dynamic_shape.min_input_shape = {"reshape_input": [144]}
                self.dynamic_shape.max_input_shape = {"reshape_input": [144]}
                self.dynamic_shape.opt_input_shape = {"reshape_input": [144]}

        # for dynamic_shape
        generate_dynamic_shape()
        self.trt_param.precision = paddle_infer.PrecisionType.Float32
        yield self.create_inference_config(), (1, 2), 1e-5
        self.trt_param.precision = paddle_infer.PrecisionType.Half
424
        yield self.create_inference_config(), (1, 2), 1e-3
425 426 427

    def add_skip_trt_case(self):
        pass
428 429 430 431 432 433

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


434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
class TrtConvertReshapeZeroDimsTest(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]]):
            if self.dims > 0:
                self.input_shape = [1] * self.dims
                return np.random.random(self.input_shape).astype(np.float32)
            elif self.dims == 0:
                self.input_shape = []
                return np.random.random([]).astype(np.float32)

        for dims in [0, 1, 2, 3]:
            for shape in [
                [],
                [1, 1],
            ]:
                dics = [
                    {
                        "shape": shape,
                    },
                ]
                self.dims = dims
                dics_intput = [{"X": ["reshape_input"]}]

                ops_config = [
                    {
                        "op_type": "reshape",
                        "op_inputs": dics_intput[0],
                        "op_outputs": {"Out": ["reshape_out"]},
                        "op_attrs": dics[0],
                    }
                ]
                ops = self.generate_op_config(ops_config)
                program_config = ProgramConfig(
                    ops=ops,
                    weights={},
                    inputs={
                        "reshape_input": TensorConfig(
                            data_gen=partial(generate_input1, dics)
                        )
                    },
                    outputs=["reshape_out"],
                )

                yield program_config

    def sample_predictor_configs(
        self, program_config
    ) -> (paddle_infer.Config, List[int], float):
        def generate_dynamic_shape(attrs):
            self.dynamic_shape.min_input_shape = {
                "reshape_input": self.input_shape
            }
            self.dynamic_shape.max_input_shape = {
                "reshape_input": self.input_shape
            }
            self.dynamic_shape.opt_input_shape = {
                "reshape_input": self.input_shape
            }

        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):
            # only test dynamic shape mode
            return 1, 2

        attrs = [
            program_config.ops[i].attrs for i in range(len(program_config.ops))
        ]

        # for dynamic_shape
        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
        self.trt_param.precision = paddle_infer.PrecisionType.Half
        yield self.create_inference_config(), generate_trt_nodes_num(
            attrs, True
        ), 1e-3

    def add_skip_trt_case(self):
        pass

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


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