slobers commited on
Commit
7029ba8
·
verified ·
1 Parent(s): 0de0224

Update src/pipeline.py

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