Spaces:
Running
on
Zero
Running
on
Zero
Upload 65 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +362 -0
- configs/.DS_Store +0 -0
- configs/inference_1024_v1.0.yaml +103 -0
- configs/inference_512_v1.0.yaml +103 -0
- configs/training_1024_v1.0/config.yaml +166 -0
- configs/training_1024_v1.0/run.sh +37 -0
- configs/training_512_v1.0/config.yaml +166 -0
- configs/training_512_v1.0/run.sh +37 -0
- lvdm/.DS_Store +0 -0
- lvdm/basics.py +100 -0
- lvdm/common.py +94 -0
- lvdm/data/base.py +23 -0
- lvdm/data/webvid.py +202 -0
- lvdm/distributions.py +95 -0
- lvdm/ema.py +76 -0
- lvdm/models/autoencoder.py +275 -0
- lvdm/models/autoencoder_dualref.py +1178 -0
- lvdm/models/ddpm3d.py +1312 -0
- lvdm/models/samplers/ddim.py +317 -0
- lvdm/models/samplers/ddim_multiplecond.py +323 -0
- lvdm/models/utils_diffusion.py +158 -0
- lvdm/modules/attention.py +514 -0
- lvdm/modules/attention_svd.py +759 -0
- lvdm/modules/encoders/condition.py +389 -0
- lvdm/modules/encoders/resampler.py +145 -0
- lvdm/modules/networks/ae_modules.py +856 -0
- lvdm/modules/networks/openaimodel3d.py +603 -0
- lvdm/modules/x_transformer.py +639 -0
- main/callbacks.py +133 -0
- main/trainer.py +168 -0
- main/utils_data.py +136 -0
- main/utils_train.py +173 -0
- prompts/.DS_Store +0 -0
- prompts/1024_interp/74906_1462_frame1.png +0 -0
- prompts/1024_interp/74906_1462_frame3.png +0 -0
- prompts/1024_interp/Japan_v2_2_062266_s2_frame1.png +0 -0
- prompts/1024_interp/Japan_v2_2_062266_s2_frame3.png +0 -0
- prompts/1024_interp/Japan_v2_3_119235_s2_frame1.png +0 -0
- prompts/1024_interp/Japan_v2_3_119235_s2_frame3.png +0 -0
- prompts/1024_interp/interp_1_1.png +0 -0
- prompts/1024_interp/interp_1_2.png +0 -0
- prompts/1024_interp/interp_2_1.png +0 -0
- prompts/1024_interp/interp_2_2.png +0 -0
- prompts/512_interp/74906_1462_frame1.png +0 -0
- prompts/512_interp/74906_1462_frame3.png +0 -0
- prompts/512_interp/Japan_v2_2_062266_s2_frame1.png +0 -0
- prompts/512_interp/Japan_v2_2_062266_s2_frame3.png +0 -0
- prompts/512_interp/Japan_v2_3_119235_s2_frame1.png +0 -0
- prompts/512_interp/Japan_v2_3_119235_s2_frame3.png +0 -0
- prompts/512_interp/prompts.txt +3 -0
app.py
ADDED
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, argparse
|
2 |
+
import sys
|
3 |
+
import gradio as gr
|
4 |
+
# from scripts.gradio.i2v_test_application import Image2Video
|
5 |
+
sys.path.insert(1, os.path.join(sys.path[0], 'lvdm'))
|
6 |
+
import spaces
|
7 |
+
|
8 |
+
|
9 |
+
import os
|
10 |
+
import time
|
11 |
+
from omegaconf import OmegaConf
|
12 |
+
import torch
|
13 |
+
from scripts.evaluation.funcs import load_model_checkpoint, save_videos, batch_ddim_sampling, get_latent_z
|
14 |
+
from utils.utils import instantiate_from_config
|
15 |
+
from huggingface_hub import hf_hub_download
|
16 |
+
from einops import repeat
|
17 |
+
import torchvision.transforms as transforms
|
18 |
+
from pytorch_lightning import seed_everything
|
19 |
+
from einops import rearrange
|
20 |
+
import cv2
|
21 |
+
|
22 |
+
import torch
|
23 |
+
print("cuda available:", torch.cuda.is_available())
|
24 |
+
|
25 |
+
|
26 |
+
from huggingface_hub import snapshot_download
|
27 |
+
import os
|
28 |
+
|
29 |
+
|
30 |
+
|
31 |
+
def download_model():
|
32 |
+
REPO_ID = 'fbnnb/tc_1024'
|
33 |
+
filename_list = ['tc1024_4k.ckpt']
|
34 |
+
tar_dir = './checkpoints/tooncrafter_1024_interp_sketch/'
|
35 |
+
if not os.path.exists(tar_dir):
|
36 |
+
os.makedirs(tar_dir)
|
37 |
+
for filename in filename_list:
|
38 |
+
local_file = os.path.join(tar_dir, filename)
|
39 |
+
if not os.path.exists(local_file):
|
40 |
+
hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir=tar_dir, local_dir_use_symlinks=False)
|
41 |
+
print("downloaded")
|
42 |
+
|
43 |
+
|
44 |
+
def get_latent_z_with_hidden_states(model, videos):
|
45 |
+
b, c, t, h, w = videos.shape
|
46 |
+
x = rearrange(videos, 'b c t h w -> (b t) c h w')
|
47 |
+
encoder_posterior, hidden_states = model.first_stage_model.encode(x, return_hidden_states=True)
|
48 |
+
|
49 |
+
hidden_states_first_last = []
|
50 |
+
### use only the first and last hidden states
|
51 |
+
for hid in hidden_states:
|
52 |
+
hid = rearrange(hid, '(b t) c h w -> b c t h w', t=t)
|
53 |
+
hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2)
|
54 |
+
hidden_states_first_last.append(hid_new)
|
55 |
+
|
56 |
+
z = model.get_first_stage_encoding(encoder_posterior).detach()
|
57 |
+
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
|
58 |
+
return z, hidden_states_first_last
|
59 |
+
|
60 |
+
|
61 |
+
|
62 |
+
def extract_frames(video_path):
|
63 |
+
# 動画ファイルを読み込む
|
64 |
+
cap = cv2.VideoCapture(video_path)
|
65 |
+
|
66 |
+
frame_list = []
|
67 |
+
frame_num = 0
|
68 |
+
|
69 |
+
while True:
|
70 |
+
# フレームを読み込む
|
71 |
+
ret, frame = cap.read()
|
72 |
+
if not ret:
|
73 |
+
break
|
74 |
+
|
75 |
+
# フレームをリストに追加
|
76 |
+
frame_list.append(frame)
|
77 |
+
frame_num += 1
|
78 |
+
|
79 |
+
print("load video length:", len(frame_list))
|
80 |
+
# 動画ファイルを閉じる
|
81 |
+
cap.release()
|
82 |
+
|
83 |
+
return frame_list
|
84 |
+
|
85 |
+
|
86 |
+
resolution = '576_1024'
|
87 |
+
resolution = (576, 1024)
|
88 |
+
download_model()
|
89 |
+
print("after download model")
|
90 |
+
result_dir = "./results/"
|
91 |
+
if not os.path.exists(result_dir):
|
92 |
+
os.mkdir(result_dir)
|
93 |
+
|
94 |
+
#ToonCrafterModel
|
95 |
+
ckpt_path='checkpoints/tooncrafter_1024_interp_sketch/tc1024_4k.ckpt'
|
96 |
+
# ckpt_path="/group/40005/gzhiwang/tc1024_4k.ckpt"
|
97 |
+
config_file='configs/inference_1024_v1.0.yaml'
|
98 |
+
config = OmegaConf.load(config_file)
|
99 |
+
model_config = config.pop("model", OmegaConf.create())
|
100 |
+
model_config['params']['unet_config']['params']['use_checkpoint']=False
|
101 |
+
|
102 |
+
model = instantiate_from_config(model_config)
|
103 |
+
assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"
|
104 |
+
# model = load_model_checkpoint(model, ckpt_path)
|
105 |
+
state = torch.load(ckpt_path, map_location='cpu')
|
106 |
+
if 'state_dict' in state:
|
107 |
+
state = state['state_dict']
|
108 |
+
if 'module' in state:
|
109 |
+
state = state['module']
|
110 |
+
|
111 |
+
missing, unexpected = model.load_state_dict(state, strict=False)
|
112 |
+
print("missing:", missing)
|
113 |
+
print("unexpected:", unexpected)
|
114 |
+
model.eval()
|
115 |
+
|
116 |
+
# cn_model.load_state_dict(load_state_dict(cn_ckpt_path, location='cpu'))
|
117 |
+
# cn_model.eval()
|
118 |
+
|
119 |
+
# model.control_model = cn_model
|
120 |
+
# model_list.append(model)
|
121 |
+
|
122 |
+
save_fps = 8
|
123 |
+
print("resolution:", resolution)
|
124 |
+
print("init done.")
|
125 |
+
|
126 |
+
def transpose_if_needed(tensor):
|
127 |
+
h = tensor.shape[-2]
|
128 |
+
w = tensor.shape[-1]
|
129 |
+
if h > w:
|
130 |
+
tensor = tensor.permute(0, 2, 1)
|
131 |
+
return tensor
|
132 |
+
|
133 |
+
def untranspose(tensor):
|
134 |
+
ndim = tensor.ndim
|
135 |
+
return tensor.transpose(ndim-1, ndim-2)
|
136 |
+
|
137 |
+
@spaces.GPU(duration=200)
|
138 |
+
def get_image(image, sketch, prompt, steps=50, cfg_scale=7.5, eta=1.0, fs=3, seed=123, control_scale=0.6):
|
139 |
+
print("enter fn")
|
140 |
+
# control_frames = extract_frames(frame_guides)
|
141 |
+
print("extract frames")
|
142 |
+
seed_everything(seed)
|
143 |
+
transform = transforms.Compose([
|
144 |
+
transforms.Resize(min(resolution)),
|
145 |
+
transforms.CenterCrop(resolution),
|
146 |
+
])
|
147 |
+
print("before empty cache")
|
148 |
+
torch.cuda.empty_cache()
|
149 |
+
print('start:', prompt, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
|
150 |
+
start = time.time()
|
151 |
+
gpu_id=0
|
152 |
+
if steps > 60:
|
153 |
+
steps = 60
|
154 |
+
|
155 |
+
global model
|
156 |
+
# model = model_list[gpu_id]
|
157 |
+
model = model.cuda()
|
158 |
+
|
159 |
+
batch_size=1
|
160 |
+
channels = model.model.diffusion_model.out_channels
|
161 |
+
frames = model.temporal_length
|
162 |
+
h, w = resolution[0] // 8, resolution[1] // 8
|
163 |
+
noise_shape = [batch_size, channels, frames, h, w]
|
164 |
+
|
165 |
+
# text cond
|
166 |
+
transposed = False
|
167 |
+
with torch.no_grad(), torch.cuda.amp.autocast(dtype=torch.float16):
|
168 |
+
text_emb = model.get_learned_conditioning([prompt])
|
169 |
+
print("before control")
|
170 |
+
#control cond
|
171 |
+
# if frame_guides is not None:
|
172 |
+
# cn_videos = []
|
173 |
+
# for frame in control_frames:
|
174 |
+
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
175 |
+
# frame = cv2.bitwise_not(frame)
|
176 |
+
# cn_tensor = torch.from_numpy(frame).unsqueeze(2).permute(2, 0, 1).float().to(model.device)
|
177 |
+
|
178 |
+
# #cn_tensor = (cn_tensor / 255. - 0.5) * 2
|
179 |
+
# cn_tensor = ( cn_tensor/255.0 )
|
180 |
+
# cn_tensor = transpose_if_needed(cn_tensor)
|
181 |
+
# cn_tensor_resized = transform(cn_tensor) #3,h,w
|
182 |
+
|
183 |
+
# cn_video = cn_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
184 |
+
# cn_videos.append(cn_video)
|
185 |
+
|
186 |
+
# cn_videos = torch.cat(cn_videos, dim=2)
|
187 |
+
# if cn_videos.shape[2] > frames:
|
188 |
+
# idxs = []
|
189 |
+
# for i in range(frames):
|
190 |
+
# index = int((i + 0.5) * cn_videos.shape[2] / frames)
|
191 |
+
# idxs.append(min(index, cn_videos.shape[2] - 1))
|
192 |
+
# cn_videos = cn_videos[:, :, idxs, :, :]
|
193 |
+
# print("cn_videos.shape after slicing", cn_videos.shape)
|
194 |
+
# model_list = []
|
195 |
+
# for model in model_list:
|
196 |
+
# model.control_scale = control_scale
|
197 |
+
# model_list.append(model)
|
198 |
+
|
199 |
+
# else:
|
200 |
+
cn_videos = None
|
201 |
+
|
202 |
+
print("image cond")
|
203 |
+
|
204 |
+
# img cond
|
205 |
+
img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(model.device)
|
206 |
+
input_h, input_w = img_tensor.shape[1:]
|
207 |
+
img_tensor = (img_tensor / 255. - 0.5) * 2
|
208 |
+
img_tensor = transpose_if_needed(img_tensor)
|
209 |
+
|
210 |
+
image_tensor_resized = transform(img_tensor) #3,h,w
|
211 |
+
videos = image_tensor_resized.unsqueeze(0).unsqueeze(2) # bc1hw
|
212 |
+
print("get latent z")
|
213 |
+
# z = get_latent_z(model, videos) #bc,1,hw
|
214 |
+
videos = repeat(videos, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
215 |
+
|
216 |
+
if sketch is not None:
|
217 |
+
img_tensor2 = torch.from_numpy(sketch).permute(2, 0, 1).float().to(model.device)
|
218 |
+
img_tensor2 = (img_tensor2 / 255. - 0.5) * 2
|
219 |
+
img_tensor2 = transpose_if_needed(img_tensor2)
|
220 |
+
image_tensor_resized2 = transform(img_tensor2) #3,h,w
|
221 |
+
videos2 = image_tensor_resized2.unsqueeze(0).unsqueeze(2) # bchw
|
222 |
+
videos2 = repeat(videos2, 'b c t h w -> b c (repeat t) h w', repeat=frames//2)
|
223 |
+
|
224 |
+
videos = torch.cat([videos, videos2], dim=2)
|
225 |
+
else:
|
226 |
+
videos = torch.cat([videos, videos], dim=2)
|
227 |
+
|
228 |
+
z, hs = get_latent_z_with_hidden_states(model, videos)
|
229 |
+
|
230 |
+
img_tensor_repeat = torch.zeros_like(z)
|
231 |
+
|
232 |
+
img_tensor_repeat[:,:,:1,:,:] = z[:,:,:1,:,:]
|
233 |
+
img_tensor_repeat[:,:,-1:,:,:] = z[:,:,-1:,:,:]
|
234 |
+
|
235 |
+
print("image embedder")
|
236 |
+
cond_images = model.embedder(img_tensor.unsqueeze(0)) ## blc
|
237 |
+
img_emb = model.image_proj_model(cond_images)
|
238 |
+
|
239 |
+
imtext_cond = torch.cat([text_emb, img_emb], dim=1)
|
240 |
+
|
241 |
+
fs = torch.tensor([fs], dtype=torch.long, device=model.device)
|
242 |
+
# print("cn videos:",cn_videos.shape, "img emb:", img_emb.shape)
|
243 |
+
cond = {"c_crossattn": [imtext_cond], "fs": fs, "c_concat": [img_tensor_repeat], "control_cond": cn_videos}
|
244 |
+
|
245 |
+
print("before sample loop")
|
246 |
+
## inference
|
247 |
+
batch_samples = batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=steps, ddim_eta=eta, cfg_scale=cfg_scale, hs=hs)
|
248 |
+
|
249 |
+
## remove the last frame
|
250 |
+
# if image2 is None:
|
251 |
+
batch_samples = batch_samples[:,:,:,:-1,...]
|
252 |
+
## b,samples,c,t,h,w
|
253 |
+
prompt_str = prompt.replace("/", "_slash_") if "/" in prompt else prompt
|
254 |
+
prompt_str = prompt_str.replace(" ", "_") if " " in prompt else prompt_str
|
255 |
+
prompt_str=prompt_str[:40]
|
256 |
+
if len(prompt_str) == 0:
|
257 |
+
prompt_str = 'empty_prompt'
|
258 |
+
|
259 |
+
global result_dir
|
260 |
+
global save_fps
|
261 |
+
if input_h > input_w:
|
262 |
+
batch_samples = untranspose(batch_samples)
|
263 |
+
|
264 |
+
save_videos(batch_samples, result_dir, filenames=[prompt_str], fps=save_fps)
|
265 |
+
print(f"Saved in {prompt_str}. Time used: {(time.time() - start):.2f} seconds")
|
266 |
+
model = model.cpu()
|
267 |
+
saved_result_dir = os.path.join(result_dir, f"{prompt_str}.mp4")
|
268 |
+
print("result saved to:", saved_result_dir)
|
269 |
+
return saved_result_dir
|
270 |
+
|
271 |
+
|
272 |
+
# @spaces.GPU
|
273 |
+
|
274 |
+
|
275 |
+
|
276 |
+
# i2v_examples_interp_1024 = [
|
277 |
+
# ['prompts/1024_interp/frame_000000.jpg', 'prompts/1024_interp/frame_000041.jpg', 'a cat is eating', 50, 7.5, 1.0, 10, 123]
|
278 |
+
# ]
|
279 |
+
|
280 |
+
i2v_examples_interp_1024 = [
|
281 |
+
['prompts/1024_interp/hall_first.jpg', 'prompts/1024_interp/hall_sketch.jpg',
|
282 |
+
'At the start, a still image of a wooden hallway with arched arches, doors, and various furniture. The scene then transitions to an animated version of the hallway, showcasing more details like a bookshelf and a window.',
|
283 |
+
50, 7.5, 1.0, 10, 123]
|
284 |
+
]
|
285 |
+
|
286 |
+
|
287 |
+
|
288 |
+
|
289 |
+
def dynamicrafter_demo(result_dir='./tmp/', res=1024):
|
290 |
+
if res == 1024:
|
291 |
+
resolution = '576_1024'
|
292 |
+
css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height:576px}"""
|
293 |
+
elif res == 512:
|
294 |
+
resolution = '320_512'
|
295 |
+
css = """#input_img {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px} #input_img2 {max-width: 512px !important} #output_vid {max-width: 512px; max-height: 320px}"""
|
296 |
+
elif res == 256:
|
297 |
+
resolution = '256_256'
|
298 |
+
css = """#input_img {max-width: 256px !important} #output_vid {max-width: 256px; max-height: 256px}"""
|
299 |
+
else:
|
300 |
+
raise NotImplementedError(f"Unsupported resolution: {res}")
|
301 |
+
# image2video = Image2Video(result_dir, resolution=resolution)
|
302 |
+
with gr.Blocks(analytics_enabled=False, css=css) as dynamicrafter_iface:
|
303 |
+
|
304 |
+
|
305 |
+
|
306 |
+
with gr.Tab(label='ToonCrafter_576x1024'):
|
307 |
+
with gr.Column():
|
308 |
+
with gr.Row():
|
309 |
+
with gr.Column():
|
310 |
+
with gr.Row():
|
311 |
+
i2v_input_image = gr.Image(label="Input Image1",elem_id="input_img")
|
312 |
+
# frame_guides = gr.Video(label="Input Guidance",elem_id="input_guidance", autoplay=True,show_share_button=True)
|
313 |
+
with gr.Row():
|
314 |
+
i2v_input_text = gr.Text(label='Prompts')
|
315 |
+
with gr.Row():
|
316 |
+
i2v_seed = gr.Slider(label='Random Seed', minimum=0, maximum=50000, step=1, value=123)
|
317 |
+
i2v_eta = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label='ETA', value=1.0, elem_id="i2v_eta")
|
318 |
+
i2v_cfg_scale = gr.Slider(minimum=1.0, maximum=15.0, step=0.5, label='CFG Scale', value=7.5, elem_id="i2v_cfg_scale")
|
319 |
+
with gr.Row():
|
320 |
+
i2v_steps = gr.Slider(minimum=1, maximum=60, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)
|
321 |
+
i2v_motion = gr.Slider(minimum=5, maximum=30, step=1, elem_id="i2v_motion", label="FPS", value=10)
|
322 |
+
control_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, elem_id="i2v_ctrl_scale", label="control_scale", value=0.6)
|
323 |
+
i2v_end_btn = gr.Button("Generate")
|
324 |
+
with gr.Column():
|
325 |
+
with gr.Row():
|
326 |
+
i2v_input_sketch = gr.Image(label="Input Image2",elem_id="input_img2")
|
327 |
+
with gr.Row():
|
328 |
+
i2v_output_video = gr.Video(label="Generated Video",elem_id="output_vid",autoplay=True,show_share_button=True)
|
329 |
+
|
330 |
+
gr.Examples(examples=i2v_examples_interp_1024,
|
331 |
+
inputs=[i2v_input_image, i2v_input_sketch, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, control_scale],
|
332 |
+
outputs=[i2v_output_video],
|
333 |
+
fn = get_image,
|
334 |
+
cache_examples=False,
|
335 |
+
)
|
336 |
+
i2v_end_btn.click(inputs=[i2v_input_image, i2v_input_sketch, i2v_input_text, i2v_steps, i2v_cfg_scale, i2v_eta, i2v_motion, i2v_seed, control_scale],
|
337 |
+
outputs=[i2v_output_video],
|
338 |
+
fn = get_image
|
339 |
+
)
|
340 |
+
|
341 |
+
|
342 |
+
return dynamicrafter_iface
|
343 |
+
|
344 |
+
|
345 |
+
def get_parser():
|
346 |
+
parser = argparse.ArgumentParser()
|
347 |
+
return parser
|
348 |
+
|
349 |
+
|
350 |
+
if __name__ == "__main__":
|
351 |
+
parser = get_parser()
|
352 |
+
args = parser.parse_args()
|
353 |
+
|
354 |
+
result_dir = os.path.join('./', 'results')
|
355 |
+
dynamicrafter_iface = dynamicrafter_demo(result_dir)
|
356 |
+
dynamicrafter_iface.queue(max_size=12)
|
357 |
+
print("launching...")
|
358 |
+
# dynamicrafter_iface.launch(max_threads=1, share=True)
|
359 |
+
|
360 |
+
dynamicrafter_iface.launch(server_name='0.0.0.0', server_port=12345)
|
361 |
+
# dynamicrafter_iface.launch()
|
362 |
+
# print("launched...")
|
configs/.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
configs/inference_1024_v1.0.yaml
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentVisualDiffusion
|
3 |
+
params:
|
4 |
+
rescale_betas_zero_snr: True
|
5 |
+
parameterization: "v"
|
6 |
+
linear_start: 0.00085
|
7 |
+
linear_end: 0.012
|
8 |
+
num_timesteps_cond: 1
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: video
|
11 |
+
cond_stage_key: caption
|
12 |
+
cond_stage_trainable: False
|
13 |
+
conditioning_key: hybrid
|
14 |
+
image_size: [72, 128]
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: False
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: False
|
19 |
+
uncond_type: 'empty_seq'
|
20 |
+
use_dynamic_rescale: true
|
21 |
+
base_scale: 0.7
|
22 |
+
fps_condition_type: 'fps'
|
23 |
+
perframe_ae: True
|
24 |
+
loop_video: true
|
25 |
+
unet_config:
|
26 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
27 |
+
params:
|
28 |
+
in_channels: 8
|
29 |
+
out_channels: 4
|
30 |
+
model_channels: 320
|
31 |
+
attention_resolutions:
|
32 |
+
- 4
|
33 |
+
- 2
|
34 |
+
- 1
|
35 |
+
num_res_blocks: 2
|
36 |
+
channel_mult:
|
37 |
+
- 1
|
38 |
+
- 2
|
39 |
+
- 4
|
40 |
+
- 4
|
41 |
+
dropout: 0.1
|
42 |
+
num_head_channels: 64
|
43 |
+
transformer_depth: 1
|
44 |
+
context_dim: 1024
|
45 |
+
use_linear: true
|
46 |
+
use_checkpoint: True
|
47 |
+
temporal_conv: True
|
48 |
+
temporal_attention: True
|
49 |
+
temporal_selfatt_only: true
|
50 |
+
use_relative_position: false
|
51 |
+
use_causal_attention: False
|
52 |
+
temporal_length: 16
|
53 |
+
addition_attention: true
|
54 |
+
image_cross_attention: true
|
55 |
+
default_fs: 24
|
56 |
+
fs_condition: true
|
57 |
+
|
58 |
+
first_stage_config:
|
59 |
+
target: lvdm.models.autoencoder.AutoencoderKL_Dualref
|
60 |
+
params:
|
61 |
+
embed_dim: 4
|
62 |
+
monitor: val/rec_loss
|
63 |
+
ddconfig:
|
64 |
+
double_z: True
|
65 |
+
z_channels: 4
|
66 |
+
resolution: 256
|
67 |
+
in_channels: 3
|
68 |
+
out_ch: 3
|
69 |
+
ch: 128
|
70 |
+
ch_mult:
|
71 |
+
- 1
|
72 |
+
- 2
|
73 |
+
- 4
|
74 |
+
- 4
|
75 |
+
num_res_blocks: 2
|
76 |
+
attn_resolutions: []
|
77 |
+
dropout: 0.0
|
78 |
+
lossconfig:
|
79 |
+
target: torch.nn.Identity
|
80 |
+
|
81 |
+
cond_stage_config:
|
82 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
83 |
+
params:
|
84 |
+
freeze: true
|
85 |
+
layer: "penultimate"
|
86 |
+
|
87 |
+
img_cond_stage_config:
|
88 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
|
89 |
+
params:
|
90 |
+
freeze: true
|
91 |
+
|
92 |
+
image_proj_stage_config:
|
93 |
+
target: lvdm.modules.encoders.resampler.Resampler
|
94 |
+
params:
|
95 |
+
dim: 1024
|
96 |
+
depth: 4
|
97 |
+
dim_head: 64
|
98 |
+
heads: 12
|
99 |
+
num_queries: 16
|
100 |
+
embedding_dim: 1280
|
101 |
+
output_dim: 1024
|
102 |
+
ff_mult: 4
|
103 |
+
video_length: 16
|
configs/inference_512_v1.0.yaml
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
target: lvdm.models.ddpm3d.LatentVisualDiffusion
|
3 |
+
params:
|
4 |
+
rescale_betas_zero_snr: True
|
5 |
+
parameterization: "v"
|
6 |
+
linear_start: 0.00085
|
7 |
+
linear_end: 0.012
|
8 |
+
num_timesteps_cond: 1
|
9 |
+
timesteps: 1000
|
10 |
+
first_stage_key: video
|
11 |
+
cond_stage_key: caption
|
12 |
+
cond_stage_trainable: False
|
13 |
+
conditioning_key: hybrid
|
14 |
+
image_size: [40, 64]
|
15 |
+
channels: 4
|
16 |
+
scale_by_std: False
|
17 |
+
scale_factor: 0.18215
|
18 |
+
use_ema: False
|
19 |
+
uncond_type: 'empty_seq'
|
20 |
+
use_dynamic_rescale: true
|
21 |
+
base_scale: 0.7
|
22 |
+
fps_condition_type: 'fps'
|
23 |
+
perframe_ae: True
|
24 |
+
loop_video: true
|
25 |
+
unet_config:
|
26 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
27 |
+
params:
|
28 |
+
in_channels: 8
|
29 |
+
out_channels: 4
|
30 |
+
model_channels: 320
|
31 |
+
attention_resolutions:
|
32 |
+
- 4
|
33 |
+
- 2
|
34 |
+
- 1
|
35 |
+
num_res_blocks: 2
|
36 |
+
channel_mult:
|
37 |
+
- 1
|
38 |
+
- 2
|
39 |
+
- 4
|
40 |
+
- 4
|
41 |
+
dropout: 0.1
|
42 |
+
num_head_channels: 64
|
43 |
+
transformer_depth: 1
|
44 |
+
context_dim: 1024
|
45 |
+
use_linear: true
|
46 |
+
use_checkpoint: True
|
47 |
+
temporal_conv: True
|
48 |
+
temporal_attention: True
|
49 |
+
temporal_selfatt_only: true
|
50 |
+
use_relative_position: false
|
51 |
+
use_causal_attention: False
|
52 |
+
temporal_length: 16
|
53 |
+
addition_attention: true
|
54 |
+
image_cross_attention: true
|
55 |
+
default_fs: 24
|
56 |
+
fs_condition: true
|
57 |
+
|
58 |
+
first_stage_config:
|
59 |
+
target: lvdm.models.autoencoder.AutoencoderKL_Dualref
|
60 |
+
params:
|
61 |
+
embed_dim: 4
|
62 |
+
monitor: val/rec_loss
|
63 |
+
ddconfig:
|
64 |
+
double_z: True
|
65 |
+
z_channels: 4
|
66 |
+
resolution: 256
|
67 |
+
in_channels: 3
|
68 |
+
out_ch: 3
|
69 |
+
ch: 128
|
70 |
+
ch_mult:
|
71 |
+
- 1
|
72 |
+
- 2
|
73 |
+
- 4
|
74 |
+
- 4
|
75 |
+
num_res_blocks: 2
|
76 |
+
attn_resolutions: []
|
77 |
+
dropout: 0.0
|
78 |
+
lossconfig:
|
79 |
+
target: torch.nn.Identity
|
80 |
+
|
81 |
+
cond_stage_config:
|
82 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
83 |
+
params:
|
84 |
+
freeze: true
|
85 |
+
layer: "penultimate"
|
86 |
+
|
87 |
+
img_cond_stage_config:
|
88 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
|
89 |
+
params:
|
90 |
+
freeze: true
|
91 |
+
|
92 |
+
image_proj_stage_config:
|
93 |
+
target: lvdm.modules.encoders.resampler.Resampler
|
94 |
+
params:
|
95 |
+
dim: 1024
|
96 |
+
depth: 4
|
97 |
+
dim_head: 64
|
98 |
+
heads: 12
|
99 |
+
num_queries: 16
|
100 |
+
embedding_dim: 1280
|
101 |
+
output_dim: 1024
|
102 |
+
ff_mult: 4
|
103 |
+
video_length: 16
|
configs/training_1024_v1.0/config.yaml
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
pretrained_checkpoint: checkpoints/dynamicrafter_1024_v1/model.ckpt
|
3 |
+
base_learning_rate: 1.0e-05
|
4 |
+
scale_lr: False
|
5 |
+
target: lvdm.models.ddpm3d.LatentVisualDiffusion
|
6 |
+
params:
|
7 |
+
rescale_betas_zero_snr: True
|
8 |
+
parameterization: "v"
|
9 |
+
linear_start: 0.00085
|
10 |
+
linear_end: 0.012
|
11 |
+
num_timesteps_cond: 1
|
12 |
+
log_every_t: 200
|
13 |
+
timesteps: 1000
|
14 |
+
first_stage_key: video
|
15 |
+
cond_stage_key: caption
|
16 |
+
cond_stage_trainable: False
|
17 |
+
image_proj_model_trainable: True
|
18 |
+
conditioning_key: hybrid
|
19 |
+
image_size: [72, 128]
|
20 |
+
channels: 4
|
21 |
+
scale_by_std: False
|
22 |
+
scale_factor: 0.18215
|
23 |
+
use_ema: False
|
24 |
+
uncond_prob: 0.05
|
25 |
+
uncond_type: 'empty_seq'
|
26 |
+
rand_cond_frame: true
|
27 |
+
use_dynamic_rescale: true
|
28 |
+
base_scale: 0.3
|
29 |
+
fps_condition_type: 'fps'
|
30 |
+
perframe_ae: True
|
31 |
+
|
32 |
+
unet_config:
|
33 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
34 |
+
params:
|
35 |
+
in_channels: 8
|
36 |
+
out_channels: 4
|
37 |
+
model_channels: 320
|
38 |
+
attention_resolutions:
|
39 |
+
- 4
|
40 |
+
- 2
|
41 |
+
- 1
|
42 |
+
num_res_blocks: 2
|
43 |
+
channel_mult:
|
44 |
+
- 1
|
45 |
+
- 2
|
46 |
+
- 4
|
47 |
+
- 4
|
48 |
+
dropout: 0.1
|
49 |
+
num_head_channels: 64
|
50 |
+
transformer_depth: 1
|
51 |
+
context_dim: 1024
|
52 |
+
use_linear: true
|
53 |
+
use_checkpoint: True
|
54 |
+
temporal_conv: True
|
55 |
+
temporal_attention: True
|
56 |
+
temporal_selfatt_only: true
|
57 |
+
use_relative_position: false
|
58 |
+
use_causal_attention: False
|
59 |
+
temporal_length: 16
|
60 |
+
addition_attention: true
|
61 |
+
image_cross_attention: true
|
62 |
+
default_fs: 10
|
63 |
+
fs_condition: true
|
64 |
+
|
65 |
+
first_stage_config:
|
66 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
67 |
+
params:
|
68 |
+
embed_dim: 4
|
69 |
+
monitor: val/rec_loss
|
70 |
+
ddconfig:
|
71 |
+
double_z: True
|
72 |
+
z_channels: 4
|
73 |
+
resolution: 256
|
74 |
+
in_channels: 3
|
75 |
+
out_ch: 3
|
76 |
+
ch: 128
|
77 |
+
ch_mult:
|
78 |
+
- 1
|
79 |
+
- 2
|
80 |
+
- 4
|
81 |
+
- 4
|
82 |
+
num_res_blocks: 2
|
83 |
+
attn_resolutions: []
|
84 |
+
dropout: 0.0
|
85 |
+
lossconfig:
|
86 |
+
target: torch.nn.Identity
|
87 |
+
|
88 |
+
cond_stage_config:
|
89 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
90 |
+
params:
|
91 |
+
freeze: true
|
92 |
+
layer: "penultimate"
|
93 |
+
|
94 |
+
img_cond_stage_config:
|
95 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
|
96 |
+
params:
|
97 |
+
freeze: true
|
98 |
+
|
99 |
+
image_proj_stage_config:
|
100 |
+
target: lvdm.modules.encoders.resampler.Resampler
|
101 |
+
params:
|
102 |
+
dim: 1024
|
103 |
+
depth: 4
|
104 |
+
dim_head: 64
|
105 |
+
heads: 12
|
106 |
+
num_queries: 16
|
107 |
+
embedding_dim: 1280
|
108 |
+
output_dim: 1024
|
109 |
+
ff_mult: 4
|
110 |
+
video_length: 16
|
111 |
+
|
112 |
+
data:
|
113 |
+
target: utils_data.DataModuleFromConfig
|
114 |
+
params:
|
115 |
+
batch_size: 1
|
116 |
+
num_workers: 12
|
117 |
+
wrap: false
|
118 |
+
train:
|
119 |
+
target: lvdm.data.webvid.WebVid
|
120 |
+
params:
|
121 |
+
data_dir: <WebVid10M DATA>
|
122 |
+
meta_path: <.csv FILE>
|
123 |
+
video_length: 16
|
124 |
+
frame_stride: 6
|
125 |
+
load_raw_resolution: true
|
126 |
+
resolution: [576, 1024]
|
127 |
+
spatial_transform: resize_center_crop
|
128 |
+
random_fs: true ## if true, we uniformly sample fs with max_fs=frame_stride (above)
|
129 |
+
|
130 |
+
lightning:
|
131 |
+
precision: 16
|
132 |
+
# strategy: deepspeed_stage_2
|
133 |
+
trainer:
|
134 |
+
benchmark: True
|
135 |
+
accumulate_grad_batches: 2
|
136 |
+
max_steps: 100000
|
137 |
+
# logger
|
138 |
+
log_every_n_steps: 50
|
139 |
+
# val
|
140 |
+
val_check_interval: 0.5
|
141 |
+
gradient_clip_algorithm: 'norm'
|
142 |
+
gradient_clip_val: 0.5
|
143 |
+
callbacks:
|
144 |
+
model_checkpoint:
|
145 |
+
target: pytorch_lightning.callbacks.ModelCheckpoint
|
146 |
+
params:
|
147 |
+
every_n_train_steps: 9000 #1000
|
148 |
+
filename: "{epoch}-{step}"
|
149 |
+
save_weights_only: True
|
150 |
+
metrics_over_trainsteps_checkpoint:
|
151 |
+
target: pytorch_lightning.callbacks.ModelCheckpoint
|
152 |
+
params:
|
153 |
+
filename: '{epoch}-{step}'
|
154 |
+
save_weights_only: True
|
155 |
+
every_n_train_steps: 10000 #20000 # 3s/step*2w=
|
156 |
+
batch_logger:
|
157 |
+
target: callbacks.ImageLogger
|
158 |
+
params:
|
159 |
+
batch_frequency: 500
|
160 |
+
to_local: False
|
161 |
+
max_images: 8
|
162 |
+
log_images_kwargs:
|
163 |
+
ddim_steps: 50
|
164 |
+
unconditional_guidance_scale: 7.5
|
165 |
+
timestep_spacing: uniform_trailing
|
166 |
+
guidance_rescale: 0.7
|
configs/training_1024_v1.0/run.sh
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# NCCL configuration
|
2 |
+
# export NCCL_DEBUG=INFO
|
3 |
+
# export NCCL_IB_DISABLE=0
|
4 |
+
# export NCCL_IB_GID_INDEX=3
|
5 |
+
# export NCCL_NET_GDR_LEVEL=3
|
6 |
+
# export NCCL_TOPO_FILE=/tmp/topo.txt
|
7 |
+
|
8 |
+
# args
|
9 |
+
name="training_1024_v1.0"
|
10 |
+
config_file=configs/${name}/config.yaml
|
11 |
+
|
12 |
+
# save root dir for logs, checkpoints, tensorboard record, etc.
|
13 |
+
save_root="<YOUR_SAVE_ROOT_DIR>"
|
14 |
+
|
15 |
+
mkdir -p $save_root/$name
|
16 |
+
|
17 |
+
## run
|
18 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch \
|
19 |
+
--nproc_per_node=$HOST_GPU_NUM --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
|
20 |
+
./main/trainer.py \
|
21 |
+
--base $config_file \
|
22 |
+
--train \
|
23 |
+
--name $name \
|
24 |
+
--logdir $save_root \
|
25 |
+
--devices $HOST_GPU_NUM \
|
26 |
+
lightning.trainer.num_nodes=1
|
27 |
+
|
28 |
+
## debugging
|
29 |
+
# CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch \
|
30 |
+
# --nproc_per_node=4 --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
|
31 |
+
# ./main/trainer.py \
|
32 |
+
# --base $config_file \
|
33 |
+
# --train \
|
34 |
+
# --name $name \
|
35 |
+
# --logdir $save_root \
|
36 |
+
# --devices 4 \
|
37 |
+
# lightning.trainer.num_nodes=1
|
configs/training_512_v1.0/config.yaml
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
pretrained_checkpoint: checkpoints/dynamicrafter_512_v1/model.ckpt
|
3 |
+
base_learning_rate: 1.0e-05
|
4 |
+
scale_lr: False
|
5 |
+
target: lvdm.models.ddpm3d.LatentVisualDiffusion
|
6 |
+
params:
|
7 |
+
rescale_betas_zero_snr: True
|
8 |
+
parameterization: "v"
|
9 |
+
linear_start: 0.00085
|
10 |
+
linear_end: 0.012
|
11 |
+
num_timesteps_cond: 1
|
12 |
+
log_every_t: 200
|
13 |
+
timesteps: 1000
|
14 |
+
first_stage_key: video
|
15 |
+
cond_stage_key: caption
|
16 |
+
cond_stage_trainable: False
|
17 |
+
image_proj_model_trainable: True
|
18 |
+
conditioning_key: hybrid
|
19 |
+
image_size: [40, 64]
|
20 |
+
channels: 4
|
21 |
+
scale_by_std: False
|
22 |
+
scale_factor: 0.18215
|
23 |
+
use_ema: False
|
24 |
+
uncond_prob: 0.05
|
25 |
+
uncond_type: 'empty_seq'
|
26 |
+
rand_cond_frame: true
|
27 |
+
use_dynamic_rescale: true
|
28 |
+
base_scale: 0.7
|
29 |
+
fps_condition_type: 'fps'
|
30 |
+
perframe_ae: True
|
31 |
+
|
32 |
+
unet_config:
|
33 |
+
target: lvdm.modules.networks.openaimodel3d.UNetModel
|
34 |
+
params:
|
35 |
+
in_channels: 8
|
36 |
+
out_channels: 4
|
37 |
+
model_channels: 320
|
38 |
+
attention_resolutions:
|
39 |
+
- 4
|
40 |
+
- 2
|
41 |
+
- 1
|
42 |
+
num_res_blocks: 2
|
43 |
+
channel_mult:
|
44 |
+
- 1
|
45 |
+
- 2
|
46 |
+
- 4
|
47 |
+
- 4
|
48 |
+
dropout: 0.1
|
49 |
+
num_head_channels: 64
|
50 |
+
transformer_depth: 1
|
51 |
+
context_dim: 1024
|
52 |
+
use_linear: true
|
53 |
+
use_checkpoint: True
|
54 |
+
temporal_conv: True
|
55 |
+
temporal_attention: True
|
56 |
+
temporal_selfatt_only: true
|
57 |
+
use_relative_position: false
|
58 |
+
use_causal_attention: False
|
59 |
+
temporal_length: 16
|
60 |
+
addition_attention: true
|
61 |
+
image_cross_attention: true
|
62 |
+
default_fs: 10
|
63 |
+
fs_condition: true
|
64 |
+
|
65 |
+
first_stage_config:
|
66 |
+
target: lvdm.models.autoencoder.AutoencoderKL
|
67 |
+
params:
|
68 |
+
embed_dim: 4
|
69 |
+
monitor: val/rec_loss
|
70 |
+
ddconfig:
|
71 |
+
double_z: True
|
72 |
+
z_channels: 4
|
73 |
+
resolution: 256
|
74 |
+
in_channels: 3
|
75 |
+
out_ch: 3
|
76 |
+
ch: 128
|
77 |
+
ch_mult:
|
78 |
+
- 1
|
79 |
+
- 2
|
80 |
+
- 4
|
81 |
+
- 4
|
82 |
+
num_res_blocks: 2
|
83 |
+
attn_resolutions: []
|
84 |
+
dropout: 0.0
|
85 |
+
lossconfig:
|
86 |
+
target: torch.nn.Identity
|
87 |
+
|
88 |
+
cond_stage_config:
|
89 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
|
90 |
+
params:
|
91 |
+
freeze: true
|
92 |
+
layer: "penultimate"
|
93 |
+
|
94 |
+
img_cond_stage_config:
|
95 |
+
target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedderV2
|
96 |
+
params:
|
97 |
+
freeze: true
|
98 |
+
|
99 |
+
image_proj_stage_config:
|
100 |
+
target: lvdm.modules.encoders.resampler.Resampler
|
101 |
+
params:
|
102 |
+
dim: 1024
|
103 |
+
depth: 4
|
104 |
+
dim_head: 64
|
105 |
+
heads: 12
|
106 |
+
num_queries: 16
|
107 |
+
embedding_dim: 1280
|
108 |
+
output_dim: 1024
|
109 |
+
ff_mult: 4
|
110 |
+
video_length: 16
|
111 |
+
|
112 |
+
data:
|
113 |
+
target: utils_data.DataModuleFromConfig
|
114 |
+
params:
|
115 |
+
batch_size: 2
|
116 |
+
num_workers: 12
|
117 |
+
wrap: false
|
118 |
+
train:
|
119 |
+
target: lvdm.data.webvid.WebVid
|
120 |
+
params:
|
121 |
+
data_dir: <WebVid10M DATA>
|
122 |
+
meta_path: <.csv FILE>
|
123 |
+
video_length: 16
|
124 |
+
frame_stride: 6
|
125 |
+
load_raw_resolution: true
|
126 |
+
resolution: [320, 512]
|
127 |
+
spatial_transform: resize_center_crop
|
128 |
+
random_fs: true ## if true, we uniformly sample fs with max_fs=frame_stride (above)
|
129 |
+
|
130 |
+
lightning:
|
131 |
+
precision: 16
|
132 |
+
# strategy: deepspeed_stage_2
|
133 |
+
trainer:
|
134 |
+
benchmark: True
|
135 |
+
accumulate_grad_batches: 2
|
136 |
+
max_steps: 100000
|
137 |
+
# logger
|
138 |
+
log_every_n_steps: 50
|
139 |
+
# val
|
140 |
+
val_check_interval: 0.5
|
141 |
+
gradient_clip_algorithm: 'norm'
|
142 |
+
gradient_clip_val: 0.5
|
143 |
+
callbacks:
|
144 |
+
model_checkpoint:
|
145 |
+
target: pytorch_lightning.callbacks.ModelCheckpoint
|
146 |
+
params:
|
147 |
+
every_n_train_steps: 9000 #1000
|
148 |
+
filename: "{epoch}-{step}"
|
149 |
+
save_weights_only: True
|
150 |
+
metrics_over_trainsteps_checkpoint:
|
151 |
+
target: pytorch_lightning.callbacks.ModelCheckpoint
|
152 |
+
params:
|
153 |
+
filename: '{epoch}-{step}'
|
154 |
+
save_weights_only: True
|
155 |
+
every_n_train_steps: 10000 #20000 # 3s/step*2w=
|
156 |
+
batch_logger:
|
157 |
+
target: callbacks.ImageLogger
|
158 |
+
params:
|
159 |
+
batch_frequency: 500
|
160 |
+
to_local: False
|
161 |
+
max_images: 8
|
162 |
+
log_images_kwargs:
|
163 |
+
ddim_steps: 50
|
164 |
+
unconditional_guidance_scale: 7.5
|
165 |
+
timestep_spacing: uniform_trailing
|
166 |
+
guidance_rescale: 0.7
|
configs/training_512_v1.0/run.sh
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# NCCL configuration
|
2 |
+
# export NCCL_DEBUG=INFO
|
3 |
+
# export NCCL_IB_DISABLE=0
|
4 |
+
# export NCCL_IB_GID_INDEX=3
|
5 |
+
# export NCCL_NET_GDR_LEVEL=3
|
6 |
+
# export NCCL_TOPO_FILE=/tmp/topo.txt
|
7 |
+
|
8 |
+
# args
|
9 |
+
name="training_512_v1.0"
|
10 |
+
config_file=configs/${name}/config.yaml
|
11 |
+
|
12 |
+
# save root dir for logs, checkpoints, tensorboard record, etc.
|
13 |
+
save_root="<YOUR_SAVE_ROOT_DIR>"
|
14 |
+
|
15 |
+
mkdir -p $save_root/$name
|
16 |
+
|
17 |
+
## run
|
18 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch \
|
19 |
+
--nproc_per_node=$HOST_GPU_NUM --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
|
20 |
+
./main/trainer.py \
|
21 |
+
--base $config_file \
|
22 |
+
--train \
|
23 |
+
--name $name \
|
24 |
+
--logdir $save_root \
|
25 |
+
--devices $HOST_GPU_NUM \
|
26 |
+
lightning.trainer.num_nodes=1
|
27 |
+
|
28 |
+
## debugging
|
29 |
+
# CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch \
|
30 |
+
# --nproc_per_node=4 --nnodes=1 --master_addr=127.0.0.1 --master_port=12352 --node_rank=0 \
|
31 |
+
# ./main/trainer.py \
|
32 |
+
# --base $config_file \
|
33 |
+
# --train \
|
34 |
+
# --name $name \
|
35 |
+
# --logdir $save_root \
|
36 |
+
# --devices 4 \
|
37 |
+
# lightning.trainer.num_nodes=1
|
lvdm/.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
lvdm/basics.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# adopted from
|
2 |
+
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
3 |
+
# and
|
4 |
+
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
5 |
+
# and
|
6 |
+
# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
|
7 |
+
#
|
8 |
+
# thanks!
|
9 |
+
|
10 |
+
import torch.nn as nn
|
11 |
+
from utils.utils import instantiate_from_config
|
12 |
+
|
13 |
+
|
14 |
+
def disabled_train(self, mode=True):
|
15 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
16 |
+
does not change anymore."""
|
17 |
+
return self
|
18 |
+
|
19 |
+
def zero_module(module):
|
20 |
+
"""
|
21 |
+
Zero out the parameters of a module and return it.
|
22 |
+
"""
|
23 |
+
for p in module.parameters():
|
24 |
+
p.detach().zero_()
|
25 |
+
return module
|
26 |
+
|
27 |
+
def scale_module(module, scale):
|
28 |
+
"""
|
29 |
+
Scale the parameters of a module and return it.
|
30 |
+
"""
|
31 |
+
for p in module.parameters():
|
32 |
+
p.detach().mul_(scale)
|
33 |
+
return module
|
34 |
+
|
35 |
+
|
36 |
+
def conv_nd(dims, *args, **kwargs):
|
37 |
+
"""
|
38 |
+
Create a 1D, 2D, or 3D convolution module.
|
39 |
+
"""
|
40 |
+
if dims == 1:
|
41 |
+
return nn.Conv1d(*args, **kwargs)
|
42 |
+
elif dims == 2:
|
43 |
+
return nn.Conv2d(*args, **kwargs)
|
44 |
+
elif dims == 3:
|
45 |
+
return nn.Conv3d(*args, **kwargs)
|
46 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
47 |
+
|
48 |
+
|
49 |
+
def linear(*args, **kwargs):
|
50 |
+
"""
|
51 |
+
Create a linear module.
|
52 |
+
"""
|
53 |
+
return nn.Linear(*args, **kwargs)
|
54 |
+
|
55 |
+
|
56 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
57 |
+
"""
|
58 |
+
Create a 1D, 2D, or 3D average pooling module.
|
59 |
+
"""
|
60 |
+
if dims == 1:
|
61 |
+
return nn.AvgPool1d(*args, **kwargs)
|
62 |
+
elif dims == 2:
|
63 |
+
return nn.AvgPool2d(*args, **kwargs)
|
64 |
+
elif dims == 3:
|
65 |
+
return nn.AvgPool3d(*args, **kwargs)
|
66 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
67 |
+
|
68 |
+
|
69 |
+
def nonlinearity(type='silu'):
|
70 |
+
if type == 'silu':
|
71 |
+
return nn.SiLU()
|
72 |
+
elif type == 'leaky_relu':
|
73 |
+
return nn.LeakyReLU()
|
74 |
+
|
75 |
+
|
76 |
+
class GroupNormSpecific(nn.GroupNorm):
|
77 |
+
def forward(self, x):
|
78 |
+
return super().forward(x.float()).type(x.dtype)
|
79 |
+
|
80 |
+
|
81 |
+
def normalization(channels, num_groups=32):
|
82 |
+
"""
|
83 |
+
Make a standard normalization layer.
|
84 |
+
:param channels: number of input channels.
|
85 |
+
:return: an nn.Module for normalization.
|
86 |
+
"""
|
87 |
+
return GroupNormSpecific(num_groups, channels)
|
88 |
+
|
89 |
+
|
90 |
+
class HybridConditioner(nn.Module):
|
91 |
+
|
92 |
+
def __init__(self, c_concat_config, c_crossattn_config):
|
93 |
+
super().__init__()
|
94 |
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
95 |
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
96 |
+
|
97 |
+
def forward(self, c_concat, c_crossattn):
|
98 |
+
c_concat = self.concat_conditioner(c_concat)
|
99 |
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
100 |
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
lvdm/common.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from inspect import isfunction
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.distributed as dist
|
6 |
+
|
7 |
+
|
8 |
+
def gather_data(data, return_np=True):
|
9 |
+
''' gather data from multiple processes to one list '''
|
10 |
+
data_list = [torch.zeros_like(data) for _ in range(dist.get_world_size())]
|
11 |
+
dist.all_gather(data_list, data) # gather not supported with NCCL
|
12 |
+
if return_np:
|
13 |
+
data_list = [data.cpu().numpy() for data in data_list]
|
14 |
+
return data_list
|
15 |
+
|
16 |
+
def autocast(f):
|
17 |
+
def do_autocast(*args, **kwargs):
|
18 |
+
with torch.cuda.amp.autocast(enabled=True,
|
19 |
+
dtype=torch.get_autocast_gpu_dtype(),
|
20 |
+
cache_enabled=torch.is_autocast_cache_enabled()):
|
21 |
+
return f(*args, **kwargs)
|
22 |
+
return do_autocast
|
23 |
+
|
24 |
+
|
25 |
+
def extract_into_tensor(a, t, x_shape):
|
26 |
+
b, *_ = t.shape
|
27 |
+
out = a.gather(-1, t)
|
28 |
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
29 |
+
|
30 |
+
|
31 |
+
def noise_like(shape, device, repeat=False):
|
32 |
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
33 |
+
noise = lambda: torch.randn(shape, device=device)
|
34 |
+
return repeat_noise() if repeat else noise()
|
35 |
+
|
36 |
+
|
37 |
+
def default(val, d):
|
38 |
+
if exists(val):
|
39 |
+
return val
|
40 |
+
return d() if isfunction(d) else d
|
41 |
+
|
42 |
+
def exists(val):
|
43 |
+
return val is not None
|
44 |
+
|
45 |
+
def identity(*args, **kwargs):
|
46 |
+
return nn.Identity()
|
47 |
+
|
48 |
+
def uniq(arr):
|
49 |
+
return{el: True for el in arr}.keys()
|
50 |
+
|
51 |
+
def mean_flat(tensor):
|
52 |
+
"""
|
53 |
+
Take the mean over all non-batch dimensions.
|
54 |
+
"""
|
55 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
56 |
+
|
57 |
+
def ismap(x):
|
58 |
+
if not isinstance(x, torch.Tensor):
|
59 |
+
return False
|
60 |
+
return (len(x.shape) == 4) and (x.shape[1] > 3)
|
61 |
+
|
62 |
+
def isimage(x):
|
63 |
+
if not isinstance(x,torch.Tensor):
|
64 |
+
return False
|
65 |
+
return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
|
66 |
+
|
67 |
+
def max_neg_value(t):
|
68 |
+
return -torch.finfo(t.dtype).max
|
69 |
+
|
70 |
+
def shape_to_str(x):
|
71 |
+
shape_str = "x".join([str(x) for x in x.shape])
|
72 |
+
return shape_str
|
73 |
+
|
74 |
+
def init_(tensor):
|
75 |
+
dim = tensor.shape[-1]
|
76 |
+
std = 1 / math.sqrt(dim)
|
77 |
+
tensor.uniform_(-std, std)
|
78 |
+
return tensor
|
79 |
+
|
80 |
+
ckpt = torch.utils.checkpoint.checkpoint
|
81 |
+
def checkpoint(func, inputs, params, flag):
|
82 |
+
"""
|
83 |
+
Evaluate a function without caching intermediate activations, allowing for
|
84 |
+
reduced memory at the expense of extra compute in the backward pass.
|
85 |
+
:param func: the function to evaluate.
|
86 |
+
:param inputs: the argument sequence to pass to `func`.
|
87 |
+
:param params: a sequence of parameters `func` depends on but does not
|
88 |
+
explicitly take as arguments.
|
89 |
+
:param flag: if False, disable gradient checkpointing.
|
90 |
+
"""
|
91 |
+
if flag:
|
92 |
+
return ckpt(func, *inputs, use_reentrant=False)
|
93 |
+
else:
|
94 |
+
return func(*inputs)
|
lvdm/data/base.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import abstractmethod
|
2 |
+
from torch.utils.data import IterableDataset
|
3 |
+
|
4 |
+
|
5 |
+
class Txt2ImgIterableBaseDataset(IterableDataset):
|
6 |
+
'''
|
7 |
+
Define an interface to make the IterableDatasets for text2img data chainable
|
8 |
+
'''
|
9 |
+
def __init__(self, num_records=0, valid_ids=None, size=256):
|
10 |
+
super().__init__()
|
11 |
+
self.num_records = num_records
|
12 |
+
self.valid_ids = valid_ids
|
13 |
+
self.sample_ids = valid_ids
|
14 |
+
self.size = size
|
15 |
+
|
16 |
+
print(f'{self.__class__.__name__} dataset contains {self.__len__()} examples.')
|
17 |
+
|
18 |
+
def __len__(self):
|
19 |
+
return self.num_records
|
20 |
+
|
21 |
+
@abstractmethod
|
22 |
+
def __iter__(self):
|
23 |
+
pass
|
lvdm/data/webvid.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
from tqdm import tqdm
|
4 |
+
import pandas as pd
|
5 |
+
from decord import VideoReader, cpu
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from torch.utils.data import Dataset
|
9 |
+
from torch.utils.data import DataLoader
|
10 |
+
from torchvision import transforms
|
11 |
+
|
12 |
+
|
13 |
+
class WebVid(Dataset):
|
14 |
+
"""
|
15 |
+
WebVid Dataset.
|
16 |
+
Assumes webvid data is structured as follows.
|
17 |
+
Webvid/
|
18 |
+
videos/
|
19 |
+
000001_000050/ ($page_dir)
|
20 |
+
1.mp4 (videoid.mp4)
|
21 |
+
...
|
22 |
+
5000.mp4
|
23 |
+
...
|
24 |
+
"""
|
25 |
+
def __init__(self,
|
26 |
+
meta_path,
|
27 |
+
data_dir,
|
28 |
+
subsample=None,
|
29 |
+
video_length=16,
|
30 |
+
resolution=[256, 512],
|
31 |
+
frame_stride=1,
|
32 |
+
frame_stride_min=1,
|
33 |
+
spatial_transform=None,
|
34 |
+
crop_resolution=None,
|
35 |
+
fps_max=None,
|
36 |
+
load_raw_resolution=False,
|
37 |
+
fixed_fps=None,
|
38 |
+
random_fs=False,
|
39 |
+
):
|
40 |
+
self.meta_path = meta_path
|
41 |
+
self.data_dir = data_dir
|
42 |
+
self.subsample = subsample
|
43 |
+
self.video_length = video_length
|
44 |
+
self.resolution = [resolution, resolution] if isinstance(resolution, int) else resolution
|
45 |
+
self.fps_max = fps_max
|
46 |
+
self.frame_stride = frame_stride
|
47 |
+
self.frame_stride_min = frame_stride_min
|
48 |
+
self.fixed_fps = fixed_fps
|
49 |
+
self.load_raw_resolution = load_raw_resolution
|
50 |
+
self.random_fs = random_fs
|
51 |
+
self._load_metadata()
|
52 |
+
if spatial_transform is not None:
|
53 |
+
if spatial_transform == "random_crop":
|
54 |
+
self.spatial_transform = transforms.RandomCrop(crop_resolution)
|
55 |
+
elif spatial_transform == "center_crop":
|
56 |
+
self.spatial_transform = transforms.Compose([
|
57 |
+
transforms.CenterCrop(resolution),
|
58 |
+
])
|
59 |
+
elif spatial_transform == "resize_center_crop":
|
60 |
+
# assert(self.resolution[0] == self.resolution[1])
|
61 |
+
self.spatial_transform = transforms.Compose([
|
62 |
+
transforms.Resize(min(self.resolution)),
|
63 |
+
transforms.CenterCrop(self.resolution),
|
64 |
+
])
|
65 |
+
elif spatial_transform == "resize":
|
66 |
+
self.spatial_transform = transforms.Resize(self.resolution)
|
67 |
+
else:
|
68 |
+
raise NotImplementedError
|
69 |
+
else:
|
70 |
+
self.spatial_transform = None
|
71 |
+
|
72 |
+
def _load_metadata(self):
|
73 |
+
metadata = pd.read_csv(self.meta_path)
|
74 |
+
print(f'>>> {len(metadata)} data samples loaded.')
|
75 |
+
if self.subsample is not None:
|
76 |
+
metadata = metadata.sample(self.subsample, random_state=0)
|
77 |
+
|
78 |
+
metadata['caption'] = metadata['name']
|
79 |
+
del metadata['name']
|
80 |
+
self.metadata = metadata
|
81 |
+
self.metadata.dropna(inplace=True)
|
82 |
+
|
83 |
+
def _get_video_path(self, sample):
|
84 |
+
rel_video_fp = os.path.join(sample['page_dir'], str(sample['videoid']) + '.mp4')
|
85 |
+
full_video_fp = os.path.join(self.data_dir, 'videos', rel_video_fp)
|
86 |
+
return full_video_fp
|
87 |
+
|
88 |
+
def __getitem__(self, index):
|
89 |
+
if self.random_fs:
|
90 |
+
frame_stride = random.randint(self.frame_stride_min, self.frame_stride)
|
91 |
+
else:
|
92 |
+
frame_stride = self.frame_stride
|
93 |
+
|
94 |
+
## get frames until success
|
95 |
+
while True:
|
96 |
+
index = index % len(self.metadata)
|
97 |
+
sample = self.metadata.iloc[index]
|
98 |
+
video_path = self._get_video_path(sample)
|
99 |
+
## video_path should be in the format of "....../WebVid/videos/$page_dir/$videoid.mp4"
|
100 |
+
caption = sample['caption']
|
101 |
+
|
102 |
+
try:
|
103 |
+
if self.load_raw_resolution:
|
104 |
+
video_reader = VideoReader(video_path, ctx=cpu(0))
|
105 |
+
else:
|
106 |
+
video_reader = VideoReader(video_path, ctx=cpu(0), width=530, height=300)
|
107 |
+
if len(video_reader) < self.video_length:
|
108 |
+
print(f"video length ({len(video_reader)}) is smaller than target length({self.video_length})")
|
109 |
+
index += 1
|
110 |
+
continue
|
111 |
+
else:
|
112 |
+
pass
|
113 |
+
except:
|
114 |
+
index += 1
|
115 |
+
print(f"Load video failed! path = {video_path}")
|
116 |
+
continue
|
117 |
+
|
118 |
+
fps_ori = video_reader.get_avg_fps()
|
119 |
+
if self.fixed_fps is not None:
|
120 |
+
frame_stride = int(frame_stride * (1.0 * fps_ori / self.fixed_fps))
|
121 |
+
|
122 |
+
## to avoid extreme cases when fixed_fps is used
|
123 |
+
frame_stride = max(frame_stride, 1)
|
124 |
+
|
125 |
+
## get valid range (adapting case by case)
|
126 |
+
required_frame_num = frame_stride * (self.video_length-1) + 1
|
127 |
+
frame_num = len(video_reader)
|
128 |
+
if frame_num < required_frame_num:
|
129 |
+
## drop extra samples if fixed fps is required
|
130 |
+
if self.fixed_fps is not None and frame_num < required_frame_num * 0.5:
|
131 |
+
index += 1
|
132 |
+
continue
|
133 |
+
else:
|
134 |
+
frame_stride = frame_num // self.video_length
|
135 |
+
required_frame_num = frame_stride * (self.video_length-1) + 1
|
136 |
+
|
137 |
+
## select a random clip
|
138 |
+
random_range = frame_num - required_frame_num
|
139 |
+
start_idx = random.randint(0, random_range) if random_range > 0 else 0
|
140 |
+
|
141 |
+
## calculate frame indices
|
142 |
+
frame_indices = [start_idx + frame_stride*i for i in range(self.video_length)]
|
143 |
+
try:
|
144 |
+
frames = video_reader.get_batch(frame_indices)
|
145 |
+
break
|
146 |
+
except:
|
147 |
+
print(f"Get frames failed! path = {video_path}; [max_ind vs frame_total:{max(frame_indices)} / {frame_num}]")
|
148 |
+
index += 1
|
149 |
+
continue
|
150 |
+
|
151 |
+
## process data
|
152 |
+
assert(frames.shape[0] == self.video_length),f'{len(frames)}, self.video_length={self.video_length}'
|
153 |
+
frames = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float() # [t,h,w,c] -> [c,t,h,w]
|
154 |
+
|
155 |
+
if self.spatial_transform is not None:
|
156 |
+
frames = self.spatial_transform(frames)
|
157 |
+
|
158 |
+
if self.resolution is not None:
|
159 |
+
assert (frames.shape[2], frames.shape[3]) == (self.resolution[0], self.resolution[1]), f'frames={frames.shape}, self.resolution={self.resolution}'
|
160 |
+
|
161 |
+
## turn frames tensors to [-1,1]
|
162 |
+
frames = (frames / 255 - 0.5) * 2
|
163 |
+
fps_clip = fps_ori // frame_stride
|
164 |
+
if self.fps_max is not None and fps_clip > self.fps_max:
|
165 |
+
fps_clip = self.fps_max
|
166 |
+
|
167 |
+
data = {'video': frames, 'caption': caption, 'path': video_path, 'fps': fps_clip, 'frame_stride': frame_stride}
|
168 |
+
return data
|
169 |
+
|
170 |
+
def __len__(self):
|
171 |
+
return len(self.metadata)
|
172 |
+
|
173 |
+
|
174 |
+
if __name__== "__main__":
|
175 |
+
meta_path = "" ## path to the meta file
|
176 |
+
data_dir = "" ## path to the data directory
|
177 |
+
save_dir = "" ## path to the save directory
|
178 |
+
dataset = WebVid(meta_path,
|
179 |
+
data_dir,
|
180 |
+
subsample=None,
|
181 |
+
video_length=16,
|
182 |
+
resolution=[256,448],
|
183 |
+
frame_stride=4,
|
184 |
+
spatial_transform="resize_center_crop",
|
185 |
+
crop_resolution=None,
|
186 |
+
fps_max=None,
|
187 |
+
load_raw_resolution=True
|
188 |
+
)
|
189 |
+
dataloader = DataLoader(dataset,
|
190 |
+
batch_size=1,
|
191 |
+
num_workers=0,
|
192 |
+
shuffle=False)
|
193 |
+
|
194 |
+
|
195 |
+
import sys
|
196 |
+
sys.path.insert(1, os.path.join(sys.path[0], '..', '..'))
|
197 |
+
from utils.save_video import tensor_to_mp4
|
198 |
+
for i, batch in tqdm(enumerate(dataloader), desc="Data Batch"):
|
199 |
+
video = batch['video']
|
200 |
+
name = batch['path'][0].split('videos/')[-1].replace('/','_')
|
201 |
+
tensor_to_mp4(video, save_dir+'/'+name, fps=8)
|
202 |
+
|
lvdm/distributions.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
class AbstractDistribution:
|
6 |
+
def sample(self):
|
7 |
+
raise NotImplementedError()
|
8 |
+
|
9 |
+
def mode(self):
|
10 |
+
raise NotImplementedError()
|
11 |
+
|
12 |
+
|
13 |
+
class DiracDistribution(AbstractDistribution):
|
14 |
+
def __init__(self, value):
|
15 |
+
self.value = value
|
16 |
+
|
17 |
+
def sample(self):
|
18 |
+
return self.value
|
19 |
+
|
20 |
+
def mode(self):
|
21 |
+
return self.value
|
22 |
+
|
23 |
+
|
24 |
+
class DiagonalGaussianDistribution(object):
|
25 |
+
def __init__(self, parameters, deterministic=False):
|
26 |
+
self.parameters = parameters
|
27 |
+
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
|
28 |
+
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
|
29 |
+
self.deterministic = deterministic
|
30 |
+
self.std = torch.exp(0.5 * self.logvar)
|
31 |
+
self.var = torch.exp(self.logvar)
|
32 |
+
if self.deterministic:
|
33 |
+
self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
|
34 |
+
|
35 |
+
def sample(self, noise=None):
|
36 |
+
if noise is None:
|
37 |
+
noise = torch.randn(self.mean.shape)
|
38 |
+
|
39 |
+
x = self.mean + self.std * noise.to(device=self.parameters.device)
|
40 |
+
return x
|
41 |
+
|
42 |
+
def kl(self, other=None):
|
43 |
+
if self.deterministic:
|
44 |
+
return torch.Tensor([0.])
|
45 |
+
else:
|
46 |
+
if other is None:
|
47 |
+
return 0.5 * torch.sum(torch.pow(self.mean, 2)
|
48 |
+
+ self.var - 1.0 - self.logvar,
|
49 |
+
dim=[1, 2, 3])
|
50 |
+
else:
|
51 |
+
return 0.5 * torch.sum(
|
52 |
+
torch.pow(self.mean - other.mean, 2) / other.var
|
53 |
+
+ self.var / other.var - 1.0 - self.logvar + other.logvar,
|
54 |
+
dim=[1, 2, 3])
|
55 |
+
|
56 |
+
def nll(self, sample, dims=[1,2,3]):
|
57 |
+
if self.deterministic:
|
58 |
+
return torch.Tensor([0.])
|
59 |
+
logtwopi = np.log(2.0 * np.pi)
|
60 |
+
return 0.5 * torch.sum(
|
61 |
+
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
|
62 |
+
dim=dims)
|
63 |
+
|
64 |
+
def mode(self):
|
65 |
+
return self.mean
|
66 |
+
|
67 |
+
|
68 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
69 |
+
"""
|
70 |
+
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
|
71 |
+
Compute the KL divergence between two gaussians.
|
72 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
73 |
+
scalars, among other use cases.
|
74 |
+
"""
|
75 |
+
tensor = None
|
76 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
77 |
+
if isinstance(obj, torch.Tensor):
|
78 |
+
tensor = obj
|
79 |
+
break
|
80 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
81 |
+
|
82 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
83 |
+
# Tensors, but it does not work for torch.exp().
|
84 |
+
logvar1, logvar2 = [
|
85 |
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
86 |
+
for x in (logvar1, logvar2)
|
87 |
+
]
|
88 |
+
|
89 |
+
return 0.5 * (
|
90 |
+
-1.0
|
91 |
+
+ logvar2
|
92 |
+
- logvar1
|
93 |
+
+ torch.exp(logvar1 - logvar2)
|
94 |
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
95 |
+
)
|
lvdm/ema.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
|
4 |
+
|
5 |
+
class LitEma(nn.Module):
|
6 |
+
def __init__(self, model, decay=0.9999, use_num_upates=True):
|
7 |
+
super().__init__()
|
8 |
+
if decay < 0.0 or decay > 1.0:
|
9 |
+
raise ValueError('Decay must be between 0 and 1')
|
10 |
+
|
11 |
+
self.m_name2s_name = {}
|
12 |
+
self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
|
13 |
+
self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
|
14 |
+
else torch.tensor(-1,dtype=torch.int))
|
15 |
+
|
16 |
+
for name, p in model.named_parameters():
|
17 |
+
if p.requires_grad:
|
18 |
+
#remove as '.'-character is not allowed in buffers
|
19 |
+
s_name = name.replace('.','')
|
20 |
+
self.m_name2s_name.update({name:s_name})
|
21 |
+
self.register_buffer(s_name,p.clone().detach().data)
|
22 |
+
|
23 |
+
self.collected_params = []
|
24 |
+
|
25 |
+
def forward(self,model):
|
26 |
+
decay = self.decay
|
27 |
+
|
28 |
+
if self.num_updates >= 0:
|
29 |
+
self.num_updates += 1
|
30 |
+
decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
|
31 |
+
|
32 |
+
one_minus_decay = 1.0 - decay
|
33 |
+
|
34 |
+
with torch.no_grad():
|
35 |
+
m_param = dict(model.named_parameters())
|
36 |
+
shadow_params = dict(self.named_buffers())
|
37 |
+
|
38 |
+
for key in m_param:
|
39 |
+
if m_param[key].requires_grad:
|
40 |
+
sname = self.m_name2s_name[key]
|
41 |
+
shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
|
42 |
+
shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
|
43 |
+
else:
|
44 |
+
assert not key in self.m_name2s_name
|
45 |
+
|
46 |
+
def copy_to(self, model):
|
47 |
+
m_param = dict(model.named_parameters())
|
48 |
+
shadow_params = dict(self.named_buffers())
|
49 |
+
for key in m_param:
|
50 |
+
if m_param[key].requires_grad:
|
51 |
+
m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
|
52 |
+
else:
|
53 |
+
assert not key in self.m_name2s_name
|
54 |
+
|
55 |
+
def store(self, parameters):
|
56 |
+
"""
|
57 |
+
Save the current parameters for restoring later.
|
58 |
+
Args:
|
59 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
60 |
+
temporarily stored.
|
61 |
+
"""
|
62 |
+
self.collected_params = [param.clone() for param in parameters]
|
63 |
+
|
64 |
+
def restore(self, parameters):
|
65 |
+
"""
|
66 |
+
Restore the parameters stored with the `store` method.
|
67 |
+
Useful to validate the model with EMA parameters without affecting the
|
68 |
+
original optimization process. Store the parameters before the
|
69 |
+
`copy_to` method. After validation (or model saving), use this to
|
70 |
+
restore the former parameters.
|
71 |
+
Args:
|
72 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
73 |
+
updated with the stored parameters.
|
74 |
+
"""
|
75 |
+
for c_param, param in zip(self.collected_params, parameters):
|
76 |
+
param.data.copy_(c_param.data)
|
lvdm/models/autoencoder.py
ADDED
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from contextlib import contextmanager
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from einops import rearrange
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import pytorch_lightning as pl
|
8 |
+
from lvdm.modules.networks.ae_modules import Encoder, Decoder
|
9 |
+
from lvdm.distributions import DiagonalGaussianDistribution
|
10 |
+
from utils.utils import instantiate_from_config
|
11 |
+
|
12 |
+
TIMESTEPS=16
|
13 |
+
class AutoencoderKL(pl.LightningModule):
|
14 |
+
def __init__(self,
|
15 |
+
ddconfig,
|
16 |
+
lossconfig,
|
17 |
+
embed_dim,
|
18 |
+
ckpt_path=None,
|
19 |
+
ignore_keys=[],
|
20 |
+
image_key="image",
|
21 |
+
colorize_nlabels=None,
|
22 |
+
monitor=None,
|
23 |
+
test=False,
|
24 |
+
logdir=None,
|
25 |
+
input_dim=4,
|
26 |
+
test_args=None,
|
27 |
+
additional_decode_keys=None,
|
28 |
+
use_checkpoint=False,
|
29 |
+
diff_boost_factor=3.0,
|
30 |
+
):
|
31 |
+
super().__init__()
|
32 |
+
self.image_key = image_key
|
33 |
+
self.encoder = Encoder(**ddconfig)
|
34 |
+
self.decoder = Decoder(**ddconfig)
|
35 |
+
self.loss = instantiate_from_config(lossconfig)
|
36 |
+
assert ddconfig["double_z"]
|
37 |
+
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
|
38 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
39 |
+
self.embed_dim = embed_dim
|
40 |
+
self.input_dim = input_dim
|
41 |
+
self.test = test
|
42 |
+
self.test_args = test_args
|
43 |
+
self.logdir = logdir
|
44 |
+
if colorize_nlabels is not None:
|
45 |
+
assert type(colorize_nlabels)==int
|
46 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
47 |
+
if monitor is not None:
|
48 |
+
self.monitor = monitor
|
49 |
+
if ckpt_path is not None:
|
50 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
51 |
+
if self.test:
|
52 |
+
self.init_test()
|
53 |
+
|
54 |
+
def init_test(self,):
|
55 |
+
self.test = True
|
56 |
+
save_dir = os.path.join(self.logdir, "test")
|
57 |
+
if 'ckpt' in self.test_args:
|
58 |
+
ckpt_name = os.path.basename(self.test_args.ckpt).split('.ckpt')[0] + f'_epoch{self._cur_epoch}'
|
59 |
+
self.root = os.path.join(save_dir, ckpt_name)
|
60 |
+
else:
|
61 |
+
self.root = save_dir
|
62 |
+
if 'test_subdir' in self.test_args:
|
63 |
+
self.root = os.path.join(save_dir, self.test_args.test_subdir)
|
64 |
+
|
65 |
+
self.root_zs = os.path.join(self.root, "zs")
|
66 |
+
self.root_dec = os.path.join(self.root, "reconstructions")
|
67 |
+
self.root_inputs = os.path.join(self.root, "inputs")
|
68 |
+
os.makedirs(self.root, exist_ok=True)
|
69 |
+
|
70 |
+
if self.test_args.save_z:
|
71 |
+
os.makedirs(self.root_zs, exist_ok=True)
|
72 |
+
if self.test_args.save_reconstruction:
|
73 |
+
os.makedirs(self.root_dec, exist_ok=True)
|
74 |
+
if self.test_args.save_input:
|
75 |
+
os.makedirs(self.root_inputs, exist_ok=True)
|
76 |
+
assert(self.test_args is not None)
|
77 |
+
self.test_maximum = getattr(self.test_args, 'test_maximum', None)
|
78 |
+
self.count = 0
|
79 |
+
self.eval_metrics = {}
|
80 |
+
self.decodes = []
|
81 |
+
self.save_decode_samples = 2048
|
82 |
+
|
83 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
84 |
+
sd = torch.load(path, map_location="cpu")
|
85 |
+
try:
|
86 |
+
self._cur_epoch = sd['epoch']
|
87 |
+
sd = sd["state_dict"]
|
88 |
+
except:
|
89 |
+
self._cur_epoch = 'null'
|
90 |
+
keys = list(sd.keys())
|
91 |
+
for k in keys:
|
92 |
+
for ik in ignore_keys:
|
93 |
+
if k.startswith(ik):
|
94 |
+
print("Deleting key {} from state_dict.".format(k))
|
95 |
+
del sd[k]
|
96 |
+
self.load_state_dict(sd, strict=False)
|
97 |
+
# self.load_state_dict(sd, strict=True)
|
98 |
+
print(f"Restored from {path}")
|
99 |
+
|
100 |
+
def encode(self, x, return_hidden_states=False, **kwargs):
|
101 |
+
if return_hidden_states:
|
102 |
+
h, hidden = self.encoder(x, return_hidden_states)
|
103 |
+
moments = self.quant_conv(h)
|
104 |
+
posterior = DiagonalGaussianDistribution(moments)
|
105 |
+
return posterior, hidden
|
106 |
+
else:
|
107 |
+
h = self.encoder(x)
|
108 |
+
moments = self.quant_conv(h)
|
109 |
+
posterior = DiagonalGaussianDistribution(moments)
|
110 |
+
return posterior
|
111 |
+
|
112 |
+
def decode(self, z, **kwargs):
|
113 |
+
if len(kwargs) == 0: ## use the original decoder in AutoencoderKL
|
114 |
+
z = self.post_quant_conv(z)
|
115 |
+
dec = self.decoder(z, **kwargs) ##change for SVD decoder by adding **kwargs
|
116 |
+
return dec
|
117 |
+
|
118 |
+
def forward(self, input, sample_posterior=True, **additional_decode_kwargs):
|
119 |
+
input_tuple = (input, )
|
120 |
+
forward_temp = partial(self._forward, sample_posterior=sample_posterior, **additional_decode_kwargs)
|
121 |
+
return checkpoint(forward_temp, input_tuple, self.parameters(), self.use_checkpoint)
|
122 |
+
|
123 |
+
|
124 |
+
def _forward(self, input, sample_posterior=True, **additional_decode_kwargs):
|
125 |
+
posterior = self.encode(input)
|
126 |
+
if sample_posterior:
|
127 |
+
z = posterior.sample()
|
128 |
+
else:
|
129 |
+
z = posterior.mode()
|
130 |
+
dec = self.decode(z, **additional_decode_kwargs)
|
131 |
+
## print(input.shape, dec.shape) torch.Size([16, 3, 256, 256]) torch.Size([16, 3, 256, 256])
|
132 |
+
return dec, posterior
|
133 |
+
|
134 |
+
def get_input(self, batch, k):
|
135 |
+
x = batch[k]
|
136 |
+
if x.dim() == 5 and self.input_dim == 4:
|
137 |
+
b,c,t,h,w = x.shape
|
138 |
+
self.b = b
|
139 |
+
self.t = t
|
140 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
141 |
+
|
142 |
+
return x
|
143 |
+
|
144 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
145 |
+
inputs = self.get_input(batch, self.image_key)
|
146 |
+
reconstructions, posterior = self(inputs)
|
147 |
+
|
148 |
+
if optimizer_idx == 0:
|
149 |
+
# train encoder+decoder+logvar
|
150 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
151 |
+
last_layer=self.get_last_layer(), split="train")
|
152 |
+
self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
153 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
154 |
+
return aeloss
|
155 |
+
|
156 |
+
if optimizer_idx == 1:
|
157 |
+
# train the discriminator
|
158 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
159 |
+
last_layer=self.get_last_layer(), split="train")
|
160 |
+
|
161 |
+
self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
162 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
163 |
+
return discloss
|
164 |
+
|
165 |
+
def validation_step(self, batch, batch_idx):
|
166 |
+
inputs = self.get_input(batch, self.image_key)
|
167 |
+
reconstructions, posterior = self(inputs)
|
168 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
|
169 |
+
last_layer=self.get_last_layer(), split="val")
|
170 |
+
|
171 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
|
172 |
+
last_layer=self.get_last_layer(), split="val")
|
173 |
+
|
174 |
+
self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
|
175 |
+
self.log_dict(log_dict_ae)
|
176 |
+
self.log_dict(log_dict_disc)
|
177 |
+
return self.log_dict
|
178 |
+
|
179 |
+
def configure_optimizers(self):
|
180 |
+
lr = self.learning_rate
|
181 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
182 |
+
list(self.decoder.parameters())+
|
183 |
+
list(self.quant_conv.parameters())+
|
184 |
+
list(self.post_quant_conv.parameters()),
|
185 |
+
lr=lr, betas=(0.5, 0.9))
|
186 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
187 |
+
lr=lr, betas=(0.5, 0.9))
|
188 |
+
return [opt_ae, opt_disc], []
|
189 |
+
|
190 |
+
def get_last_layer(self):
|
191 |
+
return self.decoder.conv_out.weight
|
192 |
+
|
193 |
+
@torch.no_grad()
|
194 |
+
def log_images(self, batch, only_inputs=False, **kwargs):
|
195 |
+
log = dict()
|
196 |
+
x = self.get_input(batch, self.image_key)
|
197 |
+
x = x.to(self.device)
|
198 |
+
if not only_inputs:
|
199 |
+
xrec, posterior = self(x)
|
200 |
+
if x.shape[1] > 3:
|
201 |
+
# colorize with random projection
|
202 |
+
assert xrec.shape[1] > 3
|
203 |
+
x = self.to_rgb(x)
|
204 |
+
xrec = self.to_rgb(xrec)
|
205 |
+
log["samples"] = self.decode(torch.randn_like(posterior.sample()))
|
206 |
+
log["reconstructions"] = xrec
|
207 |
+
log["inputs"] = x
|
208 |
+
return log
|
209 |
+
|
210 |
+
def to_rgb(self, x):
|
211 |
+
assert self.image_key == "segmentation"
|
212 |
+
if not hasattr(self, "colorize"):
|
213 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
214 |
+
x = F.conv2d(x, weight=self.colorize)
|
215 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
216 |
+
return x
|
217 |
+
|
218 |
+
class IdentityFirstStage(torch.nn.Module):
|
219 |
+
def __init__(self, *args, vq_interface=False, **kwargs):
|
220 |
+
self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
|
221 |
+
super().__init__()
|
222 |
+
|
223 |
+
def encode(self, x, *args, **kwargs):
|
224 |
+
return x
|
225 |
+
|
226 |
+
def decode(self, x, *args, **kwargs):
|
227 |
+
return x
|
228 |
+
|
229 |
+
def quantize(self, x, *args, **kwargs):
|
230 |
+
if self.vq_interface:
|
231 |
+
return x, None, [None, None, None]
|
232 |
+
return x
|
233 |
+
|
234 |
+
def forward(self, x, *args, **kwargs):
|
235 |
+
return x
|
236 |
+
|
237 |
+
from lvdm.models.autoencoder_dualref import VideoDecoder
|
238 |
+
class AutoencoderKL_Dualref(AutoencoderKL):
|
239 |
+
def __init__(self,
|
240 |
+
ddconfig,
|
241 |
+
lossconfig,
|
242 |
+
embed_dim,
|
243 |
+
ckpt_path=None,
|
244 |
+
ignore_keys=[],
|
245 |
+
image_key="image",
|
246 |
+
colorize_nlabels=None,
|
247 |
+
monitor=None,
|
248 |
+
test=False,
|
249 |
+
logdir=None,
|
250 |
+
input_dim=4,
|
251 |
+
test_args=None,
|
252 |
+
additional_decode_keys=None,
|
253 |
+
use_checkpoint=False,
|
254 |
+
diff_boost_factor=3.0,
|
255 |
+
):
|
256 |
+
super().__init__(ddconfig, lossconfig, embed_dim, ckpt_path, ignore_keys, image_key, colorize_nlabels, monitor, test, logdir, input_dim, test_args, additional_decode_keys, use_checkpoint, diff_boost_factor)
|
257 |
+
self.decoder = VideoDecoder(**ddconfig)
|
258 |
+
|
259 |
+
def _forward(self, input, sample_posterior=True, **additional_decode_kwargs):
|
260 |
+
posterior, hidden_states = self.encode(input, return_hidden_states=True)
|
261 |
+
|
262 |
+
hidden_states_first_last = []
|
263 |
+
### use only the first and last hidden states
|
264 |
+
for hid in hidden_states:
|
265 |
+
hid = rearrange(hid, '(b t) c h w -> b c t h w', t=TIMESTEPS)
|
266 |
+
hid_new = torch.cat([hid[:, :, 0:1], hid[:, :, -1:]], dim=2)
|
267 |
+
hidden_states_first_last.append(hid_new)
|
268 |
+
|
269 |
+
if sample_posterior:
|
270 |
+
z = posterior.sample()
|
271 |
+
else:
|
272 |
+
z = posterior.mode()
|
273 |
+
dec = self.decode(z, ref_context=hidden_states_first_last, **additional_decode_kwargs)
|
274 |
+
## print(input.shape, dec.shape) torch.Size([16, 3, 256, 256]) torch.Size([16, 3, 256, 256])
|
275 |
+
return dec, posterior
|
lvdm/models/autoencoder_dualref.py
ADDED
@@ -0,0 +1,1178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#### https://github.com/Stability-AI/generative-models
|
2 |
+
from einops import rearrange, repeat
|
3 |
+
import logging
|
4 |
+
from typing import Any, Callable, Optional, Iterable, Union
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
from packaging import version
|
10 |
+
logpy = logging.getLogger(__name__)
|
11 |
+
|
12 |
+
try:
|
13 |
+
import xformers
|
14 |
+
import xformers.ops
|
15 |
+
|
16 |
+
XFORMERS_IS_AVAILABLE = True
|
17 |
+
except:
|
18 |
+
XFORMERS_IS_AVAILABLE = False
|
19 |
+
logpy.warning("no module 'xformers'. Processing without...")
|
20 |
+
|
21 |
+
from lvdm.modules.attention_svd import LinearAttention, MemoryEfficientCrossAttention
|
22 |
+
|
23 |
+
|
24 |
+
def nonlinearity(x):
|
25 |
+
# swish
|
26 |
+
return x * torch.sigmoid(x)
|
27 |
+
|
28 |
+
|
29 |
+
def Normalize(in_channels, num_groups=32):
|
30 |
+
return torch.nn.GroupNorm(
|
31 |
+
num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True
|
32 |
+
)
|
33 |
+
|
34 |
+
|
35 |
+
class ResnetBlock(nn.Module):
|
36 |
+
def __init__(
|
37 |
+
self,
|
38 |
+
*,
|
39 |
+
in_channels,
|
40 |
+
out_channels=None,
|
41 |
+
conv_shortcut=False,
|
42 |
+
dropout,
|
43 |
+
temb_channels=512,
|
44 |
+
):
|
45 |
+
super().__init__()
|
46 |
+
self.in_channels = in_channels
|
47 |
+
out_channels = in_channels if out_channels is None else out_channels
|
48 |
+
self.out_channels = out_channels
|
49 |
+
self.use_conv_shortcut = conv_shortcut
|
50 |
+
|
51 |
+
self.norm1 = Normalize(in_channels)
|
52 |
+
self.conv1 = torch.nn.Conv2d(
|
53 |
+
in_channels, out_channels, kernel_size=3, stride=1, padding=1
|
54 |
+
)
|
55 |
+
if temb_channels > 0:
|
56 |
+
self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
|
57 |
+
self.norm2 = Normalize(out_channels)
|
58 |
+
self.dropout = torch.nn.Dropout(dropout)
|
59 |
+
self.conv2 = torch.nn.Conv2d(
|
60 |
+
out_channels, out_channels, kernel_size=3, stride=1, padding=1
|
61 |
+
)
|
62 |
+
if self.in_channels != self.out_channels:
|
63 |
+
if self.use_conv_shortcut:
|
64 |
+
self.conv_shortcut = torch.nn.Conv2d(
|
65 |
+
in_channels, out_channels, kernel_size=3, stride=1, padding=1
|
66 |
+
)
|
67 |
+
else:
|
68 |
+
self.nin_shortcut = torch.nn.Conv2d(
|
69 |
+
in_channels, out_channels, kernel_size=1, stride=1, padding=0
|
70 |
+
)
|
71 |
+
|
72 |
+
def forward(self, x, temb):
|
73 |
+
h = x
|
74 |
+
h = self.norm1(h)
|
75 |
+
h = nonlinearity(h)
|
76 |
+
h = self.conv1(h)
|
77 |
+
|
78 |
+
if temb is not None:
|
79 |
+
h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]
|
80 |
+
|
81 |
+
h = self.norm2(h)
|
82 |
+
h = nonlinearity(h)
|
83 |
+
h = self.dropout(h)
|
84 |
+
h = self.conv2(h)
|
85 |
+
|
86 |
+
if self.in_channels != self.out_channels:
|
87 |
+
if self.use_conv_shortcut:
|
88 |
+
x = self.conv_shortcut(x)
|
89 |
+
else:
|
90 |
+
x = self.nin_shortcut(x)
|
91 |
+
|
92 |
+
return x + h
|
93 |
+
|
94 |
+
|
95 |
+
class LinAttnBlock(LinearAttention):
|
96 |
+
"""to match AttnBlock usage"""
|
97 |
+
|
98 |
+
def __init__(self, in_channels):
|
99 |
+
super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
|
100 |
+
|
101 |
+
|
102 |
+
class AttnBlock(nn.Module):
|
103 |
+
def __init__(self, in_channels):
|
104 |
+
super().__init__()
|
105 |
+
self.in_channels = in_channels
|
106 |
+
|
107 |
+
self.norm = Normalize(in_channels)
|
108 |
+
self.q = torch.nn.Conv2d(
|
109 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
110 |
+
)
|
111 |
+
self.k = torch.nn.Conv2d(
|
112 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
113 |
+
)
|
114 |
+
self.v = torch.nn.Conv2d(
|
115 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
116 |
+
)
|
117 |
+
self.proj_out = torch.nn.Conv2d(
|
118 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
119 |
+
)
|
120 |
+
|
121 |
+
def attention(self, h_: torch.Tensor) -> torch.Tensor:
|
122 |
+
h_ = self.norm(h_)
|
123 |
+
q = self.q(h_)
|
124 |
+
k = self.k(h_)
|
125 |
+
v = self.v(h_)
|
126 |
+
|
127 |
+
b, c, h, w = q.shape
|
128 |
+
q, k, v = map(
|
129 |
+
lambda x: rearrange(x, "b c h w -> b 1 (h w) c").contiguous(), (q, k, v)
|
130 |
+
)
|
131 |
+
h_ = torch.nn.functional.scaled_dot_product_attention(
|
132 |
+
q, k, v
|
133 |
+
) # scale is dim ** -0.5 per default
|
134 |
+
# compute attention
|
135 |
+
|
136 |
+
return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
|
137 |
+
|
138 |
+
def forward(self, x, **kwargs):
|
139 |
+
h_ = x
|
140 |
+
h_ = self.attention(h_)
|
141 |
+
h_ = self.proj_out(h_)
|
142 |
+
return x + h_
|
143 |
+
|
144 |
+
|
145 |
+
class MemoryEfficientAttnBlock(nn.Module):
|
146 |
+
"""
|
147 |
+
Uses xformers efficient implementation,
|
148 |
+
see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
149 |
+
Note: this is a single-head self-attention operation
|
150 |
+
"""
|
151 |
+
|
152 |
+
#
|
153 |
+
def __init__(self, in_channels):
|
154 |
+
super().__init__()
|
155 |
+
self.in_channels = in_channels
|
156 |
+
|
157 |
+
self.norm = Normalize(in_channels)
|
158 |
+
self.q = torch.nn.Conv2d(
|
159 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
160 |
+
)
|
161 |
+
self.k = torch.nn.Conv2d(
|
162 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
163 |
+
)
|
164 |
+
self.v = torch.nn.Conv2d(
|
165 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
166 |
+
)
|
167 |
+
self.proj_out = torch.nn.Conv2d(
|
168 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
169 |
+
)
|
170 |
+
self.attention_op: Optional[Any] = None
|
171 |
+
|
172 |
+
def attention(self, h_: torch.Tensor) -> torch.Tensor:
|
173 |
+
h_ = self.norm(h_)
|
174 |
+
q = self.q(h_)
|
175 |
+
k = self.k(h_)
|
176 |
+
v = self.v(h_)
|
177 |
+
|
178 |
+
# compute attention
|
179 |
+
B, C, H, W = q.shape
|
180 |
+
q, k, v = map(lambda x: rearrange(x, "b c h w -> b (h w) c"), (q, k, v))
|
181 |
+
|
182 |
+
q, k, v = map(
|
183 |
+
lambda t: t.unsqueeze(3)
|
184 |
+
.reshape(B, t.shape[1], 1, C)
|
185 |
+
.permute(0, 2, 1, 3)
|
186 |
+
.reshape(B * 1, t.shape[1], C)
|
187 |
+
.contiguous(),
|
188 |
+
(q, k, v),
|
189 |
+
)
|
190 |
+
out = xformers.ops.memory_efficient_attention(
|
191 |
+
q, k, v, attn_bias=None, op=self.attention_op
|
192 |
+
)
|
193 |
+
|
194 |
+
out = (
|
195 |
+
out.unsqueeze(0)
|
196 |
+
.reshape(B, 1, out.shape[1], C)
|
197 |
+
.permute(0, 2, 1, 3)
|
198 |
+
.reshape(B, out.shape[1], C)
|
199 |
+
)
|
200 |
+
return rearrange(out, "b (h w) c -> b c h w", b=B, h=H, w=W, c=C)
|
201 |
+
|
202 |
+
def forward(self, x, **kwargs):
|
203 |
+
h_ = x
|
204 |
+
h_ = self.attention(h_)
|
205 |
+
h_ = self.proj_out(h_)
|
206 |
+
return x + h_
|
207 |
+
|
208 |
+
|
209 |
+
class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
|
210 |
+
def forward(self, x, context=None, mask=None, **unused_kwargs):
|
211 |
+
b, c, h, w = x.shape
|
212 |
+
x = rearrange(x, "b c h w -> b (h w) c")
|
213 |
+
out = super().forward(x, context=context, mask=mask)
|
214 |
+
out = rearrange(out, "b (h w) c -> b c h w", h=h, w=w, c=c)
|
215 |
+
return x + out
|
216 |
+
|
217 |
+
|
218 |
+
def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
|
219 |
+
assert attn_type in [
|
220 |
+
"vanilla",
|
221 |
+
"vanilla-xformers",
|
222 |
+
"memory-efficient-cross-attn",
|
223 |
+
"linear",
|
224 |
+
"none",
|
225 |
+
"memory-efficient-cross-attn-fusion",
|
226 |
+
], f"attn_type {attn_type} unknown"
|
227 |
+
if (
|
228 |
+
version.parse(torch.__version__) < version.parse("2.0.0")
|
229 |
+
and attn_type != "none"
|
230 |
+
):
|
231 |
+
assert XFORMERS_IS_AVAILABLE, (
|
232 |
+
f"We do not support vanilla attention in {torch.__version__} anymore, "
|
233 |
+
f"as it is too expensive. Please install xformers via e.g. 'pip install xformers==0.0.16'"
|
234 |
+
)
|
235 |
+
# attn_type = "vanilla-xformers"
|
236 |
+
logpy.info(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
237 |
+
if attn_type == "vanilla":
|
238 |
+
assert attn_kwargs is None
|
239 |
+
return AttnBlock(in_channels)
|
240 |
+
elif attn_type == "vanilla-xformers":
|
241 |
+
logpy.info(
|
242 |
+
f"building MemoryEfficientAttnBlock with {in_channels} in_channels..."
|
243 |
+
)
|
244 |
+
return MemoryEfficientAttnBlock(in_channels)
|
245 |
+
elif attn_type == "memory-efficient-cross-attn":
|
246 |
+
attn_kwargs["query_dim"] = in_channels
|
247 |
+
return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
|
248 |
+
elif attn_type == "memory-efficient-cross-attn-fusion":
|
249 |
+
attn_kwargs["query_dim"] = in_channels
|
250 |
+
return MemoryEfficientCrossAttentionWrapperFusion(**attn_kwargs)
|
251 |
+
elif attn_type == "none":
|
252 |
+
return nn.Identity(in_channels)
|
253 |
+
else:
|
254 |
+
return LinAttnBlock(in_channels)
|
255 |
+
|
256 |
+
class MemoryEfficientCrossAttentionWrapperFusion(MemoryEfficientCrossAttention):
|
257 |
+
# print('x.shape: ',x.shape, 'context.shape: ',context.shape) ##torch.Size([8, 128, 256, 256]) torch.Size([1, 128, 2, 256, 256])
|
258 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0, **kwargs):
|
259 |
+
super().__init__(query_dim, context_dim, heads, dim_head, dropout, **kwargs)
|
260 |
+
self.norm = Normalize(query_dim)
|
261 |
+
nn.init.zeros_(self.to_out[0].weight)
|
262 |
+
nn.init.zeros_(self.to_out[0].bias)
|
263 |
+
|
264 |
+
def forward(self, x, context=None, mask=None):
|
265 |
+
if self.training:
|
266 |
+
return checkpoint(self._forward, x, context, mask, use_reentrant=False)
|
267 |
+
else:
|
268 |
+
return self._forward(x, context, mask)
|
269 |
+
|
270 |
+
def _forward(
|
271 |
+
self,
|
272 |
+
x,
|
273 |
+
context=None,
|
274 |
+
mask=None,
|
275 |
+
):
|
276 |
+
bt, c, h, w = x.shape
|
277 |
+
h_ = self.norm(x)
|
278 |
+
h_ = rearrange(h_, "b c h w -> b (h w) c")
|
279 |
+
q = self.to_q(h_)
|
280 |
+
|
281 |
+
|
282 |
+
b, c, l, h, w = context.shape
|
283 |
+
context = rearrange(context, "b c l h w -> (b l) (h w) c")
|
284 |
+
k = self.to_k(context)
|
285 |
+
v = self.to_v(context)
|
286 |
+
k = rearrange(k, "(b l) d c -> b l d c", l=l)
|
287 |
+
k = torch.cat([k[:, [0] * (bt//b)], k[:, [1]*(bt//b)]], dim=2)
|
288 |
+
k = rearrange(k, "b l d c -> (b l) d c")
|
289 |
+
|
290 |
+
v = rearrange(v, "(b l) d c -> b l d c", l=l)
|
291 |
+
v = torch.cat([v[:, [0] * (bt//b)], v[:, [1]*(bt//b)]], dim=2)
|
292 |
+
v = rearrange(v, "b l d c -> (b l) d c")
|
293 |
+
|
294 |
+
|
295 |
+
b, _, _ = q.shape ##actually bt
|
296 |
+
q, k, v = map(
|
297 |
+
lambda t: t.unsqueeze(3)
|
298 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
299 |
+
.permute(0, 2, 1, 3)
|
300 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
301 |
+
.contiguous(),
|
302 |
+
(q, k, v),
|
303 |
+
)
|
304 |
+
|
305 |
+
# actually compute the attention, what we cannot get enough of
|
306 |
+
if version.parse(xformers.__version__) >= version.parse("0.0.21"):
|
307 |
+
# NOTE: workaround for
|
308 |
+
# https://github.com/facebookresearch/xformers/issues/845
|
309 |
+
max_bs = 32768
|
310 |
+
N = q.shape[0]
|
311 |
+
n_batches = math.ceil(N / max_bs)
|
312 |
+
out = list()
|
313 |
+
for i_batch in range(n_batches):
|
314 |
+
batch = slice(i_batch * max_bs, (i_batch + 1) * max_bs)
|
315 |
+
out.append(
|
316 |
+
xformers.ops.memory_efficient_attention(
|
317 |
+
q[batch],
|
318 |
+
k[batch],
|
319 |
+
v[batch],
|
320 |
+
attn_bias=None,
|
321 |
+
op=self.attention_op,
|
322 |
+
)
|
323 |
+
)
|
324 |
+
out = torch.cat(out, 0)
|
325 |
+
else:
|
326 |
+
out = xformers.ops.memory_efficient_attention(
|
327 |
+
q, k, v, attn_bias=None, op=self.attention_op
|
328 |
+
)
|
329 |
+
|
330 |
+
# TODO: Use this directly in the attention operation, as a bias
|
331 |
+
if exists(mask):
|
332 |
+
raise NotImplementedError
|
333 |
+
out = (
|
334 |
+
out.unsqueeze(0)
|
335 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
336 |
+
.permute(0, 2, 1, 3)
|
337 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
338 |
+
)
|
339 |
+
out = self.to_out(out)
|
340 |
+
out = rearrange(out, "bt (h w) c -> bt c h w", h=h, w=w, c=c)
|
341 |
+
return x + out
|
342 |
+
|
343 |
+
class Combiner(nn.Module):
|
344 |
+
def __init__(self, ch) -> None:
|
345 |
+
super().__init__()
|
346 |
+
self.conv = nn.Conv2d(ch,ch,1,padding=0)
|
347 |
+
|
348 |
+
nn.init.zeros_(self.conv.weight)
|
349 |
+
nn.init.zeros_(self.conv.bias)
|
350 |
+
|
351 |
+
def forward(self, x, context):
|
352 |
+
if self.training:
|
353 |
+
return checkpoint(self._forward, x, context, use_reentrant=False)
|
354 |
+
else:
|
355 |
+
return self._forward(x, context)
|
356 |
+
|
357 |
+
def _forward(self, x, context):
|
358 |
+
## x: b c h w, context: b c 2 h w
|
359 |
+
b, c, l, h, w = context.shape
|
360 |
+
bt, c, h, w = x.shape
|
361 |
+
context = rearrange(context, "b c l h w -> (b l) c h w")
|
362 |
+
context = self.conv(context)
|
363 |
+
context = rearrange(context, "(b l) c h w -> b c l h w", l=l)
|
364 |
+
x = rearrange(x, "(b t) c h w -> b c t h w", t=bt//b)
|
365 |
+
x[:,:,0] = x[:,:,0] + context[:,:,0]
|
366 |
+
x[:,:,-1] = x[:,:,-1] + context[:,:,1]
|
367 |
+
x = rearrange(x, "b c t h w -> (b t) c h w")
|
368 |
+
return x
|
369 |
+
|
370 |
+
|
371 |
+
class Decoder(nn.Module):
|
372 |
+
def __init__(
|
373 |
+
self,
|
374 |
+
*,
|
375 |
+
ch,
|
376 |
+
out_ch,
|
377 |
+
ch_mult=(1, 2, 4, 8),
|
378 |
+
num_res_blocks,
|
379 |
+
attn_resolutions,
|
380 |
+
dropout=0.0,
|
381 |
+
resamp_with_conv=True,
|
382 |
+
in_channels,
|
383 |
+
resolution,
|
384 |
+
z_channels,
|
385 |
+
give_pre_end=False,
|
386 |
+
tanh_out=False,
|
387 |
+
use_linear_attn=False,
|
388 |
+
attn_type="vanilla-xformers",
|
389 |
+
attn_level=[2,3],
|
390 |
+
**ignorekwargs,
|
391 |
+
):
|
392 |
+
super().__init__()
|
393 |
+
if use_linear_attn:
|
394 |
+
attn_type = "linear"
|
395 |
+
self.ch = ch
|
396 |
+
self.temb_ch = 0
|
397 |
+
self.num_resolutions = len(ch_mult)
|
398 |
+
self.num_res_blocks = num_res_blocks
|
399 |
+
self.resolution = resolution
|
400 |
+
self.in_channels = in_channels
|
401 |
+
self.give_pre_end = give_pre_end
|
402 |
+
self.tanh_out = tanh_out
|
403 |
+
self.attn_level = attn_level
|
404 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
405 |
+
in_ch_mult = (1,) + tuple(ch_mult)
|
406 |
+
block_in = ch * ch_mult[self.num_resolutions - 1]
|
407 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
408 |
+
self.z_shape = (1, z_channels, curr_res, curr_res)
|
409 |
+
logpy.info(
|
410 |
+
"Working with z of shape {} = {} dimensions.".format(
|
411 |
+
self.z_shape, np.prod(self.z_shape)
|
412 |
+
)
|
413 |
+
)
|
414 |
+
|
415 |
+
make_attn_cls = self._make_attn()
|
416 |
+
make_resblock_cls = self._make_resblock()
|
417 |
+
make_conv_cls = self._make_conv()
|
418 |
+
# z to block_in
|
419 |
+
self.conv_in = torch.nn.Conv2d(
|
420 |
+
z_channels, block_in, kernel_size=3, stride=1, padding=1
|
421 |
+
)
|
422 |
+
|
423 |
+
# middle
|
424 |
+
self.mid = nn.Module()
|
425 |
+
self.mid.block_1 = make_resblock_cls(
|
426 |
+
in_channels=block_in,
|
427 |
+
out_channels=block_in,
|
428 |
+
temb_channels=self.temb_ch,
|
429 |
+
dropout=dropout,
|
430 |
+
)
|
431 |
+
self.mid.attn_1 = make_attn_cls(block_in, attn_type=attn_type)
|
432 |
+
self.mid.block_2 = make_resblock_cls(
|
433 |
+
in_channels=block_in,
|
434 |
+
out_channels=block_in,
|
435 |
+
temb_channels=self.temb_ch,
|
436 |
+
dropout=dropout,
|
437 |
+
)
|
438 |
+
|
439 |
+
# upsampling
|
440 |
+
self.up = nn.ModuleList()
|
441 |
+
self.attn_refinement = nn.ModuleList()
|
442 |
+
for i_level in reversed(range(self.num_resolutions)):
|
443 |
+
block = nn.ModuleList()
|
444 |
+
attn = nn.ModuleList()
|
445 |
+
block_out = ch * ch_mult[i_level]
|
446 |
+
for i_block in range(self.num_res_blocks + 1):
|
447 |
+
block.append(
|
448 |
+
make_resblock_cls(
|
449 |
+
in_channels=block_in,
|
450 |
+
out_channels=block_out,
|
451 |
+
temb_channels=self.temb_ch,
|
452 |
+
dropout=dropout,
|
453 |
+
)
|
454 |
+
)
|
455 |
+
block_in = block_out
|
456 |
+
if curr_res in attn_resolutions:
|
457 |
+
attn.append(make_attn_cls(block_in, attn_type=attn_type))
|
458 |
+
up = nn.Module()
|
459 |
+
up.block = block
|
460 |
+
up.attn = attn
|
461 |
+
if i_level != 0:
|
462 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
463 |
+
curr_res = curr_res * 2
|
464 |
+
self.up.insert(0, up) # prepend to get consistent order
|
465 |
+
|
466 |
+
if i_level in self.attn_level:
|
467 |
+
self.attn_refinement.insert(0, make_attn_cls(block_in, attn_type='memory-efficient-cross-attn-fusion', attn_kwargs={}))
|
468 |
+
else:
|
469 |
+
self.attn_refinement.insert(0, Combiner(block_in))
|
470 |
+
# end
|
471 |
+
self.norm_out = Normalize(block_in)
|
472 |
+
self.attn_refinement.append(Combiner(block_in))
|
473 |
+
self.conv_out = make_conv_cls(
|
474 |
+
block_in, out_ch, kernel_size=3, stride=1, padding=1
|
475 |
+
)
|
476 |
+
|
477 |
+
def _make_attn(self) -> Callable:
|
478 |
+
return make_attn
|
479 |
+
|
480 |
+
def _make_resblock(self) -> Callable:
|
481 |
+
return ResnetBlock
|
482 |
+
|
483 |
+
def _make_conv(self) -> Callable:
|
484 |
+
return torch.nn.Conv2d
|
485 |
+
|
486 |
+
def get_last_layer(self, **kwargs):
|
487 |
+
return self.conv_out.weight
|
488 |
+
|
489 |
+
def forward(self, z, ref_context=None, **kwargs):
|
490 |
+
## ref_context: b c 2 h w, 2 means starting and ending frame
|
491 |
+
# assert z.shape[1:] == self.z_shape[1:]
|
492 |
+
# print("ref context:", ref_context)
|
493 |
+
self.last_z_shape = z.shape
|
494 |
+
# timestep embedding
|
495 |
+
temb = None
|
496 |
+
|
497 |
+
# z to block_in
|
498 |
+
h = self.conv_in(z)
|
499 |
+
|
500 |
+
# middle
|
501 |
+
h = self.mid.block_1(h, temb, **kwargs)
|
502 |
+
h = self.mid.attn_1(h, **kwargs)
|
503 |
+
h = self.mid.block_2(h, temb, **kwargs)
|
504 |
+
|
505 |
+
# upsampling
|
506 |
+
for i_level in reversed(range(self.num_resolutions)):
|
507 |
+
for i_block in range(self.num_res_blocks + 1):
|
508 |
+
h = self.up[i_level].block[i_block](h, temb, **kwargs)
|
509 |
+
if len(self.up[i_level].attn) > 0:
|
510 |
+
h = self.up[i_level].attn[i_block](h, **kwargs)
|
511 |
+
if ref_context:
|
512 |
+
h = self.attn_refinement[i_level](x=h, context=ref_context[i_level])
|
513 |
+
if i_level != 0:
|
514 |
+
h = self.up[i_level].upsample(h)
|
515 |
+
|
516 |
+
# end
|
517 |
+
if self.give_pre_end:
|
518 |
+
return h
|
519 |
+
|
520 |
+
h = self.norm_out(h)
|
521 |
+
h = nonlinearity(h)
|
522 |
+
if ref_context:
|
523 |
+
# print(h.shape, ref_context[i_level].shape) #torch.Size([8, 128, 256, 256]) torch.Size([1, 128, 2, 256, 256])
|
524 |
+
h = self.attn_refinement[-1](x=h, context=ref_context[-1])
|
525 |
+
h = self.conv_out(h, **kwargs)
|
526 |
+
if self.tanh_out:
|
527 |
+
h = torch.tanh(h)
|
528 |
+
return h
|
529 |
+
|
530 |
+
#####
|
531 |
+
|
532 |
+
|
533 |
+
from abc import abstractmethod
|
534 |
+
from lvdm.models.utils_diffusion import timestep_embedding
|
535 |
+
|
536 |
+
from torch.utils.checkpoint import checkpoint
|
537 |
+
from lvdm.basics import (
|
538 |
+
zero_module,
|
539 |
+
conv_nd,
|
540 |
+
linear,
|
541 |
+
normalization,
|
542 |
+
)
|
543 |
+
from lvdm.modules.networks.openaimodel3d import Upsample, Downsample
|
544 |
+
class TimestepBlock(nn.Module):
|
545 |
+
"""
|
546 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
547 |
+
"""
|
548 |
+
|
549 |
+
@abstractmethod
|
550 |
+
def forward(self, x: torch.Tensor, emb: torch.Tensor):
|
551 |
+
"""
|
552 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
553 |
+
"""
|
554 |
+
|
555 |
+
class ResBlock(TimestepBlock):
|
556 |
+
"""
|
557 |
+
A residual block that can optionally change the number of channels.
|
558 |
+
:param channels: the number of input channels.
|
559 |
+
:param emb_channels: the number of timestep embedding channels.
|
560 |
+
:param dropout: the rate of dropout.
|
561 |
+
:param out_channels: if specified, the number of out channels.
|
562 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
563 |
+
convolution instead of a smaller 1x1 convolution to change the
|
564 |
+
channels in the skip connection.
|
565 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
566 |
+
:param use_checkpoint: if True, use gradient checkpointing on this module.
|
567 |
+
:param up: if True, use this block for upsampling.
|
568 |
+
:param down: if True, use this block for downsampling.
|
569 |
+
"""
|
570 |
+
|
571 |
+
def __init__(
|
572 |
+
self,
|
573 |
+
channels: int,
|
574 |
+
emb_channels: int,
|
575 |
+
dropout: float,
|
576 |
+
out_channels: Optional[int] = None,
|
577 |
+
use_conv: bool = False,
|
578 |
+
use_scale_shift_norm: bool = False,
|
579 |
+
dims: int = 2,
|
580 |
+
use_checkpoint: bool = False,
|
581 |
+
up: bool = False,
|
582 |
+
down: bool = False,
|
583 |
+
kernel_size: int = 3,
|
584 |
+
exchange_temb_dims: bool = False,
|
585 |
+
skip_t_emb: bool = False,
|
586 |
+
):
|
587 |
+
super().__init__()
|
588 |
+
self.channels = channels
|
589 |
+
self.emb_channels = emb_channels
|
590 |
+
self.dropout = dropout
|
591 |
+
self.out_channels = out_channels or channels
|
592 |
+
self.use_conv = use_conv
|
593 |
+
self.use_checkpoint = use_checkpoint
|
594 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
595 |
+
self.exchange_temb_dims = exchange_temb_dims
|
596 |
+
|
597 |
+
if isinstance(kernel_size, Iterable):
|
598 |
+
padding = [k // 2 for k in kernel_size]
|
599 |
+
else:
|
600 |
+
padding = kernel_size // 2
|
601 |
+
|
602 |
+
self.in_layers = nn.Sequential(
|
603 |
+
normalization(channels),
|
604 |
+
nn.SiLU(),
|
605 |
+
conv_nd(dims, channels, self.out_channels, kernel_size, padding=padding),
|
606 |
+
)
|
607 |
+
|
608 |
+
self.updown = up or down
|
609 |
+
|
610 |
+
if up:
|
611 |
+
self.h_upd = Upsample(channels, False, dims)
|
612 |
+
self.x_upd = Upsample(channels, False, dims)
|
613 |
+
elif down:
|
614 |
+
self.h_upd = Downsample(channels, False, dims)
|
615 |
+
self.x_upd = Downsample(channels, False, dims)
|
616 |
+
else:
|
617 |
+
self.h_upd = self.x_upd = nn.Identity()
|
618 |
+
|
619 |
+
self.skip_t_emb = skip_t_emb
|
620 |
+
self.emb_out_channels = (
|
621 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels
|
622 |
+
)
|
623 |
+
if self.skip_t_emb:
|
624 |
+
# print(f"Skipping timestep embedding in {self.__class__.__name__}")
|
625 |
+
assert not self.use_scale_shift_norm
|
626 |
+
self.emb_layers = None
|
627 |
+
self.exchange_temb_dims = False
|
628 |
+
else:
|
629 |
+
self.emb_layers = nn.Sequential(
|
630 |
+
nn.SiLU(),
|
631 |
+
linear(
|
632 |
+
emb_channels,
|
633 |
+
self.emb_out_channels,
|
634 |
+
),
|
635 |
+
)
|
636 |
+
|
637 |
+
self.out_layers = nn.Sequential(
|
638 |
+
normalization(self.out_channels),
|
639 |
+
nn.SiLU(),
|
640 |
+
nn.Dropout(p=dropout),
|
641 |
+
zero_module(
|
642 |
+
conv_nd(
|
643 |
+
dims,
|
644 |
+
self.out_channels,
|
645 |
+
self.out_channels,
|
646 |
+
kernel_size,
|
647 |
+
padding=padding,
|
648 |
+
)
|
649 |
+
),
|
650 |
+
)
|
651 |
+
|
652 |
+
if self.out_channels == channels:
|
653 |
+
self.skip_connection = nn.Identity()
|
654 |
+
elif use_conv:
|
655 |
+
self.skip_connection = conv_nd(
|
656 |
+
dims, channels, self.out_channels, kernel_size, padding=padding
|
657 |
+
)
|
658 |
+
else:
|
659 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
660 |
+
|
661 |
+
def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
|
662 |
+
"""
|
663 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
664 |
+
:param x: an [N x C x ...] Tensor of features.
|
665 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
666 |
+
:return: an [N x C x ...] Tensor of outputs.
|
667 |
+
"""
|
668 |
+
if self.use_checkpoint:
|
669 |
+
return checkpoint(self._forward, x, emb, use_reentrant=False)
|
670 |
+
else:
|
671 |
+
return self._forward(x, emb)
|
672 |
+
|
673 |
+
def _forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
|
674 |
+
if self.updown:
|
675 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
676 |
+
h = in_rest(x)
|
677 |
+
h = self.h_upd(h)
|
678 |
+
x = self.x_upd(x)
|
679 |
+
h = in_conv(h)
|
680 |
+
else:
|
681 |
+
h = self.in_layers(x)
|
682 |
+
|
683 |
+
if self.skip_t_emb:
|
684 |
+
emb_out = torch.zeros_like(h)
|
685 |
+
else:
|
686 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
687 |
+
while len(emb_out.shape) < len(h.shape):
|
688 |
+
emb_out = emb_out[..., None]
|
689 |
+
if self.use_scale_shift_norm:
|
690 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
691 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
692 |
+
h = out_norm(h) * (1 + scale) + shift
|
693 |
+
h = out_rest(h)
|
694 |
+
else:
|
695 |
+
if self.exchange_temb_dims:
|
696 |
+
emb_out = rearrange(emb_out, "b t c ... -> b c t ...")
|
697 |
+
h = h + emb_out
|
698 |
+
h = self.out_layers(h)
|
699 |
+
return self.skip_connection(x) + h
|
700 |
+
#####
|
701 |
+
|
702 |
+
#####
|
703 |
+
from lvdm.modules.attention_svd import *
|
704 |
+
class VideoTransformerBlock(nn.Module):
|
705 |
+
ATTENTION_MODES = {
|
706 |
+
"softmax": CrossAttention,
|
707 |
+
"softmax-xformers": MemoryEfficientCrossAttention,
|
708 |
+
}
|
709 |
+
|
710 |
+
def __init__(
|
711 |
+
self,
|
712 |
+
dim,
|
713 |
+
n_heads,
|
714 |
+
d_head,
|
715 |
+
dropout=0.0,
|
716 |
+
context_dim=None,
|
717 |
+
gated_ff=True,
|
718 |
+
checkpoint=True,
|
719 |
+
timesteps=None,
|
720 |
+
ff_in=False,
|
721 |
+
inner_dim=None,
|
722 |
+
attn_mode="softmax",
|
723 |
+
disable_self_attn=False,
|
724 |
+
disable_temporal_crossattention=False,
|
725 |
+
switch_temporal_ca_to_sa=False,
|
726 |
+
):
|
727 |
+
super().__init__()
|
728 |
+
|
729 |
+
attn_cls = self.ATTENTION_MODES[attn_mode]
|
730 |
+
|
731 |
+
self.ff_in = ff_in or inner_dim is not None
|
732 |
+
if inner_dim is None:
|
733 |
+
inner_dim = dim
|
734 |
+
|
735 |
+
assert int(n_heads * d_head) == inner_dim
|
736 |
+
|
737 |
+
self.is_res = inner_dim == dim
|
738 |
+
|
739 |
+
if self.ff_in:
|
740 |
+
self.norm_in = nn.LayerNorm(dim)
|
741 |
+
self.ff_in = FeedForward(
|
742 |
+
dim, dim_out=inner_dim, dropout=dropout, glu=gated_ff
|
743 |
+
)
|
744 |
+
|
745 |
+
self.timesteps = timesteps
|
746 |
+
self.disable_self_attn = disable_self_attn
|
747 |
+
if self.disable_self_attn:
|
748 |
+
self.attn1 = attn_cls(
|
749 |
+
query_dim=inner_dim,
|
750 |
+
heads=n_heads,
|
751 |
+
dim_head=d_head,
|
752 |
+
context_dim=context_dim,
|
753 |
+
dropout=dropout,
|
754 |
+
) # is a cross-attention
|
755 |
+
else:
|
756 |
+
self.attn1 = attn_cls(
|
757 |
+
query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout
|
758 |
+
) # is a self-attention
|
759 |
+
|
760 |
+
self.ff = FeedForward(inner_dim, dim_out=dim, dropout=dropout, glu=gated_ff)
|
761 |
+
|
762 |
+
if disable_temporal_crossattention:
|
763 |
+
if switch_temporal_ca_to_sa:
|
764 |
+
raise ValueError
|
765 |
+
else:
|
766 |
+
self.attn2 = None
|
767 |
+
else:
|
768 |
+
self.norm2 = nn.LayerNorm(inner_dim)
|
769 |
+
if switch_temporal_ca_to_sa:
|
770 |
+
self.attn2 = attn_cls(
|
771 |
+
query_dim=inner_dim, heads=n_heads, dim_head=d_head, dropout=dropout
|
772 |
+
) # is a self-attention
|
773 |
+
else:
|
774 |
+
self.attn2 = attn_cls(
|
775 |
+
query_dim=inner_dim,
|
776 |
+
context_dim=context_dim,
|
777 |
+
heads=n_heads,
|
778 |
+
dim_head=d_head,
|
779 |
+
dropout=dropout,
|
780 |
+
) # is self-attn if context is none
|
781 |
+
|
782 |
+
self.norm1 = nn.LayerNorm(inner_dim)
|
783 |
+
self.norm3 = nn.LayerNorm(inner_dim)
|
784 |
+
self.switch_temporal_ca_to_sa = switch_temporal_ca_to_sa
|
785 |
+
|
786 |
+
self.checkpoint = checkpoint
|
787 |
+
if self.checkpoint:
|
788 |
+
print(f"====>{self.__class__.__name__} is using checkpointing")
|
789 |
+
else:
|
790 |
+
print(f"====>{self.__class__.__name__} is NOT using checkpointing")
|
791 |
+
|
792 |
+
def forward(
|
793 |
+
self, x: torch.Tensor, context: torch.Tensor = None, timesteps: int = None
|
794 |
+
) -> torch.Tensor:
|
795 |
+
if self.checkpoint:
|
796 |
+
return checkpoint(self._forward, x, context, timesteps, use_reentrant=False)
|
797 |
+
else:
|
798 |
+
return self._forward(x, context, timesteps=timesteps)
|
799 |
+
|
800 |
+
def _forward(self, x, context=None, timesteps=None):
|
801 |
+
assert self.timesteps or timesteps
|
802 |
+
assert not (self.timesteps and timesteps) or self.timesteps == timesteps
|
803 |
+
timesteps = self.timesteps or timesteps
|
804 |
+
B, S, C = x.shape
|
805 |
+
x = rearrange(x, "(b t) s c -> (b s) t c", t=timesteps)
|
806 |
+
|
807 |
+
if self.ff_in:
|
808 |
+
x_skip = x
|
809 |
+
x = self.ff_in(self.norm_in(x))
|
810 |
+
if self.is_res:
|
811 |
+
x += x_skip
|
812 |
+
|
813 |
+
if self.disable_self_attn:
|
814 |
+
x = self.attn1(self.norm1(x), context=context) + x
|
815 |
+
else:
|
816 |
+
x = self.attn1(self.norm1(x)) + x
|
817 |
+
|
818 |
+
if self.attn2 is not None:
|
819 |
+
if self.switch_temporal_ca_to_sa:
|
820 |
+
x = self.attn2(self.norm2(x)) + x
|
821 |
+
else:
|
822 |
+
x = self.attn2(self.norm2(x), context=context) + x
|
823 |
+
x_skip = x
|
824 |
+
x = self.ff(self.norm3(x))
|
825 |
+
if self.is_res:
|
826 |
+
x += x_skip
|
827 |
+
|
828 |
+
x = rearrange(
|
829 |
+
x, "(b s) t c -> (b t) s c", s=S, b=B // timesteps, c=C, t=timesteps
|
830 |
+
)
|
831 |
+
return x
|
832 |
+
|
833 |
+
def get_last_layer(self):
|
834 |
+
return self.ff.net[-1].weight
|
835 |
+
|
836 |
+
#####
|
837 |
+
|
838 |
+
#####
|
839 |
+
import functools
|
840 |
+
def partialclass(cls, *args, **kwargs):
|
841 |
+
class NewCls(cls):
|
842 |
+
__init__ = functools.partialmethod(cls.__init__, *args, **kwargs)
|
843 |
+
|
844 |
+
return NewCls
|
845 |
+
######
|
846 |
+
|
847 |
+
class VideoResBlock(ResnetBlock):
|
848 |
+
def __init__(
|
849 |
+
self,
|
850 |
+
out_channels,
|
851 |
+
*args,
|
852 |
+
dropout=0.0,
|
853 |
+
video_kernel_size=3,
|
854 |
+
alpha=0.0,
|
855 |
+
merge_strategy="learned",
|
856 |
+
**kwargs,
|
857 |
+
):
|
858 |
+
super().__init__(out_channels=out_channels, dropout=dropout, *args, **kwargs)
|
859 |
+
if video_kernel_size is None:
|
860 |
+
video_kernel_size = [3, 1, 1]
|
861 |
+
self.time_stack = ResBlock(
|
862 |
+
channels=out_channels,
|
863 |
+
emb_channels=0,
|
864 |
+
dropout=dropout,
|
865 |
+
dims=3,
|
866 |
+
use_scale_shift_norm=False,
|
867 |
+
use_conv=False,
|
868 |
+
up=False,
|
869 |
+
down=False,
|
870 |
+
kernel_size=video_kernel_size,
|
871 |
+
use_checkpoint=True,
|
872 |
+
skip_t_emb=True,
|
873 |
+
)
|
874 |
+
|
875 |
+
self.merge_strategy = merge_strategy
|
876 |
+
if self.merge_strategy == "fixed":
|
877 |
+
self.register_buffer("mix_factor", torch.Tensor([alpha]))
|
878 |
+
elif self.merge_strategy == "learned":
|
879 |
+
self.register_parameter(
|
880 |
+
"mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
|
881 |
+
)
|
882 |
+
else:
|
883 |
+
raise ValueError(f"unknown merge strategy {self.merge_strategy}")
|
884 |
+
|
885 |
+
def get_alpha(self, bs):
|
886 |
+
if self.merge_strategy == "fixed":
|
887 |
+
return self.mix_factor
|
888 |
+
elif self.merge_strategy == "learned":
|
889 |
+
return torch.sigmoid(self.mix_factor)
|
890 |
+
else:
|
891 |
+
raise NotImplementedError()
|
892 |
+
|
893 |
+
def forward(self, x, temb, skip_video=False, timesteps=None):
|
894 |
+
if timesteps is None:
|
895 |
+
timesteps = self.timesteps
|
896 |
+
|
897 |
+
b, c, h, w = x.shape
|
898 |
+
|
899 |
+
x = super().forward(x, temb)
|
900 |
+
|
901 |
+
if not skip_video:
|
902 |
+
x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
|
903 |
+
|
904 |
+
x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
|
905 |
+
|
906 |
+
x = self.time_stack(x, temb)
|
907 |
+
|
908 |
+
alpha = self.get_alpha(bs=b // timesteps)
|
909 |
+
x = alpha * x + (1.0 - alpha) * x_mix
|
910 |
+
|
911 |
+
x = rearrange(x, "b c t h w -> (b t) c h w")
|
912 |
+
return x
|
913 |
+
|
914 |
+
|
915 |
+
class AE3DConv(torch.nn.Conv2d):
|
916 |
+
def __init__(self, in_channels, out_channels, video_kernel_size=3, *args, **kwargs):
|
917 |
+
super().__init__(in_channels, out_channels, *args, **kwargs)
|
918 |
+
if isinstance(video_kernel_size, Iterable):
|
919 |
+
padding = [int(k // 2) for k in video_kernel_size]
|
920 |
+
else:
|
921 |
+
padding = int(video_kernel_size // 2)
|
922 |
+
|
923 |
+
self.time_mix_conv = torch.nn.Conv3d(
|
924 |
+
in_channels=out_channels,
|
925 |
+
out_channels=out_channels,
|
926 |
+
kernel_size=video_kernel_size,
|
927 |
+
padding=padding,
|
928 |
+
)
|
929 |
+
|
930 |
+
def forward(self, input, timesteps, skip_video=False):
|
931 |
+
x = super().forward(input)
|
932 |
+
if skip_video:
|
933 |
+
return x
|
934 |
+
x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)
|
935 |
+
x = self.time_mix_conv(x)
|
936 |
+
return rearrange(x, "b c t h w -> (b t) c h w")
|
937 |
+
|
938 |
+
|
939 |
+
class VideoBlock(AttnBlock):
|
940 |
+
def __init__(
|
941 |
+
self, in_channels: int, alpha: float = 0, merge_strategy: str = "learned"
|
942 |
+
):
|
943 |
+
super().__init__(in_channels)
|
944 |
+
# no context, single headed, as in base class
|
945 |
+
self.time_mix_block = VideoTransformerBlock(
|
946 |
+
dim=in_channels,
|
947 |
+
n_heads=1,
|
948 |
+
d_head=in_channels,
|
949 |
+
checkpoint=True,
|
950 |
+
ff_in=True,
|
951 |
+
attn_mode="softmax",
|
952 |
+
)
|
953 |
+
|
954 |
+
time_embed_dim = self.in_channels * 4
|
955 |
+
self.video_time_embed = torch.nn.Sequential(
|
956 |
+
torch.nn.Linear(self.in_channels, time_embed_dim),
|
957 |
+
torch.nn.SiLU(),
|
958 |
+
torch.nn.Linear(time_embed_dim, self.in_channels),
|
959 |
+
)
|
960 |
+
|
961 |
+
self.merge_strategy = merge_strategy
|
962 |
+
if self.merge_strategy == "fixed":
|
963 |
+
self.register_buffer("mix_factor", torch.Tensor([alpha]))
|
964 |
+
elif self.merge_strategy == "learned":
|
965 |
+
self.register_parameter(
|
966 |
+
"mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
|
967 |
+
)
|
968 |
+
else:
|
969 |
+
raise ValueError(f"unknown merge strategy {self.merge_strategy}")
|
970 |
+
|
971 |
+
def forward(self, x, timesteps, skip_video=False):
|
972 |
+
if skip_video:
|
973 |
+
return super().forward(x)
|
974 |
+
|
975 |
+
x_in = x
|
976 |
+
x = self.attention(x)
|
977 |
+
h, w = x.shape[2:]
|
978 |
+
x = rearrange(x, "b c h w -> b (h w) c")
|
979 |
+
|
980 |
+
x_mix = x
|
981 |
+
num_frames = torch.arange(timesteps, device=x.device)
|
982 |
+
num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
|
983 |
+
num_frames = rearrange(num_frames, "b t -> (b t)")
|
984 |
+
t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False)
|
985 |
+
emb = self.video_time_embed(t_emb) # b, n_channels
|
986 |
+
emb = emb[:, None, :]
|
987 |
+
x_mix = x_mix + emb
|
988 |
+
|
989 |
+
alpha = self.get_alpha()
|
990 |
+
x_mix = self.time_mix_block(x_mix, timesteps=timesteps)
|
991 |
+
x = alpha * x + (1.0 - alpha) * x_mix # alpha merge
|
992 |
+
|
993 |
+
x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
|
994 |
+
x = self.proj_out(x)
|
995 |
+
|
996 |
+
return x_in + x
|
997 |
+
|
998 |
+
def get_alpha(
|
999 |
+
self,
|
1000 |
+
):
|
1001 |
+
if self.merge_strategy == "fixed":
|
1002 |
+
return self.mix_factor
|
1003 |
+
elif self.merge_strategy == "learned":
|
1004 |
+
return torch.sigmoid(self.mix_factor)
|
1005 |
+
else:
|
1006 |
+
raise NotImplementedError(f"unknown merge strategy {self.merge_strategy}")
|
1007 |
+
|
1008 |
+
|
1009 |
+
class MemoryEfficientVideoBlock(MemoryEfficientAttnBlock):
|
1010 |
+
def __init__(
|
1011 |
+
self, in_channels: int, alpha: float = 0, merge_strategy: str = "learned"
|
1012 |
+
):
|
1013 |
+
super().__init__(in_channels)
|
1014 |
+
# no context, single headed, as in base class
|
1015 |
+
self.time_mix_block = VideoTransformerBlock(
|
1016 |
+
dim=in_channels,
|
1017 |
+
n_heads=1,
|
1018 |
+
d_head=in_channels,
|
1019 |
+
checkpoint=True,
|
1020 |
+
ff_in=True,
|
1021 |
+
attn_mode="softmax-xformers",
|
1022 |
+
)
|
1023 |
+
|
1024 |
+
time_embed_dim = self.in_channels * 4
|
1025 |
+
self.video_time_embed = torch.nn.Sequential(
|
1026 |
+
torch.nn.Linear(self.in_channels, time_embed_dim),
|
1027 |
+
torch.nn.SiLU(),
|
1028 |
+
torch.nn.Linear(time_embed_dim, self.in_channels),
|
1029 |
+
)
|
1030 |
+
|
1031 |
+
self.merge_strategy = merge_strategy
|
1032 |
+
if self.merge_strategy == "fixed":
|
1033 |
+
self.register_buffer("mix_factor", torch.Tensor([alpha]))
|
1034 |
+
elif self.merge_strategy == "learned":
|
1035 |
+
self.register_parameter(
|
1036 |
+
"mix_factor", torch.nn.Parameter(torch.Tensor([alpha]))
|
1037 |
+
)
|
1038 |
+
else:
|
1039 |
+
raise ValueError(f"unknown merge strategy {self.merge_strategy}")
|
1040 |
+
|
1041 |
+
def forward(self, x, timesteps, skip_time_block=False):
|
1042 |
+
if skip_time_block:
|
1043 |
+
return super().forward(x)
|
1044 |
+
|
1045 |
+
x_in = x
|
1046 |
+
x = self.attention(x)
|
1047 |
+
h, w = x.shape[2:]
|
1048 |
+
x = rearrange(x, "b c h w -> b (h w) c")
|
1049 |
+
|
1050 |
+
x_mix = x
|
1051 |
+
num_frames = torch.arange(timesteps, device=x.device)
|
1052 |
+
num_frames = repeat(num_frames, "t -> b t", b=x.shape[0] // timesteps)
|
1053 |
+
num_frames = rearrange(num_frames, "b t -> (b t)")
|
1054 |
+
t_emb = timestep_embedding(num_frames, self.in_channels, repeat_only=False)
|
1055 |
+
emb = self.video_time_embed(t_emb) # b, n_channels
|
1056 |
+
emb = emb[:, None, :]
|
1057 |
+
x_mix = x_mix + emb
|
1058 |
+
|
1059 |
+
alpha = self.get_alpha()
|
1060 |
+
x_mix = self.time_mix_block(x_mix, timesteps=timesteps)
|
1061 |
+
x = alpha * x + (1.0 - alpha) * x_mix # alpha merge
|
1062 |
+
|
1063 |
+
x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w)
|
1064 |
+
x = self.proj_out(x)
|
1065 |
+
|
1066 |
+
return x_in + x
|
1067 |
+
|
1068 |
+
def get_alpha(
|
1069 |
+
self,
|
1070 |
+
):
|
1071 |
+
if self.merge_strategy == "fixed":
|
1072 |
+
return self.mix_factor
|
1073 |
+
elif self.merge_strategy == "learned":
|
1074 |
+
return torch.sigmoid(self.mix_factor)
|
1075 |
+
else:
|
1076 |
+
raise NotImplementedError(f"unknown merge strategy {self.merge_strategy}")
|
1077 |
+
|
1078 |
+
|
1079 |
+
def make_time_attn(
|
1080 |
+
in_channels,
|
1081 |
+
attn_type="vanilla",
|
1082 |
+
attn_kwargs=None,
|
1083 |
+
alpha: float = 0,
|
1084 |
+
merge_strategy: str = "learned",
|
1085 |
+
):
|
1086 |
+
assert attn_type in [
|
1087 |
+
"vanilla",
|
1088 |
+
"vanilla-xformers",
|
1089 |
+
], f"attn_type {attn_type} not supported for spatio-temporal attention"
|
1090 |
+
print(
|
1091 |
+
f"making spatial and temporal attention of type '{attn_type}' with {in_channels} in_channels"
|
1092 |
+
)
|
1093 |
+
if not XFORMERS_IS_AVAILABLE and attn_type == "vanilla-xformers":
|
1094 |
+
print(
|
1095 |
+
f"Attention mode '{attn_type}' is not available. Falling back to vanilla attention. "
|
1096 |
+
f"This is not a problem in Pytorch >= 2.0. FYI, you are running with PyTorch version {torch.__version__}"
|
1097 |
+
)
|
1098 |
+
attn_type = "vanilla"
|
1099 |
+
|
1100 |
+
if attn_type == "vanilla":
|
1101 |
+
assert attn_kwargs is None
|
1102 |
+
return partialclass(
|
1103 |
+
VideoBlock, in_channels, alpha=alpha, merge_strategy=merge_strategy
|
1104 |
+
)
|
1105 |
+
elif attn_type == "vanilla-xformers":
|
1106 |
+
print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
|
1107 |
+
return partialclass(
|
1108 |
+
MemoryEfficientVideoBlock,
|
1109 |
+
in_channels,
|
1110 |
+
alpha=alpha,
|
1111 |
+
merge_strategy=merge_strategy,
|
1112 |
+
)
|
1113 |
+
else:
|
1114 |
+
return NotImplementedError()
|
1115 |
+
|
1116 |
+
|
1117 |
+
class Conv2DWrapper(torch.nn.Conv2d):
|
1118 |
+
def forward(self, input: torch.Tensor, **kwargs) -> torch.Tensor:
|
1119 |
+
return super().forward(input)
|
1120 |
+
|
1121 |
+
|
1122 |
+
class VideoDecoder(Decoder):
|
1123 |
+
available_time_modes = ["all", "conv-only", "attn-only"]
|
1124 |
+
|
1125 |
+
def __init__(
|
1126 |
+
self,
|
1127 |
+
*args,
|
1128 |
+
video_kernel_size: Union[int, list] = [3,1,1],
|
1129 |
+
alpha: float = 0.0,
|
1130 |
+
merge_strategy: str = "learned",
|
1131 |
+
time_mode: str = "conv-only",
|
1132 |
+
**kwargs,
|
1133 |
+
):
|
1134 |
+
self.video_kernel_size = video_kernel_size
|
1135 |
+
self.alpha = alpha
|
1136 |
+
self.merge_strategy = merge_strategy
|
1137 |
+
self.time_mode = time_mode
|
1138 |
+
assert (
|
1139 |
+
self.time_mode in self.available_time_modes
|
1140 |
+
), f"time_mode parameter has to be in {self.available_time_modes}"
|
1141 |
+
super().__init__(*args, **kwargs)
|
1142 |
+
|
1143 |
+
def get_last_layer(self, skip_time_mix=False, **kwargs):
|
1144 |
+
if self.time_mode == "attn-only":
|
1145 |
+
raise NotImplementedError("TODO")
|
1146 |
+
else:
|
1147 |
+
return (
|
1148 |
+
self.conv_out.time_mix_conv.weight
|
1149 |
+
if not skip_time_mix
|
1150 |
+
else self.conv_out.weight
|
1151 |
+
)
|
1152 |
+
|
1153 |
+
def _make_attn(self) -> Callable:
|
1154 |
+
if self.time_mode not in ["conv-only", "only-last-conv"]:
|
1155 |
+
return partialclass(
|
1156 |
+
make_time_attn,
|
1157 |
+
alpha=self.alpha,
|
1158 |
+
merge_strategy=self.merge_strategy,
|
1159 |
+
)
|
1160 |
+
else:
|
1161 |
+
return super()._make_attn()
|
1162 |
+
|
1163 |
+
def _make_conv(self) -> Callable:
|
1164 |
+
if self.time_mode != "attn-only":
|
1165 |
+
return partialclass(AE3DConv, video_kernel_size=self.video_kernel_size)
|
1166 |
+
else:
|
1167 |
+
return Conv2DWrapper
|
1168 |
+
|
1169 |
+
def _make_resblock(self) -> Callable:
|
1170 |
+
if self.time_mode not in ["attn-only", "only-last-conv"]:
|
1171 |
+
return partialclass(
|
1172 |
+
VideoResBlock,
|
1173 |
+
video_kernel_size=self.video_kernel_size,
|
1174 |
+
alpha=self.alpha,
|
1175 |
+
merge_strategy=self.merge_strategy,
|
1176 |
+
)
|
1177 |
+
else:
|
1178 |
+
return super()._make_resblock()
|
lvdm/models/ddpm3d.py
ADDED
@@ -0,0 +1,1312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
wild mixture of
|
3 |
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
4 |
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
5 |
+
https://github.com/CompVis/taming-transformers
|
6 |
+
-- merci
|
7 |
+
"""
|
8 |
+
|
9 |
+
from functools import partial
|
10 |
+
from contextlib import contextmanager
|
11 |
+
import numpy as np
|
12 |
+
from tqdm import tqdm
|
13 |
+
from einops import rearrange, repeat
|
14 |
+
import logging
|
15 |
+
mainlogger = logging.getLogger('mainlogger')
|
16 |
+
import random
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
from torch.optim.lr_scheduler import LambdaLR, CosineAnnealingLR
|
20 |
+
from torchvision.utils import make_grid
|
21 |
+
import pytorch_lightning as pl
|
22 |
+
from pytorch_lightning.utilities import rank_zero_only
|
23 |
+
from utils.utils import instantiate_from_config
|
24 |
+
from lvdm.ema import LitEma
|
25 |
+
from lvdm.models.samplers.ddim import DDIMSampler
|
26 |
+
from lvdm.distributions import DiagonalGaussianDistribution
|
27 |
+
from lvdm.models.utils_diffusion import make_beta_schedule, rescale_zero_terminal_snr
|
28 |
+
from lvdm.basics import disabled_train
|
29 |
+
from lvdm.common import (
|
30 |
+
extract_into_tensor,
|
31 |
+
noise_like,
|
32 |
+
exists,
|
33 |
+
default
|
34 |
+
)
|
35 |
+
import math
|
36 |
+
from lvdm.models.autoencoder_dualref import VideoDecoder
|
37 |
+
__conditioning_keys__ = {'concat': 'c_concat',
|
38 |
+
'crossattn': 'c_crossattn',
|
39 |
+
'adm': 'y'}
|
40 |
+
|
41 |
+
class DDPM(pl.LightningModule):
|
42 |
+
# classic DDPM with Gaussian diffusion, in image space
|
43 |
+
def __init__(self,
|
44 |
+
unet_config,
|
45 |
+
timesteps=1000,
|
46 |
+
beta_schedule="linear",
|
47 |
+
loss_type="l2",
|
48 |
+
ckpt_path=None,
|
49 |
+
ignore_keys=[],
|
50 |
+
load_only_unet=False,
|
51 |
+
monitor=None,
|
52 |
+
use_ema=True,
|
53 |
+
first_stage_key="image",
|
54 |
+
image_size=256,
|
55 |
+
channels=3,
|
56 |
+
log_every_t=100,
|
57 |
+
clip_denoised=True,
|
58 |
+
linear_start=1e-4,
|
59 |
+
linear_end=2e-2,
|
60 |
+
cosine_s=8e-3,
|
61 |
+
given_betas=None,
|
62 |
+
original_elbo_weight=0.,
|
63 |
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
64 |
+
l_simple_weight=1.,
|
65 |
+
conditioning_key=None,
|
66 |
+
parameterization="eps", # all assuming fixed variance schedules
|
67 |
+
scheduler_config=None,
|
68 |
+
use_positional_encodings=False,
|
69 |
+
learn_logvar=False,
|
70 |
+
logvar_init=0.,
|
71 |
+
rescale_betas_zero_snr=False,
|
72 |
+
):
|
73 |
+
super().__init__()
|
74 |
+
assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
|
75 |
+
self.parameterization = parameterization
|
76 |
+
mainlogger.info(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
|
77 |
+
self.cond_stage_model = None
|
78 |
+
self.clip_denoised = clip_denoised
|
79 |
+
self.log_every_t = log_every_t
|
80 |
+
self.first_stage_key = first_stage_key
|
81 |
+
self.channels = channels
|
82 |
+
self.temporal_length = unet_config.params.temporal_length
|
83 |
+
self.image_size = image_size # try conv?
|
84 |
+
if isinstance(self.image_size, int):
|
85 |
+
self.image_size = [self.image_size, self.image_size]
|
86 |
+
self.use_positional_encodings = use_positional_encodings
|
87 |
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
88 |
+
#count_params(self.model, verbose=True)
|
89 |
+
self.use_ema = use_ema
|
90 |
+
self.rescale_betas_zero_snr = rescale_betas_zero_snr
|
91 |
+
if self.use_ema:
|
92 |
+
self.model_ema = LitEma(self.model)
|
93 |
+
mainlogger.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
94 |
+
|
95 |
+
self.use_scheduler = scheduler_config is not None
|
96 |
+
if self.use_scheduler:
|
97 |
+
self.scheduler_config = scheduler_config
|
98 |
+
|
99 |
+
self.v_posterior = v_posterior
|
100 |
+
self.original_elbo_weight = original_elbo_weight
|
101 |
+
self.l_simple_weight = l_simple_weight
|
102 |
+
|
103 |
+
if monitor is not None:
|
104 |
+
self.monitor = monitor
|
105 |
+
if ckpt_path is not None:
|
106 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
107 |
+
|
108 |
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
109 |
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
110 |
+
|
111 |
+
## for reschedule
|
112 |
+
self.given_betas = given_betas
|
113 |
+
self.beta_schedule = beta_schedule
|
114 |
+
self.timesteps = timesteps
|
115 |
+
self.cosine_s = cosine_s
|
116 |
+
|
117 |
+
self.loss_type = loss_type
|
118 |
+
|
119 |
+
self.learn_logvar = learn_logvar
|
120 |
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
121 |
+
if self.learn_logvar:
|
122 |
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
123 |
+
|
124 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
125 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
126 |
+
if exists(given_betas):
|
127 |
+
betas = given_betas
|
128 |
+
else:
|
129 |
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
130 |
+
cosine_s=cosine_s)
|
131 |
+
if self.rescale_betas_zero_snr:
|
132 |
+
betas = rescale_zero_terminal_snr(betas)
|
133 |
+
|
134 |
+
alphas = 1. - betas
|
135 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
136 |
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
137 |
+
|
138 |
+
timesteps, = betas.shape
|
139 |
+
self.num_timesteps = int(timesteps)
|
140 |
+
self.linear_start = linear_start
|
141 |
+
self.linear_end = linear_end
|
142 |
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
143 |
+
|
144 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
145 |
+
|
146 |
+
self.register_buffer('betas', to_torch(betas))
|
147 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
148 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
149 |
+
|
150 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
151 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
152 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
153 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
154 |
+
|
155 |
+
if self.parameterization != 'v':
|
156 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
157 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
158 |
+
else:
|
159 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', torch.zeros_like(to_torch(alphas_cumprod)))
|
160 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.zeros_like(to_torch(alphas_cumprod)))
|
161 |
+
|
162 |
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
163 |
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
164 |
+
1. - alphas_cumprod) + self.v_posterior * betas
|
165 |
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
166 |
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
167 |
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
168 |
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
169 |
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
170 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
171 |
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
172 |
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
173 |
+
|
174 |
+
if self.parameterization == "eps":
|
175 |
+
lvlb_weights = self.betas ** 2 / (
|
176 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
177 |
+
elif self.parameterization == "x0":
|
178 |
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
179 |
+
elif self.parameterization == "v":
|
180 |
+
lvlb_weights = torch.ones_like(self.betas ** 2 / (
|
181 |
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
|
182 |
+
else:
|
183 |
+
raise NotImplementedError("mu not supported")
|
184 |
+
# TODO how to choose this term
|
185 |
+
lvlb_weights[0] = lvlb_weights[1]
|
186 |
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
187 |
+
assert not torch.isnan(self.lvlb_weights).all()
|
188 |
+
|
189 |
+
@contextmanager
|
190 |
+
def ema_scope(self, context=None):
|
191 |
+
if self.use_ema:
|
192 |
+
self.model_ema.store(self.model.parameters())
|
193 |
+
self.model_ema.copy_to(self.model)
|
194 |
+
if context is not None:
|
195 |
+
mainlogger.info(f"{context}: Switched to EMA weights")
|
196 |
+
try:
|
197 |
+
yield None
|
198 |
+
finally:
|
199 |
+
if self.use_ema:
|
200 |
+
self.model_ema.restore(self.model.parameters())
|
201 |
+
if context is not None:
|
202 |
+
mainlogger.info(f"{context}: Restored training weights")
|
203 |
+
|
204 |
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
205 |
+
sd = torch.load(path, map_location="cpu")
|
206 |
+
if "state_dict" in list(sd.keys()):
|
207 |
+
sd = sd["state_dict"]
|
208 |
+
keys = list(sd.keys())
|
209 |
+
for k in keys:
|
210 |
+
for ik in ignore_keys:
|
211 |
+
if k.startswith(ik):
|
212 |
+
mainlogger.info("Deleting key {} from state_dict.".format(k))
|
213 |
+
del sd[k]
|
214 |
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
215 |
+
sd, strict=False)
|
216 |
+
mainlogger.info(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
217 |
+
if len(missing) > 0:
|
218 |
+
mainlogger.info(f"Missing Keys: {missing}")
|
219 |
+
if len(unexpected) > 0:
|
220 |
+
mainlogger.info(f"Unexpected Keys: {unexpected}")
|
221 |
+
|
222 |
+
def q_mean_variance(self, x_start, t):
|
223 |
+
"""
|
224 |
+
Get the distribution q(x_t | x_0).
|
225 |
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
226 |
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
227 |
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
228 |
+
"""
|
229 |
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
230 |
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
231 |
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
232 |
+
return mean, variance, log_variance
|
233 |
+
|
234 |
+
def predict_start_from_noise(self, x_t, t, noise):
|
235 |
+
return (
|
236 |
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
237 |
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
238 |
+
)
|
239 |
+
|
240 |
+
def predict_start_from_z_and_v(self, x_t, t, v):
|
241 |
+
# self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
242 |
+
# self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
243 |
+
return (
|
244 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
|
245 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
|
246 |
+
)
|
247 |
+
|
248 |
+
def predict_eps_from_z_and_v(self, x_t, t, v):
|
249 |
+
return (
|
250 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
|
251 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
|
252 |
+
)
|
253 |
+
|
254 |
+
def q_posterior(self, x_start, x_t, t):
|
255 |
+
posterior_mean = (
|
256 |
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
257 |
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
258 |
+
)
|
259 |
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
260 |
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
261 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
262 |
+
|
263 |
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
264 |
+
model_out = self.model(x, t)
|
265 |
+
if self.parameterization == "eps":
|
266 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
267 |
+
elif self.parameterization == "x0":
|
268 |
+
x_recon = model_out
|
269 |
+
if clip_denoised:
|
270 |
+
x_recon.clamp_(-1., 1.)
|
271 |
+
|
272 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
273 |
+
return model_mean, posterior_variance, posterior_log_variance
|
274 |
+
|
275 |
+
@torch.no_grad()
|
276 |
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
277 |
+
b, *_, device = *x.shape, x.device
|
278 |
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
279 |
+
noise = noise_like(x.shape, device, repeat_noise)
|
280 |
+
# no noise when t == 0
|
281 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
282 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
283 |
+
|
284 |
+
@torch.no_grad()
|
285 |
+
def p_sample_loop(self, shape, return_intermediates=False):
|
286 |
+
device = self.betas.device
|
287 |
+
b = shape[0]
|
288 |
+
img = torch.randn(shape, device=device)
|
289 |
+
intermediates = [img]
|
290 |
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
291 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
292 |
+
clip_denoised=self.clip_denoised)
|
293 |
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
294 |
+
intermediates.append(img)
|
295 |
+
if return_intermediates:
|
296 |
+
return img, intermediates
|
297 |
+
return img
|
298 |
+
|
299 |
+
@torch.no_grad()
|
300 |
+
def sample(self, batch_size=16, return_intermediates=False):
|
301 |
+
image_size = self.image_size
|
302 |
+
channels = self.channels
|
303 |
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
304 |
+
return_intermediates=return_intermediates)
|
305 |
+
|
306 |
+
def q_sample(self, x_start, t, noise=None):
|
307 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
308 |
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
309 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
310 |
+
|
311 |
+
def get_v(self, x, noise, t):
|
312 |
+
return (
|
313 |
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
|
314 |
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
315 |
+
)
|
316 |
+
|
317 |
+
def get_loss(self, pred, target, mean=True):
|
318 |
+
if self.loss_type == 'l1':
|
319 |
+
loss = (target - pred).abs()
|
320 |
+
if mean:
|
321 |
+
loss = loss.mean()
|
322 |
+
elif self.loss_type == 'l2':
|
323 |
+
if mean:
|
324 |
+
loss = torch.nn.functional.mse_loss(target, pred)
|
325 |
+
else:
|
326 |
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
327 |
+
else:
|
328 |
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
329 |
+
|
330 |
+
return loss
|
331 |
+
|
332 |
+
def p_losses(self, x_start, t, noise=None):
|
333 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
334 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
335 |
+
model_out = self.model(x_noisy, t)
|
336 |
+
|
337 |
+
loss_dict = {}
|
338 |
+
if self.parameterization == "eps":
|
339 |
+
target = noise
|
340 |
+
elif self.parameterization == "x0":
|
341 |
+
target = x_start
|
342 |
+
elif self.parameterization == "v":
|
343 |
+
target = self.get_v(x_start, noise, t)
|
344 |
+
else:
|
345 |
+
raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
|
346 |
+
|
347 |
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
348 |
+
|
349 |
+
log_prefix = 'train' if self.training else 'val'
|
350 |
+
|
351 |
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
352 |
+
loss_simple = loss.mean() * self.l_simple_weight
|
353 |
+
|
354 |
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
355 |
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
356 |
+
|
357 |
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
358 |
+
|
359 |
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
360 |
+
|
361 |
+
return loss, loss_dict
|
362 |
+
|
363 |
+
def forward(self, x, *args, **kwargs):
|
364 |
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
365 |
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
366 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
367 |
+
return self.p_losses(x, t, *args, **kwargs)
|
368 |
+
|
369 |
+
def get_input(self, batch, k):
|
370 |
+
x = batch[k]
|
371 |
+
'''
|
372 |
+
if len(x.shape) == 3:
|
373 |
+
x = x[..., None]
|
374 |
+
x = rearrange(x, 'b h w c -> b c h w')
|
375 |
+
'''
|
376 |
+
x = x.to(memory_format=torch.contiguous_format).float()
|
377 |
+
return x
|
378 |
+
|
379 |
+
def shared_step(self, batch):
|
380 |
+
x = self.get_input(batch, self.first_stage_key)
|
381 |
+
loss, loss_dict = self(x)
|
382 |
+
return loss, loss_dict
|
383 |
+
|
384 |
+
def training_step(self, batch, batch_idx):
|
385 |
+
loss, loss_dict = self.shared_step(batch)
|
386 |
+
|
387 |
+
self.log_dict(loss_dict, prog_bar=True,
|
388 |
+
logger=True, on_step=True, on_epoch=True)
|
389 |
+
|
390 |
+
self.log("global_step", self.global_step,
|
391 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
392 |
+
|
393 |
+
if self.use_scheduler:
|
394 |
+
lr = self.optimizers().param_groups[0]['lr']
|
395 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
396 |
+
|
397 |
+
return loss
|
398 |
+
|
399 |
+
@torch.no_grad()
|
400 |
+
def validation_step(self, batch, batch_idx):
|
401 |
+
_, loss_dict_no_ema = self.shared_step(batch)
|
402 |
+
with self.ema_scope():
|
403 |
+
_, loss_dict_ema = self.shared_step(batch)
|
404 |
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
405 |
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
406 |
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
407 |
+
|
408 |
+
def on_train_batch_end(self, *args, **kwargs):
|
409 |
+
if self.use_ema:
|
410 |
+
self.model_ema(self.model)
|
411 |
+
|
412 |
+
def _get_rows_from_list(self, samples):
|
413 |
+
n_imgs_per_row = len(samples)
|
414 |
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
415 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
416 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
417 |
+
return denoise_grid
|
418 |
+
|
419 |
+
@torch.no_grad()
|
420 |
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
421 |
+
log = dict()
|
422 |
+
x = self.get_input(batch, self.first_stage_key)
|
423 |
+
N = min(x.shape[0], N)
|
424 |
+
n_row = min(x.shape[0], n_row)
|
425 |
+
x = x.to(self.device)[:N]
|
426 |
+
log["inputs"] = x
|
427 |
+
|
428 |
+
# get diffusion row
|
429 |
+
diffusion_row = list()
|
430 |
+
x_start = x[:n_row]
|
431 |
+
|
432 |
+
for t in range(self.num_timesteps):
|
433 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
434 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
435 |
+
t = t.to(self.device).long()
|
436 |
+
noise = torch.randn_like(x_start)
|
437 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
438 |
+
diffusion_row.append(x_noisy)
|
439 |
+
|
440 |
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
441 |
+
|
442 |
+
if sample:
|
443 |
+
# get denoise row
|
444 |
+
with self.ema_scope("Plotting"):
|
445 |
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
446 |
+
|
447 |
+
log["samples"] = samples
|
448 |
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
449 |
+
|
450 |
+
if return_keys:
|
451 |
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
452 |
+
return log
|
453 |
+
else:
|
454 |
+
return {key: log[key] for key in return_keys}
|
455 |
+
return log
|
456 |
+
|
457 |
+
def configure_optimizers(self):
|
458 |
+
lr = self.learning_rate
|
459 |
+
params = list(self.model.parameters())
|
460 |
+
if self.learn_logvar:
|
461 |
+
params = params + [self.logvar]
|
462 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
463 |
+
return opt
|
464 |
+
|
465 |
+
class LatentDiffusion(DDPM):
|
466 |
+
"""main class"""
|
467 |
+
def __init__(self,
|
468 |
+
first_stage_config,
|
469 |
+
cond_stage_config,
|
470 |
+
num_timesteps_cond=None,
|
471 |
+
cond_stage_key="caption",
|
472 |
+
cond_stage_trainable=False,
|
473 |
+
cond_stage_forward=None,
|
474 |
+
conditioning_key=None,
|
475 |
+
uncond_prob=0.2,
|
476 |
+
uncond_type="empty_seq",
|
477 |
+
scale_factor=1.0,
|
478 |
+
scale_by_std=False,
|
479 |
+
encoder_type="2d",
|
480 |
+
only_model=False,
|
481 |
+
noise_strength=0,
|
482 |
+
use_dynamic_rescale=False,
|
483 |
+
base_scale=0.7,
|
484 |
+
turning_step=400,
|
485 |
+
loop_video=False,
|
486 |
+
fps_condition_type='fs',
|
487 |
+
perframe_ae=False,
|
488 |
+
# added
|
489 |
+
logdir=None,
|
490 |
+
rand_cond_frame=False,
|
491 |
+
en_and_decode_n_samples_a_time=None,
|
492 |
+
*args, **kwargs):
|
493 |
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
494 |
+
self.scale_by_std = scale_by_std
|
495 |
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
496 |
+
# for backwards compatibility after implementation of DiffusionWrapper
|
497 |
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
498 |
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
499 |
+
conditioning_key = default(conditioning_key, 'crossattn')
|
500 |
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
501 |
+
|
502 |
+
self.cond_stage_trainable = cond_stage_trainable
|
503 |
+
self.cond_stage_key = cond_stage_key
|
504 |
+
self.noise_strength = noise_strength
|
505 |
+
self.use_dynamic_rescale = use_dynamic_rescale
|
506 |
+
self.loop_video = loop_video
|
507 |
+
self.fps_condition_type = fps_condition_type
|
508 |
+
self.perframe_ae = perframe_ae
|
509 |
+
|
510 |
+
self.logdir = logdir
|
511 |
+
self.rand_cond_frame = rand_cond_frame
|
512 |
+
self.en_and_decode_n_samples_a_time = en_and_decode_n_samples_a_time
|
513 |
+
|
514 |
+
try:
|
515 |
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
516 |
+
except:
|
517 |
+
self.num_downs = 0
|
518 |
+
if not scale_by_std:
|
519 |
+
self.scale_factor = scale_factor
|
520 |
+
else:
|
521 |
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
522 |
+
|
523 |
+
if use_dynamic_rescale:
|
524 |
+
scale_arr1 = np.linspace(1.0, base_scale, turning_step)
|
525 |
+
scale_arr2 = np.full(self.num_timesteps, base_scale)
|
526 |
+
scale_arr = np.concatenate((scale_arr1, scale_arr2))
|
527 |
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
528 |
+
self.register_buffer('scale_arr', to_torch(scale_arr))
|
529 |
+
|
530 |
+
self.instantiate_first_stage(first_stage_config)
|
531 |
+
self.instantiate_cond_stage(cond_stage_config)
|
532 |
+
self.first_stage_config = first_stage_config
|
533 |
+
self.cond_stage_config = cond_stage_config
|
534 |
+
self.clip_denoised = False
|
535 |
+
|
536 |
+
self.cond_stage_forward = cond_stage_forward
|
537 |
+
self.encoder_type = encoder_type
|
538 |
+
assert(encoder_type in ["2d", "3d"])
|
539 |
+
self.uncond_prob = uncond_prob
|
540 |
+
self.classifier_free_guidance = True if uncond_prob > 0 else False
|
541 |
+
assert(uncond_type in ["zero_embed", "empty_seq"])
|
542 |
+
self.uncond_type = uncond_type
|
543 |
+
|
544 |
+
self.restarted_from_ckpt = False
|
545 |
+
if ckpt_path is not None:
|
546 |
+
self.init_from_ckpt(ckpt_path, ignore_keys, only_model=only_model)
|
547 |
+
self.restarted_from_ckpt = True
|
548 |
+
|
549 |
+
def make_cond_schedule(self, ):
|
550 |
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
551 |
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
552 |
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
553 |
+
|
554 |
+
@rank_zero_only
|
555 |
+
@torch.no_grad()
|
556 |
+
def on_train_batch_start(self, batch, batch_idx, dataloader_idx=None):
|
557 |
+
# only for very first batch, reset the self.scale_factor
|
558 |
+
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and \
|
559 |
+
not self.restarted_from_ckpt:
|
560 |
+
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
|
561 |
+
# set rescale weight to 1./std of encodings
|
562 |
+
mainlogger.info("### USING STD-RESCALING ###")
|
563 |
+
x = super().get_input(batch, self.first_stage_key)
|
564 |
+
x = x.to(self.device)
|
565 |
+
encoder_posterior = self.encode_first_stage(x)
|
566 |
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
567 |
+
del self.scale_factor
|
568 |
+
self.register_buffer('scale_factor', 1. / z.flatten().std())
|
569 |
+
mainlogger.info(f"setting self.scale_factor to {self.scale_factor}")
|
570 |
+
mainlogger.info("### USING STD-RESCALING ###")
|
571 |
+
mainlogger.info(f"std={z.flatten().std()}")
|
572 |
+
|
573 |
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
574 |
+
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
575 |
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
576 |
+
|
577 |
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
578 |
+
if self.shorten_cond_schedule:
|
579 |
+
self.make_cond_schedule()
|
580 |
+
|
581 |
+
def instantiate_first_stage(self, config):
|
582 |
+
model = instantiate_from_config(config)
|
583 |
+
self.first_stage_model = model.eval()
|
584 |
+
self.first_stage_model.train = disabled_train
|
585 |
+
for param in self.first_stage_model.parameters():
|
586 |
+
param.requires_grad = False
|
587 |
+
|
588 |
+
def instantiate_cond_stage(self, config):
|
589 |
+
if not self.cond_stage_trainable:
|
590 |
+
model = instantiate_from_config(config)
|
591 |
+
self.cond_stage_model = model.eval()
|
592 |
+
self.cond_stage_model.train = disabled_train
|
593 |
+
for param in self.cond_stage_model.parameters():
|
594 |
+
param.requires_grad = False
|
595 |
+
else:
|
596 |
+
model = instantiate_from_config(config)
|
597 |
+
self.cond_stage_model = model
|
598 |
+
|
599 |
+
def get_learned_conditioning(self, c):
|
600 |
+
if self.cond_stage_forward is None:
|
601 |
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
602 |
+
c = self.cond_stage_model.encode(c)
|
603 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
604 |
+
c = c.mode()
|
605 |
+
else:
|
606 |
+
c = self.cond_stage_model(c)
|
607 |
+
else:
|
608 |
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
609 |
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
610 |
+
return c
|
611 |
+
|
612 |
+
def get_first_stage_encoding(self, encoder_posterior, noise=None):
|
613 |
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
614 |
+
z = encoder_posterior.sample(noise=noise)
|
615 |
+
elif isinstance(encoder_posterior, torch.Tensor):
|
616 |
+
z = encoder_posterior
|
617 |
+
else:
|
618 |
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
619 |
+
return self.scale_factor * z
|
620 |
+
|
621 |
+
@torch.no_grad()
|
622 |
+
def encode_first_stage(self, x):
|
623 |
+
if self.encoder_type == "2d" and x.dim() == 5:
|
624 |
+
b, _, t, _, _ = x.shape
|
625 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
626 |
+
reshape_back = True
|
627 |
+
else:
|
628 |
+
reshape_back = False
|
629 |
+
|
630 |
+
## consume more GPU memory but faster
|
631 |
+
if not self.perframe_ae:
|
632 |
+
encoder_posterior = self.first_stage_model.encode(x)
|
633 |
+
results = self.get_first_stage_encoding(encoder_posterior).detach()
|
634 |
+
else: ## consume less GPU memory but slower
|
635 |
+
results = []
|
636 |
+
for index in range(x.shape[0]):
|
637 |
+
frame_batch = self.first_stage_model.encode(x[index:index+1,:,:,:])
|
638 |
+
frame_result = self.get_first_stage_encoding(frame_batch).detach()
|
639 |
+
results.append(frame_result)
|
640 |
+
results = torch.cat(results, dim=0)
|
641 |
+
|
642 |
+
if reshape_back:
|
643 |
+
results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
|
644 |
+
|
645 |
+
return results
|
646 |
+
|
647 |
+
def decode_core(self, z, **kwargs):
|
648 |
+
if self.encoder_type == "2d" and z.dim() == 5:
|
649 |
+
b, _, t, _, _ = z.shape
|
650 |
+
z = rearrange(z, 'b c t h w -> (b t) c h w')
|
651 |
+
reshape_back = True
|
652 |
+
else:
|
653 |
+
reshape_back = False
|
654 |
+
|
655 |
+
z = 1. / self.scale_factor * z
|
656 |
+
if not self.perframe_ae:
|
657 |
+
results = self.first_stage_model.decode(z, **kwargs)
|
658 |
+
else:
|
659 |
+
|
660 |
+
results = []
|
661 |
+
|
662 |
+
n_samples = default(self.en_and_decode_n_samples_a_time, self.temporal_length)
|
663 |
+
n_rounds = math.ceil(z.shape[0] / n_samples)
|
664 |
+
with torch.autocast("cuda", enabled=True):
|
665 |
+
for n in range(n_rounds):
|
666 |
+
if isinstance(self.first_stage_model.decoder, VideoDecoder):
|
667 |
+
kwargs.update({"timesteps": len(z[n * n_samples : (n + 1) * n_samples])})
|
668 |
+
else:
|
669 |
+
kwargs = {}
|
670 |
+
|
671 |
+
out = self.first_stage_model.decode(
|
672 |
+
z[n * n_samples : (n + 1) * n_samples], **kwargs
|
673 |
+
)
|
674 |
+
results.append(out)
|
675 |
+
results = torch.cat(results, dim=0)
|
676 |
+
|
677 |
+
if reshape_back:
|
678 |
+
results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
|
679 |
+
return results
|
680 |
+
|
681 |
+
@torch.no_grad()
|
682 |
+
def decode_first_stage(self, z, **kwargs):
|
683 |
+
return self.decode_core(z, **kwargs)
|
684 |
+
|
685 |
+
# same as above but without decorator
|
686 |
+
def differentiable_decode_first_stage(self, z, **kwargs):
|
687 |
+
return self.decode_core(z, **kwargs)
|
688 |
+
|
689 |
+
@torch.no_grad()
|
690 |
+
def get_batch_input(self, batch, random_uncond, return_first_stage_outputs=False, return_original_cond=False):
|
691 |
+
## video shape: b, c, t, h, w
|
692 |
+
x = super().get_input(batch, self.first_stage_key)
|
693 |
+
|
694 |
+
## encode video frames x to z via a 2D encoder
|
695 |
+
z = self.encode_first_stage(x)
|
696 |
+
|
697 |
+
## get caption condition
|
698 |
+
cond = batch[self.cond_stage_key]
|
699 |
+
if random_uncond and self.uncond_type == 'empty_seq':
|
700 |
+
for i, ci in enumerate(cond):
|
701 |
+
if random.random() < self.uncond_prob:
|
702 |
+
cond[i] = ""
|
703 |
+
if isinstance(cond, dict) or isinstance(cond, list):
|
704 |
+
cond_emb = self.get_learned_conditioning(cond)
|
705 |
+
else:
|
706 |
+
cond_emb = self.get_learned_conditioning(cond.to(self.device))
|
707 |
+
if random_uncond and self.uncond_type == 'zero_embed':
|
708 |
+
for i, ci in enumerate(cond):
|
709 |
+
if random.random() < self.uncond_prob:
|
710 |
+
cond_emb[i] = torch.zeros_like(cond_emb[i])
|
711 |
+
|
712 |
+
out = [z, cond_emb]
|
713 |
+
## optional output: self-reconst or caption
|
714 |
+
if return_first_stage_outputs:
|
715 |
+
xrec = self.decode_first_stage(z)
|
716 |
+
out.extend([xrec])
|
717 |
+
|
718 |
+
if return_original_cond:
|
719 |
+
out.append(cond)
|
720 |
+
|
721 |
+
return out
|
722 |
+
|
723 |
+
def forward(self, x, c, **kwargs):
|
724 |
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
725 |
+
if self.use_dynamic_rescale:
|
726 |
+
x = x * extract_into_tensor(self.scale_arr, t, x.shape)
|
727 |
+
return self.p_losses(x, c, t, **kwargs)
|
728 |
+
|
729 |
+
def shared_step(self, batch, random_uncond, **kwargs):
|
730 |
+
x, c = self.get_batch_input(batch, random_uncond=random_uncond)
|
731 |
+
loss, loss_dict = self(x, c, **kwargs)
|
732 |
+
|
733 |
+
return loss, loss_dict
|
734 |
+
|
735 |
+
def apply_model(self, x_noisy, t, cond, **kwargs):
|
736 |
+
if isinstance(cond, dict):
|
737 |
+
# hybrid case, cond is exptected to be a dict
|
738 |
+
pass
|
739 |
+
else:
|
740 |
+
if not isinstance(cond, list):
|
741 |
+
cond = [cond]
|
742 |
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
743 |
+
cond = {key: cond}
|
744 |
+
|
745 |
+
x_recon = self.model(x_noisy, t, **cond, **kwargs)
|
746 |
+
|
747 |
+
if isinstance(x_recon, tuple):
|
748 |
+
return x_recon[0]
|
749 |
+
else:
|
750 |
+
return x_recon
|
751 |
+
|
752 |
+
def p_losses(self, x_start, cond, t, noise=None, **kwargs):
|
753 |
+
if self.noise_strength > 0:
|
754 |
+
b, c, f, _, _ = x_start.shape
|
755 |
+
offset_noise = torch.randn(b, c, f, 1, 1, device=x_start.device)
|
756 |
+
noise = default(noise, lambda: torch.randn_like(x_start) + self.noise_strength * offset_noise)
|
757 |
+
else:
|
758 |
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
759 |
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
760 |
+
|
761 |
+
model_output = self.apply_model(x_noisy, t, cond, **kwargs)
|
762 |
+
|
763 |
+
loss_dict = {}
|
764 |
+
prefix = 'train' if self.training else 'val'
|
765 |
+
|
766 |
+
if self.parameterization == "x0":
|
767 |
+
target = x_start
|
768 |
+
elif self.parameterization == "eps":
|
769 |
+
target = noise
|
770 |
+
elif self.parameterization == "v":
|
771 |
+
target = self.get_v(x_start, noise, t)
|
772 |
+
else:
|
773 |
+
raise NotImplementedError()
|
774 |
+
|
775 |
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3, 4])
|
776 |
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
777 |
+
|
778 |
+
if self.logvar.device is not self.device:
|
779 |
+
self.logvar = self.logvar.to(self.device)
|
780 |
+
logvar_t = self.logvar[t]
|
781 |
+
# logvar_t = self.logvar[t.item()].to(self.device) # device conflict when ddp shared
|
782 |
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
783 |
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
784 |
+
if self.learn_logvar:
|
785 |
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
786 |
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
787 |
+
|
788 |
+
loss = self.l_simple_weight * loss.mean()
|
789 |
+
|
790 |
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3, 4))
|
791 |
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
792 |
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
793 |
+
loss += (self.original_elbo_weight * loss_vlb)
|
794 |
+
loss_dict.update({f'{prefix}/loss': loss})
|
795 |
+
|
796 |
+
return loss, loss_dict
|
797 |
+
|
798 |
+
def training_step(self, batch, batch_idx):
|
799 |
+
loss, loss_dict = self.shared_step(batch, random_uncond=self.classifier_free_guidance)
|
800 |
+
## sync_dist | rank_zero_only
|
801 |
+
self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=False)
|
802 |
+
#self.log("epoch/global_step", self.global_step.float(), prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
803 |
+
'''
|
804 |
+
if self.use_scheduler:
|
805 |
+
lr = self.optimizers().param_groups[0]['lr']
|
806 |
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False, rank_zero_only=True)
|
807 |
+
'''
|
808 |
+
if (batch_idx+1) % self.log_every_t == 0:
|
809 |
+
mainlogger.info(f"batch:{batch_idx}|epoch:{self.current_epoch} [globalstep:{self.global_step}]: loss={loss}")
|
810 |
+
return loss
|
811 |
+
|
812 |
+
def _get_denoise_row_from_list(self, samples, desc=''):
|
813 |
+
denoise_row = []
|
814 |
+
for zd in tqdm(samples, desc=desc):
|
815 |
+
denoise_row.append(self.decode_first_stage(zd.to(self.device)))
|
816 |
+
n_log_timesteps = len(denoise_row)
|
817 |
+
|
818 |
+
denoise_row = torch.stack(denoise_row) # n_log_timesteps, b, C, H, W
|
819 |
+
|
820 |
+
if denoise_row.dim() == 5:
|
821 |
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
822 |
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
823 |
+
denoise_grid = make_grid(denoise_grid, nrow=n_log_timesteps)
|
824 |
+
elif denoise_row.dim() == 6:
|
825 |
+
# video, grid_size=[n_log_timesteps*bs, t]
|
826 |
+
video_length = denoise_row.shape[3]
|
827 |
+
denoise_grid = rearrange(denoise_row, 'n b c t h w -> b n c t h w')
|
828 |
+
denoise_grid = rearrange(denoise_grid, 'b n c t h w -> (b n) c t h w')
|
829 |
+
denoise_grid = rearrange(denoise_grid, 'n c t h w -> (n t) c h w')
|
830 |
+
denoise_grid = make_grid(denoise_grid, nrow=video_length)
|
831 |
+
else:
|
832 |
+
raise ValueError
|
833 |
+
|
834 |
+
return denoise_grid
|
835 |
+
|
836 |
+
@torch.no_grad()
|
837 |
+
def log_images(self, batch, sample=True, ddim_steps=200, ddim_eta=1., plot_denoise_rows=False, \
|
838 |
+
unconditional_guidance_scale=1.0, **kwargs):
|
839 |
+
""" log images for LatentDiffusion """
|
840 |
+
##### control sampled imgae for logging, larger value may cause OOM
|
841 |
+
sampled_img_num = 2
|
842 |
+
for key in batch.keys():
|
843 |
+
batch[key] = batch[key][:sampled_img_num]
|
844 |
+
|
845 |
+
## TBD: currently, classifier_free_guidance sampling is only supported by DDIM
|
846 |
+
use_ddim = ddim_steps is not None
|
847 |
+
log = dict()
|
848 |
+
z, c, xrec, xc = self.get_batch_input(batch, random_uncond=False,
|
849 |
+
return_first_stage_outputs=True,
|
850 |
+
return_original_cond=True)
|
851 |
+
|
852 |
+
N = xrec.shape[0]
|
853 |
+
log["reconst"] = xrec
|
854 |
+
log["condition"] = xc
|
855 |
+
|
856 |
+
|
857 |
+
if sample:
|
858 |
+
# get uncond embedding for classifier-free guidance sampling
|
859 |
+
if unconditional_guidance_scale != 1.0:
|
860 |
+
if isinstance(c, dict):
|
861 |
+
c_cat, c_emb = c["c_concat"][0], c["c_crossattn"][0]
|
862 |
+
log["condition_cat"] = c_cat
|
863 |
+
else:
|
864 |
+
c_emb = c
|
865 |
+
|
866 |
+
if self.uncond_type == "empty_seq":
|
867 |
+
prompts = N * [""]
|
868 |
+
uc = self.get_learned_conditioning(prompts)
|
869 |
+
elif self.uncond_type == "zero_embed":
|
870 |
+
uc = torch.zeros_like(c_emb)
|
871 |
+
## hybrid case
|
872 |
+
if isinstance(c, dict):
|
873 |
+
uc_hybrid = {"c_concat": [c_cat], "c_crossattn": [uc]}
|
874 |
+
uc = uc_hybrid
|
875 |
+
else:
|
876 |
+
uc = None
|
877 |
+
|
878 |
+
with self.ema_scope("Plotting"):
|
879 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
880 |
+
ddim_steps=ddim_steps,eta=ddim_eta,
|
881 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
882 |
+
unconditional_conditioning=uc, x0=z, **kwargs)
|
883 |
+
x_samples = self.decode_first_stage(samples)
|
884 |
+
log["samples"] = x_samples
|
885 |
+
|
886 |
+
if plot_denoise_rows:
|
887 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
888 |
+
log["denoise_row"] = denoise_grid
|
889 |
+
|
890 |
+
return log
|
891 |
+
|
892 |
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_x0=False, score_corrector=None, corrector_kwargs=None, **kwargs):
|
893 |
+
t_in = t
|
894 |
+
model_out = self.apply_model(x, t_in, c, **kwargs)
|
895 |
+
|
896 |
+
if score_corrector is not None:
|
897 |
+
assert self.parameterization == "eps"
|
898 |
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
899 |
+
|
900 |
+
if self.parameterization == "eps":
|
901 |
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
902 |
+
elif self.parameterization == "x0":
|
903 |
+
x_recon = model_out
|
904 |
+
else:
|
905 |
+
raise NotImplementedError()
|
906 |
+
|
907 |
+
if clip_denoised:
|
908 |
+
x_recon.clamp_(-1., 1.)
|
909 |
+
|
910 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
911 |
+
|
912 |
+
if return_x0:
|
913 |
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
914 |
+
else:
|
915 |
+
return model_mean, posterior_variance, posterior_log_variance
|
916 |
+
|
917 |
+
@torch.no_grad()
|
918 |
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_x0=False, \
|
919 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, **kwargs):
|
920 |
+
b, *_, device = *x.shape, x.device
|
921 |
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_x0=return_x0, \
|
922 |
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, **kwargs)
|
923 |
+
if return_x0:
|
924 |
+
model_mean, _, model_log_variance, x0 = outputs
|
925 |
+
else:
|
926 |
+
model_mean, _, model_log_variance = outputs
|
927 |
+
|
928 |
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
929 |
+
if noise_dropout > 0.:
|
930 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
931 |
+
# no noise when t == 0
|
932 |
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
933 |
+
|
934 |
+
if return_x0:
|
935 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
936 |
+
else:
|
937 |
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
938 |
+
|
939 |
+
@torch.no_grad()
|
940 |
+
def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, \
|
941 |
+
timesteps=None, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None, **kwargs):
|
942 |
+
|
943 |
+
if not log_every_t:
|
944 |
+
log_every_t = self.log_every_t
|
945 |
+
device = self.betas.device
|
946 |
+
b = shape[0]
|
947 |
+
# sample an initial noise
|
948 |
+
if x_T is None:
|
949 |
+
img = torch.randn(shape, device=device)
|
950 |
+
else:
|
951 |
+
img = x_T
|
952 |
+
|
953 |
+
intermediates = [img]
|
954 |
+
if timesteps is None:
|
955 |
+
timesteps = self.num_timesteps
|
956 |
+
if start_T is not None:
|
957 |
+
timesteps = min(timesteps, start_T)
|
958 |
+
|
959 |
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(range(0, timesteps))
|
960 |
+
|
961 |
+
if mask is not None:
|
962 |
+
assert x0 is not None
|
963 |
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
964 |
+
|
965 |
+
for i in iterator:
|
966 |
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
967 |
+
if self.shorten_cond_schedule:
|
968 |
+
assert self.model.conditioning_key != 'hybrid'
|
969 |
+
tc = self.cond_ids[ts].to(cond.device)
|
970 |
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
971 |
+
|
972 |
+
img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, **kwargs)
|
973 |
+
if mask is not None:
|
974 |
+
img_orig = self.q_sample(x0, ts)
|
975 |
+
img = img_orig * mask + (1. - mask) * img
|
976 |
+
|
977 |
+
if i % log_every_t == 0 or i == timesteps - 1:
|
978 |
+
intermediates.append(img)
|
979 |
+
if callback: callback(i)
|
980 |
+
if img_callback: img_callback(img, i)
|
981 |
+
|
982 |
+
if return_intermediates:
|
983 |
+
return img, intermediates
|
984 |
+
return img
|
985 |
+
|
986 |
+
@torch.no_grad()
|
987 |
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, \
|
988 |
+
verbose=True, timesteps=None, mask=None, x0=None, shape=None, **kwargs):
|
989 |
+
if shape is None:
|
990 |
+
shape = (batch_size, self.channels, self.temporal_length, *self.image_size)
|
991 |
+
if cond is not None:
|
992 |
+
if isinstance(cond, dict):
|
993 |
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
994 |
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
995 |
+
else:
|
996 |
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
997 |
+
return self.p_sample_loop(cond,
|
998 |
+
shape,
|
999 |
+
return_intermediates=return_intermediates, x_T=x_T,
|
1000 |
+
verbose=verbose, timesteps=timesteps,
|
1001 |
+
mask=mask, x0=x0, **kwargs)
|
1002 |
+
|
1003 |
+
@torch.no_grad()
|
1004 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
1005 |
+
if ddim:
|
1006 |
+
ddim_sampler = DDIMSampler(self)
|
1007 |
+
shape = (self.channels, self.temporal_length, *self.image_size)
|
1008 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
|
1009 |
+
|
1010 |
+
else:
|
1011 |
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs)
|
1012 |
+
|
1013 |
+
return samples, intermediates
|
1014 |
+
|
1015 |
+
def configure_schedulers(self, optimizer):
|
1016 |
+
assert 'target' in self.scheduler_config
|
1017 |
+
scheduler_name = self.scheduler_config.target.split('.')[-1]
|
1018 |
+
interval = self.scheduler_config.interval
|
1019 |
+
frequency = self.scheduler_config.frequency
|
1020 |
+
if scheduler_name == "LambdaLRScheduler":
|
1021 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1022 |
+
scheduler.start_step = self.global_step
|
1023 |
+
lr_scheduler = {
|
1024 |
+
'scheduler': LambdaLR(optimizer, lr_lambda=scheduler.schedule),
|
1025 |
+
'interval': interval,
|
1026 |
+
'frequency': frequency
|
1027 |
+
}
|
1028 |
+
elif scheduler_name == "CosineAnnealingLRScheduler":
|
1029 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
1030 |
+
decay_steps = scheduler.decay_steps
|
1031 |
+
last_step = -1 if self.global_step == 0 else scheduler.start_step
|
1032 |
+
lr_scheduler = {
|
1033 |
+
'scheduler': CosineAnnealingLR(optimizer, T_max=decay_steps, last_epoch=last_step),
|
1034 |
+
'interval': interval,
|
1035 |
+
'frequency': frequency
|
1036 |
+
}
|
1037 |
+
else:
|
1038 |
+
raise NotImplementedError
|
1039 |
+
return lr_scheduler
|
1040 |
+
|
1041 |
+
class LatentVisualDiffusion(LatentDiffusion):
|
1042 |
+
def __init__(self, img_cond_stage_config, image_proj_stage_config, freeze_embedder=True, image_proj_model_trainable=True, *args, **kwargs):
|
1043 |
+
super().__init__(*args, **kwargs)
|
1044 |
+
self.image_proj_model_trainable = image_proj_model_trainable
|
1045 |
+
self._init_embedder(img_cond_stage_config, freeze_embedder)
|
1046 |
+
self._init_img_ctx_projector(image_proj_stage_config, image_proj_model_trainable)
|
1047 |
+
|
1048 |
+
def _init_img_ctx_projector(self, config, trainable):
|
1049 |
+
self.image_proj_model = instantiate_from_config(config)
|
1050 |
+
if not trainable:
|
1051 |
+
self.image_proj_model.eval()
|
1052 |
+
self.image_proj_model.train = disabled_train
|
1053 |
+
for param in self.image_proj_model.parameters():
|
1054 |
+
param.requires_grad = False
|
1055 |
+
|
1056 |
+
def _init_embedder(self, config, freeze=True):
|
1057 |
+
self.embedder = instantiate_from_config(config)
|
1058 |
+
if freeze:
|
1059 |
+
self.embedder.eval()
|
1060 |
+
self.embedder.train = disabled_train
|
1061 |
+
for param in self.embedder.parameters():
|
1062 |
+
param.requires_grad = False
|
1063 |
+
|
1064 |
+
def shared_step(self, batch, random_uncond, **kwargs):
|
1065 |
+
x, c, fs = self.get_batch_input(batch, random_uncond=random_uncond, return_fs=True)
|
1066 |
+
kwargs.update({"fs": fs.long()})
|
1067 |
+
loss, loss_dict = self(x, c, **kwargs)
|
1068 |
+
return loss, loss_dict
|
1069 |
+
|
1070 |
+
def get_batch_input(self, batch, random_uncond, return_first_stage_outputs=False, return_original_cond=False, return_fs=False, return_cond_frame=False, return_original_input=False, **kwargs):
|
1071 |
+
## x: b c t h w
|
1072 |
+
x = super().get_input(batch, self.first_stage_key)
|
1073 |
+
## encode video frames x to z via a 2D encoder
|
1074 |
+
z = self.encode_first_stage(x)
|
1075 |
+
|
1076 |
+
## get caption condition
|
1077 |
+
cond_input = batch[self.cond_stage_key]
|
1078 |
+
|
1079 |
+
if isinstance(cond_input, dict) or isinstance(cond_input, list):
|
1080 |
+
cond_emb = self.get_learned_conditioning(cond_input)
|
1081 |
+
else:
|
1082 |
+
cond_emb = self.get_learned_conditioning(cond_input.to(self.device))
|
1083 |
+
|
1084 |
+
cond = {}
|
1085 |
+
## to support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
|
1086 |
+
if random_uncond:
|
1087 |
+
random_num = torch.rand(x.size(0), device=x.device)
|
1088 |
+
else:
|
1089 |
+
random_num = torch.ones(x.size(0), device=x.device) ## by doning so, we can get text embedding and complete img emb for inference
|
1090 |
+
prompt_mask = rearrange(random_num < 2 * self.uncond_prob, "n -> n 1 1")
|
1091 |
+
input_mask = 1 - rearrange((random_num >= self.uncond_prob).float() * (random_num < 3 * self.uncond_prob).float(), "n -> n 1 1 1")
|
1092 |
+
|
1093 |
+
null_prompt = self.get_learned_conditioning([""])
|
1094 |
+
prompt_imb = torch.where(prompt_mask, null_prompt, cond_emb.detach())
|
1095 |
+
|
1096 |
+
## get conditioning frame
|
1097 |
+
cond_frame_index = 0
|
1098 |
+
if self.rand_cond_frame:
|
1099 |
+
cond_frame_index = random.randint(0, self.model.diffusion_model.temporal_length-1)
|
1100 |
+
|
1101 |
+
img = x[:,:,cond_frame_index,...]
|
1102 |
+
img = input_mask * img
|
1103 |
+
## img: b c h w
|
1104 |
+
img_emb = self.embedder(img) ## b l c
|
1105 |
+
img_emb = self.image_proj_model(img_emb)
|
1106 |
+
|
1107 |
+
if self.model.conditioning_key == 'hybrid':
|
1108 |
+
## simply repeat the cond_frame to match the seq_len of z
|
1109 |
+
img_cat_cond = z[:,:,cond_frame_index,:,:]
|
1110 |
+
img_cat_cond = img_cat_cond.unsqueeze(2)
|
1111 |
+
img_cat_cond = repeat(img_cat_cond, 'b c t h w -> b c (repeat t) h w', repeat=z.shape[2])
|
1112 |
+
|
1113 |
+
cond["c_concat"] = [img_cat_cond] # b c t h w
|
1114 |
+
cond["c_crossattn"] = [torch.cat([prompt_imb, img_emb], dim=1)] ## concat in the seq_len dim
|
1115 |
+
|
1116 |
+
out = [z, cond]
|
1117 |
+
if return_first_stage_outputs:
|
1118 |
+
xrec = self.decode_first_stage(z)
|
1119 |
+
out.extend([xrec])
|
1120 |
+
|
1121 |
+
if return_original_cond:
|
1122 |
+
out.append(cond_input)
|
1123 |
+
if return_fs:
|
1124 |
+
if self.fps_condition_type == 'fs':
|
1125 |
+
fs = super().get_input(batch, 'frame_stride')
|
1126 |
+
elif self.fps_condition_type == 'fps':
|
1127 |
+
fs = super().get_input(batch, 'fps')
|
1128 |
+
out.append(fs)
|
1129 |
+
if return_cond_frame:
|
1130 |
+
out.append(x[:,:,cond_frame_index,...].unsqueeze(2))
|
1131 |
+
if return_original_input:
|
1132 |
+
out.append(x)
|
1133 |
+
|
1134 |
+
return out
|
1135 |
+
|
1136 |
+
@torch.no_grad()
|
1137 |
+
def log_images(self, batch, sample=True, ddim_steps=50, ddim_eta=1., plot_denoise_rows=False, \
|
1138 |
+
unconditional_guidance_scale=1.0, mask=None, **kwargs):
|
1139 |
+
""" log images for LatentVisualDiffusion """
|
1140 |
+
##### sampled_img_num: control sampled imgae for logging, larger value may cause OOM
|
1141 |
+
sampled_img_num = 1
|
1142 |
+
for key in batch.keys():
|
1143 |
+
batch[key] = batch[key][:sampled_img_num]
|
1144 |
+
|
1145 |
+
## TBD: currently, classifier_free_guidance sampling is only supported by DDIM
|
1146 |
+
use_ddim = ddim_steps is not None
|
1147 |
+
log = dict()
|
1148 |
+
|
1149 |
+
z, c, xrec, xc, fs, cond_x = self.get_batch_input(batch, random_uncond=False,
|
1150 |
+
return_first_stage_outputs=True,
|
1151 |
+
return_original_cond=True,
|
1152 |
+
return_fs=True,
|
1153 |
+
return_cond_frame=True)
|
1154 |
+
|
1155 |
+
N = xrec.shape[0]
|
1156 |
+
log["image_condition"] = cond_x
|
1157 |
+
log["reconst"] = xrec
|
1158 |
+
xc_with_fs = []
|
1159 |
+
for idx, content in enumerate(xc):
|
1160 |
+
xc_with_fs.append(content + '_fs=' + str(fs[idx].item()))
|
1161 |
+
log["condition"] = xc_with_fs
|
1162 |
+
kwargs.update({"fs": fs.long()})
|
1163 |
+
|
1164 |
+
c_cat = None
|
1165 |
+
if sample:
|
1166 |
+
# get uncond embedding for classifier-free guidance sampling
|
1167 |
+
if unconditional_guidance_scale != 1.0:
|
1168 |
+
if isinstance(c, dict):
|
1169 |
+
c_emb = c["c_crossattn"][0]
|
1170 |
+
if 'c_concat' in c.keys():
|
1171 |
+
c_cat = c["c_concat"][0]
|
1172 |
+
else:
|
1173 |
+
c_emb = c
|
1174 |
+
|
1175 |
+
if self.uncond_type == "empty_seq":
|
1176 |
+
prompts = N * [""]
|
1177 |
+
uc_prompt = self.get_learned_conditioning(prompts)
|
1178 |
+
elif self.uncond_type == "zero_embed":
|
1179 |
+
uc_prompt = torch.zeros_like(c_emb)
|
1180 |
+
|
1181 |
+
img = torch.zeros_like(xrec[:,:,0]) ## b c h w
|
1182 |
+
## img: b c h w
|
1183 |
+
img_emb = self.embedder(img) ## b l c
|
1184 |
+
uc_img = self.image_proj_model(img_emb)
|
1185 |
+
|
1186 |
+
uc = torch.cat([uc_prompt, uc_img], dim=1)
|
1187 |
+
## hybrid case
|
1188 |
+
if isinstance(c, dict):
|
1189 |
+
uc_hybrid = {"c_concat": [c_cat], "c_crossattn": [uc]}
|
1190 |
+
uc = uc_hybrid
|
1191 |
+
else:
|
1192 |
+
uc = None
|
1193 |
+
|
1194 |
+
with self.ema_scope("Plotting"):
|
1195 |
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
1196 |
+
ddim_steps=ddim_steps,eta=ddim_eta,
|
1197 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
1198 |
+
unconditional_conditioning=uc, x0=z, **kwargs)
|
1199 |
+
x_samples = self.decode_first_stage(samples)
|
1200 |
+
log["samples"] = x_samples
|
1201 |
+
|
1202 |
+
if plot_denoise_rows:
|
1203 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
1204 |
+
log["denoise_row"] = denoise_grid
|
1205 |
+
|
1206 |
+
return log
|
1207 |
+
|
1208 |
+
def configure_optimizers(self):
|
1209 |
+
""" configure_optimizers for LatentDiffusion """
|
1210 |
+
lr = self.learning_rate
|
1211 |
+
|
1212 |
+
params = list(self.model.parameters())
|
1213 |
+
mainlogger.info(f"@Training [{len(params)}] Full Paramters.")
|
1214 |
+
|
1215 |
+
if self.cond_stage_trainable:
|
1216 |
+
params_cond_stage = [p for p in self.cond_stage_model.parameters() if p.requires_grad == True]
|
1217 |
+
mainlogger.info(f"@Training [{len(params_cond_stage)}] Paramters for Cond_stage_model.")
|
1218 |
+
params.extend(params_cond_stage)
|
1219 |
+
|
1220 |
+
if self.image_proj_model_trainable:
|
1221 |
+
mainlogger.info(f"@Training [{len(list(self.image_proj_model.parameters()))}] Paramters for Image_proj_model.")
|
1222 |
+
params.extend(list(self.image_proj_model.parameters()))
|
1223 |
+
|
1224 |
+
if self.learn_logvar:
|
1225 |
+
mainlogger.info('Diffusion model optimizing logvar')
|
1226 |
+
if isinstance(params[0], dict):
|
1227 |
+
params.append({"params": [self.logvar]})
|
1228 |
+
else:
|
1229 |
+
params.append(self.logvar)
|
1230 |
+
|
1231 |
+
## optimizer
|
1232 |
+
optimizer = torch.optim.AdamW(params, lr=lr)
|
1233 |
+
|
1234 |
+
## lr scheduler
|
1235 |
+
if self.use_scheduler:
|
1236 |
+
mainlogger.info("Setting up scheduler...")
|
1237 |
+
lr_scheduler = self.configure_schedulers(optimizer)
|
1238 |
+
return [optimizer], [lr_scheduler]
|
1239 |
+
|
1240 |
+
return optimizer
|
1241 |
+
|
1242 |
+
|
1243 |
+
class DiffusionWrapper(pl.LightningModule):
|
1244 |
+
def __init__(self, diff_model_config, conditioning_key):
|
1245 |
+
super().__init__()
|
1246 |
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
1247 |
+
self.conditioning_key = conditioning_key
|
1248 |
+
|
1249 |
+
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None,
|
1250 |
+
c_adm=None, s=None, mask=None, **kwargs):
|
1251 |
+
# temporal_context = fps is foNone
|
1252 |
+
if self.conditioning_key is None:
|
1253 |
+
out = self.diffusion_model(x, t)
|
1254 |
+
elif self.conditioning_key == 'concat':
|
1255 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1256 |
+
out = self.diffusion_model(xc, t, **kwargs)
|
1257 |
+
elif self.conditioning_key == 'crossattn':
|
1258 |
+
cc = torch.cat(c_crossattn, 1)
|
1259 |
+
out = self.diffusion_model(x, t, context=cc, **kwargs)
|
1260 |
+
elif self.conditioning_key == 'hybrid':
|
1261 |
+
## it is just right [b,c,t,h,w]: concatenate in channel dim
|
1262 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1263 |
+
cc = torch.cat(c_crossattn, 1)
|
1264 |
+
out = self.diffusion_model(xc, t, context=cc, **kwargs)
|
1265 |
+
elif self.conditioning_key == 'resblockcond':
|
1266 |
+
cc = c_crossattn[0]
|
1267 |
+
out = self.diffusion_model(x, t, context=cc)
|
1268 |
+
elif self.conditioning_key == 'adm':
|
1269 |
+
cc = c_crossattn[0]
|
1270 |
+
out = self.diffusion_model(x, t, y=cc)
|
1271 |
+
elif self.conditioning_key == 'hybrid-adm':
|
1272 |
+
assert c_adm is not None
|
1273 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1274 |
+
cc = torch.cat(c_crossattn, 1)
|
1275 |
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm, **kwargs)
|
1276 |
+
elif self.conditioning_key == 'hybrid-time':
|
1277 |
+
assert s is not None
|
1278 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1279 |
+
cc = torch.cat(c_crossattn, 1)
|
1280 |
+
out = self.diffusion_model(xc, t, context=cc, s=s)
|
1281 |
+
elif self.conditioning_key == 'concat-time-mask':
|
1282 |
+
# assert s is not None
|
1283 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1284 |
+
out = self.diffusion_model(xc, t, context=None, s=s, mask=mask)
|
1285 |
+
elif self.conditioning_key == 'concat-adm-mask':
|
1286 |
+
# assert s is not None
|
1287 |
+
if c_concat is not None:
|
1288 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1289 |
+
else:
|
1290 |
+
xc = x
|
1291 |
+
out = self.diffusion_model(xc, t, context=None, y=s, mask=mask)
|
1292 |
+
elif self.conditioning_key == 'hybrid-adm-mask':
|
1293 |
+
cc = torch.cat(c_crossattn, 1)
|
1294 |
+
if c_concat is not None:
|
1295 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1296 |
+
else:
|
1297 |
+
xc = x
|
1298 |
+
out = self.diffusion_model(xc, t, context=cc, y=s, mask=mask)
|
1299 |
+
elif self.conditioning_key == 'hybrid-time-adm': # adm means y, e.g., class index
|
1300 |
+
# assert s is not None
|
1301 |
+
assert c_adm is not None
|
1302 |
+
xc = torch.cat([x] + c_concat, dim=1)
|
1303 |
+
cc = torch.cat(c_crossattn, 1)
|
1304 |
+
out = self.diffusion_model(xc, t, context=cc, s=s, y=c_adm)
|
1305 |
+
elif self.conditioning_key == 'crossattn-adm':
|
1306 |
+
assert c_adm is not None
|
1307 |
+
cc = torch.cat(c_crossattn, 1)
|
1308 |
+
out = self.diffusion_model(x, t, context=cc, y=c_adm)
|
1309 |
+
else:
|
1310 |
+
raise NotImplementedError()
|
1311 |
+
|
1312 |
+
return out
|
lvdm/models/samplers/ddim.py
ADDED
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from tqdm import tqdm
|
3 |
+
import torch
|
4 |
+
from lvdm.models.utils_diffusion import make_ddim_sampling_parameters, make_ddim_timesteps, rescale_noise_cfg
|
5 |
+
from lvdm.common import noise_like
|
6 |
+
from lvdm.common import extract_into_tensor
|
7 |
+
import copy
|
8 |
+
|
9 |
+
|
10 |
+
class DDIMSampler(object):
|
11 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
12 |
+
super().__init__()
|
13 |
+
self.model = model
|
14 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
15 |
+
self.schedule = schedule
|
16 |
+
self.counter = 0
|
17 |
+
|
18 |
+
def register_buffer(self, name, attr):
|
19 |
+
if type(attr) == torch.Tensor:
|
20 |
+
if attr.device != torch.device("cuda"):
|
21 |
+
attr = attr.to(torch.device("cuda"))
|
22 |
+
setattr(self, name, attr)
|
23 |
+
|
24 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
25 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
26 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
27 |
+
alphas_cumprod = self.model.alphas_cumprod
|
28 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
29 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
30 |
+
|
31 |
+
if self.model.use_dynamic_rescale:
|
32 |
+
self.ddim_scale_arr = self.model.scale_arr[self.ddim_timesteps]
|
33 |
+
self.ddim_scale_arr_prev = torch.cat([self.ddim_scale_arr[0:1], self.ddim_scale_arr[:-1]])
|
34 |
+
|
35 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
36 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
37 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
38 |
+
|
39 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
40 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
41 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
42 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
43 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
44 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
45 |
+
|
46 |
+
# ddim sampling parameters
|
47 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
48 |
+
ddim_timesteps=self.ddim_timesteps,
|
49 |
+
eta=ddim_eta,verbose=verbose)
|
50 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
51 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
52 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
53 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
54 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
55 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
56 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
57 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
58 |
+
|
59 |
+
@torch.no_grad()
|
60 |
+
def sample(self,
|
61 |
+
S,
|
62 |
+
batch_size,
|
63 |
+
shape,
|
64 |
+
conditioning=None,
|
65 |
+
callback=None,
|
66 |
+
normals_sequence=None,
|
67 |
+
img_callback=None,
|
68 |
+
quantize_x0=False,
|
69 |
+
eta=0.,
|
70 |
+
mask=None,
|
71 |
+
x0=None,
|
72 |
+
temperature=1.,
|
73 |
+
noise_dropout=0.,
|
74 |
+
score_corrector=None,
|
75 |
+
corrector_kwargs=None,
|
76 |
+
verbose=True,
|
77 |
+
schedule_verbose=False,
|
78 |
+
x_T=None,
|
79 |
+
log_every_t=100,
|
80 |
+
unconditional_guidance_scale=1.,
|
81 |
+
unconditional_conditioning=None,
|
82 |
+
precision=None,
|
83 |
+
fs=None,
|
84 |
+
timestep_spacing='uniform', #uniform_trailing for starting from last timestep
|
85 |
+
guidance_rescale=0.0,
|
86 |
+
**kwargs
|
87 |
+
):
|
88 |
+
|
89 |
+
# check condition bs
|
90 |
+
if conditioning is not None:
|
91 |
+
if isinstance(conditioning, dict):
|
92 |
+
try:
|
93 |
+
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
|
94 |
+
except:
|
95 |
+
cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]
|
96 |
+
|
97 |
+
if cbs != batch_size:
|
98 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
99 |
+
else:
|
100 |
+
if conditioning.shape[0] != batch_size:
|
101 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
102 |
+
|
103 |
+
self.make_schedule(ddim_num_steps=S, ddim_discretize=timestep_spacing, ddim_eta=eta, verbose=schedule_verbose)
|
104 |
+
|
105 |
+
# make shape
|
106 |
+
if len(shape) == 3:
|
107 |
+
C, H, W = shape
|
108 |
+
size = (batch_size, C, H, W)
|
109 |
+
elif len(shape) == 4:
|
110 |
+
C, T, H, W = shape
|
111 |
+
size = (batch_size, C, T, H, W)
|
112 |
+
|
113 |
+
samples, intermediates = self.ddim_sampling(conditioning, size,
|
114 |
+
callback=callback,
|
115 |
+
img_callback=img_callback,
|
116 |
+
quantize_denoised=quantize_x0,
|
117 |
+
mask=mask, x0=x0,
|
118 |
+
ddim_use_original_steps=False,
|
119 |
+
noise_dropout=noise_dropout,
|
120 |
+
temperature=temperature,
|
121 |
+
score_corrector=score_corrector,
|
122 |
+
corrector_kwargs=corrector_kwargs,
|
123 |
+
x_T=x_T,
|
124 |
+
log_every_t=log_every_t,
|
125 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
126 |
+
unconditional_conditioning=unconditional_conditioning,
|
127 |
+
verbose=verbose,
|
128 |
+
precision=precision,
|
129 |
+
fs=fs,
|
130 |
+
guidance_rescale=guidance_rescale,
|
131 |
+
**kwargs)
|
132 |
+
return samples, intermediates
|
133 |
+
|
134 |
+
@torch.no_grad()
|
135 |
+
def ddim_sampling(self, cond, shape,
|
136 |
+
x_T=None, ddim_use_original_steps=False,
|
137 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
138 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
139 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
140 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, verbose=True,precision=None,fs=None,guidance_rescale=0.0,
|
141 |
+
**kwargs):
|
142 |
+
device = self.model.betas.device
|
143 |
+
b = shape[0]
|
144 |
+
if x_T is None:
|
145 |
+
img = torch.randn(shape, device=device)
|
146 |
+
else:
|
147 |
+
img = x_T
|
148 |
+
if precision is not None:
|
149 |
+
if precision == 16:
|
150 |
+
img = img.to(dtype=torch.float16)
|
151 |
+
|
152 |
+
if timesteps is None:
|
153 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
154 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
155 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
156 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
157 |
+
|
158 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
159 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
160 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
161 |
+
if verbose:
|
162 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
163 |
+
else:
|
164 |
+
iterator = time_range
|
165 |
+
|
166 |
+
clean_cond = kwargs.pop("clean_cond", False)
|
167 |
+
|
168 |
+
# cond_copy, unconditional_conditioning_copy = copy.deepcopy(cond), copy.deepcopy(unconditional_conditioning)
|
169 |
+
for i, step in enumerate(iterator):
|
170 |
+
index = total_steps - i - 1
|
171 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
172 |
+
|
173 |
+
## use mask to blend noised original latent (img_orig) & new sampled latent (img)
|
174 |
+
if mask is not None:
|
175 |
+
assert x0 is not None
|
176 |
+
if clean_cond:
|
177 |
+
img_orig = x0
|
178 |
+
else:
|
179 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? <ddim inversion>
|
180 |
+
img = img_orig * mask + (1. - mask) * img # keep original & modify use img
|
181 |
+
|
182 |
+
|
183 |
+
|
184 |
+
|
185 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
186 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
187 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
188 |
+
corrector_kwargs=corrector_kwargs,
|
189 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
190 |
+
unconditional_conditioning=unconditional_conditioning,
|
191 |
+
mask=mask,x0=x0,fs=fs,guidance_rescale=guidance_rescale,
|
192 |
+
**kwargs)
|
193 |
+
|
194 |
+
|
195 |
+
img, pred_x0 = outs
|
196 |
+
if callback: callback(i)
|
197 |
+
if img_callback: img_callback(pred_x0, i)
|
198 |
+
|
199 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
200 |
+
intermediates['x_inter'].append(img)
|
201 |
+
intermediates['pred_x0'].append(pred_x0)
|
202 |
+
|
203 |
+
return img, intermediates
|
204 |
+
|
205 |
+
@torch.no_grad()
|
206 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
207 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
208 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
209 |
+
uc_type=None, conditional_guidance_scale_temporal=None,mask=None,x0=None,guidance_rescale=0.0,**kwargs):
|
210 |
+
b, *_, device = *x.shape, x.device
|
211 |
+
if x.dim() == 5:
|
212 |
+
is_video = True
|
213 |
+
else:
|
214 |
+
is_video = False
|
215 |
+
|
216 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
217 |
+
model_output = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
|
218 |
+
else:
|
219 |
+
### do_classifier_free_guidance
|
220 |
+
if isinstance(c, torch.Tensor) or isinstance(c, dict):
|
221 |
+
e_t_cond = self.model.apply_model(x, t, c, **kwargs)
|
222 |
+
e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **kwargs)
|
223 |
+
else:
|
224 |
+
raise NotImplementedError
|
225 |
+
|
226 |
+
model_output = e_t_uncond + unconditional_guidance_scale * (e_t_cond - e_t_uncond)
|
227 |
+
|
228 |
+
if guidance_rescale > 0.0:
|
229 |
+
model_output = rescale_noise_cfg(model_output, e_t_cond, guidance_rescale=guidance_rescale)
|
230 |
+
|
231 |
+
if self.model.parameterization == "v":
|
232 |
+
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
|
233 |
+
else:
|
234 |
+
e_t = model_output
|
235 |
+
|
236 |
+
if score_corrector is not None:
|
237 |
+
assert self.model.parameterization == "eps", 'not implemented'
|
238 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
239 |
+
|
240 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
241 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
242 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
243 |
+
# sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
244 |
+
sigmas = self.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
245 |
+
# select parameters corresponding to the currently considered timestep
|
246 |
+
|
247 |
+
if is_video:
|
248 |
+
size = (b, 1, 1, 1, 1)
|
249 |
+
else:
|
250 |
+
size = (b, 1, 1, 1)
|
251 |
+
a_t = torch.full(size, alphas[index], device=device)
|
252 |
+
a_prev = torch.full(size, alphas_prev[index], device=device)
|
253 |
+
sigma_t = torch.full(size, sigmas[index], device=device)
|
254 |
+
sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
|
255 |
+
|
256 |
+
# current prediction for x_0
|
257 |
+
if self.model.parameterization != "v":
|
258 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
259 |
+
else:
|
260 |
+
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
|
261 |
+
|
262 |
+
if self.model.use_dynamic_rescale:
|
263 |
+
scale_t = torch.full(size, self.ddim_scale_arr[index], device=device)
|
264 |
+
prev_scale_t = torch.full(size, self.ddim_scale_arr_prev[index], device=device)
|
265 |
+
rescale = (prev_scale_t / scale_t)
|
266 |
+
pred_x0 *= rescale
|
267 |
+
|
268 |
+
if quantize_denoised:
|
269 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
270 |
+
# direction pointing to x_t
|
271 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
272 |
+
|
273 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
274 |
+
if noise_dropout > 0.:
|
275 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
276 |
+
|
277 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
278 |
+
|
279 |
+
return x_prev, pred_x0
|
280 |
+
|
281 |
+
@torch.no_grad()
|
282 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
283 |
+
use_original_steps=False, callback=None):
|
284 |
+
|
285 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
286 |
+
timesteps = timesteps[:t_start]
|
287 |
+
|
288 |
+
time_range = np.flip(timesteps)
|
289 |
+
total_steps = timesteps.shape[0]
|
290 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
291 |
+
|
292 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
293 |
+
x_dec = x_latent
|
294 |
+
for i, step in enumerate(iterator):
|
295 |
+
index = total_steps - i - 1
|
296 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
297 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
298 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
299 |
+
unconditional_conditioning=unconditional_conditioning)
|
300 |
+
if callback: callback(i)
|
301 |
+
return x_dec
|
302 |
+
|
303 |
+
@torch.no_grad()
|
304 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
305 |
+
# fast, but does not allow for exact reconstruction
|
306 |
+
# t serves as an index to gather the correct alphas
|
307 |
+
if use_original_steps:
|
308 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
309 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
310 |
+
else:
|
311 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
312 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
313 |
+
|
314 |
+
if noise is None:
|
315 |
+
noise = torch.randn_like(x0)
|
316 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
317 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
lvdm/models/samplers/ddim_multiplecond.py
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from tqdm import tqdm
|
3 |
+
import torch
|
4 |
+
from lvdm.models.utils_diffusion import make_ddim_sampling_parameters, make_ddim_timesteps, rescale_noise_cfg
|
5 |
+
from lvdm.common import noise_like
|
6 |
+
from lvdm.common import extract_into_tensor
|
7 |
+
import copy
|
8 |
+
|
9 |
+
|
10 |
+
class DDIMSampler(object):
|
11 |
+
def __init__(self, model, schedule="linear", **kwargs):
|
12 |
+
super().__init__()
|
13 |
+
self.model = model
|
14 |
+
self.ddpm_num_timesteps = model.num_timesteps
|
15 |
+
self.schedule = schedule
|
16 |
+
self.counter = 0
|
17 |
+
|
18 |
+
def register_buffer(self, name, attr):
|
19 |
+
if type(attr) == torch.Tensor:
|
20 |
+
if attr.device != torch.device("cuda"):
|
21 |
+
attr = attr.to(torch.device("cuda"))
|
22 |
+
setattr(self, name, attr)
|
23 |
+
|
24 |
+
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
25 |
+
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
26 |
+
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
27 |
+
alphas_cumprod = self.model.alphas_cumprod
|
28 |
+
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
29 |
+
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
30 |
+
|
31 |
+
if self.model.use_dynamic_rescale:
|
32 |
+
self.ddim_scale_arr = self.model.scale_arr[self.ddim_timesteps]
|
33 |
+
self.ddim_scale_arr_prev = torch.cat([self.ddim_scale_arr[0:1], self.ddim_scale_arr[:-1]])
|
34 |
+
|
35 |
+
self.register_buffer('betas', to_torch(self.model.betas))
|
36 |
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
37 |
+
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
38 |
+
|
39 |
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
40 |
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
41 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
42 |
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
43 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
44 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
45 |
+
|
46 |
+
# ddim sampling parameters
|
47 |
+
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
48 |
+
ddim_timesteps=self.ddim_timesteps,
|
49 |
+
eta=ddim_eta,verbose=verbose)
|
50 |
+
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
51 |
+
self.register_buffer('ddim_alphas', ddim_alphas)
|
52 |
+
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
53 |
+
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
54 |
+
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
55 |
+
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
56 |
+
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
57 |
+
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
58 |
+
|
59 |
+
@torch.no_grad()
|
60 |
+
def sample(self,
|
61 |
+
S,
|
62 |
+
batch_size,
|
63 |
+
shape,
|
64 |
+
conditioning=None,
|
65 |
+
callback=None,
|
66 |
+
normals_sequence=None,
|
67 |
+
img_callback=None,
|
68 |
+
quantize_x0=False,
|
69 |
+
eta=0.,
|
70 |
+
mask=None,
|
71 |
+
x0=None,
|
72 |
+
temperature=1.,
|
73 |
+
noise_dropout=0.,
|
74 |
+
score_corrector=None,
|
75 |
+
corrector_kwargs=None,
|
76 |
+
verbose=True,
|
77 |
+
schedule_verbose=False,
|
78 |
+
x_T=None,
|
79 |
+
log_every_t=100,
|
80 |
+
unconditional_guidance_scale=1.,
|
81 |
+
unconditional_conditioning=None,
|
82 |
+
precision=None,
|
83 |
+
fs=None,
|
84 |
+
timestep_spacing='uniform', #uniform_trailing for starting from last timestep
|
85 |
+
guidance_rescale=0.0,
|
86 |
+
# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
87 |
+
**kwargs
|
88 |
+
):
|
89 |
+
|
90 |
+
# check condition bs
|
91 |
+
if conditioning is not None:
|
92 |
+
if isinstance(conditioning, dict):
|
93 |
+
try:
|
94 |
+
cbs = conditioning[list(conditioning.keys())[0]].shape[0]
|
95 |
+
except:
|
96 |
+
cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]
|
97 |
+
|
98 |
+
if cbs != batch_size:
|
99 |
+
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
100 |
+
else:
|
101 |
+
if conditioning.shape[0] != batch_size:
|
102 |
+
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
103 |
+
|
104 |
+
# print('==> timestep_spacing: ', timestep_spacing, guidance_rescale)
|
105 |
+
self.make_schedule(ddim_num_steps=S, ddim_discretize=timestep_spacing, ddim_eta=eta, verbose=schedule_verbose)
|
106 |
+
|
107 |
+
# make shape
|
108 |
+
if len(shape) == 3:
|
109 |
+
C, H, W = shape
|
110 |
+
size = (batch_size, C, H, W)
|
111 |
+
elif len(shape) == 4:
|
112 |
+
C, T, H, W = shape
|
113 |
+
size = (batch_size, C, T, H, W)
|
114 |
+
# print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
115 |
+
|
116 |
+
samples, intermediates = self.ddim_sampling(conditioning, size,
|
117 |
+
callback=callback,
|
118 |
+
img_callback=img_callback,
|
119 |
+
quantize_denoised=quantize_x0,
|
120 |
+
mask=mask, x0=x0,
|
121 |
+
ddim_use_original_steps=False,
|
122 |
+
noise_dropout=noise_dropout,
|
123 |
+
temperature=temperature,
|
124 |
+
score_corrector=score_corrector,
|
125 |
+
corrector_kwargs=corrector_kwargs,
|
126 |
+
x_T=x_T,
|
127 |
+
log_every_t=log_every_t,
|
128 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
129 |
+
unconditional_conditioning=unconditional_conditioning,
|
130 |
+
verbose=verbose,
|
131 |
+
precision=precision,
|
132 |
+
fs=fs,
|
133 |
+
guidance_rescale=guidance_rescale,
|
134 |
+
**kwargs)
|
135 |
+
return samples, intermediates
|
136 |
+
|
137 |
+
@torch.no_grad()
|
138 |
+
def ddim_sampling(self, cond, shape,
|
139 |
+
x_T=None, ddim_use_original_steps=False,
|
140 |
+
callback=None, timesteps=None, quantize_denoised=False,
|
141 |
+
mask=None, x0=None, img_callback=None, log_every_t=100,
|
142 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
143 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None, verbose=True,precision=None,fs=None,guidance_rescale=0.0,
|
144 |
+
**kwargs):
|
145 |
+
device = self.model.betas.device
|
146 |
+
b = shape[0]
|
147 |
+
if x_T is None:
|
148 |
+
img = torch.randn(shape, device=device)
|
149 |
+
else:
|
150 |
+
img = x_T
|
151 |
+
if precision is not None:
|
152 |
+
if precision == 16:
|
153 |
+
img = img.to(dtype=torch.float16)
|
154 |
+
|
155 |
+
|
156 |
+
if timesteps is None:
|
157 |
+
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
158 |
+
elif timesteps is not None and not ddim_use_original_steps:
|
159 |
+
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
160 |
+
timesteps = self.ddim_timesteps[:subset_end]
|
161 |
+
|
162 |
+
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
163 |
+
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
164 |
+
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
165 |
+
if verbose:
|
166 |
+
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
167 |
+
else:
|
168 |
+
iterator = time_range
|
169 |
+
|
170 |
+
clean_cond = kwargs.pop("clean_cond", False)
|
171 |
+
|
172 |
+
# cond_copy, unconditional_conditioning_copy = copy.deepcopy(cond), copy.deepcopy(unconditional_conditioning)
|
173 |
+
for i, step in enumerate(iterator):
|
174 |
+
index = total_steps - i - 1
|
175 |
+
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
176 |
+
|
177 |
+
## use mask to blend noised original latent (img_orig) & new sampled latent (img)
|
178 |
+
if mask is not None:
|
179 |
+
assert x0 is not None
|
180 |
+
if clean_cond:
|
181 |
+
img_orig = x0
|
182 |
+
else:
|
183 |
+
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? <ddim inversion>
|
184 |
+
img = img_orig * mask + (1. - mask) * img # keep original & modify use img
|
185 |
+
|
186 |
+
|
187 |
+
|
188 |
+
|
189 |
+
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
190 |
+
quantize_denoised=quantize_denoised, temperature=temperature,
|
191 |
+
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
192 |
+
corrector_kwargs=corrector_kwargs,
|
193 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
194 |
+
unconditional_conditioning=unconditional_conditioning,
|
195 |
+
mask=mask,x0=x0,fs=fs,guidance_rescale=guidance_rescale,
|
196 |
+
**kwargs)
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
img, pred_x0 = outs
|
201 |
+
if callback: callback(i)
|
202 |
+
if img_callback: img_callback(pred_x0, i)
|
203 |
+
|
204 |
+
if index % log_every_t == 0 or index == total_steps - 1:
|
205 |
+
intermediates['x_inter'].append(img)
|
206 |
+
intermediates['pred_x0'].append(pred_x0)
|
207 |
+
|
208 |
+
return img, intermediates
|
209 |
+
|
210 |
+
@torch.no_grad()
|
211 |
+
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
212 |
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
213 |
+
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
214 |
+
uc_type=None, cfg_img=None,mask=None,x0=None,guidance_rescale=0.0, **kwargs):
|
215 |
+
b, *_, device = *x.shape, x.device
|
216 |
+
if x.dim() == 5:
|
217 |
+
is_video = True
|
218 |
+
else:
|
219 |
+
is_video = False
|
220 |
+
if cfg_img is None:
|
221 |
+
cfg_img = unconditional_guidance_scale
|
222 |
+
|
223 |
+
unconditional_conditioning_img_nonetext = kwargs['unconditional_conditioning_img_nonetext']
|
224 |
+
|
225 |
+
|
226 |
+
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
227 |
+
model_output = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
|
228 |
+
else:
|
229 |
+
### with unconditional condition
|
230 |
+
e_t_cond = self.model.apply_model(x, t, c, **kwargs)
|
231 |
+
e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **kwargs)
|
232 |
+
e_t_uncond_img = self.model.apply_model(x, t, unconditional_conditioning_img_nonetext, **kwargs)
|
233 |
+
# text cfg
|
234 |
+
model_output = e_t_uncond + cfg_img * (e_t_uncond_img - e_t_uncond) + unconditional_guidance_scale * (e_t_cond - e_t_uncond_img)
|
235 |
+
if guidance_rescale > 0.0:
|
236 |
+
model_output = rescale_noise_cfg(model_output, e_t_cond, guidance_rescale=guidance_rescale)
|
237 |
+
|
238 |
+
if self.model.parameterization == "v":
|
239 |
+
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
|
240 |
+
else:
|
241 |
+
e_t = model_output
|
242 |
+
|
243 |
+
if score_corrector is not None:
|
244 |
+
assert self.model.parameterization == "eps", 'not implemented'
|
245 |
+
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
246 |
+
|
247 |
+
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
248 |
+
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
249 |
+
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
250 |
+
sigmas = self.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
251 |
+
# select parameters corresponding to the currently considered timestep
|
252 |
+
|
253 |
+
if is_video:
|
254 |
+
size = (b, 1, 1, 1, 1)
|
255 |
+
else:
|
256 |
+
size = (b, 1, 1, 1)
|
257 |
+
a_t = torch.full(size, alphas[index], device=device)
|
258 |
+
a_prev = torch.full(size, alphas_prev[index], device=device)
|
259 |
+
sigma_t = torch.full(size, sigmas[index], device=device)
|
260 |
+
sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
|
261 |
+
|
262 |
+
# current prediction for x_0
|
263 |
+
if self.model.parameterization != "v":
|
264 |
+
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
265 |
+
else:
|
266 |
+
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
|
267 |
+
|
268 |
+
if self.model.use_dynamic_rescale:
|
269 |
+
scale_t = torch.full(size, self.ddim_scale_arr[index], device=device)
|
270 |
+
prev_scale_t = torch.full(size, self.ddim_scale_arr_prev[index], device=device)
|
271 |
+
rescale = (prev_scale_t / scale_t)
|
272 |
+
pred_x0 *= rescale
|
273 |
+
|
274 |
+
if quantize_denoised:
|
275 |
+
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
276 |
+
# direction pointing to x_t
|
277 |
+
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
278 |
+
|
279 |
+
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
280 |
+
if noise_dropout > 0.:
|
281 |
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
282 |
+
|
283 |
+
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
284 |
+
|
285 |
+
return x_prev, pred_x0
|
286 |
+
|
287 |
+
@torch.no_grad()
|
288 |
+
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
289 |
+
use_original_steps=False, callback=None):
|
290 |
+
|
291 |
+
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
292 |
+
timesteps = timesteps[:t_start]
|
293 |
+
|
294 |
+
time_range = np.flip(timesteps)
|
295 |
+
total_steps = timesteps.shape[0]
|
296 |
+
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
297 |
+
|
298 |
+
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
299 |
+
x_dec = x_latent
|
300 |
+
for i, step in enumerate(iterator):
|
301 |
+
index = total_steps - i - 1
|
302 |
+
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
303 |
+
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
304 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
305 |
+
unconditional_conditioning=unconditional_conditioning)
|
306 |
+
if callback: callback(i)
|
307 |
+
return x_dec
|
308 |
+
|
309 |
+
@torch.no_grad()
|
310 |
+
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
311 |
+
# fast, but does not allow for exact reconstruction
|
312 |
+
# t serves as an index to gather the correct alphas
|
313 |
+
if use_original_steps:
|
314 |
+
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
315 |
+
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
316 |
+
else:
|
317 |
+
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
318 |
+
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
319 |
+
|
320 |
+
if noise is None:
|
321 |
+
noise = torch.randn_like(x0)
|
322 |
+
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
323 |
+
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
lvdm/models/utils_diffusion.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from einops import repeat
|
6 |
+
|
7 |
+
|
8 |
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
9 |
+
"""
|
10 |
+
Create sinusoidal timestep embeddings.
|
11 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
12 |
+
These may be fractional.
|
13 |
+
:param dim: the dimension of the output.
|
14 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
15 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
16 |
+
"""
|
17 |
+
if not repeat_only:
|
18 |
+
half = dim // 2
|
19 |
+
freqs = torch.exp(
|
20 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
21 |
+
).to(device=timesteps.device)
|
22 |
+
args = timesteps[:, None].float() * freqs[None]
|
23 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
24 |
+
if dim % 2:
|
25 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
26 |
+
else:
|
27 |
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
28 |
+
return embedding
|
29 |
+
|
30 |
+
|
31 |
+
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
32 |
+
if schedule == "linear":
|
33 |
+
betas = (
|
34 |
+
torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
|
35 |
+
)
|
36 |
+
|
37 |
+
elif schedule == "cosine":
|
38 |
+
timesteps = (
|
39 |
+
torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
|
40 |
+
)
|
41 |
+
alphas = timesteps / (1 + cosine_s) * np.pi / 2
|
42 |
+
alphas = torch.cos(alphas).pow(2)
|
43 |
+
alphas = alphas / alphas[0]
|
44 |
+
betas = 1 - alphas[1:] / alphas[:-1]
|
45 |
+
betas = np.clip(betas, a_min=0, a_max=0.999)
|
46 |
+
|
47 |
+
elif schedule == "sqrt_linear":
|
48 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
49 |
+
elif schedule == "sqrt":
|
50 |
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
51 |
+
else:
|
52 |
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
53 |
+
return betas.numpy()
|
54 |
+
|
55 |
+
|
56 |
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
57 |
+
if ddim_discr_method == 'uniform':
|
58 |
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
59 |
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
60 |
+
steps_out = ddim_timesteps + 1
|
61 |
+
elif ddim_discr_method == 'uniform_trailing':
|
62 |
+
c = num_ddpm_timesteps / num_ddim_timesteps
|
63 |
+
ddim_timesteps = np.flip(np.round(np.arange(num_ddpm_timesteps, 0, -c))).astype(np.int64)
|
64 |
+
steps_out = ddim_timesteps - 1
|
65 |
+
elif ddim_discr_method == 'quad':
|
66 |
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
67 |
+
steps_out = ddim_timesteps + 1
|
68 |
+
else:
|
69 |
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
70 |
+
|
71 |
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
72 |
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
73 |
+
# steps_out = ddim_timesteps + 1
|
74 |
+
if verbose:
|
75 |
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
76 |
+
return steps_out
|
77 |
+
|
78 |
+
|
79 |
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
80 |
+
# select alphas for computing the variance schedule
|
81 |
+
# print(f'ddim_timesteps={ddim_timesteps}, len_alphacums={len(alphacums)}')
|
82 |
+
alphas = alphacums[ddim_timesteps]
|
83 |
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
84 |
+
|
85 |
+
# according the formula provided in https://arxiv.org/abs/2010.02502
|
86 |
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
87 |
+
if verbose:
|
88 |
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
89 |
+
print(f'For the chosen value of eta, which is {eta}, '
|
90 |
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
91 |
+
return sigmas, alphas, alphas_prev
|
92 |
+
|
93 |
+
|
94 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
95 |
+
"""
|
96 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
97 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
98 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
99 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
100 |
+
produces the cumulative product of (1-beta) up to that
|
101 |
+
part of the diffusion process.
|
102 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
103 |
+
prevent singularities.
|
104 |
+
"""
|
105 |
+
betas = []
|
106 |
+
for i in range(num_diffusion_timesteps):
|
107 |
+
t1 = i / num_diffusion_timesteps
|
108 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
109 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
110 |
+
return np.array(betas)
|
111 |
+
|
112 |
+
def rescale_zero_terminal_snr(betas):
|
113 |
+
"""
|
114 |
+
Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
|
115 |
+
|
116 |
+
Args:
|
117 |
+
betas (`numpy.ndarray`):
|
118 |
+
the betas that the scheduler is being initialized with.
|
119 |
+
|
120 |
+
Returns:
|
121 |
+
`numpy.ndarray`: rescaled betas with zero terminal SNR
|
122 |
+
"""
|
123 |
+
# Convert betas to alphas_bar_sqrt
|
124 |
+
alphas = 1.0 - betas
|
125 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
126 |
+
alphas_bar_sqrt = np.sqrt(alphas_cumprod)
|
127 |
+
|
128 |
+
# Store old values.
|
129 |
+
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].copy()
|
130 |
+
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].copy()
|
131 |
+
|
132 |
+
# Shift so the last timestep is zero.
|
133 |
+
alphas_bar_sqrt -= alphas_bar_sqrt_T
|
134 |
+
|
135 |
+
# Scale so the first timestep is back to the old value.
|
136 |
+
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
|
137 |
+
|
138 |
+
# Convert alphas_bar_sqrt to betas
|
139 |
+
alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
|
140 |
+
alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
|
141 |
+
alphas = np.concatenate([alphas_bar[0:1], alphas])
|
142 |
+
betas = 1 - alphas
|
143 |
+
|
144 |
+
return betas
|
145 |
+
|
146 |
+
|
147 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
148 |
+
"""
|
149 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
150 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
151 |
+
"""
|
152 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
153 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
154 |
+
# rescale the results from guidance (fixes overexposure)
|
155 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
156 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
157 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
158 |
+
return noise_cfg
|
lvdm/modules/attention.py
ADDED
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn, einsum
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from einops import rearrange, repeat
|
5 |
+
from functools import partial
|
6 |
+
try:
|
7 |
+
import xformers
|
8 |
+
import xformers.ops
|
9 |
+
XFORMERS_IS_AVAILBLE = True
|
10 |
+
except:
|
11 |
+
XFORMERS_IS_AVAILBLE = False
|
12 |
+
from lvdm.common import (
|
13 |
+
checkpoint,
|
14 |
+
exists,
|
15 |
+
default,
|
16 |
+
)
|
17 |
+
from lvdm.basics import zero_module
|
18 |
+
|
19 |
+
|
20 |
+
class RelativePosition(nn.Module):
|
21 |
+
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
|
22 |
+
|
23 |
+
def __init__(self, num_units, max_relative_position):
|
24 |
+
super().__init__()
|
25 |
+
self.num_units = num_units
|
26 |
+
self.max_relative_position = max_relative_position
|
27 |
+
self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))
|
28 |
+
nn.init.xavier_uniform_(self.embeddings_table)
|
29 |
+
|
30 |
+
def forward(self, length_q, length_k):
|
31 |
+
device = self.embeddings_table.device
|
32 |
+
range_vec_q = torch.arange(length_q, device=device)
|
33 |
+
range_vec_k = torch.arange(length_k, device=device)
|
34 |
+
distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
|
35 |
+
distance_mat_clipped = torch.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
|
36 |
+
final_mat = distance_mat_clipped + self.max_relative_position
|
37 |
+
final_mat = final_mat.long()
|
38 |
+
embeddings = self.embeddings_table[final_mat]
|
39 |
+
return embeddings
|
40 |
+
|
41 |
+
|
42 |
+
class CrossAttention(nn.Module):
|
43 |
+
|
44 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
|
45 |
+
relative_position=False, temporal_length=None, video_length=None, image_cross_attention=False, image_cross_attention_scale=1.0, image_cross_attention_scale_learnable=False, text_context_len=77):
|
46 |
+
super().__init__()
|
47 |
+
inner_dim = dim_head * heads
|
48 |
+
context_dim = default(context_dim, query_dim)
|
49 |
+
|
50 |
+
self.scale = dim_head**-0.5
|
51 |
+
self.heads = heads
|
52 |
+
self.dim_head = dim_head
|
53 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
54 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
55 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
56 |
+
|
57 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
|
58 |
+
|
59 |
+
self.relative_position = relative_position
|
60 |
+
if self.relative_position:
|
61 |
+
assert(temporal_length is not None)
|
62 |
+
self.relative_position_k = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
|
63 |
+
self.relative_position_v = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
|
64 |
+
else:
|
65 |
+
## only used for spatial attention, while NOT for temporal attention
|
66 |
+
if XFORMERS_IS_AVAILBLE and temporal_length is None:
|
67 |
+
self.forward = self.efficient_forward
|
68 |
+
|
69 |
+
self.video_length = video_length
|
70 |
+
self.image_cross_attention = image_cross_attention
|
71 |
+
self.image_cross_attention_scale = image_cross_attention_scale
|
72 |
+
self.text_context_len = text_context_len
|
73 |
+
self.image_cross_attention_scale_learnable = image_cross_attention_scale_learnable
|
74 |
+
if self.image_cross_attention:
|
75 |
+
self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False)
|
76 |
+
self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)
|
77 |
+
if image_cross_attention_scale_learnable:
|
78 |
+
self.register_parameter('alpha', nn.Parameter(torch.tensor(0.)) )
|
79 |
+
|
80 |
+
|
81 |
+
def forward(self, x, context=None, mask=None):
|
82 |
+
spatial_self_attn = (context is None)
|
83 |
+
k_ip, v_ip, out_ip = None, None, None
|
84 |
+
|
85 |
+
h = self.heads
|
86 |
+
q = self.to_q(x)
|
87 |
+
context = default(context, x)
|
88 |
+
|
89 |
+
if self.image_cross_attention and not spatial_self_attn:
|
90 |
+
context, context_image = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
|
91 |
+
k = self.to_k(context)
|
92 |
+
v = self.to_v(context)
|
93 |
+
k_ip = self.to_k_ip(context_image)
|
94 |
+
v_ip = self.to_v_ip(context_image)
|
95 |
+
else:
|
96 |
+
if not spatial_self_attn:
|
97 |
+
context = context[:,:self.text_context_len,:]
|
98 |
+
k = self.to_k(context)
|
99 |
+
v = self.to_v(context)
|
100 |
+
|
101 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
102 |
+
|
103 |
+
sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale
|
104 |
+
if self.relative_position:
|
105 |
+
len_q, len_k, len_v = q.shape[1], k.shape[1], v.shape[1]
|
106 |
+
k2 = self.relative_position_k(len_q, len_k)
|
107 |
+
sim2 = einsum('b t d, t s d -> b t s', q, k2) * self.scale # TODO check
|
108 |
+
sim += sim2
|
109 |
+
del k
|
110 |
+
|
111 |
+
if exists(mask):
|
112 |
+
## feasible for causal attention mask only
|
113 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
114 |
+
mask = repeat(mask, 'b i j -> (b h) i j', h=h)
|
115 |
+
sim.masked_fill_(~(mask>0.5), max_neg_value)
|
116 |
+
|
117 |
+
# attention, what we cannot get enough of
|
118 |
+
sim = sim.softmax(dim=-1)
|
119 |
+
|
120 |
+
out = torch.einsum('b i j, b j d -> b i d', sim, v)
|
121 |
+
if self.relative_position:
|
122 |
+
v2 = self.relative_position_v(len_q, len_v)
|
123 |
+
out2 = einsum('b t s, t s d -> b t d', sim, v2) # TODO check
|
124 |
+
out += out2
|
125 |
+
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
126 |
+
|
127 |
+
|
128 |
+
## for image cross-attention
|
129 |
+
if k_ip is not None:
|
130 |
+
k_ip, v_ip = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (k_ip, v_ip))
|
131 |
+
sim_ip = torch.einsum('b i d, b j d -> b i j', q, k_ip) * self.scale
|
132 |
+
del k_ip
|
133 |
+
sim_ip = sim_ip.softmax(dim=-1)
|
134 |
+
out_ip = torch.einsum('b i j, b j d -> b i d', sim_ip, v_ip)
|
135 |
+
out_ip = rearrange(out_ip, '(b h) n d -> b n (h d)', h=h)
|
136 |
+
|
137 |
+
|
138 |
+
if out_ip is not None:
|
139 |
+
if self.image_cross_attention_scale_learnable:
|
140 |
+
out = out + self.image_cross_attention_scale * out_ip * (torch.tanh(self.alpha)+1)
|
141 |
+
else:
|
142 |
+
out = out + self.image_cross_attention_scale * out_ip
|
143 |
+
|
144 |
+
return self.to_out(out)
|
145 |
+
|
146 |
+
def efficient_forward(self, x, context=None, mask=None):
|
147 |
+
spatial_self_attn = (context is None)
|
148 |
+
k_ip, v_ip, out_ip = None, None, None
|
149 |
+
|
150 |
+
q = self.to_q(x)
|
151 |
+
context = default(context, x)
|
152 |
+
|
153 |
+
if self.image_cross_attention and not spatial_self_attn:
|
154 |
+
context, context_image = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
|
155 |
+
k = self.to_k(context)
|
156 |
+
v = self.to_v(context)
|
157 |
+
k_ip = self.to_k_ip(context_image)
|
158 |
+
v_ip = self.to_v_ip(context_image)
|
159 |
+
else:
|
160 |
+
if not spatial_self_attn:
|
161 |
+
context = context[:,:self.text_context_len,:]
|
162 |
+
k = self.to_k(context)
|
163 |
+
v = self.to_v(context)
|
164 |
+
|
165 |
+
b, _, _ = q.shape
|
166 |
+
q, k, v = map(
|
167 |
+
lambda t: t.unsqueeze(3)
|
168 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
169 |
+
.permute(0, 2, 1, 3)
|
170 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
171 |
+
.contiguous(),
|
172 |
+
(q, k, v),
|
173 |
+
)
|
174 |
+
# actually compute the attention, what we cannot get enough of
|
175 |
+
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
|
176 |
+
|
177 |
+
## for image cross-attention
|
178 |
+
if k_ip is not None:
|
179 |
+
k_ip, v_ip = map(
|
180 |
+
lambda t: t.unsqueeze(3)
|
181 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
182 |
+
.permute(0, 2, 1, 3)
|
183 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
184 |
+
.contiguous(),
|
185 |
+
(k_ip, v_ip),
|
186 |
+
)
|
187 |
+
out_ip = xformers.ops.memory_efficient_attention(q, k_ip, v_ip, attn_bias=None, op=None)
|
188 |
+
out_ip = (
|
189 |
+
out_ip.unsqueeze(0)
|
190 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
191 |
+
.permute(0, 2, 1, 3)
|
192 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
193 |
+
)
|
194 |
+
|
195 |
+
if exists(mask):
|
196 |
+
raise NotImplementedError
|
197 |
+
out = (
|
198 |
+
out.unsqueeze(0)
|
199 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
200 |
+
.permute(0, 2, 1, 3)
|
201 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
202 |
+
)
|
203 |
+
if out_ip is not None:
|
204 |
+
if self.image_cross_attention_scale_learnable:
|
205 |
+
out = out + self.image_cross_attention_scale * out_ip * (torch.tanh(self.alpha)+1)
|
206 |
+
else:
|
207 |
+
out = out + self.image_cross_attention_scale * out_ip
|
208 |
+
|
209 |
+
return self.to_out(out)
|
210 |
+
|
211 |
+
|
212 |
+
class BasicTransformerBlock(nn.Module):
|
213 |
+
|
214 |
+
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
215 |
+
disable_self_attn=False, attention_cls=None, video_length=None, image_cross_attention=False, image_cross_attention_scale=1.0, image_cross_attention_scale_learnable=False, text_context_len=77):
|
216 |
+
super().__init__()
|
217 |
+
attn_cls = CrossAttention if attention_cls is None else attention_cls
|
218 |
+
self.disable_self_attn = disable_self_attn
|
219 |
+
self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
220 |
+
context_dim=context_dim if self.disable_self_attn else None)
|
221 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
222 |
+
self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout, video_length=video_length, image_cross_attention=image_cross_attention, image_cross_attention_scale=image_cross_attention_scale, image_cross_attention_scale_learnable=image_cross_attention_scale_learnable,text_context_len=text_context_len)
|
223 |
+
self.image_cross_attention = image_cross_attention
|
224 |
+
|
225 |
+
self.norm1 = nn.LayerNorm(dim)
|
226 |
+
self.norm2 = nn.LayerNorm(dim)
|
227 |
+
self.norm3 = nn.LayerNorm(dim)
|
228 |
+
self.checkpoint = checkpoint
|
229 |
+
|
230 |
+
|
231 |
+
def forward(self, x, context=None, mask=None, **kwargs):
|
232 |
+
## implementation tricks: because checkpointing doesn't support non-tensor (e.g. None or scalar) arguments
|
233 |
+
input_tuple = (x,) ## should not be (x), otherwise *input_tuple will decouple x into multiple arguments
|
234 |
+
if context is not None:
|
235 |
+
input_tuple = (x, context)
|
236 |
+
if mask is not None:
|
237 |
+
forward_mask = partial(self._forward, mask=mask)
|
238 |
+
return checkpoint(forward_mask, (x,), self.parameters(), self.checkpoint)
|
239 |
+
return checkpoint(self._forward, input_tuple, self.parameters(), self.checkpoint)
|
240 |
+
|
241 |
+
|
242 |
+
def _forward(self, x, context=None, mask=None):
|
243 |
+
x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None, mask=mask) + x
|
244 |
+
x = self.attn2(self.norm2(x), context=context, mask=mask) + x
|
245 |
+
x = self.ff(self.norm3(x)) + x
|
246 |
+
return x
|
247 |
+
|
248 |
+
|
249 |
+
class SpatialTransformer(nn.Module):
|
250 |
+
"""
|
251 |
+
Transformer block for image-like data in spatial axis.
|
252 |
+
First, project the input (aka embedding)
|
253 |
+
and reshape to b, t, d.
|
254 |
+
Then apply standard transformer action.
|
255 |
+
Finally, reshape to image
|
256 |
+
NEW: use_linear for more efficiency instead of the 1x1 convs
|
257 |
+
"""
|
258 |
+
|
259 |
+
def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
|
260 |
+
use_checkpoint=True, disable_self_attn=False, use_linear=False, video_length=None,
|
261 |
+
image_cross_attention=False, image_cross_attention_scale_learnable=False):
|
262 |
+
super().__init__()
|
263 |
+
self.in_channels = in_channels
|
264 |
+
inner_dim = n_heads * d_head
|
265 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
266 |
+
if not use_linear:
|
267 |
+
self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
268 |
+
else:
|
269 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
270 |
+
|
271 |
+
attention_cls = None
|
272 |
+
self.transformer_blocks = nn.ModuleList([
|
273 |
+
BasicTransformerBlock(
|
274 |
+
inner_dim,
|
275 |
+
n_heads,
|
276 |
+
d_head,
|
277 |
+
dropout=dropout,
|
278 |
+
context_dim=context_dim,
|
279 |
+
disable_self_attn=disable_self_attn,
|
280 |
+
checkpoint=use_checkpoint,
|
281 |
+
attention_cls=attention_cls,
|
282 |
+
video_length=video_length,
|
283 |
+
image_cross_attention=image_cross_attention,
|
284 |
+
image_cross_attention_scale_learnable=image_cross_attention_scale_learnable,
|
285 |
+
) for d in range(depth)
|
286 |
+
])
|
287 |
+
if not use_linear:
|
288 |
+
self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
|
289 |
+
else:
|
290 |
+
self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
|
291 |
+
self.use_linear = use_linear
|
292 |
+
|
293 |
+
|
294 |
+
def forward(self, x, context=None, **kwargs):
|
295 |
+
b, c, h, w = x.shape
|
296 |
+
x_in = x
|
297 |
+
x = self.norm(x)
|
298 |
+
if not self.use_linear:
|
299 |
+
x = self.proj_in(x)
|
300 |
+
x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
|
301 |
+
if self.use_linear:
|
302 |
+
x = self.proj_in(x)
|
303 |
+
for i, block in enumerate(self.transformer_blocks):
|
304 |
+
x = block(x, context=context, **kwargs)
|
305 |
+
if self.use_linear:
|
306 |
+
x = self.proj_out(x)
|
307 |
+
x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
|
308 |
+
if not self.use_linear:
|
309 |
+
x = self.proj_out(x)
|
310 |
+
return x + x_in
|
311 |
+
|
312 |
+
|
313 |
+
class TemporalTransformer(nn.Module):
|
314 |
+
"""
|
315 |
+
Transformer block for image-like data in temporal axis.
|
316 |
+
First, reshape to b, t, d.
|
317 |
+
Then apply standard transformer action.
|
318 |
+
Finally, reshape to image
|
319 |
+
"""
|
320 |
+
def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
|
321 |
+
use_checkpoint=True, use_linear=False, only_self_att=True, causal_attention=False, causal_block_size=1,
|
322 |
+
relative_position=False, temporal_length=None):
|
323 |
+
super().__init__()
|
324 |
+
self.only_self_att = only_self_att
|
325 |
+
self.relative_position = relative_position
|
326 |
+
self.causal_attention = causal_attention
|
327 |
+
self.causal_block_size = causal_block_size
|
328 |
+
|
329 |
+
self.in_channels = in_channels
|
330 |
+
inner_dim = n_heads * d_head
|
331 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
332 |
+
self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
333 |
+
if not use_linear:
|
334 |
+
self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
335 |
+
else:
|
336 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
337 |
+
|
338 |
+
if relative_position:
|
339 |
+
assert(temporal_length is not None)
|
340 |
+
attention_cls = partial(CrossAttention, relative_position=True, temporal_length=temporal_length)
|
341 |
+
else:
|
342 |
+
attention_cls = partial(CrossAttention, temporal_length=temporal_length)
|
343 |
+
if self.causal_attention:
|
344 |
+
assert(temporal_length is not None)
|
345 |
+
self.mask = torch.tril(torch.ones([1, temporal_length, temporal_length]))
|
346 |
+
|
347 |
+
if self.only_self_att:
|
348 |
+
context_dim = None
|
349 |
+
self.transformer_blocks = nn.ModuleList([
|
350 |
+
BasicTransformerBlock(
|
351 |
+
inner_dim,
|
352 |
+
n_heads,
|
353 |
+
d_head,
|
354 |
+
dropout=dropout,
|
355 |
+
context_dim=context_dim,
|
356 |
+
attention_cls=attention_cls,
|
357 |
+
checkpoint=use_checkpoint) for d in range(depth)
|
358 |
+
])
|
359 |
+
if not use_linear:
|
360 |
+
self.proj_out = zero_module(nn.Conv1d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
|
361 |
+
else:
|
362 |
+
self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
|
363 |
+
self.use_linear = use_linear
|
364 |
+
|
365 |
+
def forward(self, x, context=None):
|
366 |
+
b, c, t, h, w = x.shape
|
367 |
+
x_in = x
|
368 |
+
x = self.norm(x)
|
369 |
+
x = rearrange(x, 'b c t h w -> (b h w) c t').contiguous()
|
370 |
+
if not self.use_linear:
|
371 |
+
x = self.proj_in(x)
|
372 |
+
x = rearrange(x, 'bhw c t -> bhw t c').contiguous()
|
373 |
+
if self.use_linear:
|
374 |
+
x = self.proj_in(x)
|
375 |
+
|
376 |
+
temp_mask = None
|
377 |
+
if self.causal_attention:
|
378 |
+
# slice the from mask map
|
379 |
+
temp_mask = self.mask[:,:t,:t].to(x.device)
|
380 |
+
|
381 |
+
if temp_mask is not None:
|
382 |
+
mask = temp_mask.to(x.device)
|
383 |
+
mask = repeat(mask, 'l i j -> (l bhw) i j', bhw=b*h*w)
|
384 |
+
else:
|
385 |
+
mask = None
|
386 |
+
|
387 |
+
if self.only_self_att:
|
388 |
+
## note: if no context is given, cross-attention defaults to self-attention
|
389 |
+
for i, block in enumerate(self.transformer_blocks):
|
390 |
+
x = block(x, mask=mask)
|
391 |
+
x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
|
392 |
+
else:
|
393 |
+
x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
|
394 |
+
context = rearrange(context, '(b t) l con -> b t l con', t=t).contiguous()
|
395 |
+
for i, block in enumerate(self.transformer_blocks):
|
396 |
+
# calculate each batch one by one (since number in shape could not greater then 65,535 for some package)
|
397 |
+
for j in range(b):
|
398 |
+
context_j = repeat(
|
399 |
+
context[j],
|
400 |
+
't l con -> (t r) l con', r=(h * w) // t, t=t).contiguous()
|
401 |
+
## note: causal mask will not applied in cross-attention case
|
402 |
+
x[j] = block(x[j], context=context_j)
|
403 |
+
|
404 |
+
if self.use_linear:
|
405 |
+
x = self.proj_out(x)
|
406 |
+
x = rearrange(x, 'b (h w) t c -> b c t h w', h=h, w=w).contiguous()
|
407 |
+
if not self.use_linear:
|
408 |
+
x = rearrange(x, 'b hw t c -> (b hw) c t').contiguous()
|
409 |
+
x = self.proj_out(x)
|
410 |
+
x = rearrange(x, '(b h w) c t -> b c t h w', b=b, h=h, w=w).contiguous()
|
411 |
+
|
412 |
+
return x + x_in
|
413 |
+
|
414 |
+
|
415 |
+
class GEGLU(nn.Module):
|
416 |
+
def __init__(self, dim_in, dim_out):
|
417 |
+
super().__init__()
|
418 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
419 |
+
|
420 |
+
def forward(self, x):
|
421 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
422 |
+
return x * F.gelu(gate)
|
423 |
+
|
424 |
+
|
425 |
+
class FeedForward(nn.Module):
|
426 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
427 |
+
super().__init__()
|
428 |
+
inner_dim = int(dim * mult)
|
429 |
+
dim_out = default(dim_out, dim)
|
430 |
+
project_in = nn.Sequential(
|
431 |
+
nn.Linear(dim, inner_dim),
|
432 |
+
nn.GELU()
|
433 |
+
) if not glu else GEGLU(dim, inner_dim)
|
434 |
+
|
435 |
+
self.net = nn.Sequential(
|
436 |
+
project_in,
|
437 |
+
nn.Dropout(dropout),
|
438 |
+
nn.Linear(inner_dim, dim_out)
|
439 |
+
)
|
440 |
+
|
441 |
+
def forward(self, x):
|
442 |
+
return self.net(x)
|
443 |
+
|
444 |
+
|
445 |
+
class LinearAttention(nn.Module):
|
446 |
+
def __init__(self, dim, heads=4, dim_head=32):
|
447 |
+
super().__init__()
|
448 |
+
self.heads = heads
|
449 |
+
hidden_dim = dim_head * heads
|
450 |
+
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
|
451 |
+
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
|
452 |
+
|
453 |
+
def forward(self, x):
|
454 |
+
b, c, h, w = x.shape
|
455 |
+
qkv = self.to_qkv(x)
|
456 |
+
q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
|
457 |
+
k = k.softmax(dim=-1)
|
458 |
+
context = torch.einsum('bhdn,bhen->bhde', k, v)
|
459 |
+
out = torch.einsum('bhde,bhdn->bhen', context, q)
|
460 |
+
out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
|
461 |
+
return self.to_out(out)
|
462 |
+
|
463 |
+
|
464 |
+
class SpatialSelfAttention(nn.Module):
|
465 |
+
def __init__(self, in_channels):
|
466 |
+
super().__init__()
|
467 |
+
self.in_channels = in_channels
|
468 |
+
|
469 |
+
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
470 |
+
self.q = torch.nn.Conv2d(in_channels,
|
471 |
+
in_channels,
|
472 |
+
kernel_size=1,
|
473 |
+
stride=1,
|
474 |
+
padding=0)
|
475 |
+
self.k = torch.nn.Conv2d(in_channels,
|
476 |
+
in_channels,
|
477 |
+
kernel_size=1,
|
478 |
+
stride=1,
|
479 |
+
padding=0)
|
480 |
+
self.v = torch.nn.Conv2d(in_channels,
|
481 |
+
in_channels,
|
482 |
+
kernel_size=1,
|
483 |
+
stride=1,
|
484 |
+
padding=0)
|
485 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
486 |
+
in_channels,
|
487 |
+
kernel_size=1,
|
488 |
+
stride=1,
|
489 |
+
padding=0)
|
490 |
+
|
491 |
+
def forward(self, x):
|
492 |
+
h_ = x
|
493 |
+
h_ = self.norm(h_)
|
494 |
+
q = self.q(h_)
|
495 |
+
k = self.k(h_)
|
496 |
+
v = self.v(h_)
|
497 |
+
|
498 |
+
# compute attention
|
499 |
+
b,c,h,w = q.shape
|
500 |
+
q = rearrange(q, 'b c h w -> b (h w) c')
|
501 |
+
k = rearrange(k, 'b c h w -> b c (h w)')
|
502 |
+
w_ = torch.einsum('bij,bjk->bik', q, k)
|
503 |
+
|
504 |
+
w_ = w_ * (int(c)**(-0.5))
|
505 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
506 |
+
|
507 |
+
# attend to values
|
508 |
+
v = rearrange(v, 'b c h w -> b c (h w)')
|
509 |
+
w_ = rearrange(w_, 'b i j -> b j i')
|
510 |
+
h_ = torch.einsum('bij,bjk->bik', v, w_)
|
511 |
+
h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
|
512 |
+
h_ = self.proj_out(h_)
|
513 |
+
|
514 |
+
return x+h_
|
lvdm/modules/attention_svd.py
ADDED
@@ -0,0 +1,759 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import math
|
3 |
+
from inspect import isfunction
|
4 |
+
from typing import Any, Optional
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from einops import rearrange, repeat
|
9 |
+
from packaging import version
|
10 |
+
from torch import nn
|
11 |
+
from torch.utils.checkpoint import checkpoint
|
12 |
+
|
13 |
+
logpy = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
if version.parse(torch.__version__) >= version.parse("2.0.0"):
|
16 |
+
SDP_IS_AVAILABLE = True
|
17 |
+
from torch.backends.cuda import SDPBackend, sdp_kernel
|
18 |
+
|
19 |
+
BACKEND_MAP = {
|
20 |
+
SDPBackend.MATH: {
|
21 |
+
"enable_math": True,
|
22 |
+
"enable_flash": False,
|
23 |
+
"enable_mem_efficient": False,
|
24 |
+
},
|
25 |
+
SDPBackend.FLASH_ATTENTION: {
|
26 |
+
"enable_math": False,
|
27 |
+
"enable_flash": True,
|
28 |
+
"enable_mem_efficient": False,
|
29 |
+
},
|
30 |
+
SDPBackend.EFFICIENT_ATTENTION: {
|
31 |
+
"enable_math": False,
|
32 |
+
"enable_flash": False,
|
33 |
+
"enable_mem_efficient": True,
|
34 |
+
},
|
35 |
+
None: {"enable_math": True, "enable_flash": True, "enable_mem_efficient": True},
|
36 |
+
}
|
37 |
+
else:
|
38 |
+
from contextlib import nullcontext
|
39 |
+
|
40 |
+
SDP_IS_AVAILABLE = False
|
41 |
+
sdp_kernel = nullcontext
|
42 |
+
BACKEND_MAP = {}
|
43 |
+
logpy.warn(
|
44 |
+
f"No SDP backend available, likely because you are running in pytorch "
|
45 |
+
f"versions < 2.0. In fact, you are using PyTorch {torch.__version__}. "
|
46 |
+
f"You might want to consider upgrading."
|
47 |
+
)
|
48 |
+
|
49 |
+
try:
|
50 |
+
import xformers
|
51 |
+
import xformers.ops
|
52 |
+
|
53 |
+
XFORMERS_IS_AVAILABLE = True
|
54 |
+
except:
|
55 |
+
XFORMERS_IS_AVAILABLE = False
|
56 |
+
logpy.warn("no module 'xformers'. Processing without...")
|
57 |
+
|
58 |
+
# from .diffusionmodules.util import mixed_checkpoint as checkpoint
|
59 |
+
|
60 |
+
|
61 |
+
def exists(val):
|
62 |
+
return val is not None
|
63 |
+
|
64 |
+
|
65 |
+
def uniq(arr):
|
66 |
+
return {el: True for el in arr}.keys()
|
67 |
+
|
68 |
+
|
69 |
+
def default(val, d):
|
70 |
+
if exists(val):
|
71 |
+
return val
|
72 |
+
return d() if isfunction(d) else d
|
73 |
+
|
74 |
+
|
75 |
+
def max_neg_value(t):
|
76 |
+
return -torch.finfo(t.dtype).max
|
77 |
+
|
78 |
+
|
79 |
+
def init_(tensor):
|
80 |
+
dim = tensor.shape[-1]
|
81 |
+
std = 1 / math.sqrt(dim)
|
82 |
+
tensor.uniform_(-std, std)
|
83 |
+
return tensor
|
84 |
+
|
85 |
+
|
86 |
+
# feedforward
|
87 |
+
class GEGLU(nn.Module):
|
88 |
+
def __init__(self, dim_in, dim_out):
|
89 |
+
super().__init__()
|
90 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
94 |
+
return x * F.gelu(gate)
|
95 |
+
|
96 |
+
|
97 |
+
class FeedForward(nn.Module):
|
98 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):
|
99 |
+
super().__init__()
|
100 |
+
inner_dim = int(dim * mult)
|
101 |
+
dim_out = default(dim_out, dim)
|
102 |
+
project_in = (
|
103 |
+
nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())
|
104 |
+
if not glu
|
105 |
+
else GEGLU(dim, inner_dim)
|
106 |
+
)
|
107 |
+
|
108 |
+
self.net = nn.Sequential(
|
109 |
+
project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out)
|
110 |
+
)
|
111 |
+
|
112 |
+
def forward(self, x):
|
113 |
+
return self.net(x)
|
114 |
+
|
115 |
+
|
116 |
+
def zero_module(module):
|
117 |
+
"""
|
118 |
+
Zero out the parameters of a module and return it.
|
119 |
+
"""
|
120 |
+
for p in module.parameters():
|
121 |
+
p.detach().zero_()
|
122 |
+
return module
|
123 |
+
|
124 |
+
|
125 |
+
def Normalize(in_channels):
|
126 |
+
return torch.nn.GroupNorm(
|
127 |
+
num_groups=32, num_channels=in_channels, eps=1e-6, affine=True
|
128 |
+
)
|
129 |
+
|
130 |
+
|
131 |
+
class LinearAttention(nn.Module):
|
132 |
+
def __init__(self, dim, heads=4, dim_head=32):
|
133 |
+
super().__init__()
|
134 |
+
self.heads = heads
|
135 |
+
hidden_dim = dim_head * heads
|
136 |
+
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
|
137 |
+
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
|
138 |
+
|
139 |
+
def forward(self, x):
|
140 |
+
b, c, h, w = x.shape
|
141 |
+
qkv = self.to_qkv(x)
|
142 |
+
q, k, v = rearrange(
|
143 |
+
qkv, "b (qkv heads c) h w -> qkv b heads c (h w)", heads=self.heads, qkv=3
|
144 |
+
)
|
145 |
+
k = k.softmax(dim=-1)
|
146 |
+
context = torch.einsum("bhdn,bhen->bhde", k, v)
|
147 |
+
out = torch.einsum("bhde,bhdn->bhen", context, q)
|
148 |
+
out = rearrange(
|
149 |
+
out, "b heads c (h w) -> b (heads c) h w", heads=self.heads, h=h, w=w
|
150 |
+
)
|
151 |
+
return self.to_out(out)
|
152 |
+
|
153 |
+
|
154 |
+
class SelfAttention(nn.Module):
|
155 |
+
ATTENTION_MODES = ("xformers", "torch", "math")
|
156 |
+
|
157 |
+
def __init__(
|
158 |
+
self,
|
159 |
+
dim: int,
|
160 |
+
num_heads: int = 8,
|
161 |
+
qkv_bias: bool = False,
|
162 |
+
qk_scale: Optional[float] = None,
|
163 |
+
attn_drop: float = 0.0,
|
164 |
+
proj_drop: float = 0.0,
|
165 |
+
attn_mode: str = "xformers",
|
166 |
+
):
|
167 |
+
super().__init__()
|
168 |
+
self.num_heads = num_heads
|
169 |
+
head_dim = dim // num_heads
|
170 |
+
self.scale = qk_scale or head_dim**-0.5
|
171 |
+
|
172 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
173 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
174 |
+
self.proj = nn.Linear(dim, dim)
|
175 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
176 |
+
assert attn_mode in self.ATTENTION_MODES
|
177 |
+
self.attn_mode = attn_mode
|
178 |
+
|
179 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
180 |
+
B, L, C = x.shape
|
181 |
+
|
182 |
+
qkv = self.qkv(x)
|
183 |
+
if self.attn_mode == "torch":
|
184 |
+
qkv = rearrange(
|
185 |
+
qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads
|
186 |
+
).float()
|
187 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # B H L D
|
188 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
189 |
+
x = rearrange(x, "B H L D -> B L (H D)")
|
190 |
+
elif self.attn_mode == "xformers":
|
191 |
+
qkv = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.num_heads)
|
192 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # B L H D
|
193 |
+
x = xformers.ops.memory_efficient_attention(q, k, v)
|
194 |
+
x = rearrange(x, "B L H D -> B L (H D)", H=self.num_heads)
|
195 |
+
elif self.attn_mode == "math":
|
196 |
+
qkv = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
|
197 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # B H L D
|
198 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
199 |
+
attn = attn.softmax(dim=-1)
|
200 |
+
attn = self.attn_drop(attn)
|
201 |
+
x = (attn @ v).transpose(1, 2).reshape(B, L, C)
|
202 |
+
else:
|
203 |
+
raise NotImplemented
|
204 |
+
|
205 |
+
x = self.proj(x)
|
206 |
+
x = self.proj_drop(x)
|
207 |
+
return x
|
208 |
+
|
209 |
+
|
210 |
+
class SpatialSelfAttention(nn.Module):
|
211 |
+
def __init__(self, in_channels):
|
212 |
+
super().__init__()
|
213 |
+
self.in_channels = in_channels
|
214 |
+
|
215 |
+
self.norm = Normalize(in_channels)
|
216 |
+
self.q = torch.nn.Conv2d(
|
217 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
218 |
+
)
|
219 |
+
self.k = torch.nn.Conv2d(
|
220 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
221 |
+
)
|
222 |
+
self.v = torch.nn.Conv2d(
|
223 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
224 |
+
)
|
225 |
+
self.proj_out = torch.nn.Conv2d(
|
226 |
+
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
227 |
+
)
|
228 |
+
|
229 |
+
def forward(self, x):
|
230 |
+
h_ = x
|
231 |
+
h_ = self.norm(h_)
|
232 |
+
q = self.q(h_)
|
233 |
+
k = self.k(h_)
|
234 |
+
v = self.v(h_)
|
235 |
+
|
236 |
+
# compute attention
|
237 |
+
b, c, h, w = q.shape
|
238 |
+
q = rearrange(q, "b c h w -> b (h w) c")
|
239 |
+
k = rearrange(k, "b c h w -> b c (h w)")
|
240 |
+
w_ = torch.einsum("bij,bjk->bik", q, k)
|
241 |
+
|
242 |
+
w_ = w_ * (int(c) ** (-0.5))
|
243 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
244 |
+
|
245 |
+
# attend to values
|
246 |
+
v = rearrange(v, "b c h w -> b c (h w)")
|
247 |
+
w_ = rearrange(w_, "b i j -> b j i")
|
248 |
+
h_ = torch.einsum("bij,bjk->bik", v, w_)
|
249 |
+
h_ = rearrange(h_, "b c (h w) -> b c h w", h=h)
|
250 |
+
h_ = self.proj_out(h_)
|
251 |
+
|
252 |
+
return x + h_
|
253 |
+
|
254 |
+
|
255 |
+
class CrossAttention(nn.Module):
|
256 |
+
def __init__(
|
257 |
+
self,
|
258 |
+
query_dim,
|
259 |
+
context_dim=None,
|
260 |
+
heads=8,
|
261 |
+
dim_head=64,
|
262 |
+
dropout=0.0,
|
263 |
+
backend=None,
|
264 |
+
):
|
265 |
+
super().__init__()
|
266 |
+
inner_dim = dim_head * heads
|
267 |
+
context_dim = default(context_dim, query_dim)
|
268 |
+
|
269 |
+
self.scale = dim_head**-0.5
|
270 |
+
self.heads = heads
|
271 |
+
|
272 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
273 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
274 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
275 |
+
|
276 |
+
self.to_out = nn.Sequential(
|
277 |
+
nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)
|
278 |
+
)
|
279 |
+
self.backend = backend
|
280 |
+
|
281 |
+
def forward(
|
282 |
+
self,
|
283 |
+
x,
|
284 |
+
context=None,
|
285 |
+
mask=None,
|
286 |
+
additional_tokens=None,
|
287 |
+
n_times_crossframe_attn_in_self=0,
|
288 |
+
):
|
289 |
+
h = self.heads
|
290 |
+
|
291 |
+
if additional_tokens is not None:
|
292 |
+
# get the number of masked tokens at the beginning of the output sequence
|
293 |
+
n_tokens_to_mask = additional_tokens.shape[1]
|
294 |
+
# add additional token
|
295 |
+
x = torch.cat([additional_tokens, x], dim=1)
|
296 |
+
|
297 |
+
q = self.to_q(x)
|
298 |
+
context = default(context, x)
|
299 |
+
k = self.to_k(context)
|
300 |
+
v = self.to_v(context)
|
301 |
+
|
302 |
+
if n_times_crossframe_attn_in_self:
|
303 |
+
# reprogramming cross-frame attention as in https://arxiv.org/abs/2303.13439
|
304 |
+
assert x.shape[0] % n_times_crossframe_attn_in_self == 0
|
305 |
+
n_cp = x.shape[0] // n_times_crossframe_attn_in_self
|
306 |
+
k = repeat(
|
307 |
+
k[::n_times_crossframe_attn_in_self], "b ... -> (b n) ...", n=n_cp
|
308 |
+
)
|
309 |
+
v = repeat(
|
310 |
+
v[::n_times_crossframe_attn_in_self], "b ... -> (b n) ...", n=n_cp
|
311 |
+
)
|
312 |
+
|
313 |
+
q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v))
|
314 |
+
|
315 |
+
## old
|
316 |
+
"""
|
317 |
+
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
318 |
+
del q, k
|
319 |
+
|
320 |
+
if exists(mask):
|
321 |
+
mask = rearrange(mask, 'b ... -> b (...)')
|
322 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
323 |
+
mask = repeat(mask, 'b j -> (b h) () j', h=h)
|
324 |
+
sim.masked_fill_(~mask, max_neg_value)
|
325 |
+
|
326 |
+
# attention, what we cannot get enough of
|
327 |
+
sim = sim.softmax(dim=-1)
|
328 |
+
|
329 |
+
out = einsum('b i j, b j d -> b i d', sim, v)
|
330 |
+
"""
|
331 |
+
## new
|
332 |
+
with sdp_kernel(**BACKEND_MAP[self.backend]):
|
333 |
+
# print("dispatching into backend", self.backend, "q/k/v shape: ", q.shape, k.shape, v.shape)
|
334 |
+
out = F.scaled_dot_product_attention(
|
335 |
+
q, k, v, attn_mask=mask
|
336 |
+
) # scale is dim_head ** -0.5 per default
|
337 |
+
|
338 |
+
del q, k, v
|
339 |
+
out = rearrange(out, "b h n d -> b n (h d)", h=h)
|
340 |
+
|
341 |
+
if additional_tokens is not None:
|
342 |
+
# remove additional token
|
343 |
+
out = out[:, n_tokens_to_mask:]
|
344 |
+
return self.to_out(out)
|
345 |
+
|
346 |
+
|
347 |
+
class MemoryEfficientCrossAttention(nn.Module):
|
348 |
+
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
349 |
+
def __init__(
|
350 |
+
self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, **kwargs
|
351 |
+
):
|
352 |
+
super().__init__()
|
353 |
+
logpy.debug(
|
354 |
+
f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, "
|
355 |
+
f"context_dim is {context_dim} and using {heads} heads with a "
|
356 |
+
f"dimension of {dim_head}."
|
357 |
+
)
|
358 |
+
inner_dim = dim_head * heads
|
359 |
+
context_dim = default(context_dim, query_dim)
|
360 |
+
|
361 |
+
self.heads = heads
|
362 |
+
self.dim_head = dim_head
|
363 |
+
|
364 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
365 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
366 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
367 |
+
|
368 |
+
self.to_out = nn.Sequential(
|
369 |
+
nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)
|
370 |
+
)
|
371 |
+
self.attention_op: Optional[Any] = None
|
372 |
+
|
373 |
+
def forward(
|
374 |
+
self,
|
375 |
+
x,
|
376 |
+
context=None,
|
377 |
+
mask=None,
|
378 |
+
additional_tokens=None,
|
379 |
+
n_times_crossframe_attn_in_self=0,
|
380 |
+
):
|
381 |
+
if additional_tokens is not None:
|
382 |
+
# get the number of masked tokens at the beginning of the output sequence
|
383 |
+
n_tokens_to_mask = additional_tokens.shape[1]
|
384 |
+
# add additional token
|
385 |
+
x = torch.cat([additional_tokens, x], dim=1)
|
386 |
+
q = self.to_q(x)
|
387 |
+
context = default(context, x)
|
388 |
+
k = self.to_k(context)
|
389 |
+
v = self.to_v(context)
|
390 |
+
|
391 |
+
if n_times_crossframe_attn_in_self:
|
392 |
+
# reprogramming cross-frame attention as in https://arxiv.org/abs/2303.13439
|
393 |
+
assert x.shape[0] % n_times_crossframe_attn_in_self == 0
|
394 |
+
# n_cp = x.shape[0]//n_times_crossframe_attn_in_self
|
395 |
+
k = repeat(
|
396 |
+
k[::n_times_crossframe_attn_in_self],
|
397 |
+
"b ... -> (b n) ...",
|
398 |
+
n=n_times_crossframe_attn_in_self,
|
399 |
+
)
|
400 |
+
v = repeat(
|
401 |
+
v[::n_times_crossframe_attn_in_self],
|
402 |
+
"b ... -> (b n) ...",
|
403 |
+
n=n_times_crossframe_attn_in_self,
|
404 |
+
)
|
405 |
+
|
406 |
+
b, _, _ = q.shape
|
407 |
+
q, k, v = map(
|
408 |
+
lambda t: t.unsqueeze(3)
|
409 |
+
.reshape(b, t.shape[1], self.heads, self.dim_head)
|
410 |
+
.permute(0, 2, 1, 3)
|
411 |
+
.reshape(b * self.heads, t.shape[1], self.dim_head)
|
412 |
+
.contiguous(),
|
413 |
+
(q, k, v),
|
414 |
+
)
|
415 |
+
|
416 |
+
# actually compute the attention, what we cannot get enough of
|
417 |
+
if version.parse(xformers.__version__) >= version.parse("0.0.21"):
|
418 |
+
# NOTE: workaround for
|
419 |
+
# https://github.com/facebookresearch/xformers/issues/845
|
420 |
+
max_bs = 32768
|
421 |
+
N = q.shape[0]
|
422 |
+
n_batches = math.ceil(N / max_bs)
|
423 |
+
out = list()
|
424 |
+
for i_batch in range(n_batches):
|
425 |
+
batch = slice(i_batch * max_bs, (i_batch + 1) * max_bs)
|
426 |
+
out.append(
|
427 |
+
xformers.ops.memory_efficient_attention(
|
428 |
+
q[batch],
|
429 |
+
k[batch],
|
430 |
+
v[batch],
|
431 |
+
attn_bias=None,
|
432 |
+
op=self.attention_op,
|
433 |
+
)
|
434 |
+
)
|
435 |
+
out = torch.cat(out, 0)
|
436 |
+
else:
|
437 |
+
out = xformers.ops.memory_efficient_attention(
|
438 |
+
q, k, v, attn_bias=None, op=self.attention_op
|
439 |
+
)
|
440 |
+
|
441 |
+
# TODO: Use this directly in the attention operation, as a bias
|
442 |
+
if exists(mask):
|
443 |
+
raise NotImplementedError
|
444 |
+
out = (
|
445 |
+
out.unsqueeze(0)
|
446 |
+
.reshape(b, self.heads, out.shape[1], self.dim_head)
|
447 |
+
.permute(0, 2, 1, 3)
|
448 |
+
.reshape(b, out.shape[1], self.heads * self.dim_head)
|
449 |
+
)
|
450 |
+
if additional_tokens is not None:
|
451 |
+
# remove additional token
|
452 |
+
out = out[:, n_tokens_to_mask:]
|
453 |
+
return self.to_out(out)
|
454 |
+
|
455 |
+
|
456 |
+
class BasicTransformerBlock(nn.Module):
|
457 |
+
ATTENTION_MODES = {
|
458 |
+
"softmax": CrossAttention, # vanilla attention
|
459 |
+
"softmax-xformers": MemoryEfficientCrossAttention, # ampere
|
460 |
+
}
|
461 |
+
|
462 |
+
def __init__(
|
463 |
+
self,
|
464 |
+
dim,
|
465 |
+
n_heads,
|
466 |
+
d_head,
|
467 |
+
dropout=0.0,
|
468 |
+
context_dim=None,
|
469 |
+
gated_ff=True,
|
470 |
+
checkpoint=True,
|
471 |
+
disable_self_attn=False,
|
472 |
+
attn_mode="softmax",
|
473 |
+
sdp_backend=None,
|
474 |
+
):
|
475 |
+
super().__init__()
|
476 |
+
assert attn_mode in self.ATTENTION_MODES
|
477 |
+
if attn_mode != "softmax" and not XFORMERS_IS_AVAILABLE:
|
478 |
+
logpy.warn(
|
479 |
+
f"Attention mode '{attn_mode}' is not available. Falling "
|
480 |
+
f"back to native attention. This is not a problem in "
|
481 |
+
f"Pytorch >= 2.0. FYI, you are running with PyTorch "
|
482 |
+
f"version {torch.__version__}."
|
483 |
+
)
|
484 |
+
attn_mode = "softmax"
|
485 |
+
elif attn_mode == "softmax" and not SDP_IS_AVAILABLE:
|
486 |
+
logpy.warn(
|
487 |
+
"We do not support vanilla attention anymore, as it is too "
|
488 |
+
"expensive. Sorry."
|
489 |
+
)
|
490 |
+
if not XFORMERS_IS_AVAILABLE:
|
491 |
+
assert (
|
492 |
+
False
|
493 |
+
), "Please install xformers via e.g. 'pip install xformers==0.0.16'"
|
494 |
+
else:
|
495 |
+
logpy.info("Falling back to xformers efficient attention.")
|
496 |
+
attn_mode = "softmax-xformers"
|
497 |
+
attn_cls = self.ATTENTION_MODES[attn_mode]
|
498 |
+
if version.parse(torch.__version__) >= version.parse("2.0.0"):
|
499 |
+
assert sdp_backend is None or isinstance(sdp_backend, SDPBackend)
|
500 |
+
else:
|
501 |
+
assert sdp_backend is None
|
502 |
+
self.disable_self_attn = disable_self_attn
|
503 |
+
self.attn1 = attn_cls(
|
504 |
+
query_dim=dim,
|
505 |
+
heads=n_heads,
|
506 |
+
dim_head=d_head,
|
507 |
+
dropout=dropout,
|
508 |
+
context_dim=context_dim if self.disable_self_attn else None,
|
509 |
+
backend=sdp_backend,
|
510 |
+
) # is a self-attention if not self.disable_self_attn
|
511 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
512 |
+
self.attn2 = attn_cls(
|
513 |
+
query_dim=dim,
|
514 |
+
context_dim=context_dim,
|
515 |
+
heads=n_heads,
|
516 |
+
dim_head=d_head,
|
517 |
+
dropout=dropout,
|
518 |
+
backend=sdp_backend,
|
519 |
+
) # is self-attn if context is none
|
520 |
+
self.norm1 = nn.LayerNorm(dim)
|
521 |
+
self.norm2 = nn.LayerNorm(dim)
|
522 |
+
self.norm3 = nn.LayerNorm(dim)
|
523 |
+
self.checkpoint = checkpoint
|
524 |
+
if self.checkpoint:
|
525 |
+
logpy.debug(f"{self.__class__.__name__} is using checkpointing")
|
526 |
+
|
527 |
+
def forward(
|
528 |
+
self, x, context=None, additional_tokens=None, n_times_crossframe_attn_in_self=0
|
529 |
+
):
|
530 |
+
kwargs = {"x": x}
|
531 |
+
|
532 |
+
if context is not None:
|
533 |
+
kwargs.update({"context": context})
|
534 |
+
|
535 |
+
if additional_tokens is not None:
|
536 |
+
kwargs.update({"additional_tokens": additional_tokens})
|
537 |
+
|
538 |
+
if n_times_crossframe_attn_in_self:
|
539 |
+
kwargs.update(
|
540 |
+
{"n_times_crossframe_attn_in_self": n_times_crossframe_attn_in_self}
|
541 |
+
)
|
542 |
+
|
543 |
+
# return mixed_checkpoint(self._forward, kwargs, self.parameters(), self.checkpoint)
|
544 |
+
if self.checkpoint:
|
545 |
+
# inputs = {"x": x, "context": context}
|
546 |
+
return checkpoint(self._forward, x, context)
|
547 |
+
# return checkpoint(self._forward, inputs, self.parameters(), self.checkpoint)
|
548 |
+
else:
|
549 |
+
return self._forward(**kwargs)
|
550 |
+
|
551 |
+
def _forward(
|
552 |
+
self, x, context=None, additional_tokens=None, n_times_crossframe_attn_in_self=0
|
553 |
+
):
|
554 |
+
x = (
|
555 |
+
self.attn1(
|
556 |
+
self.norm1(x),
|
557 |
+
context=context if self.disable_self_attn else None,
|
558 |
+
additional_tokens=additional_tokens,
|
559 |
+
n_times_crossframe_attn_in_self=n_times_crossframe_attn_in_self
|
560 |
+
if not self.disable_self_attn
|
561 |
+
else 0,
|
562 |
+
)
|
563 |
+
+ x
|
564 |
+
)
|
565 |
+
x = (
|
566 |
+
self.attn2(
|
567 |
+
self.norm2(x), context=context, additional_tokens=additional_tokens
|
568 |
+
)
|
569 |
+
+ x
|
570 |
+
)
|
571 |
+
x = self.ff(self.norm3(x)) + x
|
572 |
+
return x
|
573 |
+
|
574 |
+
|
575 |
+
class BasicTransformerSingleLayerBlock(nn.Module):
|
576 |
+
ATTENTION_MODES = {
|
577 |
+
"softmax": CrossAttention, # vanilla attention
|
578 |
+
"softmax-xformers": MemoryEfficientCrossAttention # on the A100s not quite as fast as the above version
|
579 |
+
# (todo might depend on head_dim, check, falls back to semi-optimized kernels for dim!=[16,32,64,128])
|
580 |
+
}
|
581 |
+
|
582 |
+
def __init__(
|
583 |
+
self,
|
584 |
+
dim,
|
585 |
+
n_heads,
|
586 |
+
d_head,
|
587 |
+
dropout=0.0,
|
588 |
+
context_dim=None,
|
589 |
+
gated_ff=True,
|
590 |
+
checkpoint=True,
|
591 |
+
attn_mode="softmax",
|
592 |
+
):
|
593 |
+
super().__init__()
|
594 |
+
assert attn_mode in self.ATTENTION_MODES
|
595 |
+
attn_cls = self.ATTENTION_MODES[attn_mode]
|
596 |
+
self.attn1 = attn_cls(
|
597 |
+
query_dim=dim,
|
598 |
+
heads=n_heads,
|
599 |
+
dim_head=d_head,
|
600 |
+
dropout=dropout,
|
601 |
+
context_dim=context_dim,
|
602 |
+
)
|
603 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
604 |
+
self.norm1 = nn.LayerNorm(dim)
|
605 |
+
self.norm2 = nn.LayerNorm(dim)
|
606 |
+
self.checkpoint = checkpoint
|
607 |
+
|
608 |
+
def forward(self, x, context=None):
|
609 |
+
# inputs = {"x": x, "context": context}
|
610 |
+
# return checkpoint(self._forward, inputs, self.parameters(), self.checkpoint)
|
611 |
+
return checkpoint(self._forward, x, context)
|
612 |
+
|
613 |
+
def _forward(self, x, context=None):
|
614 |
+
x = self.attn1(self.norm1(x), context=context) + x
|
615 |
+
x = self.ff(self.norm2(x)) + x
|
616 |
+
return x
|
617 |
+
|
618 |
+
|
619 |
+
class SpatialTransformer(nn.Module):
|
620 |
+
"""
|
621 |
+
Transformer block for image-like data.
|
622 |
+
First, project the input (aka embedding)
|
623 |
+
and reshape to b, t, d.
|
624 |
+
Then apply standard transformer action.
|
625 |
+
Finally, reshape to image
|
626 |
+
NEW: use_linear for more efficiency instead of the 1x1 convs
|
627 |
+
"""
|
628 |
+
|
629 |
+
def __init__(
|
630 |
+
self,
|
631 |
+
in_channels,
|
632 |
+
n_heads,
|
633 |
+
d_head,
|
634 |
+
depth=1,
|
635 |
+
dropout=0.0,
|
636 |
+
context_dim=None,
|
637 |
+
disable_self_attn=False,
|
638 |
+
use_linear=False,
|
639 |
+
attn_type="softmax",
|
640 |
+
use_checkpoint=True,
|
641 |
+
# sdp_backend=SDPBackend.FLASH_ATTENTION
|
642 |
+
sdp_backend=None,
|
643 |
+
):
|
644 |
+
super().__init__()
|
645 |
+
logpy.debug(
|
646 |
+
f"constructing {self.__class__.__name__} of depth {depth} w/ "
|
647 |
+
f"{in_channels} channels and {n_heads} heads."
|
648 |
+
)
|
649 |
+
|
650 |
+
if exists(context_dim) and not isinstance(context_dim, list):
|
651 |
+
context_dim = [context_dim]
|
652 |
+
if exists(context_dim) and isinstance(context_dim, list):
|
653 |
+
if depth != len(context_dim):
|
654 |
+
logpy.warn(
|
655 |
+
f"{self.__class__.__name__}: Found context dims "
|
656 |
+
f"{context_dim} of depth {len(context_dim)}, which does not "
|
657 |
+
f"match the specified 'depth' of {depth}. Setting context_dim "
|
658 |
+
f"to {depth * [context_dim[0]]} now."
|
659 |
+
)
|
660 |
+
# depth does not match context dims.
|
661 |
+
assert all(
|
662 |
+
map(lambda x: x == context_dim[0], context_dim)
|
663 |
+
), "need homogenous context_dim to match depth automatically"
|
664 |
+
context_dim = depth * [context_dim[0]]
|
665 |
+
elif context_dim is None:
|
666 |
+
context_dim = [None] * depth
|
667 |
+
self.in_channels = in_channels
|
668 |
+
inner_dim = n_heads * d_head
|
669 |
+
self.norm = Normalize(in_channels)
|
670 |
+
if not use_linear:
|
671 |
+
self.proj_in = nn.Conv2d(
|
672 |
+
in_channels, inner_dim, kernel_size=1, stride=1, padding=0
|
673 |
+
)
|
674 |
+
else:
|
675 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
676 |
+
|
677 |
+
self.transformer_blocks = nn.ModuleList(
|
678 |
+
[
|
679 |
+
BasicTransformerBlock(
|
680 |
+
inner_dim,
|
681 |
+
n_heads,
|
682 |
+
d_head,
|
683 |
+
dropout=dropout,
|
684 |
+
context_dim=context_dim[d],
|
685 |
+
disable_self_attn=disable_self_attn,
|
686 |
+
attn_mode=attn_type,
|
687 |
+
checkpoint=use_checkpoint,
|
688 |
+
sdp_backend=sdp_backend,
|
689 |
+
)
|
690 |
+
for d in range(depth)
|
691 |
+
]
|
692 |
+
)
|
693 |
+
if not use_linear:
|
694 |
+
self.proj_out = zero_module(
|
695 |
+
nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
|
696 |
+
)
|
697 |
+
else:
|
698 |
+
# self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
|
699 |
+
self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
|
700 |
+
self.use_linear = use_linear
|
701 |
+
|
702 |
+
def forward(self, x, context=None):
|
703 |
+
# note: if no context is given, cross-attention defaults to self-attention
|
704 |
+
if not isinstance(context, list):
|
705 |
+
context = [context]
|
706 |
+
b, c, h, w = x.shape
|
707 |
+
x_in = x
|
708 |
+
x = self.norm(x)
|
709 |
+
if not self.use_linear:
|
710 |
+
x = self.proj_in(x)
|
711 |
+
x = rearrange(x, "b c h w -> b (h w) c").contiguous()
|
712 |
+
if self.use_linear:
|
713 |
+
x = self.proj_in(x)
|
714 |
+
for i, block in enumerate(self.transformer_blocks):
|
715 |
+
if i > 0 and len(context) == 1:
|
716 |
+
i = 0 # use same context for each block
|
717 |
+
x = block(x, context=context[i])
|
718 |
+
if self.use_linear:
|
719 |
+
x = self.proj_out(x)
|
720 |
+
x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()
|
721 |
+
if not self.use_linear:
|
722 |
+
x = self.proj_out(x)
|
723 |
+
return x + x_in
|
724 |
+
|
725 |
+
|
726 |
+
class SimpleTransformer(nn.Module):
|
727 |
+
def __init__(
|
728 |
+
self,
|
729 |
+
dim: int,
|
730 |
+
depth: int,
|
731 |
+
heads: int,
|
732 |
+
dim_head: int,
|
733 |
+
context_dim: Optional[int] = None,
|
734 |
+
dropout: float = 0.0,
|
735 |
+
checkpoint: bool = True,
|
736 |
+
):
|
737 |
+
super().__init__()
|
738 |
+
self.layers = nn.ModuleList([])
|
739 |
+
for _ in range(depth):
|
740 |
+
self.layers.append(
|
741 |
+
BasicTransformerBlock(
|
742 |
+
dim,
|
743 |
+
heads,
|
744 |
+
dim_head,
|
745 |
+
dropout=dropout,
|
746 |
+
context_dim=context_dim,
|
747 |
+
attn_mode="softmax-xformers",
|
748 |
+
checkpoint=checkpoint,
|
749 |
+
)
|
750 |
+
)
|
751 |
+
|
752 |
+
def forward(
|
753 |
+
self,
|
754 |
+
x: torch.Tensor,
|
755 |
+
context: Optional[torch.Tensor] = None,
|
756 |
+
) -> torch.Tensor:
|
757 |
+
for layer in self.layers:
|
758 |
+
x = layer(x, context)
|
759 |
+
return x
|
lvdm/modules/encoders/condition.py
ADDED
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import kornia
|
4 |
+
import open_clip
|
5 |
+
from torch.utils.checkpoint import checkpoint
|
6 |
+
from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel
|
7 |
+
from lvdm.common import autocast
|
8 |
+
from utils.utils import count_params
|
9 |
+
|
10 |
+
|
11 |
+
class AbstractEncoder(nn.Module):
|
12 |
+
def __init__(self):
|
13 |
+
super().__init__()
|
14 |
+
|
15 |
+
def encode(self, *args, **kwargs):
|
16 |
+
raise NotImplementedError
|
17 |
+
|
18 |
+
|
19 |
+
class IdentityEncoder(AbstractEncoder):
|
20 |
+
def encode(self, x):
|
21 |
+
return x
|
22 |
+
|
23 |
+
|
24 |
+
class ClassEmbedder(nn.Module):
|
25 |
+
def __init__(self, embed_dim, n_classes=1000, key='class', ucg_rate=0.1):
|
26 |
+
super().__init__()
|
27 |
+
self.key = key
|
28 |
+
self.embedding = nn.Embedding(n_classes, embed_dim)
|
29 |
+
self.n_classes = n_classes
|
30 |
+
self.ucg_rate = ucg_rate
|
31 |
+
|
32 |
+
def forward(self, batch, key=None, disable_dropout=False):
|
33 |
+
if key is None:
|
34 |
+
key = self.key
|
35 |
+
# this is for use in crossattn
|
36 |
+
c = batch[key][:, None]
|
37 |
+
if self.ucg_rate > 0. and not disable_dropout:
|
38 |
+
mask = 1. - torch.bernoulli(torch.ones_like(c) * self.ucg_rate)
|
39 |
+
c = mask * c + (1 - mask) * torch.ones_like(c) * (self.n_classes - 1)
|
40 |
+
c = c.long()
|
41 |
+
c = self.embedding(c)
|
42 |
+
return c
|
43 |
+
|
44 |
+
def get_unconditional_conditioning(self, bs, device="cuda"):
|
45 |
+
uc_class = self.n_classes - 1 # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
|
46 |
+
uc = torch.ones((bs,), device=device) * uc_class
|
47 |
+
uc = {self.key: uc}
|
48 |
+
return uc
|
49 |
+
|
50 |
+
|
51 |
+
def disabled_train(self, mode=True):
|
52 |
+
"""Overwrite model.train with this function to make sure train/eval mode
|
53 |
+
does not change anymore."""
|
54 |
+
return self
|
55 |
+
|
56 |
+
|
57 |
+
class FrozenT5Embedder(AbstractEncoder):
|
58 |
+
"""Uses the T5 transformer encoder for text"""
|
59 |
+
|
60 |
+
def __init__(self, version="google/t5-v1_1-large", device="cuda", max_length=77,
|
61 |
+
freeze=True): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
|
62 |
+
super().__init__()
|
63 |
+
self.tokenizer = T5Tokenizer.from_pretrained(version)
|
64 |
+
self.transformer = T5EncoderModel.from_pretrained(version)
|
65 |
+
self.device = device
|
66 |
+
self.max_length = max_length # TODO: typical value?
|
67 |
+
if freeze:
|
68 |
+
self.freeze()
|
69 |
+
|
70 |
+
def freeze(self):
|
71 |
+
self.transformer = self.transformer.eval()
|
72 |
+
# self.train = disabled_train
|
73 |
+
for param in self.parameters():
|
74 |
+
param.requires_grad = False
|
75 |
+
|
76 |
+
def forward(self, text):
|
77 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
78 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
79 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
80 |
+
outputs = self.transformer(input_ids=tokens)
|
81 |
+
|
82 |
+
z = outputs.last_hidden_state
|
83 |
+
return z
|
84 |
+
|
85 |
+
def encode(self, text):
|
86 |
+
return self(text)
|
87 |
+
|
88 |
+
|
89 |
+
class FrozenCLIPEmbedder(AbstractEncoder):
|
90 |
+
"""Uses the CLIP transformer encoder for text (from huggingface)"""
|
91 |
+
LAYERS = [
|
92 |
+
"last",
|
93 |
+
"pooled",
|
94 |
+
"hidden"
|
95 |
+
]
|
96 |
+
|
97 |
+
def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77,
|
98 |
+
freeze=True, layer="last", layer_idx=None): # clip-vit-base-patch32
|
99 |
+
super().__init__()
|
100 |
+
assert layer in self.LAYERS
|
101 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(version)
|
102 |
+
self.transformer = CLIPTextModel.from_pretrained(version)
|
103 |
+
self.device = device
|
104 |
+
self.max_length = max_length
|
105 |
+
if freeze:
|
106 |
+
self.freeze()
|
107 |
+
self.layer = layer
|
108 |
+
self.layer_idx = layer_idx
|
109 |
+
if layer == "hidden":
|
110 |
+
assert layer_idx is not None
|
111 |
+
assert 0 <= abs(layer_idx) <= 12
|
112 |
+
|
113 |
+
def freeze(self):
|
114 |
+
self.transformer = self.transformer.eval()
|
115 |
+
# self.train = disabled_train
|
116 |
+
for param in self.parameters():
|
117 |
+
param.requires_grad = False
|
118 |
+
|
119 |
+
def forward(self, text):
|
120 |
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
121 |
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
122 |
+
tokens = batch_encoding["input_ids"].to(self.device)
|
123 |
+
outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer == "hidden")
|
124 |
+
if self.layer == "last":
|
125 |
+
z = outputs.last_hidden_state
|
126 |
+
elif self.layer == "pooled":
|
127 |
+
z = outputs.pooler_output[:, None, :]
|
128 |
+
else:
|
129 |
+
z = outputs.hidden_states[self.layer_idx]
|
130 |
+
return z
|
131 |
+
|
132 |
+
def encode(self, text):
|
133 |
+
return self(text)
|
134 |
+
|
135 |
+
|
136 |
+
class ClipImageEmbedder(nn.Module):
|
137 |
+
def __init__(
|
138 |
+
self,
|
139 |
+
model,
|
140 |
+
jit=False,
|
141 |
+
device='cuda' if torch.cuda.is_available() else 'cpu',
|
142 |
+
antialias=True,
|
143 |
+
ucg_rate=0.
|
144 |
+
):
|
145 |
+
super().__init__()
|
146 |
+
from clip import load as load_clip
|
147 |
+
self.model, _ = load_clip(name=model, device=device, jit=jit)
|
148 |
+
|
149 |
+
self.antialias = antialias
|
150 |
+
|
151 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
152 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
153 |
+
self.ucg_rate = ucg_rate
|
154 |
+
|
155 |
+
def preprocess(self, x):
|
156 |
+
# normalize to [0,1]
|
157 |
+
x = kornia.geometry.resize(x, (224, 224),
|
158 |
+
interpolation='bicubic', align_corners=True,
|
159 |
+
antialias=self.antialias)
|
160 |
+
x = (x + 1.) / 2.
|
161 |
+
# re-normalize according to clip
|
162 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
163 |
+
return x
|
164 |
+
|
165 |
+
def forward(self, x, no_dropout=False):
|
166 |
+
# x is assumed to be in range [-1,1]
|
167 |
+
out = self.model.encode_image(self.preprocess(x))
|
168 |
+
out = out.to(x.dtype)
|
169 |
+
if self.ucg_rate > 0. and not no_dropout:
|
170 |
+
out = torch.bernoulli((1. - self.ucg_rate) * torch.ones(out.shape[0], device=out.device))[:, None] * out
|
171 |
+
return out
|
172 |
+
|
173 |
+
|
174 |
+
class FrozenOpenCLIPEmbedder(AbstractEncoder):
|
175 |
+
"""
|
176 |
+
Uses the OpenCLIP transformer encoder for text
|
177 |
+
"""
|
178 |
+
LAYERS = [
|
179 |
+
# "pooled",
|
180 |
+
"last",
|
181 |
+
"penultimate"
|
182 |
+
]
|
183 |
+
|
184 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
|
185 |
+
freeze=True, layer="last"):
|
186 |
+
super().__init__()
|
187 |
+
assert layer in self.LAYERS
|
188 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'), pretrained=version)
|
189 |
+
del model.visual
|
190 |
+
self.model = model
|
191 |
+
|
192 |
+
self.device = device
|
193 |
+
self.max_length = max_length
|
194 |
+
if freeze:
|
195 |
+
self.freeze()
|
196 |
+
self.layer = layer
|
197 |
+
if self.layer == "last":
|
198 |
+
self.layer_idx = 0
|
199 |
+
elif self.layer == "penultimate":
|
200 |
+
self.layer_idx = 1
|
201 |
+
else:
|
202 |
+
raise NotImplementedError()
|
203 |
+
|
204 |
+
def freeze(self):
|
205 |
+
self.model = self.model.eval()
|
206 |
+
for param in self.parameters():
|
207 |
+
param.requires_grad = False
|
208 |
+
|
209 |
+
def forward(self, text):
|
210 |
+
tokens = open_clip.tokenize(text) ## all clip models use 77 as context length
|
211 |
+
z = self.encode_with_transformer(tokens.to(self.device))
|
212 |
+
return z
|
213 |
+
|
214 |
+
def encode_with_transformer(self, text):
|
215 |
+
x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
|
216 |
+
x = x + self.model.positional_embedding
|
217 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
218 |
+
x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
|
219 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
220 |
+
x = self.model.ln_final(x)
|
221 |
+
return x
|
222 |
+
|
223 |
+
def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
|
224 |
+
for i, r in enumerate(self.model.transformer.resblocks):
|
225 |
+
if i == len(self.model.transformer.resblocks) - self.layer_idx:
|
226 |
+
break
|
227 |
+
if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
|
228 |
+
x = checkpoint(r, x, attn_mask)
|
229 |
+
else:
|
230 |
+
x = r(x, attn_mask=attn_mask)
|
231 |
+
return x
|
232 |
+
|
233 |
+
def encode(self, text):
|
234 |
+
return self(text)
|
235 |
+
|
236 |
+
|
237 |
+
class FrozenOpenCLIPImageEmbedder(AbstractEncoder):
|
238 |
+
"""
|
239 |
+
Uses the OpenCLIP vision transformer encoder for images
|
240 |
+
"""
|
241 |
+
|
242 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
|
243 |
+
freeze=True, layer="pooled", antialias=True, ucg_rate=0.):
|
244 |
+
super().__init__()
|
245 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
|
246 |
+
pretrained=version, )
|
247 |
+
del model.transformer
|
248 |
+
self.model = model
|
249 |
+
# self.mapper = torch.nn.Linear(1280, 1024)
|
250 |
+
self.device = device
|
251 |
+
self.max_length = max_length
|
252 |
+
if freeze:
|
253 |
+
self.freeze()
|
254 |
+
self.layer = layer
|
255 |
+
if self.layer == "penultimate":
|
256 |
+
raise NotImplementedError()
|
257 |
+
self.layer_idx = 1
|
258 |
+
|
259 |
+
self.antialias = antialias
|
260 |
+
|
261 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
262 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
263 |
+
self.ucg_rate = ucg_rate
|
264 |
+
|
265 |
+
def preprocess(self, x):
|
266 |
+
# normalize to [0,1]
|
267 |
+
x = kornia.geometry.resize(x, (224, 224),
|
268 |
+
interpolation='bicubic', align_corners=True,
|
269 |
+
antialias=self.antialias)
|
270 |
+
x = (x + 1.) / 2.
|
271 |
+
# renormalize according to clip
|
272 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
273 |
+
return x
|
274 |
+
|
275 |
+
def freeze(self):
|
276 |
+
self.model = self.model.eval()
|
277 |
+
for param in self.model.parameters():
|
278 |
+
param.requires_grad = False
|
279 |
+
|
280 |
+
@autocast
|
281 |
+
def forward(self, image, no_dropout=False):
|
282 |
+
z = self.encode_with_vision_transformer(image)
|
283 |
+
if self.ucg_rate > 0. and not no_dropout:
|
284 |
+
z = torch.bernoulli((1. - self.ucg_rate) * torch.ones(z.shape[0], device=z.device))[:, None] * z
|
285 |
+
return z
|
286 |
+
|
287 |
+
def encode_with_vision_transformer(self, img):
|
288 |
+
img = self.preprocess(img)
|
289 |
+
x = self.model.visual(img)
|
290 |
+
return x
|
291 |
+
|
292 |
+
def encode(self, text):
|
293 |
+
return self(text)
|
294 |
+
|
295 |
+
class FrozenOpenCLIPImageEmbedderV2(AbstractEncoder):
|
296 |
+
"""
|
297 |
+
Uses the OpenCLIP vision transformer encoder for images
|
298 |
+
"""
|
299 |
+
|
300 |
+
def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda",
|
301 |
+
freeze=True, layer="pooled", antialias=True):
|
302 |
+
super().__init__()
|
303 |
+
model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
|
304 |
+
pretrained=version, )
|
305 |
+
del model.transformer
|
306 |
+
self.model = model
|
307 |
+
self.device = device
|
308 |
+
|
309 |
+
if freeze:
|
310 |
+
self.freeze()
|
311 |
+
self.layer = layer
|
312 |
+
if self.layer == "penultimate":
|
313 |
+
raise NotImplementedError()
|
314 |
+
self.layer_idx = 1
|
315 |
+
|
316 |
+
self.antialias = antialias
|
317 |
+
|
318 |
+
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
|
319 |
+
self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
|
320 |
+
|
321 |
+
|
322 |
+
def preprocess(self, x):
|
323 |
+
# normalize to [0,1]
|
324 |
+
x = kornia.geometry.resize(x, (224, 224),
|
325 |
+
interpolation='bicubic', align_corners=True,
|
326 |
+
antialias=self.antialias)
|
327 |
+
x = (x + 1.) / 2.
|
328 |
+
# renormalize according to clip
|
329 |
+
x = kornia.enhance.normalize(x, self.mean, self.std)
|
330 |
+
return x
|
331 |
+
|
332 |
+
def freeze(self):
|
333 |
+
self.model = self.model.eval()
|
334 |
+
for param in self.model.parameters():
|
335 |
+
param.requires_grad = False
|
336 |
+
|
337 |
+
def forward(self, image, no_dropout=False):
|
338 |
+
## image: b c h w
|
339 |
+
z = self.encode_with_vision_transformer(image)
|
340 |
+
return z
|
341 |
+
|
342 |
+
def encode_with_vision_transformer(self, x):
|
343 |
+
x = self.preprocess(x)
|
344 |
+
|
345 |
+
# to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
|
346 |
+
if self.model.visual.input_patchnorm:
|
347 |
+
# einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
|
348 |
+
x = x.reshape(x.shape[0], x.shape[1], self.model.visual.grid_size[0], self.model.visual.patch_size[0], self.model.visual.grid_size[1], self.model.visual.patch_size[1])
|
349 |
+
x = x.permute(0, 2, 4, 1, 3, 5)
|
350 |
+
x = x.reshape(x.shape[0], self.model.visual.grid_size[0] * self.model.visual.grid_size[1], -1)
|
351 |
+
x = self.model.visual.patchnorm_pre_ln(x)
|
352 |
+
x = self.model.visual.conv1(x)
|
353 |
+
else:
|
354 |
+
x = self.model.visual.conv1(x) # shape = [*, width, grid, grid]
|
355 |
+
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
|
356 |
+
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
|
357 |
+
|
358 |
+
# class embeddings and positional embeddings
|
359 |
+
x = torch.cat(
|
360 |
+
[self.model.visual.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
|
361 |
+
x], dim=1) # shape = [*, grid ** 2 + 1, width]
|
362 |
+
x = x + self.model.visual.positional_embedding.to(x.dtype)
|
363 |
+
|
364 |
+
# a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
|
365 |
+
x = self.model.visual.patch_dropout(x)
|
366 |
+
x = self.model.visual.ln_pre(x)
|
367 |
+
|
368 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
369 |
+
x = self.model.visual.transformer(x)
|
370 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
371 |
+
|
372 |
+
return x
|
373 |
+
|
374 |
+
class FrozenCLIPT5Encoder(AbstractEncoder):
|
375 |
+
def __init__(self, clip_version="openai/clip-vit-large-patch14", t5_version="google/t5-v1_1-xl", device="cuda",
|
376 |
+
clip_max_length=77, t5_max_length=77):
|
377 |
+
super().__init__()
|
378 |
+
self.clip_encoder = FrozenCLIPEmbedder(clip_version, device, max_length=clip_max_length)
|
379 |
+
self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
|
380 |
+
print(f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder) * 1.e-6:.2f} M parameters, "
|
381 |
+
f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder) * 1.e-6:.2f} M params.")
|
382 |
+
|
383 |
+
def encode(self, text):
|
384 |
+
return self(text)
|
385 |
+
|
386 |
+
def forward(self, text):
|
387 |
+
clip_z = self.clip_encoder.encode(text)
|
388 |
+
t5_z = self.t5_encoder.encode(text)
|
389 |
+
return [clip_z, t5_z]
|
lvdm/modules/encoders/resampler.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
|
2 |
+
# and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
|
3 |
+
# and https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/resampler.py
|
4 |
+
import math
|
5 |
+
import torch
|
6 |
+
import torch.nn as nn
|
7 |
+
|
8 |
+
|
9 |
+
class ImageProjModel(nn.Module):
|
10 |
+
"""Projection Model"""
|
11 |
+
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
|
12 |
+
super().__init__()
|
13 |
+
self.cross_attention_dim = cross_attention_dim
|
14 |
+
self.clip_extra_context_tokens = clip_extra_context_tokens
|
15 |
+
self.proj = nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
|
16 |
+
self.norm = nn.LayerNorm(cross_attention_dim)
|
17 |
+
|
18 |
+
def forward(self, image_embeds):
|
19 |
+
#embeds = image_embeds
|
20 |
+
embeds = image_embeds.type(list(self.proj.parameters())[0].dtype)
|
21 |
+
clip_extra_context_tokens = self.proj(embeds).reshape(-1, self.clip_extra_context_tokens, self.cross_attention_dim)
|
22 |
+
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
|
23 |
+
return clip_extra_context_tokens
|
24 |
+
|
25 |
+
|
26 |
+
# FFN
|
27 |
+
def FeedForward(dim, mult=4):
|
28 |
+
inner_dim = int(dim * mult)
|
29 |
+
return nn.Sequential(
|
30 |
+
nn.LayerNorm(dim),
|
31 |
+
nn.Linear(dim, inner_dim, bias=False),
|
32 |
+
nn.GELU(),
|
33 |
+
nn.Linear(inner_dim, dim, bias=False),
|
34 |
+
)
|
35 |
+
|
36 |
+
|
37 |
+
def reshape_tensor(x, heads):
|
38 |
+
bs, length, width = x.shape
|
39 |
+
#(bs, length, width) --> (bs, length, n_heads, dim_per_head)
|
40 |
+
x = x.view(bs, length, heads, -1)
|
41 |
+
# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
|
42 |
+
x = x.transpose(1, 2)
|
43 |
+
# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
|
44 |
+
x = x.reshape(bs, heads, length, -1)
|
45 |
+
return x
|
46 |
+
|
47 |
+
|
48 |
+
class PerceiverAttention(nn.Module):
|
49 |
+
def __init__(self, *, dim, dim_head=64, heads=8):
|
50 |
+
super().__init__()
|
51 |
+
self.scale = dim_head**-0.5
|
52 |
+
self.dim_head = dim_head
|
53 |
+
self.heads = heads
|
54 |
+
inner_dim = dim_head * heads
|
55 |
+
|
56 |
+
self.norm1 = nn.LayerNorm(dim)
|
57 |
+
self.norm2 = nn.LayerNorm(dim)
|
58 |
+
|
59 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
60 |
+
self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
|
61 |
+
self.to_out = nn.Linear(inner_dim, dim, bias=False)
|
62 |
+
|
63 |
+
|
64 |
+
def forward(self, x, latents):
|
65 |
+
"""
|
66 |
+
Args:
|
67 |
+
x (torch.Tensor): image features
|
68 |
+
shape (b, n1, D)
|
69 |
+
latent (torch.Tensor): latent features
|
70 |
+
shape (b, n2, D)
|
71 |
+
"""
|
72 |
+
x = self.norm1(x)
|
73 |
+
latents = self.norm2(latents)
|
74 |
+
|
75 |
+
b, l, _ = latents.shape
|
76 |
+
|
77 |
+
q = self.to_q(latents)
|
78 |
+
kv_input = torch.cat((x, latents), dim=-2)
|
79 |
+
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
80 |
+
|
81 |
+
q = reshape_tensor(q, self.heads)
|
82 |
+
k = reshape_tensor(k, self.heads)
|
83 |
+
v = reshape_tensor(v, self.heads)
|
84 |
+
|
85 |
+
# attention
|
86 |
+
scale = 1 / math.sqrt(math.sqrt(self.dim_head))
|
87 |
+
weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
|
88 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
89 |
+
out = weight @ v
|
90 |
+
|
91 |
+
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
|
92 |
+
|
93 |
+
return self.to_out(out)
|
94 |
+
|
95 |
+
|
96 |
+
class Resampler(nn.Module):
|
97 |
+
def __init__(
|
98 |
+
self,
|
99 |
+
dim=1024,
|
100 |
+
depth=8,
|
101 |
+
dim_head=64,
|
102 |
+
heads=16,
|
103 |
+
num_queries=8,
|
104 |
+
embedding_dim=768,
|
105 |
+
output_dim=1024,
|
106 |
+
ff_mult=4,
|
107 |
+
video_length=None, # using frame-wise version or not
|
108 |
+
):
|
109 |
+
super().__init__()
|
110 |
+
## queries for a single frame / image
|
111 |
+
self.num_queries = num_queries
|
112 |
+
self.video_length = video_length
|
113 |
+
|
114 |
+
## <num_queries> queries for each frame
|
115 |
+
if video_length is not None:
|
116 |
+
num_queries = num_queries * video_length
|
117 |
+
|
118 |
+
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
|
119 |
+
self.proj_in = nn.Linear(embedding_dim, dim)
|
120 |
+
self.proj_out = nn.Linear(dim, output_dim)
|
121 |
+
self.norm_out = nn.LayerNorm(output_dim)
|
122 |
+
|
123 |
+
self.layers = nn.ModuleList([])
|
124 |
+
for _ in range(depth):
|
125 |
+
self.layers.append(
|
126 |
+
nn.ModuleList(
|
127 |
+
[
|
128 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
129 |
+
FeedForward(dim=dim, mult=ff_mult),
|
130 |
+
]
|
131 |
+
)
|
132 |
+
)
|
133 |
+
|
134 |
+
def forward(self, x):
|
135 |
+
latents = self.latents.repeat(x.size(0), 1, 1) ## B (T L) C
|
136 |
+
x = self.proj_in(x)
|
137 |
+
|
138 |
+
for attn, ff in self.layers:
|
139 |
+
latents = attn(x, latents) + latents
|
140 |
+
latents = ff(latents) + latents
|
141 |
+
|
142 |
+
latents = self.proj_out(latents)
|
143 |
+
latents = self.norm_out(latents) # B L C or B (T L) C
|
144 |
+
|
145 |
+
return latents
|
lvdm/modules/networks/ae_modules.py
ADDED
@@ -0,0 +1,856 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pytorch_diffusion + derived encoder decoder
|
2 |
+
import math
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
import torch.nn as nn
|
7 |
+
from einops import rearrange
|
8 |
+
|
9 |
+
from utils.utils import instantiate_from_config
|
10 |
+
from lvdm.modules.attention import LinearAttention
|
11 |
+
|
12 |
+
def nonlinearity(x):
|
13 |
+
# swish
|
14 |
+
return x*torch.sigmoid(x)
|
15 |
+
|
16 |
+
|
17 |
+
def Normalize(in_channels, num_groups=32):
|
18 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
class LinAttnBlock(LinearAttention):
|
23 |
+
"""to match AttnBlock usage"""
|
24 |
+
def __init__(self, in_channels):
|
25 |
+
super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
|
26 |
+
|
27 |
+
|
28 |
+
class AttnBlock(nn.Module):
|
29 |
+
def __init__(self, in_channels):
|
30 |
+
super().__init__()
|
31 |
+
self.in_channels = in_channels
|
32 |
+
|
33 |
+
self.norm = Normalize(in_channels)
|
34 |
+
self.q = torch.nn.Conv2d(in_channels,
|
35 |
+
in_channels,
|
36 |
+
kernel_size=1,
|
37 |
+
stride=1,
|
38 |
+
padding=0)
|
39 |
+
self.k = torch.nn.Conv2d(in_channels,
|
40 |
+
in_channels,
|
41 |
+
kernel_size=1,
|
42 |
+
stride=1,
|
43 |
+
padding=0)
|
44 |
+
self.v = torch.nn.Conv2d(in_channels,
|
45 |
+
in_channels,
|
46 |
+
kernel_size=1,
|
47 |
+
stride=1,
|
48 |
+
padding=0)
|
49 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
50 |
+
in_channels,
|
51 |
+
kernel_size=1,
|
52 |
+
stride=1,
|
53 |
+
padding=0)
|
54 |
+
|
55 |
+
def forward(self, x):
|
56 |
+
h_ = x
|
57 |
+
h_ = self.norm(h_)
|
58 |
+
q = self.q(h_)
|
59 |
+
k = self.k(h_)
|
60 |
+
v = self.v(h_)
|
61 |
+
|
62 |
+
# compute attention
|
63 |
+
b,c,h,w = q.shape
|
64 |
+
q = q.reshape(b,c,h*w) # bcl
|
65 |
+
q = q.permute(0,2,1) # bcl -> blc l=hw
|
66 |
+
k = k.reshape(b,c,h*w) # bcl
|
67 |
+
|
68 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
69 |
+
w_ = w_ * (int(c)**(-0.5))
|
70 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
71 |
+
|
72 |
+
# attend to values
|
73 |
+
v = v.reshape(b,c,h*w)
|
74 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
75 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
76 |
+
h_ = h_.reshape(b,c,h,w)
|
77 |
+
|
78 |
+
h_ = self.proj_out(h_)
|
79 |
+
|
80 |
+
return x+h_
|
81 |
+
|
82 |
+
def make_attn(in_channels, attn_type="vanilla"):
|
83 |
+
assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
|
84 |
+
#print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
85 |
+
if attn_type == "vanilla":
|
86 |
+
return AttnBlock(in_channels)
|
87 |
+
elif attn_type == "none":
|
88 |
+
return nn.Identity(in_channels)
|
89 |
+
else:
|
90 |
+
return LinAttnBlock(in_channels)
|
91 |
+
|
92 |
+
class Downsample(nn.Module):
|
93 |
+
def __init__(self, in_channels, with_conv):
|
94 |
+
super().__init__()
|
95 |
+
self.with_conv = with_conv
|
96 |
+
self.in_channels = in_channels
|
97 |
+
if self.with_conv:
|
98 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
99 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
100 |
+
in_channels,
|
101 |
+
kernel_size=3,
|
102 |
+
stride=2,
|
103 |
+
padding=0)
|
104 |
+
def forward(self, x):
|
105 |
+
if self.with_conv:
|
106 |
+
pad = (0,1,0,1)
|
107 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
108 |
+
x = self.conv(x)
|
109 |
+
else:
|
110 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
111 |
+
return x
|
112 |
+
|
113 |
+
class Upsample(nn.Module):
|
114 |
+
def __init__(self, in_channels, with_conv):
|
115 |
+
super().__init__()
|
116 |
+
self.with_conv = with_conv
|
117 |
+
self.in_channels = in_channels
|
118 |
+
if self.with_conv:
|
119 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
120 |
+
in_channels,
|
121 |
+
kernel_size=3,
|
122 |
+
stride=1,
|
123 |
+
padding=1)
|
124 |
+
|
125 |
+
def forward(self, x):
|
126 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
127 |
+
if self.with_conv:
|
128 |
+
x = self.conv(x)
|
129 |
+
return x
|
130 |
+
|
131 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
132 |
+
"""
|
133 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
134 |
+
From Fairseq.
|
135 |
+
Build sinusoidal embeddings.
|
136 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
137 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
138 |
+
"""
|
139 |
+
assert len(timesteps.shape) == 1
|
140 |
+
|
141 |
+
half_dim = embedding_dim // 2
|
142 |
+
emb = math.log(10000) / (half_dim - 1)
|
143 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
144 |
+
emb = emb.to(device=timesteps.device)
|
145 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
146 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
147 |
+
if embedding_dim % 2 == 1: # zero pad
|
148 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
149 |
+
return emb
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
class ResnetBlock(nn.Module):
|
154 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
155 |
+
dropout, temb_channels=512):
|
156 |
+
super().__init__()
|
157 |
+
self.in_channels = in_channels
|
158 |
+
out_channels = in_channels if out_channels is None else out_channels
|
159 |
+
self.out_channels = out_channels
|
160 |
+
self.use_conv_shortcut = conv_shortcut
|
161 |
+
|
162 |
+
self.norm1 = Normalize(in_channels)
|
163 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
164 |
+
out_channels,
|
165 |
+
kernel_size=3,
|
166 |
+
stride=1,
|
167 |
+
padding=1)
|
168 |
+
if temb_channels > 0:
|
169 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
170 |
+
out_channels)
|
171 |
+
self.norm2 = Normalize(out_channels)
|
172 |
+
self.dropout = torch.nn.Dropout(dropout)
|
173 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
174 |
+
out_channels,
|
175 |
+
kernel_size=3,
|
176 |
+
stride=1,
|
177 |
+
padding=1)
|
178 |
+
if self.in_channels != self.out_channels:
|
179 |
+
if self.use_conv_shortcut:
|
180 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
181 |
+
out_channels,
|
182 |
+
kernel_size=3,
|
183 |
+
stride=1,
|
184 |
+
padding=1)
|
185 |
+
else:
|
186 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
187 |
+
out_channels,
|
188 |
+
kernel_size=1,
|
189 |
+
stride=1,
|
190 |
+
padding=0)
|
191 |
+
|
192 |
+
def forward(self, x, temb):
|
193 |
+
h = x
|
194 |
+
h = self.norm1(h)
|
195 |
+
h = nonlinearity(h)
|
196 |
+
h = self.conv1(h)
|
197 |
+
|
198 |
+
if temb is not None:
|
199 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
200 |
+
|
201 |
+
h = self.norm2(h)
|
202 |
+
h = nonlinearity(h)
|
203 |
+
h = self.dropout(h)
|
204 |
+
h = self.conv2(h)
|
205 |
+
|
206 |
+
if self.in_channels != self.out_channels:
|
207 |
+
if self.use_conv_shortcut:
|
208 |
+
x = self.conv_shortcut(x)
|
209 |
+
else:
|
210 |
+
x = self.nin_shortcut(x)
|
211 |
+
|
212 |
+
return x+h
|
213 |
+
|
214 |
+
class Model(nn.Module):
|
215 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
216 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
217 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
218 |
+
super().__init__()
|
219 |
+
if use_linear_attn: attn_type = "linear"
|
220 |
+
self.ch = ch
|
221 |
+
self.temb_ch = self.ch*4
|
222 |
+
self.num_resolutions = len(ch_mult)
|
223 |
+
self.num_res_blocks = num_res_blocks
|
224 |
+
self.resolution = resolution
|
225 |
+
self.in_channels = in_channels
|
226 |
+
|
227 |
+
self.use_timestep = use_timestep
|
228 |
+
if self.use_timestep:
|
229 |
+
# timestep embedding
|
230 |
+
self.temb = nn.Module()
|
231 |
+
self.temb.dense = nn.ModuleList([
|
232 |
+
torch.nn.Linear(self.ch,
|
233 |
+
self.temb_ch),
|
234 |
+
torch.nn.Linear(self.temb_ch,
|
235 |
+
self.temb_ch),
|
236 |
+
])
|
237 |
+
|
238 |
+
# downsampling
|
239 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
240 |
+
self.ch,
|
241 |
+
kernel_size=3,
|
242 |
+
stride=1,
|
243 |
+
padding=1)
|
244 |
+
|
245 |
+
curr_res = resolution
|
246 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
247 |
+
self.down = nn.ModuleList()
|
248 |
+
for i_level in range(self.num_resolutions):
|
249 |
+
block = nn.ModuleList()
|
250 |
+
attn = nn.ModuleList()
|
251 |
+
block_in = ch*in_ch_mult[i_level]
|
252 |
+
block_out = ch*ch_mult[i_level]
|
253 |
+
for i_block in range(self.num_res_blocks):
|
254 |
+
block.append(ResnetBlock(in_channels=block_in,
|
255 |
+
out_channels=block_out,
|
256 |
+
temb_channels=self.temb_ch,
|
257 |
+
dropout=dropout))
|
258 |
+
block_in = block_out
|
259 |
+
if curr_res in attn_resolutions:
|
260 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
261 |
+
down = nn.Module()
|
262 |
+
down.block = block
|
263 |
+
down.attn = attn
|
264 |
+
if i_level != self.num_resolutions-1:
|
265 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
266 |
+
curr_res = curr_res // 2
|
267 |
+
self.down.append(down)
|
268 |
+
|
269 |
+
# middle
|
270 |
+
self.mid = nn.Module()
|
271 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
272 |
+
out_channels=block_in,
|
273 |
+
temb_channels=self.temb_ch,
|
274 |
+
dropout=dropout)
|
275 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
276 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
277 |
+
out_channels=block_in,
|
278 |
+
temb_channels=self.temb_ch,
|
279 |
+
dropout=dropout)
|
280 |
+
|
281 |
+
# upsampling
|
282 |
+
self.up = nn.ModuleList()
|
283 |
+
for i_level in reversed(range(self.num_resolutions)):
|
284 |
+
block = nn.ModuleList()
|
285 |
+
attn = nn.ModuleList()
|
286 |
+
block_out = ch*ch_mult[i_level]
|
287 |
+
skip_in = ch*ch_mult[i_level]
|
288 |
+
for i_block in range(self.num_res_blocks+1):
|
289 |
+
if i_block == self.num_res_blocks:
|
290 |
+
skip_in = ch*in_ch_mult[i_level]
|
291 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
292 |
+
out_channels=block_out,
|
293 |
+
temb_channels=self.temb_ch,
|
294 |
+
dropout=dropout))
|
295 |
+
block_in = block_out
|
296 |
+
if curr_res in attn_resolutions:
|
297 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
298 |
+
up = nn.Module()
|
299 |
+
up.block = block
|
300 |
+
up.attn = attn
|
301 |
+
if i_level != 0:
|
302 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
303 |
+
curr_res = curr_res * 2
|
304 |
+
self.up.insert(0, up) # prepend to get consistent order
|
305 |
+
|
306 |
+
# end
|
307 |
+
self.norm_out = Normalize(block_in)
|
308 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
309 |
+
out_ch,
|
310 |
+
kernel_size=3,
|
311 |
+
stride=1,
|
312 |
+
padding=1)
|
313 |
+
|
314 |
+
def forward(self, x, t=None, context=None):
|
315 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
316 |
+
if context is not None:
|
317 |
+
# assume aligned context, cat along channel axis
|
318 |
+
x = torch.cat((x, context), dim=1)
|
319 |
+
if self.use_timestep:
|
320 |
+
# timestep embedding
|
321 |
+
assert t is not None
|
322 |
+
temb = get_timestep_embedding(t, self.ch)
|
323 |
+
temb = self.temb.dense[0](temb)
|
324 |
+
temb = nonlinearity(temb)
|
325 |
+
temb = self.temb.dense[1](temb)
|
326 |
+
else:
|
327 |
+
temb = None
|
328 |
+
|
329 |
+
# downsampling
|
330 |
+
hs = [self.conv_in(x)]
|
331 |
+
for i_level in range(self.num_resolutions):
|
332 |
+
for i_block in range(self.num_res_blocks):
|
333 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
334 |
+
if len(self.down[i_level].attn) > 0:
|
335 |
+
h = self.down[i_level].attn[i_block](h)
|
336 |
+
hs.append(h)
|
337 |
+
if i_level != self.num_resolutions-1:
|
338 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
339 |
+
|
340 |
+
# middle
|
341 |
+
h = hs[-1]
|
342 |
+
h = self.mid.block_1(h, temb)
|
343 |
+
h = self.mid.attn_1(h)
|
344 |
+
h = self.mid.block_2(h, temb)
|
345 |
+
|
346 |
+
# upsampling
|
347 |
+
for i_level in reversed(range(self.num_resolutions)):
|
348 |
+
for i_block in range(self.num_res_blocks+1):
|
349 |
+
h = self.up[i_level].block[i_block](
|
350 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
351 |
+
if len(self.up[i_level].attn) > 0:
|
352 |
+
h = self.up[i_level].attn[i_block](h)
|
353 |
+
if i_level != 0:
|
354 |
+
h = self.up[i_level].upsample(h)
|
355 |
+
|
356 |
+
# end
|
357 |
+
h = self.norm_out(h)
|
358 |
+
h = nonlinearity(h)
|
359 |
+
h = self.conv_out(h)
|
360 |
+
return h
|
361 |
+
|
362 |
+
def get_last_layer(self):
|
363 |
+
return self.conv_out.weight
|
364 |
+
|
365 |
+
|
366 |
+
class Encoder(nn.Module):
|
367 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
368 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
369 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
370 |
+
**ignore_kwargs):
|
371 |
+
super().__init__()
|
372 |
+
if use_linear_attn: attn_type = "linear"
|
373 |
+
self.ch = ch
|
374 |
+
self.temb_ch = 0
|
375 |
+
self.num_resolutions = len(ch_mult)
|
376 |
+
self.num_res_blocks = num_res_blocks
|
377 |
+
self.resolution = resolution
|
378 |
+
self.in_channels = in_channels
|
379 |
+
|
380 |
+
# downsampling
|
381 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
382 |
+
self.ch,
|
383 |
+
kernel_size=3,
|
384 |
+
stride=1,
|
385 |
+
padding=1)
|
386 |
+
|
387 |
+
curr_res = resolution
|
388 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
389 |
+
self.in_ch_mult = in_ch_mult
|
390 |
+
self.down = nn.ModuleList()
|
391 |
+
for i_level in range(self.num_resolutions):
|
392 |
+
block = nn.ModuleList()
|
393 |
+
attn = nn.ModuleList()
|
394 |
+
block_in = ch*in_ch_mult[i_level]
|
395 |
+
block_out = ch*ch_mult[i_level]
|
396 |
+
for i_block in range(self.num_res_blocks):
|
397 |
+
block.append(ResnetBlock(in_channels=block_in,
|
398 |
+
out_channels=block_out,
|
399 |
+
temb_channels=self.temb_ch,
|
400 |
+
dropout=dropout))
|
401 |
+
block_in = block_out
|
402 |
+
if curr_res in attn_resolutions:
|
403 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
404 |
+
down = nn.Module()
|
405 |
+
down.block = block
|
406 |
+
down.attn = attn
|
407 |
+
if i_level != self.num_resolutions-1:
|
408 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
409 |
+
curr_res = curr_res // 2
|
410 |
+
self.down.append(down)
|
411 |
+
|
412 |
+
# middle
|
413 |
+
self.mid = nn.Module()
|
414 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
415 |
+
out_channels=block_in,
|
416 |
+
temb_channels=self.temb_ch,
|
417 |
+
dropout=dropout)
|
418 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
419 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
420 |
+
out_channels=block_in,
|
421 |
+
temb_channels=self.temb_ch,
|
422 |
+
dropout=dropout)
|
423 |
+
|
424 |
+
# end
|
425 |
+
self.norm_out = Normalize(block_in)
|
426 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
427 |
+
2*z_channels if double_z else z_channels,
|
428 |
+
kernel_size=3,
|
429 |
+
stride=1,
|
430 |
+
padding=1)
|
431 |
+
|
432 |
+
def forward(self, x, return_hidden_states=False):
|
433 |
+
# timestep embedding
|
434 |
+
temb = None
|
435 |
+
|
436 |
+
# print(f'encoder-input={x.shape}')
|
437 |
+
# downsampling
|
438 |
+
hs = [self.conv_in(x)]
|
439 |
+
|
440 |
+
## if we return hidden states for decoder usage, we will store them in a list
|
441 |
+
if return_hidden_states:
|
442 |
+
hidden_states = []
|
443 |
+
# print(f'encoder-conv in feat={hs[0].shape}')
|
444 |
+
for i_level in range(self.num_resolutions):
|
445 |
+
for i_block in range(self.num_res_blocks):
|
446 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
447 |
+
# print(f'encoder-down feat={h.shape}')
|
448 |
+
if len(self.down[i_level].attn) > 0:
|
449 |
+
h = self.down[i_level].attn[i_block](h)
|
450 |
+
hs.append(h)
|
451 |
+
if return_hidden_states:
|
452 |
+
hidden_states.append(h)
|
453 |
+
if i_level != self.num_resolutions-1:
|
454 |
+
# print(f'encoder-downsample (input)={hs[-1].shape}')
|
455 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
456 |
+
# print(f'encoder-downsample (output)={hs[-1].shape}')
|
457 |
+
if return_hidden_states:
|
458 |
+
hidden_states.append(hs[0])
|
459 |
+
# middle
|
460 |
+
h = hs[-1]
|
461 |
+
h = self.mid.block_1(h, temb)
|
462 |
+
# print(f'encoder-mid1 feat={h.shape}')
|
463 |
+
h = self.mid.attn_1(h)
|
464 |
+
h = self.mid.block_2(h, temb)
|
465 |
+
# print(f'encoder-mid2 feat={h.shape}')
|
466 |
+
|
467 |
+
# end
|
468 |
+
h = self.norm_out(h)
|
469 |
+
h = nonlinearity(h)
|
470 |
+
h = self.conv_out(h)
|
471 |
+
# print(f'end feat={h.shape}')
|
472 |
+
if return_hidden_states:
|
473 |
+
return h, hidden_states
|
474 |
+
else:
|
475 |
+
return h
|
476 |
+
|
477 |
+
|
478 |
+
class Decoder(nn.Module):
|
479 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
480 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
481 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
482 |
+
attn_type="vanilla", **ignorekwargs):
|
483 |
+
super().__init__()
|
484 |
+
if use_linear_attn: attn_type = "linear"
|
485 |
+
self.ch = ch
|
486 |
+
self.temb_ch = 0
|
487 |
+
self.num_resolutions = len(ch_mult)
|
488 |
+
self.num_res_blocks = num_res_blocks
|
489 |
+
self.resolution = resolution
|
490 |
+
self.in_channels = in_channels
|
491 |
+
self.give_pre_end = give_pre_end
|
492 |
+
self.tanh_out = tanh_out
|
493 |
+
|
494 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
495 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
496 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
497 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
498 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
499 |
+
print("AE working on z of shape {} = {} dimensions.".format(
|
500 |
+
self.z_shape, np.prod(self.z_shape)))
|
501 |
+
|
502 |
+
# z to block_in
|
503 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
504 |
+
block_in,
|
505 |
+
kernel_size=3,
|
506 |
+
stride=1,
|
507 |
+
padding=1)
|
508 |
+
|
509 |
+
# middle
|
510 |
+
self.mid = nn.Module()
|
511 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
512 |
+
out_channels=block_in,
|
513 |
+
temb_channels=self.temb_ch,
|
514 |
+
dropout=dropout)
|
515 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
516 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
517 |
+
out_channels=block_in,
|
518 |
+
temb_channels=self.temb_ch,
|
519 |
+
dropout=dropout)
|
520 |
+
|
521 |
+
# upsampling
|
522 |
+
self.up = nn.ModuleList()
|
523 |
+
for i_level in reversed(range(self.num_resolutions)):
|
524 |
+
block = nn.ModuleList()
|
525 |
+
attn = nn.ModuleList()
|
526 |
+
block_out = ch*ch_mult[i_level]
|
527 |
+
for i_block in range(self.num_res_blocks+1):
|
528 |
+
block.append(ResnetBlock(in_channels=block_in,
|
529 |
+
out_channels=block_out,
|
530 |
+
temb_channels=self.temb_ch,
|
531 |
+
dropout=dropout))
|
532 |
+
block_in = block_out
|
533 |
+
if curr_res in attn_resolutions:
|
534 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
535 |
+
up = nn.Module()
|
536 |
+
up.block = block
|
537 |
+
up.attn = attn
|
538 |
+
if i_level != 0:
|
539 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
540 |
+
curr_res = curr_res * 2
|
541 |
+
self.up.insert(0, up) # prepend to get consistent order
|
542 |
+
|
543 |
+
# end
|
544 |
+
self.norm_out = Normalize(block_in)
|
545 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
546 |
+
out_ch,
|
547 |
+
kernel_size=3,
|
548 |
+
stride=1,
|
549 |
+
padding=1)
|
550 |
+
|
551 |
+
def forward(self, z):
|
552 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
553 |
+
self.last_z_shape = z.shape
|
554 |
+
|
555 |
+
# print(f'decoder-input={z.shape}')
|
556 |
+
# timestep embedding
|
557 |
+
temb = None
|
558 |
+
|
559 |
+
# z to block_in
|
560 |
+
h = self.conv_in(z)
|
561 |
+
# print(f'decoder-conv in feat={h.shape}')
|
562 |
+
|
563 |
+
# middle
|
564 |
+
h = self.mid.block_1(h, temb)
|
565 |
+
h = self.mid.attn_1(h)
|
566 |
+
h = self.mid.block_2(h, temb)
|
567 |
+
# print(f'decoder-mid feat={h.shape}')
|
568 |
+
|
569 |
+
# upsampling
|
570 |
+
for i_level in reversed(range(self.num_resolutions)):
|
571 |
+
for i_block in range(self.num_res_blocks+1):
|
572 |
+
h = self.up[i_level].block[i_block](h, temb)
|
573 |
+
if len(self.up[i_level].attn) > 0:
|
574 |
+
h = self.up[i_level].attn[i_block](h)
|
575 |
+
# print(f'decoder-up feat={h.shape}')
|
576 |
+
if i_level != 0:
|
577 |
+
h = self.up[i_level].upsample(h)
|
578 |
+
# print(f'decoder-upsample feat={h.shape}')
|
579 |
+
|
580 |
+
# end
|
581 |
+
if self.give_pre_end:
|
582 |
+
return h
|
583 |
+
|
584 |
+
h = self.norm_out(h)
|
585 |
+
h = nonlinearity(h)
|
586 |
+
h = self.conv_out(h)
|
587 |
+
# print(f'decoder-conv_out feat={h.shape}')
|
588 |
+
if self.tanh_out:
|
589 |
+
h = torch.tanh(h)
|
590 |
+
return h
|
591 |
+
|
592 |
+
|
593 |
+
class SimpleDecoder(nn.Module):
|
594 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
595 |
+
super().__init__()
|
596 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
597 |
+
ResnetBlock(in_channels=in_channels,
|
598 |
+
out_channels=2 * in_channels,
|
599 |
+
temb_channels=0, dropout=0.0),
|
600 |
+
ResnetBlock(in_channels=2 * in_channels,
|
601 |
+
out_channels=4 * in_channels,
|
602 |
+
temb_channels=0, dropout=0.0),
|
603 |
+
ResnetBlock(in_channels=4 * in_channels,
|
604 |
+
out_channels=2 * in_channels,
|
605 |
+
temb_channels=0, dropout=0.0),
|
606 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
607 |
+
Upsample(in_channels, with_conv=True)])
|
608 |
+
# end
|
609 |
+
self.norm_out = Normalize(in_channels)
|
610 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
611 |
+
out_channels,
|
612 |
+
kernel_size=3,
|
613 |
+
stride=1,
|
614 |
+
padding=1)
|
615 |
+
|
616 |
+
def forward(self, x):
|
617 |
+
for i, layer in enumerate(self.model):
|
618 |
+
if i in [1,2,3]:
|
619 |
+
x = layer(x, None)
|
620 |
+
else:
|
621 |
+
x = layer(x)
|
622 |
+
|
623 |
+
h = self.norm_out(x)
|
624 |
+
h = nonlinearity(h)
|
625 |
+
x = self.conv_out(h)
|
626 |
+
return x
|
627 |
+
|
628 |
+
|
629 |
+
class UpsampleDecoder(nn.Module):
|
630 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
631 |
+
ch_mult=(2,2), dropout=0.0):
|
632 |
+
super().__init__()
|
633 |
+
# upsampling
|
634 |
+
self.temb_ch = 0
|
635 |
+
self.num_resolutions = len(ch_mult)
|
636 |
+
self.num_res_blocks = num_res_blocks
|
637 |
+
block_in = in_channels
|
638 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
639 |
+
self.res_blocks = nn.ModuleList()
|
640 |
+
self.upsample_blocks = nn.ModuleList()
|
641 |
+
for i_level in range(self.num_resolutions):
|
642 |
+
res_block = []
|
643 |
+
block_out = ch * ch_mult[i_level]
|
644 |
+
for i_block in range(self.num_res_blocks + 1):
|
645 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
646 |
+
out_channels=block_out,
|
647 |
+
temb_channels=self.temb_ch,
|
648 |
+
dropout=dropout))
|
649 |
+
block_in = block_out
|
650 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
651 |
+
if i_level != self.num_resolutions - 1:
|
652 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
653 |
+
curr_res = curr_res * 2
|
654 |
+
|
655 |
+
# end
|
656 |
+
self.norm_out = Normalize(block_in)
|
657 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
658 |
+
out_channels,
|
659 |
+
kernel_size=3,
|
660 |
+
stride=1,
|
661 |
+
padding=1)
|
662 |
+
|
663 |
+
def forward(self, x):
|
664 |
+
# upsampling
|
665 |
+
h = x
|
666 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
667 |
+
for i_block in range(self.num_res_blocks + 1):
|
668 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
669 |
+
if i_level != self.num_resolutions - 1:
|
670 |
+
h = self.upsample_blocks[k](h)
|
671 |
+
h = self.norm_out(h)
|
672 |
+
h = nonlinearity(h)
|
673 |
+
h = self.conv_out(h)
|
674 |
+
return h
|
675 |
+
|
676 |
+
|
677 |
+
class LatentRescaler(nn.Module):
|
678 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
679 |
+
super().__init__()
|
680 |
+
# residual block, interpolate, residual block
|
681 |
+
self.factor = factor
|
682 |
+
self.conv_in = nn.Conv2d(in_channels,
|
683 |
+
mid_channels,
|
684 |
+
kernel_size=3,
|
685 |
+
stride=1,
|
686 |
+
padding=1)
|
687 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
688 |
+
out_channels=mid_channels,
|
689 |
+
temb_channels=0,
|
690 |
+
dropout=0.0) for _ in range(depth)])
|
691 |
+
self.attn = AttnBlock(mid_channels)
|
692 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
693 |
+
out_channels=mid_channels,
|
694 |
+
temb_channels=0,
|
695 |
+
dropout=0.0) for _ in range(depth)])
|
696 |
+
|
697 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
698 |
+
out_channels,
|
699 |
+
kernel_size=1,
|
700 |
+
)
|
701 |
+
|
702 |
+
def forward(self, x):
|
703 |
+
x = self.conv_in(x)
|
704 |
+
for block in self.res_block1:
|
705 |
+
x = block(x, None)
|
706 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
707 |
+
x = self.attn(x)
|
708 |
+
for block in self.res_block2:
|
709 |
+
x = block(x, None)
|
710 |
+
x = self.conv_out(x)
|
711 |
+
return x
|
712 |
+
|
713 |
+
|
714 |
+
class MergedRescaleEncoder(nn.Module):
|
715 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
716 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
717 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
718 |
+
super().__init__()
|
719 |
+
intermediate_chn = ch * ch_mult[-1]
|
720 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
721 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
722 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
723 |
+
out_ch=None)
|
724 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
725 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
726 |
+
|
727 |
+
def forward(self, x):
|
728 |
+
x = self.encoder(x)
|
729 |
+
x = self.rescaler(x)
|
730 |
+
return x
|
731 |
+
|
732 |
+
|
733 |
+
class MergedRescaleDecoder(nn.Module):
|
734 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
735 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
736 |
+
super().__init__()
|
737 |
+
tmp_chn = z_channels*ch_mult[-1]
|
738 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
739 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
740 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
741 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
742 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
743 |
+
|
744 |
+
def forward(self, x):
|
745 |
+
x = self.rescaler(x)
|
746 |
+
x = self.decoder(x)
|
747 |
+
return x
|
748 |
+
|
749 |
+
|
750 |
+
class Upsampler(nn.Module):
|
751 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
752 |
+
super().__init__()
|
753 |
+
assert out_size >= in_size
|
754 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
755 |
+
factor_up = 1.+ (out_size % in_size)
|
756 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
757 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
758 |
+
out_channels=in_channels)
|
759 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
760 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
761 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
762 |
+
|
763 |
+
def forward(self, x):
|
764 |
+
x = self.rescaler(x)
|
765 |
+
x = self.decoder(x)
|
766 |
+
return x
|
767 |
+
|
768 |
+
|
769 |
+
class Resize(nn.Module):
|
770 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
771 |
+
super().__init__()
|
772 |
+
self.with_conv = learned
|
773 |
+
self.mode = mode
|
774 |
+
if self.with_conv:
|
775 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
776 |
+
raise NotImplementedError()
|
777 |
+
assert in_channels is not None
|
778 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
779 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
780 |
+
in_channels,
|
781 |
+
kernel_size=4,
|
782 |
+
stride=2,
|
783 |
+
padding=1)
|
784 |
+
|
785 |
+
def forward(self, x, scale_factor=1.0):
|
786 |
+
if scale_factor==1.0:
|
787 |
+
return x
|
788 |
+
else:
|
789 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
790 |
+
return x
|
791 |
+
|
792 |
+
class FirstStagePostProcessor(nn.Module):
|
793 |
+
|
794 |
+
def __init__(self, ch_mult:list, in_channels,
|
795 |
+
pretrained_model:nn.Module=None,
|
796 |
+
reshape=False,
|
797 |
+
n_channels=None,
|
798 |
+
dropout=0.,
|
799 |
+
pretrained_config=None):
|
800 |
+
super().__init__()
|
801 |
+
if pretrained_config is None:
|
802 |
+
assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
803 |
+
self.pretrained_model = pretrained_model
|
804 |
+
else:
|
805 |
+
assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
806 |
+
self.instantiate_pretrained(pretrained_config)
|
807 |
+
|
808 |
+
self.do_reshape = reshape
|
809 |
+
|
810 |
+
if n_channels is None:
|
811 |
+
n_channels = self.pretrained_model.encoder.ch
|
812 |
+
|
813 |
+
self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
|
814 |
+
self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
|
815 |
+
stride=1,padding=1)
|
816 |
+
|
817 |
+
blocks = []
|
818 |
+
downs = []
|
819 |
+
ch_in = n_channels
|
820 |
+
for m in ch_mult:
|
821 |
+
blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
|
822 |
+
ch_in = m * n_channels
|
823 |
+
downs.append(Downsample(ch_in, with_conv=False))
|
824 |
+
|
825 |
+
self.model = nn.ModuleList(blocks)
|
826 |
+
self.downsampler = nn.ModuleList(downs)
|
827 |
+
|
828 |
+
|
829 |
+
def instantiate_pretrained(self, config):
|
830 |
+
model = instantiate_from_config(config)
|
831 |
+
self.pretrained_model = model.eval()
|
832 |
+
# self.pretrained_model.train = False
|
833 |
+
for param in self.pretrained_model.parameters():
|
834 |
+
param.requires_grad = False
|
835 |
+
|
836 |
+
|
837 |
+
@torch.no_grad()
|
838 |
+
def encode_with_pretrained(self,x):
|
839 |
+
c = self.pretrained_model.encode(x)
|
840 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
841 |
+
c = c.mode()
|
842 |
+
return c
|
843 |
+
|
844 |
+
def forward(self,x):
|
845 |
+
z_fs = self.encode_with_pretrained(x)
|
846 |
+
z = self.proj_norm(z_fs)
|
847 |
+
z = self.proj(z)
|
848 |
+
z = nonlinearity(z)
|
849 |
+
|
850 |
+
for submodel, downmodel in zip(self.model,self.downsampler):
|
851 |
+
z = submodel(z,temb=None)
|
852 |
+
z = downmodel(z)
|
853 |
+
|
854 |
+
if self.do_reshape:
|
855 |
+
z = rearrange(z,'b c h w -> b (h w) c')
|
856 |
+
return z
|
lvdm/modules/networks/openaimodel3d.py
ADDED
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
from abc import abstractmethod
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
from einops import rearrange
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from lvdm.models.utils_diffusion import timestep_embedding
|
8 |
+
from lvdm.common import checkpoint
|
9 |
+
from lvdm.basics import (
|
10 |
+
zero_module,
|
11 |
+
conv_nd,
|
12 |
+
linear,
|
13 |
+
avg_pool_nd,
|
14 |
+
normalization
|
15 |
+
)
|
16 |
+
from lvdm.modules.attention import SpatialTransformer, TemporalTransformer
|
17 |
+
|
18 |
+
|
19 |
+
class TimestepBlock(nn.Module):
|
20 |
+
"""
|
21 |
+
Any module where forward() takes timestep embeddings as a second argument.
|
22 |
+
"""
|
23 |
+
@abstractmethod
|
24 |
+
def forward(self, x, emb):
|
25 |
+
"""
|
26 |
+
Apply the module to `x` given `emb` timestep embeddings.
|
27 |
+
"""
|
28 |
+
|
29 |
+
|
30 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
31 |
+
"""
|
32 |
+
A sequential module that passes timestep embeddings to the children that
|
33 |
+
support it as an extra input.
|
34 |
+
"""
|
35 |
+
|
36 |
+
def forward(self, x, emb, context=None, batch_size=None):
|
37 |
+
for layer in self:
|
38 |
+
if isinstance(layer, TimestepBlock):
|
39 |
+
x = layer(x, emb, batch_size=batch_size)
|
40 |
+
elif isinstance(layer, SpatialTransformer):
|
41 |
+
x = layer(x, context)
|
42 |
+
elif isinstance(layer, TemporalTransformer):
|
43 |
+
x = rearrange(x, '(b f) c h w -> b c f h w', b=batch_size)
|
44 |
+
x = layer(x, context)
|
45 |
+
x = rearrange(x, 'b c f h w -> (b f) c h w')
|
46 |
+
else:
|
47 |
+
x = layer(x)
|
48 |
+
return x
|
49 |
+
|
50 |
+
|
51 |
+
class Downsample(nn.Module):
|
52 |
+
"""
|
53 |
+
A downsampling layer with an optional convolution.
|
54 |
+
:param channels: channels in the inputs and outputs.
|
55 |
+
:param use_conv: a bool determining if a convolution is applied.
|
56 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
57 |
+
downsampling occurs in the inner-two dimensions.
|
58 |
+
"""
|
59 |
+
|
60 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
61 |
+
super().__init__()
|
62 |
+
self.channels = channels
|
63 |
+
self.out_channels = out_channels or channels
|
64 |
+
self.use_conv = use_conv
|
65 |
+
self.dims = dims
|
66 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
67 |
+
if use_conv:
|
68 |
+
self.op = conv_nd(
|
69 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
70 |
+
)
|
71 |
+
else:
|
72 |
+
assert self.channels == self.out_channels
|
73 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
74 |
+
|
75 |
+
def forward(self, x):
|
76 |
+
assert x.shape[1] == self.channels
|
77 |
+
return self.op(x)
|
78 |
+
|
79 |
+
|
80 |
+
class Upsample(nn.Module):
|
81 |
+
"""
|
82 |
+
An upsampling layer with an optional convolution.
|
83 |
+
:param channels: channels in the inputs and outputs.
|
84 |
+
:param use_conv: a bool determining if a convolution is applied.
|
85 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
86 |
+
upsampling occurs in the inner-two dimensions.
|
87 |
+
"""
|
88 |
+
|
89 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
|
90 |
+
super().__init__()
|
91 |
+
self.channels = channels
|
92 |
+
self.out_channels = out_channels or channels
|
93 |
+
self.use_conv = use_conv
|
94 |
+
self.dims = dims
|
95 |
+
if use_conv:
|
96 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
|
97 |
+
|
98 |
+
def forward(self, x):
|
99 |
+
assert x.shape[1] == self.channels
|
100 |
+
if self.dims == 3:
|
101 |
+
x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode='nearest')
|
102 |
+
else:
|
103 |
+
x = F.interpolate(x, scale_factor=2, mode='nearest')
|
104 |
+
if self.use_conv:
|
105 |
+
x = self.conv(x)
|
106 |
+
return x
|
107 |
+
|
108 |
+
|
109 |
+
class ResBlock(TimestepBlock):
|
110 |
+
"""
|
111 |
+
A residual block that can optionally change the number of channels.
|
112 |
+
:param channels: the number of input channels.
|
113 |
+
:param emb_channels: the number of timestep embedding channels.
|
114 |
+
:param dropout: the rate of dropout.
|
115 |
+
:param out_channels: if specified, the number of out channels.
|
116 |
+
:param use_conv: if True and out_channels is specified, use a spatial
|
117 |
+
convolution instead of a smaller 1x1 convolution to change the
|
118 |
+
channels in the skip connection.
|
119 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
120 |
+
:param up: if True, use this block for upsampling.
|
121 |
+
:param down: if True, use this block for downsampling.
|
122 |
+
:param use_temporal_conv: if True, use the temporal convolution.
|
123 |
+
:param use_image_dataset: if True, the temporal parameters will not be optimized.
|
124 |
+
"""
|
125 |
+
|
126 |
+
def __init__(
|
127 |
+
self,
|
128 |
+
channels,
|
129 |
+
emb_channels,
|
130 |
+
dropout,
|
131 |
+
out_channels=None,
|
132 |
+
use_scale_shift_norm=False,
|
133 |
+
dims=2,
|
134 |
+
use_checkpoint=False,
|
135 |
+
use_conv=False,
|
136 |
+
up=False,
|
137 |
+
down=False,
|
138 |
+
use_temporal_conv=False,
|
139 |
+
tempspatial_aware=False
|
140 |
+
):
|
141 |
+
super().__init__()
|
142 |
+
self.channels = channels
|
143 |
+
self.emb_channels = emb_channels
|
144 |
+
self.dropout = dropout
|
145 |
+
self.out_channels = out_channels or channels
|
146 |
+
self.use_conv = use_conv
|
147 |
+
self.use_checkpoint = use_checkpoint
|
148 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
149 |
+
self.use_temporal_conv = use_temporal_conv
|
150 |
+
|
151 |
+
self.in_layers = nn.Sequential(
|
152 |
+
normalization(channels),
|
153 |
+
nn.SiLU(),
|
154 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
155 |
+
)
|
156 |
+
|
157 |
+
self.updown = up or down
|
158 |
+
|
159 |
+
if up:
|
160 |
+
self.h_upd = Upsample(channels, False, dims)
|
161 |
+
self.x_upd = Upsample(channels, False, dims)
|
162 |
+
elif down:
|
163 |
+
self.h_upd = Downsample(channels, False, dims)
|
164 |
+
self.x_upd = Downsample(channels, False, dims)
|
165 |
+
else:
|
166 |
+
self.h_upd = self.x_upd = nn.Identity()
|
167 |
+
|
168 |
+
self.emb_layers = nn.Sequential(
|
169 |
+
nn.SiLU(),
|
170 |
+
nn.Linear(
|
171 |
+
emb_channels,
|
172 |
+
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
|
173 |
+
),
|
174 |
+
)
|
175 |
+
self.out_layers = nn.Sequential(
|
176 |
+
normalization(self.out_channels),
|
177 |
+
nn.SiLU(),
|
178 |
+
nn.Dropout(p=dropout),
|
179 |
+
zero_module(nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)),
|
180 |
+
)
|
181 |
+
|
182 |
+
if self.out_channels == channels:
|
183 |
+
self.skip_connection = nn.Identity()
|
184 |
+
elif use_conv:
|
185 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
|
186 |
+
else:
|
187 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
188 |
+
|
189 |
+
if self.use_temporal_conv:
|
190 |
+
self.temopral_conv = TemporalConvBlock(
|
191 |
+
self.out_channels,
|
192 |
+
self.out_channels,
|
193 |
+
dropout=0.1,
|
194 |
+
spatial_aware=tempspatial_aware
|
195 |
+
)
|
196 |
+
|
197 |
+
def forward(self, x, emb, batch_size=None):
|
198 |
+
"""
|
199 |
+
Apply the block to a Tensor, conditioned on a timestep embedding.
|
200 |
+
:param x: an [N x C x ...] Tensor of features.
|
201 |
+
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
|
202 |
+
:return: an [N x C x ...] Tensor of outputs.
|
203 |
+
"""
|
204 |
+
input_tuple = (x, emb)
|
205 |
+
if batch_size:
|
206 |
+
forward_batchsize = partial(self._forward, batch_size=batch_size)
|
207 |
+
return checkpoint(forward_batchsize, input_tuple, self.parameters(), self.use_checkpoint)
|
208 |
+
return checkpoint(self._forward, input_tuple, self.parameters(), self.use_checkpoint)
|
209 |
+
|
210 |
+
def _forward(self, x, emb, batch_size=None):
|
211 |
+
if self.updown:
|
212 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
213 |
+
h = in_rest(x)
|
214 |
+
h = self.h_upd(h)
|
215 |
+
x = self.x_upd(x)
|
216 |
+
h = in_conv(h)
|
217 |
+
else:
|
218 |
+
h = self.in_layers(x)
|
219 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
220 |
+
while len(emb_out.shape) < len(h.shape):
|
221 |
+
emb_out = emb_out[..., None]
|
222 |
+
if self.use_scale_shift_norm:
|
223 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
224 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
225 |
+
h = out_norm(h) * (1 + scale) + shift
|
226 |
+
h = out_rest(h)
|
227 |
+
else:
|
228 |
+
h = h + emb_out
|
229 |
+
h = self.out_layers(h)
|
230 |
+
h = self.skip_connection(x) + h
|
231 |
+
|
232 |
+
if self.use_temporal_conv and batch_size:
|
233 |
+
h = rearrange(h, '(b t) c h w -> b c t h w', b=batch_size)
|
234 |
+
h = self.temopral_conv(h)
|
235 |
+
h = rearrange(h, 'b c t h w -> (b t) c h w')
|
236 |
+
return h
|
237 |
+
|
238 |
+
|
239 |
+
class TemporalConvBlock(nn.Module):
|
240 |
+
"""
|
241 |
+
Adapted from modelscope: https://github.com/modelscope/modelscope/blob/master/modelscope/models/multi_modal/video_synthesis/unet_sd.py
|
242 |
+
"""
|
243 |
+
def __init__(self, in_channels, out_channels=None, dropout=0.0, spatial_aware=False):
|
244 |
+
super(TemporalConvBlock, self).__init__()
|
245 |
+
if out_channels is None:
|
246 |
+
out_channels = in_channels
|
247 |
+
self.in_channels = in_channels
|
248 |
+
self.out_channels = out_channels
|
249 |
+
th_kernel_shape = (3, 1, 1) if not spatial_aware else (3, 3, 1)
|
250 |
+
th_padding_shape = (1, 0, 0) if not spatial_aware else (1, 1, 0)
|
251 |
+
tw_kernel_shape = (3, 1, 1) if not spatial_aware else (3, 1, 3)
|
252 |
+
tw_padding_shape = (1, 0, 0) if not spatial_aware else (1, 0, 1)
|
253 |
+
|
254 |
+
# conv layers
|
255 |
+
self.conv1 = nn.Sequential(
|
256 |
+
nn.GroupNorm(32, in_channels), nn.SiLU(),
|
257 |
+
nn.Conv3d(in_channels, out_channels, th_kernel_shape, padding=th_padding_shape))
|
258 |
+
self.conv2 = nn.Sequential(
|
259 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
260 |
+
nn.Conv3d(out_channels, in_channels, tw_kernel_shape, padding=tw_padding_shape))
|
261 |
+
self.conv3 = nn.Sequential(
|
262 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
263 |
+
nn.Conv3d(out_channels, in_channels, th_kernel_shape, padding=th_padding_shape))
|
264 |
+
self.conv4 = nn.Sequential(
|
265 |
+
nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
|
266 |
+
nn.Conv3d(out_channels, in_channels, tw_kernel_shape, padding=tw_padding_shape))
|
267 |
+
|
268 |
+
# zero out the last layer params,so the conv block is identity
|
269 |
+
nn.init.zeros_(self.conv4[-1].weight)
|
270 |
+
nn.init.zeros_(self.conv4[-1].bias)
|
271 |
+
|
272 |
+
def forward(self, x):
|
273 |
+
identity = x
|
274 |
+
x = self.conv1(x)
|
275 |
+
x = self.conv2(x)
|
276 |
+
x = self.conv3(x)
|
277 |
+
x = self.conv4(x)
|
278 |
+
|
279 |
+
return identity + x
|
280 |
+
|
281 |
+
class UNetModel(nn.Module):
|
282 |
+
"""
|
283 |
+
The full UNet model with attention and timestep embedding.
|
284 |
+
:param in_channels: in_channels in the input Tensor.
|
285 |
+
:param model_channels: base channel count for the model.
|
286 |
+
:param out_channels: channels in the output Tensor.
|
287 |
+
:param num_res_blocks: number of residual blocks per downsample.
|
288 |
+
:param attention_resolutions: a collection of downsample rates at which
|
289 |
+
attention will take place. May be a set, list, or tuple.
|
290 |
+
For example, if this contains 4, then at 4x downsampling, attention
|
291 |
+
will be used.
|
292 |
+
:param dropout: the dropout probability.
|
293 |
+
:param channel_mult: channel multiplier for each level of the UNet.
|
294 |
+
:param conv_resample: if True, use learned convolutions for upsampling and
|
295 |
+
downsampling.
|
296 |
+
:param dims: determines if the signal is 1D, 2D, or 3D.
|
297 |
+
:param num_classes: if specified (as an int), then this model will be
|
298 |
+
class-conditional with `num_classes` classes.
|
299 |
+
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
|
300 |
+
:param num_heads: the number of attention heads in each attention layer.
|
301 |
+
:param num_heads_channels: if specified, ignore num_heads and instead use
|
302 |
+
a fixed channel width per attention head.
|
303 |
+
:param num_heads_upsample: works with num_heads to set a different number
|
304 |
+
of heads for upsampling. Deprecated.
|
305 |
+
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
|
306 |
+
:param resblock_updown: use residual blocks for up/downsampling.
|
307 |
+
:param use_new_attention_order: use a different attention pattern for potentially
|
308 |
+
increased efficiency.
|
309 |
+
"""
|
310 |
+
|
311 |
+
def __init__(self,
|
312 |
+
in_channels,
|
313 |
+
model_channels,
|
314 |
+
out_channels,
|
315 |
+
num_res_blocks,
|
316 |
+
attention_resolutions,
|
317 |
+
dropout=0.0,
|
318 |
+
channel_mult=(1, 2, 4, 8),
|
319 |
+
conv_resample=True,
|
320 |
+
dims=2,
|
321 |
+
context_dim=None,
|
322 |
+
use_scale_shift_norm=False,
|
323 |
+
resblock_updown=False,
|
324 |
+
num_heads=-1,
|
325 |
+
num_head_channels=-1,
|
326 |
+
transformer_depth=1,
|
327 |
+
use_linear=False,
|
328 |
+
use_checkpoint=False,
|
329 |
+
temporal_conv=False,
|
330 |
+
tempspatial_aware=False,
|
331 |
+
temporal_attention=True,
|
332 |
+
use_relative_position=True,
|
333 |
+
use_causal_attention=False,
|
334 |
+
temporal_length=None,
|
335 |
+
use_fp16=False,
|
336 |
+
addition_attention=False,
|
337 |
+
temporal_selfatt_only=True,
|
338 |
+
image_cross_attention=False,
|
339 |
+
image_cross_attention_scale_learnable=False,
|
340 |
+
default_fs=4,
|
341 |
+
fs_condition=False,
|
342 |
+
):
|
343 |
+
super(UNetModel, self).__init__()
|
344 |
+
if num_heads == -1:
|
345 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
346 |
+
if num_head_channels == -1:
|
347 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
348 |
+
|
349 |
+
self.in_channels = in_channels
|
350 |
+
self.model_channels = model_channels
|
351 |
+
self.out_channels = out_channels
|
352 |
+
self.num_res_blocks = num_res_blocks
|
353 |
+
self.attention_resolutions = attention_resolutions
|
354 |
+
self.dropout = dropout
|
355 |
+
self.channel_mult = channel_mult
|
356 |
+
self.conv_resample = conv_resample
|
357 |
+
self.temporal_attention = temporal_attention
|
358 |
+
time_embed_dim = model_channels * 4
|
359 |
+
self.use_checkpoint = use_checkpoint
|
360 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
361 |
+
temporal_self_att_only = True
|
362 |
+
self.addition_attention = addition_attention
|
363 |
+
self.temporal_length = temporal_length
|
364 |
+
self.image_cross_attention = image_cross_attention
|
365 |
+
self.image_cross_attention_scale_learnable = image_cross_attention_scale_learnable
|
366 |
+
self.default_fs = default_fs
|
367 |
+
self.fs_condition = fs_condition
|
368 |
+
|
369 |
+
## Time embedding blocks
|
370 |
+
self.time_embed = nn.Sequential(
|
371 |
+
linear(model_channels, time_embed_dim),
|
372 |
+
nn.SiLU(),
|
373 |
+
linear(time_embed_dim, time_embed_dim),
|
374 |
+
)
|
375 |
+
if fs_condition:
|
376 |
+
self.fps_embedding = nn.Sequential(
|
377 |
+
linear(model_channels, time_embed_dim),
|
378 |
+
nn.SiLU(),
|
379 |
+
linear(time_embed_dim, time_embed_dim),
|
380 |
+
)
|
381 |
+
nn.init.zeros_(self.fps_embedding[-1].weight)
|
382 |
+
nn.init.zeros_(self.fps_embedding[-1].bias)
|
383 |
+
## Input Block
|
384 |
+
self.input_blocks = nn.ModuleList(
|
385 |
+
[
|
386 |
+
TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))
|
387 |
+
]
|
388 |
+
)
|
389 |
+
if self.addition_attention:
|
390 |
+
self.init_attn=TimestepEmbedSequential(
|
391 |
+
TemporalTransformer(
|
392 |
+
model_channels,
|
393 |
+
n_heads=8,
|
394 |
+
d_head=num_head_channels,
|
395 |
+
depth=transformer_depth,
|
396 |
+
context_dim=context_dim,
|
397 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
|
398 |
+
causal_attention=False, relative_position=use_relative_position,
|
399 |
+
temporal_length=temporal_length))
|
400 |
+
|
401 |
+
input_block_chans = [model_channels]
|
402 |
+
ch = model_channels
|
403 |
+
ds = 1
|
404 |
+
for level, mult in enumerate(channel_mult):
|
405 |
+
for _ in range(num_res_blocks):
|
406 |
+
layers = [
|
407 |
+
ResBlock(ch, time_embed_dim, dropout,
|
408 |
+
out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
|
409 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
410 |
+
use_temporal_conv=temporal_conv
|
411 |
+
)
|
412 |
+
]
|
413 |
+
ch = mult * model_channels
|
414 |
+
if ds in attention_resolutions:
|
415 |
+
if num_head_channels == -1:
|
416 |
+
dim_head = ch // num_heads
|
417 |
+
else:
|
418 |
+
num_heads = ch // num_head_channels
|
419 |
+
dim_head = num_head_channels
|
420 |
+
layers.append(
|
421 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
422 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
423 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False,
|
424 |
+
video_length=temporal_length, image_cross_attention=self.image_cross_attention,
|
425 |
+
image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable,
|
426 |
+
)
|
427 |
+
)
|
428 |
+
if self.temporal_attention:
|
429 |
+
layers.append(
|
430 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
431 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
432 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only,
|
433 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
434 |
+
temporal_length=temporal_length
|
435 |
+
)
|
436 |
+
)
|
437 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
438 |
+
input_block_chans.append(ch)
|
439 |
+
if level != len(channel_mult) - 1:
|
440 |
+
out_ch = ch
|
441 |
+
self.input_blocks.append(
|
442 |
+
TimestepEmbedSequential(
|
443 |
+
ResBlock(ch, time_embed_dim, dropout,
|
444 |
+
out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
|
445 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
446 |
+
down=True
|
447 |
+
)
|
448 |
+
if resblock_updown
|
449 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
450 |
+
)
|
451 |
+
)
|
452 |
+
ch = out_ch
|
453 |
+
input_block_chans.append(ch)
|
454 |
+
ds *= 2
|
455 |
+
|
456 |
+
if num_head_channels == -1:
|
457 |
+
dim_head = ch // num_heads
|
458 |
+
else:
|
459 |
+
num_heads = ch // num_head_channels
|
460 |
+
dim_head = num_head_channels
|
461 |
+
layers = [
|
462 |
+
ResBlock(ch, time_embed_dim, dropout,
|
463 |
+
dims=dims, use_checkpoint=use_checkpoint,
|
464 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
465 |
+
use_temporal_conv=temporal_conv
|
466 |
+
),
|
467 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
468 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
469 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length,
|
470 |
+
image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable
|
471 |
+
)
|
472 |
+
]
|
473 |
+
if self.temporal_attention:
|
474 |
+
layers.append(
|
475 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
476 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
477 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only,
|
478 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
479 |
+
temporal_length=temporal_length
|
480 |
+
)
|
481 |
+
)
|
482 |
+
layers.append(
|
483 |
+
ResBlock(ch, time_embed_dim, dropout,
|
484 |
+
dims=dims, use_checkpoint=use_checkpoint,
|
485 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
486 |
+
use_temporal_conv=temporal_conv
|
487 |
+
)
|
488 |
+
)
|
489 |
+
|
490 |
+
## Middle Block
|
491 |
+
self.middle_block = TimestepEmbedSequential(*layers)
|
492 |
+
|
493 |
+
## Output Block
|
494 |
+
self.output_blocks = nn.ModuleList([])
|
495 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
496 |
+
for i in range(num_res_blocks + 1):
|
497 |
+
ich = input_block_chans.pop()
|
498 |
+
layers = [
|
499 |
+
ResBlock(ch + ich, time_embed_dim, dropout,
|
500 |
+
out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
|
501 |
+
use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
|
502 |
+
use_temporal_conv=temporal_conv
|
503 |
+
)
|
504 |
+
]
|
505 |
+
ch = model_channels * mult
|
506 |
+
if ds in attention_resolutions:
|
507 |
+
if num_head_channels == -1:
|
508 |
+
dim_head = ch // num_heads
|
509 |
+
else:
|
510 |
+
num_heads = ch // num_head_channels
|
511 |
+
dim_head = num_head_channels
|
512 |
+
layers.append(
|
513 |
+
SpatialTransformer(ch, num_heads, dim_head,
|
514 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
515 |
+
use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length,
|
516 |
+
image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable
|
517 |
+
)
|
518 |
+
)
|
519 |
+
if self.temporal_attention:
|
520 |
+
layers.append(
|
521 |
+
TemporalTransformer(ch, num_heads, dim_head,
|
522 |
+
depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
|
523 |
+
use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only,
|
524 |
+
causal_attention=use_causal_attention, relative_position=use_relative_position,
|
525 |
+
temporal_length=temporal_length
|
526 |
+
)
|
527 |
+
)
|
528 |
+
if level and i == num_res_blocks:
|
529 |
+
out_ch = ch
|
530 |
+
layers.append(
|
531 |
+
ResBlock(ch, time_embed_dim, dropout,
|
532 |
+
out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
|
533 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
534 |
+
up=True
|
535 |
+
)
|
536 |
+
if resblock_updown
|
537 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
538 |
+
)
|
539 |
+
ds //= 2
|
540 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
541 |
+
|
542 |
+
self.out = nn.Sequential(
|
543 |
+
normalization(ch),
|
544 |
+
nn.SiLU(),
|
545 |
+
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
|
546 |
+
)
|
547 |
+
|
548 |
+
def forward(self, x, timesteps, context=None, features_adapter=None, fs=None, **kwargs):
|
549 |
+
b,_,t,_,_ = x.shape
|
550 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).type(x.dtype)
|
551 |
+
emb = self.time_embed(t_emb)
|
552 |
+
|
553 |
+
## repeat t times for context [(b t) 77 768] & time embedding
|
554 |
+
## check if we use per-frame image conditioning
|
555 |
+
_, l_context, _ = context.shape
|
556 |
+
if l_context == 77 + t*16: ## !!! HARD CODE here
|
557 |
+
context_text, context_img = context[:,:77,:], context[:,77:,:]
|
558 |
+
context_text = context_text.repeat_interleave(repeats=t, dim=0)
|
559 |
+
context_img = rearrange(context_img, 'b (t l) c -> (b t) l c', t=t)
|
560 |
+
context = torch.cat([context_text, context_img], dim=1)
|
561 |
+
else:
|
562 |
+
context = context.repeat_interleave(repeats=t, dim=0)
|
563 |
+
emb = emb.repeat_interleave(repeats=t, dim=0)
|
564 |
+
|
565 |
+
## always in shape (b t) c h w, except for temporal layer
|
566 |
+
x = rearrange(x, 'b c t h w -> (b t) c h w')
|
567 |
+
|
568 |
+
## combine emb
|
569 |
+
if self.fs_condition:
|
570 |
+
if fs is None:
|
571 |
+
fs = torch.tensor(
|
572 |
+
[self.default_fs] * b, dtype=torch.long, device=x.device)
|
573 |
+
fs_emb = timestep_embedding(fs, self.model_channels, repeat_only=False).type(x.dtype)
|
574 |
+
|
575 |
+
fs_embed = self.fps_embedding(fs_emb)
|
576 |
+
fs_embed = fs_embed.repeat_interleave(repeats=t, dim=0)
|
577 |
+
emb = emb + fs_embed
|
578 |
+
|
579 |
+
h = x.type(self.dtype)
|
580 |
+
adapter_idx = 0
|
581 |
+
hs = []
|
582 |
+
for id, module in enumerate(self.input_blocks):
|
583 |
+
h = module(h, emb, context=context, batch_size=b)
|
584 |
+
if id ==0 and self.addition_attention:
|
585 |
+
h = self.init_attn(h, emb, context=context, batch_size=b)
|
586 |
+
## plug-in adapter features
|
587 |
+
if ((id+1)%3 == 0) and features_adapter is not None:
|
588 |
+
h = h + features_adapter[adapter_idx]
|
589 |
+
adapter_idx += 1
|
590 |
+
hs.append(h)
|
591 |
+
if features_adapter is not None:
|
592 |
+
assert len(features_adapter)==adapter_idx, 'Wrong features_adapter'
|
593 |
+
|
594 |
+
h = self.middle_block(h, emb, context=context, batch_size=b)
|
595 |
+
for module in self.output_blocks:
|
596 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
597 |
+
h = module(h, emb, context=context, batch_size=b)
|
598 |
+
h = h.type(x.dtype)
|
599 |
+
y = self.out(h)
|
600 |
+
|
601 |
+
# reshape back to (b c t h w)
|
602 |
+
y = rearrange(y, '(b t) c h w -> b c t h w', b=b)
|
603 |
+
return y
|
lvdm/modules/x_transformer.py
ADDED
@@ -0,0 +1,639 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers"""
|
2 |
+
from functools import partial
|
3 |
+
from inspect import isfunction
|
4 |
+
from collections import namedtuple
|
5 |
+
from einops import rearrange, repeat
|
6 |
+
import torch
|
7 |
+
from torch import nn, einsum
|
8 |
+
import torch.nn.functional as F
|
9 |
+
|
10 |
+
# constants
|
11 |
+
DEFAULT_DIM_HEAD = 64
|
12 |
+
|
13 |
+
Intermediates = namedtuple('Intermediates', [
|
14 |
+
'pre_softmax_attn',
|
15 |
+
'post_softmax_attn'
|
16 |
+
])
|
17 |
+
|
18 |
+
LayerIntermediates = namedtuple('Intermediates', [
|
19 |
+
'hiddens',
|
20 |
+
'attn_intermediates'
|
21 |
+
])
|
22 |
+
|
23 |
+
|
24 |
+
class AbsolutePositionalEmbedding(nn.Module):
|
25 |
+
def __init__(self, dim, max_seq_len):
|
26 |
+
super().__init__()
|
27 |
+
self.emb = nn.Embedding(max_seq_len, dim)
|
28 |
+
self.init_()
|
29 |
+
|
30 |
+
def init_(self):
|
31 |
+
nn.init.normal_(self.emb.weight, std=0.02)
|
32 |
+
|
33 |
+
def forward(self, x):
|
34 |
+
n = torch.arange(x.shape[1], device=x.device)
|
35 |
+
return self.emb(n)[None, :, :]
|
36 |
+
|
37 |
+
|
38 |
+
class FixedPositionalEmbedding(nn.Module):
|
39 |
+
def __init__(self, dim):
|
40 |
+
super().__init__()
|
41 |
+
inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
|
42 |
+
self.register_buffer('inv_freq', inv_freq)
|
43 |
+
|
44 |
+
def forward(self, x, seq_dim=1, offset=0):
|
45 |
+
t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset
|
46 |
+
sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq)
|
47 |
+
emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1)
|
48 |
+
return emb[None, :, :]
|
49 |
+
|
50 |
+
|
51 |
+
# helpers
|
52 |
+
|
53 |
+
def exists(val):
|
54 |
+
return val is not None
|
55 |
+
|
56 |
+
|
57 |
+
def default(val, d):
|
58 |
+
if exists(val):
|
59 |
+
return val
|
60 |
+
return d() if isfunction(d) else d
|
61 |
+
|
62 |
+
|
63 |
+
def always(val):
|
64 |
+
def inner(*args, **kwargs):
|
65 |
+
return val
|
66 |
+
return inner
|
67 |
+
|
68 |
+
|
69 |
+
def not_equals(val):
|
70 |
+
def inner(x):
|
71 |
+
return x != val
|
72 |
+
return inner
|
73 |
+
|
74 |
+
|
75 |
+
def equals(val):
|
76 |
+
def inner(x):
|
77 |
+
return x == val
|
78 |
+
return inner
|
79 |
+
|
80 |
+
|
81 |
+
def max_neg_value(tensor):
|
82 |
+
return -torch.finfo(tensor.dtype).max
|
83 |
+
|
84 |
+
|
85 |
+
# keyword argument helpers
|
86 |
+
|
87 |
+
def pick_and_pop(keys, d):
|
88 |
+
values = list(map(lambda key: d.pop(key), keys))
|
89 |
+
return dict(zip(keys, values))
|
90 |
+
|
91 |
+
|
92 |
+
def group_dict_by_key(cond, d):
|
93 |
+
return_val = [dict(), dict()]
|
94 |
+
for key in d.keys():
|
95 |
+
match = bool(cond(key))
|
96 |
+
ind = int(not match)
|
97 |
+
return_val[ind][key] = d[key]
|
98 |
+
return (*return_val,)
|
99 |
+
|
100 |
+
|
101 |
+
def string_begins_with(prefix, str):
|
102 |
+
return str.startswith(prefix)
|
103 |
+
|
104 |
+
|
105 |
+
def group_by_key_prefix(prefix, d):
|
106 |
+
return group_dict_by_key(partial(string_begins_with, prefix), d)
|
107 |
+
|
108 |
+
|
109 |
+
def groupby_prefix_and_trim(prefix, d):
|
110 |
+
kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d)
|
111 |
+
kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items())))
|
112 |
+
return kwargs_without_prefix, kwargs
|
113 |
+
|
114 |
+
|
115 |
+
# classes
|
116 |
+
class Scale(nn.Module):
|
117 |
+
def __init__(self, value, fn):
|
118 |
+
super().__init__()
|
119 |
+
self.value = value
|
120 |
+
self.fn = fn
|
121 |
+
|
122 |
+
def forward(self, x, **kwargs):
|
123 |
+
x, *rest = self.fn(x, **kwargs)
|
124 |
+
return (x * self.value, *rest)
|
125 |
+
|
126 |
+
|
127 |
+
class Rezero(nn.Module):
|
128 |
+
def __init__(self, fn):
|
129 |
+
super().__init__()
|
130 |
+
self.fn = fn
|
131 |
+
self.g = nn.Parameter(torch.zeros(1))
|
132 |
+
|
133 |
+
def forward(self, x, **kwargs):
|
134 |
+
x, *rest = self.fn(x, **kwargs)
|
135 |
+
return (x * self.g, *rest)
|
136 |
+
|
137 |
+
|
138 |
+
class ScaleNorm(nn.Module):
|
139 |
+
def __init__(self, dim, eps=1e-5):
|
140 |
+
super().__init__()
|
141 |
+
self.scale = dim ** -0.5
|
142 |
+
self.eps = eps
|
143 |
+
self.g = nn.Parameter(torch.ones(1))
|
144 |
+
|
145 |
+
def forward(self, x):
|
146 |
+
norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
|
147 |
+
return x / norm.clamp(min=self.eps) * self.g
|
148 |
+
|
149 |
+
|
150 |
+
class RMSNorm(nn.Module):
|
151 |
+
def __init__(self, dim, eps=1e-8):
|
152 |
+
super().__init__()
|
153 |
+
self.scale = dim ** -0.5
|
154 |
+
self.eps = eps
|
155 |
+
self.g = nn.Parameter(torch.ones(dim))
|
156 |
+
|
157 |
+
def forward(self, x):
|
158 |
+
norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
|
159 |
+
return x / norm.clamp(min=self.eps) * self.g
|
160 |
+
|
161 |
+
|
162 |
+
class Residual(nn.Module):
|
163 |
+
def forward(self, x, residual):
|
164 |
+
return x + residual
|
165 |
+
|
166 |
+
|
167 |
+
class GRUGating(nn.Module):
|
168 |
+
def __init__(self, dim):
|
169 |
+
super().__init__()
|
170 |
+
self.gru = nn.GRUCell(dim, dim)
|
171 |
+
|
172 |
+
def forward(self, x, residual):
|
173 |
+
gated_output = self.gru(
|
174 |
+
rearrange(x, 'b n d -> (b n) d'),
|
175 |
+
rearrange(residual, 'b n d -> (b n) d')
|
176 |
+
)
|
177 |
+
|
178 |
+
return gated_output.reshape_as(x)
|
179 |
+
|
180 |
+
|
181 |
+
# feedforward
|
182 |
+
|
183 |
+
class GEGLU(nn.Module):
|
184 |
+
def __init__(self, dim_in, dim_out):
|
185 |
+
super().__init__()
|
186 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
187 |
+
|
188 |
+
def forward(self, x):
|
189 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
190 |
+
return x * F.gelu(gate)
|
191 |
+
|
192 |
+
|
193 |
+
class FeedForward(nn.Module):
|
194 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
195 |
+
super().__init__()
|
196 |
+
inner_dim = int(dim * mult)
|
197 |
+
dim_out = default(dim_out, dim)
|
198 |
+
project_in = nn.Sequential(
|
199 |
+
nn.Linear(dim, inner_dim),
|
200 |
+
nn.GELU()
|
201 |
+
) if not glu else GEGLU(dim, inner_dim)
|
202 |
+
|
203 |
+
self.net = nn.Sequential(
|
204 |
+
project_in,
|
205 |
+
nn.Dropout(dropout),
|
206 |
+
nn.Linear(inner_dim, dim_out)
|
207 |
+
)
|
208 |
+
|
209 |
+
def forward(self, x):
|
210 |
+
return self.net(x)
|
211 |
+
|
212 |
+
|
213 |
+
# attention.
|
214 |
+
class Attention(nn.Module):
|
215 |
+
def __init__(
|
216 |
+
self,
|
217 |
+
dim,
|
218 |
+
dim_head=DEFAULT_DIM_HEAD,
|
219 |
+
heads=8,
|
220 |
+
causal=False,
|
221 |
+
mask=None,
|
222 |
+
talking_heads=False,
|
223 |
+
sparse_topk=None,
|
224 |
+
use_entmax15=False,
|
225 |
+
num_mem_kv=0,
|
226 |
+
dropout=0.,
|
227 |
+
on_attn=False
|
228 |
+
):
|
229 |
+
super().__init__()
|
230 |
+
if use_entmax15:
|
231 |
+
raise NotImplementedError("Check out entmax activation instead of softmax activation!")
|
232 |
+
self.scale = dim_head ** -0.5
|
233 |
+
self.heads = heads
|
234 |
+
self.causal = causal
|
235 |
+
self.mask = mask
|
236 |
+
|
237 |
+
inner_dim = dim_head * heads
|
238 |
+
|
239 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
240 |
+
self.to_k = nn.Linear(dim, inner_dim, bias=False)
|
241 |
+
self.to_v = nn.Linear(dim, inner_dim, bias=False)
|
242 |
+
self.dropout = nn.Dropout(dropout)
|
243 |
+
|
244 |
+
# talking heads
|
245 |
+
self.talking_heads = talking_heads
|
246 |
+
if talking_heads:
|
247 |
+
self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads))
|
248 |
+
self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads))
|
249 |
+
|
250 |
+
# explicit topk sparse attention
|
251 |
+
self.sparse_topk = sparse_topk
|
252 |
+
|
253 |
+
# entmax
|
254 |
+
#self.attn_fn = entmax15 if use_entmax15 else F.softmax
|
255 |
+
self.attn_fn = F.softmax
|
256 |
+
|
257 |
+
# add memory key / values
|
258 |
+
self.num_mem_kv = num_mem_kv
|
259 |
+
if num_mem_kv > 0:
|
260 |
+
self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
|
261 |
+
self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
|
262 |
+
|
263 |
+
# attention on attention
|
264 |
+
self.attn_on_attn = on_attn
|
265 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim)
|
266 |
+
|
267 |
+
def forward(
|
268 |
+
self,
|
269 |
+
x,
|
270 |
+
context=None,
|
271 |
+
mask=None,
|
272 |
+
context_mask=None,
|
273 |
+
rel_pos=None,
|
274 |
+
sinusoidal_emb=None,
|
275 |
+
prev_attn=None,
|
276 |
+
mem=None
|
277 |
+
):
|
278 |
+
b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device
|
279 |
+
kv_input = default(context, x)
|
280 |
+
|
281 |
+
q_input = x
|
282 |
+
k_input = kv_input
|
283 |
+
v_input = kv_input
|
284 |
+
|
285 |
+
if exists(mem):
|
286 |
+
k_input = torch.cat((mem, k_input), dim=-2)
|
287 |
+
v_input = torch.cat((mem, v_input), dim=-2)
|
288 |
+
|
289 |
+
if exists(sinusoidal_emb):
|
290 |
+
# in shortformer, the query would start at a position offset depending on the past cached memory
|
291 |
+
offset = k_input.shape[-2] - q_input.shape[-2]
|
292 |
+
q_input = q_input + sinusoidal_emb(q_input, offset=offset)
|
293 |
+
k_input = k_input + sinusoidal_emb(k_input)
|
294 |
+
|
295 |
+
q = self.to_q(q_input)
|
296 |
+
k = self.to_k(k_input)
|
297 |
+
v = self.to_v(v_input)
|
298 |
+
|
299 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v))
|
300 |
+
|
301 |
+
input_mask = None
|
302 |
+
if any(map(exists, (mask, context_mask))):
|
303 |
+
q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool())
|
304 |
+
k_mask = q_mask if not exists(context) else context_mask
|
305 |
+
k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool())
|
306 |
+
q_mask = rearrange(q_mask, 'b i -> b () i ()')
|
307 |
+
k_mask = rearrange(k_mask, 'b j -> b () () j')
|
308 |
+
input_mask = q_mask * k_mask
|
309 |
+
|
310 |
+
if self.num_mem_kv > 0:
|
311 |
+
mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v))
|
312 |
+
k = torch.cat((mem_k, k), dim=-2)
|
313 |
+
v = torch.cat((mem_v, v), dim=-2)
|
314 |
+
if exists(input_mask):
|
315 |
+
input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True)
|
316 |
+
|
317 |
+
dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
|
318 |
+
mask_value = max_neg_value(dots)
|
319 |
+
|
320 |
+
if exists(prev_attn):
|
321 |
+
dots = dots + prev_attn
|
322 |
+
|
323 |
+
pre_softmax_attn = dots
|
324 |
+
|
325 |
+
if talking_heads:
|
326 |
+
dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous()
|
327 |
+
|
328 |
+
if exists(rel_pos):
|
329 |
+
dots = rel_pos(dots)
|
330 |
+
|
331 |
+
if exists(input_mask):
|
332 |
+
dots.masked_fill_(~input_mask, mask_value)
|
333 |
+
del input_mask
|
334 |
+
|
335 |
+
if self.causal:
|
336 |
+
i, j = dots.shape[-2:]
|
337 |
+
r = torch.arange(i, device=device)
|
338 |
+
mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j')
|
339 |
+
mask = F.pad(mask, (j - i, 0), value=False)
|
340 |
+
dots.masked_fill_(mask, mask_value)
|
341 |
+
del mask
|
342 |
+
|
343 |
+
if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]:
|
344 |
+
top, _ = dots.topk(self.sparse_topk, dim=-1)
|
345 |
+
vk = top[..., -1].unsqueeze(-1).expand_as(dots)
|
346 |
+
mask = dots < vk
|
347 |
+
dots.masked_fill_(mask, mask_value)
|
348 |
+
del mask
|
349 |
+
|
350 |
+
attn = self.attn_fn(dots, dim=-1)
|
351 |
+
post_softmax_attn = attn
|
352 |
+
|
353 |
+
attn = self.dropout(attn)
|
354 |
+
|
355 |
+
if talking_heads:
|
356 |
+
attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous()
|
357 |
+
|
358 |
+
out = einsum('b h i j, b h j d -> b h i d', attn, v)
|
359 |
+
out = rearrange(out, 'b h n d -> b n (h d)')
|
360 |
+
|
361 |
+
intermediates = Intermediates(
|
362 |
+
pre_softmax_attn=pre_softmax_attn,
|
363 |
+
post_softmax_attn=post_softmax_attn
|
364 |
+
)
|
365 |
+
|
366 |
+
return self.to_out(out), intermediates
|
367 |
+
|
368 |
+
|
369 |
+
class AttentionLayers(nn.Module):
|
370 |
+
def __init__(
|
371 |
+
self,
|
372 |
+
dim,
|
373 |
+
depth,
|
374 |
+
heads=8,
|
375 |
+
causal=False,
|
376 |
+
cross_attend=False,
|
377 |
+
only_cross=False,
|
378 |
+
use_scalenorm=False,
|
379 |
+
use_rmsnorm=False,
|
380 |
+
use_rezero=False,
|
381 |
+
rel_pos_num_buckets=32,
|
382 |
+
rel_pos_max_distance=128,
|
383 |
+
position_infused_attn=False,
|
384 |
+
custom_layers=None,
|
385 |
+
sandwich_coef=None,
|
386 |
+
par_ratio=None,
|
387 |
+
residual_attn=False,
|
388 |
+
cross_residual_attn=False,
|
389 |
+
macaron=False,
|
390 |
+
pre_norm=True,
|
391 |
+
gate_residual=False,
|
392 |
+
**kwargs
|
393 |
+
):
|
394 |
+
super().__init__()
|
395 |
+
ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs)
|
396 |
+
attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs)
|
397 |
+
|
398 |
+
dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD)
|
399 |
+
|
400 |
+
self.dim = dim
|
401 |
+
self.depth = depth
|
402 |
+
self.layers = nn.ModuleList([])
|
403 |
+
|
404 |
+
self.has_pos_emb = position_infused_attn
|
405 |
+
self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None
|
406 |
+
self.rotary_pos_emb = always(None)
|
407 |
+
|
408 |
+
assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance'
|
409 |
+
self.rel_pos = None
|
410 |
+
|
411 |
+
self.pre_norm = pre_norm
|
412 |
+
|
413 |
+
self.residual_attn = residual_attn
|
414 |
+
self.cross_residual_attn = cross_residual_attn
|
415 |
+
|
416 |
+
norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm
|
417 |
+
norm_class = RMSNorm if use_rmsnorm else norm_class
|
418 |
+
norm_fn = partial(norm_class, dim)
|
419 |
+
|
420 |
+
norm_fn = nn.Identity if use_rezero else norm_fn
|
421 |
+
branch_fn = Rezero if use_rezero else None
|
422 |
+
|
423 |
+
if cross_attend and not only_cross:
|
424 |
+
default_block = ('a', 'c', 'f')
|
425 |
+
elif cross_attend and only_cross:
|
426 |
+
default_block = ('c', 'f')
|
427 |
+
else:
|
428 |
+
default_block = ('a', 'f')
|
429 |
+
|
430 |
+
if macaron:
|
431 |
+
default_block = ('f',) + default_block
|
432 |
+
|
433 |
+
if exists(custom_layers):
|
434 |
+
layer_types = custom_layers
|
435 |
+
elif exists(par_ratio):
|
436 |
+
par_depth = depth * len(default_block)
|
437 |
+
assert 1 < par_ratio <= par_depth, 'par ratio out of range'
|
438 |
+
default_block = tuple(filter(not_equals('f'), default_block))
|
439 |
+
par_attn = par_depth // par_ratio
|
440 |
+
depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper
|
441 |
+
par_width = (depth_cut + depth_cut // par_attn) // par_attn
|
442 |
+
assert len(default_block) <= par_width, 'default block is too large for par_ratio'
|
443 |
+
par_block = default_block + ('f',) * (par_width - len(default_block))
|
444 |
+
par_head = par_block * par_attn
|
445 |
+
layer_types = par_head + ('f',) * (par_depth - len(par_head))
|
446 |
+
elif exists(sandwich_coef):
|
447 |
+
assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth'
|
448 |
+
layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef
|
449 |
+
else:
|
450 |
+
layer_types = default_block * depth
|
451 |
+
|
452 |
+
self.layer_types = layer_types
|
453 |
+
self.num_attn_layers = len(list(filter(equals('a'), layer_types)))
|
454 |
+
|
455 |
+
for layer_type in self.layer_types:
|
456 |
+
if layer_type == 'a':
|
457 |
+
layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs)
|
458 |
+
elif layer_type == 'c':
|
459 |
+
layer = Attention(dim, heads=heads, **attn_kwargs)
|
460 |
+
elif layer_type == 'f':
|
461 |
+
layer = FeedForward(dim, **ff_kwargs)
|
462 |
+
layer = layer if not macaron else Scale(0.5, layer)
|
463 |
+
else:
|
464 |
+
raise Exception(f'invalid layer type {layer_type}')
|
465 |
+
|
466 |
+
if isinstance(layer, Attention) and exists(branch_fn):
|
467 |
+
layer = branch_fn(layer)
|
468 |
+
|
469 |
+
if gate_residual:
|
470 |
+
residual_fn = GRUGating(dim)
|
471 |
+
else:
|
472 |
+
residual_fn = Residual()
|
473 |
+
|
474 |
+
self.layers.append(nn.ModuleList([
|
475 |
+
norm_fn(),
|
476 |
+
layer,
|
477 |
+
residual_fn
|
478 |
+
]))
|
479 |
+
|
480 |
+
def forward(
|
481 |
+
self,
|
482 |
+
x,
|
483 |
+
context=None,
|
484 |
+
mask=None,
|
485 |
+
context_mask=None,
|
486 |
+
mems=None,
|
487 |
+
return_hiddens=False
|
488 |
+
):
|
489 |
+
hiddens = []
|
490 |
+
intermediates = []
|
491 |
+
prev_attn = None
|
492 |
+
prev_cross_attn = None
|
493 |
+
|
494 |
+
mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers
|
495 |
+
|
496 |
+
for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)):
|
497 |
+
is_last = ind == (len(self.layers) - 1)
|
498 |
+
|
499 |
+
if layer_type == 'a':
|
500 |
+
hiddens.append(x)
|
501 |
+
layer_mem = mems.pop(0)
|
502 |
+
|
503 |
+
residual = x
|
504 |
+
|
505 |
+
if self.pre_norm:
|
506 |
+
x = norm(x)
|
507 |
+
|
508 |
+
if layer_type == 'a':
|
509 |
+
out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos,
|
510 |
+
prev_attn=prev_attn, mem=layer_mem)
|
511 |
+
elif layer_type == 'c':
|
512 |
+
out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn)
|
513 |
+
elif layer_type == 'f':
|
514 |
+
out = block(x)
|
515 |
+
|
516 |
+
x = residual_fn(out, residual)
|
517 |
+
|
518 |
+
if layer_type in ('a', 'c'):
|
519 |
+
intermediates.append(inter)
|
520 |
+
|
521 |
+
if layer_type == 'a' and self.residual_attn:
|
522 |
+
prev_attn = inter.pre_softmax_attn
|
523 |
+
elif layer_type == 'c' and self.cross_residual_attn:
|
524 |
+
prev_cross_attn = inter.pre_softmax_attn
|
525 |
+
|
526 |
+
if not self.pre_norm and not is_last:
|
527 |
+
x = norm(x)
|
528 |
+
|
529 |
+
if return_hiddens:
|
530 |
+
intermediates = LayerIntermediates(
|
531 |
+
hiddens=hiddens,
|
532 |
+
attn_intermediates=intermediates
|
533 |
+
)
|
534 |
+
|
535 |
+
return x, intermediates
|
536 |
+
|
537 |
+
return x
|
538 |
+
|
539 |
+
|
540 |
+
class Encoder(AttentionLayers):
|
541 |
+
def __init__(self, **kwargs):
|
542 |
+
assert 'causal' not in kwargs, 'cannot set causality on encoder'
|
543 |
+
super().__init__(causal=False, **kwargs)
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
class TransformerWrapper(nn.Module):
|
548 |
+
def __init__(
|
549 |
+
self,
|
550 |
+
*,
|
551 |
+
num_tokens,
|
552 |
+
max_seq_len,
|
553 |
+
attn_layers,
|
554 |
+
emb_dim=None,
|
555 |
+
max_mem_len=0.,
|
556 |
+
emb_dropout=0.,
|
557 |
+
num_memory_tokens=None,
|
558 |
+
tie_embedding=False,
|
559 |
+
use_pos_emb=True
|
560 |
+
):
|
561 |
+
super().__init__()
|
562 |
+
assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder'
|
563 |
+
|
564 |
+
dim = attn_layers.dim
|
565 |
+
emb_dim = default(emb_dim, dim)
|
566 |
+
|
567 |
+
self.max_seq_len = max_seq_len
|
568 |
+
self.max_mem_len = max_mem_len
|
569 |
+
self.num_tokens = num_tokens
|
570 |
+
|
571 |
+
self.token_emb = nn.Embedding(num_tokens, emb_dim)
|
572 |
+
self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if (
|
573 |
+
use_pos_emb and not attn_layers.has_pos_emb) else always(0)
|
574 |
+
self.emb_dropout = nn.Dropout(emb_dropout)
|
575 |
+
|
576 |
+
self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity()
|
577 |
+
self.attn_layers = attn_layers
|
578 |
+
self.norm = nn.LayerNorm(dim)
|
579 |
+
|
580 |
+
self.init_()
|
581 |
+
|
582 |
+
self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t()
|
583 |
+
|
584 |
+
# memory tokens (like [cls]) from Memory Transformers paper
|
585 |
+
num_memory_tokens = default(num_memory_tokens, 0)
|
586 |
+
self.num_memory_tokens = num_memory_tokens
|
587 |
+
if num_memory_tokens > 0:
|
588 |
+
self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim))
|
589 |
+
|
590 |
+
# let funnel encoder know number of memory tokens, if specified
|
591 |
+
if hasattr(attn_layers, 'num_memory_tokens'):
|
592 |
+
attn_layers.num_memory_tokens = num_memory_tokens
|
593 |
+
|
594 |
+
def init_(self):
|
595 |
+
nn.init.normal_(self.token_emb.weight, std=0.02)
|
596 |
+
|
597 |
+
def forward(
|
598 |
+
self,
|
599 |
+
x,
|
600 |
+
return_embeddings=False,
|
601 |
+
mask=None,
|
602 |
+
return_mems=False,
|
603 |
+
return_attn=False,
|
604 |
+
mems=None,
|
605 |
+
**kwargs
|
606 |
+
):
|
607 |
+
b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens
|
608 |
+
x = self.token_emb(x)
|
609 |
+
x += self.pos_emb(x)
|
610 |
+
x = self.emb_dropout(x)
|
611 |
+
|
612 |
+
x = self.project_emb(x)
|
613 |
+
|
614 |
+
if num_mem > 0:
|
615 |
+
mem = repeat(self.memory_tokens, 'n d -> b n d', b=b)
|
616 |
+
x = torch.cat((mem, x), dim=1)
|
617 |
+
|
618 |
+
# auto-handle masking after appending memory tokens
|
619 |
+
if exists(mask):
|
620 |
+
mask = F.pad(mask, (num_mem, 0), value=True)
|
621 |
+
|
622 |
+
x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs)
|
623 |
+
x = self.norm(x)
|
624 |
+
|
625 |
+
mem, x = x[:, :num_mem], x[:, num_mem:]
|
626 |
+
|
627 |
+
out = self.to_logits(x) if not return_embeddings else x
|
628 |
+
|
629 |
+
if return_mems:
|
630 |
+
hiddens = intermediates.hiddens
|
631 |
+
new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens
|
632 |
+
new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems))
|
633 |
+
return out, new_mems
|
634 |
+
|
635 |
+
if return_attn:
|
636 |
+
attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates))
|
637 |
+
return out, attn_maps
|
638 |
+
|
639 |
+
return out
|
main/callbacks.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import logging
|
4 |
+
mainlogger = logging.getLogger('mainlogger')
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torchvision
|
8 |
+
import pytorch_lightning as pl
|
9 |
+
from pytorch_lightning.callbacks import Callback
|
10 |
+
from pytorch_lightning.utilities import rank_zero_only
|
11 |
+
from pytorch_lightning.utilities import rank_zero_info
|
12 |
+
from utils.save_video import log_local, prepare_to_log
|
13 |
+
|
14 |
+
|
15 |
+
class ImageLogger(Callback):
|
16 |
+
def __init__(self, batch_frequency, max_images=8, clamp=True, rescale=True, save_dir=None, \
|
17 |
+
to_local=False, log_images_kwargs=None):
|
18 |
+
super().__init__()
|
19 |
+
self.rescale = rescale
|
20 |
+
self.batch_freq = batch_frequency
|
21 |
+
self.max_images = max_images
|
22 |
+
self.to_local = to_local
|
23 |
+
self.clamp = clamp
|
24 |
+
self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
|
25 |
+
if self.to_local:
|
26 |
+
## default save dir
|
27 |
+
self.save_dir = os.path.join(save_dir, "images")
|
28 |
+
os.makedirs(os.path.join(self.save_dir, "train"), exist_ok=True)
|
29 |
+
os.makedirs(os.path.join(self.save_dir, "val"), exist_ok=True)
|
30 |
+
|
31 |
+
def log_to_tensorboard(self, pl_module, batch_logs, filename, split, save_fps=8):
|
32 |
+
""" log images and videos to tensorboard """
|
33 |
+
global_step = pl_module.global_step
|
34 |
+
for key in batch_logs:
|
35 |
+
value = batch_logs[key]
|
36 |
+
tag = "gs%d-%s/%s-%s"%(global_step, split, filename, key)
|
37 |
+
if isinstance(value, list) and isinstance(value[0], str):
|
38 |
+
captions = ' |------| '.join(value)
|
39 |
+
pl_module.logger.experiment.add_text(tag, captions, global_step=global_step)
|
40 |
+
elif isinstance(value, torch.Tensor) and value.dim() == 5:
|
41 |
+
video = value
|
42 |
+
n = video.shape[0]
|
43 |
+
video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
|
44 |
+
frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n), padding=0) for framesheet in video] #[3, n*h, 1*w]
|
45 |
+
grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
|
46 |
+
grid = (grid + 1.0) / 2.0
|
47 |
+
grid = grid.unsqueeze(dim=0)
|
48 |
+
pl_module.logger.experiment.add_video(tag, grid, fps=save_fps, global_step=global_step)
|
49 |
+
elif isinstance(value, torch.Tensor) and value.dim() == 4:
|
50 |
+
img = value
|
51 |
+
grid = torchvision.utils.make_grid(img, nrow=int(n), padding=0)
|
52 |
+
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
53 |
+
pl_module.logger.experiment.add_image(tag, grid, global_step=global_step)
|
54 |
+
else:
|
55 |
+
pass
|
56 |
+
|
57 |
+
@rank_zero_only
|
58 |
+
def log_batch_imgs(self, pl_module, batch, batch_idx, split="train"):
|
59 |
+
""" generate images, then save and log to tensorboard """
|
60 |
+
skip_freq = self.batch_freq if split == "train" else 5
|
61 |
+
if (batch_idx+1) % skip_freq == 0:
|
62 |
+
is_train = pl_module.training
|
63 |
+
if is_train:
|
64 |
+
pl_module.eval()
|
65 |
+
torch.cuda.empty_cache()
|
66 |
+
with torch.no_grad():
|
67 |
+
log_func = pl_module.log_images
|
68 |
+
batch_logs = log_func(batch, split=split, **self.log_images_kwargs)
|
69 |
+
|
70 |
+
## process: move to CPU and clamp
|
71 |
+
batch_logs = prepare_to_log(batch_logs, self.max_images, self.clamp)
|
72 |
+
torch.cuda.empty_cache()
|
73 |
+
|
74 |
+
filename = "ep{}_idx{}_rank{}".format(
|
75 |
+
pl_module.current_epoch,
|
76 |
+
batch_idx,
|
77 |
+
pl_module.global_rank)
|
78 |
+
if self.to_local:
|
79 |
+
mainlogger.info("Log [%s] batch <%s> to local ..."%(split, filename))
|
80 |
+
filename = "gs{}_".format(pl_module.global_step) + filename
|
81 |
+
log_local(batch_logs, os.path.join(self.save_dir, split), filename, save_fps=10)
|
82 |
+
else:
|
83 |
+
mainlogger.info("Log [%s] batch <%s> to tensorboard ..."%(split, filename))
|
84 |
+
self.log_to_tensorboard(pl_module, batch_logs, filename, split, save_fps=10)
|
85 |
+
mainlogger.info('Finish!')
|
86 |
+
|
87 |
+
if is_train:
|
88 |
+
pl_module.train()
|
89 |
+
|
90 |
+
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None):
|
91 |
+
if self.batch_freq != -1 and pl_module.logdir:
|
92 |
+
self.log_batch_imgs(pl_module, batch, batch_idx, split="train")
|
93 |
+
|
94 |
+
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None):
|
95 |
+
## different with validation_step() that saving the whole validation set and only keep the latest,
|
96 |
+
## it records the performance of every validation (without overwritten) by only keep a subset
|
97 |
+
if self.batch_freq != -1 and pl_module.logdir:
|
98 |
+
self.log_batch_imgs(pl_module, batch, batch_idx, split="val")
|
99 |
+
if hasattr(pl_module, 'calibrate_grad_norm'):
|
100 |
+
if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
|
101 |
+
self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
|
102 |
+
|
103 |
+
|
104 |
+
class CUDACallback(Callback):
|
105 |
+
# see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
|
106 |
+
def on_train_epoch_start(self, trainer, pl_module):
|
107 |
+
# Reset the memory use counter
|
108 |
+
# lightning update
|
109 |
+
if int((pl.__version__).split('.')[1])>=7:
|
110 |
+
gpu_index = trainer.strategy.root_device.index
|
111 |
+
else:
|
112 |
+
gpu_index = trainer.root_gpu
|
113 |
+
torch.cuda.reset_peak_memory_stats(gpu_index)
|
114 |
+
torch.cuda.synchronize(gpu_index)
|
115 |
+
self.start_time = time.time()
|
116 |
+
|
117 |
+
def on_train_epoch_end(self, trainer, pl_module):
|
118 |
+
if int((pl.__version__).split('.')[1])>=7:
|
119 |
+
gpu_index = trainer.strategy.root_device.index
|
120 |
+
else:
|
121 |
+
gpu_index = trainer.root_gpu
|
122 |
+
torch.cuda.synchronize(gpu_index)
|
123 |
+
max_memory = torch.cuda.max_memory_allocated(gpu_index) / 2 ** 20
|
124 |
+
epoch_time = time.time() - self.start_time
|
125 |
+
|
126 |
+
try:
|
127 |
+
max_memory = trainer.training_type_plugin.reduce(max_memory)
|
128 |
+
epoch_time = trainer.training_type_plugin.reduce(epoch_time)
|
129 |
+
|
130 |
+
rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
|
131 |
+
rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
|
132 |
+
except AttributeError:
|
133 |
+
pass
|
main/trainer.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse, os, sys, datetime
|
2 |
+
from omegaconf import OmegaConf
|
3 |
+
from transformers import logging as transf_logging
|
4 |
+
import pytorch_lightning as pl
|
5 |
+
from pytorch_lightning import seed_everything
|
6 |
+
from pytorch_lightning.trainer import Trainer
|
7 |
+
import torch
|
8 |
+
sys.path.insert(1, os.path.join(sys.path[0], '..'))
|
9 |
+
from utils.utils import instantiate_from_config
|
10 |
+
from utils_train import get_trainer_callbacks, get_trainer_logger, get_trainer_strategy
|
11 |
+
from utils_train import set_logger, init_workspace, load_checkpoints
|
12 |
+
|
13 |
+
|
14 |
+
def get_parser(**parser_kwargs):
|
15 |
+
parser = argparse.ArgumentParser(**parser_kwargs)
|
16 |
+
parser.add_argument("--seed", "-s", type=int, default=20230211, help="seed for seed_everything")
|
17 |
+
parser.add_argument("--name", "-n", type=str, default="", help="experiment name, as saving folder")
|
18 |
+
|
19 |
+
parser.add_argument("--base", "-b", nargs="*", metavar="base_config.yaml", help="paths to base configs. Loaded from left-to-right. "
|
20 |
+
"Parameters can be overwritten or added with command-line options of the form `--key value`.", default=list())
|
21 |
+
|
22 |
+
parser.add_argument("--train", "-t", action='store_true', default=False, help='train')
|
23 |
+
parser.add_argument("--val", "-v", action='store_true', default=False, help='val')
|
24 |
+
parser.add_argument("--test", action='store_true', default=False, help='test')
|
25 |
+
|
26 |
+
parser.add_argument("--logdir", "-l", type=str, default="logs", help="directory for logging dat shit")
|
27 |
+
parser.add_argument("--auto_resume", action='store_true', default=False, help="resume from full-info checkpoint")
|
28 |
+
parser.add_argument("--auto_resume_weight_only", action='store_true', default=False, help="resume from weight-only checkpoint")
|
29 |
+
parser.add_argument("--debug", "-d", action='store_true', default=False, help="enable post-mortem debugging")
|
30 |
+
|
31 |
+
return parser
|
32 |
+
|
33 |
+
def get_nondefault_trainer_args(args):
|
34 |
+
parser = argparse.ArgumentParser()
|
35 |
+
parser = Trainer.add_argparse_args(parser)
|
36 |
+
default_trainer_args = parser.parse_args([])
|
37 |
+
return sorted(k for k in vars(default_trainer_args) if getattr(args, k) != getattr(default_trainer_args, k))
|
38 |
+
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
|
42 |
+
local_rank = int(os.environ.get('LOCAL_RANK'))
|
43 |
+
global_rank = int(os.environ.get('RANK'))
|
44 |
+
num_rank = int(os.environ.get('WORLD_SIZE'))
|
45 |
+
|
46 |
+
parser = get_parser()
|
47 |
+
## Extends existing argparse by default Trainer attributes
|
48 |
+
parser = Trainer.add_argparse_args(parser)
|
49 |
+
args, unknown = parser.parse_known_args()
|
50 |
+
## disable transformer warning
|
51 |
+
transf_logging.set_verbosity_error()
|
52 |
+
seed_everything(args.seed)
|
53 |
+
|
54 |
+
## yaml configs: "model" | "data" | "lightning"
|
55 |
+
configs = [OmegaConf.load(cfg) for cfg in args.base]
|
56 |
+
cli = OmegaConf.from_dotlist(unknown)
|
57 |
+
config = OmegaConf.merge(*configs, cli)
|
58 |
+
lightning_config = config.pop("lightning", OmegaConf.create())
|
59 |
+
trainer_config = lightning_config.get("trainer", OmegaConf.create())
|
60 |
+
|
61 |
+
## setup workspace directories
|
62 |
+
workdir, ckptdir, cfgdir, loginfo = init_workspace(args.name, args.logdir, config, lightning_config, global_rank)
|
63 |
+
logger = set_logger(logfile=os.path.join(loginfo, 'log_%d:%s.txt'%(global_rank, now)))
|
64 |
+
logger.info("@lightning version: %s [>=1.8 required]"%(pl.__version__))
|
65 |
+
|
66 |
+
## MODEL CONFIG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
|
67 |
+
logger.info("***** Configing Model *****")
|
68 |
+
config.model.params.logdir = workdir
|
69 |
+
model = instantiate_from_config(config.model)
|
70 |
+
|
71 |
+
## load checkpoints
|
72 |
+
model = load_checkpoints(model, config.model)
|
73 |
+
|
74 |
+
## register_schedule again to make ZTSNR work
|
75 |
+
if model.rescale_betas_zero_snr:
|
76 |
+
model.register_schedule(given_betas=model.given_betas, beta_schedule=model.beta_schedule, timesteps=model.timesteps,
|
77 |
+
linear_start=model.linear_start, linear_end=model.linear_end, cosine_s=model.cosine_s)
|
78 |
+
|
79 |
+
## update trainer config
|
80 |
+
for k in get_nondefault_trainer_args(args):
|
81 |
+
trainer_config[k] = getattr(args, k)
|
82 |
+
|
83 |
+
num_nodes = trainer_config.num_nodes
|
84 |
+
ngpu_per_node = trainer_config.devices
|
85 |
+
logger.info(f"Running on {num_rank}={num_nodes}x{ngpu_per_node} GPUs")
|
86 |
+
|
87 |
+
## setup learning rate
|
88 |
+
base_lr = config.model.base_learning_rate
|
89 |
+
bs = config.data.params.batch_size
|
90 |
+
if getattr(config.model, 'scale_lr', True):
|
91 |
+
model.learning_rate = num_rank * bs * base_lr
|
92 |
+
else:
|
93 |
+
model.learning_rate = base_lr
|
94 |
+
|
95 |
+
|
96 |
+
## DATA CONFIG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
|
97 |
+
logger.info("***** Configing Data *****")
|
98 |
+
data = instantiate_from_config(config.data)
|
99 |
+
data.setup()
|
100 |
+
for k in data.datasets:
|
101 |
+
logger.info(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
|
102 |
+
|
103 |
+
|
104 |
+
## TRAINER CONFIG >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
|
105 |
+
logger.info("***** Configing Trainer *****")
|
106 |
+
if "accelerator" not in trainer_config:
|
107 |
+
trainer_config["accelerator"] = "gpu"
|
108 |
+
|
109 |
+
## setup trainer args: pl-logger and callbacks
|
110 |
+
trainer_kwargs = dict()
|
111 |
+
trainer_kwargs["num_sanity_val_steps"] = 0
|
112 |
+
logger_cfg = get_trainer_logger(lightning_config, workdir, args.debug)
|
113 |
+
trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
|
114 |
+
|
115 |
+
## setup callbacks
|
116 |
+
callbacks_cfg = get_trainer_callbacks(lightning_config, config, workdir, ckptdir, logger)
|
117 |
+
trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
|
118 |
+
strategy_cfg = get_trainer_strategy(lightning_config)
|
119 |
+
trainer_kwargs["strategy"] = strategy_cfg if type(strategy_cfg) == str else instantiate_from_config(strategy_cfg)
|
120 |
+
trainer_kwargs['precision'] = lightning_config.get('precision', 32)
|
121 |
+
trainer_kwargs["sync_batchnorm"] = False
|
122 |
+
|
123 |
+
## trainer config: others
|
124 |
+
|
125 |
+
trainer_args = argparse.Namespace(**trainer_config)
|
126 |
+
trainer = Trainer.from_argparse_args(trainer_args, **trainer_kwargs)
|
127 |
+
|
128 |
+
## allow checkpointing via USR1
|
129 |
+
def melk(*args, **kwargs):
|
130 |
+
## run all checkpoint hooks
|
131 |
+
if trainer.global_rank == 0:
|
132 |
+
print("Summoning checkpoint.")
|
133 |
+
ckpt_path = os.path.join(ckptdir, "last_summoning.ckpt")
|
134 |
+
trainer.save_checkpoint(ckpt_path)
|
135 |
+
|
136 |
+
def divein(*args, **kwargs):
|
137 |
+
if trainer.global_rank == 0:
|
138 |
+
import pudb;
|
139 |
+
pudb.set_trace()
|
140 |
+
|
141 |
+
import signal
|
142 |
+
signal.signal(signal.SIGUSR1, melk)
|
143 |
+
signal.signal(signal.SIGUSR2, divein)
|
144 |
+
|
145 |
+
## Running LOOP >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
|
146 |
+
logger.info("***** Running the Loop *****")
|
147 |
+
if args.train:
|
148 |
+
try:
|
149 |
+
if "strategy" in lightning_config and lightning_config['strategy'].startswith('deepspeed'):
|
150 |
+
logger.info("<Training in DeepSpeed Mode>")
|
151 |
+
## deepspeed
|
152 |
+
if trainer_kwargs['precision'] == 16:
|
153 |
+
with torch.cuda.amp.autocast():
|
154 |
+
trainer.fit(model, data)
|
155 |
+
else:
|
156 |
+
trainer.fit(model, data)
|
157 |
+
else:
|
158 |
+
logger.info("<Training in DDPSharded Mode>") ## this is default
|
159 |
+
## ddpsharded
|
160 |
+
trainer.fit(model, data)
|
161 |
+
except Exception:
|
162 |
+
#melk()
|
163 |
+
raise
|
164 |
+
|
165 |
+
# if args.val:
|
166 |
+
# trainer.validate(model, data)
|
167 |
+
# if args.test or not trainer.interrupted:
|
168 |
+
# trainer.test(model, data)
|
main/utils_data.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import pytorch_lightning as pl
|
6 |
+
from torch.utils.data import DataLoader, Dataset
|
7 |
+
|
8 |
+
import os, sys
|
9 |
+
os.chdir(sys.path[0])
|
10 |
+
sys.path.append("..")
|
11 |
+
from lvdm.data.base import Txt2ImgIterableBaseDataset
|
12 |
+
from utils.utils import instantiate_from_config
|
13 |
+
|
14 |
+
|
15 |
+
def worker_init_fn(_):
|
16 |
+
worker_info = torch.utils.data.get_worker_info()
|
17 |
+
|
18 |
+
dataset = worker_info.dataset
|
19 |
+
worker_id = worker_info.id
|
20 |
+
|
21 |
+
if isinstance(dataset, Txt2ImgIterableBaseDataset):
|
22 |
+
split_size = dataset.num_records // worker_info.num_workers
|
23 |
+
# reset num_records to the true number to retain reliable length information
|
24 |
+
dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
|
25 |
+
current_id = np.random.choice(len(np.random.get_state()[1]), 1)
|
26 |
+
return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
|
27 |
+
else:
|
28 |
+
return np.random.seed(np.random.get_state()[1][0] + worker_id)
|
29 |
+
|
30 |
+
|
31 |
+
class WrappedDataset(Dataset):
|
32 |
+
"""Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
|
33 |
+
|
34 |
+
def __init__(self, dataset):
|
35 |
+
self.data = dataset
|
36 |
+
|
37 |
+
def __len__(self):
|
38 |
+
return len(self.data)
|
39 |
+
|
40 |
+
def __getitem__(self, idx):
|
41 |
+
return self.data[idx]
|
42 |
+
|
43 |
+
|
44 |
+
class DataModuleFromConfig(pl.LightningDataModule):
|
45 |
+
def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
|
46 |
+
wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
|
47 |
+
shuffle_val_dataloader=False, train_img=None,
|
48 |
+
test_max_n_samples=None):
|
49 |
+
super().__init__()
|
50 |
+
self.batch_size = batch_size
|
51 |
+
self.dataset_configs = dict()
|
52 |
+
self.num_workers = num_workers if num_workers is not None else batch_size * 2
|
53 |
+
self.use_worker_init_fn = use_worker_init_fn
|
54 |
+
if train is not None:
|
55 |
+
self.dataset_configs["train"] = train
|
56 |
+
self.train_dataloader = self._train_dataloader
|
57 |
+
if validation is not None:
|
58 |
+
self.dataset_configs["validation"] = validation
|
59 |
+
self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
|
60 |
+
if test is not None:
|
61 |
+
self.dataset_configs["test"] = test
|
62 |
+
self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
|
63 |
+
if predict is not None:
|
64 |
+
self.dataset_configs["predict"] = predict
|
65 |
+
self.predict_dataloader = self._predict_dataloader
|
66 |
+
|
67 |
+
self.img_loader = None
|
68 |
+
self.wrap = wrap
|
69 |
+
self.test_max_n_samples = test_max_n_samples
|
70 |
+
self.collate_fn = None
|
71 |
+
|
72 |
+
def prepare_data(self):
|
73 |
+
pass
|
74 |
+
|
75 |
+
def setup(self, stage=None):
|
76 |
+
self.datasets = dict((k, instantiate_from_config(self.dataset_configs[k])) for k in self.dataset_configs)
|
77 |
+
if self.wrap:
|
78 |
+
for k in self.datasets:
|
79 |
+
self.datasets[k] = WrappedDataset(self.datasets[k])
|
80 |
+
|
81 |
+
def _train_dataloader(self):
|
82 |
+
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
83 |
+
if is_iterable_dataset or self.use_worker_init_fn:
|
84 |
+
init_fn = worker_init_fn
|
85 |
+
else:
|
86 |
+
init_fn = None
|
87 |
+
loader = DataLoader(self.datasets["train"], batch_size=self.batch_size,
|
88 |
+
num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
|
89 |
+
worker_init_fn=init_fn, collate_fn=self.collate_fn,
|
90 |
+
)
|
91 |
+
return loader
|
92 |
+
|
93 |
+
def _val_dataloader(self, shuffle=False):
|
94 |
+
if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
95 |
+
init_fn = worker_init_fn
|
96 |
+
else:
|
97 |
+
init_fn = None
|
98 |
+
return DataLoader(self.datasets["validation"],
|
99 |
+
batch_size=self.batch_size,
|
100 |
+
num_workers=self.num_workers,
|
101 |
+
worker_init_fn=init_fn,
|
102 |
+
shuffle=shuffle,
|
103 |
+
collate_fn=self.collate_fn,
|
104 |
+
)
|
105 |
+
|
106 |
+
def _test_dataloader(self, shuffle=False):
|
107 |
+
try:
|
108 |
+
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
109 |
+
except:
|
110 |
+
is_iterable_dataset = isinstance(self.datasets['test'], Txt2ImgIterableBaseDataset)
|
111 |
+
|
112 |
+
if is_iterable_dataset or self.use_worker_init_fn:
|
113 |
+
init_fn = worker_init_fn
|
114 |
+
else:
|
115 |
+
init_fn = None
|
116 |
+
|
117 |
+
# do not shuffle dataloader for iterable dataset
|
118 |
+
shuffle = shuffle and (not is_iterable_dataset)
|
119 |
+
if self.test_max_n_samples is not None:
|
120 |
+
dataset = torch.utils.data.Subset(self.datasets["test"], list(range(self.test_max_n_samples)))
|
121 |
+
else:
|
122 |
+
dataset = self.datasets["test"]
|
123 |
+
return DataLoader(dataset, batch_size=self.batch_size,
|
124 |
+
num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle,
|
125 |
+
collate_fn=self.collate_fn,
|
126 |
+
)
|
127 |
+
|
128 |
+
def _predict_dataloader(self, shuffle=False):
|
129 |
+
if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
130 |
+
init_fn = worker_init_fn
|
131 |
+
else:
|
132 |
+
init_fn = None
|
133 |
+
return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
|
134 |
+
num_workers=self.num_workers, worker_init_fn=init_fn,
|
135 |
+
collate_fn=self.collate_fn,
|
136 |
+
)
|
main/utils_train.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, re
|
2 |
+
from omegaconf import OmegaConf
|
3 |
+
import logging
|
4 |
+
mainlogger = logging.getLogger('mainlogger')
|
5 |
+
|
6 |
+
import torch
|
7 |
+
from collections import OrderedDict
|
8 |
+
|
9 |
+
def init_workspace(name, logdir, model_config, lightning_config, rank=0):
|
10 |
+
workdir = os.path.join(logdir, name)
|
11 |
+
ckptdir = os.path.join(workdir, "checkpoints")
|
12 |
+
cfgdir = os.path.join(workdir, "configs")
|
13 |
+
loginfo = os.path.join(workdir, "loginfo")
|
14 |
+
|
15 |
+
# Create logdirs and save configs (all ranks will do to avoid missing directory error if rank:0 is slower)
|
16 |
+
os.makedirs(workdir, exist_ok=True)
|
17 |
+
os.makedirs(ckptdir, exist_ok=True)
|
18 |
+
os.makedirs(cfgdir, exist_ok=True)
|
19 |
+
os.makedirs(loginfo, exist_ok=True)
|
20 |
+
|
21 |
+
if rank == 0:
|
22 |
+
if "callbacks" in lightning_config and 'metrics_over_trainsteps_checkpoint' in lightning_config.callbacks:
|
23 |
+
os.makedirs(os.path.join(ckptdir, 'trainstep_checkpoints'), exist_ok=True)
|
24 |
+
OmegaConf.save(model_config, os.path.join(cfgdir, "model.yaml"))
|
25 |
+
OmegaConf.save(OmegaConf.create({"lightning": lightning_config}), os.path.join(cfgdir, "lightning.yaml"))
|
26 |
+
return workdir, ckptdir, cfgdir, loginfo
|
27 |
+
|
28 |
+
def check_config_attribute(config, name):
|
29 |
+
if name in config:
|
30 |
+
value = getattr(config, name)
|
31 |
+
return value
|
32 |
+
else:
|
33 |
+
return None
|
34 |
+
|
35 |
+
def get_trainer_callbacks(lightning_config, config, logdir, ckptdir, logger):
|
36 |
+
default_callbacks_cfg = {
|
37 |
+
"model_checkpoint": {
|
38 |
+
"target": "pytorch_lightning.callbacks.ModelCheckpoint",
|
39 |
+
"params": {
|
40 |
+
"dirpath": ckptdir,
|
41 |
+
"filename": "{epoch}",
|
42 |
+
"verbose": True,
|
43 |
+
"save_last": False,
|
44 |
+
}
|
45 |
+
},
|
46 |
+
"batch_logger": {
|
47 |
+
"target": "callbacks.ImageLogger",
|
48 |
+
"params": {
|
49 |
+
"save_dir": logdir,
|
50 |
+
"batch_frequency": 1000,
|
51 |
+
"max_images": 4,
|
52 |
+
"clamp": True,
|
53 |
+
}
|
54 |
+
},
|
55 |
+
"learning_rate_logger": {
|
56 |
+
"target": "pytorch_lightning.callbacks.LearningRateMonitor",
|
57 |
+
"params": {
|
58 |
+
"logging_interval": "step",
|
59 |
+
"log_momentum": False
|
60 |
+
}
|
61 |
+
},
|
62 |
+
"cuda_callback": {
|
63 |
+
"target": "callbacks.CUDACallback"
|
64 |
+
},
|
65 |
+
}
|
66 |
+
|
67 |
+
## optional setting for saving checkpoints
|
68 |
+
monitor_metric = check_config_attribute(config.model.params, "monitor")
|
69 |
+
if monitor_metric is not None:
|
70 |
+
mainlogger.info(f"Monitoring {monitor_metric} as checkpoint metric.")
|
71 |
+
default_callbacks_cfg["model_checkpoint"]["params"]["monitor"] = monitor_metric
|
72 |
+
default_callbacks_cfg["model_checkpoint"]["params"]["save_top_k"] = 3
|
73 |
+
default_callbacks_cfg["model_checkpoint"]["params"]["mode"] = "min"
|
74 |
+
|
75 |
+
if 'metrics_over_trainsteps_checkpoint' in lightning_config.callbacks:
|
76 |
+
mainlogger.info('Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
|
77 |
+
default_metrics_over_trainsteps_ckpt_dict = {
|
78 |
+
'metrics_over_trainsteps_checkpoint': {"target": 'pytorch_lightning.callbacks.ModelCheckpoint',
|
79 |
+
'params': {
|
80 |
+
"dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
|
81 |
+
"filename": "{epoch}-{step}",
|
82 |
+
"verbose": True,
|
83 |
+
'save_top_k': -1,
|
84 |
+
'every_n_train_steps': 10000,
|
85 |
+
'save_weights_only': True
|
86 |
+
}
|
87 |
+
}
|
88 |
+
}
|
89 |
+
default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
|
90 |
+
|
91 |
+
if "callbacks" in lightning_config:
|
92 |
+
callbacks_cfg = lightning_config.callbacks
|
93 |
+
else:
|
94 |
+
callbacks_cfg = OmegaConf.create()
|
95 |
+
callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
|
96 |
+
|
97 |
+
return callbacks_cfg
|
98 |
+
|
99 |
+
def get_trainer_logger(lightning_config, logdir, on_debug):
|
100 |
+
default_logger_cfgs = {
|
101 |
+
"tensorboard": {
|
102 |
+
"target": "pytorch_lightning.loggers.TensorBoardLogger",
|
103 |
+
"params": {
|
104 |
+
"save_dir": logdir,
|
105 |
+
"name": "tensorboard",
|
106 |
+
}
|
107 |
+
},
|
108 |
+
"testtube": {
|
109 |
+
"target": "pytorch_lightning.loggers.CSVLogger",
|
110 |
+
"params": {
|
111 |
+
"name": "testtube",
|
112 |
+
"save_dir": logdir,
|
113 |
+
}
|
114 |
+
},
|
115 |
+
}
|
116 |
+
os.makedirs(os.path.join(logdir, "tensorboard"), exist_ok=True)
|
117 |
+
default_logger_cfg = default_logger_cfgs["tensorboard"]
|
118 |
+
if "logger" in lightning_config:
|
119 |
+
logger_cfg = lightning_config.logger
|
120 |
+
else:
|
121 |
+
logger_cfg = OmegaConf.create()
|
122 |
+
logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
|
123 |
+
return logger_cfg
|
124 |
+
|
125 |
+
def get_trainer_strategy(lightning_config):
|
126 |
+
default_strategy_dict = {
|
127 |
+
"target": "pytorch_lightning.strategies.DDPShardedStrategy"
|
128 |
+
}
|
129 |
+
if "strategy" in lightning_config:
|
130 |
+
strategy_cfg = lightning_config.strategy
|
131 |
+
return strategy_cfg
|
132 |
+
else:
|
133 |
+
strategy_cfg = OmegaConf.create()
|
134 |
+
|
135 |
+
strategy_cfg = OmegaConf.merge(default_strategy_dict, strategy_cfg)
|
136 |
+
return strategy_cfg
|
137 |
+
|
138 |
+
def load_checkpoints(model, model_cfg):
|
139 |
+
if check_config_attribute(model_cfg, "pretrained_checkpoint"):
|
140 |
+
pretrained_ckpt = model_cfg.pretrained_checkpoint
|
141 |
+
assert os.path.exists(pretrained_ckpt), "Error: Pre-trained checkpoint NOT found at:%s"%pretrained_ckpt
|
142 |
+
mainlogger.info(">>> Load weights from pretrained checkpoint")
|
143 |
+
|
144 |
+
pl_sd = torch.load(pretrained_ckpt, map_location="cpu")
|
145 |
+
try:
|
146 |
+
if 'state_dict' in pl_sd.keys():
|
147 |
+
model.load_state_dict(pl_sd["state_dict"], strict=True)
|
148 |
+
mainlogger.info(">>> Loaded weights from pretrained checkpoint: %s"%pretrained_ckpt)
|
149 |
+
else:
|
150 |
+
# deepspeed
|
151 |
+
new_pl_sd = OrderedDict()
|
152 |
+
for key in pl_sd['module'].keys():
|
153 |
+
new_pl_sd[key[16:]]=pl_sd['module'][key]
|
154 |
+
model.load_state_dict(new_pl_sd, strict=True)
|
155 |
+
except:
|
156 |
+
model.load_state_dict(pl_sd)
|
157 |
+
else:
|
158 |
+
mainlogger.info(">>> Start training from scratch")
|
159 |
+
|
160 |
+
return model
|
161 |
+
|
162 |
+
def set_logger(logfile, name='mainlogger'):
|
163 |
+
logger = logging.getLogger(name)
|
164 |
+
logger.setLevel(logging.INFO)
|
165 |
+
fh = logging.FileHandler(logfile, mode='w')
|
166 |
+
fh.setLevel(logging.INFO)
|
167 |
+
ch = logging.StreamHandler()
|
168 |
+
ch.setLevel(logging.DEBUG)
|
169 |
+
fh.setFormatter(logging.Formatter("%(asctime)s-%(levelname)s: %(message)s"))
|
170 |
+
ch.setFormatter(logging.Formatter("%(message)s"))
|
171 |
+
logger.addHandler(fh)
|
172 |
+
logger.addHandler(ch)
|
173 |
+
return logger
|
prompts/.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
prompts/1024_interp/74906_1462_frame1.png
ADDED
prompts/1024_interp/74906_1462_frame3.png
ADDED
prompts/1024_interp/Japan_v2_2_062266_s2_frame1.png
ADDED
prompts/1024_interp/Japan_v2_2_062266_s2_frame3.png
ADDED
prompts/1024_interp/Japan_v2_3_119235_s2_frame1.png
ADDED
prompts/1024_interp/Japan_v2_3_119235_s2_frame3.png
ADDED
prompts/1024_interp/interp_1_1.png
ADDED
prompts/1024_interp/interp_1_2.png
ADDED
prompts/1024_interp/interp_2_1.png
ADDED
prompts/1024_interp/interp_2_2.png
ADDED
prompts/512_interp/74906_1462_frame1.png
ADDED
prompts/512_interp/74906_1462_frame3.png
ADDED
prompts/512_interp/Japan_v2_2_062266_s2_frame1.png
ADDED
prompts/512_interp/Japan_v2_2_062266_s2_frame3.png
ADDED
prompts/512_interp/Japan_v2_3_119235_s2_frame1.png
ADDED
prompts/512_interp/Japan_v2_3_119235_s2_frame3.png
ADDED
prompts/512_interp/prompts.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
walking man
|
2 |
+
an anime scene
|
3 |
+
an anime scene
|