lev1 commited on
Commit
cbea3f9
1 Parent(s): fd6da5c

Back to diffusers 0.14.x

Browse files
Files changed (4) hide show
  1. model.py +17 -18
  2. requirements.txt +1 -1
  3. text_to_video_pipeline.py +504 -0
  4. utils.py +84 -1
model.py CHANGED
@@ -1,12 +1,12 @@
1
  from enum import Enum
2
  import gc
3
  import numpy as np
4
- #import tomesd
5
  import torch
6
 
7
- from diffusers import StableDiffusionInstructPix2PixPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UNet2DConditionModel, TextToVideoZeroPipeline
8
  from diffusers.schedulers import EulerAncestralDiscreteScheduler, DDIMScheduler
9
- from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero import CrossFrameAttnProcessor
10
 
11
  import utils
12
  import gradio_utils
@@ -32,18 +32,18 @@ class Model:
32
  self.generator = torch.Generator(device=device)
33
  self.pipe_dict = {
34
  ModelType.Pix2Pix_Video: StableDiffusionInstructPix2PixPipeline,
35
- ModelType.Text2Video: TextToVideoZeroPipeline,
36
  ModelType.ControlNetCanny: StableDiffusionControlNetPipeline,
37
  ModelType.ControlNetCannyDB: StableDiffusionControlNetPipeline,
38
  ModelType.ControlNetPose: StableDiffusionControlNetPipeline,
39
  ModelType.ControlNetDepth: StableDiffusionControlNetPipeline,
40
  }
41
- self.controlnet_attn_proc = CrossFrameAttnProcessor(
42
- batch_size=2)
43
- self.pix2pix_attn_proc = CrossFrameAttnProcessor(
44
- batch_size=3)
45
- self.text2video_attn_proc = CrossFrameAttnProcessor(
46
- batch_size=2)
47
 
48
  self.pipe = None
49
  self.model_type = None
@@ -58,7 +58,7 @@ class Model:
58
  gc.collect()
59
  safety_checker = kwargs.pop('safety_checker', None)
60
  self.pipe = self.pipe_dict[model_type].from_pretrained(
61
- model_id, safety_checker=safety_checker, **kwargs).to(self.device, self.dtype)
62
  self.model_type = model_type
63
  self.model_name = model_id
64
 
@@ -86,13 +86,12 @@ class Model:
86
  def inference(self, split_to_chunks=False, chunk_size=2, **kwargs):
87
  if not hasattr(self, "pipe") or self.pipe is None:
88
  return
89
- '''
90
  if "merging_ratio" in kwargs:
91
  merging_ratio = kwargs.pop("merging_ratio")
92
 
93
  # if merging_ratio > 0:
94
  tomesd.apply_patch(self.pipe, ratio=merging_ratio)
95
- '''
96
  seed = kwargs.pop('seed', 0)
97
  if seed < 0:
98
  seed = self.generator.seed()
@@ -480,19 +479,19 @@ class Model:
480
  width=resolution,
481
  num_inference_steps=50,
482
  guidance_scale=7.5,
483
- # guidance_stop_step=1.0,
484
  t0=t0,
485
  t1=t1,
486
  motion_field_strength_x=motion_field_strength_x,
487
  motion_field_strength_y=motion_field_strength_y,
488
- # use_motion_field=use_motion_field,
489
  smooth_bg=smooth_bg,
490
  smooth_bg_strength=smooth_bg_strength,
491
  seed=seed,
492
  output_type='numpy',
493
  negative_prompt=negative_prompt,
494
- # merging_ratio=merging_ratio,
495
- # split_to_chunks=True,
496
- # chunk_size=chunk_size,
497
  )
498
  return utils.create_video(result, fps, path=path, watermark=gradio_utils.logo_name_to_path(watermark))
1
  from enum import Enum
2
  import gc
3
  import numpy as np
4
+ import tomesd
5
  import torch
6
 
7
+ from diffusers import StableDiffusionInstructPix2PixPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UNet2DConditionModel
8
  from diffusers.schedulers import EulerAncestralDiscreteScheduler, DDIMScheduler
9
+ from text_to_video_pipeline import TextToVideoPipeline
10
 
11
  import utils
12
  import gradio_utils
32
  self.generator = torch.Generator(device=device)
33
  self.pipe_dict = {
34
  ModelType.Pix2Pix_Video: StableDiffusionInstructPix2PixPipeline,
35
+ ModelType.Text2Video: TextToVideoPipeline,
36
  ModelType.ControlNetCanny: StableDiffusionControlNetPipeline,
37
  ModelType.ControlNetCannyDB: StableDiffusionControlNetPipeline,
38
  ModelType.ControlNetPose: StableDiffusionControlNetPipeline,
39
  ModelType.ControlNetDepth: StableDiffusionControlNetPipeline,
40
  }
41
+ self.controlnet_attn_proc = utils.CrossFrameAttnProcessor(
42
+ unet_chunk_size=2)
43
+ self.pix2pix_attn_proc = utils.CrossFrameAttnProcessor(
44
+ unet_chunk_size=3)
45
+ self.text2video_attn_proc = utils.CrossFrameAttnProcessor(
46
+ unet_chunk_size=2)
47
 
48
  self.pipe = None
49
  self.model_type = None
58
  gc.collect()
59
  safety_checker = kwargs.pop('safety_checker', None)
60
  self.pipe = self.pipe_dict[model_type].from_pretrained(
61
+ model_id, safety_checker=safety_checker, **kwargs).to(self.device).to(self.dtype)
62
  self.model_type = model_type
63
  self.model_name = model_id
64
 
86
  def inference(self, split_to_chunks=False, chunk_size=2, **kwargs):
87
  if not hasattr(self, "pipe") or self.pipe is None:
88
  return
89
+
90
  if "merging_ratio" in kwargs:
91
  merging_ratio = kwargs.pop("merging_ratio")
92
 
93
  # if merging_ratio > 0:
94
  tomesd.apply_patch(self.pipe, ratio=merging_ratio)
 
95
  seed = kwargs.pop('seed', 0)
96
  if seed < 0:
97
  seed = self.generator.seed()
479
  width=resolution,
480
  num_inference_steps=50,
481
  guidance_scale=7.5,
482
+ guidance_stop_step=1.0,
483
  t0=t0,
484
  t1=t1,
485
  motion_field_strength_x=motion_field_strength_x,
486
  motion_field_strength_y=motion_field_strength_y,
487
+ use_motion_field=use_motion_field,
488
  smooth_bg=smooth_bg,
489
  smooth_bg_strength=smooth_bg_strength,
490
  seed=seed,
491
  output_type='numpy',
492
  negative_prompt=negative_prompt,
493
+ merging_ratio=merging_ratio,
494
+ split_to_chunks=True,
495
+ chunk_size=chunk_size,
496
  )
497
  return utils.create_video(result, fps, path=path, watermark=gradio_utils.logo_name_to_path(watermark))
requirements.txt CHANGED
@@ -3,7 +3,7 @@ addict==2.4.0
3
  albumentations==1.3.0
4
  basicsr==1.4.2
5
  decord==0.6.0
6
- diffusers==0.15.0
7
  einops==0.6.0
8
  gradio==3.23.0
9
  kornia==0.6
3
  albumentations==1.3.0
4
  basicsr==1.4.2
5
  decord==0.6.0
6
+ diffusers==0.14.0
7
  einops==0.6.0
8
  gradio==3.23.0
9
  kornia==0.6
text_to_video_pipeline.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import StableDiffusionPipeline
2
+ import torch
3
+ from dataclasses import dataclass
4
+ from typing import Callable, List, Optional, Union
5
+ import numpy as np
6
+ from diffusers.utils import deprecate, logging, BaseOutput
7
+ from einops import rearrange, repeat
8
+ from torch.nn.functional import grid_sample
9
+ import torchvision.transforms as T
10
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.schedulers import KarrasDiffusionSchedulers
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
14
+ import PIL
15
+ from PIL import Image
16
+ from kornia.morphology import dilation
17
+
18
+
19
+ @dataclass
20
+ class TextToVideoPipelineOutput(BaseOutput):
21
+ # videos: Union[torch.Tensor, np.ndarray]
22
+ # code: Union[torch.Tensor, np.ndarray]
23
+ images: Union[List[PIL.Image.Image], np.ndarray]
24
+ nsfw_content_detected: Optional[List[bool]]
25
+
26
+
27
+ def coords_grid(batch, ht, wd, device):
28
+ # Adapted from https://github.com/princeton-vl/RAFT/blob/master/core/utils/utils.py
29
+ coords = torch.meshgrid(torch.arange(
30
+ ht, device=device), torch.arange(wd, device=device))
31
+ coords = torch.stack(coords[::-1], dim=0).float()
32
+ return coords[None].repeat(batch, 1, 1, 1)
33
+
34
+
35
+ class TextToVideoPipeline(StableDiffusionPipeline):
36
+ def __init__(
37
+ self,
38
+ vae: AutoencoderKL,
39
+ text_encoder: CLIPTextModel,
40
+ tokenizer: CLIPTokenizer,
41
+ unet: UNet2DConditionModel,
42
+ scheduler: KarrasDiffusionSchedulers,
43
+ safety_checker: StableDiffusionSafetyChecker,
44
+ feature_extractor: CLIPFeatureExtractor,
45
+ requires_safety_checker: bool = True,
46
+ ):
47
+ super().__init__(vae, text_encoder, tokenizer, unet, scheduler,
48
+ safety_checker, feature_extractor, requires_safety_checker)
49
+
50
+ def DDPM_forward(self, x0, t0, tMax, generator, device, shape, text_embeddings):
51
+ rand_device = "cpu" if device.type == "mps" else device
52
+
53
+ if x0 is None:
54
+ return torch.randn(shape, generator=generator, device=rand_device, dtype=text_embeddings.dtype).to(device)
55
+ else:
56
+ eps = torch.randn(x0.shape, dtype=text_embeddings.dtype, generator=generator,
57
+ device=rand_device)
58
+ alpha_vec = torch.prod(self.scheduler.alphas[t0:tMax])
59
+
60
+ xt = torch.sqrt(alpha_vec) * x0 + \
61
+ torch.sqrt(1-alpha_vec) * eps
62
+ return xt
63
+
64
+ def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):
65
+ shape = (batch_size, num_channels_latents, video_length, height //
66
+ self.vae_scale_factor, width // self.vae_scale_factor)
67
+ if isinstance(generator, list) and len(generator) != batch_size:
68
+ raise ValueError(
69
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
70
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
71
+ )
72
+
73
+ if latents is None:
74
+ rand_device = "cpu" if device.type == "mps" else device
75
+
76
+ if isinstance(generator, list):
77
+ shape = (1,) + shape[1:]
78
+ latents = [
79
+ torch.randn(
80
+ shape, generator=generator[i], device=rand_device, dtype=dtype)
81
+ for i in range(batch_size)
82
+ ]
83
+ latents = torch.cat(latents, dim=0).to(device)
84
+ else:
85
+ latents = torch.randn(
86
+ shape, generator=generator, device=rand_device, dtype=dtype).to(device)
87
+ else:
88
+ latents = latents.to(device)
89
+
90
+ # scale the initial noise by the standard deviation required by the scheduler
91
+ latents = latents * self.scheduler.init_noise_sigma
92
+ return latents
93
+
94
+ def warp_latents_independently(self, latents, reference_flow):
95
+ _, _, H, W = reference_flow.size()
96
+ b, _, f, h, w = latents.size()
97
+ assert b == 1
98
+ coords0 = coords_grid(f, H, W, device=latents.device).to(latents.dtype)
99
+
100
+ coords_t0 = coords0 + reference_flow
101
+ coords_t0[:, 0] /= W
102
+ coords_t0[:, 1] /= H
103
+
104
+ coords_t0 = coords_t0 * 2.0 - 1.0
105
+
106
+ coords_t0 = T.Resize((h, w))(coords_t0)
107
+
108
+ coords_t0 = rearrange(coords_t0, 'f c h w -> f h w c')
109
+
110
+ latents_0 = rearrange(latents[0], 'c f h w -> f c h w')
111
+ warped = grid_sample(latents_0, coords_t0,
112
+ mode='nearest', padding_mode='reflection')
113
+
114
+ warped = rearrange(warped, '(b f) c h w -> b c f h w', f=f)
115
+ return warped
116
+
117
+ def DDIM_backward(self, num_inference_steps, timesteps, skip_t, t0, t1, do_classifier_free_guidance, null_embs, text_embeddings, latents_local,
118
+ latents_dtype, guidance_scale, guidance_stop_step, callback, callback_steps, extra_step_kwargs, num_warmup_steps):
119
+ entered = False
120
+
121
+ f = latents_local.shape[2]
122
+
123
+ latents_local = rearrange(latents_local, "b c f w h -> (b f) c w h")
124
+
125
+ latents = latents_local.detach().clone()
126
+ x_t0_1 = None
127
+ x_t1_1 = None
128
+
129
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
130
+ for i, t in enumerate(timesteps):
131
+ if t > skip_t:
132
+ continue
133
+ else:
134
+ if not entered:
135
+ print(
136
+ f"Continue DDIM with i = {i}, t = {t}, latent = {latents.shape}, device = {latents.device}, type = {latents.dtype}")
137
+ entered = True
138
+
139
+ latents = latents.detach()
140
+ # expand the latents if we are doing classifier free guidance
141
+ latent_model_input = torch.cat(
142
+ [latents] * 2) if do_classifier_free_guidance else latents
143
+ latent_model_input = self.scheduler.scale_model_input(
144
+ latent_model_input, t)
145
+
146
+ # predict the noise residual
147
+ with torch.no_grad():
148
+ if null_embs is not None:
149
+ text_embeddings[0] = null_embs[i][0]
150
+ te = torch.cat([repeat(text_embeddings[0, :, :], "c k -> f c k", f=f),
151
+ repeat(text_embeddings[1, :, :], "c k -> f c k", f=f)])
152
+ noise_pred = self.unet(
153
+ latent_model_input, t, encoder_hidden_states=te).sample.to(dtype=latents_dtype)
154
+
155
+ # perform guidance
156
+ if do_classifier_free_guidance:
157
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(
158
+ 2)
159
+ noise_pred = noise_pred_uncond + guidance_scale * \
160
+ (noise_pred_text - noise_pred_uncond)
161
+
162
+ if i >= guidance_stop_step * len(timesteps):
163
+ alpha = 0
164
+ # compute the previous noisy sample x_t -> x_t-1
165
+ latents = self.scheduler.step(
166
+ noise_pred, t, latents, **extra_step_kwargs).prev_sample
167
+ # latents = latents - alpha * grads / (torch.norm(grads) + 1e-10)
168
+ # call the callback, if provided
169
+
170
+ if i < len(timesteps)-1 and timesteps[i+1] == t0:
171
+ x_t0_1 = latents.detach().clone()
172
+ print(f"latent t0 found at i = {i}, t = {t}")
173
+ elif i < len(timesteps)-1 and timesteps[i+1] == t1:
174
+ x_t1_1 = latents.detach().clone()
175
+ print(f"latent t1 found at i={i}, t = {t}")
176
+
177
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
178
+ progress_bar.update()
179
+ if callback is not None and i % callback_steps == 0:
180
+ callback(i, t, latents)
181
+
182
+ latents = rearrange(latents, "(b f) c w h -> b c f w h", f=f)
183
+
184
+ res = {"x0": latents.detach().clone()}
185
+ if x_t0_1 is not None:
186
+ x_t0_1 = rearrange(x_t0_1, "(b f) c w h -> b c f w h", f=f)
187
+ res["x_t0_1"] = x_t0_1.detach().clone()
188
+ if x_t1_1 is not None:
189
+ x_t1_1 = rearrange(x_t1_1, "(b f) c w h -> b c f w h", f=f)
190
+ res["x_t1_1"] = x_t1_1.detach().clone()
191
+ return res
192
+
193
+ def decode_latents(self, latents):
194
+ video_length = latents.shape[2]
195
+ latents = 1 / 0.18215 * latents
196
+ latents = rearrange(latents, "b c f h w -> (b f) c h w")
197
+ video = self.vae.decode(latents).sample
198
+ video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
199
+ video = (video / 2 + 0.5).clamp(0, 1)
200
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
201
+ video = video.detach().cpu()
202
+ return video
203
+
204
+ def create_motion_field(self, motion_field_strength_x, motion_field_strength_y, frame_ids, video_length, latents):
205
+
206
+ reference_flow = torch.zeros(
207
+ (video_length-1, 2, 512, 512), device=latents.device, dtype=latents.dtype)
208
+ for fr_idx, frame_id in enumerate(frame_ids):
209
+ reference_flow[fr_idx, 0, :,
210
+ :] = motion_field_strength_x*(frame_id)
211
+ reference_flow[fr_idx, 1, :,
212
+ :] = motion_field_strength_y*(frame_id)
213
+ return reference_flow
214
+
215
+ def create_motion_field_and_warp_latents(self, motion_field_strength_x, motion_field_strength_y, frame_ids, video_length, latents):
216
+
217
+ motion_field = self.create_motion_field(motion_field_strength_x=motion_field_strength_x,
218
+ motion_field_strength_y=motion_field_strength_y, latents=latents, video_length=video_length, frame_ids=frame_ids)
219
+ for idx, latent in enumerate(latents):
220
+ latents[idx] = self.warp_latents_independently(
221
+ latent[None], motion_field)
222
+ return motion_field, latents
223
+
224
+ @torch.no_grad()
225
+ def __call__(
226
+ self,
227
+ prompt: Union[str, List[str]],
228
+ video_length: Optional[int],
229
+ height: Optional[int] = None,
230
+ width: Optional[int] = None,
231
+ num_inference_steps: int = 50,
232
+ guidance_scale: float = 7.5,
233
+ guidance_stop_step: float = 0.5,
234
+ negative_prompt: Optional[Union[str, List[str]]] = None,
235
+ num_videos_per_prompt: Optional[int] = 1,
236
+ eta: float = 0.0,
237
+ generator: Optional[Union[torch.Generator,
238
+ List[torch.Generator]]] = None,
239
+ xT: Optional[torch.FloatTensor] = None,
240
+ null_embs: Optional[torch.FloatTensor] = None,
241
+ motion_field_strength_x: float = 12,
242
+ motion_field_strength_y: float = 12,
243
+ output_type: Optional[str] = "tensor",
244
+ return_dict: bool = True,
245
+ callback: Optional[Callable[[
246
+ int, int, torch.FloatTensor], None]] = None,
247
+ callback_steps: Optional[int] = 1,
248
+ use_motion_field: bool = True,
249
+ smooth_bg: bool = False,
250
+ smooth_bg_strength: float = 0.4,
251
+ t0: int = 44,
252
+ t1: int = 47,
253
+ **kwargs,
254
+ ):
255
+ frame_ids = kwargs.pop("frame_ids", list(range(video_length)))
256
+ assert t0 < t1
257
+ assert num_videos_per_prompt == 1
258
+ assert isinstance(prompt, list) and len(prompt) > 0
259
+ assert isinstance(negative_prompt, list) or negative_prompt is None
260
+
261
+ prompt_types = [prompt, negative_prompt]
262
+
263
+ for idx, prompt_type in enumerate(prompt_types):
264
+ prompt_template = None
265
+ for prompt in prompt_type:
266
+ if prompt_template is None:
267
+ prompt_template = prompt
268
+ else:
269
+ assert prompt == prompt_template
270
+ if prompt_types[idx] is not None:
271
+ prompt_types[idx] = prompt_types[idx][0]
272
+ prompt = prompt_types[0]
273
+ negative_prompt = prompt_types[1]
274
+
275
+ # Default height and width to unet
276
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
277
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
278
+
279
+ # Check inputs. Raise error if not correct
280
+ self.check_inputs(prompt, height, width, callback_steps)
281
+
282
+ # Define call parameters
283
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
284
+ device = self._execution_device
285
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
286
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
287
+ # corresponds to doing no classifier free guidance.
288
+ do_classifier_free_guidance = guidance_scale > 1.0
289
+
290
+ # Encode input prompt
291
+ text_embeddings = self._encode_prompt(
292
+ prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
293
+ )
294
+
295
+ # Prepare timesteps
296
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
297
+ timesteps = self.scheduler.timesteps
298
+
299
+ # print(f" Latent shape = {latents.shape}")
300
+
301
+ # Prepare latent variables
302
+ num_channels_latents = self.unet.in_channels
303
+
304
+ xT = self.prepare_latents(
305
+ batch_size * num_videos_per_prompt,
306
+ num_channels_latents,
307
+ 1,
308
+ height,
309
+ width,
310
+ text_embeddings.dtype,
311
+ device,
312
+ generator,
313
+ xT,
314
+ )
315
+ dtype = xT.dtype
316
+
317
+ # when motion field is not used, augment with random latent codes
318
+ if use_motion_field:
319
+ xT = xT[:, :, :1]
320
+ else:
321
+ if xT.shape[2] < video_length:
322
+ xT_missing = self.prepare_latents(
323
+ batch_size * num_videos_per_prompt,
324
+ num_channels_latents,
325
+ video_length-xT.shape[2],
326
+ height,
327
+ width,
328
+ text_embeddings.dtype,
329
+ device,
330
+ generator,
331
+ None,
332
+ )
333
+ xT = torch.cat([xT, xT_missing], dim=2)
334
+
335
+ xInit = xT.clone()
336
+
337
+ timesteps_ddpm = [981, 961, 941, 921, 901, 881, 861, 841, 821, 801, 781, 761, 741, 721,
338
+ 701, 681, 661, 641, 621, 601, 581, 561, 541, 521, 501, 481, 461, 441,
339
+ 421, 401, 381, 361, 341, 321, 301, 281, 261, 241, 221, 201, 181, 161,
340
+ 141, 121, 101, 81, 61, 41, 21, 1]
341
+ timesteps_ddpm.reverse()
342
+
343
+ t0 = timesteps_ddpm[t0]
344
+ t1 = timesteps_ddpm[t1]
345
+
346
+ print(f"t0 = {t0} t1 = {t1}")
347
+ x_t1_1 = None
348
+
349
+ # Prepare extra step kwargs.
350
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
351
+ # Denoising loop
352
+ num_warmup_steps = len(timesteps) - \
353
+ num_inference_steps * self.scheduler.order
354
+
355
+ shape = (batch_size, num_channels_latents, 1, height //
356
+ self.vae_scale_factor, width // self.vae_scale_factor)
357
+
358
+ ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=1000, t0=t0, t1=t1, do_classifier_free_guidance=do_classifier_free_guidance,
359
+ null_embs=null_embs, text_embeddings=text_embeddings, latents_local=xT, latents_dtype=dtype, guidance_scale=guidance_scale, guidance_stop_step=guidance_stop_step,
360
+ callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
361
+
362
+ x0 = ddim_res["x0"].detach()
363
+
364
+ if "x_t0_1" in ddim_res:
365
+ x_t0_1 = ddim_res["x_t0_1"].detach()
366
+ if "x_t1_1" in ddim_res:
367
+ x_t1_1 = ddim_res["x_t1_1"].detach()
368
+ del ddim_res
369
+ del xT
370
+ if use_motion_field:
371
+ del x0
372
+
373
+ x_t0_k = x_t0_1[:, :, :1, :, :].repeat(1, 1, video_length-1, 1, 1)
374
+
375
+ reference_flow, x_t0_k = self.create_motion_field_and_warp_latents(
376
+ motion_field_strength_x=motion_field_strength_x, motion_field_strength_y=motion_field_strength_y, latents=x_t0_k, video_length=video_length, frame_ids=frame_ids[1:])
377
+
378
+ # assuming t0=t1=1000, if t0 = 1000
379
+ if t1 > t0:
380
+ x_t1_k = self.DDPM_forward(
381
+ x0=x_t0_k, t0=t0, tMax=t1, device=device, shape=shape, text_embeddings=text_embeddings, generator=generator)
382
+ else:
383
+ x_t1_k = x_t0_k
384
+
385
+ if x_t1_1 is None:
386
+ raise Exception
387
+
388
+ x_t1 = torch.cat([x_t1_1, x_t1_k], dim=2).clone().detach()
389
+
390
+ ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
391
+ null_embs=null_embs, text_embeddings=text_embeddings, latents_local=x_t1, latents_dtype=dtype, guidance_scale=guidance_scale,
392
+ guidance_stop_step=guidance_stop_step, callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
393
+
394
+ x0 = ddim_res["x0"].detach()
395
+ del ddim_res
396
+ del x_t1
397
+ del x_t1_1
398
+ del x_t1_k
399
+ else:
400
+ x_t1 = x_t1_1.clone()
401
+ x_t1_1 = x_t1_1[:, :, :1, :, :].clone()
402
+ x_t1_k = x_t1_1[:, :, 1:, :, :].clone()
403
+ x_t0_k = x_t0_1[:, :, 1:, :, :].clone()
404
+ x_t0_1 = x_t0_1[:, :, :1, :, :].clone()
405
+
406
+ # smooth background
407
+ if smooth_bg:
408
+ h, w = x0.shape[3], x0.shape[4]
409
+ M_FG = torch.zeros((batch_size, video_length, h, w),
410
+ device=x0.device).to(x0.dtype)
411
+ for batch_idx, x0_b in enumerate(x0):
412
+ z0_b = self.decode_latents(x0_b[None]).detach()
413
+ z0_b = rearrange(z0_b[0], "c f h w -> f h w c")
414
+ for frame_idx, z0_f in enumerate(z0_b):
415
+ z0_f = torch.round(
416
+ z0_f * 255).cpu().numpy().astype(np.uint8)
417
+ # apply SOD detection
418
+ m_f = torch.tensor(self.sod_model.process_data(
419
+ z0_f), device=x0.device).to(x0.dtype)
420
+ mask = T.Resize(
421
+ size=(h, w), interpolation=T.InterpolationMode.NEAREST)(m_f[None])
422
+ kernel = torch.ones(5, 5, device=x0.device, dtype=x0.dtype)
423
+ mask = dilation(mask[None].to(x0.device), kernel)[0]
424
+ M_FG[batch_idx, frame_idx, :, :] = mask
425
+
426
+ x_t1_1_fg_masked = x_t1_1 * \
427
+ (1 - repeat(M_FG[:, 0, :, :],
428
+ "b w h -> b c 1 w h", c=x_t1_1.shape[1]))
429
+
430
+ x_t1_1_fg_masked_moved = []
431
+ for batch_idx, x_t1_1_fg_masked_b in enumerate(x_t1_1_fg_masked):
432
+ x_t1_fg_masked_b = x_t1_1_fg_masked_b.clone()
433
+
434
+ x_t1_fg_masked_b = x_t1_fg_masked_b.repeat(
435
+ 1, video_length-1, 1, 1)
436
+ if use_motion_field:
437
+ x_t1_fg_masked_b = x_t1_fg_masked_b[None]
438
+ x_t1_fg_masked_b = self.warp_latents_independently(
439
+ x_t1_fg_masked_b, reference_flow)
440
+ else:
441
+ x_t1_fg_masked_b = x_t1_fg_masked_b[None]
442
+
443
+ x_t1_fg_masked_b = torch.cat(
444
+ [x_t1_1_fg_masked_b[None], x_t1_fg_masked_b], dim=2)
445
+ x_t1_1_fg_masked_moved.append(x_t1_fg_masked_b)
446
+
447
+ x_t1_1_fg_masked_moved = torch.cat(x_t1_1_fg_masked_moved, dim=0)
448
+
449
+ M_FG_1 = M_FG[:, :1, :, :]
450
+
451
+ M_FG_warped = []
452
+ for batch_idx, m_fg_1_b in enumerate(M_FG_1):
453
+ m_fg_1_b = m_fg_1_b[None, None]
454
+ m_fg_b = m_fg_1_b.repeat(1, 1, video_length-1, 1, 1)
455
+ if use_motion_field:
456
+ m_fg_b = self.warp_latents_independently(
457
+ m_fg_b.clone(), reference_flow)
458
+ M_FG_warped.append(
459
+ torch.cat([m_fg_1_b[:1, 0], m_fg_b[:1, 0]], dim=1))
460
+
461
+ M_FG_warped = torch.cat(M_FG_warped, dim=0)
462
+
463
+ channels = x0.shape[1]
464
+
465
+ M_BG = (1-M_FG) * (1 - M_FG_warped)
466
+ M_BG = repeat(M_BG, "b f h w -> b c f h w", c=channels)
467
+ a_convex = smooth_bg_strength
468
+
469
+ latents = (1-M_BG) * x_t1 + M_BG * (a_convex *
470
+ x_t1 + (1-a_convex) * x_t1_1_fg_masked_moved)
471
+
472
+ ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
473
+ null_embs=null_embs, text_embeddings=text_embeddings, latents_local=latents, latents_dtype=dtype, guidance_scale=guidance_scale,
474
+ guidance_stop_step=guidance_stop_step, callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
475
+ x0 = ddim_res["x0"].detach()
476
+ del ddim_res
477
+ del latents
478
+
479
+ latents = x0
480
+
481
+ # manually for max memory savings
482
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
483
+ self.unet.to("cpu")
484
+ torch.cuda.empty_cache()
485
+
486
+ if output_type == "latent":
487
+ image = latents
488
+ has_nsfw_concept = None
489
+ else:
490
+ image = self.decode_latents(latents)
491
+
492
+ # Run safety checker
493
+ image, has_nsfw_concept = self.run_safety_checker(
494
+ image, device, text_embeddings.dtype)
495
+ image = rearrange(image, "b c f h w -> (b f) h w c")
496
+
497
+ # Offload last model to CPU
498
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
499
+ self.final_offload_hook.offload()
500
+
501
+ if not return_dict:
502
+ return (image, has_nsfw_concept)
503
+
504
+ return TextToVideoPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
utils.py CHANGED
@@ -133,6 +133,40 @@ def create_gif(frames, fps, rescale=False, path=None, watermark=None):
133
  imageio.mimsave(path, outputs, fps=fps)
134
  return path
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True, start_t:float=0, end_t:float=-1, output_fps:int=-1):
137
  vr = decord.VideoReader(video_path)
138
  initial_fps = vr.get_avg_fps()
@@ -178,8 +212,57 @@ def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True,
178
 
179
  return video, output_fps
180
 
181
-
182
  def post_process_gif(list_of_results, image_resolution):
183
  output_file = "/tmp/ddxk.gif"
184
  imageio.mimsave(output_file, list_of_results, fps=4)
185
  return output_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  imageio.mimsave(path, outputs, fps=fps)
134
  return path
135
 
136
+ # def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True, start_t:float=0, end_t:float=-1, output_fps:int=-1):
137
+ # vr = decord.VideoReader(video_path)
138
+ # video = vr.get_batch(range(0, len(vr))).asnumpy()
139
+ # initial_fps = vr.get_avg_fps()
140
+ # if output_fps == -1:
141
+ # output_fps = int(initial_fps)
142
+ # if end_t == -1:
143
+ # end_t = len(vr) / initial_fps
144
+ # else:
145
+ # end_t = min(len(vr) / initial_fps, end_t)
146
+ # assert 0 <= start_t < end_t
147
+ # assert output_fps > 0
148
+ # f, h, w, c = video.shape
149
+ # start_f_ind = int(start_t * initial_fps)
150
+ # end_f_ind = int(end_t * initial_fps)
151
+ # num_f = int((end_t - start_t) * output_fps)
152
+ # sample_idx = np.linspace(start_f_ind, end_f_ind, num_f, endpoint=False).astype(int)
153
+ # video = video[sample_idx]
154
+ # video = rearrange(video, "f h w c -> f c h w")
155
+ # video = torch.Tensor(video).to(device).to(dtype)
156
+ # if h > w:
157
+ # w = int(w * resolution / h)
158
+ # w = w - w % 8
159
+ # h = resolution - resolution % 8
160
+ # video = Resize((h, w))(video)
161
+ # else:
162
+ # h = int(h * resolution / w)
163
+ # h = h - h % 8
164
+ # w = resolution - resolution % 8
165
+ # video = Resize((h, w))(video)
166
+ # if normalize:
167
+ # video = video / 127.5 - 1.0
168
+ # return video, output_fps
169
+
170
  def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True, start_t:float=0, end_t:float=-1, output_fps:int=-1):
171
  vr = decord.VideoReader(video_path)
172
  initial_fps = vr.get_avg_fps()
212
 
213
  return video, output_fps
214
 
 
215
  def post_process_gif(list_of_results, image_resolution):
216
  output_file = "/tmp/ddxk.gif"
217
  imageio.mimsave(output_file, list_of_results, fps=4)
218
  return output_file
219
+
220
+
221
+ class CrossFrameAttnProcessor:
222
+ def __init__(self, unet_chunk_size=2):
223
+ self.unet_chunk_size = unet_chunk_size
224
+
225
+ def __call__(
226
+ self,
227
+ attn,
228
+ hidden_states,
229
+ encoder_hidden_states=None,
230
+ attention_mask=None):
231
+ batch_size, sequence_length, _ = hidden_states.shape
232
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
233
+ query = attn.to_q(hidden_states)
234
+
235
+ is_cross_attention = encoder_hidden_states is not None
236
+ if encoder_hidden_states is None:
237
+ encoder_hidden_states = hidden_states
238
+ elif attn.cross_attention_norm:
239
+ encoder_hidden_states = attn.norm_cross(encoder_hidden_states)
240
+ key = attn.to_k(encoder_hidden_states)
241
+ value = attn.to_v(encoder_hidden_states)
242
+ # Sparse Attention
243
+ if not is_cross_attention:
244
+ video_length = key.size()[0] // self.unet_chunk_size
245
+ # former_frame_index = torch.arange(video_length) - 1
246
+ # former_frame_index[0] = 0
247
+ former_frame_index = [0] * video_length
248
+ key = rearrange(key, "(b f) d c -> b f d c", f=video_length)
249
+ key = key[:, former_frame_index]
250
+ key = rearrange(key, "b f d c -> (b f) d c")
251
+ value = rearrange(value, "(b f) d c -> b f d c", f=video_length)
252
+ value = value[:, former_frame_index]
253
+ value = rearrange(value, "b f d c -> (b f) d c")
254
+
255
+ query = attn.head_to_batch_dim(query)
256
+ key = attn.head_to_batch_dim(key)
257
+ value = attn.head_to_batch_dim(value)
258
+
259
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
260
+ hidden_states = torch.bmm(attention_probs, value)
261
+ hidden_states = attn.batch_to_head_dim(hidden_states)
262
+
263
+ # linear proj
264
+ hidden_states = attn.to_out[0](hidden_states)
265
+ # dropout
266
+ hidden_states = attn.to_out[1](hidden_states)
267
+
268
+ return hidden_states