

'''simple docstring'''

import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs


class 	lowerCAmelCase  (   A ):







       def __init__(				self      :			str    ,   __lowercase      :			Union[str, Any]    ,   __lowercase      :			List[str]=None    ,   __lowercase      :			List[str]=True    ,   __lowercase      :			int=None    ,   **__lowercase      :			Union[str, Any]   ):







            """simple docstring"""







            __lowercase      		=parent
            __lowercase      		=config_class
            __lowercase      		=has_text_modality
            __lowercase      		=kwargs
            __lowercase      		=common_properties







       def       snake_case (				self      :			str   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict   )
            __lowercase      		=(
                ['hidden_size', 'num_attention_heads', 'num_hidden_layers']
                if self.common_properties is None
                else self.common_properties
            )

            # Add common fields for text models
            if self.has_text_modality:
                 common_properties.extend(['vocab_size']   )

            # Test that config has the common properties as getters
            for prop in common_properties:
                 self.parent.assertTrue(hasattr(__lowercase    ,   __lowercase   )    ,   msg=f'''`{prop}` does not exist'''   )

            # Test that config has the common properties as setter
            for idx, name in enumerate(__lowercase   ):
                 try:
                      setattr(__lowercase    ,   __lowercase    ,   __lowercase   )
                      self.parent.assertEqual(
                          getattr(__lowercase    ,   __lowercase   )    ,   __lowercase    ,   msg=f'''`{name} value {idx} expected, but was {getattr(__lowercase    ,   __lowercase   )}'''   )
                 except NotImplementedError:
                      # Some models might not be able to implement setters for common_properties
                      # In that case, a NotImplementedError is raised
                      pass

        # Test if config class can be called with Config(prop_name=..)
            for idx, name in enumerate(__lowercase   ):
                 try:
                      __lowercase      		=self.config_class(**{name: idx}   )
                      self.parent.assertEqual(
                          getattr(__lowercase    ,   __lowercase   )    ,   __lowercase    ,   msg=f'''`{name} value {idx} expected, but was {getattr(__lowercase    ,   __lowercase   )}'''   )
                 except NotImplementedError:
                      # Some models might not be able to implement setters for common_properties
                      # In that case, a NotImplementedError is raised
                      pass







       def       snake_case (				self      :			List[str]   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict   )
            __lowercase      		=json.loads(config.to_json_string()   )
            for key, value in self.inputs_dict.items():
                 self.parent.assertEqual(obj[key]    ,   __lowercase   )







       def       snake_case (				self      :			Any   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict   )

            with tempfile.TemporaryDirectory() as tmpdirname:
                 __lowercase      		=os.path.join(__lowercase    ,   'config.json'   )
                 config_first.to_json_file(__lowercase   )
                 __lowercase      		=self.config_class.from_json_file(__lowercase   )

            self.parent.assertEqual(config_second.to_dict()    ,   config_first.to_dict()   )







       def       snake_case (				self      :			Optional[int]   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict   )

            with tempfile.TemporaryDirectory() as tmpdirname:
                 config_first.save_pretrained(__lowercase   )
                 __lowercase      		=self.config_class.from_pretrained(__lowercase   )

            self.parent.assertEqual(config_second.to_dict()    ,   config_first.to_dict()   )







       def       snake_case (				self      :			str   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict   )

            __lowercase      		='test'
            with tempfile.TemporaryDirectory() as tmpdirname:
                 __lowercase      		=os.path.join(__lowercase    ,   __lowercase   )
                 config_first.save_pretrained(__lowercase   )
                 __lowercase      		=self.config_class.from_pretrained(__lowercase    ,   subfolder=__lowercase   )

            self.parent.assertEqual(config_second.to_dict()    ,   config_first.to_dict()   )







       def       snake_case (				self      :			Tuple   ):







            """simple docstring"""







            __lowercase      		=self.config_class(**self.inputs_dict    ,   num_labels=5   )
            self.parent.assertEqual(len(config.idalabel   )    ,   5   )
            self.parent.assertEqual(len(config.labelaid   )    ,   5   )

            __lowercase      		=3
            self.parent.assertEqual(len(config.idalabel   )    ,   3   )
            self.parent.assertEqual(len(config.labelaid   )    ,   3   )







       def       snake_case (				self      :			Tuple   ):







            """simple docstring"""







            if self.config_class.is_composition:
                 return
            __lowercase      		=self.config_class()
            self.parent.assertIsNotNone(__lowercase   )







       def       snake_case (				self      :			Tuple   ):







            """simple docstring"""







            __lowercase      		=copy.deepcopy(__lowercase   )
            __lowercase      		=self.config_class(**__lowercase   )
            __lowercase      		=[]
            for key, value in config_common_kwargs.items():
                 if key == "torch_dtype":
                      if not is_torch_available():
                           continue
                      else:
                           import torch

                           if config.torch_dtype != torch.floataa:
                                wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa)   )
                 elif getattr(__lowercase    ,   __lowercase   ) != value:
                      wrong_values.append((key, getattr(__lowercase    ,   __lowercase   ), value)   )

            if len(__lowercase   ) > 0:
                 __lowercase      		='\n'.join([f'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values]   )
                 raise ValueError(f'''The following keys were not properly set in the config:\n{errors}'''   )







       def       snake_case (				self      :			Union[str, Any]   ):







            """simple docstring"""







            self.create_and_test_config_common_properties()
            self.create_and_test_config_to_json_string()
            self.create_and_test_config_to_json_file()
            self.create_and_test_config_from_and_save_pretrained()
            self.create_and_test_config_from_and_save_pretrained_subfolder()
            self.create_and_test_config_with_num_labels()
            self.check_config_can_be_init_without_params()
            self.check_config_arguments_init()





'''simple docstring'''

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


UpperCAmelCase					 =	logging.get_logger(__name__)

UpperCAmelCase					 =	{
    '''shi-labs/dinat-mini-in1k-224''': '''https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json''',
    # See all Dinat models at https://huggingface.co/models?filter=dinat
}


class 	lowerCAmelCase  (   A ,      A ):
       lowerCAmelCase_												=			"dinat"

       lowerCAmelCase_												=			{
           "num_attention_heads": "num_heads",
           "num_hidden_layers": "num_layers",
       }







       def __init__(				self      :			int    ,   __lowercase      :			str=4    ,   __lowercase      :			str=3    ,   __lowercase      :			int=64    ,   __lowercase      :			int=[3, 4, 6, 5]    ,   __lowercase      :			Union[str, Any]=[2, 4, 8, 16]    ,   __lowercase      :			Optional[int]=7    ,   __lowercase      :			str=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]]    ,   __lowercase      :			Any=3.0    ,   __lowercase      :			Optional[Any]=True    ,   __lowercase      :			List[Any]=0.0    ,   __lowercase      :			Optional[Any]=0.0    ,   __lowercase      :			int=0.1    ,   __lowercase      :			Union[str, Any]="gelu"    ,   __lowercase      :			Any=0.0_2    ,   __lowercase      :			int=1E-5    ,   __lowercase      :			Optional[int]=0.0    ,   __lowercase      :			Optional[int]=None    ,   __lowercase      :			str=None    ,   **__lowercase      :			Any    ,   ):







            """simple docstring"""







            super().__init__(**__lowercase   )

            __lowercase      		=patch_size
            __lowercase      		=num_channels
            __lowercase      		=embed_dim
            __lowercase      		=depths
            __lowercase      		=len(__lowercase   )
            __lowercase      		=num_heads
            __lowercase      		=kernel_size
            __lowercase      		=dilations
            __lowercase      		=mlp_ratio
            __lowercase      		=qkv_bias
            __lowercase      		=hidden_dropout_prob
            __lowercase      		=attention_probs_dropout_prob
            __lowercase      		=drop_path_rate
            __lowercase      		=hidden_act
            __lowercase      		=layer_norm_eps
            __lowercase      		=initializer_range
            # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel
            # this indicates the channel dimension after the last stage of the model
            __lowercase      		=int(embed_dim * 2 ** (len(__lowercase   ) - 1)   )
            __lowercase      		=layer_scale_init_value
            __lowercase      		=['stem'] + [f'''stage{idx}''' for idx in range(1    ,   len(__lowercase   ) + 1   )]
            __lowercase		,  __lowercase      		=get_aligned_output_features_output_indices(
                out_features=__lowercase    ,   out_indices=__lowercase    ,   stage_names=self.stage_names   )


