predict.py 5.6 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 19
import logging
import time
W
WuHaobo 已提交
20

W
WuHaobo 已提交
21 22
from paddle.fluid.core import AnalysisConfig
from paddle.fluid.core import create_paddle_predictor
S
fix  
shippingwang 已提交
23 24
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
W
WuHaobo 已提交
25

littletomatodonkey's avatar
littletomatodonkey 已提交
26

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

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--image_file", type=str)
33
    parser.add_argument("-d", "--image_dir", type=str)
W
WuHaobo 已提交
34 35
    parser.add_argument("-m", "--model_file", type=str)
    parser.add_argument("-p", "--params_file", type=str)
S
fix  
shippingwang 已提交
36 37
    parser.add_argument("-b", "--batch_size", type=int, default=1)
    parser.add_argument("--use_fp16", type=str2bool, default=False)
W
WuHaobo 已提交
38 39 40
    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 已提交
41 42 43
    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 已提交
44 45 46 47 48 49

    return parser.parse_args()


def create_predictor(args):
    config = AnalysisConfig(args.model_file, args.params_file)
S
shippingwang 已提交
50

W
WuHaobo 已提交
51
    if args.use_gpu:
S
fix  
shippingwang 已提交
52
        config.enable_use_gpu(args.gpu_mem, 0)
W
WuHaobo 已提交
53 54
    else:
        config.disable_gpu()
S
shippingwang 已提交
55

S
fix  
shippingwang 已提交
56
    config.disable_glog_info()
littletomatodonkey's avatar
littletomatodonkey 已提交
57
    config.switch_ir_optim(args.ir_optim)  # default true
W
WuHaobo 已提交
58 59
    if args.use_tensorrt:
        config.enable_tensorrt_engine(
littletomatodonkey's avatar
littletomatodonkey 已提交
60 61 62
            precision_mode=AnalysisConfig.Precision.Half
            if args.use_fp16 else AnalysisConfig.Precision.Float32,
            max_batch_size=args.batch_size)
S
fix  
shippingwang 已提交
63 64 65 66

    config.enable_memory_optim()
    # use zero copy
    config.switch_use_feed_fetch_ops(False)
W
WuHaobo 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    predictor = create_paddle_predictor(config)

    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 已提交
82
        scale=img_scale, mean=img_mean, std=img_std)
W
WuHaobo 已提交
83 84 85 86 87 88
    totensor_op = utils.ToTensor()

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


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

    return data


def main():
97 98
    import os

W
WuHaobo 已提交
99
    args = parse_args()
S
shippingwang 已提交
100 101 102

    if not args.enable_benchmark:
        assert args.batch_size == 1
W
WuHaobo 已提交
103
        assert args.use_fp16 is False
S
shippingwang 已提交
104
    else:
W
WuHaobo 已提交
105
        assert args.use_gpu is True
S
shippingwang 已提交
106
        assert args.model_name is not None
W
WuHaobo 已提交
107
        assert args.use_tensorrt is True
108 109
        assert args.image_file is not None

S
fix  
shippingwang 已提交
110
    # HALF precission predict only work when using tensorrt
W
WuHaobo 已提交
111 112
    if args.use_fp16 is True:
        assert args.use_tensorrt is True
S
shippingwang 已提交
113

W
WuHaobo 已提交
114 115 116
    operators = create_operators()
    predictor = create_predictor(args)

S
fix  
shippingwang 已提交
117 118
    input_names = predictor.get_input_names()
    input_tensor = predictor.get_input_tensor(input_names[0])
littletomatodonkey's avatar
littletomatodonkey 已提交
119 120 121 122 123 124

    output_names = predictor.get_output_names()
    output_tensor = predictor.get_output_tensor(output_names[0])

    test_num = 500
    test_time = 0.0
S
fix  
shippingwang 已提交
125
    if not args.enable_benchmark:
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        image_files = []
        if args.image_file is not None:
            image_files = [args.image_file]
        elif args.image_dir is not None:
            supported_exts = ('.jpg', 'jpeg', '.png', '.gif', '.bmp')
            for root, _, files in os.walk(args.image_dir, topdown=False):
                image_files += [os.path.join(root, f) for f in files
                                if os.path.splitext(f)[-1].lower() in supported_exts]
        for image_file in image_files:
            inputs = preprocess(image_file, operators)
            inputs = np.expand_dims(
                inputs, axis=0).repeat(
                    args.batch_size, axis=0).copy()
            input_tensor.copy_from_cpu(inputs)

            predictor.zero_copy_run()

            output = output_tensor.copy_to_cpu()
            output = output.flatten()
            cls = np.argmax(output)
            score = output[cls]
            logger.info("image file: {0}".format(image_file))
            logger.info("class: {0}".format(cls))
            logger.info("score: {0}".format(score))
S
fix  
shippingwang 已提交
150
    else:
littletomatodonkey's avatar
littletomatodonkey 已提交
151 152 153 154 155 156
        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)

S
fix  
shippingwang 已提交
157 158
            predictor.zero_copy_run()

littletomatodonkey's avatar
littletomatodonkey 已提交
159 160 161 162
            output = output_tensor.copy_to_cpu()
            output = output.flatten()
            if i >= 10:
                test_time += time.time() - start_time
S
fix  
shippingwang 已提交
163

littletomatodonkey's avatar
littletomatodonkey 已提交
164 165 166 167
        fp_message = "FP16" if args.use_fp16 else "FP32"
        logger.info("{0}\t{1}\tbatch size: {2}\ttime(ms): {3}".format(
            args.model_name, fp_message, args.batch_size, 1000 * test_time /
            test_num))
W
WuHaobo 已提交
168 169 170 171


if __name__ == "__main__":
    main()