eval.py 3.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Copyright (c) 2019 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import multiprocessing

import paddle.fluid as fluid

from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results
import ppdet.utils.checkpoint as checkpoint
Y
Yang Zhang 已提交
26
from ppdet.utils.cli import ArgsParser
27
from ppdet.utils.check import check_gpu
28
from ppdet.modeling.model_input import create_feed
29 30 31 32 33 34 35 36 37 38 39 40 41
from ppdet.data.data_feed import create_reader
from ppdet.core.workspace import load_config, merge_config, create

import logging
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)


def main():
    """
    Main evaluate function
    """
Y
Yang Zhang 已提交
42
    cfg = load_config(FLAGS.config)
43
    if 'architecture' in cfg:
Y
Yang Zhang 已提交
44
        main_arch = cfg.architecture
45 46 47
    else:
        raise ValueError("'architecture' not specified in config file.")

Y
Yang Zhang 已提交
48
    merge_config(FLAGS.opt)
49

50 51 52
    # check if set use_gpu=True in paddlepaddle cpu version
    check_gpu(cfg.use_gpu)

Y
Yang Zhang 已提交
53
    if cfg.use_gpu:
54 55
        devices_num = fluid.core.get_cuda_device_count()
    else:
56 57
        devices_num = int(
            os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
58 59 60 61

    if 'eval_feed' not in cfg:
        eval_feed = create(main_arch + 'EvalFeed')
    else:
Y
Yang Zhang 已提交
62
        eval_feed = create(cfg.eval_feed)
63 64

    # define executor
Y
Yang Zhang 已提交
65
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
66 67
    exe = fluid.Executor(place)

68
    # build program
69 70 71 72 73
    model = create(main_arch)
    startup_prog = fluid.Program()
    eval_prog = fluid.Program()
    with fluid.program_guard(eval_prog, startup_prog):
        with fluid.unique_name.guard():
74
            pyreader, feed_vars = create_feed(eval_feed)
75
            fetches = model.eval(feed_vars)
76 77 78 79 80
    eval_prog = eval_prog.clone(True)

    reader = create_reader(eval_feed)
    pyreader.decorate_sample_list_generator(reader, place)

81
    # compile program for multi-devices
82 83 84 85 86 87 88 89 90
    if devices_num <= 1:
        compile_program = fluid.compiler.CompiledProgram(eval_prog)
    else:
        build_strategy = fluid.BuildStrategy()
        build_strategy.memory_optimize = False
        build_strategy.enable_inplace = False
        compile_program = fluid.compiler.CompiledProgram(
            eval_prog).with_data_parallel(build_strategy=build_strategy)

91
    # load model
92
    exe.run(startup_prog)
Y
Yang Zhang 已提交
93 94
    if 'weights' in cfg:
        checkpoint.load_pretrain(exe, eval_prog, cfg.weights)
95 96

    extra_keys = []
Y
Yang Zhang 已提交
97
    if 'metric' in cfg and cfg.metric == 'COCO':
98 99 100 101 102
        extra_keys = ['im_info', 'im_id', 'im_shape']

    keys, values, cls = parse_fetches(fetches, eval_prog, extra_keys)

    results = eval_run(exe, compile_program, pyreader, keys, values, cls)
103
    # evaluation
Y
Yang Zhang 已提交
104 105 106 107
    resolution = None
    if 'mask' in results[0]:
        resolution = model.mask_head.resolution
    eval_results(results, eval_feed, cfg.metric, resolution, FLAGS.output_file)
108 109 110


if __name__ == '__main__':
Y
Yang Zhang 已提交
111 112 113 114 115 116
    parser = ArgsParser()
    parser.add_argument(
        "-f",
        "--output_file",
        default=None,
        type=str,
117
        help="Evaluation file name, default to bbox.json and mask.json.")
Y
Yang Zhang 已提交
118
    FLAGS = parser.parse_args()
119
    main()