thisiswooyeol commited on
Commit
cb23370
·
verified ·
1 Parent(s): 4201802

Upload pipeline_stable_diffusion_migc.py

Browse files
Files changed (1) hide show
  1. pipeline_stable_diffusion_migc.py +1201 -0
pipeline_stable_diffusion_migc.py ADDED
@@ -0,0 +1,1201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
8
+ from diffusers.configuration_utils import FrozenDict
9
+ from diffusers.image_processor import VaeImageProcessor
10
+ from diffusers.loaders import (
11
+ FromSingleFileMixin,
12
+ StableDiffusionLoraLoaderMixin,
13
+ TextualInversionLoaderMixin,
14
+ )
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.models.attention_processor import Attention, AttnProcessor
17
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
18
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
19
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
20
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
21
+ from diffusers.schedulers import KarrasDiffusionSchedulers
22
+ from diffusers.utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+ from packaging import version
25
+ from scipy.ndimage import uniform_filter
26
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
27
+
28
+ # from utils import load_utils
29
+ from core.diffusion.migc.mich_arch import MIGC, NaiveFuser
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ def get_sup_mask(mask_list):
35
+ or_mask = np.zeros_like(mask_list[0])
36
+ for mask in mask_list:
37
+ or_mask += mask
38
+ or_mask[or_mask >= 1] = 1
39
+ sup_mask = 1 - or_mask
40
+ return sup_mask
41
+
42
+
43
+ class MIGCProcessor(AttnProcessor):
44
+ def __init__(self, use_migc: bool):
45
+ self.use_migc = use_migc
46
+ self.naive_fuser = NaiveFuser()
47
+
48
+ def __call__(
49
+ self,
50
+ attn: Attention,
51
+ hidden_states: torch.Tensor,
52
+ encoder_hidden_states: torch.Tensor | None = None,
53
+ attention_mask: torch.Tensor | None = None,
54
+ encoder_hidden_states_phrases=None,
55
+ bboxes: List[List[float]] = [],
56
+ ith: int = 0,
57
+ embeds_pooler: torch.Tensor | None = None,
58
+ height: int = 512,
59
+ width: int = 512,
60
+ MIGCsteps: int = 25,
61
+ NaiveFuserSteps: int = -1,
62
+ ca_scale: float | None = None,
63
+ ea_scale: float | None = None,
64
+ sac_scale: float | None = None,
65
+ ):
66
+ batch_size, sequence_length, _ = hidden_states.shape
67
+ assert batch_size == 1 or batch_size == 2, (
68
+ "We currently only implement sampling with batch_size=1, and we will implement sampling with batch_size=N as soon as possible."
69
+ )
70
+
71
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
72
+
73
+ instance_num = len(bboxes)
74
+
75
+ if ith > MIGCsteps:
76
+ use_migc = False
77
+ else:
78
+ use_migc = self.use_migc
79
+ is_vanilla_cross = instance_num == 0 or (not use_migc and ith > NaiveFuserSteps)
80
+
81
+ is_cross = encoder_hidden_states is not None
82
+
83
+ # ori_hidden_states = hidden_states.clone()
84
+
85
+ # In this case, we need to use MIGC or naive_fuser, so
86
+ # 1. We concat prompt embeds and phrases embeds
87
+ # 2. we copy the hidden_states_cond (instance_num+1) times for QKV
88
+ if is_cross and not is_vanilla_cross:
89
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_phrases])
90
+ # print(encoder_hidden_states.shape)
91
+ hidden_states_uncond = hidden_states[[0], ...]
92
+ hidden_states_cond = hidden_states[[1], ...].repeat(instance_num + 1, 1, 1)
93
+ hidden_states = torch.cat([hidden_states_uncond, hidden_states_cond])
94
+
95
+ # QKV Operation of Vanilla Self-Attention or Cross-Attention
96
+ query = attn.to_q(hidden_states)
97
+
98
+ if encoder_hidden_states is None:
99
+ encoder_hidden_states = hidden_states
100
+
101
+ key = attn.to_k(encoder_hidden_states)
102
+ value = attn.to_v(encoder_hidden_states)
103
+
104
+ query = attn.head_to_batch_dim(query)
105
+ key = attn.head_to_batch_dim(key)
106
+ value = attn.head_to_batch_dim(value)
107
+
108
+ hidden_states = F.scaled_dot_product_attention(
109
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
110
+ )
111
+ # attention_probs = attn.get_attention_scores(query, key, attention_mask) # 48 4096 77
112
+ # hidden_states = torch.bmm(attention_probs, value)
113
+ hidden_states = attn.batch_to_head_dim(hidden_states)
114
+
115
+ # linear proj
116
+ hidden_states = attn.to_out[0](hidden_states)
117
+ # dropout
118
+ hidden_states = attn.to_out[1](hidden_states)
119
+
120
+ ###### Self-Attention Results ######
121
+ if not is_cross:
122
+ return hidden_states
123
+
124
+ ###### Vanilla Cross-Attention Results ######
125
+ if is_vanilla_cross:
126
+ return hidden_states
127
+
128
+ ###### Cross-Attention with MIGC ######
129
+ # hidden_states: torch.Size([1+1+instance_num, HW, C]), the first 1 is the uncond ca output, the second 1 is the global ca output.
130
+ hidden_states_uncond = hidden_states[[0], ...] # torch.Size([1, HW, C])
131
+ cond_ca_output = hidden_states[1:, ...].unsqueeze(0) # torch.Size([1, 1+instance_num, 5, 64, 1280])
132
+ guidance_masks = []
133
+ in_box = []
134
+ # Construct Instance Guidance Mask
135
+ for bbox in bboxes:
136
+ guidance_mask = np.zeros((height, width))
137
+ w_min = int(width * bbox[0])
138
+ w_max = int(width * bbox[2])
139
+ h_min = int(height * bbox[1])
140
+ h_max = int(height * bbox[3])
141
+ guidance_mask[h_min:h_max, w_min:w_max] = 1.0
142
+ guidance_masks.append(guidance_mask[None, ...])
143
+ in_box.append([bbox[0], bbox[2], bbox[1], bbox[3]])
144
+
145
+ # Construct Background Guidance Mask
146
+ sup_mask = get_sup_mask(guidance_masks)
147
+ supplement_mask = torch.from_numpy(sup_mask[None, ...])
148
+ supplement_mask = F.interpolate(supplement_mask, (height // 8, width // 8), mode="bilinear").float()
149
+ supplement_mask = supplement_mask.to(hidden_states.device) # (1, 1, H, W)
150
+
151
+ guidance_masks = np.concatenate(guidance_masks, axis=0)
152
+ guidance_masks = guidance_masks[None, ...]
153
+ guidance_masks = torch.from_numpy(guidance_masks).float().to(cond_ca_output.device)
154
+ guidance_masks = F.interpolate(
155
+ guidance_masks, (height // 8, width // 8), mode="bilinear"
156
+ ) # (1, instance_num, H, W)
157
+
158
+ in_box = torch.from_numpy(np.array(in_box))[None, ...].float().to(cond_ca_output.device) # (1, instance_num, 4)
159
+
160
+ other_info = {}
161
+ other_info["image_token"] = hidden_states_cond[None, ...]
162
+ other_info["context"] = encoder_hidden_states[1:, ...]
163
+ other_info["box"] = in_box
164
+ other_info["context_pooler"] = embeds_pooler[:, None, :] # (instance_num, 1, 768)
165
+ other_info["supplement_mask"] = supplement_mask
166
+ other_info["attn2"] = None
167
+ other_info["attn"] = attn
168
+ other_info["height"] = height
169
+ other_info["width"] = width
170
+ other_info["ca_scale"] = ca_scale
171
+ other_info["ea_scale"] = ea_scale
172
+ other_info["sac_scale"] = sac_scale
173
+
174
+ if use_migc:
175
+ assert hasattr(attn, "migc") and isinstance(attn.migc, MIGC)
176
+ hidden_states_cond, _ = attn.migc(
177
+ cond_ca_output, guidance_masks, other_info=other_info, return_fuser_info=True
178
+ )
179
+ else:
180
+ hidden_states_cond, _ = self.naive_fuser(
181
+ cond_ca_output, guidance_masks, other_info=other_info, return_fuser_info=True
182
+ )
183
+ hidden_states_cond = hidden_states_cond.squeeze(1)
184
+
185
+ hidden_states = torch.cat([hidden_states_uncond, hidden_states_cond])
186
+ return hidden_states
187
+
188
+
189
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
190
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
191
+ r"""
192
+ Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
193
+ Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
194
+ Flawed](https://huggingface.co/papers/2305.08891).
195
+
196
+ Args:
197
+ noise_cfg (`torch.Tensor`):
198
+ The predicted noise tensor for the guided diffusion process.
199
+ noise_pred_text (`torch.Tensor`):
200
+ The predicted noise tensor for the text-guided diffusion process.
201
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
202
+ A rescale factor applied to the noise predictions.
203
+
204
+ Returns:
205
+ noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
206
+ """
207
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
208
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
209
+ # rescale the results from guidance (fixes overexposure)
210
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
211
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
212
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
213
+ return noise_cfg
214
+
215
+
216
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
217
+ def retrieve_timesteps(
218
+ scheduler,
219
+ num_inference_steps: Optional[int] = None,
220
+ device: Optional[Union[str, torch.device]] = None,
221
+ timesteps: Optional[List[int]] = None,
222
+ sigmas: Optional[List[float]] = None,
223
+ **kwargs,
224
+ ):
225
+ r"""
226
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
227
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
228
+
229
+ Args:
230
+ scheduler (`SchedulerMixin`):
231
+ The scheduler to get timesteps from.
232
+ num_inference_steps (`int`):
233
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
234
+ must be `None`.
235
+ device (`str` or `torch.device`, *optional*):
236
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
237
+ timesteps (`List[int]`, *optional*):
238
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
239
+ `num_inference_steps` and `sigmas` must be `None`.
240
+ sigmas (`List[float]`, *optional*):
241
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
242
+ `num_inference_steps` and `timesteps` must be `None`.
243
+
244
+ Returns:
245
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
246
+ second element is the number of inference steps.
247
+ """
248
+ if timesteps is not None and sigmas is not None:
249
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
250
+ if timesteps is not None:
251
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
252
+ if not accepts_timesteps:
253
+ raise ValueError(
254
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
255
+ f" timestep schedules. Please check whether you are using the correct scheduler."
256
+ )
257
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
258
+ timesteps = scheduler.timesteps
259
+ num_inference_steps = len(timesteps)
260
+ elif sigmas is not None:
261
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
262
+ if not accept_sigmas:
263
+ raise ValueError(
264
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
265
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
266
+ )
267
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
268
+ timesteps = scheduler.timesteps
269
+ num_inference_steps = len(timesteps)
270
+ else:
271
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
272
+ timesteps = scheduler.timesteps
273
+ return timesteps, num_inference_steps
274
+
275
+
276
+ class StableDiffusionMIGCPipeline(
277
+ DiffusionPipeline,
278
+ StableDiffusionMixin,
279
+ TextualInversionLoaderMixin,
280
+ StableDiffusionLoraLoaderMixin,
281
+ FromSingleFileMixin,
282
+ ):
283
+ """
284
+ Pipeline for layout-to-image generation using Stable Diffusion + MIGC (https://arxiv.org/abs/2402.05408).
285
+
286
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
287
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
288
+
289
+ The pipeline also inherits the following loading methods:
290
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
291
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
292
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
293
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
294
+
295
+ Args:
296
+ vae ([`AutoencoderKL`]):
297
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
298
+ text_encoder ([`~transformers.CLIPTextModel`]):
299
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
300
+ tokenizer ([`~transformers.CLIPTokenizer`]):
301
+ A `CLIPTokenizer` to tokenize text.
302
+ unet ([`UNet2DConditionModel`]):
303
+ A `UNet2DConditionModel` to denoise the encoded image latents.
304
+ scheduler ([`SchedulerMixin`]):
305
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
306
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
307
+ safety_checker ([`StableDiffusionSafetyChecker`]):
308
+ Classification module that estimates whether generated images could be considered offensive or harmful.
309
+ Please refer to the [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) for
310
+ more details about a model's potential harms.
311
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
312
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
313
+ """
314
+
315
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
316
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
317
+ _exclude_from_cpu_offload = ["safety_checker"]
318
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
319
+
320
+ def __init__(
321
+ self,
322
+ vae: AutoencoderKL,
323
+ text_encoder: CLIPTextModel,
324
+ tokenizer: CLIPTokenizer,
325
+ unet: UNet2DConditionModel,
326
+ scheduler: KarrasDiffusionSchedulers,
327
+ safety_checker: StableDiffusionSafetyChecker,
328
+ feature_extractor: CLIPImageProcessor,
329
+ image_encoder: CLIPVisionModelWithProjection = None,
330
+ requires_safety_checker: bool = True,
331
+ ):
332
+ super().__init__()
333
+
334
+ if scheduler is not None and getattr(scheduler.config, "steps_offset", 1) != 1:
335
+ deprecation_message = (
336
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
337
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
338
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
339
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
340
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
341
+ " file"
342
+ )
343
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
344
+ new_config = dict(scheduler.config)
345
+ new_config["steps_offset"] = 1
346
+ scheduler._internal_dict = FrozenDict(new_config)
347
+
348
+ if scheduler is not None and getattr(scheduler.config, "clip_sample", False) is True:
349
+ deprecation_message = (
350
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
351
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
352
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
353
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
354
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
355
+ )
356
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
357
+ new_config = dict(scheduler.config)
358
+ new_config["clip_sample"] = False
359
+ scheduler._internal_dict = FrozenDict(new_config)
360
+
361
+ if safety_checker is None and requires_safety_checker:
362
+ logger.warning(
363
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
364
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
365
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
366
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
367
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
368
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
369
+ )
370
+
371
+ if safety_checker is not None and feature_extractor is None:
372
+ raise ValueError(
373
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
374
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
375
+ )
376
+
377
+ is_unet_version_less_0_9_0 = (
378
+ unet is not None
379
+ and hasattr(unet.config, "_diffusers_version")
380
+ and version.parse(version.parse(unet.config._diffusers_version).base_version) < version.parse("0.9.0.dev0")
381
+ )
382
+ self._is_unet_config_sample_size_int = unet is not None and isinstance(unet.config.sample_size, int)
383
+ is_unet_sample_size_less_64 = (
384
+ unet is not None
385
+ and hasattr(unet.config, "sample_size")
386
+ and self._is_unet_config_sample_size_int
387
+ and unet.config.sample_size < 64
388
+ )
389
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
390
+ deprecation_message = (
391
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
392
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
393
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
394
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- stable-diffusion-v1-5/stable-diffusion-v1-5"
395
+ " \n- stable-diffusion-v1-5/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
396
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
397
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
398
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
399
+ " the `unet/config.json` file"
400
+ )
401
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
402
+ new_config = dict(unet.config)
403
+ new_config["sample_size"] = 64
404
+ unet._internal_dict = FrozenDict(new_config)
405
+
406
+ self._register_migc_adapters(unet)
407
+
408
+ self.register_modules(
409
+ vae=vae,
410
+ text_encoder=text_encoder,
411
+ tokenizer=tokenizer,
412
+ unet=unet,
413
+ scheduler=scheduler,
414
+ safety_checker=safety_checker,
415
+ feature_extractor=feature_extractor,
416
+ image_encoder=image_encoder,
417
+ )
418
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
419
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
420
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
421
+
422
+ # self.embedding = {}
423
+
424
+ def _register_migc_adapters(self, unet: UNet2DConditionModel):
425
+ for name, module in unet.named_modules():
426
+ if isinstance(module, Attention):
427
+ # print(f"Hook {name} {module.__class__.__name__}")
428
+ if "attn1" in name:
429
+ module.set_processor(MIGCProcessor(use_migc=False))
430
+ elif "attn2" in name and "down" in name:
431
+ module.set_processor(MIGCProcessor(use_migc=False))
432
+ elif "attn2" in name and ("up_blocks.2" in name or "up_blocks.3" in name):
433
+ module.set_processor(MIGCProcessor(use_migc=False))
434
+ elif "attn2" in name and "up_blocks.1" in name:
435
+ module.migc = MIGC(C=1280)
436
+ module.register_module("migc", module.migc)
437
+ module.set_processor(MIGCProcessor(use_migc=True))
438
+ elif "attn2" in name and "mid" in name:
439
+ module.migc = MIGC(C=1280)
440
+ module.register_module("migc", module.migc)
441
+ module.set_processor(MIGCProcessor(use_migc=True))
442
+ else:
443
+ logger.warning(f"Unknown attention module: {name}")
444
+
445
+ def encode_prompt(
446
+ self,
447
+ prompt,
448
+ device,
449
+ num_images_per_prompt,
450
+ do_classifier_free_guidance,
451
+ negative_prompt=None,
452
+ prompt_embeds: Optional[torch.Tensor] = None,
453
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
454
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
455
+ lora_scale: Optional[float] = None,
456
+ ):
457
+ r"""
458
+ Encodes the prompt into text encoder hidden states.
459
+
460
+ Args:
461
+ prompt (`str` or `List[str]`, *optional*):
462
+ prompt to be encoded
463
+ device: (`torch.device`):
464
+ torch device
465
+ num_images_per_prompt (`int`):
466
+ number of images that should be generated per prompt
467
+ do_classifier_free_guidance (`bool`):
468
+ whether to use classifier free guidance or not
469
+ negative_prompt (`str` or `List[str]`, *optional*):
470
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
471
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
472
+ less than `1`).
473
+ prompt_embeds (`torch.Tensor`, *optional*):
474
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
475
+ provided, text embeddings will be generated from `prompt` input argument.
476
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
477
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
478
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
479
+ argument.
480
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
481
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
482
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
483
+ lora_scale (`float`, *optional*):
484
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
485
+ """
486
+ # set lora scale so that monkey patched LoRA
487
+ # function of text encoder can correctly access it
488
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
489
+ self._lora_scale = lora_scale
490
+
491
+ # dynamically adjust the LoRA scale
492
+ if not USE_PEFT_BACKEND:
493
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
494
+ else:
495
+ scale_lora_layers(self.text_encoder, lora_scale)
496
+
497
+ if prompt is not None and isinstance(prompt, str):
498
+ batch_size = 1
499
+ elif prompt is not None and isinstance(prompt, list):
500
+ batch_size = len(prompt)
501
+ else:
502
+ batch_size = prompt_embeds.shape[0]
503
+
504
+ if prompt_embeds is None:
505
+ # textual inversion: process multi-vector tokens if necessary
506
+ if isinstance(self, TextualInversionLoaderMixin):
507
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
508
+
509
+ text_inputs = self.tokenizer(
510
+ prompt,
511
+ padding="max_length",
512
+ max_length=self.tokenizer.model_max_length,
513
+ truncation=True,
514
+ return_tensors="pt",
515
+ )
516
+ text_input_ids = text_inputs.input_ids
517
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
518
+
519
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
520
+ text_input_ids, untruncated_ids
521
+ ):
522
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
523
+ logger.warning(
524
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
525
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
526
+ )
527
+
528
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
529
+ attention_mask = text_inputs.attention_mask.to(device)
530
+ else:
531
+ attention_mask = None
532
+
533
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
534
+ pooled_prompt_embeds = prompt_embeds.pooler_output
535
+ prompt_embeds = prompt_embeds[0]
536
+
537
+ if self.text_encoder is not None:
538
+ prompt_embeds_dtype = self.text_encoder.dtype
539
+ elif self.unet is not None:
540
+ prompt_embeds_dtype = self.unet.dtype
541
+ else:
542
+ prompt_embeds_dtype = prompt_embeds.dtype
543
+
544
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
545
+ pooled_prompt_embeds = pooled_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
546
+
547
+ # get unconditional embeddings for classifier free guidance
548
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
549
+ uncond_tokens: List[str]
550
+ if negative_prompt is None:
551
+ uncond_tokens = [""] * batch_size
552
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
553
+ raise TypeError(
554
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
555
+ f" {type(prompt)}."
556
+ )
557
+ elif isinstance(negative_prompt, str):
558
+ uncond_tokens = [negative_prompt]
559
+ elif batch_size != len(negative_prompt):
560
+ raise ValueError(
561
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
562
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
563
+ " the batch size of `prompt`."
564
+ )
565
+ else:
566
+ uncond_tokens = negative_prompt
567
+
568
+ # textual inversion: process multi-vector tokens if necessary
569
+ if isinstance(self, TextualInversionLoaderMixin):
570
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
571
+
572
+ max_length = prompt_embeds.shape[1]
573
+ uncond_input = self.tokenizer(
574
+ uncond_tokens,
575
+ padding="max_length",
576
+ max_length=max_length,
577
+ truncation=True,
578
+ return_tensors="pt",
579
+ )
580
+
581
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
582
+ attention_mask = uncond_input.attention_mask.to(device)
583
+ else:
584
+ attention_mask = None
585
+
586
+ negative_prompt_embeds = self.text_encoder(
587
+ uncond_input.input_ids.to(device),
588
+ attention_mask=attention_mask,
589
+ )
590
+ negative_prompt_embeds = negative_prompt_embeds[0]
591
+
592
+ bs_embed, seq_len, _ = prompt_embeds.shape
593
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
594
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
595
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
596
+
597
+ if do_classifier_free_guidance:
598
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
599
+ seq_len = negative_prompt_embeds.shape[1]
600
+
601
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
602
+
603
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
604
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
605
+
606
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
607
+ bs_embed * num_images_per_prompt, -1
608
+ )
609
+
610
+ if self.text_encoder is not None:
611
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
612
+ # Retrieve the original scale by scaling back the LoRA layers
613
+ unscale_lora_layers(self.text_encoder, lora_scale)
614
+
615
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds
616
+
617
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
618
+ dtype = next(self.image_encoder.parameters()).dtype
619
+
620
+ if not isinstance(image, torch.Tensor):
621
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
622
+
623
+ image = image.to(device=device, dtype=dtype)
624
+ if output_hidden_states:
625
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
626
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
627
+ uncond_image_enc_hidden_states = self.image_encoder(
628
+ torch.zeros_like(image), output_hidden_states=True
629
+ ).hidden_states[-2]
630
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
631
+ num_images_per_prompt, dim=0
632
+ )
633
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
634
+ else:
635
+ image_embeds = self.image_encoder(image).image_embeds
636
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
637
+ uncond_image_embeds = torch.zeros_like(image_embeds)
638
+
639
+ return image_embeds, uncond_image_embeds
640
+
641
+ def run_safety_checker(self, image, device, dtype):
642
+ if self.safety_checker is None:
643
+ has_nsfw_concept = None
644
+ else:
645
+ if torch.is_tensor(image):
646
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
647
+ else:
648
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
649
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
650
+ image, has_nsfw_concept = self.safety_checker(
651
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
652
+ )
653
+ return image, has_nsfw_concept
654
+
655
+ def prepare_extra_step_kwargs(self, generator, eta):
656
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
657
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
658
+ # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
659
+ # and should be between [0, 1]
660
+
661
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
662
+ extra_step_kwargs = {}
663
+ if accepts_eta:
664
+ extra_step_kwargs["eta"] = eta
665
+
666
+ # check if the scheduler accepts generator
667
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
668
+ if accepts_generator:
669
+ extra_step_kwargs["generator"] = generator
670
+ return extra_step_kwargs
671
+
672
+ def check_inputs(
673
+ self,
674
+ prompt,
675
+ height,
676
+ width,
677
+ bboxes,
678
+ callback_steps,
679
+ negative_prompt=None,
680
+ prompt_embeds=None,
681
+ negative_prompt_embeds=None,
682
+ callback_on_step_end_tensor_inputs=None,
683
+ ):
684
+ if height % 8 != 0 or width % 8 != 0:
685
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
686
+
687
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
688
+ raise ValueError(
689
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type {type(callback_steps)}."
690
+ )
691
+ if callback_on_step_end_tensor_inputs is not None and not all(
692
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
693
+ ):
694
+ raise ValueError(
695
+ 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]}"
696
+ )
697
+
698
+ if prompt is not None and prompt_embeds is not None:
699
+ raise ValueError(
700
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
701
+ " only forward one of the two."
702
+ )
703
+ elif prompt is None and prompt_embeds is None:
704
+ raise ValueError(
705
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
706
+ )
707
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
708
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
709
+
710
+ if negative_prompt is not None and negative_prompt_embeds is not None:
711
+ raise ValueError(
712
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
713
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
714
+ )
715
+
716
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
717
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
718
+ raise ValueError(
719
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
720
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
721
+ f" {negative_prompt_embeds.shape}."
722
+ )
723
+
724
+ bboxes_batch_size = -1
725
+ if bboxes is not None:
726
+ if isinstance(bboxes, list):
727
+ if isinstance(bboxes[0], list):
728
+ if (
729
+ isinstance(bboxes[0][0], list)
730
+ and len(bboxes[0][0]) == 4
731
+ and all(isinstance(x, float) for x in bboxes[0][0])
732
+ ):
733
+ bboxes_batch_size = len(bboxes)
734
+ elif (
735
+ isinstance(bboxes[0], list)
736
+ and len(bboxes[0]) == 4
737
+ and all(isinstance(x, float) for x in bboxes[0])
738
+ ):
739
+ bboxes_batch_size = 1
740
+ else:
741
+ print(isinstance(bboxes[0], list), len(bboxes[0]))
742
+ raise TypeError(
743
+ "`bboxes` must be a list of lists of list with four floats or a list of tuples with four floats."
744
+ )
745
+ else:
746
+ print(isinstance(bboxes[0], list), len(bboxes[0]))
747
+ raise TypeError(
748
+ "`bboxes` must be a list of lists of list with four floats or a list of tuples with four floats."
749
+ )
750
+ else:
751
+ print(isinstance(bboxes[0], list), len(bboxes[0]))
752
+ raise TypeError(
753
+ "`bboxes` must be a list of lists of list with four floats or a list of tuples with four floats."
754
+ )
755
+
756
+ if prompt is not None and isinstance(prompt, str):
757
+ prompt_batch_size = 1
758
+ elif prompt is not None and isinstance(prompt, list):
759
+ prompt_batch_size = len(prompt)
760
+ elif prompt_embeds is not None:
761
+ prompt_batch_size = prompt_embeds.shape[0]
762
+ else:
763
+ raise ValueError("Cannot determine batch size from `prompt` or `prompt_embeds`.")
764
+
765
+ if bboxes_batch_size != prompt_batch_size:
766
+ raise ValueError(
767
+ f"bbox batch size must be same as prompt batch size. bbox batch size: {bboxes_batch_size}, prompt batch size: {prompt_batch_size}"
768
+ )
769
+
770
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
771
+ shape = (
772
+ batch_size,
773
+ num_channels_latents,
774
+ int(height) // self.vae_scale_factor,
775
+ int(width) // self.vae_scale_factor,
776
+ )
777
+ if isinstance(generator, list) and len(generator) != batch_size:
778
+ raise ValueError(
779
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
780
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
781
+ )
782
+
783
+ if latents is None:
784
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
785
+ else:
786
+ latents = latents.to(device)
787
+
788
+ # scale the initial noise by the standard deviation required by the scheduler
789
+ latents = latents * self.scheduler.init_noise_sigma
790
+ return latents
791
+
792
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
793
+ def get_guidance_scale_embedding(
794
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
795
+ ) -> torch.Tensor:
796
+ """
797
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
798
+
799
+ Args:
800
+ w (`torch.Tensor`):
801
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
802
+ embedding_dim (`int`, *optional*, defaults to 512):
803
+ Dimension of the embeddings to generate.
804
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
805
+ Data type of the generated embeddings.
806
+
807
+ Returns:
808
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
809
+ """
810
+ assert len(w.shape) == 1
811
+ w = w * 1000.0
812
+
813
+ half_dim = embedding_dim // 2
814
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
815
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
816
+ emb = w.to(dtype)[:, None] * emb[None, :]
817
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
818
+ if embedding_dim % 2 == 1: # zero pad
819
+ emb = torch.nn.functional.pad(emb, (0, 1))
820
+ assert emb.shape == (w.shape[0], embedding_dim)
821
+ return emb
822
+
823
+ @property
824
+ def guidance_scale(self):
825
+ return self._guidance_scale
826
+
827
+ @property
828
+ def guidance_rescale(self):
829
+ return self._guidance_rescale
830
+
831
+ @property
832
+ def clip_skip(self):
833
+ return self._clip_skip
834
+
835
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
836
+ # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
837
+ # corresponds to doing no classifier free guidance.
838
+ @property
839
+ def do_classifier_free_guidance(self):
840
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
841
+
842
+ @property
843
+ def cross_attention_kwargs(self):
844
+ return self._cross_attention_kwargs
845
+
846
+ @property
847
+ def num_timesteps(self):
848
+ return self._num_timesteps
849
+
850
+ @property
851
+ def interrupt(self):
852
+ return self._interrupt
853
+
854
+ @torch.no_grad()
855
+ def __call__(
856
+ self,
857
+ prompt: str,
858
+ phrases: List[str],
859
+ bboxes: List[List[float]],
860
+ height: Optional[int] = None,
861
+ width: Optional[int] = None,
862
+ num_inference_steps: int = 50,
863
+ timesteps: Optional[List[int]] = None,
864
+ sigmas: Optional[List[float]] = None,
865
+ guidance_scale: float = 7.5,
866
+ negative_prompt: Optional[Union[str, List[str]]] = None,
867
+ num_images_per_prompt: Optional[int] = 1,
868
+ eta: float = 0.0,
869
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
870
+ latents: Optional[torch.Tensor] = None,
871
+ prompt_embeds: Optional[torch.Tensor] = None,
872
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
873
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
874
+ output_type: Optional[str] = "pil",
875
+ return_dict: bool = True,
876
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
877
+ guidance_rescale: float = 0.0,
878
+ callback_on_step_end: Optional[
879
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
880
+ ] = None,
881
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
882
+ MIGCsteps=20,
883
+ NaiveFuserSteps=-1,
884
+ ca_scale=None,
885
+ ea_scale=None,
886
+ sac_scale=None,
887
+ aug_phase_with_and=False,
888
+ sa_preserve=False,
889
+ use_sa_preserve=False,
890
+ **kwargs,
891
+ ):
892
+ r"""
893
+ The call function to the pipeline for generation.
894
+
895
+ Args:
896
+ prompt (`str` or `List[str]`, *optional*):
897
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
898
+ instead.
899
+ token_indices (Union[List[List[List[int]]], List[List[int]]], optional):
900
+ The list of the indexes in the prompt to layout. Defaults to None.
901
+ bboxes (Union[List[List[List[float]]], List[List[float]]], optional):
902
+ The bounding boxes of the indexes to maintain layout in the image. Defaults to None.
903
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
904
+ The height in pixels of the generated image.
905
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
906
+ The width in pixels of the generated image.
907
+ num_inference_steps (`int`, *optional*, defaults to 50):
908
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
909
+ expense of slower inference.
910
+ timesteps (`List[int]`, *optional*):
911
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
912
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
913
+ passed will be used. Must be in descending order.
914
+ sigmas (`List[float]`, *optional*):
915
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
916
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
917
+ will be used.
918
+ guidance_scale (`float`, *optional*, defaults to 7.5):
919
+ A higher guidance scale value encourages the model to generate images closely linked to the text
920
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
921
+ negative_prompt (`str` or `List[str]`, *optional*):
922
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
923
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
924
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
925
+ The number of images to generate per prompt.
926
+ eta (`float`, *optional*, defaults to 0.0):
927
+ Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
928
+ applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
929
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
930
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
931
+ generation deterministic.
932
+ latents (`torch.Tensor`, *optional*):
933
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
934
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
935
+ tensor is generated by sampling using the supplied random `generator`.
936
+ prompt_embeds (`torch.Tensor`, *optional*):
937
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
938
+ provided, text embeddings are generated from the `prompt` input argument.
939
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
940
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
941
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
942
+ output_type (`str`, *optional*, defaults to `"pil"`):
943
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
944
+ return_dict (`bool`, *optional*, defaults to `True`):
945
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
946
+ plain tuple.
947
+ callback (`Callable`, *optional*):
948
+ A function that will be called every `callback_steps` steps during inference. The function will be
949
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
950
+ callback_steps (`int`, *optional*, defaults to 1):
951
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
952
+ called at every step.
953
+ cross_attention_kwargs (`dict`, *optional*):
954
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
955
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
956
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
957
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
958
+ Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when
959
+ using zero terminal SNR.
960
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
961
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
962
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
963
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
964
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
965
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
966
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
967
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
968
+ `._callback_tensor_inputs` attribute of your pipeline class.
969
+
970
+ Examples:
971
+
972
+ Returns:
973
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
974
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
975
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
976
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
977
+ "not-safe-for-work" (nsfw) content.
978
+ """
979
+
980
+ callback = kwargs.pop("callback", None)
981
+ callback_steps = kwargs.pop("callback_steps", None)
982
+
983
+ if callback is not None:
984
+ deprecate(
985
+ "callback",
986
+ "1.0.0",
987
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
988
+ )
989
+ if callback_steps is not None:
990
+ deprecate(
991
+ "callback_steps",
992
+ "1.0.0",
993
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
994
+ )
995
+
996
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
997
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
998
+
999
+ # 0. Default height and width to unet
1000
+ if not height or not width:
1001
+ height = (
1002
+ self.unet.config.sample_size
1003
+ if self._is_unet_config_sample_size_int
1004
+ else self.unet.config.sample_size[0]
1005
+ )
1006
+ width = (
1007
+ self.unet.config.sample_size
1008
+ if self._is_unet_config_sample_size_int
1009
+ else self.unet.config.sample_size[1]
1010
+ )
1011
+ height, width = height * self.vae_scale_factor, width * self.vae_scale_factor
1012
+ # to deal with lora scaling and other possible forward hooks
1013
+
1014
+ # 1. Check inputs. Raise error if not correct
1015
+ self.check_inputs(
1016
+ prompt,
1017
+ height,
1018
+ width,
1019
+ bboxes,
1020
+ callback_steps,
1021
+ negative_prompt,
1022
+ prompt_embeds,
1023
+ negative_prompt_embeds,
1024
+ callback_on_step_end_tensor_inputs,
1025
+ )
1026
+
1027
+ self._guidance_scale = guidance_scale
1028
+ self._guidance_rescale = guidance_rescale
1029
+ self._cross_attention_kwargs = cross_attention_kwargs
1030
+ self._interrupt = False
1031
+
1032
+ # 2. Define call parameters
1033
+ if prompt is not None and isinstance(prompt, str):
1034
+ batch_size = 1
1035
+ elif prompt is not None and isinstance(prompt, list):
1036
+ batch_size = len(prompt)
1037
+ else:
1038
+ batch_size = prompt_embeds.shape[0]
1039
+ if batch_size > 1:
1040
+ raise NotImplementedError("Batch processing is not supported.")
1041
+
1042
+ device = self._execution_device
1043
+
1044
+ # 3. Encode input prompt
1045
+ lora_scale = self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1046
+
1047
+ prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds = self.encode_prompt(
1048
+ prompt,
1049
+ device,
1050
+ num_images_per_prompt,
1051
+ self.do_classifier_free_guidance,
1052
+ negative_prompt,
1053
+ prompt_embeds=prompt_embeds,
1054
+ negative_prompt_embeds=negative_prompt_embeds,
1055
+ lora_scale=lora_scale,
1056
+ )
1057
+
1058
+ phrases_embeds, _, pooled_phrases_embeds = self.encode_prompt(
1059
+ phrases,
1060
+ device,
1061
+ num_images_per_prompt,
1062
+ do_classifier_free_guidance=False,
1063
+ lora_scale=lora_scale,
1064
+ )
1065
+
1066
+ # For classifier free guidance, we need to do two forward passes.
1067
+ # Here we concatenate the unconditional and text embeddings into a single batch
1068
+ # to avoid doing two forward passes
1069
+ if self.do_classifier_free_guidance:
1070
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1071
+
1072
+ # 4. Prepare timesteps
1073
+ timesteps, num_inference_steps = retrieve_timesteps(
1074
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1075
+ )
1076
+
1077
+ # 5. Prepare latent variables
1078
+ num_channels_latents = self.unet.config.in_channels
1079
+ latents = self.prepare_latents(
1080
+ batch_size * num_images_per_prompt,
1081
+ num_channels_latents,
1082
+ height,
1083
+ width,
1084
+ prompt_embeds.dtype,
1085
+ device,
1086
+ generator,
1087
+ latents,
1088
+ )
1089
+
1090
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1091
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1092
+
1093
+ # 6.1 Optionally get Guidance Scale Embedding
1094
+ timestep_cond = None
1095
+ if self.unet.config.time_cond_proj_dim is not None:
1096
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1097
+ timestep_cond = self.get_guidance_scale_embedding(
1098
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1099
+ ).to(device=device, dtype=latents.dtype)
1100
+
1101
+ # 6.2 prepare MIGC guidance_mask
1102
+ guidance_mask = np.full((4, height // 8, width // 8), 1.0)
1103
+
1104
+ for bbox in bboxes:
1105
+ w_min = max(0, int(width * bbox[0] // 8) - 5)
1106
+ w_max = min(width, int(width * bbox[2] // 8) + 5)
1107
+ h_min = max(0, int(height * bbox[1] // 8) - 5)
1108
+ h_max = min(height, int(height * bbox[3] // 8) + 5)
1109
+ guidance_mask[:, h_min:h_max, w_min:w_max] = 0
1110
+
1111
+ kernal_size = 5
1112
+ guidance_mask = uniform_filter(guidance_mask, axes=(1, 2), size=kernal_size)
1113
+ guidance_mask = torch.from_numpy(guidance_mask).to(self.device).unsqueeze(0)
1114
+
1115
+ # 7. Denoising loop
1116
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1117
+ self._num_timesteps = len(timesteps)
1118
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1119
+ for i, t in enumerate(timesteps):
1120
+ if self.interrupt:
1121
+ continue
1122
+
1123
+ # expand the latents if we are doing classifier free guidance
1124
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1125
+ if hasattr(self.scheduler, "scale_model_input"):
1126
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1127
+
1128
+ # predict the noise residual
1129
+ cross_attention_kwargs = {
1130
+ "bboxes": bboxes,
1131
+ "ith": i,
1132
+ "embeds_pooler": torch.cat([pooled_prompt_embeds, pooled_phrases_embeds]),
1133
+ "encoder_hidden_states_phrases": phrases_embeds,
1134
+ # "timestep": t,
1135
+ "height": height,
1136
+ "width": width,
1137
+ "MIGCsteps": MIGCsteps,
1138
+ "NaiveFuserSteps": NaiveFuserSteps,
1139
+ "ca_scale": ca_scale,
1140
+ "ea_scale": ea_scale,
1141
+ "sac_scale": sac_scale,
1142
+ }
1143
+
1144
+ noise_pred = self.unet(
1145
+ latent_model_input,
1146
+ t,
1147
+ encoder_hidden_states=prompt_embeds,
1148
+ timestep_cond=timestep_cond,
1149
+ cross_attention_kwargs=cross_attention_kwargs,
1150
+ return_dict=False,
1151
+ )[0]
1152
+
1153
+ # perform guidance
1154
+ if self.do_classifier_free_guidance:
1155
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1156
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1157
+
1158
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1159
+ # Based on 3.4. in https://huggingface.co/papers/2305.08891
1160
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1161
+
1162
+ # compute the previous noisy sample x_t -> x_t-1
1163
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1164
+
1165
+ if callback_on_step_end is not None:
1166
+ callback_kwargs = {}
1167
+ for k in callback_on_step_end_tensor_inputs:
1168
+ callback_kwargs[k] = locals()[k]
1169
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1170
+
1171
+ latents = callback_outputs.pop("latents", latents)
1172
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1173
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1174
+
1175
+ # call the callback, if provided
1176
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1177
+ progress_bar.update()
1178
+ if callback is not None and i % callback_steps == 0:
1179
+ step_idx = i // getattr(self.scheduler, "order", 1)
1180
+ callback(step_idx, t, latents)
1181
+
1182
+ if not output_type == "latent":
1183
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[0]
1184
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1185
+ else:
1186
+ image = latents
1187
+ has_nsfw_concept = None
1188
+
1189
+ if has_nsfw_concept is None:
1190
+ do_denormalize = [True] * image.shape[0]
1191
+ else:
1192
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1193
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1194
+
1195
+ # Offload all models
1196
+ self.maybe_free_model_hooks()
1197
+
1198
+ if not return_dict:
1199
+ return (image, has_nsfw_concept)
1200
+
1201
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)