Upload folder using huggingface_hub
Browse files- main/README.md +1 -2
- main/pipeline_stg_wan.py +661 -0
main/README.md
CHANGED
@@ -10,7 +10,7 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
|
|
10 |
|
11 |
| Example | Description | Code Example | Colab | Author |
|
12 |
|:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
|
13 |
-
|Spatiotemporal Skip Guidance (STG)|[Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) (CVPR 2025) enhances video diffusion models by generating a weaker model through layer skipping and using it as guidance, improving fidelity in models like HunyuanVideo, LTXVideo, and Mochi.|[Spatiotemporal Skip Guidance](#spatiotemporal-skip-guidance)|-|[Junha Hyung](https://junhahyung.github.io/), [Kinam Kim](https://kinam0252.github.io/)|
|
14 |
|Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
|
15 |
|Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/flux_with_cfg.ipynb)|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
|
16 |
|Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[](https://huggingface.co/spaces/exx8/differential-diffusion) [](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
|
@@ -124,7 +124,6 @@ pipe = pipe.to("cuda")
|
|
124 |
#--------Option--------#
|
125 |
prompt = "A close-up of a beautiful woman's face with colored powder exploding around her, creating an abstract splash of vibrant hues, realistic style."
|
126 |
stg_applied_layers_idx = [34]
|
127 |
-
stg_mode = "STG"
|
128 |
stg_scale = 1.0 # 0.0 for CFG
|
129 |
#----------------------#
|
130 |
|
|
|
10 |
|
11 |
| Example | Description | Code Example | Colab | Author |
|
12 |
|:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
|
13 |
+
|Spatiotemporal Skip Guidance (STG)|[Spatiotemporal Skip Guidance for Enhanced Video Diffusion Sampling](https://arxiv.org/abs/2411.18664) (CVPR 2025) enhances video diffusion models by generating a weaker model through layer skipping and using it as guidance, improving fidelity in models like HunyuanVideo, LTXVideo, and Mochi.|[Spatiotemporal Skip Guidance](#spatiotemporal-skip-guidance)|-|[Junha Hyung](https://junhahyung.github.io/), [Kinam Kim](https://kinam0252.github.io/), and [Ednaordinary](https://github.com/Ednaordinary)|
|
14 |
|Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
|
15 |
|Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/flux_with_cfg.ipynb)|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
|
16 |
|Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[](https://huggingface.co/spaces/exx8/differential-diffusion) [](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
|
|
|
124 |
#--------Option--------#
|
125 |
prompt = "A close-up of a beautiful woman's face with colored powder exploding around her, creating an abstract splash of vibrant hues, realistic style."
|
126 |
stg_applied_layers_idx = [34]
|
|
|
127 |
stg_scale = 1.0 # 0.0 for CFG
|
128 |
#----------------------#
|
129 |
|
main/pipeline_stg_wan.py
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2025 The Wan 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 html
|
16 |
+
import types
|
17 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
18 |
+
|
19 |
+
import ftfy
|
20 |
+
import regex as re
|
21 |
+
import torch
|
22 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
23 |
+
|
24 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
25 |
+
from diffusers.loaders import WanLoraLoaderMixin
|
26 |
+
from diffusers.models import AutoencoderKLWan, WanTransformer3DModel
|
27 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
28 |
+
from diffusers.pipelines.wan.pipeline_output import WanPipelineOutput
|
29 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
30 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
31 |
+
from diffusers.utils.torch_utils import randn_tensor
|
32 |
+
from diffusers.video_processor import VideoProcessor
|
33 |
+
|
34 |
+
|
35 |
+
if is_torch_xla_available():
|
36 |
+
import torch_xla.core.xla_model as xm
|
37 |
+
|
38 |
+
XLA_AVAILABLE = True
|
39 |
+
else:
|
40 |
+
XLA_AVAILABLE = False
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
43 |
+
|
44 |
+
|
45 |
+
EXAMPLE_DOC_STRING = """
|
46 |
+
Examples:
|
47 |
+
```python
|
48 |
+
>>> import torch
|
49 |
+
>>> from diffusers.utils import export_to_video
|
50 |
+
>>> from diffusers import AutoencoderKLWan
|
51 |
+
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
|
52 |
+
>>> from examples.community.pipeline_stg_wan import WanSTGPipeline
|
53 |
+
|
54 |
+
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
|
55 |
+
>>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
56 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
57 |
+
>>> pipe = WanSTGPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
58 |
+
>>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
|
59 |
+
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
|
60 |
+
>>> pipe.to("cuda")
|
61 |
+
|
62 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
63 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
64 |
+
|
65 |
+
>>> # Configure STG mode options
|
66 |
+
>>> stg_applied_layers_idx = [8] # Layer indices from 0 to 39 for 14b or 0 to 29 for 1.3b
|
67 |
+
>>> stg_scale = 1.0 # Set 0.0 for CFG
|
68 |
+
|
69 |
+
>>> output = pipe(
|
70 |
+
... prompt=prompt,
|
71 |
+
... negative_prompt=negative_prompt,
|
72 |
+
... height=720,
|
73 |
+
... width=1280,
|
74 |
+
... num_frames=81,
|
75 |
+
... guidance_scale=5.0,
|
76 |
+
... stg_applied_layers_idx=stg_applied_layers_idx,
|
77 |
+
... stg_scale=stg_scale,
|
78 |
+
... ).frames[0]
|
79 |
+
>>> export_to_video(output, "output.mp4", fps=16)
|
80 |
+
```
|
81 |
+
"""
|
82 |
+
|
83 |
+
|
84 |
+
def basic_clean(text):
|
85 |
+
text = ftfy.fix_text(text)
|
86 |
+
text = html.unescape(html.unescape(text))
|
87 |
+
return text.strip()
|
88 |
+
|
89 |
+
|
90 |
+
def whitespace_clean(text):
|
91 |
+
text = re.sub(r"\s+", " ", text)
|
92 |
+
text = text.strip()
|
93 |
+
return text
|
94 |
+
|
95 |
+
|
96 |
+
def prompt_clean(text):
|
97 |
+
text = whitespace_clean(basic_clean(text))
|
98 |
+
return text
|
99 |
+
|
100 |
+
|
101 |
+
def forward_with_stg(
|
102 |
+
self,
|
103 |
+
hidden_states: torch.Tensor,
|
104 |
+
encoder_hidden_states: torch.Tensor,
|
105 |
+
temb: torch.Tensor,
|
106 |
+
rotary_emb: torch.Tensor,
|
107 |
+
) -> torch.Tensor:
|
108 |
+
return hidden_states
|
109 |
+
|
110 |
+
|
111 |
+
def forward_without_stg(
|
112 |
+
self,
|
113 |
+
hidden_states: torch.Tensor,
|
114 |
+
encoder_hidden_states: torch.Tensor,
|
115 |
+
temb: torch.Tensor,
|
116 |
+
rotary_emb: torch.Tensor,
|
117 |
+
) -> torch.Tensor:
|
118 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
119 |
+
self.scale_shift_table + temb.float()
|
120 |
+
).chunk(6, dim=1)
|
121 |
+
|
122 |
+
# 1. Self-attention
|
123 |
+
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
124 |
+
attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
|
125 |
+
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
126 |
+
|
127 |
+
# 2. Cross-attention
|
128 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
129 |
+
attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
|
130 |
+
hidden_states = hidden_states + attn_output
|
131 |
+
|
132 |
+
# 3. Feed-forward
|
133 |
+
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states)
|
134 |
+
ff_output = self.ffn(norm_hidden_states)
|
135 |
+
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
136 |
+
|
137 |
+
return hidden_states
|
138 |
+
|
139 |
+
|
140 |
+
class WanSTGPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
141 |
+
r"""
|
142 |
+
Pipeline for text-to-video generation using Wan.
|
143 |
+
|
144 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
145 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
146 |
+
|
147 |
+
Args:
|
148 |
+
tokenizer ([`T5Tokenizer`]):
|
149 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
150 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
151 |
+
text_encoder ([`T5EncoderModel`]):
|
152 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
153 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
154 |
+
transformer ([`WanTransformer3DModel`]):
|
155 |
+
Conditional Transformer to denoise the input latents.
|
156 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
157 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
158 |
+
vae ([`AutoencoderKLWan`]):
|
159 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
160 |
+
"""
|
161 |
+
|
162 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
163 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
164 |
+
|
165 |
+
def __init__(
|
166 |
+
self,
|
167 |
+
tokenizer: AutoTokenizer,
|
168 |
+
text_encoder: UMT5EncoderModel,
|
169 |
+
transformer: WanTransformer3DModel,
|
170 |
+
vae: AutoencoderKLWan,
|
171 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
172 |
+
):
|
173 |
+
super().__init__()
|
174 |
+
|
175 |
+
self.register_modules(
|
176 |
+
vae=vae,
|
177 |
+
text_encoder=text_encoder,
|
178 |
+
tokenizer=tokenizer,
|
179 |
+
transformer=transformer,
|
180 |
+
scheduler=scheduler,
|
181 |
+
)
|
182 |
+
|
183 |
+
self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
|
184 |
+
self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
|
185 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
186 |
+
|
187 |
+
def _get_t5_prompt_embeds(
|
188 |
+
self,
|
189 |
+
prompt: Union[str, List[str]] = None,
|
190 |
+
num_videos_per_prompt: int = 1,
|
191 |
+
max_sequence_length: int = 226,
|
192 |
+
device: Optional[torch.device] = None,
|
193 |
+
dtype: Optional[torch.dtype] = None,
|
194 |
+
):
|
195 |
+
device = device or self._execution_device
|
196 |
+
dtype = dtype or self.text_encoder.dtype
|
197 |
+
|
198 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
199 |
+
prompt = [prompt_clean(u) for u in prompt]
|
200 |
+
batch_size = len(prompt)
|
201 |
+
|
202 |
+
text_inputs = self.tokenizer(
|
203 |
+
prompt,
|
204 |
+
padding="max_length",
|
205 |
+
max_length=max_sequence_length,
|
206 |
+
truncation=True,
|
207 |
+
add_special_tokens=True,
|
208 |
+
return_attention_mask=True,
|
209 |
+
return_tensors="pt",
|
210 |
+
)
|
211 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
212 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
213 |
+
|
214 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
215 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
216 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
217 |
+
prompt_embeds = torch.stack(
|
218 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
219 |
+
)
|
220 |
+
|
221 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
222 |
+
_, seq_len, _ = prompt_embeds.shape
|
223 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
224 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
225 |
+
|
226 |
+
return prompt_embeds
|
227 |
+
|
228 |
+
def encode_prompt(
|
229 |
+
self,
|
230 |
+
prompt: Union[str, List[str]],
|
231 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
232 |
+
do_classifier_free_guidance: bool = True,
|
233 |
+
num_videos_per_prompt: int = 1,
|
234 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
235 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
236 |
+
max_sequence_length: int = 226,
|
237 |
+
device: Optional[torch.device] = None,
|
238 |
+
dtype: Optional[torch.dtype] = None,
|
239 |
+
):
|
240 |
+
r"""
|
241 |
+
Encodes the prompt into text encoder hidden states.
|
242 |
+
|
243 |
+
Args:
|
244 |
+
prompt (`str` or `List[str]`, *optional*):
|
245 |
+
prompt to be encoded
|
246 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
247 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
248 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
249 |
+
less than `1`).
|
250 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
251 |
+
Whether to use classifier free guidance or not.
|
252 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
253 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
254 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
255 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
256 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
257 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
258 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
259 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
260 |
+
argument.
|
261 |
+
device: (`torch.device`, *optional*):
|
262 |
+
torch device
|
263 |
+
dtype: (`torch.dtype`, *optional*):
|
264 |
+
torch dtype
|
265 |
+
"""
|
266 |
+
device = device or self._execution_device
|
267 |
+
|
268 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
269 |
+
if prompt is not None:
|
270 |
+
batch_size = len(prompt)
|
271 |
+
else:
|
272 |
+
batch_size = prompt_embeds.shape[0]
|
273 |
+
|
274 |
+
if prompt_embeds is None:
|
275 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
276 |
+
prompt=prompt,
|
277 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
278 |
+
max_sequence_length=max_sequence_length,
|
279 |
+
device=device,
|
280 |
+
dtype=dtype,
|
281 |
+
)
|
282 |
+
|
283 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
284 |
+
negative_prompt = negative_prompt or ""
|
285 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
286 |
+
|
287 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
288 |
+
raise TypeError(
|
289 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
290 |
+
f" {type(prompt)}."
|
291 |
+
)
|
292 |
+
elif batch_size != len(negative_prompt):
|
293 |
+
raise ValueError(
|
294 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
295 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
296 |
+
" the batch size of `prompt`."
|
297 |
+
)
|
298 |
+
|
299 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
300 |
+
prompt=negative_prompt,
|
301 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
302 |
+
max_sequence_length=max_sequence_length,
|
303 |
+
device=device,
|
304 |
+
dtype=dtype,
|
305 |
+
)
|
306 |
+
|
307 |
+
return prompt_embeds, negative_prompt_embeds
|
308 |
+
|
309 |
+
def check_inputs(
|
310 |
+
self,
|
311 |
+
prompt,
|
312 |
+
negative_prompt,
|
313 |
+
height,
|
314 |
+
width,
|
315 |
+
prompt_embeds=None,
|
316 |
+
negative_prompt_embeds=None,
|
317 |
+
callback_on_step_end_tensor_inputs=None,
|
318 |
+
):
|
319 |
+
if height % 16 != 0 or width % 16 != 0:
|
320 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
321 |
+
|
322 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
323 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
324 |
+
):
|
325 |
+
raise ValueError(
|
326 |
+
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]}"
|
327 |
+
)
|
328 |
+
|
329 |
+
if prompt is not None and prompt_embeds is not None:
|
330 |
+
raise ValueError(
|
331 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
332 |
+
" only forward one of the two."
|
333 |
+
)
|
334 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
335 |
+
raise ValueError(
|
336 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
337 |
+
" only forward one of the two."
|
338 |
+
)
|
339 |
+
elif prompt is None and prompt_embeds is None:
|
340 |
+
raise ValueError(
|
341 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
342 |
+
)
|
343 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
344 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
345 |
+
elif negative_prompt is not None and (
|
346 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
347 |
+
):
|
348 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
349 |
+
|
350 |
+
def prepare_latents(
|
351 |
+
self,
|
352 |
+
batch_size: int,
|
353 |
+
num_channels_latents: int = 16,
|
354 |
+
height: int = 480,
|
355 |
+
width: int = 832,
|
356 |
+
num_frames: int = 81,
|
357 |
+
dtype: Optional[torch.dtype] = None,
|
358 |
+
device: Optional[torch.device] = None,
|
359 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
360 |
+
latents: Optional[torch.Tensor] = None,
|
361 |
+
) -> torch.Tensor:
|
362 |
+
if latents is not None:
|
363 |
+
return latents.to(device=device, dtype=dtype)
|
364 |
+
|
365 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
366 |
+
shape = (
|
367 |
+
batch_size,
|
368 |
+
num_channels_latents,
|
369 |
+
num_latent_frames,
|
370 |
+
int(height) // self.vae_scale_factor_spatial,
|
371 |
+
int(width) // self.vae_scale_factor_spatial,
|
372 |
+
)
|
373 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
374 |
+
raise ValueError(
|
375 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
376 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
377 |
+
)
|
378 |
+
|
379 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
380 |
+
return latents
|
381 |
+
|
382 |
+
@property
|
383 |
+
def guidance_scale(self):
|
384 |
+
return self._guidance_scale
|
385 |
+
|
386 |
+
@property
|
387 |
+
def do_classifier_free_guidance(self):
|
388 |
+
return self._guidance_scale > 1.0
|
389 |
+
|
390 |
+
@property
|
391 |
+
def do_spatio_temporal_guidance(self):
|
392 |
+
return self._stg_scale > 0.0
|
393 |
+
|
394 |
+
@property
|
395 |
+
def num_timesteps(self):
|
396 |
+
return self._num_timesteps
|
397 |
+
|
398 |
+
@property
|
399 |
+
def current_timestep(self):
|
400 |
+
return self._current_timestep
|
401 |
+
|
402 |
+
@property
|
403 |
+
def interrupt(self):
|
404 |
+
return self._interrupt
|
405 |
+
|
406 |
+
@property
|
407 |
+
def attention_kwargs(self):
|
408 |
+
return self._attention_kwargs
|
409 |
+
|
410 |
+
@torch.no_grad()
|
411 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
412 |
+
def __call__(
|
413 |
+
self,
|
414 |
+
prompt: Union[str, List[str]] = None,
|
415 |
+
negative_prompt: Union[str, List[str]] = None,
|
416 |
+
height: int = 480,
|
417 |
+
width: int = 832,
|
418 |
+
num_frames: int = 81,
|
419 |
+
num_inference_steps: int = 50,
|
420 |
+
guidance_scale: float = 5.0,
|
421 |
+
num_videos_per_prompt: Optional[int] = 1,
|
422 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
423 |
+
latents: Optional[torch.Tensor] = None,
|
424 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
425 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
426 |
+
output_type: Optional[str] = "np",
|
427 |
+
return_dict: bool = True,
|
428 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
429 |
+
callback_on_step_end: Optional[
|
430 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
431 |
+
] = None,
|
432 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
433 |
+
max_sequence_length: int = 512,
|
434 |
+
stg_applied_layers_idx: Optional[List[int]] = [3, 8, 16],
|
435 |
+
stg_scale: Optional[float] = 0.0,
|
436 |
+
):
|
437 |
+
r"""
|
438 |
+
The call function to the pipeline for generation.
|
439 |
+
|
440 |
+
Args:
|
441 |
+
prompt (`str` or `List[str]`, *optional*):
|
442 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
443 |
+
instead.
|
444 |
+
height (`int`, defaults to `480`):
|
445 |
+
The height in pixels of the generated image.
|
446 |
+
width (`int`, defaults to `832`):
|
447 |
+
The width in pixels of the generated image.
|
448 |
+
num_frames (`int`, defaults to `81`):
|
449 |
+
The number of frames in the generated video.
|
450 |
+
num_inference_steps (`int`, defaults to `50`):
|
451 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
452 |
+
expense of slower inference.
|
453 |
+
guidance_scale (`float`, defaults to `5.0`):
|
454 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
455 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
456 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
457 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
458 |
+
usually at the expense of lower image quality.
|
459 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
460 |
+
The number of images to generate per prompt.
|
461 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
462 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
463 |
+
generation deterministic.
|
464 |
+
latents (`torch.Tensor`, *optional*):
|
465 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
466 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
467 |
+
tensor is generated by sampling using the supplied random `generator`.
|
468 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
469 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
470 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
471 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
472 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
473 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
474 |
+
Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
|
475 |
+
attention_kwargs (`dict`, *optional*):
|
476 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
477 |
+
`self.processor` in
|
478 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
479 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
480 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
481 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
482 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
483 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
484 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
485 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
486 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
487 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
488 |
+
autocast_dtype (`torch.dtype`, *optional*, defaults to `torch.bfloat16`):
|
489 |
+
The dtype to use for the torch.amp.autocast.
|
490 |
+
|
491 |
+
Examples:
|
492 |
+
|
493 |
+
Returns:
|
494 |
+
[`~WanPipelineOutput`] or `tuple`:
|
495 |
+
If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
496 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
497 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
498 |
+
"""
|
499 |
+
|
500 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
501 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
502 |
+
|
503 |
+
# 1. Check inputs. Raise error if not correct
|
504 |
+
self.check_inputs(
|
505 |
+
prompt,
|
506 |
+
negative_prompt,
|
507 |
+
height,
|
508 |
+
width,
|
509 |
+
prompt_embeds,
|
510 |
+
negative_prompt_embeds,
|
511 |
+
callback_on_step_end_tensor_inputs,
|
512 |
+
)
|
513 |
+
|
514 |
+
self._guidance_scale = guidance_scale
|
515 |
+
self._stg_scale = stg_scale
|
516 |
+
self._attention_kwargs = attention_kwargs
|
517 |
+
self._current_timestep = None
|
518 |
+
self._interrupt = False
|
519 |
+
|
520 |
+
device = self._execution_device
|
521 |
+
|
522 |
+
# 2. Define call parameters
|
523 |
+
if prompt is not None and isinstance(prompt, str):
|
524 |
+
batch_size = 1
|
525 |
+
elif prompt is not None and isinstance(prompt, list):
|
526 |
+
batch_size = len(prompt)
|
527 |
+
else:
|
528 |
+
batch_size = prompt_embeds.shape[0]
|
529 |
+
|
530 |
+
# 3. Encode input prompt
|
531 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
532 |
+
prompt=prompt,
|
533 |
+
negative_prompt=negative_prompt,
|
534 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
535 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
536 |
+
prompt_embeds=prompt_embeds,
|
537 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
538 |
+
max_sequence_length=max_sequence_length,
|
539 |
+
device=device,
|
540 |
+
)
|
541 |
+
|
542 |
+
transformer_dtype = self.transformer.dtype
|
543 |
+
prompt_embeds = prompt_embeds.to(transformer_dtype)
|
544 |
+
if negative_prompt_embeds is not None:
|
545 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
546 |
+
|
547 |
+
# 4. Prepare timesteps
|
548 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
549 |
+
timesteps = self.scheduler.timesteps
|
550 |
+
|
551 |
+
# 5. Prepare latent variables
|
552 |
+
num_channels_latents = self.transformer.config.in_channels
|
553 |
+
latents = self.prepare_latents(
|
554 |
+
batch_size * num_videos_per_prompt,
|
555 |
+
num_channels_latents,
|
556 |
+
height,
|
557 |
+
width,
|
558 |
+
num_frames,
|
559 |
+
torch.float32,
|
560 |
+
device,
|
561 |
+
generator,
|
562 |
+
latents,
|
563 |
+
)
|
564 |
+
|
565 |
+
# 6. Denoising loop
|
566 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
567 |
+
self._num_timesteps = len(timesteps)
|
568 |
+
|
569 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
570 |
+
for i, t in enumerate(timesteps):
|
571 |
+
if self.interrupt:
|
572 |
+
continue
|
573 |
+
|
574 |
+
self._current_timestep = t
|
575 |
+
latent_model_input = latents.to(transformer_dtype)
|
576 |
+
timestep = t.expand(latents.shape[0])
|
577 |
+
|
578 |
+
if self.do_spatio_temporal_guidance:
|
579 |
+
for idx, block in enumerate(self.transformer.blocks):
|
580 |
+
block.forward = types.MethodType(forward_without_stg, block)
|
581 |
+
|
582 |
+
noise_pred = self.transformer(
|
583 |
+
hidden_states=latent_model_input,
|
584 |
+
timestep=timestep,
|
585 |
+
encoder_hidden_states=prompt_embeds,
|
586 |
+
attention_kwargs=attention_kwargs,
|
587 |
+
return_dict=False,
|
588 |
+
)[0]
|
589 |
+
|
590 |
+
if self.do_classifier_free_guidance:
|
591 |
+
noise_uncond = self.transformer(
|
592 |
+
hidden_states=latent_model_input,
|
593 |
+
timestep=timestep,
|
594 |
+
encoder_hidden_states=negative_prompt_embeds,
|
595 |
+
attention_kwargs=attention_kwargs,
|
596 |
+
return_dict=False,
|
597 |
+
)[0]
|
598 |
+
if self.do_spatio_temporal_guidance:
|
599 |
+
for idx, block in enumerate(self.transformer.blocks):
|
600 |
+
if idx in stg_applied_layers_idx:
|
601 |
+
block.forward = types.MethodType(forward_with_stg, block)
|
602 |
+
noise_perturb = self.transformer(
|
603 |
+
hidden_states=latent_model_input,
|
604 |
+
timestep=timestep,
|
605 |
+
encoder_hidden_states=prompt_embeds,
|
606 |
+
attention_kwargs=attention_kwargs,
|
607 |
+
return_dict=False,
|
608 |
+
)[0]
|
609 |
+
noise_pred = (
|
610 |
+
noise_uncond
|
611 |
+
+ guidance_scale * (noise_pred - noise_uncond)
|
612 |
+
+ self._stg_scale * (noise_pred - noise_perturb)
|
613 |
+
)
|
614 |
+
else:
|
615 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
616 |
+
|
617 |
+
# compute the previous noisy sample x_t -> x_t-1
|
618 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
619 |
+
|
620 |
+
if callback_on_step_end is not None:
|
621 |
+
callback_kwargs = {}
|
622 |
+
for k in callback_on_step_end_tensor_inputs:
|
623 |
+
callback_kwargs[k] = locals()[k]
|
624 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
625 |
+
|
626 |
+
latents = callback_outputs.pop("latents", latents)
|
627 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
628 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
629 |
+
|
630 |
+
# call the callback, if provided
|
631 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
632 |
+
progress_bar.update()
|
633 |
+
|
634 |
+
if XLA_AVAILABLE:
|
635 |
+
xm.mark_step()
|
636 |
+
|
637 |
+
self._current_timestep = None
|
638 |
+
|
639 |
+
if not output_type == "latent":
|
640 |
+
latents = latents.to(self.vae.dtype)
|
641 |
+
latents_mean = (
|
642 |
+
torch.tensor(self.vae.config.latents_mean)
|
643 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
644 |
+
.to(latents.device, latents.dtype)
|
645 |
+
)
|
646 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
647 |
+
latents.device, latents.dtype
|
648 |
+
)
|
649 |
+
latents = latents / latents_std + latents_mean
|
650 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
651 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
652 |
+
else:
|
653 |
+
video = latents
|
654 |
+
|
655 |
+
# Offload all models
|
656 |
+
self.maybe_free_model_hooks()
|
657 |
+
|
658 |
+
if not return_dict:
|
659 |
+
return (video,)
|
660 |
+
|
661 |
+
return WanPipelineOutput(frames=video)
|