linoyts HF Staff commited on
Commit
c7feeb2
·
verified ·
1 Parent(s): da7c005

Upload pipeline_flux_kontext.py

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