diffusers 0.28.2__py3-none-any.whl → 0.29.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. diffusers/__init__.py +15 -1
  2. diffusers/commands/env.py +1 -5
  3. diffusers/dependency_versions_table.py +1 -1
  4. diffusers/image_processor.py +2 -1
  5. diffusers/loaders/__init__.py +2 -2
  6. diffusers/loaders/lora.py +406 -140
  7. diffusers/loaders/lora_conversion_utils.py +7 -1
  8. diffusers/loaders/single_file.py +13 -1
  9. diffusers/loaders/single_file_model.py +15 -8
  10. diffusers/loaders/single_file_utils.py +267 -17
  11. diffusers/loaders/unet.py +307 -272
  12. diffusers/models/__init__.py +7 -3
  13. diffusers/models/attention.py +125 -1
  14. diffusers/models/attention_processor.py +169 -1
  15. diffusers/models/autoencoders/__init__.py +1 -0
  16. diffusers/models/autoencoders/autoencoder_asym_kl.py +1 -1
  17. diffusers/models/autoencoders/autoencoder_kl.py +17 -6
  18. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -2
  19. diffusers/models/autoencoders/consistency_decoder_vae.py +9 -9
  20. diffusers/models/autoencoders/vq_model.py +182 -0
  21. diffusers/models/controlnet_sd3.py +418 -0
  22. diffusers/models/controlnet_xs.py +6 -6
  23. diffusers/models/embeddings.py +112 -84
  24. diffusers/models/model_loading_utils.py +55 -0
  25. diffusers/models/modeling_utils.py +138 -20
  26. diffusers/models/normalization.py +11 -6
  27. diffusers/models/transformers/__init__.py +1 -0
  28. diffusers/models/transformers/dual_transformer_2d.py +5 -4
  29. diffusers/models/transformers/hunyuan_transformer_2d.py +149 -2
  30. diffusers/models/transformers/prior_transformer.py +5 -5
  31. diffusers/models/transformers/transformer_2d.py +2 -2
  32. diffusers/models/transformers/transformer_sd3.py +353 -0
  33. diffusers/models/transformers/transformer_temporal.py +12 -10
  34. diffusers/models/unets/unet_1d.py +3 -3
  35. diffusers/models/unets/unet_2d.py +3 -3
  36. diffusers/models/unets/unet_2d_condition.py +4 -15
  37. diffusers/models/unets/unet_3d_condition.py +5 -17
  38. diffusers/models/unets/unet_i2vgen_xl.py +4 -4
  39. diffusers/models/unets/unet_motion_model.py +4 -4
  40. diffusers/models/unets/unet_spatio_temporal_condition.py +3 -3
  41. diffusers/models/vq_model.py +8 -165
  42. diffusers/pipelines/__init__.py +11 -0
  43. diffusers/pipelines/animatediff/pipeline_animatediff.py +4 -3
  44. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +4 -3
  45. diffusers/pipelines/auto_pipeline.py +8 -0
  46. diffusers/pipelines/controlnet/pipeline_controlnet.py +4 -3
  47. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +4 -3
  48. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +4 -3
  49. diffusers/pipelines/controlnet_sd3/__init__.py +53 -0
  50. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1062 -0
  51. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +4 -3
  52. diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
  53. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +4 -3
  54. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +4 -3
  55. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +4 -3
  56. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +4 -3
  57. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +4 -3
  58. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +24 -5
  59. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +4 -3
  60. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +4 -3
  61. diffusers/pipelines/marigold/marigold_image_processing.py +35 -20
  62. diffusers/pipelines/pia/pipeline_pia.py +4 -3
  63. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
  64. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
  65. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +17 -17
  66. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +4 -3
  67. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -4
  68. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +4 -3
  69. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -3
  70. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +4 -3
  71. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +4 -3
  72. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +7 -6
  73. diffusers/pipelines/stable_diffusion_3/__init__.py +52 -0
  74. diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
  75. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +904 -0
  76. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +941 -0
  77. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +4 -3
  78. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +10 -11
  79. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +4 -3
  80. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  81. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +4 -3
  82. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +4 -3
  83. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +4 -3
  84. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +4 -3
  85. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +4 -3
  86. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +4 -3
  87. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +4 -3
  88. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -3
  89. diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
  90. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +4 -3
  91. diffusers/schedulers/__init__.py +2 -0
  92. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
  93. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -3
  94. diffusers/schedulers/scheduling_edm_euler.py +2 -4
  95. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +287 -0
  96. diffusers/schedulers/scheduling_lms_discrete.py +2 -2
  97. diffusers/training_utils.py +4 -4
  98. diffusers/utils/__init__.py +3 -0
  99. diffusers/utils/constants.py +2 -0
  100. diffusers/utils/dummy_pt_objects.py +60 -0
  101. diffusers/utils/dummy_torch_and_transformers_objects.py +45 -0
  102. diffusers/utils/dynamic_modules_utils.py +15 -13
  103. diffusers/utils/hub_utils.py +106 -0
  104. diffusers/utils/import_utils.py +0 -1
  105. diffusers/utils/logging.py +3 -1
  106. diffusers/utils/state_dict_utils.py +2 -0
  107. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/METADATA +3 -3
  108. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/RECORD +112 -112
  109. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/WHEEL +1 -1
  110. diffusers/models/dual_transformer_2d.py +0 -20
  111. diffusers/models/prior_transformer.py +0 -12
  112. diffusers/models/t5_film_transformer.py +0 -70
  113. diffusers/models/transformer_2d.py +0 -25
  114. diffusers/models/transformer_temporal.py +0 -34
  115. diffusers/models/unet_1d.py +0 -26
  116. diffusers/models/unet_1d_blocks.py +0 -203
  117. diffusers/models/unet_2d.py +0 -27
  118. diffusers/models/unet_2d_blocks.py +0 -375
  119. diffusers/models/unet_2d_condition.py +0 -25
  120. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/LICENSE +0 -0
  121. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/entry_points.txt +0 -0
  122. {diffusers-0.28.2.dist-info → diffusers-0.29.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,941 @@
1
+ # Copyright 2024 Stability AI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, Dict, List, Optional, Union
17
+
18
+ import PIL.Image
19
+ import torch
20
+ from transformers import (
21
+ CLIPTextModelWithProjection,
22
+ CLIPTokenizer,
23
+ T5EncoderModel,
24
+ T5TokenizerFast,
25
+ )
26
+
27
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
28
+ from ...models.autoencoders import AutoencoderKL
29
+ from ...models.transformers import SD3Transformer2DModel
30
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
31
+ from ...utils import (
32
+ is_torch_xla_available,
33
+ logging,
34
+ replace_example_docstring,
35
+ )
36
+ from ...utils.torch_utils import randn_tensor
37
+ from ..pipeline_utils import DiffusionPipeline
38
+ from .pipeline_output import StableDiffusion3PipelineOutput
39
+
40
+
41
+ if is_torch_xla_available():
42
+ import torch_xla.core.xla_model as xm
43
+
44
+ XLA_AVAILABLE = True
45
+ else:
46
+ XLA_AVAILABLE = False
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
+
56
+ >>> from diffusers import AutoPipelineForImage2Image
57
+ >>> from diffusers.utils import load_image
58
+
59
+ >>> device = "cuda"
60
+ >>> model_id_or_path = "stabilityai/stable-diffusion-3-medium-diffusers"
61
+ >>> pipe = AutoPipelineForImage2Image.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
62
+ >>> pipe = pipe.to(device)
63
+
64
+ >>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
65
+ >>> init_image = load_image(url).resize((512, 512))
66
+
67
+ >>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
68
+
69
+ >>> images = pipe(prompt=prompt, image=init_image, strength=0.95, guidance_scale=7.5).images[0]
70
+ ```
71
+ """
72
+
73
+
74
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
75
+ def retrieve_latents(
76
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
77
+ ):
78
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
79
+ return encoder_output.latent_dist.sample(generator)
80
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
81
+ return encoder_output.latent_dist.mode()
82
+ elif hasattr(encoder_output, "latents"):
83
+ return encoder_output.latents
84
+ else:
85
+ raise AttributeError("Could not access latents of provided encoder_output")
86
+
87
+
88
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
89
+ def retrieve_timesteps(
90
+ scheduler,
91
+ num_inference_steps: Optional[int] = None,
92
+ device: Optional[Union[str, torch.device]] = None,
93
+ timesteps: Optional[List[int]] = None,
94
+ sigmas: Optional[List[float]] = None,
95
+ **kwargs,
96
+ ):
97
+ """
98
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
99
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
100
+
101
+ Args:
102
+ scheduler (`SchedulerMixin`):
103
+ The scheduler to get timesteps from.
104
+ num_inference_steps (`int`):
105
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
106
+ must be `None`.
107
+ device (`str` or `torch.device`, *optional*):
108
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
109
+ timesteps (`List[int]`, *optional*):
110
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
111
+ `num_inference_steps` and `sigmas` must be `None`.
112
+ sigmas (`List[float]`, *optional*):
113
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
114
+ `num_inference_steps` and `timesteps` must be `None`.
115
+
116
+ Returns:
117
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
118
+ second element is the number of inference steps.
119
+ """
120
+ if timesteps is not None and sigmas is not None:
121
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
122
+ if timesteps is not None:
123
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
124
+ if not accepts_timesteps:
125
+ raise ValueError(
126
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
127
+ f" timestep schedules. Please check whether you are using the correct scheduler."
128
+ )
129
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
130
+ timesteps = scheduler.timesteps
131
+ num_inference_steps = len(timesteps)
132
+ elif sigmas is not None:
133
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
134
+ if not accept_sigmas:
135
+ raise ValueError(
136
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
137
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
138
+ )
139
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
140
+ timesteps = scheduler.timesteps
141
+ num_inference_steps = len(timesteps)
142
+ else:
143
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
144
+ timesteps = scheduler.timesteps
145
+ return timesteps, num_inference_steps
146
+
147
+
148
+ class StableDiffusion3Img2ImgPipeline(DiffusionPipeline):
149
+ r"""
150
+ Args:
151
+ transformer ([`SD3Transformer2DModel`]):
152
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
153
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
154
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
155
+ vae ([`AutoencoderKL`]):
156
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
157
+ text_encoder ([`CLIPTextModelWithProjection`]):
158
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
159
+ specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant,
160
+ with an additional added projection layer that is initialized with a diagonal matrix with the `hidden_size`
161
+ as its dimension.
162
+ text_encoder_2 ([`CLIPTextModelWithProjection`]):
163
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
164
+ specifically the
165
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
166
+ variant.
167
+ text_encoder_3 ([`T5EncoderModel`]):
168
+ Frozen text-encoder. Stable Diffusion 3 uses
169
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
170
+ [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
171
+ tokenizer (`CLIPTokenizer`):
172
+ Tokenizer of class
173
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
174
+ tokenizer_2 (`CLIPTokenizer`):
175
+ Second Tokenizer of class
176
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
177
+ tokenizer_3 (`T5TokenizerFast`):
178
+ Tokenizer of class
179
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
180
+ """
181
+
182
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder_3->transformer->vae"
183
+ _optional_components = []
184
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "negative_pooled_prompt_embeds"]
185
+
186
+ def __init__(
187
+ self,
188
+ transformer: SD3Transformer2DModel,
189
+ scheduler: FlowMatchEulerDiscreteScheduler,
190
+ vae: AutoencoderKL,
191
+ text_encoder: CLIPTextModelWithProjection,
192
+ tokenizer: CLIPTokenizer,
193
+ text_encoder_2: CLIPTextModelWithProjection,
194
+ tokenizer_2: CLIPTokenizer,
195
+ text_encoder_3: T5EncoderModel,
196
+ tokenizer_3: T5TokenizerFast,
197
+ ):
198
+ super().__init__()
199
+
200
+ self.register_modules(
201
+ vae=vae,
202
+ text_encoder=text_encoder,
203
+ text_encoder_2=text_encoder_2,
204
+ text_encoder_3=text_encoder_3,
205
+ tokenizer=tokenizer,
206
+ tokenizer_2=tokenizer_2,
207
+ tokenizer_3=tokenizer_3,
208
+ transformer=transformer,
209
+ scheduler=scheduler,
210
+ )
211
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
212
+ self.image_processor = VaeImageProcessor(
213
+ vae_scale_factor=self.vae_scale_factor, vae_latent_channels=self.vae.config.latent_channels
214
+ )
215
+ self.tokenizer_max_length = self.tokenizer.model_max_length
216
+ self.default_sample_size = self.transformer.config.sample_size
217
+
218
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_t5_prompt_embeds
219
+ def _get_t5_prompt_embeds(
220
+ self,
221
+ prompt: Union[str, List[str]] = None,
222
+ num_images_per_prompt: int = 1,
223
+ max_sequence_length: int = 256,
224
+ device: Optional[torch.device] = None,
225
+ dtype: Optional[torch.dtype] = None,
226
+ ):
227
+ device = device or self._execution_device
228
+ dtype = dtype or self.text_encoder.dtype
229
+
230
+ prompt = [prompt] if isinstance(prompt, str) else prompt
231
+ batch_size = len(prompt)
232
+
233
+ if self.text_encoder_3 is None:
234
+ return torch.zeros(
235
+ (
236
+ batch_size * num_images_per_prompt,
237
+ self.tokenizer_max_length,
238
+ self.transformer.config.joint_attention_dim,
239
+ ),
240
+ device=device,
241
+ dtype=dtype,
242
+ )
243
+
244
+ text_inputs = self.tokenizer_3(
245
+ prompt,
246
+ padding="max_length",
247
+ max_length=max_sequence_length,
248
+ truncation=True,
249
+ add_special_tokens=True,
250
+ return_tensors="pt",
251
+ )
252
+ text_input_ids = text_inputs.input_ids
253
+ untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
254
+
255
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
256
+ removed_text = self.tokenizer_3.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
257
+ logger.warning(
258
+ "The following part of your input was truncated because `max_sequence_length` is set to "
259
+ f" {max_sequence_length} tokens: {removed_text}"
260
+ )
261
+
262
+ prompt_embeds = self.text_encoder_3(text_input_ids.to(device))[0]
263
+
264
+ dtype = self.text_encoder_3.dtype
265
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
266
+
267
+ _, seq_len, _ = prompt_embeds.shape
268
+
269
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
270
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
271
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
272
+
273
+ return prompt_embeds
274
+
275
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_clip_prompt_embeds
276
+ def _get_clip_prompt_embeds(
277
+ self,
278
+ prompt: Union[str, List[str]],
279
+ num_images_per_prompt: int = 1,
280
+ device: Optional[torch.device] = None,
281
+ clip_skip: Optional[int] = None,
282
+ clip_model_index: int = 0,
283
+ ):
284
+ device = device or self._execution_device
285
+
286
+ clip_tokenizers = [self.tokenizer, self.tokenizer_2]
287
+ clip_text_encoders = [self.text_encoder, self.text_encoder_2]
288
+
289
+ tokenizer = clip_tokenizers[clip_model_index]
290
+ text_encoder = clip_text_encoders[clip_model_index]
291
+
292
+ prompt = [prompt] if isinstance(prompt, str) else prompt
293
+ batch_size = len(prompt)
294
+
295
+ text_inputs = tokenizer(
296
+ prompt,
297
+ padding="max_length",
298
+ max_length=self.tokenizer_max_length,
299
+ truncation=True,
300
+ return_tensors="pt",
301
+ )
302
+
303
+ text_input_ids = text_inputs.input_ids
304
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
305
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
306
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
307
+ logger.warning(
308
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
309
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
310
+ )
311
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
312
+ pooled_prompt_embeds = prompt_embeds[0]
313
+
314
+ if clip_skip is None:
315
+ prompt_embeds = prompt_embeds.hidden_states[-2]
316
+ else:
317
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
318
+
319
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
320
+
321
+ _, seq_len, _ = prompt_embeds.shape
322
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
323
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
324
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
325
+
326
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
327
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
328
+
329
+ return prompt_embeds, pooled_prompt_embeds
330
+
331
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline.encode_prompt
332
+ def encode_prompt(
333
+ self,
334
+ prompt: Union[str, List[str]],
335
+ prompt_2: Union[str, List[str]],
336
+ prompt_3: Union[str, List[str]],
337
+ device: Optional[torch.device] = None,
338
+ num_images_per_prompt: int = 1,
339
+ do_classifier_free_guidance: bool = True,
340
+ negative_prompt: Optional[Union[str, List[str]]] = None,
341
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
342
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
343
+ prompt_embeds: Optional[torch.FloatTensor] = None,
344
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
345
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
346
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
347
+ clip_skip: Optional[int] = None,
348
+ max_sequence_length: int = 256,
349
+ ):
350
+ r"""
351
+
352
+ Args:
353
+ prompt (`str` or `List[str]`, *optional*):
354
+ prompt to be encoded
355
+ prompt_2 (`str` or `List[str]`, *optional*):
356
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
357
+ used in all text-encoders
358
+ prompt_3 (`str` or `List[str]`, *optional*):
359
+ The prompt or prompts to be sent to the `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
360
+ used in all text-encoders
361
+ device: (`torch.device`):
362
+ torch device
363
+ num_images_per_prompt (`int`):
364
+ number of images that should be generated per prompt
365
+ do_classifier_free_guidance (`bool`):
366
+ whether to use classifier free guidance or not
367
+ negative_prompt (`str` or `List[str]`, *optional*):
368
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
369
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
370
+ less than `1`).
371
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
372
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
373
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
374
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
375
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
376
+ `text_encoder_3`. If not defined, `negative_prompt` is used in both text-encoders
377
+ prompt_embeds (`torch.FloatTensor`, *optional*):
378
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
379
+ provided, text embeddings will be generated from `prompt` input argument.
380
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
381
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
382
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
383
+ argument.
384
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
385
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
386
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
387
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
388
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
389
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
390
+ input argument.
391
+ clip_skip (`int`, *optional*):
392
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
393
+ the output of the pre-final layer will be used for computing the prompt embeddings.
394
+ """
395
+ device = device or self._execution_device
396
+
397
+ prompt = [prompt] if isinstance(prompt, str) else prompt
398
+ if prompt is not None:
399
+ batch_size = len(prompt)
400
+ else:
401
+ batch_size = prompt_embeds.shape[0]
402
+
403
+ if prompt_embeds is None:
404
+ prompt_2 = prompt_2 or prompt
405
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
406
+
407
+ prompt_3 = prompt_3 or prompt
408
+ prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
409
+
410
+ prompt_embed, pooled_prompt_embed = self._get_clip_prompt_embeds(
411
+ prompt=prompt,
412
+ device=device,
413
+ num_images_per_prompt=num_images_per_prompt,
414
+ clip_skip=clip_skip,
415
+ clip_model_index=0,
416
+ )
417
+ prompt_2_embed, pooled_prompt_2_embed = self._get_clip_prompt_embeds(
418
+ prompt=prompt_2,
419
+ device=device,
420
+ num_images_per_prompt=num_images_per_prompt,
421
+ clip_skip=clip_skip,
422
+ clip_model_index=1,
423
+ )
424
+ clip_prompt_embeds = torch.cat([prompt_embed, prompt_2_embed], dim=-1)
425
+
426
+ t5_prompt_embed = self._get_t5_prompt_embeds(
427
+ prompt=prompt_3,
428
+ num_images_per_prompt=num_images_per_prompt,
429
+ max_sequence_length=max_sequence_length,
430
+ device=device,
431
+ )
432
+
433
+ clip_prompt_embeds = torch.nn.functional.pad(
434
+ clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1])
435
+ )
436
+
437
+ prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2)
438
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
439
+
440
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
441
+ negative_prompt = negative_prompt or ""
442
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
443
+ negative_prompt_3 = negative_prompt_3 or negative_prompt
444
+
445
+ # normalize str to list
446
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
447
+ negative_prompt_2 = (
448
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
449
+ )
450
+ negative_prompt_3 = (
451
+ batch_size * [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
452
+ )
453
+
454
+ if prompt is not None and type(prompt) is not type(negative_prompt):
455
+ raise TypeError(
456
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
457
+ f" {type(prompt)}."
458
+ )
459
+ elif batch_size != len(negative_prompt):
460
+ raise ValueError(
461
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
462
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
463
+ " the batch size of `prompt`."
464
+ )
465
+
466
+ negative_prompt_embed, negative_pooled_prompt_embed = self._get_clip_prompt_embeds(
467
+ negative_prompt,
468
+ device=device,
469
+ num_images_per_prompt=num_images_per_prompt,
470
+ clip_skip=None,
471
+ clip_model_index=0,
472
+ )
473
+ negative_prompt_2_embed, negative_pooled_prompt_2_embed = self._get_clip_prompt_embeds(
474
+ negative_prompt_2,
475
+ device=device,
476
+ num_images_per_prompt=num_images_per_prompt,
477
+ clip_skip=None,
478
+ clip_model_index=1,
479
+ )
480
+ negative_clip_prompt_embeds = torch.cat([negative_prompt_embed, negative_prompt_2_embed], dim=-1)
481
+
482
+ t5_negative_prompt_embed = self._get_t5_prompt_embeds(
483
+ prompt=negative_prompt_3,
484
+ num_images_per_prompt=num_images_per_prompt,
485
+ max_sequence_length=max_sequence_length,
486
+ device=device,
487
+ )
488
+
489
+ negative_clip_prompt_embeds = torch.nn.functional.pad(
490
+ negative_clip_prompt_embeds,
491
+ (0, t5_negative_prompt_embed.shape[-1] - negative_clip_prompt_embeds.shape[-1]),
492
+ )
493
+
494
+ negative_prompt_embeds = torch.cat([negative_clip_prompt_embeds, t5_negative_prompt_embed], dim=-2)
495
+ negative_pooled_prompt_embeds = torch.cat(
496
+ [negative_pooled_prompt_embed, negative_pooled_prompt_2_embed], dim=-1
497
+ )
498
+
499
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
500
+
501
+ def check_inputs(
502
+ self,
503
+ prompt,
504
+ prompt_2,
505
+ prompt_3,
506
+ strength,
507
+ negative_prompt=None,
508
+ negative_prompt_2=None,
509
+ negative_prompt_3=None,
510
+ prompt_embeds=None,
511
+ negative_prompt_embeds=None,
512
+ pooled_prompt_embeds=None,
513
+ negative_pooled_prompt_embeds=None,
514
+ callback_on_step_end_tensor_inputs=None,
515
+ max_sequence_length=None,
516
+ ):
517
+ if strength < 0 or strength > 1:
518
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
519
+
520
+ if callback_on_step_end_tensor_inputs is not None and not all(
521
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
522
+ ):
523
+ raise ValueError(
524
+ 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]}"
525
+ )
526
+
527
+ if prompt is not None and prompt_embeds is not None:
528
+ raise ValueError(
529
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
530
+ " only forward one of the two."
531
+ )
532
+ elif prompt_2 is not None and prompt_embeds is not None:
533
+ raise ValueError(
534
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
535
+ " only forward one of the two."
536
+ )
537
+ elif prompt_3 is not None and prompt_embeds is not None:
538
+ raise ValueError(
539
+ f"Cannot forward both `prompt_3`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
540
+ " only forward one of the two."
541
+ )
542
+ elif prompt is None and prompt_embeds is None:
543
+ raise ValueError(
544
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
545
+ )
546
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
547
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
548
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
549
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
550
+ elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
551
+ raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
552
+
553
+ if negative_prompt is not None and negative_prompt_embeds is not None:
554
+ raise ValueError(
555
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
556
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
557
+ )
558
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
559
+ raise ValueError(
560
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
561
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
562
+ )
563
+ elif negative_prompt_3 is not None and negative_prompt_embeds is not None:
564
+ raise ValueError(
565
+ f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds`:"
566
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
567
+ )
568
+
569
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
570
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
571
+ raise ValueError(
572
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
573
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
574
+ f" {negative_prompt_embeds.shape}."
575
+ )
576
+
577
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
578
+ raise ValueError(
579
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
580
+ )
581
+
582
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
583
+ raise ValueError(
584
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
585
+ )
586
+
587
+ if max_sequence_length is not None and max_sequence_length > 512:
588
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
589
+
590
+ def get_timesteps(self, num_inference_steps, strength, device):
591
+ # get the original timestep using init_timestep
592
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
593
+
594
+ t_start = int(max(num_inference_steps - init_timestep, 0))
595
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
596
+ if hasattr(self.scheduler, "set_begin_index"):
597
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
598
+
599
+ return timesteps, num_inference_steps - t_start
600
+
601
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
602
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
603
+ raise ValueError(
604
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
605
+ )
606
+
607
+ image = image.to(device=device, dtype=dtype)
608
+ if image.shape[1] == self.vae.config.latent_channels:
609
+ init_latents = image
610
+
611
+ batch_size = batch_size * num_images_per_prompt
612
+ if image.shape[1] == self.vae.config.latent_channels:
613
+ init_latents = image
614
+
615
+ else:
616
+ if isinstance(generator, list) and len(generator) != batch_size:
617
+ raise ValueError(
618
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
619
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
620
+ )
621
+
622
+ elif isinstance(generator, list):
623
+ init_latents = [
624
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
625
+ for i in range(batch_size)
626
+ ]
627
+ init_latents = torch.cat(init_latents, dim=0)
628
+ else:
629
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
630
+
631
+ init_latents = (init_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
632
+
633
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
634
+ # expand init_latents for batch_size
635
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
636
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
637
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
638
+ raise ValueError(
639
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
640
+ )
641
+ else:
642
+ init_latents = torch.cat([init_latents], dim=0)
643
+
644
+ shape = init_latents.shape
645
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
646
+
647
+ # get latents
648
+ init_latents = self.scheduler.scale_noise(init_latents, timestep, noise)
649
+ latents = init_latents.to(device=device, dtype=dtype)
650
+
651
+ return latents
652
+
653
+ @property
654
+ def guidance_scale(self):
655
+ return self._guidance_scale
656
+
657
+ @property
658
+ def clip_skip(self):
659
+ return self._clip_skip
660
+
661
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
662
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
663
+ # corresponds to doing no classifier free guidance.
664
+ @property
665
+ def do_classifier_free_guidance(self):
666
+ return self._guidance_scale > 1
667
+
668
+ @property
669
+ def num_timesteps(self):
670
+ return self._num_timesteps
671
+
672
+ @property
673
+ def interrupt(self):
674
+ return self._interrupt
675
+
676
+ @torch.no_grad()
677
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
678
+ def __call__(
679
+ self,
680
+ prompt: Union[str, List[str]] = None,
681
+ prompt_2: Optional[Union[str, List[str]]] = None,
682
+ prompt_3: Optional[Union[str, List[str]]] = None,
683
+ image: PipelineImageInput = None,
684
+ strength: float = 0.6,
685
+ num_inference_steps: int = 50,
686
+ timesteps: List[int] = None,
687
+ guidance_scale: float = 7.0,
688
+ negative_prompt: Optional[Union[str, List[str]]] = None,
689
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
690
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
691
+ num_images_per_prompt: Optional[int] = 1,
692
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
693
+ latents: Optional[torch.FloatTensor] = None,
694
+ prompt_embeds: Optional[torch.FloatTensor] = None,
695
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
696
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
697
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
698
+ output_type: Optional[str] = "pil",
699
+ return_dict: bool = True,
700
+ clip_skip: Optional[int] = None,
701
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
702
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
703
+ max_sequence_length: int = 256,
704
+ ):
705
+ r"""
706
+ Function invoked when calling the pipeline for generation.
707
+
708
+ Args:
709
+ prompt (`str` or `List[str]`, *optional*):
710
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
711
+ instead.
712
+ prompt_2 (`str` or `List[str]`, *optional*):
713
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
714
+ will be used instead
715
+ prompt_3 (`str` or `List[str]`, *optional*):
716
+ The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
717
+ will be used instead
718
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
719
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
720
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
721
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
722
+ num_inference_steps (`int`, *optional*, defaults to 50):
723
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
724
+ expense of slower inference.
725
+ timesteps (`List[int]`, *optional*):
726
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
727
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
728
+ passed will be used. Must be in descending order.
729
+ guidance_scale (`float`, *optional*, defaults to 5.0):
730
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
731
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
732
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
733
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
734
+ usually at the expense of lower image quality.
735
+ negative_prompt (`str` or `List[str]`, *optional*):
736
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
737
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
738
+ less than `1`).
739
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
740
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
741
+ `text_encoder_2`. If not defined, `negative_prompt` is used instead
742
+ negative_prompt_3 (`str` or `List[str]`, *optional*):
743
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
744
+ `text_encoder_3`. If not defined, `negative_prompt` is used instead
745
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
746
+ The number of images to generate per prompt.
747
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
748
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
749
+ to make generation deterministic.
750
+ latents (`torch.FloatTensor`, *optional*):
751
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
752
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
753
+ tensor will ge generated by sampling using the supplied random `generator`.
754
+ prompt_embeds (`torch.FloatTensor`, *optional*):
755
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
756
+ provided, text embeddings will be generated from `prompt` input argument.
757
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
758
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
759
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
760
+ argument.
761
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
762
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
763
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
764
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
765
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
766
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
767
+ input argument.
768
+ output_type (`str`, *optional*, defaults to `"pil"`):
769
+ The output format of the generate image. Choose between
770
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
771
+ return_dict (`bool`, *optional*, defaults to `True`):
772
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
773
+ of a plain tuple.
774
+ callback_on_step_end (`Callable`, *optional*):
775
+ A function that calls at the end of each denoising steps during the inference. The function is called
776
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
777
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
778
+ `callback_on_step_end_tensor_inputs`.
779
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
780
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
781
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
782
+ `._callback_tensor_inputs` attribute of your pipeline class.
783
+ max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
784
+
785
+ Examples:
786
+
787
+ Returns:
788
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
789
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
790
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
791
+ """
792
+
793
+ # 1. Check inputs. Raise error if not correct
794
+ self.check_inputs(
795
+ prompt,
796
+ prompt_2,
797
+ prompt_3,
798
+ strength,
799
+ negative_prompt=negative_prompt,
800
+ negative_prompt_2=negative_prompt_2,
801
+ negative_prompt_3=negative_prompt_3,
802
+ prompt_embeds=prompt_embeds,
803
+ negative_prompt_embeds=negative_prompt_embeds,
804
+ pooled_prompt_embeds=pooled_prompt_embeds,
805
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
806
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
807
+ max_sequence_length=max_sequence_length,
808
+ )
809
+
810
+ self._guidance_scale = guidance_scale
811
+ self._clip_skip = clip_skip
812
+ self._interrupt = False
813
+
814
+ # 2. Define call parameters
815
+ if prompt is not None and isinstance(prompt, str):
816
+ batch_size = 1
817
+ elif prompt is not None and isinstance(prompt, list):
818
+ batch_size = len(prompt)
819
+ else:
820
+ batch_size = prompt_embeds.shape[0]
821
+
822
+ device = self._execution_device
823
+
824
+ (
825
+ prompt_embeds,
826
+ negative_prompt_embeds,
827
+ pooled_prompt_embeds,
828
+ negative_pooled_prompt_embeds,
829
+ ) = self.encode_prompt(
830
+ prompt=prompt,
831
+ prompt_2=prompt_2,
832
+ prompt_3=prompt_3,
833
+ negative_prompt=negative_prompt,
834
+ negative_prompt_2=negative_prompt_2,
835
+ negative_prompt_3=negative_prompt_3,
836
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
837
+ prompt_embeds=prompt_embeds,
838
+ negative_prompt_embeds=negative_prompt_embeds,
839
+ pooled_prompt_embeds=pooled_prompt_embeds,
840
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
841
+ device=device,
842
+ clip_skip=self.clip_skip,
843
+ num_images_per_prompt=num_images_per_prompt,
844
+ max_sequence_length=max_sequence_length,
845
+ )
846
+
847
+ if self.do_classifier_free_guidance:
848
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
849
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
850
+
851
+ # 3. Preprocess image
852
+ image = self.image_processor.preprocess(image)
853
+
854
+ # 4. Prepare timesteps
855
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
856
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
857
+ latent_timestep = timesteps[:1].repeat(batch_size * num_inference_steps)
858
+
859
+ # 5. Prepare latent variables
860
+ if latents is None:
861
+ latents = self.prepare_latents(
862
+ image,
863
+ latent_timestep,
864
+ batch_size,
865
+ num_images_per_prompt,
866
+ prompt_embeds.dtype,
867
+ device,
868
+ generator,
869
+ )
870
+
871
+ # 6. Denoising loop
872
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
873
+ self._num_timesteps = len(timesteps)
874
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
875
+ for i, t in enumerate(timesteps):
876
+ if self.interrupt:
877
+ continue
878
+
879
+ # expand the latents if we are doing classifier free guidance
880
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
881
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
882
+ timestep = t.expand(latent_model_input.shape[0])
883
+
884
+ noise_pred = self.transformer(
885
+ hidden_states=latent_model_input,
886
+ timestep=timestep,
887
+ encoder_hidden_states=prompt_embeds,
888
+ pooled_projections=pooled_prompt_embeds,
889
+ return_dict=False,
890
+ )[0]
891
+
892
+ # perform guidance
893
+ if self.do_classifier_free_guidance:
894
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
895
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
896
+
897
+ # compute the previous noisy sample x_t -> x_t-1
898
+ latents_dtype = latents.dtype
899
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
900
+
901
+ if latents.dtype != latents_dtype:
902
+ if torch.backends.mps.is_available():
903
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
904
+ latents = latents.to(latents_dtype)
905
+
906
+ if callback_on_step_end is not None:
907
+ callback_kwargs = {}
908
+ for k in callback_on_step_end_tensor_inputs:
909
+ callback_kwargs[k] = locals()[k]
910
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
911
+
912
+ latents = callback_outputs.pop("latents", latents)
913
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
914
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
915
+ negative_pooled_prompt_embeds = callback_outputs.pop(
916
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
917
+ )
918
+
919
+ # call the callback, if provided
920
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
921
+ progress_bar.update()
922
+
923
+ if XLA_AVAILABLE:
924
+ xm.mark_step()
925
+
926
+ if output_type == "latent":
927
+ image = latents
928
+
929
+ else:
930
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
931
+
932
+ image = self.vae.decode(latents, return_dict=False)[0]
933
+ image = self.image_processor.postprocess(image, output_type=output_type)
934
+
935
+ # Offload all models
936
+ self.maybe_free_model_hooks()
937
+
938
+ if not return_dict:
939
+ return (image,)
940
+
941
+ return StableDiffusion3PipelineOutput(images=image)