afromero commited on
Commit
22a60c2
1 Parent(s): 55f828b

Create pipeline.py

Browse files

The Flux pipeline for image inpainting using Flux-dev-Depth/Canny

Files changed (1) hide show
  1. pipeline.py +1099 -0
pipeline.py ADDED
@@ -0,0 +1,1099 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
21
+ from diffusers.loaders import (
22
+ FluxLoraLoaderMixin,
23
+ FromSingleFileMixin,
24
+ TextualInversionLoaderMixin,
25
+ )
26
+ from diffusers.models.autoencoders import AutoencoderKL
27
+ from diffusers.models.transformers import FluxTransformer2DModel
28
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
31
+ from diffusers.utils import (
32
+ USE_PEFT_BACKEND,
33
+ is_torch_xla_available,
34
+ logging,
35
+ replace_example_docstring,
36
+ scale_lora_layers,
37
+ unscale_lora_layers,
38
+ )
39
+ from diffusers.utils.torch_utils import randn_tensor
40
+ from transformers import (
41
+ CLIPTextModel,
42
+ CLIPTokenizer,
43
+ T5EncoderModel,
44
+ T5TokenizerFast,
45
+ )
46
+
47
+ if is_torch_xla_available():
48
+ import torch_xla.core.xla_model as xm
49
+
50
+ XLA_AVAILABLE = True
51
+ else:
52
+ XLA_AVAILABLE = False
53
+
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+ EXAMPLE_DOC_STRING = """
58
+ Examples:
59
+ ```py
60
+ import torch
61
+ from diffusers import DiffusionPipeline, FluxTransformer2DModel
62
+ from transformers import T5EncoderModel
63
+ from diffusers.utils import load_image
64
+ from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
65
+ import numpy as np
66
+
67
+ pipe = DiffusionPipeline.from_pretrained(
68
+ "black-forest-labs/FLUX.1-Depth-dev",
69
+ torch_dtype=torch.bfloat16,
70
+ custom_pipeline="afromero/pipeline_flux_control_inpaint",
71
+ )
72
+
73
+ transformer = FluxTransformer2DModel.from_pretrained(
74
+ "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
75
+ )
76
+ text_encoder_2 = T5EncoderModel.from_pretrained(
77
+ "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
78
+ )
79
+ pipe.transformer = transformer
80
+ pipe.text_encoder_2 = text_encoder_2
81
+ pipe.to("cuda")
82
+
83
+ prompt = "The head of a human in a robot body giving a heated speech"
84
+ control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")
85
+
86
+ head_mask = np.ones_like(control_image)*255
87
+ head_mask[65:380,300:642] = 0
88
+ mask_image = Image.fromarray(head_mask)
89
+
90
+ processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
91
+ control_image = processor(control_image)[0].convert("RGB")
92
+
93
+ image = pipe(
94
+ prompt=prompt,
95
+ control_image=control_image,
96
+ mask_image=mask_image,
97
+ strength=0.9,
98
+ height=1024,
99
+ width=1024,
100
+ num_inference_steps=30,
101
+ guidance_scale=10.0,
102
+ generator=torch.Generator().manual_seed(42),
103
+ ).images[0]
104
+ image.save("output.png")
105
+
106
+ ```
107
+ """
108
+
109
+
110
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
111
+ def calculate_shift(
112
+ image_seq_len,
113
+ base_seq_len: int = 256,
114
+ max_seq_len: int = 4096,
115
+ base_shift: float = 0.5,
116
+ max_shift: float = 1.16,
117
+ ):
118
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
119
+ b = base_shift - m * base_seq_len
120
+ mu = image_seq_len * m + b
121
+ return mu
122
+
123
+
124
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
125
+ def retrieve_latents(
126
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
127
+ ):
128
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
129
+ return encoder_output.latent_dist.sample(generator)
130
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
131
+ return encoder_output.latent_dist.mode()
132
+ elif hasattr(encoder_output, "latents"):
133
+ return encoder_output.latents
134
+ else:
135
+ raise AttributeError("Could not access latents of provided encoder_output")
136
+
137
+
138
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
139
+ def retrieve_timesteps(
140
+ scheduler,
141
+ num_inference_steps: Optional[int] = None,
142
+ device: Optional[Union[str, torch.device]] = None,
143
+ timesteps: Optional[List[int]] = None,
144
+ sigmas: Optional[List[float]] = None,
145
+ **kwargs,
146
+ ):
147
+ r"""
148
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
149
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
150
+
151
+ Args:
152
+ scheduler (`SchedulerMixin`):
153
+ The scheduler to get timesteps from.
154
+ num_inference_steps (`int`):
155
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
156
+ must be `None`.
157
+ device (`str` or `torch.device`, *optional*):
158
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
159
+ timesteps (`List[int]`, *optional*):
160
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
161
+ `num_inference_steps` and `sigmas` must be `None`.
162
+ sigmas (`List[float]`, *optional*):
163
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
164
+ `num_inference_steps` and `timesteps` must be `None`.
165
+
166
+ Returns:
167
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
168
+ second element is the number of inference steps.
169
+ """
170
+ if timesteps is not None and sigmas is not None:
171
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
172
+ if timesteps is not None:
173
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
174
+ if not accepts_timesteps:
175
+ raise ValueError(
176
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
177
+ f" timestep schedules. Please check whether you are using the correct scheduler."
178
+ )
179
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
180
+ timesteps = scheduler.timesteps
181
+ num_inference_steps = len(timesteps)
182
+ elif sigmas is not None:
183
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
184
+ if not accept_sigmas:
185
+ raise ValueError(
186
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
187
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
188
+ )
189
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
190
+ timesteps = scheduler.timesteps
191
+ num_inference_steps = len(timesteps)
192
+ else:
193
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
194
+ timesteps = scheduler.timesteps
195
+ return timesteps, num_inference_steps
196
+
197
+
198
+ class FluxControlInpaintPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
199
+ r"""
200
+ The Flux pipeline for image inpainting using Flux-dev-Depth/Canny.
201
+
202
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
203
+
204
+ Args:
205
+ transformer ([`FluxTransformer2DModel`]):
206
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
207
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
208
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
209
+ vae ([`AutoencoderKL`]):
210
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
211
+ text_encoder ([`CLIPTextModel`]):
212
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
213
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
214
+ text_encoder_2 ([`T5EncoderModel`]):
215
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
216
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
217
+ tokenizer (`CLIPTokenizer`):
218
+ Tokenizer of class
219
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
220
+ tokenizer_2 (`T5TokenizerFast`):
221
+ Second Tokenizer of class
222
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
223
+ """
224
+
225
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
226
+ _optional_components = []
227
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
228
+
229
+ def __init__(
230
+ self,
231
+ scheduler: FlowMatchEulerDiscreteScheduler,
232
+ vae: AutoencoderKL,
233
+ text_encoder: CLIPTextModel,
234
+ tokenizer: CLIPTokenizer,
235
+ text_encoder_2: T5EncoderModel,
236
+ tokenizer_2: T5TokenizerFast,
237
+ transformer: FluxTransformer2DModel,
238
+ ):
239
+ super().__init__()
240
+
241
+ self.register_modules(
242
+ vae=vae,
243
+ text_encoder=text_encoder,
244
+ text_encoder_2=text_encoder_2,
245
+ tokenizer=tokenizer,
246
+ tokenizer_2=tokenizer_2,
247
+ transformer=transformer,
248
+ scheduler=scheduler,
249
+ )
250
+ self.vae_scale_factor = (
251
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
252
+ )
253
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
254
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
255
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
256
+ self.mask_processor = VaeImageProcessor(
257
+ vae_scale_factor=self.vae_scale_factor * 2,
258
+ vae_latent_channels=self.vae.config.latent_channels,
259
+ do_normalize=False,
260
+ do_binarize=True,
261
+ do_convert_grayscale=True,
262
+ )
263
+ self.tokenizer_max_length = (
264
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
265
+ )
266
+ self.default_sample_size = 128
267
+
268
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
269
+ def _get_t5_prompt_embeds(
270
+ self,
271
+ prompt: Union[str, List[str]] = None,
272
+ num_images_per_prompt: int = 1,
273
+ max_sequence_length: int = 512,
274
+ device: Optional[torch.device] = None,
275
+ dtype: Optional[torch.dtype] = None,
276
+ ):
277
+ device = device or self._execution_device
278
+ dtype = dtype or self.text_encoder.dtype
279
+
280
+ prompt = [prompt] if isinstance(prompt, str) else prompt
281
+ batch_size = len(prompt)
282
+
283
+ if isinstance(self, TextualInversionLoaderMixin):
284
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
285
+
286
+ text_inputs = self.tokenizer_2(
287
+ prompt,
288
+ padding="max_length",
289
+ max_length=max_sequence_length,
290
+ truncation=True,
291
+ return_length=False,
292
+ return_overflowing_tokens=False,
293
+ return_tensors="pt",
294
+ )
295
+ text_input_ids = text_inputs.input_ids
296
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
297
+
298
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
299
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
300
+ logger.warning(
301
+ "The following part of your input was truncated because `max_sequence_length` is set to "
302
+ f" {max_sequence_length} tokens: {removed_text}"
303
+ )
304
+
305
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
306
+
307
+ dtype = self.text_encoder_2.dtype
308
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
309
+
310
+ _, seq_len, _ = prompt_embeds.shape
311
+
312
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
313
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
314
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
315
+
316
+ return prompt_embeds
317
+
318
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
319
+ def _get_clip_prompt_embeds(
320
+ self,
321
+ prompt: Union[str, List[str]],
322
+ num_images_per_prompt: int = 1,
323
+ device: Optional[torch.device] = None,
324
+ ):
325
+ device = device or self._execution_device
326
+
327
+ prompt = [prompt] if isinstance(prompt, str) else prompt
328
+ batch_size = len(prompt)
329
+
330
+ if isinstance(self, TextualInversionLoaderMixin):
331
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
332
+
333
+ text_inputs = self.tokenizer(
334
+ prompt,
335
+ padding="max_length",
336
+ max_length=self.tokenizer_max_length,
337
+ truncation=True,
338
+ return_overflowing_tokens=False,
339
+ return_length=False,
340
+ return_tensors="pt",
341
+ )
342
+
343
+ text_input_ids = text_inputs.input_ids
344
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
345
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
346
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
347
+ logger.warning(
348
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
349
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
350
+ )
351
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
352
+
353
+ # Use pooled output of CLIPTextModel
354
+ prompt_embeds = prompt_embeds.pooler_output
355
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
356
+
357
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
358
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
359
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
360
+
361
+ return prompt_embeds
362
+
363
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
364
+ def encode_prompt(
365
+ self,
366
+ prompt: Union[str, List[str]],
367
+ prompt_2: Union[str, List[str]],
368
+ device: Optional[torch.device] = None,
369
+ num_images_per_prompt: int = 1,
370
+ prompt_embeds: Optional[torch.FloatTensor] = None,
371
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
372
+ max_sequence_length: int = 512,
373
+ lora_scale: Optional[float] = None,
374
+ ):
375
+ r"""
376
+
377
+ Args:
378
+ prompt (`str` or `List[str]`, *optional*):
379
+ prompt to be encoded
380
+ prompt_2 (`str` or `List[str]`, *optional*):
381
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
382
+ used in all text-encoders
383
+ device: (`torch.device`):
384
+ torch device
385
+ num_images_per_prompt (`int`):
386
+ number of images that should be generated per prompt
387
+ prompt_embeds (`torch.FloatTensor`, *optional*):
388
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
389
+ provided, text embeddings will be generated from `prompt` input argument.
390
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
391
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
392
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
393
+ lora_scale (`float`, *optional*):
394
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
395
+ """
396
+ device = device or self._execution_device
397
+
398
+ # set lora scale so that monkey patched LoRA
399
+ # function of text encoder can correctly access it
400
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
401
+ self._lora_scale = lora_scale
402
+
403
+ # dynamically adjust the LoRA scale
404
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
405
+ scale_lora_layers(self.text_encoder, lora_scale)
406
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
407
+ scale_lora_layers(self.text_encoder_2, lora_scale)
408
+
409
+ prompt = [prompt] if isinstance(prompt, str) else prompt
410
+
411
+ if prompt_embeds is None:
412
+ prompt_2 = prompt_2 or prompt
413
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
414
+
415
+ # We only use the pooled prompt output from the CLIPTextModel
416
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
417
+ prompt=prompt,
418
+ device=device,
419
+ num_images_per_prompt=num_images_per_prompt,
420
+ )
421
+ prompt_embeds = self._get_t5_prompt_embeds(
422
+ prompt=prompt_2,
423
+ num_images_per_prompt=num_images_per_prompt,
424
+ max_sequence_length=max_sequence_length,
425
+ device=device,
426
+ )
427
+
428
+ if self.text_encoder is not None:
429
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
430
+ # Retrieve the original scale by scaling back the LoRA layers
431
+ unscale_lora_layers(self.text_encoder, lora_scale)
432
+
433
+ if self.text_encoder_2 is not None:
434
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
435
+ # Retrieve the original scale by scaling back the LoRA layers
436
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
437
+
438
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
439
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
440
+
441
+ return prompt_embeds, pooled_prompt_embeds, text_ids
442
+
443
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
444
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
445
+ if isinstance(generator, list):
446
+ image_latents = [
447
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
448
+ for i in range(image.shape[0])
449
+ ]
450
+ image_latents = torch.cat(image_latents, dim=0)
451
+ else:
452
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
453
+
454
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
455
+
456
+ return image_latents
457
+
458
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
459
+ def get_timesteps(self, num_inference_steps, strength, device):
460
+ # get the original timestep using init_timestep
461
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
462
+
463
+ t_start = int(max(num_inference_steps - init_timestep, 0))
464
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
465
+ if hasattr(self.scheduler, "set_begin_index"):
466
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
467
+
468
+ return timesteps, num_inference_steps - t_start
469
+
470
+ # Copied from diffusers.pipelines.flux.pipeline_flux_img2img.FluxImg2ImgPipeline.check_inputs
471
+ def check_inputs(
472
+ self,
473
+ prompt,
474
+ prompt_2,
475
+ strength,
476
+ height,
477
+ width,
478
+ prompt_embeds=None,
479
+ pooled_prompt_embeds=None,
480
+ callback_on_step_end_tensor_inputs=None,
481
+ max_sequence_length=None,
482
+ ):
483
+ if strength < 0 or strength > 1:
484
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
485
+
486
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
487
+ logger.warning(
488
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
489
+ )
490
+
491
+ if callback_on_step_end_tensor_inputs is not None and not all(
492
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
493
+ ):
494
+ raise ValueError(
495
+ 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]}"
496
+ )
497
+
498
+ if prompt is not None and prompt_embeds is not None:
499
+ raise ValueError(
500
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
501
+ " only forward one of the two."
502
+ )
503
+ elif prompt_2 is not None and prompt_embeds is not None:
504
+ raise ValueError(
505
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
506
+ " only forward one of the two."
507
+ )
508
+ elif prompt is None and prompt_embeds is None:
509
+ raise ValueError(
510
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
511
+ )
512
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
513
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
514
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
515
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
516
+
517
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
518
+ raise ValueError(
519
+ "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`."
520
+ )
521
+
522
+ if max_sequence_length is not None and max_sequence_length > 512:
523
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
524
+
525
+ @staticmethod
526
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
527
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
528
+ latent_image_ids = torch.zeros(height, width, 3)
529
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
530
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
531
+
532
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
533
+
534
+ latent_image_ids = latent_image_ids.reshape(
535
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
536
+ )
537
+
538
+ return latent_image_ids.to(device=device, dtype=dtype)
539
+
540
+ @staticmethod
541
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
542
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
543
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
544
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
545
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
546
+
547
+ return latents
548
+
549
+ @staticmethod
550
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
551
+ def _unpack_latents(latents, height, width, vae_scale_factor):
552
+ batch_size, num_patches, channels = latents.shape
553
+
554
+ # VAE applies 8x compression on images but we must also account for packing which requires
555
+ # latent height and width to be divisible by 2.
556
+ height = 2 * (int(height) // (vae_scale_factor * 2))
557
+ width = 2 * (int(width) // (vae_scale_factor * 2))
558
+
559
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
560
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
561
+
562
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
563
+
564
+ return latents
565
+
566
+ # Copied from diffusers.pipelines.flux.pipeline_flux_img2img.FluxImg2ImgPipeline.prepare_latents
567
+ def prepare_latents(
568
+ self,
569
+ image,
570
+ timestep,
571
+ batch_size,
572
+ num_channels_latents,
573
+ height,
574
+ width,
575
+ dtype,
576
+ device,
577
+ generator,
578
+ latents=None,
579
+ ):
580
+ if isinstance(generator, list) and len(generator) != batch_size:
581
+ raise ValueError(
582
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
583
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
584
+ )
585
+
586
+ # VAE applies 8x compression on images but we must also account for packing which requires
587
+ # latent height and width to be divisible by 2.
588
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
589
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
590
+ shape = (batch_size, num_channels_latents, height, width)
591
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
592
+
593
+ if latents is not None:
594
+ return latents.to(device=device, dtype=dtype), latent_image_ids
595
+
596
+ image = image.to(device=device, dtype=dtype)
597
+ image_latents = self._encode_vae_image(image=image, generator=generator)
598
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
599
+ # expand init_latents for batch_size
600
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
601
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
602
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
603
+ raise ValueError(
604
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
605
+ )
606
+ else:
607
+ image_latents = torch.cat([image_latents], dim=0)
608
+
609
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
610
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
611
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
612
+ return latents, noise, image_latents, latent_image_ids
613
+
614
+ # Copied from diffusers.pipelines.controlnet_sd3.pipeline_stable_diffusion_3_controlnet.StableDiffusion3ControlNetPipeline.prepare_image
615
+ def prepare_image(
616
+ self,
617
+ image,
618
+ width,
619
+ height,
620
+ batch_size,
621
+ num_images_per_prompt,
622
+ device,
623
+ dtype,
624
+ do_classifier_free_guidance=False,
625
+ guess_mode=False,
626
+ ):
627
+ if isinstance(image, torch.Tensor):
628
+ pass
629
+ else:
630
+ image = self.image_processor.preprocess(image, height=height, width=width)
631
+
632
+ image_batch_size = image.shape[0]
633
+
634
+ if image_batch_size == 1:
635
+ repeat_by = batch_size
636
+ else:
637
+ # image batch size is the same as prompt batch size
638
+ repeat_by = num_images_per_prompt
639
+
640
+ image = image.repeat_interleave(repeat_by, dim=0)
641
+
642
+ image = image.to(device=device, dtype=dtype)
643
+
644
+ if do_classifier_free_guidance and not guess_mode:
645
+ image = torch.cat([image] * 2)
646
+
647
+ return image
648
+
649
+
650
+ def prepare_mask_latents(
651
+ self,
652
+ mask,
653
+ masked_image,
654
+ batch_size,
655
+ num_channels_latents,
656
+ num_images_per_prompt,
657
+ height,
658
+ width,
659
+ dtype,
660
+ device,
661
+ generator,
662
+ ):
663
+ # VAE applies 8x compression on images but we must also account for packing which requires
664
+ # latent height and width to be divisible by 2.
665
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
666
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
667
+ # resize the mask to latents shape as we concatenate the mask to the latents
668
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
669
+ # and half precision
670
+ mask = torch.nn.functional.interpolate(mask, size=(height, width))
671
+ mask = mask.to(device=device, dtype=dtype)
672
+
673
+ batch_size = batch_size * num_images_per_prompt
674
+
675
+ masked_image = masked_image.to(device=device, dtype=dtype)
676
+
677
+ if masked_image.shape[1] == 16:
678
+ masked_image_latents = masked_image
679
+ else:
680
+ masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
681
+
682
+ masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
683
+
684
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
685
+ if mask.shape[0] < batch_size:
686
+ if not batch_size % mask.shape[0] == 0:
687
+ raise ValueError(
688
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
689
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
690
+ " of masks that you pass is divisible by the total requested batch size."
691
+ )
692
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
693
+ if masked_image_latents.shape[0] < batch_size:
694
+ if not batch_size % masked_image_latents.shape[0] == 0:
695
+ raise ValueError(
696
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
697
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
698
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
699
+ )
700
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
701
+
702
+ # aligning device to prevent device errors when concating it with the latent model input
703
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
704
+ masked_image_latents = self._pack_latents(
705
+ masked_image_latents,
706
+ batch_size,
707
+ num_channels_latents,
708
+ height,
709
+ width,
710
+ )
711
+ mask = self._pack_latents(
712
+ mask.repeat(1, num_channels_latents, 1, 1),
713
+ batch_size,
714
+ num_channels_latents,
715
+ height,
716
+ width,
717
+ )
718
+
719
+ return mask, masked_image_latents
720
+
721
+ @property
722
+ def guidance_scale(self):
723
+ return self._guidance_scale
724
+
725
+ @property
726
+ def joint_attention_kwargs(self):
727
+ return self._joint_attention_kwargs
728
+
729
+ @property
730
+ def num_timesteps(self):
731
+ return self._num_timesteps
732
+
733
+ @property
734
+ def interrupt(self):
735
+ return self._interrupt
736
+
737
+ @torch.no_grad()
738
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
739
+ def __call__(
740
+ self,
741
+ prompt: Union[str, List[str]] = None,
742
+ prompt_2: Optional[Union[str, List[str]]] = None,
743
+ image: PipelineImageInput = None,
744
+ control_image: PipelineImageInput = None,
745
+ mask_image: PipelineImageInput = None,
746
+ masked_image_latents: PipelineImageInput = None,
747
+ height: Optional[int] = None,
748
+ width: Optional[int] = None,
749
+ strength: float = 0.6,
750
+ num_inference_steps: int = 28,
751
+ timesteps: List[int] = None,
752
+ guidance_scale: float = 7.0,
753
+ num_images_per_prompt: Optional[int] = 1,
754
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
755
+ latents: Optional[torch.FloatTensor] = None,
756
+ prompt_embeds: Optional[torch.FloatTensor] = None,
757
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
758
+ output_type: Optional[str] = "pil",
759
+ return_dict: bool = True,
760
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
761
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
762
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
763
+ max_sequence_length: int = 512,
764
+ ):
765
+ r"""
766
+ Function invoked when calling the pipeline for generation.
767
+
768
+ Args:
769
+ prompt (`str` or `List[str]`, *optional*):
770
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
771
+ instead.
772
+ prompt_2 (`str` or `List[str]`, *optional*):
773
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
774
+ will be used instead
775
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
776
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
777
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
778
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
779
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
780
+ latents as `image`, but if passing latents directly it is not encoded again.
781
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
782
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
783
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
784
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
785
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
786
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
787
+ images must be passed as a list such that each element of the list can be correctly batched for input
788
+ to a single ControlNet.
789
+ mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
790
+ `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
791
+ are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
792
+ single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
793
+ color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
794
+ H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
795
+ 1)`, or `(H, W)`.
796
+ mask_image_latent (`torch.Tensor`, `List[torch.Tensor]`):
797
+ `Tensor` representing an image batch to mask `image` generated by VAE. If not provided, the mask
798
+ latents tensor will ge generated by `mask_image`.
799
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
800
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
801
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
802
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
803
+ strength (`float`, *optional*, defaults to 1.0):
804
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
805
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
806
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
807
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
808
+ essentially ignores `image`.
809
+ num_inference_steps (`int`, *optional*, defaults to 50):
810
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
811
+ expense of slower inference.
812
+ timesteps (`List[int]`, *optional*):
813
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
814
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
815
+ passed will be used. Must be in descending order.
816
+ guidance_scale (`float`, *optional*, defaults to 7.0):
817
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
818
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
819
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
820
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
821
+ usually at the expense of lower image quality.
822
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
823
+ The number of images to generate per prompt.
824
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
825
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
826
+ to make generation deterministic.
827
+ latents (`torch.FloatTensor`, *optional*):
828
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
829
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
830
+ tensor will ge generated by sampling using the supplied random `generator`.
831
+ prompt_embeds (`torch.FloatTensor`, *optional*):
832
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
833
+ provided, text embeddings will be generated from `prompt` input argument.
834
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
835
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
836
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
837
+ output_type (`str`, *optional*, defaults to `"pil"`):
838
+ The output format of the generate image. Choose between
839
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
840
+ return_dict (`bool`, *optional*, defaults to `True`):
841
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
842
+ joint_attention_kwargs (`dict`, *optional*):
843
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
844
+ `self.processor` in
845
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
846
+ callback_on_step_end (`Callable`, *optional*):
847
+ A function that calls at the end of each denoising steps during the inference. The function is called
848
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
849
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
850
+ `callback_on_step_end_tensor_inputs`.
851
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
852
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
853
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
854
+ `._callback_tensor_inputs` attribute of your pipeline class.
855
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
856
+
857
+ Examples:
858
+
859
+ Returns:
860
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
861
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
862
+ images.
863
+ """
864
+
865
+ height = height or self.default_sample_size * self.vae_scale_factor
866
+ width = width or self.default_sample_size * self.vae_scale_factor
867
+
868
+ # 1. Check inputs. Raise error if not correct
869
+ self.check_inputs(
870
+ prompt,
871
+ prompt_2,
872
+ strength,
873
+ height,
874
+ width,
875
+ prompt_embeds=prompt_embeds,
876
+ pooled_prompt_embeds=pooled_prompt_embeds,
877
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
878
+ max_sequence_length=max_sequence_length,
879
+ )
880
+
881
+ self._guidance_scale = guidance_scale
882
+ self._joint_attention_kwargs = joint_attention_kwargs
883
+ self._interrupt = False
884
+ device = self._execution_device
885
+
886
+ # 3. Define call parameters
887
+ if prompt is not None and isinstance(prompt, str):
888
+ batch_size = 1
889
+ elif prompt is not None and isinstance(prompt, list):
890
+ batch_size = len(prompt)
891
+ else:
892
+ batch_size = prompt_embeds.shape[0]
893
+
894
+ device = self._execution_device
895
+
896
+ # 3. Prepare text embeddings
897
+ lora_scale = (
898
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
899
+ )
900
+ (
901
+ prompt_embeds,
902
+ pooled_prompt_embeds,
903
+ text_ids,
904
+ ) = self.encode_prompt(
905
+ prompt=prompt,
906
+ prompt_2=prompt_2,
907
+ prompt_embeds=prompt_embeds,
908
+ pooled_prompt_embeds=pooled_prompt_embeds,
909
+ device=device,
910
+ num_images_per_prompt=num_images_per_prompt,
911
+ max_sequence_length=max_sequence_length,
912
+ lora_scale=lora_scale,
913
+ )
914
+
915
+
916
+ # 3. Preprocess mask and image
917
+ num_channels_latents = self.vae.config.latent_channels
918
+ if masked_image_latents is not None:
919
+ masked_image_latents = masked_image_latents.to(latents.device)
920
+ else:
921
+ image = self.image_processor.preprocess(image, height=height, width=width)
922
+ mask_image = self.mask_processor.preprocess(mask_image, height=height, width=width)
923
+
924
+ masked_image = image * (1 - mask_image)
925
+ masked_image = masked_image.to(device=device, dtype=prompt_embeds.dtype)
926
+
927
+ height, width = image.shape[-2:]
928
+ mask, masked_image_latents = self.prepare_mask_latents(
929
+ mask_image,
930
+ masked_image,
931
+ batch_size,
932
+ num_channels_latents,
933
+ num_images_per_prompt,
934
+ height,
935
+ width,
936
+ prompt_embeds.dtype,
937
+ device,
938
+ generator,
939
+ )
940
+ masked_image_latents = torch.cat((masked_image_latents, mask), dim=-1)
941
+
942
+ init_image = self.image_processor.preprocess(image, height=height, width=width)
943
+ init_image = init_image.to(dtype=torch.float32)
944
+
945
+ # 4.Prepare timesteps
946
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
947
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
948
+ mu = calculate_shift(
949
+ image_seq_len,
950
+ self.scheduler.config.base_image_seq_len,
951
+ self.scheduler.config.max_image_seq_len,
952
+ self.scheduler.config.base_shift,
953
+ self.scheduler.config.max_shift,
954
+ )
955
+ timesteps, num_inference_steps = retrieve_timesteps(
956
+ self.scheduler,
957
+ num_inference_steps,
958
+ device,
959
+ timesteps,
960
+ sigmas,
961
+ mu=mu,
962
+ )
963
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
964
+
965
+ if num_inference_steps < 1:
966
+ raise ValueError(
967
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
968
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
969
+ )
970
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
971
+
972
+ # 5. Prepare latent variables
973
+ num_channels_latents = self.transformer.config.in_channels // 8
974
+
975
+ control_image = self.prepare_image(
976
+ image=control_image,
977
+ width=width,
978
+ height=height,
979
+ batch_size=batch_size * num_images_per_prompt,
980
+ num_images_per_prompt=num_images_per_prompt,
981
+ device=device,
982
+ dtype=self.vae.dtype,
983
+ )
984
+
985
+ if control_image.ndim == 4:
986
+ control_image = self.vae.encode(control_image).latent_dist.sample(generator=generator)
987
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
988
+
989
+ height_control_image, width_control_image = control_image.shape[2:]
990
+ control_image = self._pack_latents(
991
+ control_image,
992
+ batch_size * num_images_per_prompt,
993
+ num_channels_latents,
994
+ height_control_image,
995
+ width_control_image,
996
+ )
997
+
998
+ latents, noise, image_latents, latent_image_ids = self.prepare_latents(
999
+ init_image,
1000
+ latent_timestep,
1001
+ batch_size * num_images_per_prompt,
1002
+ num_channels_latents,
1003
+ height,
1004
+ width,
1005
+ prompt_embeds.dtype,
1006
+ device,
1007
+ generator,
1008
+ latents,
1009
+ )
1010
+
1011
+ # VAE applies 8x compression on images but we must also account for packing which requires
1012
+ # latent height and width to be divisible by 2.
1013
+ height_8 = 2 * (int(height) // (self.vae_scale_factor * 2))
1014
+ width_8 = 2 * (int(width) // (self.vae_scale_factor * 2))
1015
+
1016
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1017
+ self._num_timesteps = len(timesteps)
1018
+
1019
+ # handle guidance
1020
+ if self.transformer.config.guidance_embeds:
1021
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
1022
+ guidance = guidance.expand(latents.shape[0])
1023
+ else:
1024
+ guidance = None
1025
+
1026
+ # 6. Denoising loop
1027
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1028
+ for i, t in enumerate(timesteps):
1029
+ if self.interrupt:
1030
+ continue
1031
+
1032
+ latent_model_input = torch.cat([latents, control_image], dim=2)
1033
+
1034
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1035
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
1036
+
1037
+ noise_pred = self.transformer(
1038
+ hidden_states=latent_model_input,
1039
+ timestep=timestep / 1000,
1040
+ guidance=guidance,
1041
+ pooled_projections=pooled_prompt_embeds,
1042
+ encoder_hidden_states=prompt_embeds,
1043
+ txt_ids=text_ids,
1044
+ img_ids=latent_image_ids,
1045
+ joint_attention_kwargs=self.joint_attention_kwargs,
1046
+ return_dict=False,
1047
+ )[0]
1048
+
1049
+ # compute the previous noisy sample x_t -> x_t-1
1050
+ latents_dtype = latents.dtype
1051
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1052
+
1053
+ # for 64 channel transformer only.
1054
+ init_latents_proper = image_latents
1055
+ init_mask = mask
1056
+ if i < len(timesteps) - 1:
1057
+ noise_timestep = timesteps[i + 1]
1058
+ init_latents_proper = self.scheduler.scale_noise(init_latents_proper, torch.tensor([noise_timestep]), noise)
1059
+ init_latents_proper = self._pack_latents(init_latents_proper, batch_size, num_channels_latents, height_8, width_8)
1060
+
1061
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1062
+
1063
+ if latents.dtype != latents_dtype:
1064
+ if torch.backends.mps.is_available():
1065
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1066
+ latents = latents.to(latents_dtype)
1067
+
1068
+ if callback_on_step_end is not None:
1069
+ callback_kwargs = {}
1070
+ for k in callback_on_step_end_tensor_inputs:
1071
+ callback_kwargs[k] = locals()[k]
1072
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1073
+
1074
+ latents = callback_outputs.pop("latents", latents)
1075
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1076
+
1077
+ # call the callback, if provided
1078
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1079
+ progress_bar.update()
1080
+
1081
+ if XLA_AVAILABLE:
1082
+ xm.mark_step()
1083
+
1084
+ if output_type == "latent":
1085
+ image = latents
1086
+
1087
+ else:
1088
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
1089
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1090
+ image = self.vae.decode(latents, return_dict=False)[0]
1091
+ image = self.image_processor.postprocess(image, output_type=output_type)
1092
+
1093
+ # Offload all models
1094
+ self.maybe_free_model_hooks()
1095
+
1096
+ if not return_dict:
1097
+ return (image,)
1098
+
1099
+ return FluxPipelineOutput(images=image)