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