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