LPX55 commited on
Commit
e8cf294
·
verified ·
1 Parent(s): a3afb4d

Create pipeline_flux_chameleon_og.py

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