Insta360-Research commited on
Commit
2fc1e1c
·
verified ·
1 Parent(s): c81b575

Upload pipeline.py

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