


"""simple docstring"""



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor
class 					__magic_name__		:






       def __init__(   self  :    Union[str, Any]  ,     snake_case__  :    Optional[Any]  ,     snake_case__  :    Any=3  ,     snake_case__  :    Optional[Any]=3_2  ,     snake_case__  :    Any=3  ,     snake_case__  :    str=1_0  ,     snake_case__  :    List[str]=[1_0, 2_0, 3_0, 4_0]  ,     snake_case__  :    List[Any]=[1, 1, 2, 1]  ,     snake_case__  :    int=True  ,     snake_case__  :    Tuple=True  ,     snake_case__  :    int="relu"  ,     snake_case__  :    str=3  ,     snake_case__  :    Tuple=None  ,     ):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				parent
              lowercase		:List[str]       							=				batch_size
              lowercase		:Optional[int]       							=				image_size
              lowercase		:Optional[int]       							=				num_channels
              lowercase		:List[str]       							=				embeddings_size
              lowercase		:List[str]       							=				hidden_sizes
              lowercase		:Any       							=				depths
              lowercase		:List[Any]       							=				is_training
              lowercase		:List[Any]       							=				use_labels
              lowercase		:Optional[int]       							=				hidden_act
              lowercase		:str       							=				num_labels
              lowercase		:Optional[Any]       							=				scope
              lowercase		:str       							=				len(snake_case__				)






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

              lowercase		:Tuple       							=				self.get_config()
              return config, pixel_values, labels






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              return RegNetConfig(
                  num_channels=self.num_channels  ,     embeddings_size=self.embeddings_size  ,     hidden_sizes=self.hidden_sizes  ,     depths=self.depths  ,     hidden_act=self.hidden_act  ,     num_labels=self.num_labels  ,     )






       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    Optional[int]  ,     snake_case__  :    str  ,     snake_case__  :    Optional[int]				):

              '''simple docstring'''






              lowercase		:List[Any]       							=				TFRegNetModel(config=snake_case__				)
              lowercase		:Dict       							=				model(snake_case__  ,     training=snake_case__				)
              # expected last hidden states: B, C, H // 32, W // 32
              self.parent.assertEqual(
                  result.last_hidden_state.shape  ,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)  ,     )






       def  __snake_case						(   self  :    int  ,     snake_case__  :    Any  ,     snake_case__  :    int  ,     snake_case__  :    Any				):

              '''simple docstring'''






              lowercase		:str       							=				self.num_labels
              lowercase		:int       							=				TFRegNetForImageClassification(snake_case__				)
              lowercase		:str       							=				model(snake_case__  ,     labels=snake_case__  ,     training=snake_case__				)
              self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.num_labels)				)







       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              lowercase		:Dict       							=				self.prepare_config_and_inputs()
              lowercase							,  lowercase							,  lowercase		:Optional[Any]       							=				config_and_inputs
              lowercase		:str       							=				{'''pixel_values''': pixel_values}
              return config, inputs_dict







@require_tf
class 					__magic_name__		(			__UpperCAmelCase			,						__UpperCAmelCase			,						unittest.TestCase     ):
       __A			:      List[Any]        =   (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
       __A			:      Union[str, Any]        =   (
           {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
           if is_tf_available()
           else {}
       )

       __A			:      List[str]        =   False
       __A			:      Union[str, Any]        =   False
       __A			:      Optional[Any]        =   False
       __A			:      str        =   False
       __A			:      Dict        =   False






       def  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






              lowercase		:Dict       							=				TFRegNetModelTester(self				)
              lowercase		:Any       							=				ConfigTester(self  ,     config_class=snake_case__  ,     has_text_modality=snake_case__				)






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              return






       @unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              pass






       @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  __snake_case						(   self  :    int				):

              '''simple docstring'''






              super().test_keras_fit()






       @unittest.skip(reason='''RegNet does not support input and output embeddings'''				)
       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              pass






       def  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






              lowercase							,  lowercase		:List[Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()

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

                     lowercase		:int       							=				['''pixel_values''']
                     self.assertListEqual(arg_names[:1]  ,     snake_case__				)






       def  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






              lowercase		:Any       							=				self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*snake_case__				)






       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              def check_hidden_states_output(snake_case__  :    Dict  ,     snake_case__  :    Dict  ,     snake_case__  :    Union[str, Any]				):
                     lowercase		:Union[str, Any]       							=				model_class(snake_case__				)
                     lowercase		:Union[str, Any]       							=				model(**self._prepare_for_class(snake_case__  ,     snake_case__				)  ,     training=snake_case__				)

                     lowercase		:Tuple       							=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                     lowercase		:Optional[Any]       							=				self.model_tester.num_stages
                     self.assertEqual(len(snake_case__				)  ,     expected_num_stages + 1				)

                     # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
                     self.assertListEqual(
                         list(hidden_states[0].shape[-2:]				)  ,     [self.model_tester.image_size // 2, self.model_tester.image_size // 2]  ,     )

              lowercase							,  lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()
              lowercase		:Optional[Any]       							=				['''basic''', '''bottleneck''']
              for model_class in self.all_model_classes:
                     for layer_type in layers_type:
                            lowercase		:Optional[Any]       							=				layer_type
                            lowercase		:Optional[Any]       							=				True
                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)

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

                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)






       def  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






              lowercase							,  lowercase		:int       							=				self.model_tester.prepare_config_and_inputs_for_common()

              def check_equivalence(snake_case__  :    List[str]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    Union[str, Any]  ,     snake_case__  :    Optional[int]={}				):
                     lowercase		:Tuple       							=				model(snake_case__  ,     return_dict=snake_case__  ,     **snake_case__				)
                     lowercase		:List[str]       							=				model(snake_case__  ,     return_dict=snake_case__  ,     **snake_case__				).to_tuple()

                     def recursive_check(snake_case__  :    Union[str, Any]  ,     snake_case__  :    Dict				):
                            if isinstance(snake_case__  ,     (List, Tuple)				):
                                   for tuple_iterable_value, dict_iterable_value in zip(snake_case__  ,     snake_case__				):
                                          recursive_check(snake_case__  ,     snake_case__				)
                            elif tuple_object is None:
                                   return
                            else:
                                   self.assertTrue(
                                       all(tf.equal(snake_case__  ,     snake_case__				)				)  ,     msg=(
                                           '''Tuple and dict output are not equal. Difference:'''
                                           f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object				)				)}"""
                                       )  ,     )

                            recursive_check(snake_case__  ,     snake_case__				)

              for model_class in self.all_model_classes:
                     lowercase		:int       							=				model_class(snake_case__				)

                     lowercase		:Optional[Any]       							=				self._prepare_for_class(snake_case__  ,     snake_case__				)
                     lowercase		:List[str]       							=				self._prepare_for_class(snake_case__  ,     snake_case__				)
                     check_equivalence(snake_case__  ,     snake_case__  ,     snake_case__				)

                     lowercase		:int       							=				self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
                     lowercase		:List[str]       							=				self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
                     check_equivalence(snake_case__  ,     snake_case__  ,     snake_case__				)

                     lowercase		:List[Any]       							=				self._prepare_for_class(snake_case__  ,     snake_case__				)
                     lowercase		:Dict       							=				self._prepare_for_class(snake_case__  ,     snake_case__				)
                     check_equivalence(snake_case__  ,     snake_case__  ,     snake_case__  ,     {'''output_hidden_states''': True}				)

                     lowercase		:Dict       							=				self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
                     lowercase		:List[Any]       							=				self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
                     check_equivalence(snake_case__  ,     snake_case__  ,     snake_case__  ,     {'''output_hidden_states''': True}				)






       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              lowercase		:List[str]       							=				self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*snake_case__				)







       @slow
       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowercase		:Optional[int]       							=				TFRegNetModel.from_pretrained(snake_case__				)
                     self.assertIsNotNone(snake_case__				)







def       lowerCamelCase					()     ->							int:
       lowercase		:Union[str, Any]       							=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
       return image




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






       @cached_property
       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              return (
                  AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
                  if is_vision_available()
                  else None
              )







       @slow
       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:Optional[Any]       							=				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)

              lowercase		:int       							=				self.default_image_processor
              lowercase		:Any       							=				prepare_img()
              lowercase		:int       							=				image_processor(images=snake_case__  ,     return_tensors='''tf'''				)

              # forward pass
              lowercase		:Tuple       							=				model(**snake_case__  ,     training=snake_case__				)

              # verify the logits
              lowercase		:Optional[int]       							=				tf.TensorShape((1, 1_0_0_0)				)
              self.assertEqual(outputs.logits.shape  ,     snake_case__				)

              lowercase		:Dict       							=				tf.constant([-0.41_80, -1.50_51, -3.48_36]				)

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





"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase      		=			logging.get_logger(__name__)

UpperCAmelCase      		=			{
    '''facebook/deit-base-distilled-patch16-224''': (
        '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json'''
    ),
    # See all DeiT models at https://huggingface.co/models?filter=deit
}
class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      Tuple        =   "deit"






       def __init__(   self  :    List[str]  ,     snake_case__  :    int=7_6_8  ,     snake_case__  :    List[Any]=1_2  ,     snake_case__  :    Dict=1_2  ,     snake_case__  :    List[Any]=3_0_7_2  ,     snake_case__  :    Optional[int]="gelu"  ,     snake_case__  :    Dict=0.0  ,     snake_case__  :    str=0.0  ,     snake_case__  :    List[str]=0.02  ,     snake_case__  :    Optional[int]=1e-1_2  ,     snake_case__  :    Any=2_2_4  ,     snake_case__  :    Optional[int]=1_6  ,     snake_case__  :    int=3  ,     snake_case__  :    str=True  ,     snake_case__  :    Optional[int]=1_6  ,     **snake_case__  :    List[Any]  ,     ):

              '''simple docstring'''






              super().__init__(**snake_case__				)

              lowercase		:List[str]       							=				hidden_size
              lowercase		:Union[str, Any]       							=				num_hidden_layers
              lowercase		:Optional[Any]       							=				num_attention_heads
              lowercase		:Optional[Any]       							=				intermediate_size
              lowercase		:int       							=				hidden_act
              lowercase		:int       							=				hidden_dropout_prob
              lowercase		:Dict       							=				attention_probs_dropout_prob
              lowercase		:Optional[int]       							=				initializer_range
              lowercase		:Tuple       							=				layer_norm_eps
              lowercase		:Optional[int]       							=				image_size
              lowercase		:Union[str, Any]       							=				patch_size
              lowercase		:Optional[Any]       							=				num_channels
              lowercase		:Tuple       							=				qkv_bias
              lowercase		:Optional[Any]       							=				encoder_stride







class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      Optional[int]        =   version.parse("1.11"     )






       @property
       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              return OrderedDict(
                  [
                      ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                  ]				)







       @property
       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






              return 1e-4

