





import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def 			__UpperCamelCase				(			lowercase__	:       List[Any]		,    lowercase__	:       Optional[int]=0.999		,    lowercase__	:       str="cosine"		,    )	->      List[Any]:
    '''simple docstring'''





    if alpha_transform_type == "cosine":

        def alpha_bar_fn(lowercase__	:       Tuple		):
            return math.cos((t + 0.008) / 1.008 * math.pi / 2		) ** 2

    elif alpha_transform_type == "exp":

        def alpha_bar_fn(lowercase__	:       Dict		):
            return math.exp(t * -12.0		)

    else:
        raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}'		)

    lowerCAmelCase_					:	Union[str, Any]						=   []
    for i in range(lowercase__		):
        lowerCAmelCase_					:	List[str]						=   i / num_diffusion_timesteps
        lowerCAmelCase_					:	Tuple						=   (i + 1) / num_diffusion_timesteps
        betas.append(min(1 - alpha_bar_fn(lowercase__		) / alpha_bar_fn(lowercase__		)		,    lowercase__		)		)
    return torch.tensor(lowercase__		,    dtype=torch.floataa		)

class 		__a							(	__UpperCamelCase			,__UpperCamelCase      ):
       __snake_case						:   str      =		[e.name for e in KarrasDiffusionSchedulers]
       __snake_case						:   Any      =		2



       @register_to_config
       def __init__(     self	:   Any					,			UpperCAmelCase	:   int = 10_00					,			UpperCAmelCase	:   float = 0.0_0085					,			UpperCAmelCase	:   float = 0.012					,			UpperCAmelCase	:   str = "linear"					,			UpperCAmelCase	:   Optional[Union[np.ndarray, List[float]]] = None					,			UpperCAmelCase	:   str = "epsilon"					,			UpperCAmelCase	:   str = "linspace"					,			UpperCAmelCase	:   int = 0					,			):
           if trained_betas is not None:
               lowerCAmelCase_					:	Tuple						=   torch.tensor(UpperCAmelCase					,			dtype=torch.floataa			)
           elif beta_schedule == "linear":
               lowerCAmelCase_					:	List[str]						=   torch.linspace(UpperCAmelCase					,			UpperCAmelCase					,			UpperCAmelCase					,			dtype=torch.floataa			)
           elif beta_schedule == "scaled_linear":
               # this schedule is very specific to the latent diffusion model.
               lowerCAmelCase_					:	Any						=   (
                   torch.linspace(beta_start**0.5					,			beta_end**0.5					,			UpperCAmelCase					,			dtype=torch.floataa			) ** 2
               )
           elif beta_schedule == "squaredcos_cap_v2":
               # Glide cosine schedule
               lowerCAmelCase_					:	Dict						=   betas_for_alpha_bar(UpperCAmelCase			)
           else:
               raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}'			)

           lowerCAmelCase_					:	int						=   1.0 - self.betas
           lowerCAmelCase_					:	int						=   torch.cumprod(self.alphas					,			dim=0			)

           #  set all values
           self.set_timesteps(UpperCAmelCase					,			UpperCAmelCase					,			UpperCAmelCase			)



       def  A							(     self	:   Union[str, Any]					,			UpperCAmelCase	:   Union[str, Any]					,			UpperCAmelCase	:   Any=None			):
           if schedule_timesteps is None:
               lowerCAmelCase_					:	int						=   self.timesteps

           lowerCAmelCase_					:	Any						=   (schedule_timesteps == timestep).nonzero()

           # The sigma index that is taken for the **very** first `step`
           # is always the second index (or the last index if there is only 1)
           # This way we can ensure we don't accidentally skip a sigma in
           # case we start in the middle of the denoising schedule (e.g. for image-to-image)
           if len(self._index_counter			) == 0:
               lowerCAmelCase_					:	List[Any]						=   1 if len(UpperCAmelCase			) > 1 else 0
           else:
               lowerCAmelCase_					:	Dict						=   timestep.cpu().item() if torch.is_tensor(UpperCAmelCase			) else timestep
               lowerCAmelCase_					:	int						=   self._index_counter[timestep_int]

           return indices[pos].item()



       @property
       def  A							(     self	:   Optional[Any]			):
           # standard deviation of the initial noise distribution
           if self.config.timestep_spacing in ["linspace", "trailing"]:
               return self.sigmas.max()

           return (self.sigmas.max() ** 2 + 1) ** 0.5



       def  A							(     self	:   Optional[Any]					,			UpperCAmelCase	:   torch.FloatTensor					,			UpperCAmelCase	:   Union[float, torch.FloatTensor]					,			):
           lowerCAmelCase_					:	List[Any]						=   self.index_for_timestep(UpperCAmelCase			)

           if self.state_in_first_order:
               lowerCAmelCase_					:	Optional[int]						=   self.sigmas[step_index]
           else:
               lowerCAmelCase_					:	Dict						=   self.sigmas_interpol[step_index - 1]

           lowerCAmelCase_					:	str						=   sample / ((sigma**2 + 1) ** 0.5)
           return sample



       def  A							(     self	:   List[str]					,			UpperCAmelCase	:   int					,			UpperCAmelCase	:   Union[str, torch.device] = None					,			UpperCAmelCase	:   Optional[int] = None					,			):
           lowerCAmelCase_					:	str						=   num_inference_steps

           lowerCAmelCase_					:	Optional[int]						=   num_train_timesteps or self.config.num_train_timesteps

           # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
           if self.config.timestep_spacing == "linspace":
               lowerCAmelCase_					:	List[str]						=   np.linspace(0					,			num_train_timesteps - 1					,			UpperCAmelCase					,			dtype=UpperCAmelCase			)[::-1].copy()
           elif self.config.timestep_spacing == "leading":
               lowerCAmelCase_					:	List[str]						=   num_train_timesteps // self.num_inference_steps
               # creates integer timesteps by multiplying by ratio
               # casting to int to avoid issues when num_inference_step is power of 3
               lowerCAmelCase_					:	str						=   (np.arange(0					,			UpperCAmelCase			) * step_ratio).round()[::-1].copy().astype(UpperCAmelCase			)
               timesteps += self.config.steps_offset
           elif self.config.timestep_spacing == "trailing":
               lowerCAmelCase_					:	str						=   num_train_timesteps / self.num_inference_steps
               # creates integer timesteps by multiplying by ratio
               # casting to int to avoid issues when num_inference_step is power of 3
               lowerCAmelCase_					:	List[str]						=   (np.arange(UpperCAmelCase					,			0					,			-step_ratio			)).round().copy().astype(UpperCAmelCase			)
               timesteps -= 1
           else:
               raise ValueError(
                   F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'			)

           lowerCAmelCase_					:	Optional[Any]						=   np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
           lowerCAmelCase_					:	int						=   torch.from_numpy(np.log(UpperCAmelCase			)			).to(UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[Any]						=   np.interp(UpperCAmelCase					,			np.arange(0					,			len(UpperCAmelCase			)			)					,			UpperCAmelCase			)
           lowerCAmelCase_					:	List[Any]						=   np.concatenate([sigmas, [0.0]]			).astype(np.floataa			)
           lowerCAmelCase_					:	int						=   torch.from_numpy(UpperCAmelCase			).to(device=UpperCAmelCase			)

           # compute up and down sigmas
           lowerCAmelCase_					:	Any						=   sigmas.roll(-1			)
           lowerCAmelCase_					:	List[str]						=   0.0
           lowerCAmelCase_					:	str						=   (sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
           lowerCAmelCase_					:	Union[str, Any]						=   (sigmas_next**2 - sigmas_up**2) ** 0.5
           lowerCAmelCase_					:	int						=   0.0

           # compute interpolated sigmas
           lowerCAmelCase_					:	str						=   sigmas.log().lerp(sigmas_down.log()					,			0.5			).exp()
           lowerCAmelCase_					:	Dict						=   0.0

           # set sigmas
           lowerCAmelCase_					:	Union[str, Any]						=   torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2			), sigmas[-1:]]			)
           lowerCAmelCase_					:	List[str]						=   torch.cat(
               [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2			), sigmas_interpol[-1:]]			)
           lowerCAmelCase_					:	List[str]						=   torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2			), sigmas_up[-1:]]			)
           lowerCAmelCase_					:	Union[str, Any]						=   torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2			), sigmas_down[-1:]]			)

           if str(UpperCAmelCase			).startswith("""mps"""			):
               # mps does not support float64
               lowerCAmelCase_					:	List[Any]						=   torch.from_numpy(UpperCAmelCase			).to(UpperCAmelCase					,			dtype=torch.floataa			)
           else:
               lowerCAmelCase_					:	Optional[Any]						=   torch.from_numpy(UpperCAmelCase			).to(UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[int]						=   self.sigma_to_t(UpperCAmelCase			).to(UpperCAmelCase					,			dtype=timesteps.dtype			)
           lowerCAmelCase_					:	List[str]						=   torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])					,			dim=-1			).flatten()

           lowerCAmelCase_					:	Optional[Any]						=   torch.cat([timesteps[:1], interleaved_timesteps]			)

           lowerCAmelCase_					:	Tuple						=   None

           # for exp beta schedules, such as the one for `pipeline_shap_e.py`
           # we need an index counter
           lowerCAmelCase_					:	int						=   defaultdict(UpperCAmelCase			)



       def  A							(     self	:   Dict					,			UpperCAmelCase	:   List[Any]			):
           # get log sigma
           lowerCAmelCase_					:	str						=   sigma.log()

           # get distribution
           lowerCAmelCase_					:	Dict						=   log_sigma - self.log_sigmas[:, None]

           # get sigmas range
           lowerCAmelCase_					:	List[str]						=   dists.ge(0			).cumsum(dim=0			).argmax(dim=0			).clamp(max=self.log_sigmas.shape[0] - 2			)
           lowerCAmelCase_					:	Optional[int]						=   low_idx + 1

           lowerCAmelCase_					:	int						=   self.log_sigmas[low_idx]
           lowerCAmelCase_					:	Optional[Any]						=   self.log_sigmas[high_idx]

           # interpolate sigmas
           lowerCAmelCase_					:	Optional[int]						=   (low - log_sigma) / (low - high)
           lowerCAmelCase_					:	int						=   w.clamp(0					,			1			)

           # transform interpolation to time range
           lowerCAmelCase_					:	str						=   (1 - w) * low_idx + w * high_idx
           lowerCAmelCase_					:	str						=   t.view(sigma.shape			)
           return t



       @property
       def  A							(     self	:   Union[str, Any]			):
           return self.sample is None



       def  A							(     self	:   Optional[Any]					,			UpperCAmelCase	:   Union[torch.FloatTensor, np.ndarray]					,			UpperCAmelCase	:   Union[float, torch.FloatTensor]					,			UpperCAmelCase	:   Union[torch.FloatTensor, np.ndarray]					,			UpperCAmelCase	:   Optional[torch.Generator] = None					,			UpperCAmelCase	:   bool = True					,			):
           lowerCAmelCase_					:	List[str]						=   self.index_for_timestep(UpperCAmelCase			)

           # advance index counter by 1
           lowerCAmelCase_					:	Optional[Any]						=   timestep.cpu().item() if torch.is_tensor(UpperCAmelCase			) else timestep
           self._index_counter[timestep_int] += 1

           if self.state_in_first_order:
               lowerCAmelCase_					:	str						=   self.sigmas[step_index]
               lowerCAmelCase_					:	Tuple						=   self.sigmas_interpol[step_index]
               lowerCAmelCase_					:	Optional[Any]						=   self.sigmas_up[step_index]
               lowerCAmelCase_					:	Dict						=   self.sigmas_down[step_index - 1]
           else:
               # 2nd order / KPDM2's method
               lowerCAmelCase_					:	Dict						=   self.sigmas[step_index - 1]
               lowerCAmelCase_					:	Dict						=   self.sigmas_interpol[step_index - 1]
               lowerCAmelCase_					:	Union[str, Any]						=   self.sigmas_up[step_index - 1]
               lowerCAmelCase_					:	int						=   self.sigmas_down[step_index - 1]

           # currently only gamma=0 is supported. This usually works best anyways.
           # We can support gamma in the future but then need to scale the timestep before
           # passing it to the model which requires a change in API
           lowerCAmelCase_					:	Optional[int]						=   0
           lowerCAmelCase_					:	List[Any]						=   sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

           lowerCAmelCase_					:	Optional[int]						=   model_output.device
           lowerCAmelCase_					:	Optional[Any]						=   randn_tensor(model_output.shape					,			dtype=model_output.dtype					,			device=UpperCAmelCase					,			generator=UpperCAmelCase			)

           # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
           if self.config.prediction_type == "epsilon":
               lowerCAmelCase_					:	str						=   sigma_hat if self.state_in_first_order else sigma_interpol
               lowerCAmelCase_					:	Optional[Any]						=   sample - sigma_input * model_output
           elif self.config.prediction_type == "v_prediction":
               lowerCAmelCase_					:	Optional[int]						=   sigma_hat if self.state_in_first_order else sigma_interpol
               lowerCAmelCase_					:	Tuple						=   model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
                   sample / (sigma_input**2 + 1)
               )
           elif self.config.prediction_type == "sample":
               raise NotImplementedError("""prediction_type not implemented yet: sample"""			)
           else:
               raise ValueError(
                   F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'			)

           if self.state_in_first_order:
               # 2. Convert to an ODE derivative for 1st order
               lowerCAmelCase_					:	List[Any]						=   (sample - pred_original_sample) / sigma_hat
               # 3. delta timestep
               lowerCAmelCase_					:	Tuple						=   sigma_interpol - sigma_hat

               # store for 2nd order step
               lowerCAmelCase_					:	Optional[int]						=   sample
               lowerCAmelCase_					:	Optional[int]						=   dt
               lowerCAmelCase_					:	Any						=   sample + derivative * dt
           else:
               # DPM-Solver-2
               # 2. Convert to an ODE derivative for 2nd order
               lowerCAmelCase_					:	Tuple						=   (sample - pred_original_sample) / sigma_interpol
               # 3. delta timestep
               lowerCAmelCase_					:	int						=   sigma_down - sigma_hat

               lowerCAmelCase_					:	Optional[Any]						=   self.sample
               lowerCAmelCase_					:	Any						=   None

               lowerCAmelCase_					:	Optional[Any]						=   sample + derivative * dt
               lowerCAmelCase_					:	Dict						=   prev_sample + noise * sigma_up

           if not return_dict:
               return (prev_sample,)

           return SchedulerOutput(prev_sample=UpperCAmelCase			)



       def  A							(     self	:   str					,			UpperCAmelCase	:   torch.FloatTensor					,			UpperCAmelCase	:   torch.FloatTensor					,			UpperCAmelCase	:   torch.FloatTensor					,			):
           # Make sure sigmas and timesteps have the same device and dtype as original_samples
           lowerCAmelCase_					:	Tuple						=   self.sigmas.to(device=original_samples.device					,			dtype=original_samples.dtype			)
           if original_samples.device.type == "mps" and torch.is_floating_point(UpperCAmelCase			):
               # mps does not support float64
               lowerCAmelCase_					:	Union[str, Any]						=   self.timesteps.to(original_samples.device					,			dtype=torch.floataa			)
               lowerCAmelCase_					:	Dict						=   timesteps.to(original_samples.device					,			dtype=torch.floataa			)
           else:
               lowerCAmelCase_					:	str						=   self.timesteps.to(original_samples.device			)
               lowerCAmelCase_					:	int						=   timesteps.to(original_samples.device			)

           lowerCAmelCase_					:	List[str]						=   [self.index_for_timestep(UpperCAmelCase					,			UpperCAmelCase			) for t in timesteps]

           lowerCAmelCase_					:	Any						=   sigmas[step_indices].flatten()
           while len(sigma.shape			) < len(original_samples.shape			):
               lowerCAmelCase_					:	List[str]						=   sigma.unsqueeze(-1			)

           lowerCAmelCase_					:	str						=   original_samples + noise * sigma
           return noisy_samples



       def __len__(     self	:   Optional[int]			):
           return self.config.num_train_timesteps









import gc
import os
import tempfile
import unittest

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, StableDiffusionPipeline, UNetaDConditionModel
from diffusers.loaders import AttnProcsLayers, LoraLoaderMixin
from diffusers.models.attention_processor import (
    Attention,
    AttnProcessor,
    AttnProcessor2_0,
    LoRAAttnProcessor,
    LoRAAttnProcessor2_0,
    LoRAXFormersAttnProcessor,
    XFormersAttnProcessor,
)
from diffusers.utils import TEXT_ENCODER_ATTN_MODULE, floats_tensor, torch_device
def 			__UpperCamelCase				(			lowercase__	:       nn.Module		)	->      str:
    '''simple docstring'''





    lowerCAmelCase_					:	List[Any]						=   {}
    for name in unet.attn_processors.keys():
        lowerCAmelCase_					:	str						=   None if name.endswith("""attn1.processor"""		) else unet.config.cross_attention_dim
        if name.startswith("""mid_block"""		):
            lowerCAmelCase_					:	List[str]						=   unet.config.block_out_channels[-1]
        elif name.startswith("""up_blocks"""		):
            lowerCAmelCase_					:	Any						=   int(name[len("""up_blocks."""		)]		)
            lowerCAmelCase_					:	Any						=   list(reversed(unet.config.block_out_channels		)		)[block_id]
        elif name.startswith("""down_blocks"""		):
            lowerCAmelCase_					:	Dict						=   int(name[len("""down_blocks."""		)]		)
            lowerCAmelCase_					:	Union[str, Any]						=   unet.config.block_out_channels[block_id]
        lowerCAmelCase_					:	List[str]						=   (
            LoRAAttnProcessor2_0 if hasattr(lowercase__		,    """scaled_dot_product_attention"""		) else LoRAAttnProcessor
        )
        lowerCAmelCase_					:	Any						=   lora_attn_processor_class(
            hidden_size=lowercase__		,    cross_attention_dim=lowercase__		)
    lowerCAmelCase_					:	Optional[Any]						=   AttnProcsLayers(lowercase__		)
    return lora_attn_procs, unet_lora_layers
def 			__UpperCamelCase				(			lowercase__	:       nn.Module		)	->      str:
    '''simple docstring'''





    lowerCAmelCase_					:	Optional[int]						=   {}
    lowerCAmelCase_					:	str						=   (
        LoRAAttnProcessor2_0 if hasattr(lowercase__		,    """scaled_dot_product_attention"""		) else LoRAAttnProcessor
    )
    for name, module in text_encoder.named_modules():
        if name.endswith(lowercase__		):
            lowerCAmelCase_					:	Optional[int]						=   lora_attn_processor_class(
                hidden_size=module.out_proj.out_features		,    cross_attention_dim=lowercase__		)
    return text_lora_attn_procs
def 			__UpperCamelCase				(			lowercase__	:       nn.Module		)	->      List[str]:
    '''simple docstring'''





    lowerCAmelCase_					:	int						=   create_text_encoder_lora_attn_procs(lowercase__		)
    lowerCAmelCase_					:	str						=   AttnProcsLayers(lowercase__		)
    return text_encoder_lora_layers
def 			__UpperCamelCase				(			lowercase__	:       int		,    lowercase__	:       Union[str, Any]=False		)	->      Any:
    '''simple docstring'''





    for _, attn_proc in text_lora_attn_procs.items():
        # set up.weights
        for layer_name, layer_module in attn_proc.named_modules():
            if layer_name.endswith("""_lora"""		):
                lowerCAmelCase_					:	Union[str, Any]						=   (
                    torch.randn_like(layer_module.up.weight		)
                    if randn_weight
                    else torch.zeros_like(layer_module.up.weight		)
                )
                lowerCAmelCase_					:	Optional[Any]						=   torch.nn.Parameter(lowercase__		)

class 		__a							(	unittest.TestCase      ):



       def  A							(     self	:   List[Any]			):
           torch.manual_seed(0			)
           lowerCAmelCase_					:	Any						=   UNetaDConditionModel(
               block_out_channels=(32, 64)					,			layers_per_block=2					,			sample_size=32					,			in_channels=4					,			out_channels=4					,			down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")					,			up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")					,			cross_attention_dim=32					,			)
           lowerCAmelCase_					:	Dict						=   DDIMScheduler(
               beta_start=0.0_0085					,			beta_end=0.012					,			beta_schedule="""scaled_linear"""					,			clip_sample=UpperCAmelCase					,			set_alpha_to_one=UpperCAmelCase					,			steps_offset=1					,			)
           torch.manual_seed(0			)
           lowerCAmelCase_					:	List[str]						=   AutoencoderKL(
               block_out_channels=[32, 64]					,			in_channels=3					,			out_channels=3					,			down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]					,			up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]					,			latent_channels=4					,			)
           lowerCAmelCase_					:	int						=   CLIPTextConfig(
               bos_token_id=0					,			eos_token_id=2					,			hidden_size=32					,			intermediate_size=37					,			layer_norm_eps=1e-0_5					,			num_attention_heads=4					,			num_hidden_layers=5					,			pad_token_id=1					,			vocab_size=10_00					,			)
           lowerCAmelCase_					:	str						=   CLIPTextModel(UpperCAmelCase			)
           lowerCAmelCase_					:	Union[str, Any]						=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)

           lowerCAmelCase_		,		lowerCAmelCase_					:	Union[str, Any]						=   create_unet_lora_layers(UpperCAmelCase			)
           lowerCAmelCase_					:	int						=   create_text_encoder_lora_layers(UpperCAmelCase			)

           lowerCAmelCase_					:	str						=   {
               """unet""": unet,
               """scheduler""": scheduler,
               """vae""": vae,
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
               """safety_checker""": None,
               """feature_extractor""": None,
           }
           lowerCAmelCase_					:	List[Any]						=   {
               """unet_lora_layers""": unet_lora_layers,
               """text_encoder_lora_layers""": text_encoder_lora_layers,
               """unet_lora_attn_procs""": unet_lora_attn_procs,
           }
           return pipeline_components, lora_components



       def  A							(     self	:   Tuple			):
           lowerCAmelCase_					:	Dict						=   1
           lowerCAmelCase_					:	Optional[Any]						=   10
           lowerCAmelCase_					:	List[str]						=   4
           lowerCAmelCase_					:	Tuple						=   (32, 32)

           lowerCAmelCase_					:	int						=   torch.manual_seed(0			)
           lowerCAmelCase_					:	str						=   floats_tensor((batch_size, num_channels) + sizes			)
           lowerCAmelCase_					:	int						=   torch.randint(1					,			UpperCAmelCase					,			size=(batch_size, sequence_length)					,			generator=UpperCAmelCase			)

           lowerCAmelCase_					:	Union[str, Any]						=   {
               """prompt""": """A painting of a squirrel eating a burger""",
               """generator""": generator,
               """num_inference_steps""": 2,
               """guidance_scale""": 6.0,
               """output_type""": """numpy""",
           }

           return noise, input_ids, pipeline_inputs

           # copied from: https://colab.research.google.com/gist/sayakpaul/df2ef6e1ae6d8c10a49d859883b10860/scratchpad.ipynb



       def  A							(     self	:   Dict			):
           lowerCAmelCase_					:	Union[str, Any]						=   77

           lowerCAmelCase_					:	List[Any]						=   torch.randint(2					,			56					,			size=(1, max_seq_length)					,			generator=torch.manual_seed(0			)			)

           lowerCAmelCase_					:	List[Any]						=   {}
           lowerCAmelCase_					:	Optional[Any]						=   inputs
           return prepared_inputs



       def  A							(     self	:   List[str]					,			UpperCAmelCase	:   List[str]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	List[Any]						=   self.get_dummy_components()
           LoraLoaderMixin.save_lora_weights(
               save_directory=UpperCAmelCase					,			unet_lora_layers=lora_components["""unet_lora_layers"""]					,			text_encoder_lora_layers=lora_components["""text_encoder_lora_layers"""]					,			)
           self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.bin"""			)			)			)



       def  A							(     self	:   Optional[int]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[Any]						=   self.get_dummy_components()
           lowerCAmelCase_					:	Optional[Any]						=   StableDiffusionPipeline(**UpperCAmelCase			)
           lowerCAmelCase_					:	str						=   sd_pipe.to(UpperCAmelCase			)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	List[Any]						=   self.get_dummy_inputs()

           lowerCAmelCase_					:	Tuple						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	Dict						=   original_images[0, -3:, -3:, -1]

           with tempfile.TemporaryDirectory() as tmpdirname:
               LoraLoaderMixin.save_lora_weights(
                   save_directory=UpperCAmelCase					,			unet_lora_layers=lora_components["""unet_lora_layers"""]					,			text_encoder_lora_layers=lora_components["""text_encoder_lora_layers"""]					,			)
               self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.bin"""			)			)			)
               sd_pipe.load_lora_weights(UpperCAmelCase			)

           lowerCAmelCase_					:	Any						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	Any						=   lora_images[0, -3:, -3:, -1]

           # Outputs shouldn't match.
           self.assertFalse(torch.allclose(torch.from_numpy(UpperCAmelCase			)					,			torch.from_numpy(UpperCAmelCase			)			)			)



       def  A							(     self	:   Tuple			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[Any]						=   self.get_dummy_components()
           lowerCAmelCase_					:	Union[str, Any]						=   StableDiffusionPipeline(**UpperCAmelCase			)
           lowerCAmelCase_					:	Optional[Any]						=   sd_pipe.to(UpperCAmelCase			)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[Any]						=   self.get_dummy_inputs()

           lowerCAmelCase_					:	Optional[int]						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	int						=   original_images[0, -3:, -3:, -1]

           with tempfile.TemporaryDirectory() as tmpdirname:
               LoraLoaderMixin.save_lora_weights(
                   save_directory=UpperCAmelCase					,			unet_lora_layers=lora_components["""unet_lora_layers"""]					,			text_encoder_lora_layers=lora_components["""text_encoder_lora_layers"""]					,			safe_serialization=UpperCAmelCase					,			)
               self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.safetensors"""			)			)			)
               sd_pipe.load_lora_weights(UpperCAmelCase			)

           lowerCAmelCase_					:	Any						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	List[str]						=   lora_images[0, -3:, -3:, -1]

           # Outputs shouldn't match.
           self.assertFalse(torch.allclose(torch.from_numpy(UpperCAmelCase			)					,			torch.from_numpy(UpperCAmelCase			)			)			)



       def  A							(     self	:   Dict			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[Any]						=   self.get_dummy_components()
           lowerCAmelCase_					:	Any						=   lora_components["""unet_lora_attn_procs"""]
           lowerCAmelCase_					:	str						=   StableDiffusionPipeline(**UpperCAmelCase			)
           lowerCAmelCase_					:	Union[str, Any]						=   sd_pipe.to(UpperCAmelCase			)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	Dict						=   self.get_dummy_inputs()

           lowerCAmelCase_					:	int						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	int						=   original_images[0, -3:, -3:, -1]

           with tempfile.TemporaryDirectory() as tmpdirname:
               lowerCAmelCase_					:	List[Any]						=   sd_pipe.unet
               unet.set_attn_processor(UpperCAmelCase			)
               unet.save_attn_procs(UpperCAmelCase			)
               self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.bin"""			)			)			)
               sd_pipe.load_lora_weights(UpperCAmelCase			)

           lowerCAmelCase_					:	List[str]						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	List[str]						=   lora_images[0, -3:, -3:, -1]

           # Outputs shouldn't match.
           self.assertFalse(torch.allclose(torch.from_numpy(UpperCAmelCase			)					,			torch.from_numpy(UpperCAmelCase			)			)			)



       def  A							(     self	:   int			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Dict						=   self.get_dummy_components()
           lowerCAmelCase_					:	Dict						=   StableDiffusionPipeline(**UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[int]						=   self.get_dummy_tokens()

           # inference without lora
           lowerCAmelCase_					:	List[Any]						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_without_lora.shape == (1, 77, 32)

           # create lora_attn_procs with zeroed out up.weights
           lowerCAmelCase_					:	Tuple						=   create_text_encoder_lora_attn_procs(pipe.text_encoder			)
           set_lora_up_weights(UpperCAmelCase					,			randn_weight=UpperCAmelCase			)

           # monkey patch
           pipe._modify_text_encoder(UpperCAmelCase			)

           # verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
           del text_attn_procs
           gc.collect()

           # inference with lora
           lowerCAmelCase_					:	str						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_with_lora.shape == (1, 77, 32)

           assert torch.allclose(
               UpperCAmelCase					,			UpperCAmelCase			), "lora_up_weight are all zero, so the lora outputs should be the same to without lora outputs"

           # create lora_attn_procs with randn up.weights
           lowerCAmelCase_					:	Optional[Any]						=   create_text_encoder_lora_attn_procs(pipe.text_encoder			)
           set_lora_up_weights(UpperCAmelCase					,			randn_weight=UpperCAmelCase			)

           # monkey patch
           pipe._modify_text_encoder(UpperCAmelCase			)

           # verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
           del text_attn_procs
           gc.collect()

           # inference with lora
           lowerCAmelCase_					:	Optional[int]						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_with_lora.shape == (1, 77, 32)

           assert not torch.allclose(
               UpperCAmelCase					,			UpperCAmelCase			), "lora_up_weight are not zero, so the lora outputs should be different to without lora outputs"



       def  A							(     self	:   Union[str, Any]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[int]						=   self.get_dummy_components()
           lowerCAmelCase_					:	List[Any]						=   StableDiffusionPipeline(**UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[Any]						=   self.get_dummy_tokens()

           # inference without lora
           lowerCAmelCase_					:	Optional[Any]						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_without_lora.shape == (1, 77, 32)

           # create lora_attn_procs with randn up.weights
           lowerCAmelCase_					:	int						=   create_text_encoder_lora_attn_procs(pipe.text_encoder			)
           set_lora_up_weights(UpperCAmelCase					,			randn_weight=UpperCAmelCase			)

           # monkey patch
           pipe._modify_text_encoder(UpperCAmelCase			)

           # verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
           del text_attn_procs
           gc.collect()

           # inference with lora
           lowerCAmelCase_					:	List[str]						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_with_lora.shape == (1, 77, 32)

           assert not torch.allclose(
               UpperCAmelCase					,			UpperCAmelCase			), "lora outputs should be different to without lora outputs"

           # remove monkey patch
           pipe._remove_text_encoder_monkey_patch()

           # inference with removed lora
           lowerCAmelCase_					:	Tuple						=   pipe.text_encoder(**UpperCAmelCase			)[0]
           assert outputs_without_lora_removed.shape == (1, 77, 32)

           assert torch.allclose(
               UpperCAmelCase					,			UpperCAmelCase			), "remove lora monkey patch should restore the original outputs"



       def  A							(     self	:   Any			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Any						=   self.get_dummy_components()
           lowerCAmelCase_					:	int						=   StableDiffusionPipeline(**UpperCAmelCase			)
           lowerCAmelCase_					:	int						=   sd_pipe.to(UpperCAmelCase			)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[int]						=   self.get_dummy_inputs()

           with tempfile.TemporaryDirectory() as tmpdirname:
               LoraLoaderMixin.save_lora_weights(
                   save_directory=UpperCAmelCase					,			unet_lora_layers=lora_components["""unet_lora_layers"""]					,			text_encoder_lora_layers=lora_components["""text_encoder_lora_layers"""]					,			)
               self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.bin"""			)			)			)
               sd_pipe.load_lora_weights(UpperCAmelCase			)

           lowerCAmelCase_					:	Any						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	Optional[int]						=   lora_images[0, -3:, -3:, -1]

           lowerCAmelCase_					:	Dict						=   sd_pipe(**UpperCAmelCase					,			cross_attention_kwargs={"""scale""": 0.5}			).images
           lowerCAmelCase_					:	str						=   lora_images_with_scale[0, -3:, -3:, -1]

           # Outputs shouldn't match.
           self.assertFalse(
               torch.allclose(torch.from_numpy(UpperCAmelCase			)					,			torch.from_numpy(UpperCAmelCase			)			)			)



       def  A							(     self	:   List[str]			):
           with tempfile.TemporaryDirectory() as tmpdirname:
               self.create_lora_weight_file(UpperCAmelCase			)

               lowerCAmelCase_		,		lowerCAmelCase_					:	List[str]						=   self.get_dummy_components()
               lowerCAmelCase_					:	int						=   StableDiffusionPipeline(**UpperCAmelCase			)
               lowerCAmelCase_					:	Union[str, Any]						=   sd_pipe.to(UpperCAmelCase			)
               sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

               # check if vanilla attention processors are used
               for _, module in sd_pipe.unet.named_modules():
                   if isinstance(UpperCAmelCase					,			UpperCAmelCase			):
                       self.assertIsInstance(module.processor					,			(AttnProcessor, AttnProcessor2_0)			)

            # load LoRA weight file
               sd_pipe.load_lora_weights(UpperCAmelCase			)

               # check if lora attention processors are used
               for _, module in sd_pipe.unet.named_modules():
                   if isinstance(UpperCAmelCase					,			UpperCAmelCase			):
                       lowerCAmelCase_					:	Optional[int]						=   (
                           LoRAAttnProcessor2_0 if hasattr(UpperCAmelCase					,			"""scaled_dot_product_attention"""			) else LoRAAttnProcessor
                       )
                       self.assertIsInstance(module.processor					,			UpperCAmelCase			)



       @unittest.skipIf(torch_device != """cuda"""					,			"""This test is supposed to run on GPU"""			)
       def  A							(     self	:   Any			):
           with tempfile.TemporaryDirectory() as tmpdirname:
               self.create_lora_weight_file(UpperCAmelCase			)

               lowerCAmelCase_		,		lowerCAmelCase_					:	List[str]						=   self.get_dummy_components()
               lowerCAmelCase_					:	Any						=   StableDiffusionPipeline(**UpperCAmelCase			)
               lowerCAmelCase_					:	List[str]						=   sd_pipe.to(UpperCAmelCase			)
               sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

               # enable XFormers
               sd_pipe.enable_xformers_memory_efficient_attention()

               # check if xFormers attention processors are used
               for _, module in sd_pipe.unet.named_modules():
                   if isinstance(UpperCAmelCase					,			UpperCAmelCase			):
                       self.assertIsInstance(module.processor					,			UpperCAmelCase			)

            # load LoRA weight file
               sd_pipe.load_lora_weights(UpperCAmelCase			)

               # check if lora attention processors are used
               for _, module in sd_pipe.unet.named_modules():
                   if isinstance(UpperCAmelCase					,			UpperCAmelCase			):
                       self.assertIsInstance(module.processor					,			UpperCAmelCase			)



       @unittest.skipIf(torch_device != """cuda"""					,			"""This test is supposed to run on GPU"""			)
       def  A							(     self	:   List[str]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	int						=   self.get_dummy_components()
           lowerCAmelCase_					:	Optional[int]						=   StableDiffusionPipeline(**UpperCAmelCase			)
           lowerCAmelCase_					:	Dict						=   sd_pipe.to(UpperCAmelCase			)
           sd_pipe.set_progress_bar_config(disable=UpperCAmelCase			)

           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	List[str]						=   self.get_dummy_inputs()

           # enable XFormers
           sd_pipe.enable_xformers_memory_efficient_attention()

           lowerCAmelCase_					:	Any						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	Union[str, Any]						=   original_images[0, -3:, -3:, -1]

           with tempfile.TemporaryDirectory() as tmpdirname:
               LoraLoaderMixin.save_lora_weights(
                   save_directory=UpperCAmelCase					,			unet_lora_layers=lora_components["""unet_lora_layers"""]					,			text_encoder_lora_layers=lora_components["""text_encoder_lora_layers"""]					,			)
               self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase					,			"""pytorch_lora_weights.bin"""			)			)			)
               sd_pipe.load_lora_weights(UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[Any]						=   sd_pipe(**UpperCAmelCase			).images
           lowerCAmelCase_					:	Union[str, Any]						=   lora_images[0, -3:, -3:, -1]

           # Outputs shouldn't match.
           self.assertFalse(torch.allclose(torch.from_numpy(UpperCAmelCase			)					,			torch.from_numpy(UpperCAmelCase			)			)			)


