test_build_layers.py 14.8 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import inspect
3
4
from importlib import import_module

5
import numpy as np
Kai Chen's avatar
Kai Chen committed
6
7
8
import pytest
import torch
import torch.nn as nn
9
from mmengine.registry import MODELS
10
from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm
11
from torch.nn import ReflectionPad2d, Upsample
Kai Chen's avatar
Kai Chen committed
12

13
14
15
from mmcv.cnn.bricks import (ContextBlock, ConvModule, ConvTranspose2d,
                             GeneralizedAttention, NonLocal2d,
                             build_activation_layer, build_conv_layer,
16
17
                             build_norm_layer, build_padding_layer,
                             build_plugin_layer, build_upsample_layer, is_norm)
18
from mmcv.cnn.bricks.activation import Clamp
19
20
from mmcv.cnn.bricks.norm import infer_abbr as infer_norm_abbr
from mmcv.cnn.bricks.plugin import infer_abbr as infer_plugin_abbr
Kai Chen's avatar
Kai Chen committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from mmcv.cnn.bricks.upsample import PixelShufflePack


def test_build_conv_layer():
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'Conv2d'
        build_conv_layer(cfg)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict(kernel_size=3)
        build_conv_layer(cfg)

    with pytest.raises(KeyError):
        # unsupported conv type
        cfg = dict(type='FancyConv')
        build_conv_layer(cfg)

    kwargs = dict(
        in_channels=4, out_channels=8, kernel_size=3, groups=2, dilation=2)
    cfg = None
    layer = build_conv_layer(cfg, **kwargs)
    assert isinstance(layer, nn.Conv2d)
    assert layer.in_channels == kwargs['in_channels']
    assert layer.out_channels == kwargs['out_channels']
    assert layer.kernel_size == (kwargs['kernel_size'], kwargs['kernel_size'])
    assert layer.groups == kwargs['groups']
    assert layer.dilation == (kwargs['dilation'], kwargs['dilation'])

    cfg = dict(type='Conv')
    layer = build_conv_layer(cfg, **kwargs)
    assert isinstance(layer, nn.Conv2d)
    assert layer.in_channels == kwargs['in_channels']
    assert layer.out_channels == kwargs['out_channels']
    assert layer.kernel_size == (kwargs['kernel_size'], kwargs['kernel_size'])
    assert layer.groups == kwargs['groups']
    assert layer.dilation == (kwargs['dilation'], kwargs['dilation'])

GT9505's avatar
GT9505 committed
60
61
62
63
64
65
66
67
68
    cfg = dict(type='deconv')
    layer = build_conv_layer(cfg, **kwargs)
    assert isinstance(layer, nn.ConvTranspose2d)
    assert layer.in_channels == kwargs['in_channels']
    assert layer.out_channels == kwargs['out_channels']
    assert layer.kernel_size == (kwargs['kernel_size'], kwargs['kernel_size'])
    assert layer.groups == kwargs['groups']
    assert layer.dilation == (kwargs['dilation'], kwargs['dilation'])

69
70
71
    # sparse convs cannot support the case when groups>1
    kwargs.pop('groups')

72
    for type_name, module in MODELS.module_dict.items():
73
74
75
76
77
78
79
80
81
82
83
84
85
        for type_name_ in (type_name, module):
            cfg = dict(type=type_name_)
            # SparseInverseConv2d and SparseInverseConv3d do not have the
            # argument 'dilation'
            if type_name == 'SparseInverseConv2d' or type_name == \
                    'SparseInverseConv3d':
                kwargs.pop('dilation')
            if 'conv' in type_name.lower():
                layer = build_conv_layer(cfg, **kwargs)
                assert isinstance(layer, module)
                assert layer.in_channels == kwargs['in_channels']
                assert layer.out_channels == kwargs['out_channels']
                kwargs['dilation'] = 2  # recover the key
Kai Chen's avatar
Kai Chen committed
86
87


88
def test_infer_norm_abbr():
Kai Chen's avatar
Kai Chen committed
89
90
    with pytest.raises(TypeError):
        # class_type must be a class
91
        infer_norm_abbr(0)
Kai Chen's avatar
Kai Chen committed
92
93
94

    class MyNorm:

95
        _abbr_ = 'mn'
Kai Chen's avatar
Kai Chen committed
96

97
    assert infer_norm_abbr(MyNorm) == 'mn'
Kai Chen's avatar
Kai Chen committed
98
99
100
101

    class FancyBatchNorm:
        pass

102
    assert infer_norm_abbr(FancyBatchNorm) == 'bn'
Kai Chen's avatar
Kai Chen committed
103
104
105
106

    class FancyInstanceNorm:
        pass

107
    assert infer_norm_abbr(FancyInstanceNorm) == 'in'
Kai Chen's avatar
Kai Chen committed
108
109
110
111

    class FancyLayerNorm:
        pass

112
    assert infer_norm_abbr(FancyLayerNorm) == 'ln'
Kai Chen's avatar
Kai Chen committed
113
114
115
116

    class FancyGroupNorm:
        pass

117
    assert infer_norm_abbr(FancyGroupNorm) == 'gn'
Kai Chen's avatar
Kai Chen committed
118
119
120
121

    class FancyNorm:
        pass

122
    assert infer_norm_abbr(FancyNorm) == 'norm_layer'
Kai Chen's avatar
Kai Chen committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164


def test_build_norm_layer():
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'BN'
        build_norm_layer(cfg, 3)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict()
        build_norm_layer(cfg, 3)

    with pytest.raises(KeyError):
        # unsupported norm type
        cfg = dict(type='FancyNorm')
        build_norm_layer(cfg, 3)

    with pytest.raises(AssertionError):
        # postfix must be int or str
        cfg = dict(type='BN')
        build_norm_layer(cfg, 3, postfix=[1, 2])

    with pytest.raises(AssertionError):
        # `num_groups` must be in cfg when using 'GN'
        cfg = dict(type='GN')
        build_norm_layer(cfg, 3)

    # test each type of norm layer in norm_cfg
    abbr_mapping = {
        'BN': 'bn',
        'BN1d': 'bn',
        'BN2d': 'bn',
        'BN3d': 'bn',
        'SyncBN': 'bn',
        'GN': 'gn',
        'LN': 'ln',
        'IN': 'in',
        'IN1d': 'in',
        'IN2d': 'in',
        'IN3d': 'in',
    }
165
166
167
    for type_name, module in MODELS.module_dict.items():
        if type_name not in abbr_mapping:
            continue
168
169
        if type_name == 'MMSyncBN':  # skip MMSyncBN
            continue
Kai Chen's avatar
Kai Chen committed
170
        for postfix in ['_test', 1]:
171
172
173
174
175
176
177
178
179
180
181
182
            for type_name_ in (type_name, module):
                cfg = dict(type=type_name_)
                if type_name == 'GN':
                    cfg['num_groups'] = 3
                name, layer = build_norm_layer(cfg, 3, postfix=postfix)
                assert name == abbr_mapping[type_name] + str(postfix)
                assert isinstance(layer, module)
                if type_name == 'GN':
                    assert layer.num_channels == 3
                    assert layer.num_groups == cfg['num_groups']
                elif type_name != 'LN':
                    assert layer.num_features == 3
Kai Chen's avatar
Kai Chen committed
183
184
185


def test_build_activation_layer():
186
187
188
189
190
191
192
193
    act_names = [
        'ReLU', 'LeakyReLU', 'PReLU', 'RReLU', 'ReLU6', 'ELU', 'Sigmoid',
        'Tanh'
    ]

    for module_name in ['activation', 'hsigmoid', 'hswish', 'swish']:
        act_module = import_module(f'mmcv.cnn.bricks.{module_name}')
        for key, value in act_module.__dict__.items():
194
            if inspect.isclass(value) and issubclass(value, nn.Module):
195
196
                act_names.append(key)

Kai Chen's avatar
Kai Chen committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'ReLU'
        build_activation_layer(cfg)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict()
        build_activation_layer(cfg)

    with pytest.raises(KeyError):
        # unsupported activation type
        cfg = dict(type='FancyReLU')
        build_activation_layer(cfg)

    # test each type of activation layer in activation_cfg
213
214
215
216
217
    for type_name, module in MODELS.module_dict.items():
        if type_name in act_names:
            cfg['type'] = type_name
            layer = build_activation_layer(cfg)
            assert isinstance(layer, module)
Kai Chen's avatar
Kai Chen committed
218

219
    # sanity check for Clamp
220
221
222
223
224
225
    for type_name in ('Clamp', Clamp):
        act = build_activation_layer(dict(type='Clamp'))
        x = torch.randn(10) * 1000
        y = act(x)
        assert np.logical_and((y >= -1).numpy(), (y <= 1).numpy()).all()

226
227
228
229
230
231
232
    act = build_activation_layer(dict(type='Clip', min=0))
    y = act(x)
    assert np.logical_and((y >= 0).numpy(), (y <= 1).numpy()).all()
    act = build_activation_layer(dict(type='Clamp', max=0))
    y = act(x)
    assert np.logical_and((y >= -1).numpy(), (y <= 0).numpy()).all()

Kai Chen's avatar
Kai Chen committed
233
234

def test_build_padding_layer():
235
236
237
238
    pad_names = ['zero', 'reflect', 'replicate']
    for module_name in ['padding']:
        pad_module = import_module(f'mmcv.cnn.bricks.{module_name}')
        for key, value in pad_module.__dict__.items():
239
            if inspect.isclass(value) and issubclass(value, nn.Module):
240
241
                pad_names.append(key)

Kai Chen's avatar
Kai Chen committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'reflect'
        build_padding_layer(cfg)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict()
        build_padding_layer(cfg)

    with pytest.raises(KeyError):
        # unsupported activation type
        cfg = dict(type='FancyPad')
        build_padding_layer(cfg)

257
258
259
260
261
    for type_name, module in MODELS.module_dict.items():
        if type_name in pad_names:
            cfg['type'] = type_name
            layer = build_padding_layer(cfg, 2)
            assert isinstance(layer, module)
262
263
264
265
266
267
    for type_name in (ReflectionPad2d, 'reflect'):
        input_x = torch.randn(1, 2, 5, 5)
        cfg = dict(type=type_name)
        padding_layer = build_padding_layer(cfg, 2)
        res = padding_layer(input_x)
        assert res.shape == (1, 2, 9, 9)
Kai Chen's avatar
Kai Chen committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


def test_upsample_layer():
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'bilinear'
        build_upsample_layer(cfg)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict()
        build_upsample_layer(cfg)

    with pytest.raises(KeyError):
        # unsupported activation type
        cfg = dict(type='FancyUpsample')
        build_upsample_layer(cfg)

    for type_name in ['nearest', 'bilinear']:
        cfg['type'] = type_name
        layer = build_upsample_layer(cfg)
        assert isinstance(layer, nn.Upsample)
        assert layer.mode == type_name

292
293
294
295
296
297
    cfg = dict()
    cfg['type'] = Upsample
    layer_from_cls = build_upsample_layer(cfg)
    assert isinstance(layer_from_cls, nn.Upsample)
    assert layer_from_cls.mode == 'nearest'

Kai Chen's avatar
Kai Chen committed
298
299
300
301
302
    cfg = dict(
        type='deconv', in_channels=3, out_channels=3, kernel_size=3, stride=2)
    layer = build_upsample_layer(cfg)
    assert isinstance(layer, nn.ConvTranspose2d)

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    for type_name in ('deconv', ConvTranspose2d):
        cfg = dict(type=ConvTranspose2d)
        kwargs = dict(in_channels=3, out_channels=3, kernel_size=3, stride=2)
        layer = build_upsample_layer(cfg, **kwargs)
        assert isinstance(layer, nn.ConvTranspose2d)
        assert layer.in_channels == kwargs['in_channels']
        assert layer.out_channels == kwargs['out_channels']
        assert layer.kernel_size == (kwargs['kernel_size'],
                                     kwargs['kernel_size'])
        assert layer.stride == (kwargs['stride'], kwargs['stride'])

        layer = build_upsample_layer(cfg, 3, 3, 3, 2)
        assert isinstance(layer, nn.ConvTranspose2d)
        assert layer.in_channels == kwargs['in_channels']
        assert layer.out_channels == kwargs['out_channels']
        assert layer.kernel_size == (kwargs['kernel_size'],
                                     kwargs['kernel_size'])
        assert layer.stride == (kwargs['stride'], kwargs['stride'])

    for type_name in ('pixel_shuffle', PixelShufflePack):
        cfg = dict(
            type=type_name,
            in_channels=3,
            out_channels=3,
            scale_factor=2,
            upsample_kernel=3)
        layer = build_upsample_layer(cfg)
Kai Chen's avatar
Kai Chen committed
330

331
332
333
        assert isinstance(layer, PixelShufflePack)
        assert layer.scale_factor == 2
        assert layer.upsample_kernel == 3
Kai Chen's avatar
Kai Chen committed
334
335
336
337
338
339
340
341


def test_pixel_shuffle_pack():
    x_in = torch.rand(2, 3, 10, 10)
    pixel_shuffle = PixelShufflePack(3, 3, scale_factor=2, upsample_kernel=3)
    assert pixel_shuffle.upsample_conv.kernel_size == (3, 3)
    x_out = pixel_shuffle(x_in)
    assert x_out.shape == (2, 3, 20, 20)
Kai Chen's avatar
Kai Chen committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376


def test_is_norm():
    norm_set1 = [
        nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.InstanceNorm1d,
        nn.InstanceNorm2d, nn.InstanceNorm3d, nn.LayerNorm
    ]
    norm_set2 = [nn.GroupNorm]
    for norm_type in norm_set1:
        layer = norm_type(3)
        assert is_norm(layer)
        assert not is_norm(layer, exclude=(norm_type, ))
    for norm_type in norm_set2:
        layer = norm_type(3, 6)
        assert is_norm(layer)
        assert not is_norm(layer, exclude=(norm_type, ))

    class MyNorm(nn.BatchNorm2d):
        pass

    layer = MyNorm(3)
    assert is_norm(layer)
    assert not is_norm(layer, exclude=_BatchNorm)
    assert not is_norm(layer, exclude=(_BatchNorm, ))

    layer = nn.Conv2d(3, 8, 1)
    assert not is_norm(layer)

    with pytest.raises(TypeError):
        layer = nn.BatchNorm1d(3)
        is_norm(layer, exclude='BN')

    with pytest.raises(TypeError):
        layer = nn.BatchNorm1d(3)
        is_norm(layer, exclude=('BN', ))
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417


def test_infer_plugin_abbr():
    with pytest.raises(TypeError):
        # class_type must be a class
        infer_plugin_abbr(0)

    class MyPlugin:

        _abbr_ = 'mp'

    assert infer_plugin_abbr(MyPlugin) == 'mp'

    class FancyPlugin:
        pass

    assert infer_plugin_abbr(FancyPlugin) == 'fancy_plugin'


def test_build_plugin_layer():
    with pytest.raises(TypeError):
        # cfg must be a dict
        cfg = 'Plugin'
        build_plugin_layer(cfg)

    with pytest.raises(KeyError):
        # `type` must be in cfg
        cfg = dict()
        build_plugin_layer(cfg)

    with pytest.raises(KeyError):
        # unsupported plugin type
        cfg = dict(type='FancyPlugin')
        build_plugin_layer(cfg)

    with pytest.raises(AssertionError):
        # postfix must be int or str
        cfg = dict(type='ConvModule')
        build_plugin_layer(cfg, postfix=[1, 2])

    # test ContextBlock
418
419
420
421
422
423
424
    for type_name in ('ContextBlock', ContextBlock):
        for postfix in ['', '_test', 1]:
            cfg = dict(type=type_name)
            name, layer = build_plugin_layer(
                cfg, postfix=postfix, in_channels=16, ratio=1. / 4)
            assert name == 'context_block' + str(postfix)
            assert isinstance(layer, MODELS.module_dict['ContextBlock'])
425
426

    # test GeneralizedAttention
427
428
429
430
431
432
433
434
    for type_name in ('GeneralizedAttention', GeneralizedAttention):
        for postfix in ['', '_test', 1]:
            cfg = dict(type=type_name)
            name, layer = build_plugin_layer(
                cfg, postfix=postfix, in_channels=16)
            assert name == 'gen_attention_block' + str(postfix)
            assert isinstance(layer,
                              MODELS.module_dict['GeneralizedAttention'])
435
436

    # test NonLocal2d
437
438
439
440
441
442
443
    for type_name in ('NonLocal2d', NonLocal2d):
        for postfix in ['', '_test', 1]:
            cfg = dict(type='NonLocal2d')
            name, layer = build_plugin_layer(
                cfg, postfix=postfix, in_channels=16)
            assert name == 'nonlocal_block' + str(postfix)
            assert isinstance(layer, MODELS.module_dict['NonLocal2d'])
444
445
446

    # test ConvModule
    for postfix in ['', '_test', 1]:
447
448
449
450
451
452
453
454
455
456
        for type_name in ('ConvModule', ConvModule):
            cfg = dict(type=type_name)
            name, layer = build_plugin_layer(
                cfg,
                postfix=postfix,
                in_channels=16,
                out_channels=4,
                kernel_size=3)
            assert name == 'conv_block' + str(postfix)
            assert isinstance(layer, MODELS.module_dict['ConvModule'])