AK391 commited on
Commit
0145b71
1 Parent(s): 99116c0
gen_video.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+
8
+ from model import Generator
9
+ from psp_encoder.psp_encoders import PSPEncoder
10
+ from utils import ten2cv, cv2ten
11
+
12
+ import glob
13
+ from tqdm import tqdm
14
+ import random
15
+
16
+
17
+ seed = 0
18
+
19
+ random.seed(seed)
20
+ np.random.seed(seed)
21
+ torch.manual_seed(seed)
22
+ torch.cuda.manual_seed_all(seed)
23
+
24
+
25
+ def sigmoid(x, w=1):
26
+ return 1. / (1 + np.exp(-w * x))
27
+
28
+
29
+ def get_alphas(start=-5, end=5, step=0.5, len_tail=10):
30
+ return [0] + [sigmoid(alpha) for alpha in np.arange(start, end, step)] + [1] * len_tail
31
+
32
+
33
+ def slide(entries, margin=32):
34
+ """Returns a sliding reference window.
35
+ Args:
36
+ entries: a list containing two reference images, x_prev and x_next,
37
+ both of which has a shape (1, 3, H, W)
38
+ Returns:
39
+ canvas: output slide of shape (num_frames, 3, H*2, W+margin)
40
+ """
41
+ _, C, H, W = entries[0].shape
42
+ alphas = get_alphas()
43
+ T = len(alphas) # number of frames
44
+
45
+ canvas = - torch.ones((T, C, H*2, W + margin))
46
+ merged = torch.cat(entries, dim=2) # (1, 3, H*2, W)
47
+ for t, alpha in enumerate(alphas):
48
+ top = int(H * (1 - alpha)) # top, bottom for canvas
49
+ bottom = H * 2
50
+ m_top = 0 # top, bottom for merged
51
+ m_bottom = 2 * H - top
52
+ canvas[t, :, top:bottom, :W] = merged[:, :, m_top:m_bottom, :]
53
+ return canvas
54
+
55
+
56
+ def slide_one_window(entries, margin=32):
57
+ """Returns a sliding reference window.
58
+ Args:
59
+ entries: a list containing two reference images, x_prev and x_next,
60
+ both of which has a shape (1, 3, H, W)
61
+ Returns:
62
+ canvas: output slide of shape (num_frames, 3, H, W+margin)
63
+ """
64
+ _, C, H, W = entries[0].shape
65
+ device = entries[0].device
66
+ alphas = get_alphas()
67
+ T = len(alphas) # number of frames
68
+
69
+ canvas = - torch.ones((T, C, H, W + margin)).to(device)
70
+ merged = torch.cat(entries, dim=2) # (1, 3, H*2, W)
71
+ for t, alpha in enumerate(alphas):
72
+ m_top = int(H * alpha) # top, bottom for merged
73
+ m_bottom = m_top + H
74
+ canvas[t, :, :, :W] = merged[:, :, m_top:m_bottom, :]
75
+ return canvas
76
+
77
+
78
+ def tensor2ndarray255(images):
79
+ images = torch.clamp(images * 0.5 + 0.5, 0, 1)
80
+ return (images.cpu().numpy().transpose(0, 2, 3, 1) * 255).astype(np.uint8)
81
+
82
+
83
+ @torch.no_grad()
84
+ def interpolate(args, g, sample_in, sample_style_prev, sample_style_next):
85
+ ''' returns T x C x H x W '''
86
+ frames_ten = []
87
+ alphas = get_alphas()
88
+
89
+ for alpha in alphas:
90
+ sample_style = torch.lerp(sample_style_prev, sample_style_next, alpha)
91
+ frame_ten, _ = g([sample_in], z_embed=sample_style, add_weight_index=args.add_weight_index,
92
+ input_is_latent=True, return_latents=False, randomize_noise=False)
93
+ frames_ten.append(frame_ten)
94
+ frames_ten = torch.cat(frames_ten)
95
+ return frames_ten
96
+
97
+
98
+ @torch.no_grad()
99
+ def video_ref(args, g, psp_encoder, img_in_ten, img_style_tens):
100
+ video = []
101
+ sample_in = psp_encoder(img_in_ten)
102
+
103
+ img_style_ten_prev, sample_style_prev = None, None
104
+
105
+ for idx in tqdm(range(len(img_style_tens))):
106
+ img_style_ten_next = img_style_tens[idx]
107
+ sample_style_next = g_ema.get_z_embed(img_style_ten_next)
108
+ if img_style_ten_prev is None:
109
+ img_style_ten_prev, sample_style_prev = img_style_ten_next, sample_style_next
110
+ continue
111
+
112
+ interpolated = interpolate(args, g, sample_in, sample_style_prev, sample_style_next)
113
+ entries = [img_style_ten_prev, img_style_ten_next]
114
+ slided = slide_one_window(entries, margin=0) # [T, C, H, W)
115
+ frames = torch.cat([img_in_ten.expand_as(interpolated), slided, interpolated], dim=3).cpu() # [T, C, H, W*3)
116
+ video.append(frames)
117
+ img_style_ten_prev, sample_style_prev = img_style_ten_next, sample_style_next
118
+
119
+ # append last frame 10 time
120
+ for _ in range(10):
121
+ video.append(frames[-1:])
122
+ video = tensor2ndarray255(torch.cat(video)) # [T, H, W*3, C)
123
+
124
+ return video
125
+
126
+
127
+ def save_video(fname, images, output_fps=30):
128
+ print('save video to: %s' % fname)
129
+
130
+ assert isinstance(images, np.ndarray), "images should be np.array: NHWC"
131
+ num_frames, height, width, channels = images.shape
132
+
133
+ fourcc = cv2.VideoWriter_fourcc(*'XVID')
134
+ videoWriter = cv2.VideoWriter(fname, fourcc, output_fps, (width, height))
135
+
136
+ for idx in tqdm(range(num_frames)):
137
+ frame = images[idx][:, :, ::-1] # [H, W*3, C)
138
+ videoWriter.write(frame)
139
+
140
+ videoWriter.release()
141
+
142
+
143
+ if __name__ == '__main__':
144
+ device = 'cuda'
145
+
146
+ parser = argparse.ArgumentParser()
147
+
148
+ parser.add_argument('--size', type=int, default=1024)
149
+
150
+ parser.add_argument('--ckpt', type=str, default='', help='path to BlendGAN checkpoint')
151
+ parser.add_argument('--psp_encoder_ckpt', type=str, default='', help='path to psp_encoder checkpoint')
152
+
153
+ parser.add_argument('--style_img_path', type=str, default=None, help='path to style image')
154
+ parser.add_argument('--input_img_path', type=str, default=None, help='path to input image')
155
+ parser.add_argument('--add_weight_index', type=int, default=7)
156
+
157
+ parser.add_argument('--channel_multiplier', type=int, default=2)
158
+ parser.add_argument('--outdir', type=str, default="")
159
+
160
+ args = parser.parse_args()
161
+
162
+ outdir = args.outdir
163
+ if not os.path.exists(outdir):
164
+ os.makedirs(outdir, exist_ok=True)
165
+
166
+ args.latent = 512
167
+ args.n_mlp = 8
168
+
169
+ checkpoint = torch.load(args.ckpt)
170
+ model_dict = checkpoint['g_ema']
171
+ print('ckpt: ', args.ckpt)
172
+
173
+ g_ema = Generator(
174
+ args.size, args.latent, args.n_mlp, channel_multiplier=args.channel_multiplier
175
+ ).to(device)
176
+ g_ema.load_state_dict(model_dict)
177
+ g_ema.eval()
178
+
179
+ psp_encoder = PSPEncoder(args.psp_encoder_ckpt, output_size=args.size).to(device)
180
+ psp_encoder.eval()
181
+
182
+ input_img_paths = sorted(glob.glob(os.path.join(args.input_img_path, '*.*')))
183
+ style_img_paths = sorted(glob.glob(os.path.join(args.style_img_path, '*.*')))[:]
184
+
185
+ for input_img_path in input_img_paths:
186
+ print('process: %s' % input_img_path)
187
+
188
+ name_in = os.path.splitext(os.path.basename(input_img_path))[0]
189
+ img_in = cv2.imread(input_img_path, 1)
190
+ img_in = cv2.resize(img_in, (args.size, args.size))
191
+ img_in_ten = cv2ten(img_in, device)
192
+
193
+ img_style_tens = []
194
+
195
+ style_img_path_rand = random.choices(style_img_paths, k=8)
196
+ for style_img_path in style_img_path_rand:
197
+ name_style = os.path.splitext(os.path.basename(style_img_path))[0]
198
+ img_style = cv2.imread(style_img_path, 1)
199
+ img_style = cv2.resize(img_style, (args.size, args.size))
200
+ img_style_ten = cv2ten(img_style, device)
201
+
202
+ img_style_tens.append(img_style_ten)
203
+
204
+ fname = f'{args.outdir}/{name_in}.mp4'
205
+ video = video_ref(args, g_ema, psp_encoder, img_in_ten, img_style_tens)
206
+
207
+ save_video(fname, video, output_fps=30)
208
+
209
+ print('Done!')
210
+
generate_image_pairs.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ from tqdm import tqdm
8
+
9
+ from model import Generator
10
+ from utils import ten2cv, cv2ten
11
+ import random
12
+
13
+ seed = 0
14
+
15
+ random.seed(seed)
16
+ np.random.seed(seed)
17
+ torch.manual_seed(seed)
18
+ torch.cuda.manual_seed_all(seed)
19
+
20
+
21
+ def generate(args, g_ema, device, mean_latent, sample_style, add_weight_index):
22
+ if args.sample_zs is not None:
23
+ sample_zs = torch.load(args.sample_zs)
24
+ else:
25
+ sample_zs = None
26
+
27
+ with torch.no_grad():
28
+ g_ema.eval()
29
+ for i in tqdm(range(args.pics)):
30
+ if sample_zs is not None:
31
+ sample_z = sample_zs[i]
32
+ else:
33
+ sample_z = torch.randn(1, args.latent, device=device)
34
+
35
+ sample1, _ = g_ema([sample_z],
36
+ truncation=args.truncation, truncation_latent=mean_latent, return_latents=False, randomize_noise=False)
37
+ sample2, _ = g_ema([sample_z], z_embed=sample_style, add_weight_index=add_weight_index,
38
+ truncation=args.truncation, truncation_latent=mean_latent, return_latents=False, randomize_noise=False)
39
+
40
+ sample1 = ten2cv(sample1)
41
+ sample2 = ten2cv(sample2)
42
+ out = np.concatenate([sample1, sample2], axis=1)
43
+
44
+ cv2.imwrite(f'{args.outdir}/{str(i).zfill(6)}.jpg', out)
45
+
46
+
47
+ if __name__ == '__main__':
48
+ device = 'cuda'
49
+
50
+ parser = argparse.ArgumentParser()
51
+
52
+ parser.add_argument('--size', type=int, default=1024)
53
+ parser.add_argument('--pics', type=int, default=20, help='N_PICS')
54
+ parser.add_argument('--truncation', type=float, default=0.75)
55
+ parser.add_argument('--truncation_mean', type=int, default=4096)
56
+ parser.add_argument('--ckpt', type=str, default='', help='path to BlendGAN checkpoint')
57
+ parser.add_argument('--style_img', type=str, default=None, help='path to style image')
58
+ parser.add_argument('--sample_zs', type=str, default=None)
59
+ parser.add_argument('--add_weight_index', type=int, default=6)
60
+
61
+ parser.add_argument('--channel_multiplier', type=int, default=2)
62
+ parser.add_argument('--outdir', type=str, default="")
63
+
64
+ args = parser.parse_args()
65
+
66
+ outdir = args.outdir
67
+ if not os.path.exists(outdir):
68
+ os.makedirs(outdir, exist_ok=True)
69
+
70
+ args.latent = 512
71
+ args.n_mlp = 8
72
+
73
+ checkpoint = torch.load(args.ckpt)
74
+ model_dict = checkpoint['g_ema']
75
+ if "latent_avg" in checkpoint.keys():
76
+ latent_avg = checkpoint["latent_avg"]
77
+ else:
78
+ latent_avg = None
79
+ if "truncation" in checkpoint.keys():
80
+ args.truncation = checkpoint["truncation"]
81
+
82
+ print('ckpt: ', args.ckpt)
83
+ print('truncation: ', args.truncation)
84
+
85
+ g_ema = Generator(
86
+ args.size, args.latent, args.n_mlp, channel_multiplier=args.channel_multiplier
87
+ ).to(device)
88
+ g_ema.load_state_dict(model_dict)
89
+
90
+ if args.truncation < 1:
91
+ if latent_avg is not None:
92
+ mean_latent = latent_avg
93
+ print('### use mean_latent in ckpt["latent_avg"]')
94
+ else:
95
+ with torch.no_grad():
96
+ mean_latent = g_ema.mean_latent(args.truncation_mean)
97
+ print('### generate mean_latent with \'g_ema.mean_latent\'')
98
+ else:
99
+ mean_latent = None
100
+ print('### args.truncation = 1, mean_latent is None')
101
+
102
+ if args.style_img is not None:
103
+ img = cv2.imread(args.style_img, 1)
104
+ img = cv2ten(img, device)
105
+ sample_style = g_ema.get_z_embed(img)
106
+ else:
107
+ sample_style = torch.randn(1, args.latent, device=device)
108
+
109
+ generate(args, g_ema, device, mean_latent, sample_style, args.add_weight_index)
110
+
111
+ print('Done!')
model.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d
9
+ from model_encoder import StyleEncoder
10
+
11
+
12
+ class PixelNorm(nn.Module):
13
+ def __init__(self):
14
+ super().__init__()
15
+
16
+ def forward(self, input):
17
+ return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)
18
+
19
+
20
+ def make_kernel(k):
21
+ k = torch.tensor(k, dtype=torch.float32)
22
+
23
+ if k.ndim == 1:
24
+ k = k[None, :] * k[:, None]
25
+
26
+ k /= k.sum()
27
+
28
+ return k
29
+
30
+
31
+ class Upsample(nn.Module):
32
+ def __init__(self, kernel, factor=2):
33
+ super().__init__()
34
+
35
+ self.factor = factor
36
+ kernel = make_kernel(kernel) * (factor ** 2)
37
+ self.register_buffer('kernel', kernel)
38
+
39
+ p = kernel.shape[0] - factor
40
+
41
+ pad0 = (p + 1) // 2 + factor - 1
42
+ pad1 = p // 2
43
+
44
+ self.pad = (pad0, pad1)
45
+
46
+ def forward(self, input):
47
+ out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad)
48
+
49
+ return out
50
+
51
+
52
+ class Downsample(nn.Module):
53
+ def __init__(self, kernel, factor=2):
54
+ super().__init__()
55
+
56
+ self.factor = factor
57
+ kernel = make_kernel(kernel)
58
+ self.register_buffer('kernel', kernel)
59
+
60
+ p = kernel.shape[0] - factor
61
+
62
+ pad0 = (p + 1) // 2
63
+ pad1 = p // 2
64
+
65
+ self.pad = (pad0, pad1)
66
+
67
+ def forward(self, input):
68
+ out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad)
69
+
70
+ return out
71
+
72
+
73
+ class Blur(nn.Module):
74
+ def __init__(self, kernel, pad, upsample_factor=1):
75
+ super().__init__()
76
+
77
+ kernel = make_kernel(kernel)
78
+
79
+ if upsample_factor > 1:
80
+ kernel = kernel * (upsample_factor ** 2)
81
+
82
+ self.register_buffer('kernel', kernel)
83
+
84
+ self.pad = pad
85
+
86
+ def forward(self, input):
87
+ out = upfirdn2d(input, self.kernel, pad=self.pad)
88
+
89
+ return out
90
+
91
+
92
+ class EqualConv2d(nn.Module):
93
+ def __init__(
94
+ self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True
95
+ ):
96
+ super().__init__()
97
+
98
+ self.weight = nn.Parameter(
99
+ torch.randn(out_channel, in_channel, kernel_size, kernel_size)
100
+ )
101
+ self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
102
+
103
+ self.stride = stride
104
+ self.padding = padding
105
+
106
+ if bias:
107
+ self.bias = nn.Parameter(torch.zeros(out_channel))
108
+
109
+ else:
110
+ self.bias = None
111
+
112
+ def forward(self, input):
113
+ out = F.conv2d(
114
+ input,
115
+ self.weight * self.scale,
116
+ bias=self.bias,
117
+ stride=self.stride,
118
+ padding=self.padding,
119
+ )
120
+
121
+ return out
122
+
123
+ def __repr__(self):
124
+ return (
125
+ f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},'
126
+ f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
127
+ )
128
+
129
+
130
+ class EqualLinear(nn.Module):
131
+ def __init__(
132
+ self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None
133
+ ):
134
+ super().__init__()
135
+
136
+ self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
137
+
138
+ if bias:
139
+ self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
140
+
141
+ else:
142
+ self.bias = None
143
+
144
+ self.activation = activation
145
+
146
+ self.scale = (1 / math.sqrt(in_dim)) * lr_mul
147
+ self.lr_mul = lr_mul
148
+
149
+ def forward(self, input):
150
+ if self.activation:
151
+ out = F.linear(input, self.weight * self.scale)
152
+ out = fused_leaky_relu(out, self.bias * self.lr_mul)
153
+
154
+ else:
155
+ out = F.linear(
156
+ input, self.weight * self.scale, bias=self.bias * self.lr_mul
157
+ )
158
+
159
+ return out
160
+
161
+ def __repr__(self):
162
+ return (
163
+ f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
164
+ )
165
+
166
+
167
+ class ScaledLeakyReLU(nn.Module):
168
+ def __init__(self, negative_slope=0.2):
169
+ super().__init__()
170
+
171
+ self.negative_slope = negative_slope
172
+
173
+ def forward(self, input):
174
+ out = F.leaky_relu(input, negative_slope=self.negative_slope)
175
+
176
+ return out * math.sqrt(2)
177
+
178
+
179
+ class ModulatedConv2d(nn.Module):
180
+ def __init__(
181
+ self,
182
+ in_channel,
183
+ out_channel,
184
+ kernel_size,
185
+ style_dim,
186
+ demodulate=True,
187
+ upsample=False,
188
+ downsample=False,
189
+ blur_kernel=[1, 3, 3, 1],
190
+ ):
191
+ super().__init__()
192
+
193
+ self.eps = 1e-8
194
+ self.kernel_size = kernel_size
195
+ self.in_channel = in_channel
196
+ self.out_channel = out_channel
197
+ self.upsample = upsample
198
+ self.downsample = downsample
199
+
200
+ if upsample:
201
+ factor = 2
202
+ p = (len(blur_kernel) - factor) - (kernel_size - 1)
203
+ pad0 = (p + 1) // 2 + factor - 1
204
+ pad1 = p // 2 + 1
205
+
206
+ self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor)
207
+
208
+ if downsample:
209
+ factor = 2
210
+ p = (len(blur_kernel) - factor) + (kernel_size - 1)
211
+ pad0 = (p + 1) // 2
212
+ pad1 = p // 2
213
+
214
+ self.blur = Blur(blur_kernel, pad=(pad0, pad1))
215
+
216
+ fan_in = in_channel * kernel_size ** 2
217
+ self.scale = 1 / math.sqrt(fan_in)
218
+ self.padding = kernel_size // 2
219
+
220
+ self.weight = nn.Parameter(
221
+ torch.randn(1, out_channel, in_channel, kernel_size, kernel_size)
222
+ )
223
+
224
+ self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
225
+
226
+ self.demodulate = demodulate
227
+
228
+ def __repr__(self):
229
+ return (
230
+ f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, '
231
+ f'upsample={self.upsample}, downsample={self.downsample})'
232
+ )
233
+
234
+ def forward(self, input, style):
235
+ batch, in_channel, height, width = input.shape
236
+
237
+ style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
238
+ weight = self.scale * self.weight * style
239
+
240
+ if self.demodulate:
241
+ demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8)
242
+ weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
243
+
244
+ weight = weight.view(
245
+ batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size
246
+ )
247
+
248
+ if self.upsample:
249
+ input = input.view(1, batch * in_channel, height, width)
250
+ weight = weight.view(
251
+ batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size
252
+ )
253
+ weight = weight.transpose(1, 2).reshape(
254
+ batch * in_channel, self.out_channel, self.kernel_size, self.kernel_size
255
+ )
256
+ out = F.conv_transpose2d(input, weight, padding=0, stride=2, groups=batch)
257
+ _, _, height, width = out.shape
258
+ out = out.view(batch, self.out_channel, height, width)
259
+ out = self.blur(out)
260
+
261
+ elif self.downsample:
262
+ input = self.blur(input)
263
+ _, _, height, width = input.shape
264
+ input = input.view(1, batch * in_channel, height, width)
265
+ out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
266
+ _, _, height, width = out.shape
267
+ out = out.view(batch, self.out_channel, height, width)
268
+
269
+ else:
270
+ input = input.view(1, batch * in_channel, height, width)
271
+ out = F.conv2d(input, weight, padding=self.padding, groups=batch)
272
+ _, _, height, width = out.shape
273
+ out = out.view(batch, self.out_channel, height, width)
274
+
275
+ return out
276
+
277
+
278
+ class NoiseInjection(nn.Module):
279
+ def __init__(self):
280
+ super().__init__()
281
+
282
+ self.weight = nn.Parameter(torch.zeros(1))
283
+
284
+ def forward(self, image, noise=None):
285
+ if noise is None:
286
+ batch, _, height, width = image.shape
287
+ noise = image.new_empty(batch, 1, height, width).normal_()
288
+
289
+ return image + self.weight * noise
290
+
291
+
292
+ class ConstantInput(nn.Module):
293
+ def __init__(self, channel, size=4):
294
+ super().__init__()
295
+
296
+ self.input = nn.Parameter(torch.randn(1, channel, size, size))
297
+
298
+ def forward(self, input):
299
+ batch = input.shape[0]
300
+ out = self.input.repeat(batch, 1, 1, 1)
301
+
302
+ return out
303
+
304
+
305
+ class StyledConv(nn.Module):
306
+ def __init__(
307
+ self,
308
+ in_channel,
309
+ out_channel,
310
+ kernel_size,
311
+ style_dim,
312
+ upsample=False,
313
+ blur_kernel=[1, 3, 3, 1],
314
+ demodulate=True,
315
+ ):
316
+ super().__init__()
317
+
318
+ self.conv = ModulatedConv2d(
319
+ in_channel,
320
+ out_channel,
321
+ kernel_size,
322
+ style_dim,
323
+ upsample=upsample,
324
+ blur_kernel=blur_kernel,
325
+ demodulate=demodulate,
326
+ )
327
+
328
+ self.noise = NoiseInjection()
329
+ # self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1))
330
+ # self.activate = ScaledLeakyReLU(0.2)
331
+ self.activate = FusedLeakyReLU(out_channel)
332
+
333
+ def forward(self, input, style, noise=None):
334
+ out = self.conv(input, style)
335
+ out = self.noise(out, noise=noise)
336
+ # out = out + self.bias
337
+ out = self.activate(out)
338
+
339
+ return out
340
+
341
+
342
+ class ToRGB(nn.Module):
343
+ def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]):
344
+ super().__init__()
345
+
346
+ if upsample:
347
+ self.upsample = Upsample(blur_kernel)
348
+
349
+ self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False)
350
+ self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
351
+
352
+ def forward(self, input, style, skip=None):
353
+ out = self.conv(input, style)
354
+ out = out + self.bias
355
+
356
+ if skip is not None:
357
+ skip = self.upsample(skip)
358
+
359
+ out = out + skip
360
+
361
+ return out
362
+
363
+
364
+ class Generator(nn.Module):
365
+ def __init__(
366
+ self,
367
+ size,
368
+ style_dim,
369
+ n_mlp,
370
+ channel_multiplier=2,
371
+ blur_kernel=[1, 3, 3, 1],
372
+ lr_mlp=0.01,
373
+ ):
374
+ super().__init__()
375
+
376
+ self.size = size
377
+
378
+ self.style_dim = style_dim
379
+
380
+ self.embedder = StyleEncoder(style_dim=512, n_mlp=4)
381
+
382
+ layers = [PixelNorm()]
383
+
384
+ for i in range(n_mlp):
385
+ layers.append(
386
+ EqualLinear(
387
+ style_dim, style_dim, lr_mul=lr_mlp, activation='fused_lrelu'
388
+ )
389
+ )
390
+ self.embedding = nn.Sequential(*layers)
391
+
392
+ layers = [PixelNorm()]
393
+
394
+ for i in range(n_mlp):
395
+ layers.append(
396
+ EqualLinear(
397
+ style_dim, style_dim, lr_mul=lr_mlp, activation='fused_lrelu'
398
+ )
399
+ )
400
+
401
+ self.style = nn.Sequential(*layers)
402
+
403
+ self.channels = {
404
+ 4: 512,
405
+ 8: 512,
406
+ 16: 512,
407
+ 32: 512,
408
+ 64: 256 * channel_multiplier,
409
+ 128: 128 * channel_multiplier,
410
+ 256: 64 * channel_multiplier,
411
+ 512: 32 * channel_multiplier,
412
+ 1024: 16 * channel_multiplier,
413
+ }
414
+
415
+ self.input = ConstantInput(self.channels[4])
416
+ self.conv1 = StyledConv(
417
+ self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel
418
+ )
419
+ self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False)
420
+
421
+ self.log_size = int(math.log(size, 2))
422
+ self.num_layers = (self.log_size - 2) * 2 + 1
423
+
424
+ self.convs = nn.ModuleList()
425
+ self.upsamples = nn.ModuleList()
426
+ self.to_rgbs = nn.ModuleList()
427
+ self.noises = nn.Module()
428
+
429
+ in_channel = self.channels[4]
430
+
431
+ for layer_idx in range(self.num_layers):
432
+ res = (layer_idx + 5) // 2
433
+ shape = [1, 1, 2 ** res, 2 ** res]
434
+ self.noises.register_buffer(f'noise_{layer_idx}', torch.randn(*shape))
435
+
436
+ for i in range(3, self.log_size + 1):
437
+ out_channel = self.channels[2 ** i]
438
+
439
+ self.convs.append(
440
+ StyledConv(
441
+ in_channel,
442
+ out_channel,
443
+ 3,
444
+ style_dim,
445
+ upsample=True,
446
+ blur_kernel=blur_kernel,
447
+ )
448
+ )
449
+
450
+ self.convs.append(
451
+ StyledConv(
452
+ out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel
453
+ )
454
+ )
455
+
456
+ self.to_rgbs.append(ToRGB(out_channel, style_dim))
457
+
458
+ in_channel = out_channel
459
+
460
+ self.n_latent = self.log_size * 2 - 2
461
+
462
+ self.add_weight = nn.Parameter(torch.ones(1, self.n_latent, 1))
463
+
464
+ def make_noise(self):
465
+ device = self.input.input.device
466
+
467
+ noises = [torch.randn(1, 1, 2 ** 2, 2 ** 2, device=device)]
468
+
469
+ for i in range(3, self.log_size + 1):
470
+ for _ in range(2):
471
+ noises.append(torch.randn(1, 1, 2 ** i, 2 ** i, device=device))
472
+
473
+ return noises
474
+
475
+ def mean_latent(self, n_latent):
476
+ latent_in = torch.randn(
477
+ n_latent, self.style_dim, device=self.input.input.device
478
+ )
479
+ latent = self.style(latent_in).mean(0, keepdim=True)
480
+
481
+ return latent
482
+
483
+ def get_latent(self, input):
484
+ return self.style(input)
485
+
486
+ def get_z_embed(self, image):
487
+ self.embedder.eval()
488
+ with torch.no_grad():
489
+ z_embed = self.embedder(image) # [N, 512]
490
+ return z_embed
491
+
492
+ def forward(
493
+ self,
494
+ styles=None,
495
+ return_latents=False,
496
+ inject_index=None,
497
+ truncation=1,
498
+ truncation_latent=None,
499
+ input_is_latent=False,
500
+ noise=None,
501
+ randomize_noise=True,
502
+ style_image=None,
503
+ z_embed=None,
504
+ only_return_z_embed=False,
505
+ add_weight_index=None,
506
+ ):
507
+ if only_return_z_embed and style_image is not None:
508
+ return self.get_z_embed(style_image)
509
+
510
+ if not input_is_latent:
511
+ styles = [self.style(s) for s in styles]
512
+
513
+ if noise is None:
514
+ if randomize_noise:
515
+ noise = [None] * self.num_layers
516
+ else:
517
+ noise = [
518
+ getattr(self.noises, f'noise_{i}') for i in range(self.num_layers)
519
+ ]
520
+
521
+ if truncation < 1:
522
+ style_t = []
523
+
524
+ for style in styles:
525
+ style_t.append(
526
+ truncation_latent + truncation * (style - truncation_latent)
527
+ )
528
+
529
+ styles = style_t
530
+
531
+ if len(styles) < 2:
532
+ inject_index = self.n_latent
533
+
534
+ if styles[0].ndim < 3:
535
+ latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
536
+
537
+ else:
538
+ latent = styles[0]
539
+
540
+ else:
541
+ if inject_index is None:
542
+ inject_index = random.randint(1, self.n_latent - 1)
543
+
544
+ latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
545
+ latent2 = styles[1].unsqueeze(1).repeat(1, self.n_latent - inject_index, 1)
546
+
547
+ latent = torch.cat([latent, latent2], 1) # [N, 18, 512]
548
+
549
+ if z_embed is not None:
550
+ latent_style = self.embedding(z_embed)
551
+ latent_style = latent_style.unsqueeze(1).repeat(1, self.n_latent, 1) # [N, 18, 512]
552
+ elif style_image is not None:
553
+ z_embed = self.get_z_embed(style_image) # [N, 512]
554
+ latent_style = self.embedding(z_embed)
555
+ latent_style = latent_style.unsqueeze(1).repeat(1, self.n_latent, 1) # [N, 18, 512]
556
+ else:
557
+ latent_style = None
558
+
559
+ if latent_style is not None:
560
+ self.add_weight.data = self.add_weight.data.clamp(0.0, 1.0)
561
+ if add_weight_index is not None:
562
+ add_weight_new = self.add_weight.clone()
563
+ add_weight_new[:, :add_weight_index, :] = 1.0
564
+ latent = latent * add_weight_new + latent_style * (1 - add_weight_new)
565
+ else:
566
+ latent = latent * self.add_weight + latent_style * (1 - self.add_weight)
567
+
568
+ out = self.input(latent)
569
+ out = self.conv1(out, latent[:, 0], noise=noise[0])
570
+
571
+ skip = self.to_rgb1(out, latent[:, 1])
572
+
573
+ i = 1
574
+ for conv1, conv2, noise1, noise2, to_rgb in zip(
575
+ self.convs[::2], self.convs[1::2], noise[1::2], noise[2::2], self.to_rgbs
576
+ ):
577
+ out = conv1(out, latent[:, i], noise=noise1)
578
+ out = conv2(out, latent[:, i + 1], noise=noise2)
579
+ skip = to_rgb(out, latent[:, i + 2], skip)
580
+
581
+ i += 2
582
+
583
+ image = skip
584
+
585
+ if return_latents:
586
+ if style_image is not None or z_embed is not None:
587
+ return image, latent, z_embed
588
+ else:
589
+ return image, latent
590
+
591
+ else:
592
+ return image, None
593
+
594
+
595
+ class ConvLayer(nn.Sequential):
596
+ def __init__(
597
+ self,
598
+ in_channel,
599
+ out_channel,
600
+ kernel_size,
601
+ downsample=False,
602
+ blur_kernel=[1, 3, 3, 1],
603
+ bias=True,
604
+ activate=True,
605
+ ):
606
+ layers = []
607
+
608
+ if downsample:
609
+ factor = 2
610
+ p = (len(blur_kernel) - factor) + (kernel_size - 1)
611
+ pad0 = (p + 1) // 2
612
+ pad1 = p // 2
613
+
614
+ layers.append(Blur(blur_kernel, pad=(pad0, pad1)))
615
+
616
+ stride = 2
617
+ self.padding = 0
618
+
619
+ else:
620
+ stride = 1
621
+ self.padding = kernel_size // 2
622
+
623
+ layers.append(
624
+ EqualConv2d(
625
+ in_channel,
626
+ out_channel,
627
+ kernel_size,
628
+ padding=self.padding,
629
+ stride=stride,
630
+ bias=bias and not activate,
631
+ )
632
+ )
633
+
634
+ if activate:
635
+ if bias:
636
+ layers.append(FusedLeakyReLU(out_channel))
637
+
638
+ else:
639
+ layers.append(ScaledLeakyReLU(0.2))
640
+
641
+ super().__init__(*layers)
642
+
643
+
644
+ class ResBlock(nn.Module):
645
+ def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]):
646
+ super().__init__()
647
+
648
+ self.conv1 = ConvLayer(in_channel, in_channel, 3)
649
+ self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True)
650
+
651
+ self.skip = ConvLayer(
652
+ in_channel, out_channel, 1, downsample=True, activate=False, bias=False
653
+ )
654
+
655
+ def forward(self, input):
656
+ out = self.conv1(input)
657
+ out = self.conv2(out)
658
+
659
+ skip = self.skip(input)
660
+ out = (out + skip) / math.sqrt(2)
661
+
662
+ return out
663
+
664
+
665
+ class Discriminator(nn.Module):
666
+ def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]):
667
+ super().__init__()
668
+
669
+ channels = {
670
+ 4: 512,
671
+ 8: 512,
672
+ 16: 512,
673
+ 32: 512,
674
+ 64: 256 * channel_multiplier,
675
+ 128: 128 * channel_multiplier,
676
+ 256: 64 * channel_multiplier,
677
+ 512: 32 * channel_multiplier,
678
+ 1024: 16 * channel_multiplier,
679
+ }
680
+
681
+ convs = [ConvLayer(3, channels[size], 1)]
682
+
683
+ log_size = int(math.log(size, 2))
684
+
685
+ in_channel = channels[size]
686
+
687
+ for i in range(log_size, 2, -1):
688
+ out_channel = channels[2 ** (i - 1)]
689
+
690
+ convs.append(ResBlock(in_channel, out_channel, blur_kernel))
691
+
692
+ in_channel = out_channel
693
+
694
+ self.convs = nn.Sequential(*convs)
695
+
696
+ self.stddev_group = 4
697
+ self.stddev_feat = 1
698
+
699
+ self.final_conv = ConvLayer(in_channel + 1, channels[4], 3)
700
+ self.final_linear = nn.Sequential(
701
+ EqualLinear(channels[4] * 4 * 4, channels[4], activation='fused_lrelu'),
702
+ EqualLinear(channels[4], 1),
703
+ )
704
+
705
+ def forward(self, input):
706
+ out = self.convs(input)
707
+
708
+ batch, channel, height, width = out.shape
709
+ group = min(batch, self.stddev_group)
710
+ stddev = out.view(
711
+ group, -1, self.stddev_feat, channel // self.stddev_feat, height, width
712
+ )
713
+ stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8)
714
+ stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2)
715
+ stddev = stddev.repeat(group, 1, height, width)
716
+ out = torch.cat([out, stddev], 1)
717
+
718
+ out = self.final_conv(out)
719
+
720
+ out = out.view(batch, -1)
721
+ out = self.final_linear(out)
722
+
723
+ return out
724
+
725
+
726
+ class ProjectionDiscriminator(nn.Module):
727
+ def __init__(self, size, style_dim=512, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]):
728
+ super().__init__()
729
+
730
+ channels = {
731
+ 4: 512,
732
+ 8: 512,
733
+ 16: 512,
734
+ 32: 512,
735
+ 64: 256 * channel_multiplier,
736
+ 128: 128 * channel_multiplier,
737
+ 256: 64 * channel_multiplier,
738
+ 512: 32 * channel_multiplier,
739
+ 1024: 16 * channel_multiplier,
740
+ }
741
+
742
+ convs = [ConvLayer(3, channels[size], 1)]
743
+
744
+ log_size = int(math.log(size, 2))
745
+
746
+ in_channel = channels[size]
747
+
748
+ for i in range(log_size, 2, -1):
749
+ out_channel = channels[2 ** (i - 1)]
750
+ convs.append(ResBlock(in_channel, out_channel, blur_kernel))
751
+ in_channel = out_channel
752
+
753
+ self.convs = nn.Sequential(*convs)
754
+
755
+ self.stddev_group = 4
756
+ self.stddev_feat = 1
757
+
758
+ self.final_conv = ConvLayer(in_channel + 1, channels[4], 3)
759
+
760
+ self.l_out = EqualLinear(in_channel, 1)
761
+ self.l_style = EqualLinear(style_dim, in_channel)
762
+
763
+ def forward(self, input, style):
764
+ out = self.convs(input)
765
+
766
+ batch, channel, height, width = out.shape
767
+ group = min(batch, self.stddev_group)
768
+ stddev = out.view(
769
+ group, -1, self.stddev_feat, channel // self.stddev_feat, height, width
770
+ )
771
+ stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8)
772
+ stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2)
773
+ stddev = stddev.repeat(group, 1, height, width)
774
+ out = torch.cat([out, stddev], 1)
775
+
776
+ out = self.final_conv(out)
777
+
778
+ h = torch.sum(out, dim=(2, 3))
779
+ output = self.l_out(h)
780
+ output += torch.sum(self.l_style(style) * h, dim=1, keepdim=True)
781
+
782
+ return output
model_encoder.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ from collections import namedtuple
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ import torchvision.models.vgg as vgg
10
+
11
+ from op import fused_leaky_relu
12
+
13
+
14
+ FeatureOutput = namedtuple(
15
+ "FeatureOutput", ["relu1", "relu2", "relu3", "relu4", "relu5"])
16
+
17
+
18
+ def gram_matrix(y):
19
+ (b, ch, h, w) = y.size()
20
+ features = y.view(b, ch, w * h)
21
+ features_t = features.transpose(1, 2)
22
+ gram = features.bmm(features_t) / (ch * h * w)
23
+ return gram
24
+
25
+
26
+ class FeatureExtractor(nn.Module):
27
+ """Reference:
28
+ https://discuss.pytorch.org/t/how-to-extract-features-of-an-image-from-a-trained-model/119/3
29
+ """
30
+
31
+ def __init__(self):
32
+ super(FeatureExtractor, self).__init__()
33
+ self.vgg_layers = vgg.vgg19(pretrained=True).features
34
+ self.layer_name_mapping = {
35
+ '3': "relu1",
36
+ '8': "relu2",
37
+ '17': "relu3",
38
+ '26': "relu4",
39
+ '35': "relu5",
40
+ }
41
+
42
+ def forward(self, x):
43
+ output = {}
44
+ for name, module in self.vgg_layers._modules.items():
45
+ x = module(x)
46
+ if name in self.layer_name_mapping:
47
+ output[self.layer_name_mapping[name]] = x
48
+ return FeatureOutput(**output)
49
+
50
+
51
+ class StyleEmbedder(nn.Module):
52
+ def __init__(self):
53
+ super(StyleEmbedder, self).__init__()
54
+ self.feature_extractor = FeatureExtractor()
55
+ self.feature_extractor.eval()
56
+ self.avg_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
57
+
58
+ def forward(self, img):
59
+ N = img.shape[0]
60
+ features = self.feature_extractor(self.avg_pool(img))
61
+
62
+ grams = []
63
+ for feature in features:
64
+ gram = gram_matrix(feature)
65
+ grams.append(gram.view(N, -1))
66
+ out = torch.cat(grams, dim=1)
67
+ return out
68
+
69
+
70
+ class PixelNorm(nn.Module):
71
+ def __init__(self):
72
+ super().__init__()
73
+
74
+ def forward(self, input):
75
+ return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)
76
+
77
+
78
+ class EqualLinear(nn.Module):
79
+ def __init__(
80
+ self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None
81
+ ):
82
+ super().__init__()
83
+
84
+ self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
85
+
86
+ if bias:
87
+ self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
88
+
89
+ else:
90
+ self.bias = None
91
+
92
+ self.activation = activation
93
+
94
+ self.scale = (1 / math.sqrt(in_dim)) * lr_mul
95
+ self.lr_mul = lr_mul
96
+
97
+ def forward(self, input):
98
+ if self.activation:
99
+ out = F.linear(input, self.weight * self.scale)
100
+ out = fused_leaky_relu(out, self.bias * self.lr_mul)
101
+
102
+ else:
103
+ out = F.linear(
104
+ input, self.weight * self.scale, bias=self.bias * self.lr_mul
105
+ )
106
+
107
+ return out
108
+
109
+ def __repr__(self):
110
+ return (
111
+ f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
112
+ )
113
+
114
+
115
+ class StyleEncoder(nn.Module):
116
+ def __init__(
117
+ self,
118
+ style_dim=512,
119
+ n_mlp=4,
120
+ ):
121
+ super().__init__()
122
+
123
+ self.style_dim = style_dim
124
+
125
+ e_dim = 610304
126
+ self.embedder = StyleEmbedder()
127
+
128
+ layers = []
129
+
130
+ layers.append(EqualLinear(e_dim, style_dim, lr_mul=1, activation='fused_lrelu'))
131
+ for i in range(n_mlp - 2):
132
+ layers.append(
133
+ EqualLinear(
134
+ style_dim, style_dim, lr_mul=1, activation='fused_lrelu'
135
+ )
136
+ )
137
+ layers.append(EqualLinear(style_dim, style_dim, lr_mul=1, activation=None))
138
+ self.embedder_mlp = nn.Sequential(*layers)
139
+
140
+ def forward(self, image):
141
+ z_embed = self.embedder_mlp(self.embedder(image)) # [N, 512]
142
+ return z_embed
143
+
144
+
145
+ class Projector(nn.Module):
146
+ def __init__(self, style_dim=512, n_mlp=4):
147
+ super().__init__()
148
+
149
+ layers = []
150
+ for i in range(n_mlp - 1):
151
+ layers.append(
152
+ EqualLinear(
153
+ style_dim, style_dim, lr_mul=1, activation='fused_lrelu'
154
+ )
155
+ )
156
+ layers.append(EqualLinear(style_dim, style_dim, lr_mul=1, activation=None))
157
+ self.projector = nn.Sequential(*layers)
158
+
159
+ def forward(self, x):
160
+ return self.projector(x)
op/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
1
+ from .fused_act import FusedLeakyReLU, fused_leaky_relu
2
+ from .upfirdn2d import upfirdn2d
op/fused_act.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ from torch.autograd import Function
7
+ from torch.utils.cpp_extension import load
8
+
9
+
10
+ module_path = os.path.dirname(__file__)
11
+
12
+ cuda_available = torch.cuda.is_available()
13
+
14
+ if cuda_available:
15
+ fused = load(
16
+ "fused",
17
+ sources=[
18
+ os.path.join(module_path, "fused_bias_act.cpp"),
19
+ os.path.join(module_path, "fused_bias_act_kernel.cu"),
20
+ ],
21
+ )
22
+ else:
23
+ fused = None
24
+ print("fused_act.py is running on cpu")
25
+
26
+
27
+ class FusedLeakyReLUFunctionBackward(Function):
28
+ @staticmethod
29
+ def forward(ctx, grad_output, out, negative_slope, scale):
30
+ ctx.save_for_backward(out)
31
+ ctx.negative_slope = negative_slope
32
+ ctx.scale = scale
33
+
34
+ empty = grad_output.new_empty(0)
35
+
36
+ grad_input = fused.fused_bias_act(
37
+ grad_output, empty, out, 3, 1, negative_slope, scale
38
+ )
39
+
40
+ dim = [0]
41
+
42
+ if grad_input.ndim > 2:
43
+ dim += list(range(2, grad_input.ndim))
44
+
45
+ grad_bias = grad_input.sum(dim).detach()
46
+
47
+ return grad_input, grad_bias
48
+
49
+ @staticmethod
50
+ def backward(ctx, gradgrad_input, gradgrad_bias):
51
+ out, = ctx.saved_tensors
52
+ gradgrad_out = fused.fused_bias_act(
53
+ gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale
54
+ )
55
+
56
+ return gradgrad_out, None, None, None
57
+
58
+
59
+ class FusedLeakyReLUFunction(Function):
60
+ @staticmethod
61
+ def forward(ctx, input, bias, negative_slope, scale):
62
+ empty = input.new_empty(0)
63
+ out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale)
64
+ ctx.save_for_backward(out)
65
+ ctx.negative_slope = negative_slope
66
+ ctx.scale = scale
67
+
68
+ return out
69
+
70
+ @staticmethod
71
+ def backward(ctx, grad_output):
72
+ out, = ctx.saved_tensors
73
+
74
+ grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
75
+ grad_output, out, ctx.negative_slope, ctx.scale
76
+ )
77
+
78
+ return grad_input, grad_bias, None, None
79
+
80
+
81
+ class FusedLeakyReLU(nn.Module):
82
+ def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
83
+ super().__init__()
84
+
85
+ self.bias = nn.Parameter(torch.zeros(channel))
86
+ self.negative_slope = negative_slope
87
+ self.scale = scale
88
+
89
+ def forward(self, input):
90
+ return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale)
91
+
92
+
93
+ def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):
94
+ if input.device.type == "cpu":
95
+ rest_dim = [1] * (input.ndim - bias.ndim - 1)
96
+ return (
97
+ F.leaky_relu(
98
+ input + bias.view(1, bias.shape[0], *rest_dim), negative_slope=0.2
99
+ )
100
+ * scale
101
+ )
102
+
103
+ else:
104
+ return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale)
op/fused_bias_act.cpp ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/extension.h>
2
+
3
+
4
+ torch::Tensor fused_bias_act_op(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
5
+ int act, int grad, float alpha, float scale);
6
+
7
+ #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
8
+ #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
9
+ #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
10
+
11
+ torch::Tensor fused_bias_act(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
12
+ int act, int grad, float alpha, float scale) {
13
+ CHECK_CUDA(input);
14
+ CHECK_CUDA(bias);
15
+
16
+ return fused_bias_act_op(input, bias, refer, act, grad, alpha, scale);
17
+ }
18
+
19
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
20
+ m.def("fused_bias_act", &fused_bias_act, "fused bias act (CUDA)");
21
+ }
op/fused_bias_act_kernel.cu ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
2
+ //
3
+ // This work is made available under the Nvidia Source Code License-NC.
4
+ // To view a copy of this license, visit
5
+ // https://nvlabs.github.io/stylegan2/license.html
6
+
7
+ #include <torch/types.h>
8
+
9
+ #include <ATen/ATen.h>
10
+ #include <ATen/AccumulateType.h>
11
+ #include <ATen/cuda/CUDAContext.h>
12
+ #include <ATen/cuda/CUDAApplyUtils.cuh>
13
+
14
+ #include <cuda.h>
15
+ #include <cuda_runtime.h>
16
+
17
+
18
+ template <typename scalar_t>
19
+ static __global__ void fused_bias_act_kernel(scalar_t* out, const scalar_t* p_x, const scalar_t* p_b, const scalar_t* p_ref,
20
+ int act, int grad, scalar_t alpha, scalar_t scale, int loop_x, int size_x, int step_b, int size_b, int use_bias, int use_ref) {
21
+ int xi = blockIdx.x * loop_x * blockDim.x + threadIdx.x;
22
+
23
+ scalar_t zero = 0.0;
24
+
25
+ for (int loop_idx = 0; loop_idx < loop_x && xi < size_x; loop_idx++, xi += blockDim.x) {
26
+ scalar_t x = p_x[xi];
27
+
28
+ if (use_bias) {
29
+ x += p_b[(xi / step_b) % size_b];
30
+ }
31
+
32
+ scalar_t ref = use_ref ? p_ref[xi] : zero;
33
+
34
+ scalar_t y;
35
+
36
+ switch (act * 10 + grad) {
37
+ default:
38
+ case 10: y = x; break;
39
+ case 11: y = x; break;
40
+ case 12: y = 0.0; break;
41
+
42
+ case 30: y = (x > 0.0) ? x : x * alpha; break;
43
+ case 31: y = (ref > 0.0) ? x : x * alpha; break;
44
+ case 32: y = 0.0; break;
45
+ }
46
+
47
+ out[xi] = y * scale;
48
+ }
49
+ }
50
+
51
+
52
+ torch::Tensor fused_bias_act_op(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
53
+ int act, int grad, float alpha, float scale) {
54
+ int curDevice = -1;
55
+ cudaGetDevice(&curDevice);
56
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream(curDevice);
57
+
58
+ auto x = input.contiguous();
59
+ auto b = bias.contiguous();
60
+ auto ref = refer.contiguous();
61
+
62
+ int use_bias = b.numel() ? 1 : 0;
63
+ int use_ref = ref.numel() ? 1 : 0;
64
+
65
+ int size_x = x.numel();
66
+ int size_b = b.numel();
67
+ int step_b = 1;
68
+
69
+ for (int i = 1 + 1; i < x.dim(); i++) {
70
+ step_b *= x.size(i);
71
+ }
72
+
73
+ int loop_x = 4;
74
+ int block_size = 4 * 32;
75
+ int grid_size = (size_x - 1) / (loop_x * block_size) + 1;
76
+
77
+ auto y = torch::empty_like(x);
78
+
79
+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "fused_bias_act_kernel", [&] {
80
+ fused_bias_act_kernel<scalar_t><<<grid_size, block_size, 0, stream>>>(
81
+ y.data_ptr<scalar_t>(),
82
+ x.data_ptr<scalar_t>(),
83
+ b.data_ptr<scalar_t>(),
84
+ ref.data_ptr<scalar_t>(),
85
+ act,
86
+ grad,
87
+ alpha,
88
+ scale,
89
+ loop_x,
90
+ size_x,
91
+ step_b,
92
+ size_b,
93
+ use_bias,
94
+ use_ref
95
+ );
96
+ });
97
+
98
+ return y;
99
+ }
op/upfirdn2d.cpp ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/extension.h>
2
+
3
+
4
+ torch::Tensor upfirdn2d_op(const torch::Tensor& input, const torch::Tensor& kernel,
5
+ int up_x, int up_y, int down_x, int down_y,
6
+ int pad_x0, int pad_x1, int pad_y0, int pad_y1);
7
+
8
+ #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
9
+ #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
10
+ #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
11
+
12
+ torch::Tensor upfirdn2d(const torch::Tensor& input, const torch::Tensor& kernel,
13
+ int up_x, int up_y, int down_x, int down_y,
14
+ int pad_x0, int pad_x1, int pad_y0, int pad_y1) {
15
+ CHECK_CUDA(input);
16
+ CHECK_CUDA(kernel);
17
+
18
+ return upfirdn2d_op(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1);
19
+ }
20
+
21
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
22
+ m.def("upfirdn2d", &upfirdn2d, "upfirdn2d (CUDA)");
23
+ }
op/upfirdn2d.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+ from torch.autograd import Function
6
+ from torch.utils.cpp_extension import load
7
+
8
+
9
+ module_path = os.path.dirname(__file__)
10
+
11
+ cuda_available = torch.cuda.is_available()
12
+
13
+ if cuda_available:
14
+ upfirdn2d_op = load(
15
+ "upfirdn2d",
16
+ sources=[
17
+ os.path.join(module_path, "upfirdn2d.cpp"),
18
+ os.path.join(module_path, "upfirdn2d_kernel.cu"),
19
+ ],
20
+ )
21
+ else:
22
+ fused = None
23
+ print("upfirdn2d.py is running on cpu")
24
+
25
+
26
+ class UpFirDn2dBackward(Function):
27
+ @staticmethod
28
+ def forward(
29
+ ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size
30
+ ):
31
+
32
+ up_x, up_y = up
33
+ down_x, down_y = down
34
+ g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
35
+
36
+ grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
37
+
38
+ grad_input = upfirdn2d_op.upfirdn2d(
39
+ grad_output,
40
+ grad_kernel,
41
+ down_x,
42
+ down_y,
43
+ up_x,
44
+ up_y,
45
+ g_pad_x0,
46
+ g_pad_x1,
47
+ g_pad_y0,
48
+ g_pad_y1,
49
+ )
50
+ grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3])
51
+
52
+ ctx.save_for_backward(kernel)
53
+
54
+ pad_x0, pad_x1, pad_y0, pad_y1 = pad
55
+
56
+ ctx.up_x = up_x
57
+ ctx.up_y = up_y
58
+ ctx.down_x = down_x
59
+ ctx.down_y = down_y
60
+ ctx.pad_x0 = pad_x0
61
+ ctx.pad_x1 = pad_x1
62
+ ctx.pad_y0 = pad_y0
63
+ ctx.pad_y1 = pad_y1
64
+ ctx.in_size = in_size
65
+ ctx.out_size = out_size
66
+
67
+ return grad_input
68
+
69
+ @staticmethod
70
+ def backward(ctx, gradgrad_input):
71
+ kernel, = ctx.saved_tensors
72
+
73
+ gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.in_size[3], 1)
74
+
75
+ gradgrad_out = upfirdn2d_op.upfirdn2d(
76
+ gradgrad_input,
77
+ kernel,
78
+ ctx.up_x,
79
+ ctx.up_y,
80
+ ctx.down_x,
81
+ ctx.down_y,
82
+ ctx.pad_x0,
83
+ ctx.pad_x1,
84
+ ctx.pad_y0,
85
+ ctx.pad_y1,
86
+ )
87
+ # gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.out_size[0], ctx.out_size[1], ctx.in_size[3])
88
+ gradgrad_out = gradgrad_out.view(
89
+ ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]
90
+ )
91
+
92
+ return gradgrad_out, None, None, None, None, None, None, None, None
93
+
94
+
95
+ class UpFirDn2d(Function):
96
+ @staticmethod
97
+ def forward(ctx, input, kernel, up, down, pad):
98
+ up_x, up_y = up
99
+ down_x, down_y = down
100
+ pad_x0, pad_x1, pad_y0, pad_y1 = pad
101
+
102
+ kernel_h, kernel_w = kernel.shape
103
+ batch, channel, in_h, in_w = input.shape
104
+ ctx.in_size = input.shape
105
+
106
+ input = input.reshape(-1, in_h, in_w, 1)
107
+
108
+ ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
109
+
110
+ out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
111
+ out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
112
+ ctx.out_size = (out_h, out_w)
113
+
114
+ ctx.up = (up_x, up_y)
115
+ ctx.down = (down_x, down_y)
116
+ ctx.pad = (pad_x0, pad_x1, pad_y0, pad_y1)
117
+
118
+ g_pad_x0 = kernel_w - pad_x0 - 1
119
+ g_pad_y0 = kernel_h - pad_y0 - 1
120
+ g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
121
+ g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
122
+
123
+ ctx.g_pad = (g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
124
+
125
+ out = upfirdn2d_op.upfirdn2d(
126
+ input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
127
+ )
128
+ # out = out.view(major, out_h, out_w, minor)
129
+ out = out.view(-1, channel, out_h, out_w)
130
+
131
+ return out
132
+
133
+ @staticmethod
134
+ def backward(ctx, grad_output):
135
+ kernel, grad_kernel = ctx.saved_tensors
136
+
137
+ grad_input = UpFirDn2dBackward.apply(
138
+ grad_output,
139
+ kernel,
140
+ grad_kernel,
141
+ ctx.up,
142
+ ctx.down,
143
+ ctx.pad,
144
+ ctx.g_pad,
145
+ ctx.in_size,
146
+ ctx.out_size,
147
+ )
148
+
149
+ return grad_input, None, None, None, None
150
+
151
+
152
+ def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
153
+ if input.device.type == "cpu":
154
+ out = upfirdn2d_native(
155
+ input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]
156
+ )
157
+
158
+ else:
159
+ out = UpFirDn2d.apply(
160
+ input, kernel, (up, up), (down, down), (pad[0], pad[1], pad[0], pad[1])
161
+ )
162
+
163
+ return out
164
+
165
+
166
+ def upfirdn2d_native(
167
+ input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
168
+ ):
169
+ _, channel, in_h, in_w = input.shape
170
+ input = input.reshape(-1, in_h, in_w, 1)
171
+
172
+ _, in_h, in_w, minor = input.shape
173
+ kernel_h, kernel_w = kernel.shape
174
+
175
+ out = input.view(-1, in_h, 1, in_w, 1, minor)
176
+ out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
177
+ out = out.view(-1, in_h * up_y, in_w * up_x, minor)
178
+
179
+ out = F.pad(
180
+ out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]
181
+ )
182
+ out = out[
183
+ :,
184
+ max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0),
185
+ max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0),
186
+ :,
187
+ ]
188
+
189
+ out = out.permute(0, 3, 1, 2)
190
+ out = out.reshape(
191
+ [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]
192
+ )
193
+ w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
194
+ out = F.conv2d(out, w)
195
+ out = out.reshape(
196
+ -1,
197
+ minor,
198
+ in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
199
+ in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
200
+ )
201
+ out = out.permute(0, 2, 3, 1)
202
+ out = out[:, ::down_y, ::down_x, :]
203
+
204
+ out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
205
+ out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
206
+
207
+ return out.view(-1, channel, out_h, out_w)
op/upfirdn2d_kernel.cu ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
2
+ //
3
+ // This work is made available under the Nvidia Source Code License-NC.
4
+ // To view a copy of this license, visit
5
+ // https://nvlabs.github.io/stylegan2/license.html
6
+
7
+ #include <torch/types.h>
8
+
9
+ #include <ATen/ATen.h>
10
+ #include <ATen/AccumulateType.h>
11
+ #include <ATen/cuda/CUDAApplyUtils.cuh>
12
+ #include <ATen/cuda/CUDAContext.h>
13
+
14
+ #include <cuda.h>
15
+ #include <cuda_runtime.h>
16
+
17
+ static __host__ __device__ __forceinline__ int floor_div(int a, int b) {
18
+ int c = a / b;
19
+
20
+ if (c * b > a) {
21
+ c--;
22
+ }
23
+
24
+ return c;
25
+ }
26
+
27
+ struct UpFirDn2DKernelParams {
28
+ int up_x;
29
+ int up_y;
30
+ int down_x;
31
+ int down_y;
32
+ int pad_x0;
33
+ int pad_x1;
34
+ int pad_y0;
35
+ int pad_y1;
36
+
37
+ int major_dim;
38
+ int in_h;
39
+ int in_w;
40
+ int minor_dim;
41
+ int kernel_h;
42
+ int kernel_w;
43
+ int out_h;
44
+ int out_w;
45
+ int loop_major;
46
+ int loop_x;
47
+ };
48
+
49
+ template <typename scalar_t>
50
+ __global__ void upfirdn2d_kernel_large(scalar_t *out, const scalar_t *input,
51
+ const scalar_t *kernel,
52
+ const UpFirDn2DKernelParams p) {
53
+ int minor_idx = blockIdx.x * blockDim.x + threadIdx.x;
54
+ int out_y = minor_idx / p.minor_dim;
55
+ minor_idx -= out_y * p.minor_dim;
56
+ int out_x_base = blockIdx.y * p.loop_x * blockDim.y + threadIdx.y;
57
+ int major_idx_base = blockIdx.z * p.loop_major;
58
+
59
+ if (out_x_base >= p.out_w || out_y >= p.out_h ||
60
+ major_idx_base >= p.major_dim) {
61
+ return;
62
+ }
63
+
64
+ int mid_y = out_y * p.down_y + p.up_y - 1 - p.pad_y0;
65
+ int in_y = min(max(floor_div(mid_y, p.up_y), 0), p.in_h);
66
+ int h = min(max(floor_div(mid_y + p.kernel_h, p.up_y), 0), p.in_h) - in_y;
67
+ int kernel_y = mid_y + p.kernel_h - (in_y + 1) * p.up_y;
68
+
69
+ for (int loop_major = 0, major_idx = major_idx_base;
70
+ loop_major < p.loop_major && major_idx < p.major_dim;
71
+ loop_major++, major_idx++) {
72
+ for (int loop_x = 0, out_x = out_x_base;
73
+ loop_x < p.loop_x && out_x < p.out_w; loop_x++, out_x += blockDim.y) {
74
+ int mid_x = out_x * p.down_x + p.up_x - 1 - p.pad_x0;
75
+ int in_x = min(max(floor_div(mid_x, p.up_x), 0), p.in_w);
76
+ int w = min(max(floor_div(mid_x + p.kernel_w, p.up_x), 0), p.in_w) - in_x;
77
+ int kernel_x = mid_x + p.kernel_w - (in_x + 1) * p.up_x;
78
+
79
+ const scalar_t *x_p =
80
+ &input[((major_idx * p.in_h + in_y) * p.in_w + in_x) * p.minor_dim +
81
+ minor_idx];
82
+ const scalar_t *k_p = &kernel[kernel_y * p.kernel_w + kernel_x];
83
+ int x_px = p.minor_dim;
84
+ int k_px = -p.up_x;
85
+ int x_py = p.in_w * p.minor_dim;
86
+ int k_py = -p.up_y * p.kernel_w;
87
+
88
+ scalar_t v = 0.0f;
89
+
90
+ for (int y = 0; y < h; y++) {
91
+ for (int x = 0; x < w; x++) {
92
+ v += static_cast<scalar_t>(*x_p) * static_cast<scalar_t>(*k_p);
93
+ x_p += x_px;
94
+ k_p += k_px;
95
+ }
96
+
97
+ x_p += x_py - w * x_px;
98
+ k_p += k_py - w * k_px;
99
+ }
100
+
101
+ out[((major_idx * p.out_h + out_y) * p.out_w + out_x) * p.minor_dim +
102
+ minor_idx] = v;
103
+ }
104
+ }
105
+ }
106
+
107
+ template <typename scalar_t, int up_x, int up_y, int down_x, int down_y,
108
+ int kernel_h, int kernel_w, int tile_out_h, int tile_out_w>
109
+ __global__ void upfirdn2d_kernel(scalar_t *out, const scalar_t *input,
110
+ const scalar_t *kernel,
111
+ const UpFirDn2DKernelParams p) {
112
+ const int tile_in_h = ((tile_out_h - 1) * down_y + kernel_h - 1) / up_y + 1;
113
+ const int tile_in_w = ((tile_out_w - 1) * down_x + kernel_w - 1) / up_x + 1;
114
+
115
+ __shared__ volatile float sk[kernel_h][kernel_w];
116
+ __shared__ volatile float sx[tile_in_h][tile_in_w];
117
+
118
+ int minor_idx = blockIdx.x;
119
+ int tile_out_y = minor_idx / p.minor_dim;
120
+ minor_idx -= tile_out_y * p.minor_dim;
121
+ tile_out_y *= tile_out_h;
122
+ int tile_out_x_base = blockIdx.y * p.loop_x * tile_out_w;
123
+ int major_idx_base = blockIdx.z * p.loop_major;
124
+
125
+ if (tile_out_x_base >= p.out_w | tile_out_y >= p.out_h |
126
+ major_idx_base >= p.major_dim) {
127
+ return;
128
+ }
129
+
130
+ for (int tap_idx = threadIdx.x; tap_idx < kernel_h * kernel_w;
131
+ tap_idx += blockDim.x) {
132
+ int ky = tap_idx / kernel_w;
133
+ int kx = tap_idx - ky * kernel_w;
134
+ scalar_t v = 0.0;
135
+
136
+ if (kx < p.kernel_w & ky < p.kernel_h) {
137
+ v = kernel[(p.kernel_h - 1 - ky) * p.kernel_w + (p.kernel_w - 1 - kx)];
138
+ }
139
+
140
+ sk[ky][kx] = v;
141
+ }
142
+
143
+ for (int loop_major = 0, major_idx = major_idx_base;
144
+ loop_major < p.loop_major & major_idx < p.major_dim;
145
+ loop_major++, major_idx++) {
146
+ for (int loop_x = 0, tile_out_x = tile_out_x_base;
147
+ loop_x < p.loop_x & tile_out_x < p.out_w;
148
+ loop_x++, tile_out_x += tile_out_w) {
149
+ int tile_mid_x = tile_out_x * down_x + up_x - 1 - p.pad_x0;
150
+ int tile_mid_y = tile_out_y * down_y + up_y - 1 - p.pad_y0;
151
+ int tile_in_x = floor_div(tile_mid_x, up_x);
152
+ int tile_in_y = floor_div(tile_mid_y, up_y);
153
+
154
+ __syncthreads();
155
+
156
+ for (int in_idx = threadIdx.x; in_idx < tile_in_h * tile_in_w;
157
+ in_idx += blockDim.x) {
158
+ int rel_in_y = in_idx / tile_in_w;
159
+ int rel_in_x = in_idx - rel_in_y * tile_in_w;
160
+ int in_x = rel_in_x + tile_in_x;
161
+ int in_y = rel_in_y + tile_in_y;
162
+
163
+ scalar_t v = 0.0;
164
+
165
+ if (in_x >= 0 & in_y >= 0 & in_x < p.in_w & in_y < p.in_h) {
166
+ v = input[((major_idx * p.in_h + in_y) * p.in_w + in_x) *
167
+ p.minor_dim +
168
+ minor_idx];
169
+ }
170
+
171
+ sx[rel_in_y][rel_in_x] = v;
172
+ }
173
+
174
+ __syncthreads();
175
+ for (int out_idx = threadIdx.x; out_idx < tile_out_h * tile_out_w;
176
+ out_idx += blockDim.x) {
177
+ int rel_out_y = out_idx / tile_out_w;
178
+ int rel_out_x = out_idx - rel_out_y * tile_out_w;
179
+ int out_x = rel_out_x + tile_out_x;
180
+ int out_y = rel_out_y + tile_out_y;
181
+
182
+ int mid_x = tile_mid_x + rel_out_x * down_x;
183
+ int mid_y = tile_mid_y + rel_out_y * down_y;
184
+ int in_x = floor_div(mid_x, up_x);
185
+ int in_y = floor_div(mid_y, up_y);
186
+ int rel_in_x = in_x - tile_in_x;
187
+ int rel_in_y = in_y - tile_in_y;
188
+ int kernel_x = (in_x + 1) * up_x - mid_x - 1;
189
+ int kernel_y = (in_y + 1) * up_y - mid_y - 1;
190
+
191
+ scalar_t v = 0.0;
192
+
193
+ #pragma unroll
194
+ for (int y = 0; y < kernel_h / up_y; y++)
195
+ #pragma unroll
196
+ for (int x = 0; x < kernel_w / up_x; x++)
197
+ v += sx[rel_in_y + y][rel_in_x + x] *
198
+ sk[kernel_y + y * up_y][kernel_x + x * up_x];
199
+
200
+ if (out_x < p.out_w & out_y < p.out_h) {
201
+ out[((major_idx * p.out_h + out_y) * p.out_w + out_x) * p.minor_dim +
202
+ minor_idx] = v;
203
+ }
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ torch::Tensor upfirdn2d_op(const torch::Tensor &input,
210
+ const torch::Tensor &kernel, int up_x, int up_y,
211
+ int down_x, int down_y, int pad_x0, int pad_x1,
212
+ int pad_y0, int pad_y1) {
213
+ int curDevice = -1;
214
+ cudaGetDevice(&curDevice);
215
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream(curDevice);
216
+
217
+ UpFirDn2DKernelParams p;
218
+
219
+ auto x = input.contiguous();
220
+ auto k = kernel.contiguous();
221
+
222
+ p.major_dim = x.size(0);
223
+ p.in_h = x.size(1);
224
+ p.in_w = x.size(2);
225
+ p.minor_dim = x.size(3);
226
+ p.kernel_h = k.size(0);
227
+ p.kernel_w = k.size(1);
228
+ p.up_x = up_x;
229
+ p.up_y = up_y;
230
+ p.down_x = down_x;
231
+ p.down_y = down_y;
232
+ p.pad_x0 = pad_x0;
233
+ p.pad_x1 = pad_x1;
234
+ p.pad_y0 = pad_y0;
235
+ p.pad_y1 = pad_y1;
236
+
237
+ p.out_h = (p.in_h * p.up_y + p.pad_y0 + p.pad_y1 - p.kernel_h + p.down_y) /
238
+ p.down_y;
239
+ p.out_w = (p.in_w * p.up_x + p.pad_x0 + p.pad_x1 - p.kernel_w + p.down_x) /
240
+ p.down_x;
241
+
242
+ auto out =
243
+ at::empty({p.major_dim, p.out_h, p.out_w, p.minor_dim}, x.options());
244
+
245
+ int mode = -1;
246
+
247
+ int tile_out_h = -1;
248
+ int tile_out_w = -1;
249
+
250
+ if (p.up_x == 1 && p.up_y == 1 && p.down_x == 1 && p.down_y == 1 &&
251
+ p.kernel_h <= 4 && p.kernel_w <= 4) {
252
+ mode = 1;
253
+ tile_out_h = 16;
254
+ tile_out_w = 64;
255
+ }
256
+
257
+ if (p.up_x == 1 && p.up_y == 1 && p.down_x == 1 && p.down_y == 1 &&
258
+ p.kernel_h <= 3 && p.kernel_w <= 3) {
259
+ mode = 2;
260
+ tile_out_h = 16;
261
+ tile_out_w = 64;
262
+ }
263
+
264
+ if (p.up_x == 2 && p.up_y == 2 && p.down_x == 1 && p.down_y == 1 &&
265
+ p.kernel_h <= 4 && p.kernel_w <= 4) {
266
+ mode = 3;
267
+ tile_out_h = 16;
268
+ tile_out_w = 64;
269
+ }
270
+
271
+ if (p.up_x == 2 && p.up_y == 2 && p.down_x == 1 && p.down_y == 1 &&
272
+ p.kernel_h <= 2 && p.kernel_w <= 2) {
273
+ mode = 4;
274
+ tile_out_h = 16;
275
+ tile_out_w = 64;
276
+ }
277
+
278
+ if (p.up_x == 1 && p.up_y == 1 && p.down_x == 2 && p.down_y == 2 &&
279
+ p.kernel_h <= 4 && p.kernel_w <= 4) {
280
+ mode = 5;
281
+ tile_out_h = 8;
282
+ tile_out_w = 32;
283
+ }
284
+
285
+ if (p.up_x == 1 && p.up_y == 1 && p.down_x == 2 && p.down_y == 2 &&
286
+ p.kernel_h <= 2 && p.kernel_w <= 2) {
287
+ mode = 6;
288
+ tile_out_h = 8;
289
+ tile_out_w = 32;
290
+ }
291
+
292
+ dim3 block_size;
293
+ dim3 grid_size;
294
+
295
+ if (tile_out_h > 0 && tile_out_w > 0) {
296
+ p.loop_major = (p.major_dim - 1) / 16384 + 1;
297
+ p.loop_x = 1;
298
+ block_size = dim3(32 * 8, 1, 1);
299
+ grid_size = dim3(((p.out_h - 1) / tile_out_h + 1) * p.minor_dim,
300
+ (p.out_w - 1) / (p.loop_x * tile_out_w) + 1,
301
+ (p.major_dim - 1) / p.loop_major + 1);
302
+ } else {
303
+ p.loop_major = (p.major_dim - 1) / 16384 + 1;
304
+ p.loop_x = 4;
305
+ block_size = dim3(4, 32, 1);
306
+ grid_size = dim3((p.out_h * p.minor_dim - 1) / block_size.x + 1,
307
+ (p.out_w - 1) / (p.loop_x * block_size.y) + 1,
308
+ (p.major_dim - 1) / p.loop_major + 1);
309
+ }
310
+
311
+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "upfirdn2d_cuda", [&] {
312
+ switch (mode) {
313
+ case 1:
314
+ upfirdn2d_kernel<scalar_t, 1, 1, 1, 1, 4, 4, 16, 64>
315
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
316
+ x.data_ptr<scalar_t>(),
317
+ k.data_ptr<scalar_t>(), p);
318
+
319
+ break;
320
+
321
+ case 2:
322
+ upfirdn2d_kernel<scalar_t, 1, 1, 1, 1, 3, 3, 16, 64>
323
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
324
+ x.data_ptr<scalar_t>(),
325
+ k.data_ptr<scalar_t>(), p);
326
+
327
+ break;
328
+
329
+ case 3:
330
+ upfirdn2d_kernel<scalar_t, 2, 2, 1, 1, 4, 4, 16, 64>
331
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
332
+ x.data_ptr<scalar_t>(),
333
+ k.data_ptr<scalar_t>(), p);
334
+
335
+ break;
336
+
337
+ case 4:
338
+ upfirdn2d_kernel<scalar_t, 2, 2, 1, 1, 2, 2, 16, 64>
339
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
340
+ x.data_ptr<scalar_t>(),
341
+ k.data_ptr<scalar_t>(), p);
342
+
343
+ break;
344
+
345
+ case 5:
346
+ upfirdn2d_kernel<scalar_t, 1, 1, 2, 2, 4, 4, 8, 32>
347
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
348
+ x.data_ptr<scalar_t>(),
349
+ k.data_ptr<scalar_t>(), p);
350
+
351
+ break;
352
+
353
+ case 6:
354
+ upfirdn2d_kernel<scalar_t, 1, 1, 2, 2, 4, 4, 8, 32>
355
+ <<<grid_size, block_size, 0, stream>>>(out.data_ptr<scalar_t>(),
356
+ x.data_ptr<scalar_t>(),
357
+ k.data_ptr<scalar_t>(), p);
358
+
359
+ break;
360
+
361
+ default:
362
+ upfirdn2d_kernel_large<scalar_t><<<grid_size, block_size, 0, stream>>>(
363
+ out.data_ptr<scalar_t>(), x.data_ptr<scalar_t>(),
364
+ k.data_ptr<scalar_t>(), p);
365
+ }
366
+ });
367
+
368
+ return out;
369
+ }
psp_encoder/__init__.py ADDED
File without changes
psp_encoder/helpers.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import namedtuple
2
+ import torch
3
+ from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module
4
+
5
+ """
6
+ ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
7
+ """
8
+
9
+
10
+ class Flatten(Module):
11
+ def forward(self, input):
12
+ return input.view(input.size(0), -1)
13
+
14
+
15
+ def l2_norm(input, axis=1):
16
+ norm = torch.norm(input, 2, axis, True)
17
+ output = torch.div(input, norm)
18
+ return output
19
+
20
+
21
+ class Bottleneck(namedtuple('Block', ['in_channel', 'depth', 'stride'])):
22
+ """ A named tuple describing a ResNet block. """
23
+
24
+
25
+ def get_block(in_channel, depth, num_units, stride=2):
26
+ return [Bottleneck(in_channel, depth, stride)] + [Bottleneck(depth, depth, 1) for i in range(num_units - 1)]
27
+
28
+
29
+ def get_blocks(num_layers):
30
+ if num_layers == 50:
31
+ blocks = [
32
+ get_block(in_channel=64, depth=64, num_units=3),
33
+ get_block(in_channel=64, depth=128, num_units=4),
34
+ get_block(in_channel=128, depth=256, num_units=14),
35
+ get_block(in_channel=256, depth=512, num_units=3)
36
+ ]
37
+ elif num_layers == 100:
38
+ blocks = [
39
+ get_block(in_channel=64, depth=64, num_units=3),
40
+ get_block(in_channel=64, depth=128, num_units=13),
41
+ get_block(in_channel=128, depth=256, num_units=30),
42
+ get_block(in_channel=256, depth=512, num_units=3)
43
+ ]
44
+ elif num_layers == 152:
45
+ blocks = [
46
+ get_block(in_channel=64, depth=64, num_units=3),
47
+ get_block(in_channel=64, depth=128, num_units=8),
48
+ get_block(in_channel=128, depth=256, num_units=36),
49
+ get_block(in_channel=256, depth=512, num_units=3)
50
+ ]
51
+ else:
52
+ raise ValueError("Invalid number of layers: {}. Must be one of [50, 100, 152]".format(num_layers))
53
+ return blocks
54
+
55
+
56
+ class SEModule(Module):
57
+ def __init__(self, channels, reduction):
58
+ super(SEModule, self).__init__()
59
+ self.avg_pool = AdaptiveAvgPool2d(1)
60
+ self.fc1 = Conv2d(channels, channels // reduction, kernel_size=1, padding=0, bias=False)
61
+ self.relu = ReLU(inplace=True)
62
+ self.fc2 = Conv2d(channels // reduction, channels, kernel_size=1, padding=0, bias=False)
63
+ self.sigmoid = Sigmoid()
64
+
65
+ def forward(self, x):
66
+ module_input = x
67
+ x = self.avg_pool(x)
68
+ x = self.fc1(x)
69
+ x = self.relu(x)
70
+ x = self.fc2(x)
71
+ x = self.sigmoid(x)
72
+ return module_input * x
73
+
74
+
75
+ class bottleneck_IR(Module):
76
+ def __init__(self, in_channel, depth, stride):
77
+ super(bottleneck_IR, self).__init__()
78
+ if in_channel == depth:
79
+ self.shortcut_layer = MaxPool2d(1, stride)
80
+ else:
81
+ self.shortcut_layer = Sequential(
82
+ Conv2d(in_channel, depth, (1, 1), stride, bias=False),
83
+ BatchNorm2d(depth)
84
+ )
85
+ self.res_layer = Sequential(
86
+ BatchNorm2d(in_channel),
87
+ Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False), PReLU(depth),
88
+ Conv2d(depth, depth, (3, 3), stride, 1, bias=False), BatchNorm2d(depth)
89
+ )
90
+
91
+ def forward(self, x):
92
+ shortcut = self.shortcut_layer(x)
93
+ res = self.res_layer(x)
94
+ return res + shortcut
95
+
96
+
97
+ class bottleneck_IR_SE(Module):
98
+ def __init__(self, in_channel, depth, stride):
99
+ super(bottleneck_IR_SE, self).__init__()
100
+ if in_channel == depth:
101
+ self.shortcut_layer = MaxPool2d(1, stride)
102
+ else:
103
+ self.shortcut_layer = Sequential(
104
+ Conv2d(in_channel, depth, (1, 1), stride, bias=False),
105
+ BatchNorm2d(depth)
106
+ )
107
+ self.res_layer = Sequential(
108
+ BatchNorm2d(in_channel),
109
+ Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False),
110
+ PReLU(depth),
111
+ Conv2d(depth, depth, (3, 3), stride, 1, bias=False),
112
+ BatchNorm2d(depth),
113
+ SEModule(depth, 16)
114
+ )
115
+
116
+ def forward(self, x):
117
+ shortcut = self.shortcut_layer(x)
118
+ res = self.res_layer(x)
119
+ return res + shortcut
psp_encoder/psp_encoders.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from torch import nn
5
+ from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
6
+ import math
7
+
8
+ from .helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
9
+
10
+ import sys, os
11
+ sys.path.append(os.path.dirname(__file__) + os.sep + '../')
12
+ from model import EqualLinear
13
+
14
+
15
+ """
16
+ Modified from [pSp](https://github.com/eladrich/pixel2style2pixel)
17
+ """
18
+
19
+
20
+ class GradualStyleBlock(Module):
21
+ def __init__(self, in_c, out_c, spatial):
22
+ super(GradualStyleBlock, self).__init__()
23
+ self.out_c = out_c
24
+ self.spatial = spatial
25
+ num_pools = int(np.log2(spatial))
26
+ modules = []
27
+ modules += [Conv2d(in_c, out_c, kernel_size=3, stride=2, padding=1),
28
+ nn.LeakyReLU()]
29
+ for i in range(num_pools - 1):
30
+ modules += [
31
+ Conv2d(out_c, out_c, kernel_size=3, stride=2, padding=1),
32
+ nn.LeakyReLU()
33
+ ]
34
+ self.convs = nn.Sequential(*modules)
35
+ self.linear = EqualLinear(out_c, out_c, lr_mul=1)
36
+
37
+ def forward(self, x):
38
+ x = self.convs(x)
39
+ x = x.view(-1, self.out_c)
40
+ x = self.linear(x)
41
+ return x
42
+
43
+
44
+ class GradualStyleEncoder(Module):
45
+ def __init__(self, num_layers, mode='ir', n_styles=18):
46
+ super(GradualStyleEncoder, self).__init__()
47
+ assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
48
+ assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
49
+ blocks = get_blocks(num_layers)
50
+ if mode == 'ir':
51
+ unit_module = bottleneck_IR
52
+ elif mode == 'ir_se':
53
+ unit_module = bottleneck_IR_SE
54
+ self.input_layer = Sequential(Conv2d(3, 64, (3, 3), 1, 1, bias=False),
55
+ BatchNorm2d(64),
56
+ PReLU(64))
57
+ modules = []
58
+ for block in blocks:
59
+ for bottleneck in block:
60
+ modules.append(unit_module(bottleneck.in_channel,
61
+ bottleneck.depth,
62
+ bottleneck.stride))
63
+ self.body = Sequential(*modules)
64
+
65
+ self.styles = nn.ModuleList()
66
+ self.style_count = n_styles # opts.n_styles
67
+ self.coarse_ind = 3
68
+ self.middle_ind = 7
69
+ for i in range(self.style_count):
70
+ if i < self.coarse_ind:
71
+ style = GradualStyleBlock(512, 512, 16)
72
+ elif i < self.middle_ind:
73
+ style = GradualStyleBlock(512, 512, 32)
74
+ else:
75
+ style = GradualStyleBlock(512, 512, 64)
76
+ self.styles.append(style)
77
+ self.latlayer1 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0)
78
+ self.latlayer2 = nn.Conv2d(128, 512, kernel_size=1, stride=1, padding=0)
79
+
80
+ def _upsample_add(self, x, y):
81
+ '''Upsample and add two feature maps.
82
+ Args:
83
+ x: (Variable) top feature map to be upsampled.
84
+ y: (Variable) lateral feature map.
85
+ Returns:
86
+ (Variable) added feature map.
87
+ Note in PyTorch, when input size is odd, the upsampled feature map
88
+ with `F.upsample(..., scale_factor=2, mode='nearest')`
89
+ maybe not equal to the lateral feature map size.
90
+ e.g.
91
+ original input size: [N,_,15,15] ->
92
+ conv2d feature map size: [N,_,8,8] ->
93
+ upsampled feature map size: [N,_,16,16]
94
+ So we choose bilinear upsample which supports arbitrary output sizes.
95
+ '''
96
+ _, _, H, W = y.size()
97
+ return F.interpolate(x, size=(H, W), mode='bilinear', align_corners=True) + y
98
+
99
+ def forward(self, x):
100
+ x = self.input_layer(x)
101
+
102
+ latents = []
103
+ modulelist = list(self.body._modules.values())
104
+ for i, l in enumerate(modulelist):
105
+ x = l(x)
106
+ if i == 6:
107
+ c1 = x
108
+ elif i == 20:
109
+ c2 = x
110
+ elif i == 23:
111
+ c3 = x
112
+
113
+ for j in range(self.coarse_ind):
114
+ latents.append(self.styles[j](c3))
115
+
116
+ p2 = self._upsample_add(c3, self.latlayer1(c2))
117
+ for j in range(self.coarse_ind, self.middle_ind):
118
+ latents.append(self.styles[j](p2))
119
+
120
+ p1 = self._upsample_add(p2, self.latlayer2(c1))
121
+ for j in range(self.middle_ind, self.style_count):
122
+ latents.append(self.styles[j](p1))
123
+
124
+ out = torch.stack(latents, dim=1)
125
+ return out
126
+
127
+
128
+ def get_keys(d, name):
129
+ if 'state_dict' in d:
130
+ d = d['state_dict']
131
+ d_filt = {k[len(name) + 1:]: v for k, v in d.items() if k[:len(name)] == name}
132
+ return d_filt
133
+
134
+
135
+ class PSPEncoder(Module):
136
+ def __init__(self, encoder_ckpt_path, output_size=1024):
137
+ super(PSPEncoder, self).__init__()
138
+ n_styles = int(math.log(output_size, 2)) * 2 - 2
139
+ self.encoder = GradualStyleEncoder(50, 'ir_se', n_styles)
140
+
141
+ print('Loading psp encoders weights from irse50!')
142
+ encoder_ckpt = torch.load(encoder_ckpt_path, map_location='cpu')
143
+ self.encoder.load_state_dict(get_keys(encoder_ckpt, 'encoder'), strict=True)
144
+ self.latent_avg = encoder_ckpt['latent_avg'].cuda()
145
+
146
+ self.face_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
147
+
148
+ def forward(self, x):
149
+ x = self.face_pool(x)
150
+ codes = self.encoder(x)
151
+ codes = codes + self.latent_avg.repeat(codes.shape[0], 1, 1)
152
+ return codes
153
+
style_transfer_folder.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+
8
+ from model import Generator
9
+ from psp_encoder.psp_encoders import PSPEncoder
10
+ from utils import ten2cv, cv2ten
11
+ import glob
12
+ import random
13
+
14
+ seed = 0
15
+
16
+ random.seed(seed)
17
+ np.random.seed(seed)
18
+ torch.manual_seed(seed)
19
+ torch.cuda.manual_seed_all(seed)
20
+
21
+
22
+ if __name__ == '__main__':
23
+ device = 'cuda'
24
+
25
+ parser = argparse.ArgumentParser()
26
+
27
+ parser.add_argument('--size', type=int, default=1024)
28
+
29
+ parser.add_argument('--ckpt', type=str, default='', help='path to BlendGAN checkpoint')
30
+ parser.add_argument('--psp_encoder_ckpt', type=str, default='', help='path to psp_encoder checkpoint')
31
+
32
+ parser.add_argument('--style_img_path', type=str, default=None, help='path to style image')
33
+ parser.add_argument('--input_img_path', type=str, default=None, help='path to input image')
34
+ parser.add_argument('--add_weight_index', type=int, default=6)
35
+
36
+ parser.add_argument('--channel_multiplier', type=int, default=2)
37
+ parser.add_argument('--outdir', type=str, default="")
38
+
39
+ args = parser.parse_args()
40
+
41
+ outdir = args.outdir
42
+ if not os.path.exists(outdir):
43
+ os.makedirs(outdir, exist_ok=True)
44
+
45
+ args.latent = 512
46
+ args.n_mlp = 8
47
+
48
+ checkpoint = torch.load(args.ckpt)
49
+ model_dict = checkpoint['g_ema']
50
+ print('ckpt: ', args.ckpt)
51
+
52
+ g_ema = Generator(
53
+ args.size, args.latent, args.n_mlp, channel_multiplier=args.channel_multiplier
54
+ ).to(device)
55
+ g_ema.load_state_dict(model_dict)
56
+ g_ema.eval()
57
+
58
+ psp_encoder = PSPEncoder(args.psp_encoder_ckpt, output_size=args.size).to(device)
59
+ psp_encoder.eval()
60
+
61
+ input_img_paths = sorted(glob.glob(os.path.join(args.input_img_path, '*.*')))
62
+ style_img_paths = sorted(glob.glob(os.path.join(args.style_img_path, '*.*')))[:]
63
+
64
+ num = 0
65
+
66
+ for input_img_path in input_img_paths:
67
+ print(num)
68
+ num += 1
69
+
70
+ name_in = os.path.splitext(os.path.basename(input_img_path))[0]
71
+ img_in = cv2.imread(input_img_path, 1)
72
+ img_in_ten = cv2ten(img_in, device)
73
+ img_in = cv2.resize(img_in, (args.size, args.size))
74
+
75
+ for style_img_path in style_img_paths:
76
+ name_style = os.path.splitext(os.path.basename(style_img_path))[0]
77
+ img_style = cv2.imread(style_img_path, 1)
78
+ img_style_ten = cv2ten(img_style, device)
79
+ img_style = cv2.resize(img_style, (args.size, args.size))
80
+
81
+ with torch.no_grad():
82
+ sample_style = g_ema.get_z_embed(img_style_ten)
83
+ sample_in = psp_encoder(img_in_ten)
84
+ img_out_ten, _ = g_ema([sample_in], z_embed=sample_style, add_weight_index=args.add_weight_index,
85
+ input_is_latent=True, return_latents=False, randomize_noise=False)
86
+ img_out = ten2cv(img_out_ten)
87
+ out = np.concatenate([img_in, img_style, img_out], axis=1)
88
+ # out = img_out
89
+ cv2.imwrite(f'{args.outdir}/{name_in}_v_{name_style}.jpg', out)
90
+
91
+ print('Done!')
92
+
utils.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def cv2ten(img, device):
5
+ img = (img[:, :, ::-1].transpose(2, 0, 1) / 255. - 0.5) / 0.5
6
+ img_ten = torch.from_numpy(img).float().unsqueeze(0).to(device)
7
+ return img_ten
8
+
9
+
10
+ def ten2cv(img_ten, bgr=True):
11
+ img = img_ten.squeeze(0).mul_(0.5).add_(0.5).mul_(255).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()
12
+ if bgr:
13
+ img = img[:, :, ::-1]
14
+ return img
15
+