GFPGAN

Форк
0
/
stylegan2_bilinear_arch.py 
613 строк · 21.8 Кб
1
import math
2
import random
3
import torch
4
from basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu
5
from basicsr.utils.registry import ARCH_REGISTRY
6
from torch import nn
7
from torch.nn import functional as F
8

9

10
class NormStyleCode(nn.Module):
11

12
    def forward(self, x):
13
        """Normalize the style codes.
14

15
        Args:
16
            x (Tensor): Style codes with shape (b, c).
17

18
        Returns:
19
            Tensor: Normalized tensor.
20
        """
21
        return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8)
22

23

24
class EqualLinear(nn.Module):
25
    """Equalized Linear as StyleGAN2.
26

27
    Args:
28
        in_channels (int): Size of each sample.
29
        out_channels (int): Size of each output sample.
30
        bias (bool): If set to ``False``, the layer will not learn an additive
31
            bias. Default: ``True``.
32
        bias_init_val (float): Bias initialized value. Default: 0.
33
        lr_mul (float): Learning rate multiplier. Default: 1.
34
        activation (None | str): The activation after ``linear`` operation.
35
            Supported: 'fused_lrelu', None. Default: None.
36
    """
37

38
    def __init__(self, in_channels, out_channels, bias=True, bias_init_val=0, lr_mul=1, activation=None):
39
        super(EqualLinear, self).__init__()
40
        self.in_channels = in_channels
41
        self.out_channels = out_channels
42
        self.lr_mul = lr_mul
43
        self.activation = activation
44
        if self.activation not in ['fused_lrelu', None]:
45
            raise ValueError(f'Wrong activation value in EqualLinear: {activation}'
46
                             "Supported ones are: ['fused_lrelu', None].")
47
        self.scale = (1 / math.sqrt(in_channels)) * lr_mul
48

49
        self.weight = nn.Parameter(torch.randn(out_channels, in_channels).div_(lr_mul))
50
        if bias:
51
            self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
52
        else:
53
            self.register_parameter('bias', None)
54

55
    def forward(self, x):
56
        if self.bias is None:
57
            bias = None
58
        else:
59
            bias = self.bias * self.lr_mul
60
        if self.activation == 'fused_lrelu':
61
            out = F.linear(x, self.weight * self.scale)
62
            out = fused_leaky_relu(out, bias)
63
        else:
64
            out = F.linear(x, self.weight * self.scale, bias=bias)
65
        return out
66

67
    def __repr__(self):
68
        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '
69
                f'out_channels={self.out_channels}, bias={self.bias is not None})')
70

71

72
class ModulatedConv2d(nn.Module):
73
    """Modulated Conv2d used in StyleGAN2.
74

75
    There is no bias in ModulatedConv2d.
76

77
    Args:
78
        in_channels (int): Channel number of the input.
79
        out_channels (int): Channel number of the output.
80
        kernel_size (int): Size of the convolving kernel.
81
        num_style_feat (int): Channel number of style features.
82
        demodulate (bool): Whether to demodulate in the conv layer.
83
            Default: True.
84
        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.
85
            Default: None.
86
        eps (float): A value added to the denominator for numerical stability.
87
            Default: 1e-8.
88
    """
89

90
    def __init__(self,
91
                 in_channels,
92
                 out_channels,
93
                 kernel_size,
94
                 num_style_feat,
95
                 demodulate=True,
96
                 sample_mode=None,
97
                 eps=1e-8,
98
                 interpolation_mode='bilinear'):
99
        super(ModulatedConv2d, self).__init__()
100
        self.in_channels = in_channels
101
        self.out_channels = out_channels
102
        self.kernel_size = kernel_size
103
        self.demodulate = demodulate
104
        self.sample_mode = sample_mode
105
        self.eps = eps
106
        self.interpolation_mode = interpolation_mode
107
        if self.interpolation_mode == 'nearest':
108
            self.align_corners = None
109
        else:
110
            self.align_corners = False
111

112
        self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
113
        # modulation inside each modulated conv
114
        self.modulation = EqualLinear(
115
            num_style_feat, in_channels, bias=True, bias_init_val=1, lr_mul=1, activation=None)
116

117
        self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size))
118
        self.padding = kernel_size // 2
119

120
    def forward(self, x, style):
121
        """Forward function.
122

123
        Args:
124
            x (Tensor): Tensor with shape (b, c, h, w).
125
            style (Tensor): Tensor with shape (b, num_style_feat).
126

127
        Returns:
128
            Tensor: Modulated tensor after convolution.
129
        """
130
        b, c, h, w = x.shape  # c = c_in
131
        # weight modulation
132
        style = self.modulation(style).view(b, 1, c, 1, 1)
133
        # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1)
134
        weight = self.scale * self.weight * style  # (b, c_out, c_in, k, k)
135

136
        if self.demodulate:
137
            demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps)
138
            weight = weight * demod.view(b, self.out_channels, 1, 1, 1)
139

140
        weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size)
141

142
        if self.sample_mode == 'upsample':
143
            x = F.interpolate(x, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners)
144
        elif self.sample_mode == 'downsample':
145
            x = F.interpolate(x, scale_factor=0.5, mode=self.interpolation_mode, align_corners=self.align_corners)
146

147
        b, c, h, w = x.shape
148
        x = x.view(1, b * c, h, w)
149
        # weight: (b*c_out, c_in, k, k), groups=b
150
        out = F.conv2d(x, weight, padding=self.padding, groups=b)
151
        out = out.view(b, self.out_channels, *out.shape[2:4])
152

153
        return out
154

155
    def __repr__(self):
156
        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '
157
                f'out_channels={self.out_channels}, '
158
                f'kernel_size={self.kernel_size}, '
159
                f'demodulate={self.demodulate}, sample_mode={self.sample_mode})')
160

161

162
class StyleConv(nn.Module):
163
    """Style conv.
164

165
    Args:
166
        in_channels (int): Channel number of the input.
167
        out_channels (int): Channel number of the output.
168
        kernel_size (int): Size of the convolving kernel.
169
        num_style_feat (int): Channel number of style features.
170
        demodulate (bool): Whether demodulate in the conv layer. Default: True.
171
        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.
172
            Default: None.
173
    """
174

175
    def __init__(self,
176
                 in_channels,
177
                 out_channels,
178
                 kernel_size,
179
                 num_style_feat,
180
                 demodulate=True,
181
                 sample_mode=None,
182
                 interpolation_mode='bilinear'):
183
        super(StyleConv, self).__init__()
184
        self.modulated_conv = ModulatedConv2d(
185
            in_channels,
186
            out_channels,
187
            kernel_size,
188
            num_style_feat,
189
            demodulate=demodulate,
190
            sample_mode=sample_mode,
191
            interpolation_mode=interpolation_mode)
192
        self.weight = nn.Parameter(torch.zeros(1))  # for noise injection
193
        self.activate = FusedLeakyReLU(out_channels)
194

195
    def forward(self, x, style, noise=None):
196
        # modulate
197
        out = self.modulated_conv(x, style)
198
        # noise injection
199
        if noise is None:
200
            b, _, h, w = out.shape
201
            noise = out.new_empty(b, 1, h, w).normal_()
202
        out = out + self.weight * noise
203
        # activation (with bias)
204
        out = self.activate(out)
205
        return out
206

207

208
class ToRGB(nn.Module):
209
    """To RGB from features.
210

211
    Args:
212
        in_channels (int): Channel number of input.
213
        num_style_feat (int): Channel number of style features.
214
        upsample (bool): Whether to upsample. Default: True.
215
    """
216

217
    def __init__(self, in_channels, num_style_feat, upsample=True, interpolation_mode='bilinear'):
218
        super(ToRGB, self).__init__()
219
        self.upsample = upsample
220
        self.interpolation_mode = interpolation_mode
221
        if self.interpolation_mode == 'nearest':
222
            self.align_corners = None
223
        else:
224
            self.align_corners = False
225
        self.modulated_conv = ModulatedConv2d(
226
            in_channels,
227
            3,
228
            kernel_size=1,
229
            num_style_feat=num_style_feat,
230
            demodulate=False,
231
            sample_mode=None,
232
            interpolation_mode=interpolation_mode)
233
        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
234

235
    def forward(self, x, style, skip=None):
236
        """Forward function.
237

238
        Args:
239
            x (Tensor): Feature tensor with shape (b, c, h, w).
240
            style (Tensor): Tensor with shape (b, num_style_feat).
241
            skip (Tensor): Base/skip tensor. Default: None.
242

243
        Returns:
244
            Tensor: RGB images.
245
        """
246
        out = self.modulated_conv(x, style)
247
        out = out + self.bias
248
        if skip is not None:
249
            if self.upsample:
250
                skip = F.interpolate(
251
                    skip, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners)
252
            out = out + skip
253
        return out
254

255

256
class ConstantInput(nn.Module):
257
    """Constant input.
258

259
    Args:
260
        num_channel (int): Channel number of constant input.
261
        size (int): Spatial size of constant input.
262
    """
263

264
    def __init__(self, num_channel, size):
265
        super(ConstantInput, self).__init__()
266
        self.weight = nn.Parameter(torch.randn(1, num_channel, size, size))
267

268
    def forward(self, batch):
269
        out = self.weight.repeat(batch, 1, 1, 1)
270
        return out
271

272

273
@ARCH_REGISTRY.register()
274
class StyleGAN2GeneratorBilinear(nn.Module):
275
    """StyleGAN2 Generator.
276

277
    Args:
278
        out_size (int): The spatial size of outputs.
279
        num_style_feat (int): Channel number of style features. Default: 512.
280
        num_mlp (int): Layer number of MLP style layers. Default: 8.
281
        channel_multiplier (int): Channel multiplier for large networks of
282
            StyleGAN2. Default: 2.
283
        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.
284
        narrow (float): Narrow ratio for channels. Default: 1.0.
285
    """
286

287
    def __init__(self,
288
                 out_size,
289
                 num_style_feat=512,
290
                 num_mlp=8,
291
                 channel_multiplier=2,
292
                 lr_mlp=0.01,
293
                 narrow=1,
294
                 interpolation_mode='bilinear'):
295
        super(StyleGAN2GeneratorBilinear, self).__init__()
296
        # Style MLP layers
297
        self.num_style_feat = num_style_feat
298
        style_mlp_layers = [NormStyleCode()]
299
        for i in range(num_mlp):
300
            style_mlp_layers.append(
301
                EqualLinear(
302
                    num_style_feat, num_style_feat, bias=True, bias_init_val=0, lr_mul=lr_mlp,
303
                    activation='fused_lrelu'))
304
        self.style_mlp = nn.Sequential(*style_mlp_layers)
305

306
        channels = {
307
            '4': int(512 * narrow),
308
            '8': int(512 * narrow),
309
            '16': int(512 * narrow),
310
            '32': int(512 * narrow),
311
            '64': int(256 * channel_multiplier * narrow),
312
            '128': int(128 * channel_multiplier * narrow),
313
            '256': int(64 * channel_multiplier * narrow),
314
            '512': int(32 * channel_multiplier * narrow),
315
            '1024': int(16 * channel_multiplier * narrow)
316
        }
317
        self.channels = channels
318

319
        self.constant_input = ConstantInput(channels['4'], size=4)
320
        self.style_conv1 = StyleConv(
321
            channels['4'],
322
            channels['4'],
323
            kernel_size=3,
324
            num_style_feat=num_style_feat,
325
            demodulate=True,
326
            sample_mode=None,
327
            interpolation_mode=interpolation_mode)
328
        self.to_rgb1 = ToRGB(channels['4'], num_style_feat, upsample=False, interpolation_mode=interpolation_mode)
329

330
        self.log_size = int(math.log(out_size, 2))
331
        self.num_layers = (self.log_size - 2) * 2 + 1
332
        self.num_latent = self.log_size * 2 - 2
333

334
        self.style_convs = nn.ModuleList()
335
        self.to_rgbs = nn.ModuleList()
336
        self.noises = nn.Module()
337

338
        in_channels = channels['4']
339
        # noise
340
        for layer_idx in range(self.num_layers):
341
            resolution = 2**((layer_idx + 5) // 2)
342
            shape = [1, 1, resolution, resolution]
343
            self.noises.register_buffer(f'noise{layer_idx}', torch.randn(*shape))
344
        # style convs and to_rgbs
345
        for i in range(3, self.log_size + 1):
346
            out_channels = channels[f'{2**i}']
347
            self.style_convs.append(
348
                StyleConv(
349
                    in_channels,
350
                    out_channels,
351
                    kernel_size=3,
352
                    num_style_feat=num_style_feat,
353
                    demodulate=True,
354
                    sample_mode='upsample',
355
                    interpolation_mode=interpolation_mode))
356
            self.style_convs.append(
357
                StyleConv(
358
                    out_channels,
359
                    out_channels,
360
                    kernel_size=3,
361
                    num_style_feat=num_style_feat,
362
                    demodulate=True,
363
                    sample_mode=None,
364
                    interpolation_mode=interpolation_mode))
365
            self.to_rgbs.append(
366
                ToRGB(out_channels, num_style_feat, upsample=True, interpolation_mode=interpolation_mode))
367
            in_channels = out_channels
368

369
    def make_noise(self):
370
        """Make noise for noise injection."""
371
        device = self.constant_input.weight.device
372
        noises = [torch.randn(1, 1, 4, 4, device=device)]
373

374
        for i in range(3, self.log_size + 1):
375
            for _ in range(2):
376
                noises.append(torch.randn(1, 1, 2**i, 2**i, device=device))
377

378
        return noises
379

380
    def get_latent(self, x):
381
        return self.style_mlp(x)
382

383
    def mean_latent(self, num_latent):
384
        latent_in = torch.randn(num_latent, self.num_style_feat, device=self.constant_input.weight.device)
385
        latent = self.style_mlp(latent_in).mean(0, keepdim=True)
386
        return latent
387

388
    def forward(self,
389
                styles,
390
                input_is_latent=False,
391
                noise=None,
392
                randomize_noise=True,
393
                truncation=1,
394
                truncation_latent=None,
395
                inject_index=None,
396
                return_latents=False):
397
        """Forward function for StyleGAN2Generator.
398

399
        Args:
400
            styles (list[Tensor]): Sample codes of styles.
401
            input_is_latent (bool): Whether input is latent style.
402
                Default: False.
403
            noise (Tensor | None): Input noise or None. Default: None.
404
            randomize_noise (bool): Randomize noise, used when 'noise' is
405
                False. Default: True.
406
            truncation (float): TODO. Default: 1.
407
            truncation_latent (Tensor | None): TODO. Default: None.
408
            inject_index (int | None): The injection index for mixing noise.
409
                Default: None.
410
            return_latents (bool): Whether to return style latents.
411
                Default: False.
412
        """
413
        # style codes -> latents with Style MLP layer
414
        if not input_is_latent:
415
            styles = [self.style_mlp(s) for s in styles]
416
        # noises
417
        if noise is None:
418
            if randomize_noise:
419
                noise = [None] * self.num_layers  # for each style conv layer
420
            else:  # use the stored noise
421
                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]
422
        # style truncation
423
        if truncation < 1:
424
            style_truncation = []
425
            for style in styles:
426
                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))
427
            styles = style_truncation
428
        # get style latent with injection
429
        if len(styles) == 1:
430
            inject_index = self.num_latent
431

432
            if styles[0].ndim < 3:
433
                # repeat latent code for all the layers
434
                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
435
            else:  # used for encoder with different latent code for each layer
436
                latent = styles[0]
437
        elif len(styles) == 2:  # mixing noises
438
            if inject_index is None:
439
                inject_index = random.randint(1, self.num_latent - 1)
440
            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
441
            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)
442
            latent = torch.cat([latent1, latent2], 1)
443

444
        # main generation
445
        out = self.constant_input(latent.shape[0])
446
        out = self.style_conv1(out, latent[:, 0], noise=noise[0])
447
        skip = self.to_rgb1(out, latent[:, 1])
448

449
        i = 1
450
        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],
451
                                                        noise[2::2], self.to_rgbs):
452
            out = conv1(out, latent[:, i], noise=noise1)
453
            out = conv2(out, latent[:, i + 1], noise=noise2)
454
            skip = to_rgb(out, latent[:, i + 2], skip)
455
            i += 2
456

457
        image = skip
458

459
        if return_latents:
460
            return image, latent
461
        else:
462
            return image, None
463

464

465
class ScaledLeakyReLU(nn.Module):
466
    """Scaled LeakyReLU.
467

468
    Args:
469
        negative_slope (float): Negative slope. Default: 0.2.
470
    """
471

472
    def __init__(self, negative_slope=0.2):
473
        super(ScaledLeakyReLU, self).__init__()
474
        self.negative_slope = negative_slope
475

476
    def forward(self, x):
477
        out = F.leaky_relu(x, negative_slope=self.negative_slope)
478
        return out * math.sqrt(2)
479

480

481
class EqualConv2d(nn.Module):
482
    """Equalized Linear as StyleGAN2.
483

484
    Args:
485
        in_channels (int): Channel number of the input.
486
        out_channels (int): Channel number of the output.
487
        kernel_size (int): Size of the convolving kernel.
488
        stride (int): Stride of the convolution. Default: 1
489
        padding (int): Zero-padding added to both sides of the input.
490
            Default: 0.
491
        bias (bool): If ``True``, adds a learnable bias to the output.
492
            Default: ``True``.
493
        bias_init_val (float): Bias initialized value. Default: 0.
494
    """
495

496
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, bias_init_val=0):
497
        super(EqualConv2d, self).__init__()
498
        self.in_channels = in_channels
499
        self.out_channels = out_channels
500
        self.kernel_size = kernel_size
501
        self.stride = stride
502
        self.padding = padding
503
        self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
504

505
        self.weight = nn.Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size))
506
        if bias:
507
            self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
508
        else:
509
            self.register_parameter('bias', None)
510

511
    def forward(self, x):
512
        out = F.conv2d(
513
            x,
514
            self.weight * self.scale,
515
            bias=self.bias,
516
            stride=self.stride,
517
            padding=self.padding,
518
        )
519

520
        return out
521

522
    def __repr__(self):
523
        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '
524
                f'out_channels={self.out_channels}, '
525
                f'kernel_size={self.kernel_size},'
526
                f' stride={self.stride}, padding={self.padding}, '
527
                f'bias={self.bias is not None})')
528

529

530
class ConvLayer(nn.Sequential):
531
    """Conv Layer used in StyleGAN2 Discriminator.
532

533
    Args:
534
        in_channels (int): Channel number of the input.
535
        out_channels (int): Channel number of the output.
536
        kernel_size (int): Kernel size.
537
        downsample (bool): Whether downsample by a factor of 2.
538
            Default: False.
539
        bias (bool): Whether with bias. Default: True.
540
        activate (bool): Whether use activateion. Default: True.
541
    """
542

543
    def __init__(self,
544
                 in_channels,
545
                 out_channels,
546
                 kernel_size,
547
                 downsample=False,
548
                 bias=True,
549
                 activate=True,
550
                 interpolation_mode='bilinear'):
551
        layers = []
552
        self.interpolation_mode = interpolation_mode
553
        # downsample
554
        if downsample:
555
            if self.interpolation_mode == 'nearest':
556
                self.align_corners = None
557
            else:
558
                self.align_corners = False
559

560
            layers.append(
561
                torch.nn.Upsample(scale_factor=0.5, mode=interpolation_mode, align_corners=self.align_corners))
562
        stride = 1
563
        self.padding = kernel_size // 2
564
        # conv
565
        layers.append(
566
            EqualConv2d(
567
                in_channels, out_channels, kernel_size, stride=stride, padding=self.padding, bias=bias
568
                and not activate))
569
        # activation
570
        if activate:
571
            if bias:
572
                layers.append(FusedLeakyReLU(out_channels))
573
            else:
574
                layers.append(ScaledLeakyReLU(0.2))
575

576
        super(ConvLayer, self).__init__(*layers)
577

578

579
class ResBlock(nn.Module):
580
    """Residual block used in StyleGAN2 Discriminator.
581

582
    Args:
583
        in_channels (int): Channel number of the input.
584
        out_channels (int): Channel number of the output.
585
    """
586

587
    def __init__(self, in_channels, out_channels, interpolation_mode='bilinear'):
588
        super(ResBlock, self).__init__()
589

590
        self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True)
591
        self.conv2 = ConvLayer(
592
            in_channels,
593
            out_channels,
594
            3,
595
            downsample=True,
596
            interpolation_mode=interpolation_mode,
597
            bias=True,
598
            activate=True)
599
        self.skip = ConvLayer(
600
            in_channels,
601
            out_channels,
602
            1,
603
            downsample=True,
604
            interpolation_mode=interpolation_mode,
605
            bias=False,
606
            activate=False)
607

608
    def forward(self, x):
609
        out = self.conv1(x)
610
        out = self.conv2(out)
611
        skip = self.skip(x)
612
        out = (out + skip) / math.sqrt(2)
613
        return out
614

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.