first_order.py 15.5 KB
Newer Older
F
FNRE 已提交
1
# code was heavily based on https://github.com/AliaksandrSiarohin/first-order-model
L
lzzyzlbb 已提交
2 3
# Users should be careful about adopting these functions in any commercial matters.
# https://github.com/AliaksandrSiarohin/first-order-model/blob/master/LICENSE.md
F
FNRE 已提交
4

5 6 7 8 9
import paddle
import paddle.nn as nn
import paddle.nn.functional as F


F
FNRE 已提交
10
def SyncBatchNorm(*args, **kwargs):
L
lzzyzlbb 已提交
11 12
    if paddle.distributed.get_world_size() > 1:
        return nn.SyncBatchNorm(*args, **kwargs)
F
FNRE 已提交
13
    else:
L
lzzyzlbb 已提交
14
        return nn.BatchNorm(*args, **kwargs)
F
FNRE 已提交
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


class ImagePyramide(nn.Layer):
    """
    Create image pyramide for computing pyramide perceptual loss. See Sec 3.3
    """
    def __init__(self, scales, num_channels):
        super(ImagePyramide, self).__init__()
        self.downs = paddle.nn.LayerList()
        self.name_list = []
        for scale in scales:
            self.downs.add_sublayer(
                str(scale).replace('.', '-'),
                AntiAliasInterpolation2d(num_channels, scale))
            self.name_list.append(str(scale).replace('.', '-'))

    def forward(self, x):
        out_dict = {}
        for scale, down_module in zip(self.name_list, self.downs):
            out_dict['prediction_' +
                     str(scale).replace('-', '.')] = down_module(x)
        return out_dict


def detach_kp(kp):
    return {key: value.detach() for key, value in kp.items()}


43 44 45 46 47 48 49 50 51 52
def kp2gaussian(kp, spatial_size, kp_variance):
    """
    Transform a keypoint into gaussian like representation
    """
    mean = kp['value']

    coordinate_grid = make_coordinate_grid(spatial_size, mean.dtype)
    number_of_leading_dimensions = len(mean.shape) - 1
    shape = (1, ) * number_of_leading_dimensions + tuple(coordinate_grid.shape)
    repeats = tuple(mean.shape[:number_of_leading_dimensions]) + (1, 1, 1)
F
FNRE 已提交
53 54
    coordinate_grid = coordinate_grid.reshape(shape)
    coordinate_grid = coordinate_grid.tile(repeats)
55 56 57 58 59 60 61 62 63 64 65 66

    # Preprocess kp shape
    shape = tuple(mean.shape[:number_of_leading_dimensions]) + (1, 1, 2)
    mean = mean.reshape(shape)

    mean_sub = (coordinate_grid - mean)

    out = paddle.exp(-0.5 * (mean_sub**2).sum(-1) / kp_variance)

    return out


F
FNRE 已提交
67
def make_coordinate_grid(spatial_size, type='float32'):
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    """
    Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
    """
    h, w = spatial_size
    x = paddle.arange(w, dtype=type)  #.type(type)
    y = paddle.arange(h, dtype=type)  #.type(type)

    x = (2 * (x / (w - 1)) - 1)
    y = (2 * (y / (h - 1)) - 1)

    yy = paddle.tile(y.reshape([-1, 1]), [1, w])
    xx = paddle.tile(x.reshape([1, -1]), [h, 1])

    meshed = paddle.concat([xx.unsqueeze(2), yy.unsqueeze(2)], 2)

    return meshed


class ResBlock2d(nn.Layer):
    """
    Res block, preserve spatial resolution.
    """
    def __init__(self, in_features, kernel_size, padding):
        super(ResBlock2d, self).__init__()
L
LielinJiang 已提交
92
        self.conv1 = nn.Conv2D(in_channels=in_features,
93 94 95
                               out_channels=in_features,
                               kernel_size=kernel_size,
                               padding=padding)
L
LielinJiang 已提交
96
        self.conv2 = nn.Conv2D(in_channels=in_features,
97 98 99
                               out_channels=in_features,
                               kernel_size=kernel_size,
                               padding=padding)
F
FNRE 已提交
100 101
        self.norm1 = SyncBatchNorm(in_features)
        self.norm2 = SyncBatchNorm(in_features)
102 103 104 105 106 107 108 109 110 111 112

    def forward(self, x):
        out = self.norm1(x)
        out = F.relu(out)
        out = self.conv1(out)
        out = self.norm2(out)
        out = F.relu(out)
        out = self.conv2(out)
        out += x
        return out

L
lzzyzlbb 已提交
113

L
lzzyzlbb 已提交
114 115 116 117 118 119 120
class MobileResBlock2d(nn.Layer):
    """
    Res block, preserve spatial resolution.
    """
    def __init__(self, in_features, kernel_size, padding):
        super(MobileResBlock2d, self).__init__()
        out_features = in_features * 2
L
lzzyzlbb 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        self.conv_pw = nn.Conv2D(in_channels=in_features,
                                 out_channels=out_features,
                                 kernel_size=1,
                                 padding=0,
                                 bias_attr=False)
        self.conv_dw = nn.Conv2D(in_channels=out_features,
                                 out_channels=out_features,
                                 kernel_size=kernel_size,
                                 padding=padding,
                                 groups=out_features,
                                 bias_attr=False)
        self.conv_pw_linear = nn.Conv2D(in_channels=out_features,
                                        out_channels=in_features,
                                        kernel_size=1,
                                        padding=0,
                                        bias_attr=False)
L
lzzyzlbb 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        self.norm1 = SyncBatchNorm(in_features)
        self.norm_pw = SyncBatchNorm(out_features)
        self.norm_dw = SyncBatchNorm(out_features)
        self.norm_pw_linear = SyncBatchNorm(in_features)

    def forward(self, x):
        out = self.norm1(x)
        out = F.relu(out)
        out = self.conv_pw(out)
        out = self.norm_pw(out)

        out = self.conv_dw(out)
        out = self.norm_dw(out)
        out = F.relu(out)

        out = self.conv_pw_linear(out)
        out = self.norm_pw_linear(out)
        out += x
        return out

157 158 159 160 161 162 163 164 165 166 167 168 169

class UpBlock2d(nn.Layer):
    """
    Upsampling block for use in decoder.
    """
    def __init__(self,
                 in_features,
                 out_features,
                 kernel_size=3,
                 padding=1,
                 groups=1):
        super(UpBlock2d, self).__init__()

L
LielinJiang 已提交
170
        self.conv = nn.Conv2D(in_channels=in_features,
171 172 173 174
                              out_channels=out_features,
                              kernel_size=kernel_size,
                              padding=padding,
                              groups=groups)
F
FNRE 已提交
175
        self.norm = SyncBatchNorm(out_features)
176 177 178 179 180 181 182 183

    def forward(self, x):
        out = F.interpolate(x, scale_factor=2)
        out = self.conv(out)
        out = self.norm(out)
        out = F.relu(out)
        return out

L
lzzyzlbb 已提交
184

L
lzzyzlbb 已提交
185 186 187 188
class MobileUpBlock2d(nn.Layer):
    """
    Upsampling block for use in decoder.
    """
L
lzzyzlbb 已提交
189 190 191 192 193 194
    def __init__(self,
                 in_features,
                 out_features,
                 kernel_size=3,
                 padding=1,
                 groups=1):
L
lzzyzlbb 已提交
195 196
        super(MobileUpBlock2d, self).__init__()

L
lzzyzlbb 已提交
197 198 199 200 201 202 203 204 205 206 207
        self.conv = nn.Conv2D(in_channels=in_features,
                              out_channels=in_features,
                              kernel_size=kernel_size,
                              padding=padding,
                              groups=in_features,
                              bias_attr=False)
        self.conv1 = nn.Conv2D(in_channels=in_features,
                               out_channels=out_features,
                               kernel_size=1,
                               padding=0,
                               bias_attr=False)
L
lzzyzlbb 已提交
208 209
        self.norm = SyncBatchNorm(in_features)
        self.norm1 = SyncBatchNorm(out_features)
L
lzzyzlbb 已提交
210

L
lzzyzlbb 已提交
211 212 213 214 215 216 217 218 219 220 221
    def forward(self, x):
        out = F.interpolate(x, scale_factor=2)
        out = self.conv(out)
        out = self.norm(out)
        out = F.relu(out)
        out = self.conv1(out)
        out = self.norm1(out)
        out = F.relu(out)
        return out


222 223 224 225 226 227 228 229 230 231 232
class DownBlock2d(nn.Layer):
    """
    Downsampling block for use in encoder.
    """
    def __init__(self,
                 in_features,
                 out_features,
                 kernel_size=3,
                 padding=1,
                 groups=1):
        super(DownBlock2d, self).__init__()
L
LielinJiang 已提交
233
        self.conv = nn.Conv2D(in_channels=in_features,
234 235 236 237
                              out_channels=out_features,
                              kernel_size=kernel_size,
                              padding=padding,
                              groups=groups)
F
FNRE 已提交
238
        self.norm = SyncBatchNorm(out_features)
L
LielinJiang 已提交
239
        self.pool = nn.AvgPool2D(kernel_size=(2, 2))
240 241 242 243 244 245 246 247 248

    def forward(self, x):
        out = self.conv(x)
        out = self.norm(out)
        out = F.relu(out)
        out = self.pool(out)
        return out


L
lzzyzlbb 已提交
249 250 251 252
class MobileDownBlock2d(nn.Layer):
    """
    Downsampling block for use in encoder.
    """
L
lzzyzlbb 已提交
253 254 255 256 257 258
    def __init__(self,
                 in_features,
                 out_features,
                 kernel_size=3,
                 padding=1,
                 groups=1):
L
lzzyzlbb 已提交
259
        super(MobileDownBlock2d, self).__init__()
L
lzzyzlbb 已提交
260 261 262 263 264 265
        self.conv = nn.Conv2D(in_channels=in_features,
                              out_channels=in_features,
                              kernel_size=kernel_size,
                              padding=padding,
                              groups=in_features,
                              bias_attr=False)
L
lzzyzlbb 已提交
266 267 268
        self.norm = SyncBatchNorm(in_features)
        self.pool = nn.AvgPool2D(kernel_size=(2, 2))

L
lzzyzlbb 已提交
269 270 271 272 273 274
        self.conv1 = nn.Conv2D(in_features,
                               out_features,
                               kernel_size=1,
                               padding=0,
                               stride=1,
                               bias_attr=False)
L
lzzyzlbb 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
        self.norm1 = SyncBatchNorm(out_features)

    def forward(self, x):
        out = self.conv(x)
        out = self.norm(out)
        out = F.relu(out)
        out = self.conv1(out)
        out = self.norm1(out)
        out = F.relu(out)
        out = self.pool(out)
        return out


288 289 290 291 292 293 294 295 296
class SameBlock2d(nn.Layer):
    """
    Simple block, preserve spatial resolution.
    """
    def __init__(self,
                 in_features,
                 out_features,
                 groups=1,
                 kernel_size=3,
L
lzzyzlbb 已提交
297 298
                 padding=1,
                 mobile_net=False):
299
        super(SameBlock2d, self).__init__()
L
LielinJiang 已提交
300
        self.conv = nn.Conv2D(in_channels=in_features,
301 302 303
                              out_channels=out_features,
                              kernel_size=kernel_size,
                              padding=padding,
L
lzzyzlbb 已提交
304
                              groups=groups,
L
lzzyzlbb 已提交
305
                              bias_attr=(mobile_net == False))
F
FNRE 已提交
306
        self.norm = SyncBatchNorm(out_features)
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    def forward(self, x):
        out = self.conv(x)
        out = self.norm(out)
        out = F.relu(out)
        return out


class Encoder(nn.Layer):
    """
    Hourglass Encoder
    """
    def __init__(self,
                 block_expansion,
                 in_features,
                 num_blocks=3,
L
lzzyzlbb 已提交
323
                 max_features=256,
L
lzzyzlbb 已提交
324
                 mobile_net=False):
325 326 327 328
        super(Encoder, self).__init__()

        down_blocks = []
        for i in range(num_blocks):
L
lzzyzlbb 已提交
329 330 331 332
            if mobile_net:
                down_blocks.append(
                    MobileDownBlock2d(in_features if i == 0 else min(
                        max_features, block_expansion * (2**i)),
L
lzzyzlbb 已提交
333 334 335 336
                                      min(max_features,
                                          block_expansion * (2**(i + 1))),
                                      kernel_size=3,
                                      padding=1))
L
lzzyzlbb 已提交
337 338 339 340
            else:
                down_blocks.append(
                    DownBlock2d(in_features if i == 0 else min(
                        max_features, block_expansion * (2**i)),
L
lzzyzlbb 已提交
341 342
                                min(max_features,
                                    block_expansion * (2**(i + 1))),
L
lzzyzlbb 已提交
343 344
                                kernel_size=3,
                                padding=1))
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        self.down_blocks = nn.LayerList(down_blocks)

    def forward(self, x):
        outs = [x]
        for down_block in self.down_blocks:
            outs.append(down_block(outs[-1]))
        return outs


class Decoder(nn.Layer):
    """
    Hourglass Decoder
    """
    def __init__(self,
                 block_expansion,
                 in_features,
                 num_blocks=3,
L
lzzyzlbb 已提交
362
                 max_features=256,
L
lzzyzlbb 已提交
363
                 mobile_net=False):
364 365 366 367 368 369
        super(Decoder, self).__init__()

        up_blocks = []

        for i in range(num_blocks)[::-1]:
            out_filters = min(max_features, block_expansion * (2**i))
L
lzzyzlbb 已提交
370 371
            if mobile_net:
                in_filters = (1 if i == num_blocks - 1 else 2) * min(
L
lzzyzlbb 已提交
372
                    max_features, block_expansion * (2**(i + 1)))
L
lzzyzlbb 已提交
373
                up_blocks.append(
L
lzzyzlbb 已提交
374 375 376 377
                    MobileUpBlock2d(in_filters,
                                    out_filters,
                                    kernel_size=3,
                                    padding=1))
L
lzzyzlbb 已提交
378 379 380 381
            else:
                in_filters = (1 if i == num_blocks - 1 else 2) * min(
                    max_features, block_expansion * (2**(i + 1)))
                up_blocks.append(
L
lzzyzlbb 已提交
382 383
                    UpBlock2d(in_filters, out_filters, kernel_size=3,
                              padding=1))
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

        self.up_blocks = nn.LayerList(up_blocks)
        self.out_filters = block_expansion + in_features

    def forward(self, x):
        out = x.pop()
        for up_block in self.up_blocks:
            out = up_block(out)
            skip = x.pop()
            out = paddle.concat([out, skip], axis=1)
        return out


class Hourglass(nn.Layer):
    """
    Hourglass architecture.
    """
    def __init__(self,
                 block_expansion,
                 in_features,
                 num_blocks=3,
L
lzzyzlbb 已提交
405 406
                 max_features=256,
                 mobile_net=False):
407
        super(Hourglass, self).__init__()
L
lzzyzlbb 已提交
408 409 410 411 412 413 414 415 416 417
        self.encoder = Encoder(block_expansion,
                               in_features,
                               num_blocks,
                               max_features,
                               mobile_net=mobile_net)
        self.decoder = Decoder(block_expansion,
                               in_features,
                               num_blocks,
                               max_features,
                               mobile_net=mobile_net)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        self.out_filters = self.decoder.out_filters

    def forward(self, x):
        return self.decoder(self.encoder(x))


class AntiAliasInterpolation2d(nn.Layer):
    """
    Band-limited downsampling, for better preservation of the input signal.
    """
    def __init__(self, channels, scale):
        super(AntiAliasInterpolation2d, self).__init__()
        sigma = (1 / scale - 1) / 2
        kernel_size = 2 * round(sigma * 4) + 1
        self.ka = kernel_size // 2
        self.kb = self.ka - 1 if kernel_size % 2 == 0 else self.ka

        kernel_size = [kernel_size, kernel_size]
        sigma = [sigma, sigma]
        # The gaussian kernel is the product of the
        # gaussian function of each dimension.
        kernel = 1
        meshgrids = paddle.meshgrid(
            [paddle.arange(size, dtype='float32') for size in kernel_size])
        for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
            mean = (size - 1) / 2
F
FNRE 已提交
444
            kernel *= paddle.exp(-(mgrid - mean)**2 / (2 * std**2 + 1e-9))
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

        # Make sure sum of values in gaussian kernel equals 1.
        kernel = kernel / paddle.sum(kernel)
        # Reshape to depthwise convolutional weight
        kernel = kernel.reshape([1, 1, *kernel.shape])
        kernel = paddle.tile(kernel, [channels, *[1] * (kernel.dim() - 1)])

        self.register_buffer('weight', kernel)
        self.groups = channels
        self.scale = scale

    def forward(self, input):
        if self.scale == 1.0:
            return input

        out = F.pad(input, [self.ka, self.kb, self.ka, self.kb])
        out = F.conv2d(out, weight=self.weight, groups=self.groups)
F
FNRE 已提交
462 463 464 465
        out.stop_gradient = False
        inv_scale = 1 / self.scale
        int_inv_scale = int(inv_scale)
        assert (inv_scale == int_inv_scale)
L
lzzyzlbb 已提交
466
        #out = out[:, :, ::int_inv_scale, ::int_inv_scale]
F
FNRE 已提交
467
        # patch end
L
lzzyzlbb 已提交
468
        out = paddle.fluid.layers.resize_nearest(out, scale=self.scale)
469
        return out