prithivMLmods commited on
Commit
a16f6e8
·
verified ·
1 Parent(s): 328da4c

Create pipeline_flux_controlnet_inpaint.py

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