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,434 @@
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
+ from typing import List, Optional, Union
16
+
17
+ import numpy as np
18
+ import PIL
19
+ import torch
20
+ from PIL import Image
21
+
22
+ from ...models import UNet2DConditionModel, VQModel
23
+ from ...pipelines import DiffusionPipeline
24
+ from ...pipelines.pipeline_utils import ImagePipelineOutput
25
+ from ...schedulers import DDPMScheduler
26
+ from ...utils import (
27
+ is_accelerate_available,
28
+ is_accelerate_version,
29
+ logging,
30
+ randn_tensor,
31
+ replace_example_docstring,
32
+ )
33
+
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+ EXAMPLE_DOC_STRING = """
38
+ Examples:
39
+ ```py
40
+ >>> import torch
41
+ >>> import numpy as np
42
+
43
+ >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
44
+ >>> from transformers import pipeline
45
+ >>> from diffusers.utils import load_image
46
+
47
+
48
+ >>> def make_hint(image, depth_estimator):
49
+ ... image = depth_estimator(image)["depth"]
50
+ ... image = np.array(image)
51
+ ... image = image[:, :, None]
52
+ ... image = np.concatenate([image, image, image], axis=2)
53
+ ... detected_map = torch.from_numpy(image).float() / 255.0
54
+ ... hint = detected_map.permute(2, 0, 1)
55
+ ... return hint
56
+
57
+
58
+ >>> depth_estimator = pipeline("depth-estimation")
59
+
60
+ >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
61
+ ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
62
+ ... )
63
+ >>> pipe_prior = pipe_prior.to("cuda")
64
+
65
+ >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
66
+ ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
67
+ ... )
68
+ >>> pipe = pipe.to("cuda")
69
+
70
+ >>> img = load_image(
71
+ ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
72
+ ... "/kandinsky/cat.png"
73
+ ... ).resize((768, 768))
74
+
75
+
76
+ >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")
77
+
78
+ >>> prompt = "A robot, 4k photo"
79
+ >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"
80
+
81
+ >>> generator = torch.Generator(device="cuda").manual_seed(43)
82
+
83
+ >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
84
+ >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)
85
+
86
+ >>> images = pipe(
87
+ ... image=img,
88
+ ... strength=0.5,
89
+ ... image_embeds=img_emb.image_embeds,
90
+ ... negative_image_embeds=negative_emb.image_embeds,
91
+ ... hint=hint,
92
+ ... num_inference_steps=50,
93
+ ... generator=generator,
94
+ ... height=768,
95
+ ... width=768,
96
+ ... ).images
97
+
98
+ >>> images[0].save("robot_cat.png")
99
+ ```
100
+ """
101
+
102
+
103
+ # Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.downscale_height_and_width
104
+ def downscale_height_and_width(height, width, scale_factor=8):
105
+ new_height = height // scale_factor**2
106
+ if height % scale_factor**2 != 0:
107
+ new_height += 1
108
+ new_width = width // scale_factor**2
109
+ if width % scale_factor**2 != 0:
110
+ new_width += 1
111
+ return new_height * scale_factor, new_width * scale_factor
112
+
113
+
114
+ # Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.prepare_image
115
+ def prepare_image(pil_image, w=512, h=512):
116
+ pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1)
117
+ arr = np.array(pil_image.convert("RGB"))
118
+ arr = arr.astype(np.float32) / 127.5 - 1
119
+ arr = np.transpose(arr, [2, 0, 1])
120
+ image = torch.from_numpy(arr).unsqueeze(0)
121
+ return image
122
+
123
+
124
+ class KandinskyV22ControlnetImg2ImgPipeline(DiffusionPipeline):
125
+ """
126
+ Pipeline for image-to-image generation using Kandinsky
127
+
128
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
129
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
130
+
131
+ Args:
132
+ scheduler ([`DDIMScheduler`]):
133
+ A scheduler to be used in combination with `unet` to generate image latents.
134
+ unet ([`UNet2DConditionModel`]):
135
+ Conditional U-Net architecture to denoise the image embedding.
136
+ movq ([`VQModel`]):
137
+ MoVQ Decoder to generate the image from the latents.
138
+ """
139
+
140
+ def __init__(
141
+ self,
142
+ unet: UNet2DConditionModel,
143
+ scheduler: DDPMScheduler,
144
+ movq: VQModel,
145
+ ):
146
+ super().__init__()
147
+
148
+ self.register_modules(
149
+ unet=unet,
150
+ scheduler=scheduler,
151
+ movq=movq,
152
+ )
153
+ self.movq_scale_factor = 2 ** (len(self.movq.config.block_out_channels) - 1)
154
+
155
+ # Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.KandinskyImg2ImgPipeline.get_timesteps
156
+ def get_timesteps(self, num_inference_steps, strength, device):
157
+ # get the original timestep using init_timestep
158
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
159
+
160
+ t_start = max(num_inference_steps - init_timestep, 0)
161
+ timesteps = self.scheduler.timesteps[t_start:]
162
+
163
+ return timesteps, num_inference_steps - t_start
164
+
165
+ # Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2_img2img.KandinskyV22Img2ImgPipeline.prepare_latents
166
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
167
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
168
+ raise ValueError(
169
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
170
+ )
171
+
172
+ image = image.to(device=device, dtype=dtype)
173
+
174
+ batch_size = batch_size * num_images_per_prompt
175
+
176
+ if image.shape[1] == 4:
177
+ init_latents = image
178
+
179
+ else:
180
+ if isinstance(generator, list) and len(generator) != batch_size:
181
+ raise ValueError(
182
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
183
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
184
+ )
185
+
186
+ elif isinstance(generator, list):
187
+ init_latents = [
188
+ self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
189
+ ]
190
+ init_latents = torch.cat(init_latents, dim=0)
191
+ else:
192
+ init_latents = self.movq.encode(image).latent_dist.sample(generator)
193
+
194
+ init_latents = self.movq.config.scaling_factor * init_latents
195
+
196
+ init_latents = torch.cat([init_latents], dim=0)
197
+
198
+ shape = init_latents.shape
199
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
200
+
201
+ # get latents
202
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
203
+
204
+ latents = init_latents
205
+
206
+ return latents
207
+
208
+ # Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.KandinskyV22Pipeline.enable_sequential_cpu_offload
209
+ def enable_sequential_cpu_offload(self, gpu_id=0):
210
+ r"""
211
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
212
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
213
+ when their specific submodule has its `forward` method called.
214
+ """
215
+ if is_accelerate_available():
216
+ from accelerate import cpu_offload
217
+ else:
218
+ raise ImportError("Please install accelerate via `pip install accelerate`")
219
+
220
+ device = torch.device(f"cuda:{gpu_id}")
221
+
222
+ models = [
223
+ self.unet,
224
+ self.movq,
225
+ ]
226
+ for cpu_offloaded_model in models:
227
+ if cpu_offloaded_model is not None:
228
+ cpu_offload(cpu_offloaded_model, device)
229
+
230
+ # Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.KandinskyV22Pipeline.enable_model_cpu_offload
231
+ def enable_model_cpu_offload(self, gpu_id=0):
232
+ r"""
233
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
234
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
235
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
236
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
237
+ """
238
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
239
+ from accelerate import cpu_offload_with_hook
240
+ else:
241
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
242
+
243
+ device = torch.device(f"cuda:{gpu_id}")
244
+
245
+ if self.device.type != "cpu":
246
+ self.to("cpu", silence_dtype_warnings=True)
247
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
248
+
249
+ hook = None
250
+ for cpu_offloaded_model in [self.unet, self.movq]:
251
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
252
+
253
+ # We'll offload the last model manually.
254
+ self.final_offload_hook = hook
255
+
256
+ @property
257
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
258
+ def _execution_device(self):
259
+ r"""
260
+ Returns the device on which the pipeline's models will be executed. After calling
261
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
262
+ hooks.
263
+ """
264
+ if not hasattr(self.unet, "_hf_hook"):
265
+ return self.device
266
+ for module in self.unet.modules():
267
+ if (
268
+ hasattr(module, "_hf_hook")
269
+ and hasattr(module._hf_hook, "execution_device")
270
+ and module._hf_hook.execution_device is not None
271
+ ):
272
+ return torch.device(module._hf_hook.execution_device)
273
+ return self.device
274
+
275
+ @torch.no_grad()
276
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
277
+ def __call__(
278
+ self,
279
+ image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]],
280
+ image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]],
281
+ negative_image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]],
282
+ hint: torch.FloatTensor,
283
+ height: int = 512,
284
+ width: int = 512,
285
+ num_inference_steps: int = 100,
286
+ guidance_scale: float = 4.0,
287
+ strength: float = 0.3,
288
+ num_images_per_prompt: int = 1,
289
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
290
+ output_type: Optional[str] = "pil",
291
+ return_dict: bool = True,
292
+ ):
293
+ """
294
+ Function invoked when calling the pipeline for generation.
295
+
296
+ Args:
297
+ image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`):
298
+ The clip image embeddings for text prompt, that will be used to condition the image generation.
299
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
300
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
301
+ process. Can also accpet image latents as `image`, if passing latents directly, it will not be encoded
302
+ again.
303
+ strength (`float`, *optional*, defaults to 0.8):
304
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
305
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
306
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
307
+ be maximum and the denoising process will run for the full number of iterations specified in
308
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
309
+ hint (`torch.FloatTensor`):
310
+ The controlnet condition.
311
+ negative_image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`):
312
+ The clip image embeddings for negative text prompt, will be used to condition the image generation.
313
+ height (`int`, *optional*, defaults to 512):
314
+ The height in pixels of the generated image.
315
+ width (`int`, *optional*, defaults to 512):
316
+ The width in pixels of the generated image.
317
+ num_inference_steps (`int`, *optional*, defaults to 100):
318
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
319
+ expense of slower inference.
320
+ guidance_scale (`float`, *optional*, defaults to 4.0):
321
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
322
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
323
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
324
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
325
+ usually at the expense of lower image quality.
326
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
327
+ The number of images to generate per prompt.
328
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
329
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
330
+ to make generation deterministic.
331
+ output_type (`str`, *optional*, defaults to `"pil"`):
332
+ The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
333
+ (`np.array`) or `"pt"` (`torch.Tensor`).
334
+ return_dict (`bool`, *optional*, defaults to `True`):
335
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
336
+
337
+ Examples:
338
+
339
+ Returns:
340
+ [`~pipelines.ImagePipelineOutput`] or `tuple`
341
+ """
342
+ device = self._execution_device
343
+
344
+ do_classifier_free_guidance = guidance_scale > 1.0
345
+
346
+ if isinstance(image_embeds, list):
347
+ image_embeds = torch.cat(image_embeds, dim=0)
348
+ if isinstance(negative_image_embeds, list):
349
+ negative_image_embeds = torch.cat(negative_image_embeds, dim=0)
350
+ if isinstance(hint, list):
351
+ hint = torch.cat(hint, dim=0)
352
+
353
+ batch_size = image_embeds.shape[0]
354
+
355
+ if do_classifier_free_guidance:
356
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
357
+ negative_image_embeds = negative_image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
358
+ hint = hint.repeat_interleave(num_images_per_prompt, dim=0)
359
+
360
+ image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0).to(dtype=self.unet.dtype, device=device)
361
+ hint = torch.cat([hint, hint], dim=0).to(dtype=self.unet.dtype, device=device)
362
+
363
+ if not isinstance(image, list):
364
+ image = [image]
365
+ if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image):
366
+ raise ValueError(
367
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor"
368
+ )
369
+
370
+ image = torch.cat([prepare_image(i, width, height) for i in image], dim=0)
371
+ image = image.to(dtype=image_embeds.dtype, device=device)
372
+
373
+ latents = self.movq.encode(image)["latents"]
374
+ latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
375
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
376
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
377
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
378
+ height, width = downscale_height_and_width(height, width, self.movq_scale_factor)
379
+ latents = self.prepare_latents(
380
+ latents, latent_timestep, batch_size, num_images_per_prompt, image_embeds.dtype, device, generator
381
+ )
382
+ for i, t in enumerate(self.progress_bar(timesteps)):
383
+ # expand the latents if we are doing classifier free guidance
384
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
385
+
386
+ added_cond_kwargs = {"image_embeds": image_embeds, "hint": hint}
387
+ noise_pred = self.unet(
388
+ sample=latent_model_input,
389
+ timestep=t,
390
+ encoder_hidden_states=None,
391
+ added_cond_kwargs=added_cond_kwargs,
392
+ return_dict=False,
393
+ )[0]
394
+
395
+ if do_classifier_free_guidance:
396
+ noise_pred, variance_pred = noise_pred.split(latents.shape[1], dim=1)
397
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
398
+ _, variance_pred_text = variance_pred.chunk(2)
399
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
400
+ noise_pred = torch.cat([noise_pred, variance_pred_text], dim=1)
401
+
402
+ if not (
403
+ hasattr(self.scheduler.config, "variance_type")
404
+ and self.scheduler.config.variance_type in ["learned", "learned_range"]
405
+ ):
406
+ noise_pred, _ = noise_pred.split(latents.shape[1], dim=1)
407
+
408
+ # compute the previous noisy sample x_t -> x_t-1
409
+
410
+ latents = self.scheduler.step(
411
+ noise_pred,
412
+ t,
413
+ latents,
414
+ generator=generator,
415
+ )[0]
416
+
417
+ # post-processing
418
+ image = self.movq.decode(latents, force_not_quantize=True)["sample"]
419
+
420
+ if output_type not in ["pt", "np", "pil"]:
421
+ raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}")
422
+
423
+ if output_type in ["np", "pil"]:
424
+ image = image * 0.5 + 0.5
425
+ image = image.clamp(0, 1)
426
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
427
+
428
+ if output_type == "pil":
429
+ image = self.numpy_to_pil(image)
430
+
431
+ if not return_dict:
432
+ return (image,)
433
+
434
+ return ImagePipelineOutput(images=image)