AlekseyCalvin commited on
Commit
a293504
1 Parent(s): ca9e247

Upload pipeline_flux.py

Browse files
Files changed (1) hide show
  1. pipeline_flux.py +773 -0
pipeline_flux.py ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
21
+
22
+ from ...image_processor import VaeImageProcessor
23
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin
24
+ from ...models.autoencoders import AutoencoderKL
25
+ from ...models.transformers import FluxTransformer2DModel
26
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
27
+ from ...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 ...utils.torch_utils
36
+ from ..pipeline_utils import DiffusionPipeline
37
+ from .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"] model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
170
+ _optional_components = []
171
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
172
+
173
+ def __init__(
174
+ self,
175
+ scheduler: FlowMatchEulerDiscreteScheduler,
176
+ vae: AutoencoderKL,
177
+ text_encoder: CLIPTextModel,
178
+ tokenizer: CLIPTokenizer,
179
+ text_encoder_2: T5EncoderModel,
180
+ tokenizer_2: T5TokenizerFast,
181
+ transformer: FluxTransformer2DModel,
182
+ ):
183
+ super().__init__()
184
+
185
+ self.register_modules(
186
+ vae=vae,
187
+ text_encoder=text_encoder,
188
+ text_encoder_2=text_encoder_2,
189
+ tokenizer=tokenizer,
190
+ tokenizer_2=tokenizer_2,
191
+ transformer=transformer,
192
+ scheduler=scheduler,
193
+ )
194
+ self.vae_scale_factor = (
195
+ 2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
196
+ )
197
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
198
+ self.tokenizer_max_length = (
199
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
200
+ )
201
+ self.default_sample_size = 64
202
+
203
+ def _get_t5_prompt_embeds(
204
+ self,
205
+ prompt: Union[str, List[str]] = None,
206
+ num_images_per_prompt: int = 1,
207
+ max_sequence_length: int = 512,
208
+ device: Optional[torch.device] = None,
209
+ dtype: Optional[torch.dtype] = None,
210
+ ):
211
+ device = device or self._execution_device
212
+ dtype = dtype or self.text_encoder.dtype
213
+
214
+ prompt = [prompt] if isinstance(prompt, str) else prompt
215
+ batch_size = len(prompt)
216
+
217
+ text_inputs = self.tokenizer_2(
218
+ prompt,
219
+ padding="max_length",
220
+ max_length=max_sequence_length,
221
+ truncation=True,
222
+ return_length=False,
223
+ return_overflowing_tokens=False,
224
+ return_tensors="pt",
225
+ )
226
+ text_input_ids = text_inputs.input_ids
227
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
228
+
229
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
230
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
231
+ logger.warning(
232
+ "The following part of your input was truncated because `max_sequence_length` is set to "
233
+ f" {max_sequence_length} tokens: {removed_text}"
234
+ )
235
+
236
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
237
+
238
+ dtype = self.text_encoder_2.dtype
239
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
240
+
241
+ _, seq_len, _ = prompt_embeds.shape
242
+
243
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
244
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
245
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
246
+
247
+ return prompt_embeds
248
+
249
+ def _get_clip_prompt_embeds(
250
+ self,
251
+ prompt: Union[str, List[str]],
252
+ num_images_per_prompt: int = 1,
253
+ device: Optional[torch.device] = None,
254
+ ):
255
+ device = device or self._execution_device
256
+
257
+ prompt = [prompt] if isinstance(prompt, str) else prompt
258
+ batch_size = len(prompt)
259
+
260
+ text_inputs = self.tokenizer(
261
+ prompt,
262
+ padding="max_length",
263
+ max_length=self.tokenizer_max_length,
264
+ truncation=True,
265
+ return_overflowing_tokens=False,
266
+ return_length=False,
267
+ return_tensors="pt",
268
+ )
269
+
270
+ text_input_ids = text_inputs.input_ids
271
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
272
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
273
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
274
+ logger.warning(
275
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
276
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
277
+ )
278
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
279
+
280
+ # Use pooled output of CLIPTextModel
281
+ prompt_embeds = prompt_embeds.pooler_output
282
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
283
+
284
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
285
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
286
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
287
+
288
+ return prompt_embeds
289
+
290
+ def encode_prompt(
291
+ self,
292
+ prompt: Union[str, List[str]],
293
+ prompt_2: Union[str, List[str]],
294
+ device: Optional[torch.device] = None,
295
+ num_images_per_prompt: int = 1,
296
+ prompt_embeds: Optional[torch.FloatTensor] = None,
297
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
298
+ max_sequence_length: int = 512,
299
+ lora_scale: Optional[float] = None,
300
+ ):
301
+ r"""
302
+
303
+ Args:
304
+ prompt (`str` or `List[str]`, *optional*):
305
+ prompt to be encoded
306
+ prompt_2 (`str` or `List[str]`, *optional*):
307
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
308
+ used in all text-encoders
309
+ device: (`torch.device`):
310
+ torch device
311
+ num_images_per_prompt (`int`):
312
+ number of images that should be generated per prompt
313
+ prompt_embeds (`torch.FloatTensor`, *optional*):
314
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
315
+ provided, text embeddings will be generated from `prompt` input argument.
316
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
317
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
318
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
319
+ lora_scale (`float`, *optional*):
320
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
321
+ """
322
+ device = device or self._execution_device
323
+
324
+ # set lora scale so that monkey patched LoRA
325
+ # function of text encoder can correctly access it
326
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
327
+ self._lora_scale = lora_scale
328
+
329
+ # dynamically adjust the LoRA scale
330
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
331
+ scale_lora_layers(self.text_encoder, lora_scale)
332
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
333
+ scale_lora_layers(self.text_encoder_2, lora_scale)
334
+
335
+ prompt = [prompt] if isinstance(prompt, str) else 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
+ if self.text_encoder is not None:
355
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
356
+ # Retrieve the original scale by scaling back the LoRA layers
357
+ unscale_lora_layers(self.text_encoder, lora_scale)
358
+
359
+ if self.text_encoder_2 is not None:
360
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
361
+ # Retrieve the original scale by scaling back the LoRA layers
362
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
363
+
364
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
365
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
366
+
367
+ return prompt_embeds, pooled_prompt_embeds, text_ids
368
+
369
+ def check_inputs(
370
+ self,
371
+ prompt,
372
+ prompt_2,
373
+ height,
374
+ width,
375
+ prompt_embeds=None,
376
+ pooled_prompt_embeds=None,
377
+ callback_on_step_end_tensor_inputs=None,
378
+ max_sequence_length=None,
379
+ ):
380
+ if height % 8 != 0 or width % 8 != 0:
381
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
382
+
383
+ if callback_on_step_end_tensor_inputs is not None and not all(
384
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
385
+ ):
386
+ raise ValueError(
387
+ 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]}"
388
+ )
389
+
390
+ if prompt is not None and prompt_embeds is not None:
391
+ raise ValueError(
392
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
393
+ " only forward one of the two."
394
+ )
395
+ elif prompt_2 is not None and prompt_embeds is not None:
396
+ raise ValueError(
397
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
398
+ " only forward one of the two."
399
+ )
400
+ elif prompt is None and prompt_embeds is None:
401
+ raise ValueError(
402
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
403
+ )
404
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
405
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
406
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
407
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
408
+
409
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
410
+ raise ValueError(
411
+ "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`."
412
+ )
413
+
414
+ if max_sequence_length is not None and max_sequence_length > 512:
415
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
416
+
417
+ @staticmethod
418
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
419
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
420
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
421
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
422
+
423
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
424
+
425
+ latent_image_ids = latent_image_ids.reshape(
426
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
427
+ )
428
+
429
+ return latent_image_ids.to(device=device, dtype=dtype)
430
+
431
+ @staticmethod
432
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
433
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
434
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
435
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
436
+
437
+ return latents
438
+
439
+ @staticmethod
440
+ def _unpack_latents(latents, height, width, vae_scale_factor):
441
+ batch_size, num_patches, channels = latents.shape
442
+
443
+ height = height // vae_scale_factor
444
+ width = width // vae_scale_factor
445
+
446
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
447
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
448
+
449
+ latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
450
+
451
+ return latents
452
+
453
+ def enable_vae_slicing(self):
454
+ r"""
455
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
456
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
457
+ """
458
+ self.vae.enable_slicing()
459
+
460
+ def disable_vae_slicing(self):
461
+ r"""
462
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
463
+ computing decoding in one step.
464
+ """
465
+ self.vae.disable_slicing()
466
+
467
+ def enable_vae_tiling(self):
468
+ r"""
469
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
470
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
471
+ processing larger images.
472
+ """
473
+ self.vae.enable_tiling()
474
+
475
+ def disable_vae_tiling(self):
476
+ r"""
477
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
478
+ computing decoding in one step.
479
+ """
480
+ self.vae.disable_tiling()
481
+
482
+ def prepare_latents(
483
+ self,
484
+ batch_size,
485
+ num_channels_latents,
486
+ height,
487
+ width,
488
+ dtype,
489
+ device,
490
+ generator,
491
+ latents=None,
492
+ ):
493
+ height = 2 * (int(height) // self.vae_scale_factor)
494
+ width = 2 * (int(width) // self.vae_scale_factor)
495
+
496
+ shape = (batch_size, num_channels_latents, height, width)
497
+
498
+ if latents is not None:
499
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
500
+ return latents.to(device=device, dtype=dtype), latent_image_ids
501
+
502
+ if isinstance(generator, list) and len(generator) != batch_size:
503
+ raise ValueError(
504
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
505
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
506
+ )
507
+
508
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
509
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
510
+
511
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
512
+
513
+ return latents, latent_image_ids
514
+
515
+ @property
516
+ def guidance_scale(self):
517
+ return self._guidance_scale
518
+
519
+ @property
520
+ def joint_attention_kwargs(self):
521
+ return self._joint_attention_kwargs
522
+
523
+ @property
524
+ def num_timesteps(self):
525
+ return self._num_timesteps
526
+
527
+ @property
528
+ def interrupt(self):
529
+ return self._interrupt
530
+
531
+ @torch.no_grad()
532
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
533
+ def __call__(
534
+ self,
535
+ prompt: Union[str, List[str]] = None,
536
+ prompt_2: Optional[Union[str, List[str]]] = None,
537
+ height: Optional[int] = None,
538
+ width: Optional[int] = None,
539
+ num_inference_steps: int = 28,
540
+ timesteps: List[int] = None,
541
+ guidance_scale: float = 3.5,
542
+ num_images_per_prompt: Optional[int] = 1,
543
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
544
+ latents: Optional[torch.FloatTensor] = None,
545
+ prompt_embeds: Optional[torch.FloatTensor] = None,
546
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
547
+ output_type: Optional[str] = "pil",
548
+ return_dict: bool = True,
549
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
550
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
551
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
552
+ max_sequence_length: int = 512,
553
+ ):
554
+ r"""
555
+ Function invoked when calling the pipeline for generation.
556
+
557
+ Args:
558
+ prompt (`str` or `List[str]`, *optional*):
559
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
560
+ instead.
561
+ prompt_2 (`str` or `List[str]`, *optional*):
562
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
563
+ will be used instead
564
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
565
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
566
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
567
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
568
+ num_inference_steps (`int`, *optional*, defaults to 50):
569
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
570
+ expense of slower inference.
571
+ timesteps (`List[int]`, *optional*):
572
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
573
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
574
+ passed will be used. Must be in descending order.
575
+ guidance_scale (`float`, *optional*, defaults to 7.0):
576
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
577
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
578
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
579
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
580
+ usually at the expense of lower image quality.
581
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
582
+ The number of images to generate per prompt.
583
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
584
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
585
+ to make generation deterministic.
586
+ latents (`torch.FloatTensor`, *optional*):
587
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
588
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
589
+ tensor will ge generated by sampling using the supplied random `generator`.
590
+ prompt_embeds (`torch.FloatTensor`, *optional*):
591
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
592
+ provided, text embeddings will be generated from `prompt` input argument.
593
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
594
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
595
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
596
+ output_type (`str`, *optional*, defaults to `"pil"`):
597
+ The output format of the generate image. Choose between
598
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
599
+ return_dict (`bool`, *optional*, defaults to `True`):
600
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
601
+ joint_attention_kwargs (`dict`, *optional*):
602
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
603
+ `self.processor` in
604
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
605
+ callback_on_step_end (`Callable`, *optional*):
606
+ A function that calls at the end of each denoising steps during the inference. The function is called
607
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
608
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
609
+ `callback_on_step_end_tensor_inputs`.
610
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
611
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
612
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
613
+ `._callback_tensor_inputs` attribute of your pipeline class.
614
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
615
+
616
+ Examples:
617
+
618
+ Returns:
619
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
620
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
621
+ images.
622
+ """
623
+
624
+ height = height or self.default_sample_size * self.vae_scale_factor
625
+ width = width or self.default_sample_size * self.vae_scale_factor
626
+
627
+ # 1. Check inputs. Raise error if not correct
628
+ self.check_inputs(
629
+ prompt,
630
+ prompt_2,
631
+ height,
632
+ width,
633
+ prompt_embeds=prompt_embeds,
634
+ pooled_prompt_embeds=pooled_prompt_embeds,
635
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
636
+ max_sequence_length=max_sequence_length,
637
+ )
638
+
639
+ self._guidance_scale = guidance_scale
640
+ self._joint_attention_kwargs = joint_attention_kwargs
641
+ self._interrupt = False
642
+
643
+ # 2. Define call parameters
644
+ if prompt is not None and isinstance(prompt, str):
645
+ batch_size = 1
646
+ elif prompt is not None and isinstance(prompt, list):
647
+ batch_size = len(prompt)
648
+ else:
649
+ batch_size = prompt_embeds.shape[0]
650
+
651
+ device = self._execution_device
652
+
653
+ lora_scale = (
654
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
655
+ )
656
+ (
657
+ prompt_embeds,
658
+ pooled_prompt_embeds,
659
+ text_ids,
660
+ ) = self.encode_prompt(
661
+ prompt=prompt,
662
+ prompt_2=prompt_2,
663
+ prompt_embeds=prompt_embeds,
664
+ pooled_prompt_embeds=pooled_prompt_embeds,
665
+ device=device,
666
+ num_images_per_prompt=num_images_per_prompt,
667
+ max_sequence_length=max_sequence_length,
668
+ lora_scale=lora_scale,
669
+ )
670
+
671
+ # 4. Prepare latent variables
672
+ num_channels_latents = self.transformer.config.in_channels // 4
673
+ latents, latent_image_ids = self.prepare_latents(
674
+ batch_size * num_images_per_prompt,
675
+ num_channels_latents,
676
+ height,
677
+ width,
678
+ prompt_embeds.dtype,
679
+ device,
680
+ generator,
681
+ latents,
682
+ )
683
+
684
+ # 5. Prepare timesteps
685
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
686
+ image_seq_len = latents.shape[1]
687
+ mu = calculate_shift(
688
+ image_seq_len,
689
+ self.scheduler.config.base_image_seq_len,
690
+ self.scheduler.config.max_image_seq_len,
691
+ self.scheduler.config.base_shift,
692
+ self.scheduler.config.max_shift,
693
+ )
694
+ timesteps, num_inference_steps = retrieve_timesteps(
695
+ self.scheduler,
696
+ num_inference_steps,
697
+ device,
698
+ timesteps,
699
+ sigmas,
700
+ mu=mu,
701
+ )
702
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
703
+ self._num_timesteps = len(timesteps)
704
+
705
+ # handle guidance
706
+ if self.transformer.config.guidance_embeds:
707
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
708
+ guidance = guidance.expand(latents.shape[0])
709
+ else:
710
+ guidance = None
711
+
712
+ # 6. Denoising loop
713
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
714
+ for i, t in enumerate(timesteps):
715
+ if self.interrupt:
716
+ continue
717
+
718
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
719
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
720
+
721
+ noise_pred = self.transformer(
722
+ hidden_states=latents,
723
+ timestep=timestep / 1000,
724
+ guidance=guidance,
725
+ pooled_projections=pooled_prompt_embeds,
726
+ encoder_hidden_states=prompt_embeds,
727
+ txt_ids=text_ids,
728
+ img_ids=latent_image_ids,
729
+ joint_attention_kwargs=self.joint_attention_kwargs,
730
+ return_dict=False,
731
+ )[0]
732
+
733
+ # compute the previous noisy sample x_t -> x_t-1
734
+ latents_dtype = latents.dtype
735
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
736
+
737
+ if latents.dtype != latents_dtype:
738
+ if torch.backends.mps.is_available():
739
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
740
+ latents = latents.to(latents_dtype)
741
+
742
+ if callback_on_step_end is not None:
743
+ callback_kwargs = {}
744
+ for k in callback_on_step_end_tensor_inputs:
745
+ callback_kwargs[k] = locals()[k]
746
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
747
+
748
+ latents = callback_outputs.pop("latents", latents)
749
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
750
+
751
+ # call the callback, if provided
752
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
753
+ progress_bar.update()
754
+
755
+ if XLA_AVAILABLE:
756
+ xm.mark_step()
757
+
758
+ if output_type == "latent":
759
+ image = latents
760
+
761
+ else:
762
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
763
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
764
+ image = self.vae.decode(latents, return_dict=False)[0]
765
+ image = self.image_processor.postprocess(image, output_type=output_type)
766
+
767
+ # Offload all models
768
+ self.maybe_free_model_hooks()
769
+
770
+ if not return_dict:
771
+ return (image,)
772
+
773
+ return FluxPipelineOutput(images=image)