diffusers 0.17.1__py3-none-any.whl → 0.18.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. diffusers/__init__.py +26 -1
  2. diffusers/configuration_utils.py +34 -29
  3. diffusers/dependency_versions_table.py +4 -0
  4. diffusers/image_processor.py +125 -12
  5. diffusers/loaders.py +169 -203
  6. diffusers/models/attention.py +24 -1
  7. diffusers/models/attention_flax.py +10 -5
  8. diffusers/models/attention_processor.py +3 -0
  9. diffusers/models/autoencoder_kl.py +114 -33
  10. diffusers/models/controlnet.py +131 -14
  11. diffusers/models/controlnet_flax.py +37 -26
  12. diffusers/models/cross_attention.py +17 -17
  13. diffusers/models/embeddings.py +67 -0
  14. diffusers/models/modeling_flax_utils.py +64 -56
  15. diffusers/models/modeling_utils.py +193 -104
  16. diffusers/models/prior_transformer.py +207 -37
  17. diffusers/models/resnet.py +26 -26
  18. diffusers/models/transformer_2d.py +36 -41
  19. diffusers/models/transformer_temporal.py +24 -21
  20. diffusers/models/unet_1d.py +31 -25
  21. diffusers/models/unet_2d.py +43 -30
  22. diffusers/models/unet_2d_blocks.py +210 -89
  23. diffusers/models/unet_2d_blocks_flax.py +12 -12
  24. diffusers/models/unet_2d_condition.py +172 -64
  25. diffusers/models/unet_2d_condition_flax.py +38 -24
  26. diffusers/models/unet_3d_blocks.py +34 -31
  27. diffusers/models/unet_3d_condition.py +101 -34
  28. diffusers/models/vae.py +5 -5
  29. diffusers/models/vae_flax.py +37 -34
  30. diffusers/models/vq_model.py +23 -14
  31. diffusers/pipelines/__init__.py +24 -1
  32. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +1 -1
  33. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -3
  34. diffusers/pipelines/consistency_models/__init__.py +1 -0
  35. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +337 -0
  36. diffusers/pipelines/controlnet/multicontrolnet.py +120 -1
  37. diffusers/pipelines/controlnet/pipeline_controlnet.py +59 -17
  38. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +60 -15
  39. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +60 -17
  40. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  41. diffusers/pipelines/kandinsky/__init__.py +1 -1
  42. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +4 -6
  43. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +1 -0
  44. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -0
  45. diffusers/pipelines/kandinsky2_2/__init__.py +7 -0
  46. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +317 -0
  47. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +372 -0
  48. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +434 -0
  49. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +398 -0
  50. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +531 -0
  51. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +541 -0
  52. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +605 -0
  53. diffusers/pipelines/pipeline_flax_utils.py +2 -2
  54. diffusers/pipelines/pipeline_utils.py +124 -146
  55. diffusers/pipelines/shap_e/__init__.py +27 -0
  56. diffusers/pipelines/shap_e/camera.py +147 -0
  57. diffusers/pipelines/shap_e/pipeline_shap_e.py +390 -0
  58. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +349 -0
  59. diffusers/pipelines/shap_e/renderer.py +709 -0
  60. diffusers/pipelines/stable_diffusion/__init__.py +2 -0
  61. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +261 -66
  62. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +3 -3
  63. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -3
  64. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -2
  65. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  66. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +1 -1
  67. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  68. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +719 -0
  69. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -1
  70. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +832 -0
  71. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +17 -7
  72. diffusers/pipelines/stable_diffusion_xl/__init__.py +26 -0
  73. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +823 -0
  74. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +896 -0
  75. diffusers/pipelines/stable_diffusion_xl/watermark.py +31 -0
  76. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -1
  77. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -1
  78. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +771 -0
  79. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +92 -6
  80. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  81. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +209 -91
  82. diffusers/schedulers/__init__.py +3 -0
  83. diffusers/schedulers/scheduling_consistency_models.py +380 -0
  84. diffusers/schedulers/scheduling_ddim.py +28 -6
  85. diffusers/schedulers/scheduling_ddim_inverse.py +19 -4
  86. diffusers/schedulers/scheduling_ddim_parallel.py +642 -0
  87. diffusers/schedulers/scheduling_ddpm.py +53 -7
  88. diffusers/schedulers/scheduling_ddpm_parallel.py +604 -0
  89. diffusers/schedulers/scheduling_deis_multistep.py +66 -11
  90. diffusers/schedulers/scheduling_dpmsolver_multistep.py +55 -13
  91. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +19 -4
  92. diffusers/schedulers/scheduling_dpmsolver_sde.py +73 -11
  93. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +23 -7
  94. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -9
  95. diffusers/schedulers/scheduling_euler_discrete.py +58 -8
  96. diffusers/schedulers/scheduling_heun_discrete.py +89 -14
  97. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +73 -11
  98. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +73 -11
  99. diffusers/schedulers/scheduling_lms_discrete.py +57 -8
  100. diffusers/schedulers/scheduling_pndm.py +46 -10
  101. diffusers/schedulers/scheduling_repaint.py +19 -4
  102. diffusers/schedulers/scheduling_sde_ve.py +5 -1
  103. diffusers/schedulers/scheduling_unclip.py +43 -4
  104. diffusers/schedulers/scheduling_unipc_multistep.py +48 -7
  105. diffusers/training_utils.py +1 -1
  106. diffusers/utils/__init__.py +2 -1
  107. diffusers/utils/dummy_pt_objects.py +60 -0
  108. diffusers/utils/dummy_torch_and_transformers_and_invisible_watermark_objects.py +32 -0
  109. diffusers/utils/dummy_torch_and_transformers_objects.py +180 -0
  110. diffusers/utils/hub_utils.py +1 -1
  111. diffusers/utils/import_utils.py +20 -3
  112. diffusers/utils/logging.py +15 -18
  113. diffusers/utils/outputs.py +3 -3
  114. diffusers/utils/testing_utils.py +15 -0
  115. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/METADATA +4 -2
  116. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/RECORD +120 -94
  117. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/WHEEL +1 -1
  118. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/LICENSE +0 -0
  119. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/entry_points.txt +0 -0
  120. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,771 @@
1
+ # Copyright 2023 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 inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL
20
+ import torch
21
+ from transformers import CLIPTextModel, CLIPTokenizer
22
+
23
+ from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin
24
+ from ...models import AutoencoderKL, UNet3DConditionModel
25
+ from ...schedulers import KarrasDiffusionSchedulers
26
+ from ...utils import (
27
+ is_accelerate_available,
28
+ is_accelerate_version,
29
+ logging,
30
+ randn_tensor,
31
+ replace_example_docstring,
32
+ )
33
+ from ..pipeline_utils import DiffusionPipeline
34
+ from . import TextToVideoSDPipelineOutput
35
+
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+ EXAMPLE_DOC_STRING = """
40
+ Examples:
41
+ ```py
42
+ >>> import torch
43
+ >>> from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
44
+ >>> from diffusers.utils import export_to_video
45
+
46
+ >>> pipe = DiffusionPipeline.from_pretrained("cerspense/zeroscope_v2_576w", torch_dtype=torch.float16)
47
+ >>> pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
48
+ >>> pipe.to("cuda")
49
+
50
+ >>> prompt = "spiderman running in the desert"
51
+ >>> video_frames = pipe(prompt, num_inference_steps=40, height=320, width=576, num_frames=24).frames
52
+ >>> # safe low-res video
53
+ >>> video_path = export_to_video(video_frames, output_video_path="./video_576_spiderman.mp4")
54
+
55
+ >>> # let's offload the text-to-image model
56
+ >>> pipe.to("cpu")
57
+
58
+ >>> # and load the image-to-image model
59
+ >>> pipe = DiffusionPipeline.from_pretrained(
60
+ ... "cerspense/zeroscope_v2_XL", torch_dtype=torch.float16, revision="refs/pr/15"
61
+ ... )
62
+ >>> pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
63
+ >>> pipe.enable_model_cpu_offload()
64
+
65
+ >>> # The VAE consumes A LOT of memory, let's make sure we run it in sliced mode
66
+ >>> pipe.vae.enable_slicing()
67
+
68
+ >>> # now let's upscale it
69
+ >>> video = [Image.fromarray(frame).resize((1024, 576)) for frame in video_frames]
70
+
71
+ >>> # and denoise it
72
+ >>> video_frames = pipe(prompt, video=video, strength=0.6).frames
73
+ >>> video_path = export_to_video(video_frames, output_video_path="./video_1024_spiderman.mp4")
74
+ >>> video_path
75
+ ```
76
+ """
77
+
78
+
79
+ def tensor2vid(video: torch.Tensor, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) -> List[np.ndarray]:
80
+ # This code is copied from https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
81
+ # reshape to ncfhw
82
+ mean = torch.tensor(mean, device=video.device).reshape(1, -1, 1, 1, 1)
83
+ std = torch.tensor(std, device=video.device).reshape(1, -1, 1, 1, 1)
84
+ # unnormalize back to [0,1]
85
+ video = video.mul_(std).add_(mean)
86
+ video.clamp_(0, 1)
87
+ # prepare the final outputs
88
+ i, c, f, h, w = video.shape
89
+ images = video.permute(2, 3, 0, 4, 1).reshape(
90
+ f, h, i * w, c
91
+ ) # 1st (frames, h, batch_size, w, c) 2nd (frames, h, batch_size * w, c)
92
+ images = images.unbind(dim=0) # prepare a list of indvidual (consecutive frames)
93
+ images = [(image.cpu().numpy() * 255).astype("uint8") for image in images] # f h w c
94
+ return images
95
+
96
+
97
+ def preprocess_video(video):
98
+ supported_formats = (np.ndarray, torch.Tensor, PIL.Image.Image)
99
+
100
+ if isinstance(video, supported_formats):
101
+ video = [video]
102
+ elif not (isinstance(video, list) and all(isinstance(i, supported_formats) for i in video)):
103
+ raise ValueError(
104
+ f"Input is in incorrect format: {[type(i) for i in video]}. Currently, we only support {', '.join(supported_formats)}"
105
+ )
106
+
107
+ if isinstance(video[0], PIL.Image.Image):
108
+ video = [np.array(frame) for frame in video]
109
+
110
+ if isinstance(video[0], np.ndarray):
111
+ video = np.concatenate(video, axis=0) if video[0].ndim == 5 else np.stack(video, axis=0)
112
+
113
+ if video.dtype == np.uint8:
114
+ video = np.array(video).astype(np.float32) / 255.0
115
+
116
+ if video.ndim == 4:
117
+ video = video[None, ...]
118
+
119
+ video = torch.from_numpy(video.transpose(0, 4, 1, 2, 3))
120
+
121
+ elif isinstance(video[0], torch.Tensor):
122
+ video = torch.cat(video, axis=0) if video[0].ndim == 5 else torch.stack(video, axis=0)
123
+
124
+ # don't need any preprocess if the video is latents
125
+ channel = video.shape[1]
126
+ if channel == 4:
127
+ return video
128
+
129
+ # move channels before num_frames
130
+ video = video.permute(0, 2, 1, 3, 4)
131
+
132
+ # normalize video
133
+ video = 2.0 * video - 1.0
134
+
135
+ return video
136
+
137
+
138
+ class VideoToVideoSDPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
139
+ r"""
140
+ Pipeline for text-to-video generation.
141
+
142
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
143
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
144
+
145
+ Args:
146
+ vae ([`AutoencoderKL`]):
147
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
148
+ text_encoder ([`CLIPTextModel`]):
149
+ Frozen text-encoder. Same as Stable Diffusion 2.
150
+ tokenizer (`CLIPTokenizer`):
151
+ Tokenizer of class
152
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
153
+ unet ([`UNet3DConditionModel`]): Conditional U-Net architecture to denoise the encoded video latents.
154
+ scheduler ([`SchedulerMixin`]):
155
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
156
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ vae: AutoencoderKL,
162
+ text_encoder: CLIPTextModel,
163
+ tokenizer: CLIPTokenizer,
164
+ unet: UNet3DConditionModel,
165
+ scheduler: KarrasDiffusionSchedulers,
166
+ ):
167
+ super().__init__()
168
+
169
+ self.register_modules(
170
+ vae=vae,
171
+ text_encoder=text_encoder,
172
+ tokenizer=tokenizer,
173
+ unet=unet,
174
+ scheduler=scheduler,
175
+ )
176
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
177
+
178
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
179
+ def enable_vae_slicing(self):
180
+ r"""
181
+ Enable sliced VAE decoding.
182
+
183
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
184
+ steps. This is useful to save some memory and allow larger batch sizes.
185
+ """
186
+ self.vae.enable_slicing()
187
+
188
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
189
+ def disable_vae_slicing(self):
190
+ r"""
191
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
192
+ computing decoding in one step.
193
+ """
194
+ self.vae.disable_slicing()
195
+
196
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
197
+ def enable_vae_tiling(self):
198
+ r"""
199
+ Enable tiled VAE decoding.
200
+
201
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
202
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
203
+ """
204
+ self.vae.enable_tiling()
205
+
206
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
207
+ def disable_vae_tiling(self):
208
+ r"""
209
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
210
+ computing decoding in one step.
211
+ """
212
+ self.vae.disable_tiling()
213
+
214
+ def enable_sequential_cpu_offload(self, gpu_id=0):
215
+ r"""
216
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
217
+ text_encoder, vae have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded
218
+ to GPU only when their specific submodule has its `forward` method called. Note that offloading happens on a
219
+ submodule basis. Memory savings are higher than with `enable_model_cpu_offload`, but performance is lower.
220
+ """
221
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
222
+ from accelerate import cpu_offload
223
+ else:
224
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
225
+
226
+ device = torch.device(f"cuda:{gpu_id}")
227
+
228
+ if self.device.type != "cpu":
229
+ self.to("cpu", silence_dtype_warnings=True)
230
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
231
+
232
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
233
+ cpu_offload(cpu_offloaded_model, device)
234
+
235
+ def enable_model_cpu_offload(self, gpu_id=0):
236
+ r"""
237
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
238
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
239
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
240
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
241
+ """
242
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
243
+ from accelerate import cpu_offload_with_hook
244
+ else:
245
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
246
+
247
+ device = torch.device(f"cuda:{gpu_id}")
248
+
249
+ if self.device.type != "cpu":
250
+ self.to("cpu", silence_dtype_warnings=True)
251
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
252
+
253
+ hook = None
254
+ for cpu_offloaded_model in [self.text_encoder, self.vae, self.unet]:
255
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
256
+
257
+ # We'll offload the last model manually.
258
+ self.final_offload_hook = hook
259
+
260
+ @property
261
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
262
+ def _execution_device(self):
263
+ r"""
264
+ Returns the device on which the pipeline's models will be executed. After calling
265
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
266
+ hooks.
267
+ """
268
+ if not hasattr(self.unet, "_hf_hook"):
269
+ return self.device
270
+ for module in self.unet.modules():
271
+ if (
272
+ hasattr(module, "_hf_hook")
273
+ and hasattr(module._hf_hook, "execution_device")
274
+ and module._hf_hook.execution_device is not None
275
+ ):
276
+ return torch.device(module._hf_hook.execution_device)
277
+ return self.device
278
+
279
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
280
+ def _encode_prompt(
281
+ self,
282
+ prompt,
283
+ device,
284
+ num_images_per_prompt,
285
+ do_classifier_free_guidance,
286
+ negative_prompt=None,
287
+ prompt_embeds: Optional[torch.FloatTensor] = None,
288
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
289
+ lora_scale: Optional[float] = None,
290
+ ):
291
+ r"""
292
+ Encodes the prompt into text encoder hidden states.
293
+
294
+ Args:
295
+ prompt (`str` or `List[str]`, *optional*):
296
+ prompt to be encoded
297
+ device: (`torch.device`):
298
+ torch device
299
+ num_images_per_prompt (`int`):
300
+ number of images that should be generated per prompt
301
+ do_classifier_free_guidance (`bool`):
302
+ whether to use classifier free guidance or not
303
+ negative_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
305
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
306
+ less than `1`).
307
+ prompt_embeds (`torch.FloatTensor`, *optional*):
308
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
309
+ provided, text embeddings will be generated from `prompt` input argument.
310
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
311
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
312
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
313
+ argument.
314
+ lora_scale (`float`, *optional*):
315
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
316
+ """
317
+ # set lora scale so that monkey patched LoRA
318
+ # function of text encoder can correctly access it
319
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
320
+ self._lora_scale = lora_scale
321
+
322
+ if prompt is not None and isinstance(prompt, str):
323
+ batch_size = 1
324
+ elif prompt is not None and isinstance(prompt, list):
325
+ batch_size = len(prompt)
326
+ else:
327
+ batch_size = prompt_embeds.shape[0]
328
+
329
+ if prompt_embeds is None:
330
+ # textual inversion: procecss multi-vector tokens if necessary
331
+ if isinstance(self, TextualInversionLoaderMixin):
332
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
333
+
334
+ text_inputs = self.tokenizer(
335
+ prompt,
336
+ padding="max_length",
337
+ max_length=self.tokenizer.model_max_length,
338
+ truncation=True,
339
+ return_tensors="pt",
340
+ )
341
+ text_input_ids = text_inputs.input_ids
342
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
343
+
344
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
345
+ text_input_ids, untruncated_ids
346
+ ):
347
+ removed_text = self.tokenizer.batch_decode(
348
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
349
+ )
350
+ logger.warning(
351
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
352
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
353
+ )
354
+
355
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
356
+ attention_mask = text_inputs.attention_mask.to(device)
357
+ else:
358
+ attention_mask = None
359
+
360
+ prompt_embeds = self.text_encoder(
361
+ text_input_ids.to(device),
362
+ attention_mask=attention_mask,
363
+ )
364
+ prompt_embeds = prompt_embeds[0]
365
+
366
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
367
+
368
+ bs_embed, seq_len, _ = prompt_embeds.shape
369
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
370
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
371
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
372
+
373
+ # get unconditional embeddings for classifier free guidance
374
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
375
+ uncond_tokens: List[str]
376
+ if negative_prompt is None:
377
+ uncond_tokens = [""] * batch_size
378
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
379
+ raise TypeError(
380
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
381
+ f" {type(prompt)}."
382
+ )
383
+ elif isinstance(negative_prompt, str):
384
+ uncond_tokens = [negative_prompt]
385
+ elif batch_size != len(negative_prompt):
386
+ raise ValueError(
387
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
388
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
389
+ " the batch size of `prompt`."
390
+ )
391
+ else:
392
+ uncond_tokens = negative_prompt
393
+
394
+ # textual inversion: procecss multi-vector tokens if necessary
395
+ if isinstance(self, TextualInversionLoaderMixin):
396
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
397
+
398
+ max_length = prompt_embeds.shape[1]
399
+ uncond_input = self.tokenizer(
400
+ uncond_tokens,
401
+ padding="max_length",
402
+ max_length=max_length,
403
+ truncation=True,
404
+ return_tensors="pt",
405
+ )
406
+
407
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
408
+ attention_mask = uncond_input.attention_mask.to(device)
409
+ else:
410
+ attention_mask = None
411
+
412
+ negative_prompt_embeds = self.text_encoder(
413
+ uncond_input.input_ids.to(device),
414
+ attention_mask=attention_mask,
415
+ )
416
+ negative_prompt_embeds = negative_prompt_embeds[0]
417
+
418
+ if do_classifier_free_guidance:
419
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
420
+ seq_len = negative_prompt_embeds.shape[1]
421
+
422
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
423
+
424
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
425
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
426
+
427
+ # For classifier free guidance, we need to do two forward passes.
428
+ # Here we concatenate the unconditional and text embeddings into a single batch
429
+ # to avoid doing two forward passes
430
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
431
+
432
+ return prompt_embeds
433
+
434
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
435
+ def decode_latents(self, latents):
436
+ latents = 1 / self.vae.config.scaling_factor * latents
437
+
438
+ batch_size, channels, num_frames, height, width = latents.shape
439
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
440
+
441
+ image = self.vae.decode(latents).sample
442
+ video = (
443
+ image[None, :]
444
+ .reshape(
445
+ (
446
+ batch_size,
447
+ num_frames,
448
+ -1,
449
+ )
450
+ + image.shape[2:]
451
+ )
452
+ .permute(0, 2, 1, 3, 4)
453
+ )
454
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
455
+ video = video.float()
456
+ return video
457
+
458
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
459
+ def prepare_extra_step_kwargs(self, generator, eta):
460
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
461
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
462
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
463
+ # and should be between [0, 1]
464
+
465
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
466
+ extra_step_kwargs = {}
467
+ if accepts_eta:
468
+ extra_step_kwargs["eta"] = eta
469
+
470
+ # check if the scheduler accepts generator
471
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
472
+ if accepts_generator:
473
+ extra_step_kwargs["generator"] = generator
474
+ return extra_step_kwargs
475
+
476
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.check_inputs
477
+ def check_inputs(
478
+ self, prompt, strength, callback_steps, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None
479
+ ):
480
+ if strength < 0 or strength > 1:
481
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
482
+
483
+ if (callback_steps is None) or (
484
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
485
+ ):
486
+ raise ValueError(
487
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
488
+ f" {type(callback_steps)}."
489
+ )
490
+
491
+ if prompt is not None and prompt_embeds is not None:
492
+ raise ValueError(
493
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
494
+ " only forward one of the two."
495
+ )
496
+ elif prompt is None and prompt_embeds is None:
497
+ raise ValueError(
498
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
499
+ )
500
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
501
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
502
+
503
+ if negative_prompt is not None and negative_prompt_embeds is not None:
504
+ raise ValueError(
505
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
506
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
507
+ )
508
+
509
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
510
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
511
+ raise ValueError(
512
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
513
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
514
+ f" {negative_prompt_embeds.shape}."
515
+ )
516
+
517
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
518
+ def get_timesteps(self, num_inference_steps, strength, device):
519
+ # get the original timestep using init_timestep
520
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
521
+
522
+ t_start = max(num_inference_steps - init_timestep, 0)
523
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
524
+
525
+ return timesteps, num_inference_steps - t_start
526
+
527
+ def prepare_latents(self, video, timestep, batch_size, dtype, device, generator=None):
528
+ video = video.to(device=device, dtype=dtype)
529
+
530
+ # change from (b, c, f, h, w) -> (b * f, c, w, h)
531
+ bsz, channel, frames, width, height = video.shape
532
+ video = video.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
533
+
534
+ if video.shape[1] == 4:
535
+ init_latents = video
536
+ else:
537
+ if isinstance(generator, list) and len(generator) != batch_size:
538
+ raise ValueError(
539
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
540
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
541
+ )
542
+
543
+ elif isinstance(generator, list):
544
+ init_latents = [
545
+ self.vae.encode(video[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
546
+ ]
547
+ init_latents = torch.cat(init_latents, dim=0)
548
+ else:
549
+ init_latents = self.vae.encode(video).latent_dist.sample(generator)
550
+
551
+ init_latents = self.vae.config.scaling_factor * init_latents
552
+
553
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
554
+ raise ValueError(
555
+ f"Cannot duplicate `video` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
556
+ )
557
+ else:
558
+ init_latents = torch.cat([init_latents], dim=0)
559
+
560
+ shape = init_latents.shape
561
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
562
+
563
+ # get latents
564
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
565
+ latents = init_latents
566
+
567
+ latents = latents[None, :].reshape((bsz, frames, latents.shape[1]) + latents.shape[2:]).permute(0, 2, 1, 3, 4)
568
+
569
+ return latents
570
+
571
+ @torch.no_grad()
572
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
573
+ def __call__(
574
+ self,
575
+ prompt: Union[str, List[str]] = None,
576
+ video: Union[List[np.ndarray], torch.FloatTensor] = None,
577
+ strength: float = 0.6,
578
+ num_inference_steps: int = 50,
579
+ guidance_scale: float = 15.0,
580
+ negative_prompt: Optional[Union[str, List[str]]] = None,
581
+ eta: float = 0.0,
582
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
583
+ latents: Optional[torch.FloatTensor] = None,
584
+ prompt_embeds: Optional[torch.FloatTensor] = None,
585
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
586
+ output_type: Optional[str] = "np",
587
+ return_dict: bool = True,
588
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
589
+ callback_steps: int = 1,
590
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
591
+ ):
592
+ r"""
593
+ Function invoked when calling the pipeline for generation.
594
+
595
+ Args:
596
+ prompt (`str` or `List[str]`, *optional*):
597
+ The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.
598
+ instead.
599
+ video: (`List[np.ndarray]` or `torch.FloatTensor`):
600
+ `video` frames or tensor representing a video batch, that will be used as the starting point for the
601
+ process. Can also accpet video latents as `image`, if passing latents directly, it will not be encoded
602
+ again.
603
+ strength (`float`, *optional*, defaults to 0.8):
604
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
605
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
606
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
607
+ be maximum and the denoising process will run for the full number of iterations specified in
608
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
609
+ num_inference_steps (`int`, *optional*, defaults to 50):
610
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
611
+ expense of slower inference.
612
+ guidance_scale (`float`, *optional*, defaults to 7.5):
613
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
614
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
615
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
616
+ 1`. Higher guidance scale encourages to generate videos that are closely linked to the text `prompt`,
617
+ usually at the expense of lower video quality.
618
+ negative_prompt (`str` or `List[str]`, *optional*):
619
+ The prompt or prompts not to guide the video generation. If not defined, one has to pass
620
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
621
+ less than `1`).
622
+ eta (`float`, *optional*, defaults to 0.0):
623
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
624
+ [`schedulers.DDIMScheduler`], will be ignored for others.
625
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
626
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
627
+ to make generation deterministic.
628
+ latents (`torch.FloatTensor`, *optional*):
629
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video
630
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
631
+ tensor will ge generated by sampling using the supplied random `generator`. Latents should be of shape
632
+ `(batch_size, num_channel, num_frames, height, width)`.
633
+ prompt_embeds (`torch.FloatTensor`, *optional*):
634
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
635
+ provided, text embeddings will be generated from `prompt` input argument.
636
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
637
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
638
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
639
+ argument.
640
+ output_type (`str`, *optional*, defaults to `"np"`):
641
+ The output format of the generate video. Choose between `torch.FloatTensor` or `np.array`.
642
+ return_dict (`bool`, *optional*, defaults to `True`):
643
+ Whether or not to return a [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] instead of a
644
+ plain tuple.
645
+ callback (`Callable`, *optional*):
646
+ A function that will be called every `callback_steps` steps during inference. The function will be
647
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
648
+ callback_steps (`int`, *optional*, defaults to 1):
649
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
650
+ called at every step.
651
+ cross_attention_kwargs (`dict`, *optional*):
652
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
653
+ `self.processor` in
654
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
655
+
656
+ Examples:
657
+
658
+ Returns:
659
+ [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] or `tuple`:
660
+ [`~pipelines.stable_diffusion.TextToVideoSDPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
661
+ When returning a tuple, the first element is a list with the generated frames.
662
+ """
663
+ # 0. Default height and width to unet
664
+ num_images_per_prompt = 1
665
+
666
+ # 1. Check inputs. Raise error if not correct
667
+ self.check_inputs(prompt, strength, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
668
+
669
+ # 2. Define call parameters
670
+ if prompt is not None and isinstance(prompt, str):
671
+ batch_size = 1
672
+ elif prompt is not None and isinstance(prompt, list):
673
+ batch_size = len(prompt)
674
+ else:
675
+ batch_size = prompt_embeds.shape[0]
676
+
677
+ device = self._execution_device
678
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
679
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
680
+ # corresponds to doing no classifier free guidance.
681
+ do_classifier_free_guidance = guidance_scale > 1.0
682
+
683
+ # 3. Encode input prompt
684
+ text_encoder_lora_scale = (
685
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
686
+ )
687
+ prompt_embeds = self._encode_prompt(
688
+ prompt,
689
+ device,
690
+ num_images_per_prompt,
691
+ do_classifier_free_guidance,
692
+ negative_prompt,
693
+ prompt_embeds=prompt_embeds,
694
+ negative_prompt_embeds=negative_prompt_embeds,
695
+ lora_scale=text_encoder_lora_scale,
696
+ )
697
+
698
+ # 4. Preprocess video
699
+ video = preprocess_video(video)
700
+
701
+ # 5. Prepare timesteps
702
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
703
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
704
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
705
+
706
+ # 5. Prepare latent variables
707
+ latents = self.prepare_latents(video, latent_timestep, batch_size, prompt_embeds.dtype, device, generator)
708
+
709
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
710
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
711
+
712
+ # 7. Denoising loop
713
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
714
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
715
+ for i, t in enumerate(timesteps):
716
+ # expand the latents if we are doing classifier free guidance
717
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
718
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
719
+
720
+ # predict the noise residual
721
+ noise_pred = self.unet(
722
+ latent_model_input,
723
+ t,
724
+ encoder_hidden_states=prompt_embeds,
725
+ cross_attention_kwargs=cross_attention_kwargs,
726
+ return_dict=False,
727
+ )[0]
728
+
729
+ # perform guidance
730
+ if do_classifier_free_guidance:
731
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
732
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
733
+
734
+ # reshape latents
735
+ bsz, channel, frames, width, height = latents.shape
736
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
737
+ noise_pred = noise_pred.permute(0, 2, 1, 3, 4).reshape(bsz * frames, channel, width, height)
738
+
739
+ # compute the previous noisy sample x_t -> x_t-1
740
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
741
+
742
+ # reshape latents back
743
+ latents = latents[None, :].reshape(bsz, frames, channel, width, height).permute(0, 2, 1, 3, 4)
744
+
745
+ # call the callback, if provided
746
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
747
+ progress_bar.update()
748
+ if callback is not None and i % callback_steps == 0:
749
+ callback(i, t, latents)
750
+
751
+ if output_type == "latent":
752
+ return TextToVideoSDPipelineOutput(frames=latents)
753
+
754
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
755
+ self.unet.to("cpu")
756
+
757
+ video_tensor = self.decode_latents(latents)
758
+
759
+ if output_type == "pt":
760
+ video = video_tensor
761
+ else:
762
+ video = tensor2vid(video_tensor)
763
+
764
+ # Offload last model to CPU
765
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
766
+ self.final_offload_hook.offload()
767
+
768
+ if not return_dict:
769
+ return (video,)
770
+
771
+ return TextToVideoSDPipelineOutput(frames=video)