prithivMLmods commited on
Commit
79a2132
·
verified ·
1 Parent(s): b3a3e40

Delete pipeline_fill_sd_xl.py

Browse files
Files changed (1) hide show
  1. pipeline_fill_sd_xl.py +0 -544
pipeline_fill_sd_xl.py DELETED
@@ -1,544 +0,0 @@
1
- from typing import List, Optional, Union
2
-
3
- import cv2
4
- import PIL.Image
5
- import torch
6
- import torch.nn.functional as F
7
- from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
8
- from diffusers.models import AutoencoderKL, UNet2DConditionModel
9
- from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
10
- from diffusers.schedulers import KarrasDiffusionSchedulers
11
- from diffusers.utils.torch_utils import randn_tensor
12
- from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
13
-
14
- from controlnet_union import ControlNetModel_Union
15
-
16
- def latents_to_rgb(latents):
17
- weights = ((60, -60, 25, -70), (60, -5, 15, -50), (60, 10, -5, -35))
18
-
19
- weights_tensor = torch.t(
20
- torch.tensor(weights, dtype=latents.dtype).to(latents.device)
21
- )
22
- biases_tensor = torch.tensor((150, 140, 130), dtype=latents.dtype).to(
23
- latents.device
24
- )
25
- rgb_tensor = torch.einsum(
26
- "...lxy,lr -> ...rxy", latents, weights_tensor
27
- ) + biases_tensor.unsqueeze(-1).unsqueeze(-1)
28
- image_array = rgb_tensor.clamp(0, 255)[0].byte().cpu().numpy()
29
- image_array = image_array.transpose(1, 2, 0) # Change the order of dimensions
30
-
31
- denoised_image = cv2.fastNlMeansDenoisingColored(image_array, None, 10, 10, 7, 21)
32
- blurred_image = cv2.GaussianBlur(denoised_image, (5, 5), 0)
33
- final_image = PIL.Image.fromarray(blurred_image)
34
-
35
- width, height = final_image.size
36
- final_image = final_image.resize(
37
- (width * 8, height * 8), PIL.Image.Resampling.LANCZOS
38
- )
39
-
40
- return final_image
41
-
42
-
43
- def retrieve_timesteps(
44
- scheduler,
45
- num_inference_steps: Optional[int] = None,
46
- device: Optional[Union[str, torch.device]] = None,
47
- **kwargs,
48
- ):
49
- scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
50
- timesteps = scheduler.timesteps
51
-
52
- return timesteps, num_inference_steps
53
-
54
-
55
- class StableDiffusionXLFillPipeline(DiffusionPipeline, StableDiffusionMixin):
56
- model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
57
- _optional_components = [
58
- "tokenizer",
59
- "tokenizer_2",
60
- "text_encoder",
61
- "text_encoder_2",
62
- ]
63
-
64
- def __init__(
65
- self,
66
- vae: AutoencoderKL,
67
- text_encoder: CLIPTextModel,
68
- text_encoder_2: CLIPTextModelWithProjection,
69
- tokenizer: CLIPTokenizer,
70
- tokenizer_2: CLIPTokenizer,
71
- unet: UNet2DConditionModel,
72
- controlnet: ControlNetModel_Union,
73
- scheduler: KarrasDiffusionSchedulers,
74
- force_zeros_for_empty_prompt: bool = True,
75
- ):
76
- super().__init__()
77
-
78
- self.register_modules(
79
- vae=vae,
80
- text_encoder=text_encoder,
81
- text_encoder_2=text_encoder_2,
82
- tokenizer=tokenizer,
83
- tokenizer_2=tokenizer_2,
84
- unet=unet,
85
- controlnet=controlnet,
86
- scheduler=scheduler,
87
- )
88
- self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
89
- self.image_processor = VaeImageProcessor(
90
- vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True
91
- )
92
- self.control_image_processor = VaeImageProcessor(
93
- vae_scale_factor=self.vae_scale_factor,
94
- do_convert_rgb=True,
95
- do_normalize=False,
96
- )
97
-
98
- self.register_to_config(
99
- force_zeros_for_empty_prompt=force_zeros_for_empty_prompt
100
- )
101
-
102
- def encode_prompt(
103
- self,
104
- prompt: str,
105
- device: Optional[torch.device] = None,
106
- do_classifier_free_guidance: bool = True,
107
- ):
108
- device = device or self._execution_device
109
- prompt = [prompt] if isinstance(prompt, str) else prompt
110
-
111
- if prompt is not None:
112
- batch_size = len(prompt)
113
-
114
- # Define tokenizers and text encoders
115
- tokenizers = (
116
- [self.tokenizer, self.tokenizer_2]
117
- if self.tokenizer is not None
118
- else [self.tokenizer_2]
119
- )
120
- text_encoders = (
121
- [self.text_encoder, self.text_encoder_2]
122
- if self.text_encoder is not None
123
- else [self.text_encoder_2]
124
- )
125
-
126
- prompt_2 = prompt
127
- prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
128
-
129
- # textual inversion: process multi-vector tokens if necessary
130
- prompt_embeds_list = []
131
- prompts = [prompt, prompt_2]
132
- for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
133
- text_inputs = tokenizer(
134
- prompt,
135
- padding="max_length",
136
- max_length=tokenizer.model_max_length,
137
- truncation=True,
138
- return_tensors="pt",
139
- )
140
-
141
- text_input_ids = text_inputs.input_ids
142
-
143
- prompt_embeds = text_encoder(
144
- text_input_ids.to(device), output_hidden_states=True
145
- )
146
-
147
- # We are only ALWAYS interested in the pooled output of the final text encoder
148
- pooled_prompt_embeds = prompt_embeds[0]
149
- prompt_embeds = prompt_embeds.hidden_states[-2]
150
- prompt_embeds_list.append(prompt_embeds)
151
-
152
- prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
153
-
154
- # get unconditional embeddings for classifier free guidance
155
- zero_out_negative_prompt = True
156
- negative_prompt_embeds = None
157
- negative_pooled_prompt_embeds = None
158
-
159
- if do_classifier_free_guidance and zero_out_negative_prompt:
160
- negative_prompt_embeds = torch.zeros_like(prompt_embeds)
161
- negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
162
- elif do_classifier_free_guidance and negative_prompt_embeds is None:
163
- negative_prompt = ""
164
- negative_prompt_2 = negative_prompt
165
-
166
- # normalize str to list
167
- negative_prompt = (
168
- batch_size * [negative_prompt]
169
- if isinstance(negative_prompt, str)
170
- else negative_prompt
171
- )
172
- negative_prompt_2 = (
173
- batch_size * [negative_prompt_2]
174
- if isinstance(negative_prompt_2, str)
175
- else negative_prompt_2
176
- )
177
-
178
- uncond_tokens: List[str]
179
- if prompt is not None and type(prompt) is not type(negative_prompt):
180
- raise TypeError(
181
- f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
182
- f" {type(prompt)}."
183
- )
184
- elif batch_size != len(negative_prompt):
185
- raise ValueError(
186
- f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
187
- f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
188
- " the batch size of `prompt`."
189
- )
190
- else:
191
- uncond_tokens = [negative_prompt, negative_prompt_2]
192
-
193
- negative_prompt_embeds_list = []
194
- for negative_prompt, tokenizer, text_encoder in zip(
195
- uncond_tokens, tokenizers, text_encoders
196
- ):
197
- max_length = prompt_embeds.shape[1]
198
- uncond_input = tokenizer(
199
- negative_prompt,
200
- padding="max_length",
201
- max_length=max_length,
202
- truncation=True,
203
- return_tensors="pt",
204
- )
205
-
206
- negative_prompt_embeds = text_encoder(
207
- uncond_input.input_ids.to(device),
208
- output_hidden_states=True,
209
- )
210
- # We are only ALWAYS interested in the pooled output of the final text encoder
211
- negative_pooled_prompt_embeds = negative_prompt_embeds[0]
212
- negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
213
-
214
- negative_prompt_embeds_list.append(negative_prompt_embeds)
215
-
216
- negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
217
-
218
- prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
219
-
220
- bs_embed, seq_len, _ = prompt_embeds.shape
221
- # duplicate text embeddings for each generation per prompt, using mps friendly method
222
- prompt_embeds = prompt_embeds.repeat(1, 1, 1)
223
- prompt_embeds = prompt_embeds.view(bs_embed * 1, seq_len, -1)
224
-
225
- if do_classifier_free_guidance:
226
- # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
227
- seq_len = negative_prompt_embeds.shape[1]
228
-
229
- if self.text_encoder_2 is not None:
230
- negative_prompt_embeds = negative_prompt_embeds.to(
231
- dtype=self.text_encoder_2.dtype, device=device
232
- )
233
- else:
234
- negative_prompt_embeds = negative_prompt_embeds.to(
235
- dtype=self.unet.dtype, device=device
236
- )
237
-
238
- negative_prompt_embeds = negative_prompt_embeds.repeat(1, 1, 1)
239
- negative_prompt_embeds = negative_prompt_embeds.view(
240
- batch_size * 1, seq_len, -1
241
- )
242
-
243
- pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, 1).view(bs_embed * 1, -1)
244
- if do_classifier_free_guidance:
245
- negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(
246
- 1, 1
247
- ).view(bs_embed * 1, -1)
248
-
249
- return (
250
- prompt_embeds,
251
- negative_prompt_embeds,
252
- pooled_prompt_embeds,
253
- negative_pooled_prompt_embeds,
254
- )
255
-
256
- def check_inputs(
257
- self,
258
- prompt_embeds,
259
- negative_prompt_embeds,
260
- pooled_prompt_embeds,
261
- negative_pooled_prompt_embeds,
262
- image,
263
- controlnet_conditioning_scale=1.0,
264
- ):
265
- if prompt_embeds is None:
266
- raise ValueError(
267
- "Provide `prompt_embeds`. Cannot leave `prompt_embeds` undefined."
268
- )
269
-
270
- if negative_prompt_embeds is None:
271
- raise ValueError(
272
- "Provide `negative_prompt_embeds`. Cannot leave `negative_prompt_embeds` undefined."
273
- )
274
-
275
- if prompt_embeds.shape != negative_prompt_embeds.shape:
276
- raise ValueError(
277
- "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
278
- f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
279
- f" {negative_prompt_embeds.shape}."
280
- )
281
-
282
- if prompt_embeds is not None and pooled_prompt_embeds is None:
283
- raise ValueError(
284
- "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`."
285
- )
286
-
287
- if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
288
- raise ValueError(
289
- "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
290
- )
291
-
292
- # Check `image`
293
- is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
294
- self.controlnet, torch._dynamo.eval_frame.OptimizedModule
295
- )
296
- if (
297
- isinstance(self.controlnet, ControlNetModel_Union)
298
- or is_compiled
299
- and isinstance(self.controlnet._orig_mod, ControlNetModel_Union)
300
- ):
301
- if not isinstance(image, PIL.Image.Image):
302
- raise TypeError(
303
- f"image must be passed and has to be a PIL image, but is {type(image)}"
304
- )
305
-
306
- else:
307
- assert False
308
-
309
- # Check `controlnet_conditioning_scale`
310
- if (
311
- isinstance(self.controlnet, ControlNetModel_Union)
312
- or is_compiled
313
- and isinstance(self.controlnet._orig_mod, ControlNetModel_Union)
314
- ):
315
- if not isinstance(controlnet_conditioning_scale, float):
316
- raise TypeError(
317
- "For single controlnet: `controlnet_conditioning_scale` must be type `float`."
318
- )
319
- else:
320
- assert False
321
-
322
- def prepare_image(self, image, device, dtype, do_classifier_free_guidance=False):
323
- image = self.control_image_processor.preprocess(image).to(dtype=torch.float32)
324
-
325
- image_batch_size = image.shape[0]
326
-
327
- image = image.repeat_interleave(image_batch_size, dim=0)
328
- image = image.to(device=device, dtype=dtype)
329
-
330
- if do_classifier_free_guidance:
331
- image = torch.cat([image] * 2)
332
-
333
- return image
334
-
335
- def prepare_latents(
336
- self, batch_size, num_channels_latents, height, width, dtype, device
337
- ):
338
- shape = (
339
- batch_size,
340
- num_channels_latents,
341
- int(height) // self.vae_scale_factor,
342
- int(width) // self.vae_scale_factor,
343
- )
344
-
345
- latents = randn_tensor(shape, device=device, dtype=dtype)
346
-
347
- # scale the initial noise by the standard deviation required by the scheduler
348
- latents = latents * self.scheduler.init_noise_sigma
349
- return latents
350
-
351
- @property
352
- def guidance_scale(self):
353
- return self._guidance_scale
354
-
355
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
356
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
357
- # corresponds to doing no classifier free guidance.
358
- @property
359
- def do_classifier_free_guidance(self):
360
- return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
361
-
362
- @property
363
- def num_timesteps(self):
364
- return self._num_timesteps
365
-
366
- @torch.no_grad()
367
- def __call__(
368
- self,
369
- prompt_embeds: torch.Tensor,
370
- negative_prompt_embeds: torch.Tensor,
371
- pooled_prompt_embeds: torch.Tensor,
372
- negative_pooled_prompt_embeds: torch.Tensor,
373
- image: PipelineImageInput = None,
374
- num_inference_steps: int = 8,
375
- guidance_scale: float = 1.5,
376
- controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
377
- ):
378
- # 1. Check inputs. Raise error if not correct
379
- self.check_inputs(
380
- prompt_embeds,
381
- negative_prompt_embeds,
382
- pooled_prompt_embeds,
383
- negative_pooled_prompt_embeds,
384
- image,
385
- controlnet_conditioning_scale,
386
- )
387
-
388
- self._guidance_scale = guidance_scale
389
-
390
- # 2. Define call parameters
391
- batch_size = 1
392
- device = self._execution_device
393
-
394
- # 4. Prepare image
395
- if isinstance(self.controlnet, ControlNetModel_Union):
396
- image = self.prepare_image(
397
- image=image,
398
- device=device,
399
- dtype=self.controlnet.dtype,
400
- do_classifier_free_guidance=self.do_classifier_free_guidance,
401
- )
402
- height, width = image.shape[-2:]
403
- else:
404
- assert False
405
-
406
- # 5. Prepare timesteps
407
- timesteps, num_inference_steps = retrieve_timesteps(
408
- self.scheduler, num_inference_steps, device
409
- )
410
- self._num_timesteps = len(timesteps)
411
-
412
- # 6. Prepare latent variables
413
- num_channels_latents = self.unet.config.in_channels
414
- latents = self.prepare_latents(
415
- batch_size,
416
- num_channels_latents,
417
- height,
418
- width,
419
- prompt_embeds.dtype,
420
- device,
421
- )
422
-
423
- # 7 Prepare added time ids & embeddings
424
- add_text_embeds = pooled_prompt_embeds
425
-
426
- add_time_ids = negative_add_time_ids = torch.tensor(
427
- image.shape[-2:] + torch.Size([0, 0]) + image.shape[-2:]
428
- ).unsqueeze(0)
429
-
430
- if self.do_classifier_free_guidance:
431
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
432
- add_text_embeds = torch.cat(
433
- [negative_pooled_prompt_embeds, add_text_embeds], dim=0
434
- )
435
- add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
436
-
437
- prompt_embeds = prompt_embeds.to(device)
438
- add_text_embeds = add_text_embeds.to(device)
439
- add_time_ids = add_time_ids.to(device).repeat(batch_size, 1)
440
-
441
- controlnet_image_list = [0, 0, 0, 0, 0, 0, image, 0]
442
- union_control_type = (
443
- torch.Tensor([0, 0, 0, 0, 0, 0, 1, 0])
444
- .to(device, dtype=prompt_embeds.dtype)
445
- .repeat(batch_size * 2, 1)
446
- )
447
-
448
- added_cond_kwargs = {
449
- "text_embeds": add_text_embeds,
450
- "time_ids": add_time_ids,
451
- "control_type": union_control_type,
452
- }
453
-
454
- controlnet_prompt_embeds = prompt_embeds
455
- controlnet_added_cond_kwargs = added_cond_kwargs
456
-
457
- # 8. Denoising loop
458
- num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
459
-
460
- with self.progress_bar(total=num_inference_steps) as progress_bar:
461
- for i, t in enumerate(timesteps):
462
- # expand the latents if we are doing classifier free guidance
463
- latent_model_input = (
464
- torch.cat([latents] * 2)
465
- if self.do_classifier_free_guidance
466
- else latents
467
- )
468
- latent_model_input = self.scheduler.scale_model_input(
469
- latent_model_input, t
470
- )
471
-
472
- # controlnet(s) inference
473
- control_model_input = latent_model_input
474
-
475
- down_block_res_samples, mid_block_res_sample = self.controlnet(
476
- control_model_input,
477
- t,
478
- encoder_hidden_states=controlnet_prompt_embeds,
479
- controlnet_cond_list=controlnet_image_list,
480
- conditioning_scale=controlnet_conditioning_scale,
481
- guess_mode=False,
482
- added_cond_kwargs=controlnet_added_cond_kwargs,
483
- return_dict=False,
484
- )
485
-
486
- # predict the noise residual
487
- noise_pred = self.unet(
488
- latent_model_input,
489
- t,
490
- encoder_hidden_states=prompt_embeds,
491
- timestep_cond=None,
492
- cross_attention_kwargs={},
493
- down_block_additional_residuals=down_block_res_samples,
494
- mid_block_additional_residual=mid_block_res_sample,
495
- added_cond_kwargs=added_cond_kwargs,
496
- return_dict=False,
497
- )[0]
498
-
499
- # perform guidance
500
- if self.do_classifier_free_guidance:
501
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
502
- noise_pred = noise_pred_uncond + guidance_scale * (
503
- noise_pred_text - noise_pred_uncond
504
- )
505
-
506
- # compute the previous noisy sample x_t -> x_t-1
507
- latents = self.scheduler.step(
508
- noise_pred, t, latents, return_dict=False
509
- )[0]
510
-
511
- if i == 2:
512
- prompt_embeds = prompt_embeds[-1:]
513
- add_text_embeds = add_text_embeds[-1:]
514
- add_time_ids = add_time_ids[-1:]
515
- union_control_type = union_control_type[-1:]
516
-
517
- added_cond_kwargs = {
518
- "text_embeds": add_text_embeds,
519
- "time_ids": add_time_ids,
520
- "control_type": union_control_type,
521
- }
522
-
523
- controlnet_prompt_embeds = prompt_embeds
524
- controlnet_added_cond_kwargs = added_cond_kwargs
525
-
526
- image = image[-1:]
527
- controlnet_image_list = [0, 0, 0, 0, 0, 0, image, 0]
528
-
529
- self._guidance_scale = 0.0
530
-
531
- if i == len(timesteps) - 1 or (
532
- (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
533
- ):
534
- progress_bar.update()
535
- yield latents_to_rgb(latents)
536
-
537
- latents = latents / self.vae.config.scaling_factor
538
- image = self.vae.decode(latents, return_dict=False)[0]
539
- image = self.image_processor.postprocess(image)[0]
540
-
541
- # Offload all models
542
- self.maybe_free_model_hooks()
543
-
544
- yield image