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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 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 |
+
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
|
17 |
+
import torch
|
18 |
+
import numpy as np
|
19 |
+
import inspect
|
20 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
21 |
+
from diffusers.image_processor import PipelineImageInput
|
22 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
23 |
+
|
24 |
+
|
25 |
+
if is_torch_xla_available():
|
26 |
+
import torch_xla.core.xla_model as xm
|
27 |
+
|
28 |
+
XLA_AVAILABLE = True
|
29 |
+
else:
|
30 |
+
XLA_AVAILABLE = False
|
31 |
+
|
32 |
+
|
33 |
+
def pack_latents(latents, batch_size, num_channels_latents, height, width):
|
34 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
35 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
36 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
37 |
+
|
38 |
+
return latents
|
39 |
+
|
40 |
+
|
41 |
+
def unpack_latents(latents, height, width):
|
42 |
+
batch_size, num_patches, channels = latents.shape
|
43 |
+
|
44 |
+
assert height % 2 == 0 and width % 2 == 0
|
45 |
+
latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
|
46 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
47 |
+
|
48 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
|
49 |
+
|
50 |
+
return latents
|
51 |
+
|
52 |
+
|
53 |
+
def calculate_shift(
|
54 |
+
image_seq_len,
|
55 |
+
base_seq_len: int = 256,
|
56 |
+
max_seq_len: int = 4096,
|
57 |
+
base_shift: float = 0.5,
|
58 |
+
max_shift: float = 1.15,
|
59 |
+
):
|
60 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
61 |
+
b = base_shift - m * base_seq_len
|
62 |
+
mu = image_seq_len * m + b
|
63 |
+
return mu
|
64 |
+
|
65 |
+
|
66 |
+
def retrieve_timesteps(
|
67 |
+
scheduler,
|
68 |
+
num_inference_steps: Optional[int] = None,
|
69 |
+
device: Optional[Union[str, torch.device]] = None,
|
70 |
+
timesteps: Optional[List[int]] = None,
|
71 |
+
sigmas: Optional[List[float]] = None,
|
72 |
+
**kwargs,
|
73 |
+
):
|
74 |
+
r"""
|
75 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
76 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
77 |
+
|
78 |
+
Args:
|
79 |
+
scheduler (`SchedulerMixin`):
|
80 |
+
The scheduler to get timesteps from.
|
81 |
+
num_inference_steps (`int`):
|
82 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
83 |
+
must be `None`.
|
84 |
+
device (`str` or `torch.device`, *optional*):
|
85 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
86 |
+
timesteps (`List[int]`, *optional*):
|
87 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
88 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
89 |
+
sigmas (`List[float]`, *optional*):
|
90 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
91 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
92 |
+
|
93 |
+
Returns:
|
94 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
95 |
+
second element is the number of inference steps.
|
96 |
+
"""
|
97 |
+
if timesteps is not None and sigmas is not None:
|
98 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
99 |
+
if timesteps is not None:
|
100 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
101 |
+
if not accepts_timesteps:
|
102 |
+
raise ValueError(
|
103 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
104 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
105 |
+
)
|
106 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
107 |
+
timesteps = scheduler.timesteps
|
108 |
+
num_inference_steps = len(timesteps)
|
109 |
+
elif sigmas is not None:
|
110 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
111 |
+
if not accept_sigmas:
|
112 |
+
raise ValueError(
|
113 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
114 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
115 |
+
)
|
116 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
117 |
+
timesteps = scheduler.timesteps
|
118 |
+
num_inference_steps = len(timesteps)
|
119 |
+
else:
|
120 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
121 |
+
timesteps = scheduler.timesteps
|
122 |
+
return timesteps, num_inference_steps
|
123 |
+
|
124 |
+
def prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
125 |
+
latent_image_ids = torch.zeros(height, width, 3)
|
126 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
|
127 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
|
128 |
+
|
129 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
130 |
+
|
131 |
+
latent_image_ids = latent_image_ids.reshape(
|
132 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
133 |
+
)
|
134 |
+
|
135 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
136 |
+
|
137 |
+
|
138 |
+
@torch.no_grad()
|
139 |
+
def run(
|
140 |
+
self,
|
141 |
+
prompt: Union[str, List[str]] = None,
|
142 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
143 |
+
negative_prompt: Union[str, List[str]] = None,
|
144 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
145 |
+
true_cfg_scale: float = 1.0,
|
146 |
+
height: Optional[int] = None,
|
147 |
+
width: Optional[int] = None,
|
148 |
+
num_inference_steps: int = 28,
|
149 |
+
sigmas: Optional[List[float]] = None,
|
150 |
+
timesteps: Optional[List[float]] = None,
|
151 |
+
scales: List[float] = None,
|
152 |
+
guidance_scale: float = 3.5,
|
153 |
+
num_images_per_prompt: Optional[int] = 1,
|
154 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
155 |
+
latents: Optional[torch.FloatTensor] = None,
|
156 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
157 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
158 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
159 |
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
160 |
+
negative_ip_adapter_image: Optional[PipelineImageInput] = None,
|
161 |
+
negative_ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
162 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
163 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
164 |
+
output_type: Optional[str] = "pil",
|
165 |
+
return_dict: bool = True,
|
166 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
167 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
168 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
169 |
+
max_sequence_length: int = 512,
|
170 |
+
):
|
171 |
+
r"""
|
172 |
+
Function invoked when calling the pipeline for generation.
|
173 |
+
|
174 |
+
Args:
|
175 |
+
prompt (`str` or `List[str]`, *optional*):
|
176 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
177 |
+
instead.
|
178 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
179 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
180 |
+
will be used instead.
|
181 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
182 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
183 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
|
184 |
+
not greater than `1`).
|
185 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
186 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
187 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
188 |
+
true_cfg_scale (`float`, *optional*, defaults to 1.0):
|
189 |
+
When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
|
190 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
191 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
192 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
193 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
194 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
195 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
196 |
+
expense of slower inference.
|
197 |
+
sigmas (`List[float]`, *optional*):
|
198 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
199 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
200 |
+
will be used.
|
201 |
+
guidance_scale (`float`, *optional*, defaults to 3.5):
|
202 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
203 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
204 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
205 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
206 |
+
the text `prompt`, usually at the expense of lower image quality.
|
207 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
208 |
+
The number of images to generate per prompt.
|
209 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
210 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
211 |
+
to make generation deterministic.
|
212 |
+
latents (`torch.FloatTensor`, *optional*):
|
213 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
214 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
215 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
216 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
217 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
218 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
219 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
220 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
221 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
222 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
223 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
224 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
225 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
|
226 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
227 |
+
negative_ip_adapter_image:
|
228 |
+
(`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
229 |
+
negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
230 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
231 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
|
232 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
233 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
234 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
235 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
236 |
+
argument.
|
237 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
238 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
239 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
240 |
+
input argument.
|
241 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
242 |
+
The output format of the generate image. Choose between
|
243 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
244 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
245 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
246 |
+
joint_attention_kwargs (`dict`, *optional*):
|
247 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
248 |
+
`self.processor` in
|
249 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
250 |
+
callback_on_step_end (`Callable`, *optional*):
|
251 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
252 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
253 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
254 |
+
`callback_on_step_end_tensor_inputs`.
|
255 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
256 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
257 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
258 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
259 |
+
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
|
260 |
+
|
261 |
+
Examples:
|
262 |
+
|
263 |
+
Returns:
|
264 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
265 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
266 |
+
images.
|
267 |
+
"""
|
268 |
+
|
269 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
270 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
271 |
+
|
272 |
+
# 1. Check inputs. Raise error if not correct
|
273 |
+
self.check_inputs(
|
274 |
+
prompt,
|
275 |
+
prompt_2,
|
276 |
+
height,
|
277 |
+
width,
|
278 |
+
negative_prompt=negative_prompt,
|
279 |
+
negative_prompt_2=negative_prompt_2,
|
280 |
+
prompt_embeds=prompt_embeds,
|
281 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
282 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
283 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
284 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
285 |
+
max_sequence_length=max_sequence_length,
|
286 |
+
)
|
287 |
+
|
288 |
+
self._guidance_scale = guidance_scale
|
289 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
290 |
+
self._current_timestep = None
|
291 |
+
self._interrupt = False
|
292 |
+
|
293 |
+
# 2. Define call parameters
|
294 |
+
if prompt is not None and isinstance(prompt, str):
|
295 |
+
batch_size = 1
|
296 |
+
elif prompt is not None and isinstance(prompt, list):
|
297 |
+
batch_size = len(prompt)
|
298 |
+
else:
|
299 |
+
batch_size = prompt_embeds.shape[0]
|
300 |
+
|
301 |
+
device = self._execution_device
|
302 |
+
|
303 |
+
lora_scale = (
|
304 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
305 |
+
)
|
306 |
+
has_neg_prompt = negative_prompt is not None or (
|
307 |
+
negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
|
308 |
+
)
|
309 |
+
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
|
310 |
+
(
|
311 |
+
prompt_embeds,
|
312 |
+
pooled_prompt_embeds,
|
313 |
+
text_ids,
|
314 |
+
) = self.encode_prompt(
|
315 |
+
prompt=prompt,
|
316 |
+
prompt_2=prompt_2,
|
317 |
+
prompt_embeds=prompt_embeds,
|
318 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
319 |
+
device=device,
|
320 |
+
num_images_per_prompt=num_images_per_prompt,
|
321 |
+
max_sequence_length=max_sequence_length,
|
322 |
+
lora_scale=lora_scale,
|
323 |
+
)
|
324 |
+
if do_true_cfg:
|
325 |
+
(
|
326 |
+
negative_prompt_embeds,
|
327 |
+
negative_pooled_prompt_embeds,
|
328 |
+
negative_text_ids,
|
329 |
+
) = self.encode_prompt(
|
330 |
+
prompt=negative_prompt,
|
331 |
+
prompt_2=negative_prompt_2,
|
332 |
+
prompt_embeds=negative_prompt_embeds,
|
333 |
+
pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
334 |
+
device=device,
|
335 |
+
num_images_per_prompt=num_images_per_prompt,
|
336 |
+
max_sequence_length=max_sequence_length,
|
337 |
+
lora_scale=lora_scale,
|
338 |
+
)
|
339 |
+
|
340 |
+
# 4. Prepare latent variables
|
341 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
342 |
+
latents, latent_image_ids = self.prepare_latents(
|
343 |
+
batch_size * num_images_per_prompt,
|
344 |
+
num_channels_latents,
|
345 |
+
height,
|
346 |
+
width,
|
347 |
+
prompt_embeds.dtype,
|
348 |
+
device,
|
349 |
+
generator,
|
350 |
+
latents,
|
351 |
+
)
|
352 |
+
|
353 |
+
# 5. Prepare timesteps
|
354 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
355 |
+
image_seq_len = latents.shape[1]
|
356 |
+
mu = calculate_shift(
|
357 |
+
image_seq_len,
|
358 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
359 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
360 |
+
self.scheduler.config.get("base_shift", 0.5),
|
361 |
+
self.scheduler.config.get("max_shift", 1.15),
|
362 |
+
)
|
363 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
364 |
+
self.scheduler,
|
365 |
+
num_inference_steps,
|
366 |
+
device,
|
367 |
+
sigmas=sigmas,
|
368 |
+
mu=mu,
|
369 |
+
) if timesteps is None else (timesteps, len(timesteps))
|
370 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
371 |
+
self._num_timesteps = len(timesteps)
|
372 |
+
|
373 |
+
# handle guidance
|
374 |
+
if self.transformer.config.guidance_embeds:
|
375 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
376 |
+
guidance = guidance.expand(latents.shape[0])
|
377 |
+
else:
|
378 |
+
guidance = None
|
379 |
+
|
380 |
+
if (ip_adapter_image is not None or ip_adapter_image_embeds is not None) and (
|
381 |
+
negative_ip_adapter_image is None and negative_ip_adapter_image_embeds is None
|
382 |
+
):
|
383 |
+
negative_ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
|
384 |
+
negative_ip_adapter_image = [negative_ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
|
385 |
+
|
386 |
+
elif (ip_adapter_image is None and ip_adapter_image_embeds is None) and (
|
387 |
+
negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None
|
388 |
+
):
|
389 |
+
ip_adapter_image = np.zeros((width, height, 3), dtype=np.uint8)
|
390 |
+
ip_adapter_image = [ip_adapter_image] * self.transformer.encoder_hid_proj.num_ip_adapters
|
391 |
+
|
392 |
+
if self.joint_attention_kwargs is None:
|
393 |
+
self._joint_attention_kwargs = {}
|
394 |
+
|
395 |
+
image_embeds = None
|
396 |
+
negative_image_embeds = None
|
397 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
398 |
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
399 |
+
ip_adapter_image,
|
400 |
+
ip_adapter_image_embeds,
|
401 |
+
device,
|
402 |
+
batch_size * num_images_per_prompt,
|
403 |
+
)
|
404 |
+
if negative_ip_adapter_image is not None or negative_ip_adapter_image_embeds is not None:
|
405 |
+
negative_image_embeds = self.prepare_ip_adapter_image_embeds(
|
406 |
+
negative_ip_adapter_image,
|
407 |
+
negative_ip_adapter_image_embeds,
|
408 |
+
device,
|
409 |
+
batch_size * num_images_per_prompt,
|
410 |
+
)
|
411 |
+
|
412 |
+
# 6. Denoising loop
|
413 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
414 |
+
for i, t in enumerate(timesteps):
|
415 |
+
if self.interrupt:
|
416 |
+
continue
|
417 |
+
|
418 |
+
self._current_timestep = t
|
419 |
+
if image_embeds is not None:
|
420 |
+
self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds
|
421 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
422 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
423 |
+
|
424 |
+
noise_pred = self.transformer(
|
425 |
+
hidden_states=latents,
|
426 |
+
timestep=timestep / 1000,
|
427 |
+
guidance=guidance,
|
428 |
+
pooled_projections=pooled_prompt_embeds,
|
429 |
+
encoder_hidden_states=prompt_embeds,
|
430 |
+
txt_ids=text_ids,
|
431 |
+
img_ids=latent_image_ids,
|
432 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
433 |
+
return_dict=False,
|
434 |
+
)[0]
|
435 |
+
|
436 |
+
if do_true_cfg:
|
437 |
+
if negative_image_embeds is not None:
|
438 |
+
self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds
|
439 |
+
neg_noise_pred = self.transformer(
|
440 |
+
hidden_states=latents,
|
441 |
+
timestep=timestep / 1000,
|
442 |
+
guidance=guidance,
|
443 |
+
pooled_projections=negative_pooled_prompt_embeds,
|
444 |
+
encoder_hidden_states=negative_prompt_embeds,
|
445 |
+
txt_ids=negative_text_ids,
|
446 |
+
img_ids=latent_image_ids,
|
447 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
448 |
+
return_dict=False,
|
449 |
+
)[0]
|
450 |
+
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
|
451 |
+
|
452 |
+
# compute the previous noisy sample x_t -> x_t-1
|
453 |
+
if scales is None:
|
454 |
+
latents_dtype = latents.dtype
|
455 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
456 |
+
else:
|
457 |
+
latents_dtype = latents.dtype
|
458 |
+
sigma = sigmas[i]
|
459 |
+
sigma_next = sigmas[i + 1]
|
460 |
+
x0_pred = (latents - sigma * noise_pred)
|
461 |
+
x0_pred = unpack_latents(x0_pred, scales[i], scales[i])
|
462 |
+
if scales and i + 1 < len(scales):
|
463 |
+
x0_pred = torch.nn.functional.interpolate(x0_pred, size=scales[i + 1], mode='bicubic')
|
464 |
+
latent_image_ids = prepare_latent_image_ids(batch_size, scales[i + 1] // 2, scales[i + 1] // 2, device, prompt_embeds.dtype)
|
465 |
+
x0_pred = pack_latents(x0_pred, *x0_pred.shape)
|
466 |
+
noise = torch.randn(x0_pred.shape, generator=generator, dtype=x0_pred.dtype).to(x0_pred.device)
|
467 |
+
latents = (1 - sigma_next) * x0_pred + sigma_next * noise
|
468 |
+
|
469 |
+
if latents.dtype != latents_dtype:
|
470 |
+
if torch.backends.mps.is_available():
|
471 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
472 |
+
latents = latents.to(latents_dtype)
|
473 |
+
|
474 |
+
if callback_on_step_end is not None:
|
475 |
+
callback_kwargs = {}
|
476 |
+
for k in callback_on_step_end_tensor_inputs:
|
477 |
+
callback_kwargs[k] = locals()[k]
|
478 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
479 |
+
|
480 |
+
latents = callback_outputs.pop("latents", latents)
|
481 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
482 |
+
|
483 |
+
# call the callback, if provided
|
484 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
485 |
+
progress_bar.update()
|
486 |
+
|
487 |
+
if XLA_AVAILABLE:
|
488 |
+
xm.mark_step()
|
489 |
+
|
490 |
+
self._current_timestep = None
|
491 |
+
|
492 |
+
if output_type == "latent":
|
493 |
+
image = latents
|
494 |
+
else:
|
495 |
+
if scales is not None:
|
496 |
+
height, width = int(scales[-1] * 8), int(scales[-1] * 8)
|
497 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
498 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
499 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
500 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
501 |
+
|
502 |
+
# Offload all models
|
503 |
+
self.maybe_free_model_hooks()
|
504 |
+
|
505 |
+
if not return_dict:
|
506 |
+
return (image,)
|
507 |
+
|
508 |
+
return FluxPipelineOutput(images=image)
|