predict.py 4.9 KB
Newer Older
W
WuHaobo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.

import argparse
W
WuHaobo 已提交
16
import utils
W
WuHaobo 已提交
17
import numpy as np
S
fix  
shippingwang 已提交
18
import time
W
WuHaobo 已提交
19

L
littletomatodonkey 已提交
20 21
from paddle.inference import Config
from paddle.inference import create_predictor
W
WuHaobo 已提交
22

littletomatodonkey's avatar
littletomatodonkey 已提交
23

W
WuHaobo 已提交
24 25 26 27 28 29 30 31
def parse_args():
    def str2bool(v):
        return v.lower() in ("true", "t", "1")

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--image_file", type=str)
    parser.add_argument("-m", "--model_file", type=str)
    parser.add_argument("-p", "--params_file", type=str)
S
fix  
shippingwang 已提交
32 33
    parser.add_argument("-b", "--batch_size", type=int, default=1)
    parser.add_argument("--use_fp16", type=str2bool, default=False)
W
WuHaobo 已提交
34 35 36
    parser.add_argument("--use_gpu", type=str2bool, default=True)
    parser.add_argument("--ir_optim", type=str2bool, default=True)
    parser.add_argument("--use_tensorrt", type=str2bool, default=False)
S
fix  
shippingwang 已提交
37 38 39
    parser.add_argument("--gpu_mem", type=int, default=8000)
    parser.add_argument("--enable_benchmark", type=str2bool, default=False)
    parser.add_argument("--model_name", type=str)
W
WuHaobo 已提交
40 41 42 43

    return parser.parse_args()


L
littletomatodonkey 已提交
44 45
def create_paddle_predictor(args):
    config = Config(args.model_file, args.params_file)
S
shippingwang 已提交
46

W
WuHaobo 已提交
47
    if args.use_gpu:
S
fix  
shippingwang 已提交
48
        config.enable_use_gpu(args.gpu_mem, 0)
W
WuHaobo 已提交
49 50
    else:
        config.disable_gpu()
S
shippingwang 已提交
51

S
fix  
shippingwang 已提交
52
    config.disable_glog_info()
littletomatodonkey's avatar
littletomatodonkey 已提交
53
    config.switch_ir_optim(args.ir_optim)  # default true
W
WuHaobo 已提交
54 55
    if args.use_tensorrt:
        config.enable_tensorrt_engine(
L
littletomatodonkey 已提交
56 57
            precision_mode=Config.PrecisionType.Half
            if args.use_fp16 else Config.PrecisionType.Float32,
littletomatodonkey's avatar
littletomatodonkey 已提交
58
            max_batch_size=args.batch_size)
S
fix  
shippingwang 已提交
59 60 61 62

    config.enable_memory_optim()
    # use zero copy
    config.switch_use_feed_fetch_ops(False)
L
littletomatodonkey 已提交
63
    predictor = create_predictor(config)
W
WuHaobo 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77

    return predictor


def create_operators():
    size = 224
    img_mean = [0.485, 0.456, 0.406]
    img_std = [0.229, 0.224, 0.225]
    img_scale = 1.0 / 255.0

    decode_op = utils.DecodeImage()
    resize_op = utils.ResizeImage(resize_short=256)
    crop_op = utils.CropImage(size=(size, size))
    normalize_op = utils.NormalizeImage(
littletomatodonkey's avatar
littletomatodonkey 已提交
78
        scale=img_scale, mean=img_mean, std=img_std)
W
WuHaobo 已提交
79 80 81 82 83 84
    totensor_op = utils.ToTensor()

    return [decode_op, resize_op, crop_op, normalize_op, totensor_op]


def preprocess(fname, ops):
W
WuHaobo 已提交
85
    data = open(fname, 'rb').read()
W
WuHaobo 已提交
86 87 88 89 90 91 92 93
    for op in ops:
        data = op(data)

    return data


def main():
    args = parse_args()
S
shippingwang 已提交
94 95 96

    if not args.enable_benchmark:
        assert args.batch_size == 1
W
WuHaobo 已提交
97
        assert args.use_fp16 is False
S
shippingwang 已提交
98
    else:
W
WuHaobo 已提交
99
        assert args.use_gpu is True
S
shippingwang 已提交
100
        assert args.model_name is not None
S
fix  
shippingwang 已提交
101
    # HALF precission predict only work when using tensorrt
W
WuHaobo 已提交
102 103
    if args.use_fp16 is True:
        assert args.use_tensorrt is True
S
shippingwang 已提交
104

W
WuHaobo 已提交
105
    operators = create_operators()
L
littletomatodonkey 已提交
106
    predictor = create_paddle_predictor(args)
W
WuHaobo 已提交
107

S
fix  
shippingwang 已提交
108
    input_names = predictor.get_input_names()
L
littletomatodonkey 已提交
109
    input_tensor = predictor.get_input_handle(input_names[0])
littletomatodonkey's avatar
littletomatodonkey 已提交
110 111

    output_names = predictor.get_output_names()
L
littletomatodonkey 已提交
112
    output_tensor = predictor.get_output_handle(output_names[0])
littletomatodonkey's avatar
littletomatodonkey 已提交
113 114 115

    test_num = 500
    test_time = 0.0
S
fix  
shippingwang 已提交
116
    if not args.enable_benchmark:
littletomatodonkey's avatar
littletomatodonkey 已提交
117 118 119 120 121 122
        inputs = preprocess(args.image_file, operators)
        inputs = np.expand_dims(
            inputs, axis=0).repeat(
                args.batch_size, axis=0).copy()
        input_tensor.copy_from_cpu(inputs)

L
littletomatodonkey 已提交
123
        predictor.run()
littletomatodonkey's avatar
littletomatodonkey 已提交
124 125 126 127 128

        output = output_tensor.copy_to_cpu()
        output = output.flatten()
        cls = np.argmax(output)
        score = output[cls]
littletomatodonkey's avatar
littletomatodonkey 已提交
129 130 131
        print("Current image file: {}".format(args.image_file))
        print("\ttop-1 class: {0}".format(cls))
        print("\ttop-1 score: {0}".format(score))
S
fix  
shippingwang 已提交
132
    else:
littletomatodonkey's avatar
littletomatodonkey 已提交
133 134 135 136 137 138
        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 已提交
139
            predictor.run()
S
fix  
shippingwang 已提交
140

littletomatodonkey's avatar
littletomatodonkey 已提交
141 142 143 144
            output = output_tensor.copy_to_cpu()
            output = output.flatten()
            if i >= 10:
                test_time += time.time() - start_time
littletomatodonkey's avatar
littletomatodonkey 已提交
145
            time.sleep(0.01)  # sleep for T4 GPU
S
fix  
shippingwang 已提交
146

littletomatodonkey's avatar
littletomatodonkey 已提交
147
        fp_message = "FP16" if args.use_fp16 else "FP32"
littletomatodonkey's avatar
littletomatodonkey 已提交
148 149 150 151
        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(
            args.model_name, trt_msg, fp_message, args.batch_size, 1000 *
            test_time / test_num))
W
WuHaobo 已提交
152 153 154 155


if __name__ == "__main__":
    main()