diffusers 0.30.2__py3-none-any.whl → 0.31.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 (173) hide show
  1. diffusers/__init__.py +38 -2
  2. diffusers/configuration_utils.py +12 -0
  3. diffusers/dependency_versions_table.py +1 -1
  4. diffusers/image_processor.py +257 -54
  5. diffusers/loaders/__init__.py +2 -0
  6. diffusers/loaders/ip_adapter.py +5 -1
  7. diffusers/loaders/lora_base.py +14 -7
  8. diffusers/loaders/lora_conversion_utils.py +332 -0
  9. diffusers/loaders/lora_pipeline.py +707 -41
  10. diffusers/loaders/peft.py +1 -0
  11. diffusers/loaders/single_file_utils.py +81 -4
  12. diffusers/loaders/textual_inversion.py +2 -0
  13. diffusers/loaders/unet.py +39 -8
  14. diffusers/models/__init__.py +4 -0
  15. diffusers/models/adapter.py +53 -53
  16. diffusers/models/attention.py +86 -10
  17. diffusers/models/attention_processor.py +169 -133
  18. diffusers/models/autoencoders/autoencoder_kl.py +71 -11
  19. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +287 -85
  20. diffusers/models/controlnet_flux.py +536 -0
  21. diffusers/models/controlnet_sd3.py +7 -3
  22. diffusers/models/controlnet_sparsectrl.py +0 -1
  23. diffusers/models/embeddings.py +238 -61
  24. diffusers/models/embeddings_flax.py +23 -9
  25. diffusers/models/model_loading_utils.py +182 -14
  26. diffusers/models/modeling_utils.py +283 -46
  27. diffusers/models/normalization.py +79 -0
  28. diffusers/models/transformers/__init__.py +1 -0
  29. diffusers/models/transformers/auraflow_transformer_2d.py +1 -0
  30. diffusers/models/transformers/cogvideox_transformer_3d.py +58 -36
  31. diffusers/models/transformers/pixart_transformer_2d.py +9 -1
  32. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  33. diffusers/models/transformers/transformer_flux.py +161 -44
  34. diffusers/models/transformers/transformer_sd3.py +7 -1
  35. diffusers/models/unets/unet_2d_condition.py +8 -8
  36. diffusers/models/unets/unet_motion_model.py +41 -63
  37. diffusers/models/upsampling.py +6 -6
  38. diffusers/pipelines/__init__.py +40 -7
  39. diffusers/pipelines/animatediff/__init__.py +2 -0
  40. diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
  41. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +44 -20
  42. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
  43. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +2 -0
  44. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -66
  45. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  46. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -1
  47. diffusers/pipelines/auto_pipeline.py +39 -8
  48. diffusers/pipelines/cogvideo/__init__.py +6 -0
  49. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +32 -34
  50. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +794 -0
  51. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +837 -0
  52. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +825 -0
  53. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  54. diffusers/pipelines/cogview3/__init__.py +47 -0
  55. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  56. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  57. diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -1
  58. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +8 -0
  59. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +8 -0
  60. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +36 -13
  61. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -1
  62. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +8 -1
  63. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +17 -3
  64. diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
  65. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +3 -1
  66. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  67. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  68. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  69. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
  70. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
  71. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  72. diffusers/pipelines/flux/__init__.py +10 -0
  73. diffusers/pipelines/flux/pipeline_flux.py +53 -20
  74. diffusers/pipelines/flux/pipeline_flux_controlnet.py +984 -0
  75. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +988 -0
  76. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1182 -0
  77. diffusers/pipelines/flux/pipeline_flux_img2img.py +850 -0
  78. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1015 -0
  79. diffusers/pipelines/free_noise_utils.py +365 -5
  80. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +15 -3
  81. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
  82. diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
  83. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
  84. diffusers/pipelines/kolors/tokenizer.py +4 -0
  85. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
  86. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
  87. diffusers/pipelines/latte/pipeline_latte.py +2 -2
  88. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
  89. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
  90. diffusers/pipelines/lumina/pipeline_lumina.py +2 -2
  91. diffusers/pipelines/pag/__init__.py +6 -0
  92. diffusers/pipelines/pag/pag_utils.py +8 -2
  93. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -1
  94. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1544 -0
  95. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +2 -2
  96. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1685 -0
  97. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +17 -5
  98. diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
  99. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +1 -1
  100. diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
  101. diffusers/pipelines/pag/pipeline_pag_sd_3.py +12 -3
  102. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
  103. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1091 -0
  104. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
  105. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
  106. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
  107. diffusers/pipelines/pia/pipeline_pia.py +2 -0
  108. diffusers/pipelines/pipeline_loading_utils.py +225 -27
  109. diffusers/pipelines/pipeline_utils.py +123 -180
  110. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
  111. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
  112. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
  113. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
  114. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +28 -6
  115. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
  116. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
  117. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
  118. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +12 -3
  119. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +20 -4
  120. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +3 -3
  121. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  122. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
  123. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
  124. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -4
  125. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -14
  126. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -14
  127. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
  128. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
  129. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
  130. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
  131. diffusers/quantizers/__init__.py +16 -0
  132. diffusers/quantizers/auto.py +126 -0
  133. diffusers/quantizers/base.py +233 -0
  134. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  135. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +558 -0
  136. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  137. diffusers/quantizers/quantization_config.py +391 -0
  138. diffusers/schedulers/scheduling_ddim.py +4 -1
  139. diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
  140. diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
  141. diffusers/schedulers/scheduling_ddpm.py +4 -1
  142. diffusers/schedulers/scheduling_ddpm_parallel.py +4 -1
  143. diffusers/schedulers/scheduling_deis_multistep.py +78 -1
  144. diffusers/schedulers/scheduling_dpmsolver_multistep.py +82 -1
  145. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +80 -1
  146. diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
  147. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +82 -1
  148. diffusers/schedulers/scheduling_edm_euler.py +8 -6
  149. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
  150. diffusers/schedulers/scheduling_euler_discrete.py +92 -7
  151. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
  152. diffusers/schedulers/scheduling_heun_discrete.py +114 -8
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
  155. diffusers/schedulers/scheduling_lms_discrete.py +76 -1
  156. diffusers/schedulers/scheduling_sasolver.py +78 -1
  157. diffusers/schedulers/scheduling_unclip.py +4 -1
  158. diffusers/schedulers/scheduling_unipc_multistep.py +78 -1
  159. diffusers/training_utils.py +48 -18
  160. diffusers/utils/__init__.py +2 -1
  161. diffusers/utils/dummy_pt_objects.py +60 -0
  162. diffusers/utils/dummy_torch_and_transformers_objects.py +195 -0
  163. diffusers/utils/hub_utils.py +16 -4
  164. diffusers/utils/import_utils.py +31 -8
  165. diffusers/utils/loading_utils.py +28 -4
  166. diffusers/utils/peft_utils.py +3 -3
  167. diffusers/utils/testing_utils.py +59 -0
  168. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/METADATA +7 -6
  169. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/RECORD +173 -147
  170. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/WHEEL +1 -1
  171. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/LICENSE +0 -0
  172. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/entry_points.txt +0 -0
  173. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,984 @@
1
+ # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX 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, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import (
21
+ CLIPTextModel,
22
+ CLIPTokenizer,
23
+ T5EncoderModel,
24
+ T5TokenizerFast,
25
+ )
26
+
27
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
28
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
29
+ from ...models.autoencoders import AutoencoderKL
30
+ from ...models.controlnet_flux import FluxControlNetModel, FluxMultiControlNetModel
31
+ from ...models.transformers import FluxTransformer2DModel
32
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
33
+ from ...utils import (
34
+ USE_PEFT_BACKEND,
35
+ is_torch_xla_available,
36
+ logging,
37
+ replace_example_docstring,
38
+ scale_lora_layers,
39
+ unscale_lora_layers,
40
+ )
41
+ from ...utils.torch_utils import randn_tensor
42
+ from ..pipeline_utils import DiffusionPipeline
43
+ from .pipeline_output import FluxPipelineOutput
44
+
45
+
46
+ if is_torch_xla_available():
47
+ import torch_xla.core.xla_model as xm
48
+
49
+ XLA_AVAILABLE = True
50
+ else:
51
+ XLA_AVAILABLE = False
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ EXAMPLE_DOC_STRING = """
57
+ Examples:
58
+ ```py
59
+ >>> import torch
60
+ >>> from diffusers.utils import load_image
61
+ >>> from diffusers import FluxControlNetPipeline
62
+ >>> from diffusers import FluxControlNetModel
63
+
64
+ >>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny"
65
+ >>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
66
+ >>> pipe = FluxControlNetPipeline.from_pretrained(
67
+ ... base_model, controlnet=controlnet, torch_dtype=torch.bfloat16
68
+ ... )
69
+ >>> pipe.to("cuda")
70
+ >>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
71
+ >>> prompt = "A girl in city, 25 years old, cool, futuristic"
72
+ >>> image = pipe(
73
+ ... prompt,
74
+ ... control_image=control_image,
75
+ ... control_guidance_start=0.2,
76
+ ... control_guidance_end=0.8,
77
+ ... controlnet_conditioning_scale=1.0,
78
+ ... num_inference_steps=28,
79
+ ... guidance_scale=3.5,
80
+ ... ).images[0]
81
+ >>> image.save("flux.png")
82
+ ```
83
+ """
84
+
85
+
86
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
87
+ def calculate_shift(
88
+ image_seq_len,
89
+ base_seq_len: int = 256,
90
+ max_seq_len: int = 4096,
91
+ base_shift: float = 0.5,
92
+ max_shift: float = 1.16,
93
+ ):
94
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
95
+ b = base_shift - m * base_seq_len
96
+ mu = image_seq_len * m + b
97
+ return mu
98
+
99
+
100
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
101
+ def retrieve_timesteps(
102
+ scheduler,
103
+ num_inference_steps: Optional[int] = None,
104
+ device: Optional[Union[str, torch.device]] = None,
105
+ timesteps: Optional[List[int]] = None,
106
+ sigmas: Optional[List[float]] = None,
107
+ **kwargs,
108
+ ):
109
+ r"""
110
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
111
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
112
+
113
+ Args:
114
+ scheduler (`SchedulerMixin`):
115
+ The scheduler to get timesteps from.
116
+ num_inference_steps (`int`):
117
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
118
+ must be `None`.
119
+ device (`str` or `torch.device`, *optional*):
120
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
121
+ timesteps (`List[int]`, *optional*):
122
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
123
+ `num_inference_steps` and `sigmas` must be `None`.
124
+ sigmas (`List[float]`, *optional*):
125
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
126
+ `num_inference_steps` and `timesteps` must be `None`.
127
+
128
+ Returns:
129
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
130
+ second element is the number of inference steps.
131
+ """
132
+ if timesteps is not None and sigmas is not None:
133
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
134
+ if timesteps is not None:
135
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
136
+ if not accepts_timesteps:
137
+ raise ValueError(
138
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
139
+ f" timestep schedules. Please check whether you are using the correct scheduler."
140
+ )
141
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
142
+ timesteps = scheduler.timesteps
143
+ num_inference_steps = len(timesteps)
144
+ elif sigmas is not None:
145
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
146
+ if not accept_sigmas:
147
+ raise ValueError(
148
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
149
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
150
+ )
151
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
152
+ timesteps = scheduler.timesteps
153
+ num_inference_steps = len(timesteps)
154
+ else:
155
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
156
+ timesteps = scheduler.timesteps
157
+ return timesteps, num_inference_steps
158
+
159
+
160
+ class FluxControlNetPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
161
+ r"""
162
+ The Flux pipeline for text-to-image generation.
163
+
164
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
165
+
166
+ Args:
167
+ transformer ([`FluxTransformer2DModel`]):
168
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
169
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
170
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
171
+ vae ([`AutoencoderKL`]):
172
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
173
+ text_encoder ([`CLIPTextModel`]):
174
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
175
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
176
+ text_encoder_2 ([`T5EncoderModel`]):
177
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
178
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
179
+ tokenizer (`CLIPTokenizer`):
180
+ Tokenizer of class
181
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
182
+ tokenizer_2 (`T5TokenizerFast`):
183
+ Second Tokenizer of class
184
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
185
+ """
186
+
187
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
188
+ _optional_components = []
189
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
190
+
191
+ def __init__(
192
+ self,
193
+ scheduler: FlowMatchEulerDiscreteScheduler,
194
+ vae: AutoencoderKL,
195
+ text_encoder: CLIPTextModel,
196
+ tokenizer: CLIPTokenizer,
197
+ text_encoder_2: T5EncoderModel,
198
+ tokenizer_2: T5TokenizerFast,
199
+ transformer: FluxTransformer2DModel,
200
+ controlnet: Union[
201
+ FluxControlNetModel, List[FluxControlNetModel], Tuple[FluxControlNetModel], FluxMultiControlNetModel
202
+ ],
203
+ ):
204
+ super().__init__()
205
+ if isinstance(controlnet, (list, tuple)):
206
+ controlnet = FluxMultiControlNetModel(controlnet)
207
+
208
+ self.register_modules(
209
+ vae=vae,
210
+ text_encoder=text_encoder,
211
+ text_encoder_2=text_encoder_2,
212
+ tokenizer=tokenizer,
213
+ tokenizer_2=tokenizer_2,
214
+ transformer=transformer,
215
+ scheduler=scheduler,
216
+ controlnet=controlnet,
217
+ )
218
+ self.vae_scale_factor = (
219
+ 2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
220
+ )
221
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
222
+ self.tokenizer_max_length = (
223
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
224
+ )
225
+ self.default_sample_size = 64
226
+
227
+ def _get_t5_prompt_embeds(
228
+ self,
229
+ prompt: Union[str, List[str]] = None,
230
+ num_images_per_prompt: int = 1,
231
+ max_sequence_length: int = 512,
232
+ device: Optional[torch.device] = None,
233
+ dtype: Optional[torch.dtype] = None,
234
+ ):
235
+ device = device or self._execution_device
236
+ dtype = dtype or self.text_encoder.dtype
237
+
238
+ prompt = [prompt] if isinstance(prompt, str) else prompt
239
+ batch_size = len(prompt)
240
+
241
+ if isinstance(self, TextualInversionLoaderMixin):
242
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
243
+
244
+ text_inputs = self.tokenizer_2(
245
+ prompt,
246
+ padding="max_length",
247
+ max_length=max_sequence_length,
248
+ truncation=True,
249
+ return_length=False,
250
+ return_overflowing_tokens=False,
251
+ return_tensors="pt",
252
+ )
253
+ text_input_ids = text_inputs.input_ids
254
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
255
+
256
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
257
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
258
+ logger.warning(
259
+ "The following part of your input was truncated because `max_sequence_length` is set to "
260
+ f" {max_sequence_length} tokens: {removed_text}"
261
+ )
262
+
263
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
264
+
265
+ dtype = self.text_encoder_2.dtype
266
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
267
+
268
+ _, seq_len, _ = prompt_embeds.shape
269
+
270
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
271
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
272
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
273
+
274
+ return prompt_embeds
275
+
276
+ def _get_clip_prompt_embeds(
277
+ self,
278
+ prompt: Union[str, List[str]],
279
+ num_images_per_prompt: int = 1,
280
+ device: Optional[torch.device] = None,
281
+ ):
282
+ device = device or self._execution_device
283
+
284
+ prompt = [prompt] if isinstance(prompt, str) else prompt
285
+ batch_size = len(prompt)
286
+
287
+ if isinstance(self, TextualInversionLoaderMixin):
288
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
289
+
290
+ text_inputs = self.tokenizer(
291
+ prompt,
292
+ padding="max_length",
293
+ max_length=self.tokenizer_max_length,
294
+ truncation=True,
295
+ return_overflowing_tokens=False,
296
+ return_length=False,
297
+ return_tensors="pt",
298
+ )
299
+
300
+ text_input_ids = text_inputs.input_ids
301
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
302
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
303
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
304
+ logger.warning(
305
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
306
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
307
+ )
308
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
309
+
310
+ # Use pooled output of CLIPTextModel
311
+ prompt_embeds = prompt_embeds.pooler_output
312
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
313
+
314
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
315
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
316
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
317
+
318
+ return prompt_embeds
319
+
320
+ def encode_prompt(
321
+ self,
322
+ prompt: Union[str, List[str]],
323
+ prompt_2: Union[str, List[str]],
324
+ device: Optional[torch.device] = None,
325
+ num_images_per_prompt: int = 1,
326
+ prompt_embeds: Optional[torch.FloatTensor] = None,
327
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
328
+ max_sequence_length: int = 512,
329
+ lora_scale: Optional[float] = None,
330
+ ):
331
+ r"""
332
+
333
+ Args:
334
+ prompt (`str` or `List[str]`, *optional*):
335
+ prompt to be encoded
336
+ prompt_2 (`str` or `List[str]`, *optional*):
337
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
338
+ used in all text-encoders
339
+ device: (`torch.device`):
340
+ torch device
341
+ num_images_per_prompt (`int`):
342
+ number of images that should be generated per prompt
343
+ prompt_embeds (`torch.FloatTensor`, *optional*):
344
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
345
+ provided, text embeddings will be generated from `prompt` input argument.
346
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
347
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
348
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
349
+ clip_skip (`int`, *optional*):
350
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
351
+ the output of the pre-final layer will be used for computing the prompt embeddings.
352
+ lora_scale (`float`, *optional*):
353
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
354
+ """
355
+ device = device or self._execution_device
356
+
357
+ # set lora scale so that monkey patched LoRA
358
+ # function of text encoder can correctly access it
359
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
360
+ self._lora_scale = lora_scale
361
+
362
+ # dynamically adjust the LoRA scale
363
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
364
+ scale_lora_layers(self.text_encoder, lora_scale)
365
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
366
+ scale_lora_layers(self.text_encoder_2, lora_scale)
367
+
368
+ prompt = [prompt] if isinstance(prompt, str) else prompt
369
+
370
+ if prompt_embeds is None:
371
+ prompt_2 = prompt_2 or prompt
372
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
373
+
374
+ # We only use the pooled prompt output from the CLIPTextModel
375
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
376
+ prompt=prompt,
377
+ device=device,
378
+ num_images_per_prompt=num_images_per_prompt,
379
+ )
380
+ prompt_embeds = self._get_t5_prompt_embeds(
381
+ prompt=prompt_2,
382
+ num_images_per_prompt=num_images_per_prompt,
383
+ max_sequence_length=max_sequence_length,
384
+ device=device,
385
+ )
386
+
387
+ if self.text_encoder is not None:
388
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
389
+ # Retrieve the original scale by scaling back the LoRA layers
390
+ unscale_lora_layers(self.text_encoder, lora_scale)
391
+
392
+ if self.text_encoder_2 is not None:
393
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
394
+ # Retrieve the original scale by scaling back the LoRA layers
395
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
396
+
397
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
398
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
399
+
400
+ return prompt_embeds, pooled_prompt_embeds, text_ids
401
+
402
+ def check_inputs(
403
+ self,
404
+ prompt,
405
+ prompt_2,
406
+ height,
407
+ width,
408
+ prompt_embeds=None,
409
+ pooled_prompt_embeds=None,
410
+ callback_on_step_end_tensor_inputs=None,
411
+ max_sequence_length=None,
412
+ ):
413
+ if height % 8 != 0 or width % 8 != 0:
414
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
415
+
416
+ if callback_on_step_end_tensor_inputs is not None and not all(
417
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
418
+ ):
419
+ raise ValueError(
420
+ 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]}"
421
+ )
422
+
423
+ if prompt is not None and prompt_embeds is not None:
424
+ raise ValueError(
425
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
426
+ " only forward one of the two."
427
+ )
428
+ elif prompt_2 is not None and prompt_embeds is not None:
429
+ raise ValueError(
430
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
431
+ " only forward one of the two."
432
+ )
433
+ elif prompt is None and prompt_embeds is None:
434
+ raise ValueError(
435
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
436
+ )
437
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
438
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
439
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
440
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
441
+
442
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
443
+ raise ValueError(
444
+ "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`."
445
+ )
446
+
447
+ if max_sequence_length is not None and max_sequence_length > 512:
448
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
449
+
450
+ @staticmethod
451
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
452
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
453
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
454
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
455
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
456
+
457
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
458
+
459
+ latent_image_ids = latent_image_ids.reshape(
460
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
461
+ )
462
+
463
+ return latent_image_ids.to(device=device, dtype=dtype)
464
+
465
+ @staticmethod
466
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
467
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
468
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
469
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
470
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
471
+
472
+ return latents
473
+
474
+ @staticmethod
475
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
476
+ def _unpack_latents(latents, height, width, vae_scale_factor):
477
+ batch_size, num_patches, channels = latents.shape
478
+
479
+ height = height // vae_scale_factor
480
+ width = width // vae_scale_factor
481
+
482
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
483
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
484
+
485
+ latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
486
+
487
+ return latents
488
+
489
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_latents
490
+ def prepare_latents(
491
+ self,
492
+ batch_size,
493
+ num_channels_latents,
494
+ height,
495
+ width,
496
+ dtype,
497
+ device,
498
+ generator,
499
+ latents=None,
500
+ ):
501
+ height = 2 * (int(height) // self.vae_scale_factor)
502
+ width = 2 * (int(width) // self.vae_scale_factor)
503
+
504
+ shape = (batch_size, num_channels_latents, height, width)
505
+
506
+ if latents is not None:
507
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
508
+ return latents.to(device=device, dtype=dtype), latent_image_ids
509
+
510
+ if isinstance(generator, list) and len(generator) != batch_size:
511
+ raise ValueError(
512
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
513
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
514
+ )
515
+
516
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
517
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
518
+
519
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
520
+
521
+ return latents, latent_image_ids
522
+
523
+ # Copied from diffusers.pipelines.controlnet_sd3.pipeline_stable_diffusion_3_controlnet.StableDiffusion3ControlNetPipeline.prepare_image
524
+ def prepare_image(
525
+ self,
526
+ image,
527
+ width,
528
+ height,
529
+ batch_size,
530
+ num_images_per_prompt,
531
+ device,
532
+ dtype,
533
+ do_classifier_free_guidance=False,
534
+ guess_mode=False,
535
+ ):
536
+ if isinstance(image, torch.Tensor):
537
+ pass
538
+ else:
539
+ image = self.image_processor.preprocess(image, height=height, width=width)
540
+
541
+ image_batch_size = image.shape[0]
542
+
543
+ if image_batch_size == 1:
544
+ repeat_by = batch_size
545
+ else:
546
+ # image batch size is the same as prompt batch size
547
+ repeat_by = num_images_per_prompt
548
+
549
+ image = image.repeat_interleave(repeat_by, dim=0)
550
+
551
+ image = image.to(device=device, dtype=dtype)
552
+
553
+ if do_classifier_free_guidance and not guess_mode:
554
+ image = torch.cat([image] * 2)
555
+
556
+ return image
557
+
558
+ @property
559
+ def guidance_scale(self):
560
+ return self._guidance_scale
561
+
562
+ @property
563
+ def joint_attention_kwargs(self):
564
+ return self._joint_attention_kwargs
565
+
566
+ @property
567
+ def num_timesteps(self):
568
+ return self._num_timesteps
569
+
570
+ @property
571
+ def interrupt(self):
572
+ return self._interrupt
573
+
574
+ @torch.no_grad()
575
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
576
+ def __call__(
577
+ self,
578
+ prompt: Union[str, List[str]] = None,
579
+ prompt_2: Optional[Union[str, List[str]]] = None,
580
+ height: Optional[int] = None,
581
+ width: Optional[int] = None,
582
+ num_inference_steps: int = 28,
583
+ timesteps: List[int] = None,
584
+ guidance_scale: float = 7.0,
585
+ control_guidance_start: Union[float, List[float]] = 0.0,
586
+ control_guidance_end: Union[float, List[float]] = 1.0,
587
+ control_image: PipelineImageInput = None,
588
+ control_mode: Optional[Union[int, List[int]]] = None,
589
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
590
+ num_images_per_prompt: Optional[int] = 1,
591
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
592
+ latents: Optional[torch.FloatTensor] = None,
593
+ prompt_embeds: Optional[torch.FloatTensor] = None,
594
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
595
+ output_type: Optional[str] = "pil",
596
+ return_dict: bool = True,
597
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
598
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
599
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
600
+ max_sequence_length: int = 512,
601
+ ):
602
+ r"""
603
+ Function invoked when calling the pipeline for generation.
604
+
605
+ Args:
606
+ prompt (`str` or `List[str]`, *optional*):
607
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
608
+ instead.
609
+ prompt_2 (`str` or `List[str]`, *optional*):
610
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
611
+ will be used instead
612
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
613
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
614
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
615
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
616
+ num_inference_steps (`int`, *optional*, defaults to 50):
617
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
618
+ expense of slower inference.
619
+ timesteps (`List[int]`, *optional*):
620
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
621
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
622
+ passed will be used. Must be in descending order.
623
+ guidance_scale (`float`, *optional*, defaults to 7.0):
624
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
625
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
626
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
627
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
628
+ usually at the expense of lower image quality.
629
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
630
+ The percentage of total steps at which the ControlNet starts applying.
631
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
632
+ The percentage of total steps at which the ControlNet stops applying.
633
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
634
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
635
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
636
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
637
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
638
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
639
+ images must be passed as a list such that each element of the list can be correctly batched for input
640
+ to a single ControlNet.
641
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
642
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
643
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
644
+ the corresponding scale as a list.
645
+ control_mode (`int` or `List[int]`,, *optional*, defaults to None):
646
+ The control mode when applying ControlNet-Union.
647
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
648
+ The number of images to generate per prompt.
649
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
650
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
651
+ to make generation deterministic.
652
+ latents (`torch.FloatTensor`, *optional*):
653
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
654
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
655
+ tensor will ge generated by sampling using the supplied random `generator`.
656
+ prompt_embeds (`torch.FloatTensor`, *optional*):
657
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
658
+ provided, text embeddings will be generated from `prompt` input argument.
659
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
660
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
661
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
662
+ output_type (`str`, *optional*, defaults to `"pil"`):
663
+ The output format of the generate image. Choose between
664
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
665
+ return_dict (`bool`, *optional*, defaults to `True`):
666
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
667
+ joint_attention_kwargs (`dict`, *optional*):
668
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
669
+ `self.processor` in
670
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
671
+ callback_on_step_end (`Callable`, *optional*):
672
+ A function that calls at the end of each denoising steps during the inference. The function is called
673
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
674
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
675
+ `callback_on_step_end_tensor_inputs`.
676
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
677
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
678
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
679
+ `._callback_tensor_inputs` attribute of your pipeline class.
680
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
681
+
682
+ Examples:
683
+
684
+ Returns:
685
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
686
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
687
+ images.
688
+ """
689
+
690
+ height = height or self.default_sample_size * self.vae_scale_factor
691
+ width = width or self.default_sample_size * self.vae_scale_factor
692
+
693
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
694
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
695
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
696
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
697
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
698
+ mult = len(self.controlnet.nets) if isinstance(self.controlnet, FluxMultiControlNetModel) else 1
699
+ control_guidance_start, control_guidance_end = (
700
+ mult * [control_guidance_start],
701
+ mult * [control_guidance_end],
702
+ )
703
+
704
+ # 1. Check inputs. Raise error if not correct
705
+ self.check_inputs(
706
+ prompt,
707
+ prompt_2,
708
+ height,
709
+ width,
710
+ prompt_embeds=prompt_embeds,
711
+ pooled_prompt_embeds=pooled_prompt_embeds,
712
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
713
+ max_sequence_length=max_sequence_length,
714
+ )
715
+
716
+ self._guidance_scale = guidance_scale
717
+ self._joint_attention_kwargs = joint_attention_kwargs
718
+ self._interrupt = False
719
+
720
+ # 2. Define call parameters
721
+ if prompt is not None and isinstance(prompt, str):
722
+ batch_size = 1
723
+ elif prompt is not None and isinstance(prompt, list):
724
+ batch_size = len(prompt)
725
+ else:
726
+ batch_size = prompt_embeds.shape[0]
727
+
728
+ device = self._execution_device
729
+ dtype = self.transformer.dtype
730
+
731
+ lora_scale = (
732
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
733
+ )
734
+ (
735
+ prompt_embeds,
736
+ pooled_prompt_embeds,
737
+ text_ids,
738
+ ) = self.encode_prompt(
739
+ prompt=prompt,
740
+ prompt_2=prompt_2,
741
+ prompt_embeds=prompt_embeds,
742
+ pooled_prompt_embeds=pooled_prompt_embeds,
743
+ device=device,
744
+ num_images_per_prompt=num_images_per_prompt,
745
+ max_sequence_length=max_sequence_length,
746
+ lora_scale=lora_scale,
747
+ )
748
+
749
+ # 3. Prepare control image
750
+ num_channels_latents = self.transformer.config.in_channels // 4
751
+ if isinstance(self.controlnet, FluxControlNetModel):
752
+ control_image = self.prepare_image(
753
+ image=control_image,
754
+ width=width,
755
+ height=height,
756
+ batch_size=batch_size * num_images_per_prompt,
757
+ num_images_per_prompt=num_images_per_prompt,
758
+ device=device,
759
+ dtype=self.vae.dtype,
760
+ )
761
+ height, width = control_image.shape[-2:]
762
+
763
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
764
+ controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True
765
+ if self.controlnet.input_hint_block is None:
766
+ # vae encode
767
+ control_image = self.vae.encode(control_image).latent_dist.sample()
768
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
769
+
770
+ # pack
771
+ height_control_image, width_control_image = control_image.shape[2:]
772
+ control_image = self._pack_latents(
773
+ control_image,
774
+ batch_size * num_images_per_prompt,
775
+ num_channels_latents,
776
+ height_control_image,
777
+ width_control_image,
778
+ )
779
+
780
+ # Here we ensure that `control_mode` has the same length as the control_image.
781
+ if control_mode is not None:
782
+ if not isinstance(control_mode, int):
783
+ raise ValueError(" For `FluxControlNet`, `control_mode` should be an `int` or `None`")
784
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
785
+ control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
786
+
787
+ elif isinstance(self.controlnet, FluxMultiControlNetModel):
788
+ control_images = []
789
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
790
+ controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True
791
+ for i, control_image_ in enumerate(control_image):
792
+ control_image_ = self.prepare_image(
793
+ image=control_image_,
794
+ width=width,
795
+ height=height,
796
+ batch_size=batch_size * num_images_per_prompt,
797
+ num_images_per_prompt=num_images_per_prompt,
798
+ device=device,
799
+ dtype=self.vae.dtype,
800
+ )
801
+ height, width = control_image_.shape[-2:]
802
+
803
+ if self.controlnet.nets[0].input_hint_block is None:
804
+ # vae encode
805
+ control_image_ = self.vae.encode(control_image_).latent_dist.sample()
806
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
807
+
808
+ # pack
809
+ height_control_image, width_control_image = control_image_.shape[2:]
810
+ control_image_ = self._pack_latents(
811
+ control_image_,
812
+ batch_size * num_images_per_prompt,
813
+ num_channels_latents,
814
+ height_control_image,
815
+ width_control_image,
816
+ )
817
+ control_images.append(control_image_)
818
+
819
+ control_image = control_images
820
+
821
+ # Here we ensure that `control_mode` has the same length as the control_image.
822
+ if isinstance(control_mode, list) and len(control_mode) != len(control_image):
823
+ raise ValueError(
824
+ "For Multi-ControlNet, `control_mode` must be a list of the same "
825
+ + " length as the number of controlnets (control images) specified"
826
+ )
827
+ if not isinstance(control_mode, list):
828
+ control_mode = [control_mode] * len(control_image)
829
+ # set control mode
830
+ control_modes = []
831
+ for cmode in control_mode:
832
+ if cmode is None:
833
+ cmode = -1
834
+ control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long)
835
+ control_modes.append(control_mode)
836
+ control_mode = control_modes
837
+
838
+ # 4. Prepare latent variables
839
+ num_channels_latents = self.transformer.config.in_channels // 4
840
+ latents, latent_image_ids = self.prepare_latents(
841
+ batch_size * num_images_per_prompt,
842
+ num_channels_latents,
843
+ height,
844
+ width,
845
+ prompt_embeds.dtype,
846
+ device,
847
+ generator,
848
+ latents,
849
+ )
850
+
851
+ # 5. Prepare timesteps
852
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
853
+ image_seq_len = latents.shape[1]
854
+ mu = calculate_shift(
855
+ image_seq_len,
856
+ self.scheduler.config.base_image_seq_len,
857
+ self.scheduler.config.max_image_seq_len,
858
+ self.scheduler.config.base_shift,
859
+ self.scheduler.config.max_shift,
860
+ )
861
+ timesteps, num_inference_steps = retrieve_timesteps(
862
+ self.scheduler,
863
+ num_inference_steps,
864
+ device,
865
+ timesteps,
866
+ sigmas,
867
+ mu=mu,
868
+ )
869
+
870
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
871
+ self._num_timesteps = len(timesteps)
872
+
873
+ # 6. Create tensor stating which controlnets to keep
874
+ controlnet_keep = []
875
+ for i in range(len(timesteps)):
876
+ keeps = [
877
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
878
+ for s, e in zip(control_guidance_start, control_guidance_end)
879
+ ]
880
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
881
+
882
+ # 7. Denoising loop
883
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
884
+ for i, t in enumerate(timesteps):
885
+ if self.interrupt:
886
+ continue
887
+
888
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
889
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
890
+
891
+ if isinstance(self.controlnet, FluxMultiControlNetModel):
892
+ use_guidance = self.controlnet.nets[0].config.guidance_embeds
893
+ else:
894
+ use_guidance = self.controlnet.config.guidance_embeds
895
+
896
+ guidance = torch.tensor([guidance_scale], device=device) if use_guidance else None
897
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
898
+
899
+ if isinstance(controlnet_keep[i], list):
900
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
901
+ else:
902
+ controlnet_cond_scale = controlnet_conditioning_scale
903
+ if isinstance(controlnet_cond_scale, list):
904
+ controlnet_cond_scale = controlnet_cond_scale[0]
905
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
906
+
907
+ # controlnet
908
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
909
+ hidden_states=latents,
910
+ controlnet_cond=control_image,
911
+ controlnet_mode=control_mode,
912
+ conditioning_scale=cond_scale,
913
+ timestep=timestep / 1000,
914
+ guidance=guidance,
915
+ pooled_projections=pooled_prompt_embeds,
916
+ encoder_hidden_states=prompt_embeds,
917
+ txt_ids=text_ids,
918
+ img_ids=latent_image_ids,
919
+ joint_attention_kwargs=self.joint_attention_kwargs,
920
+ return_dict=False,
921
+ )
922
+
923
+ guidance = (
924
+ torch.tensor([guidance_scale], device=device) if self.transformer.config.guidance_embeds else None
925
+ )
926
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
927
+
928
+ noise_pred = self.transformer(
929
+ hidden_states=latents,
930
+ timestep=timestep / 1000,
931
+ guidance=guidance,
932
+ pooled_projections=pooled_prompt_embeds,
933
+ encoder_hidden_states=prompt_embeds,
934
+ controlnet_block_samples=controlnet_block_samples,
935
+ controlnet_single_block_samples=controlnet_single_block_samples,
936
+ txt_ids=text_ids,
937
+ img_ids=latent_image_ids,
938
+ joint_attention_kwargs=self.joint_attention_kwargs,
939
+ return_dict=False,
940
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
941
+ )[0]
942
+
943
+ # compute the previous noisy sample x_t -> x_t-1
944
+ latents_dtype = latents.dtype
945
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
946
+
947
+ if latents.dtype != latents_dtype:
948
+ if torch.backends.mps.is_available():
949
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
950
+ latents = latents.to(latents_dtype)
951
+
952
+ if callback_on_step_end is not None:
953
+ callback_kwargs = {}
954
+ for k in callback_on_step_end_tensor_inputs:
955
+ callback_kwargs[k] = locals()[k]
956
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
957
+
958
+ latents = callback_outputs.pop("latents", latents)
959
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
960
+
961
+ # call the callback, if provided
962
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
963
+ progress_bar.update()
964
+
965
+ if XLA_AVAILABLE:
966
+ xm.mark_step()
967
+
968
+ if output_type == "latent":
969
+ image = latents
970
+
971
+ else:
972
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
973
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
974
+
975
+ image = self.vae.decode(latents, return_dict=False)[0]
976
+ image = self.image_processor.postprocess(image, output_type=output_type)
977
+
978
+ # Offload all models
979
+ self.maybe_free_model_hooks()
980
+
981
+ if not return_dict:
982
+ return (image,)
983
+
984
+ return FluxPipelineOutput(images=image)