Spaces:
Runtime error
Runtime error
Linoy Tsaban
commited on
Commit
•
248a53d
1
Parent(s):
e24d40d
Update preprocess_utils.py
Browse files- preprocess_utils.py +262 -28
preprocess_utils.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
2 |
from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler
|
|
|
3 |
# suppress partial model loading warning
|
4 |
logging.set_verbosity_error()
|
5 |
|
@@ -12,6 +13,8 @@ from torchvision.io import write_video
|
|
12 |
from pathlib import Path
|
13 |
from utils import *
|
14 |
import torchvision.transforms as T
|
|
|
|
|
15 |
|
16 |
|
17 |
def get_timesteps(scheduler, num_inference_steps, strength, device):
|
@@ -64,7 +67,9 @@ class Preprocess(nn.Module):
|
|
64 |
self.text_encoder = text_encoder
|
65 |
self.unet = unet
|
66 |
self.scheduler=scheduler
|
|
|
67 |
self.total_inverted_latents = {}
|
|
|
68 |
|
69 |
self.paths, self.frames, self.latents = self.get_data(self.config["data_path"], self.config["n_frames"])
|
70 |
print("self.frames", self.frames.shape)
|
@@ -163,14 +168,34 @@ class Preprocess(nn.Module):
|
|
163 |
)[0]
|
164 |
return noise_pred
|
165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
@torch.no_grad()
|
167 |
def get_text_embeds(self, prompt, negative_prompt, device="cuda"):
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length,
|
172 |
-
return_tensors='pt')
|
173 |
-
uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(device))[0]
|
174 |
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
175 |
return text_embeddings
|
176 |
|
@@ -192,7 +217,7 @@ class Preprocess(nn.Module):
|
|
192 |
for i in range(0, len(imgs), batch_size):
|
193 |
posterior = self.vae.encode(imgs[i:i + batch_size]).latent_dist
|
194 |
latent = posterior.mean if deterministic else posterior.sample()
|
195 |
-
latents.append(latent *
|
196 |
latents = torch.cat(latents)
|
197 |
return latents
|
198 |
|
@@ -264,6 +289,137 @@ class Preprocess(nn.Module):
|
|
264 |
self.total_inverted_latents[f'noisy_latents_{t}'] = latent_frames.clone()
|
265 |
|
266 |
return latent_frames
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
267 |
|
268 |
@torch.no_grad()
|
269 |
def ddim_sample(self, x, cond, batch_size):
|
@@ -295,6 +451,8 @@ class Preprocess(nn.Module):
|
|
295 |
pred_x0 = (x_batch - sigma * eps) / mu
|
296 |
x[b:b + batch_size] = mu_prev * pred_x0 + sigma_prev * eps
|
297 |
return x
|
|
|
|
|
298 |
|
299 |
@torch.no_grad()
|
300 |
def extract_latents(self,
|
@@ -303,31 +461,89 @@ class Preprocess(nn.Module):
|
|
303 |
batch_size,
|
304 |
timesteps_to_save,
|
305 |
inversion_prompt='',
|
306 |
-
|
|
|
|
|
|
|
|
|
307 |
self.scheduler.set_timesteps(num_steps)
|
308 |
cond = self.get_text_embeds(inversion_prompt, "")[1].unsqueeze(0)
|
309 |
latent_frames = self.latents
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
318 |
|
|
|
|
|
319 |
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
|
326 |
-
|
327 |
-
|
|
|
328 |
|
329 |
-
|
|
|
|
|
330 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
|
332 |
def prep(opt):
|
333 |
# timesteps to save
|
@@ -348,11 +564,14 @@ def prep(opt):
|
|
348 |
seed_everything(opt["seed"])
|
349 |
if not opt["frames"]: # original non demo setting
|
350 |
save_path = os.path.join(opt["save_dir"],
|
|
|
351 |
f'sd_{opt["sd_version"]}',
|
352 |
Path(opt["data_path"]).stem,
|
353 |
f'steps_{opt["steps"]}',
|
354 |
f'nframes_{opt["n_frames"]}')
|
355 |
os.makedirs(os.path.join(save_path, f'latents'), exist_ok=True)
|
|
|
|
|
356 |
add_dict_to_yaml_file(os.path.join(opt["save_dir"], 'inversion_prompts.yaml'), Path(opt["data_path"]).stem, opt["inversion_prompt"])
|
357 |
# save inversion prompt in a txt file
|
358 |
with open(os.path.join(save_path, 'inversion_prompt.txt'), 'w') as f:
|
@@ -360,16 +579,31 @@ def prep(opt):
|
|
360 |
else:
|
361 |
save_path = None
|
362 |
|
363 |
-
model = Preprocess(device,
|
|
|
|
|
|
|
|
|
|
|
|
|
364 |
|
365 |
-
|
366 |
num_steps=model.config["steps"],
|
367 |
save_path=save_path,
|
368 |
batch_size=model.config["batch_size"],
|
369 |
timesteps_to_save=timesteps_to_save,
|
370 |
inversion_prompt=model.config["inversion_prompt"],
|
|
|
|
|
|
|
371 |
)
|
372 |
|
373 |
-
|
374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
375 |
|
|
|
1 |
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
2 |
from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler
|
3 |
+
from diffusers.utils.torch_utils import randn_tensor
|
4 |
# suppress partial model loading warning
|
5 |
logging.set_verbosity_error()
|
6 |
|
|
|
13 |
from pathlib import Path
|
14 |
from utils import *
|
15 |
import torchvision.transforms as T
|
16 |
+
import cv2
|
17 |
+
import numpy as np
|
18 |
|
19 |
|
20 |
def get_timesteps(scheduler, num_inference_steps, strength, device):
|
|
|
67 |
self.text_encoder = text_encoder
|
68 |
self.unet = unet
|
69 |
self.scheduler=scheduler
|
70 |
+
|
71 |
self.total_inverted_latents = {}
|
72 |
+
self.noise_total = None # will contain all zs if inversion == 'ddpm', var name chosen to match the save path of zs used in pr https://github.com/omerbt/TokenFlow/pull/24/files#
|
73 |
|
74 |
self.paths, self.frames, self.latents = self.get_data(self.config["data_path"], self.config["n_frames"])
|
75 |
print("self.frames", self.frames.shape)
|
|
|
168 |
)[0]
|
169 |
return noise_pred
|
170 |
|
171 |
+
@torch.no_grad()
|
172 |
+
def encode_text(self, prompts, device=None):
|
173 |
+
if device is None:
|
174 |
+
device = self.device
|
175 |
+
text_inputs = self.tokenizer(
|
176 |
+
prompts,
|
177 |
+
padding="max_length",
|
178 |
+
max_length=self.tokenizer.model_max_length,
|
179 |
+
return_tensors="pt",
|
180 |
+
)
|
181 |
+
text_input_ids = text_inputs.input_ids
|
182 |
+
|
183 |
+
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
|
184 |
+
removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length:])
|
185 |
+
print(
|
186 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
187 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
188 |
+
)
|
189 |
+
text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
|
190 |
+
text_embeddings = self.text_encoder(text_input_ids.to(device))[0]
|
191 |
+
|
192 |
+
return text_embeddings
|
193 |
+
|
194 |
@torch.no_grad()
|
195 |
def get_text_embeds(self, prompt, negative_prompt, device="cuda"):
|
196 |
+
text_embeddings = self.encode_text(prompt, device=device)
|
197 |
+
uncond_embeddings = self.encode_text(negative_prompt, device=device)
|
198 |
+
|
|
|
|
|
|
|
199 |
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
200 |
return text_embeddings
|
201 |
|
|
|
217 |
for i in range(0, len(imgs), batch_size):
|
218 |
posterior = self.vae.encode(imgs[i:i + batch_size]).latent_dist
|
219 |
latent = posterior.mean if deterministic else posterior.sample()
|
220 |
+
latents.append(latent * self.vae.config.scaling_factor)
|
221 |
latents = torch.cat(latents)
|
222 |
return latents
|
223 |
|
|
|
289 |
self.total_inverted_latents[f'noisy_latents_{t}'] = latent_frames.clone()
|
290 |
|
291 |
return latent_frames
|
292 |
+
|
293 |
+
@torch.no_grad()
|
294 |
+
def ddpm_inversion(self, cond,
|
295 |
+
latent_frames,
|
296 |
+
batch_size,
|
297 |
+
num_inversion_steps,
|
298 |
+
save_path=None,
|
299 |
+
save_latents=True,
|
300 |
+
eta: float = 1.0,
|
301 |
+
skip_steps=20):
|
302 |
+
timesteps = self.scheduler.timesteps
|
303 |
+
return_inverted_latents = self.config["frames"] is not None
|
304 |
+
|
305 |
+
variance_noise_shape = (
|
306 |
+
num_inversion_steps,
|
307 |
+
*latent_frames.shape)
|
308 |
+
x0 = latent_frames
|
309 |
+
|
310 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
|
311 |
+
xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=cond.dtype)
|
312 |
+
|
313 |
+
for t in reversed(timesteps):
|
314 |
+
idx = t_to_idx[int(t)]
|
315 |
+
for b in range(0, x0.shape[0], batch_size):
|
316 |
+
x_batch = x0[b:b + batch_size]
|
317 |
+
|
318 |
+
noise = randn_tensor(shape=x_batch.shape, device=self.device, dtype=x0.dtype)
|
319 |
+
xts[idx, b:b + batch_size] = self.scheduler.add_noise(x_batch, noise, t)
|
320 |
+
|
321 |
+
xts = torch.cat([xts, x0.unsqueeze(0)], dim=0)
|
322 |
+
|
323 |
+
zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=cond.dtype)
|
324 |
+
|
325 |
+
for t in tqdm(timesteps):
|
326 |
+
idx = t_to_idx[int(t)]
|
327 |
+
# 1. predict noise residual
|
328 |
+
for b in range(0, x0.shape[0], batch_size):
|
329 |
+
xt = xts[idx, b:b + batch_size]
|
330 |
+
|
331 |
+
cond_batch = cond.repeat(xt.shape[0], 1, 1)
|
332 |
+
noise_pred = self.unet(xt, timestep=t, encoder_hidden_states=cond_batch).sample
|
333 |
+
|
334 |
+
xtm1 = xts[idx + 1, b:b + batch_size]
|
335 |
+
z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, eta)
|
336 |
+
zs[idx, b:b + batch_size] = z
|
337 |
+
|
338 |
+
# correction to avoid error accumulation
|
339 |
+
xts[idx + 1, b:b + batch_size] = xtm1_corrected
|
340 |
+
|
341 |
+
if save_latents:
|
342 |
+
torch.save(xts[idx], os.path.join(save_path, 'latents', f'noisy_latents_{t}.pt'))
|
343 |
+
|
344 |
+
if return_inverted_latents:
|
345 |
+
self.total_inverted_latents[f'noisy_latents_{t}'] = xts[idx].clone()
|
346 |
+
|
347 |
+
if save_path:
|
348 |
+
torch.save(xts[idx], os.path.join(save_path, 'latents', f'noisy_latents_{t}.pt'))
|
349 |
+
torch.save(zs, os.path.join(save_path, 'latents', f'noise_total.pt'))
|
350 |
+
|
351 |
+
if return_inverted_latents:
|
352 |
+
self.total_inverted_latents[f'noisy_latents_{t}'] = xts[idx].clone()
|
353 |
+
self.noise_total = zs.clone()
|
354 |
+
|
355 |
+
return xts[skip_steps].expand(latent_frames.shape[0], -1, -1, -1), zs
|
356 |
+
|
357 |
+
def prepare_extra_step_kwargs(self, eta):
|
358 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
359 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
360 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
361 |
+
# and should be between [0, 1]
|
362 |
+
|
363 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
364 |
+
extra_step_kwargs = {}
|
365 |
+
if accepts_eta:
|
366 |
+
extra_step_kwargs["eta"] = eta
|
367 |
+
|
368 |
+
# check if the scheduler accepts generator
|
369 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
370 |
+
return extra_step_kwargs
|
371 |
+
|
372 |
+
@torch.no_grad()
|
373 |
+
def ddpm_sample(self, init_latents, cond, batch_size, num_inversion_steps, skip_steps, eta, zs_all,
|
374 |
+
guidance_scale=0):
|
375 |
+
use_ddpm = True
|
376 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
377 |
+
|
378 |
+
total_latents = init_latents
|
379 |
+
self.scheduler.set_timesteps(num_inversion_steps, device=device)
|
380 |
+
timesteps = self.scheduler.timesteps
|
381 |
+
zs_total = zs_all[skip_steps:]
|
382 |
+
|
383 |
+
if use_ddpm:
|
384 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps[-zs_total.shape[0]:])}
|
385 |
+
timesteps = timesteps[-zs_total.shape[0]:]
|
386 |
+
|
387 |
+
num_warmup_steps = len(timesteps) - num_inversion_steps * self.scheduler.order
|
388 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(eta)
|
389 |
+
|
390 |
+
for i, t in enumerate(tqdm(timesteps)):
|
391 |
+
for b in range(0, total_latents.shape[0], batch_size):
|
392 |
+
latents = total_latents[b:b + batch_size]
|
393 |
+
if do_classifier_free_guidance:
|
394 |
+
latent_model_input = torch.cat([latents] * 2)
|
395 |
+
else:
|
396 |
+
latent_model_input = latents
|
397 |
+
cond_batch = cond.repeat(latents.shape[0], 1, 1)
|
398 |
+
|
399 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
400 |
+
|
401 |
+
noise_pred = self.unet(
|
402 |
+
latent_model_input,
|
403 |
+
t,
|
404 |
+
encoder_hidden_states=cond_batch,
|
405 |
+
return_dict=False,
|
406 |
+
)[0]
|
407 |
+
|
408 |
+
if do_classifier_free_guidance:
|
409 |
+
noise_pred_out = noise_pred.chunk(2) # [b,4, 64, 64]
|
410 |
+
noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
|
411 |
+
|
412 |
+
# default text guidance
|
413 |
+
noise_guidance = guidance_scale * (noise_pred_text - noise_pred_uncond)
|
414 |
+
|
415 |
+
noise_pred = noise_pred_uncond + noise_guidance
|
416 |
+
|
417 |
+
idx = t_to_idx[int(t)]
|
418 |
+
zs = zs_total[idx, b:b + batch_size]
|
419 |
+
latents = self.scheduler.step(noise_pred, t, latents, variance_noise=zs,
|
420 |
+
**extra_step_kwargs).prev_sample
|
421 |
+
total_latents[b:b + batch_size] = latents
|
422 |
+
return total_latents
|
423 |
|
424 |
@torch.no_grad()
|
425 |
def ddim_sample(self, x, cond, batch_size):
|
|
|
451 |
pred_x0 = (x_batch - sigma * eps) / mu
|
452 |
x[b:b + batch_size] = mu_prev * pred_x0 + sigma_prev * eps
|
453 |
return x
|
454 |
+
|
455 |
+
|
456 |
|
457 |
@torch.no_grad()
|
458 |
def extract_latents(self,
|
|
|
461 |
batch_size,
|
462 |
timesteps_to_save,
|
463 |
inversion_prompt='',
|
464 |
+
skip_steps=20,
|
465 |
+
inversion_type='ddim',
|
466 |
+
eta=1.0,
|
467 |
+
reconstruction=False):
|
468 |
+
|
469 |
self.scheduler.set_timesteps(num_steps)
|
470 |
cond = self.get_text_embeds(inversion_prompt, "")[1].unsqueeze(0)
|
471 |
latent_frames = self.latents
|
472 |
+
|
473 |
+
if inversion_type == 'ddim':
|
474 |
+
inverted_x= self.ddim_inversion(cond,
|
475 |
+
latent_frames,
|
476 |
+
save_path,
|
477 |
+
batch_size=batch_size,
|
478 |
+
save_latents=True if save_path else False,
|
479 |
+
timesteps_to_save=timesteps_to_save)
|
480 |
+
|
481 |
+
if reconstruction:
|
482 |
+
latent_reconstruction = self.ddim_sample(inverted_x, cond, batch_size=batch_size)
|
483 |
+
|
484 |
+
rgb_reconstruction = self.decode_latents(latent_reconstruction)
|
485 |
+
return (self.frames, self.latents, self.total_inverted_latents), rgb_reconstruction
|
486 |
+
|
487 |
+
else:
|
488 |
+
return (self.frames, self.latents, self.total_inverted_latents), None
|
489 |
+
|
490 |
+
elif inversion_type == 'ddpm':
|
491 |
+
inverted_x, zs = self.ddpm_inversion(cond,
|
492 |
+
latent_frames,
|
493 |
+
save_path= save_path,
|
494 |
+
batch_size=batch_size,
|
495 |
+
save_latents=True if save_path else False,
|
496 |
+
num_inversion_steps=num_steps,
|
497 |
+
eta=eta,
|
498 |
+
skip_steps=skip_steps)
|
499 |
+
|
500 |
+
cond = self.encode_text(inversion_prompt)
|
501 |
+
if reconstruction:
|
502 |
+
latent_reconstruction = self.ddpm_sample(init_latents=inverted_x,
|
503 |
+
cond=cond, batch_size=batch_size,
|
504 |
+
num_inversion_steps=num_steps, skip_steps=skip_steps,
|
505 |
+
eta=eta, zs_all=zs)
|
506 |
+
rgb_reconstruction = self.decode_latents(latent_reconstruction)
|
507 |
+
return (self.frames, self.latents, self.total_inverted_latents, self.noise_total), rgb_reconstruction
|
508 |
+
else:
|
509 |
+
return (self.frames, self.latents, self.total_inverted_latents, self.noise_total), None
|
510 |
|
511 |
+
else:
|
512 |
+
raise NotImplementedError()
|
513 |
|
514 |
+
def compute_noise(scheduler, prev_latents, latents, timestep, noise_pred, eta):
|
515 |
+
# 1. get previous step value (=t-1)
|
516 |
+
prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
|
517 |
+
|
518 |
+
# 2. compute alphas, betas
|
519 |
+
alpha_prod_t = scheduler.alphas_cumprod[timestep]
|
520 |
+
alpha_prod_t_prev = (
|
521 |
+
scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
|
522 |
+
)
|
523 |
+
|
524 |
+
beta_prod_t = 1 - alpha_prod_t
|
525 |
|
526 |
+
# 3. compute predicted original sample from predicted noise also called
|
527 |
+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
528 |
+
pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
|
529 |
|
530 |
+
# 4. Clip "predicted x_0"
|
531 |
+
if scheduler.config.clip_sample:
|
532 |
+
pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
|
533 |
|
534 |
+
# 5. compute variance: "sigma_t(η)" -> see formula (16)
|
535 |
+
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
|
536 |
+
variance = scheduler._get_variance(timestep, prev_timestep)
|
537 |
+
std_dev_t = eta * variance ** (0.5)
|
538 |
+
|
539 |
+
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
540 |
+
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t ** 2) ** (0.5) * noise_pred
|
541 |
+
|
542 |
+
# modifed so that updated xtm1 is returned as well (to avoid error accumulation)
|
543 |
+
mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
|
544 |
+
noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
|
545 |
+
|
546 |
+
return noise, mu_xt + (eta * variance ** 0.5) * noise
|
547 |
|
548 |
def prep(opt):
|
549 |
# timesteps to save
|
|
|
564 |
seed_everything(opt["seed"])
|
565 |
if not opt["frames"]: # original non demo setting
|
566 |
save_path = os.path.join(opt["save_dir"],
|
567 |
+
f'inversion_{opt[inversion]}',
|
568 |
f'sd_{opt["sd_version"]}',
|
569 |
Path(opt["data_path"]).stem,
|
570 |
f'steps_{opt["steps"]}',
|
571 |
f'nframes_{opt["n_frames"]}')
|
572 |
os.makedirs(os.path.join(save_path, f'latents'), exist_ok=True)
|
573 |
+
if opt[inversion] == 'ddpm':
|
574 |
+
os.makedirs(os.path.join(save_path, f'latents'), exist_ok=True)
|
575 |
add_dict_to_yaml_file(os.path.join(opt["save_dir"], 'inversion_prompts.yaml'), Path(opt["data_path"]).stem, opt["inversion_prompt"])
|
576 |
# save inversion prompt in a txt file
|
577 |
with open(os.path.join(save_path, 'inversion_prompt.txt'), 'w') as f:
|
|
|
579 |
else:
|
580 |
save_path = None
|
581 |
|
582 |
+
model = Preprocess(device,
|
583 |
+
config,
|
584 |
+
vae=vae,
|
585 |
+
text_encoder=text_encoder,
|
586 |
+
scheduler=scheduler,
|
587 |
+
tokenizer=tokenizer,
|
588 |
+
unet=unet)
|
589 |
|
590 |
+
frames_and_latents, rgb_reconstruction = model.extract_latents(
|
591 |
num_steps=model.config["steps"],
|
592 |
save_path=save_path,
|
593 |
batch_size=model.config["batch_size"],
|
594 |
timesteps_to_save=timesteps_to_save,
|
595 |
inversion_prompt=model.config["inversion_prompt"],
|
596 |
+
inversion_type=model.config[inversion],
|
597 |
+
skip_steps=model.config[skip_steps],
|
598 |
+
reconstruction=model.config[reconstruct]
|
599 |
)
|
600 |
|
601 |
+
if model.config[inversion] == 'ddpm':
|
602 |
+
frames, latents, total_inverted_latents, zs = frames_and_latents
|
603 |
+
return frames, latents, total_inverted_latents, zs, rgb_reconstruction
|
604 |
+
else:
|
605 |
+
frames, latents, total_inverted_latents = frames_and_latents
|
606 |
+
return frames, latents, total_inverted_latents, rgb_reconstruction
|
607 |
+
|
608 |
+
|
609 |
|