Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
94aa7fa
·
verified ·
1 Parent(s): f89c69f

Upload folder using huggingface_hub

Browse files
main/README.md CHANGED
@@ -88,7 +88,7 @@ PIXART-α Controlnet pipeline | Implementation of the controlnet model for pixar
88
  | FaithDiff Stable Diffusion XL Pipeline | Implementation of [(CVPR 2025) FaithDiff: Unleashing Diffusion Priors for Faithful Image Super-resolutionUnleashing Diffusion Priors for Faithful Image Super-resolution](https://huggingface.co/papers/2411.18824) - FaithDiff is a faithful image super-resolution method that leverages latent diffusion models by actively adapting the diffusion prior and jointly fine-tuning its components (encoder and diffusion model) with an alignment module to ensure high fidelity and structural consistency. | [FaithDiff Stable Diffusion XL Pipeline](#faithdiff-stable-diffusion-xl-pipeline) | [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/jychen9811/FaithDiff) | [Junyang Chen, Jinshan Pan, Jiangxin Dong, IMAG Lab, (Adapted by Eliseu Silva)](https://github.com/JyChen9811/FaithDiff) |
89
  | Stable Diffusion 3 InstructPix2Pix Pipeline | Implementation of Stable Diffusion 3 InstructPix2Pix Pipeline | [Stable Diffusion 3 InstructPix2Pix Pipeline](#stable-diffusion-3-instructpix2pix-pipeline) | [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/BleachNick/SD3_UltraEdit_freeform) [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/CaptainZZZ/sd3-instructpix2pix) | [Jiayu Zhang](https://github.com/xduzhangjiayu) and [Haozhe Zhao](https://github.com/HaozheZhao)|
90
  | Flux Kontext multiple images | A modified version of the `FluxKontextPipeline` that supports calling Flux Kontext with multiple reference images.| [Flux Kontext multiple input Pipeline](#flux-kontext-multiple-images) | - | [Net-Mist](https://github.com/Net-Mist) |
91
-
92
 
93
  To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly.
94
 
@@ -5527,3 +5527,106 @@ images = pipe(
5527
  ).images
5528
  images[0].save("pizzeria.png")
5529
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  | FaithDiff Stable Diffusion XL Pipeline | Implementation of [(CVPR 2025) FaithDiff: Unleashing Diffusion Priors for Faithful Image Super-resolutionUnleashing Diffusion Priors for Faithful Image Super-resolution](https://huggingface.co/papers/2411.18824) - FaithDiff is a faithful image super-resolution method that leverages latent diffusion models by actively adapting the diffusion prior and jointly fine-tuning its components (encoder and diffusion model) with an alignment module to ensure high fidelity and structural consistency. | [FaithDiff Stable Diffusion XL Pipeline](#faithdiff-stable-diffusion-xl-pipeline) | [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/jychen9811/FaithDiff) | [Junyang Chen, Jinshan Pan, Jiangxin Dong, IMAG Lab, (Adapted by Eliseu Silva)](https://github.com/JyChen9811/FaithDiff) |
89
  | Stable Diffusion 3 InstructPix2Pix Pipeline | Implementation of Stable Diffusion 3 InstructPix2Pix Pipeline | [Stable Diffusion 3 InstructPix2Pix Pipeline](#stable-diffusion-3-instructpix2pix-pipeline) | [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/BleachNick/SD3_UltraEdit_freeform) [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/CaptainZZZ/sd3-instructpix2pix) | [Jiayu Zhang](https://github.com/xduzhangjiayu) and [Haozhe Zhao](https://github.com/HaozheZhao)|
90
  | Flux Kontext multiple images | A modified version of the `FluxKontextPipeline` that supports calling Flux Kontext with multiple reference images.| [Flux Kontext multiple input Pipeline](#flux-kontext-multiple-images) | - | [Net-Mist](https://github.com/Net-Mist) |
91
+ | Flux Fill ControlNet Pipeline | A modified version of the `FluxFillPipeline` and `FluxControlNetInpaintPipeline` that supports Controlnet with Flux Fill model.| [Flux Fill ControlNet Pipeline](#Flux-Fill-ControlNet-Pipeline) | - | [pratim4dasude](https://github.com/pratim4dasude) |
92
 
93
  To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly.
94
 
 
5527
  ).images
5528
  images[0].save("pizzeria.png")
5529
  ```
5530
+
5531
+ # Flux Fill ControlNet Pipeline
5532
+
5533
+ This implementation of Flux Fill + ControlNet Inpaint combines the fill-style masked editing of FLUX.1-Fill-dev with full ControlNet conditioning. The base image is processed through the Fill model while the ControlNet receives the corresponding conditioning input (depth, canny, pose, etc.), and both outputs are fused during denoising to guide structure and composition.
5534
+
5535
+ While FLUX.1-Fill-dev is designed for mask-based edits, it was not originally trained to operate jointly with ControlNet. In practice, this combined setup works well for structured inpainting tasks, though results may vary depending on the conditioning strength and the alignment between the mask and the control input.
5536
+
5537
+ ## Example Usage
5538
+
5539
+
5540
+ ```python
5541
+ import torch
5542
+ from diffusers import (
5543
+ FluxControlNetModel,
5544
+ FluxPriorReduxPipeline,
5545
+ )
5546
+ from diffusers.utils import load_image
5547
+
5548
+ # NEW PIPELINE (updated name)
5549
+ from pipline_flux_fill_controlnet_Inpaint import FluxControlNetFillInpaintPipeline
5550
+
5551
+ device = "cuda" if torch.cuda.is_available() else "cpu"
5552
+ dtype = torch.bfloat16
5553
+
5554
+ # Models
5555
+ base_model = "black-forest-labs/FLUX.1-Fill-dev"
5556
+ controlnet_model = "Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro-2.0"
5557
+ prior_model = "black-forest-labs/FLUX.1-Redux-dev"
5558
+
5559
+ # Load ControlNet
5560
+ controlnet = FluxControlNetModel.from_pretrained(
5561
+ controlnet_model,
5562
+ torch_dtype=dtype,
5563
+ )
5564
+
5565
+ # Load Fill + ControlNet Pipeline
5566
+ fill_pipe = FluxControlNetFillInpaintPipeline.from_pretrained(
5567
+ base_model,
5568
+ controlnet=controlnet,
5569
+ torch_dtype=dtype,
5570
+ ).to(device)
5571
+
5572
+ # OPTIONAL FP8
5573
+ # fill_pipe.transformer.enable_layerwise_casting(
5574
+ # storage_dtype=torch.float8_e4m3fn,
5575
+ # compute_dtype=torch.bfloat16
5576
+ # )
5577
+
5578
+ # OPTIONAL Prior Redux
5579
+ #pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(
5580
+ # prior_model,
5581
+ # torch_dtype=dtype,
5582
+ #).to(device)
5583
+
5584
+ # Inputs
5585
+
5586
+ # combined_image = load_image("person_input.png")
5587
+
5588
+
5589
+ # 1. Prior conditioning
5590
+ #prior_out = pipe_prior_redux(
5591
+ # image=cloth_image,
5592
+ # prompt=cloth_prompt,
5593
+ #)
5594
+
5595
+ # 2. Fill Inpaint with ControlNet
5596
+
5597
+ # canny (0), tile (1), depth (2), blur (3), pose (4), gray (5), low quality (6).
5598
+
5599
+ img = load_image(r"imgs/background.jpg")
5600
+ mask = load_image(r"imgs/mask.png")
5601
+
5602
+ control_image_depth = load_image(r"imgs/dog_depth _2.png")
5603
+
5604
+ result = fill_pipe(
5605
+ prompt="a dog on a bench",
5606
+ image=img,
5607
+ mask_image=mask,
5608
+
5609
+ control_image=control_image_depth,
5610
+ control_mode=[2], # union mode
5611
+ control_guidance_start=0.0,
5612
+ control_guidance_end=0.8,
5613
+ controlnet_conditioning_scale=0.9,
5614
+
5615
+ height=1024,
5616
+ width=1024,
5617
+
5618
+ strength=1.0,
5619
+ guidance_scale=50.0,
5620
+ num_inference_steps=60,
5621
+ max_sequence_length=512,
5622
+
5623
+ # **prior_out,
5624
+ )
5625
+
5626
+ # result.images[0].save("flux_fill_controlnet_inpaint.png")
5627
+
5628
+ from datetime import datetime
5629
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
5630
+ result.images[0].save(f"flux_fill_controlnet_inpaint_depth{timestamp}.jpg")
5631
+ ```
5632
+
main/pipline_flux_fill_controlnet_Inpaint.py ADDED
@@ -0,0 +1,1319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import PIL
6
+ import torch
7
+ from transformers import (
8
+ CLIPTextModel,
9
+ CLIPTokenizer,
10
+ T5EncoderModel,
11
+ T5TokenizerFast,
12
+ )
13
+
14
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
15
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
16
+ from diffusers.models.autoencoders import AutoencoderKL
17
+ from diffusers.models.controlnets.controlnet_flux import FluxControlNetModel, FluxMultiControlNetModel
18
+ from diffusers.models.transformers import FluxTransformer2DModel
19
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
20
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
21
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
22
+ from diffusers.utils import (
23
+ USE_PEFT_BACKEND,
24
+ is_torch_xla_available,
25
+ logging,
26
+ replace_example_docstring,
27
+ scale_lora_layers,
28
+ unscale_lora_layers,
29
+ )
30
+ from diffusers.utils.torch_utils import randn_tensor
31
+
32
+
33
+ if is_torch_xla_available():
34
+ import torch_xla.core.xla_model as xm
35
+
36
+ XLA_AVAILABLE = True
37
+ else:
38
+ XLA_AVAILABLE = False
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ EXAMPLE_DOC_STRING = """
43
+ Examples:
44
+ ```py
45
+ >>> import torch
46
+ >>> from diffusers import FluxControlNetInpaintPipeline
47
+ >>> from diffusers.models import FluxControlNetModel
48
+ >>> from diffusers.utils import load_image
49
+
50
+ >>> controlnet = FluxControlNetModel.from_pretrained(
51
+ ... "InstantX/FLUX.1-dev-controlnet-canny", torch_dtype=torch.float16
52
+ ... )
53
+ >>> pipe = FluxControlNetInpaintPipeline.from_pretrained(
54
+ ... "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
55
+ ... )
56
+ >>> pipe.to("cuda")
57
+
58
+ >>> control_image = load_image(
59
+ ... "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
60
+ ... )
61
+ >>> init_image = load_image(
62
+ ... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
63
+ ... )
64
+ >>> mask_image = load_image(
65
+ ... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
66
+ ... )
67
+
68
+ >>> prompt = "A girl holding a sign that says InstantX"
69
+ >>> image = pipe(
70
+ ... prompt,
71
+ ... image=init_image,
72
+ ... mask_image=mask_image,
73
+ ... control_image=control_image,
74
+ ... control_guidance_start=0.2,
75
+ ... control_guidance_end=0.8,
76
+ ... controlnet_conditioning_scale=0.7,
77
+ ... strength=0.7,
78
+ ... num_inference_steps=28,
79
+ ... guidance_scale=3.5,
80
+ ... ).images[0]
81
+ >>> image.save("flux_controlnet_inpaint.png")
82
+ ```
83
+ """
84
+
85
+
86
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
87
+ def calculate_shift(
88
+ image_seq_len,
89
+ base_seq_len: int = 256,
90
+ max_seq_len: int = 4096,
91
+ base_shift: float = 0.5,
92
+ max_shift: float = 1.15,
93
+ ):
94
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
95
+ b = base_shift - m * base_seq_len
96
+ mu = image_seq_len * m + b
97
+ return mu
98
+
99
+
100
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
101
+ def retrieve_latents(
102
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
103
+ ):
104
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
105
+ return encoder_output.latent_dist.sample(generator)
106
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
107
+ return encoder_output.latent_dist.mode()
108
+ elif hasattr(encoder_output, "latents"):
109
+ return encoder_output.latents
110
+ else:
111
+ raise AttributeError("Could not access latents of provided encoder_output")
112
+
113
+
114
+ def retrieve_latents_fill(
115
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
116
+ ):
117
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
118
+ return encoder_output.latent_dist.sample(generator)
119
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
120
+ return encoder_output.latent_dist.mode()
121
+ elif hasattr(encoder_output, "latents"):
122
+ return encoder_output.latents
123
+ else:
124
+ raise AttributeError("Could not access latents of provided encoder_output")
125
+
126
+
127
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
128
+ def retrieve_timesteps(
129
+ scheduler,
130
+ num_inference_steps: Optional[int] = None,
131
+ device: Optional[Union[str, torch.device]] = None,
132
+ timesteps: Optional[List[int]] = None,
133
+ sigmas: Optional[List[float]] = None,
134
+ **kwargs,
135
+ ):
136
+ r"""
137
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
138
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
139
+
140
+ Args:
141
+ scheduler (`SchedulerMixin`):
142
+ The scheduler to get timesteps from.
143
+ num_inference_steps (`int`):
144
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
145
+ must be `None`.
146
+ device (`str` or `torch.device`, *optional*):
147
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
148
+ timesteps (`List[int]`, *optional*):
149
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
150
+ `num_inference_steps` and `sigmas` must be `None`.
151
+ sigmas (`List[float]`, *optional*):
152
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
153
+ `num_inference_steps` and `timesteps` must be `None`.
154
+
155
+ Returns:
156
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
157
+ second element is the number of inference steps.
158
+ """
159
+ if timesteps is not None and sigmas is not None:
160
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
161
+ if timesteps is not None:
162
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
163
+ if not accepts_timesteps:
164
+ raise ValueError(
165
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
166
+ f" timestep schedules. Please check whether you are using the correct scheduler."
167
+ )
168
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
169
+ timesteps = scheduler.timesteps
170
+ num_inference_steps = len(timesteps)
171
+ elif sigmas is not None:
172
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
173
+ if not accept_sigmas:
174
+ raise ValueError(
175
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
176
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
177
+ )
178
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
179
+ timesteps = scheduler.timesteps
180
+ num_inference_steps = len(timesteps)
181
+ else:
182
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
183
+ timesteps = scheduler.timesteps
184
+ return timesteps, num_inference_steps
185
+
186
+
187
+ class FluxControlNetFillInpaintPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
188
+ r"""
189
+ The Flux controlnet pipeline for inpainting.
190
+
191
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
192
+
193
+ Args:
194
+ transformer ([`FluxTransformer2DModel`]):
195
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
196
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
197
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
198
+ vae ([`AutoencoderKL`]):
199
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
200
+ text_encoder ([`CLIPTextModel`]):
201
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
202
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
203
+ text_encoder_2 ([`T5EncoderModel`]):
204
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
205
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
206
+ tokenizer (`CLIPTokenizer`):
207
+ Tokenizer of class
208
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
209
+ tokenizer_2 (`T5TokenizerFast`):
210
+ Second Tokenizer of class
211
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
212
+ """
213
+
214
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
215
+ _optional_components = []
216
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "control_image", "mask", "masked_image_latents"]
217
+
218
+ def __init__(
219
+ self,
220
+ scheduler: FlowMatchEulerDiscreteScheduler,
221
+ vae: AutoencoderKL,
222
+ text_encoder: CLIPTextModel,
223
+ tokenizer: CLIPTokenizer,
224
+ text_encoder_2: T5EncoderModel,
225
+ tokenizer_2: T5TokenizerFast,
226
+ transformer: FluxTransformer2DModel,
227
+ controlnet: Union[
228
+ FluxControlNetModel, List[FluxControlNetModel], Tuple[FluxControlNetModel], FluxMultiControlNetModel
229
+ ],
230
+ ):
231
+ super().__init__()
232
+ if isinstance(controlnet, (list, tuple)):
233
+ controlnet = FluxMultiControlNetModel(controlnet)
234
+
235
+ self.register_modules(
236
+ scheduler=scheduler,
237
+ vae=vae,
238
+ text_encoder=text_encoder,
239
+ tokenizer=tokenizer,
240
+ text_encoder_2=text_encoder_2,
241
+ tokenizer_2=tokenizer_2,
242
+ transformer=transformer,
243
+ controlnet=controlnet,
244
+ )
245
+
246
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
247
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
248
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
249
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
250
+ latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
251
+ self.mask_processor = VaeImageProcessor(
252
+ vae_scale_factor=self.vae_scale_factor * 2,
253
+ vae_latent_channels=latent_channels,
254
+ do_normalize=False,
255
+ do_binarize=True,
256
+ do_convert_grayscale=True,
257
+ )
258
+ self.tokenizer_max_length = (
259
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
260
+ )
261
+ self.default_sample_size = 128
262
+
263
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
264
+ def _get_t5_prompt_embeds(
265
+ self,
266
+ prompt: Union[str, List[str]] = None,
267
+ num_images_per_prompt: int = 1,
268
+ max_sequence_length: int = 512,
269
+ device: Optional[torch.device] = None,
270
+ dtype: Optional[torch.dtype] = None,
271
+ ):
272
+ device = device or self._execution_device
273
+ dtype = dtype or self.text_encoder.dtype
274
+
275
+ prompt = [prompt] if isinstance(prompt, str) else prompt
276
+ batch_size = len(prompt)
277
+
278
+ if isinstance(self, TextualInversionLoaderMixin):
279
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
280
+
281
+ text_inputs = self.tokenizer_2(
282
+ prompt,
283
+ padding="max_length",
284
+ max_length=max_sequence_length,
285
+ truncation=True,
286
+ return_length=False,
287
+ return_overflowing_tokens=False,
288
+ return_tensors="pt",
289
+ )
290
+ text_input_ids = text_inputs.input_ids
291
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
292
+
293
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
294
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
295
+ logger.warning(
296
+ "The following part of your input was truncated because `max_sequence_length` is set to "
297
+ f" {max_sequence_length} tokens: {removed_text}"
298
+ )
299
+
300
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
301
+
302
+ dtype = self.text_encoder_2.dtype
303
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
304
+
305
+ _, seq_len, _ = prompt_embeds.shape
306
+
307
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
308
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
309
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
310
+
311
+ return prompt_embeds
312
+
313
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
314
+ def _get_clip_prompt_embeds(
315
+ self,
316
+ prompt: Union[str, List[str]],
317
+ num_images_per_prompt: int = 1,
318
+ device: Optional[torch.device] = None,
319
+ ):
320
+ device = device or self._execution_device
321
+
322
+ prompt = [prompt] if isinstance(prompt, str) else prompt
323
+ batch_size = len(prompt)
324
+
325
+ if isinstance(self, TextualInversionLoaderMixin):
326
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
327
+
328
+ text_inputs = self.tokenizer(
329
+ prompt,
330
+ padding="max_length",
331
+ max_length=self.tokenizer_max_length,
332
+ truncation=True,
333
+ return_overflowing_tokens=False,
334
+ return_length=False,
335
+ return_tensors="pt",
336
+ )
337
+
338
+ text_input_ids = text_inputs.input_ids
339
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
340
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
341
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
342
+ logger.warning(
343
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
344
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
345
+ )
346
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
347
+
348
+ # Use pooled output of CLIPTextModel
349
+ prompt_embeds = prompt_embeds.pooler_output
350
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
351
+
352
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
353
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
354
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
355
+
356
+ return prompt_embeds
357
+
358
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
359
+ def encode_prompt(
360
+ self,
361
+ prompt: Union[str, List[str]],
362
+ prompt_2: Union[str, List[str]],
363
+ device: Optional[torch.device] = None,
364
+ num_images_per_prompt: int = 1,
365
+ prompt_embeds: Optional[torch.FloatTensor] = None,
366
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
367
+ max_sequence_length: int = 512,
368
+ lora_scale: Optional[float] = None,
369
+ ):
370
+ r"""
371
+
372
+ Args:
373
+ prompt (`str` or `List[str]`, *optional*):
374
+ prompt to be encoded
375
+ prompt_2 (`str` or `List[str]`, *optional*):
376
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
377
+ used in all text-encoders
378
+ device: (`torch.device`):
379
+ torch device
380
+ num_images_per_prompt (`int`):
381
+ number of images that should be generated per prompt
382
+ prompt_embeds (`torch.FloatTensor`, *optional*):
383
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
384
+ provided, text embeddings will be generated from `prompt` input argument.
385
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
386
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
387
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
388
+ lora_scale (`float`, *optional*):
389
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
390
+ """
391
+ device = device or self._execution_device
392
+
393
+ # set lora scale so that monkey patched LoRA
394
+ # function of text encoder can correctly access it
395
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
396
+ self._lora_scale = lora_scale
397
+
398
+ # dynamically adjust the LoRA scale
399
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
400
+ scale_lora_layers(self.text_encoder, lora_scale)
401
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
402
+ scale_lora_layers(self.text_encoder_2, lora_scale)
403
+
404
+ prompt = [prompt] if isinstance(prompt, str) else prompt
405
+
406
+ if prompt_embeds is None:
407
+ prompt_2 = prompt_2 or prompt
408
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
409
+
410
+ # We only use the pooled prompt output from the CLIPTextModel
411
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
412
+ prompt=prompt,
413
+ device=device,
414
+ num_images_per_prompt=num_images_per_prompt,
415
+ )
416
+ prompt_embeds = self._get_t5_prompt_embeds(
417
+ prompt=prompt_2,
418
+ num_images_per_prompt=num_images_per_prompt,
419
+ max_sequence_length=max_sequence_length,
420
+ device=device,
421
+ )
422
+
423
+ if self.text_encoder is not None:
424
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
425
+ # Retrieve the original scale by scaling back the LoRA layers
426
+ unscale_lora_layers(self.text_encoder, lora_scale)
427
+
428
+ if self.text_encoder_2 is not None:
429
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
430
+ # Retrieve the original scale by scaling back the LoRA layers
431
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
432
+
433
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
434
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
435
+
436
+ return prompt_embeds, pooled_prompt_embeds, text_ids
437
+
438
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
439
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
440
+ if isinstance(generator, list):
441
+ image_latents = [
442
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
443
+ for i in range(image.shape[0])
444
+ ]
445
+ image_latents = torch.cat(image_latents, dim=0)
446
+ else:
447
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
448
+
449
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
450
+
451
+ return image_latents
452
+
453
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
454
+ def get_timesteps(self, num_inference_steps, strength, device):
455
+ # get the original timestep using init_timestep
456
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
457
+
458
+ t_start = int(max(num_inference_steps - init_timestep, 0))
459
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
460
+ if hasattr(self.scheduler, "set_begin_index"):
461
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
462
+
463
+ return timesteps, num_inference_steps - t_start
464
+
465
+ def check_inputs(
466
+ self,
467
+ prompt,
468
+ prompt_2,
469
+ image,
470
+ mask_image,
471
+ strength,
472
+ height,
473
+ width,
474
+ output_type,
475
+ prompt_embeds=None,
476
+ pooled_prompt_embeds=None,
477
+ callback_on_step_end_tensor_inputs=None,
478
+ padding_mask_crop=None,
479
+ max_sequence_length=None,
480
+ ):
481
+ if strength < 0 or strength > 1:
482
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
483
+
484
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
485
+ logger.warning(
486
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
487
+ )
488
+
489
+ if callback_on_step_end_tensor_inputs is not None and not all(
490
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
491
+ ):
492
+ raise ValueError(
493
+ 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]}"
494
+ )
495
+
496
+ if prompt is not None and prompt_embeds is not None:
497
+ raise ValueError(
498
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
499
+ " only forward one of the two."
500
+ )
501
+ elif prompt_2 is not None and prompt_embeds is not None:
502
+ raise ValueError(
503
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
504
+ " only forward one of the two."
505
+ )
506
+ elif prompt is None and prompt_embeds is None:
507
+ raise ValueError(
508
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
509
+ )
510
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
511
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
512
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
513
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
514
+
515
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
516
+ raise ValueError(
517
+ "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`."
518
+ )
519
+
520
+ if padding_mask_crop is not None:
521
+ if not isinstance(image, PIL.Image.Image):
522
+ raise ValueError(
523
+ f"The image should be a PIL image when inpainting mask crop, but is of type {type(image)}."
524
+ )
525
+ if not isinstance(mask_image, PIL.Image.Image):
526
+ raise ValueError(
527
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
528
+ f" {type(mask_image)}."
529
+ )
530
+ if output_type != "pil":
531
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is {output_type}.")
532
+
533
+ if max_sequence_length is not None and max_sequence_length > 512:
534
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
535
+
536
+ @staticmethod
537
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
538
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
539
+ latent_image_ids = torch.zeros(height, width, 3)
540
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
541
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
542
+
543
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
544
+
545
+ latent_image_ids = latent_image_ids.reshape(
546
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
547
+ )
548
+
549
+ return latent_image_ids.to(device=device, dtype=dtype)
550
+
551
+ @staticmethod
552
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
553
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
554
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
555
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
556
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
557
+
558
+ return latents
559
+
560
+ @staticmethod
561
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
562
+ def _unpack_latents(latents, height, width, vae_scale_factor):
563
+ batch_size, num_patches, channels = latents.shape
564
+
565
+ # VAE applies 8x compression on images but we must also account for packing which requires
566
+ # latent height and width to be divisible by 2.
567
+ height = 2 * (int(height) // (vae_scale_factor * 2))
568
+ width = 2 * (int(width) // (vae_scale_factor * 2))
569
+
570
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
571
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
572
+
573
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
574
+
575
+ return latents
576
+
577
+ def prepare_latents(
578
+ self,
579
+ image,
580
+ timestep,
581
+ batch_size,
582
+ num_channels_latents,
583
+ height,
584
+ width,
585
+ dtype,
586
+ device,
587
+ generator,
588
+ latents=None,
589
+ ):
590
+ if isinstance(generator, list) and len(generator) != batch_size:
591
+ raise ValueError(
592
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
593
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
594
+ )
595
+
596
+ # VAE applies 8x compression on images but we must also account for packing which requires
597
+ # latent height and width to be divisible by 2.
598
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
599
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
600
+ shape = (batch_size, num_channels_latents, height, width)
601
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
602
+
603
+ image = image.to(device=device, dtype=dtype)
604
+ image_latents = self._encode_vae_image(image=image, generator=generator)
605
+
606
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
607
+ # expand init_latents for batch_size
608
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
609
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
610
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
611
+ raise ValueError(
612
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
613
+ )
614
+ else:
615
+ image_latents = torch.cat([image_latents], dim=0)
616
+
617
+ if latents is None:
618
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
619
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
620
+ else:
621
+ noise = latents.to(device)
622
+ latents = noise
623
+
624
+ noise = self._pack_latents(noise, batch_size, num_channels_latents, height, width)
625
+ image_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height, width)
626
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
627
+
628
+ return latents, noise, image_latents, latent_image_ids
629
+
630
+ def prepare_mask_latents(
631
+ self,
632
+ mask,
633
+ masked_image,
634
+ batch_size,
635
+ num_channels_latents,
636
+ num_images_per_prompt,
637
+ height,
638
+ width,
639
+ dtype,
640
+ device,
641
+ generator,
642
+ ):
643
+ # VAE applies 8x compression on images but we must also account for packing which requires
644
+ # latent height and width to be divisible by 2.
645
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
646
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
647
+ # resize the mask to latents shape as we concatenate the mask to the latents
648
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
649
+ # and half precision
650
+ mask = torch.nn.functional.interpolate(mask, size=(height, width))
651
+ mask = mask.to(device=device, dtype=dtype)
652
+
653
+ batch_size = batch_size * num_images_per_prompt
654
+
655
+ masked_image = masked_image.to(device=device, dtype=dtype)
656
+
657
+ if masked_image.shape[1] == 16:
658
+ masked_image_latents = masked_image
659
+ else:
660
+ masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
661
+
662
+ masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
663
+
664
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
665
+ if mask.shape[0] < batch_size:
666
+ if not batch_size % mask.shape[0] == 0:
667
+ raise ValueError(
668
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
669
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
670
+ " of masks that you pass is divisible by the total requested batch size."
671
+ )
672
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
673
+ if masked_image_latents.shape[0] < batch_size:
674
+ if not batch_size % masked_image_latents.shape[0] == 0:
675
+ raise ValueError(
676
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
677
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
678
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
679
+ )
680
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
681
+
682
+ # aligning device to prevent device errors when concating it with the latent model input
683
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
684
+ masked_image_latents = self._pack_latents(
685
+ masked_image_latents,
686
+ batch_size,
687
+ num_channels_latents,
688
+ height,
689
+ width,
690
+ )
691
+
692
+ mask = self._pack_latents(
693
+ mask.repeat(1, num_channels_latents, 1, 1),
694
+ batch_size,
695
+ num_channels_latents,
696
+ height,
697
+ width,
698
+ )
699
+ return mask, masked_image_latents
700
+
701
+ # Copied from diffusers.pipelines.controlnet_sd3.pipeline_stable_diffusion_3_controlnet.StableDiffusion3ControlNetPipeline.prepare_image
702
+ def prepare_image(
703
+ self,
704
+ image,
705
+ width,
706
+ height,
707
+ batch_size,
708
+ num_images_per_prompt,
709
+ device,
710
+ dtype,
711
+ do_classifier_free_guidance=False,
712
+ guess_mode=False,
713
+ ):
714
+ if isinstance(image, torch.Tensor):
715
+ pass
716
+ else:
717
+ image = self.image_processor.preprocess(image, height=height, width=width)
718
+
719
+ image_batch_size = image.shape[0]
720
+
721
+ if image_batch_size == 1:
722
+ repeat_by = batch_size
723
+ else:
724
+ # image batch size is the same as prompt batch size
725
+ repeat_by = num_images_per_prompt
726
+
727
+ image = image.repeat_interleave(repeat_by, dim=0)
728
+
729
+ image = image.to(device=device, dtype=dtype)
730
+
731
+ if do_classifier_free_guidance and not guess_mode:
732
+ image = torch.cat([image] * 2)
733
+
734
+ return image
735
+
736
+ def prepare_mask_latents_fill(
737
+ self,
738
+ mask,
739
+ masked_image,
740
+ batch_size,
741
+ num_channels_latents,
742
+ num_images_per_prompt,
743
+ height,
744
+ width,
745
+ dtype,
746
+ device,
747
+ generator,
748
+ ):
749
+ # 1. calculate the height and width of the latents
750
+ # VAE applies 8x compression on images but we must also account for packing which requires
751
+ # latent height and width to be divisible by 2.
752
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
753
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
754
+
755
+ # 2. encode the masked image
756
+ if masked_image.shape[1] == num_channels_latents:
757
+ masked_image_latents = masked_image
758
+ else:
759
+ masked_image_latents = retrieve_latents_fill(self.vae.encode(masked_image), generator=generator)
760
+
761
+ masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
762
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
763
+
764
+ # 3. duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
765
+ batch_size = batch_size * num_images_per_prompt
766
+ if mask.shape[0] < batch_size:
767
+ if not batch_size % mask.shape[0] == 0:
768
+ raise ValueError(
769
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
770
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
771
+ " of masks that you pass is divisible by the total requested batch size."
772
+ )
773
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
774
+ if masked_image_latents.shape[0] < batch_size:
775
+ if not batch_size % masked_image_latents.shape[0] == 0:
776
+ raise ValueError(
777
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
778
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
779
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
780
+ )
781
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
782
+
783
+ # 4. pack the masked_image_latents
784
+ # batch_size, num_channels_latents, height, width -> batch_size, height//2 * width//2 , num_channels_latents*4
785
+ masked_image_latents = self._pack_latents(
786
+ masked_image_latents,
787
+ batch_size,
788
+ num_channels_latents,
789
+ height,
790
+ width,
791
+ )
792
+
793
+ # 5.resize mask to latents shape we we concatenate the mask to the latents
794
+ mask = mask[:, 0, :, :] # batch_size, 8 * height, 8 * width (mask has not been 8x compressed)
795
+ mask = mask.view(
796
+ batch_size, height, self.vae_scale_factor, width, self.vae_scale_factor
797
+ ) # batch_size, height, 8, width, 8
798
+ mask = mask.permute(0, 2, 4, 1, 3) # batch_size, 8, 8, height, width
799
+ mask = mask.reshape(
800
+ batch_size, self.vae_scale_factor * self.vae_scale_factor, height, width
801
+ ) # batch_size, 8*8, height, width
802
+
803
+ # 6. pack the mask:
804
+ # batch_size, 64, height, width -> batch_size, height//2 * width//2 , 64*2*2
805
+ mask = self._pack_latents(
806
+ mask,
807
+ batch_size,
808
+ self.vae_scale_factor * self.vae_scale_factor,
809
+ height,
810
+ width,
811
+ )
812
+ mask = mask.to(device=device, dtype=dtype)
813
+
814
+ return mask, masked_image_latents
815
+
816
+ @property
817
+ def guidance_scale(self):
818
+ return self._guidance_scale
819
+
820
+ @property
821
+ def joint_attention_kwargs(self):
822
+ return self._joint_attention_kwargs
823
+
824
+ @property
825
+ def num_timesteps(self):
826
+ return self._num_timesteps
827
+
828
+ @property
829
+ def interrupt(self):
830
+ return self._interrupt
831
+
832
+ @torch.no_grad()
833
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
834
+ def __call__(
835
+ self,
836
+ prompt: Union[str, List[str]] = None,
837
+ prompt_2: Optional[Union[str, List[str]]] = None,
838
+ image: PipelineImageInput = None,
839
+ mask_image: PipelineImageInput = None,
840
+ masked_image_latents: PipelineImageInput = None,
841
+ control_image: PipelineImageInput = None,
842
+ height: Optional[int] = None,
843
+ width: Optional[int] = None,
844
+ strength: float = 0.6,
845
+ padding_mask_crop: Optional[int] = None,
846
+ sigmas: Optional[List[float]] = None,
847
+ num_inference_steps: int = 28,
848
+ guidance_scale: float = 7.0,
849
+ control_guidance_start: Union[float, List[float]] = 0.0,
850
+ control_guidance_end: Union[float, List[float]] = 1.0,
851
+ control_mode: Optional[Union[int, List[int]]] = None,
852
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
853
+ num_images_per_prompt: Optional[int] = 1,
854
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
855
+ latents: Optional[torch.FloatTensor] = None,
856
+ prompt_embeds: Optional[torch.FloatTensor] = None,
857
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
858
+ output_type: Optional[str] = "pil",
859
+ return_dict: bool = True,
860
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
861
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
862
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
863
+ max_sequence_length: int = 512,
864
+ ):
865
+ """
866
+ Function invoked when calling the pipeline for generation.
867
+
868
+ Args:
869
+ prompt (`str` or `List[str]`, *optional*):
870
+ The prompt or prompts to guide the image generation.
871
+ prompt_2 (`str` or `List[str]`, *optional*):
872
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`.
873
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
874
+ The image(s) to inpaint.
875
+ mask_image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
876
+ The mask image(s) to use for inpainting. White pixels in the mask will be repainted, while black pixels
877
+ will be preserved.
878
+ masked_image_latents (`torch.FloatTensor`, *optional*):
879
+ Pre-generated masked image latents.
880
+ control_image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
881
+ The ControlNet input condition. Image to control the generation.
882
+ height (`int`, *optional*, defaults to self.default_sample_size * self.vae_scale_factor):
883
+ The height in pixels of the generated image.
884
+ width (`int`, *optional*, defaults to self.default_sample_size * self.vae_scale_factor):
885
+ The width in pixels of the generated image.
886
+ strength (`float`, *optional*, defaults to 0.6):
887
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1.
888
+ padding_mask_crop (`int`, *optional*):
889
+ The size of the padding to use when cropping the mask.
890
+ num_inference_steps (`int`, *optional*, defaults to 28):
891
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
892
+ expense of slower inference.
893
+ sigmas (`List[float]`, *optional*):
894
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
895
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
896
+ will be used.
897
+ guidance_scale (`float`, *optional*, defaults to 7.0):
898
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
899
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
900
+ The percentage of total steps at which the ControlNet starts applying.
901
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
902
+ The percentage of total steps at which the ControlNet stops applying.
903
+ control_mode (`int` or `List[int]`, *optional*):
904
+ The mode for the ControlNet. If multiple ControlNets are used, this should be a list.
905
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
906
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
907
+ to the residual in the original transformer.
908
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
909
+ The number of images to generate per prompt.
910
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
911
+ One or more [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) to
912
+ make generation deterministic.
913
+ latents (`torch.FloatTensor`, *optional*):
914
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
915
+ generation. Can be used to tweak the same generation with different prompts.
916
+ prompt_embeds (`torch.FloatTensor`, *optional*):
917
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
918
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
919
+ Pre-generated pooled text embeddings.
920
+ output_type (`str`, *optional*, defaults to `"pil"`):
921
+ The output format of the generate image. Choose between `PIL.Image` or `np.array`.
922
+ return_dict (`bool`, *optional*, defaults to `True`):
923
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
924
+ joint_attention_kwargs (`dict`, *optional*):
925
+ Additional keyword arguments to be passed to the joint attention mechanism.
926
+ callback_on_step_end (`Callable`, *optional*):
927
+ A function that calls at the end of each denoising step during the inference.
928
+ callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
929
+ The list of tensor inputs for the `callback_on_step_end` function.
930
+ max_sequence_length (`int`, *optional*, defaults to 512):
931
+ The maximum length of the sequence to be generated.
932
+
933
+ Examples:
934
+
935
+ Returns:
936
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
937
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
938
+ images.
939
+ """
940
+ height = height or self.default_sample_size * self.vae_scale_factor
941
+ width = width or self.default_sample_size * self.vae_scale_factor
942
+
943
+ global_height = height
944
+ global_width = width
945
+
946
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
947
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
948
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
949
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
950
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
951
+ mult = len(self.controlnet.nets) if isinstance(self.controlnet, FluxMultiControlNetModel) else 1
952
+ control_guidance_start, control_guidance_end = (
953
+ mult * [control_guidance_start],
954
+ mult * [control_guidance_end],
955
+ )
956
+
957
+ # 1. Check inputs
958
+ self.check_inputs(
959
+ prompt,
960
+ prompt_2,
961
+ image,
962
+ mask_image,
963
+ strength,
964
+ height,
965
+ width,
966
+ output_type=output_type,
967
+ prompt_embeds=prompt_embeds,
968
+ pooled_prompt_embeds=pooled_prompt_embeds,
969
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
970
+ padding_mask_crop=padding_mask_crop,
971
+ max_sequence_length=max_sequence_length,
972
+ )
973
+
974
+ self._guidance_scale = guidance_scale
975
+ self._joint_attention_kwargs = joint_attention_kwargs
976
+ self._interrupt = False
977
+
978
+ # 2. Define call parameters
979
+ if prompt is not None and isinstance(prompt, str):
980
+ batch_size = 1
981
+ elif prompt is not None and isinstance(prompt, list):
982
+ batch_size = len(prompt)
983
+ else:
984
+ batch_size = prompt_embeds.shape[0]
985
+
986
+ device = self._execution_device
987
+ dtype = self.transformer.dtype
988
+
989
+ # 3. Encode input prompt
990
+ lora_scale = (
991
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
992
+ )
993
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
994
+ prompt=prompt,
995
+ prompt_2=prompt_2,
996
+ prompt_embeds=prompt_embeds,
997
+ pooled_prompt_embeds=pooled_prompt_embeds,
998
+ device=device,
999
+ num_images_per_prompt=num_images_per_prompt,
1000
+ max_sequence_length=max_sequence_length,
1001
+ lora_scale=lora_scale,
1002
+ )
1003
+
1004
+ # 4. Preprocess mask and image
1005
+ if padding_mask_crop is not None:
1006
+ crops_coords = self.mask_processor.get_crop_region(
1007
+ mask_image, global_width, global_height, pad=padding_mask_crop
1008
+ )
1009
+ resize_mode = "fill"
1010
+ else:
1011
+ crops_coords = None
1012
+ resize_mode = "default"
1013
+
1014
+ original_image = image
1015
+ init_image = self.image_processor.preprocess(
1016
+ image, height=global_height, width=global_width, crops_coords=crops_coords, resize_mode=resize_mode
1017
+ )
1018
+ init_image = init_image.to(dtype=torch.float32)
1019
+
1020
+ # 5. Prepare control image
1021
+ # num_channels_latents = self.transformer.config.in_channels // 4
1022
+ num_channels_latents = self.vae.config.latent_channels
1023
+
1024
+ if isinstance(self.controlnet, FluxControlNetModel):
1025
+ control_image = self.prepare_image(
1026
+ image=control_image,
1027
+ width=width,
1028
+ height=height,
1029
+ batch_size=batch_size * num_images_per_prompt,
1030
+ num_images_per_prompt=num_images_per_prompt,
1031
+ device=device,
1032
+ dtype=self.vae.dtype,
1033
+ )
1034
+ height, width = control_image.shape[-2:]
1035
+
1036
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
1037
+ controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True
1038
+ if self.controlnet.input_hint_block is None:
1039
+ # vae encode
1040
+ control_image = retrieve_latents(self.vae.encode(control_image), generator=generator)
1041
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
1042
+
1043
+ # pack
1044
+ height_control_image, width_control_image = control_image.shape[2:]
1045
+ control_image = self._pack_latents(
1046
+ control_image,
1047
+ batch_size * num_images_per_prompt,
1048
+ num_channels_latents,
1049
+ height_control_image,
1050
+ width_control_image,
1051
+ )
1052
+
1053
+ # set control mode
1054
+ if control_mode is not None:
1055
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
1056
+ control_mode = control_mode.reshape([-1, 1])
1057
+
1058
+ elif isinstance(self.controlnet, FluxMultiControlNetModel):
1059
+ control_images = []
1060
+
1061
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
1062
+ controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True
1063
+ for i, control_image_ in enumerate(control_image):
1064
+ control_image_ = self.prepare_image(
1065
+ image=control_image_,
1066
+ width=width,
1067
+ height=height,
1068
+ batch_size=batch_size * num_images_per_prompt,
1069
+ num_images_per_prompt=num_images_per_prompt,
1070
+ device=device,
1071
+ dtype=self.vae.dtype,
1072
+ )
1073
+ height, width = control_image_.shape[-2:]
1074
+
1075
+ if self.controlnet.nets[0].input_hint_block is None:
1076
+ # vae encode
1077
+ control_image_ = retrieve_latents(self.vae.encode(control_image_), generator=generator)
1078
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
1079
+
1080
+ # pack
1081
+ height_control_image, width_control_image = control_image_.shape[2:]
1082
+ control_image_ = self._pack_latents(
1083
+ control_image_,
1084
+ batch_size * num_images_per_prompt,
1085
+ num_channels_latents,
1086
+ height_control_image,
1087
+ width_control_image,
1088
+ )
1089
+
1090
+ control_images.append(control_image_)
1091
+
1092
+ control_image = control_images
1093
+
1094
+ # set control mode
1095
+ control_mode_ = []
1096
+ if isinstance(control_mode, list):
1097
+ for cmode in control_mode:
1098
+ if cmode is None:
1099
+ control_mode_.append(-1)
1100
+ else:
1101
+ control_mode_.append(cmode)
1102
+ control_mode = torch.tensor(control_mode_).to(device, dtype=torch.long)
1103
+ control_mode = control_mode.reshape([-1, 1])
1104
+
1105
+ # 6. Prepare timesteps
1106
+
1107
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
1108
+ image_seq_len = (int(global_height) // self.vae_scale_factor // 2) * (
1109
+ int(global_width) // self.vae_scale_factor // 2
1110
+ )
1111
+ mu = calculate_shift(
1112
+ image_seq_len,
1113
+ self.scheduler.config.get("base_image_seq_len", 256),
1114
+ self.scheduler.config.get("max_image_seq_len", 4096),
1115
+ self.scheduler.config.get("base_shift", 0.5),
1116
+ self.scheduler.config.get("max_shift", 1.15),
1117
+ )
1118
+ timesteps, num_inference_steps = retrieve_timesteps(
1119
+ self.scheduler,
1120
+ num_inference_steps,
1121
+ device,
1122
+ sigmas=sigmas,
1123
+ mu=mu,
1124
+ )
1125
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
1126
+
1127
+ if num_inference_steps < 1:
1128
+ raise ValueError(
1129
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1130
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1131
+ )
1132
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1133
+
1134
+ # 7. Prepare latent variables
1135
+
1136
+ latents, noise, image_latents, latent_image_ids = self.prepare_latents(
1137
+ init_image,
1138
+ latent_timestep,
1139
+ batch_size * num_images_per_prompt,
1140
+ num_channels_latents,
1141
+ global_height,
1142
+ global_width,
1143
+ prompt_embeds.dtype,
1144
+ device,
1145
+ generator,
1146
+ latents,
1147
+ )
1148
+
1149
+ # 8. Prepare mask latents
1150
+ mask_condition = self.mask_processor.preprocess(
1151
+ mask_image, height=global_height, width=global_width, resize_mode=resize_mode, crops_coords=crops_coords
1152
+ )
1153
+ if masked_image_latents is None:
1154
+ masked_image = init_image * (mask_condition < 0.5)
1155
+ else:
1156
+ masked_image = masked_image_latents
1157
+
1158
+ mask, masked_image_latents = self.prepare_mask_latents(
1159
+ mask_condition,
1160
+ masked_image,
1161
+ batch_size,
1162
+ num_channels_latents,
1163
+ num_images_per_prompt,
1164
+ global_height,
1165
+ global_width,
1166
+ prompt_embeds.dtype,
1167
+ device,
1168
+ generator,
1169
+ )
1170
+
1171
+ mask_imagee = self.mask_processor.preprocess(mask_image, height=height, width=width)
1172
+ masked_imagee = init_image * (1 - mask_imagee)
1173
+ masked_imagee = masked_imagee.to(dtype=self.vae.dtype, device=device)
1174
+ maskkk, masked_image_latentsss = self.prepare_mask_latents_fill(
1175
+ mask_imagee,
1176
+ masked_imagee,
1177
+ batch_size,
1178
+ num_channels_latents,
1179
+ num_images_per_prompt,
1180
+ height,
1181
+ width,
1182
+ prompt_embeds.dtype,
1183
+ device,
1184
+ generator,
1185
+ )
1186
+
1187
+ controlnet_keep = []
1188
+ for i in range(len(timesteps)):
1189
+ keeps = [
1190
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1191
+ for s, e in zip(control_guidance_start, control_guidance_end)
1192
+ ]
1193
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
1194
+
1195
+ # 9. Denoising loop
1196
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1197
+ self._num_timesteps = len(timesteps)
1198
+
1199
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1200
+ for i, t in enumerate(timesteps):
1201
+ if self.interrupt:
1202
+ continue
1203
+
1204
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
1205
+
1206
+ # predict the noise residual
1207
+ if isinstance(self.controlnet, FluxMultiControlNetModel):
1208
+ use_guidance = self.controlnet.nets[0].config.guidance_embeds
1209
+ else:
1210
+ use_guidance = self.controlnet.config.guidance_embeds
1211
+ if use_guidance:
1212
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
1213
+ guidance = guidance.expand(latents.shape[0])
1214
+ else:
1215
+ guidance = None
1216
+
1217
+ if isinstance(controlnet_keep[i], list):
1218
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1219
+ else:
1220
+ controlnet_cond_scale = controlnet_conditioning_scale
1221
+ if isinstance(controlnet_cond_scale, list):
1222
+ controlnet_cond_scale = controlnet_cond_scale[0]
1223
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1224
+
1225
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
1226
+ hidden_states=latents,
1227
+ controlnet_cond=control_image,
1228
+ controlnet_mode=control_mode,
1229
+ conditioning_scale=cond_scale,
1230
+ timestep=timestep / 1000,
1231
+ guidance=guidance,
1232
+ pooled_projections=pooled_prompt_embeds,
1233
+ encoder_hidden_states=prompt_embeds,
1234
+ txt_ids=text_ids,
1235
+ img_ids=latent_image_ids,
1236
+ joint_attention_kwargs=self.joint_attention_kwargs,
1237
+ return_dict=False,
1238
+ )
1239
+
1240
+ if self.transformer.config.guidance_embeds:
1241
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
1242
+ guidance = guidance.expand(latents.shape[0])
1243
+ else:
1244
+ guidance = None
1245
+
1246
+ masked_image_latents_fill = torch.cat((masked_image_latentsss, maskkk), dim=-1)
1247
+ latent_model_input = torch.cat([latents, masked_image_latents_fill], dim=2)
1248
+
1249
+ noise_pred = self.transformer(
1250
+ hidden_states=latent_model_input,
1251
+ timestep=timestep / 1000,
1252
+ guidance=guidance,
1253
+ pooled_projections=pooled_prompt_embeds,
1254
+ encoder_hidden_states=prompt_embeds,
1255
+ controlnet_block_samples=controlnet_block_samples,
1256
+ controlnet_single_block_samples=controlnet_single_block_samples,
1257
+ txt_ids=text_ids,
1258
+ img_ids=latent_image_ids,
1259
+ joint_attention_kwargs=self.joint_attention_kwargs,
1260
+ return_dict=False,
1261
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
1262
+ )[0]
1263
+
1264
+ # compute the previous noisy sample x_t -> x_t-1
1265
+ latents_dtype = latents.dtype
1266
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1267
+
1268
+ # For inpainting, we need to apply the mask and add the masked image latents
1269
+ init_latents_proper = image_latents
1270
+ init_mask = mask
1271
+
1272
+ if i < len(timesteps) - 1:
1273
+ noise_timestep = timesteps[i + 1]
1274
+ init_latents_proper = self.scheduler.scale_noise(
1275
+ init_latents_proper, torch.tensor([noise_timestep]), noise
1276
+ )
1277
+
1278
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1279
+
1280
+ if latents.dtype != latents_dtype:
1281
+ if torch.backends.mps.is_available():
1282
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1283
+ latents = latents.to(latents_dtype)
1284
+
1285
+ # call the callback, if provided
1286
+ if callback_on_step_end is not None:
1287
+ callback_kwargs = {}
1288
+ for k in callback_on_step_end_tensor_inputs:
1289
+ callback_kwargs[k] = locals()[k]
1290
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1291
+
1292
+ latents = callback_outputs.pop("latents", latents)
1293
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1294
+ control_image = callback_outputs.pop("control_image", control_image)
1295
+ mask = callback_outputs.pop("mask", mask)
1296
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
1297
+
1298
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1299
+ progress_bar.update()
1300
+
1301
+ if XLA_AVAILABLE:
1302
+ xm.mark_step()
1303
+
1304
+ # Post-processing
1305
+ if output_type == "latent":
1306
+ image = latents
1307
+ else:
1308
+ latents = self._unpack_latents(latents, global_height, global_width, self.vae_scale_factor)
1309
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1310
+ image = self.vae.decode(latents, return_dict=False)[0]
1311
+ image = self.image_processor.postprocess(image, output_type=output_type)
1312
+
1313
+ # Offload all models
1314
+ self.maybe_free_model_hooks()
1315
+
1316
+ if not return_dict:
1317
+ return (image,)
1318
+
1319
+ return FluxPipelineOutput(images=image)