run.py 5.5 KB
Newer Older
C
ceci3 已提交
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.

Z
zhouzj 已提交
15 16 17 18 19
import os
import argparse
import random
import paddle
import numpy as np
W
whs 已提交
20
from paddleseg.cvlibs import Config as PaddleSegDataConfig
Z
zhouzj 已提交
21
from paddleseg.utils import worker_init_fn
W
whs 已提交
22

Z
zhouzj 已提交
23
from paddleslim.auto_compression import AutoCompression
24
from paddleslim.common import load_config as load_slim_config
Z
zhouzj 已提交
25 26 27 28
from paddleseg.core.infer import reverse_transform
from paddleseg.utils import metrics


C
ceci3 已提交
29 30
def argsparser():
    parser = argparse.ArgumentParser(description=__doc__)
Z
zhouzj 已提交
31
    parser.add_argument(
C
ceci3 已提交
32
        '--config_path',
Z
zhouzj 已提交
33 34
        type=str,
        default=None,
C
ceci3 已提交
35
        help="path of compression strategy config.")
Z
zhouzj 已提交
36 37 38 39 40
    parser.add_argument(
        '--save_dir',
        type=str,
        default=None,
        help="directory to save compressed model.")
C
ceci3 已提交
41
    return parser
Z
zhouzj 已提交
42 43 44


def eval_function(exe, compiled_test_program, test_feed_names, test_fetch_list):
45
    batch_sampler = paddle.io.BatchSampler(
Z
zhouzj 已提交
46 47 48 49
        eval_dataset, batch_size=1, shuffle=False, drop_last=False)
    loader = paddle.io.DataLoader(
        eval_dataset,
        batch_sampler=batch_sampler,
C
ceci3 已提交
50
        num_workers=0,
Z
zhouzj 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        return_list=True, )

    total_iters = len(loader)
    intersect_area_all = 0
    pred_area_all = 0
    label_area_all = 0

    print("Start evaluating (total_samples: {}, total_iters: {})...".format(
        len(eval_dataset), total_iters))

    for iter, (image, label) in enumerate(loader):
        paddle.enable_static()

        label = np.array(label).astype('int64')
        ori_shape = np.array(label).shape[-2:]

        image = np.array(image)
        logits = exe.run(compiled_test_program,
                         feed={test_feed_names[0]: image},
                         fetch_list=test_fetch_list,
                         return_numpy=True)

        paddle.disable_static()
        logit = logits[0]

        logit = reverse_transform(
            paddle.to_tensor(logit),
            ori_shape,
            eval_dataset.transforms.transforms,
            mode='bilinear')
81 82 83 84 85
        pred = paddle.to_tensor(logit)
        if len(
                pred.shape
        ) == 4:  # for humanseg model whose prediction is distribution but not class id
            pred = paddle.argmax(pred, axis=1, keepdim=True, dtype='int32')
Z
zhouzj 已提交
86 87 88 89 90 91

        intersect_area, pred_area, label_area = metrics.calculate_area(
            pred,
            paddle.to_tensor(label),
            eval_dataset.num_classes,
            ignore_index=eval_dataset.ignore_index)
92 93 94
        intersect_area_all = intersect_area_all + intersect_area
        pred_area_all = pred_area_all + pred_area
        label_area_all = label_area_all + label_area
Z
zhouzj 已提交
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

    class_iou, miou = metrics.mean_iou(intersect_area_all, pred_area_all,
                                       label_area_all)
    class_acc, acc = metrics.accuracy(intersect_area_all, pred_area_all)
    kappa = metrics.kappa(intersect_area_all, pred_area_all, label_area_all)
    class_dice, mdice = metrics.dice(intersect_area_all, pred_area_all,
                                     label_area_all)

    infor = "[EVAL] #Images: {} mIoU: {:.4f} Acc: {:.4f} Kappa: {:.4f} Dice: {:.4f}".format(
        len(eval_dataset), miou, acc, kappa, mdice)
    print(infor)

    paddle.enable_static()
    return miou


def reader_wrapper(reader):
    def gen():
        for i, data in enumerate(reader()):
            imgs = np.array(data[0])
            yield {"x": imgs}

    return gen


C
ceci3 已提交
120 121 122 123 124
def main(args):
    all_config = load_slim_config(args.config_path)
    assert "Global" in all_config, f"Key 'Global' not found in config file. \n{all_config}"
    config = all_config["Global"]

125 126
    rank_id = paddle.distributed.get_rank()
    place = paddle.CUDAPlace(rank_id)
W
whs 已提交
127
    # step1: load dataset config and create dataloader
C
ceci3 已提交
128
    data_cfg = PaddleSegDataConfig(config['reader_config'])
W
whs 已提交
129 130
    train_dataset = data_cfg.train_dataset
    eval_dataset = data_cfg.val_dataset
Z
zhouzj 已提交
131
    batch_sampler = paddle.io.DistributedBatchSampler(
W
whs 已提交
132 133 134 135
        train_dataset,
        batch_size=data_cfg.batch_size,
        shuffle=True,
        drop_last=True)
Z
zhouzj 已提交
136 137
    train_loader = paddle.io.DataLoader(
        train_dataset,
138
        places=[place],
Z
zhouzj 已提交
139
        batch_sampler=batch_sampler,
C
ceci3 已提交
140
        num_workers=0,
Z
zhouzj 已提交
141
        return_list=True,
Z
zhouzj 已提交
142
        worker_init_fn=worker_init_fn)
Z
zhouzj 已提交
143 144
    train_dataloader = reader_wrapper(train_loader)

W
whs 已提交
145 146 147
    nranks = paddle.distributed.get_world_size()
    rank_id = paddle.distributed.get_rank()

W
whs 已提交
148
    # step2: create and instance of AutoCompression
Z
zhouzj 已提交
149
    ac = AutoCompression(
C
ceci3 已提交
150 151 152
        model_dir=config['model_dir'],
        model_filename=config['model_filename'],
        params_filename=config['params_filename'],
Z
zhouzj 已提交
153
        save_dir=args.save_dir,
C
ceci3 已提交
154
        config=all_config,
Z
zhouzj 已提交
155
        train_dataloader=train_dataloader,
C
ceci3 已提交
156 157
        eval_callback=eval_function if nranks > 1 and rank_id != 0 else None,
        deploy_hardware=config.get('deploy_hardware') or None)
Z
zhouzj 已提交
158

W
whs 已提交
159
    # step3: start the compression job
Z
zhouzj 已提交
160
    ac.compress()
C
ceci3 已提交
161 162 163 164 165 166 167


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