File size: 13,403 Bytes
4a582ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
231
232
233
234
235
236
237
238
239
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
330
331
332
333
334
335
336
337
338
339
340
341
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# The gca code was heavily based on https://github.com/Yaoyi-Li/GCA-Matting
# and https://github.com/open-mmlab/mmediting

import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddleseg.cvlibs import manager, param_init
from paddleseg.utils import utils

from ppmatting.models.layers import GuidedCxtAtten


class ResNet_D(nn.Layer):
    def __init__(self,
                 input_channels,
                 layers,
                 late_downsample=False,
                 pretrained=None):

        super().__init__()

        self.pretrained = pretrained

        self._norm_layer = nn.BatchNorm
        self.inplanes = 64
        self.late_downsample = late_downsample
        self.midplanes = 64 if late_downsample else 32
        self.start_stride = [1, 2, 1, 2] if late_downsample else [2, 1, 2, 1]
        self.conv1 = nn.utils.spectral_norm(
            nn.Conv2D(
                input_channels,
                32,
                kernel_size=3,
                stride=self.start_stride[0],
                padding=1,
                bias_attr=False))
        self.conv2 = nn.utils.spectral_norm(
            nn.Conv2D(
                32,
                self.midplanes,
                kernel_size=3,
                stride=self.start_stride[1],
                padding=1,
                bias_attr=False))
        self.conv3 = nn.utils.spectral_norm(
            nn.Conv2D(
                self.midplanes,
                self.inplanes,
                kernel_size=3,
                stride=self.start_stride[2],
                padding=1,
                bias_attr=False))
        self.bn1 = self._norm_layer(32)
        self.bn2 = self._norm_layer(self.midplanes)
        self.bn3 = self._norm_layer(self.inplanes)
        self.activation = nn.ReLU()
        self.layer1 = self._make_layer(
            BasicBlock, 64, layers[0], stride=self.start_stride[3])
        self.layer2 = self._make_layer(BasicBlock, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(BasicBlock, 256, layers[2], stride=2)
        self.layer_bottleneck = self._make_layer(
            BasicBlock, 512, layers[3], stride=2)

        self.init_weight()

    def _make_layer(self, block, planes, block_num, stride=1):
        if block_num == 0:
            return nn.Sequential(nn.Identity())
        norm_layer = self._norm_layer
        downsample = None
        if stride != 1:
            downsample = nn.Sequential(
                nn.AvgPool2D(2, stride),
                nn.utils.spectral_norm(
                    conv1x1(self.inplanes, planes * block.expansion)),
                norm_layer(planes * block.expansion), )
        elif self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.utils.spectral_norm(
                    conv1x1(self.inplanes, planes * block.expansion, stride)),
                norm_layer(planes * block.expansion), )

        layers = [block(self.inplanes, planes, stride, downsample, norm_layer)]
        self.inplanes = planes * block.expansion
        for _ in range(1, block_num):
            layers.append(block(self.inplanes, planes, norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.activation(x)
        x = self.conv2(x)
        x = self.bn2(x)
        x1 = self.activation(x)  # N x 32 x 256 x 256
        x = self.conv3(x1)
        x = self.bn3(x)
        x2 = self.activation(x)  # N x 64 x 128 x 128

        x3 = self.layer1(x2)  # N x 64 x 128 x 128
        x4 = self.layer2(x3)  # N x 128 x 64 x 64
        x5 = self.layer3(x4)  # N x 256 x 32 x 32
        x = self.layer_bottleneck(x5)  # N x 512 x 16 x 16

        return x, (x1, x2, x3, x4, x5)

    def init_weight(self):

        for layer in self.sublayers():
            if isinstance(layer, nn.Conv2D):

                if hasattr(layer, "weight_orig"):
                    param = layer.weight_orig
                else:
                    param = layer.weight
                param_init.xavier_uniform(param)

            elif isinstance(layer, (nn.BatchNorm, nn.SyncBatchNorm)):
                param_init.constant_init(layer.weight, value=1.0)
                param_init.constant_init(layer.bias, value=0.0)

            elif isinstance(layer, BasicBlock):
                param_init.constant_init(layer.bn2.weight, value=0.0)

        if self.pretrained is not None:
            utils.load_pretrained_model(self, self.pretrained)


@manager.MODELS.add_component
class ResShortCut_D(ResNet_D):
    def __init__(self,
                 input_channels,
                 layers,
                 late_downsample=False,
                 pretrained=None):
        super().__init__(
            input_channels,
            layers,
            late_downsample=late_downsample,
            pretrained=pretrained)

        self.shortcut_inplane = [input_channels, self.midplanes, 64, 128, 256]
        self.shortcut_plane = [32, self.midplanes, 64, 128, 256]

        self.shortcut = nn.LayerList()
        for stage, inplane in enumerate(self.shortcut_inplane):
            self.shortcut.append(
                self._make_shortcut(inplane, self.shortcut_plane[stage]))

    def _make_shortcut(self, inplane, planes):
        return nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2D(
                    inplane, planes, kernel_size=3, padding=1,
                    bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(planes),
            nn.utils.spectral_norm(
                nn.Conv2D(
                    planes, planes, kernel_size=3, padding=1, bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(planes))

    def forward(self, x):

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.activation(out)
        out = self.conv2(out)
        out = self.bn2(out)
        x1 = self.activation(out)  # N x 32 x 256 x 256
        out = self.conv3(x1)
        out = self.bn3(out)
        out = self.activation(out)

        x2 = self.layer1(out)  # N x 64 x 128 x 128
        x3 = self.layer2(x2)  # N x 128 x 64 x 64
        x4 = self.layer3(x3)  # N x 256 x 32 x 32
        out = self.layer_bottleneck(x4)  # N x 512 x 16 x 16

        fea1 = self.shortcut[0](x)  # input image and trimap
        fea2 = self.shortcut[1](x1)
        fea3 = self.shortcut[2](x2)
        fea4 = self.shortcut[3](x3)
        fea5 = self.shortcut[4](x4)

        return out, {
            'shortcut': (fea1, fea2, fea3, fea4, fea5),
            'image': x[:, :3, ...]
        }


@manager.MODELS.add_component
class ResGuidedCxtAtten(ResNet_D):
    def __init__(self,
                 input_channels,
                 layers,
                 late_downsample=False,
                 pretrained=None):
        super().__init__(
            input_channels,
            layers,
            late_downsample=late_downsample,
            pretrained=pretrained)
        self.input_channels = input_channels
        self.shortcut_inplane = [input_channels, self.midplanes, 64, 128, 256]
        self.shortcut_plane = [32, self.midplanes, 64, 128, 256]

        self.shortcut = nn.LayerList()
        for stage, inplane in enumerate(self.shortcut_inplane):
            self.shortcut.append(
                self._make_shortcut(inplane, self.shortcut_plane[stage]))

        self.guidance_head = nn.Sequential(
            nn.Pad2D(
                1, mode="reflect"),
            nn.utils.spectral_norm(
                nn.Conv2D(
                    3, 16, kernel_size=3, padding=0, stride=2,
                    bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(16),
            nn.Pad2D(
                1, mode="reflect"),
            nn.utils.spectral_norm(
                nn.Conv2D(
                    16, 32, kernel_size=3, padding=0, stride=2,
                    bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(32),
            nn.Pad2D(
                1, mode="reflect"),
            nn.utils.spectral_norm(
                nn.Conv2D(
                    32,
                    128,
                    kernel_size=3,
                    padding=0,
                    stride=2,
                    bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(128))

        self.gca = GuidedCxtAtten(128, 128)

        self.init_weight()

    def init_weight(self):

        for layer in self.sublayers():
            if isinstance(layer, nn.Conv2D):
                initializer = nn.initializer.XavierUniform()
                if hasattr(layer, "weight_orig"):
                    param = layer.weight_orig
                else:
                    param = layer.weight
                initializer(param, param.block)

            elif isinstance(layer, (nn.BatchNorm, nn.SyncBatchNorm)):
                param_init.constant_init(layer.weight, value=1.0)
                param_init.constant_init(layer.bias, value=0.0)

            elif isinstance(layer, BasicBlock):
                param_init.constant_init(layer.bn2.weight, value=0.0)

        if self.pretrained is not None:
            utils.load_pretrained_model(self, self.pretrained)

    def _make_shortcut(self, inplane, planes):
        return nn.Sequential(
            nn.utils.spectral_norm(
                nn.Conv2D(
                    inplane, planes, kernel_size=3, padding=1,
                    bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(planes),
            nn.utils.spectral_norm(
                nn.Conv2D(
                    planes, planes, kernel_size=3, padding=1, bias_attr=False)),
            nn.ReLU(),
            self._norm_layer(planes))

    def forward(self, x):

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.activation(out)
        out = self.conv2(out)
        out = self.bn2(out)
        x1 = self.activation(out)  # N x 32 x 256 x 256
        out = self.conv3(x1)
        out = self.bn3(out)
        out = self.activation(out)

        im_fea = self.guidance_head(
            x[:, :3, ...])  # downsample origin image and extract features
        if self.input_channels == 6:
            unknown = F.interpolate(
                x[:, 4:5, ...], scale_factor=1 / 8, mode='nearest')
        else:
            unknown = x[:, 3:, ...].equal(paddle.to_tensor([1.]))
            unknown = paddle.cast(unknown, dtype='float32')
            unknown = F.interpolate(unknown, scale_factor=1 / 8, mode='nearest')

        x2 = self.layer1(out)  # N x 64 x 128 x 128
        x3 = self.layer2(x2)  # N x 128 x 64 x 64
        x3 = self.gca(im_fea, x3, unknown)  # contextual attention
        x4 = self.layer3(x3)  # N x 256 x 32 x 32
        out = self.layer_bottleneck(x4)  # N x 512 x 16 x 16

        fea1 = self.shortcut[0](x)  # input image and trimap
        fea2 = self.shortcut[1](x1)
        fea3 = self.shortcut[2](x2)
        fea4 = self.shortcut[3](x3)
        fea5 = self.shortcut[4](x4)

        return out, {
            'shortcut': (fea1, fea2, fea3, fea4, fea5),
            'image_fea': im_fea,
            'unknown': unknown,
        }


class BasicBlock(nn.Layer):
    expansion = 1

    def __init__(self,
                 inplanes,
                 planes,
                 stride=1,
                 downsample=None,
                 norm_layer=None):
        super().__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = nn.utils.spectral_norm(conv3x3(inplanes, planes, stride))
        self.bn1 = norm_layer(planes)
        self.activation = nn.ReLU()
        self.conv2 = nn.utils.spectral_norm(conv3x3(planes, planes))
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.activation(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.activation(out)

        return out


def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2D(
        in_planes,
        out_planes,
        kernel_size=3,
        stride=stride,
        padding=dilation,
        groups=groups,
        bias_attr=False,
        dilation=dilation)


def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2D(
        in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False)