quantumos commited on
Commit
44492b2
·
verified ·
1 Parent(s): 4c65234

Upload 8 files

Browse files
pipelines/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .v_express_pipeline import VExpressPipeline
pipelines/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (212 Bytes). View file
 
pipelines/__pycache__/context.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
pipelines/__pycache__/utils.cpython-310.pyc ADDED
Binary file (5.61 kB). View file
 
pipelines/__pycache__/v_express_pipeline.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
pipelines/context.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO: Adapted from cli
2
+ from typing import Callable, List, Optional
3
+
4
+ import numpy as np
5
+
6
+
7
+ def ordered_halving(val):
8
+ bin_str = f"{val:064b}"
9
+ bin_flip = bin_str[::-1]
10
+ as_int = int(bin_flip, 2)
11
+
12
+ return as_int / (1 << 64)
13
+
14
+
15
+ def uniform(
16
+ step: int = ...,
17
+ num_steps: Optional[int] = None,
18
+ num_frames: int = ...,
19
+ context_size: Optional[int] = None,
20
+ context_stride: int = 3,
21
+ context_overlap: int = 4,
22
+ closed_loop: bool = True,
23
+ ):
24
+ if num_frames <= context_size:
25
+ yield list(range(num_frames))
26
+ return
27
+
28
+ context_stride = min(
29
+ context_stride, int(np.ceil(np.log2(num_frames / context_size))) + 1
30
+ )
31
+
32
+ for context_step in 1 << np.arange(context_stride):
33
+ pad = int(round(num_frames * ordered_halving(step)))
34
+ for j in range(
35
+ int(ordered_halving(step) * context_step) + pad,
36
+ num_frames + pad + (0 if closed_loop else -context_overlap),
37
+ (context_size * context_step - context_overlap),
38
+ ):
39
+ next_itr = []
40
+ for e in range(j, j + context_size * context_step, context_step):
41
+ if e >= num_frames:
42
+ e = num_frames - 2 - e % num_frames
43
+ next_itr.append(e)
44
+
45
+ yield next_itr
46
+
47
+
48
+ def get_context_scheduler(name: str) -> Callable:
49
+ if name == "uniform":
50
+ return uniform
51
+ else:
52
+ raise ValueError(f"Unknown context_overlap policy {name}")
53
+
54
+
55
+ def get_total_steps(
56
+ scheduler,
57
+ timesteps: List[int],
58
+ num_steps: Optional[int] = None,
59
+ num_frames: int = ...,
60
+ context_size: Optional[int] = None,
61
+ context_stride: int = 3,
62
+ context_overlap: int = 4,
63
+ closed_loop: bool = True,
64
+ ):
65
+ return sum(
66
+ len(
67
+ list(
68
+ scheduler(
69
+ i,
70
+ num_steps,
71
+ num_frames,
72
+ context_size,
73
+ context_stride,
74
+ context_overlap,
75
+ )
76
+ )
77
+ )
78
+ for i in range(len(timesteps))
79
+ )
pipelines/utils.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import pathlib
4
+
5
+ import cv2
6
+ import numpy as np
7
+ import os
8
+
9
+ from imageio_ffmpeg import get_ffmpeg_exe
10
+ from scipy.ndimage import median_filter
11
+
12
+
13
+ tensor_interpolation = None
14
+
15
+
16
+ def get_tensor_interpolation_method():
17
+ return tensor_interpolation
18
+
19
+
20
+ def set_tensor_interpolation_method(is_slerp):
21
+ global tensor_interpolation
22
+ tensor_interpolation = slerp if is_slerp else linear
23
+
24
+
25
+ def linear(v1, v2, t):
26
+ return (1.0 - t) * v1 + t * v2
27
+
28
+
29
+ def slerp(
30
+ v0: torch.Tensor, v1: torch.Tensor, t: float, DOT_THRESHOLD: float = 0.9995
31
+ ) -> torch.Tensor:
32
+ u0 = v0 / v0.norm()
33
+ u1 = v1 / v1.norm()
34
+ dot = (u0 * u1).sum()
35
+ if dot.abs() > DOT_THRESHOLD:
36
+ # logger.info(f'warning: v0 and v1 close to parallel, using linear interpolation instead.')
37
+ return (1.0 - t) * v0 + t * v1
38
+ omega = dot.acos()
39
+ return (((1.0 - t) * omega).sin() * v0 + (t * omega).sin() * v1) / omega.sin()
40
+
41
+
42
+ def draw_kps_image(image, kps, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255)]):
43
+ stick_width = 4
44
+ limb_seq = np.array([[0, 2], [1, 2]])
45
+ kps = np.array(kps)
46
+
47
+ canvas = image
48
+
49
+ for i in range(len(limb_seq)):
50
+ index = limb_seq[i]
51
+ color = color_list[index[0]]
52
+
53
+ x = kps[index][:, 0]
54
+ y = kps[index][:, 1]
55
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
56
+ angle = int(math.degrees(math.atan2(y[0] - y[1], x[0] - x[1])))
57
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stick_width), angle, 0, 360, 1)
58
+ cv2.fillConvexPoly(canvas, polygon, [int(float(c) * 0.6) for c in color])
59
+
60
+ for idx_kp, kp in enumerate(kps):
61
+ color = color_list[idx_kp]
62
+ x, y = kp
63
+ cv2.circle(canvas, (int(x), int(y)), 4, color, -1)
64
+
65
+ return canvas
66
+
67
+
68
+ def save_video(video_tensor, audio_path, output_path, fps=30.0):
69
+ pathlib.Path(output_path).parent.mkdir(exist_ok=True, parents=True)
70
+
71
+ video_tensor = video_tensor[0, ...]
72
+ _, num_frames, height, width = video_tensor.shape
73
+
74
+ video_tensor = video_tensor.permute(1, 2, 3, 0)
75
+ video_np = (video_tensor * 255).numpy().astype(np.uint8)
76
+ video_np_filtered = median_filter(video_np, size=(3, 3, 3, 1))
77
+
78
+ output_name = pathlib.Path(output_path).stem
79
+ temp_output_path = output_path.replace(output_name, output_name + '-temp')
80
+ video_writer = cv2.VideoWriter(temp_output_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
81
+
82
+ for i in range(num_frames):
83
+ frame_image = video_np_filtered[i]
84
+ frame_image = cv2.cvtColor(frame_image, cv2.COLOR_RGB2BGR)
85
+ video_writer.write(frame_image)
86
+ video_writer.release()
87
+
88
+ cmd = (f'{get_ffmpeg_exe()} -i "{temp_output_path}" -i "{audio_path}" '
89
+ f'-map 0:v -map 1:a -c:v h264 -shortest -y "{output_path}" -loglevel quiet')
90
+ os.system(cmd)
91
+ os.remove(temp_output_path)
92
+
93
+
94
+ def compute_dist(x1, y1, x2, y2):
95
+ return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
96
+
97
+
98
+ def compute_ratio(kps):
99
+ l_eye_x, l_eye_y = kps[0][0], kps[0][1]
100
+ r_eye_x, r_eye_y = kps[1][0], kps[1][1]
101
+ nose_x, nose_y = kps[2][0], kps[2][1]
102
+ d_left = compute_dist(l_eye_x, l_eye_y, nose_x, nose_y)
103
+ d_right = compute_dist(r_eye_x, r_eye_y, nose_x, nose_y)
104
+ ratio = d_left / (d_right + 1e-6)
105
+ return ratio
106
+
107
+
108
+ def point_to_line_dist(point, line_points):
109
+ point = np.array(point)
110
+ line_points = np.array(line_points)
111
+ line_vec = line_points[1] - line_points[0]
112
+ point_vec = point - line_points[0]
113
+ line_norm = line_vec / np.sqrt(np.sum(line_vec ** 2))
114
+ point_vec_scaled = point_vec * 1.0 / np.sqrt(np.sum(line_vec ** 2))
115
+ t = np.dot(line_norm, point_vec_scaled)
116
+ if t < 0.0:
117
+ t = 0.0
118
+ elif t > 1.0:
119
+ t = 1.0
120
+ nearest = line_points[0] + t * line_vec
121
+ dist = np.sqrt(np.sum((point - nearest) ** 2))
122
+ return dist
123
+
124
+
125
+ def get_face_size(kps):
126
+ # 0: left eye, 1: right eye, 2: nose
127
+ A = kps[0, :]
128
+ B = kps[1, :]
129
+ C = kps[2, :]
130
+
131
+ AB_dist = math.sqrt((A[0] - B[0])**2 + (A[1] - B[1])**2)
132
+ C_AB_dist = point_to_line_dist(C, [A, B])
133
+ return AB_dist, C_AB_dist
134
+
135
+
136
+ def get_rescale_params(kps_ref, kps_target):
137
+ kps_ref = np.array(kps_ref)
138
+ kps_target = np.array(kps_target)
139
+
140
+ ref_AB_dist, ref_C_AB_dist = get_face_size(kps_ref)
141
+ target_AB_dist, target_C_AB_dist = get_face_size(kps_target)
142
+
143
+ scale_width = ref_AB_dist / target_AB_dist
144
+ scale_height = ref_C_AB_dist / target_C_AB_dist
145
+
146
+ return scale_width, scale_height
147
+
148
+
149
+ def retarget_kps(ref_kps, tgt_kps_list, only_offset=True):
150
+ ref_kps = np.array(ref_kps)
151
+ tgt_kps_list = np.array(tgt_kps_list)
152
+
153
+ ref_ratio = compute_ratio(ref_kps)
154
+
155
+ ratio_delta = 10000
156
+ selected_tgt_kps_idx = None
157
+ for idx, tgt_kps in enumerate(tgt_kps_list):
158
+ tgt_ratio = compute_ratio(tgt_kps)
159
+ if math.fabs(tgt_ratio - ref_ratio) < ratio_delta:
160
+ selected_tgt_kps_idx = idx
161
+ ratio_delta = tgt_ratio
162
+
163
+ scale_width, scale_height = get_rescale_params(
164
+ kps_ref=ref_kps,
165
+ kps_target=tgt_kps_list[selected_tgt_kps_idx],
166
+ )
167
+
168
+ rescaled_tgt_kps_list = np.array(tgt_kps_list)
169
+ rescaled_tgt_kps_list[:, :, 0] *= scale_width
170
+ rescaled_tgt_kps_list[:, :, 1] *= scale_height
171
+
172
+ if only_offset:
173
+ nose_offset = rescaled_tgt_kps_list[:, 2, :] - rescaled_tgt_kps_list[0, 2, :]
174
+ nose_offset = nose_offset[:, np.newaxis, :]
175
+ ref_kps_repeat = np.tile(ref_kps, (tgt_kps_list.shape[0], 1, 1))
176
+
177
+ ref_kps_repeat[:, :, :] -= (nose_offset / 2.0)
178
+ rescaled_tgt_kps_list = ref_kps_repeat
179
+ else:
180
+ nose_offset_x = rescaled_tgt_kps_list[0, 2, 0] - ref_kps[2][0]
181
+ nose_offset_y = rescaled_tgt_kps_list[0, 2, 1] - ref_kps[2][1]
182
+
183
+ rescaled_tgt_kps_list[:, :, 0] -= nose_offset_x
184
+ rescaled_tgt_kps_list[:, :, 1] -= nose_offset_y
185
+
186
+ return rescaled_tgt_kps_list
pipelines/v_express_pipeline.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/magic-research/magic-animate/blob/main/magicanimate/pipelines/pipeline_animation.py
2
+ import inspect
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from diffusers import DiffusionPipeline
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ from diffusers.schedulers import (
12
+ DDIMScheduler,
13
+ DPMSolverMultistepScheduler,
14
+ EulerAncestralDiscreteScheduler,
15
+ EulerDiscreteScheduler,
16
+ LMSDiscreteScheduler,
17
+ PNDMScheduler,
18
+ )
19
+ from diffusers.utils import BaseOutput, is_accelerate_available
20
+ from diffusers.utils.torch_utils import randn_tensor
21
+ from einops import rearrange
22
+ from tqdm import tqdm
23
+ from transformers import CLIPImageProcessor
24
+
25
+ from modules import ReferenceAttentionControl
26
+ from .context import get_context_scheduler
27
+ from .utils import get_tensor_interpolation_method
28
+
29
+
30
+ def retrieve_timesteps(
31
+ scheduler,
32
+ num_inference_steps: Optional[int] = None,
33
+ device: Optional[Union[str, torch.device]] = None,
34
+ timesteps: Optional[List[int]] = None,
35
+ **kwargs,
36
+ ):
37
+ """
38
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
39
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
40
+
41
+ Args:
42
+ scheduler (`SchedulerMixin`):
43
+ The scheduler to get timesteps from.
44
+ num_inference_steps (`int`):
45
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
46
+ `timesteps` must be `None`.
47
+ device (`str` or `torch.device`, *optional*):
48
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
49
+ timesteps (`List[int]`, *optional*):
50
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
51
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
52
+ must be `None`.
53
+
54
+ Returns:
55
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
56
+ second element is the number of inference steps.
57
+ """
58
+ if timesteps is not None:
59
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
60
+ if not accepts_timesteps:
61
+ raise ValueError(
62
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
63
+ f" timestep schedules. Please check whether you are using the correct scheduler."
64
+ )
65
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
66
+ timesteps = scheduler.timesteps
67
+ num_inference_steps = len(timesteps)
68
+ else:
69
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
70
+ timesteps = scheduler.timesteps
71
+ return timesteps, num_inference_steps
72
+
73
+
74
+ @dataclass
75
+ class PipelineOutput(BaseOutput):
76
+ video_latents: Union[torch.Tensor, np.ndarray]
77
+
78
+
79
+ class VExpressPipeline(DiffusionPipeline):
80
+ _optional_components = []
81
+
82
+ def __init__(
83
+ self,
84
+ vae,
85
+ reference_net,
86
+ denoising_unet,
87
+ v_kps_guider,
88
+ audio_processor,
89
+ audio_encoder,
90
+ audio_projection,
91
+ scheduler: Union[
92
+ DDIMScheduler,
93
+ PNDMScheduler,
94
+ LMSDiscreteScheduler,
95
+ EulerDiscreteScheduler,
96
+ EulerAncestralDiscreteScheduler,
97
+ DPMSolverMultistepScheduler,
98
+ ],
99
+ image_proj_model=None,
100
+ tokenizer=None,
101
+ text_encoder=None,
102
+ ):
103
+ super().__init__()
104
+
105
+ self.register_modules(
106
+ vae=vae,
107
+ reference_net=reference_net,
108
+ denoising_unet=denoising_unet,
109
+ v_kps_guider=v_kps_guider,
110
+ audio_processor=audio_processor,
111
+ audio_encoder=audio_encoder,
112
+ audio_projection=audio_projection,
113
+ scheduler=scheduler,
114
+ image_proj_model=image_proj_model,
115
+ tokenizer=tokenizer,
116
+ text_encoder=text_encoder,
117
+ )
118
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
119
+ self.clip_image_processor = CLIPImageProcessor()
120
+ self.reference_image_processor = VaeImageProcessor(
121
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True
122
+ )
123
+ self.condition_image_processor = VaeImageProcessor(
124
+ vae_scale_factor=self.vae_scale_factor,
125
+ do_convert_rgb=True,
126
+ do_normalize=False,
127
+ )
128
+
129
+ def enable_vae_slicing(self):
130
+ self.vae.enable_slicing()
131
+
132
+ def disable_vae_slicing(self):
133
+ self.vae.disable_slicing()
134
+
135
+ def enable_sequential_cpu_offload(self, gpu_id=0):
136
+ if is_accelerate_available():
137
+ from accelerate import cpu_offload
138
+ else:
139
+ raise ImportError("Please install accelerate via `pip install accelerate`")
140
+
141
+ device = torch.device(f"cuda:{gpu_id}")
142
+
143
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
144
+ if cpu_offloaded_model is not None:
145
+ cpu_offload(cpu_offloaded_model, device)
146
+
147
+ @property
148
+ def _execution_device(self):
149
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
150
+ return self.device
151
+ for module in self.unet.modules():
152
+ if (
153
+ hasattr(module, "_hf_hook")
154
+ and hasattr(module._hf_hook, "execution_device")
155
+ and module._hf_hook.execution_device is not None
156
+ ):
157
+ return torch.device(module._hf_hook.execution_device)
158
+ return self.device
159
+
160
+ @torch.no_grad()
161
+ def decode_latents(self, latents):
162
+ video_length = latents.shape[2]
163
+ latents = 1 / 0.18215 * latents
164
+ latents = rearrange(latents, "b c f h w -> (b f) c h w")
165
+ # video = self.vae.decode(latents).sample
166
+ video = []
167
+ for frame_idx in tqdm(range(latents.shape[0])):
168
+ image = self.vae.decode(latents[frame_idx: frame_idx + 1].to(self.vae.device)).sample
169
+ video.append(image)
170
+ video = torch.cat(video)
171
+ video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
172
+ video = (video / 2 + 0.5).clamp(0, 1)
173
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
174
+ video = video.cpu().float().numpy()
175
+ return video
176
+
177
+ def prepare_extra_step_kwargs(self, generator, eta):
178
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
179
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
180
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
181
+ # and should be between [0, 1]
182
+
183
+ accepts_eta = "eta" in set(
184
+ inspect.signature(self.scheduler.step).parameters.keys()
185
+ )
186
+ extra_step_kwargs = {}
187
+ if accepts_eta:
188
+ extra_step_kwargs["eta"] = eta
189
+
190
+ # check if the scheduler accepts generator
191
+ accepts_generator = "generator" in set(
192
+ inspect.signature(self.scheduler.step).parameters.keys()
193
+ )
194
+ if accepts_generator:
195
+ extra_step_kwargs["generator"] = generator
196
+ return extra_step_kwargs
197
+
198
+ def prepare_latents(
199
+ self,
200
+ batch_size,
201
+ num_channels_latents,
202
+ width,
203
+ height,
204
+ video_length,
205
+ dtype,
206
+ device,
207
+ generator,
208
+ latents=None
209
+ ):
210
+ shape = (
211
+ batch_size,
212
+ num_channels_latents,
213
+ video_length,
214
+ height // self.vae_scale_factor,
215
+ width // self.vae_scale_factor,
216
+ )
217
+ if isinstance(generator, list) and len(generator) != batch_size:
218
+ raise ValueError(
219
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
220
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
221
+ )
222
+
223
+ if latents is None:
224
+ latents = randn_tensor(
225
+ shape, generator=generator, device=device, dtype=dtype
226
+ )
227
+
228
+ else:
229
+ latents = latents.to(device)
230
+
231
+ # scale the initial noise by the standard deviation required by the scheduler
232
+ latents = latents * self.scheduler.init_noise_sigma
233
+ return latents
234
+
235
+ def _encode_prompt(
236
+ self,
237
+ prompt,
238
+ device,
239
+ num_videos_per_prompt,
240
+ do_classifier_free_guidance,
241
+ negative_prompt,
242
+ ):
243
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
244
+
245
+ text_inputs = self.tokenizer(
246
+ prompt,
247
+ padding="max_length",
248
+ max_length=self.tokenizer.model_max_length,
249
+ truncation=True,
250
+ return_tensors="pt",
251
+ )
252
+ text_input_ids = text_inputs.input_ids
253
+ untruncated_ids = self.tokenizer(
254
+ prompt, padding="longest", return_tensors="pt"
255
+ ).input_ids
256
+
257
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
258
+ text_input_ids, untruncated_ids
259
+ ):
260
+ removed_text = self.tokenizer.batch_decode(
261
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]
262
+ )
263
+
264
+ if (
265
+ hasattr(self.text_encoder.config, "use_attention_mask")
266
+ and self.text_encoder.config.use_attention_mask
267
+ ):
268
+ attention_mask = text_inputs.attention_mask.to(device)
269
+ else:
270
+ attention_mask = None
271
+
272
+ text_embeddings = self.text_encoder(
273
+ text_input_ids.to(device),
274
+ attention_mask=attention_mask,
275
+ )
276
+ text_embeddings = text_embeddings[0]
277
+
278
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
279
+ bs_embed, seq_len, _ = text_embeddings.shape
280
+ text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1)
281
+ text_embeddings = text_embeddings.view(
282
+ bs_embed * num_videos_per_prompt, seq_len, -1
283
+ )
284
+
285
+ # get unconditional embeddings for classifier free guidance
286
+ if do_classifier_free_guidance:
287
+ uncond_tokens: List[str]
288
+ if negative_prompt is None:
289
+ uncond_tokens = [""] * batch_size
290
+ elif type(prompt) is not type(negative_prompt):
291
+ raise TypeError(
292
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
293
+ f" {type(prompt)}."
294
+ )
295
+ elif isinstance(negative_prompt, str):
296
+ uncond_tokens = [negative_prompt]
297
+ elif batch_size != len(negative_prompt):
298
+ raise ValueError(
299
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
300
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
301
+ " the batch size of `prompt`."
302
+ )
303
+ else:
304
+ uncond_tokens = negative_prompt
305
+
306
+ max_length = text_input_ids.shape[-1]
307
+ uncond_input = self.tokenizer(
308
+ uncond_tokens,
309
+ padding="max_length",
310
+ max_length=max_length,
311
+ truncation=True,
312
+ return_tensors="pt",
313
+ )
314
+
315
+ if (
316
+ hasattr(self.text_encoder.config, "use_attention_mask")
317
+ and self.text_encoder.config.use_attention_mask
318
+ ):
319
+ attention_mask = uncond_input.attention_mask.to(device)
320
+ else:
321
+ attention_mask = None
322
+
323
+ uncond_embeddings = self.text_encoder(
324
+ uncond_input.input_ids.to(device),
325
+ attention_mask=attention_mask,
326
+ )
327
+ uncond_embeddings = uncond_embeddings[0]
328
+
329
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
330
+ seq_len = uncond_embeddings.shape[1]
331
+ uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1)
332
+ uncond_embeddings = uncond_embeddings.view(
333
+ batch_size * num_videos_per_prompt, seq_len, -1
334
+ )
335
+
336
+ # For classifier free guidance, we need to do two forward passes.
337
+ # Here we concatenate the unconditional and text embeddings into a single batch
338
+ # to avoid doing two forward passes
339
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
340
+
341
+ return text_embeddings
342
+
343
+ def interpolate_latents(
344
+ self, latents: torch.Tensor, interpolation_factor: int, device
345
+ ):
346
+ if interpolation_factor < 2:
347
+ return latents
348
+
349
+ new_latents = torch.zeros(
350
+ (
351
+ latents.shape[0],
352
+ latents.shape[1],
353
+ ((latents.shape[2] - 1) * interpolation_factor) + 1,
354
+ latents.shape[3],
355
+ latents.shape[4],
356
+ ),
357
+ device=latents.device,
358
+ dtype=latents.dtype,
359
+ )
360
+
361
+ org_video_length = latents.shape[2]
362
+ rate = [i / interpolation_factor for i in range(interpolation_factor)][1:]
363
+
364
+ new_index = 0
365
+
366
+ v0 = None
367
+ v1 = None
368
+
369
+ for i0, i1 in zip(range(org_video_length), range(org_video_length)[1:]):
370
+ v0 = latents[:, :, i0, :, :]
371
+ v1 = latents[:, :, i1, :, :]
372
+
373
+ new_latents[:, :, new_index, :, :] = v0
374
+ new_index += 1
375
+
376
+ for f in rate:
377
+ v = get_tensor_interpolation_method()(
378
+ v0.to(device=device), v1.to(device=device), f
379
+ )
380
+ new_latents[:, :, new_index, :, :] = v.to(latents.device)
381
+ new_index += 1
382
+
383
+ new_latents[:, :, new_index, :, :] = v1
384
+ new_index += 1
385
+
386
+ return new_latents
387
+
388
+ def get_timesteps(self, num_inference_steps, strength, device):
389
+ # get the original timestep using init_timestep
390
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
391
+
392
+ t_start = max(num_inference_steps - init_timestep, 0)
393
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order:]
394
+
395
+ return timesteps, num_inference_steps - t_start
396
+
397
+ def prepare_reference_latent(self, reference_image, height, width):
398
+ reference_image_tensor = self.reference_image_processor.preprocess(reference_image, height=height, width=width)
399
+ reference_image_tensor = reference_image_tensor.to(dtype=self.dtype, device=self.device)
400
+ reference_image_latents = self.vae.encode(reference_image_tensor).latent_dist.mean
401
+ reference_image_latents = reference_image_latents * 0.18215
402
+ return reference_image_latents
403
+
404
+ def prepare_kps_feature(self, kps_images, height, width, do_classifier_free_guidance):
405
+ kps_image_tensors = []
406
+ for idx, kps_image in enumerate(kps_images):
407
+ kps_image_tensor = self.condition_image_processor.preprocess(kps_image, height=height, width=width)
408
+ kps_image_tensor = kps_image_tensor.unsqueeze(2) # [bs, c, 1, h, w]
409
+ kps_image_tensors.append(kps_image_tensor)
410
+ kps_images_tensor = torch.cat(kps_image_tensors, dim=2) # [bs, c, t, h, w]
411
+ kps_images_tensor = kps_images_tensor.to(device=self.device, dtype=self.dtype)
412
+
413
+ kps_feature = self.v_kps_guider(kps_images_tensor)
414
+
415
+ if do_classifier_free_guidance:
416
+ uc_kps_feature = torch.zeros_like(kps_feature)
417
+ kps_feature = torch.cat([uc_kps_feature, kps_feature], dim=0)
418
+
419
+ return kps_feature
420
+
421
+ def prepare_audio_embeddings(self, audio_waveform, video_length, num_pad_audio_frames, do_classifier_free_guidance):
422
+ audio_waveform = self.audio_processor(audio_waveform, return_tensors="pt", sampling_rate=16000)['input_values']
423
+ audio_waveform = audio_waveform.to(self.device, self.dtype)
424
+ audio_embeddings = self.audio_encoder(audio_waveform).last_hidden_state # [1, num_embeds, d]
425
+
426
+ audio_embeddings = torch.nn.functional.interpolate(
427
+ audio_embeddings.permute(0, 2, 1),
428
+ size=2 * video_length,
429
+ mode='linear',
430
+ )[0, :, :].permute(1, 0) # [2*vid_len, dim]
431
+
432
+ audio_embeddings = torch.cat([
433
+ torch.zeros_like(audio_embeddings)[:2 * num_pad_audio_frames, :],
434
+ audio_embeddings,
435
+ torch.zeros_like(audio_embeddings)[:2 * num_pad_audio_frames, :],
436
+ ], dim=0) # [2*num_pad+2*vid_len+2*num_pad, dim]
437
+
438
+ frame_audio_embeddings = []
439
+ for frame_idx in range(video_length):
440
+ start_sample = frame_idx
441
+ end_sample = frame_idx + 2 * num_pad_audio_frames
442
+
443
+ frame_audio_embedding = audio_embeddings[2 * start_sample:2 * (end_sample + 1), :] # [2*num_pad+1, dim]
444
+ frame_audio_embeddings.append(frame_audio_embedding)
445
+ audio_embeddings = torch.stack(frame_audio_embeddings, dim=0) # [vid_len, 2*num_pad+1, dim]
446
+
447
+ audio_embeddings = self.audio_projection(audio_embeddings).unsqueeze(0)
448
+ if do_classifier_free_guidance:
449
+ uc_audio_embeddings = torch.zeros_like(audio_embeddings)
450
+ audio_embeddings = torch.cat([uc_audio_embeddings, audio_embeddings], dim=0)
451
+ return audio_embeddings
452
+
453
+ @torch.no_grad()
454
+ def __call__(
455
+ self,
456
+ vae_latents,
457
+ reference_image,
458
+ kps_images,
459
+ audio_waveform,
460
+ width,
461
+ height,
462
+ video_length,
463
+ num_inference_steps,
464
+ guidance_scale,
465
+ strength=1.,
466
+ num_images_per_prompt=1,
467
+ eta: float = 0.0,
468
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
469
+ output_type: Optional[str] = "tensor",
470
+ return_dict: bool = True,
471
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
472
+ callback_steps: Optional[int] = 1,
473
+ context_schedule="uniform",
474
+ context_frames=24,
475
+ context_stride=1,
476
+ context_overlap=4,
477
+ context_batch_size=1,
478
+ interpolation_factor=1,
479
+ reference_attention_weight=1.,
480
+ audio_attention_weight=1.,
481
+ num_pad_audio_frames=2,
482
+ **kwargs,
483
+ ):
484
+ # Default height and width to unet
485
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
486
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
487
+
488
+ device = self._execution_device
489
+
490
+ do_classifier_free_guidance = guidance_scale > 1.0
491
+ batch_size = 1
492
+
493
+ # Prepare timesteps
494
+ timesteps = None
495
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
496
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
497
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
498
+
499
+ reference_control_writer = ReferenceAttentionControl(
500
+ self.reference_net,
501
+ do_classifier_free_guidance=do_classifier_free_guidance,
502
+ mode="write",
503
+ batch_size=batch_size,
504
+ fusion_blocks="full",
505
+ )
506
+ reference_control_reader = ReferenceAttentionControl(
507
+ self.denoising_unet,
508
+ do_classifier_free_guidance=do_classifier_free_guidance,
509
+ mode="read",
510
+ batch_size=batch_size,
511
+ fusion_blocks="full",
512
+ reference_attention_weight=reference_attention_weight,
513
+ audio_attention_weight=audio_attention_weight,
514
+ )
515
+
516
+ num_channels_latents = self.denoising_unet.in_channels
517
+
518
+ latents = self.prepare_latents(
519
+ batch_size * num_images_per_prompt,
520
+ num_channels_latents,
521
+ width,
522
+ height,
523
+ video_length,
524
+ self.dtype,
525
+ device,
526
+ generator
527
+ )
528
+ latents = self.scheduler.add_noise(vae_latents, latents, latent_timestep)
529
+
530
+ # Prepare extra step kwargs.
531
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
532
+
533
+ reference_image_latents = self.prepare_reference_latent(reference_image, height, width)
534
+ kps_feature = self.prepare_kps_feature(kps_images, height, width, do_classifier_free_guidance)
535
+ audio_embeddings = self.prepare_audio_embeddings(
536
+ audio_waveform,
537
+ video_length,
538
+ num_pad_audio_frames,
539
+ do_classifier_free_guidance,
540
+ )
541
+
542
+ context_scheduler = get_context_scheduler(context_schedule)
543
+
544
+ # denoising loop
545
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
546
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
547
+ for i, t in enumerate(timesteps):
548
+ noise_pred = torch.zeros(
549
+ (
550
+ latents.shape[0] * (2 if do_classifier_free_guidance else 1),
551
+ *latents.shape[1:],
552
+ ),
553
+ device=latents.device,
554
+ dtype=latents.dtype,
555
+ )
556
+ counter = torch.zeros(
557
+ (1, 1, latents.shape[2], 1, 1),
558
+ device=latents.device,
559
+ dtype=latents.dtype,
560
+ )
561
+
562
+ # 1. Forward reference image
563
+ if i == 0:
564
+ encoder_hidden_states = torch.zeros((1, 1, 768), dtype=self.dtype, device=self.device)
565
+ self.reference_net(
566
+ reference_image_latents,
567
+ torch.zeros_like(t),
568
+ encoder_hidden_states=encoder_hidden_states,
569
+ return_dict=False,
570
+ )
571
+
572
+ context_queue = list(
573
+ context_scheduler(
574
+ 0,
575
+ num_inference_steps,
576
+ latents.shape[2],
577
+ context_frames,
578
+ context_stride,
579
+ context_overlap,
580
+ )
581
+ )
582
+
583
+ num_context_batches = math.ceil(len(context_queue) / context_batch_size)
584
+ global_context = []
585
+ for i in range(num_context_batches):
586
+ global_context.append(context_queue[i * context_batch_size: (i + 1) * context_batch_size])
587
+
588
+ for context in global_context:
589
+ # 3.1 expand the latents if we are doing classifier free guidance
590
+ latent_model_input = (
591
+ torch.cat([latents[:, :, c] for c in context])
592
+ .to(device)
593
+ .repeat(2 if do_classifier_free_guidance else 1, 1, 1, 1, 1)
594
+ )
595
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
596
+
597
+ latent_kps_feature = torch.cat([kps_feature[:, :, c] for c in context])
598
+
599
+ latent_audio_embeddings = torch.cat([audio_embeddings[:, c, ...] for c in context], dim=0)
600
+ _, _, num_tokens, dim = latent_audio_embeddings.shape
601
+ latent_audio_embeddings = latent_audio_embeddings.reshape(-1, num_tokens, dim)
602
+
603
+ reference_control_reader.update(reference_control_writer, do_classifier_free_guidance)
604
+
605
+ pred = self.denoising_unet(
606
+ latent_model_input,
607
+ t,
608
+ encoder_hidden_states=latent_audio_embeddings.reshape(-1, num_tokens, dim),
609
+ kps_features=latent_kps_feature,
610
+ return_dict=False,
611
+ )[0]
612
+
613
+ for j, c in enumerate(context):
614
+ noise_pred[:, :, c] = noise_pred[:, :, c] + pred
615
+ counter[:, :, c] = counter[:, :, c] + 1
616
+
617
+ # perform guidance
618
+ if do_classifier_free_guidance:
619
+ noise_pred_uncond, noise_pred_text = (noise_pred / counter).chunk(2)
620
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
621
+
622
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
623
+
624
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
625
+ progress_bar.update()
626
+ if callback is not None and i % callback_steps == 0:
627
+ step_idx = i // getattr(self.scheduler, "order", 1)
628
+ callback(step_idx, t, latents)
629
+
630
+ reference_control_reader.clear()
631
+ reference_control_writer.clear()
632
+
633
+ if interpolation_factor > 0:
634
+ latents = self.interpolate_latents(latents, interpolation_factor, device)
635
+
636
+ # Convert to tensor
637
+ if output_type == "tensor":
638
+ latents = latents
639
+
640
+ if not return_dict:
641
+ return latents
642
+
643
+ return PipelineOutput(video_latents=latents)