4
from basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu
5
from basicsr.utils.registry import ARCH_REGISTRY
7
from torch.nn import functional as F
10
class NormStyleCode(nn.Module):
13
"""Normalize the style codes.
16
x (Tensor): Style codes with shape (b, c).
19
Tensor: Normalized tensor.
21
return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8)
24
class EqualLinear(nn.Module):
25
"""Equalized Linear as StyleGAN2.
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.
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
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
49
self.weight = nn.Parameter(torch.randn(out_channels, in_channels).div_(lr_mul))
51
self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
53
self.register_parameter('bias', None)
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)
64
out = F.linear(x, self.weight * self.scale, bias=bias)
68
return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '
69
f'out_channels={self.out_channels}, bias={self.bias is not None})')
72
class ModulatedConv2d(nn.Module):
73
"""Modulated Conv2d used in StyleGAN2.
75
There is no bias in ModulatedConv2d.
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.
84
sample_mode (str | None): Indicating 'upsample', 'downsample' or None.
86
eps (float): A value added to the denominator for numerical stability.
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
106
self.interpolation_mode = interpolation_mode
107
if self.interpolation_mode == 'nearest':
108
self.align_corners = None
110
self.align_corners = False
112
self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
114
self.modulation = EqualLinear(
115
num_style_feat, in_channels, bias=True, bias_init_val=1, lr_mul=1, activation=None)
117
self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size))
118
self.padding = kernel_size // 2
120
def forward(self, x, style):
124
x (Tensor): Tensor with shape (b, c, h, w).
125
style (Tensor): Tensor with shape (b, num_style_feat).
128
Tensor: Modulated tensor after convolution.
132
style = self.modulation(style).view(b, 1, c, 1, 1)
134
weight = self.scale * self.weight * style
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)
140
weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size)
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)
148
x = x.view(1, b * c, h, w)
150
out = F.conv2d(x, weight, padding=self.padding, groups=b)
151
out = out.view(b, self.out_channels, *out.shape[2:4])
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})')
162
class StyleConv(nn.Module):
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.
182
interpolation_mode='bilinear'):
183
super(StyleConv, self).__init__()
184
self.modulated_conv = ModulatedConv2d(
189
demodulate=demodulate,
190
sample_mode=sample_mode,
191
interpolation_mode=interpolation_mode)
192
self.weight = nn.Parameter(torch.zeros(1))
193
self.activate = FusedLeakyReLU(out_channels)
195
def forward(self, x, style, noise=None):
197
out = self.modulated_conv(x, style)
200
b, _, h, w = out.shape
201
noise = out.new_empty(b, 1, h, w).normal_()
202
out = out + self.weight * noise
204
out = self.activate(out)
208
class ToRGB(nn.Module):
209
"""To RGB from features.
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.
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
224
self.align_corners = False
225
self.modulated_conv = ModulatedConv2d(
229
num_style_feat=num_style_feat,
232
interpolation_mode=interpolation_mode)
233
self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
235
def forward(self, x, style, skip=None):
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.
246
out = self.modulated_conv(x, style)
247
out = out + self.bias
250
skip = F.interpolate(
251
skip, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners)
256
class ConstantInput(nn.Module):
260
num_channel (int): Channel number of constant input.
261
size (int): Spatial size of constant input.
264
def __init__(self, num_channel, size):
265
super(ConstantInput, self).__init__()
266
self.weight = nn.Parameter(torch.randn(1, num_channel, size, size))
268
def forward(self, batch):
269
out = self.weight.repeat(batch, 1, 1, 1)
273
@ARCH_REGISTRY.register()
274
class StyleGAN2GeneratorBilinear(nn.Module):
275
"""StyleGAN2 Generator.
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.
291
channel_multiplier=2,
294
interpolation_mode='bilinear'):
295
super(StyleGAN2GeneratorBilinear, self).__init__()
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(
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)
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)
317
self.channels = channels
319
self.constant_input = ConstantInput(channels['4'], size=4)
320
self.style_conv1 = StyleConv(
324
num_style_feat=num_style_feat,
327
interpolation_mode=interpolation_mode)
328
self.to_rgb1 = ToRGB(channels['4'], num_style_feat, upsample=False, interpolation_mode=interpolation_mode)
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
334
self.style_convs = nn.ModuleList()
335
self.to_rgbs = nn.ModuleList()
336
self.noises = nn.Module()
338
in_channels = channels['4']
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))
345
for i in range(3, self.log_size + 1):
346
out_channels = channels[f'{2**i}']
347
self.style_convs.append(
352
num_style_feat=num_style_feat,
354
sample_mode='upsample',
355
interpolation_mode=interpolation_mode))
356
self.style_convs.append(
361
num_style_feat=num_style_feat,
364
interpolation_mode=interpolation_mode))
366
ToRGB(out_channels, num_style_feat, upsample=True, interpolation_mode=interpolation_mode))
367
in_channels = out_channels
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)]
374
for i in range(3, self.log_size + 1):
376
noises.append(torch.randn(1, 1, 2**i, 2**i, device=device))
380
def get_latent(self, x):
381
return self.style_mlp(x)
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)
390
input_is_latent=False,
392
randomize_noise=True,
394
truncation_latent=None,
396
return_latents=False):
397
"""Forward function for StyleGAN2Generator.
400
styles (list[Tensor]): Sample codes of styles.
401
input_is_latent (bool): Whether input is latent style.
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.
410
return_latents (bool): Whether to return style latents.
414
if not input_is_latent:
415
styles = [self.style_mlp(s) for s in styles]
419
noise = [None] * self.num_layers
421
noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]
424
style_truncation = []
426
style_truncation.append(truncation_latent + truncation * (style - truncation_latent))
427
styles = style_truncation
430
inject_index = self.num_latent
432
if styles[0].ndim < 3:
434
latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
437
elif len(styles) == 2:
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)
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])
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)
465
class ScaledLeakyReLU(nn.Module):
469
negative_slope (float): Negative slope. Default: 0.2.
472
def __init__(self, negative_slope=0.2):
473
super(ScaledLeakyReLU, self).__init__()
474
self.negative_slope = negative_slope
476
def forward(self, x):
477
out = F.leaky_relu(x, negative_slope=self.negative_slope)
478
return out * math.sqrt(2)
481
class EqualConv2d(nn.Module):
482
"""Equalized Linear as StyleGAN2.
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.
491
bias (bool): If ``True``, adds a learnable bias to the output.
493
bias_init_val (float): Bias initialized value. Default: 0.
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
502
self.padding = padding
503
self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
505
self.weight = nn.Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size))
507
self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
509
self.register_parameter('bias', None)
511
def forward(self, x):
514
self.weight * self.scale,
517
padding=self.padding,
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})')
530
class ConvLayer(nn.Sequential):
531
"""Conv Layer used in StyleGAN2 Discriminator.
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.
539
bias (bool): Whether with bias. Default: True.
540
activate (bool): Whether use activateion. Default: True.
550
interpolation_mode='bilinear'):
552
self.interpolation_mode = interpolation_mode
555
if self.interpolation_mode == 'nearest':
556
self.align_corners = None
558
self.align_corners = False
561
torch.nn.Upsample(scale_factor=0.5, mode=interpolation_mode, align_corners=self.align_corners))
563
self.padding = kernel_size // 2
567
in_channels, out_channels, kernel_size, stride=stride, padding=self.padding, bias=bias
572
layers.append(FusedLeakyReLU(out_channels))
574
layers.append(ScaledLeakyReLU(0.2))
576
super(ConvLayer, self).__init__(*layers)
579
class ResBlock(nn.Module):
580
"""Residual block used in StyleGAN2 Discriminator.
583
in_channels (int): Channel number of the input.
584
out_channels (int): Channel number of the output.
587
def __init__(self, in_channels, out_channels, interpolation_mode='bilinear'):
588
super(ResBlock, self).__init__()
590
self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True)
591
self.conv2 = ConvLayer(
596
interpolation_mode=interpolation_mode,
599
self.skip = ConvLayer(
604
interpolation_mode=interpolation_mode,
608
def forward(self, x):
610
out = self.conv2(out)
612
out = (out + skip) / math.sqrt(2)