diffusers/community-pipelines-mirror
Community Pipeline Examples For more information about community pipelines, please have a look at this issue. Community pipeline examples consist pipelines that have been added by the community. Please have a look at the following tables to get an overview of all community examples. Click on the Code Example to get a copy-and-paste ready code example that you can try out. If a community pipeline doesn't work as expected, please open an issue and ping the author on it. Please… See the full description on the dataset page: https://huggingface.co/datasets/diffusers/community-pipelines-mirror.
922k
1import math2import numbers3from typing import Any, Callable, Dict, List, Optional, Union4 5import torch6import torch.nn.functional as F7from torch import nn8 9from diffusers.image_processor import PipelineImageInput10from diffusers.models import AsymmetricAutoencoderKL, ImageProjection11from diffusers.models.attention_processor import Attention, AttnProcessor12from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput13from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint import (14 StableDiffusionInpaintPipeline,15 retrieve_timesteps,16)17from diffusers.utils import deprecate18 19 20class RASGAttnProcessor:21 def __init__(self, mask, token_idx, scale_factor):22 self.attention_scores = None # Stores the last output of the similarity matrix here. Each layer will get its own RASGAttnProcessor assigned23 self.mask = mask24 self.token_idx = token_idx25 self.scale_factor = scale_factor26 self.mask_resoltuion = mask.shape[-1] * mask.shape[-2] # 64 x 64 if the image is 512x51227 28 def __call__(29 self,30 attn: Attention,31 hidden_states: torch.Tensor,32 encoder_hidden_states: Optional[torch.Tensor] = None,33 attention_mask: Optional[torch.Tensor] = None,34 temb: Optional[torch.Tensor] = None,35 scale: float = 1.0,36 ) -> torch.Tensor:37 # Same as the default AttnProcessor up untill the part where similarity matrix gets saved38 downscale_factor = self.mask_resoltuion // hidden_states.shape[1]39 residual = hidden_states40 41 if attn.spatial_norm is not None:42 hidden_states = attn.spatial_norm(hidden_states, temb)43 44 input_ndim = hidden_states.ndim45 46 if input_ndim == 4:47 batch_size, channel, height, width = hidden_states.shape48 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)49 50 batch_size, sequence_length, _ = (51 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape52 )53 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)54 55 if attn.group_norm is not None:56 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)57 58 query = attn.to_q(hidden_states)59 60 if encoder_hidden_states is None:61 encoder_hidden_states = hidden_states62 elif attn.norm_cross:63 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)64 65 key = attn.to_k(encoder_hidden_states)66 value = attn.to_v(encoder_hidden_states)67 68 query = attn.head_to_batch_dim(query)69 key = attn.head_to_batch_dim(key)70 value = attn.head_to_batch_dim(value)71 72 # Automatically recognize the resolution and save the attention similarity values73 # We need to use the values before the softmax function, hence the rewritten get_attention_scores function.74 if downscale_factor == self.scale_factor**2:75 self.attention_scores = get_attention_scores(attn, query, key, attention_mask)76 attention_probs = self.attention_scores.softmax(dim=-1)77 attention_probs = attention_probs.to(query.dtype)78 else:79 attention_probs = attn.get_attention_scores(query, key, attention_mask) # Original code80 81 hidden_states = torch.bmm(attention_probs, value)82 hidden_states = attn.batch_to_head_dim(hidden_states)83 84 # linear proj85 hidden_states = attn.to_out[0](hidden_states)86 # dropout87 hidden_states = attn.to_out[1](hidden_states)88 89 if input_ndim == 4:90 hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)91 92 if attn.residual_connection:93 hidden_states = hidden_states + residual94 95 hidden_states = hidden_states / attn.rescale_output_factor96 97 return hidden_states98 99 100class PAIntAAttnProcessor:101 def __init__(self, transformer_block, mask, token_idx, do_classifier_free_guidance, scale_factors):102 self.transformer_block = transformer_block # Stores the parent transformer block.103 self.mask = mask104 self.scale_factors = scale_factors105 self.do_classifier_free_guidance = do_classifier_free_guidance106 self.token_idx = token_idx107 self.shape = mask.shape[2:]108 self.mask_resoltuion = mask.shape[-1] * mask.shape[-2] # 64 x 64109 self.default_processor = AttnProcessor()110 111 def __call__(112 self,113 attn: Attention,114 hidden_states: torch.Tensor,115 encoder_hidden_states: Optional[torch.Tensor] = None,116 attention_mask: Optional[torch.Tensor] = None,117 temb: Optional[torch.Tensor] = None,118 scale: float = 1.0,119 ) -> torch.Tensor:120 # Automatically recognize the resolution of the current attention layer and resize the masks accordingly121 downscale_factor = self.mask_resoltuion // hidden_states.shape[1]122 123 mask = None124 for factor in self.scale_factors:125 if downscale_factor == factor**2:126 shape = (self.shape[0] // factor, self.shape[1] // factor)127 mask = F.interpolate(self.mask, shape, mode="bicubic") # B, 1, H, W128 break129 if mask is None:130 return self.default_processor(attn, hidden_states, encoder_hidden_states, attention_mask, temb, scale)131 132 # STARTS HERE133 residual = hidden_states134 # Save the input hidden_states for later use135 input_hidden_states = hidden_states136 137 # ================================================== #138 # =============== SELF ATTENTION 1 ================= #139 # ================================================== #140 141 if attn.spatial_norm is not None:142 hidden_states = attn.spatial_norm(hidden_states, temb)143 144 input_ndim = hidden_states.ndim145 146 if input_ndim == 4:147 batch_size, channel, height, width = hidden_states.shape148 hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)149 150 batch_size, sequence_length, _ = (151 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape152 )153 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)154 155 if attn.group_norm is not None:156 hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)157 158 query = attn.to_q(hidden_states)159 160 if encoder_hidden_states is None:161 encoder_hidden_states = hidden_states162 elif attn.norm_cross:163 encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)164 165 key = attn.to_k(encoder_hidden_states)166 value = attn.to_v(encoder_hidden_states)167 168 query = attn.head_to_batch_dim(query)169 key = attn.head_to_batch_dim(key)170 value = attn.head_to_batch_dim(value)171 172 # self_attention_probs = attn.get_attention_scores(query, key, attention_mask) # We can't use post-softmax attention scores in this case173 self_attention_scores = get_attention_scores(174 attn, query, key, attention_mask175 ) # The custom function returns pre-softmax probabilities176 self_attention_probs = self_attention_scores.softmax(177 dim=-1178 ) # Manually compute the probabilities here, the scores will be reused in the second part of PAIntA179 self_attention_probs = self_attention_probs.to(query.dtype)180 181 hidden_states = torch.bmm(self_attention_probs, value)182 hidden_states = attn.batch_to_head_dim(hidden_states)183 184 # linear proj185 hidden_states = attn.to_out[0](hidden_states)186 # dropout187 hidden_states = attn.to_out[1](hidden_states)188 189 # x = x + self.attn1(self.norm1(x))190 191 if input_ndim == 4:192 hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)193 194 if attn.residual_connection: # So many residuals everywhere195 hidden_states = hidden_states + residual196 197 self_attention_output_hidden_states = hidden_states / attn.rescale_output_factor198 199 # ================================================== #200 # ============ BasicTransformerBlock =============== #201 # ================================================== #202 # We use a hack by running the code from the BasicTransformerBlock that is between Self and Cross attentions here203 # The other option would've been modifying the BasicTransformerBlock and adding this functionality here.204 # I assumed that changing the BasicTransformerBlock would have been a bigger deal and decided to use this hack isntead.205 206 # The SelfAttention block recieves the normalized latents from the BasicTransformerBlock,207 # But the residual of the output is the non-normalized version.208 # Therefore we unnormalize the input hidden state here209 unnormalized_input_hidden_states = (210 input_hidden_states + self.transformer_block.norm1.bias211 ) * self.transformer_block.norm1.weight212 213 # TODO: return if neccessary214 # if self.use_ada_layer_norm_zero:215 # attn_output = gate_msa.unsqueeze(1) * attn_output216 # elif self.use_ada_layer_norm_single:217 # attn_output = gate_msa * attn_output218 219 transformer_hidden_states = self_attention_output_hidden_states + unnormalized_input_hidden_states220 if transformer_hidden_states.ndim == 4:221 transformer_hidden_states = transformer_hidden_states.squeeze(1)222 223 # TODO: return if neccessary224 # 2.5 GLIGEN Control225 # if gligen_kwargs is not None:226 # transformer_hidden_states = self.fuser(transformer_hidden_states, gligen_kwargs["objs"])227 # NOTE: we experimented with using GLIGEN and HDPainter together, the results were not that great228 229 # 3. Cross-Attention230 if self.transformer_block.use_ada_layer_norm:231 # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, timestep)232 raise NotImplementedError()233 elif self.transformer_block.use_ada_layer_norm_zero or self.transformer_block.use_layer_norm:234 transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states)235 elif self.transformer_block.use_ada_layer_norm_single:236 # For PixArt norm2 isn't applied here:237 # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103238 transformer_norm_hidden_states = transformer_hidden_states239 elif self.transformer_block.use_ada_layer_norm_continuous:240 # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, added_cond_kwargs["pooled_text_emb"])241 raise NotImplementedError()242 else:243 raise ValueError("Incorrect norm")244 245 if self.transformer_block.pos_embed is not None and self.transformer_block.use_ada_layer_norm_single is False:246 transformer_norm_hidden_states = self.transformer_block.pos_embed(transformer_norm_hidden_states)247 248 # ================================================== #249 # ================= CROSS ATTENTION ================ #250 # ================================================== #251 252 # We do an initial pass of the CrossAttention up to obtaining the similarity matrix here.253 # The similarity matrix is used to obtain scaling coefficients for the attention matrix of the self attention254 # We reuse the previously computed self-attention matrix, and only repeat the steps after the softmax255 256 cross_attention_input_hidden_states = (257 transformer_norm_hidden_states # Renaming the variable for the sake of readability258 )259 260 # TODO: check if classifier_free_guidance is being used before splitting here261 if self.do_classifier_free_guidance:262 # Our scaling coefficients depend only on the conditional part, so we split the inputs263 (264 _cross_attention_input_hidden_states_unconditional,265 cross_attention_input_hidden_states_conditional,266 ) = cross_attention_input_hidden_states.chunk(2)267 268 # Same split for the encoder_hidden_states i.e. the tokens269 # Since the SelfAttention processors don't get the encoder states as input, we inject them into the processor in the begining.270 _encoder_hidden_states_unconditional, encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(271 2272 )273 else:274 cross_attention_input_hidden_states_conditional = cross_attention_input_hidden_states275 encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(2)276 277 # Rename the variables for the sake of readability278 # The part below is the beginning of the __call__ function of the following CrossAttention layer279 cross_attention_hidden_states = cross_attention_input_hidden_states_conditional280 cross_attention_encoder_hidden_states = encoder_hidden_states_conditional281 282 attn2 = self.transformer_block.attn2283 284 if attn2.spatial_norm is not None:285 cross_attention_hidden_states = attn2.spatial_norm(cross_attention_hidden_states, temb)286 287 input_ndim = cross_attention_hidden_states.ndim288 289 if input_ndim == 4:290 batch_size, channel, height, width = cross_attention_hidden_states.shape291 cross_attention_hidden_states = cross_attention_hidden_states.view(292 batch_size, channel, height * width293 ).transpose(1, 2)294 295 (296 batch_size,297 sequence_length,298 _,299 ) = cross_attention_hidden_states.shape # It is definitely a cross attention, so no need for an if block300 # TODO: change the attention_mask here301 attention_mask = attn2.prepare_attention_mask(302 None, sequence_length, batch_size303 ) # I assume the attention mask is the same...304 305 if attn2.group_norm is not None:306 cross_attention_hidden_states = attn2.group_norm(cross_attention_hidden_states.transpose(1, 2)).transpose(307 1, 2308 )309 310 query2 = attn2.to_q(cross_attention_hidden_states)311 312 if attn2.norm_cross:313 cross_attention_encoder_hidden_states = attn2.norm_encoder_hidden_states(314 cross_attention_encoder_hidden_states315 )316 317 key2 = attn2.to_k(cross_attention_encoder_hidden_states)318 query2 = attn2.head_to_batch_dim(query2)319 key2 = attn2.head_to_batch_dim(key2)320 321 cross_attention_probs = attn2.get_attention_scores(query2, key2, attention_mask)322 323 # CrossAttention ends here, the remaining part is not used324 325 # ================================================== #326 # ================ SELF ATTENTION 2 ================ #327 # ================================================== #328 # DEJA VU!329 330 mask = (mask > 0.5).to(self_attention_output_hidden_states.dtype)331 m = mask.to(self_attention_output_hidden_states.device)332 # m = rearrange(m, 'b c h w -> b (h w) c').contiguous()333 m = m.permute(0, 2, 3, 1).reshape((m.shape[0], -1, m.shape[1])).contiguous() # B HW 1334 m = torch.matmul(m, m.permute(0, 2, 1)) + (1 - m)335 336 # # Compute scaling coefficients for the similarity matrix337 # # Select the cross attention values for the correct tokens only!338 # cross_attention_probs = cross_attention_probs.mean(dim = 0)339 # cross_attention_probs = cross_attention_probs[:, self.token_idx].sum(dim=1)340 341 # cross_attention_probs = cross_attention_probs.reshape(shape)342 # gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(self_attention_output_hidden_states.device)343 # cross_attention_probs = gaussian_smoothing(cross_attention_probs.unsqueeze(0))[0] # optional smoothing344 # cross_attention_probs = cross_attention_probs.reshape(-1)345 # cross_attention_probs = ((cross_attention_probs - torch.median(cross_attention_probs.ravel())) / torch.max(cross_attention_probs.ravel())).clip(0, 1)346 347 # c = (1 - m) * cross_attention_probs.reshape(1, 1, -1) + m # PAIntA scaling coefficients348 349 # Compute scaling coefficients for the similarity matrix350 # Select the cross attention values for the correct tokens only!351 352 batch_size, dims, channels = cross_attention_probs.shape353 batch_size = batch_size // attn.heads354 cross_attention_probs = cross_attention_probs.reshape((batch_size, attn.heads, dims, channels)) # B, D, HW, T355 356 cross_attention_probs = cross_attention_probs.mean(dim=1) # B, HW, T357 cross_attention_probs = cross_attention_probs[..., self.token_idx].sum(dim=-1) # B, HW358 cross_attention_probs = cross_attention_probs.reshape((batch_size,) + shape) # , B, H, W359 360 gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(361 self_attention_output_hidden_states.device362 )363 cross_attention_probs = gaussian_smoothing(cross_attention_probs[:, None])[:, 0] # optional smoothing B, H, W364 365 # Median normalization366 cross_attention_probs = cross_attention_probs.reshape(batch_size, -1) # B, HW367 cross_attention_probs = (368 cross_attention_probs - cross_attention_probs.median(dim=-1, keepdim=True).values369 ) / cross_attention_probs.max(dim=-1, keepdim=True).values370 cross_attention_probs = cross_attention_probs.clip(0, 1)371 372 c = (1 - m) * cross_attention_probs.reshape(batch_size, 1, -1) + m373 c = c.repeat_interleave(attn.heads, 0) # BD, HW374 if self.do_classifier_free_guidance:375 c = torch.cat([c, c]) # 2BD, HW376 377 # Rescaling the original self-attention matrix378 self_attention_scores_rescaled = self_attention_scores * c379 self_attention_probs_rescaled = self_attention_scores_rescaled.softmax(dim=-1)380 381 # Continuing the self attention normally using the new matrix382 hidden_states = torch.bmm(self_attention_probs_rescaled, value)383 hidden_states = attn.batch_to_head_dim(hidden_states)384 385 # linear proj386 hidden_states = attn.to_out[0](hidden_states)387 # dropout388 hidden_states = attn.to_out[1](hidden_states)389 390 if input_ndim == 4:391 hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)392 393 if attn.residual_connection:394 hidden_states = hidden_states + input_hidden_states395 396 hidden_states = hidden_states / attn.rescale_output_factor397 398 return hidden_states399 400 401class StableDiffusionHDPainterPipeline(StableDiffusionInpaintPipeline):402 def get_tokenized_prompt(self, prompt):403 out = self.tokenizer(prompt)404 return [self.tokenizer.decode(x) for x in out["input_ids"]]405 406 def init_attn_processors(407 self,408 mask,409 token_idx,410 use_painta=True,411 use_rasg=True,412 painta_scale_factors=[2, 4], # 64x64 -> [16x16, 32x32]413 rasg_scale_factor=4, # 64x64 -> 16x16414 self_attention_layer_name="attn1",415 cross_attention_layer_name="attn2",416 list_of_painta_layer_names=None,417 list_of_rasg_layer_names=None,418 ):419 default_processor = AttnProcessor()420 width, height = mask.shape[-2:]421 width, height = width // self.vae_scale_factor, height // self.vae_scale_factor422 423 painta_scale_factors = [x * self.vae_scale_factor for x in painta_scale_factors]424 rasg_scale_factor = self.vae_scale_factor * rasg_scale_factor425 426 attn_processors = {}427 for x in self.unet.attn_processors:428 if (list_of_painta_layer_names is None and self_attention_layer_name in x) or (429 list_of_painta_layer_names is not None and x in list_of_painta_layer_names430 ):431 if use_painta:432 transformer_block = self.unet.get_submodule(x.replace(".attn1.processor", ""))433 attn_processors[x] = PAIntAAttnProcessor(434 transformer_block, mask, token_idx, self.do_classifier_free_guidance, painta_scale_factors435 )436 else:437 attn_processors[x] = default_processor438 elif (list_of_rasg_layer_names is None and cross_attention_layer_name in x) or (439 list_of_rasg_layer_names is not None and x in list_of_rasg_layer_names440 ):441 if use_rasg:442 attn_processors[x] = RASGAttnProcessor(mask, token_idx, rasg_scale_factor)443 else:444 attn_processors[x] = default_processor445 446 self.unet.set_attn_processor(attn_processors)447 # import json448 # with open('/home/hayk.manukyan/repos/diffusers/debug.txt', 'a') as f:449 # json.dump({x:str(y) for x,y in self.unet.attn_processors.items()}, f, indent=4)450 451 @torch.no_grad()452 def __call__(453 self,454 prompt: Union[str, List[str]] = None,455 image: PipelineImageInput = None,456 mask_image: PipelineImageInput = None,457 masked_image_latents: torch.Tensor = None,458 height: Optional[int] = None,459 width: Optional[int] = None,460 padding_mask_crop: Optional[int] = None,461 strength: float = 1.0,462 num_inference_steps: int = 50,463 timesteps: List[int] = None,464 guidance_scale: float = 7.5,465 positive_prompt: Optional[str] = "",466 negative_prompt: Optional[Union[str, List[str]]] = None,467 num_images_per_prompt: Optional[int] = 1,468 eta: float = 0.01,469 generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,470 latents: Optional[torch.Tensor] = None,471 prompt_embeds: Optional[torch.Tensor] = None,472 negative_prompt_embeds: Optional[torch.Tensor] = None,473 ip_adapter_image: Optional[PipelineImageInput] = None,474 output_type: Optional[str] = "pil",475 return_dict: bool = True,476 cross_attention_kwargs: Optional[Dict[str, Any]] = None,477 clip_skip: int = None,478 callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,479 callback_on_step_end_tensor_inputs: List[str] = ["latents"],480 use_painta=True,481 use_rasg=True,482 self_attention_layer_name=".attn1",483 cross_attention_layer_name=".attn2",484 painta_scale_factors=[2, 4], # 16 x 16 and 32 x 32485 rasg_scale_factor=4, # 16x16 by default486 list_of_painta_layer_names=None,487 list_of_rasg_layer_names=None,488 **kwargs,489 ):490 callback = kwargs.pop("callback", None)491 callback_steps = kwargs.pop("callback_steps", None)492 493 if callback is not None:494 deprecate(495 "callback",496 "1.0.0",497 "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",498 )499 if callback_steps is not None:500 deprecate(501 "callback_steps",502 "1.0.0",503 "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",504 )505 506 # 0. Default height and width to unet507 height = height or self.unet.config.sample_size * self.vae_scale_factor508 width = width or self.unet.config.sample_size * self.vae_scale_factor509 510 #511 prompt_no_positives = prompt512 if isinstance(prompt, list):513 prompt = [x + positive_prompt for x in prompt]514 else:515 prompt = prompt + positive_prompt516 517 # 1. Check inputs518 self.check_inputs(519 prompt,520 image,521 mask_image,522 height,523 width,524 strength,525 callback_steps,526 negative_prompt,527 prompt_embeds,528 negative_prompt_embeds,529 callback_on_step_end_tensor_inputs,530 padding_mask_crop,531 )532 533 self._guidance_scale = guidance_scale534 self._clip_skip = clip_skip535 self._cross_attention_kwargs = cross_attention_kwargs536 self._interrupt = False537 538 # 2. Define call parameters539 if prompt is not None and isinstance(prompt, str):540 batch_size = 1541 elif prompt is not None and isinstance(prompt, list):542 batch_size = len(prompt)543 else:544 batch_size = prompt_embeds.shape[0]545 546 # assert batch_size == 1, "Does not work with batch size > 1 currently"547 548 device = self._execution_device549 550 # 3. Encode input prompt551 text_encoder_lora_scale = (552 cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None553 )554 prompt_embeds, negative_prompt_embeds = self.encode_prompt(555 prompt,556 device,557 num_images_per_prompt,558 self.do_classifier_free_guidance,559 negative_prompt,560 prompt_embeds=prompt_embeds,561 negative_prompt_embeds=negative_prompt_embeds,562 lora_scale=text_encoder_lora_scale,563 clip_skip=self.clip_skip,564 )565 # For classifier free guidance, we need to do two forward passes.566 # Here we concatenate the unconditional and text embeddings into a single batch567 # to avoid doing two forward passes568 if self.do_classifier_free_guidance:569 prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])570 571 if ip_adapter_image is not None:572 output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True573 image_embeds, negative_image_embeds = self.encode_image(574 ip_adapter_image, device, num_images_per_prompt, output_hidden_state575 )576 if self.do_classifier_free_guidance:577 image_embeds = torch.cat([negative_image_embeds, image_embeds])578 579 # 4. set timesteps580 timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)581 timesteps, num_inference_steps = self.get_timesteps(582 num_inference_steps=num_inference_steps, strength=strength, device=device583 )584 # check that number of inference steps is not < 1 - as this doesn't make sense585 if num_inference_steps < 1:586 raise ValueError(587 f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"588 f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."589 )590 # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)591 latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)592 # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise593 is_strength_max = strength == 1.0594 595 # 5. Preprocess mask and image596 597 if padding_mask_crop is not None:598 crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)599 resize_mode = "fill"600 else:601 crops_coords = None602 resize_mode = "default"603 604 original_image = image605 init_image = self.image_processor.preprocess(606 image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode607 )608 init_image = init_image.to(dtype=torch.float32)609 610 # 6. Prepare latent variables611 num_channels_latents = self.vae.config.latent_channels612 num_channels_unet = self.unet.config.in_channels613 return_image_latents = num_channels_unet == 4614 615 latents_outputs = self.prepare_latents(616 batch_size * num_images_per_prompt,617 num_channels_latents,618 height,619 width,620 prompt_embeds.dtype,621 device,622 generator,623 latents,624 image=init_image,625 timestep=latent_timestep,626 is_strength_max=is_strength_max,627 return_noise=True,628 return_image_latents=return_image_latents,629 )630 631 if return_image_latents:632 latents, noise, image_latents = latents_outputs633 else:634 latents, noise = latents_outputs635 636 # 7. Prepare mask latent variables637 mask_condition = self.mask_processor.preprocess(638 mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords639 )640 641 if masked_image_latents is None:642 masked_image = init_image * (mask_condition < 0.5)643 else:644 masked_image = masked_image_latents645 646 mask, masked_image_latents = self.prepare_mask_latents(647 mask_condition,648 masked_image,649 batch_size * num_images_per_prompt,650 height,651 width,652 prompt_embeds.dtype,653 device,654 generator,655 self.do_classifier_free_guidance,656 )657 658 # 7.5 Setting up HD-Painter659 660 # Get the indices of the tokens to be modified by both RASG and PAIntA661 token_idx = list(range(1, self.get_tokenized_prompt(prompt_no_positives).index("<|endoftext|>"))) + [662 self.get_tokenized_prompt(prompt).index("<|endoftext|>")663 ]664 665 # Setting up the attention processors666 self.init_attn_processors(667 mask_condition,668 token_idx,669 use_painta,670 use_rasg,671 painta_scale_factors=painta_scale_factors,672 rasg_scale_factor=rasg_scale_factor,673 self_attention_layer_name=self_attention_layer_name,674 cross_attention_layer_name=cross_attention_layer_name,675 list_of_painta_layer_names=list_of_painta_layer_names,676 list_of_rasg_layer_names=list_of_rasg_layer_names,677 )678 679 # 8. Check that sizes of mask, masked image and latents match680 if num_channels_unet == 9:681 # default case for runwayml/stable-diffusion-inpainting682 num_channels_mask = mask.shape[1]683 num_channels_masked_image = masked_image_latents.shape[1]684 if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:685 raise ValueError(686 f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"687 f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"688 f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"689 f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"690 " `pipeline.unet` or your `mask_image` or `image` input."691 )692 elif num_channels_unet != 4:693 raise ValueError(694 f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."695 )696 697 # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline698 extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)699 700 if use_rasg:701 extra_step_kwargs["generator"] = None702 703 # 9.1 Add image embeds for IP-Adapter704 added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None705 706 # 9.2 Optionally get Guidance Scale Embedding707 timestep_cond = None708 if self.unet.config.time_cond_proj_dim is not None:709 guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)710 timestep_cond = self.get_guidance_scale_embedding(711 guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim712 ).to(device=device, dtype=latents.dtype)713 714 # 10. Denoising loop715 num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order716 self._num_timesteps = len(timesteps)717 painta_active = True718 719 with self.progress_bar(total=num_inference_steps) as progress_bar:720 for i, t in enumerate(timesteps):721 if self.interrupt:722 continue723 724 if t < 500 and painta_active:725 self.init_attn_processors(726 mask_condition,727 token_idx,728 False,729 use_rasg,730 painta_scale_factors=painta_scale_factors,731 rasg_scale_factor=rasg_scale_factor,732 self_attention_layer_name=self_attention_layer_name,733 cross_attention_layer_name=cross_attention_layer_name,734 list_of_painta_layer_names=list_of_painta_layer_names,735 list_of_rasg_layer_names=list_of_rasg_layer_names,736 )737 painta_active = False738 739 with torch.enable_grad():740 self.unet.zero_grad()741 latents = latents.detach()742 latents.requires_grad = True743 744 # expand the latents if we are doing classifier free guidance745 latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents746 747 # concat latents, mask, masked_image_latents in the channel dimension748 latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)749 750 if num_channels_unet == 9:751 latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)752 753 self.scheduler.latents = latents754 self.encoder_hidden_states = prompt_embeds755 for attn_processor in self.unet.attn_processors.values():756 attn_processor.encoder_hidden_states = prompt_embeds757 758 # predict the noise residual759 noise_pred = self.unet(760 latent_model_input,761 t,762 encoder_hidden_states=prompt_embeds,763 timestep_cond=timestep_cond,764 cross_attention_kwargs=self.cross_attention_kwargs,765 added_cond_kwargs=added_cond_kwargs,766 return_dict=False,767 )[0]768 769 # perform guidance770 if self.do_classifier_free_guidance:771 noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)772 noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)773 774 if use_rasg:775 # Perform RASG776 _, _, height, width = mask_condition.shape # 512 x 512777 scale_factor = self.vae_scale_factor * rasg_scale_factor # 8 * 4 = 32778 779 # TODO: Fix for > 1 batch_size780 rasg_mask = F.interpolate(781 mask_condition, (height // scale_factor, width // scale_factor), mode="bicubic"782 )[0, 0] # mode is nearest by default, B, H, W783 784 # Aggregate the saved attention maps785 attn_map = []786 for processor in self.unet.attn_processors.values():787 if hasattr(processor, "attention_scores") and processor.attention_scores is not None:788 if self.do_classifier_free_guidance:789 attn_map.append(processor.attention_scores.chunk(2)[1]) # (B/2) x H, 256, 77790 else:791 attn_map.append(processor.attention_scores) # B x H, 256, 77 ?792 793 attn_map = (794 torch.cat(attn_map)795 .mean(0)796 .permute(1, 0)797 .reshape((-1, height // scale_factor, width // scale_factor))798 ) # 77, 16, 16799 800 # Compute the attention score801 attn_score = -sum(802 [803 F.binary_cross_entropy_with_logits(x - 1.0, rasg_mask.to(device))804 for x in attn_map[token_idx]805 ]806 )807 808 # Backward the score and compute the gradients809 attn_score.backward()810 811 # Normalzie the gradients and compute the noise component812 variance_noise = latents.grad.detach()813 # print("VARIANCE SHAPE", variance_noise.shape)814 variance_noise -= torch.mean(variance_noise, [1, 2, 3], keepdim=True)815 variance_noise /= torch.std(variance_noise, [1, 2, 3], keepdim=True)816 else:817 variance_noise = None818 819 # compute the previous noisy sample x_t -> x_t-1820 latents = self.scheduler.step(821 noise_pred, t, latents, **extra_step_kwargs, return_dict=False, variance_noise=variance_noise822 )[0]823 824 if num_channels_unet == 4:825 init_latents_proper = image_latents826 if self.do_classifier_free_guidance:827 init_mask, _ = mask.chunk(2)828 else:829 init_mask = mask830 831 if i < len(timesteps) - 1:832 noise_timestep = timesteps[i + 1]833 init_latents_proper = self.scheduler.add_noise(834 init_latents_proper, noise, torch.tensor([noise_timestep])835 )836 837 latents = (1 - init_mask) * init_latents_proper + init_mask * latents838 839 if callback_on_step_end is not None:840 callback_kwargs = {}841 for k in callback_on_step_end_tensor_inputs:842 callback_kwargs[k] = locals()[k]843 callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)844 845 latents = callback_outputs.pop("latents", latents)846 prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)847 negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)848 mask = callback_outputs.pop("mask", mask)849 masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)850 851 # call the callback, if provided852 if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):853 progress_bar.update()854 if callback is not None and i % callback_steps == 0:855 step_idx = i // getattr(self.scheduler, "order", 1)856 callback(step_idx, t, latents)857 858 if not output_type == "latent":859 condition_kwargs = {}860 if isinstance(self.vae, AsymmetricAutoencoderKL):861 init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)862 init_image_condition = init_image.clone()863 init_image = self._encode_vae_image(init_image, generator=generator)864 mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)865 condition_kwargs = {"image": init_image_condition, "mask": mask_condition}866 image = self.vae.decode(867 latents / self.vae.config.scaling_factor, return_dict=False, generator=generator, **condition_kwargs868 )[0]869 image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)870 else:871 image = latents872 has_nsfw_concept = None873 874 if has_nsfw_concept is None:875 do_denormalize = [True] * image.shape[0]876 else:877 do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]878 879 image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)880 881 if padding_mask_crop is not None:882 image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]883 884 # Offload all models885 self.maybe_free_model_hooks()886 887 if not return_dict:888 return (image, has_nsfw_concept)889 890 return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)891 892 893# ============= Utility Functions ============== #894 895 896class GaussianSmoothing(nn.Module):897 """898 Apply gaussian smoothing on a899 1d, 2d or 3d tensor. Filtering is performed seperately for each channel900 in the input using a depthwise convolution.901 Arguments:902 channels (int, sequence): Number of channels of the input tensors. Output will903 have this number of channels as well.904 kernel_size (int, sequence): Size of the gaussian kernel.905 sigma (float, sequence): Standard deviation of the gaussian kernel.906 dim (int, optional): The number of dimensions of the data.907 Default value is 2 (spatial).908 """909 910 def __init__(self, channels, kernel_size, sigma, dim=2):911 super(GaussianSmoothing, self).__init__()912 if isinstance(kernel_size, numbers.Number):913 kernel_size = [kernel_size] * dim914 if isinstance(sigma, numbers.Number):915 sigma = [sigma] * dim916 917 # The gaussian kernel is the product of the918 # gaussian function of each dimension.919 kernel = 1920 meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])921 for size, std, mgrid in zip(kernel_size, sigma, meshgrids):922 mean = (size - 1) / 2923 kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))924 925 # Make sure sum of values in gaussian kernel equals 1.926 kernel = kernel / torch.sum(kernel)927 928 # Reshape to depthwise convolutional weight929 kernel = kernel.view(1, 1, *kernel.size())930 kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))931 932 self.register_buffer("weight", kernel)933 self.groups = channels934 935 if dim == 1:936 self.conv = F.conv1d937 elif dim == 2:938 self.conv = F.conv2d939 elif dim == 3:940 self.conv = F.conv3d941 else:942 raise RuntimeError("Only 1, 2 and 3 dimensions are supported. Received {}.".format(dim))943 944 def forward(self, input):945 """946 Apply gaussian filter to input.947 Arguments:948 input (torch.Tensor): Input to apply gaussian filter on.949 Returns:950 filtered (torch.Tensor): Filtered output.951 """952 return self.conv(input, weight=self.weight.to(input.dtype), groups=self.groups, padding="same")953 954 955def get_attention_scores(956 self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None957) -> torch.Tensor:958 r"""959 Compute the attention scores.960 961 Args:962 query (`torch.Tensor`): The query tensor.963 key (`torch.Tensor`): The key tensor.964 attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.965 966 Returns:967 `torch.Tensor`: The attention probabilities/scores.968 """969 if self.upcast_attention:970 query = query.float()971 key = key.float()972 973 if attention_mask is None:974 baddbmm_input = torch.empty(975 query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device976 )977 beta = 0978 else:979 baddbmm_input = attention_mask980 beta = 1981 982 attention_scores = torch.baddbmm(983 baddbmm_input,984 query,985 key.transpose(-1, -2),986 beta=beta,987 alpha=self.scale,988 )989 del baddbmm_input990 991 if self.upcast_softmax:992 attention_scores = attention_scores.float()993 994 return attention_scores995 