run_main.py 6.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2022 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.

C
ceci3 已提交
15 16
import os
import sys
17
import numpy as np
18
import argparse
19
import paddle
C
ceci3 已提交
20 21
from ppdet.core.workspace import load_config, merge_config
from ppdet.core.workspace import create
22 23 24 25 26
from ppdet.metrics import COCOMetric
from paddleslim.auto_compression.config_helpers import load_config as load_slim_config
from paddleslim.auto_compression import AutoCompression


27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
def argsparser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--config_path',
        type=str,
        default=None,
        help="path of compression strategy config.",
        required=True)
    parser.add_argument(
        '--save_dir',
        type=str,
        default='output',
        help="directory to save compressed model.")
    parser.add_argument(
        '--devices',
        type=str,
        default='gpu',
        help="which device used to compress.")
    parser.add_argument(
        '--eval', type=bool, default=False, help="whether to run evaluation.")

    return parser


def print_arguments(args):
    print('-----------  Running Arguments -----------')
    for arg, value in sorted(vars(args).items()):
        print('%s: %s' % (arg, value))
    print('------------------------------------------')
56 57


58
def reader_wrapper(reader, input_list):
59 60
    def gen():
        for data in reader:
61 62 63 64
            in_dict = {}
            for input_name in input_list:
                in_dict[input_name] = data[input_name]
            yield in_dict
65 66 67 68

    return gen


69
def eval(compress_config):
70

71
    place = paddle.CUDAPlace(0) if FLAGS.devices == 'gpu' else paddle.CPUPlace()
72 73 74
    exe = paddle.static.Executor(place)

    val_program, feed_target_names, fetch_targets = paddle.fluid.io.load_inference_model(
75
        compress_config["model_dir"],
76
        exe,
77 78
        model_filename=compress_config["model_filename"],
        params_filename=compress_config["params_filename"], )
79 80 81 82 83 84
    clsid2catid = {v: k for k, v in dataset.catid2clsid.items()}

    anno_file = dataset.get_anno()
    metric = COCOMetric(
        anno_file=anno_file, clsid2catid=clsid2catid, bias=0, IouType='bbox')
    for batch_id, data in enumerate(val_loader):
85 86 87 88 89
        data_all = {k: np.array(v) for k, v in data.items()}
        data_input = {}
        for k, v in data.items():
            if k in compress_config['input_list']:
                data_input[k] = np.array(v)
90
        outs = exe.run(val_program,
91
                       feed=data_input,
92 93 94 95 96 97 98 99 100 101
                       fetch_list=fetch_targets,
                       return_numpy=False)
        res = {}
        for out in outs:
            v = np.array(out)
            if len(v.shape) > 1:
                res['bbox'] = v
            else:
                res['bbox_num'] = v

102
        metric.update(data_all, res)
103 104 105 106 107 108 109 110 111 112 113 114 115 116
        if batch_id % 100 == 0:
            print('Eval iter:', batch_id)
    metric.accumulate()
    metric.log()
    metric.reset()


def eval_function(exe, compiled_test_program, test_feed_names, test_fetch_list):
    clsid2catid = {v: k for k, v in dataset.catid2clsid.items()}

    anno_file = dataset.get_anno()
    metric = COCOMetric(
        anno_file=anno_file, clsid2catid=clsid2catid, bias=1, IouType='bbox')
    for batch_id, data in enumerate(val_loader):
117 118 119 120 121
        data_all = {k: np.array(v) for k, v in data.items()}
        data_input = {}
        for k, v in data.items():
            if k in test_feed_names:
                data_input[k] = np.array(v)
122
        outs = exe.run(compiled_test_program,
123
                       feed=data_input,
124 125 126 127 128 129 130 131 132 133
                       fetch_list=test_fetch_list,
                       return_numpy=False)
        res = {}
        for out in outs:
            v = np.array(out)
            if len(v.shape) > 1:
                res['bbox'] = v
            else:
                res['bbox_num'] = v

134
        metric.update(data_all, res)
135 136 137 138 139 140 141 142 143
        if batch_id % 100 == 0:
            print('Eval iter:', batch_id)
    metric.accumulate()
    metric.log()
    map_res = metric.get_results()
    metric.reset()
    return map_res['bbox'][0]


144 145
def main():
    compress_config, train_config = load_slim_config(FLAGS.config_path)
146
    reader_cfg = load_config(compress_config['reader_config'])
C
ceci3 已提交
147

148
    train_loader = create('EvalReader')(reader_cfg['TrainDataset'],
149 150
                                        reader_cfg['worker_num'],
                                        return_list=True)
151 152 153
    train_loader = reader_wrapper(train_loader, compress_config['input_list'])

    global dataset
154
    dataset = reader_cfg['EvalDataset']
155 156
    global val_loader
    val_loader = create('EvalReader')(reader_cfg['EvalDataset'],
157 158
                                      reader_cfg['worker_num'],
                                      return_list=True)
C
ceci3 已提交
159

160 161
    if FLAGS.eval:
        eval(compress_config)
162 163 164 165 166 167
        sys.exit(0)

    if 'Evaluation' in compress_config.keys() and compress_config['Evaluation']:
        eval_func = eval_function
    else:
        eval_func = None
C
ceci3 已提交
168

169
    ac = AutoCompression(
170 171 172
        model_dir=compress_config["model_dir"],
        model_filename=compress_config["model_filename"],
        params_filename=compress_config["params_filename"],
173
        save_dir=FLAGS.save_dir,
174 175
        strategy_config=compress_config,
        train_config=train_config,
176
        train_dataloader=train_loader,
C
ceci3 已提交
177
        eval_callback=eval_func)
C
ceci3 已提交
178

179
    ac.compress()
180 181 182 183


if __name__ == '__main__':
    paddle.enable_static()
184 185 186 187 188 189 190 191
    parser = argsparser()
    FLAGS = parser.parse_args()
    print_arguments(FLAGS)

    assert FLAGS.devices in ['cpu', 'gpu', 'xpu', 'npu']
    paddle.set_device(FLAGS.devices)

    main()