generator_starganv2.py 13.3 KB
Newer Older
W
wangna11BD 已提交
1 2 3
# code was heavily based on https://github.com/clovaai/stargan-v2
# Users should be careful about adopting these functions in any commercial matters.
# https://github.com/clovaai/stargan-v2#license
4 5 6 7 8 9 10 11 12 13
import paddle
from paddle import nn
import paddle.nn.functional as F

from .builder import GENERATORS
import numpy as np
import math

from ppgan.modules.wing import CoordConvTh, ConvBlock, HourGlass, preprocess

L
lzzyzlbb 已提交
14 15 16
from ppgan.utils.download import get_path_from_url

FAN_WEIGHT_URL = "https://paddlegan.bj.bcebos.com/models/wing.pdparams"
17

W
wangna11BD 已提交
18

19
class ResBlk(nn.Layer):
W
wangna11BD 已提交
20 21 22 23 24 25
    def __init__(self,
                 dim_in,
                 dim_out,
                 actv=nn.LeakyReLU(0.2),
                 normalize=False,
                 downsample=False):
26 27 28 29 30 31
        super().__init__()
        self.actv = actv
        self.normalize = normalize
        self.downsample = downsample
        self.learned_sc = dim_in != dim_out
        self._build_weights(dim_in, dim_out)
W
wangna11BD 已提交
32
        self.maxpool = nn.AvgPool2D(kernel_size=2)
33 34 35 36 37

    def _build_weights(self, dim_in, dim_out):
        self.conv1 = nn.Conv2D(dim_in, dim_in, 3, 1, 1)
        self.conv2 = nn.Conv2D(dim_in, dim_out, 3, 1, 1)
        if self.normalize:
W
wangna11BD 已提交
38 39 40 41 42 43
            self.norm1 = nn.InstanceNorm2D(dim_in,
                                           weight_attr=True,
                                           bias_attr=True)
            self.norm2 = nn.InstanceNorm2D(dim_in,
                                           weight_attr=True,
                                           bias_attr=True)
44 45 46 47 48 49 50
        if self.learned_sc:
            self.conv1x1 = nn.Conv2D(dim_in, dim_out, 1, 1, 0, bias_attr=False)

    def _shortcut(self, x):
        if self.learned_sc:
            x = self.conv1x1(x)
        if self.downsample:
W
wangna11BD 已提交
51
            x = self.maxpool(x)
52 53 54 55 56 57 58 59
        return x

    def _residual(self, x):
        if self.normalize:
            x = self.norm1(x)
        x = self.actv(x)
        x = self.conv1(x)
        if self.downsample:
W
wangna11BD 已提交
60
            x = self.maxpool(x)
61 62 63 64 65 66 67 68 69 70 71 72 73 74
        if self.normalize:
            x = self.norm2(x)
        x = self.actv(x)
        x = self.conv2(x)
        return x

    def forward(self, x):
        x = self._shortcut(x) + self._residual(x)
        return x / math.sqrt(2)  # unit variance


class AdaIN(nn.Layer):
    def __init__(self, style_dim, num_features):
        super().__init__()
W
wangna11BD 已提交
75 76 77 78
        self.norm = nn.InstanceNorm2D(num_features,
                                      weight_attr=False,
                                      bias_attr=False)
        self.fc = nn.Linear(style_dim, num_features * 2)
79 80 81 82 83 84 85 86 87 88

    def forward(self, x, s):
        h = self.fc(s)
        # h = h.view(h.size(0), h.size(1), 1, 1)
        h = paddle.reshape(h, (h.shape[0], h.shape[1], 1, 1))
        gamma, beta = paddle.chunk(h, chunks=2, axis=1)
        return (1 + gamma) * self.norm(x) + beta


class AdainResBlk(nn.Layer):
W
wangna11BD 已提交
89 90 91 92 93 94 95
    def __init__(self,
                 dim_in,
                 dim_out,
                 style_dim=64,
                 w_hpf=0,
                 actv=nn.LeakyReLU(0.2),
                 upsample=False):
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
        super().__init__()
        self.w_hpf = w_hpf
        self.actv = actv
        self.upsample = upsample
        self.learned_sc = dim_in != dim_out
        self._build_weights(dim_in, dim_out, style_dim)

    def _build_weights(self, dim_in, dim_out, style_dim=64):
        self.conv1 = nn.Conv2D(dim_in, dim_out, 3, 1, 1)
        self.conv2 = nn.Conv2D(dim_out, dim_out, 3, 1, 1)
        self.norm1 = AdaIN(style_dim, dim_in)
        self.norm2 = AdaIN(style_dim, dim_out)
        if self.learned_sc:
            self.conv1x1 = nn.Conv2D(dim_in, dim_out, 1, 1, 0, bias_attr=False)

    def _shortcut(self, x):
        if self.upsample:
            x = F.interpolate(x, scale_factor=2, mode='nearest')
        if self.learned_sc:
            x = self.conv1x1(x)
        return x

    def _residual(self, x, s):
        x = self.norm1(x, s)
        x = self.actv(x)
        if self.upsample:
            x = F.interpolate(x, scale_factor=2, mode='nearest')
        x = self.conv1(x)
        x = self.norm2(x, s)
        x = self.actv(x)
        x = self.conv2(x)
        return x

    def forward(self, x, s):
        out = self._residual(x, s)
        if self.w_hpf == 0:
            out = (out + self._shortcut(x)) / math.sqrt(2)
        return out


class HighPass(nn.Layer):
    def __init__(self, w_hpf):
        super(HighPass, self).__init__()
W
wangna11BD 已提交
139 140
        self.filter = paddle.to_tensor([[-1, -1, -1], [-1, 8., -1],
                                        [-1, -1, -1]]) / w_hpf
141 142 143

    def forward(self, x):
        # filter = self.filter.unsqueeze(0).unsqueeze(1).repeat(x.size(1), 1, 1, 1)
W
wangna11BD 已提交
144 145
        filter = self.filter.unsqueeze(0).unsqueeze(1).tile(
            [x.shape[1], 1, 1, 1])
146 147 148 149 150 151 152 153 154 155 156 157 158 159
        return F.conv2d(x, filter, padding=1, groups=x.shape[1])


@GENERATORS.register()
class StarGANv2Generator(nn.Layer):
    def __init__(self, img_size=256, style_dim=64, max_conv_dim=512, w_hpf=1):
        super().__init__()
        dim_in = 2**14 // img_size
        self.img_size = img_size
        self.from_rgb = nn.Conv2D(3, dim_in, 3, 1, 1)
        self.encode = nn.LayerList()
        self.decode = nn.LayerList()
        self.to_rgb = nn.Sequential(
            nn.InstanceNorm2D(dim_in, weight_attr=True, bias_attr=True),
W
wangna11BD 已提交
160
            nn.LeakyReLU(0.2), nn.Conv2D(dim_in, 3, 1, 1, 0))
161 162 163 164 165 166

        # down/up-sampling blocks
        repeat_num = int(np.log2(img_size)) - 4
        if w_hpf > 0:
            repeat_num += 1
        for _ in range(repeat_num):
W
wangna11BD 已提交
167
            dim_out = min(dim_in * 2, max_conv_dim)
168 169 170
            self.encode.append(
                ResBlk(dim_in, dim_out, normalize=True, downsample=True))
            if len(self.decode) == 0:
W
wangna11BD 已提交
171 172 173 174 175 176
                self.decode.append(
                    AdainResBlk(dim_out,
                                dim_in,
                                style_dim,
                                w_hpf=w_hpf,
                                upsample=True))
177
            else:
W
wangna11BD 已提交
178 179 180 181 182 183
                self.decode.insert(0,
                                   AdainResBlk(dim_out,
                                               dim_in,
                                               style_dim,
                                               w_hpf=w_hpf,
                                               upsample=True))  # stack-like
184 185 186 187
            dim_in = dim_out

        # bottleneck blocks
        for _ in range(2):
W
wangna11BD 已提交
188
            self.encode.append(ResBlk(dim_out, dim_out, normalize=True))
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            self.decode.insert(
                0, AdainResBlk(dim_out, dim_out, style_dim, w_hpf=w_hpf))

        if w_hpf > 0:
            self.hpf = HighPass(w_hpf)

    def forward(self, x, s, masks=None):
        x = self.from_rgb(x)
        cache = {}
        for block in self.encode:
            if (masks is not None) and (x.shape[2] in [32, 64, 128]):
                cache[x.shape[2]] = x
            x = block(x)
        for block in self.decode:
            x = block(x, s)
            if (masks is not None) and (x.shape[2] in [32, 64, 128]):
                mask = masks[0] if x.shape[2] in [32] else masks[1]
W
wangna11BD 已提交
206 207 208
                mask = F.interpolate(mask,
                                     size=[x.shape[2], x.shape[2]],
                                     mode='bilinear')
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
                x = x + self.hpf(mask * cache[x.shape[2]])
        return self.to_rgb(x)


@GENERATORS.register()
class StarGANv2Mapping(nn.Layer):
    def __init__(self, latent_dim=16, style_dim=64, num_domains=2):
        super().__init__()
        layers = []
        layers += [nn.Linear(latent_dim, 512)]
        layers += [nn.ReLU()]
        for _ in range(3):
            layers += [nn.Linear(512, 512)]
            layers += [nn.ReLU()]
        self.shared = nn.Sequential(*layers)

        self.unshared = nn.LayerList()
        for _ in range(num_domains):
W
wangna11BD 已提交
227 228 229 230 231
            self.unshared.append(
                nn.Sequential(nn.Linear(512, 512),
                              nn.ReLU(), nn.Linear(512, 512), nn.ReLU(),
                              nn.Linear(512, 512), nn.ReLU(),
                              nn.Linear(512, style_dim)))
232 233 234 235 236 237 238 239 240 241

    def forward(self, z, y):
        h = self.shared(z)
        out = []
        for layer in self.unshared:
            out += [layer(h)]
        out = paddle.stack(out, axis=1)  # (batch, num_domains, style_dim)
        idx = paddle.to_tensor(np.array(range(y.shape[0]))).astype('int')
        s = []
        for i in range(idx.shape[0]):
W
wangna11BD 已提交
242 243 244 245
            s += [
                out[idx[i].numpy().astype(np.int).tolist()[0],
                    y[i].numpy().astype(np.int).tolist()[0]]
            ]
246 247 248 249 250 251 252
        s = paddle.stack(s)
        s = paddle.reshape(s, (s.shape[0], -1))
        return s


@GENERATORS.register()
class StarGANv2Style(nn.Layer):
W
wangna11BD 已提交
253 254 255 256 257
    def __init__(self,
                 img_size=256,
                 style_dim=64,
                 num_domains=2,
                 max_conv_dim=512):
258 259 260 261 262 263 264
        super().__init__()
        dim_in = 2**14 // img_size
        blocks = []
        blocks += [nn.Conv2D(3, dim_in, 3, 1, 1)]

        repeat_num = int(np.log2(img_size)) - 2
        for _ in range(repeat_num):
W
wangna11BD 已提交
265
            dim_out = min(dim_in * 2, max_conv_dim)
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            blocks += [ResBlk(dim_in, dim_out, downsample=True)]
            dim_in = dim_out

        blocks += [nn.LeakyReLU(0.2)]
        blocks += [nn.Conv2D(dim_out, dim_out, 4, 1, 0)]
        blocks += [nn.LeakyReLU(0.2)]
        self.shared = nn.Sequential(*blocks)

        self.unshared = nn.LayerList()
        for _ in range(num_domains):
            self.unshared.append(nn.Linear(dim_out, style_dim))

    def forward(self, x, y):
        h = self.shared(x)
        h = paddle.reshape(h, (h.shape[0], -1))
        out = []
        for layer in self.unshared:
            out += [layer(h)]
        out = paddle.stack(out, axis=1)  # (batch, num_domains, style_dim)
        idx = paddle.to_tensor(np.array(range(y.shape[0]))).astype('int')
        s = []
        for i in range(idx.shape[0]):
W
wangna11BD 已提交
288 289 290 291
            s += [
                out[idx[i].numpy().astype(np.int).tolist()[0],
                    y[i].numpy().astype(np.int).tolist()[0]]
            ]
292 293 294 295 296 297 298
        s = paddle.stack(s)
        s = paddle.reshape(s, (s.shape[0], -1))
        return s


@GENERATORS.register()
class FAN(nn.Layer):
W
wangna11BD 已提交
299 300 301 302 303
    def __init__(self,
                 num_modules=1,
                 end_relu=False,
                 num_landmarks=98,
                 fname_pretrained=None):
304 305 306 307 308
        super(FAN, self).__init__()
        self.num_modules = num_modules
        self.end_relu = end_relu

        # Base part
W
wangna11BD 已提交
309 310 311 312 313 314 315 316 317
        self.conv1 = CoordConvTh(256,
                                 256,
                                 True,
                                 False,
                                 in_channels=3,
                                 out_channels=64,
                                 kernel_size=7,
                                 stride=2,
                                 padding=3)
318 319 320 321 322 323 324 325 326 327
        self.bn1 = nn.BatchNorm2D(64)
        self.conv2 = ConvBlock(64, 128)
        self.conv3 = ConvBlock(128, 128)
        self.conv4 = ConvBlock(128, 256)

        # Stacking part
        self.add_sublayer('m0', HourGlass(1, 4, 256, first_one=True))
        self.add_sublayer('top_m_0', ConvBlock(256, 256))
        self.add_sublayer('conv_last0', nn.Conv2D(256, 256, 1, 1, 0))
        self.add_sublayer('bn_end0', nn.BatchNorm2D(256))
W
wangna11BD 已提交
328
        self.add_sublayer('l0', nn.Conv2D(256, num_landmarks + 1, 1, 1, 0))
329 330 331

        if fname_pretrained is not None:
            self.load_pretrained_weights(fname_pretrained)
L
lzzyzlbb 已提交
332 333 334
        else:
            weight_path = get_path_from_url(FAN_WEIGHT_URL)
            self.load_pretrained_weights(weight_path)
335 336 337 338 339 340 341 342

    def load_pretrained_weights(self, fname):
        import pickle
        import six

        with open(fname, 'rb') as f:
            checkpoint = pickle.load(f) if six.PY2 else pickle.load(
                f, encoding='latin1')
W
wangna11BD 已提交
343

344
        model_weights = self.state_dict()
W
wangna11BD 已提交
345 346 347 348
        model_weights.update({
            k: v
            for k, v in checkpoint['state_dict'].items() if k in model_weights
        })
349 350 351 352 353 354 355 356 357 358 359 360 361 362
        self.set_state_dict(model_weights)

    def forward(self, x):
        x, _ = self.conv1(x)
        x = F.relu(self.bn1(x), True)
        x = F.avg_pool2d(self.conv2(x), 2, stride=2)
        x = self.conv3(x)
        x = self.conv4(x)

        outputs = []
        boundary_channels = []
        tmp_out = None
        ll, boundary_channel = self._sub_layers['m0'](x, tmp_out)
        ll = self._sub_layers['top_m_0'](ll)
W
wangna11BD 已提交
363 364 365
        ll = F.relu(
            self._sub_layers['bn_end0'](self._sub_layers['conv_last0'](ll)),
            True)
366 367 368 369 370 371 372 373 374 375 376 377 378

        # Predict heatmaps
        tmp_out = self._sub_layers['l0'](ll)
        if self.end_relu:
            tmp_out = F.relu(tmp_out)  # HACK: Added relu
        outputs.append(tmp_out)
        boundary_channels.append(boundary_channel)
        return outputs, boundary_channels

    @paddle.no_grad()
    def get_heatmap(self, x, b_preprocess=True):
        ''' outputs 0-1 normalized heatmap '''
        x = F.interpolate(x, size=[256, 256], mode='bilinear')
W
wangna11BD 已提交
379
        x_01 = x * 0.5 + 0.5
380 381 382 383
        outputs, _ = self(x_01)
        heatmaps = outputs[-1][:, :-1, :, :]
        scale_factor = x.shape[2] // heatmaps.shape[2]
        if b_preprocess:
W
wangna11BD 已提交
384 385 386 387
            heatmaps = F.interpolate(heatmaps,
                                     scale_factor=scale_factor,
                                     mode='bilinear',
                                     align_corners=True)
388 389
            heatmaps = preprocess(heatmaps)
        return heatmaps