diffusers 0.28.2__py3-none-any.whl → 0.29.0__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 (118) hide show
  1. diffusers/__init__.py +9 -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 +1 -1
  9. diffusers/loaders/single_file_model.py +5 -0
  10. diffusers/loaders/single_file_utils.py +242 -2
  11. diffusers/loaders/unet.py +307 -272
  12. diffusers/models/__init__.py +5 -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_xs.py +6 -6
  22. diffusers/models/embeddings.py +112 -84
  23. diffusers/models/model_loading_utils.py +55 -0
  24. diffusers/models/modeling_utils.py +128 -17
  25. diffusers/models/normalization.py +11 -6
  26. diffusers/models/transformers/__init__.py +1 -0
  27. diffusers/models/transformers/dual_transformer_2d.py +5 -4
  28. diffusers/models/transformers/hunyuan_transformer_2d.py +149 -2
  29. diffusers/models/transformers/prior_transformer.py +5 -5
  30. diffusers/models/transformers/transformer_2d.py +2 -2
  31. diffusers/models/transformers/transformer_sd3.py +344 -0
  32. diffusers/models/transformers/transformer_temporal.py +12 -10
  33. diffusers/models/unets/unet_1d.py +3 -3
  34. diffusers/models/unets/unet_2d.py +3 -3
  35. diffusers/models/unets/unet_2d_condition.py +4 -15
  36. diffusers/models/unets/unet_3d_condition.py +5 -17
  37. diffusers/models/unets/unet_i2vgen_xl.py +4 -4
  38. diffusers/models/unets/unet_motion_model.py +4 -4
  39. diffusers/models/unets/unet_spatio_temporal_condition.py +3 -3
  40. diffusers/models/vq_model.py +8 -165
  41. diffusers/pipelines/__init__.py +2 -0
  42. diffusers/pipelines/animatediff/pipeline_animatediff.py +4 -3
  43. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +4 -3
  44. diffusers/pipelines/controlnet/pipeline_controlnet.py +4 -3
  45. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +4 -3
  46. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +4 -3
  47. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +4 -3
  48. diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
  49. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +4 -3
  50. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +4 -3
  51. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +4 -3
  52. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +4 -3
  53. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +4 -3
  54. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +24 -5
  55. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +4 -3
  56. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +4 -3
  57. diffusers/pipelines/marigold/marigold_image_processing.py +35 -20
  58. diffusers/pipelines/pia/pipeline_pia.py +4 -3
  59. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
  60. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
  61. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +17 -17
  62. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +4 -3
  63. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -4
  64. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +4 -3
  65. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -3
  66. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +4 -3
  67. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +4 -3
  68. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +7 -6
  69. diffusers/pipelines/stable_diffusion_3/__init__.py +52 -0
  70. diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
  71. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +886 -0
  72. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +923 -0
  73. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +4 -3
  74. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +10 -11
  75. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +4 -3
  76. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  77. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +4 -3
  78. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +4 -3
  79. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +4 -3
  80. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +4 -3
  81. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +4 -3
  82. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +4 -3
  83. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +4 -3
  84. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -3
  85. diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
  86. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +4 -3
  87. diffusers/schedulers/__init__.py +2 -0
  88. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
  89. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -3
  90. diffusers/schedulers/scheduling_edm_euler.py +2 -4
  91. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +287 -0
  92. diffusers/schedulers/scheduling_lms_discrete.py +2 -2
  93. diffusers/training_utils.py +4 -4
  94. diffusers/utils/__init__.py +3 -0
  95. diffusers/utils/constants.py +2 -0
  96. diffusers/utils/dummy_pt_objects.py +30 -0
  97. diffusers/utils/dummy_torch_and_transformers_objects.py +30 -0
  98. diffusers/utils/dynamic_modules_utils.py +15 -13
  99. diffusers/utils/hub_utils.py +106 -0
  100. diffusers/utils/import_utils.py +0 -1
  101. diffusers/utils/logging.py +3 -1
  102. diffusers/utils/state_dict_utils.py +2 -0
  103. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/METADATA +45 -45
  104. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/RECORD +108 -111
  105. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/WHEEL +1 -1
  106. diffusers/models/dual_transformer_2d.py +0 -20
  107. diffusers/models/prior_transformer.py +0 -12
  108. diffusers/models/t5_film_transformer.py +0 -70
  109. diffusers/models/transformer_2d.py +0 -25
  110. diffusers/models/transformer_temporal.py +0 -34
  111. diffusers/models/unet_1d.py +0 -26
  112. diffusers/models/unet_1d_blocks.py +0 -203
  113. diffusers/models/unet_2d.py +0 -27
  114. diffusers/models/unet_2d_blocks.py +0 -375
  115. diffusers/models/unet_2d_condition.py +0 -25
  116. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/LICENSE +0 -0
  117. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/entry_points.txt +0 -0
  118. {diffusers-0.28.2.dist-info → diffusers-0.29.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,923 @@
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
+ device: Optional[torch.device] = None,
224
+ dtype: Optional[torch.dtype] = None,
225
+ ):
226
+ device = device or self._execution_device
227
+ dtype = dtype or self.text_encoder.dtype
228
+
229
+ prompt = [prompt] if isinstance(prompt, str) else prompt
230
+ batch_size = len(prompt)
231
+
232
+ if self.text_encoder_3 is None:
233
+ return torch.zeros(
234
+ (batch_size, self.tokenizer_max_length, self.transformer.config.joint_attention_dim),
235
+ device=device,
236
+ dtype=dtype,
237
+ )
238
+
239
+ text_inputs = self.tokenizer_3(
240
+ prompt,
241
+ padding="max_length",
242
+ max_length=self.tokenizer_max_length,
243
+ truncation=True,
244
+ add_special_tokens=True,
245
+ return_tensors="pt",
246
+ )
247
+ text_input_ids = text_inputs.input_ids
248
+ untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
249
+
250
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
251
+ removed_text = self.tokenizer_3.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
252
+ logger.warning(
253
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
254
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
255
+ )
256
+
257
+ prompt_embeds = self.text_encoder_3(text_input_ids.to(device))[0]
258
+
259
+ dtype = self.text_encoder_3.dtype
260
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
261
+
262
+ _, seq_len, _ = prompt_embeds.shape
263
+
264
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
265
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
266
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
267
+
268
+ return prompt_embeds
269
+
270
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_clip_prompt_embeds
271
+ def _get_clip_prompt_embeds(
272
+ self,
273
+ prompt: Union[str, List[str]],
274
+ num_images_per_prompt: int = 1,
275
+ device: Optional[torch.device] = None,
276
+ clip_skip: Optional[int] = None,
277
+ clip_model_index: int = 0,
278
+ ):
279
+ device = device or self._execution_device
280
+
281
+ clip_tokenizers = [self.tokenizer, self.tokenizer_2]
282
+ clip_text_encoders = [self.text_encoder, self.text_encoder_2]
283
+
284
+ tokenizer = clip_tokenizers[clip_model_index]
285
+ text_encoder = clip_text_encoders[clip_model_index]
286
+
287
+ prompt = [prompt] if isinstance(prompt, str) else prompt
288
+ batch_size = len(prompt)
289
+
290
+ text_inputs = tokenizer(
291
+ prompt,
292
+ padding="max_length",
293
+ max_length=self.tokenizer_max_length,
294
+ truncation=True,
295
+ return_tensors="pt",
296
+ )
297
+
298
+ text_input_ids = text_inputs.input_ids
299
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
300
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
301
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
302
+ logger.warning(
303
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
304
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
305
+ )
306
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
307
+ pooled_prompt_embeds = prompt_embeds[0]
308
+
309
+ if clip_skip is None:
310
+ prompt_embeds = prompt_embeds.hidden_states[-2]
311
+ else:
312
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
313
+
314
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
315
+
316
+ _, seq_len, _ = prompt_embeds.shape
317
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
318
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
319
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
320
+
321
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
322
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
323
+
324
+ return prompt_embeds, pooled_prompt_embeds
325
+
326
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline.encode_prompt
327
+ def encode_prompt(
328
+ self,
329
+ prompt: Union[str, List[str]],
330
+ prompt_2: Union[str, List[str]],
331
+ prompt_3: Union[str, List[str]],
332
+ device: Optional[torch.device] = None,
333
+ num_images_per_prompt: int = 1,
334
+ do_classifier_free_guidance: bool = True,
335
+ negative_prompt: Optional[Union[str, List[str]]] = None,
336
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
337
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
338
+ prompt_embeds: Optional[torch.FloatTensor] = None,
339
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
340
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
341
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
342
+ clip_skip: Optional[int] = None,
343
+ ):
344
+ r"""
345
+
346
+ Args:
347
+ prompt (`str` or `List[str]`, *optional*):
348
+ prompt to be encoded
349
+ prompt_2 (`str` or `List[str]`, *optional*):
350
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
351
+ used in all text-encoders
352
+ prompt_3 (`str` or `List[str]`, *optional*):
353
+ The prompt or prompts to be sent to the `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
354
+ used in all text-encoders
355
+ device: (`torch.device`):
356
+ torch device
357
+ num_images_per_prompt (`int`):
358
+ number of images that should be generated per prompt
359
+ do_classifier_free_guidance (`bool`):
360
+ whether to use classifier free guidance or not
361
+ negative_prompt (`str` or `List[str]`, *optional*):
362
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
363
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
364
+ less than `1`).
365
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
366
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
367
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
368
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
369
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
370
+ `text_encoder_3`. If not defined, `negative_prompt` is used in both text-encoders
371
+ prompt_embeds (`torch.FloatTensor`, *optional*):
372
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
373
+ provided, text embeddings will be generated from `prompt` input argument.
374
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
375
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
376
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
377
+ argument.
378
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
379
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
380
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
381
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
382
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
383
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
384
+ input argument.
385
+ clip_skip (`int`, *optional*):
386
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
387
+ the output of the pre-final layer will be used for computing the prompt embeddings.
388
+ """
389
+ device = device or self._execution_device
390
+
391
+ prompt = [prompt] if isinstance(prompt, str) else prompt
392
+ if prompt is not None:
393
+ batch_size = len(prompt)
394
+ else:
395
+ batch_size = prompt_embeds.shape[0]
396
+
397
+ if prompt_embeds is None:
398
+ prompt_2 = prompt_2 or prompt
399
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
400
+
401
+ prompt_3 = prompt_3 or prompt
402
+ prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
403
+
404
+ prompt_embed, pooled_prompt_embed = self._get_clip_prompt_embeds(
405
+ prompt=prompt,
406
+ device=device,
407
+ num_images_per_prompt=num_images_per_prompt,
408
+ clip_skip=clip_skip,
409
+ clip_model_index=0,
410
+ )
411
+ prompt_2_embed, pooled_prompt_2_embed = self._get_clip_prompt_embeds(
412
+ prompt=prompt_2,
413
+ device=device,
414
+ num_images_per_prompt=num_images_per_prompt,
415
+ clip_skip=clip_skip,
416
+ clip_model_index=1,
417
+ )
418
+ clip_prompt_embeds = torch.cat([prompt_embed, prompt_2_embed], dim=-1)
419
+
420
+ t5_prompt_embed = self._get_t5_prompt_embeds(
421
+ prompt=prompt_3,
422
+ num_images_per_prompt=num_images_per_prompt,
423
+ device=device,
424
+ )
425
+
426
+ clip_prompt_embeds = torch.nn.functional.pad(
427
+ clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1])
428
+ )
429
+
430
+ prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2)
431
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
432
+
433
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
434
+ negative_prompt = negative_prompt or ""
435
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
436
+ negative_prompt_3 = negative_prompt_3 or negative_prompt
437
+
438
+ # normalize str to list
439
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
440
+ negative_prompt_2 = (
441
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
442
+ )
443
+ negative_prompt_3 = (
444
+ batch_size * [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
445
+ )
446
+
447
+ if prompt is not None and type(prompt) is not type(negative_prompt):
448
+ raise TypeError(
449
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
450
+ f" {type(prompt)}."
451
+ )
452
+ elif batch_size != len(negative_prompt):
453
+ raise ValueError(
454
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
455
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
456
+ " the batch size of `prompt`."
457
+ )
458
+
459
+ negative_prompt_embed, negative_pooled_prompt_embed = self._get_clip_prompt_embeds(
460
+ negative_prompt,
461
+ device=device,
462
+ num_images_per_prompt=num_images_per_prompt,
463
+ clip_skip=None,
464
+ clip_model_index=0,
465
+ )
466
+ negative_prompt_2_embed, negative_pooled_prompt_2_embed = self._get_clip_prompt_embeds(
467
+ negative_prompt_2,
468
+ device=device,
469
+ num_images_per_prompt=num_images_per_prompt,
470
+ clip_skip=None,
471
+ clip_model_index=1,
472
+ )
473
+ negative_clip_prompt_embeds = torch.cat([negative_prompt_embed, negative_prompt_2_embed], dim=-1)
474
+
475
+ t5_negative_prompt_embed = self._get_t5_prompt_embeds(
476
+ prompt=negative_prompt_3, num_images_per_prompt=num_images_per_prompt, device=device
477
+ )
478
+
479
+ negative_clip_prompt_embeds = torch.nn.functional.pad(
480
+ negative_clip_prompt_embeds,
481
+ (0, t5_negative_prompt_embed.shape[-1] - negative_clip_prompt_embeds.shape[-1]),
482
+ )
483
+
484
+ negative_prompt_embeds = torch.cat([negative_clip_prompt_embeds, t5_negative_prompt_embed], dim=-2)
485
+ negative_pooled_prompt_embeds = torch.cat(
486
+ [negative_pooled_prompt_embed, negative_pooled_prompt_2_embed], dim=-1
487
+ )
488
+
489
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
490
+
491
+ def check_inputs(
492
+ self,
493
+ prompt,
494
+ prompt_2,
495
+ prompt_3,
496
+ strength,
497
+ negative_prompt=None,
498
+ negative_prompt_2=None,
499
+ negative_prompt_3=None,
500
+ prompt_embeds=None,
501
+ negative_prompt_embeds=None,
502
+ pooled_prompt_embeds=None,
503
+ negative_pooled_prompt_embeds=None,
504
+ callback_on_step_end_tensor_inputs=None,
505
+ ):
506
+ if strength < 0 or strength > 1:
507
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
508
+
509
+ if callback_on_step_end_tensor_inputs is not None and not all(
510
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
511
+ ):
512
+ raise ValueError(
513
+ 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]}"
514
+ )
515
+
516
+ if prompt is not None and prompt_embeds is not None:
517
+ raise ValueError(
518
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
519
+ " only forward one of the two."
520
+ )
521
+ elif prompt_2 is not None and prompt_embeds is not None:
522
+ raise ValueError(
523
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
524
+ " only forward one of the two."
525
+ )
526
+ elif prompt_3 is not None and prompt_embeds is not None:
527
+ raise ValueError(
528
+ f"Cannot forward both `prompt_3`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
529
+ " only forward one of the two."
530
+ )
531
+ elif prompt is None and prompt_embeds is None:
532
+ raise ValueError(
533
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
534
+ )
535
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
536
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
537
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
538
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
539
+ elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
540
+ raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
541
+
542
+ if negative_prompt is not None and negative_prompt_embeds is not None:
543
+ raise ValueError(
544
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
545
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
546
+ )
547
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
548
+ raise ValueError(
549
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
550
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
551
+ )
552
+ elif negative_prompt_3 is not None and negative_prompt_embeds is not None:
553
+ raise ValueError(
554
+ f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds`:"
555
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
556
+ )
557
+
558
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
559
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
560
+ raise ValueError(
561
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
562
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
563
+ f" {negative_prompt_embeds.shape}."
564
+ )
565
+
566
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
567
+ raise ValueError(
568
+ "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`."
569
+ )
570
+
571
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
572
+ raise ValueError(
573
+ "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`."
574
+ )
575
+
576
+ def get_timesteps(self, num_inference_steps, strength, device):
577
+ # get the original timestep using init_timestep
578
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
579
+
580
+ t_start = int(max(num_inference_steps - init_timestep, 0))
581
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
582
+ if hasattr(self.scheduler, "set_begin_index"):
583
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
584
+
585
+ return timesteps, num_inference_steps - t_start
586
+
587
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
588
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
589
+ raise ValueError(
590
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
591
+ )
592
+
593
+ image = image.to(device=device, dtype=dtype)
594
+ if image.shape[1] == self.vae.config.latent_channels:
595
+ init_latents = image
596
+
597
+ batch_size = batch_size * num_images_per_prompt
598
+ if image.shape[1] == self.vae.config.latent_channels:
599
+ init_latents = image
600
+
601
+ else:
602
+ if isinstance(generator, list) and len(generator) != batch_size:
603
+ raise ValueError(
604
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
605
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
606
+ )
607
+
608
+ elif isinstance(generator, list):
609
+ init_latents = [
610
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
611
+ for i in range(batch_size)
612
+ ]
613
+ init_latents = torch.cat(init_latents, dim=0)
614
+ else:
615
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
616
+
617
+ init_latents = (init_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
618
+
619
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
620
+ # expand init_latents for batch_size
621
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
622
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
623
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
624
+ raise ValueError(
625
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
626
+ )
627
+ else:
628
+ init_latents = torch.cat([init_latents], dim=0)
629
+
630
+ shape = init_latents.shape
631
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
632
+
633
+ # get latents
634
+ init_latents = self.scheduler.scale_noise(init_latents, timestep, noise)
635
+ latents = init_latents.to(device=device, dtype=dtype)
636
+
637
+ return latents
638
+
639
+ @property
640
+ def guidance_scale(self):
641
+ return self._guidance_scale
642
+
643
+ @property
644
+ def clip_skip(self):
645
+ return self._clip_skip
646
+
647
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
648
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
649
+ # corresponds to doing no classifier free guidance.
650
+ @property
651
+ def do_classifier_free_guidance(self):
652
+ return self._guidance_scale > 1
653
+
654
+ @property
655
+ def num_timesteps(self):
656
+ return self._num_timesteps
657
+
658
+ @property
659
+ def interrupt(self):
660
+ return self._interrupt
661
+
662
+ @torch.no_grad()
663
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
664
+ def __call__(
665
+ self,
666
+ prompt: Union[str, List[str]] = None,
667
+ prompt_2: Optional[Union[str, List[str]]] = None,
668
+ prompt_3: Optional[Union[str, List[str]]] = None,
669
+ image: PipelineImageInput = None,
670
+ strength: float = 0.6,
671
+ num_inference_steps: int = 50,
672
+ timesteps: List[int] = None,
673
+ guidance_scale: float = 7.0,
674
+ negative_prompt: Optional[Union[str, List[str]]] = None,
675
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
676
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
677
+ num_images_per_prompt: Optional[int] = 1,
678
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
679
+ latents: Optional[torch.FloatTensor] = None,
680
+ prompt_embeds: Optional[torch.FloatTensor] = None,
681
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
682
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
683
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
684
+ output_type: Optional[str] = "pil",
685
+ return_dict: bool = True,
686
+ clip_skip: Optional[int] = None,
687
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
688
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
689
+ ):
690
+ r"""
691
+ Function invoked when calling the pipeline for generation.
692
+
693
+ Args:
694
+ prompt (`str` or `List[str]`, *optional*):
695
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
696
+ instead.
697
+ prompt_2 (`str` or `List[str]`, *optional*):
698
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
699
+ will be used instead
700
+ prompt_3 (`str` or `List[str]`, *optional*):
701
+ The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
702
+ will be used instead
703
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
704
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
705
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
706
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
707
+ num_inference_steps (`int`, *optional*, defaults to 50):
708
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
709
+ expense of slower inference.
710
+ timesteps (`List[int]`, *optional*):
711
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
712
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
713
+ passed will be used. Must be in descending order.
714
+ guidance_scale (`float`, *optional*, defaults to 5.0):
715
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
716
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
717
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
718
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
719
+ usually at the expense of lower image quality.
720
+ negative_prompt (`str` or `List[str]`, *optional*):
721
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
722
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
723
+ less than `1`).
724
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
725
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
726
+ `text_encoder_2`. If not defined, `negative_prompt` is used instead
727
+ negative_prompt_3 (`str` or `List[str]`, *optional*):
728
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
729
+ `text_encoder_3`. If not defined, `negative_prompt` is used instead
730
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
731
+ The number of images to generate per prompt.
732
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
733
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
734
+ to make generation deterministic.
735
+ latents (`torch.FloatTensor`, *optional*):
736
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
737
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
738
+ tensor will ge generated by sampling using the supplied random `generator`.
739
+ prompt_embeds (`torch.FloatTensor`, *optional*):
740
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
741
+ provided, text embeddings will be generated from `prompt` input argument.
742
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
743
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
744
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
745
+ argument.
746
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
747
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
748
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
749
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
750
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
751
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
752
+ input argument.
753
+ output_type (`str`, *optional*, defaults to `"pil"`):
754
+ The output format of the generate image. Choose between
755
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
756
+ return_dict (`bool`, *optional*, defaults to `True`):
757
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
758
+ of a plain tuple.
759
+ callback_on_step_end (`Callable`, *optional*):
760
+ A function that calls at the end of each denoising steps during the inference. The function is called
761
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
762
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
763
+ `callback_on_step_end_tensor_inputs`.
764
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
765
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
766
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
767
+ `._callback_tensor_inputs` attribute of your pipeline class.
768
+
769
+ Examples:
770
+
771
+ Returns:
772
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
773
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
774
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
775
+ """
776
+
777
+ # 1. Check inputs. Raise error if not correct
778
+ self.check_inputs(
779
+ prompt,
780
+ prompt_2,
781
+ prompt_3,
782
+ strength,
783
+ negative_prompt=negative_prompt,
784
+ negative_prompt_2=negative_prompt_2,
785
+ negative_prompt_3=negative_prompt_3,
786
+ prompt_embeds=prompt_embeds,
787
+ negative_prompt_embeds=negative_prompt_embeds,
788
+ pooled_prompt_embeds=pooled_prompt_embeds,
789
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
790
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
791
+ )
792
+
793
+ self._guidance_scale = guidance_scale
794
+ self._clip_skip = clip_skip
795
+ self._interrupt = False
796
+
797
+ # 2. Define call parameters
798
+ if prompt is not None and isinstance(prompt, str):
799
+ batch_size = 1
800
+ elif prompt is not None and isinstance(prompt, list):
801
+ batch_size = len(prompt)
802
+ else:
803
+ batch_size = prompt_embeds.shape[0]
804
+
805
+ device = self._execution_device
806
+
807
+ (
808
+ prompt_embeds,
809
+ negative_prompt_embeds,
810
+ pooled_prompt_embeds,
811
+ negative_pooled_prompt_embeds,
812
+ ) = self.encode_prompt(
813
+ prompt=prompt,
814
+ prompt_2=prompt_2,
815
+ prompt_3=prompt_3,
816
+ negative_prompt=negative_prompt,
817
+ negative_prompt_2=negative_prompt_2,
818
+ negative_prompt_3=negative_prompt_3,
819
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
820
+ prompt_embeds=prompt_embeds,
821
+ negative_prompt_embeds=negative_prompt_embeds,
822
+ pooled_prompt_embeds=pooled_prompt_embeds,
823
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
824
+ device=device,
825
+ clip_skip=self.clip_skip,
826
+ num_images_per_prompt=num_images_per_prompt,
827
+ )
828
+
829
+ if self.do_classifier_free_guidance:
830
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
831
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
832
+
833
+ # 3. Preprocess image
834
+ image = self.image_processor.preprocess(image)
835
+
836
+ # 4. Prepare timesteps
837
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
838
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
839
+ latent_timestep = timesteps[:1].repeat(batch_size * num_inference_steps)
840
+
841
+ # 5. Prepare latent variables
842
+ if latents is None:
843
+ latents = self.prepare_latents(
844
+ image,
845
+ latent_timestep,
846
+ batch_size,
847
+ num_images_per_prompt,
848
+ prompt_embeds.dtype,
849
+ device,
850
+ generator,
851
+ )
852
+
853
+ # 6. Denoising loop
854
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
855
+ self._num_timesteps = len(timesteps)
856
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
857
+ for i, t in enumerate(timesteps):
858
+ if self.interrupt:
859
+ continue
860
+
861
+ # expand the latents if we are doing classifier free guidance
862
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
863
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
864
+ timestep = t.expand(latent_model_input.shape[0])
865
+
866
+ noise_pred = self.transformer(
867
+ hidden_states=latent_model_input,
868
+ timestep=timestep,
869
+ encoder_hidden_states=prompt_embeds,
870
+ pooled_projections=pooled_prompt_embeds,
871
+ return_dict=False,
872
+ )[0]
873
+
874
+ # perform guidance
875
+ if self.do_classifier_free_guidance:
876
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
877
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
878
+
879
+ # compute the previous noisy sample x_t -> x_t-1
880
+ latents_dtype = latents.dtype
881
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
882
+
883
+ if latents.dtype != latents_dtype:
884
+ if torch.backends.mps.is_available():
885
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
886
+ latents = latents.to(latents_dtype)
887
+
888
+ if callback_on_step_end is not None:
889
+ callback_kwargs = {}
890
+ for k in callback_on_step_end_tensor_inputs:
891
+ callback_kwargs[k] = locals()[k]
892
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
893
+
894
+ latents = callback_outputs.pop("latents", latents)
895
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
896
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
897
+ negative_pooled_prompt_embeds = callback_outputs.pop(
898
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
899
+ )
900
+
901
+ # call the callback, if provided
902
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
903
+ progress_bar.update()
904
+
905
+ if XLA_AVAILABLE:
906
+ xm.mark_step()
907
+
908
+ if output_type == "latent":
909
+ image = latents
910
+
911
+ else:
912
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
913
+
914
+ image = self.vae.decode(latents, return_dict=False)[0]
915
+ image = self.image_processor.postprocess(image, output_type=output_type)
916
+
917
+ # Offload all models
918
+ self.maybe_free_model_hooks()
919
+
920
+ if not return_dict:
921
+ return (image,)
922
+
923
+ return StableDiffusion3PipelineOutput(images=image)