Diffusers
TalHach61 commited on
Commit
d8c1bff
·
verified ·
1 Parent(s): 93db988

Create pipeline_bria_controlnet.py

Browse files
Files changed (1) hide show
  1. pipeline_bria_controlnet.py +559 -0
pipeline_bria_controlnet.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI 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
+ from typing import Any, Callable, Dict, List, Optional, Union
16
+ import torch
17
+ from transformers import (
18
+ T5EncoderModel,
19
+ T5TokenizerFast,
20
+ )
21
+ from diffusers.image_processor import PipelineImageInput
22
+
23
+ from diffusers import AutoencoderKL # Waiting for diffusers udpdate
24
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
25
+ from diffusers.schedulers import KarrasDiffusionSchedulers
26
+ from diffusers.utils import logging
27
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
28
+ from controlnet_bria import BriaControlNetModel, BriaMultiControlNetModel
29
+ from diffusers.pipelines.flux.pipeline_flux import retrieve_timesteps, calculate_shift
30
+ from pipeline_bria import BriaPipeline
31
+ from transformer_bria import BriaTransformer2DModel
32
+ from bria_utils import get_original_sigmas
33
+ import numpy as np
34
+ import diffusers
35
+
36
+ XLA_AVAILABLE = False
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ class BriaControlNetPipeline(BriaPipeline):
43
+ r"""
44
+ Args:
45
+ transformer ([`SD3Transformer2DModel`]):
46
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
47
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
48
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
49
+ vae ([`AutoencoderKL`]):
50
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
51
+ text_encoder ([`T5EncoderModel`]):
52
+ Frozen text-encoder. Stable Diffusion 3 uses
53
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
54
+ [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
55
+ tokenizer (`T5TokenizerFast`):
56
+ Tokenizer of class
57
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
58
+ """
59
+
60
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder->transformer->vae"
61
+ _optional_components = []
62
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "negative_pooled_prompt_embeds"]
63
+
64
+ def __init__( # EYAL - removed clip text encoder + tokenizer
65
+ self,
66
+ transformer: BriaTransformer2DModel,
67
+ scheduler: Union[FlowMatchEulerDiscreteScheduler, KarrasDiffusionSchedulers],
68
+ vae: AutoencoderKL,
69
+ text_encoder: T5EncoderModel,
70
+ tokenizer: T5TokenizerFast,
71
+ controlnet: BriaControlNetModel,
72
+ ):
73
+ super().__init__(
74
+ transformer=transformer, scheduler=scheduler, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer
75
+ )
76
+ self.register_modules(controlnet=controlnet)
77
+
78
+ def prepare_image(
79
+ self,
80
+ image,
81
+ width,
82
+ height,
83
+ batch_size,
84
+ num_images_per_prompt,
85
+ device,
86
+ dtype,
87
+ do_classifier_free_guidance=False,
88
+ guess_mode=False,
89
+ ):
90
+ if isinstance(image, torch.Tensor):
91
+ pass
92
+ else:
93
+ image = self.image_processor.preprocess(image, height=height, width=width)
94
+
95
+ image_batch_size = image.shape[0]
96
+
97
+ if image_batch_size == 1:
98
+ repeat_by = batch_size
99
+ else:
100
+ # image batch size is the same as prompt batch size
101
+ repeat_by = num_images_per_prompt
102
+
103
+ image = image.repeat_interleave(repeat_by, dim=0)
104
+
105
+ image = image.to(device=device, dtype=dtype)
106
+
107
+ if do_classifier_free_guidance and not guess_mode:
108
+ image = torch.cat([image] * 2)
109
+
110
+ return image
111
+
112
+ def prepare_control(self, control_image, width, height, batch_size, num_images_per_prompt, device, control_mode):
113
+ num_channels_latents = self.transformer.config.in_channels // 4
114
+ control_image = self.prepare_image(
115
+ image=control_image,
116
+ width=width,
117
+ height=height,
118
+ batch_size=batch_size * num_images_per_prompt,
119
+ num_images_per_prompt=num_images_per_prompt,
120
+ device=device,
121
+ dtype=self.vae.dtype,
122
+ )
123
+ height, width = control_image.shape[-2:]
124
+
125
+ # vae encode
126
+ control_image = self.vae.encode(control_image).latent_dist.sample()
127
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
128
+
129
+ # pack
130
+ height_control_image, width_control_image = control_image.shape[2:]
131
+ control_image = self._pack_latents(
132
+ control_image,
133
+ batch_size * num_images_per_prompt,
134
+ num_channels_latents,
135
+ height_control_image,
136
+ width_control_image,
137
+ )
138
+
139
+ # Here we ensure that `control_mode` has the same length as the control_image.
140
+ if control_mode is not None:
141
+ if not isinstance(control_mode, int):
142
+ raise ValueError(" For `BriaControlNet`, `control_mode` should be an `int` or `None`")
143
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
144
+ control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
145
+
146
+ return control_image, control_mode
147
+
148
+ def prepare_multi_control(self, control_image, width, height, batch_size, num_images_per_prompt, device, control_mode):
149
+ num_channels_latents = self.transformer.config.in_channels // 4
150
+ control_images = []
151
+ for i, control_image_ in enumerate(control_image):
152
+ control_image_ = self.prepare_image(
153
+ image=control_image_,
154
+ width=width,
155
+ height=height,
156
+ batch_size=batch_size * num_images_per_prompt,
157
+ num_images_per_prompt=num_images_per_prompt,
158
+ device=device,
159
+ dtype=self.vae.dtype,
160
+ )
161
+ height, width = control_image_.shape[-2:]
162
+
163
+ # vae encode
164
+ control_image_ = self.vae.encode(control_image_).latent_dist.sample()
165
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
166
+
167
+ # pack
168
+ height_control_image, width_control_image = control_image_.shape[2:]
169
+ control_image_ = self._pack_latents(
170
+ control_image_,
171
+ batch_size * num_images_per_prompt,
172
+ num_channels_latents,
173
+ height_control_image,
174
+ width_control_image,
175
+ )
176
+ control_images.append(control_image_)
177
+
178
+ control_image = control_images
179
+
180
+ # Here we ensure that `control_mode` has the same length as the control_image.
181
+ if isinstance(control_mode, list) and len(control_mode) != len(control_image):
182
+ raise ValueError(
183
+ "For Multi-ControlNet, `control_mode` must be a list of the same "
184
+ + " length as the number of controlnets (control images) specified"
185
+ )
186
+ if not isinstance(control_mode, list):
187
+ control_mode = [control_mode] * len(control_image)
188
+ # set control mode
189
+ control_modes = []
190
+ for cmode in control_mode:
191
+ if cmode is None:
192
+ cmode = -1
193
+ control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long)
194
+ control_modes.append(control_mode)
195
+ control_mode = control_modes
196
+
197
+ return control_image, control_mode
198
+
199
+ def get_controlnet_keep(self, timesteps, control_guidance_start, control_guidance_end):
200
+ controlnet_keep = []
201
+ for i in range(len(timesteps)):
202
+ keeps = [
203
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
204
+ for s, e in zip(control_guidance_start, control_guidance_end)
205
+ ]
206
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, BriaControlNetModel) else keeps)
207
+ return controlnet_keep
208
+
209
+ def get_control_start_end(self, control_guidance_start, control_guidance_end):
210
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
211
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
212
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
213
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
214
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
215
+ mult = 1 # TODO - why is this 1?
216
+ control_guidance_start, control_guidance_end = (
217
+ mult * [control_guidance_start],
218
+ mult * [control_guidance_end],
219
+ )
220
+
221
+ return control_guidance_start, control_guidance_end
222
+
223
+ @torch.no_grad()
224
+ def __call__(
225
+ self,
226
+ prompt: Union[str, List[str]] = None,
227
+ height: Optional[int] = None,
228
+ width: Optional[int] = None,
229
+ num_inference_steps: int = 30,
230
+ timesteps: List[int] = None,
231
+ guidance_scale: float = 3.5,
232
+ control_guidance_start: Union[float, List[float]] = 0.0,
233
+ control_guidance_end: Union[float, List[float]] = 1.0,
234
+ control_image: Optional[PipelineImageInput] = None,
235
+ control_mode: Optional[Union[int, List[int]]] = None,
236
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
237
+ negative_prompt: Optional[Union[str, List[str]]] = None,
238
+ num_images_per_prompt: Optional[int] = 1,
239
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
240
+ latents: Optional[torch.FloatTensor] = None,
241
+ prompt_embeds: Optional[torch.FloatTensor] = None,
242
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
243
+ output_type: Optional[str] = "pil",
244
+ return_dict: bool = True,
245
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
246
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
247
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
248
+ max_sequence_length: int = 128,
249
+ ):
250
+ r"""
251
+ Function invoked when calling the pipeline for generation.
252
+ Args:
253
+ prompt (`str` or `List[str]`, *optional*):
254
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
255
+ instead.
256
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
257
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
258
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
259
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
260
+ num_inference_steps (`int`, *optional*, defaults to 50):
261
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
262
+ expense of slower inference.
263
+ timesteps (`List[int]`, *optional*):
264
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
265
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
266
+ passed will be used. Must be in descending order.
267
+ guidance_scale (`float`, *optional*, defaults to 5.0):
268
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
269
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
270
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
271
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
272
+ usually at the expense of lower image quality.
273
+ negative_prompt (`str` or `List[str]`, *optional*):
274
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
275
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
276
+ less than `1`).
277
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
278
+ The number of images to generate per prompt.
279
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
280
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
281
+ to make generation deterministic.
282
+ latents (`torch.FloatTensor`, *optional*):
283
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
284
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
285
+ tensor will ge generated by sampling using the supplied random `generator`.
286
+ prompt_embeds (`torch.FloatTensor`, *optional*):
287
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
288
+ provided, text embeddings will be generated from `prompt` input argument.
289
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
290
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
291
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
292
+ argument.
293
+ output_type (`str`, *optional*, defaults to `"pil"`):
294
+ The output format of the generate image. Choose between
295
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
296
+ return_dict (`bool`, *optional*, defaults to `True`):
297
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
298
+ of a plain tuple.
299
+ joint_attention_kwargs (`dict`, *optional*):
300
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
301
+ `self.processor` in
302
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
303
+ callback_on_step_end (`Callable`, *optional*):
304
+ A function that calls at the end of each denoising steps during the inference. The function is called
305
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
306
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
307
+ `callback_on_step_end_tensor_inputs`.
308
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
309
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
310
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
311
+ `._callback_tensor_inputs` attribute of your pipeline class.
312
+ max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
313
+ Examples:
314
+ Returns:
315
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
316
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
317
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
318
+ """
319
+
320
+ height = height or self.default_sample_size * self.vae_scale_factor
321
+ width = width or self.default_sample_size * self.vae_scale_factor
322
+ control_guidance_start, control_guidance_end = self.get_control_start_end(
323
+ control_guidance_start=control_guidance_start, control_guidance_end=control_guidance_end
324
+ )
325
+
326
+ # 1. Check inputs. Raise error if not correct
327
+ self.check_inputs(
328
+ prompt,
329
+ height,
330
+ width,
331
+ negative_prompt=negative_prompt,
332
+ prompt_embeds=prompt_embeds,
333
+ negative_prompt_embeds=negative_prompt_embeds,
334
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
335
+ max_sequence_length=max_sequence_length,
336
+ )
337
+
338
+ self._guidance_scale = guidance_scale
339
+ self._joint_attention_kwargs = joint_attention_kwargs
340
+ self._interrupt = False
341
+
342
+ # 2. Define call parameters
343
+ if prompt is not None and isinstance(prompt, str):
344
+ batch_size = 1
345
+ elif prompt is not None and isinstance(prompt, list):
346
+ batch_size = len(prompt)
347
+ else:
348
+ batch_size = prompt_embeds.shape[0]
349
+
350
+ device = self._execution_device
351
+
352
+ lora_scale = self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
353
+
354
+ (prompt_embeds, negative_prompt_embeds, text_ids) = self.encode_prompt(
355
+ prompt=prompt,
356
+ negative_prompt=negative_prompt,
357
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
358
+ prompt_embeds=prompt_embeds,
359
+ negative_prompt_embeds=negative_prompt_embeds,
360
+ device=device,
361
+ num_images_per_prompt=num_images_per_prompt,
362
+ max_sequence_length=max_sequence_length,
363
+ lora_scale=lora_scale,
364
+ )
365
+
366
+ if self.do_classifier_free_guidance:
367
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
368
+
369
+ # 3. Prepare control image
370
+ if control_image is not None:
371
+ if isinstance(self.controlnet, BriaControlNetModel):
372
+ control_image, control_mode = self.prepare_control(
373
+ control_image=control_image,
374
+ width=width,
375
+ height=height,
376
+ batch_size=batch_size,
377
+ num_images_per_prompt=num_images_per_prompt,
378
+ device=device,
379
+ control_mode=control_mode,
380
+ )
381
+ elif isinstance(self.controlnet, BriaMultiControlNetModel):
382
+ control_image, control_mode = self.prepare_multi_control(
383
+ control_image=control_image,
384
+ width=width,
385
+ height=height,
386
+ batch_size=batch_size,
387
+ num_images_per_prompt=num_images_per_prompt,
388
+ device=device,
389
+ control_mode=control_mode,
390
+ )
391
+
392
+ # 4. Prepare timesteps
393
+ # Sample from training sigmas
394
+
395
+ if isinstance(self.scheduler,FlowMatchEulerDiscreteScheduler) and self.scheduler.config['use_dynamic_shifting']:
396
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
397
+ if type(control_image) == list:
398
+ image_seq_len = control_image[0].shape[1]
399
+ else:
400
+ image_seq_len = control_image.shape[1]
401
+ print(f"Using dynamic shift in pipeline with sequence length {image_seq_len}")
402
+
403
+ mu = calculate_shift(
404
+ image_seq_len,
405
+ self.scheduler.config.base_image_seq_len,
406
+ self.scheduler.config.max_image_seq_len,
407
+ self.scheduler.config.base_shift,
408
+ self.scheduler.config.max_shift,
409
+ )
410
+ timesteps, num_inference_steps = retrieve_timesteps(
411
+ self.scheduler,
412
+ num_inference_steps,
413
+ device,
414
+ timesteps=None,
415
+ sigmas=sigmas,
416
+ mu=mu,
417
+ )
418
+ else:
419
+ # 4. Prepare timesteps
420
+ sigmas = get_original_sigmas(
421
+ num_train_timesteps=self.scheduler.config.num_train_timesteps, num_inference_steps=num_inference_steps
422
+ )
423
+ timesteps, num_inference_steps = retrieve_timesteps(
424
+ self.scheduler, num_inference_steps, device, timesteps, sigmas=sigmas
425
+ )
426
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
427
+ self._num_timesteps = len(timesteps)
428
+
429
+ # 5. Prepare latent variables
430
+ num_channels_latents = self.transformer.config.in_channels // 4 # due to patch=2, we devide by 4
431
+ latents, latent_image_ids = self.prepare_latents(
432
+ batch_size=batch_size * num_images_per_prompt,
433
+ num_channels_latents=num_channels_latents,
434
+ height=height,
435
+ width=width,
436
+ dtype=prompt_embeds.dtype,
437
+ device=device,
438
+ generator=generator,
439
+ latents=latents,
440
+ )
441
+
442
+ # 6. Create tensor stating which controlnets to keep
443
+ if control_image is not None:
444
+ controlnet_keep = self.get_controlnet_keep(
445
+ timesteps=timesteps,
446
+ control_guidance_start=control_guidance_start,
447
+ control_guidance_end=control_guidance_end,
448
+ )
449
+
450
+ if diffusers.__version__>='0.32.0':
451
+ latent_image_ids=latent_image_ids[0]
452
+ text_ids=text_ids[0]
453
+
454
+ # EYAL - added the CFG loop
455
+ # 7. Denoising loop
456
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
457
+ for i, t in enumerate(timesteps):
458
+ if self.interrupt:
459
+ continue
460
+
461
+ # expand the latents if we are doing classifier free guidance
462
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
463
+ # if type(self.scheduler) != FlowMatchEulerDiscreteScheduler:
464
+ if not isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
465
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
466
+
467
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
468
+ timestep = t.expand(latent_model_input.shape[0])
469
+
470
+ # Handling ControlNet
471
+ if control_image is not None:
472
+ if isinstance(controlnet_keep[i], list):
473
+ if isinstance(controlnet_conditioning_scale, list):
474
+ cond_scale = controlnet_conditioning_scale
475
+ else:
476
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
477
+ else:
478
+ controlnet_cond_scale = controlnet_conditioning_scale
479
+ if isinstance(controlnet_cond_scale, list):
480
+ controlnet_cond_scale = controlnet_cond_scale[0]
481
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
482
+
483
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
484
+ hidden_states=latents,
485
+ controlnet_cond=control_image,
486
+ controlnet_mode=control_mode,
487
+ conditioning_scale=cond_scale,
488
+ timestep=timestep,
489
+ # guidance=guidance,
490
+ # pooled_projections=pooled_prompt_embeds,
491
+ encoder_hidden_states=prompt_embeds,
492
+ txt_ids=text_ids,
493
+ img_ids=latent_image_ids,
494
+ joint_attention_kwargs=self.joint_attention_kwargs,
495
+ return_dict=False,
496
+ )
497
+ else:
498
+ controlnet_block_samples, controlnet_single_block_samples = None, None
499
+
500
+ # This is predicts "v" from flow-matching
501
+ noise_pred = self.transformer(
502
+ hidden_states=latent_model_input,
503
+ timestep=timestep,
504
+ encoder_hidden_states=prompt_embeds,
505
+ joint_attention_kwargs=self.joint_attention_kwargs,
506
+ return_dict=False,
507
+ txt_ids=text_ids,
508
+ img_ids=latent_image_ids,
509
+ controlnet_block_samples=controlnet_block_samples,
510
+ controlnet_single_block_samples=controlnet_single_block_samples,
511
+ )[0]
512
+
513
+ # perform guidance
514
+ if self.do_classifier_free_guidance:
515
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
516
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
517
+
518
+ # compute the previous noisy sample x_t -> x_t-1
519
+ latents_dtype = latents.dtype
520
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
521
+
522
+ if latents.dtype != latents_dtype:
523
+ if torch.backends.mps.is_available():
524
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
525
+ latents = latents.to(latents_dtype)
526
+
527
+ if callback_on_step_end is not None:
528
+ callback_kwargs = {}
529
+ for k in callback_on_step_end_tensor_inputs:
530
+ callback_kwargs[k] = locals()[k]
531
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
532
+
533
+ latents = callback_outputs.pop("latents", latents)
534
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
535
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
536
+
537
+ # call the callback, if provided
538
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
539
+ progress_bar.update()
540
+
541
+ if XLA_AVAILABLE:
542
+ xm.mark_step()
543
+
544
+ if output_type == "latent":
545
+ image = latents
546
+
547
+ else:
548
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
549
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
550
+ image = self.vae.decode(latents.to(dtype=self.vae.dtype), return_dict=False)[0]
551
+ image = self.image_processor.postprocess(image, output_type=output_type)
552
+
553
+ # Offload all models
554
+ self.maybe_free_model_hooks()
555
+
556
+ if not return_dict:
557
+ return (image,)
558
+
559
+ return FluxPipelineOutput(images=image)