wanghx47 commited on
Commit
13f7591
1 Parent(s): ac9337d

add model file.

Browse files
Files changed (6) hide show
  1. .gitattributes +37 -35
  2. README.md +82 -1
  3. cfgpag.jpg +0 -0
  4. pipeline.py +1710 -0
  5. sd_pag_demo.ipynb +0 -0
  6. uncond_generation_pag.jpg +0 -0
.gitattributes CHANGED
@@ -1,35 +1,37 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ pag_sdxl.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ pag_uncond.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,84 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ pipeline_tag: unconditional-image-generation
5
+ tags:
6
+ - Diffusion Models
7
+ - Stable Diffusion
8
+ - Perturbed-Attention Guidance
9
+ - PAG
10
  ---
11
+
12
+ # Perturbed-Attention Guidance for SDXL
13
+
14
+ <div style="display:flex">
15
+ <video width=50% autoplay loop controls>
16
+ <source src="https://huggingface.co/multimodalart/sdxl_perturbed_attention_guidance/resolve/main/pag_sdxl.mp4" type="video/mp4">
17
+ </video>
18
+ <video width=50% autoplay loop controls>
19
+ <source src="https://huggingface.co/multimodalart/sdxl_perturbed_attention_guidance/resolve/main/pag_uncond.mp4" type="video/mp4">
20
+ </video>
21
+ </div>
22
+
23
+ The original Perturbed-Attention Guidance for unconditional models and SD1.5 by [Hyoungwon Cho](https://huggingface.co/hyoungwoncho) is availiable at [hyoungwoncho/sd_perturbed_attention_guidance](https://huggingface.co/hyoungwoncho/sd_perturbed_attention_guidance)
24
+
25
+ [Project](https://ku-cvlab.github.io/Perturbed-Attention-Guidance/) / [arXiv](https://arxiv.org/abs/2403.17377) / [GitHub](https://github.com/KU-CVLAB/Perturbed-Attention-Guidance)
26
+
27
+ This repository is just a simple SDXL implementation of the Perturbed-Attention Guidance (PAG) on Stable Diffusion XL (SDXL) for the 🧨 diffusers library.
28
+
29
+
30
+ ## Quickstart
31
+
32
+ Loading Custom Pipeline:
33
+
34
+ ```py
35
+ from diffusers import StableDiffusionXLPipeline
36
+
37
+ pipe = StableDiffusionXLPipeline.from_pretrained(
38
+ "stabilityai/stable-diffusion-xl-base-1.0",
39
+ custom_pipeline="multimodalart/sdxl_perturbed_attention_guidance",
40
+ torch_dtype=torch.float16
41
+ )
42
+
43
+ device="cuda"
44
+ pipe = pipe.to(device)
45
+ ```
46
+
47
+ Unconditional sampling with PAG:
48
+ ![image/jpeg](uncond_generation_pag.jpg)
49
+
50
+ ```py
51
+ output = pipe(
52
+ "",
53
+ num_inference_steps=50,
54
+ guidance_scale=0.0,
55
+ pag_scale=5.0,
56
+ pag_applied_layers=['mid']
57
+ ).images
58
+ ```
59
+
60
+ Sampling with PAG and CFG:
61
+ ![image/jpeg](cfgpag.jpg)
62
+ ```py
63
+ output = pipe(
64
+ "the spirit of a tamagotchi wandering in the city of Vienna",
65
+ num_inference_steps=25,
66
+ guidance_scale=4.0,
67
+ pag_scale=3.0,
68
+ pag_applied_layers=['mid']
69
+ ).images
70
+ ```
71
+
72
+ ## Parameters
73
+
74
+ `guidance_scale` : guidance scale of CFG (ex: `7.5`)
75
+
76
+ `pag_scale` : guidance scale of PAG (ex: `4.0`)
77
+
78
+ `pag_applied_layers`: layer to apply perturbation (ex: ['mid'])
79
+
80
+ `pag_applied_layers_index` : index of the layers to apply perturbation (ex: ['m0', 'm1'])
81
+
82
+ ## Stable Diffusion XL Demo
83
+
84
+ [Try it here](https://huggingface.co/spaces/multimodalart/perturbed-attention-guidance-sdxl)
cfgpag.jpg ADDED
pipeline.py ADDED
@@ -0,0 +1,1710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ```
67
+ """
68
+
69
+
70
+ class PAGIdentitySelfAttnProcessor:
71
+ r"""
72
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
73
+ """
74
+
75
+ def __init__(self):
76
+ if not hasattr(F, "scaled_dot_product_attention"):
77
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
78
+
79
+ def __call__(
80
+ self,
81
+ attn: Attention,
82
+ hidden_states: torch.FloatTensor,
83
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
84
+ attention_mask: Optional[torch.FloatTensor] = None,
85
+ temb: Optional[torch.FloatTensor] = None,
86
+ *args,
87
+ **kwargs,
88
+ ) -> torch.FloatTensor:
89
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
90
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
91
+ deprecate("scale", "1.0.0", deprecation_message)
92
+
93
+ residual = hidden_states
94
+ if attn.spatial_norm is not None:
95
+ hidden_states = attn.spatial_norm(hidden_states, temb)
96
+
97
+ input_ndim = hidden_states.ndim
98
+ if input_ndim == 4:
99
+ batch_size, channel, height, width = hidden_states.shape
100
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
101
+
102
+ # chunk
103
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
104
+
105
+ # original path
106
+ batch_size, sequence_length, _ = hidden_states_org.shape
107
+
108
+ if attention_mask is not None:
109
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
110
+ # scaled_dot_product_attention expects attention_mask shape to be
111
+ # (batch, heads, source_length, target_length)
112
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
113
+
114
+ if attn.group_norm is not None:
115
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
116
+
117
+ query = attn.to_q(hidden_states_org)
118
+ key = attn.to_k(hidden_states_org)
119
+ value = attn.to_v(hidden_states_org)
120
+
121
+ inner_dim = key.shape[-1]
122
+ head_dim = inner_dim // attn.heads
123
+
124
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
125
+
126
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
127
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
128
+
129
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
130
+ # TODO: add support for attn.scale when we move to Torch 2.1
131
+ hidden_states_org = F.scaled_dot_product_attention(
132
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
133
+ )
134
+
135
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
136
+ hidden_states_org = hidden_states_org.to(query.dtype)
137
+
138
+ # linear proj
139
+ hidden_states_org = attn.to_out[0](hidden_states_org)
140
+ # dropout
141
+ hidden_states_org = attn.to_out[1](hidden_states_org)
142
+
143
+ if input_ndim == 4:
144
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
145
+
146
+ # perturbed path (identity attention)
147
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
148
+
149
+ if attention_mask is not None:
150
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
151
+ # scaled_dot_product_attention expects attention_mask shape to be
152
+ # (batch, heads, source_length, target_length)
153
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
154
+
155
+ if attn.group_norm is not None:
156
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
157
+
158
+ value = attn.to_v(hidden_states_ptb)
159
+
160
+ # hidden_states_ptb = torch.zeros(value.shape).to(value.get_device())
161
+ hidden_states_ptb = value
162
+
163
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
164
+
165
+ # linear proj
166
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
167
+ # dropout
168
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
169
+
170
+ if input_ndim == 4:
171
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
172
+
173
+ # cat
174
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
175
+
176
+ if attn.residual_connection:
177
+ hidden_states = hidden_states + residual
178
+
179
+ hidden_states = hidden_states / attn.rescale_output_factor
180
+
181
+ return hidden_states
182
+
183
+
184
+ class PAGCFGIdentitySelfAttnProcessor:
185
+ r"""
186
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
187
+ """
188
+
189
+ def __init__(self):
190
+ if not hasattr(F, "scaled_dot_product_attention"):
191
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
192
+
193
+ def __call__(
194
+ self,
195
+ attn: Attention,
196
+ hidden_states: torch.FloatTensor,
197
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
198
+ attention_mask: Optional[torch.FloatTensor] = None,
199
+ temb: Optional[torch.FloatTensor] = None,
200
+ *args,
201
+ **kwargs,
202
+ ) -> torch.FloatTensor:
203
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
204
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
205
+ deprecate("scale", "1.0.0", deprecation_message)
206
+
207
+ residual = hidden_states
208
+ if attn.spatial_norm is not None:
209
+ hidden_states = attn.spatial_norm(hidden_states, temb)
210
+
211
+ input_ndim = hidden_states.ndim
212
+ if input_ndim == 4:
213
+ batch_size, channel, height, width = hidden_states.shape
214
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
215
+
216
+ # chunk
217
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
218
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
219
+
220
+ # original path
221
+ batch_size, sequence_length, _ = hidden_states_org.shape
222
+
223
+ if attention_mask is not None:
224
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
225
+ # scaled_dot_product_attention expects attention_mask shape to be
226
+ # (batch, heads, source_length, target_length)
227
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
228
+
229
+ if attn.group_norm is not None:
230
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
231
+
232
+ query = attn.to_q(hidden_states_org)
233
+ key = attn.to_k(hidden_states_org)
234
+ value = attn.to_v(hidden_states_org)
235
+
236
+ inner_dim = key.shape[-1]
237
+ head_dim = inner_dim // attn.heads
238
+
239
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
240
+
241
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
242
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
243
+
244
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
245
+ # TODO: add support for attn.scale when we move to Torch 2.1
246
+ hidden_states_org = F.scaled_dot_product_attention(
247
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
248
+ )
249
+
250
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
251
+ hidden_states_org = hidden_states_org.to(query.dtype)
252
+
253
+ # linear proj
254
+ hidden_states_org = attn.to_out[0](hidden_states_org)
255
+ # dropout
256
+ hidden_states_org = attn.to_out[1](hidden_states_org)
257
+
258
+ if input_ndim == 4:
259
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
260
+
261
+ # perturbed path (identity attention)
262
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
263
+
264
+ if attention_mask is not None:
265
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
266
+ # scaled_dot_product_attention expects attention_mask shape to be
267
+ # (batch, heads, source_length, target_length)
268
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
269
+
270
+ if attn.group_norm is not None:
271
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
272
+
273
+ value = attn.to_v(hidden_states_ptb)
274
+ hidden_states_ptb = value
275
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
276
+
277
+ # linear proj
278
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
279
+ # dropout
280
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
281
+
282
+ if input_ndim == 4:
283
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
284
+
285
+ # cat
286
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
287
+
288
+ if attn.residual_connection:
289
+ hidden_states = hidden_states + residual
290
+
291
+ hidden_states = hidden_states / attn.rescale_output_factor
292
+
293
+ return hidden_states
294
+
295
+ if is_invisible_watermark_available():
296
+ from diffusers.pipelines.stable_diffusion_xl.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
+ """
309
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
310
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
311
+ """
312
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
313
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
314
+ # rescale the results from guidance (fixes overexposure)
315
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
316
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
317
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
318
+ return noise_cfg
319
+
320
+
321
+ def retrieve_timesteps(
322
+ scheduler,
323
+ num_inference_steps: Optional[int] = None,
324
+ device: Optional[Union[str, torch.device]] = None,
325
+ timesteps: Optional[List[int]] = None,
326
+ **kwargs,
327
+ ):
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.
348
+ """
349
+ if timesteps is not None:
350
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
351
+ if not accepts_timesteps:
352
+ raise ValueError(
353
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
354
+ f" timestep schedules. Please check whether you are using the correct scheduler."
355
+ )
356
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
357
+ timesteps = scheduler.timesteps
358
+ num_inference_steps = len(timesteps)
359
+ else:
360
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
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`):
504
+ number of images that should be generated per prompt
505
+ do_classifier_free_guidance (`bool`):
506
+ whether to use classifier free guidance or not
507
+ negative_prompt (`str` or `List[str]`, *optional*):
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.
517
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
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`:"
636
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
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
+
714
+ if not isinstance(image, torch.Tensor):
715
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
716
+
717
+ image = image.to(device=device, dtype=dtype)
718
+ if output_hidden_states:
719
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
720
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
721
+ uncond_image_enc_hidden_states = self.image_encoder(
722
+ torch.zeros_like(image), output_hidden_states=True
723
+ ).hidden_states[-2]
724
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
725
+ num_images_per_prompt, dim=0
726
+ )
727
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
728
+ else:
729
+ image_embeds = self.image_encoder(image).image_embeds
730
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
731
+ uncond_image_embeds = torch.zeros_like(image_embeds)
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):
741
+ ip_adapter_image = [ip_adapter_image]
742
+
743
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
744
+ raise ValueError(
745
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
746
+ )
747
+
748
+ image_embeds = []
749
+ for single_ip_adapter_image, image_proj_layer in zip(
750
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
751
+ ):
752
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
753
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
754
+ single_ip_adapter_image, device, 1, output_hidden_state
755
+ )
756
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
757
+ single_negative_image_embeds = torch.stack(
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.
791
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
792
+ # and should be between [0, 1]
793
+
794
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
795
+ extra_step_kwargs = {}
796
+ if accepts_eta:
797
+ extra_step_kwargs["eta"] = eta
798
+
799
+ # check if the scheduler accepts generator
800
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
801
+ if accepts_generator:
802
+ extra_step_kwargs["generator"] = generator
803
+ return extra_step_kwargs
804
+
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,
821
+ ):
822
+ if height % 8 != 0 or width % 8 != 0:
823
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
824
+
825
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
826
+ raise ValueError(
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
+ ):
834
+ raise ValueError(
835
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
836
+ )
837
+
838
+ if prompt is not None and prompt_embeds is not None:
839
+ raise ValueError(
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:
870
+ raise ValueError(
871
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
872
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
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:
905
+ raise ValueError(
906
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
907
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
908
+ )
909
+
910
+ if latents is None:
911
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
912
+ else:
913
+ latents = latents.to(device)
914
+
915
+ # scale the initial noise by the standard deviation required by the scheduler
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
977
+
978
+ half_dim = embedding_dim // 2
979
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
980
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
981
+ emb = w.to(dtype)[:, None] * emb[None, :]
982
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
983
+ if embedding_dim % 2 == 1: # zero pad
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
+
991
+ beta_prod_t = 1 - alpha_prod_t
992
+ if self.scheduler.config.prediction_type == "epsilon":
993
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
994
+ elif self.scheduler.config.prediction_type == "sample":
995
+ pred_original_sample = model_output
996
+ elif self.scheduler.config.prediction_type == "v_prediction":
997
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
998
+ # predict V
999
+ model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
1000
+ else:
1001
+ raise ValueError(
1002
+ f"prediction_type given as {self.scheduler.config.prediction_type} must be one of `epsilon`, `sample`,"
1003
+ " or `v_prediction`"
1004
+ )
1005
+
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
1024
+
1025
+ @property
1026
+ def guidance_rescale(self):
1027
+ return self._guidance_rescale
1028
+
1029
+ @property
1030
+ def clip_skip(self):
1031
+ return self._clip_skip
1032
+
1033
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1034
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1035
+ # corresponds to doing no classifier free guidance.
1036
+ @property
1037
+ def do_classifier_free_guidance(self):
1038
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1039
+
1040
+ @property
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
1051
+
1052
+ @property
1053
+ def interrupt(self):
1054
+ return self._interrupt
1055
+
1056
+ @property
1057
+ def pag_scale(self):
1058
+ return self._pag_scale
1059
+
1060
+ @property
1061
+ def do_adversarial_guidance(self):
1062
+ return self._pag_scale > 0
1063
+
1064
+ @property
1065
+ def pag_adaptive_scaling(self):
1066
+ return self._pag_adaptive_scaling
1067
+
1068
+ @property
1069
+ def do_pag_adaptive_scaling(self):
1070
+ return self._pag_adaptive_scaling > 0
1071
+
1072
+ @property
1073
+ def pag_drop_rate(self):
1074
+ return self._pag_drop_rate
1075
+
1076
+ @property
1077
+ def pag_applied_layers(self):
1078
+ return self._pag_applied_layers
1079
+
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.
1151
+ timesteps (`List[int]`, *optional*):
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,
1254
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1255
+ `callback_on_step_end_tensor_inputs`.
1256
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
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)
1270
+ callback_steps = kwargs.pop("callback_steps", None)
1271
+
1272
+ if callback is not 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,
1308
+ )
1309
+
1310
+ self._guidance_scale = guidance_scale
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
1326
+ elif prompt is not None and isinstance(prompt, list):
1327
+ batch_size = len(prompt)
1328
+ else:
1329
+ batch_size = prompt_embeds.shape[0]
1330
+
1331
+ device = self._execution_device
1332
+
1333
+ # 3. Encode input prompt
1334
+ lora_scale = (
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
+
1362
+ # 5. Prepare latent variables
1363
+ num_channels_latents = self.unet.config.in_channels
1364
+ latents = self.prepare_latents(
1365
+ batch_size * num_images_per_prompt,
1366
+ num_channels_latents,
1367
+ height,
1368
+ width,
1369
+ prompt_embeds.dtype,
1370
+ device,
1371
+ generator,
1372
+ latents,
1373
+ )
1374
+
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)
1455
+ timestep_cond = self.get_guidance_scale_embedding(
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 = []
1463
+ up_layers = []
1464
+ for name, module in self.unet.named_modules():
1465
+ if 'attn1' in name and 'to' not in name:
1466
+ layer_type = name.split('.')[0].split('_')[0]
1467
+ if layer_type == 'down':
1468
+ down_layers.append(module)
1469
+ elif layer_type == 'mid':
1470
+ mid_layers.append(module)
1471
+ elif layer_type == 'up':
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)
1485
+ #pag
1486
+ elif not self.do_classifier_free_guidance and self.do_adversarial_guidance:
1487
+ latent_model_input = torch.cat([latents] * 2)
1488
+ #both
1489
+ elif self.do_classifier_free_guidance and self.do_adversarial_guidance:
1490
+ latent_model_input = torch.cat([latents] * 3)
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
+
1498
+ if self.do_classifier_free_guidance:
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,
1550
+ encoder_hidden_states=prompt_embeds,
1551
+ timestep_cond=timestep_cond,
1552
+ cross_attention_kwargs=self.cross_attention_kwargs,
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
1566
+ if self.do_pag_adaptive_scaling:
1567
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000-t)
1568
+ if signal_scale<0:
1569
+ signal_scale = 0
1570
+
1571
+ noise_pred = noise_pred_original + signal_scale * (noise_pred_original - noise_pred_perturb)
1572
+
1573
+ # both
1574
+ elif self.do_classifier_free_guidance and self.do_adversarial_guidance:
1575
+
1576
+ noise_pred_uncond, noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(3)
1577
+
1578
+ signal_scale = self.pag_scale
1579
+ if self.do_pag_adaptive_scaling:
1580
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000-t)
1581
+ if signal_scale<0:
1582
+ signal_scale = 0
1583
+
1584
+ noise_pred = noise_pred_text + (self.guidance_scale-1.0) * (noise_pred_text - noise_pred_uncond) + signal_scale * (noise_pred_text - noise_pred_text_perturb)
1585
+
1586
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1587
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
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 = {}
1600
+ for k in callback_on_step_end_tensor_inputs:
1601
+ callback_kwargs[k] = locals()[k]
1602
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1603
+
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):
1616
+ progress_bar.update()
1617
+ if callback is not None and i % callback_steps == 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)
sd_pag_demo.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
uncond_generation_pag.jpg ADDED