compress.py 8.2 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 26
# 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 time
import multiprocessing
import numpy as np
import sys
sys.path.append("../../")
from paddle.fluid.contrib.slim import Compressor

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)

33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# 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
)

from paddle import fluid
from ppdet.core.workspace import load_config, merge_config, create
from ppdet.data.data_feed import create_reader
from ppdet.utils.eval_utils import parse_fetches, eval_results
from ppdet.utils.cli import ArgsParser
from ppdet.utils.check import check_gpu
import ppdet.utils.checkpoint as checkpoint
from ppdet.modeling.model_input import create_feed

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


55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
def eval_run(exe, compile_program, reader, keys, values, cls, test_feed):
    """
    Run evaluation program, return program outputs.
    """
    iter_id = 0
    results = []
    if len(cls) != 0:
        values = []
        for i in range(len(cls)):
            _, accum_map = cls[i].get_map_var()
            cls[i].reset(exe)
            values.append(accum_map)

    images_num = 0
    start_time = time.time()
    has_bbox = 'bbox' in keys
    for data in reader():
        data = test_feed.feed(data)
73
        feed_data = {'image': data['image'], 'im_size': data['im_size']}
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        outs = exe.run(compile_program,
                       feed=feed_data,
                       fetch_list=[values[0]],
                       return_numpy=False)
        outs.append(data['gt_box'])
        outs.append(data['gt_label'])
        outs.append(data['is_difficult'])
        res = {
            k: (np.array(v), v.recursive_sequence_lengths())
            for k, v in zip(keys, outs)
        }
        results.append(res)
        if iter_id % 100 == 0:
            logger.info('Test iter {}'.format(iter_id))
        iter_id += 1
        images_num += len(res['bbox'][1][0]) if has_bbox else 1
    logger.info('Test finish iter {}'.format(iter_id))

    end_time = time.time()
    fps = images_num / (end_time - start_time)
    if has_bbox:
        logger.info('Total number of images: {}, inference time: {} fps.'.
                    format(images_num, fps))
    else:
        logger.info('Total iteration: {}, inference time: {} batch/s.'.format(
            images_num, fps))

    return results


def main():
    cfg = load_config(FLAGS.config)
    if 'architecture' in cfg:
        main_arch = cfg.architecture
    else:
        raise ValueError("'architecture' not specified in config file.")

    merge_config(FLAGS.opt)
    if 'log_iter' not in cfg:
        cfg.log_iter = 20

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

    if cfg.use_gpu:
        devices_num = fluid.core.get_cuda_device_count()
    else:
        devices_num = int(
            os.environ.get('CPU_NUM', multiprocessing.cpu_count()))

    if 'train_feed' not in cfg:
        train_feed = create(main_arch + 'TrainFeed')
    else:
        train_feed = create(cfg.train_feed)

    if 'eval_feed' not in cfg:
        eval_feed = create(main_arch + 'EvalFeed')
    else:
        eval_feed = create(cfg.eval_feed)

    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)

    lr_builder = create('LearningRate')
    optim_builder = create('OptimizerBuilder')

    # build program
    startup_prog = fluid.Program()
    train_prog = fluid.Program()
    with fluid.program_guard(train_prog, startup_prog):
        with fluid.unique_name.guard():
            model = create(main_arch)
W
wangguanzhong 已提交
146
            _, feed_vars = create_feed(train_feed, True)
147 148 149 150 151 152
            train_fetches = model.train(feed_vars)
            loss = train_fetches['loss']
            lr = lr_builder()
            optimizer = optim_builder(lr)
            optimizer.minimize(loss)

153
    train_reader = create_reader(train_feed, cfg.max_iters, FLAGS.dataset_dir)
154 155 156 157 158 159

    # parse train fetches
    train_keys, train_values, _ = parse_fetches(train_fetches)
    train_keys.append("lr")
    train_values.append(lr.name)

160
    train_fetch_list = []
161 162 163 164 165 166 167
    for k, v in zip(train_keys, train_values):
        train_fetch_list.append((k, v))

    eval_prog = fluid.Program()
    with fluid.program_guard(eval_prog, startup_prog):
        with fluid.unique_name.guard():
            model = create(main_arch)
W
wangguanzhong 已提交
168
            _, test_feed_vars = create_feed(eval_feed, True)
169 170 171 172 173 174 175 176 177 178 179 180 181 182
            fetches = model.eval(test_feed_vars)

    eval_prog = eval_prog.clone(True)

    eval_reader = create_reader(eval_feed, args_path=FLAGS.dataset_dir)
    test_data_feed = fluid.DataFeeder(test_feed_vars.values(), place)

    # parse eval fetches
    extra_keys = []
    if cfg.metric == 'COCO':
        extra_keys = ['im_info', 'im_id', 'im_shape']
    if cfg.metric == 'VOC':
        extra_keys = ['gt_box', 'gt_label', 'is_difficult']
    eval_keys, eval_values, eval_cls = parse_fetches(fetches, eval_prog,
183 184
                                                     extra_keys)
    eval_fetch_list = []
185 186 187 188 189 190 191 192 193 194 195 196
    for k, v in zip(eval_keys, eval_values):
        eval_fetch_list.append((k, v))

    exe.run(startup_prog)
    checkpoint.load_params(exe, train_prog, cfg.pretrain_weights)

    best_box_ap_list = []

    def eval_func(program, scope):

        #place = fluid.CPUPlace()
        #exe = fluid.Executor(place)
197 198
        results = eval_run(exe, program, eval_reader, eval_keys, eval_values,
                           eval_cls, test_data_feed)
199 200 201 202

        resolution = None
        if 'mask' in results[0]:
            resolution = model.mask_head.resolution
203 204 205
        box_ap_stats = eval_results(results, eval_feed, cfg.metric,
                                    cfg.num_classes, resolution, False,
                                    FLAGS.output_eval)
206 207 208 209
        if len(best_box_ap_list) == 0:
            best_box_ap_list.append(box_ap_stats[0])
        elif box_ap_stats[0] > best_box_ap_list[0]:
            best_box_ap_list[0] = box_ap_stats[0]
210
        logger.info("Best test box ap: {}".format(best_box_ap_list[0]))
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        return best_box_ap_list[0]

    test_feed = [('image', test_feed_vars['image'].name),
                 ('im_size', test_feed_vars['im_size'].name)]

    com = Compressor(
        place,
        fluid.global_scope(),
        train_prog,
        train_reader=train_reader,
        train_feed_list=[(key, value.name) for key, value in feed_vars.items()],
        train_fetch_list=train_fetch_list,
        eval_program=eval_prog,
        eval_reader=eval_reader,
        eval_feed_list=test_feed,
        eval_func={'map': eval_func},
        eval_fetch_list=[eval_fetch_list[0]],
        save_eval_model=True,
229
        prune_infer_model=[["image", "im_size"], ["multiclass_nms_0.tmp_0"]],
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        train_optimizer=None)
    com.config(FLAGS.slim_file)
    com.run()


if __name__ == '__main__':
    parser = ArgsParser()
    parser.add_argument(
        "-s",
        "--slim_file",
        default=None,
        type=str,
        help="Config file of PaddleSlim.")
    parser.add_argument(
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation directory, default is current directory.")
    parser.add_argument(
        "-d",
        "--dataset_dir",
        default=None,
        type=str,
        help="Dataset path, same as DataFeed.dataset.dataset_dir")
    FLAGS = parser.parse_args()
    main()