multimodalart HF staff commited on
Commit
43cbf18
1 Parent(s): 994e46a

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +746 -521
pipeline.py CHANGED
@@ -1,45 +1,66 @@
1
- # Implementation of StableDiffusionPAGPipeline
2
 
3
  import inspect
4
- from typing import Any, Callable, Dict, List, Optional, Union
5
 
6
  import torch
7
  import torch.nn.functional as F
8
  from packaging import version
9
- from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
10
 
11
- from diffusers.configuration_utils import FrozenDict
 
 
 
 
 
 
 
12
  from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
13
- from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
 
 
 
 
 
14
  from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
15
- from diffusers.models.attention_processor import FusedAttnProcessor2_0
 
 
 
 
 
 
16
  from diffusers.models.lora import adjust_lora_scale_text_encoder
17
  from diffusers.schedulers import KarrasDiffusionSchedulers
18
  from diffusers.utils import (
19
  USE_PEFT_BACKEND,
20
  deprecate,
 
 
21
  logging,
22
  replace_example_docstring,
23
  scale_lora_layers,
24
  unscale_lora_layers,
25
  )
26
  from diffusers.utils.torch_utils import randn_tensor
27
- from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
- from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
29
- from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
30
 
31
  from diffusers.models.attention_processor import Attention, AttnProcessor2_0
32
 
33
-
34
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
 
36
  EXAMPLE_DOC_STRING = """
37
  Examples:
38
  ```py
39
  >>> import torch
40
- >>> from diffusers import StableDiffusionPipeline
41
- >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
 
 
 
42
  >>> pipe = pipe.to("cuda")
 
43
  >>> prompt = "a photo of an astronaut riding a horse on mars"
44
  >>> image = pipe(prompt).images[0]
45
  ```
@@ -271,6 +292,17 @@ class PAGCFGIdentitySelfAttnProcessor:
271
 
272
  return hidden_states
273
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
  def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
276
  """
@@ -296,18 +328,20 @@ def retrieve_timesteps(
296
  """
297
  Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
298
  custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
 
299
  Args:
300
  scheduler (`SchedulerMixin`):
301
  The scheduler to get timesteps from.
302
  num_inference_steps (`int`):
303
- The number of diffusion steps used when generating samples with a pre-trained model. If used,
304
- `timesteps` must be `None`.
305
  device (`str` or `torch.device`, *optional*):
306
  The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
307
  timesteps (`List[int]`, *optional*):
308
  Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
309
  timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
310
  must be `None`.
 
311
  Returns:
312
  `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
313
  second element is the number of inference steps.
@@ -327,215 +361,143 @@ def retrieve_timesteps(
327
  timesteps = scheduler.timesteps
328
  return timesteps, num_inference_steps
329
 
330
-
331
- class StableDiffusionPipeline(
332
- DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
 
 
 
 
333
  ):
334
  r"""
335
- Pipeline for text-to-image generation using Stable Diffusion.
336
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
337
- implemented for all pipelines (downloading, saving, running on a particular device, etc.).
 
 
338
  The pipeline also inherits the following loading methods:
339
  - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
340
- - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
341
- - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
342
  - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
 
 
343
  - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
 
344
  Args:
345
  vae ([`AutoencoderKL`]):
346
- Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
347
- text_encoder ([`~transformers.CLIPTextModel`]):
348
- Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
349
- tokenizer ([`~transformers.CLIPTokenizer`]):
350
- A `CLIPTokenizer` to tokenize text.
351
- unet ([`UNet2DConditionModel`]):
352
- A `UNet2DConditionModel` to denoise the encoded image latents.
 
 
 
 
 
 
 
 
 
 
 
353
  scheduler ([`SchedulerMixin`]):
354
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
355
  [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
356
- safety_checker ([`StableDiffusionSafetyChecker`]):
357
- Classification module that estimates whether generated images could be considered offensive or harmful.
358
- Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
359
- about a model's potential harms.
360
- feature_extractor ([`~transformers.CLIPImageProcessor`]):
361
- A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
 
362
  """
363
 
364
- model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
365
- _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
366
- _exclude_from_cpu_offload = ["safety_checker"]
367
- _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  def __init__(
370
  self,
371
  vae: AutoencoderKL,
372
  text_encoder: CLIPTextModel,
 
373
  tokenizer: CLIPTokenizer,
 
374
  unet: UNet2DConditionModel,
375
  scheduler: KarrasDiffusionSchedulers,
376
- safety_checker: StableDiffusionSafetyChecker,
377
- feature_extractor: CLIPImageProcessor,
378
  image_encoder: CLIPVisionModelWithProjection = None,
379
- requires_safety_checker: bool = True,
 
 
380
  ):
381
  super().__init__()
382
 
383
- if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
384
- deprecation_message = (
385
- f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
386
- f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
387
- "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
388
- " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
389
- " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
390
- " file"
391
- )
392
- deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
393
- new_config = dict(scheduler.config)
394
- new_config["steps_offset"] = 1
395
- scheduler._internal_dict = FrozenDict(new_config)
396
-
397
- if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
398
- deprecation_message = (
399
- f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
400
- " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
401
- " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
402
- " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
403
- " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
404
- )
405
- deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
406
- new_config = dict(scheduler.config)
407
- new_config["clip_sample"] = False
408
- scheduler._internal_dict = FrozenDict(new_config)
409
-
410
- if safety_checker is None and requires_safety_checker:
411
- logger.warning(
412
- f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
413
- " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
414
- " results in services or applications open to the public. Both the diffusers team and Hugging Face"
415
- " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
416
- " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
417
- " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
418
- )
419
-
420
- if safety_checker is not None and feature_extractor is None:
421
- raise ValueError(
422
- "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
423
- " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
424
- )
425
-
426
- is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
427
- version.parse(unet.config._diffusers_version).base_version
428
- ) < version.parse("0.9.0.dev0")
429
- is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
430
- if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
431
- deprecation_message = (
432
- "The configuration file of the unet has set the default `sample_size` to smaller than"
433
- " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
434
- " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
435
- " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
436
- " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
437
- " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
438
- " in the config might lead to incorrect results in future versions. If you have downloaded this"
439
- " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
440
- " the `unet/config.json` file"
441
- )
442
- deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
443
- new_config = dict(unet.config)
444
- new_config["sample_size"] = 64
445
- unet._internal_dict = FrozenDict(new_config)
446
-
447
  self.register_modules(
448
  vae=vae,
449
  text_encoder=text_encoder,
 
450
  tokenizer=tokenizer,
 
451
  unet=unet,
452
  scheduler=scheduler,
453
- safety_checker=safety_checker,
454
- feature_extractor=feature_extractor,
455
  image_encoder=image_encoder,
 
456
  )
 
457
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
458
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
459
- self.register_to_config(requires_safety_checker=requires_safety_checker)
460
 
461
- def enable_vae_slicing(self):
462
- r"""
463
- Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
464
- compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
465
- """
466
- self.vae.enable_slicing()
467
 
468
- def disable_vae_slicing(self):
469
- r"""
470
- Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
471
- computing decoding in one step.
472
- """
473
- self.vae.disable_slicing()
474
 
475
- def enable_vae_tiling(self):
476
- r"""
477
- Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
478
- compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
479
- processing larger images.
480
- """
481
- self.vae.enable_tiling()
482
-
483
- def disable_vae_tiling(self):
484
- r"""
485
- Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
486
- computing decoding in one step.
487
- """
488
- self.vae.disable_tiling()
489
-
490
- def _encode_prompt(
491
- self,
492
- prompt,
493
- device,
494
- num_images_per_prompt,
495
- do_classifier_free_guidance,
496
- negative_prompt=None,
497
- prompt_embeds: Optional[torch.FloatTensor] = None,
498
- negative_prompt_embeds: Optional[torch.FloatTensor] = None,
499
- lora_scale: Optional[float] = None,
500
- **kwargs,
501
- ):
502
- deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
503
- deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
504
-
505
- prompt_embeds_tuple = self.encode_prompt(
506
- prompt=prompt,
507
- device=device,
508
- num_images_per_prompt=num_images_per_prompt,
509
- do_classifier_free_guidance=do_classifier_free_guidance,
510
- negative_prompt=negative_prompt,
511
- prompt_embeds=prompt_embeds,
512
- negative_prompt_embeds=negative_prompt_embeds,
513
- lora_scale=lora_scale,
514
- **kwargs,
515
- )
516
-
517
- # concatenate for backwards comp
518
- prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
519
-
520
- return prompt_embeds
521
 
522
  def encode_prompt(
523
  self,
524
- prompt,
525
- device,
526
- num_images_per_prompt,
527
- do_classifier_free_guidance,
528
- negative_prompt=None,
 
 
529
  prompt_embeds: Optional[torch.FloatTensor] = None,
530
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
 
 
531
  lora_scale: Optional[float] = None,
532
  clip_skip: Optional[int] = None,
533
  ):
534
  r"""
535
  Encodes the prompt into text encoder hidden states.
 
536
  Args:
537
  prompt (`str` or `List[str]`, *optional*):
538
  prompt to be encoded
 
 
 
539
  device: (`torch.device`):
540
  torch device
541
  num_images_per_prompt (`int`):
@@ -546,6 +508,9 @@ class StableDiffusionPipeline(
546
  The prompt or prompts not to guide the image generation. If not defined, one has to pass
547
  `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
548
  less than `1`).
 
 
 
549
  prompt_embeds (`torch.FloatTensor`, *optional*):
550
  Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
551
  provided, text embeddings will be generated from `prompt` input argument.
@@ -553,104 +518,118 @@ class StableDiffusionPipeline(
553
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
554
  weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
555
  argument.
 
 
 
 
 
 
 
556
  lora_scale (`float`, *optional*):
557
- A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
558
  clip_skip (`int`, *optional*):
559
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
560
  the output of the pre-final layer will be used for computing the prompt embeddings.
561
  """
 
 
562
  # set lora scale so that monkey patched LoRA
563
  # function of text encoder can correctly access it
564
- if lora_scale is not None and isinstance(self, LoraLoaderMixin):
565
  self._lora_scale = lora_scale
566
 
567
  # dynamically adjust the LoRA scale
568
- if not USE_PEFT_BACKEND:
569
- adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
570
- else:
571
- scale_lora_layers(self.text_encoder, lora_scale)
 
572
 
573
- if prompt is not None and isinstance(prompt, str):
574
- batch_size = 1
575
- elif prompt is not None and isinstance(prompt, list):
 
 
 
 
 
 
576
  batch_size = len(prompt)
577
  else:
578
  batch_size = prompt_embeds.shape[0]
579
 
 
 
 
 
 
 
580
  if prompt_embeds is None:
581
- # textual inversion: process multi-vector tokens if necessary
582
- if isinstance(self, TextualInversionLoaderMixin):
583
- prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
584
-
585
- text_inputs = self.tokenizer(
586
- prompt,
587
- padding="max_length",
588
- max_length=self.tokenizer.model_max_length,
589
- truncation=True,
590
- return_tensors="pt",
591
- )
592
- text_input_ids = text_inputs.input_ids
593
- untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
594
 
595
- if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
596
- text_input_ids, untruncated_ids
597
- ):
598
- removed_text = self.tokenizer.batch_decode(
599
- untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
600
- )
601
- logger.warning(
602
- "The following part of your input was truncated because CLIP can only handle sequences up to"
603
- f" {self.tokenizer.model_max_length} tokens: {removed_text}"
 
 
 
 
604
  )
605
 
606
- if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
607
- attention_mask = text_inputs.attention_mask.to(device)
608
- else:
609
- attention_mask = None
610
 
611
- if clip_skip is None:
612
- prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
613
- prompt_embeds = prompt_embeds[0]
614
- else:
615
- prompt_embeds = self.text_encoder(
616
- text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
617
- )
618
- # Access the `hidden_states` first, that contains a tuple of
619
- # all the hidden states from the encoder layers. Then index into
620
- # the tuple to access the hidden states from the desired layer.
621
- prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
622
- # We also need to apply the final LayerNorm here to not mess with the
623
- # representations. The `last_hidden_states` that we typically use for
624
- # obtaining the final prompt representations passes through the LayerNorm
625
- # layer.
626
- prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
627
 
628
- if self.text_encoder is not None:
629
- prompt_embeds_dtype = self.text_encoder.dtype
630
- elif self.unet is not None:
631
- prompt_embeds_dtype = self.unet.dtype
632
- else:
633
- prompt_embeds_dtype = prompt_embeds.dtype
634
 
635
- prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
 
 
 
 
 
 
636
 
637
- bs_embed, seq_len, _ = prompt_embeds.shape
638
- # duplicate text embeddings for each generation per prompt, using mps friendly method
639
- prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
640
- prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
641
 
642
  # get unconditional embeddings for classifier free guidance
643
- if do_classifier_free_guidance and negative_prompt_embeds is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
644
  uncond_tokens: List[str]
645
- if negative_prompt is None:
646
- uncond_tokens = [""] * batch_size
647
- elif prompt is not None and type(prompt) is not type(negative_prompt):
648
  raise TypeError(
649
  f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
650
  f" {type(prompt)}."
651
  )
652
- elif isinstance(negative_prompt, str):
653
- uncond_tokens = [negative_prompt]
654
  elif batch_size != len(negative_prompt):
655
  raise ValueError(
656
  f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
@@ -658,47 +637,77 @@ class StableDiffusionPipeline(
658
  " the batch size of `prompt`."
659
  )
660
  else:
661
- uncond_tokens = negative_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
 
663
- # textual inversion: process multi-vector tokens if necessary
664
- if isinstance(self, TextualInversionLoaderMixin):
665
- uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
666
-
667
- max_length = prompt_embeds.shape[1]
668
- uncond_input = self.tokenizer(
669
- uncond_tokens,
670
- padding="max_length",
671
- max_length=max_length,
672
- truncation=True,
673
- return_tensors="pt",
674
- )
675
 
676
- if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
677
- attention_mask = uncond_input.attention_mask.to(device)
678
- else:
679
- attention_mask = None
680
 
681
- negative_prompt_embeds = self.text_encoder(
682
- uncond_input.input_ids.to(device),
683
- attention_mask=attention_mask,
684
- )
685
- negative_prompt_embeds = negative_prompt_embeds[0]
 
 
 
 
 
 
686
 
687
  if do_classifier_free_guidance:
688
  # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
689
  seq_len = negative_prompt_embeds.shape[1]
690
 
691
- negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
 
 
 
692
 
693
  negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
694
  negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
695
 
696
- if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
697
- # Retrieve the original scale by scaling back the LoRA layers
698
- unscale_lora_layers(self.text_encoder, lora_scale)
 
 
 
 
699
 
700
- return prompt_embeds, negative_prompt_embeds
 
 
 
701
 
 
 
 
 
 
 
 
 
702
  def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
703
  dtype = next(self.image_encoder.parameters()).dtype
704
 
@@ -723,8 +732,9 @@ class StableDiffusionPipeline(
723
 
724
  return image_embeds, uncond_image_embeds
725
 
 
726
  def prepare_ip_adapter_image_embeds(
727
- self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
728
  ):
729
  if ip_adapter_image_embeds is None:
730
  if not isinstance(ip_adapter_image, list):
@@ -748,40 +758,33 @@ class StableDiffusionPipeline(
748
  [single_negative_image_embeds] * num_images_per_prompt, dim=0
749
  )
750
 
751
- if self.do_classifier_free_guidance:
752
  single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
753
  single_image_embeds = single_image_embeds.to(device)
754
 
755
  image_embeds.append(single_image_embeds)
756
  else:
757
- image_embeds = ip_adapter_image_embeds
758
- return image_embeds
759
-
760
- def run_safety_checker(self, image, device, dtype):
761
- if self.safety_checker is None:
762
- has_nsfw_concept = None
763
- else:
764
- if torch.is_tensor(image):
765
- feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
766
- else:
767
- feature_extractor_input = self.image_processor.numpy_to_pil(image)
768
- safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
769
- image, has_nsfw_concept = self.safety_checker(
770
- images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
771
- )
772
- return image, has_nsfw_concept
773
-
774
- def decode_latents(self, latents):
775
- deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
776
- deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
777
 
778
- latents = 1 / self.vae.config.scaling_factor * latents
779
- image = self.vae.decode(latents, return_dict=False)[0]
780
- image = (image / 2 + 0.5).clamp(0, 1)
781
- # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
782
- image = image.cpu().permute(0, 2, 3, 1).float().numpy()
783
- return image
784
 
 
785
  def prepare_extra_step_kwargs(self, generator, eta):
786
  # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
787
  # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
@@ -802,12 +805,16 @@ class StableDiffusionPipeline(
802
  def check_inputs(
803
  self,
804
  prompt,
 
805
  height,
806
  width,
807
  callback_steps,
808
  negative_prompt=None,
 
809
  prompt_embeds=None,
810
  negative_prompt_embeds=None,
 
 
811
  ip_adapter_image=None,
812
  ip_adapter_image_embeds=None,
813
  callback_on_step_end_tensor_inputs=None,
@@ -820,6 +827,7 @@ class StableDiffusionPipeline(
820
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
821
  f" {type(callback_steps)}."
822
  )
 
823
  if callback_on_step_end_tensor_inputs is not None and not all(
824
  k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
825
  ):
@@ -832,18 +840,30 @@ class StableDiffusionPipeline(
832
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
833
  " only forward one of the two."
834
  )
 
 
 
 
 
835
  elif prompt is None and prompt_embeds is None:
836
  raise ValueError(
837
  "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
838
  )
839
  elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
840
  raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
 
 
841
 
842
  if negative_prompt is not None and negative_prompt_embeds is not None:
843
  raise ValueError(
844
  f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
845
  f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
846
  )
 
 
 
 
 
847
 
848
  if prompt_embeds is not None and negative_prompt_embeds is not None:
849
  if prompt_embeds.shape != negative_prompt_embeds.shape:
@@ -853,11 +873,32 @@ class StableDiffusionPipeline(
853
  f" {negative_prompt_embeds.shape}."
854
  )
855
 
 
 
 
 
 
 
 
 
 
 
856
  if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
857
  raise ValueError(
858
  "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
859
  )
860
 
 
 
 
 
 
 
 
 
 
 
 
861
  def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
862
  shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
863
  if isinstance(generator, list) and len(generator) != batch_size:
@@ -875,94 +916,61 @@ class StableDiffusionPipeline(
875
  latents = latents * self.scheduler.init_noise_sigma
876
  return latents
877
 
878
- def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
879
- r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
880
- The suffixes after the scaling factors represent the stages where they are being applied.
881
- Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
882
- that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
883
- Args:
884
- s1 (`float`):
885
- Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
886
- mitigate "oversmoothing effect" in the enhanced denoising process.
887
- s2 (`float`):
888
- Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
889
- mitigate "oversmoothing effect" in the enhanced denoising process.
890
- b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
891
- b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
892
- """
893
- if not hasattr(self, "unet"):
894
- raise ValueError("The pipeline must have `unet` for using FreeU.")
895
- self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
896
 
897
- def disable_freeu(self):
898
- """Disables the FreeU mechanism if enabled."""
899
- self.unet.disable_freeu()
 
900
 
901
- # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections
902
- def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
903
- """
904
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
905
- key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
906
- <Tip warning={true}>
907
- This API is 🧪 experimental.
908
- </Tip>
909
- Args:
910
- unet (`bool`, defaults to `True`): To apply fusion on the UNet.
911
- vae (`bool`, defaults to `True`): To apply fusion on the VAE.
912
- """
913
- self.fusing_unet = False
914
- self.fusing_vae = False
915
-
916
- if unet:
917
- self.fusing_unet = True
918
- self.unet.fuse_qkv_projections()
919
- self.unet.set_attn_processor(FusedAttnProcessor2_0())
920
-
921
- if vae:
922
- if not isinstance(self.vae, AutoencoderKL):
923
- raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.")
924
-
925
- self.fusing_vae = True
926
- self.vae.fuse_qkv_projections()
927
- self.vae.set_attn_processor(FusedAttnProcessor2_0())
928
-
929
- # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections
930
- def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
931
- """Disable QKV projection fusion if enabled.
932
- <Tip warning={true}>
933
- This API is 🧪 experimental.
934
- </Tip>
935
- Args:
936
- unet (`bool`, defaults to `True`): To apply fusion on the UNet.
937
- vae (`bool`, defaults to `True`): To apply fusion on the VAE.
938
- """
939
- if unet:
940
- if not self.fusing_unet:
941
- logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.")
942
- else:
943
- self.unet.unfuse_qkv_projections()
944
- self.fusing_unet = False
945
 
946
- if vae:
947
- if not self.fusing_vae:
948
- logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
949
- else:
950
- self.vae.unfuse_qkv_projections()
951
- self.fusing_vae = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952
 
953
  # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
954
- def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
 
 
955
  """
956
  See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
 
957
  Args:
958
- timesteps (`torch.Tensor`):
959
- generate embedding vectors at these timesteps
960
  embedding_dim (`int`, *optional*, defaults to 512):
961
- dimension of the embeddings to generate
962
- dtype:
963
- data type of the generated embeddings
 
964
  Returns:
965
- `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
966
  """
967
  assert len(w.shape) == 1
968
  w = w * 1000.0
@@ -976,7 +984,7 @@ class StableDiffusionPipeline(
976
  emb = torch.nn.functional.pad(emb, (0, 1))
977
  assert emb.shape == (w.shape[0], embedding_dim)
978
  return emb
979
-
980
  def pred_z0(self, sample, model_output, timestep):
981
  alpha_prod_t = self.scheduler.alphas_cumprod[timestep].to(sample.device)
982
 
@@ -998,19 +1006,18 @@ class StableDiffusionPipeline(
998
  return pred_original_sample
999
 
1000
  def pred_x0(self, latents, noise_pred, t, generator, device, prompt_embeds, output_type):
1001
-
1002
  pred_z0 = self.pred_z0(latents, noise_pred, t)
1003
  pred_x0 = self.vae.decode(
1004
  pred_z0 / self.vae.config.scaling_factor,
1005
  return_dict=False,
1006
  generator=generator
1007
  )[0]
1008
- pred_x0, ____ = self.run_safety_checker(pred_x0, device, prompt_embeds.dtype)
1009
  do_denormalize = [True] * pred_x0.shape[0]
1010
  pred_x0 = self.image_processor.postprocess(pred_x0, output_type=output_type, do_denormalize=do_denormalize)
1011
 
1012
  return pred_x0
1013
-
1014
  @property
1015
  def guidance_scale(self):
1016
  return self._guidance_scale
@@ -1034,6 +1041,10 @@ class StableDiffusionPipeline(
1034
  def cross_attention_kwargs(self):
1035
  return self._cross_attention_kwargs
1036
 
 
 
 
 
1037
  @property
1038
  def num_timesteps(self):
1039
  return self._num_timesteps
@@ -1041,7 +1052,7 @@ class StableDiffusionPipeline(
1041
  @property
1042
  def interrupt(self):
1043
  return self._interrupt
1044
-
1045
  @property
1046
  def pag_scale(self):
1047
  return self._pag_scale
@@ -1069,50 +1080,71 @@ class StableDiffusionPipeline(
1069
  @property
1070
  def pag_applied_layers_index(self):
1071
  return self._pag_applied_layers_index
1072
-
1073
-
1074
  @torch.no_grad()
1075
  @replace_example_docstring(EXAMPLE_DOC_STRING)
1076
  def __call__(
1077
  self,
1078
  prompt: Union[str, List[str]] = None,
 
1079
  height: Optional[int] = None,
1080
  width: Optional[int] = None,
1081
  num_inference_steps: int = 50,
1082
  timesteps: List[int] = None,
1083
- guidance_scale: float = 7.5,
 
1084
  pag_scale: float = 0.0,
1085
  pag_adaptive_scaling: float = 0.0,
1086
  pag_drop_rate: float = 0.5,
1087
- pag_applied_layers: List[str] = ['down'], #['down', 'mid', 'up']
1088
- pag_applied_layers_index: List[str] = ['d4'], #['d4', 'd5', 'm0']
1089
  negative_prompt: Optional[Union[str, List[str]]] = None,
 
1090
  num_images_per_prompt: Optional[int] = 1,
1091
  eta: float = 0.0,
1092
  generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1093
  latents: Optional[torch.FloatTensor] = None,
1094
  prompt_embeds: Optional[torch.FloatTensor] = None,
1095
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
 
 
1096
  ip_adapter_image: Optional[PipelineImageInput] = None,
1097
  ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
1098
  output_type: Optional[str] = "pil",
1099
  return_dict: bool = True,
1100
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1101
  guidance_rescale: float = 0.0,
 
 
 
 
 
 
1102
  clip_skip: Optional[int] = None,
1103
  callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1104
  callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1105
  **kwargs,
1106
  ):
1107
  r"""
1108
- The call function to the pipeline for generation.
 
1109
  Args:
1110
  prompt (`str` or `List[str]`, *optional*):
1111
- The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1112
- height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1113
- The height in pixels of the generated image.
1114
- width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1115
- The width in pixels of the generated image.
 
 
 
 
 
 
 
 
 
 
1116
  num_inference_steps (`int`, *optional*, defaults to 50):
1117
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1118
  expense of slower inference.
@@ -1120,49 +1152,102 @@ class StableDiffusionPipeline(
1120
  Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1121
  in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1122
  passed will be used. Must be in descending order.
1123
- guidance_scale (`float`, *optional*, defaults to 7.5):
1124
- A higher guidance scale value encourages the model to generate images closely linked to the text
1125
- `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
 
 
 
 
 
 
 
 
 
 
1126
  negative_prompt (`str` or `List[str]`, *optional*):
1127
- The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1128
- pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
 
 
 
 
1129
  num_images_per_prompt (`int`, *optional*, defaults to 1):
1130
  The number of images to generate per prompt.
1131
  eta (`float`, *optional*, defaults to 0.0):
1132
- Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1133
- to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1134
  generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1135
- A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1136
- generation deterministic.
1137
  latents (`torch.FloatTensor`, *optional*):
1138
- Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1139
  generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1140
- tensor is generated by sampling using the supplied random `generator`.
1141
  prompt_embeds (`torch.FloatTensor`, *optional*):
1142
- Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1143
- provided, text embeddings are generated from the `prompt` input argument.
1144
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1145
- Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1146
- not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
 
 
 
 
 
 
 
 
1147
  ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1148
  ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
1149
- Pre-generated image embeddings for IP-Adapter. If not
 
 
1150
  provided, embeddings are computed from the `ip_adapter_image` input argument.
1151
  output_type (`str`, *optional*, defaults to `"pil"`):
1152
- The output format of the generated image. Choose between `PIL.Image` or `np.array`.
 
1153
  return_dict (`bool`, *optional*, defaults to `True`):
1154
- Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1155
- plain tuple.
1156
  cross_attention_kwargs (`dict`, *optional*):
1157
- A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1158
- [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
 
1159
  guidance_rescale (`float`, *optional*, defaults to 0.0):
1160
- Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
1161
- Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
1162
- using zero terminal SNR.
1163
- clip_skip (`int`, *optional*):
1164
- Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1165
- the output of the pre-final layer will be used for computing the prompt embeddings.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1166
  callback_on_step_end (`Callable`, *optional*):
1167
  A function that calls at the end of each denoising steps during the inference. The function is called
1168
  with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
@@ -1172,13 +1257,13 @@ class StableDiffusionPipeline(
1172
  The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1173
  will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1174
  `._callback_tensor_inputs` attribute of your pipeline class.
 
1175
  Examples:
 
1176
  Returns:
1177
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1178
- If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1179
- otherwise a `tuple` is returned where the first element is a list with the generated images and the
1180
- second element is a list of `bool`s indicating whether the corresponding generated image contains
1181
- "not-safe-for-work" (nsfw) content.
1182
  """
1183
 
1184
  callback = kwargs.pop("callback", None)
@@ -1188,29 +1273,35 @@ class StableDiffusionPipeline(
1188
  deprecate(
1189
  "callback",
1190
  "1.0.0",
1191
- "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1192
  )
1193
  if callback_steps is not None:
1194
  deprecate(
1195
  "callback_steps",
1196
  "1.0.0",
1197
- "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1198
  )
1199
 
1200
  # 0. Default height and width to unet
1201
- height = height or self.unet.config.sample_size * self.vae_scale_factor
1202
- width = width or self.unet.config.sample_size * self.vae_scale_factor
1203
- # to deal with lora scaling and other possible forward hooks
 
 
1204
 
1205
  # 1. Check inputs. Raise error if not correct
1206
  self.check_inputs(
1207
  prompt,
 
1208
  height,
1209
  width,
1210
  callback_steps,
1211
  negative_prompt,
 
1212
  prompt_embeds,
1213
  negative_prompt_embeds,
 
 
1214
  ip_adapter_image,
1215
  ip_adapter_image_embeds,
1216
  callback_on_step_end_tensor_inputs,
@@ -1220,14 +1311,15 @@ class StableDiffusionPipeline(
1220
  self._guidance_rescale = guidance_rescale
1221
  self._clip_skip = clip_skip
1222
  self._cross_attention_kwargs = cross_attention_kwargs
 
1223
  self._interrupt = False
1224
-
1225
  self._pag_scale = pag_scale
1226
  self._pag_adaptive_scaling = pag_adaptive_scaling
1227
  self._pag_drop_rate = pag_drop_rate
1228
  self._pag_applied_layers = pag_applied_layers
1229
  self._pag_applied_layers_index = pag_applied_layers_index
1230
-
1231
  # 2. Define call parameters
1232
  if prompt is not None and isinstance(prompt, str):
1233
  batch_size = 1
@@ -1243,37 +1335,27 @@ class StableDiffusionPipeline(
1243
  self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1244
  )
1245
 
1246
- prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1247
- prompt,
1248
- device,
1249
- num_images_per_prompt,
1250
- self.do_classifier_free_guidance,
1251
- negative_prompt,
 
 
 
 
 
 
 
1252
  prompt_embeds=prompt_embeds,
1253
  negative_prompt_embeds=negative_prompt_embeds,
 
 
1254
  lora_scale=lora_scale,
1255
  clip_skip=self.clip_skip,
1256
  )
1257
 
1258
- # For classifier free guidance, we need to do two forward passes.
1259
- # Here we concatenate the unconditional and text embeddings into a single batch
1260
- # to avoid doing two forward passes
1261
-
1262
- #cfg
1263
- if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
1264
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1265
- #pag
1266
- elif not self.do_classifier_free_guidance and self.do_adversarial_guidance:
1267
- prompt_embeds = torch.cat([prompt_embeds, prompt_embeds])
1268
- #both
1269
- elif self.do_classifier_free_guidance and self.do_adversarial_guidance:
1270
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds])
1271
-
1272
- if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1273
- image_embeds = self.prepare_ip_adapter_image_embeds(
1274
- ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_images_per_prompt
1275
- )
1276
-
1277
  # 4. Prepare timesteps
1278
  timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1279
 
@@ -1293,14 +1375,80 @@ class StableDiffusionPipeline(
1293
  # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1294
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1295
 
1296
- # 6.1 Add image embeds for IP-Adapter
1297
- added_cond_kwargs = (
1298
- {"image_embeds": image_embeds}
1299
- if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
1300
- else None
 
 
 
 
 
 
 
 
1301
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302
 
1303
- # 6.2 Optionally get Guidance Scale Embedding
1304
  timestep_cond = None
1305
  if self.unet.config.time_cond_proj_dim is not None:
1306
  guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
@@ -1308,7 +1456,7 @@ class StableDiffusionPipeline(
1308
  guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1309
  ).to(device=device, dtype=latents.dtype)
1310
 
1311
- # 7. Denoising loop
1312
  if self.do_adversarial_guidance:
1313
  down_layers = []
1314
  mid_layers = []
@@ -1324,14 +1472,13 @@ class StableDiffusionPipeline(
1324
  up_layers.append(module)
1325
  else:
1326
  raise ValueError(f"Invalid layer type: {layer_type}")
1327
-
1328
- num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1329
  self._num_timesteps = len(timesteps)
1330
  with self.progress_bar(total=num_inference_steps) as progress_bar:
1331
  for i, t in enumerate(timesteps):
1332
  if self.interrupt:
1333
  continue
1334
-
1335
  #cfg
1336
  if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
1337
  latent_model_input = torch.cat([latents] * 2)
@@ -1344,7 +1491,7 @@ class StableDiffusionPipeline(
1344
  #no
1345
  else:
1346
  latent_model_input = latents
1347
-
1348
  # change attention layer in UNet if use PAG
1349
  if self.do_adversarial_guidance:
1350
 
@@ -1352,26 +1499,51 @@ class StableDiffusionPipeline(
1352
  replace_processor = PAGCFGIdentitySelfAttnProcessor()
1353
  else:
1354
  replace_processor = PAGIdentitySelfAttnProcessor()
1355
-
1356
- drop_layers = self.pag_applied_layers_index
1357
- for drop_layer in drop_layers:
1358
- try:
1359
- if drop_layer[0] == 'd':
1360
- down_layers[int(drop_layer[1])].processor = replace_processor
1361
- elif drop_layer[0] == 'm':
1362
- mid_layers[int(drop_layer[1])].processor = replace_processor
1363
- elif drop_layer[0] == 'u':
1364
- up_layers[int(drop_layer[1])].processor = replace_processor
1365
- else:
1366
- raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1367
- except IndexError:
1368
- raise ValueError(
1369
- f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1370
- )
1371
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1372
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1373
-
1374
  # predict the noise residual
 
 
 
 
1375
  noise_pred = self.unet(
1376
  latent_model_input,
1377
  t,
@@ -1381,20 +1553,13 @@ class StableDiffusionPipeline(
1381
  added_cond_kwargs=added_cond_kwargs,
1382
  return_dict=False,
1383
  )[0]
1384
-
1385
  # perform guidance
1386
-
1387
- # cfg
1388
  if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
1389
-
1390
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1391
-
1392
- delta = noise_pred_text - noise_pred_uncond
1393
- noise_pred = noise_pred_uncond + self.guidance_scale * delta
1394
-
1395
  # pag
1396
  elif not self.do_classifier_free_guidance and self.do_adversarial_guidance:
1397
-
1398
  noise_pred_original, noise_pred_perturb = noise_pred.chunk(2)
1399
 
1400
  signal_scale = self.pag_scale
@@ -1423,7 +1588,12 @@ class StableDiffusionPipeline(
1423
  noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1424
 
1425
  # compute the previous noisy sample x_t -> x_t-1
 
1426
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
 
 
 
 
1427
 
1428
  if callback_on_step_end is not None:
1429
  callback_kwargs = {}
@@ -1434,6 +1604,12 @@ class StableDiffusionPipeline(
1434
  latents = callback_outputs.pop("latents", latents)
1435
  prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1436
  negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
 
 
 
 
 
 
1437
 
1438
  # call the callback, if provided
1439
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
@@ -1442,44 +1618,93 @@ class StableDiffusionPipeline(
1442
  step_idx = i // getattr(self.scheduler, "order", 1)
1443
  callback(step_idx, t, latents)
1444
 
 
 
 
1445
  if not output_type == "latent":
1446
- image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1447
- 0
1448
- ]
1449
- image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1450
  else:
1451
  image = latents
1452
- has_nsfw_concept = None
1453
 
1454
- if has_nsfw_concept is None:
1455
- do_denormalize = [True] * image.shape[0]
1456
- else:
1457
- do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1458
 
1459
- image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1460
 
1461
  # Offload all models
1462
  self.maybe_free_model_hooks()
1463
 
1464
  if not return_dict:
1465
- return (image, has_nsfw_concept)
1466
-
1467
- # change attention layer in UNet if use PAG
1468
- if self.do_adversarial_guidance:
1469
- drop_layers = self.pag_applied_layers_index
1470
- for drop_layer in drop_layers:
1471
- try:
1472
- if drop_layer[0] == 'd':
1473
- down_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1474
- elif drop_layer[0] == 'm':
1475
- mid_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1476
- elif drop_layer[0] == 'u':
1477
- up_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1478
- else:
1479
- raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1480
- except IndexError:
1481
- raise ValueError(
1482
- f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1483
- )
1484
 
1485
- return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation of StableDiffusionXLPAGPipeline
2
 
3
  import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
 
6
  import torch
7
  import torch.nn.functional as F
8
  from packaging import version
 
9
 
10
+ from transformers import (
11
+ CLIPImageProcessor,
12
+ CLIPTextModel,
13
+ CLIPTextModelWithProjection,
14
+ CLIPTokenizer,
15
+ CLIPVisionModelWithProjection,
16
+ )
17
+
18
  from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
19
+ from diffusers.loaders import (
20
+ FromSingleFileMixin,
21
+ IPAdapterMixin,
22
+ StableDiffusionXLLoraLoaderMixin,
23
+ TextualInversionLoaderMixin,
24
+ )
25
  from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
26
+ from diffusers.models.attention_processor import (
27
+ AttnProcessor2_0,
28
+ FusedAttnProcessor2_0,
29
+ LoRAAttnProcessor2_0,
30
+ LoRAXFormersAttnProcessor,
31
+ XFormersAttnProcessor,
32
+ )
33
  from diffusers.models.lora import adjust_lora_scale_text_encoder
34
  from diffusers.schedulers import KarrasDiffusionSchedulers
35
  from diffusers.utils import (
36
  USE_PEFT_BACKEND,
37
  deprecate,
38
+ is_invisible_watermark_available,
39
+ is_torch_xla_available,
40
  logging,
41
  replace_example_docstring,
42
  scale_lora_layers,
43
  unscale_lora_layers,
44
  )
45
  from diffusers.utils.torch_utils import randn_tensor
46
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
47
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
 
48
 
49
  from diffusers.models.attention_processor import Attention, AttnProcessor2_0
50
 
 
51
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
52
 
53
  EXAMPLE_DOC_STRING = """
54
  Examples:
55
  ```py
56
  >>> import torch
57
+ >>> from diffusers import StableDiffusionXLPipeline
58
+
59
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
60
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
61
+ ... )
62
  >>> pipe = pipe.to("cuda")
63
+
64
  >>> prompt = "a photo of an astronaut riding a horse on mars"
65
  >>> image = pipe(prompt).images[0]
66
  ```
 
292
 
293
  return hidden_states
294
 
295
+ if is_invisible_watermark_available():
296
+ from .watermark import StableDiffusionXLWatermarker
297
+
298
+ if is_torch_xla_available():
299
+ import torch_xla.core.xla_model as xm
300
+
301
+ XLA_AVAILABLE = True
302
+ else:
303
+ XLA_AVAILABLE = False
304
+
305
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
306
 
307
  def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
308
  """
 
328
  """
329
  Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
330
  custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
331
+
332
  Args:
333
  scheduler (`SchedulerMixin`):
334
  The scheduler to get timesteps from.
335
  num_inference_steps (`int`):
336
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
337
+ must be `None`.
338
  device (`str` or `torch.device`, *optional*):
339
  The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
340
  timesteps (`List[int]`, *optional*):
341
  Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
342
  timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
343
  must be `None`.
344
+
345
  Returns:
346
  `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
347
  second element is the number of inference steps.
 
361
  timesteps = scheduler.timesteps
362
  return timesteps, num_inference_steps
363
 
364
+ class StableDiffusionXLPipeline(
365
+ DiffusionPipeline,
366
+ StableDiffusionMixin,
367
+ FromSingleFileMixin,
368
+ StableDiffusionXLLoraLoaderMixin,
369
+ TextualInversionLoaderMixin,
370
+ IPAdapterMixin,
371
  ):
372
  r"""
373
+ Pipeline for text-to-image generation using Stable Diffusion XL.
374
+
375
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
376
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
377
+
378
  The pipeline also inherits the following loading methods:
379
  - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
 
 
380
  - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
381
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
382
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
383
  - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
384
+
385
  Args:
386
  vae ([`AutoencoderKL`]):
387
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
388
+ text_encoder ([`CLIPTextModel`]):
389
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
390
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
391
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
392
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
393
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
394
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
395
+ specifically the
396
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
397
+ variant.
398
+ tokenizer (`CLIPTokenizer`):
399
+ Tokenizer of class
400
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
401
+ tokenizer_2 (`CLIPTokenizer`):
402
+ Second Tokenizer of class
403
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
404
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
405
  scheduler ([`SchedulerMixin`]):
406
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
407
  [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
408
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
409
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
410
+ `stabilityai/stable-diffusion-xl-base-1-0`.
411
+ add_watermarker (`bool`, *optional*):
412
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
413
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
414
+ watermarker will be used.
415
  """
416
 
417
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
418
+ _optional_components = [
419
+ "tokenizer",
420
+ "tokenizer_2",
421
+ "text_encoder",
422
+ "text_encoder_2",
423
+ "image_encoder",
424
+ "feature_extractor",
425
+ ]
426
+ _callback_tensor_inputs = [
427
+ "latents",
428
+ "prompt_embeds",
429
+ "negative_prompt_embeds",
430
+ "add_text_embeds",
431
+ "add_time_ids",
432
+ "negative_pooled_prompt_embeds",
433
+ "negative_add_time_ids",
434
+ ]
435
 
436
  def __init__(
437
  self,
438
  vae: AutoencoderKL,
439
  text_encoder: CLIPTextModel,
440
+ text_encoder_2: CLIPTextModelWithProjection,
441
  tokenizer: CLIPTokenizer,
442
+ tokenizer_2: CLIPTokenizer,
443
  unet: UNet2DConditionModel,
444
  scheduler: KarrasDiffusionSchedulers,
 
 
445
  image_encoder: CLIPVisionModelWithProjection = None,
446
+ feature_extractor: CLIPImageProcessor = None,
447
+ force_zeros_for_empty_prompt: bool = True,
448
+ add_watermarker: Optional[bool] = None,
449
  ):
450
  super().__init__()
451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
  self.register_modules(
453
  vae=vae,
454
  text_encoder=text_encoder,
455
+ text_encoder_2=text_encoder_2,
456
  tokenizer=tokenizer,
457
+ tokenizer_2=tokenizer_2,
458
  unet=unet,
459
  scheduler=scheduler,
 
 
460
  image_encoder=image_encoder,
461
+ feature_extractor=feature_extractor,
462
  )
463
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
464
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
465
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
 
466
 
467
+ self.default_sample_size = self.unet.config.sample_size
 
 
 
 
 
468
 
469
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
 
 
 
 
 
470
 
471
+ if add_watermarker:
472
+ self.watermark = StableDiffusionXLWatermarker()
473
+ else:
474
+ self.watermark = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
 
476
  def encode_prompt(
477
  self,
478
+ prompt: str,
479
+ prompt_2: Optional[str] = None,
480
+ device: Optional[torch.device] = None,
481
+ num_images_per_prompt: int = 1,
482
+ do_classifier_free_guidance: bool = True,
483
+ negative_prompt: Optional[str] = None,
484
+ negative_prompt_2: Optional[str] = None,
485
  prompt_embeds: Optional[torch.FloatTensor] = None,
486
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
487
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
488
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
489
  lora_scale: Optional[float] = None,
490
  clip_skip: Optional[int] = None,
491
  ):
492
  r"""
493
  Encodes the prompt into text encoder hidden states.
494
+
495
  Args:
496
  prompt (`str` or `List[str]`, *optional*):
497
  prompt to be encoded
498
+ prompt_2 (`str` or `List[str]`, *optional*):
499
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
500
+ used in both text-encoders
501
  device: (`torch.device`):
502
  torch device
503
  num_images_per_prompt (`int`):
 
508
  The prompt or prompts not to guide the image generation. If not defined, one has to pass
509
  `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
510
  less than `1`).
511
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
512
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
513
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
514
  prompt_embeds (`torch.FloatTensor`, *optional*):
515
  Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
516
  provided, text embeddings will be generated from `prompt` input argument.
 
518
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
519
  weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
520
  argument.
521
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
522
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
523
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
524
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
525
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
526
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
527
+ input argument.
528
  lora_scale (`float`, *optional*):
529
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
530
  clip_skip (`int`, *optional*):
531
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
532
  the output of the pre-final layer will be used for computing the prompt embeddings.
533
  """
534
+ device = device or self._execution_device
535
+
536
  # set lora scale so that monkey patched LoRA
537
  # function of text encoder can correctly access it
538
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
539
  self._lora_scale = lora_scale
540
 
541
  # dynamically adjust the LoRA scale
542
+ if self.text_encoder is not None:
543
+ if not USE_PEFT_BACKEND:
544
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
545
+ else:
546
+ scale_lora_layers(self.text_encoder, lora_scale)
547
 
548
+ if self.text_encoder_2 is not None:
549
+ if not USE_PEFT_BACKEND:
550
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
551
+ else:
552
+ scale_lora_layers(self.text_encoder_2, lora_scale)
553
+
554
+ prompt = [prompt] if isinstance(prompt, str) else prompt
555
+
556
+ if prompt is not None:
557
  batch_size = len(prompt)
558
  else:
559
  batch_size = prompt_embeds.shape[0]
560
 
561
+ # Define tokenizers and text encoders
562
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
563
+ text_encoders = (
564
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
565
+ )
566
+
567
  if prompt_embeds is None:
568
+ prompt_2 = prompt_2 or prompt
569
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
 
 
 
 
 
 
 
 
 
 
 
570
 
571
+ # textual inversion: process multi-vector tokens if necessary
572
+ prompt_embeds_list = []
573
+ prompts = [prompt, prompt_2]
574
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
575
+ if isinstance(self, TextualInversionLoaderMixin):
576
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
577
+
578
+ text_inputs = tokenizer(
579
+ prompt,
580
+ padding="max_length",
581
+ max_length=tokenizer.model_max_length,
582
+ truncation=True,
583
+ return_tensors="pt",
584
  )
585
 
586
+ text_input_ids = text_inputs.input_ids
587
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
 
 
588
 
589
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
590
+ text_input_ids, untruncated_ids
591
+ ):
592
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
593
+ logger.warning(
594
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
595
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
596
+ )
 
 
 
 
 
 
 
 
597
 
598
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
 
 
 
 
 
599
 
600
+ # We are only ALWAYS interested in the pooled output of the final text encoder
601
+ pooled_prompt_embeds = prompt_embeds[0]
602
+ if clip_skip is None:
603
+ prompt_embeds = prompt_embeds.hidden_states[-2]
604
+ else:
605
+ # "2" because SDXL always indexes from the penultimate layer.
606
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
607
 
608
+ prompt_embeds_list.append(prompt_embeds)
609
+
610
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
 
611
 
612
  # get unconditional embeddings for classifier free guidance
613
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
614
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
615
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
616
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
617
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
618
+ negative_prompt = negative_prompt or ""
619
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
620
+
621
+ # normalize str to list
622
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
623
+ negative_prompt_2 = (
624
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
625
+ )
626
+
627
  uncond_tokens: List[str]
628
+ if prompt is not None and type(prompt) is not type(negative_prompt):
 
 
629
  raise TypeError(
630
  f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
631
  f" {type(prompt)}."
632
  )
 
 
633
  elif batch_size != len(negative_prompt):
634
  raise ValueError(
635
  f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
 
637
  " the batch size of `prompt`."
638
  )
639
  else:
640
+ uncond_tokens = [negative_prompt, negative_prompt_2]
641
+
642
+ negative_prompt_embeds_list = []
643
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
644
+ if isinstance(self, TextualInversionLoaderMixin):
645
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
646
+
647
+ max_length = prompt_embeds.shape[1]
648
+ uncond_input = tokenizer(
649
+ negative_prompt,
650
+ padding="max_length",
651
+ max_length=max_length,
652
+ truncation=True,
653
+ return_tensors="pt",
654
+ )
655
 
656
+ negative_prompt_embeds = text_encoder(
657
+ uncond_input.input_ids.to(device),
658
+ output_hidden_states=True,
659
+ )
660
+ # We are only ALWAYS interested in the pooled output of the final text encoder
661
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
662
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
 
 
 
 
 
663
 
664
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
 
 
 
665
 
666
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
667
+
668
+ if self.text_encoder_2 is not None:
669
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
670
+ else:
671
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
672
+
673
+ bs_embed, seq_len, _ = prompt_embeds.shape
674
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
675
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
676
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
677
 
678
  if do_classifier_free_guidance:
679
  # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
680
  seq_len = negative_prompt_embeds.shape[1]
681
 
682
+ if self.text_encoder_2 is not None:
683
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
684
+ else:
685
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
686
 
687
  negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
688
  negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
689
 
690
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
691
+ bs_embed * num_images_per_prompt, -1
692
+ )
693
+ if do_classifier_free_guidance:
694
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
695
+ bs_embed * num_images_per_prompt, -1
696
+ )
697
 
698
+ if self.text_encoder is not None:
699
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
700
+ # Retrieve the original scale by scaling back the LoRA layers
701
+ unscale_lora_layers(self.text_encoder, lora_scale)
702
 
703
+ if self.text_encoder_2 is not None:
704
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
705
+ # Retrieve the original scale by scaling back the LoRA layers
706
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
707
+
708
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
709
+
710
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
711
  def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
712
  dtype = next(self.image_encoder.parameters()).dtype
713
 
 
732
 
733
  return image_embeds, uncond_image_embeds
734
 
735
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
736
  def prepare_ip_adapter_image_embeds(
737
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
738
  ):
739
  if ip_adapter_image_embeds is None:
740
  if not isinstance(ip_adapter_image, list):
 
758
  [single_negative_image_embeds] * num_images_per_prompt, dim=0
759
  )
760
 
761
+ if do_classifier_free_guidance:
762
  single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
763
  single_image_embeds = single_image_embeds.to(device)
764
 
765
  image_embeds.append(single_image_embeds)
766
  else:
767
+ repeat_dims = [1]
768
+ image_embeds = []
769
+ for single_image_embeds in ip_adapter_image_embeds:
770
+ if do_classifier_free_guidance:
771
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
772
+ single_image_embeds = single_image_embeds.repeat(
773
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
774
+ )
775
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
776
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
777
+ )
778
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
779
+ else:
780
+ single_image_embeds = single_image_embeds.repeat(
781
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
782
+ )
783
+ image_embeds.append(single_image_embeds)
 
 
 
784
 
785
+ return image_embeds
 
 
 
 
 
786
 
787
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
788
  def prepare_extra_step_kwargs(self, generator, eta):
789
  # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
790
  # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
 
805
  def check_inputs(
806
  self,
807
  prompt,
808
+ prompt_2,
809
  height,
810
  width,
811
  callback_steps,
812
  negative_prompt=None,
813
+ negative_prompt_2=None,
814
  prompt_embeds=None,
815
  negative_prompt_embeds=None,
816
+ pooled_prompt_embeds=None,
817
+ negative_pooled_prompt_embeds=None,
818
  ip_adapter_image=None,
819
  ip_adapter_image_embeds=None,
820
  callback_on_step_end_tensor_inputs=None,
 
827
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
828
  f" {type(callback_steps)}."
829
  )
830
+
831
  if callback_on_step_end_tensor_inputs is not None and not all(
832
  k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
833
  ):
 
840
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
841
  " only forward one of the two."
842
  )
843
+ elif prompt_2 is not None and prompt_embeds is not None:
844
+ raise ValueError(
845
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
846
+ " only forward one of the two."
847
+ )
848
  elif prompt is None and prompt_embeds is None:
849
  raise ValueError(
850
  "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
851
  )
852
  elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
853
  raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
854
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
855
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
856
 
857
  if negative_prompt is not None and negative_prompt_embeds is not None:
858
  raise ValueError(
859
  f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
860
  f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
861
  )
862
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
863
+ raise ValueError(
864
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
865
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
866
+ )
867
 
868
  if prompt_embeds is not None and negative_prompt_embeds is not None:
869
  if prompt_embeds.shape != negative_prompt_embeds.shape:
 
873
  f" {negative_prompt_embeds.shape}."
874
  )
875
 
876
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
877
+ raise ValueError(
878
+ "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`."
879
+ )
880
+
881
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
882
+ raise ValueError(
883
+ "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`."
884
+ )
885
+
886
  if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
887
  raise ValueError(
888
  "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
889
  )
890
 
891
+ if ip_adapter_image_embeds is not None:
892
+ if not isinstance(ip_adapter_image_embeds, list):
893
+ raise ValueError(
894
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
895
+ )
896
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
897
+ raise ValueError(
898
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
899
+ )
900
+
901
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
902
  def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
903
  shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
904
  if isinstance(generator, list) and len(generator) != batch_size:
 
916
  latents = latents * self.scheduler.init_noise_sigma
917
  return latents
918
 
919
+ def _get_add_time_ids(
920
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
921
+ ):
922
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923
 
924
+ passed_add_embed_dim = (
925
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
926
+ )
927
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
928
 
929
+ if expected_add_embed_dim != passed_add_embed_dim:
930
+ raise ValueError(
931
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
932
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
933
 
934
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
935
+ return add_time_ids
936
+
937
+ def upcast_vae(self):
938
+ dtype = self.vae.dtype
939
+ self.vae.to(dtype=torch.float32)
940
+ use_torch_2_0_or_xformers = isinstance(
941
+ self.vae.decoder.mid_block.attentions[0].processor,
942
+ (
943
+ AttnProcessor2_0,
944
+ XFormersAttnProcessor,
945
+ LoRAXFormersAttnProcessor,
946
+ LoRAAttnProcessor2_0,
947
+ FusedAttnProcessor2_0,
948
+ ),
949
+ )
950
+ # if xformers or torch_2_0 is used attention block does not need
951
+ # to be in float32 which can save lots of memory
952
+ if use_torch_2_0_or_xformers:
953
+ self.vae.post_quant_conv.to(dtype)
954
+ self.vae.decoder.conv_in.to(dtype)
955
+ self.vae.decoder.mid_block.to(dtype)
956
 
957
  # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
958
+ def get_guidance_scale_embedding(
959
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
960
+ ) -> torch.FloatTensor:
961
  """
962
  See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
963
+
964
  Args:
965
+ w (`torch.Tensor`):
966
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
967
  embedding_dim (`int`, *optional*, defaults to 512):
968
+ Dimension of the embeddings to generate.
969
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
970
+ Data type of the generated embeddings.
971
+
972
  Returns:
973
+ `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
974
  """
975
  assert len(w.shape) == 1
976
  w = w * 1000.0
 
984
  emb = torch.nn.functional.pad(emb, (0, 1))
985
  assert emb.shape == (w.shape[0], embedding_dim)
986
  return emb
987
+
988
  def pred_z0(self, sample, model_output, timestep):
989
  alpha_prod_t = self.scheduler.alphas_cumprod[timestep].to(sample.device)
990
 
 
1006
  return pred_original_sample
1007
 
1008
  def pred_x0(self, latents, noise_pred, t, generator, device, prompt_embeds, output_type):
 
1009
  pred_z0 = self.pred_z0(latents, noise_pred, t)
1010
  pred_x0 = self.vae.decode(
1011
  pred_z0 / self.vae.config.scaling_factor,
1012
  return_dict=False,
1013
  generator=generator
1014
  )[0]
1015
+ #pred_x0, ____ = self.run_safety_checker(pred_x0, device, prompt_embeds.dtype)
1016
  do_denormalize = [True] * pred_x0.shape[0]
1017
  pred_x0 = self.image_processor.postprocess(pred_x0, output_type=output_type, do_denormalize=do_denormalize)
1018
 
1019
  return pred_x0
1020
+
1021
  @property
1022
  def guidance_scale(self):
1023
  return self._guidance_scale
 
1041
  def cross_attention_kwargs(self):
1042
  return self._cross_attention_kwargs
1043
 
1044
+ @property
1045
+ def denoising_end(self):
1046
+ return self._denoising_end
1047
+
1048
  @property
1049
  def num_timesteps(self):
1050
  return self._num_timesteps
 
1052
  @property
1053
  def interrupt(self):
1054
  return self._interrupt
1055
+
1056
  @property
1057
  def pag_scale(self):
1058
  return self._pag_scale
 
1080
  @property
1081
  def pag_applied_layers_index(self):
1082
  return self._pag_applied_layers_index
1083
+
 
1084
  @torch.no_grad()
1085
  @replace_example_docstring(EXAMPLE_DOC_STRING)
1086
  def __call__(
1087
  self,
1088
  prompt: Union[str, List[str]] = None,
1089
+ prompt_2: Optional[Union[str, List[str]]] = None,
1090
  height: Optional[int] = None,
1091
  width: Optional[int] = None,
1092
  num_inference_steps: int = 50,
1093
  timesteps: List[int] = None,
1094
+ denoising_end: Optional[float] = None,
1095
+ guidance_scale: float = 5.0,
1096
  pag_scale: float = 0.0,
1097
  pag_adaptive_scaling: float = 0.0,
1098
  pag_drop_rate: float = 0.5,
1099
+ pag_applied_layers: List[str] = ['mid'], #['down', 'mid', 'up']
1100
+ pag_applied_layers_index: List[str] = None, #['d4', 'd5', 'm0']
1101
  negative_prompt: Optional[Union[str, List[str]]] = None,
1102
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1103
  num_images_per_prompt: Optional[int] = 1,
1104
  eta: float = 0.0,
1105
  generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1106
  latents: Optional[torch.FloatTensor] = None,
1107
  prompt_embeds: Optional[torch.FloatTensor] = None,
1108
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1109
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1110
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1111
  ip_adapter_image: Optional[PipelineImageInput] = None,
1112
  ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
1113
  output_type: Optional[str] = "pil",
1114
  return_dict: bool = True,
1115
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1116
  guidance_rescale: float = 0.0,
1117
+ original_size: Optional[Tuple[int, int]] = None,
1118
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1119
+ target_size: Optional[Tuple[int, int]] = None,
1120
+ negative_original_size: Optional[Tuple[int, int]] = None,
1121
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1122
+ negative_target_size: Optional[Tuple[int, int]] = None,
1123
  clip_skip: Optional[int] = None,
1124
  callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1125
  callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1126
  **kwargs,
1127
  ):
1128
  r"""
1129
+ Function invoked when calling the pipeline for generation.
1130
+
1131
  Args:
1132
  prompt (`str` or `List[str]`, *optional*):
1133
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1134
+ instead.
1135
+ prompt_2 (`str` or `List[str]`, *optional*):
1136
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1137
+ used in both text-encoders
1138
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1139
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
1140
+ Anything below 512 pixels won't work well for
1141
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1142
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1143
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1144
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
1145
+ Anything below 512 pixels won't work well for
1146
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1147
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1148
  num_inference_steps (`int`, *optional*, defaults to 50):
1149
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1150
  expense of slower inference.
 
1152
  Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1153
  in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1154
  passed will be used. Must be in descending order.
1155
+ denoising_end (`float`, *optional*):
1156
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1157
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1158
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1159
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1160
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1161
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1162
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1163
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1164
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1165
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1166
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1167
+ usually at the expense of lower image quality.
1168
  negative_prompt (`str` or `List[str]`, *optional*):
1169
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1170
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1171
+ less than `1`).
1172
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1173
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1174
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1175
  num_images_per_prompt (`int`, *optional*, defaults to 1):
1176
  The number of images to generate per prompt.
1177
  eta (`float`, *optional*, defaults to 0.0):
1178
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1179
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1180
  generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1181
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1182
+ to make generation deterministic.
1183
  latents (`torch.FloatTensor`, *optional*):
1184
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1185
  generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1186
+ tensor will ge generated by sampling using the supplied random `generator`.
1187
  prompt_embeds (`torch.FloatTensor`, *optional*):
1188
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1189
+ provided, text embeddings will be generated from `prompt` input argument.
1190
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1191
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1192
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1193
+ argument.
1194
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1195
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1196
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1197
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1198
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1199
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1200
+ input argument.
1201
  ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1202
  ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
1203
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1204
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1205
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1206
  provided, embeddings are computed from the `ip_adapter_image` input argument.
1207
  output_type (`str`, *optional*, defaults to `"pil"`):
1208
+ The output format of the generate image. Choose between
1209
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1210
  return_dict (`bool`, *optional*, defaults to `True`):
1211
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
1212
+ of a plain tuple.
1213
  cross_attention_kwargs (`dict`, *optional*):
1214
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1215
+ `self.processor` in
1216
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1217
  guidance_rescale (`float`, *optional*, defaults to 0.0):
1218
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1219
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1220
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1221
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1222
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1223
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1224
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1225
+ explained in section 2.2 of
1226
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1227
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1228
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1229
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1230
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1231
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1232
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1233
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1234
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1235
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1236
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1237
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1238
+ micro-conditioning as explained in section 2.2 of
1239
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1240
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1241
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1242
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1243
+ micro-conditioning as explained in section 2.2 of
1244
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1245
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1246
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1247
+ To negatively condition the generation process based on a target image resolution. It should be as same
1248
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1249
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1250
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1251
  callback_on_step_end (`Callable`, *optional*):
1252
  A function that calls at the end of each denoising steps during the inference. The function is called
1253
  with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
 
1257
  The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1258
  will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1259
  `._callback_tensor_inputs` attribute of your pipeline class.
1260
+
1261
  Examples:
1262
+
1263
  Returns:
1264
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1265
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1266
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
 
 
1267
  """
1268
 
1269
  callback = kwargs.pop("callback", None)
 
1273
  deprecate(
1274
  "callback",
1275
  "1.0.0",
1276
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1277
  )
1278
  if callback_steps is not None:
1279
  deprecate(
1280
  "callback_steps",
1281
  "1.0.0",
1282
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1283
  )
1284
 
1285
  # 0. Default height and width to unet
1286
+ height = height or self.default_sample_size * self.vae_scale_factor
1287
+ width = width or self.default_sample_size * self.vae_scale_factor
1288
+
1289
+ original_size = original_size or (height, width)
1290
+ target_size = target_size or (height, width)
1291
 
1292
  # 1. Check inputs. Raise error if not correct
1293
  self.check_inputs(
1294
  prompt,
1295
+ prompt_2,
1296
  height,
1297
  width,
1298
  callback_steps,
1299
  negative_prompt,
1300
+ negative_prompt_2,
1301
  prompt_embeds,
1302
  negative_prompt_embeds,
1303
+ pooled_prompt_embeds,
1304
+ negative_pooled_prompt_embeds,
1305
  ip_adapter_image,
1306
  ip_adapter_image_embeds,
1307
  callback_on_step_end_tensor_inputs,
 
1311
  self._guidance_rescale = guidance_rescale
1312
  self._clip_skip = clip_skip
1313
  self._cross_attention_kwargs = cross_attention_kwargs
1314
+ self._denoising_end = denoising_end
1315
  self._interrupt = False
1316
+
1317
  self._pag_scale = pag_scale
1318
  self._pag_adaptive_scaling = pag_adaptive_scaling
1319
  self._pag_drop_rate = pag_drop_rate
1320
  self._pag_applied_layers = pag_applied_layers
1321
  self._pag_applied_layers_index = pag_applied_layers_index
1322
+
1323
  # 2. Define call parameters
1324
  if prompt is not None and isinstance(prompt, str):
1325
  batch_size = 1
 
1335
  self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1336
  )
1337
 
1338
+ (
1339
+ prompt_embeds,
1340
+ negative_prompt_embeds,
1341
+ pooled_prompt_embeds,
1342
+ negative_pooled_prompt_embeds,
1343
+ ) = self.encode_prompt(
1344
+ prompt=prompt,
1345
+ prompt_2=prompt_2,
1346
+ device=device,
1347
+ num_images_per_prompt=num_images_per_prompt,
1348
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1349
+ negative_prompt=negative_prompt,
1350
+ negative_prompt_2=negative_prompt_2,
1351
  prompt_embeds=prompt_embeds,
1352
  negative_prompt_embeds=negative_prompt_embeds,
1353
+ pooled_prompt_embeds=pooled_prompt_embeds,
1354
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1355
  lora_scale=lora_scale,
1356
  clip_skip=self.clip_skip,
1357
  )
1358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1359
  # 4. Prepare timesteps
1360
  timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1361
 
 
1375
  # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1376
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1377
 
1378
+ # 7. Prepare added time ids & embeddings
1379
+ add_text_embeds = pooled_prompt_embeds
1380
+ if self.text_encoder_2 is None:
1381
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1382
+ else:
1383
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1384
+
1385
+ add_time_ids = self._get_add_time_ids(
1386
+ original_size,
1387
+ crops_coords_top_left,
1388
+ target_size,
1389
+ dtype=prompt_embeds.dtype,
1390
+ text_encoder_projection_dim=text_encoder_projection_dim,
1391
  )
1392
+ if negative_original_size is not None and negative_target_size is not None:
1393
+ negative_add_time_ids = self._get_add_time_ids(
1394
+ negative_original_size,
1395
+ negative_crops_coords_top_left,
1396
+ negative_target_size,
1397
+ dtype=prompt_embeds.dtype,
1398
+ text_encoder_projection_dim=text_encoder_projection_dim,
1399
+ )
1400
+ else:
1401
+ negative_add_time_ids = add_time_ids
1402
+
1403
+ #cfg
1404
+ if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
1405
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1406
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1407
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1408
+ #pag
1409
+ elif not self.do_classifier_free_guidance and self.do_adversarial_guidance:
1410
+ prompt_embeds = torch.cat([prompt_embeds, prompt_embeds], dim=0)
1411
+ add_text_embeds = torch.cat([add_text_embeds, add_text_embeds], dim=0)
1412
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1413
+ #both
1414
+ elif self.do_classifier_free_guidance and self.do_adversarial_guidance:
1415
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0)
1416
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds, add_text_embeds], dim=0)
1417
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids, add_time_ids], dim=0)
1418
+
1419
+ prompt_embeds = prompt_embeds.to(device)
1420
+ add_text_embeds = add_text_embeds.to(device)
1421
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1422
+
1423
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1424
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1425
+ ip_adapter_image,
1426
+ ip_adapter_image_embeds,
1427
+ device,
1428
+ batch_size * num_images_per_prompt,
1429
+ self.do_classifier_free_guidance,
1430
+ )
1431
+
1432
+ # 8. Denoising loop
1433
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1434
+
1435
+ # 8.1 Apply denoising_end
1436
+ if (
1437
+ self.denoising_end is not None
1438
+ and isinstance(self.denoising_end, float)
1439
+ and self.denoising_end > 0
1440
+ and self.denoising_end < 1
1441
+ ):
1442
+ discrete_timestep_cutoff = int(
1443
+ round(
1444
+ self.scheduler.config.num_train_timesteps
1445
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1446
+ )
1447
+ )
1448
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1449
+ timesteps = timesteps[:num_inference_steps]
1450
 
1451
+ # 9. Optionally get Guidance Scale Embedding
1452
  timestep_cond = None
1453
  if self.unet.config.time_cond_proj_dim is not None:
1454
  guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
 
1456
  guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1457
  ).to(device=device, dtype=latents.dtype)
1458
 
1459
+ # 10. Create down mid and up layer lists
1460
  if self.do_adversarial_guidance:
1461
  down_layers = []
1462
  mid_layers = []
 
1472
  up_layers.append(module)
1473
  else:
1474
  raise ValueError(f"Invalid layer type: {layer_type}")
1475
+
 
1476
  self._num_timesteps = len(timesteps)
1477
  with self.progress_bar(total=num_inference_steps) as progress_bar:
1478
  for i, t in enumerate(timesteps):
1479
  if self.interrupt:
1480
  continue
1481
+
1482
  #cfg
1483
  if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
1484
  latent_model_input = torch.cat([latents] * 2)
 
1491
  #no
1492
  else:
1493
  latent_model_input = latents
1494
+
1495
  # change attention layer in UNet if use PAG
1496
  if self.do_adversarial_guidance:
1497
 
 
1499
  replace_processor = PAGCFGIdentitySelfAttnProcessor()
1500
  else:
1501
  replace_processor = PAGIdentitySelfAttnProcessor()
1502
+
1503
+ if(self.pag_applied_layers_index):
1504
+ drop_layers = self.pag_applied_layers_index
1505
+ for drop_layer in drop_layers:
1506
+ layer_number = int(drop_layer[1:])
1507
+ try:
1508
+ if drop_layer[0] == 'd':
1509
+ down_layers[layer_number].processor = replace_processor
1510
+ elif drop_layer[0] == 'm':
1511
+ mid_layers[layer_number].processor = replace_processor
1512
+ elif drop_layer[0] == 'u':
1513
+ up_layers[layer_number].processor = replace_processor
1514
+ else:
1515
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1516
+ except IndexError:
1517
+ raise ValueError(
1518
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1519
+ )
1520
+ elif(self.pag_applied_layers):
1521
+ drop_full_layers = self.pag_applied_layers
1522
+ for drop_full_layer in drop_full_layers:
1523
+ try:
1524
+ if drop_full_layer == "down":
1525
+ for down_layer in down_layers:
1526
+ down_layer.processor = replace_processor
1527
+ elif drop_full_layer == "mid":
1528
+ for mid_layer in mid_layers:
1529
+ mid_layer.processor = replace_processor
1530
+ elif drop_full_layer == "up":
1531
+ for up_layer in up_layers:
1532
+ up_layer.processor = replace_processor
1533
+ else:
1534
+ raise ValueError(f"Invalid layer type: {drop_full_layer}")
1535
+ except IndexError:
1536
+ raise ValueError(
1537
+ f"Invalid layer index: {drop_full_layer}. Available layers are: down, mid and up. If you need to specify each layer index, you can use `pag_applied_layers_index`"
1538
+ )
1539
+
1540
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1541
+
1542
  # predict the noise residual
1543
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1544
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1545
+ added_cond_kwargs["image_embeds"] = image_embeds
1546
+
1547
  noise_pred = self.unet(
1548
  latent_model_input,
1549
  t,
 
1553
  added_cond_kwargs=added_cond_kwargs,
1554
  return_dict=False,
1555
  )[0]
1556
+
1557
  # perform guidance
 
 
1558
  if self.do_classifier_free_guidance and not self.do_adversarial_guidance:
 
1559
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1560
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
 
 
 
1561
  # pag
1562
  elif not self.do_classifier_free_guidance and self.do_adversarial_guidance:
 
1563
  noise_pred_original, noise_pred_perturb = noise_pred.chunk(2)
1564
 
1565
  signal_scale = self.pag_scale
 
1588
  noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1589
 
1590
  # compute the previous noisy sample x_t -> x_t-1
1591
+ latents_dtype = latents.dtype
1592
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1593
+ if latents.dtype != latents_dtype:
1594
+ if torch.backends.mps.is_available():
1595
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1596
+ latents = latents.to(latents_dtype)
1597
 
1598
  if callback_on_step_end is not None:
1599
  callback_kwargs = {}
 
1604
  latents = callback_outputs.pop("latents", latents)
1605
  prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1606
  negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1607
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1608
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1609
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1610
+ )
1611
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1612
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1613
 
1614
  # call the callback, if provided
1615
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
 
1618
  step_idx = i // getattr(self.scheduler, "order", 1)
1619
  callback(step_idx, t, latents)
1620
 
1621
+ if XLA_AVAILABLE:
1622
+ xm.mark_step()
1623
+
1624
  if not output_type == "latent":
1625
+ # make sure the VAE is in float32 mode, as it overflows in float16
1626
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1627
+
1628
+ if needs_upcasting:
1629
+ self.upcast_vae()
1630
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1631
+ elif latents.dtype != self.vae.dtype:
1632
+ if torch.backends.mps.is_available():
1633
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1634
+ self.vae = self.vae.to(latents.dtype)
1635
+
1636
+ # unscale/denormalize the latents
1637
+ # denormalize with the mean and std if available and not None
1638
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1639
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1640
+ if has_latents_mean and has_latents_std:
1641
+ latents_mean = (
1642
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1643
+ )
1644
+ latents_std = (
1645
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1646
+ )
1647
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1648
+ else:
1649
+ latents = latents / self.vae.config.scaling_factor
1650
+
1651
+ image = self.vae.decode(latents, return_dict=False)[0]
1652
+
1653
+ # cast back to fp16 if needed
1654
+ if needs_upcasting:
1655
+ self.vae.to(dtype=torch.float16)
1656
  else:
1657
  image = latents
 
1658
 
1659
+ if not output_type == "latent":
1660
+ # apply watermark if available
1661
+ if self.watermark is not None:
1662
+ image = self.watermark.apply_watermark(image)
1663
 
1664
+ image = self.image_processor.postprocess(image, output_type=output_type)
1665
 
1666
  # Offload all models
1667
  self.maybe_free_model_hooks()
1668
 
1669
  if not return_dict:
1670
+ return (image,)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1671
 
1672
+ #Change the attention layers back to original ones after PAG was applied
1673
+ if self.do_adversarial_guidance:
1674
+ if(self.pag_applied_layers_index):
1675
+ drop_layers = self.pag_applied_layers_index
1676
+ for drop_layer in drop_layers:
1677
+ layer_number = int(drop_layer[1:])
1678
+ try:
1679
+ if drop_layer[0] == 'd':
1680
+ down_layers[layer_number].processor = AttnProcessor2_0()
1681
+ elif drop_layer[0] == 'm':
1682
+ mid_layers[layer_number].processor = AttnProcessor2_0()
1683
+ elif drop_layer[0] == 'u':
1684
+ up_layers[layer_number].processor = AttnProcessor2_0()
1685
+ else:
1686
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1687
+ except IndexError:
1688
+ raise ValueError(
1689
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1690
+ )
1691
+ elif(self.pag_applied_layers):
1692
+ drop_full_layers = self.pag_applied_layers
1693
+ for drop_full_layer in drop_full_layers:
1694
+ try:
1695
+ if drop_full_layer == "down":
1696
+ for down_layer in down_layers:
1697
+ down_layer.processor = AttnProcessor2_0()
1698
+ elif drop_full_layer == "mid":
1699
+ for mid_layer in mid_layers:
1700
+ mid_layer.processor = AttnProcessor2_0()
1701
+ elif drop_full_layer == "up":
1702
+ for up_layer in up_layers:
1703
+ up_layer.processor = AttnProcessor2_0()
1704
+ else:
1705
+ raise ValueError(f"Invalid layer type: {drop_full_layer}")
1706
+ except IndexError:
1707
+ raise ValueError(
1708
+ f"Invalid layer index: {drop_full_layer}. Available layers are: down, mid and up. If you need to specify each layer index, you can use `pag_applied_layers_index`"
1709
+ )
1710
+ return StableDiffusionXLPipelineOutput(images=image)