nviolante commited on
Commit
2c71af2
·
verified ·
1 Parent(s): 7d1dd65

Upload pipeline_dot3d.py with huggingface_hub

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