multimodalart HF Staff commited on
Commit
4f163f1
·
verified ·
1 Parent(s): 5b8270b

Upload kontext_pipeline.py

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