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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The HunyuanVideo Team and The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import types
|
16 |
+
import inspect
|
17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
import torch
|
21 |
+
from transformers import CLIPTextModel, CLIPTokenizer, LlamaModel, LlamaTokenizerFast
|
22 |
+
|
23 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
24 |
+
from diffusers.loaders import HunyuanVideoLoraLoaderMixin
|
25 |
+
from diffusers.models import AutoencoderKLHunyuanVideo, HunyuanVideoTransformer3DModel
|
26 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
27 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
28 |
+
from diffusers.utils.torch_utils import randn_tensor
|
29 |
+
from diffusers.video_processor import VideoProcessor
|
30 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
31 |
+
from diffusers.pipelines.hunyuan_video.pipeline_output import HunyuanVideoPipelineOutput
|
32 |
+
|
33 |
+
|
34 |
+
if is_torch_xla_available():
|
35 |
+
import torch_xla.core.xla_model as xm
|
36 |
+
|
37 |
+
XLA_AVAILABLE = True
|
38 |
+
else:
|
39 |
+
XLA_AVAILABLE = False
|
40 |
+
|
41 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
42 |
+
|
43 |
+
|
44 |
+
EXAMPLE_DOC_STRING = """
|
45 |
+
Examples:
|
46 |
+
```python
|
47 |
+
>>> import torch
|
48 |
+
>>> from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
|
49 |
+
>>> from diffusers.utils import export_to_video
|
50 |
+
|
51 |
+
>>> model_id = "hunyuanvideo-community/HunyuanVideo"
|
52 |
+
>>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
|
53 |
+
... model_id, subfolder="transformer", torch_dtype=torch.bfloat16
|
54 |
+
... )
|
55 |
+
>>> pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
|
56 |
+
>>> pipe.vae.enable_tiling()
|
57 |
+
>>> pipe.to("cuda")
|
58 |
+
|
59 |
+
>>> output = pipe(
|
60 |
+
... prompt="A cat walks on the grass, realistic",
|
61 |
+
... height=320,
|
62 |
+
... width=512,
|
63 |
+
... num_frames=61,
|
64 |
+
... num_inference_steps=30,
|
65 |
+
... ).frames[0]
|
66 |
+
>>> export_to_video(output, "output.mp4", fps=15)
|
67 |
+
```
|
68 |
+
"""
|
69 |
+
|
70 |
+
|
71 |
+
DEFAULT_PROMPT_TEMPLATE = {
|
72 |
+
"template": (
|
73 |
+
"<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: "
|
74 |
+
"1. The main content and theme of the video."
|
75 |
+
"2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
|
76 |
+
"3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
|
77 |
+
"4. background environment, light, style and atmosphere."
|
78 |
+
"5. camera angles, movements, and transitions used in the video:<|eot_id|>"
|
79 |
+
"<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
|
80 |
+
),
|
81 |
+
"crop_start": 95,
|
82 |
+
}
|
83 |
+
|
84 |
+
|
85 |
+
def forward_with_stg(
|
86 |
+
self,
|
87 |
+
hidden_states: torch.Tensor,
|
88 |
+
encoder_hidden_states: torch.Tensor,
|
89 |
+
temb: torch.Tensor,
|
90 |
+
attention_mask: Optional[torch.Tensor] = None,
|
91 |
+
freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
92 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
93 |
+
return hidden_states, encoder_hidden_states
|
94 |
+
|
95 |
+
|
96 |
+
def forward_without_stg(
|
97 |
+
self,
|
98 |
+
hidden_states: torch.Tensor,
|
99 |
+
encoder_hidden_states: torch.Tensor,
|
100 |
+
temb: torch.Tensor,
|
101 |
+
attention_mask: Optional[torch.Tensor] = None,
|
102 |
+
freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
103 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
104 |
+
# 1. Input normalization
|
105 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
|
106 |
+
norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
|
107 |
+
encoder_hidden_states, emb=temb
|
108 |
+
)
|
109 |
+
|
110 |
+
# 2. Joint attention
|
111 |
+
attn_output, context_attn_output = self.attn(
|
112 |
+
hidden_states=norm_hidden_states,
|
113 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
114 |
+
attention_mask=attention_mask,
|
115 |
+
image_rotary_emb=freqs_cis,
|
116 |
+
)
|
117 |
+
|
118 |
+
# 3. Modulation and residual connection
|
119 |
+
hidden_states = hidden_states + attn_output * gate_msa.unsqueeze(1)
|
120 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
|
121 |
+
|
122 |
+
norm_hidden_states = self.norm2(hidden_states)
|
123 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
124 |
+
|
125 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
126 |
+
norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
127 |
+
|
128 |
+
# 4. Feed-forward
|
129 |
+
ff_output = self.ff(norm_hidden_states)
|
130 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
131 |
+
|
132 |
+
hidden_states = hidden_states + gate_mlp.unsqueeze(1) * ff_output
|
133 |
+
encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
134 |
+
|
135 |
+
return hidden_states, encoder_hidden_states
|
136 |
+
|
137 |
+
|
138 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
139 |
+
def retrieve_timesteps(
|
140 |
+
scheduler,
|
141 |
+
num_inference_steps: Optional[int] = None,
|
142 |
+
device: Optional[Union[str, torch.device]] = None,
|
143 |
+
timesteps: Optional[List[int]] = None,
|
144 |
+
sigmas: Optional[List[float]] = None,
|
145 |
+
**kwargs,
|
146 |
+
):
|
147 |
+
r"""
|
148 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
149 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
150 |
+
|
151 |
+
Args:
|
152 |
+
scheduler (`SchedulerMixin`):
|
153 |
+
The scheduler to get timesteps from.
|
154 |
+
num_inference_steps (`int`):
|
155 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
156 |
+
must be `None`.
|
157 |
+
device (`str` or `torch.device`, *optional*):
|
158 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
159 |
+
timesteps (`List[int]`, *optional*):
|
160 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
161 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
162 |
+
sigmas (`List[float]`, *optional*):
|
163 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
164 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
165 |
+
|
166 |
+
Returns:
|
167 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
168 |
+
second element is the number of inference steps.
|
169 |
+
"""
|
170 |
+
if timesteps is not None and sigmas is not None:
|
171 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
172 |
+
if timesteps is not None:
|
173 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
174 |
+
if not accepts_timesteps:
|
175 |
+
raise ValueError(
|
176 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
177 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
178 |
+
)
|
179 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
180 |
+
timesteps = scheduler.timesteps
|
181 |
+
num_inference_steps = len(timesteps)
|
182 |
+
elif sigmas is not None:
|
183 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
184 |
+
if not accept_sigmas:
|
185 |
+
raise ValueError(
|
186 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
187 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
188 |
+
)
|
189 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
190 |
+
timesteps = scheduler.timesteps
|
191 |
+
num_inference_steps = len(timesteps)
|
192 |
+
else:
|
193 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
194 |
+
timesteps = scheduler.timesteps
|
195 |
+
return timesteps, num_inference_steps
|
196 |
+
|
197 |
+
|
198 |
+
class HunyuanVideoSTGPipeline(DiffusionPipeline, HunyuanVideoLoraLoaderMixin):
|
199 |
+
r"""
|
200 |
+
Pipeline for text-to-video generation using HunyuanVideo.
|
201 |
+
|
202 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
203 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
204 |
+
|
205 |
+
Args:
|
206 |
+
text_encoder ([`LlamaModel`]):
|
207 |
+
[Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
|
208 |
+
tokenizer (`LlamaTokenizer`):
|
209 |
+
Tokenizer from [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
|
210 |
+
transformer ([`HunyuanVideoTransformer3DModel`]):
|
211 |
+
Conditional Transformer to denoise the encoded image latents.
|
212 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
213 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
214 |
+
vae ([`AutoencoderKLHunyuanVideo`]):
|
215 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
216 |
+
text_encoder_2 ([`CLIPTextModel`]):
|
217 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
218 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
219 |
+
tokenizer_2 (`CLIPTokenizer`):
|
220 |
+
Tokenizer of class
|
221 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
222 |
+
"""
|
223 |
+
|
224 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
225 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
226 |
+
|
227 |
+
def __init__(
|
228 |
+
self,
|
229 |
+
text_encoder: LlamaModel,
|
230 |
+
tokenizer: LlamaTokenizerFast,
|
231 |
+
transformer: HunyuanVideoTransformer3DModel,
|
232 |
+
vae: AutoencoderKLHunyuanVideo,
|
233 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
234 |
+
text_encoder_2: CLIPTextModel,
|
235 |
+
tokenizer_2: CLIPTokenizer,
|
236 |
+
):
|
237 |
+
super().__init__()
|
238 |
+
|
239 |
+
self.register_modules(
|
240 |
+
vae=vae,
|
241 |
+
text_encoder=text_encoder,
|
242 |
+
tokenizer=tokenizer,
|
243 |
+
transformer=transformer,
|
244 |
+
scheduler=scheduler,
|
245 |
+
text_encoder_2=text_encoder_2,
|
246 |
+
tokenizer_2=tokenizer_2,
|
247 |
+
)
|
248 |
+
|
249 |
+
self.vae_scale_factor_temporal = self.vae.temporal_compression_ratio if getattr(self, "vae", None) else 4
|
250 |
+
self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio if getattr(self, "vae", None) else 8
|
251 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
252 |
+
|
253 |
+
def _get_llama_prompt_embeds(
|
254 |
+
self,
|
255 |
+
prompt: Union[str, List[str]],
|
256 |
+
prompt_template: Dict[str, Any],
|
257 |
+
num_videos_per_prompt: int = 1,
|
258 |
+
device: Optional[torch.device] = None,
|
259 |
+
dtype: Optional[torch.dtype] = None,
|
260 |
+
max_sequence_length: int = 256,
|
261 |
+
num_hidden_layers_to_skip: int = 2,
|
262 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
263 |
+
device = device or self._execution_device
|
264 |
+
dtype = dtype or self.text_encoder.dtype
|
265 |
+
|
266 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
267 |
+
batch_size = len(prompt)
|
268 |
+
|
269 |
+
prompt = [prompt_template["template"].format(p) for p in prompt]
|
270 |
+
|
271 |
+
crop_start = prompt_template.get("crop_start", None)
|
272 |
+
if crop_start is None:
|
273 |
+
prompt_template_input = self.tokenizer(
|
274 |
+
prompt_template["template"],
|
275 |
+
padding="max_length",
|
276 |
+
return_tensors="pt",
|
277 |
+
return_length=False,
|
278 |
+
return_overflowing_tokens=False,
|
279 |
+
return_attention_mask=False,
|
280 |
+
)
|
281 |
+
crop_start = prompt_template_input["input_ids"].shape[-1]
|
282 |
+
# Remove <|eot_id|> token and placeholder {}
|
283 |
+
crop_start -= 2
|
284 |
+
|
285 |
+
max_sequence_length += crop_start
|
286 |
+
text_inputs = self.tokenizer(
|
287 |
+
prompt,
|
288 |
+
max_length=max_sequence_length,
|
289 |
+
padding="max_length",
|
290 |
+
truncation=True,
|
291 |
+
return_tensors="pt",
|
292 |
+
return_length=False,
|
293 |
+
return_overflowing_tokens=False,
|
294 |
+
return_attention_mask=True,
|
295 |
+
)
|
296 |
+
text_input_ids = text_inputs.input_ids.to(device=device)
|
297 |
+
prompt_attention_mask = text_inputs.attention_mask.to(device=device)
|
298 |
+
|
299 |
+
prompt_embeds = self.text_encoder(
|
300 |
+
input_ids=text_input_ids,
|
301 |
+
attention_mask=prompt_attention_mask,
|
302 |
+
output_hidden_states=True,
|
303 |
+
).hidden_states[-(num_hidden_layers_to_skip + 1)]
|
304 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype)
|
305 |
+
|
306 |
+
if crop_start is not None and crop_start > 0:
|
307 |
+
prompt_embeds = prompt_embeds[:, crop_start:]
|
308 |
+
prompt_attention_mask = prompt_attention_mask[:, crop_start:]
|
309 |
+
|
310 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
311 |
+
_, seq_len, _ = prompt_embeds.shape
|
312 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
313 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
314 |
+
prompt_attention_mask = prompt_attention_mask.repeat(1, num_videos_per_prompt)
|
315 |
+
prompt_attention_mask = prompt_attention_mask.view(batch_size * num_videos_per_prompt, seq_len)
|
316 |
+
|
317 |
+
return prompt_embeds, prompt_attention_mask
|
318 |
+
|
319 |
+
def _get_clip_prompt_embeds(
|
320 |
+
self,
|
321 |
+
prompt: Union[str, List[str]],
|
322 |
+
num_videos_per_prompt: int = 1,
|
323 |
+
device: Optional[torch.device] = None,
|
324 |
+
dtype: Optional[torch.dtype] = None,
|
325 |
+
max_sequence_length: int = 77,
|
326 |
+
) -> torch.Tensor:
|
327 |
+
device = device or self._execution_device
|
328 |
+
dtype = dtype or self.text_encoder_2.dtype
|
329 |
+
|
330 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
331 |
+
batch_size = len(prompt)
|
332 |
+
|
333 |
+
text_inputs = self.tokenizer_2(
|
334 |
+
prompt,
|
335 |
+
padding="max_length",
|
336 |
+
max_length=max_sequence_length,
|
337 |
+
truncation=True,
|
338 |
+
return_tensors="pt",
|
339 |
+
)
|
340 |
+
|
341 |
+
text_input_ids = text_inputs.input_ids
|
342 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
343 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
344 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
|
345 |
+
logger.warning(
|
346 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
347 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
348 |
+
)
|
349 |
+
|
350 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False).pooler_output
|
351 |
+
|
352 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
353 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
|
354 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, -1)
|
355 |
+
|
356 |
+
return prompt_embeds
|
357 |
+
|
358 |
+
def encode_prompt(
|
359 |
+
self,
|
360 |
+
prompt: Union[str, List[str]],
|
361 |
+
prompt_2: Union[str, List[str]] = None,
|
362 |
+
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
|
363 |
+
num_videos_per_prompt: int = 1,
|
364 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
365 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
366 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
367 |
+
device: Optional[torch.device] = None,
|
368 |
+
dtype: Optional[torch.dtype] = None,
|
369 |
+
max_sequence_length: int = 256,
|
370 |
+
):
|
371 |
+
if prompt_embeds is None:
|
372 |
+
prompt_embeds, prompt_attention_mask = self._get_llama_prompt_embeds(
|
373 |
+
prompt,
|
374 |
+
prompt_template,
|
375 |
+
num_videos_per_prompt,
|
376 |
+
device=device,
|
377 |
+
dtype=dtype,
|
378 |
+
max_sequence_length=max_sequence_length,
|
379 |
+
)
|
380 |
+
|
381 |
+
if pooled_prompt_embeds is None:
|
382 |
+
if prompt_2 is None and pooled_prompt_embeds is None:
|
383 |
+
prompt_2 = prompt
|
384 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
385 |
+
prompt,
|
386 |
+
num_videos_per_prompt,
|
387 |
+
device=device,
|
388 |
+
dtype=dtype,
|
389 |
+
max_sequence_length=77,
|
390 |
+
)
|
391 |
+
|
392 |
+
return prompt_embeds, pooled_prompt_embeds, prompt_attention_mask
|
393 |
+
|
394 |
+
def check_inputs(
|
395 |
+
self,
|
396 |
+
prompt,
|
397 |
+
prompt_2,
|
398 |
+
height,
|
399 |
+
width,
|
400 |
+
prompt_embeds=None,
|
401 |
+
callback_on_step_end_tensor_inputs=None,
|
402 |
+
prompt_template=None,
|
403 |
+
):
|
404 |
+
if height % 16 != 0 or width % 16 != 0:
|
405 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
406 |
+
|
407 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
408 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
409 |
+
):
|
410 |
+
raise ValueError(
|
411 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
412 |
+
)
|
413 |
+
|
414 |
+
if prompt is not None and prompt_embeds is not None:
|
415 |
+
raise ValueError(
|
416 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
417 |
+
" only forward one of the two."
|
418 |
+
)
|
419 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
420 |
+
raise ValueError(
|
421 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
422 |
+
" only forward one of the two."
|
423 |
+
)
|
424 |
+
elif prompt is None and prompt_embeds is None:
|
425 |
+
raise ValueError(
|
426 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
427 |
+
)
|
428 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
429 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
430 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
431 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
432 |
+
|
433 |
+
if prompt_template is not None:
|
434 |
+
if not isinstance(prompt_template, dict):
|
435 |
+
raise ValueError(f"`prompt_template` has to be of type `dict` but is {type(prompt_template)}")
|
436 |
+
if "template" not in prompt_template:
|
437 |
+
raise ValueError(
|
438 |
+
f"`prompt_template` has to contain a key `template` but only found {prompt_template.keys()}"
|
439 |
+
)
|
440 |
+
|
441 |
+
def prepare_latents(
|
442 |
+
self,
|
443 |
+
batch_size: int,
|
444 |
+
num_channels_latents: 32,
|
445 |
+
height: int = 720,
|
446 |
+
width: int = 1280,
|
447 |
+
num_frames: int = 129,
|
448 |
+
dtype: Optional[torch.dtype] = None,
|
449 |
+
device: Optional[torch.device] = None,
|
450 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
451 |
+
latents: Optional[torch.Tensor] = None,
|
452 |
+
) -> torch.Tensor:
|
453 |
+
if latents is not None:
|
454 |
+
return latents.to(device=device, dtype=dtype)
|
455 |
+
|
456 |
+
shape = (
|
457 |
+
batch_size,
|
458 |
+
num_channels_latents,
|
459 |
+
num_frames,
|
460 |
+
int(height) // self.vae_scale_factor_spatial,
|
461 |
+
int(width) // self.vae_scale_factor_spatial,
|
462 |
+
)
|
463 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
464 |
+
raise ValueError(
|
465 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
466 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
467 |
+
)
|
468 |
+
|
469 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
470 |
+
return latents
|
471 |
+
|
472 |
+
def enable_vae_slicing(self):
|
473 |
+
r"""
|
474 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
475 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
476 |
+
"""
|
477 |
+
self.vae.enable_slicing()
|
478 |
+
|
479 |
+
def disable_vae_slicing(self):
|
480 |
+
r"""
|
481 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
482 |
+
computing decoding in one step.
|
483 |
+
"""
|
484 |
+
self.vae.disable_slicing()
|
485 |
+
|
486 |
+
def enable_vae_tiling(self):
|
487 |
+
r"""
|
488 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
489 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
490 |
+
processing larger images.
|
491 |
+
"""
|
492 |
+
self.vae.enable_tiling()
|
493 |
+
|
494 |
+
def disable_vae_tiling(self):
|
495 |
+
r"""
|
496 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
497 |
+
computing decoding in one step.
|
498 |
+
"""
|
499 |
+
self.vae.disable_tiling()
|
500 |
+
|
501 |
+
@property
|
502 |
+
def guidance_scale(self):
|
503 |
+
return self._guidance_scale
|
504 |
+
|
505 |
+
@property
|
506 |
+
def do_spatio_temporal_guidance(self):
|
507 |
+
return self._stg_scale > 0.0
|
508 |
+
|
509 |
+
@property
|
510 |
+
def num_timesteps(self):
|
511 |
+
return self._num_timesteps
|
512 |
+
|
513 |
+
@property
|
514 |
+
def attention_kwargs(self):
|
515 |
+
return self._attention_kwargs
|
516 |
+
|
517 |
+
@property
|
518 |
+
def current_timestep(self):
|
519 |
+
return self._current_timestep
|
520 |
+
|
521 |
+
@property
|
522 |
+
def interrupt(self):
|
523 |
+
return self._interrupt
|
524 |
+
|
525 |
+
@torch.no_grad()
|
526 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
527 |
+
def __call__(
|
528 |
+
self,
|
529 |
+
prompt: Union[str, List[str]] = None,
|
530 |
+
prompt_2: Union[str, List[str]] = None,
|
531 |
+
height: int = 720,
|
532 |
+
width: int = 1280,
|
533 |
+
num_frames: int = 129,
|
534 |
+
num_inference_steps: int = 50,
|
535 |
+
sigmas: List[float] = None,
|
536 |
+
guidance_scale: float = 6.0,
|
537 |
+
num_videos_per_prompt: Optional[int] = 1,
|
538 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
539 |
+
latents: Optional[torch.Tensor] = None,
|
540 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
541 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
542 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
543 |
+
output_type: Optional[str] = "pil",
|
544 |
+
return_dict: bool = True,
|
545 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
546 |
+
callback_on_step_end: Optional[
|
547 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
548 |
+
] = None,
|
549 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
550 |
+
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
|
551 |
+
max_sequence_length: int = 256,
|
552 |
+
stg_applied_layers_idx: Optional[List[int]] = [2],
|
553 |
+
stg_scale: Optional[float] = 0.0,
|
554 |
+
do_rescaling: Optional[bool] = False,
|
555 |
+
):
|
556 |
+
r"""
|
557 |
+
The call function to the pipeline for generation.
|
558 |
+
|
559 |
+
Args:
|
560 |
+
prompt (`str` or `List[str]`, *optional*):
|
561 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
562 |
+
instead.
|
563 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
564 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
565 |
+
will be used instead.
|
566 |
+
height (`int`, defaults to `720`):
|
567 |
+
The height in pixels of the generated image.
|
568 |
+
width (`int`, defaults to `1280`):
|
569 |
+
The width in pixels of the generated image.
|
570 |
+
num_frames (`int`, defaults to `129`):
|
571 |
+
The number of frames in the generated video.
|
572 |
+
num_inference_steps (`int`, defaults to `50`):
|
573 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
574 |
+
expense of slower inference.
|
575 |
+
sigmas (`List[float]`, *optional*):
|
576 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
577 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
578 |
+
will be used.
|
579 |
+
guidance_scale (`float`, defaults to `6.0`):
|
580 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
581 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
582 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
583 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
584 |
+
usually at the expense of lower image quality. Note that the only available HunyuanVideo model is
|
585 |
+
CFG-distilled, which means that traditional guidance between unconditional and conditional latent is
|
586 |
+
not applied.
|
587 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
588 |
+
The number of images to generate per prompt.
|
589 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
590 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
591 |
+
generation deterministic.
|
592 |
+
latents (`torch.Tensor`, *optional*):
|
593 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
594 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
595 |
+
tensor is generated by sampling using the supplied random `generator`.
|
596 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
597 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
598 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
599 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
600 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
601 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
602 |
+
Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a plain tuple.
|
603 |
+
attention_kwargs (`dict`, *optional*):
|
604 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
605 |
+
`self.processor` in
|
606 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
607 |
+
clip_skip (`int`, *optional*):
|
608 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
609 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
610 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
611 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
612 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
613 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
614 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
615 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
616 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
617 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
618 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
619 |
+
|
620 |
+
Examples:
|
621 |
+
|
622 |
+
Returns:
|
623 |
+
[`~HunyuanVideoPipelineOutput`] or `tuple`:
|
624 |
+
If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned, otherwise a `tuple` is returned
|
625 |
+
where the first element is a list with the generated images and the second element is a list of `bool`s
|
626 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
627 |
+
"""
|
628 |
+
|
629 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
630 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
631 |
+
|
632 |
+
# 1. Check inputs. Raise error if not correct
|
633 |
+
self.check_inputs(
|
634 |
+
prompt,
|
635 |
+
prompt_2,
|
636 |
+
height,
|
637 |
+
width,
|
638 |
+
prompt_embeds,
|
639 |
+
callback_on_step_end_tensor_inputs,
|
640 |
+
prompt_template,
|
641 |
+
)
|
642 |
+
|
643 |
+
self._stg_scale = stg_scale
|
644 |
+
self._guidance_scale = guidance_scale
|
645 |
+
self._attention_kwargs = attention_kwargs
|
646 |
+
self._current_timestep = None
|
647 |
+
self._interrupt = False
|
648 |
+
|
649 |
+
device = self._execution_device
|
650 |
+
|
651 |
+
# 2. Define call parameters
|
652 |
+
if prompt is not None and isinstance(prompt, str):
|
653 |
+
batch_size = 1
|
654 |
+
elif prompt is not None and isinstance(prompt, list):
|
655 |
+
batch_size = len(prompt)
|
656 |
+
else:
|
657 |
+
batch_size = prompt_embeds.shape[0]
|
658 |
+
|
659 |
+
# 3. Encode input prompt
|
660 |
+
prompt_embeds, pooled_prompt_embeds, prompt_attention_mask = self.encode_prompt(
|
661 |
+
prompt=prompt,
|
662 |
+
prompt_2=prompt_2,
|
663 |
+
prompt_template=prompt_template,
|
664 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
665 |
+
prompt_embeds=prompt_embeds,
|
666 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
667 |
+
prompt_attention_mask=prompt_attention_mask,
|
668 |
+
device=device,
|
669 |
+
max_sequence_length=max_sequence_length,
|
670 |
+
)
|
671 |
+
|
672 |
+
transformer_dtype = self.transformer.dtype
|
673 |
+
prompt_embeds = prompt_embeds.to(transformer_dtype)
|
674 |
+
prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
|
675 |
+
if pooled_prompt_embeds is not None:
|
676 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
|
677 |
+
|
678 |
+
# 4. Prepare timesteps
|
679 |
+
sigmas = np.linspace(1.0, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
|
680 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
681 |
+
self.scheduler,
|
682 |
+
num_inference_steps,
|
683 |
+
device,
|
684 |
+
sigmas=sigmas,
|
685 |
+
)
|
686 |
+
|
687 |
+
# 5. Prepare latent variables
|
688 |
+
num_channels_latents = self.transformer.config.in_channels
|
689 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
690 |
+
latents = self.prepare_latents(
|
691 |
+
batch_size * num_videos_per_prompt,
|
692 |
+
num_channels_latents,
|
693 |
+
height,
|
694 |
+
width,
|
695 |
+
num_latent_frames,
|
696 |
+
torch.float32,
|
697 |
+
device,
|
698 |
+
generator,
|
699 |
+
latents,
|
700 |
+
)
|
701 |
+
|
702 |
+
# 6. Prepare guidance condition
|
703 |
+
guidance = torch.tensor([guidance_scale] * latents.shape[0], dtype=transformer_dtype, device=device) * 1000.0
|
704 |
+
|
705 |
+
# 7. Denoising loop
|
706 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
707 |
+
self._num_timesteps = len(timesteps)
|
708 |
+
|
709 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
710 |
+
for i, t in enumerate(timesteps):
|
711 |
+
if self.interrupt:
|
712 |
+
continue
|
713 |
+
|
714 |
+
self._current_timestep = t
|
715 |
+
latent_model_input = latents.to(transformer_dtype)
|
716 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
717 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
718 |
+
|
719 |
+
if self.do_spatio_temporal_guidance:
|
720 |
+
for i in stg_applied_layers_idx:
|
721 |
+
self.transformer.transformer_blocks[i].forward = types.MethodType(forward_without_stg, self.transformer.transformer_blocks[i])
|
722 |
+
|
723 |
+
noise_pred = self.transformer(
|
724 |
+
hidden_states=latent_model_input,
|
725 |
+
timestep=timestep,
|
726 |
+
encoder_hidden_states=prompt_embeds,
|
727 |
+
encoder_attention_mask=prompt_attention_mask,
|
728 |
+
pooled_projections=pooled_prompt_embeds,
|
729 |
+
guidance=guidance,
|
730 |
+
attention_kwargs=attention_kwargs,
|
731 |
+
return_dict=False,
|
732 |
+
)[0]
|
733 |
+
|
734 |
+
if self.do_spatio_temporal_guidance:
|
735 |
+
for i in stg_applied_layers_idx:
|
736 |
+
self.transformer.transformer_blocks[i].forward = types.MethodType(forward_with_stg, self.transformer.transformer_blocks[i])
|
737 |
+
|
738 |
+
noise_pred_perturb = self.transformer(
|
739 |
+
hidden_states=latent_model_input,
|
740 |
+
timestep=timestep,
|
741 |
+
encoder_hidden_states=prompt_embeds,
|
742 |
+
encoder_attention_mask=prompt_attention_mask,
|
743 |
+
pooled_projections=pooled_prompt_embeds,
|
744 |
+
guidance=guidance,
|
745 |
+
attention_kwargs=attention_kwargs,
|
746 |
+
return_dict=False,
|
747 |
+
)[0]
|
748 |
+
noise_pred = noise_pred + self._stg_scale * (noise_pred - noise_pred_perturb)
|
749 |
+
|
750 |
+
if do_rescaling:
|
751 |
+
rescaling_scale = 0.7
|
752 |
+
factor = noise_pred_text.std() / noise_pred.std()
|
753 |
+
factor = rescaling_scale * factor + (1 - rescaling_scale)
|
754 |
+
noise_pred = noise_pred * factor
|
755 |
+
|
756 |
+
# compute the previous noisy sample x_t -> x_t-1
|
757 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
758 |
+
|
759 |
+
if callback_on_step_end is not None:
|
760 |
+
callback_kwargs = {}
|
761 |
+
for k in callback_on_step_end_tensor_inputs:
|
762 |
+
callback_kwargs[k] = locals()[k]
|
763 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
764 |
+
|
765 |
+
latents = callback_outputs.pop("latents", latents)
|
766 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
767 |
+
|
768 |
+
# call the callback, if provided
|
769 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
770 |
+
progress_bar.update()
|
771 |
+
|
772 |
+
if XLA_AVAILABLE:
|
773 |
+
xm.mark_step()
|
774 |
+
|
775 |
+
self._current_timestep = None
|
776 |
+
|
777 |
+
if not output_type == "latent":
|
778 |
+
latents = latents.to(self.vae.dtype) / self.vae.config.scaling_factor
|
779 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
780 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
781 |
+
else:
|
782 |
+
video = latents
|
783 |
+
|
784 |
+
# Offload all models
|
785 |
+
self.maybe_free_model_hooks()
|
786 |
+
|
787 |
+
if not return_dict:
|
788 |
+
return (video,)
|
789 |
+
|
790 |
+
return HunyuanVideoPipelineOutput(frames=video)
|