File size: 12,357 Bytes
a3d2818
70a1838
 
a3d2818
70a1838
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63970f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
from torch import nn
import torch
from torch.nn import functional as F
from typing import Optional
import math

class WSLinear(nn.Module):
    '''
    Weighted scale linear for equalized learning rate.

    Args:
        in_features (int): The number of input features.
        out_features (int): The number of output features.
    '''

    def __init__(self, in_features: int, out_features: int) -> None:
        super(WSLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features

        self.linear = nn.Linear(self.in_features, self.out_features)
        self.scale = (2 / self.in_features) ** 0.5
        self.bias = self.linear.bias
        self.linear.bias = None

        self._init_weights()

    def _init_weights(self) -> None:
        nn.init.normal_(self.linear.weight)
        nn.init.zeros_(self.bias)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.linear(x * self.scale) + self.bias
    
class WSConv2d(nn.Module):
    """
    Weight-scaled Conv2d layer for equalized learning rate.

    Args:
        in_channels (int): Number of input channels.
        out_channels (int): Number of output channels.
        kernel_size (int, optional): Size of the convolving kernel. Default: 3.
        stride (int, optional): Stride of the convolution. Default: 1.
        padding (int, optional): Padding added to all sides of the input. Default: 1.
        gain (float, optional): Gain factor for weight initialization. Default: 2.
    """
    def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, gain=2):
        super().__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
        self.scale = (gain / (in_channels * kernel_size ** 2)) ** 0.5
        self.bias = self.conv.bias
        self.conv.bias = None  # Remove bias to apply it after scaling

        # Initialize weights
        nn.init.normal_(self.conv.weight)
        nn.init.zeros_(self.bias)

    def forward(self, x):
        return self.conv(x * self.scale) + self.bias.view(1, self.bias.shape[0], 1, 1)

class Mapping(nn.Module):
    '''
    Mapping network.

    Args:
        features (int): Number of features in the input and output.
        num_layers (int): Number of layers in the feed forward network.
        num_styles (int): Number of styles to generate.
    '''

    def __init__(
        self,
        features: int,
        num_styles: int,
        num_layers: int = 8,
    ) -> None:
        super(Mapping, self).__init__()
        self.features = features
        self.num_layers = num_layers
        self.num_styles = num_styles

        layers = []
        for _ in range(self.num_layers):
            layers.append(WSLinear(self.features, self.features))
            layers.append(nn.LeakyReLU(0.2))

        self.fc = nn.Sequential(*layers)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        '''
        Args:
            x (torch.Tensor): Input tensor of shape (b, l).

        Returns:
            torch.Tensor: Output tensor with the same shape as input.
        '''

        x = self.fc(x) # (b, l)
        return x

class AdaIN(nn.Module):
    '''
    Adaptive Instance Normalization (AdaIN)
    AdaIN(x_i, y) = y_s,i * (x_i - mean(x_i)) / std(x_i) + y_b,i

    Args:
        eps (float, optional): Small value to avoid division by zero. Default value is 0.00001.
    '''

    def __init__(self, eps: float= 1e-5) -> None:
        super(AdaIN, self).__init__()
        self.eps = eps

    def forward(
        self,
        x: torch.Tensor,
        scale: torch.Tensor,
        shift: torch.Tensor
    ) -> torch.Tensor:
        '''
        Args:
            x (torch.Tensor): Input tensor of shape (b, c, h, w).
            scale (torch.Tensor): Scale tensor of shape (b, c).
            shift (torch.Tensor): Shift tensor of shape (b, c).

        Returns:
            torch.Tensor: Output tensor of shape (b, c, h, w).
        '''

        b, c, *_ = x.shape

        mean = x.mean(dim=(2, 3), keepdim=True) # (b, c, 1, 1)
        std = x.std(dim=(2, 3), keepdim=True) # (b, c, 1, 1)
        x_norm = (x - mean) / (std ** 2 + self.eps) ** .5

        scale = scale.view(b, c, 1, 1) # (b, c, 1, 1)
        shift = scale.view(b, c, 1, 1) # (b, c, 1, 1)
        outputs = scale * x_norm + shift # (b, c, h, w)

        return outputs

class SynthesisLayer(nn.Module):
    '''
    Synthesis network layer which consist of:
    - Conv2d.
    - AdaIN.
    - Affine transformation.
    - Noise injection.

    Args:
        in_channels (int): The number of input channels.
        out_channels (int): The number of output channels.
        latent_features (int): The number of latent features.
        use_conv (bool, optional): Whether to use convolution or not. Default value is True.
    '''

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        latent_features: int,
        use_conv: bool = True
    ) -> None:
        super(SynthesisLayer, self).__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.latent_features = latent_features
        self.use_conv = use_conv

        self.conv = nn.Sequential(
            WSConv2d(self.in_channels, self.out_channels, kernel_size=3, padding=1),
            nn.LeakyReLU(0.2)
        ) if self.use_conv else nn.Identity()
        self.norm = AdaIN()
        self.scale_transform = WSLinear(self.latent_features, self.out_channels)
        self.shift_transform = WSLinear(self.latent_features, self.out_channels)
        self.noise_factor = nn.Parameter(torch.zeros(1, self.out_channels, 1, 1))

        self._init_weights()

    def _init_weights(self) -> None:
        for m in self.modules():
            if isinstance(m, (nn.Conv2d, nn.Linear)):
                nn.init.normal_(m.weight)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
        nn.init.ones_(self.scale_transform.bias)

    def forward(
        self,
        x: torch.Tensor,
        w: torch.Tensor,
        noise: Optional[torch.Tensor] = None
    ) -> torch.Tensor:
        '''
        Args:
            x (torch.Tensor): Input tensor of shape (b, c, h, w).
            w (torch.Tensor): Latent space vector of shape (b, l).
            noise (torch.Tensor, optional): Noise tensor of shape (b, 1, h, w). Default value is None.

        Returns:
            torch.Tensor: Output tensor of shape (b, c, h, w).
        '''

        b, _, h, w_ = x.shape
        x = self.conv(x) # (b, o_c, h, w)
        if noise is None:
            noise = torch.randn(b, 1, h, w_, device=x.device) # (b, 1, h, w)
        x += self.noise_factor * noise # (b, o_c, h, w)
        y_s = self.scale_transform(w) # (b, o_c)
        y_b = self.shift_transform(w) # (b, o_c)
        x = self.norm(x, y_s, y_b) # (b, i_c, h, w)

        return x
    

class SynthesisBlock(nn.Module):
    '''
    Synthesis network block which consist of:
    - Optional upsampling.
    - 2 Synthesis Layers.

    Args:
        in_channels (int): The number of input channels.
        out_channels (int): The number of output channels.
        latent_features (int): The number of latent features.
        use_conv (bool, optional): Whether to use convolution or not. Default value is True.
        upsample (bool, optional): Whether to use upsampling or not. Default value is True.
    '''

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        latent_features: int,
        *,
        use_conv: bool = True,
        upsample: bool = True
     ) -> None:
        super(SynthesisBlock, self).__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.latent_features = latent_features
        self.use_conv = use_conv
        self.upsample = upsample

        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear') if self.upsample else nn.Identity()
        self.layers = nn.ModuleList([
            SynthesisLayer(self.in_channels, self.in_channels, self.latent_features, use_conv=self.use_conv),
            SynthesisLayer(self.in_channels, self.out_channels, self.latent_features)
        ])

    def forward(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
        '''
        Args:
            x (torch.Tensor): Input tensor of shape (b, c, h, w).
            w (torch.Tensor): Latent vector of shape (b, l).

        Returns:
            torch.Tensor: Output tensor of shape (b, c, h, w) if not upsample else (b, c, 2h, 2w).
        '''

        x = self.upsample(x) # (b, c, h, w) if not upsample else (b, c, 2h, 2w)

        for layer in self.layers:
            x = layer(x, w) # (b, c, h, w) if not upsample else (b, c, 2h, 2w)

        return x

class Synthesis(nn.Module):
    '''
    Synthesis network which consist of:
    - Constant tensor.
    - Synthesis blocks.
    - ToRGB convolutions.

    Args:
        resolution (int): The resolution of the image.
        const_channels (int): The number of channels in the constant tensor. Default value is 512.
    '''

    def __init__(self, resolution: int, const_channels: int = 512) -> None:
        super(Synthesis, self).__init__()
        self.const_channels = const_channels
        self.resolution = resolution

        self.resolution_levels = int(math.log2(resolution) - 1)

        self.constant = nn.Parameter(torch.ones(1, self.const_channels, 4, 4)) # (c, 4, 4)

        in_channels = self.const_channels
        blocks = [ SynthesisBlock(in_channels, in_channels, self.const_channels, use_conv=False, upsample=False) ]
        to_rgb = [ WSConv2d(in_channels, 3, kernel_size=1, padding=0) ]

        for _ in range(self.resolution_levels - 1):
            blocks.append(SynthesisBlock(in_channels, in_channels // 2, self.const_channels))
            to_rgb.append(WSConv2d(in_channels // 2, 3, kernel_size=1, padding=0))
            in_channels //= 2

        self.blocks = nn.ModuleList(blocks)
        self.to_rgb = nn.ModuleList(to_rgb)

    def forward(self, w: torch.Tensor, alpha: float, steps: int) -> torch.Tensor:
        '''
        Args:
            w (torch.Tensor): Latent space vector of shape (b, l).
            alpha (float): Fade in alpha value.
            steps (int): The number of steps starting from 0.

        Returns:
            torch.Tensor: Output tensor of shape (b, 3, h, w).
        '''

        b = w.size(0)
        x = self.constant.expand(b, -1, -1, -1).clone() # (b, c, h, w)

        if steps == 0:
            x = self.blocks[0](x, w) # (b, c, h, w)
            x = self.to_rgb[0](x) # (b, c, h, w)
            return x

        for i in range(steps):
            x = self.blocks[i](x, w) # (b, c, h/2, w/2)

        old_rgb = self.to_rgb[steps - 1](x) # (b, 3, h/2, w/2)

        x = self.blocks[steps](x, w) # (b, 3, h, w)
        new_rgb = self.to_rgb[steps](x) # (b, 3, h, w)
        old_rgb = F.interpolate(old_rgb, scale_factor=2, mode='bilinear', align_corners=False) # (b, 3, h, w)

        x = (1 - alpha) * old_rgb + alpha * new_rgb # (b, 3, h, w)

        return x

class StyleGAN(nn.Module):
    '''
    StyleGAN implementation.

    Args:
        num_features (int): The number of features in the latent space vector.
        resolution (int): The resolution of the image.
        num_blocks (int, optional): The number of blocks in the synthesis network. Default value is 10.
    '''

    def __init__(self, num_features: int, resolution: int, num_blocks: int = 10):
        super(StyleGAN, self).__init__()
        self.num_features = num_features
        self.resolution = resolution
        self.num_blocks = num_blocks

        self.mapping = Mapping(self.num_features, self.num_blocks)
        self.synthesis = Synthesis(self.resolution, self.num_features)

    def forward(self, x: torch.Tensor, alpha: float, steps: int) -> torch.Tensor:
        '''
        Args:
            x (torch.Tensor): Random input tensor of shape (b, l).
            alpha (float): Fade in alpha value.
            steps (int): The number of steps starting from 0.

        Returns:
            torch.Tensor: Output tensor of shape (b, c, h, w).
        '''

        w = self.mapping(x) # (b, l)
        outputs = self.synthesis(w, alpha, steps) # (b, c, h, w)

        return outputs