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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
# Note:
|
| 17 |
+
# This pipeline relies on a "hack" discovered by the community that allows
|
| 18 |
+
# the generation of videos given an input image with AnimateDiff. It works
|
| 19 |
+
# by creating a copy of the image `num_frames` times and progressively adding
|
| 20 |
+
# more noise to the image based on the strength and latent interpolation method.
|
| 21 |
+
|
| 22 |
+
import inspect
|
| 23 |
+
from types import FunctionType
|
| 24 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
| 29 |
+
|
| 30 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
| 31 |
+
from diffusers.loaders import IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
|
| 32 |
+
from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
|
| 33 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 34 |
+
from diffusers.models.unets.unet_motion_model import MotionAdapter
|
| 35 |
+
from diffusers.pipelines.animatediff.pipeline_output import AnimateDiffPipelineOutput
|
| 36 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 37 |
+
from diffusers.schedulers import (
|
| 38 |
+
DDIMScheduler,
|
| 39 |
+
DPMSolverMultistepScheduler,
|
| 40 |
+
EulerAncestralDiscreteScheduler,
|
| 41 |
+
EulerDiscreteScheduler,
|
| 42 |
+
LMSDiscreteScheduler,
|
| 43 |
+
PNDMScheduler,
|
| 44 |
+
)
|
| 45 |
+
from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
|
| 46 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 50 |
+
|
| 51 |
+
EXAMPLE_DOC_STRING = """
|
| 52 |
+
Examples:
|
| 53 |
+
```py
|
| 54 |
+
>>> import torch
|
| 55 |
+
>>> from diffusers import MotionAdapter, DiffusionPipeline, DDIMScheduler
|
| 56 |
+
>>> from diffusers.utils import export_to_gif, load_image
|
| 57 |
+
|
| 58 |
+
>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
|
| 59 |
+
>>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
|
| 60 |
+
>>> pipe = DiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE", motion_adapter=adapter, custom_pipeline="pipeline_animatediff_img2video").to("cuda")
|
| 61 |
+
>>> pipe.scheduler = pipe.scheduler = DDIMScheduler.from_pretrained(model_id, subfolder="scheduler", clip_sample=False, timestep_spacing="linspace", beta_schedule="linear", steps_offset=1)
|
| 62 |
+
|
| 63 |
+
>>> image = load_image("snail.png")
|
| 64 |
+
>>> output = pipe(image=image, prompt="A snail moving on the ground", strength=0.8, latent_interpolation_method="slerp")
|
| 65 |
+
>>> frames = output.frames[0]
|
| 66 |
+
>>> export_to_gif(frames, "animation.gif")
|
| 67 |
+
```
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def lerp(
|
| 72 |
+
v0: torch.Tensor,
|
| 73 |
+
v1: torch.Tensor,
|
| 74 |
+
t: Union[float, torch.Tensor],
|
| 75 |
+
) -> torch.Tensor:
|
| 76 |
+
r"""
|
| 77 |
+
Linear Interpolation between two tensors.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
v0 (`torch.Tensor`): First tensor.
|
| 81 |
+
v1 (`torch.Tensor`): Second tensor.
|
| 82 |
+
t: (`float` or `torch.Tensor`): Interpolation factor.
|
| 83 |
+
"""
|
| 84 |
+
t_is_float = False
|
| 85 |
+
input_device = v0.device
|
| 86 |
+
v0 = v0.cpu().numpy()
|
| 87 |
+
v1 = v1.cpu().numpy()
|
| 88 |
+
|
| 89 |
+
if isinstance(t, torch.Tensor):
|
| 90 |
+
t = t.cpu().numpy()
|
| 91 |
+
else:
|
| 92 |
+
t_is_float = True
|
| 93 |
+
t = np.array([t], dtype=v0.dtype)
|
| 94 |
+
|
| 95 |
+
t = t[..., None]
|
| 96 |
+
v0 = v0[None, ...]
|
| 97 |
+
v1 = v1[None, ...]
|
| 98 |
+
v2 = (1 - t) * v0 + t * v1
|
| 99 |
+
|
| 100 |
+
if t_is_float and v0.ndim > 1:
|
| 101 |
+
assert v2.shape[0] == 1
|
| 102 |
+
v2 = np.squeeze(v2, axis=0)
|
| 103 |
+
|
| 104 |
+
v2 = torch.from_numpy(v2).to(input_device)
|
| 105 |
+
return v2
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def slerp(
|
| 109 |
+
v0: torch.Tensor,
|
| 110 |
+
v1: torch.Tensor,
|
| 111 |
+
t: Union[float, torch.Tensor],
|
| 112 |
+
DOT_THRESHOLD: float = 0.9995,
|
| 113 |
+
) -> torch.Tensor:
|
| 114 |
+
r"""
|
| 115 |
+
Spherical Linear Interpolation between two tensors.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
v0 (`torch.Tensor`): First tensor.
|
| 119 |
+
v1 (`torch.Tensor`): Second tensor.
|
| 120 |
+
t: (`float` or `torch.Tensor`): Interpolation factor.
|
| 121 |
+
DOT_THRESHOLD (`float`):
|
| 122 |
+
Dot product threshold exceeding which linear interpolation will be used
|
| 123 |
+
because input tensors are close to parallel.
|
| 124 |
+
"""
|
| 125 |
+
t_is_float = False
|
| 126 |
+
input_device = v0.device
|
| 127 |
+
v0 = v0.cpu().numpy()
|
| 128 |
+
v1 = v1.cpu().numpy()
|
| 129 |
+
|
| 130 |
+
if isinstance(t, torch.Tensor):
|
| 131 |
+
t = t.cpu().numpy()
|
| 132 |
+
else:
|
| 133 |
+
t_is_float = True
|
| 134 |
+
t = np.array([t], dtype=v0.dtype)
|
| 135 |
+
|
| 136 |
+
dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
|
| 137 |
+
|
| 138 |
+
if np.abs(dot) > DOT_THRESHOLD:
|
| 139 |
+
# v0 and v1 are close to parallel, so use linear interpolation instead
|
| 140 |
+
v2 = lerp(v0, v1, t)
|
| 141 |
+
else:
|
| 142 |
+
theta_0 = np.arccos(dot)
|
| 143 |
+
sin_theta_0 = np.sin(theta_0)
|
| 144 |
+
theta_t = theta_0 * t
|
| 145 |
+
sin_theta_t = np.sin(theta_t)
|
| 146 |
+
s0 = np.sin(theta_0 - theta_t) / sin_theta_0
|
| 147 |
+
s1 = sin_theta_t / sin_theta_0
|
| 148 |
+
s0 = s0[..., None]
|
| 149 |
+
s1 = s1[..., None]
|
| 150 |
+
v0 = v0[None, ...]
|
| 151 |
+
v1 = v1[None, ...]
|
| 152 |
+
v2 = s0 * v0 + s1 * v1
|
| 153 |
+
|
| 154 |
+
if t_is_float and v0.ndim > 1:
|
| 155 |
+
assert v2.shape[0] == 1
|
| 156 |
+
v2 = np.squeeze(v2, axis=0)
|
| 157 |
+
|
| 158 |
+
v2 = torch.from_numpy(v2).to(input_device)
|
| 159 |
+
return v2
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# Copied from diffusers.pipelines.animatediff.pipeline_animatediff.tensor2vid
|
| 163 |
+
def tensor2vid(video: torch.Tensor, processor, output_type="np"):
|
| 164 |
+
batch_size, channels, num_frames, height, width = video.shape
|
| 165 |
+
outputs = []
|
| 166 |
+
for batch_idx in range(batch_size):
|
| 167 |
+
batch_vid = video[batch_idx].permute(1, 0, 2, 3)
|
| 168 |
+
batch_output = processor.postprocess(batch_vid, output_type)
|
| 169 |
+
|
| 170 |
+
outputs.append(batch_output)
|
| 171 |
+
|
| 172 |
+
if output_type == "np":
|
| 173 |
+
outputs = np.stack(outputs)
|
| 174 |
+
|
| 175 |
+
elif output_type == "pt":
|
| 176 |
+
outputs = torch.stack(outputs)
|
| 177 |
+
|
| 178 |
+
elif not output_type == "pil":
|
| 179 |
+
raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
|
| 180 |
+
|
| 181 |
+
return outputs
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
| 185 |
+
def retrieve_latents(
|
| 186 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 187 |
+
):
|
| 188 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 189 |
+
return encoder_output.latent_dist.sample(generator)
|
| 190 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 191 |
+
return encoder_output.latent_dist.mode()
|
| 192 |
+
elif hasattr(encoder_output, "latents"):
|
| 193 |
+
return encoder_output.latents
|
| 194 |
+
else:
|
| 195 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
| 199 |
+
def retrieve_timesteps(
|
| 200 |
+
scheduler,
|
| 201 |
+
num_inference_steps: Optional[int] = None,
|
| 202 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 203 |
+
timesteps: Optional[List[int]] = None,
|
| 204 |
+
**kwargs,
|
| 205 |
+
):
|
| 206 |
+
"""
|
| 207 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 208 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
scheduler (`SchedulerMixin`):
|
| 212 |
+
The scheduler to get timesteps from.
|
| 213 |
+
num_inference_steps (`int`):
|
| 214 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
| 215 |
+
`timesteps` must be `None`.
|
| 216 |
+
device (`str` or `torch.device`, *optional*):
|
| 217 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 218 |
+
timesteps (`List[int]`, *optional*):
|
| 219 |
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
| 220 |
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
| 221 |
+
must be `None`.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 225 |
+
second element is the number of inference steps.
|
| 226 |
+
"""
|
| 227 |
+
if timesteps is not None:
|
| 228 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 229 |
+
if not accepts_timesteps:
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 232 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 233 |
+
)
|
| 234 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 235 |
+
timesteps = scheduler.timesteps
|
| 236 |
+
num_inference_steps = len(timesteps)
|
| 237 |
+
else:
|
| 238 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 239 |
+
timesteps = scheduler.timesteps
|
| 240 |
+
return timesteps, num_inference_steps
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class AnimateDiffImgToVideoPipeline(
|
| 244 |
+
DiffusionPipeline,
|
| 245 |
+
StableDiffusionMixin,
|
| 246 |
+
TextualInversionLoaderMixin,
|
| 247 |
+
IPAdapterMixin,
|
| 248 |
+
StableDiffusionLoraLoaderMixin,
|
| 249 |
+
):
|
| 250 |
+
r"""
|
| 251 |
+
Pipeline for image-to-video generation.
|
| 252 |
+
|
| 253 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 254 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 255 |
+
|
| 256 |
+
The pipeline also inherits the following loading methods:
|
| 257 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 258 |
+
- [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 259 |
+
- [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 260 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
vae ([`AutoencoderKL`]):
|
| 264 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 265 |
+
text_encoder ([`CLIPTextModel`]):
|
| 266 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 267 |
+
tokenizer (`CLIPTokenizer`):
|
| 268 |
+
A [`~transformers.CLIPTokenizer`] to tokenize text.
|
| 269 |
+
unet ([`UNet2DConditionModel`]):
|
| 270 |
+
A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
|
| 271 |
+
motion_adapter ([`MotionAdapter`]):
|
| 272 |
+
A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
|
| 273 |
+
scheduler ([`SchedulerMixin`]):
|
| 274 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 275 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
| 279 |
+
_optional_components = ["feature_extractor", "image_encoder"]
|
| 280 |
+
|
| 281 |
+
def __init__(
|
| 282 |
+
self,
|
| 283 |
+
vae: AutoencoderKL,
|
| 284 |
+
text_encoder: CLIPTextModel,
|
| 285 |
+
tokenizer: CLIPTokenizer,
|
| 286 |
+
unet: UNet2DConditionModel,
|
| 287 |
+
motion_adapter: MotionAdapter,
|
| 288 |
+
scheduler: Union[
|
| 289 |
+
DDIMScheduler,
|
| 290 |
+
PNDMScheduler,
|
| 291 |
+
LMSDiscreteScheduler,
|
| 292 |
+
EulerDiscreteScheduler,
|
| 293 |
+
EulerAncestralDiscreteScheduler,
|
| 294 |
+
DPMSolverMultistepScheduler,
|
| 295 |
+
],
|
| 296 |
+
feature_extractor: CLIPImageProcessor = None,
|
| 297 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 298 |
+
):
|
| 299 |
+
super().__init__()
|
| 300 |
+
unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
|
| 301 |
+
|
| 302 |
+
self.register_modules(
|
| 303 |
+
vae=vae,
|
| 304 |
+
text_encoder=text_encoder,
|
| 305 |
+
tokenizer=tokenizer,
|
| 306 |
+
unet=unet,
|
| 307 |
+
motion_adapter=motion_adapter,
|
| 308 |
+
scheduler=scheduler,
|
| 309 |
+
feature_extractor=feature_extractor,
|
| 310 |
+
image_encoder=image_encoder,
|
| 311 |
+
)
|
| 312 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
|
| 313 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 314 |
+
|
| 315 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
|
| 316 |
+
def encode_prompt(
|
| 317 |
+
self,
|
| 318 |
+
prompt,
|
| 319 |
+
device,
|
| 320 |
+
num_images_per_prompt,
|
| 321 |
+
do_classifier_free_guidance,
|
| 322 |
+
negative_prompt=None,
|
| 323 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 324 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 325 |
+
lora_scale: Optional[float] = None,
|
| 326 |
+
clip_skip: Optional[int] = None,
|
| 327 |
+
):
|
| 328 |
+
r"""
|
| 329 |
+
Encodes the prompt into text encoder hidden states.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 333 |
+
prompt to be encoded
|
| 334 |
+
device: (`torch.device`):
|
| 335 |
+
torch device
|
| 336 |
+
num_images_per_prompt (`int`):
|
| 337 |
+
number of images that should be generated per prompt
|
| 338 |
+
do_classifier_free_guidance (`bool`):
|
| 339 |
+
whether to use classifier free guidance or not
|
| 340 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 341 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 342 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 343 |
+
less than `1`).
|
| 344 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 345 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 346 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 347 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 348 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 349 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 350 |
+
argument.
|
| 351 |
+
lora_scale (`float`, *optional*):
|
| 352 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 353 |
+
clip_skip (`int`, *optional*):
|
| 354 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 355 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 356 |
+
"""
|
| 357 |
+
# set lora scale so that monkey patched LoRA
|
| 358 |
+
# function of text encoder can correctly access it
|
| 359 |
+
if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
|
| 360 |
+
self._lora_scale = lora_scale
|
| 361 |
+
|
| 362 |
+
# dynamically adjust the LoRA scale
|
| 363 |
+
if not USE_PEFT_BACKEND:
|
| 364 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 365 |
+
else:
|
| 366 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 367 |
+
|
| 368 |
+
if prompt is not None and isinstance(prompt, str):
|
| 369 |
+
batch_size = 1
|
| 370 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 371 |
+
batch_size = len(prompt)
|
| 372 |
+
else:
|
| 373 |
+
batch_size = prompt_embeds.shape[0]
|
| 374 |
+
|
| 375 |
+
if prompt_embeds is None:
|
| 376 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 377 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 378 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 379 |
+
|
| 380 |
+
text_inputs = self.tokenizer(
|
| 381 |
+
prompt,
|
| 382 |
+
padding="max_length",
|
| 383 |
+
max_length=self.tokenizer.model_max_length,
|
| 384 |
+
truncation=True,
|
| 385 |
+
return_tensors="pt",
|
| 386 |
+
)
|
| 387 |
+
text_input_ids = text_inputs.input_ids
|
| 388 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 389 |
+
|
| 390 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 391 |
+
text_input_ids, untruncated_ids
|
| 392 |
+
):
|
| 393 |
+
removed_text = self.tokenizer.batch_decode(
|
| 394 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 395 |
+
)
|
| 396 |
+
logger.warning(
|
| 397 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 398 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 402 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 403 |
+
else:
|
| 404 |
+
attention_mask = None
|
| 405 |
+
|
| 406 |
+
if clip_skip is None:
|
| 407 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 408 |
+
prompt_embeds = prompt_embeds[0]
|
| 409 |
+
else:
|
| 410 |
+
prompt_embeds = self.text_encoder(
|
| 411 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 412 |
+
)
|
| 413 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 414 |
+
# all the hidden states from the encoder layers. Then index into
|
| 415 |
+
# the tuple to access the hidden states from the desired layer.
|
| 416 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 417 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 418 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 419 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 420 |
+
# layer.
|
| 421 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 422 |
+
|
| 423 |
+
if self.text_encoder is not None:
|
| 424 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 425 |
+
elif self.unet is not None:
|
| 426 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 427 |
+
else:
|
| 428 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 429 |
+
|
| 430 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 431 |
+
|
| 432 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 433 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 434 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 435 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 436 |
+
|
| 437 |
+
# get unconditional embeddings for classifier free guidance
|
| 438 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 439 |
+
uncond_tokens: List[str]
|
| 440 |
+
if negative_prompt is None:
|
| 441 |
+
uncond_tokens = [""] * batch_size
|
| 442 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 443 |
+
raise TypeError(
|
| 444 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 445 |
+
f" {type(prompt)}."
|
| 446 |
+
)
|
| 447 |
+
elif isinstance(negative_prompt, str):
|
| 448 |
+
uncond_tokens = [negative_prompt]
|
| 449 |
+
elif batch_size != len(negative_prompt):
|
| 450 |
+
raise ValueError(
|
| 451 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 452 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 453 |
+
" the batch size of `prompt`."
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
uncond_tokens = negative_prompt
|
| 457 |
+
|
| 458 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 459 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 460 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 461 |
+
|
| 462 |
+
max_length = prompt_embeds.shape[1]
|
| 463 |
+
uncond_input = self.tokenizer(
|
| 464 |
+
uncond_tokens,
|
| 465 |
+
padding="max_length",
|
| 466 |
+
max_length=max_length,
|
| 467 |
+
truncation=True,
|
| 468 |
+
return_tensors="pt",
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 472 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 473 |
+
else:
|
| 474 |
+
attention_mask = None
|
| 475 |
+
|
| 476 |
+
negative_prompt_embeds = self.text_encoder(
|
| 477 |
+
uncond_input.input_ids.to(device),
|
| 478 |
+
attention_mask=attention_mask,
|
| 479 |
+
)
|
| 480 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 481 |
+
|
| 482 |
+
if do_classifier_free_guidance:
|
| 483 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 484 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 485 |
+
|
| 486 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 487 |
+
|
| 488 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 489 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 490 |
+
|
| 491 |
+
if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 492 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 493 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 494 |
+
|
| 495 |
+
return prompt_embeds, negative_prompt_embeds
|
| 496 |
+
|
| 497 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
| 498 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
| 499 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 500 |
+
|
| 501 |
+
if not isinstance(image, torch.Tensor):
|
| 502 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 503 |
+
|
| 504 |
+
image = image.to(device=device, dtype=dtype)
|
| 505 |
+
if output_hidden_states:
|
| 506 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
| 507 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
| 508 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
| 509 |
+
torch.zeros_like(image), output_hidden_states=True
|
| 510 |
+
).hidden_states[-2]
|
| 511 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
| 512 |
+
num_images_per_prompt, dim=0
|
| 513 |
+
)
|
| 514 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
| 515 |
+
else:
|
| 516 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 517 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 518 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
| 519 |
+
|
| 520 |
+
return image_embeds, uncond_image_embeds
|
| 521 |
+
|
| 522 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
| 523 |
+
def prepare_ip_adapter_image_embeds(
|
| 524 |
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
|
| 525 |
+
):
|
| 526 |
+
if ip_adapter_image_embeds is None:
|
| 527 |
+
if not isinstance(ip_adapter_image, list):
|
| 528 |
+
ip_adapter_image = [ip_adapter_image]
|
| 529 |
+
|
| 530 |
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
| 531 |
+
raise ValueError(
|
| 532 |
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
image_embeds = []
|
| 536 |
+
for single_ip_adapter_image, image_proj_layer in zip(
|
| 537 |
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
| 538 |
+
):
|
| 539 |
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
| 540 |
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
| 541 |
+
single_ip_adapter_image, device, 1, output_hidden_state
|
| 542 |
+
)
|
| 543 |
+
single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
|
| 544 |
+
single_negative_image_embeds = torch.stack(
|
| 545 |
+
[single_negative_image_embeds] * num_images_per_prompt, dim=0
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
if self.do_classifier_free_guidance:
|
| 549 |
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
|
| 550 |
+
single_image_embeds = single_image_embeds.to(device)
|
| 551 |
+
|
| 552 |
+
image_embeds.append(single_image_embeds)
|
| 553 |
+
else:
|
| 554 |
+
image_embeds = ip_adapter_image_embeds
|
| 555 |
+
return image_embeds
|
| 556 |
+
|
| 557 |
+
# Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
|
| 558 |
+
def decode_latents(self, latents):
|
| 559 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 560 |
+
|
| 561 |
+
batch_size, channels, num_frames, height, width = latents.shape
|
| 562 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
|
| 563 |
+
|
| 564 |
+
image = self.vae.decode(latents).sample
|
| 565 |
+
video = (
|
| 566 |
+
image[None, :]
|
| 567 |
+
.reshape(
|
| 568 |
+
(
|
| 569 |
+
batch_size,
|
| 570 |
+
num_frames,
|
| 571 |
+
-1,
|
| 572 |
+
)
|
| 573 |
+
+ image.shape[2:]
|
| 574 |
+
)
|
| 575 |
+
.permute(0, 2, 1, 3, 4)
|
| 576 |
+
)
|
| 577 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 578 |
+
video = video.float()
|
| 579 |
+
return video
|
| 580 |
+
|
| 581 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 582 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 583 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 584 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 585 |
+
# eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
|
| 586 |
+
# and should be between [0, 1]
|
| 587 |
+
|
| 588 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 589 |
+
extra_step_kwargs = {}
|
| 590 |
+
if accepts_eta:
|
| 591 |
+
extra_step_kwargs["eta"] = eta
|
| 592 |
+
|
| 593 |
+
# check if the scheduler accepts generator
|
| 594 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 595 |
+
if accepts_generator:
|
| 596 |
+
extra_step_kwargs["generator"] = generator
|
| 597 |
+
return extra_step_kwargs
|
| 598 |
+
|
| 599 |
+
def check_inputs(
|
| 600 |
+
self,
|
| 601 |
+
prompt,
|
| 602 |
+
height,
|
| 603 |
+
width,
|
| 604 |
+
callback_steps,
|
| 605 |
+
negative_prompt=None,
|
| 606 |
+
prompt_embeds=None,
|
| 607 |
+
negative_prompt_embeds=None,
|
| 608 |
+
callback_on_step_end_tensor_inputs=None,
|
| 609 |
+
latent_interpolation_method=None,
|
| 610 |
+
):
|
| 611 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 612 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 613 |
+
|
| 614 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 615 |
+
raise ValueError(
|
| 616 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 617 |
+
f" {type(callback_steps)}."
|
| 618 |
+
)
|
| 619 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 620 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 621 |
+
):
|
| 622 |
+
raise ValueError(
|
| 623 |
+
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]}"
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
if prompt is not None and prompt_embeds is not None:
|
| 627 |
+
raise ValueError(
|
| 628 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 629 |
+
" only forward one of the two."
|
| 630 |
+
)
|
| 631 |
+
elif prompt is None and prompt_embeds is None:
|
| 632 |
+
raise ValueError(
|
| 633 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 634 |
+
)
|
| 635 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 636 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 637 |
+
|
| 638 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 639 |
+
raise ValueError(
|
| 640 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 641 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 645 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 646 |
+
raise ValueError(
|
| 647 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 648 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 649 |
+
f" {negative_prompt_embeds.shape}."
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
if latent_interpolation_method is not None:
|
| 653 |
+
if latent_interpolation_method not in ["lerp", "slerp"] and not isinstance(
|
| 654 |
+
latent_interpolation_method, FunctionType
|
| 655 |
+
):
|
| 656 |
+
raise ValueError(
|
| 657 |
+
"`latent_interpolation_method` must be one of `lerp`, `slerp` or a Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]"
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
def prepare_latents(
|
| 661 |
+
self,
|
| 662 |
+
image,
|
| 663 |
+
strength,
|
| 664 |
+
batch_size,
|
| 665 |
+
num_channels_latents,
|
| 666 |
+
num_frames,
|
| 667 |
+
height,
|
| 668 |
+
width,
|
| 669 |
+
dtype,
|
| 670 |
+
device,
|
| 671 |
+
generator,
|
| 672 |
+
latents=None,
|
| 673 |
+
latent_interpolation_method="slerp",
|
| 674 |
+
):
|
| 675 |
+
shape = (
|
| 676 |
+
batch_size,
|
| 677 |
+
num_channels_latents,
|
| 678 |
+
num_frames,
|
| 679 |
+
height // self.vae_scale_factor,
|
| 680 |
+
width // self.vae_scale_factor,
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
if latents is None:
|
| 684 |
+
image = image.to(device=device, dtype=dtype)
|
| 685 |
+
|
| 686 |
+
if image.shape[1] == 4:
|
| 687 |
+
latents = image
|
| 688 |
+
else:
|
| 689 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 690 |
+
if self.vae.config.force_upcast:
|
| 691 |
+
image = image.float()
|
| 692 |
+
self.vae.to(dtype=torch.float32)
|
| 693 |
+
|
| 694 |
+
if isinstance(generator, list):
|
| 695 |
+
if len(generator) != batch_size:
|
| 696 |
+
raise ValueError(
|
| 697 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 698 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
init_latents = [
|
| 702 |
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
| 703 |
+
for i in range(batch_size)
|
| 704 |
+
]
|
| 705 |
+
init_latents = torch.cat(init_latents, dim=0)
|
| 706 |
+
else:
|
| 707 |
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
| 708 |
+
|
| 709 |
+
if self.vae.config.force_upcast:
|
| 710 |
+
self.vae.to(dtype)
|
| 711 |
+
|
| 712 |
+
init_latents = init_latents.to(dtype)
|
| 713 |
+
init_latents = self.vae.config.scaling_factor * init_latents
|
| 714 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 715 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 716 |
+
|
| 717 |
+
if latent_interpolation_method == "lerp":
|
| 718 |
+
|
| 719 |
+
def latent_cls(v0, v1, index):
|
| 720 |
+
return lerp(v0, v1, index / num_frames * (1 - strength))
|
| 721 |
+
elif latent_interpolation_method == "slerp":
|
| 722 |
+
|
| 723 |
+
def latent_cls(v0, v1, index):
|
| 724 |
+
return slerp(v0, v1, index / num_frames * (1 - strength))
|
| 725 |
+
else:
|
| 726 |
+
latent_cls = latent_interpolation_method
|
| 727 |
+
|
| 728 |
+
for i in range(num_frames):
|
| 729 |
+
latents[:, :, i, :, :] = latent_cls(latents[:, :, i, :, :], init_latents, i)
|
| 730 |
+
else:
|
| 731 |
+
if shape != latents.shape:
|
| 732 |
+
# [B, C, F, H, W]
|
| 733 |
+
raise ValueError(f"`latents` expected to have {shape=}, but found {latents.shape=}")
|
| 734 |
+
latents = latents.to(device, dtype=dtype)
|
| 735 |
+
|
| 736 |
+
return latents
|
| 737 |
+
|
| 738 |
+
@torch.no_grad()
|
| 739 |
+
def __call__(
|
| 740 |
+
self,
|
| 741 |
+
image: PipelineImageInput,
|
| 742 |
+
prompt: Optional[Union[str, List[str]]] = None,
|
| 743 |
+
height: Optional[int] = None,
|
| 744 |
+
width: Optional[int] = None,
|
| 745 |
+
num_frames: int = 16,
|
| 746 |
+
num_inference_steps: int = 50,
|
| 747 |
+
timesteps: Optional[List[int]] = None,
|
| 748 |
+
guidance_scale: float = 7.5,
|
| 749 |
+
strength: float = 0.8,
|
| 750 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 751 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 752 |
+
eta: float = 0.0,
|
| 753 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 754 |
+
latents: Optional[torch.Tensor] = None,
|
| 755 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 756 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 757 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 758 |
+
ip_adapter_image_embeds: Optional[PipelineImageInput] = None,
|
| 759 |
+
output_type: Optional[str] = "pil",
|
| 760 |
+
return_dict: bool = True,
|
| 761 |
+
callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
|
| 762 |
+
callback_steps: Optional[int] = 1,
|
| 763 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 764 |
+
clip_skip: Optional[int] = None,
|
| 765 |
+
latent_interpolation_method: Union[str, Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]] = "slerp",
|
| 766 |
+
):
|
| 767 |
+
r"""
|
| 768 |
+
The call function to the pipeline for generation.
|
| 769 |
+
|
| 770 |
+
Args:
|
| 771 |
+
image (`PipelineImageInput`):
|
| 772 |
+
The input image to condition the generation on.
|
| 773 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 774 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 775 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 776 |
+
The height in pixels of the generated video.
|
| 777 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 778 |
+
The width in pixels of the generated video.
|
| 779 |
+
num_frames (`int`, *optional*, defaults to 16):
|
| 780 |
+
The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
|
| 781 |
+
amounts to 2 seconds of video.
|
| 782 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 783 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
|
| 784 |
+
expense of slower inference.
|
| 785 |
+
strength (`float`, *optional*, defaults to 0.8):
|
| 786 |
+
Higher strength leads to more differences between original image and generated video.
|
| 787 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 788 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 789 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 790 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 791 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 792 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 793 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 794 |
+
Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only applies
|
| 795 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 796 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 797 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 798 |
+
generation deterministic.
|
| 799 |
+
latents (`torch.Tensor`, *optional*):
|
| 800 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
|
| 801 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 802 |
+
tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
|
| 803 |
+
`(batch_size, num_channel, num_frames, height, width)`.
|
| 804 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 805 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 806 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 807 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 808 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 809 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 810 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
| 811 |
+
Optional image input to work with IP Adapters.
|
| 812 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
| 813 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
|
| 814 |
+
Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
|
| 815 |
+
if `do_classifier_free_guidance` is set to `True`.
|
| 816 |
+
If not provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 817 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 818 |
+
The output format of the generated video. Choose between `torch.Tensor`, `PIL.Image` or
|
| 819 |
+
`np.array`.
|
| 820 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 821 |
+
Whether or not to return a [`AnimateDiffImgToVideoPipelineOutput`] instead
|
| 822 |
+
of a plain tuple.
|
| 823 |
+
callback (`Callable`, *optional*):
|
| 824 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 825 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
|
| 826 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 827 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 828 |
+
every step.
|
| 829 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 830 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 831 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 832 |
+
clip_skip (`int`, *optional*):
|
| 833 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 834 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 835 |
+
latent_interpolation_method (`str` or `Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]]`, *optional*):
|
| 836 |
+
Must be one of "lerp", "slerp" or a callable that takes in a random noisy latent, image latent and a frame index
|
| 837 |
+
as input and returns an initial latent for sampling.
|
| 838 |
+
Examples:
|
| 839 |
+
|
| 840 |
+
Returns:
|
| 841 |
+
[`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
|
| 842 |
+
If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
|
| 843 |
+
returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
|
| 844 |
+
"""
|
| 845 |
+
# 0. Default height and width to unet
|
| 846 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 847 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 848 |
+
|
| 849 |
+
num_videos_per_prompt = 1
|
| 850 |
+
|
| 851 |
+
# 1. Check inputs. Raise error if not correct
|
| 852 |
+
self.check_inputs(
|
| 853 |
+
prompt=prompt,
|
| 854 |
+
height=height,
|
| 855 |
+
width=width,
|
| 856 |
+
callback_steps=callback_steps,
|
| 857 |
+
negative_prompt=negative_prompt,
|
| 858 |
+
prompt_embeds=prompt_embeds,
|
| 859 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 860 |
+
latent_interpolation_method=latent_interpolation_method,
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# 2. Define call parameters
|
| 864 |
+
if prompt is not None and isinstance(prompt, str):
|
| 865 |
+
batch_size = 1
|
| 866 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 867 |
+
batch_size = len(prompt)
|
| 868 |
+
else:
|
| 869 |
+
batch_size = prompt_embeds.shape[0]
|
| 870 |
+
|
| 871 |
+
device = self._execution_device
|
| 872 |
+
|
| 873 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 874 |
+
# of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
|
| 875 |
+
# corresponds to doing no classifier free guidance.
|
| 876 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 877 |
+
|
| 878 |
+
# 3. Encode input prompt
|
| 879 |
+
text_encoder_lora_scale = (
|
| 880 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 881 |
+
)
|
| 882 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 883 |
+
prompt,
|
| 884 |
+
device,
|
| 885 |
+
num_videos_per_prompt,
|
| 886 |
+
do_classifier_free_guidance,
|
| 887 |
+
negative_prompt,
|
| 888 |
+
prompt_embeds=prompt_embeds,
|
| 889 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 890 |
+
lora_scale=text_encoder_lora_scale,
|
| 891 |
+
clip_skip=clip_skip,
|
| 892 |
+
)
|
| 893 |
+
|
| 894 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 895 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 896 |
+
# to avoid doing two forward passes
|
| 897 |
+
if do_classifier_free_guidance:
|
| 898 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 899 |
+
|
| 900 |
+
if ip_adapter_image is not None:
|
| 901 |
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 902 |
+
ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_videos_per_prompt
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
# 4. Preprocess image
|
| 906 |
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
| 907 |
+
|
| 908 |
+
# 5. Prepare timesteps
|
| 909 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
| 910 |
+
|
| 911 |
+
# 6. Prepare latent variables
|
| 912 |
+
num_channels_latents = self.unet.config.in_channels
|
| 913 |
+
latents = self.prepare_latents(
|
| 914 |
+
image=image,
|
| 915 |
+
strength=strength,
|
| 916 |
+
batch_size=batch_size * num_videos_per_prompt,
|
| 917 |
+
num_channels_latents=num_channels_latents,
|
| 918 |
+
num_frames=num_frames,
|
| 919 |
+
height=height,
|
| 920 |
+
width=width,
|
| 921 |
+
dtype=prompt_embeds.dtype,
|
| 922 |
+
device=device,
|
| 923 |
+
generator=generator,
|
| 924 |
+
latents=latents,
|
| 925 |
+
latent_interpolation_method=latent_interpolation_method,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 929 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 930 |
+
|
| 931 |
+
# 8. Add image embeds for IP-Adapter
|
| 932 |
+
added_cond_kwargs = (
|
| 933 |
+
{"image_embeds": image_embeds}
|
| 934 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None
|
| 935 |
+
else None
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
# 9. Denoising loop
|
| 939 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 940 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 941 |
+
for i, t in enumerate(timesteps):
|
| 942 |
+
# expand the latents if we are doing classifier free guidance
|
| 943 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 944 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 945 |
+
|
| 946 |
+
# predict the noise residual
|
| 947 |
+
noise_pred = self.unet(
|
| 948 |
+
latent_model_input,
|
| 949 |
+
t,
|
| 950 |
+
encoder_hidden_states=prompt_embeds,
|
| 951 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 952 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 953 |
+
).sample
|
| 954 |
+
|
| 955 |
+
# perform guidance
|
| 956 |
+
if do_classifier_free_guidance:
|
| 957 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 958 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 959 |
+
|
| 960 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 961 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 962 |
+
|
| 963 |
+
# call the callback, if provided
|
| 964 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 965 |
+
progress_bar.update()
|
| 966 |
+
if callback is not None and i % callback_steps == 0:
|
| 967 |
+
callback(i, t, latents)
|
| 968 |
+
|
| 969 |
+
if output_type == "latent":
|
| 970 |
+
return AnimateDiffPipelineOutput(frames=latents)
|
| 971 |
+
|
| 972 |
+
# 10. Post-processing
|
| 973 |
+
if output_type == "latent":
|
| 974 |
+
video = latents
|
| 975 |
+
else:
|
| 976 |
+
video_tensor = self.decode_latents(latents)
|
| 977 |
+
video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
|
| 978 |
+
|
| 979 |
+
# 11. Offload all models
|
| 980 |
+
self.maybe_free_model_hooks()
|
| 981 |
+
|
| 982 |
+
if not return_dict:
|
| 983 |
+
return (video,)
|
| 984 |
+
|
| 985 |
+
return AnimateDiffPipelineOutput(frames=video)
|