eval.py 5.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 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

22 23 24 25 26 27 28 29 30 31 32
def set_paddle_flags(**kwargs):
    for key, value in kwargs.items():
        if os.environ.get(key, None) is None:
            os.environ[key] = str(value)

# NOTE(paddle-dev): All of these flags should be set before
# `import paddle`. Otherwise, it would not take any effect.
set_paddle_flags(
    FLAGS_eager_delete_tensor_gb=0,  # enable GC to save memory
)

33 34
import paddle.fluid as fluid

35
from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
36
import ppdet.utils.checkpoint as checkpoint
Y
Yang Zhang 已提交
37
from ppdet.utils.cli import ArgsParser
38
from ppdet.utils.check import check_gpu
39
from ppdet.modeling.model_input import create_feed
40 41 42 43 44 45 46 47 48 49 50 51 52
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 已提交
53
    cfg = load_config(FLAGS.config)
54
    if 'architecture' in cfg:
Y
Yang Zhang 已提交
55
        main_arch = cfg.architecture
56 57 58
    else:
        raise ValueError("'architecture' not specified in config file.")

Y
Yang Zhang 已提交
59
    merge_config(FLAGS.opt)
60

61 62 63
    # check if set use_gpu=True in paddlepaddle cpu version
    check_gpu(cfg.use_gpu)

Y
Yang Zhang 已提交
64
    if cfg.use_gpu:
65 66
        devices_num = fluid.core.get_cuda_device_count()
    else:
67 68
        devices_num = int(
            os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
69 70 71 72

    if 'eval_feed' not in cfg:
        eval_feed = create(main_arch + 'EvalFeed')
    else:
Y
Yang Zhang 已提交
73
        eval_feed = create(cfg.eval_feed)
74 75

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

79
    # build program
80 81 82 83 84
    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():
85
            pyreader, feed_vars = create_feed(eval_feed)
86
            fetches = model.eval(feed_vars)
87 88
    eval_prog = eval_prog.clone(True)

W
wangguanzhong 已提交
89
    reader = create_reader(eval_feed, args_path=FLAGS.dataset_dir)
90 91
    pyreader.decorate_sample_list_generator(reader, place)

92 93 94 95 96
    # eval already exists json file
    if FLAGS.json_eval:
        json_eval_results(eval_feed, cfg.metric,
                json_directory=FLAGS.output_eval)
        return
97
    # compile program for multi-devices
98 99 100 101 102 103 104 105 106
    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)

107
    # load model
108
    exe.run(startup_prog)
Y
Yang Zhang 已提交
109 110
    if 'weights' in cfg:
        checkpoint.load_pretrain(exe, eval_prog, cfg.weights)
111

112 113
    assert cfg.metric in ['COCO', 'VOC'], \
            "unknown metric type {}".format(cfg.metric)
114
    extra_keys = []
115
    if cfg.metric == 'COCO':
116
        extra_keys = ['im_info', 'im_id', 'im_shape']
117 118
    if cfg.metric == 'VOC':
        extra_keys = ['gt_box', 'gt_label', 'is_difficult']
119 120 121

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

122 123 124 125 126 127
    # whether output bbox is normalized in model output layer
    is_bbox_normalized = False
    if hasattr(model, 'is_bbox_normalized') and \
            callable(model.is_bbox_normalized):
        is_bbox_normalized = model.is_bbox_normalized()

128
    results = eval_run(exe, compile_program, pyreader, keys, values, cls)
129
    # evaluation
Y
Yang Zhang 已提交
130 131 132
    resolution = None
    if 'mask' in results[0]:
        resolution = model.mask_head.resolution
W
wangguanzhong 已提交
133
    eval_results(results, eval_feed, cfg.metric, cfg.num_classes, resolution,
134
                 is_bbox_normalized, FLAGS.output_eval)
135 136

if __name__ == '__main__':
Y
Yang Zhang 已提交
137 138
    parser = ArgsParser()
    parser.add_argument(
139 140 141 142
        "--json_eval",
        action='store_true',
        default=False,
        help="Whether to re eval with already exists bbox.json or mask.json")
W
wangguanzhong 已提交
143 144 145 146 147 148
    parser.add_argument(
        "-d",
        "--dataset_dir",
        default=None,
        type=str,
        help="Dataset path, same as DataFeed.dataset.dataset_dir")
149 150 151 152 153
    parser.add_argument(
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation file directory, default is current directory.")
Y
Yang Zhang 已提交
154
    FLAGS = parser.parse_args()
155
    main()