Diff of /tools/test.py [000000] .. [4e96d3]

Switch to unified view

a b/tools/test.py
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import argparse
3
import os
4
import os.path as osp
5
import shutil
6
import time
7
import warnings
8
9
import mmcv
10
import torch
11
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
12
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
13
                         wrap_fp16_model)
14
from mmcv.utils import DictAction
15
16
from mmseg.apis import multi_gpu_test, single_gpu_test
17
from mmseg.datasets import build_dataloader, build_dataset
18
from mmseg.models import build_segmentor
19
20
21
def parse_args():
22
    parser = argparse.ArgumentParser(
23
        description='mmseg test (and eval) a model')
24
    parser.add_argument('config', help='test config file path')
25
    parser.add_argument('checkpoint', help='checkpoint file')
26
    parser.add_argument(
27
        '--work-dir',
28
        help=('if specified, the evaluation metric results will be dumped'
29
              'into the directory as json'))
30
    parser.add_argument(
31
        '--aug-test', action='store_true', help='Use Flip and Multi scale aug')
32
    parser.add_argument('--out', help='output result file in pickle format')
33
    parser.add_argument(
34
        '--format-only',
35
        action='store_true',
36
        help='Format the output results without perform evaluation. It is'
37
        'useful when you want to format the result to a specific format and '
38
        'submit it to the test server')
39
    parser.add_argument(
40
        '--eval',
41
        type=str,
42
        nargs='+',
43
        help='evaluation metrics, which depends on the dataset, e.g., "mIoU"'
44
        ' for generic datasets, and "cityscapes" for Cityscapes')
45
    parser.add_argument('--show', action='store_true', help='show results')
46
    parser.add_argument(
47
        '--show-dir', help='directory where painted images will be saved')
48
    parser.add_argument(
49
        '--gpu-collect',
50
        action='store_true',
51
        help='whether to use gpu to collect results.')
52
    parser.add_argument(
53
        '--tmpdir',
54
        help='tmp directory used for collecting results from multiple '
55
        'workers, available when gpu_collect is not specified')
56
    parser.add_argument(
57
        '--options',
58
        nargs='+',
59
        action=DictAction,
60
        help="--options is deprecated in favor of --cfg_options' and it will "
61
        'not be supported in version v0.22.0. Override some settings in the '
62
        'used config, the key-value pair in xxx=yyy format will be merged '
63
        'into config file. If the value to be overwritten is a list, it '
64
        'should be like key="[a,b]" or key=a,b It also allows nested '
65
        'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation '
66
        'marks are necessary and that no white space is allowed.')
67
    parser.add_argument(
68
        '--cfg-options',
69
        nargs='+',
70
        action=DictAction,
71
        help='override some settings in the used config, the key-value pair '
72
        'in xxx=yyy format will be merged into config file. If the value to '
73
        'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
74
        'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
75
        'Note that the quotation marks are necessary and that no white space '
76
        'is allowed.')
77
    parser.add_argument(
78
        '--eval-options',
79
        nargs='+',
80
        action=DictAction,
81
        help='custom options for evaluation')
82
    parser.add_argument(
83
        '--launcher',
84
        choices=['none', 'pytorch', 'slurm', 'mpi'],
85
        default='none',
86
        help='job launcher')
87
    parser.add_argument(
88
        '--opacity',
89
        type=float,
90
        default=0.5,
91
        help='Opacity of painted segmentation map. In (0, 1] range.')
92
    parser.add_argument('--local_rank', type=int, default=0)
93
    args = parser.parse_args()
94
    if 'LOCAL_RANK' not in os.environ:
95
        os.environ['LOCAL_RANK'] = str(args.local_rank)
96
97
    if args.options and args.cfg_options:
98
        raise ValueError(
99
            '--options and --cfg-options cannot be both '
100
            'specified, --options is deprecated in favor of --cfg-options. '
101
            '--options will not be supported in version v0.22.0.')
102
    if args.options:
103
        warnings.warn('--options is deprecated in favor of --cfg-options. '
104
                      '--options will not be supported in version v0.22.0.')
105
        args.cfg_options = args.options
106
107
    return args
108
109
110
def main():
111
    args = parse_args()
112
113
    assert args.out or args.eval or args.format_only or args.show \
114
        or args.show_dir, \
115
        ('Please specify at least one operation (save/eval/format/show the '
116
         'results / save the results) with the argument "--out", "--eval"'
117
         ', "--format-only", "--show" or "--show-dir"')
118
119
    if args.eval and args.format_only:
120
        raise ValueError('--eval and --format_only cannot be both specified')
121
122
    if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):
123
        raise ValueError('The output file must be a pkl file.')
124
125
    cfg = mmcv.Config.fromfile(args.config)
126
    if args.cfg_options is not None:
127
        cfg.merge_from_dict(args.cfg_options)
128
    # set cudnn_benchmark
129
    if cfg.get('cudnn_benchmark', False):
130
        torch.backends.cudnn.benchmark = True
131
    if args.aug_test:
132
        # hard code index
133
        cfg.data.test.pipeline[1].img_ratios = [
134
            0.5, 0.75, 1.0, 1.25, 1.5, 1.75
135
        ]
136
        cfg.data.test.pipeline[1].flip = True
137
    cfg.model.pretrained = None
138
    cfg.data.test.test_mode = True
139
140
    # init distributed env first, since logger depends on the dist info.
141
    if args.launcher == 'none':
142
        distributed = False
143
    else:
144
        distributed = True
145
        init_dist(args.launcher, **cfg.dist_params)
146
147
    rank, _ = get_dist_info()
148
    # allows not to create
149
    if args.work_dir is not None and rank == 0:
150
        mmcv.mkdir_or_exist(osp.abspath(args.work_dir))
151
        timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
152
        json_file = osp.join(args.work_dir, f'eval_{timestamp}.json')
153
154
    # build the dataloader
155
    # TODO: support multiple images per gpu (only minor changes are needed)
156
    dataset = build_dataset(cfg.data.test)
157
    data_loader = build_dataloader(
158
        dataset,
159
        samples_per_gpu=1,
160
        workers_per_gpu=cfg.data.workers_per_gpu,
161
        dist=distributed,
162
        shuffle=False)
163
164
    # build the model and load checkpoint
165
    cfg.model.train_cfg = None
166
    model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg'))
167
    fp16_cfg = cfg.get('fp16', None)
168
    if fp16_cfg is not None:
169
        wrap_fp16_model(model)
170
    checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
171
    if 'CLASSES' in checkpoint.get('meta', {}):
172
        model.CLASSES = checkpoint['meta']['CLASSES']
173
    else:
174
        print('"CLASSES" not found in meta, use dataset.CLASSES instead')
175
        model.CLASSES = dataset.CLASSES
176
    if 'PALETTE' in checkpoint.get('meta', {}):
177
        model.PALETTE = checkpoint['meta']['PALETTE']
178
    else:
179
        print('"PALETTE" not found in meta, use dataset.PALETTE instead')
180
        model.PALETTE = dataset.PALETTE
181
182
    # clean gpu memory when starting a new evaluation.
183
    torch.cuda.empty_cache()
184
    eval_kwargs = {} if args.eval_options is None else args.eval_options
185
186
    # Deprecated
187
    efficient_test = eval_kwargs.get('efficient_test', False)
188
    if efficient_test:
189
        warnings.warn(
190
            '``efficient_test=True`` does not have effect in tools/test.py, '
191
            'the evaluation and format results are CPU memory efficient by '
192
            'default')
193
194
    eval_on_format_results = (
195
        args.eval is not None and 'cityscapes' in args.eval)
196
    if eval_on_format_results:
197
        assert len(args.eval) == 1, 'eval on format results is not ' \
198
                                    'applicable for metrics other than ' \
199
                                    'cityscapes'
200
    if args.format_only or eval_on_format_results:
201
        if 'imgfile_prefix' in eval_kwargs:
202
            tmpdir = eval_kwargs['imgfile_prefix']
203
        else:
204
            tmpdir = '.format_cityscapes'
205
            eval_kwargs.setdefault('imgfile_prefix', tmpdir)
206
        mmcv.mkdir_or_exist(tmpdir)
207
    else:
208
        tmpdir = None
209
210
    if not distributed:
211
        model = MMDataParallel(model, device_ids=[0])
212
        results = single_gpu_test(
213
            model,
214
            data_loader,
215
            args.show,
216
            args.show_dir,
217
            False,
218
            args.opacity,
219
            pre_eval=args.eval is not None and not eval_on_format_results,
220
            format_only=args.format_only or eval_on_format_results,
221
            format_args=eval_kwargs)
222
    else:
223
        model = MMDistributedDataParallel(
224
            model.cuda(),
225
            device_ids=[torch.cuda.current_device()],
226
            broadcast_buffers=False)
227
        results = multi_gpu_test(
228
            model,
229
            data_loader,
230
            args.tmpdir,
231
            args.gpu_collect,
232
            False,
233
            pre_eval=args.eval is not None and not eval_on_format_results,
234
            format_only=args.format_only or eval_on_format_results,
235
            format_args=eval_kwargs)
236
237
    rank, _ = get_dist_info()
238
    if rank == 0:
239
        if args.out:
240
            warnings.warn(
241
                'The behavior of ``args.out`` has been changed since MMSeg '
242
                'v0.16, the pickled outputs could be seg map as type of '
243
                'np.array, pre-eval results or file paths for '
244
                '``dataset.format_results()``.')
245
            print(f'\nwriting results to {args.out}')
246
            mmcv.dump(results, args.out)
247
        if args.eval:
248
            eval_kwargs.update(metric=args.eval)
249
            metric = dataset.evaluate(results, **eval_kwargs)
250
            metric_dict = dict(config=args.config, metric=metric)
251
            if args.work_dir is not None and rank == 0:
252
                mmcv.dump(metric_dict, json_file, indent=4)
253
            if tmpdir is not None and eval_on_format_results:
254
                # remove tmp dir when cityscapes evaluation
255
                shutil.rmtree(tmpdir)
256
257
258
if __name__ == '__main__':
259
    main()