analysis.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
# 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.

import os
import sys
import numpy as np
import argparse
import paddle
from tqdm import tqdm
21
from post_process import YOLOPostProcess, coco_metric
22 23
from dataset import COCOValDataset, COCOTrainDataset
from paddleslim.common import load_config, load_onnx_model
24
from paddleslim.quant.analysis import Analysis
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39


def argsparser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--config_path',
        type=str,
        default=None,
        help="path of analysis config.",
        required=True)
    parser.add_argument(
        '--devices',
        type=str,
        default='gpu',
        help="which device used to compress.")
G
Guanghua Yu 已提交
40 41 42 43
    parser.add_argument(
        '--resume',
        type=bool,
        default=False,
44 45
        help=
        "When break off while ananlyzing, could resume analysis program and load already analyzed information."
G
Guanghua Yu 已提交
46
    )
47 48 49 50 51 52 53 54 55 56 57
    return parser


def eval_function(exe, compiled_test_program, test_feed_names, test_fetch_list):
    bboxes_list, bbox_nums_list, image_id_list = [], [], []
    with tqdm(
            total=len(val_loader),
            bar_format='Evaluation stage, Run batch:|{bar}| {n_fmt}/{total_fmt}',
            ncols=80) as t:
        for data in val_loader:
            data_all = {k: np.array(v) for k, v in data.items()}
58 59 60 61 62
            outs = exe.run(
                compiled_test_program,
                feed={test_feed_names[0]: data_all['image']},
                fetch_list=test_fetch_list,
                return_numpy=False)
63
            res = {}
64
            postprocess = YOLOPostProcess(
65 66 67 68 69 70 71 72 73 74 75 76 77 78
                score_threshold=0.001, nms_threshold=0.65, multi_label=True)
            res = postprocess(np.array(outs[0]), data_all['scale_factor'])
            bboxes_list.append(res['bbox'])
            bbox_nums_list.append(res['bbox_num'])
            image_id_list.append(np.array(data_all['im_id']))
            t.update()
    map_res = coco_metric(anno_file, bboxes_list, bbox_nums_list, image_id_list)
    return map_res[0]


def main():

    global config
    config = load_config(FLAGS.config_path)
79
    ptq_config = config['PTQ']
80

81 82
    input_name = 'x2paddle_image_arrays' if config[
        'arch'] == 'YOLOv6' else 'x2paddle_images'
83 84

    # val dataset is sufficient for PTQ
85 86 87
    dataset = COCOTrainDataset(
        dataset_dir=config['dataset_dir'],
        image_dir=config['val_image_dir'],
88 89
        anno_path=config['val_anno_path'],
        input_name=input_name)
90 91 92 93
    data_loader = paddle.io.DataLoader(
        dataset, batch_size=1, shuffle=True, drop_last=True, num_workers=0)

    global val_loader
94
    # fast_val_anno_path, such as annotation path of several pictures can accelerate analysis
95 96 97
    dataset = COCOValDataset(
        dataset_dir=config['dataset_dir'],
        image_dir=config['val_image_dir'],
98 99
        anno_path=config['fast_val_anno_path'] if
        config['fast_val_anno_path'] is not None else config['val_anno_path'])
100 101 102 103 104 105 106 107
    global anno_file
    anno_file = dataset.ann_file
    val_loader = paddle.io.DataLoader(
        dataset, batch_size=1, shuffle=False, drop_last=False, num_workers=0)

    load_onnx_model(config["model_dir"])
    inference_model_path = config["model_dir"].rstrip().rstrip(
        '.onnx') + '_infer'
108 109
    analyzer = Analysis(
        float_model_dir=inference_model_path,
110 111 112 113
        model_filename='model.pdmodel',
        params_filename='model.pdiparams',
        eval_function=eval_function,
        data_loader=data_loader,
114
        save_dir=config['save_dir'],
G
Guanghua Yu 已提交
115
        resume=FLAGS.resume,
116
        quant_config=ptq_config)
117

C
Chang Xu 已提交
118 119
    analyzer.statistical_analyse()
    analyzer.metric_error_analyse()
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

    if config['get_target_quant_model']:
        if config['fast_val_anno_path'] is not None:
            # change fast_val_loader to full val_loader
            dataset = COCOValDataset(
                dataset_dir=config['dataset_dir'],
                image_dir=config['val_image_dir'],
                anno_path=config['val_anno_path'])
            anno_file = dataset.ann_file
            val_loader = paddle.io.DataLoader(
                dataset,
                batch_size=1,
                shuffle=False,
                drop_last=False,
                num_workers=0)
        # get the quantized model that satisfies target metric you set
        analyzer.get_target_quant_model(config['target_metric'])
137 138 139 140 141 142 143 144 145 146 147


if __name__ == '__main__':
    paddle.enable_static()
    parser = argsparser()
    FLAGS = parser.parse_args()

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

    main()