conv_module.py 3.81 KB
Newer Older
Kai Chen's avatar
Kai Chen committed
1
2
3
import warnings

import torch.nn as nn
Kai Chen's avatar
Kai Chen committed
4
from mmcv.cnn import kaiming_init, constant_init
Kai Chen's avatar
Kai Chen committed
5

6
from .conv_ws import ConvWS2d
Kai Chen's avatar
Kai Chen committed
7
8
from .norm import build_norm_layer

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
conv_cfg = {
    'Conv': nn.Conv2d,
    'ConvWS': ConvWS2d,
    # TODO: octave conv
}


def build_conv_layer(cfg, *args, **kwargs):
    """ Build convolution layer

    Args:
        cfg (None or dict): cfg should contain:
            type (str): identify conv layer type.
            layer args: args needed to instantiate a conv layer.

    Returns:
        layer (nn.Module): created conv layer
    """
    if cfg is None:
        cfg_ = dict(type='Conv')
    else:
        assert isinstance(cfg, dict) and 'type' in cfg
        cfg_ = cfg.copy()

    layer_type = cfg_.pop('type')
    if layer_type not in conv_cfg:
        raise KeyError('Unrecognized norm type {}'.format(layer_type))
    else:
        conv_layer = conv_cfg[layer_type]

    layer = conv_layer(*args, **kwargs, **cfg_)

    return layer

Kai Chen's avatar
Kai Chen committed
43
44
45
46
47
48
49
50
51
52
53
54

class ConvModule(nn.Module):

    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride=1,
                 padding=0,
                 dilation=1,
                 groups=1,
                 bias=True,
55
                 conv_cfg=None,
Kai Chen's avatar
Kai Chen committed
56
57
58
59
60
                 normalize=None,
                 activation='relu',
                 inplace=True,
                 activate_last=True):
        super(ConvModule, self).__init__()
61
62
        assert conv_cfg is None or isinstance(conv_cfg, dict)
        assert normalize is None or isinstance(normalize, dict)
Kai Chen's avatar
Kai Chen committed
63
64
65
66
67
68
69
70
71
        self.with_norm = normalize is not None
        self.with_activatation = activation is not None
        self.with_bias = bias
        self.activation = activation
        self.activate_last = activate_last

        if self.with_norm and self.with_bias:
            warnings.warn('ConvModule has norm and bias at the same time')

72
73
        self.conv = build_conv_layer(
            conv_cfg,
Kai Chen's avatar
Kai Chen committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
            in_channels,
            out_channels,
            kernel_size,
            stride,
            padding,
            dilation,
            groups,
            bias=bias)

        self.in_channels = self.conv.in_channels
        self.out_channels = self.conv.out_channels
        self.kernel_size = self.conv.kernel_size
        self.stride = self.conv.stride
        self.padding = self.conv.padding
        self.dilation = self.conv.dilation
        self.transposed = self.conv.transposed
        self.output_padding = self.conv.output_padding
        self.groups = self.conv.groups

        if self.with_norm:
Kai Chen's avatar
Kai Chen committed
94
            norm_channels = out_channels if self.activate_last else in_channels
ThangVu's avatar
ThangVu committed
95
96
            self.norm_name, norm = build_norm_layer(normalize, norm_channels)
            self.add_module(self.norm_name, norm)
Kai Chen's avatar
Kai Chen committed
97
98
99
100
101
102
103
104
105

        if self.with_activatation:
            assert activation in ['relu'], 'Only ReLU supported.'
            if self.activation == 'relu':
                self.activate = nn.ReLU(inplace=inplace)

        # Default using msra init
        self.init_weights()

ThangVu's avatar
ThangVu committed
106
107
108
109
    @property
    def norm(self):
        return getattr(self, self.norm_name)

Kai Chen's avatar
Kai Chen committed
110
111
    def init_weights(self):
        nonlinearity = 'relu' if self.activation is None else self.activation
Kai Chen's avatar
Kai Chen committed
112
        kaiming_init(self.conv, nonlinearity=nonlinearity)
Kai Chen's avatar
Kai Chen committed
113
        if self.with_norm:
Kai Chen's avatar
Kai Chen committed
114
            constant_init(self.norm, 1, bias=0)
Kai Chen's avatar
Kai Chen committed
115
116
117
118
119

    def forward(self, x, activate=True, norm=True):
        if self.activate_last:
            x = self.conv(x)
            if norm and self.with_norm:
ThangVu's avatar
ThangVu committed
120
                x = self.norm(x)
Kai Chen's avatar
Kai Chen committed
121
122
123
124
            if activate and self.with_activatation:
                x = self.activate(x)
        else:
            if norm and self.with_norm:
ThangVu's avatar
ThangVu committed
125
                x = self.norm(x)
Kai Chen's avatar
Kai Chen committed
126
127
128
129
            if activate and self.with_activatation:
                x = self.activate(x)
            x = self.conv(x)
        return x