test_runner.py 8.47 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import logging
3
import os
4
import os.path as osp
5
import platform
6
7
import random
import string
8
import tempfile
Kai Chen's avatar
Kai Chen committed
9

10
11
12
import pytest
import torch
import torch.nn as nn
13

Kai Chen's avatar
Kai Chen committed
14
from mmcv.parallel import MMDataParallel
15
16
from mmcv.runner import (RUNNERS, EpochBasedRunner, IterBasedRunner,
                         build_runner)
Miao Zheng's avatar
Miao Zheng committed
17
from mmcv.runner.hooks import IterTimerHook
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


class OldStyleModel(nn.Module):

    def __init__(self):
        super().__init__()
        self.conv = nn.Conv2d(3, 3, 1)


class Model(OldStyleModel):

    def train_step(self):
        pass

    def val_step(self):
        pass


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def test_build_runner():
    temp_root = tempfile.gettempdir()
    dir_name = ''.join(
        [random.choice(string.ascii_letters) for _ in range(10)])

    default_args = dict(
        model=Model(),
        work_dir=osp.join(temp_root, dir_name),
        logger=logging.getLogger())
    cfg = dict(type='EpochBasedRunner', max_epochs=1)
    runner = build_runner(cfg, default_args=default_args)
    assert runner._max_epochs == 1
    cfg = dict(type='IterBasedRunner', max_iters=1)
    runner = build_runner(cfg, default_args=default_args)
    assert runner._max_iters == 1

    with pytest.raises(ValueError, match='Only one of'):
        cfg = dict(type='IterBasedRunner', max_epochs=1, max_iters=1)
        runner = build_runner(cfg, default_args=default_args)


@pytest.mark.parametrize('runner_class', RUNNERS.module_dict.values())
def test_epoch_based_runner(runner_class):
59
    with pytest.warns(DeprecationWarning):
60
61
        # batch_processor is deprecated
        model = OldStyleModel()
62

63
64
        def batch_processor():
            pass
65

66
        _ = runner_class(model, batch_processor, logger=logging.getLogger())
67
68
69
70

    with pytest.raises(TypeError):
        # batch_processor must be callable
        model = OldStyleModel()
71
        _ = runner_class(model, batch_processor=0, logger=logging.getLogger())
Harry's avatar
Harry committed
72
73
74
75
76

    with pytest.raises(TypeError):
        # optimizer must be a optimizer or a dict of optimizers
        model = Model()
        optimizer = 'NotAOptimizer'
77
        _ = runner_class(
Harry's avatar
Harry committed
78
79
80
81
82
83
            model, optimizer=optimizer, logger=logging.getLogger())

    with pytest.raises(TypeError):
        # optimizer must be a optimizer or a dict of optimizers
        model = Model()
        optimizers = dict(optim1=torch.optim.Adam(), optim2='NotAOptimizer')
84
        _ = runner_class(
Harry's avatar
Harry committed
85
86
87
88
89
            model, optimizer=optimizers, logger=logging.getLogger())

    with pytest.raises(TypeError):
        # logger must be a logging.Logger
        model = Model()
90
        _ = runner_class(model, logger=None)
Harry's avatar
Harry committed
91
92
93
94

    with pytest.raises(TypeError):
        # meta must be a dict or None
        model = Model()
95
        _ = runner_class(model, logger=logging.getLogger(), meta=['list'])
96
97
98
99

    with pytest.raises(AssertionError):
        # model must implement the method train_step()
        model = OldStyleModel()
100
        _ = runner_class(model, logger=logging.getLogger())
101
102
103
104

    with pytest.raises(TypeError):
        # work_dir must be a str or None
        model = Model()
105
        _ = runner_class(model, work_dir=1, logger=logging.getLogger())
106
107
108
109
110
111
112
113

    with pytest.raises(RuntimeError):
        # batch_processor and train_step() cannot be both set

        def batch_processor():
            pass

        model = Model()
114
        _ = runner_class(model, batch_processor, logger=logging.getLogger())
115
116
117
118
119
120
121

    # test work_dir
    model = Model()
    temp_root = tempfile.gettempdir()
    dir_name = ''.join(
        [random.choice(string.ascii_letters) for _ in range(10)])
    work_dir = osp.join(temp_root, dir_name)
122
    _ = runner_class(model, work_dir=work_dir, logger=logging.getLogger())
123
    assert osp.isdir(work_dir)
124
    _ = runner_class(model, work_dir=work_dir, logger=logging.getLogger())
125
126
127
128
    assert osp.isdir(work_dir)
    os.removedirs(work_dir)


129
130
@pytest.mark.parametrize('runner_class', RUNNERS.module_dict.values())
def test_runner_with_parallel(runner_class):
Kai Chen's avatar
Kai Chen committed
131
132
133
134
135

    def batch_processor():
        pass

    model = MMDataParallel(OldStyleModel())
136
    _ = runner_class(model, batch_processor, logger=logging.getLogger())
Kai Chen's avatar
Kai Chen committed
137

138
    model = MMDataParallel(Model())
139
    _ = runner_class(model, logger=logging.getLogger())
140

Kai Chen's avatar
Kai Chen committed
141
142
143
144
145
146
147
    with pytest.raises(RuntimeError):
        # batch_processor and train_step() cannot be both set

        def batch_processor():
            pass

        model = MMDataParallel(Model())
148
        _ = runner_class(model, batch_processor, logger=logging.getLogger())
Kai Chen's avatar
Kai Chen committed
149
150


151
152
@pytest.mark.parametrize('runner_class', RUNNERS.module_dict.values())
def test_save_checkpoint(runner_class):
153
    model = Model()
154
    runner = runner_class(model=model, logger=logging.getLogger())
155

156
157
158
159
    with pytest.raises(TypeError):
        # meta should be None or dict
        runner.save_checkpoint('.', meta=list())

160
161
162
163
164
    with tempfile.TemporaryDirectory() as root:
        runner.save_checkpoint(root)

        latest_path = osp.join(root, 'latest.pth')
        assert osp.exists(latest_path)
165
166
167
168
169
170
171

        if isinstance(runner, EpochBasedRunner):
            first_ckp_path = osp.join(root, 'epoch_1.pth')
        elif isinstance(runner, IterBasedRunner):
            first_ckp_path = osp.join(root, 'iter_1.pth')

        assert osp.exists(first_ckp_path)
172
173
174
175
176
177

        if platform.system() != 'Windows':
            assert osp.realpath(latest_path) == osp.realpath(first_ckp_path)
        else:
            # use copy instead of symlink on windows
            pass
178
179

        torch.load(latest_path)
180
181


182
183
@pytest.mark.parametrize('runner_class', RUNNERS.module_dict.values())
def test_build_lr_momentum_hook(runner_class):
184
    model = Model()
185
    runner = runner_class(model=model, logger=logging.getLogger())
186
187
188

    # test policy that is already title
    lr_config = dict(
Yawei Li's avatar
Yawei Li committed
189
        policy='CosineAnnealing',
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        by_epoch=False,
        min_lr_ratio=0,
        warmup_iters=2,
        warmup_ratio=0.9)
    runner.register_lr_hook(lr_config)
    assert len(runner.hooks) == 1

    # test policy that is already title
    lr_config = dict(
        policy='Cyclic',
        by_epoch=False,
        target_ratio=(10, 1),
        cyclic_times=1,
        step_ratio_up=0.4)
    runner.register_lr_hook(lr_config)
    assert len(runner.hooks) == 2

    # test policy that is not title
    lr_config = dict(
        policy='cyclic',
        by_epoch=False,
        target_ratio=(0.85 / 0.95, 1),
        cyclic_times=1,
        step_ratio_up=0.4)
    runner.register_lr_hook(lr_config)
    assert len(runner.hooks) == 3

    # test policy that is title
    lr_config = dict(
        policy='Step',
        warmup='linear',
        warmup_iters=500,
        warmup_ratio=1.0 / 3,
        step=[8, 11])
    runner.register_lr_hook(lr_config)
    assert len(runner.hooks) == 4

    # test policy that is not title
    lr_config = dict(
        policy='step',
        warmup='linear',
        warmup_iters=500,
        warmup_ratio=1.0 / 3,
        step=[8, 11])
    runner.register_lr_hook(lr_config)
    assert len(runner.hooks) == 5

    # test policy that is already title
    mom_config = dict(
Yawei Li's avatar
Yawei Li committed
239
        policy='CosineAnnealing',
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        min_momentum_ratio=0.99 / 0.95,
        by_epoch=False,
        warmup_iters=2,
        warmup_ratio=0.9 / 0.95)
    runner.register_momentum_hook(mom_config)
    assert len(runner.hooks) == 6

    # test policy that is already title
    mom_config = dict(
        policy='Cyclic',
        by_epoch=False,
        target_ratio=(0.85 / 0.95, 1),
        cyclic_times=1,
        step_ratio_up=0.4)
    runner.register_momentum_hook(mom_config)
    assert len(runner.hooks) == 7

    # test policy that is already title
    mom_config = dict(
        policy='cyclic',
        by_epoch=False,
        target_ratio=(0.85 / 0.95, 1),
        cyclic_times=1,
        step_ratio_up=0.4)
    runner.register_momentum_hook(mom_config)
    assert len(runner.hooks) == 8
Miao Zheng's avatar
Miao Zheng committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288


@pytest.mark.parametrize('runner_class', RUNNERS.module_dict.values())
def test_register_timer_hook(runner_class):
    model = Model()
    runner = runner_class(model=model, logger=logging.getLogger())

    # test register None
    timer_config = None
    runner.register_timer_hook(timer_config)
    assert len(runner.hooks) == 0

    # test register IterTimerHook with config
    timer_config = dict(type='IterTimerHook')
    runner.register_timer_hook(timer_config)
    assert len(runner.hooks) == 1
    assert isinstance(runner.hooks[0], IterTimerHook)

    # test register IterTimerHook
    timer_config = IterTimerHook()
    runner.register_timer_hook(timer_config)
    assert len(runner.hooks) == 2
    assert isinstance(runner.hooks[1], IterTimerHook)