hyoungwoncho commited on
Commit
36de266
1 Parent(s): 5983668

Upload pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +1705 -0
pipeline.py ADDED
@@ -0,0 +1,1705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation of Stable Diffusion ControlNet Pipeline with Perturbed-Attention Guidance
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
11
+
12
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
13
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
14
+ from diffusers.models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
15
+ from diffusers.models.attention_processor import Attention, AttnProcessor2_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 is_compiled_module, is_torch_version, randn_tensor
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
28
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
29
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
30
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ EXAMPLE_DOC_STRING = """
37
+ Examples:
38
+ ```py
39
+ >>> # !pip install opencv-python transformers accelerate
40
+ >>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
41
+ >>> from diffusers.utils import load_image
42
+ >>> import numpy as np
43
+ >>> import torch
44
+
45
+ >>> import cv2
46
+ >>> from PIL import Image
47
+
48
+ >>> # download an image
49
+ >>> image = load_image(
50
+ ... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
51
+ ... )
52
+ >>> image = np.array(image)
53
+
54
+ >>> # get canny image
55
+ >>> image = cv2.Canny(image, 100, 200)
56
+ >>> image = image[:, :, None]
57
+ >>> image = np.concatenate([image, image, image], axis=2)
58
+ >>> canny_image = Image.fromarray(image)
59
+
60
+ >>> # load control net and stable diffusion v1-5
61
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
62
+ >>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
63
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
64
+ ... )
65
+
66
+ >>> # speed up diffusion process with faster scheduler and memory optimization
67
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
68
+ >>> # remove following line if xformers is not installed
69
+ >>> pipe.enable_xformers_memory_efficient_attention()
70
+
71
+ >>> pipe.enable_model_cpu_offload()
72
+
73
+ >>> # generate image
74
+ >>> generator = torch.manual_seed(0)
75
+ >>> image = pipe(
76
+ ... "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
77
+ ... ).images[0]
78
+ ```
79
+ """
80
+
81
+
82
+ class PAGIdentitySelfAttnProcessor:
83
+ r"""
84
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
85
+ """
86
+
87
+ def __init__(self):
88
+ if not hasattr(F, "scaled_dot_product_attention"):
89
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
90
+
91
+ def __call__(
92
+ self,
93
+ attn: Attention,
94
+ hidden_states: torch.FloatTensor,
95
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
96
+ attention_mask: Optional[torch.FloatTensor] = None,
97
+ temb: Optional[torch.FloatTensor] = None,
98
+ *args,
99
+ **kwargs,
100
+ ) -> torch.FloatTensor:
101
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
102
+ 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`."
103
+ deprecate("scale", "1.0.0", deprecation_message)
104
+
105
+ residual = hidden_states
106
+ if attn.spatial_norm is not None:
107
+ hidden_states = attn.spatial_norm(hidden_states, temb)
108
+
109
+ input_ndim = hidden_states.ndim
110
+ if input_ndim == 4:
111
+ batch_size, channel, height, width = hidden_states.shape
112
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
113
+
114
+ # chunk
115
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
116
+
117
+ # original path
118
+ batch_size, sequence_length, _ = hidden_states_org.shape
119
+
120
+ if attention_mask is not None:
121
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
122
+ # scaled_dot_product_attention expects attention_mask shape to be
123
+ # (batch, heads, source_length, target_length)
124
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
125
+
126
+ if attn.group_norm is not None:
127
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
128
+
129
+ query = attn.to_q(hidden_states_org)
130
+ key = attn.to_k(hidden_states_org)
131
+ value = attn.to_v(hidden_states_org)
132
+
133
+ inner_dim = key.shape[-1]
134
+ head_dim = inner_dim // attn.heads
135
+
136
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
137
+
138
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
139
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
140
+
141
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
142
+ # TODO: add support for attn.scale when we move to Torch 2.1
143
+ hidden_states_org = F.scaled_dot_product_attention(
144
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
145
+ )
146
+
147
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
148
+ hidden_states_org = hidden_states_org.to(query.dtype)
149
+
150
+ # linear proj
151
+ hidden_states_org = attn.to_out[0](hidden_states_org)
152
+ # dropout
153
+ hidden_states_org = attn.to_out[1](hidden_states_org)
154
+
155
+ if input_ndim == 4:
156
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
157
+
158
+ # perturbed path (identity attention)
159
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
160
+
161
+ if attention_mask is not None:
162
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
163
+ # scaled_dot_product_attention expects attention_mask shape to be
164
+ # (batch, heads, source_length, target_length)
165
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
166
+
167
+ if attn.group_norm is not None:
168
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
169
+
170
+ value = attn.to_v(hidden_states_ptb)
171
+
172
+ # hidden_states_ptb = torch.zeros(value.shape).to(value.get_device())
173
+ hidden_states_ptb = value
174
+
175
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
176
+
177
+ # linear proj
178
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
179
+ # dropout
180
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
181
+
182
+ if input_ndim == 4:
183
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
184
+
185
+ # cat
186
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
187
+
188
+ if attn.residual_connection:
189
+ hidden_states = hidden_states + residual
190
+
191
+ hidden_states = hidden_states / attn.rescale_output_factor
192
+
193
+ return hidden_states
194
+
195
+
196
+ class PAGCFGIdentitySelfAttnProcessor:
197
+ r"""
198
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
199
+ """
200
+
201
+ def __init__(self):
202
+ if not hasattr(F, "scaled_dot_product_attention"):
203
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
204
+
205
+ def __call__(
206
+ self,
207
+ attn: Attention,
208
+ hidden_states: torch.FloatTensor,
209
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
210
+ attention_mask: Optional[torch.FloatTensor] = None,
211
+ temb: Optional[torch.FloatTensor] = None,
212
+ *args,
213
+ **kwargs,
214
+ ) -> torch.FloatTensor:
215
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
216
+ 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`."
217
+ deprecate("scale", "1.0.0", deprecation_message)
218
+
219
+ residual = hidden_states
220
+ if attn.spatial_norm is not None:
221
+ hidden_states = attn.spatial_norm(hidden_states, temb)
222
+
223
+ input_ndim = hidden_states.ndim
224
+ if input_ndim == 4:
225
+ batch_size, channel, height, width = hidden_states.shape
226
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
227
+
228
+ # chunk
229
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
230
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
231
+
232
+ # original path
233
+ batch_size, sequence_length, _ = hidden_states_org.shape
234
+
235
+ if attention_mask is not None:
236
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
237
+ # scaled_dot_product_attention expects attention_mask shape to be
238
+ # (batch, heads, source_length, target_length)
239
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
240
+
241
+ if attn.group_norm is not None:
242
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
243
+
244
+ query = attn.to_q(hidden_states_org)
245
+ key = attn.to_k(hidden_states_org)
246
+ value = attn.to_v(hidden_states_org)
247
+
248
+ inner_dim = key.shape[-1]
249
+ head_dim = inner_dim // attn.heads
250
+
251
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
252
+
253
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
254
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
255
+
256
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
257
+ # TODO: add support for attn.scale when we move to Torch 2.1
258
+ hidden_states_org = F.scaled_dot_product_attention(
259
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
260
+ )
261
+
262
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
263
+ hidden_states_org = hidden_states_org.to(query.dtype)
264
+
265
+ # linear proj
266
+ hidden_states_org = attn.to_out[0](hidden_states_org)
267
+ # dropout
268
+ hidden_states_org = attn.to_out[1](hidden_states_org)
269
+
270
+ if input_ndim == 4:
271
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
272
+
273
+ # perturbed path (identity attention)
274
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
275
+
276
+ if attention_mask is not None:
277
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
278
+ # scaled_dot_product_attention expects attention_mask shape to be
279
+ # (batch, heads, source_length, target_length)
280
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
281
+
282
+ if attn.group_norm is not None:
283
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
284
+
285
+ value = attn.to_v(hidden_states_ptb)
286
+ hidden_states_ptb = value
287
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
288
+
289
+ # linear proj
290
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
291
+ # dropout
292
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
293
+
294
+ if input_ndim == 4:
295
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
296
+
297
+ # cat
298
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
299
+
300
+ if attn.residual_connection:
301
+ hidden_states = hidden_states + residual
302
+
303
+ hidden_states = hidden_states / attn.rescale_output_factor
304
+
305
+ return hidden_states
306
+
307
+
308
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
309
+ def retrieve_timesteps(
310
+ scheduler,
311
+ num_inference_steps: Optional[int] = None,
312
+ device: Optional[Union[str, torch.device]] = None,
313
+ timesteps: Optional[List[int]] = None,
314
+ **kwargs,
315
+ ):
316
+ """
317
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
318
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
319
+
320
+ Args:
321
+ scheduler (`SchedulerMixin`):
322
+ The scheduler to get timesteps from.
323
+ num_inference_steps (`int`):
324
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
325
+ must be `None`.
326
+ device (`str` or `torch.device`, *optional*):
327
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
328
+ timesteps (`List[int]`, *optional*):
329
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
330
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
331
+ must be `None`.
332
+
333
+ Returns:
334
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
335
+ second element is the number of inference steps.
336
+ """
337
+ if timesteps is not None:
338
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
339
+ if not accepts_timesteps:
340
+ raise ValueError(
341
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
342
+ f" timestep schedules. Please check whether you are using the correct scheduler."
343
+ )
344
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
345
+ timesteps = scheduler.timesteps
346
+ num_inference_steps = len(timesteps)
347
+ else:
348
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
349
+ timesteps = scheduler.timesteps
350
+ return timesteps, num_inference_steps
351
+
352
+
353
+ class StableDiffusionControlNetPipeline(
354
+ DiffusionPipeline,
355
+ StableDiffusionMixin,
356
+ TextualInversionLoaderMixin,
357
+ LoraLoaderMixin,
358
+ IPAdapterMixin,
359
+ FromSingleFileMixin,
360
+ ):
361
+ r"""
362
+ Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
363
+
364
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
365
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
366
+
367
+ The pipeline also inherits the following loading methods:
368
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
369
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
370
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
371
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
372
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
373
+
374
+ Args:
375
+ vae ([`AutoencoderKL`]):
376
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
377
+ text_encoder ([`~transformers.CLIPTextModel`]):
378
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
379
+ tokenizer ([`~transformers.CLIPTokenizer`]):
380
+ A `CLIPTokenizer` to tokenize text.
381
+ unet ([`UNet2DConditionModel`]):
382
+ A `UNet2DConditionModel` to denoise the encoded image latents.
383
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
384
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
385
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
386
+ additional conditioning.
387
+ scheduler ([`SchedulerMixin`]):
388
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
389
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
390
+ safety_checker ([`StableDiffusionSafetyChecker`]):
391
+ Classification module that estimates whether generated images could be considered offensive or harmful.
392
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
393
+ about a model's potential harms.
394
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
395
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
396
+ """
397
+
398
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
399
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
400
+ _exclude_from_cpu_offload = ["safety_checker"]
401
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
402
+
403
+ def __init__(
404
+ self,
405
+ vae: AutoencoderKL,
406
+ text_encoder: CLIPTextModel,
407
+ tokenizer: CLIPTokenizer,
408
+ unet: UNet2DConditionModel,
409
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
410
+ scheduler: KarrasDiffusionSchedulers,
411
+ safety_checker: StableDiffusionSafetyChecker,
412
+ feature_extractor: CLIPImageProcessor,
413
+ image_encoder: CLIPVisionModelWithProjection = None,
414
+ requires_safety_checker: bool = True,
415
+ ):
416
+ super().__init__()
417
+
418
+ if safety_checker is None and requires_safety_checker:
419
+ logger.warning(
420
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
421
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
422
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
423
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
424
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
425
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
426
+ )
427
+
428
+ if safety_checker is not None and feature_extractor is None:
429
+ raise ValueError(
430
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
431
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
432
+ )
433
+
434
+ if isinstance(controlnet, (list, tuple)):
435
+ controlnet = MultiControlNetModel(controlnet)
436
+
437
+ self.register_modules(
438
+ vae=vae,
439
+ text_encoder=text_encoder,
440
+ tokenizer=tokenizer,
441
+ unet=unet,
442
+ controlnet=controlnet,
443
+ scheduler=scheduler,
444
+ safety_checker=safety_checker,
445
+ feature_extractor=feature_extractor,
446
+ image_encoder=image_encoder,
447
+ )
448
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
449
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
450
+ self.control_image_processor = VaeImageProcessor(
451
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
452
+ )
453
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
454
+
455
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
456
+ def _encode_prompt(
457
+ self,
458
+ prompt,
459
+ device,
460
+ num_images_per_prompt,
461
+ do_classifier_free_guidance,
462
+ negative_prompt=None,
463
+ prompt_embeds: Optional[torch.FloatTensor] = None,
464
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
465
+ lora_scale: Optional[float] = None,
466
+ **kwargs,
467
+ ):
468
+ 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."
469
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
470
+
471
+ prompt_embeds_tuple = self.encode_prompt(
472
+ prompt=prompt,
473
+ device=device,
474
+ num_images_per_prompt=num_images_per_prompt,
475
+ do_classifier_free_guidance=do_classifier_free_guidance,
476
+ negative_prompt=negative_prompt,
477
+ prompt_embeds=prompt_embeds,
478
+ negative_prompt_embeds=negative_prompt_embeds,
479
+ lora_scale=lora_scale,
480
+ **kwargs,
481
+ )
482
+
483
+ # concatenate for backwards comp
484
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
485
+
486
+ return prompt_embeds
487
+
488
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
489
+ def encode_prompt(
490
+ self,
491
+ prompt,
492
+ device,
493
+ num_images_per_prompt,
494
+ do_classifier_free_guidance,
495
+ negative_prompt=None,
496
+ prompt_embeds: Optional[torch.FloatTensor] = None,
497
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
498
+ lora_scale: Optional[float] = None,
499
+ clip_skip: Optional[int] = None,
500
+ ):
501
+ r"""
502
+ Encodes the prompt into text encoder hidden states.
503
+
504
+ Args:
505
+ prompt (`str` or `List[str]`, *optional*):
506
+ prompt to be encoded
507
+ device: (`torch.device`):
508
+ torch device
509
+ num_images_per_prompt (`int`):
510
+ number of images that should be generated per prompt
511
+ do_classifier_free_guidance (`bool`):
512
+ whether to use classifier free guidance or not
513
+ negative_prompt (`str` or `List[str]`, *optional*):
514
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
515
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
516
+ less than `1`).
517
+ prompt_embeds (`torch.FloatTensor`, *optional*):
518
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
519
+ provided, text embeddings will be generated from `prompt` input argument.
520
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
521
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
522
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
523
+ argument.
524
+ lora_scale (`float`, *optional*):
525
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
526
+ clip_skip (`int`, *optional*):
527
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
528
+ the output of the pre-final layer will be used for computing the prompt embeddings.
529
+ """
530
+ # set lora scale so that monkey patched LoRA
531
+ # function of text encoder can correctly access it
532
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
533
+ self._lora_scale = lora_scale
534
+
535
+ # dynamically adjust the LoRA scale
536
+ if not USE_PEFT_BACKEND:
537
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
538
+ else:
539
+ scale_lora_layers(self.text_encoder, lora_scale)
540
+
541
+ if prompt is not None and isinstance(prompt, str):
542
+ batch_size = 1
543
+ elif prompt is not None and isinstance(prompt, list):
544
+ batch_size = len(prompt)
545
+ else:
546
+ batch_size = prompt_embeds.shape[0]
547
+
548
+ if prompt_embeds is None:
549
+ # textual inversion: process multi-vector tokens if necessary
550
+ if isinstance(self, TextualInversionLoaderMixin):
551
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
552
+
553
+ text_inputs = self.tokenizer(
554
+ prompt,
555
+ padding="max_length",
556
+ max_length=self.tokenizer.model_max_length,
557
+ truncation=True,
558
+ return_tensors="pt",
559
+ )
560
+ text_input_ids = text_inputs.input_ids
561
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
562
+
563
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
564
+ text_input_ids, untruncated_ids
565
+ ):
566
+ removed_text = self.tokenizer.batch_decode(
567
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
568
+ )
569
+ logger.warning(
570
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
571
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
572
+ )
573
+
574
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
575
+ attention_mask = text_inputs.attention_mask.to(device)
576
+ else:
577
+ attention_mask = None
578
+
579
+ if clip_skip is None:
580
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
581
+ prompt_embeds = prompt_embeds[0]
582
+ else:
583
+ prompt_embeds = self.text_encoder(
584
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
585
+ )
586
+ # Access the `hidden_states` first, that contains a tuple of
587
+ # all the hidden states from the encoder layers. Then index into
588
+ # the tuple to access the hidden states from the desired layer.
589
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
590
+ # We also need to apply the final LayerNorm here to not mess with the
591
+ # representations. The `last_hidden_states` that we typically use for
592
+ # obtaining the final prompt representations passes through the LayerNorm
593
+ # layer.
594
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
595
+
596
+ if self.text_encoder is not None:
597
+ prompt_embeds_dtype = self.text_encoder.dtype
598
+ elif self.unet is not None:
599
+ prompt_embeds_dtype = self.unet.dtype
600
+ else:
601
+ prompt_embeds_dtype = prompt_embeds.dtype
602
+
603
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
604
+
605
+ bs_embed, seq_len, _ = prompt_embeds.shape
606
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
607
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
608
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
609
+
610
+ # get unconditional embeddings for classifier free guidance
611
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
612
+ uncond_tokens: List[str]
613
+ if negative_prompt is None:
614
+ uncond_tokens = [""] * batch_size
615
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
616
+ raise TypeError(
617
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
618
+ f" {type(prompt)}."
619
+ )
620
+ elif isinstance(negative_prompt, str):
621
+ uncond_tokens = [negative_prompt]
622
+ elif batch_size != len(negative_prompt):
623
+ raise ValueError(
624
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
625
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
626
+ " the batch size of `prompt`."
627
+ )
628
+ else:
629
+ uncond_tokens = negative_prompt
630
+
631
+ # textual inversion: process multi-vector tokens if necessary
632
+ if isinstance(self, TextualInversionLoaderMixin):
633
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
634
+
635
+ max_length = prompt_embeds.shape[1]
636
+ uncond_input = self.tokenizer(
637
+ uncond_tokens,
638
+ padding="max_length",
639
+ max_length=max_length,
640
+ truncation=True,
641
+ return_tensors="pt",
642
+ )
643
+
644
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
645
+ attention_mask = uncond_input.attention_mask.to(device)
646
+ else:
647
+ attention_mask = None
648
+
649
+ negative_prompt_embeds = self.text_encoder(
650
+ uncond_input.input_ids.to(device),
651
+ attention_mask=attention_mask,
652
+ )
653
+ negative_prompt_embeds = negative_prompt_embeds[0]
654
+
655
+ if do_classifier_free_guidance:
656
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
657
+ seq_len = negative_prompt_embeds.shape[1]
658
+
659
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
660
+
661
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
662
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
663
+
664
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
665
+ # Retrieve the original scale by scaling back the LoRA layers
666
+ unscale_lora_layers(self.text_encoder, lora_scale)
667
+
668
+ return prompt_embeds, negative_prompt_embeds
669
+
670
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
671
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
672
+ dtype = next(self.image_encoder.parameters()).dtype
673
+
674
+ if not isinstance(image, torch.Tensor):
675
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
676
+
677
+ image = image.to(device=device, dtype=dtype)
678
+ if output_hidden_states:
679
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
680
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
681
+ uncond_image_enc_hidden_states = self.image_encoder(
682
+ torch.zeros_like(image), output_hidden_states=True
683
+ ).hidden_states[-2]
684
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
685
+ num_images_per_prompt, dim=0
686
+ )
687
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
688
+ else:
689
+ image_embeds = self.image_encoder(image).image_embeds
690
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
691
+ uncond_image_embeds = torch.zeros_like(image_embeds)
692
+
693
+ return image_embeds, uncond_image_embeds
694
+
695
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
696
+ def prepare_ip_adapter_image_embeds(
697
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
698
+ ):
699
+ if ip_adapter_image_embeds is None:
700
+ if not isinstance(ip_adapter_image, list):
701
+ ip_adapter_image = [ip_adapter_image]
702
+
703
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
704
+ raise ValueError(
705
+ 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."
706
+ )
707
+
708
+ image_embeds = []
709
+ for single_ip_adapter_image, image_proj_layer in zip(
710
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
711
+ ):
712
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
713
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
714
+ single_ip_adapter_image, device, 1, output_hidden_state
715
+ )
716
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
717
+ single_negative_image_embeds = torch.stack(
718
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
719
+ )
720
+
721
+ if do_classifier_free_guidance:
722
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
723
+ single_image_embeds = single_image_embeds.to(device)
724
+
725
+ image_embeds.append(single_image_embeds)
726
+ else:
727
+ repeat_dims = [1]
728
+ image_embeds = []
729
+ for single_image_embeds in ip_adapter_image_embeds:
730
+ if do_classifier_free_guidance:
731
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
732
+ single_image_embeds = single_image_embeds.repeat(
733
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
734
+ )
735
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
736
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
737
+ )
738
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
739
+ else:
740
+ single_image_embeds = single_image_embeds.repeat(
741
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
742
+ )
743
+ image_embeds.append(single_image_embeds)
744
+
745
+ return image_embeds
746
+
747
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
748
+ def run_safety_checker(self, image, device, dtype):
749
+ if self.safety_checker is None:
750
+ has_nsfw_concept = None
751
+ else:
752
+ if torch.is_tensor(image):
753
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
754
+ else:
755
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
756
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
757
+ image, has_nsfw_concept = self.safety_checker(
758
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
759
+ )
760
+ return image, has_nsfw_concept
761
+
762
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
763
+ def decode_latents(self, latents):
764
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
765
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
766
+
767
+ latents = 1 / self.vae.config.scaling_factor * latents
768
+ image = self.vae.decode(latents, return_dict=False)[0]
769
+ image = (image / 2 + 0.5).clamp(0, 1)
770
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
771
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
772
+ return image
773
+
774
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
775
+ def prepare_extra_step_kwargs(self, generator, eta):
776
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
777
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
778
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
779
+ # and should be between [0, 1]
780
+
781
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
782
+ extra_step_kwargs = {}
783
+ if accepts_eta:
784
+ extra_step_kwargs["eta"] = eta
785
+
786
+ # check if the scheduler accepts generator
787
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
788
+ if accepts_generator:
789
+ extra_step_kwargs["generator"] = generator
790
+ return extra_step_kwargs
791
+
792
+ def check_inputs(
793
+ self,
794
+ prompt,
795
+ image,
796
+ callback_steps,
797
+ negative_prompt=None,
798
+ prompt_embeds=None,
799
+ negative_prompt_embeds=None,
800
+ ip_adapter_image=None,
801
+ ip_adapter_image_embeds=None,
802
+ controlnet_conditioning_scale=1.0,
803
+ control_guidance_start=0.0,
804
+ control_guidance_end=1.0,
805
+ callback_on_step_end_tensor_inputs=None,
806
+ ):
807
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
808
+ raise ValueError(
809
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
810
+ f" {type(callback_steps)}."
811
+ )
812
+
813
+ if callback_on_step_end_tensor_inputs is not None and not all(
814
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
815
+ ):
816
+ raise ValueError(
817
+ 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]}"
818
+ )
819
+
820
+ if prompt is not None and prompt_embeds is not None:
821
+ raise ValueError(
822
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
823
+ " only forward one of the two."
824
+ )
825
+ elif prompt is None and prompt_embeds is None:
826
+ raise ValueError(
827
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
828
+ )
829
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
830
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
831
+
832
+ if negative_prompt is not None and negative_prompt_embeds is not None:
833
+ raise ValueError(
834
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
835
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
836
+ )
837
+
838
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
839
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
840
+ raise ValueError(
841
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
842
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
843
+ f" {negative_prompt_embeds.shape}."
844
+ )
845
+
846
+ # Check `image`
847
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
848
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
849
+ )
850
+ if (
851
+ isinstance(self.controlnet, ControlNetModel)
852
+ or is_compiled
853
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
854
+ ):
855
+ self.check_image(image, prompt, prompt_embeds)
856
+ elif (
857
+ isinstance(self.controlnet, MultiControlNetModel)
858
+ or is_compiled
859
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
860
+ ):
861
+ if not isinstance(image, list):
862
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
863
+
864
+ # When `image` is a nested list:
865
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
866
+ elif any(isinstance(i, list) for i in image):
867
+ transposed_image = [list(t) for t in zip(*image)]
868
+ if len(transposed_image) != len(self.controlnet.nets):
869
+ raise ValueError(
870
+ f"For multiple controlnets: if you pass`image` as a list of list, each sublist must have the same length as the number of controlnets, but the sublists in `image` got {len(transposed_image)} images and {len(self.controlnet.nets)} ControlNets."
871
+ )
872
+ for image_ in transposed_image:
873
+ self.check_image(image_, prompt, prompt_embeds)
874
+ elif len(image) != len(self.controlnet.nets):
875
+ raise ValueError(
876
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
877
+ )
878
+ else:
879
+ for image_ in image:
880
+ self.check_image(image_, prompt, prompt_embeds)
881
+ else:
882
+ assert False
883
+
884
+ # Check `controlnet_conditioning_scale`
885
+ if (
886
+ isinstance(self.controlnet, ControlNetModel)
887
+ or is_compiled
888
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
889
+ ):
890
+ if not isinstance(controlnet_conditioning_scale, float):
891
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
892
+ elif (
893
+ isinstance(self.controlnet, MultiControlNetModel)
894
+ or is_compiled
895
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
896
+ ):
897
+ if isinstance(controlnet_conditioning_scale, list):
898
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
899
+ raise ValueError(
900
+ "A single batch of varying conditioning scale settings (e.g. [[1.0, 0.5], [0.2, 0.8]]) is not supported at the moment. "
901
+ "The conditioning scale must be fixed across the batch."
902
+ )
903
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
904
+ self.controlnet.nets
905
+ ):
906
+ raise ValueError(
907
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
908
+ " the same length as the number of controlnets"
909
+ )
910
+ else:
911
+ assert False
912
+
913
+ if not isinstance(control_guidance_start, (tuple, list)):
914
+ control_guidance_start = [control_guidance_start]
915
+
916
+ if not isinstance(control_guidance_end, (tuple, list)):
917
+ control_guidance_end = [control_guidance_end]
918
+
919
+ if len(control_guidance_start) != len(control_guidance_end):
920
+ raise ValueError(
921
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
922
+ )
923
+
924
+ if isinstance(self.controlnet, MultiControlNetModel):
925
+ if len(control_guidance_start) != len(self.controlnet.nets):
926
+ raise ValueError(
927
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
928
+ )
929
+
930
+ for start, end in zip(control_guidance_start, control_guidance_end):
931
+ if start >= end:
932
+ raise ValueError(
933
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
934
+ )
935
+ if start < 0.0:
936
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
937
+ if end > 1.0:
938
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
939
+
940
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
941
+ raise ValueError(
942
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
943
+ )
944
+
945
+ if ip_adapter_image_embeds is not None:
946
+ if not isinstance(ip_adapter_image_embeds, list):
947
+ raise ValueError(
948
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
949
+ )
950
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
951
+ raise ValueError(
952
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
953
+ )
954
+
955
+ def check_image(self, image, prompt, prompt_embeds):
956
+ image_is_pil = isinstance(image, PIL.Image.Image)
957
+ image_is_tensor = isinstance(image, torch.Tensor)
958
+ image_is_np = isinstance(image, np.ndarray)
959
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
960
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
961
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
962
+
963
+ if (
964
+ not image_is_pil
965
+ and not image_is_tensor
966
+ and not image_is_np
967
+ and not image_is_pil_list
968
+ and not image_is_tensor_list
969
+ and not image_is_np_list
970
+ ):
971
+ raise TypeError(
972
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
973
+ )
974
+
975
+ if image_is_pil:
976
+ image_batch_size = 1
977
+ else:
978
+ image_batch_size = len(image)
979
+
980
+ if prompt is not None and isinstance(prompt, str):
981
+ prompt_batch_size = 1
982
+ elif prompt is not None and isinstance(prompt, list):
983
+ prompt_batch_size = len(prompt)
984
+ elif prompt_embeds is not None:
985
+ prompt_batch_size = prompt_embeds.shape[0]
986
+
987
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
988
+ raise ValueError(
989
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
990
+ )
991
+
992
+ def prepare_image(
993
+ self,
994
+ image,
995
+ width,
996
+ height,
997
+ batch_size,
998
+ num_images_per_prompt,
999
+ device,
1000
+ dtype,
1001
+ do_classifier_free_guidance=False,
1002
+ do_perturbed_attention_guidance=False,
1003
+ guess_mode=False,
1004
+ ):
1005
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1006
+ image_batch_size = image.shape[0]
1007
+
1008
+ if image_batch_size == 1:
1009
+ repeat_by = batch_size
1010
+ else:
1011
+ # image batch size is the same as prompt batch size
1012
+ repeat_by = num_images_per_prompt
1013
+
1014
+ image = image.repeat_interleave(repeat_by, dim=0)
1015
+
1016
+ image = image.to(device=device, dtype=dtype)
1017
+
1018
+ if do_classifier_free_guidance and not do_perturbed_attention_guidance and not guess_mode:
1019
+ image = torch.cat([image] * 2)
1020
+ elif not do_classifier_free_guidance and do_perturbed_attention_guidance and not guess_mode:
1021
+ image = torch.cat([image] * 2)
1022
+ elif do_classifier_free_guidance and do_perturbed_attention_guidance and not guess_mode:
1023
+ image = torch.cat([image] * 3)
1024
+
1025
+ return image
1026
+
1027
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
1028
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
1029
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
1030
+ if isinstance(generator, list) and len(generator) != batch_size:
1031
+ raise ValueError(
1032
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
1033
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
1034
+ )
1035
+
1036
+ if latents is None:
1037
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
1038
+ else:
1039
+ latents = latents.to(device)
1040
+
1041
+ # scale the initial noise by the standard deviation required by the scheduler
1042
+ latents = latents * self.scheduler.init_noise_sigma
1043
+ return latents
1044
+
1045
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1046
+ def get_guidance_scale_embedding(
1047
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1048
+ ) -> torch.FloatTensor:
1049
+ """
1050
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1051
+
1052
+ Args:
1053
+ w (`torch.Tensor`):
1054
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1055
+ embedding_dim (`int`, *optional*, defaults to 512):
1056
+ Dimension of the embeddings to generate.
1057
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1058
+ Data type of the generated embeddings.
1059
+
1060
+ Returns:
1061
+ `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1062
+ """
1063
+ assert len(w.shape) == 1
1064
+ w = w * 1000.0
1065
+
1066
+ half_dim = embedding_dim // 2
1067
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1068
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1069
+ emb = w.to(dtype)[:, None] * emb[None, :]
1070
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1071
+ if embedding_dim % 2 == 1: # zero pad
1072
+ emb = torch.nn.functional.pad(emb, (0, 1))
1073
+ assert emb.shape == (w.shape[0], embedding_dim)
1074
+ return emb
1075
+
1076
+ @property
1077
+ def guidance_scale(self):
1078
+ return self._guidance_scale
1079
+
1080
+ @property
1081
+ def clip_skip(self):
1082
+ return self._clip_skip
1083
+
1084
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1085
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1086
+ # corresponds to doing no classifier free guidance.
1087
+ @property
1088
+ def do_classifier_free_guidance(self):
1089
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1090
+
1091
+ @property
1092
+ def cross_attention_kwargs(self):
1093
+ return self._cross_attention_kwargs
1094
+
1095
+ @property
1096
+ def num_timesteps(self):
1097
+ return self._num_timesteps
1098
+
1099
+ @property
1100
+ def pag_scale(self):
1101
+ return self._pag_scale
1102
+
1103
+ @property
1104
+ def do_perturbed_attention_guidance(self):
1105
+ return self._pag_scale > 0
1106
+
1107
+ @property
1108
+ def pag_adaptive_scaling(self):
1109
+ return self._pag_adaptive_scaling
1110
+
1111
+ @property
1112
+ def do_pag_adaptive_scaling(self):
1113
+ return self._pag_adaptive_scaling > 0
1114
+
1115
+ @property
1116
+ def pag_applied_layers_index(self):
1117
+ return self._pag_applied_layers_index
1118
+
1119
+ @torch.no_grad()
1120
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1121
+ def __call__(
1122
+ self,
1123
+ prompt: Union[str, List[str]] = None,
1124
+ image: PipelineImageInput = None,
1125
+ height: Optional[int] = None,
1126
+ width: Optional[int] = None,
1127
+ num_inference_steps: int = 50,
1128
+ timesteps: List[int] = None,
1129
+ guidance_scale: float = 7.5,
1130
+ pag_scale: float = 0.0,
1131
+ pag_adaptive_scaling: float = 0.0,
1132
+ pag_applied_layers_index: List[str] = ["d4"], # ['d4', 'd5', 'm0']
1133
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1134
+ num_images_per_prompt: Optional[int] = 1,
1135
+ eta: float = 0.0,
1136
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1137
+ latents: Optional[torch.FloatTensor] = None,
1138
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1139
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1140
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1141
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
1142
+ output_type: Optional[str] = "pil",
1143
+ return_dict: bool = True,
1144
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1145
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1146
+ guess_mode: bool = False,
1147
+ control_guidance_start: Union[float, List[float]] = 0.0,
1148
+ control_guidance_end: Union[float, List[float]] = 1.0,
1149
+ clip_skip: Optional[int] = None,
1150
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1151
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1152
+ **kwargs,
1153
+ ):
1154
+ r"""
1155
+ The call function to the pipeline for generation.
1156
+
1157
+ Args:
1158
+ prompt (`str` or `List[str]`, *optional*):
1159
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1160
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
1161
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
1162
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
1163
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
1164
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
1165
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
1166
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
1167
+ input to a single ControlNet. When `prompt` is a list, and if a list of images is passed for a single
1168
+ ControlNet, each will be paired with each prompt in the `prompt` list. This also applies to multiple
1169
+ ControlNets, where a list of image lists can be passed to batch for each prompt and each ControlNet.
1170
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1171
+ The height in pixels of the generated image.
1172
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1173
+ The width in pixels of the generated image.
1174
+ num_inference_steps (`int`, *optional*, defaults to 50):
1175
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1176
+ expense of slower inference.
1177
+ timesteps (`List[int]`, *optional*):
1178
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1179
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1180
+ passed will be used. Must be in descending order.
1181
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1182
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1183
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1184
+ negative_prompt (`str` or `List[str]`, *optional*):
1185
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1186
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1187
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1188
+ The number of images to generate per prompt.
1189
+ eta (`float`, *optional*, defaults to 0.0):
1190
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1191
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1192
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1193
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1194
+ generation deterministic.
1195
+ latents (`torch.FloatTensor`, *optional*):
1196
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1197
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1198
+ tensor is generated by sampling using the supplied random `generator`.
1199
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1200
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1201
+ provided, text embeddings are generated from the `prompt` input argument.
1202
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1203
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1204
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1205
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1206
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
1207
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1208
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1209
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1210
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1211
+ output_type (`str`, *optional*, defaults to `"pil"`):
1212
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1213
+ return_dict (`bool`, *optional*, defaults to `True`):
1214
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1215
+ plain tuple.
1216
+ callback (`Callable`, *optional*):
1217
+ A function that calls every `callback_steps` steps during inference. The function is called with the
1218
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1219
+ callback_steps (`int`, *optional*, defaults to 1):
1220
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
1221
+ every step.
1222
+ cross_attention_kwargs (`dict`, *optional*):
1223
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1224
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1225
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1226
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1227
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
1228
+ the corresponding scale as a list.
1229
+ guess_mode (`bool`, *optional*, defaults to `False`):
1230
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
1231
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
1232
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1233
+ The percentage of total steps at which the ControlNet starts applying.
1234
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1235
+ The percentage of total steps at which the ControlNet stops applying.
1236
+ clip_skip (`int`, *optional*):
1237
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1238
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1239
+ callback_on_step_end (`Callable`, *optional*):
1240
+ A function that calls at the end of each denoising steps during the inference. The function is called
1241
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1242
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1243
+ `callback_on_step_end_tensor_inputs`.
1244
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1245
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1246
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1247
+ `._callback_tensor_inputs` attribute of your pipeline class.
1248
+
1249
+ Examples:
1250
+
1251
+ Returns:
1252
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1253
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1254
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1255
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1256
+ "not-safe-for-work" (nsfw) content.
1257
+ """
1258
+
1259
+ callback = kwargs.pop("callback", None)
1260
+ callback_steps = kwargs.pop("callback_steps", None)
1261
+
1262
+ if callback is not None:
1263
+ deprecate(
1264
+ "callback",
1265
+ "1.0.0",
1266
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1267
+ )
1268
+ if callback_steps is not None:
1269
+ deprecate(
1270
+ "callback_steps",
1271
+ "1.0.0",
1272
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1273
+ )
1274
+
1275
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1276
+
1277
+ # align format for control guidance
1278
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1279
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1280
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1281
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1282
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1283
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1284
+ control_guidance_start, control_guidance_end = (
1285
+ mult * [control_guidance_start],
1286
+ mult * [control_guidance_end],
1287
+ )
1288
+
1289
+ # 1. Check inputs. Raise error if not correct
1290
+ self.check_inputs(
1291
+ prompt,
1292
+ image,
1293
+ callback_steps,
1294
+ negative_prompt,
1295
+ prompt_embeds,
1296
+ negative_prompt_embeds,
1297
+ ip_adapter_image,
1298
+ ip_adapter_image_embeds,
1299
+ controlnet_conditioning_scale,
1300
+ control_guidance_start,
1301
+ control_guidance_end,
1302
+ callback_on_step_end_tensor_inputs,
1303
+ )
1304
+
1305
+ self._guidance_scale = guidance_scale
1306
+ self._clip_skip = clip_skip
1307
+ self._cross_attention_kwargs = cross_attention_kwargs
1308
+
1309
+ self._pag_scale = pag_scale
1310
+ self._pag_adaptive_scaling = pag_adaptive_scaling
1311
+ self._pag_applied_layers_index = pag_applied_layers_index
1312
+
1313
+ # 2. Define call parameters
1314
+ if prompt is not None and isinstance(prompt, str):
1315
+ batch_size = 1
1316
+ elif prompt is not None and isinstance(prompt, list):
1317
+ batch_size = len(prompt)
1318
+ else:
1319
+ batch_size = prompt_embeds.shape[0]
1320
+
1321
+ device = self._execution_device
1322
+
1323
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1324
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1325
+
1326
+ global_pool_conditions = (
1327
+ controlnet.config.global_pool_conditions
1328
+ if isinstance(controlnet, ControlNetModel)
1329
+ else controlnet.nets[0].config.global_pool_conditions
1330
+ )
1331
+ guess_mode = guess_mode or global_pool_conditions
1332
+
1333
+ # 3. Encode input prompt
1334
+ text_encoder_lora_scale = (
1335
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1336
+ )
1337
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1338
+ prompt,
1339
+ device,
1340
+ num_images_per_prompt,
1341
+ self.do_classifier_free_guidance,
1342
+ negative_prompt,
1343
+ prompt_embeds=prompt_embeds,
1344
+ negative_prompt_embeds=negative_prompt_embeds,
1345
+ lora_scale=text_encoder_lora_scale,
1346
+ clip_skip=self.clip_skip,
1347
+ )
1348
+ # For classifier free guidance, we need to do two forward passes.
1349
+ # Here we concatenate the unconditional and text embeddings into a single batch
1350
+ # to avoid doing two forward passes
1351
+
1352
+ # cfg
1353
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1354
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1355
+ # pag
1356
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1357
+ prompt_embeds = torch.cat([prompt_embeds, prompt_embeds])
1358
+ # both
1359
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1360
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds])
1361
+
1362
+ if ip_adapter_image is not None and self.do_perturbed_attention_guidance:
1363
+ raise ValueError(
1364
+ "IP-Adapter with perturbed-attention guidance is not supported yet."
1365
+ )
1366
+
1367
+
1368
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1369
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1370
+ ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_images_per_prompt
1371
+ )
1372
+
1373
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1374
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1375
+ ip_adapter_image,
1376
+ ip_adapter_image_embeds,
1377
+ device,
1378
+ batch_size * num_images_per_prompt,
1379
+ self.do_classifier_free_guidance,
1380
+ )
1381
+
1382
+ # 4. Prepare image
1383
+ if isinstance(controlnet, ControlNetModel):
1384
+ image = self.prepare_image(
1385
+ image=image,
1386
+ width=width,
1387
+ height=height,
1388
+ batch_size=batch_size * num_images_per_prompt,
1389
+ num_images_per_prompt=num_images_per_prompt,
1390
+ device=device,
1391
+ dtype=controlnet.dtype,
1392
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1393
+ do_perturbed_attention_guidance=self.do_perturbed_attention_guidance,
1394
+ guess_mode=guess_mode,
1395
+ )
1396
+ height, width = image.shape[-2:]
1397
+ elif isinstance(controlnet, MultiControlNetModel):
1398
+ images = []
1399
+
1400
+ # Nested lists as ControlNet condition
1401
+ if isinstance(image[0], list):
1402
+ # Transpose the nested image list
1403
+ image = [list(t) for t in zip(*image)]
1404
+
1405
+ for image_ in image:
1406
+ image_ = self.prepare_image(
1407
+ image=image_,
1408
+ width=width,
1409
+ height=height,
1410
+ batch_size=batch_size * num_images_per_prompt,
1411
+ num_images_per_prompt=num_images_per_prompt,
1412
+ device=device,
1413
+ dtype=controlnet.dtype,
1414
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1415
+ do_perturbed_attention_guidance=self.do_perturbed_attention_guidance,
1416
+ guess_mode=guess_mode,
1417
+ )
1418
+
1419
+ images.append(image_)
1420
+
1421
+ image = images
1422
+ height, width = image[0].shape[-2:]
1423
+ else:
1424
+ assert False
1425
+
1426
+ # 5. Prepare timesteps
1427
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1428
+ self._num_timesteps = len(timesteps)
1429
+
1430
+ # 6. Prepare latent variables
1431
+ num_channels_latents = self.unet.config.in_channels
1432
+ latents = self.prepare_latents(
1433
+ batch_size * num_images_per_prompt,
1434
+ num_channels_latents,
1435
+ height,
1436
+ width,
1437
+ prompt_embeds.dtype,
1438
+ device,
1439
+ generator,
1440
+ latents,
1441
+ )
1442
+
1443
+ # 6.5 Optionally get Guidance Scale Embedding
1444
+ timestep_cond = None
1445
+ if self.unet.config.time_cond_proj_dim is not None:
1446
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1447
+ timestep_cond = self.get_guidance_scale_embedding(
1448
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1449
+ ).to(device=device, dtype=latents.dtype)
1450
+
1451
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1452
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1453
+
1454
+ # 7.1 Add image embeds for IP-Adapter
1455
+ added_cond_kwargs = (
1456
+ {"image_embeds": image_embeds}
1457
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
1458
+ else None
1459
+ )
1460
+
1461
+ # 7.2 Create tensor stating which controlnets to keep
1462
+ controlnet_keep = []
1463
+ for i in range(len(timesteps)):
1464
+ keeps = [
1465
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1466
+ for s, e in zip(control_guidance_start, control_guidance_end)
1467
+ ]
1468
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1469
+
1470
+ # 8. Denoising loop
1471
+ if self.do_perturbed_attention_guidance:
1472
+ down_layers = []
1473
+ mid_layers = []
1474
+ up_layers = []
1475
+ for name, module in self.unet.named_modules():
1476
+ if "attn1" in name and "to" not in name:
1477
+ layer_type = name.split(".")[0].split("_")[0]
1478
+ if layer_type == "down":
1479
+ down_layers.append(module)
1480
+ elif layer_type == "mid":
1481
+ mid_layers.append(module)
1482
+ elif layer_type == "up":
1483
+ up_layers.append(module)
1484
+ else:
1485
+ raise ValueError(f"Invalid layer type: {layer_type}")
1486
+
1487
+ # change attention layer in UNet if use PAG
1488
+ if self.do_perturbed_attention_guidance:
1489
+ if self.do_classifier_free_guidance:
1490
+ replace_processor = PAGCFGIdentitySelfAttnProcessor()
1491
+ else:
1492
+ replace_processor = PAGIdentitySelfAttnProcessor()
1493
+
1494
+ drop_layers = self.pag_applied_layers_index
1495
+ for drop_layer in drop_layers:
1496
+ try:
1497
+ if drop_layer[0] == "d":
1498
+ down_layers[int(drop_layer[1])].processor = replace_processor
1499
+ elif drop_layer[0] == "m":
1500
+ mid_layers[int(drop_layer[1])].processor = replace_processor
1501
+ elif drop_layer[0] == "u":
1502
+ up_layers[int(drop_layer[1])].processor = replace_processor
1503
+ else:
1504
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1505
+ except IndexError:
1506
+ raise ValueError(
1507
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1508
+ )
1509
+
1510
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1511
+ is_unet_compiled = is_compiled_module(self.unet)
1512
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1513
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1514
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1515
+ for i, t in enumerate(timesteps):
1516
+ # Relevant thread:
1517
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1518
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1519
+ torch._inductor.cudagraph_mark_step_begin()
1520
+ # expand the latents if we are doing guidance
1521
+ # cfg
1522
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1523
+ latent_model_input = torch.cat([latents] * 2)
1524
+ # pag
1525
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1526
+ latent_model_input = torch.cat([latents] * 2)
1527
+ # both
1528
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1529
+ latent_model_input = torch.cat([latents] * 3)
1530
+ # no
1531
+ else:
1532
+ latent_model_input = latents
1533
+
1534
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1535
+
1536
+ # controlnet(s) inference
1537
+ if guess_mode and self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1538
+ control_model_input = latents
1539
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1540
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1541
+ elif guess_mode and not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1542
+ control_model_input = latents
1543
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1544
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1545
+ elif guess_mode and self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1546
+ raise ValueError(
1547
+ "guess mode with both guidance is not supported."
1548
+ )
1549
+ else:
1550
+ control_model_input = latent_model_input
1551
+ controlnet_prompt_embeds = prompt_embeds
1552
+
1553
+ if isinstance(controlnet_keep[i], list):
1554
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1555
+ else:
1556
+ controlnet_cond_scale = controlnet_conditioning_scale
1557
+ if isinstance(controlnet_cond_scale, list):
1558
+ controlnet_cond_scale = controlnet_cond_scale[0]
1559
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1560
+
1561
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1562
+ control_model_input,
1563
+ t,
1564
+ encoder_hidden_states=controlnet_prompt_embeds,
1565
+ controlnet_cond=image,
1566
+ conditioning_scale=cond_scale,
1567
+ guess_mode=guess_mode,
1568
+ return_dict=False,
1569
+ )
1570
+
1571
+ if guess_mode and self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1572
+ # Infered ControlNet only for the conditional batch.
1573
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1574
+ # add 0 to the unconditional batch to keep it unchanged.
1575
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1576
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1577
+ elif guess_mode and not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1578
+ # Infered ControlNet only for the conditional batch.
1579
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1580
+ # add 0 to the unconditional batch to keep it unchanged.
1581
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1582
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1583
+ elif guess_mode and self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1584
+ raise ValueError(
1585
+ "guess mode with both guidance is not supported."
1586
+ )
1587
+
1588
+ # predict the noise residual
1589
+ noise_pred = self.unet(
1590
+ latent_model_input,
1591
+ t,
1592
+ encoder_hidden_states=prompt_embeds,
1593
+ timestep_cond=timestep_cond,
1594
+ cross_attention_kwargs=self.cross_attention_kwargs,
1595
+ down_block_additional_residuals=down_block_res_samples,
1596
+ mid_block_additional_residual=mid_block_res_sample,
1597
+ added_cond_kwargs=added_cond_kwargs,
1598
+ return_dict=False,
1599
+ )[0]
1600
+
1601
+ # perform guidance
1602
+
1603
+ # cfg
1604
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1605
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1606
+
1607
+ delta = noise_pred_text - noise_pred_uncond
1608
+ noise_pred = noise_pred_uncond + self.guidance_scale * delta
1609
+
1610
+ # pag
1611
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1612
+ noise_pred_original, noise_pred_perturb = noise_pred.chunk(2)
1613
+
1614
+ signal_scale = self.pag_scale
1615
+ if self.do_pag_adaptive_scaling:
1616
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000 - t)
1617
+ if signal_scale < 0:
1618
+ signal_scale = 0
1619
+
1620
+ noise_pred = noise_pred_original + signal_scale * (noise_pred_original - noise_pred_perturb)
1621
+
1622
+ # both
1623
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1624
+ noise_pred_uncond, noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(3)
1625
+
1626
+ signal_scale = self.pag_scale
1627
+ if self.do_pag_adaptive_scaling:
1628
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000 - t)
1629
+ if signal_scale < 0:
1630
+ signal_scale = 0
1631
+
1632
+ noise_pred = (
1633
+ noise_pred_text
1634
+ + (self.guidance_scale - 1.0) * (noise_pred_text - noise_pred_uncond)
1635
+ + signal_scale * (noise_pred_text - noise_pred_text_perturb)
1636
+ )
1637
+
1638
+ # compute the previous noisy sample x_t -> x_t-1
1639
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1640
+
1641
+ if callback_on_step_end is not None:
1642
+ callback_kwargs = {}
1643
+ for k in callback_on_step_end_tensor_inputs:
1644
+ callback_kwargs[k] = locals()[k]
1645
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1646
+
1647
+ latents = callback_outputs.pop("latents", latents)
1648
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1649
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1650
+
1651
+ # call the callback, if provided
1652
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1653
+ progress_bar.update()
1654
+ if callback is not None and i % callback_steps == 0:
1655
+ step_idx = i // getattr(self.scheduler, "order", 1)
1656
+ callback(step_idx, t, latents)
1657
+
1658
+ # If we do sequential model offloading, let's offload unet and controlnet
1659
+ # manually for max memory savings
1660
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1661
+ self.unet.to("cpu")
1662
+ self.controlnet.to("cpu")
1663
+ torch.cuda.empty_cache()
1664
+
1665
+ if not output_type == "latent":
1666
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1667
+ 0
1668
+ ]
1669
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1670
+ else:
1671
+ image = latents
1672
+ has_nsfw_concept = None
1673
+
1674
+ if has_nsfw_concept is None:
1675
+ do_denormalize = [True] * image.shape[0]
1676
+ else:
1677
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1678
+
1679
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1680
+
1681
+ # Offload all models
1682
+ self.maybe_free_model_hooks()
1683
+
1684
+ # change attention layer in UNet if use PAG
1685
+ if self.do_perturbed_attention_guidance:
1686
+ drop_layers = self.pag_applied_layers_index
1687
+ for drop_layer in drop_layers:
1688
+ try:
1689
+ if drop_layer[0] == "d":
1690
+ down_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1691
+ elif drop_layer[0] == "m":
1692
+ mid_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1693
+ elif drop_layer[0] == "u":
1694
+ up_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1695
+ else:
1696
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1697
+ except IndexError:
1698
+ raise ValueError(
1699
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1700
+ )
1701
+
1702
+ if not return_dict:
1703
+ return (image, has_nsfw_concept)
1704
+
1705
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)