





from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import numpy as np
  import tensorflow as tf

  from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
  from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor

class 		__a							(	__UpperCamelCase      ):



       def  A							(     self	:   Optional[int]			):
           lowerCAmelCase_					:	Optional[int]						=   self.config_class(**self.inputs_dict			)
           self.parent.assertTrue(hasattr(UpperCAmelCase					,			"""hidden_sizes"""			)			)
           self.parent.assertTrue(hasattr(UpperCAmelCase					,			"""neck_hidden_sizes"""			)			)
           self.parent.assertTrue(hasattr(UpperCAmelCase					,			"""num_attention_heads"""			)			)






class 		__a							:



       def __init__(     self	:   int					,			UpperCAmelCase	:   Dict					,			UpperCAmelCase	:   List[str]=13					,			UpperCAmelCase	:   Dict=32					,			UpperCAmelCase	:   List[Any]=2					,			UpperCAmelCase	:   Union[str, Any]=3					,			UpperCAmelCase	:   Optional[Any]=6_40					,			UpperCAmelCase	:   Union[str, Any]=4					,			UpperCAmelCase	:   int="silu"					,			UpperCAmelCase	:   Union[str, Any]=3					,			UpperCAmelCase	:   Optional[int]=32					,			UpperCAmelCase	:   Any=0.1					,			UpperCAmelCase	:   Tuple=0.1					,			UpperCAmelCase	:   Optional[Any]=0.1					,			UpperCAmelCase	:   Any=0.02					,			UpperCAmelCase	:   Tuple=True					,			UpperCAmelCase	:   str=True					,			UpperCAmelCase	:   int=10					,			UpperCAmelCase	:   str=None					,			):
           lowerCAmelCase_					:	List[str]						=   parent
           lowerCAmelCase_					:	List[Any]						=   batch_size
           lowerCAmelCase_					:	str						=   image_size
           lowerCAmelCase_					:	int						=   patch_size
           lowerCAmelCase_					:	Tuple						=   num_channels
           lowerCAmelCase_					:	Optional[int]						=   last_hidden_size
           lowerCAmelCase_					:	Optional[int]						=   num_attention_heads
           lowerCAmelCase_					:	List[str]						=   hidden_act
           lowerCAmelCase_					:	Optional[int]						=   conv_kernel_size
           lowerCAmelCase_					:	Union[str, Any]						=   output_stride
           lowerCAmelCase_					:	Any						=   hidden_dropout_prob
           lowerCAmelCase_					:	Tuple						=   attention_probs_dropout_prob
           lowerCAmelCase_					:	Optional[Any]						=   classifier_dropout_prob
           lowerCAmelCase_					:	Tuple						=   use_labels
           lowerCAmelCase_					:	Dict						=   is_training
           lowerCAmelCase_					:	int						=   num_labels
           lowerCAmelCase_					:	Optional[Any]						=   initializer_range
           lowerCAmelCase_					:	Dict						=   scope



       def  A							(     self	:   Union[str, Any]			):
           lowerCAmelCase_					:	int						=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

           lowerCAmelCase_					:	Union[str, Any]						=   None
           lowerCAmelCase_					:	Optional[Any]						=   None
           if self.use_labels:
               lowerCAmelCase_					:	List[Any]						=   ids_tensor([self.batch_size]					,			self.num_labels			)
               lowerCAmelCase_					:	Optional[Any]						=   ids_tensor([self.batch_size, self.image_size, self.image_size]					,			self.num_labels			)

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

           return config, pixel_values, labels, pixel_labels



       def  A							(     self	:   Optional[int]			):
           return MobileViTConfig(
               image_size=self.image_size					,			patch_size=self.patch_size					,			num_channels=self.num_channels					,			num_attention_heads=self.num_attention_heads					,			hidden_act=self.hidden_act					,			conv_kernel_size=self.conv_kernel_size					,			output_stride=self.output_stride					,			hidden_dropout_prob=self.hidden_dropout_prob					,			attention_probs_dropout_prob=self.attention_probs_dropout_prob					,			classifier_dropout_prob=self.classifier_dropout_prob					,			initializer_range=self.initializer_range					,			)



       def  A							(     self	:   int					,			UpperCAmelCase	:   Tuple					,			UpperCAmelCase	:   int					,			UpperCAmelCase	:   str					,			UpperCAmelCase	:   Tuple			):
           lowerCAmelCase_					:	List[str]						=   TFMobileViTModel(config=UpperCAmelCase			)
           lowerCAmelCase_					:	List[str]						=   model(UpperCAmelCase					,			training=UpperCAmelCase			)
           lowerCAmelCase_					:	int						=   self.image_size // self.output_stride
           self.parent.assertEqual(
               result.last_hidden_state.shape					,			(self.batch_size, self.last_hidden_size, expected_height, expected_width)			)



       def  A							(     self	:   Union[str, Any]					,			UpperCAmelCase	:   Tuple					,			UpperCAmelCase	:   str					,			UpperCAmelCase	:   Union[str, Any]					,			UpperCAmelCase	:   Optional[Any]			):
           lowerCAmelCase_					:	Dict						=   self.num_labels
           lowerCAmelCase_					:	Union[str, Any]						=   TFMobileViTForImageClassification(UpperCAmelCase			)
           lowerCAmelCase_					:	str						=   model(UpperCAmelCase					,			labels=UpperCAmelCase					,			training=UpperCAmelCase			)
           self.parent.assertEqual(result.logits.shape					,			(self.batch_size, self.num_labels)			)



       def  A							(     self	:   int					,			UpperCAmelCase	:   Union[str, Any]					,			UpperCAmelCase	:   List[str]					,			UpperCAmelCase	:   Tuple					,			UpperCAmelCase	:   Tuple			):
           lowerCAmelCase_					:	str						=   self.num_labels
           lowerCAmelCase_					:	str						=   TFMobileViTForSemanticSegmentation(UpperCAmelCase			)
           lowerCAmelCase_					:	Tuple						=   self.image_size // self.output_stride

           lowerCAmelCase_					:	List[str]						=   model(UpperCAmelCase					,			training=UpperCAmelCase			)
           self.parent.assertEqual(
               result.logits.shape					,			(self.batch_size, self.num_labels, expected_height, expected_width)			)

           lowerCAmelCase_					:	Union[str, Any]						=   model(UpperCAmelCase					,			labels=UpperCAmelCase					,			training=UpperCAmelCase			)
           self.parent.assertEqual(
               result.logits.shape					,			(self.batch_size, self.num_labels, expected_height, expected_width)			)



       def  A							(     self	:   Optional[Any]			):
           lowerCAmelCase_					:	List[Any]						=   self.prepare_config_and_inputs()
           lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_		,		lowerCAmelCase_					:	Union[str, Any]						=   config_and_inputs
           lowerCAmelCase_					:	Optional[int]						=   {"""pixel_values""": pixel_values}
           return config, inputs_dict






@require_tf
class 		__a							(	__UpperCamelCase			,__UpperCamelCase			,unittest.TestCase      ):
       __snake_case						:   Optional[int]      =		(
           (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
           if is_tf_available()
           else ()
       )
       __snake_case						:   Tuple      =		(
           {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
           if is_tf_available()
           else {}
       )

       __snake_case						:   Optional[Any]      =		False
       __snake_case						:   List[Any]      =		False
       __snake_case						:   Dict      =		False
       __snake_case						:   Optional[Any]      =		False
       __snake_case						:   Optional[int]      =		False



       def  A							(     self	:   str			):
           lowerCAmelCase_					:	str						=   TFMobileViTModelTester(self			)
           lowerCAmelCase_					:	Union[str, Any]						=   TFMobileViTConfigTester(self					,			config_class=UpperCAmelCase					,			has_text_modality=UpperCAmelCase			)



       def  A							(     self	:   int			):
           self.config_tester.run_common_tests()



       @unittest.skip(reason="""MobileViT does not use inputs_embeds"""			)
       def  A							(     self	:   List[str]			):
           pass



       @unittest.skip(reason="""MobileViT does not support input and output embeddings"""			)
       def  A							(     self	:   Union[str, Any]			):
           pass



       @unittest.skip(reason="""MobileViT does not output attentions"""			)
       def  A							(     self	:   List[str]			):
           pass



       def  A							(     self	:   Optional[int]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Optional[Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               lowerCAmelCase_					:	List[Any]						=   model_class(UpperCAmelCase			)
               lowerCAmelCase_					:	List[Any]						=   inspect.signature(model.call			)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               lowerCAmelCase_					:	List[Any]						=   [*signature.parameters.keys()]

               lowerCAmelCase_					:	List[Any]						=   ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]					,			UpperCAmelCase			)



       def  A							(     self	:   Any			):
           lowerCAmelCase_					:	List[str]						=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase			)



       def  A							(     self	:   Dict			):
           def check_hidden_states_output(UpperCAmelCase	:   Dict					,			UpperCAmelCase	:   Dict					,			UpperCAmelCase	:   Union[str, Any]			):
               lowerCAmelCase_					:	List[str]						=   model_class(UpperCAmelCase			)

               lowerCAmelCase_					:	Optional[Any]						=   model(**self._prepare_for_class(UpperCAmelCase					,			UpperCAmelCase			)			)

               lowerCAmelCase_					:	Optional[Any]						=   outputs.hidden_states

               lowerCAmelCase_					:	List[Any]						=   5
               self.assertEqual(len(UpperCAmelCase			)					,			UpperCAmelCase			)

               # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
               # with the width and height being successively divided by 2.
               lowerCAmelCase_					:	List[Any]						=   2
               for i in range(len(UpperCAmelCase			)			):
                   self.assertListEqual(
                       list(hidden_states[i].shape[-2:]			)					,			[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]					,			)
                   divisor *= 2

               self.assertEqual(self.model_tester.output_stride					,			divisor // 2			)

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

           for model_class in self.all_model_classes:
               lowerCAmelCase_					:	List[str]						=   True
               check_hidden_states_output(UpperCAmelCase					,			UpperCAmelCase					,			UpperCAmelCase			)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               lowerCAmelCase_					:	List[str]						=   True

               check_hidden_states_output(UpperCAmelCase					,			UpperCAmelCase					,			UpperCAmelCase			)



       def  A							(     self	:   Optional[int]			):
           lowerCAmelCase_					:	Optional[int]						=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase			)



       def  A							(     self	:   Optional[int]			):
           lowerCAmelCase_					:	str						=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase			)



       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""			)			) == 0					,			reason="""TF does not support backprop for grouped convolutions on CPU."""					,			)
       def  A							(     self	:   Dict			):
           super().test_dataset_conversion()



       def  A							(     self	:   int					,			UpperCAmelCase	:   List[str]					,			UpperCAmelCase	:   Any					,			UpperCAmelCase	:   Any=2e-1					,			UpperCAmelCase	:   Optional[Any]=2e-1			):
           self.assertTrue(np.allclose(UpperCAmelCase					,			UpperCAmelCase					,			atol=UpperCAmelCase					,			rtol=UpperCAmelCase			)			)



       @unittest.skipIf(
           not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""			)			) == 0					,			reason="""TF does not support backprop for grouped convolutions on CPU."""					,			)
       @slow
       def  A							(     self	:   Tuple			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Tuple						=   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
               if model_class.__name__ != "TFMobileViTModel":
                   lowerCAmelCase_					:	Optional[int]						=   model_class(UpperCAmelCase			)
                   if getattr(UpperCAmelCase					,			"""hf_compute_loss"""					,			UpperCAmelCase			):
                       super().test_keras_fit()



       def  A							(     self	:   Union[str, Any]			):
           lowerCAmelCase_		,		lowerCAmelCase_					:	Any						=   self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
               # set an ignore index to correctly test the masked loss used in
               # `TFMobileViTForSemanticSegmentation`.
               if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
                   lowerCAmelCase_					:	List[str]						=   5

               lowerCAmelCase_					:	int						=   model_class(UpperCAmelCase			)
               if getattr(UpperCAmelCase					,			"""hf_compute_loss"""					,			UpperCAmelCase			):
                   # The number of elements in the loss should be the same as the number of elements in the label
                   lowerCAmelCase_					:	Any						=   self._prepare_for_class(inputs_dict.copy()					,			UpperCAmelCase					,			return_labels=UpperCAmelCase			)
                   lowerCAmelCase_					:	int						=   prepared_for_class[
                       sorted(prepared_for_class.keys() - inputs_dict.keys()					,			reverse=UpperCAmelCase			)[0]
                   ]
                   lowerCAmelCase_					:	str						=   added_label.shape.as_list()[:1]

                   # Test that model correctly compute the loss with kwargs
                   lowerCAmelCase_					:	List[str]						=   self._prepare_for_class(inputs_dict.copy()					,			UpperCAmelCase					,			return_labels=UpperCAmelCase			)
                   lowerCAmelCase_					:	Any						=   {"""input_ids""", """pixel_values""", """input_features"""}
                   lowerCAmelCase_					:	Any						=   possible_input_names.intersection(set(UpperCAmelCase			)			).pop()
                   lowerCAmelCase_					:	int						=   prepared_for_class.pop(UpperCAmelCase			)

                   lowerCAmelCase_					:	Union[str, Any]						=   model(UpperCAmelCase					,			**UpperCAmelCase			)[0]
                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

                   # Test that model correctly compute the loss when we mask some positions
                   lowerCAmelCase_					:	Any						=   self._prepare_for_class(inputs_dict.copy()					,			UpperCAmelCase					,			return_labels=UpperCAmelCase			)
                   lowerCAmelCase_					:	Optional[Any]						=   {"""input_ids""", """pixel_values""", """input_features"""}
                   lowerCAmelCase_					:	int						=   possible_input_names.intersection(set(UpperCAmelCase			)			).pop()
                   lowerCAmelCase_					:	str						=   prepared_for_class.pop(UpperCAmelCase			)
                   if "labels" in prepared_for_class:
                       lowerCAmelCase_					:	List[str]						=   prepared_for_class["""labels"""].numpy()
                       if len(labels.shape			) > 1 and labels.shape[1] != 1:
                           # labels[0] = -100
                           lowerCAmelCase_					:	str						=   tf.convert_to_tensor(UpperCAmelCase			)
                           lowerCAmelCase_					:	List[Any]						=   model(UpperCAmelCase					,			**UpperCAmelCase			)[0]
                           self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)
                           self.assertTrue(not np.any(np.isnan(loss.numpy()			)			)			)

                # Test that model correctly compute the loss with a dict
                   lowerCAmelCase_					:	Tuple						=   self._prepare_for_class(inputs_dict.copy()					,			UpperCAmelCase					,			return_labels=UpperCAmelCase			)
                   lowerCAmelCase_					:	str						=   model(UpperCAmelCase			)[0]
                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

                   # Test that model correctly compute the loss with a tuple
                   lowerCAmelCase_					:	Union[str, Any]						=   self._prepare_for_class(inputs_dict.copy()					,			UpperCAmelCase					,			return_labels=UpperCAmelCase			)

                   # Get keys that were added with the _prepare_for_class function
                   lowerCAmelCase_					:	List[Any]						=   prepared_for_class.keys() - inputs_dict.keys()
                   lowerCAmelCase_					:	List[Any]						=   inspect.signature(model.call			).parameters
                   lowerCAmelCase_					:	Optional[Any]						=   list(signature.keys()			)

                   # Create a dictionary holding the location of the tensors in the tuple
                   lowerCAmelCase_					:	Union[str, Any]						=   {0: input_name}
                   for label_key in label_keys:
                       lowerCAmelCase_					:	Union[str, Any]						=   signature_names.index(UpperCAmelCase			)
                       lowerCAmelCase_					:	int						=   label_key
                   lowerCAmelCase_					:	Tuple						=   sorted(tuple_index_mapping.items()			)
                   # Initialize a list with their default values, update the values and convert to a tuple
                   lowerCAmelCase_					:	Union[str, Any]						=   []

                   for name in signature_names:
                       if name != "kwargs":
                           list_input.append(signature[name].default			)

                   for index, value in sorted_tuple_index_mapping:
                       lowerCAmelCase_					:	int						=   prepared_for_class[value]

                   lowerCAmelCase_					:	Dict						=   tuple(UpperCAmelCase			)

                   # Send to model
                   lowerCAmelCase_					:	Tuple						=   model(tuple_input[:-1]			)[0]

                   self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)



       @slow
       def  A							(     self	:   Any			):
           for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowerCAmelCase_					:	Optional[Any]						=   TFMobileViTModel.from_pretrained(UpperCAmelCase			)
               self.assertIsNotNone(UpperCAmelCase			)






def 			__UpperCamelCase				(			)	->      Dict:
    '''simple docstring'''





    lowerCAmelCase_					:	Optional[int]						=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
    return image

@require_tf
class 		__a							(	unittest.TestCase      ):



       @slow
       def  A							(     self	:   Tuple			):
           lowerCAmelCase_					:	int						=   TFMobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""			)

           lowerCAmelCase_					:	Optional[Any]						=   MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""			)
           lowerCAmelCase_					:	Any						=   prepare_img()
           lowerCAmelCase_					:	str						=   image_processor(images=UpperCAmelCase					,			return_tensors="""tf"""			)

           # forward pass
           lowerCAmelCase_					:	List[str]						=   model(**UpperCAmelCase					,			training=UpperCAmelCase			)

           # verify the logits
           lowerCAmelCase_					:	str						=   tf.TensorShape((1, 10_00)			)
           self.assertEqual(outputs.logits.shape					,			UpperCAmelCase			)

           lowerCAmelCase_					:	str						=   tf.constant([-1.9364, -1.2327, -0.4653]			)

           tf.debugging.assert_near(outputs.logits[0, :3]					,			UpperCAmelCase					,			atol=1e-4					,			rtol=1e-0_4			)



       @slow
       def  A							(     self	:   Dict			):
           # `from_pt` will be removed
           lowerCAmelCase_					:	Optional[Any]						=   TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""			)

           lowerCAmelCase_					:	Optional[Any]						=   MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""			)

           lowerCAmelCase_					:	Optional[int]						=   prepare_img()
           lowerCAmelCase_					:	int						=   image_processor(images=UpperCAmelCase					,			return_tensors="""tf"""			)

           # forward pass
           lowerCAmelCase_					:	Tuple						=   model(inputs.pixel_values					,			training=UpperCAmelCase			)
           lowerCAmelCase_					:	Optional[int]						=   outputs.logits

           # verify the logits
           lowerCAmelCase_					:	Optional[Any]						=   tf.TensorShape((1, 21, 32, 32)			)
           self.assertEqual(logits.shape					,			UpperCAmelCase			)

           lowerCAmelCase_					:	Optional[Any]						=   tf.constant(
               [
                   [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
                   [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
                   [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
               ]			)

           tf.debugging.assert_near(logits[0, :3, :3, :3]					,			UpperCAmelCase					,			rtol=1e-4					,			atol=1e-4			)









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			)			)			)


