Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
a701b72
·
verified ·
1 Parent(s): e73e60b

Upload folder using huggingface_hub

Browse files
main/regional_prompting_stable_diffusion.py CHANGED
@@ -1,14 +1,43 @@
 
1
  import math
2
- from typing import Dict, Optional
3
 
4
  import torch
5
  import torchvision.transforms.functional as FF
6
  from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
7
 
8
- from diffusers import StableDiffusionPipeline
 
 
 
 
 
 
9
  from diffusers.models import AutoencoderKL, UNet2DConditionModel
 
 
 
10
  from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
11
  from diffusers.schedulers import KarrasDiffusionSchedulers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
 
14
  try:
@@ -21,7 +50,14 @@ KCOMM = "ADDCOMM"
21
  KBRK = "BREAK"
22
 
23
 
24
- class RegionalPromptingStableDiffusionPipeline(StableDiffusionPipeline):
 
 
 
 
 
 
 
25
  r"""
26
  Args for Regional Prompting Pipeline:
27
  rp_args:dict
@@ -78,17 +114,7 @@ class RegionalPromptingStableDiffusionPipeline(StableDiffusionPipeline):
78
  image_encoder: CLIPVisionModelWithProjection = None,
79
  requires_safety_checker: bool = True,
80
  ):
81
- super().__init__(
82
- vae,
83
- text_encoder,
84
- tokenizer,
85
- unet,
86
- scheduler,
87
- safety_checker,
88
- feature_extractor,
89
- image_encoder,
90
- requires_safety_checker,
91
- )
92
  self.register_modules(
93
  vae=vae,
94
  text_encoder=text_encoder,
@@ -99,6 +125,17 @@ class RegionalPromptingStableDiffusionPipeline(StableDiffusionPipeline):
99
  feature_extractor=feature_extractor,
100
  image_encoder=image_encoder,
101
  )
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  @torch.no_grad()
104
  def __call__(
@@ -413,7 +450,7 @@ class RegionalPromptingStableDiffusionPipeline(StableDiffusionPipeline):
413
 
414
  hook_forwards(self.unet)
415
 
416
- output = StableDiffusionPipeline(**self.components)(
417
  prompt=prompt,
418
  prompt_embeds=embs,
419
  negative_prompt=negative_prompt,
@@ -449,6 +486,909 @@ class RegionalPromptingStableDiffusionPipeline(StableDiffusionPipeline):
449
 
450
  return output
451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
 
453
  ### Make prompt list for each regions
454
  def promptsmaker(prompts, batch):
@@ -663,3 +1603,88 @@ def scaled_dot_product_attention(
663
  get_attn_maps(self, attn_weight)
664
  attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
665
  return attn_weight @ value
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
  import math
3
+ from typing import Any, Callable, Dict, List, Optional, Union
4
 
5
  import torch
6
  import torchvision.transforms.functional as FF
7
  from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
8
 
9
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
10
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
11
+ from diffusers.loaders import StableDiffusionLoraLoaderMixin
12
+ from diffusers.loaders.ip_adapter import IPAdapterMixin
13
+ from diffusers.loaders.lora_pipeline import LoraLoaderMixin
14
+ from diffusers.loaders.single_file import FromSingleFileMixin
15
+ from diffusers.loaders.textual_inversion import TextualInversionLoaderMixin
16
  from diffusers.models import AutoencoderKL, UNet2DConditionModel
17
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
18
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
19
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
20
  from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
21
  from diffusers.schedulers import KarrasDiffusionSchedulers
22
+ from diffusers.utils import (
23
+ USE_PEFT_BACKEND,
24
+ deprecate,
25
+ is_torch_xla_available,
26
+ logging,
27
+ scale_lora_layers,
28
+ unscale_lora_layers,
29
+ )
30
+ from diffusers.utils.torch_utils import randn_tensor
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
 
42
 
43
  try:
 
50
  KBRK = "BREAK"
51
 
52
 
53
+ class RegionalPromptingStableDiffusionPipeline(
54
+ DiffusionPipeline,
55
+ TextualInversionLoaderMixin,
56
+ LoraLoaderMixin,
57
+ IPAdapterMixin,
58
+ FromSingleFileMixin,
59
+ StableDiffusionLoraLoaderMixin,
60
+ ):
61
  r"""
62
  Args for Regional Prompting Pipeline:
63
  rp_args:dict
 
114
  image_encoder: CLIPVisionModelWithProjection = None,
115
  requires_safety_checker: bool = True,
116
  ):
117
+ super().__init__()
 
 
 
 
 
 
 
 
 
 
118
  self.register_modules(
119
  vae=vae,
120
  text_encoder=text_encoder,
 
125
  feature_extractor=feature_extractor,
126
  image_encoder=image_encoder,
127
  )
128
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
129
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
130
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
131
+
132
+ # Initialize additional properties needed for DiffusionPipeline
133
+ self._num_timesteps = None
134
+ self._interrupt = False
135
+ self._guidance_scale = 7.5
136
+ self._guidance_rescale = 0.0
137
+ self._clip_skip = None
138
+ self._cross_attention_kwargs = None
139
 
140
  @torch.no_grad()
141
  def __call__(
 
450
 
451
  hook_forwards(self.unet)
452
 
453
+ output = self.stable_diffusion_call(
454
  prompt=prompt,
455
  prompt_embeds=embs,
456
  negative_prompt=negative_prompt,
 
486
 
487
  return output
488
 
489
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
490
+ def prepare_extra_step_kwargs(self, generator, eta):
491
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
492
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
493
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
494
+ # and should be between [0, 1]
495
+
496
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
497
+ extra_step_kwargs = {}
498
+ if accepts_eta:
499
+ extra_step_kwargs["eta"] = eta
500
+
501
+ # check if the scheduler accepts generator
502
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
503
+ if accepts_generator:
504
+ extra_step_kwargs["generator"] = generator
505
+ return extra_step_kwargs
506
+
507
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
508
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
509
+ shape = (
510
+ batch_size,
511
+ num_channels_latents,
512
+ int(height) // self.vae_scale_factor,
513
+ int(width) // self.vae_scale_factor,
514
+ )
515
+ if isinstance(generator, list) and len(generator) != batch_size:
516
+ raise ValueError(
517
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
518
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
519
+ )
520
+
521
+ if latents is None:
522
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
523
+ else:
524
+ latents = latents.to(device)
525
+
526
+ # scale the initial noise by the standard deviation required by the scheduler
527
+ latents = latents * self.scheduler.init_noise_sigma
528
+ return latents
529
+
530
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
531
+ def encode_prompt(
532
+ self,
533
+ prompt,
534
+ device,
535
+ num_images_per_prompt,
536
+ do_classifier_free_guidance,
537
+ negative_prompt=None,
538
+ prompt_embeds: Optional[torch.Tensor] = None,
539
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
540
+ lora_scale: Optional[float] = None,
541
+ clip_skip: Optional[int] = None,
542
+ ):
543
+ r"""
544
+ Encodes the prompt into text encoder hidden states.
545
+
546
+ Args:
547
+ prompt (`str` or `List[str]`, *optional*):
548
+ prompt to be encoded
549
+ device: (`torch.device`):
550
+ torch device
551
+ num_images_per_prompt (`int`):
552
+ number of images that should be generated per prompt
553
+ do_classifier_free_guidance (`bool`):
554
+ whether to use classifier free guidance or not
555
+ negative_prompt (`str` or `List[str]`, *optional*):
556
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
557
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
558
+ less than `1`).
559
+ prompt_embeds (`torch.Tensor`, *optional*):
560
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
561
+ provided, text embeddings will be generated from `prompt` input argument.
562
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
563
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
564
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
565
+ argument.
566
+ lora_scale (`float`, *optional*):
567
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
568
+ clip_skip (`int`, *optional*):
569
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
570
+ the output of the pre-final layer will be used for computing the prompt embeddings.
571
+ """
572
+ # set lora scale so that monkey patched LoRA
573
+ # function of text encoder can correctly access it
574
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
575
+ self._lora_scale = lora_scale
576
+
577
+ # dynamically adjust the LoRA scale
578
+ if not USE_PEFT_BACKEND:
579
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
580
+ else:
581
+ scale_lora_layers(self.text_encoder, lora_scale)
582
+
583
+ if prompt is not None and isinstance(prompt, str):
584
+ batch_size = 1
585
+ elif prompt is not None and isinstance(prompt, list):
586
+ batch_size = len(prompt)
587
+ else:
588
+ batch_size = prompt_embeds.shape[0]
589
+
590
+ if prompt_embeds is None:
591
+ # textual inversion: process multi-vector tokens if necessary
592
+ if isinstance(self, TextualInversionLoaderMixin):
593
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
594
+
595
+ text_inputs = self.tokenizer(
596
+ prompt,
597
+ padding="max_length",
598
+ max_length=self.tokenizer.model_max_length,
599
+ truncation=True,
600
+ return_tensors="pt",
601
+ )
602
+ text_input_ids = text_inputs.input_ids
603
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
604
+
605
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
606
+ text_input_ids, untruncated_ids
607
+ ):
608
+ removed_text = self.tokenizer.batch_decode(
609
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
610
+ )
611
+ logger.warning(
612
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
613
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
614
+ )
615
+
616
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
617
+ attention_mask = text_inputs.attention_mask.to(device)
618
+ else:
619
+ attention_mask = None
620
+
621
+ if clip_skip is None:
622
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
623
+ prompt_embeds = prompt_embeds[0]
624
+ else:
625
+ prompt_embeds = self.text_encoder(
626
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
627
+ )
628
+ # Access the `hidden_states` first, that contains a tuple of
629
+ # all the hidden states from the encoder layers. Then index into
630
+ # the tuple to access the hidden states from the desired layer.
631
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
632
+ # We also need to apply the final LayerNorm here to not mess with the
633
+ # representations. The `last_hidden_states` that we typically use for
634
+ # obtaining the final prompt representations passes through the LayerNorm
635
+ # layer.
636
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
637
+
638
+ if self.text_encoder is not None:
639
+ prompt_embeds_dtype = self.text_encoder.dtype
640
+ elif self.unet is not None:
641
+ prompt_embeds_dtype = self.unet.dtype
642
+ else:
643
+ prompt_embeds_dtype = prompt_embeds.dtype
644
+
645
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
646
+
647
+ bs_embed, seq_len, _ = prompt_embeds.shape
648
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
649
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
650
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
651
+
652
+ # get unconditional embeddings for classifier free guidance
653
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
654
+ uncond_tokens: List[str]
655
+ if negative_prompt is None:
656
+ uncond_tokens = [""] * batch_size
657
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
658
+ raise TypeError(
659
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
660
+ f" {type(prompt)}."
661
+ )
662
+ elif isinstance(negative_prompt, str):
663
+ uncond_tokens = [negative_prompt]
664
+ elif batch_size != len(negative_prompt):
665
+ raise ValueError(
666
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
667
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
668
+ " the batch size of `prompt`."
669
+ )
670
+ else:
671
+ uncond_tokens = negative_prompt
672
+
673
+ # textual inversion: process multi-vector tokens if necessary
674
+ if isinstance(self, TextualInversionLoaderMixin):
675
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
676
+
677
+ max_length = prompt_embeds.shape[1]
678
+ uncond_input = self.tokenizer(
679
+ uncond_tokens,
680
+ padding="max_length",
681
+ max_length=max_length,
682
+ truncation=True,
683
+ return_tensors="pt",
684
+ )
685
+
686
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
687
+ attention_mask = uncond_input.attention_mask.to(device)
688
+ else:
689
+ attention_mask = None
690
+
691
+ negative_prompt_embeds = self.text_encoder(
692
+ uncond_input.input_ids.to(device),
693
+ attention_mask=attention_mask,
694
+ )
695
+ negative_prompt_embeds = negative_prompt_embeds[0]
696
+
697
+ if do_classifier_free_guidance:
698
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
699
+ seq_len = negative_prompt_embeds.shape[1]
700
+
701
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
702
+
703
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
704
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
705
+
706
+ if self.text_encoder is not None:
707
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
708
+ # Retrieve the original scale by scaling back the LoRA layers
709
+ unscale_lora_layers(self.text_encoder, lora_scale)
710
+
711
+ return prompt_embeds, negative_prompt_embeds
712
+
713
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
714
+ def check_inputs(
715
+ self,
716
+ prompt,
717
+ height,
718
+ width,
719
+ callback_steps,
720
+ negative_prompt=None,
721
+ prompt_embeds=None,
722
+ negative_prompt_embeds=None,
723
+ ip_adapter_image=None,
724
+ ip_adapter_image_embeds=None,
725
+ callback_on_step_end_tensor_inputs=None,
726
+ ):
727
+ if height % 8 != 0 or width % 8 != 0:
728
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
729
+
730
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
731
+ raise ValueError(
732
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
733
+ f" {type(callback_steps)}."
734
+ )
735
+ if callback_on_step_end_tensor_inputs is not None and not all(
736
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
737
+ ):
738
+ raise ValueError(
739
+ 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]}"
740
+ )
741
+
742
+ if prompt is not None and prompt_embeds is not None:
743
+ raise ValueError(
744
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
745
+ " only forward one of the two."
746
+ )
747
+ elif prompt is None and prompt_embeds is None:
748
+ raise ValueError(
749
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
750
+ )
751
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
752
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
753
+
754
+ if negative_prompt is not None and negative_prompt_embeds is not None:
755
+ raise ValueError(
756
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
757
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
758
+ )
759
+
760
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
761
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
762
+ raise ValueError(
763
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
764
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
765
+ f" {negative_prompt_embeds.shape}."
766
+ )
767
+
768
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
769
+ raise ValueError(
770
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
771
+ )
772
+
773
+ if ip_adapter_image_embeds is not None:
774
+ if not isinstance(ip_adapter_image_embeds, list):
775
+ raise ValueError(
776
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
777
+ )
778
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
779
+ raise ValueError(
780
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
781
+ )
782
+
783
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
784
+ @torch.no_grad()
785
+ def stable_diffusion_call(
786
+ self,
787
+ prompt: Union[str, List[str]] = None,
788
+ height: Optional[int] = None,
789
+ width: Optional[int] = None,
790
+ num_inference_steps: int = 50,
791
+ timesteps: List[int] = None,
792
+ sigmas: List[float] = None,
793
+ guidance_scale: float = 7.5,
794
+ negative_prompt: Optional[Union[str, List[str]]] = None,
795
+ num_images_per_prompt: Optional[int] = 1,
796
+ eta: float = 0.0,
797
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
798
+ latents: Optional[torch.Tensor] = None,
799
+ prompt_embeds: Optional[torch.Tensor] = None,
800
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
801
+ ip_adapter_image: Optional[PipelineImageInput] = None,
802
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
803
+ output_type: Optional[str] = "pil",
804
+ return_dict: bool = True,
805
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
806
+ guidance_rescale: float = 0.0,
807
+ clip_skip: Optional[int] = None,
808
+ callback_on_step_end: Optional[
809
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
810
+ ] = None,
811
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
812
+ **kwargs,
813
+ ):
814
+ r"""
815
+ The call function to the pipeline for generation.
816
+
817
+ Args:
818
+ prompt (`str` or `List[str]`, *optional*):
819
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
820
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
821
+ The height in pixels of the generated image.
822
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
823
+ The width in pixels of the generated image.
824
+ num_inference_steps (`int`, *optional*, defaults to 50):
825
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
826
+ expense of slower inference.
827
+ timesteps (`List[int]`, *optional*):
828
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
829
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
830
+ passed will be used. Must be in descending order.
831
+ sigmas (`List[float]`, *optional*):
832
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
833
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
834
+ will be used.
835
+ guidance_scale (`float`, *optional*, defaults to 7.5):
836
+ A higher guidance scale value encourages the model to generate images closely linked to the text
837
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
838
+ negative_prompt (`str` or `List[str]`, *optional*):
839
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
840
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
841
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
842
+ The number of images to generate per prompt.
843
+ eta (`float`, *optional*, defaults to 0.0):
844
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
845
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
846
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
847
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
848
+ generation deterministic.
849
+ latents (`torch.Tensor`, *optional*):
850
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
851
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
852
+ tensor is generated by sampling using the supplied random `generator`.
853
+ prompt_embeds (`torch.Tensor`, *optional*):
854
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
855
+ provided, text embeddings are generated from the `prompt` input argument.
856
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
857
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
858
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
859
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
860
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
861
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
862
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
863
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
864
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
865
+ output_type (`str`, *optional*, defaults to `"pil"`):
866
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
867
+ return_dict (`bool`, *optional*, defaults to `True`):
868
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
869
+ plain tuple.
870
+ cross_attention_kwargs (`dict`, *optional*):
871
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
872
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
873
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
874
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
875
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
876
+ using zero terminal SNR.
877
+ clip_skip (`int`, *optional*):
878
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
879
+ the output of the pre-final layer will be used for computing the prompt embeddings.
880
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
881
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
882
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
883
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
884
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
885
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
886
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
887
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
888
+ `._callback_tensor_inputs` attribute of your pipeline class.
889
+
890
+ Examples:
891
+
892
+ Returns:
893
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
894
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
895
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
896
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
897
+ "not-safe-for-work" (nsfw) content.
898
+ """
899
+
900
+ callback = kwargs.pop("callback", None)
901
+ callback_steps = kwargs.pop("callback_steps", None)
902
+ self.model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
903
+ self._optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
904
+ self._exclude_from_cpu_offload = ["safety_checker"]
905
+ self._callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
906
+
907
+ if callback is not None:
908
+ deprecate(
909
+ "callback",
910
+ "1.0.0",
911
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
912
+ )
913
+ if callback_steps is not None:
914
+ deprecate(
915
+ "callback_steps",
916
+ "1.0.0",
917
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
918
+ )
919
+
920
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
921
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
922
+
923
+ # 0. Default height and width to unet
924
+ if not height or not width:
925
+ height = (
926
+ self.unet.config.sample_size
927
+ if self._is_unet_config_sample_size_int
928
+ else self.unet.config.sample_size[0]
929
+ )
930
+ width = (
931
+ self.unet.config.sample_size
932
+ if self._is_unet_config_sample_size_int
933
+ else self.unet.config.sample_size[1]
934
+ )
935
+ height, width = height * self.vae_scale_factor, width * self.vae_scale_factor
936
+ # to deal with lora scaling and other possible forward hooks
937
+
938
+ # 1. Check inputs. Raise error if not correct
939
+ self.check_inputs(
940
+ prompt,
941
+ height,
942
+ width,
943
+ callback_steps,
944
+ negative_prompt,
945
+ prompt_embeds,
946
+ negative_prompt_embeds,
947
+ ip_adapter_image,
948
+ ip_adapter_image_embeds,
949
+ callback_on_step_end_tensor_inputs,
950
+ )
951
+
952
+ self._guidance_scale = guidance_scale
953
+ self._guidance_rescale = guidance_rescale
954
+ self._clip_skip = clip_skip
955
+ self._cross_attention_kwargs = cross_attention_kwargs
956
+ self._interrupt = False
957
+
958
+ # 2. Define call parameters
959
+ if prompt is not None and isinstance(prompt, str):
960
+ batch_size = 1
961
+ elif prompt is not None and isinstance(prompt, list):
962
+ batch_size = len(prompt)
963
+ else:
964
+ batch_size = prompt_embeds.shape[0]
965
+
966
+ device = self._execution_device
967
+
968
+ # 3. Encode input prompt
969
+ lora_scale = (
970
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
971
+ )
972
+
973
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
974
+ prompt,
975
+ device,
976
+ num_images_per_prompt,
977
+ self.do_classifier_free_guidance,
978
+ negative_prompt,
979
+ prompt_embeds=prompt_embeds,
980
+ negative_prompt_embeds=negative_prompt_embeds,
981
+ lora_scale=lora_scale,
982
+ clip_skip=self.clip_skip,
983
+ )
984
+
985
+ # For classifier free guidance, we need to do two forward passes.
986
+ # Here we concatenate the unconditional and text embeddings into a single batch
987
+ # to avoid doing two forward passes
988
+ if self.do_classifier_free_guidance:
989
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
990
+
991
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
992
+ image_embeds = self.prepare_ip_adapter_image_embeds(
993
+ ip_adapter_image,
994
+ ip_adapter_image_embeds,
995
+ device,
996
+ batch_size * num_images_per_prompt,
997
+ self.do_classifier_free_guidance,
998
+ )
999
+
1000
+ # 4. Prepare timesteps
1001
+ timesteps, num_inference_steps = retrieve_timesteps(
1002
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1003
+ )
1004
+
1005
+ # 5. Prepare latent variables
1006
+ num_channels_latents = self.unet.config.in_channels
1007
+ latents = self.prepare_latents(
1008
+ batch_size * num_images_per_prompt,
1009
+ num_channels_latents,
1010
+ height,
1011
+ width,
1012
+ prompt_embeds.dtype,
1013
+ device,
1014
+ generator,
1015
+ latents,
1016
+ )
1017
+
1018
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1019
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1020
+
1021
+ # 6.1 Add image embeds for IP-Adapter
1022
+ added_cond_kwargs = (
1023
+ {"image_embeds": image_embeds}
1024
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
1025
+ else None
1026
+ )
1027
+
1028
+ # 6.2 Optionally get Guidance Scale Embedding
1029
+ timestep_cond = None
1030
+ if self.unet.config.time_cond_proj_dim is not None:
1031
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1032
+ timestep_cond = self.get_guidance_scale_embedding(
1033
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1034
+ ).to(device=device, dtype=latents.dtype)
1035
+
1036
+ # 7. Denoising loop
1037
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1038
+ self._num_timesteps = len(timesteps)
1039
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1040
+ for i, t in enumerate(timesteps):
1041
+ if self.interrupt:
1042
+ continue
1043
+
1044
+ # expand the latents if we are doing classifier free guidance
1045
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1046
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1047
+
1048
+ # predict the noise residual
1049
+ noise_pred = self.unet(
1050
+ latent_model_input,
1051
+ t,
1052
+ encoder_hidden_states=prompt_embeds,
1053
+ timestep_cond=timestep_cond,
1054
+ cross_attention_kwargs=self.cross_attention_kwargs,
1055
+ added_cond_kwargs=added_cond_kwargs,
1056
+ return_dict=False,
1057
+ )[0]
1058
+
1059
+ # perform guidance
1060
+ if self.do_classifier_free_guidance:
1061
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1062
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1063
+
1064
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1065
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1066
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1067
+
1068
+ # compute the previous noisy sample x_t -> x_t-1
1069
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1070
+
1071
+ if callback_on_step_end is not None:
1072
+ callback_kwargs = {}
1073
+ for k in callback_on_step_end_tensor_inputs:
1074
+ callback_kwargs[k] = locals()[k]
1075
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1076
+
1077
+ latents = callback_outputs.pop("latents", latents)
1078
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1079
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1080
+
1081
+ # call the callback, if provided
1082
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1083
+ progress_bar.update()
1084
+ if callback is not None and i % callback_steps == 0:
1085
+ step_idx = i // getattr(self.scheduler, "order", 1)
1086
+ callback(step_idx, t, latents)
1087
+
1088
+ if XLA_AVAILABLE:
1089
+ xm.mark_step()
1090
+
1091
+ if not output_type == "latent":
1092
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1093
+ 0
1094
+ ]
1095
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1096
+ else:
1097
+ image = latents
1098
+ has_nsfw_concept = None
1099
+
1100
+ if has_nsfw_concept is None:
1101
+ do_denormalize = [True] * image.shape[0]
1102
+ else:
1103
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1104
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1105
+
1106
+ # Offload all models
1107
+ self.maybe_free_model_hooks()
1108
+
1109
+ if not return_dict:
1110
+ return (image, has_nsfw_concept)
1111
+
1112
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1113
+
1114
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
1115
+ def _encode_prompt(
1116
+ self,
1117
+ prompt,
1118
+ device,
1119
+ num_images_per_prompt,
1120
+ do_classifier_free_guidance,
1121
+ negative_prompt=None,
1122
+ prompt_embeds: Optional[torch.Tensor] = None,
1123
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1124
+ lora_scale: Optional[float] = None,
1125
+ **kwargs,
1126
+ ):
1127
+ r"""Encodes the prompt into text encoder hidden states."""
1128
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
1129
+
1130
+ # get prompt text embeddings
1131
+ text_inputs = self.tokenizer(
1132
+ prompt,
1133
+ padding="max_length",
1134
+ max_length=self.tokenizer.model_max_length,
1135
+ truncation=True,
1136
+ return_tensors="pt",
1137
+ )
1138
+ text_input_ids = text_inputs.input_ids
1139
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
1140
+
1141
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
1142
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
1143
+ logger.warning(
1144
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
1145
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
1146
+ )
1147
+
1148
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
1149
+ attention_mask = text_inputs.attention_mask.to(device)
1150
+ else:
1151
+ attention_mask = None
1152
+
1153
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
1154
+ # cast text_encoder.dtype to prevent overflow when using bf16
1155
+ text_input_ids = text_input_ids.to(device=device, dtype=self.text_encoder.dtype)
1156
+ prompt_embeds = self.text_encoder(
1157
+ text_input_ids,
1158
+ attention_mask=attention_mask,
1159
+ )
1160
+ prompt_embeds = prompt_embeds[0]
1161
+ else:
1162
+ text_encoder_lora_scale = None
1163
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
1164
+ text_encoder_lora_scale = lora_scale
1165
+ if text_encoder_lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
1166
+ # dynamically adjust the LoRA scale
1167
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
1168
+
1169
+ prompt_embeds = self.text_encoder(
1170
+ text_input_ids.to(device),
1171
+ attention_mask=attention_mask,
1172
+ )
1173
+ prompt_embeds = prompt_embeds[0]
1174
+
1175
+ # duplicate text embeddings for each generation per prompt
1176
+ bs_embed, seq_len, _ = prompt_embeds.shape
1177
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
1178
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
1179
+
1180
+ # get unconditional embeddings for classifier free guidance
1181
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
1182
+ uncond_tokens: List[str]
1183
+ if negative_prompt is None:
1184
+ uncond_tokens = [""]
1185
+ elif type(prompt) is not type(negative_prompt):
1186
+ raise TypeError(
1187
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
1188
+ f" {type(prompt)}."
1189
+ )
1190
+ elif isinstance(negative_prompt, str):
1191
+ uncond_tokens = [negative_prompt]
1192
+ elif batch_size != len(negative_prompt):
1193
+ raise ValueError(
1194
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
1195
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
1196
+ " the batch size of `prompt`."
1197
+ )
1198
+ else:
1199
+ uncond_tokens = negative_prompt
1200
+
1201
+ # textual inversion: process multi-vector tokens if necessary
1202
+ if isinstance(self, TextualInversionLoaderMixin):
1203
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
1204
+
1205
+ max_length = prompt_embeds.shape[1]
1206
+ uncond_input = self.tokenizer(
1207
+ uncond_tokens,
1208
+ padding="max_length",
1209
+ max_length=max_length,
1210
+ truncation=True,
1211
+ return_tensors="pt",
1212
+ )
1213
+
1214
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
1215
+ attention_mask = uncond_input.attention_mask.to(device)
1216
+ else:
1217
+ attention_mask = None
1218
+
1219
+ negative_prompt_embeds = self.text_encoder(
1220
+ uncond_input.input_ids.to(device),
1221
+ attention_mask=attention_mask,
1222
+ )
1223
+ negative_prompt_embeds = negative_prompt_embeds[0]
1224
+
1225
+ if do_classifier_free_guidance:
1226
+ # duplicate unconditional embeddings for each generation per prompt
1227
+ seq_len = negative_prompt_embeds.shape[1]
1228
+
1229
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
1230
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
1231
+
1232
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
1233
+ # Unscale LoRA weights to avoid overfitting. This is a hack
1234
+ unscale_lora_layers(self.text_encoder, lora_scale)
1235
+
1236
+ return prompt_embeds, negative_prompt_embeds
1237
+
1238
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
1239
+ """Encodes the image into image encoder hidden states."""
1240
+ dtype = next(self.image_encoder.parameters()).dtype
1241
+
1242
+ if not isinstance(image, torch.Tensor):
1243
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
1244
+
1245
+ image = image.to(device=device, dtype=dtype)
1246
+ if output_hidden_states:
1247
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
1248
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
1249
+ uncond_image_enc_hidden_states = self.image_encoder(
1250
+ torch.zeros_like(image), output_hidden_states=True
1251
+ ).hidden_states[-2]
1252
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
1253
+ num_images_per_prompt, dim=0
1254
+ )
1255
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
1256
+ else:
1257
+ image_embeds = self.image_encoder(image).image_embeds
1258
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
1259
+ uncond_image_embeds = torch.zeros_like(image_embeds)
1260
+
1261
+ return image_embeds, uncond_image_embeds
1262
+
1263
+ def prepare_ip_adapter_image_embeds(
1264
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
1265
+ ):
1266
+ """Prepares and processes IP-Adapter image embeddings."""
1267
+ image_embeds = []
1268
+ if do_classifier_free_guidance:
1269
+ negative_image_embeds = []
1270
+ if ip_adapter_image_embeds is None:
1271
+ for image in ip_adapter_image:
1272
+ if not isinstance(image, torch.Tensor):
1273
+ image = self.image_processor.preprocess(image)
1274
+ image = image.to(device=device)
1275
+ if len(image.shape) == 3:
1276
+ image = image.unsqueeze(0)
1277
+ image_emb, neg_image_emb = self.encode_image(image, device, num_images_per_prompt, True)
1278
+ image_embeds.append(image_emb)
1279
+ if do_classifier_free_guidance:
1280
+ negative_image_embeds.append(neg_image_emb)
1281
+
1282
+ if len(image_embeds) == 1:
1283
+ image_embeds = image_embeds[0]
1284
+ if do_classifier_free_guidance:
1285
+ negative_image_embeds = negative_image_embeds[0]
1286
+ else:
1287
+ image_embeds = torch.cat(image_embeds, dim=0)
1288
+ if do_classifier_free_guidance:
1289
+ negative_image_embeds = torch.cat(negative_image_embeds, dim=0)
1290
+ else:
1291
+ repeat_dim = 2 if do_classifier_free_guidance else 1
1292
+ image_embeds = ip_adapter_image_embeds.repeat_interleave(repeat_dim, dim=0)
1293
+ if do_classifier_free_guidance:
1294
+ negative_image_embeds = torch.zeros_like(image_embeds)
1295
+
1296
+ if do_classifier_free_guidance:
1297
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1298
+
1299
+ return image_embeds
1300
+
1301
+ def run_safety_checker(self, image, device, dtype):
1302
+ """Runs the safety checker on the generated image."""
1303
+ if self.safety_checker is None:
1304
+ has_nsfw_concept = None
1305
+ return image, has_nsfw_concept
1306
+
1307
+ if isinstance(self.safety_checker, StableDiffusionSafetyChecker):
1308
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
1309
+ image, has_nsfw_concept = self.safety_checker(
1310
+ images=image,
1311
+ clip_input=safety_checker_input.pixel_values.to(dtype),
1312
+ )
1313
+ else:
1314
+ images_np = self.numpy_to_pil(image)
1315
+ safety_checker_input = self.safety_checker.feature_extractor(images_np, return_tensors="pt").to(device)
1316
+ has_nsfw_concept = self.safety_checker(
1317
+ images=image,
1318
+ clip_input=safety_checker_input.pixel_values.to(dtype),
1319
+ )[1]
1320
+
1321
+ return image, has_nsfw_concept
1322
+
1323
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
1324
+ def decode_latents(self, latents):
1325
+ """Decodes the latents to images."""
1326
+ latents = 1 / self.vae.config.scaling_factor * latents
1327
+ image = self.vae.decode(latents, return_dict=False)[0]
1328
+ image = (image / 2 + 0.5).clamp(0, 1)
1329
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
1330
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
1331
+ return image
1332
+
1333
+ @property
1334
+ def guidance_scale(self):
1335
+ return self._guidance_scale
1336
+
1337
+ @property
1338
+ def guidance_rescale(self):
1339
+ return self._guidance_rescale
1340
+
1341
+ # copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion
1342
+ def get_guidance_scale_embedding(
1343
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1344
+ ):
1345
+ """Gets the guidance scale embedding for classifier free guidance conditioning.
1346
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1347
+
1348
+ Args:
1349
+ w (`torch.Tensor`):
1350
+ The guidance scale tensor used for classifier free guidance conditioning.
1351
+ embedding_dim (`int`, defaults to 512):
1352
+ The dimensionality of the guidance scale embedding.
1353
+ dtype (`torch.dtype`, defaults to torch.float32):
1354
+ The dtype of the embedding.
1355
+
1356
+ Returns:
1357
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1358
+ """
1359
+ assert len(w.shape) == 1
1360
+ w = w * 1000.0
1361
+
1362
+ half_dim = embedding_dim // 2
1363
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1364
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1365
+ emb = w.to(dtype)[:, None] * emb[None, :]
1366
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1367
+ if embedding_dim % 2 == 1: # zero pad
1368
+ emb = torch.nn.functional.pad(emb, (0, 1))
1369
+ assert emb.shape == (w.shape[0], embedding_dim)
1370
+ return emb
1371
+
1372
+ @property
1373
+ def clip_skip(self):
1374
+ return self._clip_skip
1375
+
1376
+ @property
1377
+ def num_timesteps(self):
1378
+ return self._num_timesteps
1379
+
1380
+ @property
1381
+ def interrupt(self):
1382
+ return self._interrupt
1383
+
1384
+ @property
1385
+ def cross_attention_kwargs(self):
1386
+ return self._cross_attention_kwargs
1387
+
1388
+ @property
1389
+ def do_classifier_free_guidance(self):
1390
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1391
+
1392
 
1393
  ### Make prompt list for each regions
1394
  def promptsmaker(prompts, batch):
 
1603
  get_attn_maps(self, attn_weight)
1604
  attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
1605
  return attn_weight @ value
1606
+
1607
+
1608
+ def retrieve_timesteps(
1609
+ scheduler,
1610
+ num_inference_steps: Optional[int] = None,
1611
+ device: Optional[Union[str, torch.device]] = None,
1612
+ timesteps: Optional[List[int]] = None,
1613
+ sigmas: Optional[List[float]] = None,
1614
+ **kwargs,
1615
+ ):
1616
+ r"""
1617
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
1618
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
1619
+
1620
+ Args:
1621
+ scheduler (`SchedulerMixin`):
1622
+ The scheduler to get timesteps from.
1623
+ num_inference_steps (`int`):
1624
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
1625
+ must be `None`.
1626
+ device (`str` or `torch.device`, *optional*):
1627
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
1628
+ timesteps (`List[int]`, *optional*):
1629
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
1630
+ `num_inference_steps` and `sigmas` must be `None`.
1631
+ sigmas (`List[float]`, *optional*):
1632
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
1633
+ `num_inference_steps` and `timesteps` must be `None`.
1634
+
1635
+ Returns:
1636
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
1637
+ second element is the number of inference steps.
1638
+ """
1639
+ if timesteps is not None and sigmas is not None:
1640
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
1641
+ if timesteps is not None:
1642
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
1643
+ if not accepts_timesteps:
1644
+ raise ValueError(
1645
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
1646
+ f" timestep schedules. Please check whether you are using the correct scheduler."
1647
+ )
1648
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
1649
+ timesteps = scheduler.timesteps
1650
+ num_inference_steps = len(timesteps)
1651
+ elif sigmas is not None:
1652
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
1653
+ if not accept_sigmas:
1654
+ raise ValueError(
1655
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
1656
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
1657
+ )
1658
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
1659
+ timesteps = scheduler.timesteps
1660
+ num_inference_steps = len(timesteps)
1661
+ else:
1662
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
1663
+ timesteps = scheduler.timesteps
1664
+ return timesteps, num_inference_steps
1665
+
1666
+
1667
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
1668
+ r"""
1669
+ Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
1670
+ Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
1671
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1672
+
1673
+ Args:
1674
+ noise_cfg (`torch.Tensor`):
1675
+ The predicted noise tensor for the guided diffusion process.
1676
+ noise_pred_text (`torch.Tensor`):
1677
+ The predicted noise tensor for the text-guided diffusion process.
1678
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1679
+ A rescale factor applied to the noise predictions.
1680
+
1681
+ Returns:
1682
+ noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
1683
+ """
1684
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
1685
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
1686
+ # rescale the results from guidance (fixes overexposure)
1687
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
1688
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
1689
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
1690
+ return noise_cfg