ivand-all3d commited on
Commit
93aaa02
·
1 Parent(s): e6ca313

Add missing flux script

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