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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 Black Forest Labs, The HuggingFace Team and InstantX Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import inspect
|
16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
17 |
+
|
18 |
+
import numpy as np
|
19 |
+
import torch
|
20 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
21 |
+
|
22 |
+
from diffusers.image_processor import VaeImageProcessor
|
23 |
+
from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin
|
24 |
+
from diffusers.models.autoencoders import AutoencoderKL
|
25 |
+
from diffusers.models.transformers import FluxTransformer2DModel
|
26 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
27 |
+
from diffusers.utils import (
|
28 |
+
USE_PEFT_BACKEND,
|
29 |
+
is_torch_xla_available,
|
30 |
+
logging,
|
31 |
+
replace_example_docstring,
|
32 |
+
scale_lora_layers,
|
33 |
+
unscale_lora_layers,
|
34 |
+
)
|
35 |
+
from diffusers.utils.torch_utils import randn_tensor
|
36 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
37 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
38 |
+
|
39 |
+
|
40 |
+
if is_torch_xla_available():
|
41 |
+
import torch_xla.core.xla_model as xm
|
42 |
+
|
43 |
+
XLA_AVAILABLE = True
|
44 |
+
else:
|
45 |
+
XLA_AVAILABLE = False
|
46 |
+
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
49 |
+
|
50 |
+
EXAMPLE_DOC_STRING = """
|
51 |
+
Examples:
|
52 |
+
```py
|
53 |
+
>>> import torch
|
54 |
+
>>> from diffusers import FluxPipeline
|
55 |
+
|
56 |
+
>>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
|
57 |
+
>>> pipe.to("cuda")
|
58 |
+
>>> prompt = "A cat holding a sign that says hello world"
|
59 |
+
>>> # Depending on the variant being used, the pipeline call will slightly vary.
|
60 |
+
>>> # Refer to the pipeline documentation for more details.
|
61 |
+
>>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
|
62 |
+
>>> image.save("flux.png")
|
63 |
+
```
|
64 |
+
"""
|
65 |
+
|
66 |
+
|
67 |
+
def calculate_shift(
|
68 |
+
image_seq_len,
|
69 |
+
base_seq_len: int = 256,
|
70 |
+
max_seq_len: int = 4096,
|
71 |
+
base_shift: float = 0.5,
|
72 |
+
max_shift: float = 1.16,
|
73 |
+
):
|
74 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
75 |
+
b = base_shift - m * base_seq_len
|
76 |
+
mu = image_seq_len * m + b
|
77 |
+
return mu
|
78 |
+
|
79 |
+
|
80 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
81 |
+
def retrieve_timesteps(
|
82 |
+
scheduler,
|
83 |
+
num_inference_steps: Optional[int] = None,
|
84 |
+
device: Optional[Union[str, torch.device]] = None,
|
85 |
+
timesteps: Optional[List[int]] = None,
|
86 |
+
sigmas: Optional[List[float]] = None,
|
87 |
+
**kwargs,
|
88 |
+
):
|
89 |
+
"""
|
90 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
91 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
92 |
+
|
93 |
+
Args:
|
94 |
+
scheduler (`SchedulerMixin`):
|
95 |
+
The scheduler to get timesteps from.
|
96 |
+
num_inference_steps (`int`):
|
97 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
98 |
+
must be `None`.
|
99 |
+
device (`str` or `torch.device`, *optional*):
|
100 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
101 |
+
timesteps (`List[int]`, *optional*):
|
102 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
103 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
104 |
+
sigmas (`List[float]`, *optional*):
|
105 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
106 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
107 |
+
|
108 |
+
Returns:
|
109 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
110 |
+
second element is the number of inference steps.
|
111 |
+
"""
|
112 |
+
if timesteps is not None and sigmas is not None:
|
113 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
114 |
+
if timesteps is not None:
|
115 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
116 |
+
if not accepts_timesteps:
|
117 |
+
raise ValueError(
|
118 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
119 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
120 |
+
)
|
121 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
122 |
+
timesteps = scheduler.timesteps
|
123 |
+
num_inference_steps = len(timesteps)
|
124 |
+
elif sigmas is not None:
|
125 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
126 |
+
if not accept_sigmas:
|
127 |
+
raise ValueError(
|
128 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
129 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
130 |
+
)
|
131 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
132 |
+
timesteps = scheduler.timesteps
|
133 |
+
num_inference_steps = len(timesteps)
|
134 |
+
else:
|
135 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
136 |
+
timesteps = scheduler.timesteps
|
137 |
+
return timesteps, num_inference_steps
|
138 |
+
|
139 |
+
|
140 |
+
class FluxPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
|
141 |
+
r"""
|
142 |
+
The Flux pipeline for text-to-image generation.
|
143 |
+
|
144 |
+
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
|
145 |
+
|
146 |
+
Args:
|
147 |
+
transformer ([`FluxTransformer2DModel`]):
|
148 |
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
149 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
150 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
151 |
+
vae ([`AutoencoderKL`]):
|
152 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
153 |
+
text_encoder ([`CLIPTextModel`]):
|
154 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
155 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
156 |
+
text_encoder_2 ([`T5EncoderModel`]):
|
157 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
158 |
+
the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
159 |
+
tokenizer (`CLIPTokenizer`):
|
160 |
+
Tokenizer of class
|
161 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
162 |
+
tokenizer_2 (`T5TokenizerFast`):
|
163 |
+
Second Tokenizer of class
|
164 |
+
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
|
165 |
+
"""
|
166 |
+
|
167 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
168 |
+
_optional_components = []
|
169 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
170 |
+
|
171 |
+
def __init__(
|
172 |
+
self,
|
173 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
174 |
+
vae: AutoencoderKL,
|
175 |
+
text_encoder: CLIPTextModel,
|
176 |
+
tokenizer: CLIPTokenizer,
|
177 |
+
text_encoder_2: T5EncoderModel,
|
178 |
+
tokenizer_2: T5TokenizerFast,
|
179 |
+
transformer: FluxTransformer2DModel,
|
180 |
+
):
|
181 |
+
super().__init__()
|
182 |
+
|
183 |
+
self.register_modules(
|
184 |
+
vae=vae,
|
185 |
+
text_encoder=text_encoder,
|
186 |
+
text_encoder_2=text_encoder_2,
|
187 |
+
tokenizer=tokenizer,
|
188 |
+
tokenizer_2=tokenizer_2,
|
189 |
+
transformer=transformer,
|
190 |
+
scheduler=scheduler,
|
191 |
+
)
|
192 |
+
self.vae_scale_factor = (
|
193 |
+
2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
|
194 |
+
)
|
195 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
196 |
+
self.tokenizer_max_length = (
|
197 |
+
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
|
198 |
+
)
|
199 |
+
self.default_sample_size = 64
|
200 |
+
|
201 |
+
def _get_t5_prompt_embeds(
|
202 |
+
self,
|
203 |
+
prompt: Union[str, List[str]] = None,
|
204 |
+
num_images_per_prompt: int = 1,
|
205 |
+
max_sequence_length: int = 512,
|
206 |
+
device: Optional[torch.device] = None,
|
207 |
+
dtype: Optional[torch.dtype] = None,
|
208 |
+
):
|
209 |
+
device = device or self._execution_device
|
210 |
+
dtype = dtype or self.text_encoder.dtype
|
211 |
+
|
212 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
213 |
+
batch_size = len(prompt)
|
214 |
+
|
215 |
+
text_inputs = self.tokenizer_2(
|
216 |
+
prompt,
|
217 |
+
padding="max_length",
|
218 |
+
max_length=max_sequence_length,
|
219 |
+
truncation=True,
|
220 |
+
return_length=False,
|
221 |
+
return_overflowing_tokens=False,
|
222 |
+
return_tensors="pt",
|
223 |
+
)
|
224 |
+
text_input_ids = text_inputs.input_ids
|
225 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
226 |
+
|
227 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
228 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
229 |
+
logger.warning(
|
230 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
231 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
232 |
+
)
|
233 |
+
|
234 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
|
235 |
+
|
236 |
+
dtype = self.text_encoder_2.dtype
|
237 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
238 |
+
|
239 |
+
_, seq_len, _ = prompt_embeds.shape
|
240 |
+
|
241 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
242 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
243 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
244 |
+
|
245 |
+
return prompt_embeds
|
246 |
+
|
247 |
+
def _get_clip_prompt_embeds(
|
248 |
+
self,
|
249 |
+
prompt: Union[str, List[str]],
|
250 |
+
num_images_per_prompt: int = 1,
|
251 |
+
device: Optional[torch.device] = None,
|
252 |
+
):
|
253 |
+
device = device or self._execution_device
|
254 |
+
|
255 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
256 |
+
batch_size = len(prompt)
|
257 |
+
|
258 |
+
text_inputs = self.tokenizer(
|
259 |
+
prompt,
|
260 |
+
padding="max_length",
|
261 |
+
max_length=self.tokenizer_max_length,
|
262 |
+
truncation=True,
|
263 |
+
return_overflowing_tokens=False,
|
264 |
+
return_length=False,
|
265 |
+
return_tensors="pt",
|
266 |
+
)
|
267 |
+
|
268 |
+
text_input_ids = text_inputs.input_ids
|
269 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
270 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
271 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
272 |
+
logger.warning(
|
273 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
274 |
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
275 |
+
)
|
276 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
277 |
+
|
278 |
+
# Use pooled output of CLIPTextModel
|
279 |
+
prompt_embeds = prompt_embeds.pooler_output
|
280 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
281 |
+
|
282 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
283 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
|
284 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
285 |
+
|
286 |
+
return prompt_embeds
|
287 |
+
|
288 |
+
def encode_prompt(
|
289 |
+
self,
|
290 |
+
prompt: Union[str, List[str]],
|
291 |
+
prompt_2: Union[str, List[str]],
|
292 |
+
negative_prompt: Union[str, List[str]],
|
293 |
+
device: Optional[torch.device] = None,
|
294 |
+
num_images_per_prompt: int = 1,
|
295 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
296 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
297 |
+
max_sequence_length: int = 512,
|
298 |
+
lora_scale: Optional[float] = None,
|
299 |
+
):
|
300 |
+
r"""
|
301 |
+
|
302 |
+
Args:
|
303 |
+
prompt (`str` or `List[str]`, *optional*):
|
304 |
+
prompt to be encoded
|
305 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
306 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
307 |
+
used in all text-encoders
|
308 |
+
device: (`torch.device`):
|
309 |
+
torch device
|
310 |
+
num_images_per_prompt (`int`):
|
311 |
+
number of images that should be generated per prompt
|
312 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
313 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
314 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
315 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
316 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
317 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
318 |
+
lora_scale (`float`, *optional*):
|
319 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
320 |
+
"""
|
321 |
+
device = device or self._execution_device
|
322 |
+
|
323 |
+
# set lora scale so that monkey patched LoRA
|
324 |
+
# function of text encoder can correctly access it
|
325 |
+
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
|
326 |
+
self._lora_scale = lora_scale
|
327 |
+
|
328 |
+
# dynamically adjust the LoRA scale
|
329 |
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
330 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
331 |
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
332 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
333 |
+
|
334 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
335 |
+
negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
336 |
+
|
337 |
+
if prompt_embeds is None:
|
338 |
+
prompt_2 = prompt_2 or prompt
|
339 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
340 |
+
|
341 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
342 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
343 |
+
prompt=prompt,
|
344 |
+
device=device,
|
345 |
+
num_images_per_prompt=num_images_per_prompt,
|
346 |
+
)
|
347 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
348 |
+
prompt=prompt_2,
|
349 |
+
num_images_per_prompt=num_images_per_prompt,
|
350 |
+
max_sequence_length=max_sequence_length,
|
351 |
+
device=device,
|
352 |
+
)
|
353 |
+
|
354 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
355 |
+
negative_pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
356 |
+
prompt=negative_prompt,
|
357 |
+
device=device,
|
358 |
+
num_images_per_prompt=num_images_per_prompt,
|
359 |
+
)
|
360 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
361 |
+
prompt=negative_prompt,
|
362 |
+
num_images_per_prompt=num_images_per_prompt,
|
363 |
+
max_sequence_length=max_sequence_length,
|
364 |
+
device=device,
|
365 |
+
)
|
366 |
+
|
367 |
+
if self.text_encoder is not None:
|
368 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
369 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
370 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
371 |
+
|
372 |
+
if self.text_encoder_2 is not None:
|
373 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
374 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
375 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
376 |
+
|
377 |
+
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
|
378 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
379 |
+
|
380 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids, negative_prompt_embeds, negative_pooled_prompt_embeds
|
381 |
+
|
382 |
+
def check_inputs(
|
383 |
+
self,
|
384 |
+
prompt,
|
385 |
+
prompt_2,
|
386 |
+
height,
|
387 |
+
width,
|
388 |
+
prompt_embeds=None,
|
389 |
+
pooled_prompt_embeds=None,
|
390 |
+
callback_on_step_end_tensor_inputs=None,
|
391 |
+
max_sequence_length=None,
|
392 |
+
):
|
393 |
+
if height % 8 != 0 or width % 8 != 0:
|
394 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
395 |
+
|
396 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
397 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
398 |
+
):
|
399 |
+
raise ValueError(
|
400 |
+
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]}"
|
401 |
+
)
|
402 |
+
|
403 |
+
if prompt is not None and prompt_embeds is not None:
|
404 |
+
raise ValueError(
|
405 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
406 |
+
" only forward one of the two."
|
407 |
+
)
|
408 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
409 |
+
raise ValueError(
|
410 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
411 |
+
" only forward one of the two."
|
412 |
+
)
|
413 |
+
elif prompt is None and prompt_embeds is None:
|
414 |
+
raise ValueError(
|
415 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
416 |
+
)
|
417 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
418 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
419 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
420 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
421 |
+
|
422 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
423 |
+
raise ValueError(
|
424 |
+
"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`."
|
425 |
+
)
|
426 |
+
|
427 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
428 |
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
429 |
+
|
430 |
+
@staticmethod
|
431 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
432 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
433 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
|
434 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
|
435 |
+
|
436 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
437 |
+
|
438 |
+
latent_image_ids = latent_image_ids.reshape(
|
439 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
440 |
+
)
|
441 |
+
|
442 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
443 |
+
|
444 |
+
@staticmethod
|
445 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
446 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
447 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
448 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
449 |
+
|
450 |
+
return latents
|
451 |
+
|
452 |
+
@staticmethod
|
453 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
454 |
+
batch_size, num_patches, channels = latents.shape
|
455 |
+
|
456 |
+
height = height // vae_scale_factor
|
457 |
+
width = width // vae_scale_factor
|
458 |
+
|
459 |
+
latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
|
460 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
461 |
+
|
462 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
|
463 |
+
|
464 |
+
return latents
|
465 |
+
|
466 |
+
def enable_vae_slicing(self):
|
467 |
+
r"""
|
468 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
469 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
470 |
+
"""
|
471 |
+
self.vae.enable_slicing()
|
472 |
+
|
473 |
+
def disable_vae_slicing(self):
|
474 |
+
r"""
|
475 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
476 |
+
computing decoding in one step.
|
477 |
+
"""
|
478 |
+
self.vae.disable_slicing()
|
479 |
+
|
480 |
+
def enable_vae_tiling(self):
|
481 |
+
r"""
|
482 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
483 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
484 |
+
processing larger images.
|
485 |
+
"""
|
486 |
+
self.vae.enable_tiling()
|
487 |
+
|
488 |
+
def disable_vae_tiling(self):
|
489 |
+
r"""
|
490 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
491 |
+
computing decoding in one step.
|
492 |
+
"""
|
493 |
+
self.vae.disable_tiling()
|
494 |
+
|
495 |
+
def prepare_latents(
|
496 |
+
self,
|
497 |
+
batch_size,
|
498 |
+
num_channels_latents,
|
499 |
+
height,
|
500 |
+
width,
|
501 |
+
dtype,
|
502 |
+
device,
|
503 |
+
generator,
|
504 |
+
latents=None,
|
505 |
+
):
|
506 |
+
height = 2 * (int(height) // self.vae_scale_factor)
|
507 |
+
width = 2 * (int(width) // self.vae_scale_factor)
|
508 |
+
|
509 |
+
shape = (batch_size, num_channels_latents, height, width)
|
510 |
+
|
511 |
+
if latents is not None:
|
512 |
+
latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
|
513 |
+
return latents.to(device=device, dtype=dtype), latent_image_ids
|
514 |
+
|
515 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
516 |
+
raise ValueError(
|
517 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
518 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
519 |
+
)
|
520 |
+
|
521 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
522 |
+
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
|
523 |
+
|
524 |
+
latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
|
525 |
+
|
526 |
+
return latents, latent_image_ids
|
527 |
+
|
528 |
+
@property
|
529 |
+
def guidance_scale(self):
|
530 |
+
return self._guidance_scale
|
531 |
+
|
532 |
+
@property
|
533 |
+
def do_classifier_free_guidance(self):
|
534 |
+
return self._guidance_scale > 1
|
535 |
+
|
536 |
+
@property
|
537 |
+
def joint_attention_kwargs(self):
|
538 |
+
return self._joint_attention_kwargs
|
539 |
+
|
540 |
+
@property
|
541 |
+
def num_timesteps(self):
|
542 |
+
return self._num_timesteps
|
543 |
+
|
544 |
+
@property
|
545 |
+
def interrupt(self):
|
546 |
+
return self._interrupt
|
547 |
+
|
548 |
+
@torch.no_grad()
|
549 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
550 |
+
def __call__(
|
551 |
+
self,
|
552 |
+
prompt: Union[str, List[str]] = None,
|
553 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
554 |
+
negative_prompt: Union[str, List[str]] = None,
|
555 |
+
height: Optional[int] = None,
|
556 |
+
width: Optional[int] = None,
|
557 |
+
num_inference_steps: int = 28,
|
558 |
+
timesteps: List[int] = None,
|
559 |
+
guidance_scale: float = 3.5,
|
560 |
+
num_images_per_prompt: Optional[int] = 1,
|
561 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
562 |
+
latents: Optional[torch.FloatTensor] = None,
|
563 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
564 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
565 |
+
output_type: Optional[str] = "pil",
|
566 |
+
return_dict: bool = True,
|
567 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
568 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
569 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
570 |
+
max_sequence_length: int = 512,
|
571 |
+
):
|
572 |
+
r"""
|
573 |
+
Function invoked when calling the pipeline for generation.
|
574 |
+
|
575 |
+
Args:
|
576 |
+
prompt (`str` or `List[str]`, *optional*):
|
577 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
578 |
+
instead.
|
579 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
580 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
581 |
+
will be used instead
|
582 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
583 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
584 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
585 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
586 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
587 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
588 |
+
expense of slower inference.
|
589 |
+
timesteps (`List[int]`, *optional*):
|
590 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
591 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
592 |
+
passed will be used. Must be in descending order.
|
593 |
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
594 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
595 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
596 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
597 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
598 |
+
usually at the expense of lower image quality.
|
599 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
600 |
+
The number of images to generate per prompt.
|
601 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
602 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
603 |
+
to make generation deterministic.
|
604 |
+
latents (`torch.FloatTensor`, *optional*):
|
605 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
606 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
607 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
608 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
609 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
610 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
611 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
612 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
613 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
614 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
615 |
+
The output format of the generate image. Choose between
|
616 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
617 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
618 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
619 |
+
joint_attention_kwargs (`dict`, *optional*):
|
620 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
621 |
+
`self.processor` in
|
622 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
623 |
+
callback_on_step_end (`Callable`, *optional*):
|
624 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
625 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
626 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
627 |
+
`callback_on_step_end_tensor_inputs`.
|
628 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
629 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
630 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
631 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
632 |
+
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
|
633 |
+
|
634 |
+
Examples:
|
635 |
+
|
636 |
+
Returns:
|
637 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
638 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
639 |
+
images.
|
640 |
+
"""
|
641 |
+
|
642 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
643 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
644 |
+
|
645 |
+
# 1. Check inputs. Raise error if not correct
|
646 |
+
self.check_inputs(
|
647 |
+
prompt,
|
648 |
+
prompt_2,
|
649 |
+
height,
|
650 |
+
width,
|
651 |
+
prompt_embeds=prompt_embeds,
|
652 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
653 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
654 |
+
max_sequence_length=max_sequence_length,
|
655 |
+
)
|
656 |
+
|
657 |
+
self._guidance_scale = guidance_scale
|
658 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
659 |
+
self._interrupt = False
|
660 |
+
|
661 |
+
# 2. Define call parameters
|
662 |
+
if prompt is not None and isinstance(prompt, str):
|
663 |
+
batch_size = 1
|
664 |
+
elif prompt is not None and isinstance(prompt, list):
|
665 |
+
batch_size = len(prompt)
|
666 |
+
else:
|
667 |
+
batch_size = prompt_embeds.shape[0]
|
668 |
+
|
669 |
+
device = self._execution_device
|
670 |
+
|
671 |
+
lora_scale = (
|
672 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
673 |
+
)
|
674 |
+
(
|
675 |
+
prompt_embeds,
|
676 |
+
pooled_prompt_embeds,
|
677 |
+
text_ids,
|
678 |
+
negative_prompt_embeds,
|
679 |
+
negative_pooled_prompt_embeds
|
680 |
+
) = self.encode_prompt(
|
681 |
+
prompt=prompt,
|
682 |
+
prompt_2=prompt_2,
|
683 |
+
negative_prompt=negative_prompt,
|
684 |
+
prompt_embeds=prompt_embeds,
|
685 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
686 |
+
device=device,
|
687 |
+
num_images_per_prompt=num_images_per_prompt,
|
688 |
+
max_sequence_length=max_sequence_length,
|
689 |
+
lora_scale=lora_scale,
|
690 |
+
)
|
691 |
+
|
692 |
+
if self.do_classifier_free_guidance:
|
693 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
694 |
+
pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
|
695 |
+
|
696 |
+
# 4. Prepare latent variables
|
697 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
698 |
+
latents, latent_image_ids = self.prepare_latents(
|
699 |
+
batch_size * num_images_per_prompt,
|
700 |
+
num_channels_latents,
|
701 |
+
height,
|
702 |
+
width,
|
703 |
+
prompt_embeds.dtype,
|
704 |
+
device,
|
705 |
+
generator,
|
706 |
+
latents,
|
707 |
+
)
|
708 |
+
|
709 |
+
# 5. Prepare timesteps
|
710 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
711 |
+
image_seq_len = latents.shape[1]
|
712 |
+
mu = calculate_shift(
|
713 |
+
image_seq_len,
|
714 |
+
self.scheduler.config.base_image_seq_len,
|
715 |
+
self.scheduler.config.max_image_seq_len,
|
716 |
+
self.scheduler.config.base_shift,
|
717 |
+
self.scheduler.config.max_shift,
|
718 |
+
)
|
719 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
720 |
+
self.scheduler,
|
721 |
+
num_inference_steps,
|
722 |
+
device,
|
723 |
+
timesteps,
|
724 |
+
sigmas,
|
725 |
+
mu=mu,
|
726 |
+
)
|
727 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
728 |
+
self._num_timesteps = len(timesteps)
|
729 |
+
|
730 |
+
# 6. Denoising loop
|
731 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
732 |
+
for i, t in enumerate(timesteps):
|
733 |
+
if self.interrupt:
|
734 |
+
continue
|
735 |
+
|
736 |
+
# expand the latents if we are doing classifier free guidance
|
737 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
738 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
739 |
+
timestep = t.expand(latent_model_input.shape[0])
|
740 |
+
|
741 |
+
noise_pred = self.transformer(
|
742 |
+
hidden_states=latent_model_input,
|
743 |
+
timestep=timestep / 1000,
|
744 |
+
pooled_projections=pooled_prompt_embeds,
|
745 |
+
encoder_hidden_states=prompt_embeds,
|
746 |
+
txt_ids=text_ids,
|
747 |
+
img_ids=latent_image_ids,
|
748 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
749 |
+
return_dict=False,
|
750 |
+
)[0]
|
751 |
+
|
752 |
+
if self.do_classifier_free_guidance:
|
753 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
754 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
755 |
+
|
756 |
+
# compute the previous noisy sample x_t -> x_t-1
|
757 |
+
latents_dtype = latents.dtype
|
758 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
759 |
+
|
760 |
+
if latents.dtype != latents_dtype:
|
761 |
+
if torch.backends.mps.is_available():
|
762 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
763 |
+
latents = latents.to(latents_dtype)
|
764 |
+
|
765 |
+
if callback_on_step_end is not None:
|
766 |
+
callback_kwargs = {}
|
767 |
+
for k in callback_on_step_end_tensor_inputs:
|
768 |
+
callback_kwargs[k] = locals()[k]
|
769 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
770 |
+
|
771 |
+
latents = callback_outputs.pop("latents", latents)
|
772 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
773 |
+
|
774 |
+
# call the callback, if provided
|
775 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
776 |
+
progress_bar.update()
|
777 |
+
|
778 |
+
if XLA_AVAILABLE:
|
779 |
+
xm.mark_step()
|
780 |
+
|
781 |
+
if output_type == "latent":
|
782 |
+
image = latents
|
783 |
+
|
784 |
+
else:
|
785 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
786 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
787 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
788 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
789 |
+
|
790 |
+
# Offload all models
|
791 |
+
self.maybe_free_model_hooks()
|
792 |
+
|
793 |
+
if not return_dict:
|
794 |
+
return (image,)
|
795 |
+
|
796 |
+
return FluxPipelineOutput(images=image)
|