CoolFace
Datasetpublic

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.

sourceHugging Faceupdated 28d agoView on Hugging Face
9likes22kdownloads
stable_diffusion_reference.py796 linesDownload Raw Back to v0.20.1
1# Inspired by: https://github.com/Mikubill/sd-webui-controlnet/discussions/1236 and https://github.com/Mikubill/sd-webui-controlnet/discussions/12802from typing import Any, Callable, Dict, List, Optional, Tuple, Union3 4import numpy as np5import PIL.Image6import torch7 8from diffusers import StableDiffusionPipeline9from diffusers.models.attention import BasicTransformerBlock10from diffusers.models.unet_2d_blocks import CrossAttnDownBlock2D, CrossAttnUpBlock2D, DownBlock2D, UpBlock2D11from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput12from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg13from diffusers.utils import PIL_INTERPOLATION, logging, randn_tensor14 15 16logger = logging.get_logger(__name__)  # pylint: disable=invalid-name17 18EXAMPLE_DOC_STRING = """19    Examples:20        ```py21        >>> import torch22        >>> from diffusers import UniPCMultistepScheduler23        >>> from diffusers.utils import load_image24 25        >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")26 27        >>> pipe = StableDiffusionReferencePipeline.from_pretrained(28                "runwayml/stable-diffusion-v1-5",29                safety_checker=None,30                torch_dtype=torch.float1631                ).to('cuda:0')32 33        >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)34 35        >>> result_img = pipe(ref_image=input_image,36                        prompt="1girl",37                        num_inference_steps=20,38                        reference_attn=True,39                        reference_adain=True).images[0]40 41        >>> result_img.show()42        ```43"""44 45 46def torch_dfs(model: torch.nn.Module):47    result = [model]48    for child in model.children():49        result += torch_dfs(child)50    return result51 52 53class StableDiffusionReferencePipeline(StableDiffusionPipeline):54    def _default_height_width(self, height, width, image):55        # NOTE: It is possible that a list of images have different56        # dimensions for each image, so just checking the first image57        # is not _exactly_ correct, but it is simple.58        while isinstance(image, list):59            image = image[0]60 61        if height is None:62            if isinstance(image, PIL.Image.Image):63                height = image.height64            elif isinstance(image, torch.Tensor):65                height = image.shape[2]66 67            height = (height // 8) * 8  # round down to nearest multiple of 868 69        if width is None:70            if isinstance(image, PIL.Image.Image):71                width = image.width72            elif isinstance(image, torch.Tensor):73                width = image.shape[3]74 75            width = (width // 8) * 8  # round down to nearest multiple of 876 77        return height, width78 79    def prepare_image(80        self,81        image,82        width,83        height,84        batch_size,85        num_images_per_prompt,86        device,87        dtype,88        do_classifier_free_guidance=False,89        guess_mode=False,90    ):91        if not isinstance(image, torch.Tensor):92            if isinstance(image, PIL.Image.Image):93                image = [image]94 95            if isinstance(image[0], PIL.Image.Image):96                images = []97 98                for image_ in image:99                    image_ = image_.convert("RGB")100                    image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])101                    image_ = np.array(image_)102                    image_ = image_[None, :]103                    images.append(image_)104 105                image = images106 107                image = np.concatenate(image, axis=0)108                image = np.array(image).astype(np.float32) / 255.0109                image = (image - 0.5) / 0.5110                image = image.transpose(0, 3, 1, 2)111                image = torch.from_numpy(image)112            elif isinstance(image[0], torch.Tensor):113                image = torch.cat(image, dim=0)114 115        image_batch_size = image.shape[0]116 117        if image_batch_size == 1:118            repeat_by = batch_size119        else:120            # image batch size is the same as prompt batch size121            repeat_by = num_images_per_prompt122 123        image = image.repeat_interleave(repeat_by, dim=0)124 125        image = image.to(device=device, dtype=dtype)126 127        if do_classifier_free_guidance and not guess_mode:128            image = torch.cat([image] * 2)129 130        return image131 132    def prepare_ref_latents(self, refimage, batch_size, dtype, device, generator, do_classifier_free_guidance):133        refimage = refimage.to(device=device, dtype=dtype)134 135        # encode the mask image into latents space so we can concatenate it to the latents136        if isinstance(generator, list):137            ref_image_latents = [138                self.vae.encode(refimage[i : i + 1]).latent_dist.sample(generator=generator[i])139                for i in range(batch_size)140            ]141            ref_image_latents = torch.cat(ref_image_latents, dim=0)142        else:143            ref_image_latents = self.vae.encode(refimage).latent_dist.sample(generator=generator)144        ref_image_latents = self.vae.config.scaling_factor * ref_image_latents145 146        # duplicate mask and ref_image_latents for each generation per prompt, using mps friendly method147        if ref_image_latents.shape[0] < batch_size:148            if not batch_size % ref_image_latents.shape[0] == 0:149                raise ValueError(150                    "The passed images and the required batch size don't match. Images are supposed to be duplicated"151                    f" to a total batch size of {batch_size}, but {ref_image_latents.shape[0]} images were passed."152                    " Make sure the number of images that you pass is divisible by the total requested batch size."153                )154            ref_image_latents = ref_image_latents.repeat(batch_size // ref_image_latents.shape[0], 1, 1, 1)155 156        # aligning device to prevent device errors when concating it with the latent model input157        ref_image_latents = ref_image_latents.to(device=device, dtype=dtype)158        return ref_image_latents159 160    @torch.no_grad()161    def __call__(162        self,163        prompt: Union[str, List[str]] = None,164        ref_image: Union[torch.FloatTensor, PIL.Image.Image] = None,165        height: Optional[int] = None,166        width: Optional[int] = None,167        num_inference_steps: int = 50,168        guidance_scale: float = 7.5,169        negative_prompt: Optional[Union[str, List[str]]] = None,170        num_images_per_prompt: Optional[int] = 1,171        eta: float = 0.0,172        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,173        latents: Optional[torch.FloatTensor] = None,174        prompt_embeds: Optional[torch.FloatTensor] = None,175        negative_prompt_embeds: Optional[torch.FloatTensor] = None,176        output_type: Optional[str] = "pil",177        return_dict: bool = True,178        callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,179        callback_steps: int = 1,180        cross_attention_kwargs: Optional[Dict[str, Any]] = None,181        guidance_rescale: float = 0.0,182        attention_auto_machine_weight: float = 1.0,183        gn_auto_machine_weight: float = 1.0,184        style_fidelity: float = 0.5,185        reference_attn: bool = True,186        reference_adain: bool = True,187    ):188        r"""189        Function invoked when calling the pipeline for generation.190 191        Args:192            prompt (`str` or `List[str]`, *optional*):193                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.194                instead.195            ref_image (`torch.FloatTensor`, `PIL.Image.Image`):196                The Reference Control input condition. Reference Control uses this input condition to generate guidance to Unet. If197                the type is specified as `Torch.FloatTensor`, it is passed to Reference Control as is. `PIL.Image.Image` can198                also be accepted as an image.199            height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):200                The height in pixels of the generated image.201            width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):202                The width in pixels of the generated image.203            num_inference_steps (`int`, *optional*, defaults to 50):204                The number of denoising steps. More denoising steps usually lead to a higher quality image at the205                expense of slower inference.206            guidance_scale (`float`, *optional*, defaults to 7.5):207                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).208                `guidance_scale` is defined as `w` of equation 2. of [Imagen209                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >210                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,211                usually at the expense of lower image quality.212            negative_prompt (`str` or `List[str]`, *optional*):213                The prompt or prompts not to guide the image generation. If not defined, one has to pass214                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is215                less than `1`).216            num_images_per_prompt (`int`, *optional*, defaults to 1):217                The number of images to generate per prompt.218            eta (`float`, *optional*, defaults to 0.0):219                Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to220                [`schedulers.DDIMScheduler`], will be ignored for others.221            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):222                One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)223                to make generation deterministic.224            latents (`torch.FloatTensor`, *optional*):225                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image226                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents227                tensor will ge generated by sampling using the supplied random `generator`.228            prompt_embeds (`torch.FloatTensor`, *optional*):229                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not230                provided, text embeddings will be generated from `prompt` input argument.231            negative_prompt_embeds (`torch.FloatTensor`, *optional*):232                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt233                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input234                argument.235            output_type (`str`, *optional*, defaults to `"pil"`):236                The output format of the generate image. Choose between237                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.238            return_dict (`bool`, *optional*, defaults to `True`):239                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a240                plain tuple.241            callback (`Callable`, *optional*):242                A function that will be called every `callback_steps` steps during inference. The function will be243                called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.244            callback_steps (`int`, *optional*, defaults to 1):245                The frequency at which the `callback` function will be called. If not specified, the callback will be246                called at every step.247            cross_attention_kwargs (`dict`, *optional*):248                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under249                `self.processor` in250                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).251            guidance_rescale (`float`, *optional*, defaults to 0.7):252                Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are253                Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of254                [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).255                Guidance rescale factor should fix overexposure when using zero terminal SNR.256            attention_auto_machine_weight (`float`):257                Weight of using reference query for self attention's context.258                If attention_auto_machine_weight=1.0, use reference query for all self attention's context.259            gn_auto_machine_weight (`float`):260                Weight of using reference adain. If gn_auto_machine_weight=2.0, use all reference adain plugins.261            style_fidelity (`float`):262                style fidelity of ref_uncond_xt. If style_fidelity=1.0, control more important,263                elif style_fidelity=0.0, prompt more important, else balanced.264            reference_attn (`bool`):265                Whether to use reference query for self attention's context.266            reference_adain (`bool`):267                Whether to use reference adain.268 269        Examples:270 271        Returns:272            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:273            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.274            When returning a tuple, the first element is a list with the generated images, and the second element is a275            list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"276            (nsfw) content, according to the `safety_checker`.277        """278        assert reference_attn or reference_adain, "`reference_attn` or `reference_adain` must be True."279 280        # 0. Default height and width to unet281        height, width = self._default_height_width(height, width, ref_image)282 283        # 1. Check inputs. Raise error if not correct284        self.check_inputs(285            prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds286        )287 288        # 2. Define call parameters289        if prompt is not None and isinstance(prompt, str):290            batch_size = 1291        elif prompt is not None and isinstance(prompt, list):292            batch_size = len(prompt)293        else:294            batch_size = prompt_embeds.shape[0]295 296        device = self._execution_device297        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)298        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`299        # corresponds to doing no classifier free guidance.300        do_classifier_free_guidance = guidance_scale > 1.0301 302        # 3. Encode input prompt303        text_encoder_lora_scale = (304            cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None305        )306        prompt_embeds = self._encode_prompt(307            prompt,308            device,309            num_images_per_prompt,310            do_classifier_free_guidance,311            negative_prompt,312            prompt_embeds=prompt_embeds,313            negative_prompt_embeds=negative_prompt_embeds,314            lora_scale=text_encoder_lora_scale,315        )316 317        # 4. Preprocess reference image318        ref_image = self.prepare_image(319            image=ref_image,320            width=width,321            height=height,322            batch_size=batch_size * num_images_per_prompt,323            num_images_per_prompt=num_images_per_prompt,324            device=device,325            dtype=prompt_embeds.dtype,326        )327 328        # 5. Prepare timesteps329        self.scheduler.set_timesteps(num_inference_steps, device=device)330        timesteps = self.scheduler.timesteps331 332        # 6. Prepare latent variables333        num_channels_latents = self.unet.config.in_channels334        latents = self.prepare_latents(335            batch_size * num_images_per_prompt,336            num_channels_latents,337            height,338            width,339            prompt_embeds.dtype,340            device,341            generator,342            latents,343        )344 345        # 7. Prepare reference latent variables346        ref_image_latents = self.prepare_ref_latents(347            ref_image,348            batch_size * num_images_per_prompt,349            prompt_embeds.dtype,350            device,351            generator,352            do_classifier_free_guidance,353        )354 355        # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline356        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)357 358        # 9. Modify self attention and group norm359        MODE = "write"360        uc_mask = (361            torch.Tensor([1] * batch_size * num_images_per_prompt + [0] * batch_size * num_images_per_prompt)362            .type_as(ref_image_latents)363            .bool()364        )365 366        def hacked_basic_transformer_inner_forward(367            self,368            hidden_states: torch.FloatTensor,369            attention_mask: Optional[torch.FloatTensor] = None,370            encoder_hidden_states: Optional[torch.FloatTensor] = None,371            encoder_attention_mask: Optional[torch.FloatTensor] = None,372            timestep: Optional[torch.LongTensor] = None,373            cross_attention_kwargs: Dict[str, Any] = None,374            class_labels: Optional[torch.LongTensor] = None,375        ):376            if self.use_ada_layer_norm:377                norm_hidden_states = self.norm1(hidden_states, timestep)378            elif self.use_ada_layer_norm_zero:379                norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(380                    hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype381                )382            else:383                norm_hidden_states = self.norm1(hidden_states)384 385            # 1. Self-Attention386            cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}387            if self.only_cross_attention:388                attn_output = self.attn1(389                    norm_hidden_states,390                    encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,391                    attention_mask=attention_mask,392                    **cross_attention_kwargs,393                )394            else:395                if MODE == "write":396                    self.bank.append(norm_hidden_states.detach().clone())397                    attn_output = self.attn1(398                        norm_hidden_states,399                        encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,400                        attention_mask=attention_mask,401                        **cross_attention_kwargs,402                    )403                if MODE == "read":404                    if attention_auto_machine_weight > self.attn_weight:405                        attn_output_uc = self.attn1(406                            norm_hidden_states,407                            encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1),408                            # attention_mask=attention_mask,409                            **cross_attention_kwargs,410                        )411                        attn_output_c = attn_output_uc.clone()412                        if do_classifier_free_guidance and style_fidelity > 0:413                            attn_output_c[uc_mask] = self.attn1(414                                norm_hidden_states[uc_mask],415                                encoder_hidden_states=norm_hidden_states[uc_mask],416                                **cross_attention_kwargs,417                            )418                        attn_output = style_fidelity * attn_output_c + (1.0 - style_fidelity) * attn_output_uc419                        self.bank.clear()420                    else:421                        attn_output = self.attn1(422                            norm_hidden_states,423                            encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,424                            attention_mask=attention_mask,425                            **cross_attention_kwargs,426                        )427            if self.use_ada_layer_norm_zero:428                attn_output = gate_msa.unsqueeze(1) * attn_output429            hidden_states = attn_output + hidden_states430 431            if self.attn2 is not None:432                norm_hidden_states = (433                    self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)434                )435 436                # 2. Cross-Attention437                attn_output = self.attn2(438                    norm_hidden_states,439                    encoder_hidden_states=encoder_hidden_states,440                    attention_mask=encoder_attention_mask,441                    **cross_attention_kwargs,442                )443                hidden_states = attn_output + hidden_states444 445            # 3. Feed-forward446            norm_hidden_states = self.norm3(hidden_states)447 448            if self.use_ada_layer_norm_zero:449                norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]450 451            ff_output = self.ff(norm_hidden_states)452 453            if self.use_ada_layer_norm_zero:454                ff_output = gate_mlp.unsqueeze(1) * ff_output455 456            hidden_states = ff_output + hidden_states457 458            return hidden_states459 460        def hacked_mid_forward(self, *args, **kwargs):461            eps = 1e-6462            x = self.original_forward(*args, **kwargs)463            if MODE == "write":464                if gn_auto_machine_weight >= self.gn_weight:465                    var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)466                    self.mean_bank.append(mean)467                    self.var_bank.append(var)468            if MODE == "read":469                if len(self.mean_bank) > 0 and len(self.var_bank) > 0:470                    var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)471                    std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5472                    mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))473                    var_acc = sum(self.var_bank) / float(len(self.var_bank))474                    std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5475                    x_uc = (((x - mean) / std) * std_acc) + mean_acc476                    x_c = x_uc.clone()477                    if do_classifier_free_guidance and style_fidelity > 0:478                        x_c[uc_mask] = x[uc_mask]479                    x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc480                self.mean_bank = []481                self.var_bank = []482            return x483 484        def hack_CrossAttnDownBlock2D_forward(485            self,486            hidden_states: torch.FloatTensor,487            temb: Optional[torch.FloatTensor] = None,488            encoder_hidden_states: Optional[torch.FloatTensor] = None,489            attention_mask: Optional[torch.FloatTensor] = None,490            cross_attention_kwargs: Optional[Dict[str, Any]] = None,491            encoder_attention_mask: Optional[torch.FloatTensor] = None,492        ):493            eps = 1e-6494 495            # TODO(Patrick, William) - attention mask is not used496            output_states = ()497 498            for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):499                hidden_states = resnet(hidden_states, temb)500                hidden_states = attn(501                    hidden_states,502                    encoder_hidden_states=encoder_hidden_states,503                    cross_attention_kwargs=cross_attention_kwargs,504                    attention_mask=attention_mask,505                    encoder_attention_mask=encoder_attention_mask,506                    return_dict=False,507                )[0]508                if MODE == "write":509                    if gn_auto_machine_weight >= self.gn_weight:510                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)511                        self.mean_bank.append([mean])512                        self.var_bank.append([var])513                if MODE == "read":514                    if len(self.mean_bank) > 0 and len(self.var_bank) > 0:515                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)516                        std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5517                        mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))518                        var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))519                        std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5520                        hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc521                        hidden_states_c = hidden_states_uc.clone()522                        if do_classifier_free_guidance and style_fidelity > 0:523                            hidden_states_c[uc_mask] = hidden_states[uc_mask]524                        hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc525 526                output_states = output_states + (hidden_states,)527 528            if MODE == "read":529                self.mean_bank = []530                self.var_bank = []531 532            if self.downsamplers is not None:533                for downsampler in self.downsamplers:534                    hidden_states = downsampler(hidden_states)535 536                output_states = output_states + (hidden_states,)537 538            return hidden_states, output_states539 540        def hacked_DownBlock2D_forward(self, hidden_states, temb=None):541            eps = 1e-6542 543            output_states = ()544 545            for i, resnet in enumerate(self.resnets):546                hidden_states = resnet(hidden_states, temb)547 548                if MODE == "write":549                    if gn_auto_machine_weight >= self.gn_weight:550                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)551                        self.mean_bank.append([mean])552                        self.var_bank.append([var])553                if MODE == "read":554                    if len(self.mean_bank) > 0 and len(self.var_bank) > 0:555                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)556                        std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5557                        mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))558                        var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))559                        std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5560                        hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc561                        hidden_states_c = hidden_states_uc.clone()562                        if do_classifier_free_guidance and style_fidelity > 0:563                            hidden_states_c[uc_mask] = hidden_states[uc_mask]564                        hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc565 566                output_states = output_states + (hidden_states,)567 568            if MODE == "read":569                self.mean_bank = []570                self.var_bank = []571 572            if self.downsamplers is not None:573                for downsampler in self.downsamplers:574                    hidden_states = downsampler(hidden_states)575 576                output_states = output_states + (hidden_states,)577 578            return hidden_states, output_states579 580        def hacked_CrossAttnUpBlock2D_forward(581            self,582            hidden_states: torch.FloatTensor,583            res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],584            temb: Optional[torch.FloatTensor] = None,585            encoder_hidden_states: Optional[torch.FloatTensor] = None,586            cross_attention_kwargs: Optional[Dict[str, Any]] = None,587            upsample_size: Optional[int] = None,588            attention_mask: Optional[torch.FloatTensor] = None,589            encoder_attention_mask: Optional[torch.FloatTensor] = None,590        ):591            eps = 1e-6592            # TODO(Patrick, William) - attention mask is not used593            for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)):594                # pop res hidden states595                res_hidden_states = res_hidden_states_tuple[-1]596                res_hidden_states_tuple = res_hidden_states_tuple[:-1]597                hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)598                hidden_states = resnet(hidden_states, temb)599                hidden_states = attn(600                    hidden_states,601                    encoder_hidden_states=encoder_hidden_states,602                    cross_attention_kwargs=cross_attention_kwargs,603                    attention_mask=attention_mask,604                    encoder_attention_mask=encoder_attention_mask,605                    return_dict=False,606                )[0]607 608                if MODE == "write":609                    if gn_auto_machine_weight >= self.gn_weight:610                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)611                        self.mean_bank.append([mean])612                        self.var_bank.append([var])613                if MODE == "read":614                    if len(self.mean_bank) > 0 and len(self.var_bank) > 0:615                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)616                        std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5617                        mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))618                        var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))619                        std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5620                        hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc621                        hidden_states_c = hidden_states_uc.clone()622                        if do_classifier_free_guidance and style_fidelity > 0:623                            hidden_states_c[uc_mask] = hidden_states[uc_mask]624                        hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc625 626            if MODE == "read":627                self.mean_bank = []628                self.var_bank = []629 630            if self.upsamplers is not None:631                for upsampler in self.upsamplers:632                    hidden_states = upsampler(hidden_states, upsample_size)633 634            return hidden_states635 636        def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):637            eps = 1e-6638            for i, resnet in enumerate(self.resnets):639                # pop res hidden states640                res_hidden_states = res_hidden_states_tuple[-1]641                res_hidden_states_tuple = res_hidden_states_tuple[:-1]642                hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)643                hidden_states = resnet(hidden_states, temb)644 645                if MODE == "write":646                    if gn_auto_machine_weight >= self.gn_weight:647                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)648                        self.mean_bank.append([mean])649                        self.var_bank.append([var])650                if MODE == "read":651                    if len(self.mean_bank) > 0 and len(self.var_bank) > 0:652                        var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0)653                        std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5654                        mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i]))655                        var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i]))656                        std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5657                        hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc658                        hidden_states_c = hidden_states_uc.clone()659                        if do_classifier_free_guidance and style_fidelity > 0:660                            hidden_states_c[uc_mask] = hidden_states[uc_mask]661                        hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc662 663            if MODE == "read":664                self.mean_bank = []665                self.var_bank = []666 667            if self.upsamplers is not None:668                for upsampler in self.upsamplers:669                    hidden_states = upsampler(hidden_states, upsample_size)670 671            return hidden_states672 673        if reference_attn:674            attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock)]675            attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])676 677            for i, module in enumerate(attn_modules):678                module._original_inner_forward = module.forward679                module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)680                module.bank = []681                module.attn_weight = float(i) / float(len(attn_modules))682 683        if reference_adain:684            gn_modules = [self.unet.mid_block]685            self.unet.mid_block.gn_weight = 0686 687            down_blocks = self.unet.down_blocks688            for w, module in enumerate(down_blocks):689                module.gn_weight = 1.0 - float(w) / float(len(down_blocks))690                gn_modules.append(module)691 692            up_blocks = self.unet.up_blocks693            for w, module in enumerate(up_blocks):694                module.gn_weight = float(w) / float(len(up_blocks))695                gn_modules.append(module)696 697            for i, module in enumerate(gn_modules):698                if getattr(module, "original_forward", None) is None:699                    module.original_forward = module.forward700                if i == 0:701                    # mid_block702                    module.forward = hacked_mid_forward.__get__(module, torch.nn.Module)703                elif isinstance(module, CrossAttnDownBlock2D):704                    module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D)705                elif isinstance(module, DownBlock2D):706                    module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D)707                elif isinstance(module, CrossAttnUpBlock2D):708                    module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D)709                elif isinstance(module, UpBlock2D):710                    module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D)711                module.mean_bank = []712                module.var_bank = []713                module.gn_weight *= 2714 715        # 10. Denoising loop716        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order717        with self.progress_bar(total=num_inference_steps) as progress_bar:718            for i, t in enumerate(timesteps):719                # expand the latents if we are doing classifier free guidance720                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents721                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)722 723                # ref only part724                noise = randn_tensor(725                    ref_image_latents.shape, generator=generator, device=device, dtype=ref_image_latents.dtype726                )727                ref_xt = self.scheduler.add_noise(728                    ref_image_latents,729                    noise,730                    t.reshape(731                        1,732                    ),733                )734                ref_xt = torch.cat([ref_xt] * 2) if do_classifier_free_guidance else ref_xt735                ref_xt = self.scheduler.scale_model_input(ref_xt, t)736 737                MODE = "write"738                self.unet(739                    ref_xt,740                    t,741                    encoder_hidden_states=prompt_embeds,742                    cross_attention_kwargs=cross_attention_kwargs,743                    return_dict=False,744                )745 746                # predict the noise residual747                MODE = "read"748                noise_pred = self.unet(749                    latent_model_input,750                    t,751                    encoder_hidden_states=prompt_embeds,752                    cross_attention_kwargs=cross_attention_kwargs,753                    return_dict=False,754                )[0]755 756                # perform guidance757                if do_classifier_free_guidance:758                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)759                    noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)760 761                if do_classifier_free_guidance and guidance_rescale > 0.0:762                    # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf763                    noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)764 765                # compute the previous noisy sample x_t -> x_t-1766                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]767 768                # call the callback, if provided769                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):770                    progress_bar.update()771                    if callback is not None and i % callback_steps == 0:772                        callback(i, t, latents)773 774        if not output_type == "latent":775            image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]776            image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)777        else:778            image = latents779            has_nsfw_concept = None780 781        if has_nsfw_concept is None:782            do_denormalize = [True] * image.shape[0]783        else:784            do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]785 786        image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)787 788        # Offload last model to CPU789        if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:790            self.final_offload_hook.offload()791 792        if not return_dict:793            return (image, has_nsfw_concept)794 795        return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)796