'''simple docstring'''
import argparse

import requests
import torch
from PIL import Image

from transformers import (
    CLIPSegConfig,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPSegTextConfig,
    CLIPSegVisionConfig,
    CLIPTokenizer,
    ViTImageProcessor,
)







def 			_UpperCamelCase			(  _a						:						List[Any]      ):




    """simple docstring"""



    __UpperCamelCase						:						Tuple		     =	CLIPSegTextConfig()
    __UpperCamelCase						:						List[Any]		     =	CLIPSegVisionConfig(patch_size=1_6      )

    __UpperCamelCase						:						Optional[Any]		     =	True if 'refined' in model_name else False
    __UpperCamelCase						:						Optional[Any]		     =	1_6 if 'rd16' in model_name else 6_4

    __UpperCamelCase						:						int		     =	CLIPSegConfig.from_text_vision_configs(
        _a					,  _a					,  use_complex_transposed_convolution=_a					,  reduce_dim=_a					,  )
    return config







def 			_UpperCamelCase			(  _a						:						Optional[Any]      ):




    """simple docstring"""



    if "clip_model" in name:
        __UpperCamelCase						:						Optional[int]		     =	name.replace('clip_model'					,  'clip'      )
    if "transformer" in name:
        if "visual" in name:
            __UpperCamelCase						:						str		     =	name.replace('visual.transformer'					,  'vision_model'      )
        else:
            __UpperCamelCase						:						Any		     =	name.replace('transformer'					,  'text_model'      )
    if "resblocks" in name:
        __UpperCamelCase						:						Optional[int]		     =	name.replace('resblocks'					,  'encoder.layers'      )
    if "ln_1" in name:
        __UpperCamelCase						:						List[Any]		     =	name.replace('ln_1'					,  'layer_norm1'      )
    if "ln_2" in name:
        __UpperCamelCase						:						Any		     =	name.replace('ln_2'					,  'layer_norm2'      )
    if "c_fc" in name:
        __UpperCamelCase						:						int		     =	name.replace('c_fc'					,  'fc1'      )
    if "c_proj" in name:
        __UpperCamelCase						:						int		     =	name.replace('c_proj'					,  'fc2'      )
    if "attn" in name and "self" not in name:
        __UpperCamelCase						:						Dict		     =	name.replace('attn'					,  'self_attn'      )
    # text encoder
    if "token_embedding" in name:
        __UpperCamelCase						:						str		     =	name.replace('token_embedding'					,  'text_model.embeddings.token_embedding'      )
    if "positional_embedding" in name and "visual" not in name:
        __UpperCamelCase						:						Any		     =	name.replace('positional_embedding'					,  'text_model.embeddings.position_embedding.weight'      )
    if "ln_final" in name:
        __UpperCamelCase						:						Union[str, Any]		     =	name.replace('ln_final'					,  'text_model.final_layer_norm'      )
    # vision encoder
    if "visual.class_embedding" in name:
        __UpperCamelCase						:						str		     =	name.replace('visual.class_embedding'					,  'vision_model.embeddings.class_embedding'      )
    if "visual.conv1" in name:
        __UpperCamelCase						:						Tuple		     =	name.replace('visual.conv1'					,  'vision_model.embeddings.patch_embedding'      )
    if "visual.positional_embedding" in name:
        __UpperCamelCase						:						int		     =	name.replace('visual.positional_embedding'					,  'vision_model.embeddings.position_embedding.weight'      )
    if "visual.ln_pre" in name:
        __UpperCamelCase						:						Union[str, Any]		     =	name.replace('visual.ln_pre'					,  'vision_model.pre_layrnorm'      )
    if "visual.ln_post" in name:
        __UpperCamelCase						:						Tuple		     =	name.replace('visual.ln_post'					,  'vision_model.post_layernorm'      )
    # projection layers
    if "visual.proj" in name:
        __UpperCamelCase						:						Any		     =	name.replace('visual.proj'					,  'visual_projection.weight'      )
    if "text_projection" in name:
        __UpperCamelCase						:						Optional[int]		     =	name.replace('text_projection'					,  'text_projection.weight'      )
    # decoder
    if "trans_conv" in name:
        __UpperCamelCase						:						Optional[Any]		     =	name.replace('trans_conv'					,  'transposed_convolution'      )
    if "film_mul" in name or "film_add" in name or "reduce" in name or "transposed_convolution" in name:
        __UpperCamelCase						:						str		     =	'decoder.' + name
    if "blocks" in name:
        __UpperCamelCase						:						Optional[Any]		     =	name.replace('blocks'					,  'decoder.layers'      )
    if "linear1" in name:
        __UpperCamelCase						:						Tuple		     =	name.replace('linear1'					,  'mlp.fc1'      )
    if "linear2" in name:
        __UpperCamelCase						:						Any		     =	name.replace('linear2'					,  'mlp.fc2'      )
    if "norm1" in name and "layer_" not in name:
        __UpperCamelCase						:						Union[str, Any]		     =	name.replace('norm1'					,  'layer_norm1'      )
    if "norm2" in name and "layer_" not in name:
        __UpperCamelCase						:						str		     =	name.replace('norm2'					,  'layer_norm2'      )

    return name







def 			_UpperCamelCase			(  _a						:						List[str]					,  _a						:						int      ):




    """simple docstring"""



    for key in orig_state_dict.copy().keys():
        __UpperCamelCase						:						str		     =	orig_state_dict.pop(_a      )

        if key.startswith('clip_model'      ) and "attn.in_proj" in key:
            __UpperCamelCase						:						Tuple		     =	key.split('.'      )
            if "visual" in key:
                __UpperCamelCase						:						Dict		     =	int(key_split[4]      )
                __UpperCamelCase						:						Union[str, Any]		     =	config.vision_config.hidden_size
                __UpperCamelCase						:						Dict		     =	'vision_model'
            else:
                __UpperCamelCase						:						str		     =	int(key_split[3]      )
                __UpperCamelCase						:						Optional[int]		     =	config.text_config.hidden_size
                __UpperCamelCase						:						int		     =	'text_model'

            if "weight" in key:
                __UpperCamelCase						:						Optional[Any]		     =	val[:dim, :]
                __UpperCamelCase						:						Optional[Any]		     =	val[
                    dim : dim * 2, :
                ]
                __UpperCamelCase						:						Union[str, Any]		     =	val[-dim:, :]
            else:
                __UpperCamelCase						:						Tuple		     =	val[:dim]
                __UpperCamelCase						:						Union[str, Any]		     =	val[dim : dim * 2]
                __UpperCamelCase						:						Any		     =	val[-dim:]
        elif "self_attn" in key and "out_proj" not in key:
            __UpperCamelCase						:						List[str]		     =	key.split('.'      )
            __UpperCamelCase						:						int		     =	int(key_split[1]      )
            __UpperCamelCase						:						Optional[Any]		     =	config.reduce_dim
            if "weight" in key:
                __UpperCamelCase						:						Tuple		     =	val[:dim, :]
                __UpperCamelCase						:						Dict		     =	val[dim : dim * 2, :]
                __UpperCamelCase						:						Tuple		     =	val[-dim:, :]
            else:
                __UpperCamelCase						:						List[str]		     =	val[:dim]
                __UpperCamelCase						:						Dict		     =	val[dim : dim * 2]
                __UpperCamelCase						:						str		     =	val[-dim:]
        else:
            __UpperCamelCase						:						Union[str, Any]		     =	rename_key(_a      )
            if "visual_projection" in new_name or "text_projection" in new_name:
                __UpperCamelCase						:						int		     =	val.T
            __UpperCamelCase						:						int		     =	val

    return orig_state_dict







def 			_UpperCamelCase			(  ):




    """simple docstring"""



    __UpperCamelCase						:						List[Any]		     =	'http://images.cocodataset.org/val2017/000000039769.jpg'
    __UpperCamelCase						:						Tuple		     =	Image.open(requests.get(_a					,  stream=_a      ).raw      )
    return image







def 			_UpperCamelCase			(  _a						:						int					,  _a						:						List[Any]					,  _a						:						List[Any]					,  _a						:						List[Any]      ):




    """simple docstring"""



    __UpperCamelCase						:						Tuple		     =	get_clipseg_config(_a      )
    __UpperCamelCase						:						Optional[Any]		     =	CLIPSegForImageSegmentation(_a      )
    model.eval()

    __UpperCamelCase						:						Tuple		     =	torch.load(_a					,  map_location='cpu'      )

    # remove some keys
    for key in state_dict.copy().keys():
        if key.startswith('model'      ):
            state_dict.pop(_a					,  _a      )

    # rename some keys
    __UpperCamelCase						:						Any		     =	convert_state_dict(_a					,  _a      )
    __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	model.load_state_dict(_a					,  strict=_a      )

    if missing_keys != ["clip.text_model.embeddings.position_ids", "clip.vision_model.embeddings.position_ids"]:
        raise ValueError('Missing keys that are not expected: {}'.format(_a      )      )
    if unexpected_keys != ["decoder.reduce.weight", "decoder.reduce.bias"]:
        raise ValueError(f"""Unexpected keys: {unexpected_keys}"""      )

    __UpperCamelCase						:						Dict		     =	ViTImageProcessor(size=3_5_2      )
    __UpperCamelCase						:						List[str]		     =	CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32'      )
    __UpperCamelCase						:						Optional[Any]		     =	CLIPSegProcessor(image_processor=_a					,  tokenizer=_a      )

    __UpperCamelCase						:						str		     =	prepare_img()
    __UpperCamelCase						:						List[str]		     =	['a glass', 'something to fill', 'wood', 'a jar']

    __UpperCamelCase						:						Tuple		     =	processor(text=_a					,  images=[image] * len(_a      )					,  padding='max_length'					,  return_tensors='pt'      )

    with torch.no_grad():
        __UpperCamelCase						:						str		     =	model(**_a      )

    # verify values
    __UpperCamelCase						:						Any		     =	torch.tensor([0.1110, -0.1882, 0.1645]      )
    __UpperCamelCase						:						List[str]		     =	torch.tensor([0.2692, -0.7197, -0.1328]      )
    if model_name == "clipseg-rd64-refined":
        __UpperCamelCase						:						List[Any]		     =	torch.tensor(
            [[-10.0407, -9.9431, -10.2646], [-9.9751, -9.7064, -9.9586], [-9.6891, -9.5645, -9.9618]]      )
    elif model_name == "clipseg-rd64":
        __UpperCamelCase						:						Union[str, Any]		     =	torch.tensor(
            [[-7.2877, -7.2711, -7.2463], [-7.2652, -7.2780, -7.2520], [-7.2239, -7.2204, -7.2001]]      )
    elif model_name == "clipseg-rd16":
        __UpperCamelCase						:						Union[str, Any]		     =	torch.tensor(
            [[-6.3955, -6.4055, -6.4151], [-6.3911, -6.4033, -6.4100], [-6.3474, -6.3702, -6.3762]]      )
    else:
        raise ValueError(f"""Model name {model_name} not supported."""      )

    assert torch.allclose(outputs.logits[0, :3, :3]					,  _a					,  atol=1E-3      )
    assert torch.allclose(outputs.conditional_embeddings[0, :3]					,  _a					,  atol=1E-3      )
    assert torch.allclose(outputs.pooled_output[0, :3]					,  _a					,  atol=1E-3      )
    print('Looks ok!'      )

    if pytorch_dump_folder_path is not None:
        print(f"""Saving model and processor to {pytorch_dump_folder_path}"""      )
        model.save_pretrained(_a      )
        processor.save_pretrained(_a      )

    if push_to_hub:
        print(f"""Pushing model and processor for {model_name} to the hub"""      )
        model.push_to_hub(f"""CIDAS/{model_name}"""      )
        processor.push_to_hub(f"""CIDAS/{model_name}"""      )


if __name__ == "__main__":
  a=	argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--model_name''',
      default='''clipseg-rd64''',
      type=str,
      choices=['''clipseg-rd16''', '''clipseg-rd64''', '''clipseg-rd64-refined'''],
      help=(
          '''Name of the model. Supported models are: clipseg-rd64, clipseg-rd16 and clipseg-rd64-refined (rd meaning'''
          ''' reduce dimension)'''
      ),
  )
  parser.add_argument(
      '''--checkpoint_path''',
      default='''/Users/nielsrogge/Documents/CLIPSeg/clip_plus_rd64-uni.pth''',
      type=str,
      help=(
          '''Path to the original checkpoint. Note that the script assumes that the checkpoint includes both CLIP and'''
          ''' the decoder weights.'''
      ),
  )
  parser.add_argument(
      '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
  )
  parser.add_argument(
      '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
  )

  a=	parser.parse_args()
  convert_clipseg_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)




'''simple docstring'''
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			(  _a						:						nn.Module      ):




    """simple docstring"""



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







def 			_UpperCamelCase			(  _a						:						nn.Module      ):




    """simple docstring"""



    __UpperCamelCase						:						Optional[int]		     =	{}
    __UpperCamelCase						:						List[str]		     =	(
        LoRAAttnProcessor2_0 if hasattr(_a					,  'scaled_dot_product_attention'      ) else LoRAAttnProcessor
    )
    for name, module in text_encoder.named_modules():
        if name.endswith(_a      ):
            __UpperCamelCase						:						List[Any]		     =	lora_attn_processor_class(
                hidden_size=module.out_proj.out_features					,  cross_attention_dim=_a      )
    return text_lora_attn_procs







def 			_UpperCamelCase			(  _a						:						nn.Module      ):




    """simple docstring"""



    __UpperCamelCase						:						Optional[Any]		     =	create_text_encoder_lora_attn_procs(_a      )
    __UpperCamelCase						:						Any		     =	AttnProcsLayers(_a      )
    return text_encoder_lora_layers







def 			_UpperCamelCase			(  _a						:						int					,  _a						:						List[Any]=False      ):




    """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'      ):
                __UpperCamelCase						:						List[str]		     =	(
                    torch.randn_like(layer_module.up.weight      )
                    if randn_weight
                    else torch.zeros_like(layer_module.up.weight      )
                )
                __UpperCamelCase						:						Any		     =	torch.nn.Parameter(_a      )






class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=4  ,      out_channels=4  ,      down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,      up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,      cross_attention_dim=3_2  ,      )
         __UpperCamelCase						:						int		     =	DDIMScheduler(
             beta_start=0.0_0_0_8_5  ,      beta_end=0.0_1_2  ,      beta_schedule='scaled_linear'  ,      clip_sample=_lowerCamelCase  ,      set_alpha_to_one=_lowerCamelCase  ,      steps_offset=1  ,      )
         torch.manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	AutoencoderKL(
             block_out_channels=[3_2, 6_4]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=4  ,      )
         __UpperCamelCase						:						str		     =	CLIPTextConfig(
             bos_token_id=0  ,      eos_token_id=2  ,      hidden_size=3_2  ,      intermediate_size=3_7  ,      layer_norm_eps=1E-0_5  ,      num_attention_heads=4  ,      num_hidden_layers=5  ,      pad_token_id=1  ,      vocab_size=1_0_0_0  ,      )
         __UpperCamelCase						:						List[str]		     =	CLIPTextModel(_lowerCamelCase     )
         __UpperCamelCase						:						int		     =	CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

         __UpperCamelCase     ,       __UpperCamelCase						:						Union[str, Any]		     =	create_unet_lora_layers(_lowerCamelCase     )
         __UpperCamelCase						:						Any		     =	create_text_encoder_lora_layers(_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	{
             'unet': unet,
             'scheduler': scheduler,
             'vae': vae,
             'text_encoder': text_encoder,
             'tokenizer': tokenizer,
             'safety_checker': None,
             'feature_extractor': None,
         }
         __UpperCamelCase						:						List[str]		     =	{
             '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 lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Any		     =	1
         __UpperCamelCase						:						Union[str, Any]		     =	1_0
         __UpperCamelCase						:						Dict		     =	4
         __UpperCamelCase						:						Optional[Any]		     =	(3_2, 3_2)

         __UpperCamelCase						:						Any		     =	torch.manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	floats_tensor((batch_size, num_channels) + sizes     )
         __UpperCamelCase						:						List[str]		     =	torch.randint(1  ,      _lowerCamelCase  ,      size=(batch_size, sequence_length)  ,      generator=_lowerCamelCase     )

         __UpperCamelCase						:						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 lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						int		     =	7_7

         __UpperCamelCase						:						Any		     =	torch.randint(2  ,      5_6  ,      size=(1, max_seq_length)  ,      generator=torch.manual_seed(0     )     )

         __UpperCamelCase						:						List[str]		     =	{}
         __UpperCamelCase						:						Optional[int]		     =	inputs
         return prepared_inputs







     def lowerCAmelCase  (		self  ,      _lowerCamelCase     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						int		     =	self.get_dummy_components()
         LoraLoaderMixin.save_lora_weights(
             save_directory=_lowerCamelCase  ,      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(_lowerCamelCase  ,      'pytorch_lora_weights.bin'     )     )     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						List[str]		     =	self.get_dummy_components()
         __UpperCamelCase						:						List[str]		     =	StableDiffusionPipeline(**_lowerCamelCase     )
         __UpperCamelCase						:						Dict		     =	sd_pipe.to(_lowerCamelCase     )
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Union[str, Any]		     =	self.get_dummy_inputs()

         __UpperCamelCase						:						Any		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						int		     =	original_images[0, -3:, -3:, -1]

         with tempfile.TemporaryDirectory() as tmpdirname:
             LoraLoaderMixin.save_lora_weights(
                 save_directory=_lowerCamelCase  ,      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(_lowerCamelCase  ,      'pytorch_lora_weights.bin'     )     )     )
             sd_pipe.load_lora_weights(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						Optional[int]		     =	lora_images[0, -3:, -3:, -1]

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Tuple		     =	self.get_dummy_components()
         __UpperCamelCase						:						str		     =	StableDiffusionPipeline(**_lowerCamelCase     )
         __UpperCamelCase						:						Union[str, Any]		     =	sd_pipe.to(_lowerCamelCase     )
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Tuple		     =	self.get_dummy_inputs()

         __UpperCamelCase						:						Optional[Any]		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						Optional[int]		     =	original_images[0, -3:, -3:, -1]

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

         __UpperCamelCase						:						Dict		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						Dict		     =	lora_images[0, -3:, -3:, -1]

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						List[str]		     =	self.get_dummy_components()
         __UpperCamelCase						:						List[Any]		     =	lora_components['unet_lora_attn_procs']
         __UpperCamelCase						:						Union[str, Any]		     =	StableDiffusionPipeline(**_lowerCamelCase     )
         __UpperCamelCase						:						int		     =	sd_pipe.to(_lowerCamelCase     )
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						str		     =	self.get_dummy_inputs()

         __UpperCamelCase						:						Dict		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						Dict		     =	original_images[0, -3:, -3:, -1]

         with tempfile.TemporaryDirectory() as tmpdirname:
             __UpperCamelCase						:						Union[str, Any]		     =	sd_pipe.unet
             unet.set_attn_processor(_lowerCamelCase     )
             unet.save_attn_procs(_lowerCamelCase     )
             self.assertTrue(os.path.isfile(os.path.join(_lowerCamelCase  ,      'pytorch_lora_weights.bin'     )     )     )
             sd_pipe.load_lora_weights(_lowerCamelCase     )

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

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Dict		     =	self.get_dummy_components()
         __UpperCamelCase						:						Any		     =	StableDiffusionPipeline(**_lowerCamelCase     )

         __UpperCamelCase						:						Any		     =	self.get_dummy_tokens()

         # inference without lora
         __UpperCamelCase						:						List[str]		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_without_lora.shape == (1, 7_7, 3_2)

         # create lora_attn_procs with zeroed out up.weights
         __UpperCamelCase						:						Any		     =	create_text_encoder_lora_attn_procs(pipe.text_encoder     )
         set_lora_up_weights(_lowerCamelCase  ,      randn_weight=_lowerCamelCase     )

         # monkey patch
         pipe._modify_text_encoder(_lowerCamelCase     )

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

         # inference with lora
         __UpperCamelCase						:						Tuple		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_with_lora.shape == (1, 7_7, 3_2)

         assert torch.allclose(
             _lowerCamelCase  ,      _lowerCamelCase     ), "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
         __UpperCamelCase						:						Optional[int]		     =	create_text_encoder_lora_attn_procs(pipe.text_encoder     )
         set_lora_up_weights(_lowerCamelCase  ,      randn_weight=_lowerCamelCase     )

         # monkey patch
         pipe._modify_text_encoder(_lowerCamelCase     )

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

         # inference with lora
         __UpperCamelCase						:						Optional[int]		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_with_lora.shape == (1, 7_7, 3_2)

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	self.get_dummy_components()
         __UpperCamelCase						:						Any		     =	StableDiffusionPipeline(**_lowerCamelCase     )

         __UpperCamelCase						:						List[Any]		     =	self.get_dummy_tokens()

         # inference without lora
         __UpperCamelCase						:						str		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_without_lora.shape == (1, 7_7, 3_2)

         # create lora_attn_procs with randn up.weights
         __UpperCamelCase						:						Any		     =	create_text_encoder_lora_attn_procs(pipe.text_encoder     )
         set_lora_up_weights(_lowerCamelCase  ,      randn_weight=_lowerCamelCase     )

         # monkey patch
         pipe._modify_text_encoder(_lowerCamelCase     )

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

         # inference with lora
         __UpperCamelCase						:						Any		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_with_lora.shape == (1, 7_7, 3_2)

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

         # remove monkey patch
         pipe._remove_text_encoder_monkey_patch()

         # inference with removed lora
         __UpperCamelCase						:						Dict		     =	pipe.text_encoder(**_lowerCamelCase     )[0]
         assert outputs_without_lora_removed.shape == (1, 7_7, 3_2)

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.get_dummy_components()
         __UpperCamelCase						:						Any		     =	StableDiffusionPipeline(**_lowerCamelCase     )
         __UpperCamelCase						:						List[str]		     =	sd_pipe.to(_lowerCamelCase     )
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						int		     =	self.get_dummy_inputs()

         with tempfile.TemporaryDirectory() as tmpdirname:
             LoraLoaderMixin.save_lora_weights(
                 save_directory=_lowerCamelCase  ,      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(_lowerCamelCase  ,      'pytorch_lora_weights.bin'     )     )     )
             sd_pipe.load_lora_weights(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						List[Any]		     =	lora_images[0, -3:, -3:, -1]

         __UpperCamelCase						:						List[str]		     =	sd_pipe(**_lowerCamelCase  ,      cross_attention_kwargs={'scale': 0.5}     ).images
         __UpperCamelCase						:						Union[str, Any]		     =	lora_images_with_scale[0, -3:, -3:, -1]

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







     def lowerCAmelCase  (		self     ):
         with tempfile.TemporaryDirectory() as tmpdirname:
             self.create_lora_weight_file(_lowerCamelCase     )

             __UpperCamelCase     ,       __UpperCamelCase						:						Dict		     =	self.get_dummy_components()
             __UpperCamelCase						:						Union[str, Any]		     =	StableDiffusionPipeline(**_lowerCamelCase     )
             __UpperCamelCase						:						Tuple		     =	sd_pipe.to(_lowerCamelCase     )
             sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

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

            # load LoRA weight file
             sd_pipe.load_lora_weights(_lowerCamelCase     )

             # check if lora attention processors are used
             for _, module in sd_pipe.unet.named_modules():
                 if isinstance(_lowerCamelCase  ,      _lowerCamelCase     ):
                     __UpperCamelCase						:						Union[str, Any]		     =	(
                         LoRAAttnProcessor2_0 if hasattr(_lowerCamelCase  ,      'scaled_dot_product_attention'     ) else LoRAAttnProcessor
                     )
                     self.assertIsInstance(module.processor  ,      _lowerCamelCase     )







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

             __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	self.get_dummy_components()
             __UpperCamelCase						:						Dict		     =	StableDiffusionPipeline(**_lowerCamelCase     )
             __UpperCamelCase						:						str		     =	sd_pipe.to(_lowerCamelCase     )
             sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

             # 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(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assertIsInstance(module.processor  ,      _lowerCamelCase     )

            # load LoRA weight file
             sd_pipe.load_lora_weights(_lowerCamelCase     )

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







     @unittest.skipIf(torch_device != 'cuda'  ,      'This test is supposed to run on GPU'     )
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Union[str, Any]		     =	self.get_dummy_components()
         __UpperCamelCase						:						Dict		     =	StableDiffusionPipeline(**_lowerCamelCase     )
         __UpperCamelCase						:						str		     =	sd_pipe.to(_lowerCamelCase     )
         sd_pipe.set_progress_bar_config(disable=_lowerCamelCase     )

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

         # enable XFormers
         sd_pipe.enable_xformers_memory_efficient_attention()

         __UpperCamelCase						:						Optional[Any]		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						Optional[int]		     =	original_images[0, -3:, -3:, -1]

         with tempfile.TemporaryDirectory() as tmpdirname:
             LoraLoaderMixin.save_lora_weights(
                 save_directory=_lowerCamelCase  ,      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(_lowerCamelCase  ,      'pytorch_lora_weights.bin'     )     )     )
             sd_pipe.load_lora_weights(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	sd_pipe(**_lowerCamelCase     ).images
         __UpperCamelCase						:						List[Any]		     =	lora_images[0, -3:, -3:, -1]

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



