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