






from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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 tensorflow as tf

     from transformers import (
         TFDeiTForImageClassification,
         TFDeiTForImageClassificationWithTeacher,
         TFDeiTForMaskedImageModeling,
         TFDeiTModel,
     )
     from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import DeiTImageProcessor




class 			snake_case__   :

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=13			,						a__=30			,						a__=2			,						a__=3			,						a__=True			,						a__=True			,						a__=32			,						a__=2			,						a__=4			,						a__=37			,						a__="gelu"			,						a__=0.1			,						a__=0.1			,						a__=10			,						a__=0.02			,						a__=3			,						a__=None			,						a__=2			,						) ->      str:






            '''simple docstring'''





            __snake_case			:List[Any]          =						parent
            __snake_case			:Dict          =						batch_size
            __snake_case			:List[str]          =						image_size
            __snake_case			:Dict          =						patch_size
            __snake_case			:List[Any]          =						num_channels
            __snake_case			:Optional[int]          =						is_training
            __snake_case			:Tuple          =						use_labels
            __snake_case			:Any          =						hidden_size
            __snake_case			:Optional[Any]          =						num_hidden_layers
            __snake_case			:Optional[Any]          =						num_attention_heads
            __snake_case			:Any          =						intermediate_size
            __snake_case			:Dict          =						hidden_act
            __snake_case			:str          =						hidden_dropout_prob
            __snake_case			:Optional[Any]          =						attention_probs_dropout_prob
            __snake_case			:Optional[Any]          =						type_sequence_label_size
            __snake_case			:Union[str, Any]          =						initializer_range
            __snake_case			:List[str]          =						scope
            __snake_case			:Dict          =						encoder_stride

            # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
            __snake_case			:List[Any]          =						(image_size // patch_size) ** 2
            __snake_case			:Any          =						num_patches + 2



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Tuple          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            __snake_case			:Union[str, Any]          =						None
            if self.use_labels:
                 __snake_case			:str          =						ids_tensor([self.batch_size]			,						self.type_sequence_label_size    )

            __snake_case			:List[Any]          =						self.get_config()

            return config, pixel_values, labels



       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            return DeiTConfig(
                image_size=self.image_size			,						patch_size=self.patch_size			,						num_channels=self.num_channels			,						hidden_size=self.hidden_size			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						hidden_act=self.hidden_act			,						hidden_dropout_prob=self.hidden_dropout_prob			,						attention_probs_dropout_prob=self.attention_probs_dropout_prob			,						is_decoder=a__			,						initializer_range=self.initializer_range			,						encoder_stride=self.encoder_stride			,						)



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Tuple          =						TFDeiTModel(config=a__    )
            __snake_case			:Any          =						model(a__    )
            self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Any          =						TFDeiTForMaskedImageModeling(config=a__    )
            __snake_case			:List[str]          =						model(a__    )
            self.parent.assertEqual(
                result.reconstruction.shape			,						(self.batch_size, self.num_channels, self.image_size, self.image_size)    )

            # test greyscale images
            __snake_case			:List[str]          =						1
            __snake_case			:int          =						TFDeiTForMaskedImageModeling(a__    )

            __snake_case			:Any          =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
            __snake_case			:List[Any]          =						model(a__    )
            self.parent.assertEqual(result.reconstruction.shape			,						(self.batch_size, 1, self.image_size, self.image_size)    )



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Any          =						self.type_sequence_label_size
            __snake_case			:str          =						TFDeiTForImageClassification(a__    )
            __snake_case			:List[str]          =						model(a__			,						labels=a__    )
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.type_sequence_label_size)    )

            # test greyscale images
            __snake_case			:Tuple          =						1
            __snake_case			:List[str]          =						TFDeiTForImageClassification(a__    )

            __snake_case			:Tuple          =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
            __snake_case			:Optional[Any]          =						model(a__			,						labels=a__    )
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.type_sequence_label_size)    )



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Dict          =						self.prepare_config_and_inputs()
            __snake_case       , __snake_case       , __snake_case			:str          =						config_and_inputs
            __snake_case			:List[Any]          =						{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_tf
class 			snake_case__   (							lowercase_	,    lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Dict 				= (
           (
               TFDeiTModel,
               TFDeiTForImageClassification,
               TFDeiTForImageClassificationWithTeacher,
               TFDeiTForMaskedImageModeling,
           )
           if is_tf_available()
           else ()
       )
       lowerCamelCase							:				Optional[int] 				= (
           {
               "feature-extraction": TFDeiTModel,
               "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
           }
           if is_tf_available()
           else {}
       )

       lowerCamelCase							:				Union[str, Any] 				= False
       lowerCamelCase							:				List[Any] 				= False
       lowerCamelCase							:				Optional[int] 				= False
       lowerCamelCase							:				List[Any] 				= False



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						TFDeiTModelTester(self    )
            __snake_case			:Dict          =						ConfigTester(self			,						config_class=a__			,						has_text_modality=a__			,						hidden_size=37    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            self.config_tester.run_common_tests()



       @unittest.skip(reason="""DeiT does not use inputs_embeds"""    )
       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            pass



       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case       , __snake_case			:Tuple          =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case			:List[str]          =						model_class(a__    )
                 self.assertIsInstance(model.get_input_embeddings()			,						(tf.keras.layers.Layer)    )
                 __snake_case			:str          =						model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(a__			,						tf.keras.layers.Dense    )    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case       , __snake_case			:str          =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case			:Tuple          =						model_class(a__    )
                 __snake_case			:Optional[int]          =						inspect.signature(model.call    )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 __snake_case			:Any          =						[*signature.parameters.keys()]

                 __snake_case			:Any          =						["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]			,						a__    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*a__    )



       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*a__    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*a__    )



       def 					__lowercase						(							self			,						a__			,						a__			,						a__=False    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Tuple          =						super()._prepare_for_class(a__			,						a__			,						return_labels=a__    )

            if return_labels:
                 if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call    ).parameters:
                      del inputs_dict["labels"]

            return inputs_dict



       @slow
       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __snake_case			:Union[str, Any]          =						TFDeiTModel.from_pretrained(a__    )
                 self.assertIsNotNone(a__    )






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			:Dict          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
     return image




@require_tf
@require_vision
class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       @cached_property
       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            return (
                DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""    )
                if is_vision_available()
                else None
            )



       @slow
       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Any          =						TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""    )

            __snake_case			:Dict          =						self.default_image_processor
            __snake_case			:List[Any]          =						prepare_img()
            __snake_case			:Optional[Any]          =						image_processor(images=a__			,						return_tensors="""tf"""    )

            # forward pass
            __snake_case			:Optional[int]          =						model(**a__    )

            # verify the logits
            __snake_case			:Tuple          =						tf.TensorShape((1, 10_00)    )
            self.assertEqual(outputs.logits.shape			,						a__    )

            __snake_case			:Tuple          =						tf.constant([-1.02_66, 0.19_12, -1.28_61]    )

            self.assertTrue(np.allclose(outputs.logits[0, :3]			,						a__			,						atol=1e-4    )    )










import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
     pass

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__							=     logging.get_logger(__name__)

lowerCamelCase__							=     {
    """kakaobrain/align-base""": """https://huggingface.co/kakaobrain/align-base/resolve/main/config.json""",
}




class 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Union[str, Any] 				= "align_text_model"



       def __init__(							self			,						a__=3_05_22			,						a__=7_68			,						a__=12			,						a__=12			,						a__=30_72			,						a__="gelu"			,						a__=0.1			,						a__=0.1			,						a__=5_12			,						a__=2			,						a__=0.02			,						a__=1e-12			,						a__=0			,						a__="absolute"			,						a__=True			,						**a__			,						) ->      List[str]:






            '''simple docstring'''





            super().__init__(**a__    )

            __snake_case			:Optional[int]          =						vocab_size
            __snake_case			:List[str]          =						hidden_size
            __snake_case			:Optional[Any]          =						num_hidden_layers
            __snake_case			:int          =						num_attention_heads
            __snake_case			:Optional[Any]          =						hidden_act
            __snake_case			:Union[str, Any]          =						intermediate_size
            __snake_case			:int          =						hidden_dropout_prob
            __snake_case			:Optional[Any]          =						attention_probs_dropout_prob
            __snake_case			:List[str]          =						max_position_embeddings
            __snake_case			:List[str]          =						type_vocab_size
            __snake_case			:Union[str, Any]          =						initializer_range
            __snake_case			:str          =						layer_norm_eps
            __snake_case			:Any          =						position_embedding_type
            __snake_case			:List[str]          =						use_cache
            __snake_case			:Optional[int]          =						pad_token_id



       @classmethod
       def 					__lowercase						(							cls			,						a__			,						**a__    ) ->      "PretrainedConfig":






            '''simple docstring'''





            cls._set_token_in_kwargs(a__    )

            __snake_case       , __snake_case			:Tuple          =						cls.get_config_dict(a__			,						**a__    )

            # get the text config dict if we are loading from AlignConfig
            if config_dict.get("""model_type"""    ) == "align":
                 __snake_case			:Any          =						config_dict["""text_config"""]

            if "model_type" in config_dict and hasattr(cls			,						"""model_type"""    ) and config_dict["model_type"] != cls.model_type:
                 logger.warning(
                     F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
                     F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''    )

            return cls.from_dict(a__			,						**a__    )




class 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				Optional[int] 				= "align_vision_model"



       def __init__(							self			,						a__ = 3			,						a__ = 6_00			,						a__ = 2.0			,						a__ = 3.1			,						a__ = 8			,						a__ = [3, 3, 5, 3, 5, 5, 3]			,						a__ = [32, 16, 24, 40, 80, 1_12, 1_92]			,						a__ = [16, 24, 40, 80, 1_12, 1_92, 3_20]			,						a__ = []			,						a__ = [1, 2, 2, 2, 1, 2, 1]			,						a__ = [1, 2, 2, 3, 3, 4, 1]			,						a__ = [1, 6, 6, 6, 6, 6, 6]			,						a__ = 0.25			,						a__ = "swish"			,						a__ = 25_60			,						a__ = "mean"			,						a__ = 0.02			,						a__ = 0.0_01			,						a__ = 0.99			,						a__ = 0.2			,						**a__			,						) ->      List[Any]:






            '''simple docstring'''





            super().__init__(**a__    )

            __snake_case			:Union[str, Any]          =						num_channels
            __snake_case			:List[str]          =						image_size
            __snake_case			:int          =						width_coefficient
            __snake_case			:int          =						depth_coefficient
            __snake_case			:List[Any]          =						depth_divisor
            __snake_case			:Any          =						kernel_sizes
            __snake_case			:Optional[int]          =						in_channels
            __snake_case			:Optional[int]          =						out_channels
            __snake_case			:int          =						depthwise_padding
            __snake_case			:List[str]          =						strides
            __snake_case			:Union[str, Any]          =						num_block_repeats
            __snake_case			:Dict          =						expand_ratios
            __snake_case			:Union[str, Any]          =						squeeze_expansion_ratio
            __snake_case			:Any          =						hidden_act
            __snake_case			:Optional[Any]          =						hidden_dim
            __snake_case			:Union[str, Any]          =						pooling_type
            __snake_case			:Union[str, Any]          =						initializer_range
            __snake_case			:Optional[Any]          =						batch_norm_eps
            __snake_case			:List[Any]          =						batch_norm_momentum
            __snake_case			:Optional[int]          =						drop_connect_rate
            __snake_case			:Union[str, Any]          =						sum(a__    ) * 4



       @classmethod
       def 					__lowercase						(							cls			,						a__			,						**a__    ) ->      "PretrainedConfig":






            '''simple docstring'''





            cls._set_token_in_kwargs(a__    )

            __snake_case       , __snake_case			:int          =						cls.get_config_dict(a__			,						**a__    )

            # get the vision config dict if we are loading from AlignConfig
            if config_dict.get("""model_type"""    ) == "align":
                 __snake_case			:str          =						config_dict["""vision_config"""]

            if "model_type" in config_dict and hasattr(cls			,						"""model_type"""    ) and config_dict["model_type"] != cls.model_type:
                 logger.warning(
                     F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
                     F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''    )

            return cls.from_dict(a__			,						**a__    )




class 			snake_case__   (							lowercase_):

       '''simple docstring'''
       lowerCamelCase							:				str 				= "align"
       lowerCamelCase							:				Union[str, Any] 				= True



       def __init__(							self			,						a__=None			,						a__=None			,						a__=6_40			,						a__=1.0			,						a__=0.02			,						**a__			,						) ->      Dict:






            '''simple docstring'''





            super().__init__(**a__    )

            if text_config is None:
                 __snake_case			:Union[str, Any]          =						{}
                 logger.info("""text_config is None. Initializing the AlignTextConfig with default values."""    )

            if vision_config is None:
                 __snake_case			:str          =						{}
                 logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values."""    )

            __snake_case			:List[Any]          =						AlignTextConfig(**a__    )
            __snake_case			:Tuple          =						AlignVisionConfig(**a__    )

            __snake_case			:Tuple          =						projection_dim
            __snake_case			:int          =						temperature_init_value
            __snake_case			:Any          =						initializer_range



       @classmethod
       def 					__lowercase						(							cls			,						a__			,						a__			,						**a__    ) ->      str:






            '''simple docstring'''





            return cls(text_config=text_config.to_dict()			,						vision_config=vision_config.to_dict()			,						**a__    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						copy.deepcopy(self.__dict__    )
            __snake_case			:Dict          =						self.text_config.to_dict()
            __snake_case			:Union[str, Any]          =						self.vision_config.to_dict()
            __snake_case			:List[Any]          =						self.__class__.model_type
            return output


