makeup.py 11.6 KB
Newer Older
L
lijianshe02 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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
lijianshe02 已提交
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
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 已提交
52
            nn.Conv2D(dim_in,
L
lijianshe02 已提交
53 54 55 56 57
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False),
L
LielinJiang 已提交
58
            nn.InstanceNorm2D(dim_out,
L
lijianshe02 已提交
59 60
                              weight_attr=weight_attr,
                              bias_attr=bias_attr), nn.ReLU(),
L
LielinJiang 已提交
61
            nn.Conv2D(dim_out,
L
lijianshe02 已提交
62 63 64 65 66
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False),
L
LielinJiang 已提交
67
            nn.InstanceNorm2D(dim_out,
L
lijianshe02 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80
                              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 已提交
81
            nn.Conv2D(dim_in,
L
lijianshe02 已提交
82 83 84 85 86
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False), PONO())
L
lijianshe02 已提交
87 88
        ks = 3
        pw = ks // 2
L
LielinJiang 已提交
89 90
        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 已提交
91 92
        self.block2 = nn.Sequential(
            nn.ReLU(),
L
LielinJiang 已提交
93
            nn.Conv2D(dim_out,
L
lijianshe02 已提交
94 95 96 97 98
                      dim_out,
                      kernel_size=3,
                      stride=1,
                      padding=1,
                      bias_attr=False), PONO())
L
LielinJiang 已提交
99 100
        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 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    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 已提交
122
            nn.Conv2D(3,
L
lijianshe02 已提交
123 124 125 126 127
                      conv_dim,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False))
L
lijianshe02 已提交
128
        layers.append(
L
LielinJiang 已提交
129
            nn.InstanceNorm2D(conv_dim, weight_attr=None, bias_attr=None))
L
lijianshe02 已提交
130 131 132 133 134 135 136

        layers.append(nn.ReLU())

        # Down-Sampling
        curr_dim = conv_dim
        for i in range(2):
            layers.append(
L
LielinJiang 已提交
137
                nn.Conv2D(curr_dim,
L
lijianshe02 已提交
138 139 140 141 142
                          curr_dim * 2,
                          kernel_size=4,
                          stride=2,
                          padding=1,
                          bias_attr=False))
L
lijianshe02 已提交
143
            layers.append(
L
LielinJiang 已提交
144
                nn.InstanceNorm2D(curr_dim * 2,
L
lijianshe02 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
                                  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 已提交
169
            nn.Conv2D(3,
L
lijianshe02 已提交
170 171 172 173 174
                      conv_dim,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False))
L
lijianshe02 已提交
175
        layers.append(
L
LielinJiang 已提交
176
            nn.InstanceNorm2D(conv_dim, weight_attr=False, bias_attr=False))
L
lijianshe02 已提交
177 178 179 180 181 182 183

        layers.append(nn.ReLU())

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


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

    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 已提交
239 240
        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 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254
        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 已提交
255
                nn.Conv2DTranspose(curr_dim,
L
lijianshe02 已提交
256 257 258 259 260 261
                                   curr_dim // 2,
                                   kernel_size=4,
                                   stride=2,
                                   padding=1,
                                   bias_attr=False))
            layers.append(
L
LielinJiang 已提交
262
                nn.InstanceNorm2D(curr_dim // 2,
L
lijianshe02 已提交
263 264 265 266 267 268
                                  weight_attr=False,
                                  bias_attr=False))

            setattr(self, "up_acts_" + str(i), nn.ReLU())
            setattr(
                self, "up_betas_" + str(i),
L
LielinJiang 已提交
269
                nn.Conv2DTranspose(y_dim,
L
lijianshe02 已提交
270 271 272 273 274 275
                                   curr_dim // 2,
                                   kernel_size=4,
                                   stride=2,
                                   padding=1))
            setattr(
                self, "up_gammas_" + str(i),
L
LielinJiang 已提交
276
                nn.Conv2DTranspose(y_dim,
L
lijianshe02 已提交
277 278 279 280 281 282 283
                                   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 已提交
284
            nn.Conv2D(curr_dim,
L
lijianshe02 已提交
285 286 287 288 289
                      3,
                      kernel_size=7,
                      stride=1,
                      padding=3,
                      bias_attr=False)
L
lijianshe02 已提交
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
        ]
        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
        x_flat = x.reshape([-1, c, h * w])
        x_flat = self.w * x_flat
        if x_p is not None:
            x_flat = paddle.concat([x_flat, x_p], axis=1)

        _, c2, h2, w2 = y.shape
        y_flat = y.reshape([-1, c2, h2 * w2])
        y_flat = self.w * y_flat
        if y_p is not None:
            y_flat = paddle.concat([y_flat, y_p], axis=1)
        a_ = paddle.matmul(x_flat, y_flat, transpose_x=True) * 200.0

        # mask softmax
        if consistency_mask is not None:
            a_ = a_ - 100.0 * (1 - consistency_mask)
        a = F.softmax(a_, axis=-1)

        gamma, beta = self.simple_spade(y)

        beta = beta.reshape([-1, h2 * w2, 1])
        beta = paddle.matmul(a, beta)
        beta = beta.reshape([-1, 1, h2, w2])
        gamma = gamma.reshape([-1, h2 * w2, 1])
        gamma = paddle.matmul(a, gamma)
        gamma = gamma.reshape([-1, 1, h2, w2])
        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