makeup.py 13.0 KB
Newer Older
Q
qingqing01 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
L
lijianshe02 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

L
lzzyzlbb 已提交
15 16 17 18
# code was heavily based on https://github.com/wtjiang98/PSGAN
# MIT License 
# Copyright (c) 2020 Wentao Jiang

L
lijianshe02 已提交
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
import paddle
import paddle.nn as nn
import paddle.nn.functional as F

import functools
import numpy as np

from ...modules.norm import build_norm_layer

from .builder import GENERATORS


class PONO(paddle.nn.Layer):
    def __init__(self, eps=1e-5):
        super(PONO, self).__init__()
        self.eps = eps

    def forward(self, x):
        mean = paddle.mean(x, axis=1, keepdim=True)
        var = paddle.mean(paddle.square(x - mean), axis=1, keepdim=True)
        tmp = (x - mean) / paddle.sqrt(var + self.eps)

        return tmp


class ResidualBlock(paddle.nn.Layer):
    """Residual Block with instance normalization."""
    def __init__(self, dim_in, dim_out, mode=None):
        super(ResidualBlock, self).__init__()
        if mode == 't':
            weight_attr = False
            bias_attr = False
        elif mode == 'p' or (mode is None):
            weight_attr = None
            bias_attr = None

        self.main = nn.Sequential(
L
LielinJiang 已提交
56
            nn.Conv2D(dim_in,
L
lijianshe02 已提交
57 58 59 60 61
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False),
L
LielinJiang 已提交
62
            nn.InstanceNorm2D(dim_out,
L
lijianshe02 已提交
63 64
                              weight_attr=weight_attr,
                              bias_attr=bias_attr), nn.ReLU(),
L
LielinJiang 已提交
65
            nn.Conv2D(dim_out,
L
lijianshe02 已提交
66 67 68 69 70
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False),
L
LielinJiang 已提交
71
            nn.InstanceNorm2D(dim_out,
L
lijianshe02 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
                              weight_attr=weight_attr,
                              bias_attr=bias_attr))

    def forward(self, x):
        """forward"""
        return x + self.main(x)


class StyleResidualBlock(paddle.nn.Layer):
    """Residual Block with instance normalization."""
    def __init__(self, dim_in, dim_out):
        super(StyleResidualBlock, self).__init__()
        self.block1 = nn.Sequential(
L
LielinJiang 已提交
85
            nn.Conv2D(dim_in,
L
lijianshe02 已提交
86 87 88 89 90
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False), PONO())
L
lijianshe02 已提交
91 92
        ks = 3
        pw = ks // 2
L
LielinJiang 已提交
93 94
        self.beta1 = nn.Conv2D(dim_in, dim_out, kernel_size=ks, padding=pw)
        self.gamma1 = nn.Conv2D(dim_in, dim_out, kernel_size=ks, padding=pw)
L
lijianshe02 已提交
95 96
        self.block2 = nn.Sequential(
            nn.ReLU(),
L
LielinJiang 已提交
97
            nn.Conv2D(dim_out,
L
lijianshe02 已提交
98 99 100 101 102
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False), PONO())
L
LielinJiang 已提交
103 104
        self.beta2 = nn.Conv2D(dim_in, dim_out, kernel_size=ks, padding=pw)
        self.gamma2 = nn.Conv2D(dim_in, dim_out, kernel_size=ks, padding=pw)
L
lijianshe02 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

    def forward(self, x, y):
        """forward"""
        x_ = self.block1(x)
        b = self.beta1(y)
        g = self.gamma1(y)
        x_ = (g + 1) * x_ + b
        x_ = self.block2(x_)
        b = self.beta2(y)
        g = self.gamma2(y)
        x_ = (g + 1) * x_ + b
        return x + x_


class MDNet(paddle.nn.Layer):
    """MDNet in PSGAN"""
    def __init__(self, conv_dim=64, repeat_num=3):
        super(MDNet, self).__init__()

        layers = []
        layers.append(
L
LielinJiang 已提交
126
            nn.Conv2D(3,
L
lijianshe02 已提交
127 128 129 130 131
                      conv_dim,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False))
L
lijianshe02 已提交
132
        layers.append(
L
LielinJiang 已提交
133
            nn.InstanceNorm2D(conv_dim, weight_attr=None, bias_attr=None))
L
lijianshe02 已提交
134 135 136 137 138 139 140

        layers.append(nn.ReLU())

        # Down-Sampling
        curr_dim = conv_dim
        for i in range(2):
            layers.append(
L
LielinJiang 已提交
141
                nn.Conv2D(curr_dim,
L
lijianshe02 已提交
142 143 144 145 146
                          curr_dim * 2,
                          kernel_size=4,
                          stride=2,
                          padding=1,
                          bias_attr=False))
L
lijianshe02 已提交
147
            layers.append(
L
LielinJiang 已提交
148
                nn.InstanceNorm2D(curr_dim * 2,
L
lijianshe02 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
                                  weight_attr=None,
                                  bias_attr=None))
            layers.append(nn.ReLU())
            curr_dim = curr_dim * 2

        # Bottleneck
        for i in range(repeat_num):
            layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim))

        self.main = nn.Sequential(*layers)

    def forward(self, x):
        """forward"""
        out = self.main(x)
        return out


class TNetDown(paddle.nn.Layer):
    """MDNet in PSGAN"""
    def __init__(self, conv_dim=64, repeat_num=3):
        super(TNetDown, self).__init__()

        layers = []
        layers.append(
L
LielinJiang 已提交
173
            nn.Conv2D(3,
L
lijianshe02 已提交
174 175 176 177 178
                      conv_dim,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False))
L
lijianshe02 已提交
179
        layers.append(
L
LielinJiang 已提交
180
            nn.InstanceNorm2D(conv_dim, weight_attr=False, bias_attr=False))
L
lijianshe02 已提交
181 182 183 184 185 186 187

        layers.append(nn.ReLU())

        # Down-Sampling
        curr_dim = conv_dim
        for i in range(2):
            layers.append(
L
LielinJiang 已提交
188
                nn.Conv2D(curr_dim,
L
lijianshe02 已提交
189 190 191 192 193
                          curr_dim * 2,
                          kernel_size=4,
                          stride=2,
                          padding=1,
                          bias_attr=False))
L
lijianshe02 已提交
194
            layers.append(
L
LielinJiang 已提交
195
                nn.InstanceNorm2D(curr_dim * 2,
L
lijianshe02 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
                                  weight_attr=False,
                                  bias_attr=False))
            layers.append(nn.ReLU())
            curr_dim = curr_dim * 2

        # Bottleneck
        for i in range(repeat_num):
            layers.append(
                ResidualBlock(dim_in=curr_dim, dim_out=curr_dim, mode='t'))

        self.main = nn.Sequential(*layers)

    def forward(self, x):
        """forward"""
        out = self.main(x)
        return out


L
lijianshe02 已提交
214
class GetMatrix(paddle.nn.Layer):
L
lijianshe02 已提交
215 216
    def __init__(self, dim_in, dim_out):
        super(GetMatrix, self).__init__()
L
LielinJiang 已提交
217
        self.get_gamma = nn.Conv2D(dim_in,
L
lijianshe02 已提交
218 219 220 221 222
                                   dim_out,
                                   kernel_size=1,
                                   stride=1,
                                   padding=0,
                                   bias_attr=False)
L
LielinJiang 已提交
223
        self.get_beta = nn.Conv2D(dim_in,
L
lijianshe02 已提交
224 225 226 227 228
                                  dim_out,
                                  kernel_size=1,
                                  stride=1,
                                  padding=0,
                                  bias_attr=False)
L
lijianshe02 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242

    def forward(self, x):
        gamma = self.get_gamma(x)
        beta = self.get_beta(x)
        return gamma, beta


class MANet(paddle.nn.Layer):
    """MANet in PSGAN"""
    def __init__(self, conv_dim=64, repeat_num=3, w=0.01):
        super(MANet, self).__init__()
        self.encoder = TNetDown(conv_dim=conv_dim, repeat_num=repeat_num)
        curr_dim = conv_dim * 4
        self.w = w
L
LielinJiang 已提交
243 244
        self.beta = nn.Conv2D(curr_dim, curr_dim, kernel_size=3, padding=1)
        self.gamma = nn.Conv2D(curr_dim, curr_dim, kernel_size=3, padding=1)
L
lijianshe02 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258
        self.simple_spade = GetMatrix(curr_dim, 1)  # get the makeup matrix
        self.repeat_num = repeat_num
        for i in range(repeat_num):
            setattr(self, "bottlenecks_" + str(i),
                    ResidualBlock(dim_in=curr_dim, dim_out=curr_dim, mode='t'))
        # Up-Sampling
        self.upsamplers = []
        self.up_betas = []
        self.up_gammas = []
        self.up_acts = []
        y_dim = curr_dim
        for i in range(2):
            layers = []
            layers.append(
L
LielinJiang 已提交
259
                nn.Conv2DTranspose(curr_dim,
L
lijianshe02 已提交
260 261 262 263 264 265
                                   curr_dim // 2,
                                   kernel_size=4,
                                   stride=2,
                                   padding=1,
                                   bias_attr=False))
            layers.append(
L
LielinJiang 已提交
266
                nn.InstanceNorm2D(curr_dim // 2,
L
lijianshe02 已提交
267 268 269 270 271 272
                                  weight_attr=False,
                                  bias_attr=False))

            setattr(self, "up_acts_" + str(i), nn.ReLU())
            setattr(
                self, "up_betas_" + str(i),
L
LielinJiang 已提交
273
                nn.Conv2DTranspose(y_dim,
L
lijianshe02 已提交
274 275 276 277 278 279
                                   curr_dim // 2,
                                   kernel_size=4,
                                   stride=2,
                                   padding=1))
            setattr(
                self, "up_gammas_" + str(i),
L
LielinJiang 已提交
280
                nn.Conv2DTranspose(y_dim,
L
lijianshe02 已提交
281 282 283 284 285 286 287
                                   curr_dim // 2,
                                   kernel_size=4,
                                   stride=2,
                                   padding=1))
            setattr(self, "up_samplers_" + str(i), nn.Sequential(*layers))
            curr_dim = curr_dim // 2
        self.img_reg = [
L
LielinJiang 已提交
288
            nn.Conv2D(curr_dim,
L
lijianshe02 已提交
289 290 291 292 293
                      3,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False)
L
lijianshe02 已提交
294 295 296 297 298 299 300 301 302 303 304
        ]
        self.img_reg = nn.Sequential(*self.img_reg)

    def forward(self, x, y, x_p, y_p, consistency_mask, mask_x, mask_y):
        """forward"""
        # y -> ref feature
        # x -> src img
        x = self.encoder(x)
        _, c, h, w = x.shape

        _, c2, h2, w2 = y.shape
L
lijianshe02 已提交
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

        mask_x = F.interpolate(mask_x, size=(64, 64))
        mask_x = mask_x.transpose((1, 0, 2, 3))
        mask_x_re = mask_x.tile([1, x.shape[1], 1, 1])
        mask_x_diff_re = mask_x.tile([1, x_p.shape[1], 1, 1])
        mask_y = F.interpolate(mask_y, size=(64, 64))
        mask_y = mask_y.transpose((1, 0, 2, 3))
        mask_y_re = mask_y.tile([1, y.shape[1], 1, 1])
        mask_y_diff_re = mask_y.tile([1, y_p.shape[1], 1, 1])

        x_re = x.tile([3, 1, 1, 1])
        y_re = y.tile([3, 1, 1, 1])
        x_flat = x_re * mask_x_re
        y_flat = y_re * mask_y_re

        x_p = x_p.tile([3, 1, 1, 1]) * mask_x_diff_re
        y_p = y_p.tile([3, 1, 1, 1]) * mask_y_diff_re

        norm_x = paddle.norm(x_p, axis=1,
                             keepdim=True).tile([1, x_p.shape[1], 1, 1])
        norm_x = paddle.where(norm_x == 0, paddle.to_tensor(1e10), norm_x)
        x_p = x_p / norm_x
        norm_y = paddle.norm(y_p, axis=1,
                             keepdim=True).tile([1, y_p.shape[1], 1, 1])
        norm_y = paddle.where(norm_y == 0, paddle.to_tensor(1e10), norm_y)
        y_p = y_p / norm_y

        x_flat = paddle.concat([x_flat * 0.01, x_p], axis=1)
        y_flat = paddle.concat([y_flat * 0.01, y_p], axis=1)

        x_flat_re = x_flat.reshape([3, x_flat.shape[1], h * w])
        y_flat_re = y_flat.reshape([3, y_flat.shape[1], h2 * w2])

        a_ = paddle.matmul(x_flat_re, y_flat_re, transpose_x=True)

        with paddle.no_grad():
            a_mask = a_ != 0

        a_ *= 200
L
lijianshe02 已提交
344
        a = F.softmax(a_, axis=-1)
L
lijianshe02 已提交
345
        a = a * a_mask
L
lijianshe02 已提交
346 347

        gamma, beta = self.simple_spade(y)
L
lijianshe02 已提交
348 349
        gamma = gamma.tile([3, 1, 1, 1]) * mask_y
        beta = beta.tile([3, 1, 1, 1]) * mask_y
L
lijianshe02 已提交
350 351 352

        beta = beta.reshape([-1, h2 * w2, 1])
        beta = paddle.matmul(a, beta)
L
lijianshe02 已提交
353
        beta = beta.transpose((0, 2, 1))
L
lijianshe02 已提交
354 355 356
        beta = beta.reshape([-1, 1, h2, w2])
        gamma = gamma.reshape([-1, h2 * w2, 1])
        gamma = paddle.matmul(a, gamma)
L
lijianshe02 已提交
357
        gamma = gamma.transpose((0, 2, 1))
L
lijianshe02 已提交
358
        gamma = gamma.reshape([-1, 1, h2, w2])
L
lijianshe02 已提交
359 360 361

        beta = (beta[0] + beta[1] + beta[2]).unsqueeze(0)
        gamma = (gamma[0] + gamma[1] + gamma[2]).unsqueeze(0)
L
lijianshe02 已提交
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
        x = x * (1 + gamma) + beta

        for i in range(self.repeat_num):
            layer = getattr(self, "bottlenecks_" + str(i))
            x = layer(x)

        for idx in range(2):
            layer = getattr(self, "up_samplers_" + str(idx))
            x = layer(x)
            layer = getattr(self, "up_acts_" + str(idx))
            x = layer(x)
        x = self.img_reg(x)
        x = paddle.tanh(x)
        return x, a


@GENERATORS.register()
class GeneratorPSGANAttention(paddle.nn.Layer):
    def __init__(self, conv_dim=64, repeat_num=3):
        super(GeneratorPSGANAttention, self).__init__()
        self.ma_net = MANet(conv_dim=conv_dim, repeat_num=repeat_num)
        self.md_net = MDNet(conv_dim=conv_dim, repeat_num=repeat_num)

    def forward(self, x, y, x_p, y_p, consistency_mask, mask_x, mask_y):
        """forward"""
        y = self.md_net(y)
        out, a = self.ma_net(x, y, x_p, y_p, consistency_mask, mask_x, mask_y)
        return out, a