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

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

Kai Chen's avatar
Kai Chen committed
13
from mmcv.parallel import MMDataParallel
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from mmcv.runner import EpochBasedRunner


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


def test_epoch_based_runner():

    with pytest.warns(UserWarning):
        # batch_processor is deprecated
        model = OldStyleModel()
38

39
40
        def batch_processor():
            pass
41

Harry's avatar
Harry committed
42
43
        _ = EpochBasedRunner(
            model, batch_processor, logger=logging.getLogger())
44
45
46
47

    with pytest.raises(TypeError):
        # batch_processor must be callable
        model = OldStyleModel()
Harry's avatar
Harry committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        _ = EpochBasedRunner(
            model, batch_processor=0, logger=logging.getLogger())

    with pytest.raises(TypeError):
        # optimizer must be a optimizer or a dict of optimizers
        model = Model()
        optimizer = 'NotAOptimizer'
        _ = EpochBasedRunner(
            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')
        _ = EpochBasedRunner(
            model, optimizer=optimizers, logger=logging.getLogger())

    with pytest.raises(TypeError):
        # logger must be a logging.Logger
        model = Model()
        _ = EpochBasedRunner(model, logger=None)

    with pytest.raises(TypeError):
        # meta must be a dict or None
        model = Model()
        _ = EpochBasedRunner(model, logger=logging.getLogger(), meta=['list'])
74
75
76
77

    with pytest.raises(AssertionError):
        # model must implement the method train_step()
        model = OldStyleModel()
Harry's avatar
Harry committed
78
        _ = EpochBasedRunner(model, logger=logging.getLogger())
79
80
81
82

    with pytest.raises(TypeError):
        # work_dir must be a str or None
        model = Model()
Harry's avatar
Harry committed
83
        _ = EpochBasedRunner(model, work_dir=1, logger=logging.getLogger())
84
85
86
87
88
89
90
91

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

        def batch_processor():
            pass

        model = Model()
Harry's avatar
Harry committed
92
93
        _ = EpochBasedRunner(
            model, batch_processor, logger=logging.getLogger())
94
95
96
97
98
99
100

    # 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)
Harry's avatar
Harry committed
101
    _ = EpochBasedRunner(model, work_dir=work_dir, logger=logging.getLogger())
102
    assert osp.isdir(work_dir)
Harry's avatar
Harry committed
103
    _ = EpochBasedRunner(model, work_dir=work_dir, logger=logging.getLogger())
104
105
106
107
    assert osp.isdir(work_dir)
    os.removedirs(work_dir)


Kai Chen's avatar
Kai Chen committed
108
109
110
111
112
113
def test_runner_with_parallel():

    def batch_processor():
        pass

    model = MMDataParallel(OldStyleModel())
Harry's avatar
Harry committed
114
    _ = EpochBasedRunner(model, batch_processor, logger=logging.getLogger())
Kai Chen's avatar
Kai Chen committed
115

116
117
118
    model = MMDataParallel(Model())
    _ = EpochBasedRunner(model, logger=logging.getLogger())

Kai Chen's avatar
Kai Chen committed
119
120
121
122
123
124
125
    with pytest.raises(RuntimeError):
        # batch_processor and train_step() cannot be both set

        def batch_processor():
            pass

        model = MMDataParallel(Model())
Harry's avatar
Harry committed
126
127
        _ = EpochBasedRunner(
            model, batch_processor, logger=logging.getLogger())
Kai Chen's avatar
Kai Chen committed
128
129


130
131
132
def test_save_checkpoint():
    model = Model()
    runner = EpochBasedRunner(model=model, logger=logging.getLogger())
133
134
135
136
137
138
139
140
141

    with tempfile.TemporaryDirectory() as root:
        runner.save_checkpoint(root)

        latest_path = osp.join(root, 'latest.pth')
        epoch1_path = osp.join(root, 'epoch_1.pth')

        assert osp.exists(latest_path)
        assert osp.exists(epoch1_path)
Kai Chen's avatar
Kai Chen committed
142
        assert osp.realpath(latest_path) == osp.realpath(epoch1_path)
143
144

        torch.load(latest_path)
145
146
147


def test_build_lr_momentum_hook():
148
149
    model = Model()
    runner = EpochBasedRunner(model=model, logger=logging.getLogger())
150
151
152

    # test policy that is already title
    lr_config = dict(
Yawei Li's avatar
Yawei Li committed
153
        policy='CosineAnnealing',
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        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
203
        policy='CosineAnnealing',
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
        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