Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
e171bbe
·
verified ·
1 Parent(s): e9d361a

Upload folder using huggingface_hub

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