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inspect
|
2 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
7 |
+
|
8 |
+
from diffusers.image_processor import (VaeImageProcessor)
|
9 |
+
from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin
|
10 |
+
from diffusers.models.autoencoders import AutoencoderKL
|
11 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
12 |
+
from diffusers.utils import (
|
13 |
+
USE_PEFT_BACKEND,
|
14 |
+
is_torch_xla_available,
|
15 |
+
logging,
|
16 |
+
scale_lora_layers,
|
17 |
+
unscale_lora_layers,
|
18 |
+
)
|
19 |
+
from diffusers.utils.torch_utils import randn_tensor
|
20 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
21 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
22 |
+
from torchvision.transforms.functional import pad
|
23 |
+
from diffusers import FluxTransformer2DModel
|
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 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
33 |
+
|
34 |
+
def calculate_shift(
|
35 |
+
image_seq_len,
|
36 |
+
base_seq_len: int = 256,
|
37 |
+
max_seq_len: int = 4096,
|
38 |
+
base_shift: float = 0.5,
|
39 |
+
max_shift: float = 1.16,
|
40 |
+
):
|
41 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
42 |
+
b = base_shift - m * base_seq_len
|
43 |
+
mu = image_seq_len * m + b
|
44 |
+
return mu
|
45 |
+
|
46 |
+
def prepare_latent_image_ids_(height, width, device, dtype):
|
47 |
+
latent_image_ids = torch.zeros(height//2, width//2, 3, device=device, dtype=dtype)
|
48 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height//2, device=device)[:, None] # y
|
49 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width//2, device=device)[None, :] # x
|
50 |
+
return latent_image_ids
|
51 |
+
|
52 |
+
def prepare_latent_subject_ids(height, width, device, dtype):
|
53 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3, device=device, dtype=dtype)
|
54 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2, device=device)[:, None]
|
55 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2, device=device)[None, :]
|
56 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
57 |
+
latent_image_ids = latent_image_ids.reshape(
|
58 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
59 |
+
)
|
60 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
61 |
+
|
62 |
+
def resize_position_encoding(batch_size, original_height, original_width, target_height, target_width, device, dtype):
|
63 |
+
latent_image_ids = prepare_latent_image_ids_(original_height, original_width, device, dtype)
|
64 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
65 |
+
latent_image_ids = latent_image_ids.reshape(
|
66 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
67 |
+
)
|
68 |
+
|
69 |
+
scale_h = original_height / target_height
|
70 |
+
scale_w = original_width / target_width
|
71 |
+
latent_image_ids_resized = torch.zeros(target_height//2, target_width//2, 3, device=device, dtype=dtype)
|
72 |
+
latent_image_ids_resized[..., 1] = latent_image_ids_resized[..., 1] + torch.arange(target_height//2, device=device)[:, None] * scale_h
|
73 |
+
latent_image_ids_resized[..., 2] = latent_image_ids_resized[..., 2] + torch.arange(target_width//2, device=device)[None, :] * scale_w
|
74 |
+
|
75 |
+
cond_latent_image_id_height, cond_latent_image_id_width, cond_latent_image_id_channels = latent_image_ids_resized.shape
|
76 |
+
cond_latent_image_ids = latent_image_ids_resized.reshape(
|
77 |
+
cond_latent_image_id_height * cond_latent_image_id_width, cond_latent_image_id_channels
|
78 |
+
)
|
79 |
+
return latent_image_ids, cond_latent_image_ids
|
80 |
+
|
81 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
82 |
+
def retrieve_latents(
|
83 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
84 |
+
):
|
85 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
86 |
+
return encoder_output.latent_dist.sample(generator)
|
87 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
88 |
+
return encoder_output.latent_dist.mode()
|
89 |
+
elif hasattr(encoder_output, "latents"):
|
90 |
+
return encoder_output.latents
|
91 |
+
else:
|
92 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
93 |
+
|
94 |
+
|
95 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
96 |
+
def retrieve_timesteps(
|
97 |
+
scheduler,
|
98 |
+
num_inference_steps: Optional[int] = None,
|
99 |
+
device: Optional[Union[str, torch.device]] = None,
|
100 |
+
timesteps: Optional[List[int]] = None,
|
101 |
+
sigmas: Optional[List[float]] = None,
|
102 |
+
**kwargs,
|
103 |
+
):
|
104 |
+
if timesteps is not None and sigmas is not None:
|
105 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
106 |
+
if timesteps is not None:
|
107 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
108 |
+
if not accepts_timesteps:
|
109 |
+
raise ValueError(
|
110 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
111 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
112 |
+
)
|
113 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
114 |
+
timesteps = scheduler.timesteps
|
115 |
+
num_inference_steps = len(timesteps)
|
116 |
+
elif sigmas is not None:
|
117 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
118 |
+
if not accept_sigmas:
|
119 |
+
raise ValueError(
|
120 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
121 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
122 |
+
)
|
123 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
124 |
+
timesteps = scheduler.timesteps
|
125 |
+
num_inference_steps = len(timesteps)
|
126 |
+
else:
|
127 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
128 |
+
timesteps = scheduler.timesteps
|
129 |
+
return timesteps, num_inference_steps
|
130 |
+
|
131 |
+
|
132 |
+
class FluxPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
|
133 |
+
def __init__(
|
134 |
+
self,
|
135 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
136 |
+
vae: AutoencoderKL,
|
137 |
+
text_encoder: CLIPTextModel,
|
138 |
+
tokenizer: CLIPTokenizer,
|
139 |
+
text_encoder_2: T5EncoderModel,
|
140 |
+
tokenizer_2: T5TokenizerFast,
|
141 |
+
transformer: FluxTransformer2DModel,
|
142 |
+
):
|
143 |
+
super().__init__()
|
144 |
+
|
145 |
+
self.register_modules(
|
146 |
+
vae=vae,
|
147 |
+
text_encoder=text_encoder,
|
148 |
+
text_encoder_2=text_encoder_2,
|
149 |
+
tokenizer=tokenizer,
|
150 |
+
tokenizer_2=tokenizer_2,
|
151 |
+
transformer=transformer,
|
152 |
+
scheduler=scheduler,
|
153 |
+
)
|
154 |
+
self.vae_scale_factor = (
|
155 |
+
2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
|
156 |
+
)
|
157 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
158 |
+
self.tokenizer_max_length = (
|
159 |
+
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
|
160 |
+
)
|
161 |
+
self.default_sample_size = 64
|
162 |
+
|
163 |
+
def _get_t5_prompt_embeds(
|
164 |
+
self,
|
165 |
+
prompt: Union[str, List[str]] = None,
|
166 |
+
num_images_per_prompt: int = 1,
|
167 |
+
max_sequence_length: int = 512,
|
168 |
+
device: Optional[torch.device] = None,
|
169 |
+
dtype: Optional[torch.dtype] = None,
|
170 |
+
):
|
171 |
+
device = device or self._execution_device
|
172 |
+
dtype = dtype or self.text_encoder.dtype
|
173 |
+
|
174 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
175 |
+
batch_size = len(prompt)
|
176 |
+
|
177 |
+
text_inputs = self.tokenizer_2(
|
178 |
+
prompt,
|
179 |
+
padding="max_length",
|
180 |
+
max_length=max_sequence_length,
|
181 |
+
truncation=True,
|
182 |
+
return_length=False,
|
183 |
+
return_overflowing_tokens=False,
|
184 |
+
return_tensors="pt",
|
185 |
+
)
|
186 |
+
text_input_ids = text_inputs.input_ids
|
187 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
188 |
+
|
189 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
190 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
|
191 |
+
logger.warning(
|
192 |
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
193 |
+
f" {max_sequence_length} tokens: {removed_text}"
|
194 |
+
)
|
195 |
+
|
196 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
|
197 |
+
|
198 |
+
dtype = self.text_encoder_2.dtype
|
199 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
200 |
+
|
201 |
+
_, seq_len, _ = prompt_embeds.shape
|
202 |
+
|
203 |
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
204 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
205 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
206 |
+
|
207 |
+
return prompt_embeds
|
208 |
+
|
209 |
+
def _get_clip_prompt_embeds(
|
210 |
+
self,
|
211 |
+
prompt: Union[str, List[str]],
|
212 |
+
num_images_per_prompt: int = 1,
|
213 |
+
device: Optional[torch.device] = None,
|
214 |
+
):
|
215 |
+
device = device or self._execution_device
|
216 |
+
|
217 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
218 |
+
batch_size = len(prompt)
|
219 |
+
|
220 |
+
text_inputs = self.tokenizer(
|
221 |
+
prompt,
|
222 |
+
padding="max_length",
|
223 |
+
max_length=self.tokenizer_max_length,
|
224 |
+
truncation=True,
|
225 |
+
return_overflowing_tokens=False,
|
226 |
+
return_length=False,
|
227 |
+
return_tensors="pt",
|
228 |
+
)
|
229 |
+
|
230 |
+
text_input_ids = text_inputs.input_ids
|
231 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
232 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
233 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1: -1])
|
234 |
+
logger.warning(
|
235 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
236 |
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
237 |
+
)
|
238 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
|
239 |
+
|
240 |
+
# Use pooled output of CLIPTextModel
|
241 |
+
prompt_embeds = prompt_embeds.pooler_output
|
242 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
243 |
+
|
244 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
245 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
|
246 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
247 |
+
|
248 |
+
return prompt_embeds
|
249 |
+
|
250 |
+
def encode_prompt(
|
251 |
+
self,
|
252 |
+
prompt: Union[str, List[str]],
|
253 |
+
prompt_2: Union[str, List[str]],
|
254 |
+
device: Optional[torch.device] = None,
|
255 |
+
num_images_per_prompt: int = 1,
|
256 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
257 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
258 |
+
max_sequence_length: int = 512,
|
259 |
+
lora_scale: Optional[float] = None,
|
260 |
+
):
|
261 |
+
device = device or self._execution_device
|
262 |
+
|
263 |
+
# set lora scale so that monkey patched LoRA
|
264 |
+
# function of text encoder can correctly access it
|
265 |
+
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
|
266 |
+
self._lora_scale = lora_scale
|
267 |
+
|
268 |
+
# dynamically adjust the LoRA scale
|
269 |
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
270 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
271 |
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
272 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
273 |
+
|
274 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
275 |
+
|
276 |
+
if prompt_embeds is None:
|
277 |
+
prompt_2 = prompt_2 or prompt
|
278 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
279 |
+
|
280 |
+
# We only use the pooled prompt output from the CLIPTextModel
|
281 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
282 |
+
prompt=prompt,
|
283 |
+
device=device,
|
284 |
+
num_images_per_prompt=num_images_per_prompt,
|
285 |
+
)
|
286 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
287 |
+
prompt=prompt_2,
|
288 |
+
num_images_per_prompt=num_images_per_prompt,
|
289 |
+
max_sequence_length=max_sequence_length,
|
290 |
+
device=device,
|
291 |
+
)
|
292 |
+
|
293 |
+
if self.text_encoder is not None:
|
294 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
295 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
296 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
297 |
+
|
298 |
+
if self.text_encoder_2 is not None:
|
299 |
+
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
|
300 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
301 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
302 |
+
|
303 |
+
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
|
304 |
+
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
|
305 |
+
|
306 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
307 |
+
|
308 |
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
|
309 |
+
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
|
310 |
+
if isinstance(generator, list):
|
311 |
+
image_latents = [
|
312 |
+
retrieve_latents(self.vae.encode(image[i: i + 1]), generator=generator[i])
|
313 |
+
for i in range(image.shape[0])
|
314 |
+
]
|
315 |
+
image_latents = torch.cat(image_latents, dim=0)
|
316 |
+
else:
|
317 |
+
image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
318 |
+
|
319 |
+
image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
320 |
+
|
321 |
+
return image_latents
|
322 |
+
|
323 |
+
def check_inputs(
|
324 |
+
self,
|
325 |
+
prompt,
|
326 |
+
prompt_2,
|
327 |
+
height,
|
328 |
+
width,
|
329 |
+
prompt_embeds=None,
|
330 |
+
pooled_prompt_embeds=None,
|
331 |
+
callback_on_step_end_tensor_inputs=None,
|
332 |
+
max_sequence_length=None,
|
333 |
+
):
|
334 |
+
if height % 8 != 0 or width % 8 != 0:
|
335 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
336 |
+
|
337 |
+
if prompt is not None and prompt_embeds is not None:
|
338 |
+
raise ValueError(
|
339 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
340 |
+
" only forward one of the two."
|
341 |
+
)
|
342 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
343 |
+
raise ValueError(
|
344 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
345 |
+
" only forward one of the two."
|
346 |
+
)
|
347 |
+
elif prompt is None and prompt_embeds is None:
|
348 |
+
raise ValueError(
|
349 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
350 |
+
)
|
351 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
352 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
353 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
354 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
355 |
+
|
356 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
357 |
+
raise ValueError(
|
358 |
+
"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`."
|
359 |
+
)
|
360 |
+
|
361 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
362 |
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
363 |
+
|
364 |
+
@staticmethod
|
365 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
366 |
+
latent_image_ids = torch.zeros(height // 2, width // 2, 3)
|
367 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
|
368 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
|
369 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
370 |
+
latent_image_ids = latent_image_ids.reshape(
|
371 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
372 |
+
)
|
373 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
377 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
378 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
379 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
380 |
+
return latents
|
381 |
+
|
382 |
+
@staticmethod
|
383 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
384 |
+
batch_size, num_patches, channels = latents.shape
|
385 |
+
|
386 |
+
height = height // vae_scale_factor
|
387 |
+
width = width // vae_scale_factor
|
388 |
+
|
389 |
+
latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
|
390 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
391 |
+
|
392 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
|
393 |
+
|
394 |
+
return latents
|
395 |
+
|
396 |
+
def enable_vae_slicing(self):
|
397 |
+
r"""
|
398 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
399 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
400 |
+
"""
|
401 |
+
self.vae.enable_slicing()
|
402 |
+
|
403 |
+
def disable_vae_slicing(self):
|
404 |
+
r"""
|
405 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
406 |
+
computing decoding in one step.
|
407 |
+
"""
|
408 |
+
self.vae.disable_slicing()
|
409 |
+
|
410 |
+
def enable_vae_tiling(self):
|
411 |
+
r"""
|
412 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
413 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
414 |
+
processing larger images.
|
415 |
+
"""
|
416 |
+
self.vae.enable_tiling()
|
417 |
+
|
418 |
+
def disable_vae_tiling(self):
|
419 |
+
r"""
|
420 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
421 |
+
computing decoding in one step.
|
422 |
+
"""
|
423 |
+
self.vae.disable_tiling()
|
424 |
+
|
425 |
+
def prepare_latents(
|
426 |
+
self,
|
427 |
+
batch_size,
|
428 |
+
num_channels_latents,
|
429 |
+
height,
|
430 |
+
width,
|
431 |
+
dtype,
|
432 |
+
device,
|
433 |
+
generator,
|
434 |
+
subject_image,
|
435 |
+
condition_image,
|
436 |
+
latents=None,
|
437 |
+
cond_number=1,
|
438 |
+
sub_number=1
|
439 |
+
):
|
440 |
+
height_cond = 2 * (self.cond_size // self.vae_scale_factor)
|
441 |
+
width_cond = 2 * (self.cond_size // self.vae_scale_factor)
|
442 |
+
height = 2 * (int(height) // self.vae_scale_factor)
|
443 |
+
width = 2 * (int(width) // self.vae_scale_factor)
|
444 |
+
|
445 |
+
shape = (batch_size, num_channels_latents, height, width) # 1 16 106 80
|
446 |
+
noise_latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
447 |
+
noise_latents = self._pack_latents(noise_latents, batch_size, num_channels_latents, height, width)
|
448 |
+
noise_latent_image_ids, cond_latent_image_ids = resize_position_encoding(
|
449 |
+
batch_size,
|
450 |
+
height,
|
451 |
+
width,
|
452 |
+
height_cond,
|
453 |
+
width_cond,
|
454 |
+
device,
|
455 |
+
dtype,
|
456 |
+
)
|
457 |
+
|
458 |
+
latents_to_concat = []
|
459 |
+
latents_ids_to_concat = [noise_latent_image_ids]
|
460 |
+
|
461 |
+
# subject
|
462 |
+
if subject_image is not None:
|
463 |
+
shape_subject = (batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
464 |
+
subject_image = subject_image.to(device=device, dtype=dtype)
|
465 |
+
subject_image_latents = self._encode_vae_image(image=subject_image, generator=generator)
|
466 |
+
subject_latents = self._pack_latents(subject_image_latents, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
467 |
+
mask2 = torch.zeros(shape_subject, device=device, dtype=dtype)
|
468 |
+
mask2 = self._pack_latents(mask2, batch_size, num_channels_latents, height_cond*sub_number, width_cond)
|
469 |
+
latent_subject_ids = prepare_latent_subject_ids(height_cond, width_cond, device, dtype)
|
470 |
+
latent_subject_ids[:, 1] += 64 # fixed offset
|
471 |
+
subject_latent_image_ids = torch.concat([latent_subject_ids for _ in range(sub_number)], dim=-2)
|
472 |
+
latents_to_concat.append(subject_latents)
|
473 |
+
latents_ids_to_concat.append(subject_latent_image_ids)
|
474 |
+
|
475 |
+
# spatial
|
476 |
+
if condition_image is not None:
|
477 |
+
shape_cond = (batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
478 |
+
condition_image = condition_image.to(device=device, dtype=dtype)
|
479 |
+
image_latents = self._encode_vae_image(image=condition_image, generator=generator)
|
480 |
+
cond_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
481 |
+
mask3 = torch.zeros(shape_cond, device=device, dtype=dtype)
|
482 |
+
mask3 = self._pack_latents(mask3, batch_size, num_channels_latents, height_cond*cond_number, width_cond)
|
483 |
+
cond_latent_image_ids = cond_latent_image_ids
|
484 |
+
cond_latent_image_ids = torch.concat([cond_latent_image_ids for _ in range(cond_number)], dim=-2)
|
485 |
+
latents_ids_to_concat.append(cond_latent_image_ids)
|
486 |
+
latents_to_concat.append(cond_latents)
|
487 |
+
|
488 |
+
cond_latents = torch.concat(latents_to_concat, dim=-2)
|
489 |
+
latent_image_ids = torch.concat(latents_ids_to_concat, dim=-2)
|
490 |
+
return cond_latents, latent_image_ids, noise_latents
|
491 |
+
|
492 |
+
@property
|
493 |
+
def guidance_scale(self):
|
494 |
+
return self._guidance_scale
|
495 |
+
|
496 |
+
@property
|
497 |
+
def joint_attention_kwargs(self):
|
498 |
+
return self._joint_attention_kwargs
|
499 |
+
|
500 |
+
@property
|
501 |
+
def num_timesteps(self):
|
502 |
+
return self._num_timesteps
|
503 |
+
|
504 |
+
@property
|
505 |
+
def interrupt(self):
|
506 |
+
return self._interrupt
|
507 |
+
|
508 |
+
@torch.no_grad()
|
509 |
+
def __call__(
|
510 |
+
self,
|
511 |
+
prompt: Union[str, List[str]] = None,
|
512 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
513 |
+
height: Optional[int] = None,
|
514 |
+
width: Optional[int] = None,
|
515 |
+
num_inference_steps: int = 28,
|
516 |
+
timesteps: List[int] = None,
|
517 |
+
guidance_scale: float = 3.5,
|
518 |
+
num_images_per_prompt: Optional[int] = 1,
|
519 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
520 |
+
latents: Optional[torch.FloatTensor] = None,
|
521 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
522 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
523 |
+
output_type: Optional[str] = "pil",
|
524 |
+
return_dict: bool = True,
|
525 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
526 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
527 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
528 |
+
max_sequence_length: int = 512,
|
529 |
+
spatial_images=[],
|
530 |
+
subject_images=[],
|
531 |
+
cond_size=512,
|
532 |
+
):
|
533 |
+
|
534 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
535 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
536 |
+
self.cond_size = cond_size
|
537 |
+
|
538 |
+
# 1. Check inputs. Raise error if not correct
|
539 |
+
self.check_inputs(
|
540 |
+
prompt,
|
541 |
+
prompt_2,
|
542 |
+
height,
|
543 |
+
width,
|
544 |
+
prompt_embeds=prompt_embeds,
|
545 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
546 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
547 |
+
max_sequence_length=max_sequence_length,
|
548 |
+
)
|
549 |
+
|
550 |
+
self._guidance_scale = guidance_scale
|
551 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
552 |
+
self._interrupt = False
|
553 |
+
|
554 |
+
cond_number = len(spatial_images)
|
555 |
+
sub_number = len(subject_images)
|
556 |
+
|
557 |
+
if sub_number > 0:
|
558 |
+
subject_image_ls = []
|
559 |
+
for subject_image in subject_images:
|
560 |
+
w, h = subject_image.size[:2]
|
561 |
+
scale = self.cond_size / max(h, w)
|
562 |
+
new_h, new_w = int(h * scale), int(w * scale)
|
563 |
+
subject_image = self.image_processor.preprocess(subject_image, height=new_h, width=new_w)
|
564 |
+
subject_image = subject_image.to(dtype=torch.float32)
|
565 |
+
pad_h = cond_size - subject_image.shape[-2]
|
566 |
+
pad_w = cond_size - subject_image.shape[-1]
|
567 |
+
subject_image = pad(
|
568 |
+
subject_image,
|
569 |
+
padding=(int(pad_w / 2), int(pad_h / 2), int(pad_w / 2), int(pad_h / 2)),
|
570 |
+
fill=0
|
571 |
+
)
|
572 |
+
subject_image_ls.append(subject_image)
|
573 |
+
subject_image = torch.concat(subject_image_ls, dim=-2)
|
574 |
+
else:
|
575 |
+
subject_image = None
|
576 |
+
|
577 |
+
if cond_number > 0:
|
578 |
+
condition_image_ls = []
|
579 |
+
for img in spatial_images:
|
580 |
+
print(img)
|
581 |
+
condition_image = self.image_processor.preprocess(img, height=self.cond_size, width=self.cond_size)
|
582 |
+
condition_image = condition_image.to(dtype=torch.float32)
|
583 |
+
condition_image_ls.append(condition_image)
|
584 |
+
condition_image = torch.concat(condition_image_ls, dim=-2)
|
585 |
+
else:
|
586 |
+
condition_image = None
|
587 |
+
|
588 |
+
# 2. Define call parameters
|
589 |
+
if prompt is not None and isinstance(prompt, str):
|
590 |
+
batch_size = 1
|
591 |
+
elif prompt is not None and isinstance(prompt, list):
|
592 |
+
batch_size = len(prompt)
|
593 |
+
else:
|
594 |
+
batch_size = prompt_embeds.shape[0]
|
595 |
+
|
596 |
+
device = self._execution_device
|
597 |
+
|
598 |
+
lora_scale = (
|
599 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
600 |
+
)
|
601 |
+
(
|
602 |
+
prompt_embeds,
|
603 |
+
pooled_prompt_embeds,
|
604 |
+
text_ids,
|
605 |
+
) = self.encode_prompt(
|
606 |
+
prompt=prompt,
|
607 |
+
prompt_2=prompt_2,
|
608 |
+
prompt_embeds=prompt_embeds,
|
609 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
610 |
+
device=device,
|
611 |
+
num_images_per_prompt=num_images_per_prompt,
|
612 |
+
max_sequence_length=max_sequence_length,
|
613 |
+
lora_scale=lora_scale,
|
614 |
+
)
|
615 |
+
|
616 |
+
# 4. Prepare latent variables
|
617 |
+
num_channels_latents = self.transformer.config.in_channels // 4 # 16
|
618 |
+
cond_latents, latent_image_ids, noise_latents = self.prepare_latents(
|
619 |
+
batch_size * num_images_per_prompt,
|
620 |
+
num_channels_latents,
|
621 |
+
height,
|
622 |
+
width,
|
623 |
+
prompt_embeds.dtype,
|
624 |
+
device,
|
625 |
+
generator,
|
626 |
+
subject_image,
|
627 |
+
condition_image,
|
628 |
+
latents,
|
629 |
+
cond_number,
|
630 |
+
sub_number
|
631 |
+
)
|
632 |
+
latents = noise_latents
|
633 |
+
# 5. Prepare timesteps
|
634 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
635 |
+
image_seq_len = latents.shape[1]
|
636 |
+
mu = calculate_shift(
|
637 |
+
image_seq_len,
|
638 |
+
self.scheduler.config.base_image_seq_len,
|
639 |
+
self.scheduler.config.max_image_seq_len,
|
640 |
+
self.scheduler.config.base_shift,
|
641 |
+
self.scheduler.config.max_shift,
|
642 |
+
)
|
643 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
644 |
+
self.scheduler,
|
645 |
+
num_inference_steps,
|
646 |
+
device,
|
647 |
+
timesteps,
|
648 |
+
sigmas,
|
649 |
+
mu=mu,
|
650 |
+
)
|
651 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
652 |
+
self._num_timesteps = len(timesteps)
|
653 |
+
|
654 |
+
# handle guidance
|
655 |
+
if self.transformer.config.guidance_embeds:
|
656 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
657 |
+
guidance = guidance.expand(latents.shape[0])
|
658 |
+
else:
|
659 |
+
guidance = None
|
660 |
+
|
661 |
+
## Caching conditions
|
662 |
+
# clean the cache
|
663 |
+
try:
|
664 |
+
for name, attn_processor in self.transformer.attn_processors.items():
|
665 |
+
attn_processor.bank_kv.clear()
|
666 |
+
except:
|
667 |
+
pass
|
668 |
+
# cache with warmup latents
|
669 |
+
t = torch.tensor([timesteps[0]], device=device)
|
670 |
+
timestep = t.expand(cond_latents.shape[0]).to(latents.dtype)
|
671 |
+
warmup_image_ids = latent_image_ids[latents.shape[1]:, :]
|
672 |
+
_ = self.transformer(
|
673 |
+
hidden_states=cond_latents,
|
674 |
+
timestep=torch.ones_like(timestep) * 0,
|
675 |
+
guidance=guidance,
|
676 |
+
pooled_projections=pooled_prompt_embeds,
|
677 |
+
encoder_hidden_states=prompt_embeds,
|
678 |
+
txt_ids=text_ids,
|
679 |
+
img_ids=warmup_image_ids,
|
680 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
681 |
+
return_dict=False,
|
682 |
+
)[0]
|
683 |
+
|
684 |
+
del cond_latents, spatial_images, condition_image, condition_image_ls, img, _
|
685 |
+
torch.cuda.empty_cache()
|
686 |
+
|
687 |
+
# 6. Denoising loop
|
688 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
689 |
+
for i, t in enumerate(timesteps):
|
690 |
+
if self.interrupt:
|
691 |
+
continue
|
692 |
+
|
693 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
694 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
695 |
+
noise_pred = self.transformer(
|
696 |
+
hidden_states=latents,
|
697 |
+
timestep=timestep / 1000,
|
698 |
+
guidance=guidance,
|
699 |
+
pooled_projections=pooled_prompt_embeds,
|
700 |
+
encoder_hidden_states=prompt_embeds,
|
701 |
+
txt_ids=text_ids,
|
702 |
+
img_ids=latent_image_ids,
|
703 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
704 |
+
return_dict=False,
|
705 |
+
)[0]
|
706 |
+
|
707 |
+
# compute the previous noisy sample x_t -> x_t-1
|
708 |
+
latents_dtype = latents.dtype
|
709 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
710 |
+
|
711 |
+
if latents.dtype != latents_dtype:
|
712 |
+
if torch.backends.mps.is_available():
|
713 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
714 |
+
latents = latents.to(latents_dtype)
|
715 |
+
|
716 |
+
if callback_on_step_end is not None:
|
717 |
+
callback_kwargs = {}
|
718 |
+
for k in callback_on_step_end_tensor_inputs:
|
719 |
+
callback_kwargs[k] = locals()[k]
|
720 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
721 |
+
|
722 |
+
latents = callback_outputs.pop("latents", latents)
|
723 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
724 |
+
|
725 |
+
# call the callback, if provided
|
726 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
727 |
+
progress_bar.update()
|
728 |
+
|
729 |
+
if XLA_AVAILABLE:
|
730 |
+
xm.mark_step()
|
731 |
+
|
732 |
+
if output_type == "latent":
|
733 |
+
image = latents
|
734 |
+
else:
|
735 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
736 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
737 |
+
image = self.vae.decode(latents.to(dtype=self.vae.dtype), return_dict=False)[0]
|
738 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
739 |
+
|
740 |
+
# Offload all models
|
741 |
+
self.maybe_free_model_hooks()
|
742 |
+
|
743 |
+
if not return_dict:
|
744 |
+
return (image,)
|
745 |
+
|
746 |
+
return FluxPipelineOutput(images=image)
|