modules.py 7.85 KB
Newer Older
1
2
3
4
5
6
7
8
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
43
44
45
46
47
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
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
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
# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, normal_init
from mmcv.runner import load_checkpoint
from mmcv.utils.parrots_wrapper import _BatchNorm

from mmgen.utils import get_root_logger


class GeneratorBlock(nn.Module):
    """Generator block used in SinGAN.

    Args:
        in_channels (int): Input channels.
        out_channels (int): Output channels.
        num_scales (int): The number of scales/stages in generator. Note
            that this number is counted from zero, which is the same as the
            original paper.
        kernel_size (int, optional): Kernel size, same as :obj:`nn.Conv2d`.
            Defaults to 3.
        padding (int, optional): Padding for the convolutional layer, same as
            :obj:`nn.Conv2d`. Defaults to 0.
        num_layers (int, optional): The number of convolutional layers in each
            generator block. Defaults to 5.
        base_channels (int, optional): The basic channels for convolutional
            layers in the generator block. Defaults to 32.
        min_feat_channels (int, optional): Minimum channels for the feature
            maps in the generator block. Defaults to 32.
        out_act_cfg (dict | None, optional): Configs for output activation
            layer. Defaults to dict(type='Tanh').
        stride (int, optional): Same as :obj:`nn.Conv2d`. Defaults to 1.
        allow_no_residual (bool, optional): Whether to allow no residual link
            in this block. Defaults to False.
    """

    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 padding,
                 num_layers,
                 base_channels,
                 min_feat_channels,
                 out_act_cfg=dict(type='Tanh'),
                 stride=1,
                 allow_no_residual=False,
                 **kwargs):
        super().__init__()
        self.in_channels = in_channels

        self.base_channels = base_channels

        self.kernel_size = kernel_size
        self.num_layers = num_layers
        self.allow_no_residual = allow_no_residual

        self.head = ConvModule(
            in_channels=in_channels,
            out_channels=base_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=1,
            norm_cfg=dict(type='BN'),
            act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
            **kwargs)

        self.body = nn.Sequential()

        for i in range(num_layers - 2):
            feat_channels_ = int(base_channels / pow(2, (i + 1)))
            block = ConvModule(
                max(2 * feat_channels_, min_feat_channels),
                max(feat_channels_, min_feat_channels),
                kernel_size=kernel_size,
                padding=padding,
                stride=stride,
                norm_cfg=dict(type='BN'),
                act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
                **kwargs)
            self.body.add_module(f'block{i+1}', block)

        self.tail = ConvModule(
            max(feat_channels_, min_feat_channels),
            out_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=1,
            norm_cfg=None,
            act_cfg=out_act_cfg,
            **kwargs)

        self.init_weights()

    def forward(self, x, prev):
        """Forward function.

        Args:
            x (Tensor): Input feature map.
            prev (Tensor): Previous feature map.

        Returns:
            Tensor: Output feature map with the shape of (N, C, H, W).
        """
        x = self.head(x)
        x = self.body(x)
        x = self.tail(x)

        # if prev and x are not in the same shape at the channel dimension
        if self.allow_no_residual and x.shape[1] != prev.shape[1]:
            return x

        return x + prev

    def init_weights(self, pretrained=None):
        if isinstance(pretrained, str):
            logger = get_root_logger()
            load_checkpoint(self, pretrained, strict=False, logger=logger)
        elif pretrained is None:
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    normal_init(m, 0, 0.02)
                elif isinstance(m, (_BatchNorm, nn.InstanceNorm2d)):
                    constant_init(m, 1)
        else:
            raise TypeError('pretrained must be a str or None but'
                            f' got {type(pretrained)} instead.')


class DiscriminatorBlock(nn.Module):
    """Discriminator Block used in SinGAN.

    Args:
        in_channels (int): Input channels.
        base_channels (int): Base channels for this block.
        min_feat_channels (int): The minimum channels for feature map.
        kernel_size (int): Size of convolutional kernel, same as
            :obj:`nn.Conv2d`.
        padding (int): Padding for convolutional layer, same as
            :obj:`nn.Conv2d`.
        num_layers (int): The number of convolutional layers in this block.
        norm_cfg (dict | None, optional): Config for the normalization layer.
            Defaults to dict(type='BN').
        act_cfg (dict | None, optional): Config for the activation layer.
            Defaults to dict(type='LeakyReLU', negative_slope=0.2).
        stride (int, optional): The stride for the convolutional layer, same as
            :obj:`nn.Conv2d`. Defaults to 1.
    """

    def __init__(self,
                 in_channels,
                 base_channels,
                 min_feat_channels,
                 kernel_size,
                 padding,
                 num_layers,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='LeakyReLU', negative_slope=0.2),
                 stride=1,
                 **kwargs):
        super().__init__()

        self.base_channels = base_channels
        self.stride = stride
        self.head = ConvModule(
            in_channels,
            base_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=1,
            norm_cfg=norm_cfg,
            act_cfg=act_cfg,
            **kwargs)

        self.body = nn.Sequential()

        for i in range(num_layers - 2):
            feat_channels_ = int(base_channels / pow(2, (i + 1)))
            block = ConvModule(
                max(2 * feat_channels_, min_feat_channels),
                max(feat_channels_, min_feat_channels),
                kernel_size=kernel_size,
                padding=padding,
                stride=stride,
                conv_cfg=None,
                norm_cfg=norm_cfg,
                act_cfg=act_cfg,
                **kwargs)
            self.body.add_module(f'block{i+1}', block)

        self.tail = ConvModule(
            max(feat_channels_, min_feat_channels),
            1,
            kernel_size=kernel_size,
            padding=padding,
            stride=1,
            norm_cfg=None,
            act_cfg=None,
            **kwargs)

        self.init_weights()

    def forward(self, x):
        """Forward function.

        Args:
            x (Tensor): Input feature map with shape of (N, C, H, W).

        Returns:
            Tensor: Output feature map.
        """
        x = self.head(x)
        x = self.body(x)
        x = self.tail(x)

        return x

    # TODO: study the effects of init functions
    def init_weights(self, pretrained=None):
        if isinstance(pretrained, str):
            logger = get_root_logger()
            load_checkpoint(self, pretrained, strict=False, logger=logger)
        elif pretrained is None:
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    normal_init(m, 0, 0.02)
                elif isinstance(m, (_BatchNorm, nn.InstanceNorm2d)):
                    constant_init(m, 1)
        else:
            raise TypeError('pretrained must be a str or None but'
                            f' got {type(pretrained)} instead.')