suayptalha commited on
Commit
7102ec5
·
verified ·
1 Parent(s): 59bdb34

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +438 -0
pipeline.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import FluxControlPipeline, FluxTransformer2DModel
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+ import torch
4
+
5
+ from diffusers.image_processor import PipelineImageInput
6
+ import numpy as np
7
+ import torch.nn.functional as F
8
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
9
+ from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps, XLA_AVAILABLE
10
+
11
+
12
+ class Flex2Pipeline(FluxControlPipeline):
13
+ def __init__(
14
+ self,
15
+ scheduler,
16
+ vae,
17
+ text_encoder,
18
+ tokenizer,
19
+ text_encoder_2,
20
+ tokenizer_2,
21
+ transformer,
22
+ ):
23
+ super().__init__(scheduler, vae, text_encoder, tokenizer, text_encoder_2, tokenizer_2, transformer)
24
+
25
+ def check_inputs(
26
+ self,
27
+ prompt,
28
+ prompt_2,
29
+ height,
30
+ width,
31
+ prompt_embeds=None,
32
+ pooled_prompt_embeds=None,
33
+ callback_on_step_end_tensor_inputs=None,
34
+ max_sequence_length=None,
35
+ inpaint_image=None,
36
+ inpaint_mask=None,
37
+ control_image=None,
38
+ ):
39
+ super().check_inputs(
40
+ prompt,
41
+ prompt_2,
42
+ height,
43
+ width,
44
+ prompt_embeds=prompt_embeds,
45
+ pooled_prompt_embeds=pooled_prompt_embeds,
46
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
47
+ max_sequence_length=max_sequence_length,
48
+ )
49
+ if inpaint_image is not None and inpaint_mask is None:
50
+ raise ValueError(
51
+ "If `inpaint_image` is passed, `inpaint_mask` must be passed as well. "
52
+ "Please make sure to pass both `inpaint_image` and `inpaint_mask`."
53
+ )
54
+ if inpaint_mask is not None and inpaint_image is None:
55
+ raise ValueError(
56
+ "If `inpaint_mask` is passed, `inpaint_image` must be passed as well. "
57
+ "Please make sure to pass both `inpaint_image` and `inpaint_mask`."
58
+ )
59
+
60
+ @torch.no_grad()
61
+ def __call__(
62
+ self,
63
+ prompt: Union[str, List[str]] = None,
64
+ prompt_2: Optional[Union[str, List[str]]] = None,
65
+ inpaint_image: Optional[PipelineImageInput] = None,
66
+ inpaint_mask: Optional[PipelineImageInput] = None,
67
+ control_image: Optional[PipelineImageInput] = None,
68
+ control_strength: Optional[float] = 1.0,
69
+ control_stop: Optional[float] = 1.0,
70
+ height: Optional[int] = None,
71
+ width: Optional[int] = None,
72
+ num_inference_steps: int = 28,
73
+ sigmas: Optional[List[float]] = None,
74
+ guidance_scale: float = 3.5,
75
+ num_images_per_prompt: Optional[int] = 1,
76
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
77
+ latents: Optional[torch.FloatTensor] = None,
78
+ prompt_embeds: Optional[torch.FloatTensor] = None,
79
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
80
+ output_type: Optional[str] = "pil",
81
+ return_dict: bool = True,
82
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
83
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
84
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
85
+ max_sequence_length: int = 512,
86
+ **kwargs,
87
+ ):
88
+ r"""
89
+ Function invoked when calling the pipeline for generation.
90
+
91
+ Args:
92
+ prompt (`str` or `List[str]`, *optional*):
93
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
94
+ instead.
95
+ prompt_2 (`str` or `List[str]`, *optional*):
96
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
97
+ will be used instead
98
+ inpaint_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
99
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
100
+ The image to be inpainted.
101
+ inpaint_mask (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
102
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
103
+ A black and white mask to be used for inpainting. The white pixels are the areas to be inpainted, while the
104
+ black pixels are the areas to be kept.
105
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
106
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
107
+ The control image (line, depth, pose, etc.) to be used for the generation. The control image
108
+ control_strength (`float`, *optional*, defaults to 1.0):
109
+ The strength of the control image. The higher the value, the more the control image will be used to
110
+ guide the generation. The lower the value, the less the control image will be used to guide the
111
+ generation.
112
+ control_stop (`float`, *optional*, defaults to 1.0):
113
+ The percentage of the generation to drop out the control. 0.0 to 1.0. 0.5 mean the control will be dropped
114
+ out at 50% of the generation.
115
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
116
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
117
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
118
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
119
+ num_inference_steps (`int`, *optional*, defaults to 50):
120
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
121
+ expense of slower inference.
122
+ sigmas (`List[float]`, *optional*):
123
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
124
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
125
+ will be used.
126
+ guidance_scale (`float`, *optional*, defaults to 3.5):
127
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
128
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
129
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
130
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
131
+ usually at the expense of lower image quality.
132
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
133
+ The number of images to generate per prompt.
134
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
135
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
136
+ to make generation deterministic.
137
+ latents (`torch.FloatTensor`, *optional*):
138
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
139
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
140
+ tensor will ge generated by sampling using the supplied random `generator`.
141
+ prompt_embeds (`torch.FloatTensor`, *optional*):
142
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
143
+ provided, text embeddings will be generated from `prompt` input argument.
144
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
145
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
146
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
147
+ output_type (`str`, *optional*, defaults to `"pil"`):
148
+ The output format of the generate image. Choose between
149
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
150
+ return_dict (`bool`, *optional*, defaults to `True`):
151
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
152
+ joint_attention_kwargs (`dict`, *optional*):
153
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
154
+ `self.processor` in
155
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
156
+ callback_on_step_end (`Callable`, *optional*):
157
+ A function that calls at the end of each denoising steps during the inference. The function is called
158
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
159
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
160
+ `callback_on_step_end_tensor_inputs`.
161
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
162
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
163
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
164
+ `._callback_tensor_inputs` attribute of your pipeline class.
165
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
166
+
167
+ Examples:
168
+
169
+ Returns:
170
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
171
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
172
+ images.
173
+ """
174
+
175
+ height = height or self.default_sample_size * self.vae_scale_factor
176
+ width = width or self.default_sample_size * self.vae_scale_factor
177
+
178
+ # 1. Check inputs. Raise error if not correct
179
+ self.check_inputs(
180
+ prompt,
181
+ prompt_2,
182
+ height,
183
+ width,
184
+ prompt_embeds=prompt_embeds,
185
+ pooled_prompt_embeds=pooled_prompt_embeds,
186
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
187
+ max_sequence_length=max_sequence_length,
188
+ )
189
+
190
+ self._guidance_scale = guidance_scale
191
+ self._joint_attention_kwargs = joint_attention_kwargs
192
+ self._interrupt = False
193
+
194
+ # 2. Define call parameters
195
+ if prompt is not None and isinstance(prompt, str):
196
+ batch_size = 1
197
+ elif prompt is not None and isinstance(prompt, list):
198
+ batch_size = len(prompt)
199
+ else:
200
+ batch_size = prompt_embeds.shape[0]
201
+
202
+ device = self._execution_device
203
+
204
+ # 3. Prepare text embeddings
205
+ lora_scale = (
206
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
207
+ )
208
+ (
209
+ prompt_embeds,
210
+ pooled_prompt_embeds,
211
+ text_ids,
212
+ ) = self.encode_prompt(
213
+ prompt=prompt,
214
+ prompt_2=prompt_2,
215
+ prompt_embeds=prompt_embeds,
216
+ pooled_prompt_embeds=pooled_prompt_embeds,
217
+ device=device,
218
+ num_images_per_prompt=num_images_per_prompt,
219
+ max_sequence_length=max_sequence_length,
220
+ lora_scale=lora_scale,
221
+ )
222
+
223
+ # 4. Prepare latent variables
224
+ num_channels_latents = self.transformer.config.in_channels // 4
225
+
226
+ # only prepare latents for non controls
227
+ # (16 + 1 + 16 )
228
+ num_control_channels = 33
229
+ num_channels_latents = num_channels_latents - num_control_channels
230
+
231
+ control_latents = None
232
+ inpaint_latents = None
233
+ inpaint_latents_mask = None
234
+
235
+ latent_height = height // self.vae_scale_factor
236
+ latent_width = width // self.vae_scale_factor
237
+
238
+ # process the control and inpaint channels
239
+
240
+ if control_image is None:
241
+ control_latents = torch.zeros(
242
+ batch_size * num_images_per_prompt,
243
+ 3,
244
+ latent_height,
245
+ latent_width,
246
+ device=device,
247
+ dtype=self.vae.dtype,
248
+ )
249
+ else:
250
+ control_image = self.prepare_image(
251
+ image=control_image,
252
+ width=width,
253
+ height=height,
254
+ batch_size=batch_size * num_images_per_prompt,
255
+ num_images_per_prompt=num_images_per_prompt,
256
+ device=device,
257
+ dtype=self.vae.dtype,
258
+ )
259
+ control_image = self.vae.encode(control_image).latent_dist.sample(generator=generator)
260
+ control_latents = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
261
+
262
+ # apply control strength
263
+ control_latents = control_latents * control_strength
264
+
265
+ if inpaint_image is None and inpaint_mask is None:
266
+ inpaint_latents = torch.zeros(
267
+ batch_size * num_images_per_prompt,
268
+ 3,
269
+ latent_height,
270
+ latent_width,
271
+ device=device,
272
+ dtype=self.vae.dtype,
273
+ )
274
+ inpaint_latents_mask = torch.ones(
275
+ batch_size * num_images_per_prompt,
276
+ 1,
277
+ latent_height,
278
+ latent_width,
279
+ device=device,
280
+ dtype=self.vae.dtype,
281
+ )
282
+ else:
283
+ inpaint_image = self.prepare_image(
284
+ image=inpaint_image,
285
+ width=width,
286
+ height=height,
287
+ batch_size=batch_size * num_images_per_prompt,
288
+ num_images_per_prompt=num_images_per_prompt,
289
+ device=device,
290
+ dtype=self.vae.dtype,
291
+ )
292
+ inpaint_image = self.vae.encode(inpaint_image).latent_dist.sample(generator=generator)
293
+ inpaint_latents = (inpaint_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
294
+ height_inpaint_image, width_inpaint_image = control_image.shape[2:]
295
+
296
+ inpaint_mask = self.prepare_image(
297
+ image=inpaint_mask,
298
+ width=width,
299
+ height=height,
300
+ batch_size=batch_size * num_images_per_prompt,
301
+ num_images_per_prompt=num_images_per_prompt,
302
+ device=device,
303
+ dtype=self.vae.dtype,
304
+ )
305
+ # mask is 3 ch -1 to 1. make it 1ch, 0 to 1
306
+ inpaint_mask = inpaint_mask[:, 0:1, :, :] * 0.5 + 0.5
307
+ # resize to match height_inpaint_image and width_inpaint_image
308
+ inpaint_latents_mask = F.interpolate(inpaint_mask, size=(height_inpaint_image, width_inpaint_image), mode="bilinear", align_corners=False)
309
+
310
+ # apply inverted mask to inpaint latents
311
+ inpaint_latents = inpaint_latents * (1 - inpaint_latents_mask)
312
+
313
+ # concat the latent controls on the channel dimension every step
314
+ latent_controls = torch.cat([inpaint_latents, inpaint_latents_mask, control_latents], dim=1)
315
+ latent_no_controls = torch.cat([inpaint_latents, inpaint_latents_mask, torch.zeros_like(control_latents)], dim=1)
316
+
317
+ # pack the controls
318
+ height_latent_controls, width_latent_controls = latent_controls.shape[2:]
319
+ packed_latent_controls = self._pack_latents(
320
+ latent_controls,
321
+ batch_size * num_images_per_prompt,
322
+ num_control_channels,
323
+ height_latent_controls,
324
+ width_latent_controls,
325
+ )
326
+ packed_latent_no_controls = self._pack_latents(
327
+ latent_no_controls,
328
+ batch_size * num_images_per_prompt,
329
+ num_control_channels,
330
+ height_latent_controls,
331
+ width_latent_controls,
332
+ )
333
+
334
+ latents, latent_image_ids = self.prepare_latents(
335
+ batch_size * num_images_per_prompt,
336
+ num_channels_latents,
337
+ height,
338
+ width,
339
+ prompt_embeds.dtype,
340
+ device,
341
+ generator,
342
+ latents,
343
+ )
344
+
345
+ # 5. Prepare timesteps
346
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
347
+ image_seq_len = latents.shape[1]
348
+ mu = calculate_shift(
349
+ image_seq_len,
350
+ self.scheduler.config.get("base_image_seq_len", 256),
351
+ self.scheduler.config.get("max_image_seq_len", 4096),
352
+ self.scheduler.config.get("base_shift", 0.5),
353
+ self.scheduler.config.get("max_shift", 1.15),
354
+ )
355
+ timesteps, num_inference_steps = retrieve_timesteps(
356
+ self.scheduler,
357
+ num_inference_steps,
358
+ device,
359
+ sigmas=sigmas,
360
+ mu=mu,
361
+ )
362
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
363
+ self._num_timesteps = len(timesteps)
364
+
365
+ # handle guidance
366
+ if self.transformer.config.guidance_embeds:
367
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
368
+ guidance = guidance.expand(latents.shape[0])
369
+ else:
370
+ guidance = None
371
+
372
+ control_cutoff = int(len(timesteps) * control_stop)
373
+
374
+ # 6. Denoising loop
375
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
376
+ for i, t in enumerate(timesteps):
377
+ if self.interrupt:
378
+ continue
379
+
380
+ control_latents = packed_latent_controls if i < control_cutoff else packed_latent_no_controls
381
+
382
+ latent_model_input = torch.cat([latents, control_latents], dim=2)
383
+
384
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
385
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
386
+
387
+ noise_pred = self.transformer(
388
+ hidden_states=latent_model_input,
389
+ timestep=timestep / 1000,
390
+ guidance=guidance,
391
+ pooled_projections=pooled_prompt_embeds,
392
+ encoder_hidden_states=prompt_embeds,
393
+ txt_ids=text_ids,
394
+ img_ids=latent_image_ids,
395
+ joint_attention_kwargs=self.joint_attention_kwargs,
396
+ return_dict=False,
397
+ )[0]
398
+
399
+ # compute the previous noisy sample x_t -> x_t-1
400
+ latents_dtype = latents.dtype
401
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
402
+
403
+ if latents.dtype != latents_dtype:
404
+ if torch.backends.mps.is_available():
405
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
406
+ latents = latents.to(latents_dtype)
407
+
408
+ if callback_on_step_end is not None:
409
+ callback_kwargs = {}
410
+ for k in callback_on_step_end_tensor_inputs:
411
+ callback_kwargs[k] = locals()[k]
412
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
413
+
414
+ latents = callback_outputs.pop("latents", latents)
415
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
416
+
417
+ # call the callback, if provided
418
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
419
+ progress_bar.update()
420
+
421
+ if XLA_AVAILABLE:
422
+ xm.mark_step()
423
+
424
+ if output_type == "latent":
425
+ image = latents
426
+ else:
427
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
428
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
429
+ image = self.vae.decode(latents, return_dict=False)[0]
430
+ image = self.image_processor.postprocess(image, output_type=output_type)
431
+
432
+ # Offload all models
433
+ self.maybe_free_model_hooks()
434
+
435
+ if not return_dict:
436
+ return (image,)
437
+
438
+ return FluxPipelineOutput(images=image)