predict.py 3.9 KB
Newer Older
W
WuHaobo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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 16 17
import sys
sys.path.insert(0, ".")
import tools.infer.utils as utils
W
WuHaobo 已提交
18
import numpy as np
19
import cv2
S
fix  
shippingwang 已提交
20
import time
W
WuHaobo 已提交
21

L
littletomatodonkey 已提交
22 23
from paddle.inference import Config
from paddle.inference import create_predictor
W
WuHaobo 已提交
24

littletomatodonkey's avatar
littletomatodonkey 已提交
25

L
littletomatodonkey 已提交
26 27
def create_paddle_predictor(args):
    config = Config(args.model_file, args.params_file)
S
shippingwang 已提交
28

W
WuHaobo 已提交
29
    if args.use_gpu:
S
fix  
shippingwang 已提交
30
        config.enable_use_gpu(args.gpu_mem, 0)
W
WuHaobo 已提交
31 32
    else:
        config.disable_gpu()
T
Tingquan Gao 已提交
33 34 35 36
        if args.enable_mkldnn:
            # cache 10 different shapes for mkldnn to avoid memory leak
            config.set_mkldnn_cache_capacity(10)
            config.enable_mkldnn()
S
shippingwang 已提交
37

S
fix  
shippingwang 已提交
38
    config.disable_glog_info()
littletomatodonkey's avatar
littletomatodonkey 已提交
39
    config.switch_ir_optim(args.ir_optim)  # default true
W
WuHaobo 已提交
40 41
    if args.use_tensorrt:
        config.enable_tensorrt_engine(
L
littletomatodonkey 已提交
42 43
            precision_mode=Config.PrecisionType.Half
            if args.use_fp16 else Config.PrecisionType.Float32,
littletomatodonkey's avatar
littletomatodonkey 已提交
44
            max_batch_size=args.batch_size)
S
fix  
shippingwang 已提交
45 46 47 48

    config.enable_memory_optim()
    # use zero copy
    config.switch_use_feed_fetch_ops(False)
L
littletomatodonkey 已提交
49
    predictor = create_predictor(config)
W
WuHaobo 已提交
50 51 52 53

    return predictor


54
def main(args):
S
shippingwang 已提交
55 56
    if not args.enable_benchmark:
        assert args.batch_size == 1
W
WuHaobo 已提交
57
        assert args.use_fp16 is False
S
shippingwang 已提交
58
    else:
W
WuHaobo 已提交
59
        assert args.use_gpu is True
60
        assert args.model is not None
S
fix  
shippingwang 已提交
61
    # HALF precission predict only work when using tensorrt
W
WuHaobo 已提交
62 63
    if args.use_fp16 is True:
        assert args.use_tensorrt is True
S
shippingwang 已提交
64

L
littletomatodonkey 已提交
65
    predictor = create_paddle_predictor(args)
W
WuHaobo 已提交
66

S
fix  
shippingwang 已提交
67
    input_names = predictor.get_input_names()
L
littletomatodonkey 已提交
68
    input_tensor = predictor.get_input_handle(input_names[0])
littletomatodonkey's avatar
littletomatodonkey 已提交
69 70

    output_names = predictor.get_output_names()
L
littletomatodonkey 已提交
71
    output_tensor = predictor.get_output_handle(output_names[0])
littletomatodonkey's avatar
littletomatodonkey 已提交
72 73 74

    test_num = 500
    test_time = 0.0
S
fix  
shippingwang 已提交
75
    if not args.enable_benchmark:
76 77 78 79 80 81 82 83 84
        # for PaddleHubServing
        if args.hubserving:
            img = args.image_file
        # for predict only
        else:
            img = cv2.imread(args.image_file)[:, :, ::-1]
        assert img is not None, "Error in loading image: {}".format(
            args.image_file)
        inputs = utils.preprocess(img, args)
littletomatodonkey's avatar
littletomatodonkey 已提交
85 86 87 88 89
        inputs = np.expand_dims(
            inputs, axis=0).repeat(
                args.batch_size, axis=0).copy()
        input_tensor.copy_from_cpu(inputs)

L
littletomatodonkey 已提交
90
        predictor.run()
littletomatodonkey's avatar
littletomatodonkey 已提交
91 92

        output = output_tensor.copy_to_cpu()
93
        return utils.postprocess(output, args)
S
fix  
shippingwang 已提交
94
    else:
littletomatodonkey's avatar
littletomatodonkey 已提交
95 96 97 98 99 100
        for i in range(0, test_num + 10):
            inputs = np.random.rand(args.batch_size, 3, 224,
                                    224).astype(np.float32)
            start_time = time.time()
            input_tensor.copy_from_cpu(inputs)

L
littletomatodonkey 已提交
101
            predictor.run()
S
fix  
shippingwang 已提交
102

littletomatodonkey's avatar
littletomatodonkey 已提交
103 104 105 106
            output = output_tensor.copy_to_cpu()
            output = output.flatten()
            if i >= 10:
                test_time += time.time() - start_time
littletomatodonkey's avatar
littletomatodonkey 已提交
107
            time.sleep(0.01)  # sleep for T4 GPU
S
fix  
shippingwang 已提交
108

littletomatodonkey's avatar
littletomatodonkey 已提交
109
        fp_message = "FP16" if args.use_fp16 else "FP32"
littletomatodonkey's avatar
littletomatodonkey 已提交
110 111
        trt_msg = "using tensorrt" if args.use_tensorrt else "not using tensorrt"
        print("{0}\t{1}\t{2}\tbatch size: {3}\ttime(ms): {4}".format(
112 113
            args.model, trt_msg, fp_message, args.batch_size, 1000 * test_time
            / test_num))
W
WuHaobo 已提交
114 115 116


if __name__ == "__main__":
117 118 119 120 121
    args = utils.parse_args()
    classes, scores = main(args)
    print("Current image file: {}".format(args.image_file))
    print("\ttop-1 class: {0}".format(classes[0]))
    print("\ttop-1 score: {0}".format(scores[0]))