AK391
commited on
Commit
•
0145b71
1
Parent(s):
99116c0
add files
Browse files- gen_video.py +210 -0
- generate_image_pairs.py +111 -0
- model.py +782 -0
- model_encoder.py +160 -0
- op/__init__.py +2 -0
- op/fused_act.py +104 -0
- op/fused_bias_act.cpp +21 -0
- op/fused_bias_act_kernel.cu +99 -0
- op/upfirdn2d.cpp +23 -0
- op/upfirdn2d.py +207 -0
- op/upfirdn2d_kernel.cu +369 -0
- psp_encoder/__init__.py +0 -0
- psp_encoder/helpers.py +119 -0
- psp_encoder/psp_encoders.py +153 -0
- style_transfer_folder.py +92 -0
- utils.py +15 -0
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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|