Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
POSTECH-CVLab
GitHub Repository: POSTECH-CVLab/PyTorch-StudioGAN
Path: blob/master/src/models/stylegan3.py
809 views
1
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
#
3
# NVIDIA CORPORATION and its licensors retain all intellectual property
4
# and proprietary rights in and to this software, related documentation
5
# and any modifications thereto. Any use, reproduction, disclosure or
6
# distribution of this software and related documentation without an express
7
# license agreement from NVIDIA CORPORATION is strictly prohibited.
8
9
"""Generator architecture from the paper
10
"Alias-Free Generative Adversarial Networks"."""
11
12
import numpy as np
13
import scipy.signal
14
import scipy.optimize
15
import torch
16
import utils.style_misc as misc
17
18
from utils.style_ops import conv2d_gradfix
19
from utils.style_ops import filtered_lrelu
20
from utils.style_ops import bias_act
21
22
#----------------------------------------------------------------------------
23
24
def modulated_conv2d(
25
x, # Input tensor: [batch_size, in_channels, in_height, in_width]
26
w, # Weight tensor: [out_channels, in_channels, kernel_height, kernel_width]
27
s, # Style tensor: [batch_size, in_channels]
28
demodulate = True, # Apply weight demodulation?
29
padding = 0, # Padding: int or [padH, padW]
30
input_gain = None, # Optional scale factors for the input channels: [], [in_channels], or [batch_size, in_channels]
31
):
32
with misc.suppress_tracer_warnings(): # this value will be treated as a constant
33
batch_size = int(x.shape[0])
34
out_channels, in_channels, kh, kw = w.shape
35
misc.assert_shape(w, [out_channels, in_channels, kh, kw]) # [OIkk]
36
misc.assert_shape(x, [batch_size, in_channels, None, None]) # [NIHW]
37
misc.assert_shape(s, [batch_size, in_channels]) # [NI]
38
39
# Pre-normalize inputs.
40
if demodulate:
41
w = w * w.square().mean([1,2,3], keepdim=True).rsqrt()
42
s = s * s.square().mean().rsqrt()
43
44
# Modulate weights.
45
w = w.unsqueeze(0) # [NOIkk]
46
w = w * s.unsqueeze(1).unsqueeze(3).unsqueeze(4) # [NOIkk]
47
48
# Demodulate weights.
49
if demodulate:
50
dcoefs = (w.square().sum(dim=[2,3,4]) + 1e-8).rsqrt() # [NO]
51
w = w * dcoefs.unsqueeze(2).unsqueeze(3).unsqueeze(4) # [NOIkk]
52
53
# Apply input scaling.
54
if input_gain is not None:
55
input_gain = input_gain.expand(batch_size, in_channels) # [NI]
56
w = w * input_gain.unsqueeze(1).unsqueeze(3).unsqueeze(4) # [NOIkk]
57
58
# Execute as one fused op using grouped convolution.
59
x = x.reshape(1, -1, *x.shape[2:])
60
w = w.reshape(-1, in_channels, kh, kw)
61
x = conv2d_gradfix.conv2d(input=x, weight=w.to(x.dtype), padding=padding, groups=batch_size)
62
x = x.reshape(batch_size, -1, *x.shape[2:])
63
return x
64
65
#----------------------------------------------------------------------------
66
67
class FullyConnectedLayer(torch.nn.Module):
68
def __init__(self,
69
in_features, # Number of input features.
70
out_features, # Number of output features.
71
activation = 'linear', # Activation function: 'relu', 'lrelu', etc.
72
bias = True, # Apply additive bias before the activation function?
73
lr_multiplier = 1, # Learning rate multiplier.
74
weight_init = 1, # Initial standard deviation of the weight tensor.
75
bias_init = 0, # Initial value of the additive bias.
76
):
77
super().__init__()
78
self.in_features = in_features
79
self.out_features = out_features
80
self.activation = activation
81
self.weight = torch.nn.Parameter(torch.randn([out_features, in_features]) * (weight_init / lr_multiplier))
82
bias_init = np.broadcast_to(np.asarray(bias_init, dtype=np.float32), [out_features])
83
self.bias = torch.nn.Parameter(torch.from_numpy(bias_init / lr_multiplier)) if bias else None
84
self.weight_gain = lr_multiplier / np.sqrt(in_features)
85
self.bias_gain = lr_multiplier
86
87
def forward(self, x):
88
w = self.weight.to(x.dtype) * self.weight_gain
89
b = self.bias
90
if b is not None:
91
b = b.to(x.dtype)
92
if self.bias_gain != 1:
93
b = b * self.bias_gain
94
if self.activation == 'linear' and b is not None:
95
x = torch.addmm(b.unsqueeze(0), x, w.t())
96
else:
97
x = x.matmul(w.t())
98
x = bias_act.bias_act(x, b, act=self.activation)
99
return x
100
101
def extra_repr(self):
102
return f'in_features={self.in_features:d}, out_features={self.out_features:d}, activation={self.activation:s}'
103
104
#----------------------------------------------------------------------------
105
106
class MappingNetwork(torch.nn.Module):
107
def __init__(self,
108
z_dim, # Input latent (Z) dimensionality.
109
c_dim, # Conditioning label (C) dimensionality, 0 = no labels.
110
w_dim, # Intermediate latent (W) dimensionality.
111
num_ws, # Number of intermediate latents to output.
112
num_layers = 2, # Number of mapping layers.
113
lr_multiplier = 0.01, # Learning rate multiplier for the mapping layers.
114
w_avg_beta = 0.998, # Decay for tracking the moving average of W during training.
115
):
116
super().__init__()
117
self.z_dim = z_dim
118
self.c_dim = c_dim
119
self.w_dim = w_dim
120
self.num_ws = num_ws
121
self.num_layers = num_layers
122
self.w_avg_beta = w_avg_beta
123
124
# Construct layers.
125
self.embed = FullyConnectedLayer(self.c_dim, self.w_dim) if self.c_dim > 0 else None
126
features = [self.z_dim + (self.w_dim if self.c_dim > 0 else 0)] + [self.w_dim] * self.num_layers
127
for idx, in_features, out_features in zip(range(num_layers), features[:-1], features[1:]):
128
layer = FullyConnectedLayer(in_features, out_features, activation='lrelu', lr_multiplier=lr_multiplier)
129
setattr(self, f'fc{idx}', layer)
130
self.register_buffer('w_avg', torch.zeros([w_dim]))
131
132
def forward(self, z, c, truncation_psi=1, truncation_cutoff=None, update_emas=False):
133
misc.assert_shape(z, [None, self.z_dim])
134
if truncation_cutoff is None:
135
truncation_cutoff = self.num_ws
136
137
# Embed, normalize, and concatenate inputs.
138
x = z.to(torch.float32)
139
x = x * (x.square().mean(1, keepdim=True) + 1e-8).rsqrt()
140
if self.c_dim > 0:
141
misc.assert_shape(c, [None, self.c_dim])
142
y = self.embed(c.to(torch.float32))
143
y = y * (y.square().mean(1, keepdim=True) + 1e-8).rsqrt()
144
x = torch.cat([x, y], dim=1) if x is not None else y
145
146
# Execute layers.
147
for idx in range(self.num_layers):
148
x = getattr(self, f'fc{idx}')(x)
149
150
# Update moving average of W.
151
if update_emas:
152
self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta))
153
154
# Broadcast and apply truncation.
155
x = x.unsqueeze(1).repeat([1, self.num_ws, 1])
156
if truncation_psi != 1:
157
x[:, :truncation_cutoff] = self.w_avg.lerp(x[:, :truncation_cutoff], truncation_psi)
158
return x
159
160
def extra_repr(self):
161
return f'z_dim={self.z_dim:d}, c_dim={self.c_dim:d}, w_dim={self.w_dim:d}, num_ws={self.num_ws:d}'
162
163
#----------------------------------------------------------------------------
164
165
class SynthesisInput(torch.nn.Module):
166
def __init__(self,
167
w_dim, # Intermediate latent (W) dimensionality.
168
channels, # Number of output channels.
169
size, # Output spatial size: int or [width, height].
170
sampling_rate, # Output sampling rate.
171
bandwidth, # Output bandwidth.
172
):
173
super().__init__()
174
self.w_dim = w_dim
175
self.channels = channels
176
self.size = np.broadcast_to(np.asarray(size), [2])
177
self.sampling_rate = sampling_rate
178
self.bandwidth = bandwidth
179
180
# Draw random frequencies from uniform 2D disc.
181
freqs = torch.randn([self.channels, 2])
182
radii = freqs.square().sum(dim=1, keepdim=True).sqrt()
183
freqs /= radii * radii.square().exp().pow(0.25)
184
freqs *= bandwidth
185
phases = torch.rand([self.channels]) - 0.5
186
187
# Setup parameters and buffers.
188
self.weight = torch.nn.Parameter(torch.randn([self.channels, self.channels]))
189
self.affine = FullyConnectedLayer(w_dim, 4, weight_init=0, bias_init=[1,0,0,0])
190
self.register_buffer('transform', torch.eye(3, 3)) # User-specified inverse transform wrt. resulting image.
191
self.register_buffer('freqs', freqs)
192
self.register_buffer('phases', phases)
193
194
def forward(self, w):
195
# Introduce batch dimension.
196
transforms = self.transform.unsqueeze(0) # [batch, row, col]
197
freqs = self.freqs.unsqueeze(0) # [batch, channel, xy]
198
phases = self.phases.unsqueeze(0) # [batch, channel]
199
200
# Apply learned transformation.
201
t = self.affine(w) # t = (r_c, r_s, t_x, t_y)
202
t = t / t[:, :2].norm(dim=1, keepdim=True) # t' = (r'_c, r'_s, t'_x, t'_y)
203
m_r = torch.eye(3, device=w.device).unsqueeze(0).repeat([w.shape[0], 1, 1]) # Inverse rotation wrt. resulting image.
204
m_r[:, 0, 0] = t[:, 0] # r'_c
205
m_r[:, 0, 1] = -t[:, 1] # r'_s
206
m_r[:, 1, 0] = t[:, 1] # r'_s
207
m_r[:, 1, 1] = t[:, 0] # r'_c
208
m_t = torch.eye(3, device=w.device).unsqueeze(0).repeat([w.shape[0], 1, 1]) # Inverse translation wrt. resulting image.
209
m_t[:, 0, 2] = -t[:, 2] # t'_x
210
m_t[:, 1, 2] = -t[:, 3] # t'_y
211
transforms = m_r @ m_t @ transforms # First rotate resulting image, then translate, and finally apply user-specified transform.
212
213
# Transform frequencies.
214
phases = phases + (freqs @ transforms[:, :2, 2:]).squeeze(2)
215
freqs = freqs @ transforms[:, :2, :2]
216
217
# Dampen out-of-band frequencies that may occur due to the user-specified transform.
218
amplitudes = (1 - (freqs.norm(dim=2) - self.bandwidth) / (self.sampling_rate / 2 - self.bandwidth)).clamp(0, 1)
219
220
# Construct sampling grid.
221
theta = torch.eye(2, 3, device=w.device)
222
theta[0, 0] = 0.5 * self.size[0] / self.sampling_rate
223
theta[1, 1] = 0.5 * self.size[1] / self.sampling_rate
224
grids = torch.nn.functional.affine_grid(theta.unsqueeze(0), [1, 1, self.size[1], self.size[0]], align_corners=False)
225
226
# Compute Fourier features.
227
x = (grids.unsqueeze(3) @ freqs.permute(0, 2, 1).unsqueeze(1).unsqueeze(2)).squeeze(3) # [batch, height, width, channel]
228
x = x + phases.unsqueeze(1).unsqueeze(2)
229
x = torch.sin(x * (np.pi * 2))
230
x = x * amplitudes.unsqueeze(1).unsqueeze(2)
231
232
# Apply trainable mapping.
233
weight = self.weight / np.sqrt(self.channels)
234
x = x @ weight.t()
235
236
# Ensure correct shape.
237
x = x.permute(0, 3, 1, 2) # [batch, channel, height, width]
238
misc.assert_shape(x, [w.shape[0], self.channels, int(self.size[1]), int(self.size[0])])
239
return x
240
241
def extra_repr(self):
242
return '\n'.join([
243
f'w_dim={self.w_dim:d}, channels={self.channels:d}, size={list(self.size)},',
244
f'sampling_rate={self.sampling_rate:g}, bandwidth={self.bandwidth:g}'])
245
246
#----------------------------------------------------------------------------
247
248
class SynthesisLayer(torch.nn.Module):
249
def __init__(self,
250
w_dim, # Intermediate latent (W) dimensionality.
251
is_torgb, # Is this the final ToRGB layer?
252
is_critically_sampled, # Does this layer use critical sampling?
253
use_fp16, # Does this layer use FP16?
254
255
# Input & output specifications.
256
in_channels, # Number of input channels.
257
out_channels, # Number of output channels.
258
in_size, # Input spatial size: int or [width, height].
259
out_size, # Output spatial size: int or [width, height].
260
in_sampling_rate, # Input sampling rate (s).
261
out_sampling_rate, # Output sampling rate (s).
262
in_cutoff, # Input cutoff frequency (f_c).
263
out_cutoff, # Output cutoff frequency (f_c).
264
in_half_width, # Input transition band half-width (f_h).
265
out_half_width, # Output Transition band half-width (f_h).
266
267
# Hyperparameters.
268
conv_kernel = 3, # Convolution kernel size. Ignored for final the ToRGB layer.
269
filter_size = 6, # Low-pass filter size relative to the lower resolution when up/downsampling.
270
lrelu_upsampling = 2, # Relative sampling rate for leaky ReLU. Ignored for final the ToRGB layer.
271
use_radial_filters = False, # Use radially symmetric downsampling filter? Ignored for critically sampled layers.
272
conv_clamp = 256, # Clamp the output to [-X, +X], None = disable clamping.
273
magnitude_ema_beta = 0.999, # Decay rate for the moving average of input magnitudes.
274
):
275
super().__init__()
276
self.w_dim = w_dim
277
self.is_torgb = is_torgb
278
self.is_critically_sampled = is_critically_sampled
279
self.use_fp16 = use_fp16
280
self.in_channels = in_channels
281
self.out_channels = out_channels
282
self.in_size = np.broadcast_to(np.asarray(in_size), [2])
283
self.out_size = np.broadcast_to(np.asarray(out_size), [2])
284
self.in_sampling_rate = in_sampling_rate
285
self.out_sampling_rate = out_sampling_rate
286
self.tmp_sampling_rate = max(in_sampling_rate, out_sampling_rate) * (1 if is_torgb else lrelu_upsampling)
287
self.in_cutoff = in_cutoff
288
self.out_cutoff = out_cutoff
289
self.in_half_width = in_half_width
290
self.out_half_width = out_half_width
291
self.conv_kernel = 1 if is_torgb else conv_kernel
292
self.conv_clamp = conv_clamp
293
self.magnitude_ema_beta = magnitude_ema_beta
294
295
# Setup parameters and buffers.
296
self.affine = FullyConnectedLayer(self.w_dim, self.in_channels, bias_init=1)
297
self.weight = torch.nn.Parameter(torch.randn([self.out_channels, self.in_channels, self.conv_kernel, self.conv_kernel]))
298
self.bias = torch.nn.Parameter(torch.zeros([self.out_channels]))
299
self.register_buffer('magnitude_ema', torch.ones([]))
300
301
# Design upsampling filter.
302
self.up_factor = int(np.rint(self.tmp_sampling_rate / self.in_sampling_rate))
303
assert self.in_sampling_rate * self.up_factor == self.tmp_sampling_rate
304
self.up_taps = filter_size * self.up_factor if self.up_factor > 1 and not self.is_torgb else 1
305
self.register_buffer('up_filter', self.design_lowpass_filter(
306
numtaps=self.up_taps, cutoff=self.in_cutoff, width=self.in_half_width*2, fs=self.tmp_sampling_rate))
307
308
# Design downsampling filter.
309
self.down_factor = int(np.rint(self.tmp_sampling_rate / self.out_sampling_rate))
310
assert self.out_sampling_rate * self.down_factor == self.tmp_sampling_rate
311
self.down_taps = filter_size * self.down_factor if self.down_factor > 1 and not self.is_torgb else 1
312
self.down_radial = use_radial_filters and not self.is_critically_sampled
313
self.register_buffer('down_filter', self.design_lowpass_filter(
314
numtaps=self.down_taps, cutoff=self.out_cutoff, width=self.out_half_width*2, fs=self.tmp_sampling_rate, radial=self.down_radial))
315
316
# Compute padding.
317
pad_total = (self.out_size - 1) * self.down_factor + 1 # Desired output size before downsampling.
318
pad_total -= (self.in_size + self.conv_kernel - 1) * self.up_factor # Input size after upsampling.
319
pad_total += self.up_taps + self.down_taps - 2 # Size reduction caused by the filters.
320
pad_lo = (pad_total + self.up_factor) // 2 # Shift sample locations according to the symmetric interpretation (Appendix C.3).
321
pad_hi = pad_total - pad_lo
322
self.padding = [int(pad_lo[0]), int(pad_hi[0]), int(pad_lo[1]), int(pad_hi[1])]
323
324
def forward(self, x, w, noise_mode='random', force_fp32=False, update_emas=False):
325
assert noise_mode in ['random', 'const', 'none'] # unused
326
misc.assert_shape(x, [None, self.in_channels, int(self.in_size[1]), int(self.in_size[0])])
327
misc.assert_shape(w, [x.shape[0], self.w_dim])
328
329
# Track input magnitude.
330
if update_emas:
331
with torch.autograd.profiler.record_function('update_magnitude_ema'):
332
magnitude_cur = x.detach().to(torch.float32).square().mean()
333
self.magnitude_ema.copy_(magnitude_cur.lerp(self.magnitude_ema, self.magnitude_ema_beta))
334
input_gain = self.magnitude_ema.rsqrt()
335
336
# Execute affine layer.
337
styles = self.affine(w)
338
if self.is_torgb:
339
weight_gain = 1 / np.sqrt(self.in_channels * (self.conv_kernel ** 2))
340
styles = styles * weight_gain
341
342
# Execute modulated conv2d.
343
dtype = torch.float16 if (self.use_fp16 and not force_fp32 and x.device.type == 'cuda') else torch.float32
344
x = modulated_conv2d(x=x.to(dtype), w=self.weight, s=styles,
345
padding=self.conv_kernel-1, demodulate=(not self.is_torgb), input_gain=input_gain)
346
347
# Execute bias, filtered leaky ReLU, and clamping.
348
gain = 1 if self.is_torgb else np.sqrt(2)
349
slope = 1 if self.is_torgb else 0.2
350
x = filtered_lrelu.filtered_lrelu(x=x, fu=self.up_filter, fd=self.down_filter, b=self.bias.to(x.dtype),
351
up=self.up_factor, down=self.down_factor, padding=self.padding, gain=gain, slope=slope, clamp=self.conv_clamp)
352
353
# Ensure correct shape and dtype.
354
misc.assert_shape(x, [None, self.out_channels, int(self.out_size[1]), int(self.out_size[0])])
355
assert x.dtype == dtype
356
return x
357
358
@staticmethod
359
def design_lowpass_filter(numtaps, cutoff, width, fs, radial=False):
360
assert numtaps >= 1
361
362
# Identity filter.
363
if numtaps == 1:
364
return None
365
366
# Separable Kaiser low-pass filter.
367
if not radial:
368
f = scipy.signal.firwin(numtaps=numtaps, cutoff=cutoff, width=width, fs=fs)
369
return torch.as_tensor(f, dtype=torch.float32)
370
371
# Radially symmetric jinc-based filter.
372
x = (np.arange(numtaps) - (numtaps - 1) / 2) / fs
373
r = np.hypot(*np.meshgrid(x, x))
374
f = scipy.special.j1(2 * cutoff * (np.pi * r)) / (np.pi * r)
375
beta = scipy.signal.kaiser_beta(scipy.signal.kaiser_atten(numtaps, width / (fs / 2)))
376
w = np.kaiser(numtaps, beta)
377
f *= np.outer(w, w)
378
f /= np.sum(f)
379
return torch.as_tensor(f, dtype=torch.float32)
380
381
def extra_repr(self):
382
return '\n'.join([
383
f'w_dim={self.w_dim:d}, is_torgb={self.is_torgb},',
384
f'is_critically_sampled={self.is_critically_sampled}, use_fp16={self.use_fp16},',
385
f'in_sampling_rate={self.in_sampling_rate:g}, out_sampling_rate={self.out_sampling_rate:g},',
386
f'in_cutoff={self.in_cutoff:g}, out_cutoff={self.out_cutoff:g},',
387
f'in_half_width={self.in_half_width:g}, out_half_width={self.out_half_width:g},',
388
f'in_size={list(self.in_size)}, out_size={list(self.out_size)},',
389
f'in_channels={self.in_channels:d}, out_channels={self.out_channels:d}'])
390
391
#----------------------------------------------------------------------------
392
393
class SynthesisNetwork(torch.nn.Module):
394
def __init__(self,
395
w_dim, # Intermediate latent (W) dimensionality.
396
img_resolution, # Output image resolution.
397
img_channels, # Number of color channels.
398
channel_base = 32768, # Overall multiplier for the number of channels.
399
channel_max = 512, # Maximum number of channels in any layer.
400
num_layers = 14, # Total number of layers, excluding Fourier features and ToRGB.
401
num_critical = 2, # Number of critically sampled layers at the end.
402
first_cutoff = 2, # Cutoff frequency of the first layer (f_{c,0}).
403
first_stopband = 2**2.1, # Minimum stopband of the first layer (f_{t,0}).
404
last_stopband_rel = 2**0.3, # Minimum stopband of the last layer, expressed relative to the cutoff.
405
margin_size = 10, # Number of additional pixels outside the image.
406
output_scale = 0.25, # Scale factor for the output image.
407
num_fp16_res = 4, # Use FP16 for the N highest resolutions.
408
**layer_kwargs, # Arguments for SynthesisLayer.
409
):
410
super().__init__()
411
self.w_dim = w_dim
412
self.num_ws = num_layers + 2
413
self.img_resolution = img_resolution
414
self.img_channels = img_channels
415
self.num_layers = num_layers
416
self.num_critical = num_critical
417
self.margin_size = margin_size
418
self.output_scale = output_scale
419
self.num_fp16_res = num_fp16_res
420
421
# Geometric progression of layer cutoffs and min. stopbands.
422
last_cutoff = self.img_resolution / 2 # f_{c,N}
423
last_stopband = last_cutoff * last_stopband_rel # f_{t,N}
424
exponents = np.minimum(np.arange(self.num_layers + 1) / (self.num_layers - self.num_critical), 1)
425
cutoffs = first_cutoff * (last_cutoff / first_cutoff) ** exponents # f_c[i]
426
stopbands = first_stopband * (last_stopband / first_stopband) ** exponents # f_t[i]
427
428
# Compute remaining layer parameters.
429
sampling_rates = np.exp2(np.ceil(np.log2(np.minimum(stopbands * 2, self.img_resolution)))) # s[i]
430
half_widths = np.maximum(stopbands, sampling_rates / 2) - cutoffs # f_h[i]
431
sizes = sampling_rates + self.margin_size * 2
432
sizes[-2:] = self.img_resolution
433
channels = np.rint(np.minimum((channel_base / 2) / cutoffs, channel_max))
434
channels[-1] = self.img_channels
435
436
# Construct layers.
437
self.input = SynthesisInput(
438
w_dim=self.w_dim, channels=int(channels[0]), size=int(sizes[0]),
439
sampling_rate=sampling_rates[0], bandwidth=cutoffs[0])
440
self.layer_names = []
441
for idx in range(self.num_layers + 1):
442
prev = max(idx - 1, 0)
443
is_torgb = (idx == self.num_layers)
444
is_critically_sampled = (idx >= self.num_layers - self.num_critical)
445
use_fp16 = (sampling_rates[idx] * (2 ** self.num_fp16_res) > self.img_resolution)
446
layer = SynthesisLayer(
447
w_dim=self.w_dim, is_torgb=is_torgb, is_critically_sampled=is_critically_sampled, use_fp16=use_fp16,
448
in_channels=int(channels[prev]), out_channels= int(channels[idx]),
449
in_size=int(sizes[prev]), out_size=int(sizes[idx]),
450
in_sampling_rate=int(sampling_rates[prev]), out_sampling_rate=int(sampling_rates[idx]),
451
in_cutoff=cutoffs[prev], out_cutoff=cutoffs[idx],
452
in_half_width=half_widths[prev], out_half_width=half_widths[idx],
453
**layer_kwargs)
454
name = f'L{idx}_{layer.out_size[0]}_{layer.out_channels}'
455
setattr(self, name, layer)
456
self.layer_names.append(name)
457
458
def forward(self, ws, **layer_kwargs):
459
misc.assert_shape(ws, [None, self.num_ws, self.w_dim])
460
ws = ws.to(torch.float32).unbind(dim=1)
461
462
# Execute layers.
463
x = self.input(ws[0])
464
for name, w in zip(self.layer_names, ws[1:]):
465
x = getattr(self, name)(x, w, **layer_kwargs)
466
if self.output_scale != 1:
467
x = x * self.output_scale
468
469
# Ensure correct shape and dtype.
470
misc.assert_shape(x, [None, self.img_channels, self.img_resolution, self.img_resolution])
471
x = x.to(torch.float32)
472
return x
473
474
def extra_repr(self):
475
return '\n'.join([
476
f'w_dim={self.w_dim:d}, num_ws={self.num_ws:d},',
477
f'img_resolution={self.img_resolution:d}, img_channels={self.img_channels:d},',
478
f'num_layers={self.num_layers:d}, num_critical={self.num_critical:d},',
479
f'margin_size={self.margin_size:d}, num_fp16_res={self.num_fp16_res:d}'])
480
481
#----------------------------------------------------------------------------
482
483
class Generator(torch.nn.Module):
484
def __init__(self,
485
z_dim, # Input latent (Z) dimensionality.
486
c_dim, # Conditioning label (C) dimensionality.
487
w_dim, # Intermediate latent (W) dimensionality.
488
img_resolution, # Output resolution.
489
img_channels, # Number of output color channels.
490
MODEL, # MODEL config required for infoGAN
491
mapping_kwargs = {}, # Arguments for MappingNetwork.
492
synthesis_kwargs = {}, # Arguments for SynthesisNetwork.
493
):
494
super().__init__()
495
self.z_dim = z_dim
496
self.c_dim = c_dim
497
self.w_dim = w_dim
498
self.MODEL = MODEL
499
self.img_resolution = img_resolution
500
self.img_channels = img_channels
501
502
z_extra_dim = 0
503
if self.MODEL.info_type in ["discrete", "both"]:
504
z_extra_dim += self.MODEL.info_num_discrete_c*self.MODEL.info_dim_discrete_c
505
if self.MODEL.info_type in ["continuous", "both"]:
506
z_extra_dim += self.MODEL.info_num_conti_c
507
508
if self.MODEL.info_type != "N/A":
509
self.z_dim += z_extra_dim
510
511
self.synthesis = SynthesisNetwork(w_dim=w_dim, img_resolution=img_resolution, img_channels=img_channels, **synthesis_kwargs)
512
self.num_ws = self.synthesis.num_ws
513
self.mapping = MappingNetwork(z_dim=z_dim, c_dim=c_dim, w_dim=w_dim, num_ws=self.num_ws, **mapping_kwargs)
514
515
def forward(self, z, c, eval=False, truncation_psi=1, truncation_cutoff=None, update_emas=False, **synthesis_kwargs):
516
ws = self.mapping(z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas)
517
img = self.synthesis(ws, update_emas=update_emas, **synthesis_kwargs)
518
return img
519
520
#----------------------------------------------------------------------------
521
522