comdoleger commited on
Commit
3f8ab0b
·
verified ·
1 Parent(s): 272ed4b

Upload extensions_built_in/flex2/pipeline.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. extensions_built_in/flex2/pipeline.py +348 -0
extensions_built_in/flex2/pipeline.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from PIL import Image
8
+ import torch.nn.functional as F
9
+ from torchvision import transforms
10
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
11
+ from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps, XLA_AVAILABLE
12
+
13
+
14
+ class Flex2Pipeline(FluxControlPipeline):
15
+ def __init__(
16
+ self,
17
+ scheduler,
18
+ vae,
19
+ text_encoder,
20
+ tokenizer,
21
+ text_encoder_2,
22
+ tokenizer_2,
23
+ transformer,
24
+ ):
25
+ super().__init__(scheduler, vae, text_encoder, tokenizer, text_encoder_2, tokenizer_2, transformer)
26
+
27
+ @torch.no_grad()
28
+ def __call__(
29
+ self,
30
+ prompt: Union[str, List[str]] = None,
31
+ prompt_2: Optional[Union[str, List[str]]] = None,
32
+ control_image: Optional[PipelineImageInput] = None,
33
+ height: Optional[int] = None,
34
+ width: Optional[int] = None,
35
+ num_inference_steps: int = 28,
36
+ sigmas: Optional[List[float]] = None,
37
+ guidance_scale: float = 3.5,
38
+ num_images_per_prompt: Optional[int] = 1,
39
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
40
+ latents: Optional[torch.FloatTensor] = None,
41
+ prompt_embeds: Optional[torch.FloatTensor] = None,
42
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
43
+ output_type: Optional[str] = "pil",
44
+ return_dict: bool = True,
45
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
46
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
47
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
48
+ max_sequence_length: int = 512,
49
+ control_image_idx: int = 0,
50
+ **kwargs,
51
+ ):
52
+ r"""
53
+ Function invoked when calling the pipeline for generation.
54
+
55
+ Args:
56
+ prompt (`str` or `List[str]`, *optional*):
57
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
58
+ instead.
59
+ prompt_2 (`str` or `List[str]`, *optional*):
60
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
61
+ will be used instead
62
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
63
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
64
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
65
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
66
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
67
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
68
+ images must be passed as a list such that each element of the list can be correctly batched for input
69
+ to a single ControlNet.
70
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
71
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
72
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
73
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
74
+ num_inference_steps (`int`, *optional*, defaults to 50):
75
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
76
+ expense of slower inference.
77
+ sigmas (`List[float]`, *optional*):
78
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
79
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
80
+ will be used.
81
+ guidance_scale (`float`, *optional*, defaults to 3.5):
82
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
83
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
84
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
85
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
86
+ usually at the expense of lower image quality.
87
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
88
+ The number of images to generate per prompt.
89
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
90
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
91
+ to make generation deterministic.
92
+ latents (`torch.FloatTensor`, *optional*):
93
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
94
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
95
+ tensor will ge generated by sampling using the supplied random `generator`.
96
+ prompt_embeds (`torch.FloatTensor`, *optional*):
97
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
98
+ provided, text embeddings will be generated from `prompt` input argument.
99
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
100
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
101
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
102
+ output_type (`str`, *optional*, defaults to `"pil"`):
103
+ The output format of the generate image. Choose between
104
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
105
+ return_dict (`bool`, *optional*, defaults to `True`):
106
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
107
+ joint_attention_kwargs (`dict`, *optional*):
108
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
109
+ `self.processor` in
110
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
111
+ callback_on_step_end (`Callable`, *optional*):
112
+ A function that calls at the end of each denoising steps during the inference. The function is called
113
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
114
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
115
+ `callback_on_step_end_tensor_inputs`.
116
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
117
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
118
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
119
+ `._callback_tensor_inputs` attribute of your pipeline class.
120
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
121
+
122
+ Examples:
123
+
124
+ Returns:
125
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
126
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
127
+ images.
128
+ """
129
+
130
+ height = height or self.default_sample_size * self.vae_scale_factor
131
+ width = width or self.default_sample_size * self.vae_scale_factor
132
+
133
+ # 1. Check inputs. Raise error if not correct
134
+ self.check_inputs(
135
+ prompt,
136
+ prompt_2,
137
+ height,
138
+ width,
139
+ prompt_embeds=prompt_embeds,
140
+ pooled_prompt_embeds=pooled_prompt_embeds,
141
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
142
+ max_sequence_length=max_sequence_length,
143
+ )
144
+
145
+ self._guidance_scale = guidance_scale
146
+ self._joint_attention_kwargs = joint_attention_kwargs
147
+ self._interrupt = False
148
+
149
+ # 2. Define call parameters
150
+ if prompt is not None and isinstance(prompt, str):
151
+ batch_size = 1
152
+ elif prompt is not None and isinstance(prompt, list):
153
+ batch_size = len(prompt)
154
+ else:
155
+ batch_size = prompt_embeds.shape[0]
156
+
157
+ device = self._execution_device
158
+
159
+ # 3. Prepare text embeddings
160
+ lora_scale = (
161
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
162
+ )
163
+ (
164
+ prompt_embeds,
165
+ pooled_prompt_embeds,
166
+ text_ids,
167
+ ) = self.encode_prompt(
168
+ prompt=prompt,
169
+ prompt_2=prompt_2,
170
+ prompt_embeds=prompt_embeds,
171
+ pooled_prompt_embeds=pooled_prompt_embeds,
172
+ device=device,
173
+ num_images_per_prompt=num_images_per_prompt,
174
+ max_sequence_length=max_sequence_length,
175
+ lora_scale=lora_scale,
176
+ )
177
+
178
+ # 4. Prepare latent variables
179
+ # num_channels_latents = self.transformer.config.in_channels // 8
180
+ num_channels_latents = 128 // 8
181
+
182
+ # pull mask off control image if there is one it is a pil image
183
+ mask = None
184
+ if control_image is not None and control_image.mode == "RGBA":
185
+ control_img_array = np.array(control_image)
186
+ mask = control_img_array[:, :, 3:4]
187
+ # scale it to 0 - 1
188
+ mask = mask / 255.0
189
+ # control image ideally would be a full image here
190
+ control_img_array = control_img_array[:, :, :3]
191
+ control_image = Image.fromarray(control_img_array.astype(np.uint8))
192
+
193
+ if control_image is not None:
194
+
195
+ control_image = self.prepare_image(
196
+ image=control_image,
197
+ width=width,
198
+ height=height,
199
+ batch_size=batch_size * num_images_per_prompt,
200
+ num_images_per_prompt=num_images_per_prompt,
201
+ device=device,
202
+ dtype=self.vae.dtype,
203
+ )
204
+
205
+ if control_image.ndim == 4:
206
+ num_control_channels = num_channels_latents
207
+ control_image = self.vae.encode(control_image).latent_dist.sample(generator=generator)
208
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
209
+
210
+ if mask is not None:
211
+ transform = transforms.Compose([
212
+ transforms.ToTensor(),
213
+ ])
214
+ mask = transform(mask).to(device, dtype=control_image.dtype).unsqueeze(0)
215
+ # resize mask to match control image
216
+ mask = F.interpolate(mask, size=(control_image.shape[2], control_image.shape[3]), mode="bilinear", align_corners=False)
217
+ mask = mask.to(device)
218
+ # apply the mask to the control image so the inpaint latent area is 0
219
+ # mask is currently 0 for inpaint area and 1 for image area
220
+ control_image = control_image * mask
221
+ # invert mask so it is 1 for inpaint area and 0 for image area
222
+ mask = 1 - mask
223
+ control_image = torch.cat([control_image, mask], dim=1)
224
+ num_control_channels += 1
225
+
226
+ height_control_image, width_control_image = control_image.shape[2:]
227
+ control_image = self._pack_latents(
228
+ control_image,
229
+ batch_size * num_images_per_prompt,
230
+ num_control_channels,
231
+ height_control_image,
232
+ width_control_image,
233
+ )
234
+
235
+ latents, latent_image_ids = self.prepare_latents(
236
+ batch_size * num_images_per_prompt,
237
+ num_channels_latents,
238
+ height,
239
+ width,
240
+ prompt_embeds.dtype,
241
+ device,
242
+ generator,
243
+ latents,
244
+ )
245
+
246
+ # 5. Prepare timesteps
247
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
248
+ image_seq_len = latents.shape[1]
249
+ mu = calculate_shift(
250
+ image_seq_len,
251
+ self.scheduler.config.get("base_image_seq_len", 256),
252
+ self.scheduler.config.get("max_image_seq_len", 4096),
253
+ self.scheduler.config.get("base_shift", 0.5),
254
+ self.scheduler.config.get("max_shift", 1.15),
255
+ )
256
+ timesteps, num_inference_steps = retrieve_timesteps(
257
+ self.scheduler,
258
+ num_inference_steps,
259
+ device,
260
+ sigmas=sigmas,
261
+ mu=mu,
262
+ )
263
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
264
+ self._num_timesteps = len(timesteps)
265
+
266
+ # handle guidance
267
+ if self.transformer.config.guidance_embeds:
268
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
269
+ guidance = guidance.expand(latents.shape[0])
270
+ else:
271
+ guidance = None
272
+
273
+ # 6. Denoising loop
274
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
275
+ for i, t in enumerate(timesteps):
276
+ if self.interrupt:
277
+ continue
278
+
279
+ # make a blank control latent
280
+ control_image_list = [
281
+ # impainting
282
+ torch.cat([torch.zeros_like(latents), torch.ones_like(latents[:, :, :4])], dim=2),
283
+ # control
284
+ torch.zeros_like(latents),
285
+ ]
286
+ if control_image is not None:
287
+
288
+ control_image_list[control_image_idx] = control_image
289
+
290
+ latent_model_input = torch.cat([latents] + control_image_list, dim=2)
291
+
292
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
293
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
294
+
295
+ noise_pred = self.transformer(
296
+ hidden_states=latent_model_input,
297
+ timestep=timestep / 1000,
298
+ guidance=guidance,
299
+ pooled_projections=pooled_prompt_embeds,
300
+ encoder_hidden_states=prompt_embeds,
301
+ txt_ids=text_ids,
302
+ img_ids=latent_image_ids,
303
+ joint_attention_kwargs=self.joint_attention_kwargs,
304
+ return_dict=False,
305
+ )[0]
306
+
307
+ # compute the previous noisy sample x_t -> x_t-1
308
+ latents_dtype = latents.dtype
309
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
310
+
311
+ if latents.dtype != latents_dtype:
312
+ if torch.backends.mps.is_available():
313
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
314
+ latents = latents.to(latents_dtype)
315
+
316
+ if callback_on_step_end is not None:
317
+ callback_kwargs = {}
318
+ for k in callback_on_step_end_tensor_inputs:
319
+ callback_kwargs[k] = locals()[k]
320
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
321
+
322
+ latents = callback_outputs.pop("latents", latents)
323
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
324
+
325
+ # call the callback, if provided
326
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
327
+ progress_bar.update()
328
+
329
+ if XLA_AVAILABLE:
330
+ xm.mark_step()
331
+
332
+ if output_type == "latent":
333
+ image = latents
334
+ else:
335
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
336
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
337
+ image = self.vae.decode(latents, return_dict=False)[0]
338
+ image = self.image_processor.postprocess(image, output_type=output_type)
339
+
340
+ # Offload all models
341
+ self.maybe_free_model_hooks()
342
+
343
+ if not return_dict:
344
+ return (image,)
345
+
346
+ return FluxPipelineOutput(images=image)
347
+
348
+