Linoy Tsaban commited on
Commit
5eb8981
1 Parent(s): 4e5195b

Create tokenflow_pnp.py

Browse files
Files changed (1) hide show
  1. tokenflow_pnp.py +363 -0
tokenflow_pnp.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import numpy as np
4
+ import cv2
5
+ from pathlib import Path
6
+ import torch
7
+ import torch.nn as nn
8
+ import torchvision.transforms as T
9
+ import argparse
10
+ from PIL import Image
11
+ import yaml
12
+ from tqdm import tqdm
13
+ from transformers import logging
14
+ from diffusers import DDIMScheduler, StableDiffusionPipeline
15
+
16
+ from tokenflow_utils import *
17
+ from util import save_video, seed_everything
18
+
19
+ # suppress partial model loading warning
20
+ logging.set_verbosity_error()
21
+
22
+ VAE_BATCH_SIZE = 10
23
+
24
+
25
+ class TokenFlow(nn.Module):
26
+ def __init__(self, config,
27
+ frames=None,
28
+ # latents = None,
29
+ inverted_latents = None):
30
+ super().__init__()
31
+ self.config = config
32
+ self.device = config["device"]
33
+
34
+ sd_version = config["sd_version"]
35
+ self.sd_version = sd_version
36
+ if sd_version == '2.1':
37
+ model_key = "stabilityai/stable-diffusion-2-1-base"
38
+ elif sd_version == '2.0':
39
+ model_key = "stabilityai/stable-diffusion-2-base"
40
+ elif sd_version == '1.5':
41
+ model_key = "runwayml/stable-diffusion-v1-5"
42
+ elif sd_version == 'depth':
43
+ model_key = "stabilityai/stable-diffusion-2-depth"
44
+ else:
45
+ raise ValueError(f'Stable-diffusion version {sd_version} not supported.')
46
+
47
+ # Create SD models
48
+ print('Loading SD model')
49
+
50
+ pipe = StableDiffusionPipeline.from_pretrained(model_key, torch_dtype=torch.float16).to("cuda")
51
+ pipe.enable_xformers_memory_efficient_attention()
52
+
53
+ self.vae = pipe.vae
54
+ self.tokenizer = pipe.tokenizer
55
+ self.text_encoder = pipe.text_encoder
56
+ self.unet = pipe.unet
57
+
58
+ self.scheduler = DDIMScheduler.from_pretrained(model_key, subfolder="scheduler")
59
+ self.scheduler.set_timesteps(config["n_timesteps"], device=self.device)
60
+ print('SD model loaded')
61
+
62
+ # data
63
+ self.frames, self.inverted_latents = frames, inverted_latents
64
+ self.latents_path = self.get_latents_path()
65
+
66
+ # load frames
67
+ self.paths, self.frames, self.latents, self.eps = self.get_data()
68
+
69
+ if self.sd_version == 'depth':
70
+ self.depth_maps = self.prepare_depth_maps()
71
+
72
+ self.text_embeds = self.get_text_embeds(config["prompt"], config["negative_prompt"])
73
+ # pnp_inversion_prompt = self.get_pnp_inversion_prompt()
74
+ self.pnp_guidance_embeds = self.get_text_embeds(config["pnp_inversion_prompt"], config["pnp_inversion_prompt"]).chunk(2)[0]
75
+
76
+ @torch.no_grad()
77
+ def prepare_depth_maps(self, model_type='DPT_Large', device='cuda'):
78
+ depth_maps = []
79
+ midas = torch.hub.load("intel-isl/MiDaS", model_type)
80
+ midas.to(device)
81
+ midas.eval()
82
+
83
+ midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
84
+
85
+ if model_type == "DPT_Large" or model_type == "DPT_Hybrid":
86
+ transform = midas_transforms.dpt_transform
87
+ else:
88
+ transform = midas_transforms.small_transform
89
+
90
+ for i in range(len(self.paths)):
91
+ img = cv2.imread(self.paths[i])
92
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
93
+
94
+ latent_h = img.shape[0] // 8
95
+ latent_w = img.shape[1] // 8
96
+
97
+ input_batch = transform(img).to(device)
98
+ prediction = midas(input_batch)
99
+
100
+ depth_map = torch.nn.functional.interpolate(
101
+ prediction.unsqueeze(1),
102
+ size=(latent_h, latent_w),
103
+ mode="bicubic",
104
+ align_corners=False,
105
+ )
106
+ depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
107
+ depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
108
+ depth_map = 2.0 * (depth_map - depth_min) / (depth_max - depth_min) - 1.0
109
+ depth_maps.append(depth_map)
110
+
111
+ return torch.cat(depth_maps).to(torch.float16).to(self.device)
112
+
113
+ def get_pnp_inversion_prompt(self):
114
+ inv_prompts_path = os.path.join(str(Path(self.latents_path).parent), 'inversion_prompt.txt')
115
+ # read inversion prompt
116
+ with open(inv_prompts_path, 'r') as f:
117
+ inv_prompt = f.read()
118
+ return inv_prompt
119
+
120
+ def get_latents_path(self):
121
+ read_from_files = self.frames is None
122
+ # read_from_files = True
123
+ if read_from_files:
124
+ latents_path = os.path.join(self.config["latents_path"], f'sd_{self.config["sd_version"]}',
125
+ Path(self.config["data_path"]).stem, f'steps_{self.config["n_inversion_steps"]}')
126
+ latents_path = [x for x in glob.glob(f'{latents_path}/*') if '.' not in Path(x).name]
127
+ n_frames = [int([x for x in latents_path[i].split('/') if 'nframes' in x][0].split('_')[1]) for i in range(len(latents_path))]
128
+ print("n_frames", n_frames)
129
+ latents_path = latents_path[np.argmax(n_frames)]
130
+ print("latents_path", latents_path)
131
+ self.config["n_frames"] = min(max(n_frames), self.config["n_frames"])
132
+
133
+ else:
134
+ n_frames = self.frames.shape[0]
135
+ self.config["n_frames"] = min(n_frames, self.config["n_frames"])
136
+
137
+ if self.config["n_frames"] % self.config["batch_size"] != 0:
138
+ # make n_frames divisible by batch_size
139
+ self.config["n_frames"] = self.config["n_frames"] - (self.config["n_frames"] % self.config["batch_size"])
140
+ print("Number of frames: ", self.config["n_frames"])
141
+ if read_from_files:
142
+ print("YOOOOOOO", os.path.join(latents_path, 'latents'))
143
+ return os.path.join(latents_path, 'latents')
144
+ else:
145
+ return None
146
+
147
+ @torch.no_grad()
148
+ def get_text_embeds(self, prompt, negative_prompt, batch_size=1):
149
+ # Tokenize text and get embeddings
150
+ text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length,
151
+ truncation=True, return_tensors='pt')
152
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
153
+
154
+ # Do the same for unconditional embeddings
155
+ uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length,
156
+ return_tensors='pt')
157
+
158
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
159
+
160
+ # Cat for final embeddings
161
+ text_embeddings = torch.cat([uncond_embeddings] * batch_size + [text_embeddings] * batch_size)
162
+ return text_embeddings
163
+
164
+ @torch.no_grad()
165
+ def encode_imgs(self, imgs, batch_size=VAE_BATCH_SIZE, deterministic=False):
166
+ imgs = 2 * imgs - 1
167
+ latents = []
168
+ for i in range(0, len(imgs), batch_size):
169
+ posterior = self.vae.encode(imgs[i:i + batch_size]).latent_dist
170
+ latent = posterior.mean if deterministic else posterior.sample()
171
+ latents.append(latent * 0.18215)
172
+ latents = torch.cat(latents)
173
+ return latents
174
+
175
+ @torch.no_grad()
176
+ def decode_latents(self, latents, batch_size=VAE_BATCH_SIZE):
177
+ latents = 1 / 0.18215 * latents
178
+ imgs = []
179
+ for i in range(0, len(latents), batch_size):
180
+ imgs.append(self.vae.decode(latents[i:i + batch_size]).sample)
181
+ imgs = torch.cat(imgs)
182
+ imgs = (imgs / 2 + 0.5).clamp(0, 1)
183
+ return imgs
184
+
185
+
186
+ def get_data(self):
187
+ read_from_files = self.frames is None
188
+ # read_from_files = True
189
+ if read_from_files:
190
+ # load frames
191
+ paths = [os.path.join(self.config["data_path"], "%05d.jpg" % idx) for idx in
192
+ range(self.config["n_frames"])]
193
+ if not os.path.exists(paths[0]):
194
+ paths = [os.path.join(self.config["data_path"], "%05d.png" % idx) for idx in
195
+ range(self.config["n_frames"])]
196
+ frames = [Image.open(paths[idx]).convert('RGB') for idx in range(self.config["n_frames"])]
197
+ if frames[0].size[0] == frames[0].size[1]:
198
+ frames = [frame.resize((512, 512), resample=Image.Resampling.LANCZOS) for frame in frames]
199
+ frames = torch.stack([T.ToTensor()(frame) for frame in frames]).to(torch.float16).to(self.device)
200
+ save_video(frames, f'{self.config["output_path"]}/input_fps10.mp4', fps=10)
201
+ save_video(frames, f'{self.config["output_path"]}/input_fps20.mp4', fps=20)
202
+ save_video(frames, f'{self.config["output_path"]}/input_fps30.mp4', fps=30)
203
+ else:
204
+ frames = self.frames
205
+ # encode to latents
206
+ latents = self.encode_imgs(frames, deterministic=True).to(torch.float16).to(self.device)
207
+ # get noise
208
+ eps = self.get_ddim_eps(latents, range(self.config["n_frames"])).to(torch.float16).to(self.device)
209
+ if not read_from_files:
210
+ return None, frames, latents, eps
211
+ return paths, frames, latents, eps
212
+
213
+ def get_ddim_eps(self, latent, indices):
214
+ read_from_files = self.inverted_latents is None
215
+ # read_from_files = True
216
+ if read_from_files:
217
+ noisest = max([int(x.split('_')[-1].split('.')[0]) for x in glob.glob(os.path.join(self.latents_path, f'noisy_latents_*.pt'))])
218
+ print("noisets:", noisest)
219
+ print("indecies:", indices)
220
+ latents_path = os.path.join(self.latents_path, f'noisy_latents_{noisest}.pt')
221
+ noisy_latent = torch.load(latents_path)[indices].to(self.device)
222
+
223
+ # path = os.path.join('test_latents', f'noisy_latents_{noisest}.pt')
224
+ # f_noisy_latent = torch.load(path)[indices].to(self.device)
225
+ # print(f_noisy_latent==noisy_latent)
226
+ else:
227
+ noisest = max([int(key.split("_")[-1]) for key in self.inverted_latents.keys()])
228
+ print("noisets:", noisest)
229
+ print("indecies:", indices)
230
+ noisy_latent = self.inverted_latents[f'noisy_latents_{noisest}'][indices]
231
+
232
+ alpha_prod_T = self.scheduler.alphas_cumprod[noisest]
233
+ mu_T, sigma_T = alpha_prod_T ** 0.5, (1 - alpha_prod_T) ** 0.5
234
+ eps = (noisy_latent - mu_T * latent) / sigma_T
235
+ return eps
236
+
237
+ @torch.no_grad()
238
+ def denoise_step(self, x, t, indices):
239
+ # register the time step and features in pnp injection modules
240
+ read_files = self.inverted_latents is None
241
+
242
+ if read_files:
243
+ source_latents = load_source_latents_t(t, self.latents_path)[indices]
244
+
245
+ else:
246
+ source_latents = self.inverted_latents[f'noisy_latents_{t}'][indices]
247
+
248
+ latent_model_input = torch.cat([source_latents] + ([x] * 2))
249
+ if self.sd_version == 'depth':
250
+ latent_model_input = torch.cat([latent_model_input, torch.cat([self.depth_maps[indices]] * 3)], dim=1)
251
+
252
+ register_time(self, t.item())
253
+
254
+ # compute text embeddings
255
+ text_embed_input = torch.cat([self.pnp_guidance_embeds.repeat(len(indices), 1, 1),
256
+ torch.repeat_interleave(self.text_embeds, len(indices), dim=0)])
257
+
258
+ # apply the denoising network
259
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embed_input)['sample']
260
+
261
+ # perform guidance
262
+ _, noise_pred_uncond, noise_pred_cond = noise_pred.chunk(3)
263
+ noise_pred = noise_pred_uncond + self.config["guidance_scale"] * (noise_pred_cond - noise_pred_uncond)
264
+
265
+ # compute the denoising step with the reference model
266
+ denoised_latent = self.scheduler.step(noise_pred, t, x)['prev_sample']
267
+ return denoised_latent
268
+
269
+ @torch.autocast(dtype=torch.float16, device_type='cuda')
270
+ def batched_denoise_step(self, x, t, indices):
271
+ batch_size = self.config["batch_size"]
272
+ denoised_latents = []
273
+ pivotal_idx = torch.randint(batch_size, (len(x)//batch_size,)) + torch.arange(0,len(x),batch_size)
274
+
275
+ register_pivotal(self, True)
276
+ self.denoise_step(x[pivotal_idx], t, indices[pivotal_idx])
277
+ register_pivotal(self, False)
278
+ for i, b in enumerate(range(0, len(x), batch_size)):
279
+ register_batch_idx(self, i)
280
+ denoised_latents.append(self.denoise_step(x[b:b + batch_size], t, indices[b:b + batch_size]))
281
+ denoised_latents = torch.cat(denoised_latents)
282
+ return denoised_latents
283
+
284
+ def init_method(self, conv_injection_t, qk_injection_t):
285
+ self.qk_injection_timesteps = self.scheduler.timesteps[:qk_injection_t] if qk_injection_t >= 0 else []
286
+ self.conv_injection_timesteps = self.scheduler.timesteps[:conv_injection_t] if conv_injection_t >= 0 else []
287
+ register_extended_attention_pnp(self, self.qk_injection_timesteps)
288
+ register_conv_injection(self, self.conv_injection_timesteps)
289
+ set_tokenflow(self.unet)
290
+
291
+ def save_vae_recon(self):
292
+ os.makedirs(f'{self.config["output_path"]}/vae_recon', exist_ok=True)
293
+ decoded = self.decode_latents(self.latents)
294
+ for i in range(len(decoded)):
295
+ T.ToPILImage()(decoded[i]).save(f'{self.config["output_path"]}/vae_recon/%05d.png' % i)
296
+ save_video(decoded, f'{self.config["output_path"]}/vae_recon_10.mp4', fps=10)
297
+ save_video(decoded, f'{self.config["output_path"]}/vae_recon_20.mp4', fps=20)
298
+ save_video(decoded, f'{self.config["output_path"]}/vae_recon_30.mp4', fps=30)
299
+
300
+ def edit_video(self):
301
+ save_files = self.inverted_latents is None # if we're in the original non-demo setting
302
+ if save_files:
303
+ os.makedirs(f'{self.config["output_path"]}/img_ode', exist_ok=True)
304
+ self.save_vae_recon()
305
+ # self.save_vae_recon()
306
+ pnp_f_t = int(self.config["n_timesteps"] * self.config["pnp_f_t"])
307
+ pnp_attn_t = int(self.config["n_timesteps"] * self.config["pnp_attn_t"])
308
+
309
+ self.init_method(conv_injection_t=pnp_f_t, qk_injection_t=pnp_attn_t)
310
+
311
+ noisy_latents = self.scheduler.add_noise(self.latents, self.eps, self.scheduler.timesteps[0])
312
+ edited_frames = self.sample_loop(noisy_latents, torch.arange(self.config["n_frames"]))
313
+
314
+ if save_files:
315
+ save_video(edited_frames, f'{self.config["output_path"]}/tokenflow_PnP_fps_10.mp4')
316
+ save_video(edited_frames, f'{self.config["output_path"]}/tokenflow_PnP_fps_20.mp4', fps=20)
317
+ save_video(edited_frames, f'{self.config["output_path"]}/tokenflow_PnP_fps_30.mp4', fps=30)
318
+ print('Done!')
319
+ else:
320
+ return edited_frames
321
+
322
+ def sample_loop(self, x, indices):
323
+ save_files = self.inverted_latents is None # if we're in the original non-demo setting
324
+ # save_files = True
325
+ if save_files:
326
+ os.makedirs(f'{self.config["output_path"]}/img_ode', exist_ok=True)
327
+ for i, t in enumerate(tqdm(self.scheduler.timesteps, desc="Sampling")):
328
+ x = self.batched_denoise_step(x, t, indices)
329
+
330
+ decoded_latents = self.decode_latents(x)
331
+ if save_files:
332
+ for i in range(len(decoded_latents)):
333
+ T.ToPILImage()(decoded_latents[i]).save(f'{self.config["output_path"]}/img_ode/%05d.png' % i)
334
+
335
+ return decoded_latents
336
+
337
+
338
+ # def run(config):
339
+ # seed_everything(config["seed"])
340
+ # print(config)
341
+ # editor = TokenFlow(config)
342
+ # editor.edit_video()
343
+
344
+
345
+ # if __name__ == '__main__':
346
+ # parser = argparse.ArgumentParser()
347
+ # parser.add_argument('--config_path', type=str, default='configs/config_pnp.yaml')
348
+ # opt = parser.parse_args()
349
+ # with open(opt.config_path, "r") as f:
350
+ # config = yaml.safe_load(f)
351
+ # config["output_path"] = os.path.join(config["output_path"] + f'_pnp_SD_{config["sd_version"]}',
352
+ # Path(config["data_path"]).stem,
353
+ # config["prompt"][:240],
354
+ # f'attn_{config["pnp_attn_t"]}_f_{config["pnp_f_t"]}',
355
+ # f'batch_size_{str(config["batch_size"])}',
356
+ # str(config["n_timesteps"]),
357
+ # )
358
+ # os.makedirs(config["output_path"], exist_ok=True)
359
+ # print(config["data_path"])
360
+ # assert os.path.exists(config["data_path"]), "Data path does not exist"
361
+ # with open(os.path.join(config["output_path"], "config.yaml"), "w") as f:
362
+ # yaml.dump(config, f)
363
+ # run(config)